keyring-agent-core 0.3.18 → 0.3.19
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 +19 -0
- package/dist/index.js +48 -48
- package/dist/index.native.js +163 -163
- 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=r,this.metaMessages=o,t.name&&(this.name=t.name)}walk(e){return Wc(this,e)}};function Wc(n,e){if(e?.(n))return n;let t=n&&typeof n=="object"?n.cause:void 0;return t!=null?Wc(t,e):e?null:n}var Wt=class extends F{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."]})}},ya=class extends F{name="AbiEncodingLengthMismatchError";constructor({expectedLength:e,givenLength:t}){super("ABI encoding parameters/values length mismatch.",{metaMessages:[`Expected length (parameters): ${e}`,`Given length (values): ${t}`]})}},ba=class extends F{name="AbiEncodingArrayLengthMismatchError";constructor({expectedLength:e,givenLength:t,type:r}){super(`ABI encoding array length mismatch for type ${r}.`,{metaMessages:[`Expected length: ${e}`,`Given length: ${t}`]})}},it=class extends F{name="InvalidAbiValueError";constructor({type:e,value:t,reason:r}){super(`Invalid value for ABI type "${e}".`,{metaMessages:[`Value: ${Yc(t)}`,`Reason: ${r}`]})}},wa=class extends F{name="IntegerOutOfRangeError";constructor({type:e,value:t,min:r,max:o}){super(`Number "${t}" is not in safe ${e} range.`,{metaMessages:[`Range: ${r} \u2026 ${o}`]})}},or=class extends F{name="InvalidAddressError";constructor(e){super(`Address "${Yc(e)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]})}};function Yc(n){if(typeof n=="bigint")return n.toString();if(typeof n=="string")return n;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}var ka=class extends F{name="AbiEncodingBytesSizeMismatchError";constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" does not match expected size of bytes${e}.`)}},Yt=class extends F{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."]})}},va=class extends F{name="AbiDecodingDataSizeTooSmallError";data;params;size;constructor({data:e,params:t,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${t.map(o=>o.type).join(", ")})`,`Data: ${e} (${r} bytes)`]}),this.data=e,this.params=t,this.size=r}},sr=class extends F{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."]})}},Ta=class extends F{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."]})}},Gt=class extends F{name="InvalidAbiSignatureError";constructor(e,t){super(`Invalid ABI signature: "${e}".`,{metaMessages:t?[t]:['Expected e.g. "function balanceOf(address owner) view returns (uint256)".']})}};var hm=/^0x[0-9a-fA-F]*$/;function xn(n,{strict:e=!0}={}){return typeof n!="string"?!1:e?hm.test(n):n.startsWith("0x")}function gt(n){return n.startsWith("0x")||n.startsWith("0X")?n.slice(2):n}function ms(n){return typeof n=="string"?Math.ceil(gt(n).length/2):n.length}function Cn(n,e,t){let r=gt(n),o=(e??0)*2,s=t===void 0?r.length:t*2;return`0x${r.slice(o,s)}`}function Aa(n){return`0x${n.map(gt).join("")}`}function Rn(n){let e=new Uint8Array(n.reduce((r,o)=>r+o.length,0)),t=0;for(let r of n)e.set(r,t),t+=r.length;return e}function Kt(n){let e=gt(n),t=e.length%2?`0${e}`:e,r=new Uint8Array(t.length/2);for(let o=0;o<r.length;o++)r[o]=parseInt(t.slice(o*2,o*2+2),16);return r}function It(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`0x${e}`}function el(n){return new TextEncoder().encode(n)}function tl(n){return new TextDecoder().decode(n)}function Fe(n,e={}){let{size:t,signed:r}=e,o=BigInt(n);if(o<0n){if(!t)throw new Error("numberToHex: negative values require a `size`");o+=1n<<BigInt(t*8)}else if(r&&t){let a=(1n<<BigInt(t*8-1))-1n;if(o>a)throw new Error(`numberToHex: ${n} overflows int${t*8}`)}let s=o.toString(16);if(!t)return`0x${s}`;if(s.length>t*2)throw new Error(`numberToHex: ${n} overflows ${t} bytes`);return`0x${s.padStart(t*2,"0")}`}function nl(n,e=32){if(n.length>e)throw new Error(`padLeft: ${n.length} bytes exceeds ${e}`);let t=new Uint8Array(e);return t.set(n,e-n.length),t}function rl(n,e=32){if(n.length>e)throw new Error(`padRight: ${n.length} bytes exceeds ${e}`);let t=new Uint8Array(e);return t.set(n),t}function En(n){let e=1n<<256n,t=(n%e+e)%e;return Kt(t.toString(16).padStart(64,"0"))}function ar(n,{signed:e=!1}={}){let t=BigInt(It(n));if(!e)return t;let r=BigInt(n.length*8);return t>=1n<<r-1n?t-(1n<<r):t}function lt(n,{signed:e=!1}={}){return gt(n)?ar(Kt(n),{signed:e}):0n}function Pa(n,e={}){return Number(lt(n,e))}var Gc=require("js-sha3");var fm=/^0x[0-9a-fA-F]{40}$/;function R(n){return typeof n=="string"&&fm.test(n)}function ir(n){let e=gt(n).toLowerCase(),t=(0,Gc.keccak_256)(e),r="";for(let o=0;o<e.length;o++)r+=parseInt(t[o],16)>=8?e[o].toUpperCase():e[o];return`0x${r}`}function ol(n){if(!R(n))throw new Error(`Address "${n}" is invalid.`);return ir(n)}function sl(n,e){return R(n)&&R(e)&&n.toLowerCase()===e.toLowerCase()}var Sa=require("js-sha3");function xa(n){return`0x${(0,Sa.keccak_256)(n)}`}function Kc(n){return`0x${(0,Sa.keccak_256)(new TextEncoder().encode(n))}`}function jt(n){let e=n.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function zt(n){return n.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1").replace(/^byte(\[|$)/,"bytes1$1")}function hs(n){let e=zt(n.type);return e==="tuple"||e.startsWith("tuple[")?`(${(n.components??[]).map(hs).join(",")})${e.slice(5)}`:e}function lr(n){return`${n.name??""}(${(n.inputs??[]).map(hs).join(",")})`}function Ut(n){let e=typeof n=="string"?n:lr(n);return`0x${(0,Sa.keccak_256)(new TextEncoder().encode(e)).slice(0,8)}`}function al(n){let e=typeof n=="string"?n:lr(n);return Kc(e)}function jc(n,e){let t=zt(e.type),r=jt(t);if(r){let[o,s]=r;return!Array.isArray(n)||o!==null&&n.length!==o?!1:n.every(a=>jc(a,{...e,type:s}))}if(t==="tuple"){let o=e.components??[];return Array.isArray(n)?n.length===o.length:typeof n=="object"&&n!==null}return t==="address"?typeof n=="string"&&/^0x[0-9a-fA-F]{40}$/.test(n):t==="bool"?typeof n=="boolean":t==="string"?typeof n=="string":t.startsWith("bytes")?typeof n=="string"||n instanceof Uint8Array:t.startsWith("uint")||t.startsWith("int")?typeof n=="number"||typeof n=="bigint"||typeof n=="string":!0}function Xt({abi:n,name:e,args:t,type:r}){let o=r??"function",s=n.filter(i=>(i.type??"function")===o);if(e.startsWith("0x")&&e.length===10)return s.find(i=>Ut(i)===e.toLowerCase());if(e.includes("("))return s.find(i=>lr(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)=>jc(t[d],c))})??a[0]}function _n(n){let e=Xt(n);if(!e)throw new Ta({name:n.name,type:n.type??"function"});return e}function zc(n){let e=new Uint8Array(Math.ceil(n.length/32)*32);return e.set(n),{dynamic:!0,encoded:Rn([En(BigInt(n.length)),e])}}function Xc(n,e){let t=n.slice(e.length),r=t===""?256:Number(t);if(!Number.isInteger(r)||r<8||r>256||r%8!==0)throw new Wt(n);return r}function Qc(n,e){if(typeof n=="bigint")return n;if(typeof n=="number"){if(!Number.isInteger(n))throw new it({type:e,value:n,reason:"expected an integer, got a fractional number"});return BigInt(n)}if(typeof n=="string"&&n.trim()!=="")try{return BigInt(n.trim())}catch{throw new it({type:e,value:n,reason:"string is not a valid integer"})}throw new it({type:e,value:n,reason:"expected a bigint, number or numeric string"})}function Jc(n,{bits:e,signed:t,type:r}){let o=t?(1n<<BigInt(e-1))-1n:(1n<<BigInt(e))-1n,s=t?-(1n<<BigInt(e-1)):0n;if(n<s||n>o)throw new wa({type:r,value:n,min:s,max:o})}function Zc(n,e){if(n instanceof Uint8Array)return n;if(typeof n=="string"){if(!xn(n))throw new it({type:e,value:n,reason:"expected 0x-prefixed hex"});return Kt(n)}throw new it({type:e,value:n,reason:"expected a hex string or Uint8Array"})}function il(n,e){let t=jt(n.type);if(t){let[o,s]=t;if(!Array.isArray(e))throw new it({type:n.type,value:e,reason:"expected an array"});return gm({...n,type:s},e,o,n.type)}if(n.type==="tuple")return ym(n,e);let r=zt(n.type);if(r==="address"){if(!R(e))throw new or(e);return{dynamic:!1,encoded:nl(Kt(gt(e).toLowerCase()))}}if(r==="bool"){if(typeof e!="boolean")throw new it({type:r,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(r)){let o=Qc(e,r);return Jc(o,{bits:Xc(r,"uint"),signed:!1,type:r}),{dynamic:!1,encoded:En(o)}}if(/^int\d*$/.test(r)){let o=Qc(e,r);return Jc(o,{bits:Xc(r,"int"),signed:!0,type:r}),o<0n&&(o+=1n<<256n),{dynamic:!1,encoded:En(o)}}if(/^bytes\d+$/.test(r)){let o=Number(r.slice(5));if(o<1||o>32)throw new Wt(n.type);let s=Zc(e,r);if(s.length!==o)throw new ka({expectedSize:o,value:String(e)});return{dynamic:!1,encoded:rl(s)}}if(r==="bytes")return zc(Zc(e,r));if(r==="string"){if(typeof e!="string"&&!(e instanceof Uint8Array))throw new it({type:r,value:e,reason:"expected a string"});return zc(typeof e=="string"?el(e):e)}throw new Wt(n.type)}function ll(n){let e=0;for(let{dynamic:s,encoded:a}of n)e+=s?32:a.length;let t=[],r=[],o=0;for(let{dynamic:s,encoded:a}of n)s?(t.push(En(BigInt(e+o))),r.push(a),o+=a.length):t.push(a);return Rn([...t,...r])}function gm(n,e,t,r){let o=t===null;if(!o&&e.length!==t)throw new ba({expectedLength:t,givenLength:e.length,type:r});let s=!1,a=[];for(let i of e){let l=il(n,i);l.dynamic&&(s=!0),a.push(l)}if(o||s){let i=ll(a);if(!o)return{dynamic:!0,encoded:i};let l=En(BigInt(a.length));return{dynamic:!0,encoded:a.length>0?Rn([l,i]):l}}return{dynamic:!1,encoded:Rn(a.map(i=>i.encoded))}}function ym(n,e){let t=n.components??[],r=!1,o=[];for(let s=0;s<t.length;s++){let a=t[s],i=il(a,Array.isArray(e)?e[s]:e[a.name??""]);i.dynamic&&(r=!0),o.push(i)}return{dynamic:r,encoded:r?ll(o):Rn(o.map(s=>s.encoded))}}function cr(n,e){if(n.length!==e.length)throw new ya({expectedLength:n.length,givenLength:e.length});return n.length===0?"0x":It(ll(n.map((t,r)=>il(t,e[r]))))}function M({abi:n,functionName:e,args:t=[]}){let r=_n({abi:n,name:e,args:t,type:"function"}),o=Ut(r),s=r.inputs??[];return s.length===0?o:Aa([o,cr(s,t)])}function cl({abi:n,errorName:e,args:t=[]}){let r=_n({abi:n,name:e,args:t,type:"error"}),o=r.inputs??[],s=Ut(r);return o.length===0?s:Aa([s,cr(o,t)])}function bm(n){let e=n.replace(/^u?int/,"");return e?Number(e):256}function fs(n,e){if(e<0||e+32>n.length)throw new sr({position:e,length:n.length});return n.subarray(e,e+32)}function pl(n,e){let t=ar(fs(n,e));if(t>BigInt(n.length))throw new sr({position:Number(t),length:n.length});return Number(t)}function ul(n){let e=jt(n.type);if(e){let[r,o]=e;return r===null||ul({...n,type:o})}if(n.type==="tuple")return(n.components??[]).some(ul);let t=zt(n.type);return t==="bytes"||t==="string"}function dl(n){let e=jt(n.type);if(e){let[t,r]=e;return t===null?32:t*dl({...n,type:r})}return n.type==="tuple"?(n.components??[]).reduce((t,r)=>t+dl(r),0):32}function ml(n,e,t){let r=[],o=e;for(let s of t)ul(s)?(r.push(eu(n,e+pl(n,o),s)),o+=32):(r.push(eu(n,o,s)),o+=dl(s));return r}function wm(n,e,t,r){let o=r===null?pl(n,e):r,s=r===null?e+32:e;return ml(n,s,new Array(o).fill(t))}function km(n,e,t){let r=t.components??[],o=ml(n,e,r);if(r.length===0||r.some(i=>!i.name))return o;let a={};return r.forEach((i,l)=>{a[i.name]=o[l]}),a}function eu(n,e,t){let r=jt(t.type);if(r){let[s,a]=r;return wm(n,e,{...t,type:a},s)}if(t.type==="tuple")return km(n,e,t);let o=zt(t.type);if(o==="address")return ir(It(fs(n,e).subarray(12)));if(o==="bool")return ar(fs(n,e))!==0n;if(/^u?int\d*$/.test(o)){let s=o.startsWith("int"),a=ar(fs(n,e),{signed:s});return bm(o)>48?a:Number(a)}if(/^bytes\d+$/.test(o)){let s=Number(o.slice(5));return It(fs(n,e).subarray(0,s))}if(o==="bytes"||o==="string"){let s=pl(n,e),a=e+32;if(a+s>n.length)throw new sr({position:a+s,length:n.length});let i=n.subarray(a,a+s);return o==="bytes"?It(i):tl(i)}throw new Wt(t.type)}function Ie(n,e){let t=typeof e=="string"?Kt(e):e;if(t.length===0){if(n.length>0)throw new Yt;return[]}if(t.length<32)throw new va({data:typeof e=="string"?e:It(e),params:n,size:t.length});return ml(t,0,n)}function ee(n){if(!n)return null;try{let[e]=Ie([{type:"uint256"}],n);return e}catch{return null}}function B(n){if(!n)return null;try{let[e]=Ie([{type:"address"}],n),t=e;return/^0x0{40}$/i.test(t)?null:t}catch{return null}}function ur(n){if(!n)return null;try{let[e]=Ie([{type:"string"}],n),t=tu(e);if(t)return t}catch{}try{let[e]=Ie([{type:"bytes32"}],n);return Ra(e)}catch{return null}}function dr(n){return Ca(ee(n))}function Ca(n){let e=typeof n=="bigint"?Number(n):typeof n=="number"?n:NaN;return Number.isFinite(e)&&e>=0&&e<=36?e:null}function Ra(n){return typeof n!="string"||!n.startsWith("0x")?null:tu(Buffer.from(n.slice(2),"hex").toString("utf8"))||null}function tu(n){return n.replace(/[^\x20-\x7e]/g,"").trim()}function yt({abi:n,functionName:e,args:t,data:r}){let s=_n({abi:n,name:e,args:t,type:"function"}).outputs??[],a=Ie(s,r);if(a.length!==0)return a.length===1?a[0]:a}function hl({abi:n,data:e}){let t=Cn(e,0,4),r=_n({abi:n,name:t,type:"function"}),o=r.inputs??[];return{functionName:r.name,args:o.length===0||ms(e)<=4?[]:Ie(o,Cn(e,4))}}var nu={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},ru={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},ou={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 pr({abi:n=[],data:e}){let t=Cn(e,0,4);if(ms(e)<4)throw new Error(`Cannot decode error result: "${e}" is too short.`);let r=[...n,nu,ru],o=Xt({abi:r,name:t,type:"error"})??r.find(a=>(a.type??"")==="error"&&Ut(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?Ie(s,Cn(e,4)):void 0}}function gs({abi:n,data:e}){if(!(!e||e==="0x"))try{let{errorName:t,args:r}=pr({abi:n,data:e});if(t==="Error")return String(r?.[0]??"");if(t==="Panic"){let o=Number(r?.[0]??0);return ou[o]??`Panic code ${o}.`}return!r||r.length===0?t:`${t}(${r.map(o=>String(o)).join(", ")})`}catch{return}}var vm=new Set(["pure","view","nonpayable","payable"]),Tm=new Set(["external","public","internal","private","calldata","memory","storage"]);function gl(n,e){let t=0;for(let r=e;r<n.length;r++)if(n[r]==="(")t++;else if(n[r]===")"&&(t--,t===0))return r;throw new Gt(n,"Unbalanced parentheses.")}function au(n){let e=[],t=0,r="";for(let o of n){if(o==="("&&t++,o===")"&&t--,o===","&&t===0){e.push(r),r="";continue}r+=o}return r.trim()&&e.push(r),e.map(o=>o.trim()).filter(Boolean)}function Am(n){let e=n.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:e?.[1]??"",rest:(e?.[2]??"").trim()}}function su(n,e){let t=!1,r;for(let o of n)o==="indexed"?t=!0:Tm.has(o)||(r=o);return{...e,...r?{name:r}:{},...t?{indexed:!0}:{}}}function yl(n){let e=n.trim();if(e.startsWith("(")){let o=gl(e,0),s=au(e.slice(1,o)).map(yl),{suffix:a,rest:i}=Am(e.slice(o+1).trim());return su(i.split(/\s+/).filter(Boolean),{type:`tuple${a}`,components:s})}let[t,...r]=e.split(/\s+/).filter(Boolean);if(!t)throw new Gt(n,"Missing parameter type.");return su(r,{type:t})}function bs(n){return au(n).map(yl)}function ys(n,e,t){let r=n.indexOf("(",e);if(r===-1)throw new Gt(t,"Missing parameter list.");let o=gl(n,r);return{name:n.slice(e,r).trim(),params:bs(n.slice(r+1,o)),rest:n.slice(o+1).trim()}}function fl(n,e){return n.split(/[\s()]+/).find(r=>vm.has(r))??e}function Ea(n){let e=n.trim();if(e.startsWith("function ")){let{name:t,params:r,rest:o}=ys(e,9,n),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 Gt(n,"`returns` without a parameter list.");i=bs(o.slice(l+1,gl(o,l)))}return{type:"function",name:t,inputs:r,outputs:i,stateMutability:fl(a,"nonpayable")}}if(e.startsWith("event ")){let{name:t,params:r}=ys(e,6,n);return{type:"event",name:t,inputs:r}}if(e.startsWith("error ")){let{name:t,params:r}=ys(e,6,n);return{type:"error",name:t,inputs:r}}if(e.startsWith("constructor")){let{params:t,rest:r}=ys(e,11,n);return{type:"constructor",inputs:t,stateMutability:fl(r,"nonpayable")}}if(e.startsWith("fallback")){let{rest:t}=ys(e,8,n);return{type:"fallback",stateMutability:fl(t,"nonpayable")}}if(e.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new Gt(n,"Expected function, event, error, constructor, fallback or receive.")}function bl(n){return n.map(Ea)}function bt({blockNumber:n,blockTag:e="latest"}={}){return n!==void 0?Fe(n):e}function ws(n){let{account:e,to:t,data:r,value:o,gas:s,gasPrice:a,maxFeePerGas:i,maxPriorityFeePerGas:l,nonce:c}=n,d={};return e&&(d.from=e),t&&(d.to=t),r&&(d.data=r),o!==void 0&&(d.value=Fe(o)),s!==void 0&&(d.gas=Fe(s)),a!==void 0&&(d.gasPrice=Fe(a)),i!==void 0&&(d.maxFeePerGas=Fe(i)),l!==void 0&&(d.maxPriorityFeePerGas=Fe(l)),c!==void 0&&(d.nonce=Fe(c)),d}function wl(n){let e={};for(let[t,r]of Object.entries(n)){let o={};r.balance!==void 0&&(o.balance=Fe(r.balance)),r.nonce!==void 0&&(o.nonce=Fe(r.nonce)),r.code!==void 0&&(o.code=r.code),r.state&&(o.state=r.state),r.stateDiff&&(o.stateDiff=r.stateDiff),e[t]=o}return e}async function mr(n){return lt(await n.request({method:"eth_blockNumber"}))}async function hr(n){return Pa(await n.request({method:"eth_chainId"}))}async function fr(n,{address:e,...t}){return lt(await n.request({method:"eth_getBalance",params:[e,bt(t)]}))}async function Qt(n,{address:e,...t}){let r=await n.request({method:"eth_getCode",params:[e,bt(t)]});return!r||r==="0x"?void 0:r}async function gr(n,{address:e,slot:t,...r}){return await n.request({method:"eth_getStorageAt",params:[e,t,bt(r)]})??void 0}async function yr(n,{address:e,...t}){return Pa(await n.request({method:"eth_getTransactionCount",params:[e,bt(t)]}))}async function br(n){return lt(await n.request({method:"eth_gasPrice"}))}async function _a(n){return lt(await n.request({method:"eth_maxPriorityFeePerGas"}))}async function wr(n,{blockNumber:e,blockTag:t,...r}){return lt(await n.request({method:"eth_estimateGas",params:[ws(r),bt({blockNumber:e,blockTag:t})]}))}async function kr(n,{includeTransactions:e=!1,...t}={}){let r=await n.request({method:"eth_getBlockByNumber",params:[bt(t),e]});return r?{...r,blockNumber:r.number?lt(r.number):void 0,blockTimestamp:r.timestamp?lt(r.timestamp):void 0,baseFee:r.baseFeePerGas?lt(r.baseFeePerGas):void 0}:null}var re="0xcA11bde05977b3631167028862bE2a173976CA11",iu={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:re,blockCreated:14353601}}},lu={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:re,blockCreated:4286263}}},cu={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:re}}},uu={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:re,blockCreated:25770160}}},du={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:re,blockCreated:5022}}},pu={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:re,blockCreated:7654707}}},mu={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:re}}},hu={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:re}}},fu={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:re}}},gu={id:999,hexId:"0x3e7",name:"HyperEVM",nativeCurrency:{name:"HYPE",symbol:"HYPE",decimals:18},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}},contracts:{multicall3:{address:re}}},yu={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:re}}},bu={id:143,hexId:"0x8f",name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://rpc.monad.xyz"]}},contracts:{multicall3:{address:re}}},Nn=[iu,lu,cu,uu,du,pu,mu,hu,fu,gu,yu,bu];var wu=new Map,kl=new Map;function Pm(n,e){return`${n??"unknown"}|${e.toLowerCase()}`}async function ku(n,e=re){let t=Pm(n.chain?.id??n.chain?.hexId,e),r=wu.get(t);if(r!==void 0)return r;let o=kl.get(t);if(o)return o;let s=(async()=>{try{let i=await Qt(n,{address:e})!==void 0;return wu.set(t,i),i}catch{return!0}finally{kl.delete(t)}})();return kl.set(t,s),s}async function Ln(n,e,t=!1){return t||typeof n.batch?.multicall=="object"&&n.batch.multicall.assumeMulticall3?!0:ku(n,e)}var ct=[{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 q=[{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}]}],vr=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]}];var Tr=[{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 wt=[{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 Ar=class extends F{name="ChainNotFoundError";constructor(e){super(`Chain "${e}" is not supported.`,{metaMessages:["Add it to `chain/chains/definitions.ts`, or pass an explicit `transport`/`rpcUrl`."]})}},In=class extends F{name="ClientChainNotConfiguredError";constructor(){super("No chain was configured on the client.",{metaMessages:["Pass `chain` to createPublicClient(), or pass the address the action needs explicitly."]})}},Jt=class extends F{name="ChainDoesNotSupportContractError";constructor({chain:e,contract:t,blockNumber:r}){super(r!==void 0?`Chain "${e}" does not support contract "${t}" at block ${r}.`:`Chain "${e}" does not support contract "${t}".`,{metaMessages:["Pass the contract address explicitly to use it on this chain."]})}};async function vl(n,e,t){let r=new Array(n.length);if(n.length===0)return r;let o=0,s=Math.max(1,Math.min(e>0?e:n.length,n.length));async function a(){for(;;){let i=o++;if(i>=n.length)return;try{r[i]={status:"fulfilled",value:await t(n[i],i)}}catch(l){r[i]={status:"rejected",reason:l}}}}return await Promise.all(Array.from({length:s},a)),r}function ks({blockNumber:n,chain:e,contract:t}){let r=e.contracts?.[t];if(!r)throw new Jt({chain:e.name,contract:t});if(n!==void 0&&r.blockCreated!==void 0&&r.blockCreated>Number(n))throw new Jt({blockNumber:n,chain:e.name,contract:t});return r.address}var Pr=class extends F{name="RawContractError";data;constructor({data:e,shortMessage:t="The contract call reverted."}){super(t),this.data=e}},Tl=class extends F{name="ContractFunctionRevertedError";errorName;errorArgs;reason;data;constructor({abi:e,data:t,functionName:r}){let o=t?gs({abi:e,data:t}):void 0,s,a;if(t&&t!=="0x")try{let i=pr({abi:e,data:t});s=i.errorName,a=i.args}catch{}super(o?`The contract function "${r??"call"}" reverted with the following reason:
|
|
3
|
-
${o}`:`The contract function "${r??"call"}" reverted.`,{metaMessages:t&&t!=="0x"?[`Revert data: ${t}`]:[]}),this.reason=o,this.errorName=s,this.errorArgs=a,this.data=t}},Al=class extends F{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."]})}},Pl=class extends F{name="ContractFunctionExecutionError";abi;address;args;functionName;constructor(e,{abi:t,address:r,args:o,functionName:s,sender:a}){let i=t&&s?Xt({abi:t,name:s,args:o}):void 0,l=i?lr(i):s,c=o&&o.length>0?` args: (${o.map(u=>Sm(u)).join(", ")})`:void 0,d=i?.inputs?.length?`(${i.inputs.map(hs).join(", ")})`:"()";super(e instanceof F?e.shortMessage:`An error occurred calling "${s??"contract"}".`,{cause:e,metaMessages:[...r?[`Contract: ${r}`]:[],...l?[`Function: ${l}${i?"":d}`]:[],...c?[c]:[],...a?[`Sender: ${a}`]:[]]}),this.abi=t,this.address=r,this.args=o,this.functionName=s}},vs=class extends F{name="CallExecutionError";constructor(e,{to:t,data:r}){super(e instanceof F?e.shortMessage:"The call failed.",{cause:e,metaMessages:[...t?[`To: ${t}`]:[],...r?[`Data: ${r}`]:[]]})}};function Sm(n){if(typeof n=="bigint")return n.toString();if(typeof n=="string")return n;try{return JSON.stringify(n,(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return String(n)}}function vu(n){if(!n||typeof n!="object")return;let e=n,t=e.data;if(typeof t=="string"&&t.startsWith("0x"))return t;if(t&&typeof t=="object"){let r=t.data;if(typeof r=="string"&&r.startsWith("0x"))return r}return e.cause?vu(e.cause):void 0}function Sr(n,{abi:e,address:t,args:r,functionName:o,sender:s}){let a=vu(n),i=n instanceof Yt?new Al({functionName:o}):a!==void 0?new Tl({abi:e,data:a,functionName:o}):n;return new Pl(i,{abi:e,address:t,args:r,functionName:o,sender:s})}var Sl=new Map;function Ts({fn:n,id:e,shouldSplitBatch:t,wait:r=0}){let o=()=>Sl.get(e)??void 0,s=i=>Sl.set(e,i),a=async i=>{o()===i&&Sl.delete(e);try{let l=await n(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=o();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)},r)})}}}function xm(n){return!!(n.data&&n.to&&!n.account&&!n.value&&!n.gas&&!n.gasPrice&&!n.maxFeePerGas&&!n.maxPriorityFeePerGas&&n.nonce===void 0&&!n.stateOverride)}async function Cm(n,e){let{batchSize:t=1024,wait:r=0}=typeof n.batch?.multicall=="object"?n.batch.multicall:{},{blockNumber:o,blockTag:s="latest",data:a,to:i}=e;if(!n.chain)throw new In;let l=ks({blockNumber:o,chain:n.chain,contract:"multicall3"});if(!await Ln(n,l,!1))throw new Jt({chain:n.chain.name,contract:"multicall3"});let c=o!==void 0?Fe(o):s,{schedule:d}=Ts({id:`${n.uid}.call.${c}`,wait:r,shouldSplitBatch:m=>m.reduce((f,h)=>f+(h.data.length-2)/2,0)>t,fn:async m=>{let f=M({abi:ct,functionName:"aggregate3",args:[m.map(g=>({allowFailure:!0,callData:g.data,target:g.to}))]}),h=await n.request({method:"eth_call",params:[{to:l,data:f},c]});return yt({abi:ct,functionName:"aggregate3",data:h})}}),{returnData:u,success:p}=await d({data:a,to:i});if(!p)throw new Pr({data:u});return u}async function kt(n,e){let{blockNumber:t,blockTag:r,stateOverride:o,skipBatch:s,...a}=e;if(n.batch?.multicall&&!s&&xm(e))try{let l=await Cm(n,{blockNumber:t,blockTag:r,data:a.data,to:a.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof In||l instanceof Jt))throw new vs(l,{to:a.to,data:a.data})}let i=[ws(a),bt({blockNumber:t,blockTag:r})];o&&i.push(wl(o));try{let l=await n.request({method:"eth_call",params:i});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new vs(l,{to:a.to,data:a.data})}}var xl=8;function Tu(n,e){if(e!==void 0&&e>0)return e;let t=typeof n.batch?.multicall=="object"?n.batch.multicall.fallbackConcurrency:void 0;return t!==void 0&&t>0?t:xl}function As(n,e,t){if(e)return e;if(!n.chain)throw new In;let r=n.chain.contracts?.multicall3;return r?t!==void 0&&r.blockCreated!==void 0&&r.blockCreated>Number(t)?re:r.address:re}async function xr(n,e,t={}){let{concurrency:r,account:o,blockNumber:s,blockTag:a,stateOverride:i}=t;return(await vl(e,Tu(n,r),async c=>{let{data:d}=await kt(n,{to:c.target,data:c.callData,account:o,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 vt(n,e){let{abi:t,address:r,functionName:o,args:s,...a}=e;try{let i=M({abi:t,functionName:o,args:s}),{data:l}=await kt(n,{...a,to:r,data:i});return yt({abi:t,functionName:o,args:s,data:l??"0x"})}catch(i){throw Sr(i,{abi:t,address:r,args:s,functionName:o,sender:a.account})}}var Rm=1024,Em=50;async function Zt(n,e){let{calls:t,account:r,blockNumber:o,blockTag:s,batchSize:a=Rm,maxCalls:i=Em,multicallAddress:l,stateOverride:c,fallbackConcurrency:d}=e,u=t.map(()=>({success:!1,returnData:"0x"}));if(t.length===0)return u;let p=As(n,l,o),m=[];if(t.forEach((b,y)=>{R(b.target)&&xn(b.callData)&&m.push({index:y,call:b})}),m.length===0)return u;if(!await Ln(n,p,l!==void 0))return(await xr(n,m.map(y=>y.call),{account:r,blockNumber:o,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=>vt(n,{abi:ct,address:p,functionName:"aggregate3",args:[b.calls.map(y=>({target:y.target,allowFailure:!0,callData:y.callData}))],account:r,blockNumber:o,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 Au="https://wallet-api.pantograph.app/keyring/chains_v6",_m=6,Nm=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,Pu={},Cr=null;function Lm(n){let e=Array.isArray(n.rpcs)?n.rpcs:[],t=typeof n.linkProvider=="string"?[n.linkProvider]:[],r=[];for(let o of[...t,...e]){if(typeof o!="string")continue;let s=o.trim();if(!(!s.startsWith("https://")||Nm.test(s))&&(r.includes(s)||r.push(s),r.length>=_m))break}return r}function Su(n){if(!n||typeof n!="object"||Array.isArray(n))return{};let e={};for(let[t,r]of Object.entries(n)){if(!r||typeof r!="object")continue;let o=r,s=Tt(t)??(typeof o.chainId=="number"?Tt(o.chainId):void 0);if(!s)continue;let a=Lm(o);a.length>0&&(e[s]=a)}return e}function xu(n){Pu=n}function Cl(n){let e=Tt(n);return e?Pu[e]??[]:[]}function Rl(){Cr||La()}function La(n={}){let{url:e=Au,force:t=!1,debug:r=!1}=n;return Cr&&!t||(Cr=(async()=>{try{let o=await C.get(e);if(!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);let s=Su(o.data),a=Object.keys(s).length;if(a===0)throw new Error("catalogue contained no usable RPC endpoints");return xu(s),r&&console.log(`[chains] loaded RPC endpoints for ${a} chains from ${e}`),!0}catch(o){if(r){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 Im=new Map(Nn.map(n=>[n.hexId.toLowerCase(),n])),Um=new Map(Nn.map(n=>[n.id,n]));function Tt(n){if(typeof n=="number")return Number.isFinite(n)&&n>=0?`0x${n.toString(16)}`:void 0;let e=n.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 Ce(n){if(typeof n=="number")return Um.get(n);let e=Tt(n);return e?Im.get(e):void 0}function Un(n){return Ce(n)?.nativeCurrency}var Qe=Object.fromEntries(Nn.map(n=>[n.hexId,n.rpcUrls.default.http[0]]));function El(n){return Ce(n)?.rpcUrls.default.http[0]}var _l={};function Dn(n){let e={};if(n)for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=Tt(t)??t.toLowerCase();e[o]=r.trim()}_l=e}function Ps(){return{..._l}}function On(n){Rl();let e=Tt(n),t=e?_l[e]:void 0,r=Cl(n),o=Ce(n)?.rpcUrls.default.http??[];return[...new Set([...t?[t]:[],...r,...o])]}function Mn(n){return On(n)[0]}function Nl(n){let e=Ce(n);if(!e)return;let t=On(n),r=e.rpcUrls.default.http;return t.length===0||t.length===r.length&&t.every((o,s)=>o===r[s])?e:{...e,rpcUrls:{default:{http:t}}}}var en=class extends F{name="HttpRequestError";status;url;body;headers;constructor({body:e,details:t,headers:r,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=r}},Rr=class extends F{name="TimeoutError";constructor({body:e,url:t,timeout:r}){super("The request took too long to respond.",{details:`The request timed out after ${r}ms.`,metaMessages:[`URL: ${t}`,...e?[`Request body: ${JSON.stringify(e)}`]:[]]})}},Er=class extends F{name="NetworkError";constructor({cause:e,url:t}){super("Could not reach the RPC endpoint.",{cause:e,metaMessages:[`URL: ${t}`]})}},Ia=class extends F{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.']})}},Ss=class extends F{name="FallbackTransportError";constructor({cause:e,count:t}){super(`All ${t} fallback transports failed.`,{cause:e})}};var _r=class extends F{name="RpcRequestError";code;data;constructor({body:e,error:t,url:r,shortMessage:o}){super(o??"RPC request failed.",{details:t.message,metaMessages:[...r?[`URL: ${r}`]:[],...e?[`Request body: ${JSON.stringify(e)}`]:[],`Error code: ${t.code}`]}),this.code=t.code,this.data=t.data}};function Je(n,e,t){return class extends _r{static code=e;name=n;constructor(r){super({...r,shortMessage:t})}}}var Dm=Je("ParseRpcError",-32700,"The node could not parse the JSON request."),Om=Je("InvalidRequestRpcError",-32600,"The JSON request is not valid."),Mm=Je("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),Fm=Je("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),Bm=Je("InternalRpcError",-32603,"The node reported an internal error."),qm=Je("InvalidInputRpcError",-32e3,"The RPC input is not valid."),$m=Je("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),Hm=Je("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),Vm=Je("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),Wm=Je("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),Ll=Je("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),Ym=Je("UserRejectedRequestError",4001,"The user rejected the request."),Gm=new Map([[-32700,Dm],[-32600,Om],[-32601,Mm],[-32602,Fm],[-32603,Bm],[-32e3,qm],[-32001,$m],[-32002,Hm],[-32003,Vm],[-32004,Wm],[-32005,Ll],[4001,Ym]]);function Cu(n){let e=Gm.get(n.error.code);return e?new e(n):new _r(n)}function Ru(n){return new Promise(e=>setTimeout(e,n))}async function Il(n,{retryCount:e=2,delay:t=150,shouldRetry:r=()=>!0}={}){let o=0;for(;;)try{return await n()}catch(s){if(o++,o>e||!r({count:o,error:s}))throw s;let a=typeof t=="function"?t({count:o,error:s}):t*2**(o-1);a>0&&await Ru(a)}}function Ul(n){let e=n?.["retry-after"];if(!e)return;let t=Number(e);if(Number.isFinite(t))return t*1e3;let r=Date.parse(e);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var Km=new Set([408,413,429,500,502,503,504]),jm=new Set([401,402,403]);function Ua(n){return n instanceof Rr||n instanceof Er?!0:n instanceof en?n.status?Km.has(n.status)||n.status>=500:!0:n instanceof Ll?!0:n instanceof _r?n.code===-32603:!1}function Da(n){return n instanceof en&&n.status&&jm.has(n.status)?!0:Ua(n)}function Oa(n,{retryCount:e=3,retryDelay:t=150}={}){return function(o,s={}){return Il(()=>n(o),{retryCount:s.retryCount??e,shouldRetry:({error:a})=>Ua(a),delay:({count:a,error:i})=>{let l=i instanceof en?Ul(i.headers):void 0;return l!==void 0?l:(s.retryDelay??t)*2**(a-1)}})}}function tn({key:n,name:e,type:t,request:r,retryCount:o=3,retryDelay:s=150,timeout:a=1e4},i){return{config:{key:n,name:e,type:t,request:r,retryCount:o,retryDelay:s,timeout:a},request:Oa(r,{retryCount:o,retryDelay:s}),value:i}}function nn(n,e={}){let{key:t="fallback",name:r="Fallback",retryCount:o=0,retryDelay:s,onTransportError:a}=e;return(i={})=>{let l=n.map(d=>d(i));if(l.length===0)throw new Ss({count:0});return tn({key:t,name:r,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}),!Da(m))throw m}throw new Ss({cause:u,count:l.length})},retryCount:o,retryDelay:s,timeout:i.timeout},{transports:l})}}var Eu=0;function _u(){return Eu+=1,Eu}function zm(n){let e=n?.code;if(e==="ECONNABORTED"||e==="ETIMEDOUT")return!0;let t=n?.message??"";return/timeout/i.test(t)}var Nr=class{url;timeout;fetchOptions;constructor(e,{timeout:t=1e4,fetchOptions:r={}}={}){this.url=e,this.timeout=t,this.fetchOptions=r}async post(e){let t;try{t=await C.post(this.url,e,{...this.fetchOptions,timeout:this.timeout,headers:{"Content-Type":"application/json",...this.fetchOptions.headers}})}catch(r){throw zm(r)?new Rr({body:e,url:this.url,timeout:this.timeout}):new Er({cause:r,url:this.url})}if(!t.ok)throw new en({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:_u(),...e};return await this.post(t)??{id:t.id}}async requestBatch(e){let t=e.map(s=>({jsonrpc:"2.0",id:_u(),...s})),r=await this.post(t);if(!Array.isArray(r))return t.map(s=>({id:s.id,error:r?.error??{code:-32603,message:"Malformed batch response."}}));let o=new Map(r.map(s=>[s.id,s]));return t.map((s,a)=>o.get(s.id)??r[a]??{id:s.id,error:{code:-32603,message:"Missing response for batched request."}})}};function Nu(n,e,t){if(n.error)throw Cu({body:e,error:n.error,url:t});return n.result}function ut(n,e={}){let{batch:t,fetchOptions:r,key:o="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=n??c?.rpcUrls.default.http[0];if(!g)throw new Ia;let b=new Nr(g,{timeout:h,fetchOptions:r});return tn({key:o,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}=Ts({id:`${g}:${m}:${f}`,wait:f,shouldSplitBatch:P=>P.length>m,fn:P=>b.requestBatch(P)});return Nu(await v(k),k,g)}return Nu(await b.request(k),k,g)}},{url:g})}}var Xm=1024;async function Lr(n,e){let{contracts:t,allowFailure:r=!0,account:o,blockNumber:s,blockTag:a,multicallAddress:i,stateOverride:l,fallbackConcurrency:c}=e,d=e.batchSize??(typeof n.batch?.multicall=="object"&&n.batch.multicall.batchSize||Xm),u=new Array(t.length);if(t.length===0)return r?u:[];let p=As(n,i,s),m=[],f;t.forEach((b,y)=>{let{abi:w,address:k,functionName:v,args:P}=b,S;try{if(!R(k))throw new or(k);S=M({abi:w,functionName:v,args:P})}catch(L){let E=Sr(L,{abi:w,address:k,args:P,functionName:v,sender:o});if(!r)throw E;u[y]={status:"failure",error:E};return}let x=(S.length-2)/2;(!f||d>0&&f.size+x>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+=x}),(await Ln(n,p,i!==void 0)?await Promise.allSettled(m.map(b=>vt(n,{abi:ct,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 xr(n,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],P=Sr(b.reason,{abi:v.abi,address:v.address,args:v.args,functionName:v.functionName,sender:o});if(!r)throw P;u[k]={status:"failure",error:P}}return}w.indexes.forEach((k,v)=>{let P=t[k],S=b.value[v];try{if(!S)throw new Error("Multicall returned fewer results than calls.");if(!S.success)throw new Pr({data:S.returnData});if(!S.returnData||S.returnData==="0x")throw new Yt;let x=yt({abi:P.abi,functionName:P.functionName,args:P.args,data:S.returnData});u[k]={status:"success",result:x}}catch(x){let L=Sr(x,{abi:P.abi,address:P.address,args:P.args,functionName:P.functionName,sender:o});if(!r)throw L;u[k]={status:"failure",error:L}}})});for(let b=0;b<t.length;b++){if(u[b])continue;let y=new Error("Multicall returned no result for this call.");if(!r)throw y;u[b]={status:"failure",error:y}}return r?u:u.map(b=>b.result)}var Qm=0,Fn=class{key;name;uid;chain;transport;batch;request;constructor(e={}){let{batch:t,key:r="public",name:o="Public Client",retryCount:s,retryDelay:a,timeout:i}=e;this.chain=Zm(e.chain),this.key=r,this.name=o,this.batch=t,this.uid=`${r}-${++Qm}-${Math.random().toString(36).slice(2,8)}`;let c=(e.transport??Jm(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 kt(this,e)}readContract(e){return vt(this,e)}multicall(e){return Lr(this,e)}multicallRaw(e){return Zt(this,e)}getBlockNumber(){return mr(this)}getChainId(){return hr(this)}getBalance(e){return fr(this,e)}getCode(e){return Qt(this,e)}getStorageAt(e){return gr(this,e)}getTransactionCount(e){return yr(this,e)}getGasPrice(){return br(this)}estimateMaxPriorityFeePerGas(){return _a(this)}estimateGas(e){return wr(this,e)}getBlock(e){return kr(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 Jm(n,e){if(n)return ut(n);let t=e?.rpcUrls.default.http??[];return t.length>1?nn(t.map(r=>ut(r,{retryCount:1}))):ut(t[0])}function Zm(n){if(n===void 0)return;if(typeof n=="object")return n;let e=Nl(n);if(!e)throw new Ar(n);return e}function rn(n={}){return new Fn(n)}var Dl=new Map;function eh(n,e){return{id:parseInt(n,16),hexId:n,name:`Chain ${parseInt(n,16)}`,nativeCurrency:{name:"Native",symbol:"ETH",decimals:18},rpcUrls:{default:{http:e}},contracts:{multicall3:{address:re}}}}function Re(n,e={}){let{batch:t=!0,pinRpcUrl:r=!1,fallbackConcurrency:o,assumeMulticall3:s}=e,a=Tt(n),i=e.rpcUrl?.trim(),l=a?On(a):[],c=i?r?[i]:[...new Set([i,...l])]:l;if(c.length===0)throw new Ar(n);let d=`${a??n}|${c.join(",")}|${t?1:0}|${o??""}|${s?1:0}`,u=Dl.get(d);if(u)return u;let p=rn({chain:a&&!Ce(a)?eh(a,c):a,transport:c.length===1?ut(c[0]):nn(c.map(m=>ut(m,{retryCount:1}))),batch:t?{multicall:{fallbackConcurrency:o,assumeMulticall3:s}}:void 0});return Dl.set(d,p),p}function Ma(){Dl.clear()}function Ml(n,e){try{return Re(n,{rpcUrl:e?.trim()||void 0})}catch{return null}}async function Ae(n,e,t){let r=new Array(e.length).fill(null),o=e.length>0?Ml(n,t):null;if(!o)return r;let s=[];if(e.forEach((a,i)=>{!R(a.target)||!xn(a.callData)||s.push({index:i,target:a.target,callData:a.callData})}),s.length===0)return r;try{(await Zt(o,{calls:s})).forEach((i,l)=>{i.success&&(r[s[l].index]=i.returnData)})}catch{}return r}function Fa(n){return n?.status==="success"?n.result:void 0}async function Ol(n,e){try{return await n.multicall({contracts:e})}catch{return[]}}async function on(n,e,t){let r=e.map(()=>({symbol:null,decimals:null})),o=e.length>0?Ml(n,t):null;if(!o)return r;let s=[];if(e.forEach((l,c)=>{R(l)&&s.push({index:c,address:l})}),s.length===0)return r;let a=await Ol(o,s.flatMap(l=>[{address:l.address,abi:q,functionName:"symbol"},{address:l.address,abi:q,functionName:"decimals"}]));s.forEach((l,c)=>{let d=Fa(a[c*2]);typeof d=="string"&&d.trim()&&(r[l.index].symbol=d.trim()),r[l.index].decimals=Ca(Fa(a[c*2+1]))});let i=s.filter(l=>r[l.index].symbol===null);if(i.length>0){let l=await Ol(o,i.map(c=>({address:c.address,abi:vr,functionName:"symbol"})));i.forEach((c,d)=>{r[c.index].symbol=Ra(Fa(l[d]))})}return r}async function Lu(n,e,t){let r=new Array(e.length).fill(null),o=e.length>0?Ml(n,t):null;if(!o)return r;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 Ol(o,s.map(i=>({address:i.address,abi:Tr,functionName:"tokenURI",args:[i.tokenId]})))).forEach((i,l)=>{let c=Fa(i);if(typeof c!="string")return;let d=c.replace(/\0+$/,"").trim();d&&(r[s[l].index]=d)}),r}function xs(n){return Ir(String(n))??"0"}function Ir(n){let e=n.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let t=e[1]==="-"?"-":"",r=e[2]??"",o=e[3]??"";if(r===""&&o==="")return null;let s=e[4]?parseInt(e[4],10):0,a=r+o,i=r.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 Fl(n){let e=Ir(n);if(e===null||e.startsWith("-"))return null;let[t,r=""]=e.split(".");return{mant:BigInt(t+r),frac:r.length}}function Ba(n,e){let t=n<0n,r=(t?-n:n).toString(),o;if(e===0)o=r;else{let s=r.padStart(e+1,"0"),a=s.length-e;o=`${s.slice(0,a)}.${s.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return t?`-${o}`:o}function Bn(n,e){let t=Ir(n);if(t===null||t.startsWith("-"))return null;let[r,o=""]=t.split("."),s=o.slice(0,e).padEnd(e,"0");try{let a=BigInt(r||"0")*10n**BigInt(e)+BigInt(s||"0");return a>0n?a:null}catch{return null}}function qn(n){if(typeof n=="number")return Number.isFinite(n)&&n>0?xs(n):null;if(typeof n!="string")return null;let e=n.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=Ir(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function Dt(n,e){let t=Ir(n);if(t===null||e<0)return n;let r=t.startsWith("-"),[o,s=""]=(r?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 r?`-${i}`:i}function $n(n,e,t,r){let o=Fl(n);if(!o||t<=0n||r<0)return n;let s=o.mant*e*10n**BigInt(r)/(t*10n**BigInt(o.frac));return Ba(s,r)}function sn(n,e){let t=Fl(n),r=Fl(e);if(!t||!r){let i=Number(n),l=Number(e);return i<l?-1:i>l?1:0}let o=Math.max(t.frac,r.frac),s=t.mant*10n**BigInt(o-t.frac),a=r.mant*10n**BigInt(o-r.frac);return s<a?-1:s>a?1:0}var th={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"}]},nh="payment-required",rh="PAYMENT-SIGNATURE",oh="X-PAYMENT",sh="payment-response",ah="x-payment-response",ih=600,lh=300,ch={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 Iu(n){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(n),t=Array.from(e,r=>String.fromCharCode(r)).join("");return globalThis.btoa(t)}return Buffer.from(n,"utf8").toString("base64")}function Du(n){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return new TextDecoder("utf-8").decode(t)}return Buffer.from(n,"base64").toString("utf8")}function uh(){let n=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(n);else for(let t=0;t<32;t++)n[t]=Math.floor(Math.random()*256);return"0x"+Array.from(n,t=>t.toString(16).padStart(2,"0")).join("")}function Ou(n){let e=String(n);if(e.includes(":")){let[r,o]=e.split(":"),s=parseInt(o,10);if(r!=="eip155"||Number.isNaN(s))throw new Error(`Unsupported x402 network: ${n} (only EVM "eip155:*" is supported)`);return s}let t=ch[e.toLowerCase()];if(t===void 0)throw new Error(`Unsupported x402 network: ${n}`);return t}function Mu(n){if(!n.query||Object.keys(n.query).length===0)return n.url;let e=Object.entries(n.query).map(([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(r)}`).join("&");return n.url.includes("?")?`${n.url}&${e}`:`${n.url}?${e}`}function qa(n){let e=n.headers[nh];if(e){let o=Uu(dh(e));return o&&Array.isArray(o.accepts)?{version:2,payload:o}:null}let t=n.data,r=t&&typeof t=="object"?t:Uu(t);return r&&Array.isArray(r.accepts)?{version:1,payload:r}:null}function Uu(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e&&typeof e=="object"?e:null}catch{return null}}function dh(n){try{return Du(n)}catch{return null}}function ph(n){let e=n.amount??n.maxAmountRequired;return typeof n.scheme!="string"||typeof n.network!="string"||e==null||typeof n.asset!="string"||typeof n.payTo!="string"?null:{scheme:n.scheme,network:n.network,amount:String(e),asset:n.asset,payTo:n.payTo,...typeof n.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:n.maxTimeoutSeconds}:{},...n.extra&&typeof n.extra=="object"?{extra:n.extra}:{},...typeof n.resource=="string"?{resource:n.resource}:{},...typeof n.description=="string"?{description:n.description}:{},...typeof n.mimeType=="string"?{mimeType:n.mimeType}:{},...n.outputSchema!=null?{outputSchema:n.outputSchema}:{}}}function mh(n){let e=null;for(let t of n){let r=ph(t);if(r){if(r.scheme!=="exact"){e=`unsupported scheme "${r.scheme}"`;continue}try{return Ou(r.network),r}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 Bl(n,e,t,r){let o=qa(n);if(!o)throw new Error("402 response carries no x402 payment requirements");let{version:s,payload:a}=o,i=mh(a.accepts??[]);if(!t)throw new Error("No connected wallet address to build the payment from");let l=Ou(i.network),c=Math.floor(Date.now()/1e3),d={from:t,to:i.payTo,value:String(i.amount),validAfter:String(Math.max(0,c-ih)),validBefore:String(c+(i.maxTimeoutSeconds??lh)),nonce:uh()},u={domain:{name:i.extra?.name,version:i.extra?.version,chainId:l,verifyingContract:i.asset},types:th,primaryType:"TransferWithAuthorization",message:{...d}};return{request:{url:Mu(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}:{},...r?{userQuery:r}:{}}}async function hh(n,e,t,r){let o=Mu(e),s=await n.request(e.method??"GET",o,e.body,{headers:e.headers});if(s.status===402)return{status:"payment_required",challenge:Bl(s,e,t,r)};if(!s.ok)throw new Error(_(s));return{status:"ok",data:s.data}}async function ql(n,e,t){let{url:r,method:o,body:s,headers:a}=e.request,i=await n.request(o,r,s,{headers:{...a??{},...$l(e,t)}});if(i.ok)return i.data;throw new Error(gh(i)??_(i))}function fh(n){return qa(n)!==null}function Fu(n){let e=Bu(n);return e?.errorReason?e.errorReason:qa(n)?.payload.error??null}function gh(n){let e=Fu(n);return e?`x402 payment rejected: ${e}`:null}var yh={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 $l(n,e){let{requirements:t,authorization:r}=n,o={signature:e,authorization:r};if(n.x402Version===1){let a={x402Version:1,scheme:t.scheme,network:t.network,payload:o};return{[oh]:Iu(JSON.stringify(a))}}let s={x402Version:2,...n.resource!=null?{resource:n.resource}:{},accepted:bh(t),payload:o,...n.extensions!=null?{extensions:n.extensions}:{}};return{[rh]:Iu(JSON.stringify(s))}}function bh(n){let{resource:e,description:t,mimeType:r,outputSchema:o,...s}=n;return s}function Bu(n){let e=n.headers[sh]??n.headers[ah];if(!e)return null;try{return JSON.parse(Du(e))}catch{return null}}function wh(n,e){return n==null?e:yh[n]??`Chain ${n}`}async function qu(n){let e=n.requirements,r=n.resource?.description||e.description,o=n.chainId??null,s=null,a=null;if(o!=null){let[l]=await on("0x"+o.toString(16),[e.asset]);s=l?.symbol??null,a=l?.decimals??null}let i=String(e.amount);if(a!==null)try{i=Ba(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:wh(o,e.network),payTo:e.payTo,...r?{description:r}:{},resourceUrl:n.request.url}}function Hl(n){return async(e,t)=>{let r=n.getPayer(),o=n.getSigner();if(!r||!o)return null;let s;try{s=Bl(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},r)}catch{return null}let a;try{a=await o({typedData:s.typedData,display:await qu(s)})}catch{a=null}return a?$l(s,a):null}}var an=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Hn(n){if(!n||typeof n!="object")return!1;let e=n;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function Cs(n){if(n?.aborted)throw new an}function Vl(n,e){if(!e)return{signal:n.signal,cleanup:()=>{}};if(e.aborted)return n.abort(),{signal:n.signal,cleanup:()=>{}};let t=()=>n.abort();return e.addEventListener("abort",t),{signal:n.signal,cleanup:()=>e.removeEventListener("abort",t)}}var $u={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},kh="https://nft.keyring.app/api/gemini-stable",vh="https://generativelanguage.googleapis.com",Th=new Set([408,429,500,502,503,504]),Hu=3e4,$a=n=>new Promise(e=>setTimeout(e,n));function Ha(n,e,t){if(t!=null&&t>0)return Math.min(t,Hu);let r=Math.min(e*2**(n-1),Hu);return r/2+Math.random()*(r/2)}function Ah(n){if(!n)return null;let e=Number(n);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(n);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var ve=class{model;maxTokens;temperature;thinkingBudget;baseUrl;apiKey;requestSignal;constructor(e){this.model=e.model??"gemini-2.5-flash",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.thinkingBudget=e.thinkingBudget===void 0?0:e.thinkingBudget,this.apiKey=e.apiKey?.trim()??"",this.baseUrl=(e.baseUrl??(this.apiKey?vh:kh)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,t,r){let{systemInstruction:o,contents:s}=this.toContents(e),{maxRetries:a=5,retryDelayMs:i=1e3}=r??{},l=r?.signal??this.requestSignal;Cs(l);let c=s.length>0?s:[{role:"user",parts:[{text:"(continue)"}]}];if(r?._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=r?.thinkingBudget===void 0?this.thinkingBudget:r.thinkingBudget,u={maxOutputTokens:r?.maxOutputTokens??this.maxTokens,temperature:this.temperature};d!=null&&(u.thinkingConfig={thinkingBudget:d});let p={contents:c,generationConfig:u};o&&(p.systemInstruction=o),t?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],r?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):r?.googleSearch&&(p.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,f="Unknown error";for(let h=1;h<=a;h++){Cs(l);let g;try{g=await C.post(m,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(S){if(Hn(S))throw S;if(f=S instanceof Error?S.message:String(S),h>=a)break;await $a(Ha(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}`,!Th.has(g.status))throw new Error(f);if(h>=a)break;let x=Ah(g.headers["retry-after"]??null);await $a(Ha(h,i,x));continue}if(g.data==null||typeof g.data!="object"){if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,h>=a)break;await $a(Ha(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 $a(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 P=b.usageMetadata?{promptTokens:b.usageMetadata.promptTokenCount??0,completionTokens:b.usageMetadata.candidatesTokenCount??0,totalTokens:b.usageMetadata.totalTokenCount??0,thoughtsTokens:b.usageMetadata.thoughtsTokenCount??0,cachedTokens:b.usageMetadata.cachedContentTokenCount??0}:void 0;return{text:w,toolCalls:k,usage:P,finishReason:y.finishReason}}throw new Error(f)}toContents(e){let t=[],r=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){r.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){r.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o=[];for(let i of r){let l=o[o.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):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(u=>u.functionCall)||l.role==="model"&&l.parts.some(u=>u.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 r={},o=[];for(let s of t.parameters){let a={type:$u[s.type]??"STRING",description:s.description};s.type==="array"&&(a.items={type:$u[s.items?.type??"string"]??"STRING"}),r[s.name]=a,s.required&&o.push(s.name)}return{name:t.name,description:t.description,parameters:{type:"OBJECT",properties:r,required:o}}})}};var Ur=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,r){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,r),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 Dr=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],Ph=new Set(Dr),ln=[...Dr],Wl=new Set(ln),Be="0x1",Mr="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function Sh(n){return n.map(e=>Or[e]??e).join(", ")}function Va(n){let e=new Set;if(n)for(let r of n){let o=Wa(r);o&&e.add(o)}let t=Dr.filter(r=>!e.has(r));ln=t.length>0?[...t]:[...Dr],Wl=new Set(ln),Be=ln.includes("0x1")?"0x1":ln[0],Mr=Sh(ln)}var xh={"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 D(n){let e=Wa(n);return e&&Wl.has(e)?e:null}function Wa(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=xh[e];if(t)return t;let r=null;return/^0x[0-9a-f]+$/.test(e)?r=e:/^[0-9]+$/.test(e)&&(r="0x"+Number(e).toString(16)),r&&Ph.has(r)?r:null}function qe(n){return D(n)!==null}function $e(){return[...ln]}var cn=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${Mr}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Ot=n=>typeof n=="string"&&n.trim()!=="";function K(n,e){if(Ot(n)){let t=D(n);if(t)return t;throw new cn(n.trim())}if(Ot(e?.chain)){let t=D(e.chain);if(t)return t;throw new cn(e.chain.trim())}return null}function Ya(n,e){return D(n)??D(e?.chain)??void 0}var Or={"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(n){let e=Wa(n);return e&&Or[e]?Or[e]:typeof n=="string"&&n.trim()?n.trim():"the requested chain"}var Ch={"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 Vu(n,e){let t=Wa(n),r=t?Ch[t]:void 0;return!r||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${r}/tx/${e.trim()}`}var Rh={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function Wu(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return e?Rh[e]??null:null}var Eh={"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 Ga(n){let e=D(n);return e?Eh[e]??null:null}function Ka(n,e){if(!Ot(n)||!Ot(e))return null;let t=D(n),r=D(e);return!t||!r||t===r?null:{from:t,to:r,fromLabel:Or[t]??t,toLabel:Or[r]??r}}function Fr(n){return`Hex chain ID of the ${n} \u2014 same ids as \`chain\` (e.g. "0xa" Optimism, "0x2105" Base). ONLY set this when the user names a chain FOR THIS SIDE SPECIFICALLY, i.e. they named a chain per token \u2014 "swap ETH on Optimism to ETH on Base", "buy USDC on Base using ETH on Arbitrum". When the user names ONE chain for the whole request (or none), leave this EMPTY and use \`chain\` instead. Never copy the same chain into both sides.`}function ja(n,e){return{error:"cross_chain_not_supported",_instructions:`The user asked to ${n} from ${e.fromLabel} to ${e.toLabel} \u2014 that is a CROSS-CHAIN (bridge) request, which is NOT supported: a ${n} happens entirely on ONE network. Tell them, in their language, that ${n}ping between two different networks isn't supported yet, and that they can ${n} between tokens that are both on ${e.fromLabel}, or both on ${e.toLabel} (switching their wallet's network first). Do NOT proceed. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var Ze=`Hex chain ID \u2014 e.g. "0xa" Optimism, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0x38" BSC, "0x1" Ethereum, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. Set this WHENEVER the user names a network anywhere in their request \u2014 "swap USDC on Optimism", "buy PEPE on Base", "\u0111\u1ED5i USDC tr\xEAn Optimism", "mua PEPE tr\xEAn Base" \u2014 by mapping that name to its hex id from the list above. Do this EVEN IF it differs from the wallet's currently connected chain: that is a normal request, and the wallet is asked to switch networks when the transaction is signed. NEVER substitute the connected chain for a network the user named, and never leave this empty just because the two differ. OMIT it only when the user names no network at all \u2014 the connected wallet chain is then used automatically.`;function Yu(n,e){let t=typeof n=="string"?n.trim():"",r=e&&e.length?e.filter(s=>Wl.has(s)):[];return(r.length?r:ln).map(s=>{let a=Or[s]??s;return{label:a,prompt:t?`${t} (${a})`:a}})}function Br(n,e){return{actionButtons:Yu(e),_instructions:`The user wants to ${n} 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 ge=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=Yu(e,t)}},Rs=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 ce(n,e){if(Ot(n))return n.trim();if(Ot(e?.walletAddress))return e.walletAddress.trim();throw new Rs}function Pe(n,e,t){if(Ot(n)){let r=D(n);if(r)return r;throw new cn(n.trim())}if(Ot(e?.chain)){let r=D(e.chain);if(r)return r;throw new cn(e.chain.trim())}if(Ot(e?.walletAddress))throw new ge(typeof e?.query=="string"?e.query:void 0,t);return Be}var A=class{category;async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a=_h(s);return{toolName:this.name,callId:r,success:!0,data:a.data,duration:Date.now()-o,...a.actionButtons?{actionButtons:a.actionButtons}:{},...a.ui?{ui:a.ui}:{}}}catch(s){return s instanceof ge?{toolName:this.name,callId:r,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 Rs?{toolName:this.name,callId:r,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:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}};function _h(n){if(!n||typeof n!="object")return{data:n};let e=n,t=e.actionButtons,r=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(!r&&!s)return{data:n};let{actionButtons:a,ui:i,...l}=e;return{data:l,...r?{actionButtons:r}:{},...s?{ui:s}:{}}}function Gu(n){if(!n)return;let e=n.yieldProtocolV2;if(e!=null)return e;let t=n.yieldProtocol;return t??(e===null||t===null?null:void 0)}function Ku(n){let e=n?.newConfig?.yieldInfo;if(e?.assetToken){let t=e.assetDecimals==null||e.assetDecimals===""?NaN:Number(e.assetDecimals);return{address:String(e.assetToken).toLowerCase(),...Number.isFinite(t)?{decimals:t}:{},fixedPrice:e.assetFixedPrice??null}}return n?.yieldAsset}function Vn(n){let e=Gu(n),t=Ku(n);return e===void 0&&t===void 0?null:{yieldProtocol:e,yieldAsset:t}}var Nh="https://wallet-api.pantograph.app",Lh="0x0000000000000000000000000000000000000000",Qu={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},Ju={"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 Ih(n){return Qu[n.toLowerCase()]||n}function ju(n){let e=[];for(let[t,r]of Object.entries(n))if(r!=null)if(Array.isArray(r))for(let o of r)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);return e.join("&")}function Yl(n){let e=n,t=e.decimals,r=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,o=e.price,s=o!=null?parseFloat(String(o)):NaN,a=typeof e.symbolOnchain=="string"?e.symbolOnchain.trim():"";return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(r)?r:0,...a?{symbol:a}:{},...Number.isFinite(s)?{usd_price:s}:{}}}function zu(n){if(Array.isArray(n))return n;let e=n;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function Ue(n){if(n==null)return null;let e=typeof n=="number"?n:parseFloat(String(n));return Number.isFinite(e)?e:null}var za=new WeakSet;function Xu(n,e){let t=typeof n.symbolOnchain=="string"?n.symbolOnchain.trim():"",r=n.decimals,o=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,s=Ue(n.price_change_percentage_24h)??Ue(n.priceChange24h)??Ue(n.usd_price_24hr_percent_change)??Ue(n.price_change_24h)??Ue(n.priceChange),a={chainId:e,tokenAddress:n.address??n.token_address??"",name:n.name??null,symbol:t||n.symbol||null,decimals:o!=null&&Number.isFinite(o)?o:null,logo:n.logoURI??n.icon_image??n.logo??null,usdPrice:Ue(n.price)??Ue(n.usd_price),marketCap:Ue(n.market_cap)??Ue(n.marketCap),totalVolume:{"24h":Ue(n.total_volume)??Ue(n.volume24h)},pricePercentChange:{"24h":s}};return t&&za.add(a),a}var Uh=100;function Dh(n,e){let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t}var ye=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Nh).replace(/\/+$/,"")}tokensUrl(e,t){let r=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${r}?addresses=${encodeURIComponent(t)}`}async fetchTokensAll(e,t){let r=Dh(t,Uh);return(await Promise.all(r.map(async s=>{try{let a=`${this.baseUrl}/keyrings/tokens/all/${e}?addresses=${encodeURIComponent(s.join(","))}`,i=await C.get(a);return i.ok?zu(i.data):[]}catch{return[]}}))).flat()}async enrichTokenPrices(e,t){let r=new Map;if(e.length===0)return r;try{let o=e.map(i=>i.token_address),s=await this.fetchTokensAll(parseInt(t,16),o),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}:{}});let d=Vn(i);d&&r.set(l,d)}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 r}async getYieldPricingTokens(e,t){let r=(t??[]).map(s=>String(s??"").trim()).filter(Boolean);if(r.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{return await this.fetchTokensAll(o,r)}catch{return[]}}async getTokenMetadata(e,t){try{let r=this.tokensUrl(t,e),o=await C.get(r);if(!o.ok)return null;let s=zu(o.data),a=e.toLowerCase()===Lh,i=s.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return i?Yl(i):null}catch{return null}}async getTokensMetadata(e,t){let r={};if(e.length===0)return r;try{let o=await this.fetchTokensAll(parseInt(t,16),e),s=new Set(e.map(a=>a.toLowerCase()));for(let a of o){let i=a.address?.toLowerCase()||a.token_address?.toLowerCase()||(a.address===""?"":null);i&&s.has(i)&&(r[i]=Yl(a))}}catch{}return r}async searchTokensByKey(e){let{key:t,chain:r}=e;if(!t)return{success:!1,error:"Search key is required"};let s=parseInt(r||Be,16);if(isNaN(s))return{success:!1,error:`Invalid hex chain: ${r}`};try{let a=ju({chainId:s,key:t}),i=`${this.baseUrl}/token-list/all?${a}`,l=await C.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(Yl)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||Be,r=5,o=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let s=Ju[t.toLowerCase()]??[],a=o!=null?o+s.length:r+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=>Xu(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=o!=null?[...p,...m].slice(0,o):[...p,...m.slice(0,r)];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 r=e.filter(s=>s.tokenAddress&&(s.marketCap==null||s.totalVolume?.["24h"]==null||!za.has(s)));if(r.length===0)return;let o=await this.getTokensMetadata(r.map(s=>s.tokenAddress),t);for(let s of r){let a=o[s.tokenAddress.toLowerCase()];if(!a)continue;let i=typeof a.symbolOnchain=="string"?a.symbolOnchain.trim():"";i&&!za.has(s)&&(s.symbol=i,za.add(s)),s.marketCap==null&&(s.marketCap=Ue(a.market_cap)??Ue(a.marketCap)),s.totalVolume?.["24h"]==null&&(s.totalVolume={"24h":Ue(a.total_volume)??Ue(a.volume24h)})}}async fetchTopGainers(e,t,r="24h"){let o=parseInt(e,16),s=ju({chainId:o,duration:r,limit:t}),a=`${this.baseUrl}/token-list/all/top-gainers${s?`?${s}`:""}`,i=[];for(let l=0;l<5;l++){let c=await C.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=>Xu(l,e))}async getTopGainers(e){let t=e?.chain||Be,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,o=e?.duration||"24h";try{let s=await this.fetchTopGainers(t,r,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 X(n,e,t,r=[]){return{target:n,callData:M({abi:e,functionName:t,args:r})}}var Wn=1e27,Xa=10n**27n,Es=31536e3,Oh=10;function et(n){return Number.isFinite(n)&&n>=0&&n<=Oh?n:null}function Gl(n){return Math.expm1(n)}function tt(n,e){return Number(n)/10**e}function _s(n){return new Date(n).toISOString().slice(0,10)}async function un(n,e,t){let r=`${t.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${n.token}?range=h&day=${7}`,o=await C.get(r);if(!o.ok)throw new Error(_(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 At=class{underlyingCall(e){return X(e.contract,wt,"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 r=ee(e);return r===null?null:tt(r,t.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,t){return this.balanceIsUnderlying?null:X(e.contract,wt,"convertToAssets",[t])}},Pt=class extends At{type="spark";balanceIsUnderlying=!1;sizeCall(e){return X(e.contract,wt,"totalAssets")}fetchApy(e,t,r,o){return un(e,t,r)}};var Kl=[{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 jl=[{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 Ja=[{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"}]}]}],qr=[{type:"function",name:"UNDERLYING_ASSET_ADDRESS",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"POOL",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}],zl=[{type:"function",name:"ADDRESSES_PROVIDER",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var Mt=[{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"}],Xl=[{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 $r=[{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"vsr",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],dn=[{inputs:[],name:"getAPR",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getConversionRate",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],Ql=[{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 Jl=[{inputs:[],name:"manager",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}],Zl=[{inputs:[],name:"pool",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var Bh=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!, $reserve: ReserveRequest!) {
|
|
1
|
+
"use strict";var em=Object.create;var ga=Object.defineProperty;var tm=Object.getOwnPropertyDescriptor;var nm=Object.getOwnPropertyNames;var rm=Object.getPrototypeOf,om=Object.prototype.hasOwnProperty;var sm=(n,e)=>{for(var t in e)ga(n,t,{get:e[t],enumerable:!0})},Fc=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of nm(e))!om.call(n,o)&&o!==t&&ga(n,o,{get:()=>e[o],enumerable:!(r=tm(e,o))||r.enumerable});return n};var am=(n,e,t)=>(t=n!=null?em(rm(n)):{},Fc(e||!n||!n.__esModule?ga(t,"default",{value:n,enumerable:!0}):t,n)),im=n=>Fc(ga({},"__esModule",{value:!0}),n);var ew={};sm(ew,{AI_AGENT_TOOL_NAMES:()=>$i,AbortError:()=>sn,AgentCore:()=>zi,ApproveTokenTool:()=>ns,BaseNftAiTool:()=>xt,BaseSwapProvider:()=>yn,BaseTool:()=>A,BaseWalletActionTool:()=>st,BuyTokenTool:()=>rs,CachedResource:()=>_t,ChatHistory:()=>as,CoinpoolConfigApi:()=>js,DEFAULT_CHAIN:()=>Be,DEFAULT_PROVIDER:()=>Bt,DEFAULT_RPC_BY_CHAIN:()=>Je,DEFILLAMA_EXTRA_SIGNALS:()=>ft,DEFILLAMA_POOL_CHAIN_HEXES:()=>Go,DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION:()=>Ye,DebridgeProvider:()=>Io,DefiLlamaEstimatePoolYieldTool:()=>Jo,DefiLlamaPoolByAddressTool:()=>Qo,DefiLlamaPoolCandidateResolver:()=>Zo,DefiLlamaPoolDetailTool:()=>Xo,DefiLlamaPoolSearchTool:()=>zo,DefiLlamaPoolService:()=>Me,DefiLlamaTopPoolsTool:()=>jo,EstimatePoolYieldTool:()=>Fo,GeminiProvider:()=>ve,GeminiSearchAiTool:()=>Ao,HEX_TO_PANTOGRAPH:()=>Xu,KeyringSettingApi:()=>Qs,KnowledgeBase:()=>ls,LendingMarketDetailTool:()=>mo,LendingMarketsTool:()=>po,LendingReadService:()=>co,LendingService:()=>dt,LendingSupplyService:()=>uo,MULTICALL3_ADDRESS:()=>re,ManageLiquidityRedirectTool:()=>Zn,MoralisService:()=>O,NATIVE_GAS_LIMIT:()=>Lp,NFC_AGENT_TOOL_NAMES:()=>qi,NFC_AMAZON_DEFAULT_DOMAIN:()=>fc,NFC_AMAZON_DOMAINS:()=>hc,NFTContractInfoTool:()=>bo,NFTMetadataTool:()=>wo,NFT_AGENT_TOOL_NAMES:()=>Bi,NfcBuyTool:()=>To,NfcInfoTool:()=>vo,NoFormTool:()=>sa,OpenAddLiquidityFormTool:()=>Xn,OpenSupplyFormTool:()=>fo,POOL_UNISWAP_AGENT_TOOL_NAMES:()=>Vi,PantographService:()=>ye,PoolByAddressTool:()=>Mo,PoolDetailTool:()=>Do,PoolFallbackAiTool:()=>Po,PoolPriceRangesTool:()=>Jn,PoolSearchTool:()=>Oo,PoolService:()=>ce,PoolSwapRouter:()=>Eo,PreviewAddLiquidityTool:()=>Qn,PublicClient:()=>On,RelayProvider:()=>Co,Router:()=>cs,SUPPLIABLE_TYPES:()=>ac,SUPPORTED_CHAINS:()=>Or,SUPPORTED_CHAINS_LABEL:()=>Fr,SWAP_PROVIDER_CONFIG:()=>Lo,SendNativeTool:()=>es,SendNftTool:()=>ss,SendTokenTool:()=>ts,Subagent:()=>ne,SubgraphAddPoolTool:()=>Yo,SubgraphCoinPoolPairsTool:()=>Wo,SubgraphPoolByAddressTool:()=>$o,SubgraphPoolByPositionIdTool:()=>Ho,SubgraphPoolSearchTool:()=>Bo,SubgraphPositionDetailTool:()=>Vo,SubgraphTrendingPoolsTool:()=>qo,Summarizer:()=>is,SwapProviderFactory:()=>Xs,SwapRouter:()=>Ro,SwapRouterRegistry:()=>zs,SwapTokenTool:()=>os,Synthesizer:()=>us,TOKEN_AGENT_TOOL_NAMES:()=>Fi,TRANSFER_TOPIC:()=>yp,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Qu,TokenAnalyticsTool:()=>Kr,TokenHoldersTool:()=>Gr,TokenInfoTool:()=>Yr,TokenScoreTool:()=>jr,ToolRegistry:()=>Dr,TopGainersTool:()=>Xr,TopPoolsTool:()=>Uo,TransactionByHashTool:()=>lo,TrendingTokensTool:()=>zr,UNISWAP_CHAIN_SLUG:()=>Zs,UNRESOLVED_ASSET:()=>Wn,UpstashKnowledgeBase:()=>Tn,UserSwapRouter:()=>_o,WALLET_ACTION_AGENT_TOOL_NAMES:()=>Wi,WALLET_AGENT_TOOL_NAMES:()=>Mi,WalletApprovalsTool:()=>so,WalletDefiPositionsTool:()=>ao,WalletDefiProtocolPositionsTool:()=>io,WalletHistoryTool:()=>eo,WalletLendingPositionsTool:()=>ho,WalletNFTsTool:()=>yo,WalletNftTransfersTool:()=>no,WalletPnlSummaryTool:()=>ro,WalletPnlTool:()=>oo,WalletTokenBalancesTool:()=>Zr,WalletTokenTransfersTool:()=>to,WebsiteTrustKeyringAgent:()=>Xi,ZERO_ADDRESS:()=>le,amazonDomainForLanguage:()=>gc,apiClient:()=>C,applyYieldConversions:()=>ni,buildApprovals:()=>Ci,buildChallenge:()=>Bl,buildRangePresets:()=>kc,buildUniswapPoolUrl:()=>Xe,call:()=>kt,canDeriveV3PoolAddress:()=>Sc,chains:()=>_n,checkNativeGasAffordable:()=>na,checksumAddress:()=>lr,clampTick:()=>Et,clearPublicClientCache:()=>Ma,coinpoolConfigApi:()=>wn,compareDecimal:()=>on,completeX402:()=>ql,configureSupportedChains:()=>Va,configureSwapProvider:()=>Si,convertSusdsShares:()=>Vn,createAiAgent:()=>da,createDefaultSubagents:()=>Yi,createNfcAgent:()=>ua,createNftAgent:()=>ca,createPoolUniswapAgent:()=>pa,createPublicClient:()=>rn,createTokenAgent:()=>la,createTransport:()=>tn,createWalletActionAgent:()=>ma,createWalletAgent:()=>ia,createX402SignatureProvider:()=>Hl,decodeAbiParameters:()=>Ie,decodeErrorResult:()=>mr,decodeFunctionData:()=>hl,decodeFunctionResult:()=>yt,defiLlamaPoolInfoScope:()=>Ve,defiLlamaPoolSupportsLabel:()=>We,deriveV3PoolAddress:()=>xc,displayFromChallenge:()=>Bu,effectivePriceUSD:()=>qs,encodeAbiParameters:()=>ur,encodeApprove:()=>xi,encodeErrorResult:()=>cl,encodeFunctionData:()=>M,encodeSignedHeader:()=>$l,erc1155Abi:()=>Na,erc20Abi:()=>q,erc20Abi_bytes32:()=>Tr,erc721Abi:()=>Ar,estimateGas:()=>kr,estimateNativeGasReserveWei:()=>ea,estimateTransactionFeeWei:()=>Rc,ethCallAt:()=>ud,ethCallByChain:()=>Cf,exactAmountString:()=>Fn,extractOutRaw:()=>mp,extractQuoteError:()=>hp,fallback:()=>nn,feeWeiToNative:()=>Ec,fetchTopMarketplaces:()=>yc,fetchUnderlyingPricesUSD:()=>Vs,floorToDecimals:()=>je,formatDefiLlamaPool:()=>_e,getAbiItem:()=>Xt,getAddress:()=>ol,getBalance:()=>gr,getBlock:()=>vr,getBlockNumber:()=>hr,getChain:()=>Ce,getChainContractAddress:()=>ks,getChainId:()=>fr,getChainMeta:()=>mt,getCode:()=>Qt,getDefaultRpcUrl:()=>El,getGasPrice:()=>wr,getNativeTokenInfo:()=>jn,getPublicClient:()=>Re,getRevertReason:()=>gs,getRpcOverrides:()=>Ps,getStorageAt:()=>yr,getTokenPriceUSD:()=>Za,getTransactionCount:()=>br,http:()=>ut,humanToWei:()=>Mn,ingestKnowledgeBase:()=>Qp,isAbortError:()=>qn,isAddress:()=>R,isAddressEqual:()=>sl,isPaymentRequired:()=>gh,isShareBasedProtocol:()=>Vr,isShareBasedYieldToken:()=>td,isSupplyChain:()=>ii,keyringSettingApi:()=>bn,listCandidateChains:()=>sc,listSupplyChains:()=>ai,mulDivFloor:()=>Bn,multicall:()=>Ir,multicall3Abi:()=>ct,multicallRaw:()=>Zt,nativeGasShortfall:()=>Up,nfcAmazonSearchUrl:()=>bi,normaliseCountry:()=>wi,normalizeDecimal:()=>Ur,normalizePriceRangeToPool:()=>xo,parseAbi:()=>bl,parseAbiItem:()=>Ea,parseAbiParameters:()=>bs,pickLogo:()=>qt,planYieldTokenConversions:()=>nc,priceToTick:()=>Kn,protocolLabelFor:()=>ze,psm3For:()=>ti,readContract:()=>vt,readPaymentError:()=>Mu,readPaymentRequired:()=>qa,readProtocolFeeWei:()=>Ri,readReceipt:()=>Fu,readSpendableBalance:()=>oa,readTokenUsdPrice:()=>ra,registerMaybeNoForm:()=>Oi,requestWithX402:()=>fh,resolveGasLimit:()=>Ip,resolveNfcShopLinks:()=>ko,resolveRawYieldAsset:()=>Gu,resolveRawYieldIdentity:()=>$n,resolveRawYieldProtocol:()=>Yu,resolveRpcUrl:()=>Dn,resolveRpcUrls:()=>Un,resolveTokenPriceUSD:()=>$s,roundTickToSpacing:()=>Rt,rpcCall:()=>cd,setRpcOverrides:()=>In,spendableNative:()=>ta,swapProviderFactory:()=>No,swapRouterRegistry:()=>Pi,tickToPrice:()=>pt,toEventSelector:()=>al,toFunctionSelector:()=>Ut,toPantographChain:()=>Uh,toPlainDecimal:()=>xs,unitPriceUSD:()=>Wr,valueYieldTokens:()=>ri,weiToHuman:()=>Ba});module.exports=im(ew);var qc=am(require("axios"));var Bc="0.3.19";var cm=`keyring-agent-core/${Bc} (Keyring Chatbot Agent; +https://keyring.app)`,Ji=null;function $c(n){Ji=n}var um=["payment-signature","x-payment"];function dm(n){return n?Object.keys(n).some(e=>um.includes(e.toLowerCase())):!1}var Hc;function ps(n){Hc=n}var pm=3e4,mm=typeof process<"u"&&process.versions?.node!=null,Zi=class{instance;constructor(e={}){this.instance=qc.default.create({baseURL:e.baseURL,timeout:e.timeout??pm,validateStatus:()=>!0,headers:{Accept:"application/json",...mm?{"Accept-Encoding":"gzip, deflate, br","User-Agent":e.userAgent??cm}:{},...e.headers}})}async request(e,t,r,o={}){let s=o.signal??Hc,a=await this.instance.request({...o,signal:s,method:e,url:t,data:r}),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&&Ji&&!dm(o.headers)){let c=await Ji(l,{url:t,method:String(e),body:r,headers:o.headers});if(c)return this.request(e,t,r,{...o,headers:{...o.headers,...c}})}return l}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,r){return this.request("POST",e,t,r)}put(e,t,r){return this.request("PUT",e,t,r)}patch(e,t,r){return this.request("PATCH",e,t,r)}delete(e,t){return this.request("DELETE",e,void 0,t)}},C=new Zi;function _(n){let{data:e,status:t,statusText:r}=n,o=r?`HTTP ${t} ${r}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||o;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 o}function hm(n){return n instanceof F?n.details||n.shortMessage:n instanceof Error?n.message:typeof n=="string"?n:""}var F=class extends Error{name="BaseError";shortMessage;details;metaMessages;constructor(e,t={}){let r=t.details??hm(t.cause),o=t.metaMessages??[],s=[e||"An error occurred.",...o.length>0?["",...o]:[],...r?["",`Details: ${r}`]:[]].join(`
|
|
2
|
+
`);super(s,t.cause!==void 0?{cause:t.cause}:void 0),this.shortMessage=e,this.details=r,this.metaMessages=o,t.name&&(this.name=t.name)}walk(e){return Vc(this,e)}};function Vc(n,e){if(e?.(n))return n;let t=n&&typeof n=="object"?n.cause:void 0;return t!=null?Vc(t,e):e?null:n}var Wt=class extends F{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."]})}},ya=class extends F{name="AbiEncodingLengthMismatchError";constructor({expectedLength:e,givenLength:t}){super("ABI encoding parameters/values length mismatch.",{metaMessages:[`Expected length (parameters): ${e}`,`Given length (values): ${t}`]})}},ba=class extends F{name="AbiEncodingArrayLengthMismatchError";constructor({expectedLength:e,givenLength:t,type:r}){super(`ABI encoding array length mismatch for type ${r}.`,{metaMessages:[`Expected length: ${e}`,`Given length: ${t}`]})}},it=class extends F{name="InvalidAbiValueError";constructor({type:e,value:t,reason:r}){super(`Invalid value for ABI type "${e}".`,{metaMessages:[`Value: ${Wc(t)}`,`Reason: ${r}`]})}},wa=class extends F{name="IntegerOutOfRangeError";constructor({type:e,value:t,min:r,max:o}){super(`Number "${t}" is not in safe ${e} range.`,{metaMessages:[`Range: ${r} \u2026 ${o}`]})}},sr=class extends F{name="InvalidAddressError";constructor(e){super(`Address "${Wc(e)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]})}};function Wc(n){if(typeof n=="bigint")return n.toString();if(typeof n=="string")return n;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}var ka=class extends F{name="AbiEncodingBytesSizeMismatchError";constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" does not match expected size of bytes${e}.`)}},Yt=class extends F{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."]})}},va=class extends F{name="AbiDecodingDataSizeTooSmallError";data;params;size;constructor({data:e,params:t,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${t.map(o=>o.type).join(", ")})`,`Data: ${e} (${r} bytes)`]}),this.data=e,this.params=t,this.size=r}},ar=class extends F{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."]})}},Ta=class extends F{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."]})}},Gt=class extends F{name="InvalidAbiSignatureError";constructor(e,t){super(`Invalid ABI signature: "${e}".`,{metaMessages:t?[t]:['Expected e.g. "function balanceOf(address owner) view returns (uint256)".']})}};var fm=/^0x[0-9a-fA-F]*$/;function Sn(n,{strict:e=!0}={}){return typeof n!="string"?!1:e?fm.test(n):n.startsWith("0x")}function gt(n){return n.startsWith("0x")||n.startsWith("0X")?n.slice(2):n}function ms(n){return typeof n=="string"?Math.ceil(gt(n).length/2):n.length}function xn(n,e,t){let r=gt(n),o=(e??0)*2,s=t===void 0?r.length:t*2;return`0x${r.slice(o,s)}`}function Aa(n){return`0x${n.map(gt).join("")}`}function Cn(n){let e=new Uint8Array(n.reduce((r,o)=>r+o.length,0)),t=0;for(let r of n)e.set(r,t),t+=r.length;return e}function Kt(n){let e=gt(n),t=e.length%2?`0${e}`:e,r=new Uint8Array(t.length/2);for(let o=0;o<r.length;o++)r[o]=parseInt(t.slice(o*2,o*2+2),16);return r}function It(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`0x${e}`}function el(n){return new TextEncoder().encode(n)}function tl(n){return new TextDecoder().decode(n)}function Fe(n,e={}){let{size:t,signed:r}=e,o=BigInt(n);if(o<0n){if(!t)throw new Error("numberToHex: negative values require a `size`");o+=1n<<BigInt(t*8)}else if(r&&t){let a=(1n<<BigInt(t*8-1))-1n;if(o>a)throw new Error(`numberToHex: ${n} overflows int${t*8}`)}let s=o.toString(16);if(!t)return`0x${s}`;if(s.length>t*2)throw new Error(`numberToHex: ${n} overflows ${t} bytes`);return`0x${s.padStart(t*2,"0")}`}function nl(n,e=32){if(n.length>e)throw new Error(`padLeft: ${n.length} bytes exceeds ${e}`);let t=new Uint8Array(e);return t.set(n,e-n.length),t}function rl(n,e=32){if(n.length>e)throw new Error(`padRight: ${n.length} bytes exceeds ${e}`);let t=new Uint8Array(e);return t.set(n),t}function Rn(n){let e=1n<<256n,t=(n%e+e)%e;return Kt(t.toString(16).padStart(64,"0"))}function ir(n,{signed:e=!1}={}){let t=BigInt(It(n));if(!e)return t;let r=BigInt(n.length*8);return t>=1n<<r-1n?t-(1n<<r):t}function lt(n,{signed:e=!1}={}){return gt(n)?ir(Kt(n),{signed:e}):0n}function Pa(n,e={}){return Number(lt(n,e))}var Yc=require("js-sha3");var gm=/^0x[0-9a-fA-F]{40}$/;function R(n){return typeof n=="string"&&gm.test(n)}function lr(n){let e=gt(n).toLowerCase(),t=(0,Yc.keccak_256)(e),r="";for(let o=0;o<e.length;o++)r+=parseInt(t[o],16)>=8?e[o].toUpperCase():e[o];return`0x${r}`}function ol(n){if(!R(n))throw new Error(`Address "${n}" is invalid.`);return lr(n)}function sl(n,e){return R(n)&&R(e)&&n.toLowerCase()===e.toLowerCase()}var Sa=require("js-sha3");function xa(n){return`0x${(0,Sa.keccak_256)(n)}`}function Gc(n){return`0x${(0,Sa.keccak_256)(new TextEncoder().encode(n))}`}function jt(n){let e=n.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function zt(n){return n.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1").replace(/^byte(\[|$)/,"bytes1$1")}function hs(n){let e=zt(n.type);return e==="tuple"||e.startsWith("tuple[")?`(${(n.components??[]).map(hs).join(",")})${e.slice(5)}`:e}function cr(n){return`${n.name??""}(${(n.inputs??[]).map(hs).join(",")})`}function Ut(n){let e=typeof n=="string"?n:cr(n);return`0x${(0,Sa.keccak_256)(new TextEncoder().encode(e)).slice(0,8)}`}function al(n){let e=typeof n=="string"?n:cr(n);return Gc(e)}function Kc(n,e){let t=zt(e.type),r=jt(t);if(r){let[o,s]=r;return!Array.isArray(n)||o!==null&&n.length!==o?!1:n.every(a=>Kc(a,{...e,type:s}))}if(t==="tuple"){let o=e.components??[];return Array.isArray(n)?n.length===o.length:typeof n=="object"&&n!==null}return t==="address"?typeof n=="string"&&/^0x[0-9a-fA-F]{40}$/.test(n):t==="bool"?typeof n=="boolean":t==="string"?typeof n=="string":t.startsWith("bytes")?typeof n=="string"||n instanceof Uint8Array:t.startsWith("uint")||t.startsWith("int")?typeof n=="number"||typeof n=="bigint"||typeof n=="string":!0}function Xt({abi:n,name:e,args:t,type:r}){let o=r??"function",s=n.filter(i=>(i.type??"function")===o);if(e.startsWith("0x")&&e.length===10)return s.find(i=>Ut(i)===e.toLowerCase());if(e.includes("("))return s.find(i=>cr(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)=>Kc(t[d],c))})??a[0]}function En(n){let e=Xt(n);if(!e)throw new Ta({name:n.name,type:n.type??"function"});return e}function jc(n){let e=new Uint8Array(Math.ceil(n.length/32)*32);return e.set(n),{dynamic:!0,encoded:Cn([Rn(BigInt(n.length)),e])}}function zc(n,e){let t=n.slice(e.length),r=t===""?256:Number(t);if(!Number.isInteger(r)||r<8||r>256||r%8!==0)throw new Wt(n);return r}function Xc(n,e){if(typeof n=="bigint")return n;if(typeof n=="number"){if(!Number.isInteger(n))throw new it({type:e,value:n,reason:"expected an integer, got a fractional number"});return BigInt(n)}if(typeof n=="string"&&n.trim()!=="")try{return BigInt(n.trim())}catch{throw new it({type:e,value:n,reason:"string is not a valid integer"})}throw new it({type:e,value:n,reason:"expected a bigint, number or numeric string"})}function Qc(n,{bits:e,signed:t,type:r}){let o=t?(1n<<BigInt(e-1))-1n:(1n<<BigInt(e))-1n,s=t?-(1n<<BigInt(e-1)):0n;if(n<s||n>o)throw new wa({type:r,value:n,min:s,max:o})}function Jc(n,e){if(n instanceof Uint8Array)return n;if(typeof n=="string"){if(!Sn(n))throw new it({type:e,value:n,reason:"expected 0x-prefixed hex"});return Kt(n)}throw new it({type:e,value:n,reason:"expected a hex string or Uint8Array"})}function il(n,e){let t=jt(n.type);if(t){let[o,s]=t;if(!Array.isArray(e))throw new it({type:n.type,value:e,reason:"expected an array"});return ym({...n,type:s},e,o,n.type)}if(n.type==="tuple")return bm(n,e);let r=zt(n.type);if(r==="address"){if(!R(e))throw new sr(e);return{dynamic:!1,encoded:nl(Kt(gt(e).toLowerCase()))}}if(r==="bool"){if(typeof e!="boolean")throw new it({type:r,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(r)){let o=Xc(e,r);return Qc(o,{bits:zc(r,"uint"),signed:!1,type:r}),{dynamic:!1,encoded:Rn(o)}}if(/^int\d*$/.test(r)){let o=Xc(e,r);return Qc(o,{bits:zc(r,"int"),signed:!0,type:r}),o<0n&&(o+=1n<<256n),{dynamic:!1,encoded:Rn(o)}}if(/^bytes\d+$/.test(r)){let o=Number(r.slice(5));if(o<1||o>32)throw new Wt(n.type);let s=Jc(e,r);if(s.length!==o)throw new ka({expectedSize:o,value:String(e)});return{dynamic:!1,encoded:rl(s)}}if(r==="bytes")return jc(Jc(e,r));if(r==="string"){if(typeof e!="string"&&!(e instanceof Uint8Array))throw new it({type:r,value:e,reason:"expected a string"});return jc(typeof e=="string"?el(e):e)}throw new Wt(n.type)}function ll(n){let e=0;for(let{dynamic:s,encoded:a}of n)e+=s?32:a.length;let t=[],r=[],o=0;for(let{dynamic:s,encoded:a}of n)s?(t.push(Rn(BigInt(e+o))),r.push(a),o+=a.length):t.push(a);return Cn([...t,...r])}function ym(n,e,t,r){let o=t===null;if(!o&&e.length!==t)throw new ba({expectedLength:t,givenLength:e.length,type:r});let s=!1,a=[];for(let i of e){let l=il(n,i);l.dynamic&&(s=!0),a.push(l)}if(o||s){let i=ll(a);if(!o)return{dynamic:!0,encoded:i};let l=Rn(BigInt(a.length));return{dynamic:!0,encoded:a.length>0?Cn([l,i]):l}}return{dynamic:!1,encoded:Cn(a.map(i=>i.encoded))}}function bm(n,e){let t=n.components??[],r=!1,o=[];for(let s=0;s<t.length;s++){let a=t[s],i=il(a,Array.isArray(e)?e[s]:e[a.name??""]);i.dynamic&&(r=!0),o.push(i)}return{dynamic:r,encoded:r?ll(o):Cn(o.map(s=>s.encoded))}}function ur(n,e){if(n.length!==e.length)throw new ya({expectedLength:n.length,givenLength:e.length});return n.length===0?"0x":It(ll(n.map((t,r)=>il(t,e[r]))))}function M({abi:n,functionName:e,args:t=[]}){let r=En({abi:n,name:e,args:t,type:"function"}),o=Ut(r),s=r.inputs??[];return s.length===0?o:Aa([o,ur(s,t)])}function cl({abi:n,errorName:e,args:t=[]}){let r=En({abi:n,name:e,args:t,type:"error"}),o=r.inputs??[],s=Ut(r);return o.length===0?s:Aa([s,ur(o,t)])}function wm(n){let e=n.replace(/^u?int/,"");return e?Number(e):256}function fs(n,e){if(e<0||e+32>n.length)throw new ar({position:e,length:n.length});return n.subarray(e,e+32)}function pl(n,e){let t=ir(fs(n,e));if(t>BigInt(n.length))throw new ar({position:Number(t),length:n.length});return Number(t)}function ul(n){let e=jt(n.type);if(e){let[r,o]=e;return r===null||ul({...n,type:o})}if(n.type==="tuple")return(n.components??[]).some(ul);let t=zt(n.type);return t==="bytes"||t==="string"}function dl(n){let e=jt(n.type);if(e){let[t,r]=e;return t===null?32:t*dl({...n,type:r})}return n.type==="tuple"?(n.components??[]).reduce((t,r)=>t+dl(r),0):32}function ml(n,e,t){let r=[],o=e;for(let s of t)ul(s)?(r.push(Zc(n,e+pl(n,o),s)),o+=32):(r.push(Zc(n,o,s)),o+=dl(s));return r}function km(n,e,t,r){let o=r===null?pl(n,e):r,s=r===null?e+32:e;return ml(n,s,new Array(o).fill(t))}function vm(n,e,t){let r=t.components??[],o=ml(n,e,r);if(r.length===0||r.some(i=>!i.name))return o;let a={};return r.forEach((i,l)=>{a[i.name]=o[l]}),a}function Zc(n,e,t){let r=jt(t.type);if(r){let[s,a]=r;return km(n,e,{...t,type:a},s)}if(t.type==="tuple")return vm(n,e,t);let o=zt(t.type);if(o==="address")return lr(It(fs(n,e).subarray(12)));if(o==="bool")return ir(fs(n,e))!==0n;if(/^u?int\d*$/.test(o)){let s=o.startsWith("int"),a=ir(fs(n,e),{signed:s});return wm(o)>48?a:Number(a)}if(/^bytes\d+$/.test(o)){let s=Number(o.slice(5));return It(fs(n,e).subarray(0,s))}if(o==="bytes"||o==="string"){let s=pl(n,e),a=e+32;if(a+s>n.length)throw new ar({position:a+s,length:n.length});let i=n.subarray(a,a+s);return o==="bytes"?It(i):tl(i)}throw new Wt(t.type)}function Ie(n,e){let t=typeof e=="string"?Kt(e):e;if(t.length===0){if(n.length>0)throw new Yt;return[]}if(t.length<32)throw new va({data:typeof e=="string"?e:It(e),params:n,size:t.length});return ml(t,0,n)}function ee(n){if(!n)return null;try{let[e]=Ie([{type:"uint256"}],n);return e}catch{return null}}function B(n){if(!n)return null;try{let[e]=Ie([{type:"address"}],n),t=e;return/^0x0{40}$/i.test(t)?null:t}catch{return null}}function dr(n){if(!n)return null;try{let[e]=Ie([{type:"string"}],n),t=eu(e);if(t)return t}catch{}try{let[e]=Ie([{type:"bytes32"}],n);return Ra(e)}catch{return null}}function pr(n){return Ca(ee(n))}function Ca(n){let e=typeof n=="bigint"?Number(n):typeof n=="number"?n:NaN;return Number.isFinite(e)&&e>=0&&e<=36?e:null}function Ra(n){return typeof n!="string"||!n.startsWith("0x")?null:eu(Buffer.from(n.slice(2),"hex").toString("utf8"))||null}function eu(n){return n.replace(/[^\x20-\x7e]/g,"").trim()}function yt({abi:n,functionName:e,args:t,data:r}){let s=En({abi:n,name:e,args:t,type:"function"}).outputs??[],a=Ie(s,r);if(a.length!==0)return a.length===1?a[0]:a}function hl({abi:n,data:e}){let t=xn(e,0,4),r=En({abi:n,name:t,type:"function"}),o=r.inputs??[];return{functionName:r.name,args:o.length===0||ms(e)<=4?[]:Ie(o,xn(e,4))}}var tu={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},nu={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},ru={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 mr({abi:n=[],data:e}){let t=xn(e,0,4);if(ms(e)<4)throw new Error(`Cannot decode error result: "${e}" is too short.`);let r=[...n,tu,nu],o=Xt({abi:r,name:t,type:"error"})??r.find(a=>(a.type??"")==="error"&&Ut(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?Ie(s,xn(e,4)):void 0}}function gs({abi:n,data:e}){if(!(!e||e==="0x"))try{let{errorName:t,args:r}=mr({abi:n,data:e});if(t==="Error")return String(r?.[0]??"");if(t==="Panic"){let o=Number(r?.[0]??0);return ru[o]??`Panic code ${o}.`}return!r||r.length===0?t:`${t}(${r.map(o=>String(o)).join(", ")})`}catch{return}}var Tm=new Set(["pure","view","nonpayable","payable"]),Am=new Set(["external","public","internal","private","calldata","memory","storage"]);function gl(n,e){let t=0;for(let r=e;r<n.length;r++)if(n[r]==="(")t++;else if(n[r]===")"&&(t--,t===0))return r;throw new Gt(n,"Unbalanced parentheses.")}function su(n){let e=[],t=0,r="";for(let o of n){if(o==="("&&t++,o===")"&&t--,o===","&&t===0){e.push(r),r="";continue}r+=o}return r.trim()&&e.push(r),e.map(o=>o.trim()).filter(Boolean)}function Pm(n){let e=n.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:e?.[1]??"",rest:(e?.[2]??"").trim()}}function ou(n,e){let t=!1,r;for(let o of n)o==="indexed"?t=!0:Am.has(o)||(r=o);return{...e,...r?{name:r}:{},...t?{indexed:!0}:{}}}function yl(n){let e=n.trim();if(e.startsWith("(")){let o=gl(e,0),s=su(e.slice(1,o)).map(yl),{suffix:a,rest:i}=Pm(e.slice(o+1).trim());return ou(i.split(/\s+/).filter(Boolean),{type:`tuple${a}`,components:s})}let[t,...r]=e.split(/\s+/).filter(Boolean);if(!t)throw new Gt(n,"Missing parameter type.");return ou(r,{type:t})}function bs(n){return su(n).map(yl)}function ys(n,e,t){let r=n.indexOf("(",e);if(r===-1)throw new Gt(t,"Missing parameter list.");let o=gl(n,r);return{name:n.slice(e,r).trim(),params:bs(n.slice(r+1,o)),rest:n.slice(o+1).trim()}}function fl(n,e){return n.split(/[\s()]+/).find(r=>Tm.has(r))??e}function Ea(n){let e=n.trim();if(e.startsWith("function ")){let{name:t,params:r,rest:o}=ys(e,9,n),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 Gt(n,"`returns` without a parameter list.");i=bs(o.slice(l+1,gl(o,l)))}return{type:"function",name:t,inputs:r,outputs:i,stateMutability:fl(a,"nonpayable")}}if(e.startsWith("event ")){let{name:t,params:r}=ys(e,6,n);return{type:"event",name:t,inputs:r}}if(e.startsWith("error ")){let{name:t,params:r}=ys(e,6,n);return{type:"error",name:t,inputs:r}}if(e.startsWith("constructor")){let{params:t,rest:r}=ys(e,11,n);return{type:"constructor",inputs:t,stateMutability:fl(r,"nonpayable")}}if(e.startsWith("fallback")){let{rest:t}=ys(e,8,n);return{type:"fallback",stateMutability:fl(t,"nonpayable")}}if(e.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new Gt(n,"Expected function, event, error, constructor, fallback or receive.")}function bl(n){return n.map(Ea)}function bt({blockNumber:n,blockTag:e="latest"}={}){return n!==void 0?Fe(n):e}function ws(n){let{account:e,to:t,data:r,value:o,gas:s,gasPrice:a,maxFeePerGas:i,maxPriorityFeePerGas:l,nonce:c}=n,d={};return e&&(d.from=e),t&&(d.to=t),r&&(d.data=r),o!==void 0&&(d.value=Fe(o)),s!==void 0&&(d.gas=Fe(s)),a!==void 0&&(d.gasPrice=Fe(a)),i!==void 0&&(d.maxFeePerGas=Fe(i)),l!==void 0&&(d.maxPriorityFeePerGas=Fe(l)),c!==void 0&&(d.nonce=Fe(c)),d}function wl(n){let e={};for(let[t,r]of Object.entries(n)){let o={};r.balance!==void 0&&(o.balance=Fe(r.balance)),r.nonce!==void 0&&(o.nonce=Fe(r.nonce)),r.code!==void 0&&(o.code=r.code),r.state&&(o.state=r.state),r.stateDiff&&(o.stateDiff=r.stateDiff),e[t]=o}return e}async function hr(n){return lt(await n.request({method:"eth_blockNumber"}))}async function fr(n){return Pa(await n.request({method:"eth_chainId"}))}async function gr(n,{address:e,...t}){return lt(await n.request({method:"eth_getBalance",params:[e,bt(t)]}))}async function Qt(n,{address:e,...t}){let r=await n.request({method:"eth_getCode",params:[e,bt(t)]});return!r||r==="0x"?void 0:r}async function yr(n,{address:e,slot:t,...r}){return await n.request({method:"eth_getStorageAt",params:[e,t,bt(r)]})??void 0}async function br(n,{address:e,...t}){return Pa(await n.request({method:"eth_getTransactionCount",params:[e,bt(t)]}))}async function wr(n){return lt(await n.request({method:"eth_gasPrice"}))}async function _a(n){return lt(await n.request({method:"eth_maxPriorityFeePerGas"}))}async function kr(n,{blockNumber:e,blockTag:t,...r}){return lt(await n.request({method:"eth_estimateGas",params:[ws(r),bt({blockNumber:e,blockTag:t})]}))}async function vr(n,{includeTransactions:e=!1,...t}={}){let r=await n.request({method:"eth_getBlockByNumber",params:[bt(t),e]});return r?{...r,blockNumber:r.number?lt(r.number):void 0,blockTimestamp:r.timestamp?lt(r.timestamp):void 0,baseFee:r.baseFeePerGas?lt(r.baseFeePerGas):void 0}:null}var re="0xcA11bde05977b3631167028862bE2a173976CA11",au={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:re,blockCreated:14353601}}},iu={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:re,blockCreated:4286263}}},lu={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:re}}},cu={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:re,blockCreated:25770160}}},uu={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:re,blockCreated:5022}}},du={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:re,blockCreated:7654707}}},pu={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:re}}},mu={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:re}}},hu={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:re}}},fu={id:999,hexId:"0x3e7",name:"HyperEVM",nativeCurrency:{name:"HYPE",symbol:"HYPE",decimals:18},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}},contracts:{multicall3:{address:re}}},gu={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:re}}},yu={id:143,hexId:"0x8f",name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://rpc.monad.xyz"]}},contracts:{multicall3:{address:re}}},_n=[au,iu,lu,cu,uu,du,pu,mu,hu,fu,gu,yu];var bu=new Map,kl=new Map;function Sm(n,e){return`${n??"unknown"}|${e.toLowerCase()}`}async function wu(n,e=re){let t=Sm(n.chain?.id??n.chain?.hexId,e),r=bu.get(t);if(r!==void 0)return r;let o=kl.get(t);if(o)return o;let s=(async()=>{try{let i=await Qt(n,{address:e})!==void 0;return bu.set(t,i),i}catch{return!0}finally{kl.delete(t)}})();return kl.set(t,s),s}async function Nn(n,e,t=!1){return t||typeof n.batch?.multicall=="object"&&n.batch.multicall.assumeMulticall3?!0:wu(n,e)}var ct=[{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 q=[{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}]}],Tr=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]}];var Ar=[{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 wt=[{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 Pr=class extends F{name="ChainNotFoundError";constructor(e){super(`Chain "${e}" is not supported.`,{metaMessages:["Add it to `chain/chains/definitions.ts`, or pass an explicit `transport`/`rpcUrl`."]})}},Ln=class extends F{name="ClientChainNotConfiguredError";constructor(){super("No chain was configured on the client.",{metaMessages:["Pass `chain` to createPublicClient(), or pass the address the action needs explicitly."]})}},Jt=class extends F{name="ChainDoesNotSupportContractError";constructor({chain:e,contract:t,blockNumber:r}){super(r!==void 0?`Chain "${e}" does not support contract "${t}" at block ${r}.`:`Chain "${e}" does not support contract "${t}".`,{metaMessages:["Pass the contract address explicitly to use it on this chain."]})}};async function vl(n,e,t){let r=new Array(n.length);if(n.length===0)return r;let o=0,s=Math.max(1,Math.min(e>0?e:n.length,n.length));async function a(){for(;;){let i=o++;if(i>=n.length)return;try{r[i]={status:"fulfilled",value:await t(n[i],i)}}catch(l){r[i]={status:"rejected",reason:l}}}}return await Promise.all(Array.from({length:s},a)),r}function ks({blockNumber:n,chain:e,contract:t}){let r=e.contracts?.[t];if(!r)throw new Jt({chain:e.name,contract:t});if(n!==void 0&&r.blockCreated!==void 0&&r.blockCreated>Number(n))throw new Jt({blockNumber:n,chain:e.name,contract:t});return r.address}var Sr=class extends F{name="RawContractError";data;constructor({data:e,shortMessage:t="The contract call reverted."}){super(t),this.data=e}},Tl=class extends F{name="ContractFunctionRevertedError";errorName;errorArgs;reason;data;constructor({abi:e,data:t,functionName:r}){let o=t?gs({abi:e,data:t}):void 0,s,a;if(t&&t!=="0x")try{let i=mr({abi:e,data:t});s=i.errorName,a=i.args}catch{}super(o?`The contract function "${r??"call"}" reverted with the following reason:
|
|
3
|
+
${o}`:`The contract function "${r??"call"}" reverted.`,{metaMessages:t&&t!=="0x"?[`Revert data: ${t}`]:[]}),this.reason=o,this.errorName=s,this.errorArgs=a,this.data=t}},Al=class extends F{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."]})}},Pl=class extends F{name="ContractFunctionExecutionError";abi;address;args;functionName;constructor(e,{abi:t,address:r,args:o,functionName:s,sender:a}){let i=t&&s?Xt({abi:t,name:s,args:o}):void 0,l=i?cr(i):s,c=o&&o.length>0?` args: (${o.map(u=>xm(u)).join(", ")})`:void 0,d=i?.inputs?.length?`(${i.inputs.map(hs).join(", ")})`:"()";super(e instanceof F?e.shortMessage:`An error occurred calling "${s??"contract"}".`,{cause:e,metaMessages:[...r?[`Contract: ${r}`]:[],...l?[`Function: ${l}${i?"":d}`]:[],...c?[c]:[],...a?[`Sender: ${a}`]:[]]}),this.abi=t,this.address=r,this.args=o,this.functionName=s}},vs=class extends F{name="CallExecutionError";constructor(e,{to:t,data:r}){super(e instanceof F?e.shortMessage:"The call failed.",{cause:e,metaMessages:[...t?[`To: ${t}`]:[],...r?[`Data: ${r}`]:[]]})}};function xm(n){if(typeof n=="bigint")return n.toString();if(typeof n=="string")return n;try{return JSON.stringify(n,(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return String(n)}}function ku(n){if(!n||typeof n!="object")return;let e=n,t=e.data;if(typeof t=="string"&&t.startsWith("0x"))return t;if(t&&typeof t=="object"){let r=t.data;if(typeof r=="string"&&r.startsWith("0x"))return r}return e.cause?ku(e.cause):void 0}function xr(n,{abi:e,address:t,args:r,functionName:o,sender:s}){let a=ku(n),i=n instanceof Yt?new Al({functionName:o}):a!==void 0?new Tl({abi:e,data:a,functionName:o}):n;return new Pl(i,{abi:e,address:t,args:r,functionName:o,sender:s})}var Sl=new Map;function Ts({fn:n,id:e,shouldSplitBatch:t,wait:r=0}){let o=()=>Sl.get(e)??void 0,s=i=>Sl.set(e,i),a=async i=>{o()===i&&Sl.delete(e);try{let l=await n(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=o();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)},r)})}}}function Cm(n){return!!(n.data&&n.to&&!n.account&&!n.value&&!n.gas&&!n.gasPrice&&!n.maxFeePerGas&&!n.maxPriorityFeePerGas&&n.nonce===void 0&&!n.stateOverride)}async function Rm(n,e){let{batchSize:t=1024,wait:r=0}=typeof n.batch?.multicall=="object"?n.batch.multicall:{},{blockNumber:o,blockTag:s="latest",data:a,to:i}=e;if(!n.chain)throw new Ln;let l=ks({blockNumber:o,chain:n.chain,contract:"multicall3"});if(!await Nn(n,l,!1))throw new Jt({chain:n.chain.name,contract:"multicall3"});let c=o!==void 0?Fe(o):s,{schedule:d}=Ts({id:`${n.uid}.call.${c}`,wait:r,shouldSplitBatch:m=>m.reduce((f,h)=>f+(h.data.length-2)/2,0)>t,fn:async m=>{let f=M({abi:ct,functionName:"aggregate3",args:[m.map(g=>({allowFailure:!0,callData:g.data,target:g.to}))]}),h=await n.request({method:"eth_call",params:[{to:l,data:f},c]});return yt({abi:ct,functionName:"aggregate3",data:h})}}),{returnData:u,success:p}=await d({data:a,to:i});if(!p)throw new Sr({data:u});return u}async function kt(n,e){let{blockNumber:t,blockTag:r,stateOverride:o,skipBatch:s,...a}=e;if(n.batch?.multicall&&!s&&Cm(e))try{let l=await Rm(n,{blockNumber:t,blockTag:r,data:a.data,to:a.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof Ln||l instanceof Jt))throw new vs(l,{to:a.to,data:a.data})}let i=[ws(a),bt({blockNumber:t,blockTag:r})];o&&i.push(wl(o));try{let l=await n.request({method:"eth_call",params:i});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new vs(l,{to:a.to,data:a.data})}}var xl=8;function vu(n,e){if(e!==void 0&&e>0)return e;let t=typeof n.batch?.multicall=="object"?n.batch.multicall.fallbackConcurrency:void 0;return t!==void 0&&t>0?t:xl}function As(n,e,t){if(e)return e;if(!n.chain)throw new Ln;let r=n.chain.contracts?.multicall3;return r?t!==void 0&&r.blockCreated!==void 0&&r.blockCreated>Number(t)?re:r.address:re}async function Cr(n,e,t={}){let{concurrency:r,account:o,blockNumber:s,blockTag:a,stateOverride:i}=t;return(await vl(e,vu(n,r),async c=>{let{data:d}=await kt(n,{to:c.target,data:c.callData,account:o,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 vt(n,e){let{abi:t,address:r,functionName:o,args:s,...a}=e;try{let i=M({abi:t,functionName:o,args:s}),{data:l}=await kt(n,{...a,to:r,data:i});return yt({abi:t,functionName:o,args:s,data:l??"0x"})}catch(i){throw xr(i,{abi:t,address:r,args:s,functionName:o,sender:a.account})}}var Em=1024,_m=50;async function Zt(n,e){let{calls:t,account:r,blockNumber:o,blockTag:s,batchSize:a=Em,maxCalls:i=_m,multicallAddress:l,stateOverride:c,fallbackConcurrency:d}=e,u=t.map(()=>({success:!1,returnData:"0x"}));if(t.length===0)return u;let p=As(n,l,o),m=[];if(t.forEach((b,y)=>{R(b.target)&&Sn(b.callData)&&m.push({index:y,call:b})}),m.length===0)return u;if(!await Nn(n,p,l!==void 0))return(await Cr(n,m.map(y=>y.call),{account:r,blockNumber:o,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=>vt(n,{abi:ct,address:p,functionName:"aggregate3",args:[b.calls.map(y=>({target:y.target,allowFailure:!0,callData:y.callData}))],account:r,blockNumber:o,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 Tu="https://wallet-api.pantograph.app/keyring/chains_v6",Nm=6,Lm=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,Au={},Rr=null;function Im(n){let e=Array.isArray(n.rpcs)?n.rpcs:[],t=typeof n.linkProvider=="string"?[n.linkProvider]:[],r=[];for(let o of[...t,...e]){if(typeof o!="string")continue;let s=o.trim();if(!(!s.startsWith("https://")||Lm.test(s))&&(r.includes(s)||r.push(s),r.length>=Nm))break}return r}function Pu(n){if(!n||typeof n!="object"||Array.isArray(n))return{};let e={};for(let[t,r]of Object.entries(n)){if(!r||typeof r!="object")continue;let o=r,s=Tt(t)??(typeof o.chainId=="number"?Tt(o.chainId):void 0);if(!s)continue;let a=Im(o);a.length>0&&(e[s]=a)}return e}function Su(n){Au=n}function Cl(n){let e=Tt(n);return e?Au[e]??[]:[]}function Rl(){Rr||La()}function La(n={}){let{url:e=Tu,force:t=!1,debug:r=!1}=n;return Rr&&!t||(Rr=(async()=>{try{let o=await C.get(e);if(!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);let s=Pu(o.data),a=Object.keys(s).length;if(a===0)throw new Error("catalogue contained no usable RPC endpoints");return Su(s),r&&console.log(`[chains] loaded RPC endpoints for ${a} chains from ${e}`),!0}catch(o){if(r){let s=o instanceof Error?o.message:String(o);console.warn(`[chains] remote RPC catalogue unavailable (${s}); using built-in endpoints`)}return Rr=null,!1}})()),Rr}var Um=new Map(_n.map(n=>[n.hexId.toLowerCase(),n])),Dm=new Map(_n.map(n=>[n.id,n]));function Tt(n){if(typeof n=="number")return Number.isFinite(n)&&n>=0?`0x${n.toString(16)}`:void 0;let e=n.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 Ce(n){if(typeof n=="number")return Dm.get(n);let e=Tt(n);return e?Um.get(e):void 0}function Dt(n){return Ce(n)?.nativeCurrency}var Je=Object.fromEntries(_n.map(n=>[n.hexId,n.rpcUrls.default.http[0]]));function El(n){return Ce(n)?.rpcUrls.default.http[0]}var _l={};function In(n){let e={};if(n)for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=Tt(t)??t.toLowerCase();e[o]=r.trim()}_l=e}function Ps(){return{..._l}}function Un(n){Rl();let e=Tt(n),t=e?_l[e]:void 0,r=Cl(n),o=Ce(n)?.rpcUrls.default.http??[];return[...new Set([...t?[t]:[],...r,...o])]}function Dn(n){return Un(n)[0]}function Nl(n){let e=Ce(n);if(!e)return;let t=Un(n),r=e.rpcUrls.default.http;return t.length===0||t.length===r.length&&t.every((o,s)=>o===r[s])?e:{...e,rpcUrls:{default:{http:t}}}}var en=class extends F{name="HttpRequestError";status;url;body;headers;constructor({body:e,details:t,headers:r,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=r}},Er=class extends F{name="TimeoutError";constructor({body:e,url:t,timeout:r}){super("The request took too long to respond.",{details:`The request timed out after ${r}ms.`,metaMessages:[`URL: ${t}`,...e?[`Request body: ${JSON.stringify(e)}`]:[]]})}},_r=class extends F{name="NetworkError";constructor({cause:e,url:t}){super("Could not reach the RPC endpoint.",{cause:e,metaMessages:[`URL: ${t}`]})}},Ia=class extends F{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.']})}},Ss=class extends F{name="FallbackTransportError";constructor({cause:e,count:t}){super(`All ${t} fallback transports failed.`,{cause:e})}};var Nr=class extends F{name="RpcRequestError";code;data;constructor({body:e,error:t,url:r,shortMessage:o}){super(o??"RPC request failed.",{details:t.message,metaMessages:[...r?[`URL: ${r}`]:[],...e?[`Request body: ${JSON.stringify(e)}`]:[],`Error code: ${t.code}`]}),this.code=t.code,this.data=t.data}};function Ze(n,e,t){return class extends Nr{static code=e;name=n;constructor(r){super({...r,shortMessage:t})}}}var Om=Ze("ParseRpcError",-32700,"The node could not parse the JSON request."),Mm=Ze("InvalidRequestRpcError",-32600,"The JSON request is not valid."),Fm=Ze("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),Bm=Ze("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),qm=Ze("InternalRpcError",-32603,"The node reported an internal error."),$m=Ze("InvalidInputRpcError",-32e3,"The RPC input is not valid."),Hm=Ze("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),Vm=Ze("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),Wm=Ze("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),Ym=Ze("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),Ll=Ze("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),Gm=Ze("UserRejectedRequestError",4001,"The user rejected the request."),Km=new Map([[-32700,Om],[-32600,Mm],[-32601,Fm],[-32602,Bm],[-32603,qm],[-32e3,$m],[-32001,Hm],[-32002,Vm],[-32003,Wm],[-32004,Ym],[-32005,Ll],[4001,Gm]]);function xu(n){let e=Km.get(n.error.code);return e?new e(n):new Nr(n)}function Cu(n){return new Promise(e=>setTimeout(e,n))}async function Il(n,{retryCount:e=2,delay:t=150,shouldRetry:r=()=>!0}={}){let o=0;for(;;)try{return await n()}catch(s){if(o++,o>e||!r({count:o,error:s}))throw s;let a=typeof t=="function"?t({count:o,error:s}):t*2**(o-1);a>0&&await Cu(a)}}function Ul(n){let e=n?.["retry-after"];if(!e)return;let t=Number(e);if(Number.isFinite(t))return t*1e3;let r=Date.parse(e);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var jm=new Set([408,413,429,500,502,503,504]),zm=new Set([401,402,403]);function Ua(n){return n instanceof Er||n instanceof _r?!0:n instanceof en?n.status?jm.has(n.status)||n.status>=500:!0:n instanceof Ll?!0:n instanceof Nr?n.code===-32603:!1}function Da(n){return n instanceof en&&n.status&&zm.has(n.status)?!0:Ua(n)}function Oa(n,{retryCount:e=3,retryDelay:t=150}={}){return function(o,s={}){return Il(()=>n(o),{retryCount:s.retryCount??e,shouldRetry:({error:a})=>Ua(a),delay:({count:a,error:i})=>{let l=i instanceof en?Ul(i.headers):void 0;return l!==void 0?l:(s.retryDelay??t)*2**(a-1)}})}}function tn({key:n,name:e,type:t,request:r,retryCount:o=3,retryDelay:s=150,timeout:a=1e4},i){return{config:{key:n,name:e,type:t,request:r,retryCount:o,retryDelay:s,timeout:a},request:Oa(r,{retryCount:o,retryDelay:s}),value:i}}function nn(n,e={}){let{key:t="fallback",name:r="Fallback",retryCount:o=0,retryDelay:s,onTransportError:a}=e;return(i={})=>{let l=n.map(d=>d(i));if(l.length===0)throw new Ss({count:0});return tn({key:t,name:r,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}),!Da(m))throw m}throw new Ss({cause:u,count:l.length})},retryCount:o,retryDelay:s,timeout:i.timeout},{transports:l})}}var Ru=0;function Eu(){return Ru+=1,Ru}function Xm(n){let e=n?.code;if(e==="ECONNABORTED"||e==="ETIMEDOUT")return!0;let t=n?.message??"";return/timeout/i.test(t)}var Lr=class{url;timeout;fetchOptions;constructor(e,{timeout:t=1e4,fetchOptions:r={}}={}){this.url=e,this.timeout=t,this.fetchOptions=r}async post(e){let t;try{t=await C.post(this.url,e,{...this.fetchOptions,timeout:this.timeout,headers:{"Content-Type":"application/json",...this.fetchOptions.headers}})}catch(r){throw Xm(r)?new Er({body:e,url:this.url,timeout:this.timeout}):new _r({cause:r,url:this.url})}if(!t.ok)throw new en({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:Eu(),...e};return await this.post(t)??{id:t.id}}async requestBatch(e){let t=e.map(s=>({jsonrpc:"2.0",id:Eu(),...s})),r=await this.post(t);if(!Array.isArray(r))return t.map(s=>({id:s.id,error:r?.error??{code:-32603,message:"Malformed batch response."}}));let o=new Map(r.map(s=>[s.id,s]));return t.map((s,a)=>o.get(s.id)??r[a]??{id:s.id,error:{code:-32603,message:"Missing response for batched request."}})}};function _u(n,e,t){if(n.error)throw xu({body:e,error:n.error,url:t});return n.result}function ut(n,e={}){let{batch:t,fetchOptions:r,key:o="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=n??c?.rpcUrls.default.http[0];if(!g)throw new Ia;let b=new Lr(g,{timeout:h,fetchOptions:r});return tn({key:o,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}=Ts({id:`${g}:${m}:${f}`,wait:f,shouldSplitBatch:P=>P.length>m,fn:P=>b.requestBatch(P)});return _u(await v(k),k,g)}return _u(await b.request(k),k,g)}},{url:g})}}var Qm=1024;async function Ir(n,e){let{contracts:t,allowFailure:r=!0,account:o,blockNumber:s,blockTag:a,multicallAddress:i,stateOverride:l,fallbackConcurrency:c}=e,d=e.batchSize??(typeof n.batch?.multicall=="object"&&n.batch.multicall.batchSize||Qm),u=new Array(t.length);if(t.length===0)return r?u:[];let p=As(n,i,s),m=[],f;t.forEach((b,y)=>{let{abi:w,address:k,functionName:v,args:P}=b,S;try{if(!R(k))throw new sr(k);S=M({abi:w,functionName:v,args:P})}catch(L){let E=xr(L,{abi:w,address:k,args:P,functionName:v,sender:o});if(!r)throw E;u[y]={status:"failure",error:E};return}let x=(S.length-2)/2;(!f||d>0&&f.size+x>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+=x}),(await Nn(n,p,i!==void 0)?await Promise.allSettled(m.map(b=>vt(n,{abi:ct,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 Cr(n,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],P=xr(b.reason,{abi:v.abi,address:v.address,args:v.args,functionName:v.functionName,sender:o});if(!r)throw P;u[k]={status:"failure",error:P}}return}w.indexes.forEach((k,v)=>{let P=t[k],S=b.value[v];try{if(!S)throw new Error("Multicall returned fewer results than calls.");if(!S.success)throw new Sr({data:S.returnData});if(!S.returnData||S.returnData==="0x")throw new Yt;let x=yt({abi:P.abi,functionName:P.functionName,args:P.args,data:S.returnData});u[k]={status:"success",result:x}}catch(x){let L=xr(x,{abi:P.abi,address:P.address,args:P.args,functionName:P.functionName,sender:o});if(!r)throw L;u[k]={status:"failure",error:L}}})});for(let b=0;b<t.length;b++){if(u[b])continue;let y=new Error("Multicall returned no result for this call.");if(!r)throw y;u[b]={status:"failure",error:y}}return r?u:u.map(b=>b.result)}var Jm=0,On=class{key;name;uid;chain;transport;batch;request;constructor(e={}){let{batch:t,key:r="public",name:o="Public Client",retryCount:s,retryDelay:a,timeout:i}=e;this.chain=eh(e.chain),this.key=r,this.name=o,this.batch=t,this.uid=`${r}-${++Jm}-${Math.random().toString(36).slice(2,8)}`;let c=(e.transport??Zm(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 kt(this,e)}readContract(e){return vt(this,e)}multicall(e){return Ir(this,e)}multicallRaw(e){return Zt(this,e)}getBlockNumber(){return hr(this)}getChainId(){return fr(this)}getBalance(e){return gr(this,e)}getCode(e){return Qt(this,e)}getStorageAt(e){return yr(this,e)}getTransactionCount(e){return br(this,e)}getGasPrice(){return wr(this)}estimateMaxPriorityFeePerGas(){return _a(this)}estimateGas(e){return kr(this,e)}getBlock(e){return vr(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 Zm(n,e){if(n)return ut(n);let t=e?.rpcUrls.default.http??[];return t.length>1?nn(t.map(r=>ut(r,{retryCount:1}))):ut(t[0])}function eh(n){if(n===void 0)return;if(typeof n=="object")return n;let e=Nl(n);if(!e)throw new Pr(n);return e}function rn(n={}){return new On(n)}var Dl=new Map;function th(n,e){return{id:parseInt(n,16),hexId:n,name:`Chain ${parseInt(n,16)}`,nativeCurrency:{name:"Native",symbol:"ETH",decimals:18},rpcUrls:{default:{http:e}},contracts:{multicall3:{address:re}}}}function Re(n,e={}){let{batch:t=!0,pinRpcUrl:r=!1,fallbackConcurrency:o,assumeMulticall3:s}=e,a=Tt(n),i=e.rpcUrl?.trim(),l=a?Un(a):[],c=i?r?[i]:[...new Set([i,...l])]:l;if(c.length===0)throw new Pr(n);let d=`${a??n}|${c.join(",")}|${t?1:0}|${o??""}|${s?1:0}`,u=Dl.get(d);if(u)return u;let p=rn({chain:a&&!Ce(a)?th(a,c):a,transport:c.length===1?ut(c[0]):nn(c.map(m=>ut(m,{retryCount:1}))),batch:t?{multicall:{fallbackConcurrency:o,assumeMulticall3:s}}:void 0});return Dl.set(d,p),p}function Ma(){Dl.clear()}function Ml(n,e){try{return Re(n,{rpcUrl:e?.trim()||void 0})}catch{return null}}async function Ae(n,e,t){let r=new Array(e.length).fill(null),o=e.length>0?Ml(n,t):null;if(!o)return r;let s=[];if(e.forEach((a,i)=>{!R(a.target)||!Sn(a.callData)||s.push({index:i,target:a.target,callData:a.callData})}),s.length===0)return r;try{(await Zt(o,{calls:s})).forEach((i,l)=>{i.success&&(r[s[l].index]=i.returnData)})}catch{}return r}function Fa(n){return n?.status==="success"?n.result:void 0}async function Ol(n,e){try{return await n.multicall({contracts:e})}catch{return[]}}async function At(n,e,t){let r=e.map(()=>({symbol:null,decimals:null})),o=e.length>0?Ml(n,t):null;if(!o)return r;let s=[];if(e.forEach((l,c)=>{R(l)&&s.push({index:c,address:l})}),s.length===0)return r;let a=await Ol(o,s.flatMap(l=>[{address:l.address,abi:q,functionName:"symbol"},{address:l.address,abi:q,functionName:"decimals"}]));s.forEach((l,c)=>{let d=Fa(a[c*2]);typeof d=="string"&&d.trim()&&(r[l.index].symbol=d.trim()),r[l.index].decimals=Ca(Fa(a[c*2+1]))});let i=s.filter(l=>r[l.index].symbol===null);if(i.length>0){let l=await Ol(o,i.map(c=>({address:c.address,abi:Tr,functionName:"symbol"})));i.forEach((c,d)=>{r[c.index].symbol=Ra(Fa(l[d]))})}return r}async function Nu(n,e,t){let r=new Array(e.length).fill(null),o=e.length>0?Ml(n,t):null;if(!o)return r;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 Ol(o,s.map(i=>({address:i.address,abi:Ar,functionName:"tokenURI",args:[i.tokenId]})))).forEach((i,l)=>{let c=Fa(i);if(typeof c!="string")return;let d=c.replace(/\0+$/,"").trim();d&&(r[s[l].index]=d)}),r}function xs(n){return Ur(String(n))??"0"}function Ur(n){let e=n.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let t=e[1]==="-"?"-":"",r=e[2]??"",o=e[3]??"";if(r===""&&o==="")return null;let s=e[4]?parseInt(e[4],10):0,a=r+o,i=r.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 Fl(n){let e=Ur(n);if(e===null||e.startsWith("-"))return null;let[t,r=""]=e.split(".");return{mant:BigInt(t+r),frac:r.length}}function Ba(n,e){let t=n<0n,r=(t?-n:n).toString(),o;if(e===0)o=r;else{let s=r.padStart(e+1,"0"),a=s.length-e;o=`${s.slice(0,a)}.${s.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return t?`-${o}`:o}function Mn(n,e){let t=Ur(n);if(t===null||t.startsWith("-"))return null;let[r,o=""]=t.split("."),s=o.slice(0,e).padEnd(e,"0");try{let a=BigInt(r||"0")*10n**BigInt(e)+BigInt(s||"0");return a>0n?a:null}catch{return null}}function Fn(n){if(typeof n=="number")return Number.isFinite(n)&&n>0?xs(n):null;if(typeof n!="string")return null;let e=n.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=Ur(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function je(n,e){let t=Ur(n);if(t===null||e<0)return n;let r=t.startsWith("-"),[o,s=""]=(r?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 r?`-${i}`:i}function Bn(n,e,t,r){let o=Fl(n);if(!o||t<=0n||r<0)return n;let s=o.mant*e*10n**BigInt(r)/(t*10n**BigInt(o.frac));return Ba(s,r)}function on(n,e){let t=Fl(n),r=Fl(e);if(!t||!r){let i=Number(n),l=Number(e);return i<l?-1:i>l?1:0}let o=Math.max(t.frac,r.frac),s=t.mant*10n**BigInt(o-t.frac),a=r.mant*10n**BigInt(o-r.frac);return s<a?-1:s>a?1:0}var nh={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"}]},rh="payment-required",oh="PAYMENT-SIGNATURE",sh="X-PAYMENT",ah="payment-response",ih="x-payment-response",lh=600,ch=300,uh={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 Lu(n){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(n),t=Array.from(e,r=>String.fromCharCode(r)).join("");return globalThis.btoa(t)}return Buffer.from(n,"utf8").toString("base64")}function Uu(n){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return new TextDecoder("utf-8").decode(t)}return Buffer.from(n,"base64").toString("utf8")}function dh(){let n=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(n);else for(let t=0;t<32;t++)n[t]=Math.floor(Math.random()*256);return"0x"+Array.from(n,t=>t.toString(16).padStart(2,"0")).join("")}function Du(n){let e=String(n);if(e.includes(":")){let[r,o]=e.split(":"),s=parseInt(o,10);if(r!=="eip155"||Number.isNaN(s))throw new Error(`Unsupported x402 network: ${n} (only EVM "eip155:*" is supported)`);return s}let t=uh[e.toLowerCase()];if(t===void 0)throw new Error(`Unsupported x402 network: ${n}`);return t}function Ou(n){if(!n.query||Object.keys(n.query).length===0)return n.url;let e=Object.entries(n.query).map(([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(r)}`).join("&");return n.url.includes("?")?`${n.url}&${e}`:`${n.url}?${e}`}function qa(n){let e=n.headers[rh];if(e){let o=Iu(ph(e));return o&&Array.isArray(o.accepts)?{version:2,payload:o}:null}let t=n.data,r=t&&typeof t=="object"?t:Iu(t);return r&&Array.isArray(r.accepts)?{version:1,payload:r}:null}function Iu(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e&&typeof e=="object"?e:null}catch{return null}}function ph(n){try{return Uu(n)}catch{return null}}function mh(n){let e=n.amount??n.maxAmountRequired;return typeof n.scheme!="string"||typeof n.network!="string"||e==null||typeof n.asset!="string"||typeof n.payTo!="string"?null:{scheme:n.scheme,network:n.network,amount:String(e),asset:n.asset,payTo:n.payTo,...typeof n.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:n.maxTimeoutSeconds}:{},...n.extra&&typeof n.extra=="object"?{extra:n.extra}:{},...typeof n.resource=="string"?{resource:n.resource}:{},...typeof n.description=="string"?{description:n.description}:{},...typeof n.mimeType=="string"?{mimeType:n.mimeType}:{},...n.outputSchema!=null?{outputSchema:n.outputSchema}:{}}}function hh(n){let e=null;for(let t of n){let r=mh(t);if(r){if(r.scheme!=="exact"){e=`unsupported scheme "${r.scheme}"`;continue}try{return Du(r.network),r}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 Bl(n,e,t,r){let o=qa(n);if(!o)throw new Error("402 response carries no x402 payment requirements");let{version:s,payload:a}=o,i=hh(a.accepts??[]);if(!t)throw new Error("No connected wallet address to build the payment from");let l=Du(i.network),c=Math.floor(Date.now()/1e3),d={from:t,to:i.payTo,value:String(i.amount),validAfter:String(Math.max(0,c-lh)),validBefore:String(c+(i.maxTimeoutSeconds??ch)),nonce:dh()},u={domain:{name:i.extra?.name,version:i.extra?.version,chainId:l,verifyingContract:i.asset},types:nh,primaryType:"TransferWithAuthorization",message:{...d}};return{request:{url:Ou(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}:{},...r?{userQuery:r}:{}}}async function fh(n,e,t,r){let o=Ou(e),s=await n.request(e.method??"GET",o,e.body,{headers:e.headers});if(s.status===402)return{status:"payment_required",challenge:Bl(s,e,t,r)};if(!s.ok)throw new Error(_(s));return{status:"ok",data:s.data}}async function ql(n,e,t){let{url:r,method:o,body:s,headers:a}=e.request,i=await n.request(o,r,s,{headers:{...a??{},...$l(e,t)}});if(i.ok)return i.data;throw new Error(yh(i)??_(i))}function gh(n){return qa(n)!==null}function Mu(n){let e=Fu(n);return e?.errorReason?e.errorReason:qa(n)?.payload.error??null}function yh(n){let e=Mu(n);return e?`x402 payment rejected: ${e}`:null}var bh={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 $l(n,e){let{requirements:t,authorization:r}=n,o={signature:e,authorization:r};if(n.x402Version===1){let a={x402Version:1,scheme:t.scheme,network:t.network,payload:o};return{[sh]:Lu(JSON.stringify(a))}}let s={x402Version:2,...n.resource!=null?{resource:n.resource}:{},accepted:wh(t),payload:o,...n.extensions!=null?{extensions:n.extensions}:{}};return{[oh]:Lu(JSON.stringify(s))}}function wh(n){let{resource:e,description:t,mimeType:r,outputSchema:o,...s}=n;return s}function Fu(n){let e=n.headers[ah]??n.headers[ih];if(!e)return null;try{return JSON.parse(Uu(e))}catch{return null}}function kh(n,e){return n==null?e:bh[n]??`Chain ${n}`}async function Bu(n){let e=n.requirements,r=n.resource?.description||e.description,o=n.chainId??null,s=null,a=null;if(o!=null){let[l]=await At("0x"+o.toString(16),[e.asset]);s=l?.symbol??null,a=l?.decimals??null}let i=String(e.amount);if(a!==null)try{i=Ba(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:kh(o,e.network),payTo:e.payTo,...r?{description:r}:{},resourceUrl:n.request.url}}function Hl(n){return async(e,t)=>{let r=n.getPayer(),o=n.getSigner();if(!r||!o)return null;let s;try{s=Bl(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},r)}catch{return null}let a;try{a=await o({typedData:s.typedData,display:await Bu(s)})}catch{a=null}return a?$l(s,a):null}}var sn=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function qn(n){if(!n||typeof n!="object")return!1;let e=n;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function Cs(n){if(n?.aborted)throw new sn}function Vl(n,e){if(!e)return{signal:n.signal,cleanup:()=>{}};if(e.aborted)return n.abort(),{signal:n.signal,cleanup:()=>{}};let t=()=>n.abort();return e.addEventListener("abort",t),{signal:n.signal,cleanup:()=>e.removeEventListener("abort",t)}}var qu={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},vh="https://nft.keyring.app/api/gemini-stable",Th="https://generativelanguage.googleapis.com",Ah=new Set([408,429,500,502,503,504]),$u=3e4,$a=n=>new Promise(e=>setTimeout(e,n));function Ha(n,e,t){if(t!=null&&t>0)return Math.min(t,$u);let r=Math.min(e*2**(n-1),$u);return r/2+Math.random()*(r/2)}function Ph(n){if(!n)return null;let e=Number(n);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(n);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var ve=class{model;maxTokens;temperature;thinkingBudget;baseUrl;apiKey;requestSignal;constructor(e){this.model=e.model??"gemini-2.5-flash",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.thinkingBudget=e.thinkingBudget===void 0?0:e.thinkingBudget,this.apiKey=e.apiKey?.trim()??"",this.baseUrl=(e.baseUrl??(this.apiKey?Th:vh)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,t,r){let{systemInstruction:o,contents:s}=this.toContents(e),{maxRetries:a=5,retryDelayMs:i=1e3}=r??{},l=r?.signal??this.requestSignal;Cs(l);let c=s.length>0?s:[{role:"user",parts:[{text:"(continue)"}]}];if(r?._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=r?.thinkingBudget===void 0?this.thinkingBudget:r.thinkingBudget,u={maxOutputTokens:r?.maxOutputTokens??this.maxTokens,temperature:this.temperature};d!=null&&(u.thinkingConfig={thinkingBudget:d});let p={contents:c,generationConfig:u};o&&(p.systemInstruction=o),t?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],r?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):r?.googleSearch&&(p.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,f="Unknown error";for(let h=1;h<=a;h++){Cs(l);let g;try{g=await C.post(m,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(S){if(qn(S))throw S;if(f=S instanceof Error?S.message:String(S),h>=a)break;await $a(Ha(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}`,!Ah.has(g.status))throw new Error(f);if(h>=a)break;let x=Ph(g.headers["retry-after"]??null);await $a(Ha(h,i,x));continue}if(g.data==null||typeof g.data!="object"){if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,h>=a)break;await $a(Ha(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 $a(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 P=b.usageMetadata?{promptTokens:b.usageMetadata.promptTokenCount??0,completionTokens:b.usageMetadata.candidatesTokenCount??0,totalTokens:b.usageMetadata.totalTokenCount??0,thoughtsTokens:b.usageMetadata.thoughtsTokenCount??0,cachedTokens:b.usageMetadata.cachedContentTokenCount??0}:void 0;return{text:w,toolCalls:k,usage:P,finishReason:y.finishReason}}throw new Error(f)}toContents(e){let t=[],r=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){r.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){r.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o=[];for(let i of r){let l=o[o.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):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(u=>u.functionCall)||l.role==="model"&&l.parts.some(u=>u.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 r={},o=[];for(let s of t.parameters){let a={type:qu[s.type]??"STRING",description:s.description};s.type==="array"&&(a.items={type:qu[s.items?.type??"string"]??"STRING"}),r[s.name]=a,s.required&&o.push(s.name)}return{name:t.name,description:t.description,parameters:{type:"OBJECT",properties:r,required:o}}})}};var Dr=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,r){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,r),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 Or=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],Sh=new Set(Or),an=[...Or],Wl=new Set(an),Be="0x1",Fr="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function xh(n){return n.map(e=>Mr[e]??e).join(", ")}function Va(n){let e=new Set;if(n)for(let r of n){let o=Wa(r);o&&e.add(o)}let t=Or.filter(r=>!e.has(r));an=t.length>0?[...t]:[...Or],Wl=new Set(an),Be=an.includes("0x1")?"0x1":an[0],Fr=xh(an)}var Ch={"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 D(n){let e=Wa(n);return e&&Wl.has(e)?e:null}function Wa(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=Ch[e];if(t)return t;let r=null;return/^0x[0-9a-f]+$/.test(e)?r=e:/^[0-9]+$/.test(e)&&(r="0x"+Number(e).toString(16)),r&&Sh.has(r)?r:null}function qe(n){return D(n)!==null}function $e(){return[...an]}var ln=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${Fr}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Ot=n=>typeof n=="string"&&n.trim()!=="";function K(n,e){if(Ot(n)){let t=D(n);if(t)return t;throw new ln(n.trim())}if(Ot(e?.chain)){let t=D(e.chain);if(t)return t;throw new ln(e.chain.trim())}return null}function Ya(n,e){return D(n)??D(e?.chain)??void 0}var Mr={"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(n){let e=Wa(n);return e&&Mr[e]?Mr[e]:typeof n=="string"&&n.trim()?n.trim():"the requested chain"}var Rh={"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 Hu(n,e){let t=Wa(n),r=t?Rh[t]:void 0;return!r||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${r}/tx/${e.trim()}`}var Eh={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function Vu(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return e?Eh[e]??null:null}var _h={"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 Ga(n){let e=D(n);return e?_h[e]??null:null}function Ka(n,e){if(!Ot(n)||!Ot(e))return null;let t=D(n),r=D(e);return!t||!r||t===r?null:{from:t,to:r,fromLabel:Mr[t]??t,toLabel:Mr[r]??r}}function Br(n){return`Hex chain ID of the ${n} \u2014 same ids as \`chain\` (e.g. "0xa" Optimism, "0x2105" Base). ONLY set this when the user names a chain FOR THIS SIDE SPECIFICALLY, i.e. they named a chain per token \u2014 "swap ETH on Optimism to ETH on Base", "buy USDC on Base using ETH on Arbitrum". When the user names ONE chain for the whole request (or none), leave this EMPTY and use \`chain\` instead. Never copy the same chain into both sides.`}function ja(n,e){return{error:"cross_chain_not_supported",_instructions:`The user asked to ${n} from ${e.fromLabel} to ${e.toLabel} \u2014 that is a CROSS-CHAIN (bridge) request, which is NOT supported: a ${n} happens entirely on ONE network. Tell them, in their language, that ${n}ping between two different networks isn't supported yet, and that they can ${n} between tokens that are both on ${e.fromLabel}, or both on ${e.toLabel} (switching their wallet's network first). Do NOT proceed. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var et=`Hex chain ID \u2014 e.g. "0xa" Optimism, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0x38" BSC, "0x1" Ethereum, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. Set this WHENEVER the user names a network anywhere in their request \u2014 "swap USDC on Optimism", "buy PEPE on Base", "\u0111\u1ED5i USDC tr\xEAn Optimism", "mua PEPE tr\xEAn Base" \u2014 by mapping that name to its hex id from the list above. Do this EVEN IF it differs from the wallet's currently connected chain: that is a normal request, and the wallet is asked to switch networks when the transaction is signed. NEVER substitute the connected chain for a network the user named, and never leave this empty just because the two differ. OMIT it only when the user names no network at all \u2014 the connected wallet chain is then used automatically.`;function Wu(n,e){let t=typeof n=="string"?n.trim():"",r=e&&e.length?e.filter(s=>Wl.has(s)):[];return(r.length?r:an).map(s=>{let a=Mr[s]??s;return{label:a,prompt:t?`${t} (${a})`:a}})}function qr(n,e){return{actionButtons:Wu(e),_instructions:`The user wants to ${n} 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 ge=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=Wu(e,t)}},Rs=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 ue(n,e){if(Ot(n))return n.trim();if(Ot(e?.walletAddress))return e.walletAddress.trim();throw new Rs}function Pe(n,e,t){if(Ot(n)){let r=D(n);if(r)return r;throw new ln(n.trim())}if(Ot(e?.chain)){let r=D(e.chain);if(r)return r;throw new ln(e.chain.trim())}if(Ot(e?.walletAddress))throw new ge(typeof e?.query=="string"?e.query:void 0,t);return Be}var A=class{category;async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a=Nh(s);return{toolName:this.name,callId:r,success:!0,data:a.data,duration:Date.now()-o,...a.actionButtons?{actionButtons:a.actionButtons}:{},...a.ui?{ui:a.ui}:{}}}catch(s){return s instanceof ge?{toolName:this.name,callId:r,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 Rs?{toolName:this.name,callId:r,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:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}};function Nh(n){if(!n||typeof n!="object")return{data:n};let e=n,t=e.actionButtons,r=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(!r&&!s)return{data:n};let{actionButtons:a,ui:i,...l}=e;return{data:l,...r?{actionButtons:r}:{},...s?{ui:s}:{}}}function Yu(n){if(!n)return;let e=n.yieldProtocolV2;if(e!=null)return e;let t=n.yieldProtocol;return t??(e===null||t===null?null:void 0)}function Gu(n){let e=n?.newConfig?.yieldInfo;if(e?.assetToken){let t=e.assetDecimals==null||e.assetDecimals===""?NaN:Number(e.assetDecimals);return{address:String(e.assetToken).toLowerCase(),...Number.isFinite(t)?{decimals:t}:{},fixedPrice:e.assetFixedPrice??null}}return n?.yieldAsset}function $n(n){let e=Yu(n),t=Gu(n);return e===void 0&&t===void 0?null:{yieldProtocol:e,yieldAsset:t}}var Lh="https://wallet-api.pantograph.app",Ih="0x0000000000000000000000000000000000000000",Xu={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},Qu={"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 Uh(n){return Xu[n.toLowerCase()]||n}function Ku(n){let e=[];for(let[t,r]of Object.entries(n))if(r!=null)if(Array.isArray(r))for(let o of r)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);return e.join("&")}function Yl(n){let e=n,t=e.decimals,r=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,o=e.price,s=o!=null?parseFloat(String(o)):NaN,a=typeof e.symbolOnchain=="string"?e.symbolOnchain.trim():"";return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(r)?r:0,...a?{symbol:a}:{},...Number.isFinite(s)?{usd_price:s}:{}}}function ju(n){if(Array.isArray(n))return n;let e=n;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function Ue(n){if(n==null)return null;let e=typeof n=="number"?n:parseFloat(String(n));return Number.isFinite(e)?e:null}var za=new WeakSet;function zu(n,e){let t=typeof n.symbolOnchain=="string"?n.symbolOnchain.trim():"",r=n.decimals,o=typeof r=="number"?r:typeof r=="string"?parseInt(r,10):null,s=Ue(n.price_change_percentage_24h)??Ue(n.priceChange24h)??Ue(n.usd_price_24hr_percent_change)??Ue(n.price_change_24h)??Ue(n.priceChange),a={chainId:e,tokenAddress:n.address??n.token_address??"",name:n.name??null,symbol:t||n.symbol||null,decimals:o!=null&&Number.isFinite(o)?o:null,logo:n.logoURI??n.icon_image??n.logo??null,usdPrice:Ue(n.price)??Ue(n.usd_price),marketCap:Ue(n.market_cap)??Ue(n.marketCap),totalVolume:{"24h":Ue(n.total_volume)??Ue(n.volume24h)},pricePercentChange:{"24h":s}};return t&&za.add(a),a}var Dh=100;function Oh(n,e){let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t}var ye=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Lh).replace(/\/+$/,"")}tokensUrl(e,t){let r=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${r}?addresses=${encodeURIComponent(t)}`}async fetchTokensAll(e,t){let r=Oh(t,Dh);return(await Promise.all(r.map(async s=>{try{let a=`${this.baseUrl}/keyrings/tokens/all/${e}?addresses=${encodeURIComponent(s.join(","))}`,i=await C.get(a);return i.ok?ju(i.data):[]}catch{return[]}}))).flat()}async enrichTokenPrices(e,t){let r=new Map;if(e.length===0)return r;try{let o=e.map(i=>i.token_address),s=await this.fetchTokensAll(parseInt(t,16),o),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}:{}});let d=$n(i);d&&r.set(l,d)}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 r}async getYieldPricingTokens(e,t){let r=(t??[]).map(s=>String(s??"").trim()).filter(Boolean);if(r.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{return await this.fetchTokensAll(o,r)}catch{return[]}}async getTokenMetadata(e,t){try{let r=this.tokensUrl(t,e),o=await C.get(r);if(!o.ok)return null;let s=ju(o.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?Yl(i):null}catch{return null}}async getTokensMetadata(e,t){let r={};if(e.length===0)return r;try{let o=await this.fetchTokensAll(parseInt(t,16),e),s=new Set(e.map(a=>a.toLowerCase()));for(let a of o){let i=a.address?.toLowerCase()||a.token_address?.toLowerCase()||(a.address===""?"":null);i&&s.has(i)&&(r[i]=Yl(a))}}catch{}return r}async searchTokensByKey(e){let{key:t,chain:r}=e;if(!t)return{success:!1,error:"Search key is required"};let s=parseInt(r||Be,16);if(isNaN(s))return{success:!1,error:`Invalid hex chain: ${r}`};try{let a=Ku({chainId:s,key:t}),i=`${this.baseUrl}/token-list/all?${a}`,l=await C.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(Yl)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||Be,r=5,o=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let s=Qu[t.toLowerCase()]??[],a=o!=null?o+s.length:r+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=>zu(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=o!=null?[...p,...m].slice(0,o):[...p,...m.slice(0,r)];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 r=e.filter(s=>s.tokenAddress&&(s.marketCap==null||s.totalVolume?.["24h"]==null||!za.has(s)));if(r.length===0)return;let o=await this.getTokensMetadata(r.map(s=>s.tokenAddress),t);for(let s of r){let a=o[s.tokenAddress.toLowerCase()];if(!a)continue;let i=typeof a.symbolOnchain=="string"?a.symbolOnchain.trim():"";i&&!za.has(s)&&(s.symbol=i,za.add(s)),s.marketCap==null&&(s.marketCap=Ue(a.market_cap)??Ue(a.marketCap)),s.totalVolume?.["24h"]==null&&(s.totalVolume={"24h":Ue(a.total_volume)??Ue(a.volume24h)})}}async fetchTopGainers(e,t,r="24h"){let o=parseInt(e,16),s=Ku({chainId:o,duration:r,limit:t}),a=`${this.baseUrl}/token-list/all/top-gainers${s?`?${s}`:""}`,i=[];for(let l=0;l<5;l++){let c=await C.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=>zu(l,e))}async getTopGainers(e){let t=e?.chain||Be,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,o=e?.duration||"24h";try{let s=await this.fetchTopGainers(t,r,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 Q(n,e,t,r=[]){return{target:n,callData:M({abi:e,functionName:t,args:r})}}var Hn=1e27,Xa=10n**27n,Es=31536e3,Mh=10;function tt(n){return Number.isFinite(n)&&n>=0&&n<=Mh?n:null}function Gl(n){return Math.expm1(n)}function nt(n,e){return Number(n)/10**e}function _s(n){return new Date(n).toISOString().slice(0,10)}async function cn(n,e,t){let r=`${t.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${n.token}?range=h&day=${7}`,o=await C.get(r);if(!o.ok)throw new Error(_(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 Pt=class{underlyingCall(e){return Q(e.contract,wt,"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 r=ee(e);return r===null?null:nt(r,t.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,t){return this.balanceIsUnderlying?null:Q(e.contract,wt,"convertToAssets",[t])}},St=class extends Pt{type="spark";balanceIsUnderlying=!1;sizeCall(e){return Q(e.contract,wt,"totalAssets")}fetchApy(e,t,r,o){return cn(e,t,r)}};var Kl=[{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 jl=[{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 Ja=[{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"}]}]}],$r=[{type:"function",name:"UNDERLYING_ASSET_ADDRESS",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"POOL",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}],zl=[{type:"function",name:"ADDRESSES_PROVIDER",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var Mt=[{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"}],Xl=[{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 Hr=[{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"vsr",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],un=[{inputs:[],name:"getAPR",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getConversionRate",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],Ql=[{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 Jl=[{inputs:[],name:"manager",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}],Zl=[{inputs:[],name:"pool",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var qh=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!, $reserve: ReserveRequest!) {
|
|
5
5
|
value: supplyAPYHistory(request: $request) { date avgRate { value } }
|
|
6
6
|
reserve(request: $reserve) {
|
|
7
7
|
incentives {
|
|
@@ -11,53 +11,53 @@ ${o}`:`The contract function "${r??"call"}" reverted.`,{metaMessages:t&&t!=="0x"
|
|
|
11
11
|
... on MerklSupplyIncentive { extraSupplyApr { value } payoutToken { symbol } customMessage }
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
|
-
}`;function
|
|
14
|
+
}`;function $h(n){return(n||[]).flatMap(e=>{let t=Number(e?.extraSupplyApr?.value);return!Number.isFinite(t)||t<=0?[]:[{fraction:Gl(t),tokenSymbol:e?.rewardTokenSymbol??e?.payoutToken?.symbol??null,conditions:e?.customMessage?.trim()||null}]})}var Ns=class extends Pt{type="aave-v3";balanceIsUnderlying=!0;underlyingCall(e){return Q(e.token,$r,"UNDERLYING_ASSET_ADDRESS")}sizeCall(e){return Q(e.token,q,"totalSupply")}liveRateCall(e,t){return Q(e.contract,Ja,"getReserveData",[t.address])}decodeLiveRate(e){if(!e)return null;let t;try{let[r]=Ie(Ja[0].outputs,e);t=r.currentLiquidityRate}catch{return null}return tt(Gl(Number(t)/Hn))}async fetchApy(e,t,r,o){let s={chainId:t.chainId,market:e.contract,underlyingToken:o.address,window:"LAST_WEEK"},a=await C.post(r.aaveApiUrl,{operationName:"SupplyAPYHistory",query:qh,variables:{request:s,reserve:{chainId:t.chainId,market:e.contract,underlyingToken:o.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:$h(a.data?.data?.reserve?.incentives)}}};var Hh={1:"0x1B0e765F6224C21223AeA2af16c1C46E38885a40",10:"0x443EA0340cb75a160F31A440722dec7b5bc3C2E9",130:"0x6f7D514bbD4aFf3BcD1140B7344b32f063dEe486",137:"0x45939657d1CA34A8FA39A924B71D28Fe8431e581",2020:"0x31CdEe8609Bc15fD33cc525f101B70a81b2B1E59",5e3:"0xCd83CbBFCE149d141A5171C3D6a0F0fCCeE225Ab",8453:"0x123964802e6ABabBE1Bc9547D72Ef1B69B00A6b1",42161:"0x88730d254A2f7e6AC8388c3198aFd694bA9f7fae",59144:"0x2c7118c4C88B9841FCF839074c26Ae8f035f2921",534352:"0x70167D30964cbFDc315ECAe02441Af747bE0c5Ee"};async function Vh(n,e){let t=Hh[Number(e)];if(!t)return null;let[r]=await Ae(e,[Q(t,Xl,"rewardConfig",[n.contract])]),o=B(r);if(o===null||/^0x0+$/i.test(o))return null;let[s]=await At(e,[o]);return{address:o,symbol:s?.symbol??null}}async function Wh(n,e,t){let r=String(e.chainId),[o,s,a]=await Ae(r,[Q(n.contract,Mt,"baseTrackingSupplySpeed"),Q(n.contract,Mt,"baseIndexScale"),Q(n.token,q,"totalSupply")]),i=ee(o),l=ee(s),c=ee(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 Vh(n,r);if(d===null)return[];let[u,p]=await Promise.all([Za(r,d.address),Za(r,t.address)]);if(!(Number(u)>0)||!(Number(p)>0))return[];let m=nt(c,t.decimals)*Number(p);if(!(m>0))return[];let h=Number(i)/Number(l)*Es*Number(u)/m,g=tt(h);return g===null||g<=0?[]:[{fraction:g,tokenSymbol:d.symbol,conditions:null}]}var Ls=class extends Pt{type="compound-v3";balanceIsUnderlying=!0;underlyingCall(e){return Q(e.contract,Mt,"baseToken")}sizeCall(e){return Q(e.token,q,"totalSupply")}liveRateCall(e){return Q(e.contract,Mt,"getUtilization")}followUpRateCall(e,t){let r=ee(t);return r===null?null:Q(e.contract,Mt,"getSupplyRate",[r])}decodeLiveRate(e){let t=ee(e);return t===null?null:tt(Number(t)/1e18*Es)}async fetchApy(e,t,r,o){let[s,a]=await Promise.all([cn(e,t,r),Wh(e,t,o).catch(()=>[])]);return{...s,rewards:a}}};var Yh="https://api.maple.finance/v2/graphql",Gh=`query PoolApy($id: ID!) {
|
|
15
15
|
poolV2(id: $id) {
|
|
16
16
|
tvl
|
|
17
17
|
weeklyApy
|
|
18
18
|
}
|
|
19
|
-
}`,
|
|
19
|
+
}`,Kh=1e28;function jh(n,e){if(n==null||!Number.isInteger(e.decimals)||e.decimals<0)return null;let t=Number(n)/10**e.decimals;return Number.isFinite(t)&&t>=0?t:null}function zh(n){return n==null?null:tt(Number(n)/Kh/100)}async function Xh(n){let e=await C.post(Yh,{operationName:"PoolApy",query:Gh,variables:{id:n.contract.toLowerCase()}});if(!e.ok)throw new Error(_(e));return e.data?.data?.poolV2}var Is=class extends St{type="maple";async fetchApy(e,t,r,o){let[s,a]=await Promise.all([cn(e,t,r),Xh(e)]);return{...s,current:zh(a?.weeklyApy),sizeOverride:jh(a?.tvl,o)}}};var Qh=`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
|
-
}`,Us=class extends Pt{type="morpho-v2";async fetchApy(e,t,r){let o=Math.floor(Date.now()/1e3),s=await C.post(r.morphoApiUrl,{operationName:"VaultV2ByAddress",query:Xh,variables:{address:e.contract,chainId:t.chainId,options:{startTimestamp:o-7*86400,endTimestamp:o,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 Ds=class extends Pt{type="spark";liveRateCall(e){return X(e.contract,$r,"rateProvider")}followUpRateCall(e,t){let r=B(t);return r===null?null:X(r,dn,"getAPR")}decodeLiveRate(e){let t=ee(e);return t===null?null:et(Math.expm1(Number(t)/Wn))}},Os=class extends Pt{type="spark-ethereum";liveRateCall(e){return X(e.contract,$r,"vsr")}decodeLiveRate(e){let t=ee(e);if(t===null||t<=0n)return null;let r=Number(t-Xa)/Wn;return r>-1?et(Math.expm1(Math.log1p(r)*Es)):null}};var Ms=class extends At{type="spark-l2-susds";balanceIsUnderlying=!1;underlyingCall(){return null}sizeCall(e){return X(e.token,q,"totalSupply")}liveRateCall(e){return X(e.contract,dn,"getAPR")}decodeLiveRate(e){let t=ee(e);return t===null?null:et(Math.expm1(Number(t)/Wn))}convertToAssetsCall(e){return X(e.contract,dn,"getConversionRate")}fetchApy(e,t,r){return un(e,t,r)}};function Yn(n,e,t,r){if(e<=0n||!Number.isInteger(t)||!Number.isInteger(r)||t<0||r<0)return null;let o=n*e/Xa,s=r-t;return s===0?o:s>0?o*10n**BigInt(s):o/10n**BigInt(-s)}var ei={"aave-v3":{protocol:new Ns,label:"Aave V3",home:"https://app.aave.com"},"compound-v3":{protocol:new Ls,label:"Compound V3",home:"https://app.compound.finance"},spark:{protocol:new Ds,label:"Spark",home:"https://app.spark.finance"},"spark-ethereum":{protocol:new Os,label:"Spark",home:"https://app.spark.finance"},"spark-l2-susds":{protocol:new Ms,label:"Spark",home:"https://app.spark.finance"},"morpho-v2":{protocol:new Us,label:"Morpho V2",home:"https://app.morpho.org"},maple:{protocol:new Is,label:"Maple",home:"https://app.maple.finance"}},Qh=ei.spark.protocol;function pn(n){return ei[n.type]?.protocol??Qh}function je(n){return ei[n]?.label??null}function Fs(n){return ei[n]?.home??null}var Gn="0x0000000000000000000000000000000000000000";function Bs(n){let e=parseInt(n,16);return Number.isFinite(e)?{chainId:e}:null}function Ft(n){if(typeof n=="number")return Number.isInteger(n)&&n>0?`0x${n.toString(16)}`:null;if(typeof n!="string")return null;let e=n.trim().toLowerCase();if(!e)return null;if(!/^(0x[0-9a-f]+|\d+)$/.test(e))return D(e);let t=e.startsWith("0x")?parseInt(e,16):Number(e);return Number.isInteger(t)&&t>0?`0x${t.toString(16)}`:null}var Jh={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function ti(n){let e=Ft(n);return e?Jh[e]??null:null}function Zu(n){return["susds","usds","rateProvider"].map(e=>({target:n,callData:M({abi:Ql,functionName:e})}))}var ed=3,Zh={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function ec(n){let e=Ft(n),t=e?Zh[e]:void 0;return t?{target:t,callData:M({abi:dn,functionName:"getConversionRate"})}:null}var ef=new Set(["spark","spark-ethereum","spark-l2-susds","morpho-v2","maple"]),td="spark-l2-susds";function Hr(n){return!!n&&ef.has(n)}var tc=n=>{if(n==null||n==="")return null;let e=Number(n);return!Number.isInteger(e)||e<0||e>36?null:e},tf=n=>{if(n==null||n==="")return null;let e=Number(n);return Number.isFinite(e)&&e>0?e:null};function qs(n){let e=tf(n.yieldAsset?.fixedPrice);return e!==null?e:Number.isFinite(n.priceUSD)?n.priceUSD:0}function nd(n){if(!Hr(n.yieldProtocol)||tc(n.yieldAsset?.decimals)===null||n.yieldProtocol===td&&!ec(n.chain))return!1;let e=qs(n);return Number.isFinite(e)&&e>0}function nc(n){let e=[],t=[];for(let r of n)if(!(r.rawBalance<=0n)&&nd(r)){if(r.yieldProtocol===td){let o=ec(r.chain);if(!o)continue;e.push({key:r.key,...o}),t.push(r.key);continue}e.push({key:r.key,target:r.address,callData:M({abi:wt,functionName:"convertToAssets",args:[r.rawBalance]})})}return{calls:e,rateKeys:t}}function ni(n,e,t){let r=new Map(n.map(i=>[i.key,i])),o=new Set(e.rateKeys),s=new Map;e.calls.forEach((i,l)=>{let c=ee(t[l]??null);if(c===null)return;if(!o.has(i.key)){s.set(i.key,c);return}let d=r.get(i.key),u=tc(d?.yieldAsset?.decimals);if(!d||u===null)return;let p=Yn(d.rawBalance,c,d.decimals,u);p!==null&&s.set(i.key,p)});let a=new Map;for(let i of n){let l=tt(i.rawBalance,i.decimals),c=qs(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=tc(i.yieldAsset?.decimals);if(p===null){a.set(i.key,u);continue}let m=tt(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 ri(n,e,t={}){let r=e.map(a=>a.chain==null?{...a,chain:n}:a),o=nc(r);if(o.calls.length===0)return ni(r,o,[]);let s=await Ae(String(n),o.calls,t.rpcUrl);return ni(r,o,s)}async function Vs(n,e,t){let r=new Map,o=[...new Set(e.filter(s=>s?.address&&rd(s.fixedPrice)===null).map(s=>String(s?.address).toLowerCase()))];if(o.length===0)return r;try{let s=await(t??new ye).getYieldPricingTokens(n,o);for(let a of s){let i=Hs(a?.price);a?.address&&i!=null&&i>0&&r.set(String(a.address).toLowerCase(),i)}}catch{}return r}function Vr(n,e,t){let r=rd(n?.fixedPrice);if(r!==null)return r;let o=n?.address?e.get(String(n.address).toLowerCase()):void 0;return o!=null&&o>0?o:Hs(t)??0}function rd(n){let e=Hs(n);return e!=null&&e>0?e:null}async function Za(n,e,t={}){let r=await nf(n,e,t.apiBaseUrl);if(!r)return null;if(!r.yieldProtocol)return $s(n,r,t);let o=t.apiBaseUrl?new ye({baseUrl:t.apiBaseUrl}):void 0,s=await Vs(n,[r.yieldAsset],o);return $s(n,{...r,price:Vr(r.yieldAsset,s,r.price)},t)}async function $s(n,e,t={}){let r=Hs(e?.price),o=l=>l!=null&&l>0?l:null;if(!e?.yieldProtocol)return o(r);let s=qs({key:"price",address:"",rawBalance:0n,decimals:0,priceUSD:r??0,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:n});if(!(s>0))return null;if(!Hr(e?.yieldProtocol))return s;let a=Math.trunc(Hs(e?.decimals)??18);if(!Number.isInteger(a)||a<0||a>36)return o(r);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:n};try{let c=(await ri(n,[i],t)).get(i.key);return c?.converted?o(c.pricePerTokenUSD):null}catch{return null}}async function nf(n,e,t){let r=String(e??"").toLowerCase();if(!r)return null;try{let a=(await new ye(t?{baseUrl:t}:void 0).getYieldPricingTokens(n,[r])).find(l=>String(l?.address??"").toLowerCase()===r);if(!a)return null;let i=Vn(a);return i?{...a,...i}:a}catch{return null}}function Hs(n){if(n==null||n==="")return null;let e=typeof n=="number"?n:Number(n);return Number.isFinite(e)?e:null}var rf="https://nft.keyring.app",of="https://nft.keyring.app",sf=.01,I=5,oe=1e3,af=25,lf="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",cf="0x0000000000000000000000000000000000000000",U=class extends Error{constructor(t,r){super(r);this.status=t;this.name="MoralisHttpError"}status};function se(n){return n||Be}function ae(n){let e=[];for(let[t,r]of Object.entries(n))if(r!=null)if(Array.isArray(r))for(let o of r)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);return e.join("&")}function ie(n){return new Promise(e=>setTimeout(e,n))}function uf(n){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!n||typeof n!="object")return e;let t=n;if("active_protocols"in t||"total_usd_value"in t){let o=t;return{...e,...o,protocols:o.protocols||[]}}let r=t.result;return!r||typeof r!="object"?e:{active_protocols:r.activeProtocols??0,total_positions:r.totalPositions??0,total_usd_value:r.totalUsd??0,total_unclaimed_usd_value:r.totalUnclaimedUsd??0,protocols:(r.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 df(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;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(r=>({token_type:r.tokenType,address:r.address,contract_address:r.address,name:r.name??"",symbol:r.symbol??"",decimals:r.decimals??18,logo:r.logo,balance:r.balance??"0",balance_formatted:r.balanceFormatted??"0",usd_price:r.usdPrice,usd_value:r.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,r)=>Number(t)-Number(r)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function rc(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,r)=>Number(t)-Number(r)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var O=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??rf).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??of).replace(/\/+$/,""),this.pantograph=new ye({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:r,tokenAddresses:o,excludeSpam:s=!1,excludeUnverifiedContracts:a=!1,convertYieldValues:i=!0}=e;if(!t)return{success:!1,error:"Address is required"};let l=se(r),c="Unknown error";for(let d=1;d<=I;d++)try{let u={chain:l,exclude_spam:s,exclude_unverified_contracts:a,limit:100};o&&(u.token_addresses=o);let p=[],m=null;do{m&&(u.cursor=m);let h=ae(u),g=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${h}`,b=await C.get(g);if(!b.ok)throw new U(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()===lf?cf: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>=sf)}return{success:!0,data:f}}catch(u){if(c=u instanceof Error?u.message:"Unknown error",u instanceof U&&u.status===400)break;d<I&&await ie(oe)}return{success:!1,error:c}}async getTokenMetadata(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Token address is required"};let o=se(r),s="Unknown error",a=await this.pantograph.getTokenMetadata(t,o);if(a)return{success:!0,data:a};for(let i=1;i<=I;i++)try{let[l,c]=await Promise.allSettled([C.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${ae({chain:o,addresses:[t]})}`),C.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${ae({chain:o,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<I&&await ie(oe);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 U&&l.status===400)break;i<I&&await ie(oe)}return{success:!1,error:s}}async getWalletNFTs(e){let{address:t,chain:r,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 d=se(r),u=[],p=a,m,f;for(let h=0;h<af;h++){let g=await this.fetchWalletNftsPage({address:t,moralisChain:d,limit:o,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:r,limit:o,excludeSpam:s,cursor:a,tokenAddresses:i,includePrices:l,format:c}=e,d="Unknown error";for(let u=1;u<=I;u++)try{let p={chain:r,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=ae(p),f=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${m}`,h=await C.get(f);if(!h.ok)throw new U(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 U&&p.status===400)break;u<I&&await ie(oe)}return{success:!1,error:d}}async getWalletNftCollections(e){let{address:t,chain:r,limit:o=100,excludeSpam:s=!0,cursor:a}=e;if(!t)return{success:!1,error:"Address is required"};let i=se(r),l="Unknown error";for(let c=1;c<=I;c++)try{let d={chain:i,limit:o,exclude_spam:s};a&&(d.cursor=a);let u=ae(d),p=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/collections?${u}`,m=await C.get(p);if(!m.ok)throw new U(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 U&&d.status===400)break;c<I&&await ie(oe)}return{success:!1,error:l}}async getNftMetadata(e){let{address:t,tokenId:r,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(r==null||r==="")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=se(o),d="Unknown error";for(let u=1;u<=I;u++)try{let p={chain:c,format:s,normalizeMetadata:a,media_items:i};l&&(p.include=l);let m=ae(p),f=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(r)}?${m}`,h=await C.get(f);if(!h.ok)throw new U(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 U&&p.status===400)break;u<I&&await ie(oe)}return{success:!1,error:d}}async getNftContractMetadata(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Contract address is required"};let o=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await C.get(l);if(!c.ok)throw new U(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 U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getWalletHistory(e){let{address:t,chain:r,limit:o=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(!R(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=se(r),f=Math.max(1,Math.min(100,Math.floor(o))),h="Unknown error";for(let g=1;g<=I;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=ae(b),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${y}`,k=await C.get(w);if(!k.ok)throw new U(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 U&&b.status===400)break;g<I&&await ie(oe)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:r,contractAddresses:o,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(!R(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=se(r),m=Math.max(1,Math.min(100,Math.floor(s))),f="Unknown error";for(let h=1;h<=I;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),o?.length&&(g.contract_addresses=o);let b=ae(g),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${b}`,w=await C.get(y);if(!w.ok)throw new U(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 U&&g.status===400)break;h<I&&await ie(oe)}return{success:!1,error:f}}async getWalletNftTransfers(e){let{address:t,chain:r,contractAddresses:o,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(!R(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let f=se(r),h=Math.max(1,Math.min(100,Math.floor(s))),g="Unknown error";for(let b=1;b<=I;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),o?.length&&(y.contract_addresses=o),p!=null&&(y.include_prices=p);let w=ae(y),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,v=await C.get(k);if(!v.ok)throw new U(v.status,_(v));let P=v.data;return{success:!0,data:P?.data??P}}catch(y){if(g=y instanceof Error?y.message:"Unknown error",y instanceof U&&y.status===400)break;b<I&&await ie(oe)}return{success:!1,error:g}}async getTokenHolders(e){let{address:t,chain:r}=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=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await C.get(l);if(!c.ok)throw new U(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 U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getWalletPnlSummary(e){let{address:t,chain:r,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=se(r),a="Unknown error";for(let i=1;i<=I;i++)try{let l={chain:s};o&&(l.days=o);let c=ae(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,u=await C.get(d);if(!u.ok)throw new U(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 U&&l.status===400)break;i<I&&await ie(oe)}return{success:!1,error:a}}async getWalletPnl(e){let{address:t,chain:r,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=se(r),i="Unknown error";for(let l=1;l<=I;l++)try{let c={chain:a};o&&(c.days=o),s&&s.length>0&&(c.token_addresses=s.slice(0,25));let d=ae(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${d}`,p=await C.get(u);if(!p.ok)throw new U(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 U&&c.status===400)break;l<I&&await ie(oe)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:r}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let o=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await C.get(l);if(!c.ok)throw new U(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 U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getWalletApprovals(e){let{address:t,chain:r,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=se(r),i="Unknown error";for(let l=1;l<=I;l++)try{let c={chain:a};o!=null&&(c.limit=o),s&&(c.cursor=s);let d=ae(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${d}`,p=await C.get(u);if(!p.ok)throw new U(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 U&&c.status===400)break;l<I&&await ie(oe)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:r}=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=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await C.get(l);if(!c.ok)throw new U(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:uf(u)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getWalletDefiPositions(e){let{address:t,chain:r}=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=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await C.get(l);if(!c.ok)throw new U(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:df(u)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:r,chain:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!r)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=se(o),a="Unknown error";for(let i=1;i<=I;i++)try{let l=ae({chains:s}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(r)}/positions?${l}`,d=await C.get(c);if(!d.ok)throw new U(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 U&&l.status===400)break;i<I&&await ie(oe)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:r}=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=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await C.get(l);if(!c.ok)throw new U(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 U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getTokenScore(e){let{address:t,chain:r}=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=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await C.get(l);if(!c.ok)throw new U(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 U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getTrendingTokens(e){let t=e?.chain,r=e?.limit,o="Unknown error";for(let s=1;s<=I;s++)try{let a={};t&&(a.chain=se(t)),r!=null&&(a.limit=r);let i=ae(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await C.get(l);if(!c.ok)throw new U(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:rc(u)}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof U&&a.status===400)break;s<I&&await ie(oe)}return{success:!1,error:o}}async getTopGainers(e){let{chain:t,timeFrame:r,minMarketCap:o,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=I;i++)try{let l={};t&&(l.chain=se(t)),r&&(l.time_frame=r),o!=null&&(l.min_market_cap=o),s!=null&&(l.security_score=s);let c=ae(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,u=await C.get(d);if(!u.ok)throw new U(u.status,_(u));let p=u.data,m=p?.data??p;return{success:!0,data:rc(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<I&&await ie(oe)}return{success:!1,error:a}}async getTopLosers(e){let{chain:t,timeFrame:r,minMarketCap:o,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=I;i++)try{let l={};t&&(l.chain=se(t)),r&&(l.time_frame=r),o!=null&&(l.min_market_cap=o),s!=null&&(l.security_score=s);let c=ae(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,u=await C.get(d);if(!u.ok)throw new U(u.status,_(u));let p=u.data,m=p?.data??p;return{success:!0,data:rc(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<I&&await ie(oe)}return{success:!1,error:a}}async getUnderlyingPricesUSD(e,t){return Vs(se(e),t,this.pantograph)}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}async applyYieldValues(e,t,r){if(e.length===0||r.size===0)return;let o=[],s=new Map;if(e.forEach((a,i)=>{let l=r.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),o.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})}),o.length!==0)try{let a=await Vs(t,o.map(l=>l.yieldAsset),this.pantograph);for(let l of o)l.priceUSD=Vr(l.yieldAsset,a,l.priceUSD);let i=await ri(t,o);for(let[l,c]of i){let d=s.get(l);d&&(!Number.isFinite(c.valueUSD)||!Number.isFinite(c.pricePerTokenUSD)||c.pricePerTokenUSD<=0||(d.usd_value=c.valueUSD,d.usd_price=c.pricePerTokenUSD))}}catch{}}};var pf="FORMAT (overrides any length asked above): reply with AT MOST 8 bullet points, ONE sentence each (max ~30 words), most relevant to the request first. News items: the date and source in a few words. No introduction, headings, sub-bullets, or closing summary.",mf=1536;function hf(n){let e=n.lastIndexOf(`
|
|
26
|
-
`);if(e>0)return n.slice(0,e).trimEnd();let t=Math.max(n.lastIndexOf(". "),n.lastIndexOf("! "),n.lastIndexOf("? "));return t>0?n.slice(0,t+1):n}var
|
|
25
|
+
}`,Us=class extends St{type="morpho-v2";async fetchApy(e,t,r){let o=Math.floor(Date.now()/1e3),s=await C.post(r.morphoApiUrl,{operationName:"VaultV2ByAddress",query:Qh,variables:{address:e.contract,chainId:t.chainId,options:{startTimestamp:o-7*86400,endTimestamp:o,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 Ds=class extends St{type="spark";liveRateCall(e){return Q(e.contract,Hr,"rateProvider")}followUpRateCall(e,t){let r=B(t);return r===null?null:Q(r,un,"getAPR")}decodeLiveRate(e){let t=ee(e);return t===null?null:tt(Math.expm1(Number(t)/Hn))}},Os=class extends St{type="spark-ethereum";liveRateCall(e){return Q(e.contract,Hr,"vsr")}decodeLiveRate(e){let t=ee(e);if(t===null||t<=0n)return null;let r=Number(t-Xa)/Hn;return r>-1?tt(Math.expm1(Math.log1p(r)*Es)):null}};var Ms=class extends Pt{type="spark-l2-susds";balanceIsUnderlying=!1;underlyingCall(){return null}sizeCall(e){return Q(e.token,q,"totalSupply")}liveRateCall(e){return Q(e.contract,un,"getAPR")}decodeLiveRate(e){let t=ee(e);return t===null?null:tt(Math.expm1(Number(t)/Hn))}convertToAssetsCall(e){return Q(e.contract,un,"getConversionRate")}fetchApy(e,t,r){return cn(e,t,r)}};function Vn(n,e,t,r){if(e<=0n||!Number.isInteger(t)||!Number.isInteger(r)||t<0||r<0)return null;let o=n*e/Xa,s=r-t;return s===0?o:s>0?o*10n**BigInt(s):o/10n**BigInt(-s)}var ei={"aave-v3":{protocol:new Ns,label:"Aave V3",home:"https://app.aave.com"},"compound-v3":{protocol:new Ls,label:"Compound V3",home:"https://app.compound.finance"},spark:{protocol:new Ds,label:"Spark",home:"https://app.spark.finance"},"spark-ethereum":{protocol:new Os,label:"Spark",home:"https://app.spark.finance"},"spark-l2-susds":{protocol:new Ms,label:"Spark",home:"https://app.spark.finance"},"morpho-v2":{protocol:new Us,label:"Morpho V2",home:"https://app.morpho.org"},maple:{protocol:new Is,label:"Maple",home:"https://app.maple.finance"}},Jh=ei.spark.protocol;function dn(n){return ei[n.type]?.protocol??Jh}function ze(n){return ei[n]?.label??null}function Fs(n){return ei[n]?.home??null}var Wn="0x0000000000000000000000000000000000000000";function Bs(n){let e=parseInt(n,16);return Number.isFinite(e)?{chainId:e}:null}function Ft(n){if(typeof n=="number")return Number.isInteger(n)&&n>0?`0x${n.toString(16)}`:null;if(typeof n!="string")return null;let e=n.trim().toLowerCase();if(!e)return null;if(!/^(0x[0-9a-f]+|\d+)$/.test(e))return D(e);let t=e.startsWith("0x")?parseInt(e,16):Number(e);return Number.isInteger(t)&&t>0?`0x${t.toString(16)}`:null}var Zh={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function ti(n){let e=Ft(n);return e?Zh[e]??null:null}function Ju(n){return["susds","usds","rateProvider"].map(e=>({target:n,callData:M({abi:Ql,functionName:e})}))}var Zu=3,ef={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function ec(n){let e=Ft(n),t=e?ef[e]:void 0;return t?{target:t,callData:M({abi:un,functionName:"getConversionRate"})}:null}var tf=new Set(["spark","spark-ethereum","spark-l2-susds","morpho-v2","maple"]),ed="spark-l2-susds";function Vr(n){return!!n&&tf.has(n)}var tc=n=>{if(n==null||n==="")return null;let e=Number(n);return!Number.isInteger(e)||e<0||e>36?null:e},nf=n=>{if(n==null||n==="")return null;let e=Number(n);return Number.isFinite(e)&&e>0?e:null};function qs(n){let e=nf(n.yieldAsset?.fixedPrice);return e!==null?e:Number.isFinite(n.priceUSD)?n.priceUSD:0}function td(n){if(!Vr(n.yieldProtocol)||tc(n.yieldAsset?.decimals)===null||n.yieldProtocol===ed&&!ec(n.chain))return!1;let e=qs(n);return Number.isFinite(e)&&e>0}function nc(n){let e=[],t=[];for(let r of n)if(!(r.rawBalance<=0n)&&td(r)){if(r.yieldProtocol===ed){let o=ec(r.chain);if(!o)continue;e.push({key:r.key,...o}),t.push(r.key);continue}e.push({key:r.key,target:r.address,callData:M({abi:wt,functionName:"convertToAssets",args:[r.rawBalance]})})}return{calls:e,rateKeys:t}}function ni(n,e,t){let r=new Map(n.map(i=>[i.key,i])),o=new Set(e.rateKeys),s=new Map;e.calls.forEach((i,l)=>{let c=ee(t[l]??null);if(c===null)return;if(!o.has(i.key)){s.set(i.key,c);return}let d=r.get(i.key),u=tc(d?.yieldAsset?.decimals);if(!d||u===null)return;let p=Vn(d.rawBalance,c,d.decimals,u);p!==null&&s.set(i.key,p)});let a=new Map;for(let i of n){let l=nt(i.rawBalance,i.decimals),c=qs(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=tc(i.yieldAsset?.decimals);if(p===null){a.set(i.key,u);continue}let m=nt(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 ri(n,e,t={}){let r=e.map(a=>a.chain==null?{...a,chain:n}:a),o=nc(r);if(o.calls.length===0)return ni(r,o,[]);let s=await Ae(String(n),o.calls,t.rpcUrl);return ni(r,o,s)}async function Vs(n,e,t){let r=new Map,o=[...new Set(e.filter(s=>s?.address&&nd(s.fixedPrice)===null).map(s=>String(s?.address).toLowerCase()))];if(o.length===0)return r;try{let s=await(t??new ye).getYieldPricingTokens(n,o);for(let a of s){let i=Hs(a?.price);a?.address&&i!=null&&i>0&&r.set(String(a.address).toLowerCase(),i)}}catch{}return r}function Wr(n,e,t){let r=nd(n?.fixedPrice);if(r!==null)return r;let o=n?.address?e.get(String(n.address).toLowerCase()):void 0;return o!=null&&o>0?o:Hs(t)??0}function nd(n){let e=Hs(n);return e!=null&&e>0?e:null}async function Za(n,e,t={}){let r=await rf(n,e,t.apiBaseUrl);if(!r)return null;if(!r.yieldProtocol)return $s(n,r,t);let o=t.apiBaseUrl?new ye({baseUrl:t.apiBaseUrl}):void 0,s=await Vs(n,[r.yieldAsset],o);return $s(n,{...r,price:Wr(r.yieldAsset,s,r.price)},t)}async function $s(n,e,t={}){let r=Hs(e?.price),o=l=>l!=null&&l>0?l:null;if(!e?.yieldProtocol)return o(r);let s=qs({key:"price",address:"",rawBalance:0n,decimals:0,priceUSD:r??0,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:n});if(!(s>0))return null;if(!Vr(e?.yieldProtocol))return s;let a=Math.trunc(Hs(e?.decimals)??18);if(!Number.isInteger(a)||a<0||a>36)return o(r);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:n};try{let c=(await ri(n,[i],t)).get(i.key);return c?.converted?o(c.pricePerTokenUSD):null}catch{return null}}async function rf(n,e,t){let r=String(e??"").toLowerCase();if(!r)return null;try{let a=(await new ye(t?{baseUrl:t}:void 0).getYieldPricingTokens(n,[r])).find(l=>String(l?.address??"").toLowerCase()===r);if(!a)return null;let i=$n(a);return i?{...a,...i}:a}catch{return null}}function Hs(n){if(n==null||n==="")return null;let e=typeof n=="number"?n:Number(n);return Number.isFinite(e)?e:null}var of="https://nft.keyring.app",sf="https://nft.keyring.app",af=.01,I=5,oe=1e3,lf=25,cf="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",uf="0x0000000000000000000000000000000000000000",U=class extends Error{constructor(t,r){super(r);this.status=t;this.name="MoralisHttpError"}status};function se(n){return n||Be}function ae(n){let e=[];for(let[t,r]of Object.entries(n))if(r!=null)if(Array.isArray(r))for(let o of r)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);return e.join("&")}function ie(n){return new Promise(e=>setTimeout(e,n))}function df(n){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!n||typeof n!="object")return e;let t=n;if("active_protocols"in t||"total_usd_value"in t){let o=t;return{...e,...o,protocols:o.protocols||[]}}let r=t.result;return!r||typeof r!="object"?e:{active_protocols:r.activeProtocols??0,total_positions:r.totalPositions??0,total_usd_value:r.totalUsd??0,total_unclaimed_usd_value:r.totalUnclaimedUsd??0,protocols:(r.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 pf(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;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(r=>({token_type:r.tokenType,address:r.address,contract_address:r.address,name:r.name??"",symbol:r.symbol??"",decimals:r.decimals??18,logo:r.logo,balance:r.balance??"0",balance_formatted:r.balanceFormatted??"0",usd_price:r.usdPrice,usd_value:r.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,r)=>Number(t)-Number(r)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function rc(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,r)=>Number(t)-Number(r)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var O=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??of).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??sf).replace(/\/+$/,""),this.pantograph=new ye({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:r,tokenAddresses:o,excludeSpam:s=!1,excludeUnverifiedContracts:a=!1,convertYieldValues:i=!0}=e;if(!t)return{success:!1,error:"Address is required"};let l=se(r),c="Unknown error";for(let d=1;d<=I;d++)try{let u={chain:l,exclude_spam:s,exclude_unverified_contracts:a,limit:100};o&&(u.token_addresses=o);let p=[],m=null;do{m&&(u.cursor=m);let h=ae(u),g=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${h}`,b=await C.get(g);if(!b.ok)throw new U(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()===cf?uf: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>=af)}return{success:!0,data:f}}catch(u){if(c=u instanceof Error?u.message:"Unknown error",u instanceof U&&u.status===400)break;d<I&&await ie(oe)}return{success:!1,error:c}}async getTokenMetadata(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Token address is required"};let o=se(r),s="Unknown error",a=await this.pantograph.getTokenMetadata(t,o);if(a)return{success:!0,data:a};for(let i=1;i<=I;i++)try{let[l,c]=await Promise.allSettled([C.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${ae({chain:o,addresses:[t]})}`),C.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${ae({chain:o,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<I&&await ie(oe);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 U&&l.status===400)break;i<I&&await ie(oe)}return{success:!1,error:s}}async getWalletNFTs(e){let{address:t,chain:r,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 d=se(r),u=[],p=a,m,f;for(let h=0;h<lf;h++){let g=await this.fetchWalletNftsPage({address:t,moralisChain:d,limit:o,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:r,limit:o,excludeSpam:s,cursor:a,tokenAddresses:i,includePrices:l,format:c}=e,d="Unknown error";for(let u=1;u<=I;u++)try{let p={chain:r,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=ae(p),f=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${m}`,h=await C.get(f);if(!h.ok)throw new U(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 U&&p.status===400)break;u<I&&await ie(oe)}return{success:!1,error:d}}async getWalletNftCollections(e){let{address:t,chain:r,limit:o=100,excludeSpam:s=!0,cursor:a}=e;if(!t)return{success:!1,error:"Address is required"};let i=se(r),l="Unknown error";for(let c=1;c<=I;c++)try{let d={chain:i,limit:o,exclude_spam:s};a&&(d.cursor=a);let u=ae(d),p=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/collections?${u}`,m=await C.get(p);if(!m.ok)throw new U(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 U&&d.status===400)break;c<I&&await ie(oe)}return{success:!1,error:l}}async getNftMetadata(e){let{address:t,tokenId:r,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(r==null||r==="")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=se(o),d="Unknown error";for(let u=1;u<=I;u++)try{let p={chain:c,format:s,normalizeMetadata:a,media_items:i};l&&(p.include=l);let m=ae(p),f=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(r)}?${m}`,h=await C.get(f);if(!h.ok)throw new U(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 U&&p.status===400)break;u<I&&await ie(oe)}return{success:!1,error:d}}async getNftContractMetadata(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Contract address is required"};let o=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await C.get(l);if(!c.ok)throw new U(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 U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getWalletHistory(e){let{address:t,chain:r,limit:o=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(!R(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=se(r),f=Math.max(1,Math.min(100,Math.floor(o))),h="Unknown error";for(let g=1;g<=I;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=ae(b),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${y}`,k=await C.get(w);if(!k.ok)throw new U(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 U&&b.status===400)break;g<I&&await ie(oe)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:r,contractAddresses:o,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(!R(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=se(r),m=Math.max(1,Math.min(100,Math.floor(s))),f="Unknown error";for(let h=1;h<=I;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),o?.length&&(g.contract_addresses=o);let b=ae(g),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${b}`,w=await C.get(y);if(!w.ok)throw new U(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 U&&g.status===400)break;h<I&&await ie(oe)}return{success:!1,error:f}}async getWalletNftTransfers(e){let{address:t,chain:r,contractAddresses:o,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(!R(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let f=se(r),h=Math.max(1,Math.min(100,Math.floor(s))),g="Unknown error";for(let b=1;b<=I;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),o?.length&&(y.contract_addresses=o),p!=null&&(y.include_prices=p);let w=ae(y),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,v=await C.get(k);if(!v.ok)throw new U(v.status,_(v));let P=v.data;return{success:!0,data:P?.data??P}}catch(y){if(g=y instanceof Error?y.message:"Unknown error",y instanceof U&&y.status===400)break;b<I&&await ie(oe)}return{success:!1,error:g}}async getTokenHolders(e){let{address:t,chain:r}=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=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await C.get(l);if(!c.ok)throw new U(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 U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getWalletPnlSummary(e){let{address:t,chain:r,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=se(r),a="Unknown error";for(let i=1;i<=I;i++)try{let l={chain:s};o&&(l.days=o);let c=ae(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,u=await C.get(d);if(!u.ok)throw new U(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 U&&l.status===400)break;i<I&&await ie(oe)}return{success:!1,error:a}}async getWalletPnl(e){let{address:t,chain:r,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=se(r),i="Unknown error";for(let l=1;l<=I;l++)try{let c={chain:a};o&&(c.days=o),s&&s.length>0&&(c.token_addresses=s.slice(0,25));let d=ae(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${d}`,p=await C.get(u);if(!p.ok)throw new U(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 U&&c.status===400)break;l<I&&await ie(oe)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:r}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let o=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await C.get(l);if(!c.ok)throw new U(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 U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getWalletApprovals(e){let{address:t,chain:r,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=se(r),i="Unknown error";for(let l=1;l<=I;l++)try{let c={chain:a};o!=null&&(c.limit=o),s&&(c.cursor=s);let d=ae(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${d}`,p=await C.get(u);if(!p.ok)throw new U(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 U&&c.status===400)break;l<I&&await ie(oe)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:r}=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=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await C.get(l);if(!c.ok)throw new U(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:df(u)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getWalletDefiPositions(e){let{address:t,chain:r}=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=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await C.get(l);if(!c.ok)throw new U(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:pf(u)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:r,chain:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!r)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=se(o),a="Unknown error";for(let i=1;i<=I;i++)try{let l=ae({chains:s}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(r)}/positions?${l}`,d=await C.get(c);if(!d.ok)throw new U(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 U&&l.status===400)break;i<I&&await ie(oe)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:r}=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=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await C.get(l);if(!c.ok)throw new U(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 U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getTokenScore(e){let{address:t,chain:r}=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=se(r),s="Unknown error";for(let a=1;a<=I;a++)try{let i=ae({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await C.get(l);if(!c.ok)throw new U(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 U&&i.status===400)break;a<I&&await ie(oe)}return{success:!1,error:s}}async getTrendingTokens(e){let t=e?.chain,r=e?.limit,o="Unknown error";for(let s=1;s<=I;s++)try{let a={};t&&(a.chain=se(t)),r!=null&&(a.limit=r);let i=ae(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await C.get(l);if(!c.ok)throw new U(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:rc(u)}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof U&&a.status===400)break;s<I&&await ie(oe)}return{success:!1,error:o}}async getTopGainers(e){let{chain:t,timeFrame:r,minMarketCap:o,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=I;i++)try{let l={};t&&(l.chain=se(t)),r&&(l.time_frame=r),o!=null&&(l.min_market_cap=o),s!=null&&(l.security_score=s);let c=ae(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,u=await C.get(d);if(!u.ok)throw new U(u.status,_(u));let p=u.data,m=p?.data??p;return{success:!0,data:rc(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<I&&await ie(oe)}return{success:!1,error:a}}async getTopLosers(e){let{chain:t,timeFrame:r,minMarketCap:o,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=I;i++)try{let l={};t&&(l.chain=se(t)),r&&(l.time_frame=r),o!=null&&(l.min_market_cap=o),s!=null&&(l.security_score=s);let c=ae(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,u=await C.get(d);if(!u.ok)throw new U(u.status,_(u));let p=u.data,m=p?.data??p;return{success:!0,data:rc(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof U&&l.status===400)break;i<I&&await ie(oe)}return{success:!1,error:a}}async getUnderlyingPricesUSD(e,t){return Vs(se(e),t,this.pantograph)}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}async applyYieldValues(e,t,r){if(e.length===0||r.size===0)return;let o=[],s=new Map;if(e.forEach((a,i)=>{let l=r.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),o.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})}),o.length!==0)try{let a=await Vs(t,o.map(l=>l.yieldAsset),this.pantograph);for(let l of o)l.priceUSD=Wr(l.yieldAsset,a,l.priceUSD);let i=await ri(t,o);for(let[l,c]of i){let d=s.get(l);d&&(!Number.isFinite(c.valueUSD)||!Number.isFinite(c.pricePerTokenUSD)||c.pricePerTokenUSD<=0||(d.usd_value=c.valueUSD,d.usd_price=c.pricePerTokenUSD))}}catch{}}};var mf="FORMAT (overrides any length asked above): reply with AT MOST 8 bullet points, ONE sentence each (max ~30 words), most relevant to the request first. News items: the date and source in a few words. No introduction, headings, sub-bullets, or closing summary.",hf=1536;function ff(n){let e=n.lastIndexOf(`
|
|
26
|
+
`);if(e>0)return n.slice(0,e).trimEnd();let t=Math.max(n.lastIndexOf(". "),n.lastIndexOf("! "),n.lastIndexOf("? "));return t>0?n.slice(0,t+1):n}var Yr=class extends A{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 O(e),this.llm=new ve(e?.llm??{})}async run(e,t){let r=e.keyword||"",o=e.prompt||"",s=t?.walletAddress||void 0;if(!r)return{error:"Missing required parameter: keyword"};let a;try{a=Pe(e.chain,t)}catch(i){if(i instanceof ln)return await this.researchTokenChainAgnostic(r,o,s);throw i}return await this.searchToken(r,a,o,s)}async researchTokenChainAgnostic(e,t,r){let o=[r?`User's connected wallet address: ${r}`: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(`
|
|
27
27
|
`),s=t?await this.askGeminiWithSearch(t,o):null;return{_instructions:'The token info comes from web research only (the user is on a chain this app does not support on-chain). Present a clear summary of the token using the research: what it is, current USD price and 24h change, market data, recent news and the catalyst behind any price move, and a brief, clearly-hedged sense of market direction (no financial advice). Do NOT add a labelled "AI Analysis" heading and do NOT mention that the analysis came from AI \u2014 write it as a normal token summary. If a field is unknown, omit it. Do NOT mention chains, tools, or that anything is unsupported; just answer the question.',keyword:e,token:null,userHoldsToken:!1,research:s}}async searchToken(e,t,r,o){let s=[o?`User's connected wallet address: ${o}`: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(`
|
|
28
28
|
`),[a,i,l]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),o?this.findTokenInWallet(o,t,e):Promise.resolve(null),r?this.askGeminiWithSearch(r,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 r=Date.now();try{let o=await this.llm.chat([...t?[{role:"system",content:t,timestamp:r}]:[],{role:"user",content:`${e}
|
|
29
29
|
|
|
30
|
-
${pf}`,timestamp:r}],void 0,{googleSearch:!0,maxRetries:1,maxOutputTokens:mf}),s=o.text?.trim()??"";return(o.finishReason==="MAX_TOKENS"?hf(s):s)||null}catch{return null}}async findTokenInWallet(e,t,r){if(!r)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=r.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 Yr=class extends A{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 O(e)}async run(e,t){let r=Pe(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 u=await this.resolveContractAddress(s,r,o);if(!u)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${r?T(r):"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:r});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:r||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(e,t,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,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 Gr=class extends A{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 O(e)}async run(e,t){let r=Pe(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 u=await this.resolveContractAddress(s,r,o);if(!u)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${r?T(r):"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:r});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:r||"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,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,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 Kr=class extends A{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 O(e)}async run(e,t){let r=Pe(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,r,o);if(!p)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${r?T(r):"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:r});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:r||"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,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,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 jr=class extends A{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 ye({baseUrl:e?.pantographUrl})}async run(e,t){let r=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:r,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):
|
|
30
|
+
${mf}`,timestamp:r}],void 0,{googleSearch:!0,maxRetries:1,maxOutputTokens:hf}),s=o.text?.trim()??"";return(o.finishReason==="MAX_TOKENS"?ff(s):s)||null}catch{return null}}async findTokenInWallet(e,t,r){if(!r)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=r.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 Gr=class extends A{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 O(e)}async run(e,t){let r=Pe(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 u=await this.resolveContractAddress(s,r,o);if(!u)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${r?T(r):"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:r});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:r||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(e,t,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,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 Kr=class extends A{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 O(e)}async run(e,t){let r=Pe(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 u=await this.resolveContractAddress(s,r,o);if(!u)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${r?T(r):"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:r});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:r||"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,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,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 jr=class extends A{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 O(e)}async run(e,t){let r=Pe(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,r,o);if(!p)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${r?T(r):"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:r});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:r||"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,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,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 zr=class extends A{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 ye({baseUrl:e?.pantographUrl})}async run(e,t){let r=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:r,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):
|
|
31
31
|
<rank>. <name> (<symbol>)
|
|
32
32
|
- Price: <usdPrice>
|
|
33
33
|
- Market Cap: <marketCap>
|
|
34
34
|
- 24h Price Change: <pricePercentChange.24h>
|
|
35
35
|
- 24h Volume: <totalVolume.24h>
|
|
36
|
-
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:r?T(r):"all",count:a.length,tokens:a}}};var
|
|
36
|
+
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:r?T(r):"all",count:a.length,tokens:a}}};var od={"1h":"1h","1d":"24h","1w":"7d","1M":"30d"},rd=Object.keys(od),Xr=class extends A{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 ye({baseUrl:e?.pantographUrl})}async run(e,t){let r=Ya(e.chain,t),o=typeof e.timeFrame=="string"?e.timeFrame.trim():void 0;if(o&&!rd.includes(o))return{error:`Invalid timeFrame "${o}". Allowed values: ${rd.join(", ")}.`};let s=o||void 0,a=s?od[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:r,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):
|
|
37
37
|
<rank>. <name> (<symbol>)
|
|
38
38
|
- Price: <usdPrice>
|
|
39
39
|
- Market Cap: <marketCap>
|
|
40
40
|
- Price Change: <pricePercentChange.24h> (prefix "+" for positive, "-" for negative)
|
|
41
41
|
- 24h Volume: <totalVolume.24h>
|
|
42
|
-
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:r?T(r):"all",timeFrame:s??null,count:c.length,tokens:c}}};function Xr(n){if(!Number.isFinite(n))return"0.00";let e=n<0,[t,r=""]=Math.abs(n).toFixed(8).split(".");return`${e?"-":""}${t}.${(r+"00").slice(0,2)}`}function Qr(n){if(!(typeof n!="number"||!Number.isFinite(n)||n<=0))return`($${Xr(n)})`}var Jr=class extends A{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 O(e)}async run(e,t){let r=ce(e.address,t),o=K(e.chain,t);if(o){let i=await this.service.getWalletTokenBalances({address:r,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1});return i.success?this.renderBalances(r,o,i.data?.result||[]):{error:i.error||"Failed to fetch token balances"}}let s=$e(),a=await Promise.all(s.map(async i=>{let l=await this.service.getWalletTokenBalances({address:r,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(r,a)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",r=e.balance_formatted??"0",o=e.symbol||"",s=typeof e.usd_value=="number"?`$${Xr(e.usd_value)}`:"$-";return`- ${t}: ${r} ${o} (${s})`.replace(/\s+/g," ").trim()}renderBalances(e,t,r){let o=r.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:`$${Xr(o)}`,tokens:r.map(s=>this.toTokenLine(s))}}renderBalancesByChain(e,t){let r=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=r.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:`$${Xr(o)}`,chains:r.map(s=>({chain:s.chain,totalUsdValue:`$${Xr(s.total)}`,tokens:s.tokens.map(a=>this.toTokenLine(a))}))}}};var Zr=class extends A{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 O(e)}async run(e,t){let r=ce(e.address,t),o=Pe(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:r,chain:o,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 P=Vu(o,v.hash);return P?{...v,explorerUrl:P}: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:r,chain:o||"default",pagination:{cursor:y.data?.cursor??null,hasMore:!!y.data?.cursor},transactionCount:k.length,transactions:k}}};function ff(n){if(n.value_decimal)return n.value_decimal;let e=parseInt(n.token_decimals??"18",10);if(isNaN(e)||e===0)return n.value;try{let t=BigInt(n.value),r=BigInt(10)**BigInt(e),o=t/r,a=(t%r).toString().padStart(e,"0").replace(/0+$/,"");return a?`${o}.${a}`:`${o}`}catch{return n.value}}var eo=class extends A{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 O(e)}async run(e,t){let r=ce(e.address,t),o=Pe(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(E=>typeof E=="string"&&!!E).map(E=>E.trim()):void 0,y,w;if(g){let E=await this.resolveContractAddressBySymbol(g,r,o);E&&(b=[E.address],y=E.symbol,w=E.name)}let k=await this.service.getWalletTokenTransfers({address:r,chain:o,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=r.toLowerCase(),S=(k.data?.result||[]).map(E=>{let ke=E.from_address.toLowerCase()===v,V=ke?"send":"receive",z=ke?E.to_address:E.from_address,fe=ke?E.to_address_label??void 0:E.from_address_label??void 0,Ne=ke?E.to_address_entity??void 0:E.from_address_entity??void 0;return{...E,direction:V,amount_formatted:ff(E),counterparty:z,counterparty_label:fe,counterparty_entity:Ne}}),x=h==="all"?S:S.filter(E=>E.direction===h);if(g&&!b){let E=g.toLowerCase();x=x.filter(ke=>(ke.token_symbol??"").toLowerCase()===E)}let L=this.buildCounterparties(x);return{walletAddress:r,chain:o||"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:x.length,transfers:x,counterparties:L}}async resolveContractAddressBySymbol(e,t,r){let o=e.toLowerCase(),s=await this.service.getWalletTokenBalances({address:t,chain:r});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:r});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,r=new Map;for(let s of e){let a=s.direction==="send"?t:r,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(r)}}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 to=class extends A{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 O(e)}async run(e,t){let r=ce(e.address,t),o=Pe(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(x=>typeof x=="string"&&!!x).map(x=>x.trim()):void 0,y=await this.service.getWalletNftTransfers({address:r,chain:o,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=r.toLowerCase(),v=(y.data?.result||[]).map(x=>{let L=x.from_address.toLowerCase()===w,E=L?"send":"receive",ke=L?x.to_address:x.from_address,V=L?x.to_address_label??void 0:x.from_address_label??void 0,z=L?x.to_address_entity??void 0:x.from_address_entity??void 0;return{...x,direction:E,counterparty:ke,counterparty_label:V,counterparty_entity:z}}),P=g==="all"?v:v.filter(x=>x.direction===g),S=this.buildCounterparties(P);return{walletAddress:r,chain:o||"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:P.length,transfers:P,counterparties:S}}buildCounterparties(e){let t=new Map,r=new Map;for(let s of e){let a=s.direction==="send"?t:r,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(r)}}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 gf=["all","7","30","60","90"],no=class extends A{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 O(e)}async run(e,t){let r=ce(e.address,t),o=K(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=gf.includes(s)?s:void 0;if(o){let h=await this.service.getWalletPnlSummary({address:r,chain:o,days:a});return h.success?{walletAddress:r,chain:o,days:a??"all",summary:this.mapSummary(h.data)}:{error:h.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all($e().map(async h=>{let g=await this.service.getWalletPnlSummary({address:r,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:r,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 yf=["all","7","30","60","90"],oi=25,ro=class extends A{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 ${oi}. 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 ${oi}.`,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 ${oi}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=ce(e.address,t),o=K(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=yf.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(o){let u=await this.fetchChainPnl(r,o,a,i,l);return u.ok?{walletAddress:r,chain:o,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($e().map(async u=>({chain:u,res:await this.fetchChainPnl(r,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:r,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,r,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=bf([...a.map(u=>u.address),...s]).slice(0,oi),c=l.length>0?l:void 0,d=await this.service.getWalletPnl({address:e,chain:t,days:r,tokenAddresses:c});return{ok:d.success,error:d.error,tokens:d.data?.result??[],tokenAddresses:c,resolvedFromSymbols:a,unresolvedSymbols:i}}async resolveContractAddress(e,t,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,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 bf(n){let e=new Set,t=[];for(let r of n){let o=r.toLowerCase();e.has(o)||(e.add(o),t.push(r))}return t}var wf=BigInt(2)**BigInt(255),oo=class extends A{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 O(e)}async run(e,t){let r=ce(e.address,t),o=Pe(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:r,chain:o,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=>kf(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:r,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:u.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:f.length},approvals:u,riskyApprovals:f}}};function kf(n){let e=vf(n.value);return{blockNumber:n.block_number,blockTimestamp:n.block_timestamp??null,transactionHash:n.transaction_hash??null,value:n.value,valueFormatted:n.value_formatted??null,isUnlimited:e,token:{address:n.token.address,addressLabel:n.token.address_label??null,name:n.token.name??null,symbol:n.token.symbol??null,logo:n.token.logo??null,possibleSpam:!!n.token.possible_spam,verifiedContract:n.token.verified_contract??null,currentBalance:n.token.current_balance??null,currentBalanceFormatted:n.token.current_balance_formatted??null,usdPrice:n.token.usd_price??null,usdAtRisk:n.token.usd_at_risk??null},spender:{address:n.spender.address,label:n.spender.address_label??null,entity:n.spender.entity??null,entityLogo:n.spender.entity_logo??null}}}function vf(n){if(!n)return!1;try{return BigInt(n)>=wf}catch{return!1}}var so=class extends A{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 O(e)}async run(e,t){let r=ce(e.address,t),o=K(e.chain,t);if(o){let i=await this.service.getWalletDefiPositions({address:r,chain:o});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=i.data||[];return{walletAddress:r,chain:o,positionCount:l.length,positions:l.map(ad)}}let a=(await Promise.all($e().map(async i=>{let l=await this.service.getWalletDefiPositions({address:r,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(ad)}));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:r,chain:"all",positionCount:a.reduce((i,l)=>i+l.positionCount,0),chains:a}}};function ad(n){return{protocolName:n.protocol_name,protocolId:n.protocol_id,protocolUrl:n.protocol_url,protocolLogo:n.protocol_logo,accountHealthFactor:n.account_data?.health_factor??null,position:Tf(n.position)}}function Tf(n){return{label:n.label,address:n.address,balanceUsd:n.balance_usd,totalUnclaimedUsdValue:n.total_unclaimed_usd_value,tokens:(n.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:n.position_details??null}}var ao=class extends A{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 O(e)}async run(e,t){let r=e.protocol?.trim();if(!r)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let o=ce(e.address,t),s=K(e.chain,t);if(s){let l=await this.service.getWalletDefiProtocolPositions({address:o,protocol:r,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($e().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:r,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 ${r} 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:r,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(Af)}}};function Af(n){return{label:n.label,address:n.address,balanceUsd:n.balance_usd,totalUnclaimedUsdValue:n.total_unclaimed_usd_value,tokens:(n.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:n.position_details??null}}function Pf(n){try{return(Number(BigInt(n))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return n}}var io=class extends A{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 O(e)}async run(e,t){let r=e.transactionHash;if(!r)return{error:"Transaction hash is required."};let o=Pe(e.chain,t),s=await this.service.getTransactionByHash({transactionHash:r,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:Pf(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 id=new Map;function Sf(n){let e=id.get(n);if(e)return e;let t=rn({rpcUrl:n});return id.set(n,t),t}async function ld(n,e,t=[]){let r=await Sf(n).rpc(e,t);if(r===void 0)throw new Error(`RPC ${e}: empty result`);return r}function cd(n,e,t){return ld(n,"eth_call",[{to:e,data:t},"latest"])}async function xf(n,e,t){let r=Mn(n);if(!r)return null;try{return await cd(r,e,t)}catch{return null}}function N(n,e){globalThis.__LENDING_DEBUG__!==!1&&(e===void 0?console.log(`[LEND] ${n}`):console.log(`[LEND] ${n}`,JSON.stringify(e,Cf)))}function Cf(n,e){return typeof e=="bigint"?`${e}n`:e}var Rf=6e4,oc=new Map;async function Ws(n,e){let t=Ft(e),r=t?parseInt(t,16):NaN;if(!t||!Number.isFinite(r))return[];let o=`${n}|${t}`,s=oc.get(o);if(s&&Date.now()-s.at<Rf)return s.markets;let a=Ef(n,t,r),i=a.then(l=>l.markets);return oc.set(o,{at:Date.now(),markets:i}),a.then(l=>{l.answered||oc.delete(o)}),i}async function si(n,e){return(await Ws(n,e)).length>0}async function Ef(n,e,t){try{let r=`${n}/supply/v2?chainId=${t}&limit=100&page=1`;N("catalog: GET",r);let o=await C.get(r);if(!o.ok){let a=o.status>=400&&o.status<500;return N(a?"catalog: chain not served":"catalog: FAILED",{chain:e,status:o.status,message:_(o)}),{markets:[],answered:a}}let s=(o.data?.data?.items||[]).flatMap(a=>{let i=_f(a,e);return i?[i]:[]});return N("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(r){return N("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:e,message:r?.message}),{markets:[],answered:!1}}}function ud(n,e){let t=e.trim().toLowerCase();if(!t)return[];if(R(t))return n.filter(o=>o.contract===t||o.token===t);let r=n.filter(o=>o.name.trim().toLowerCase()===t);return r.length>0?r:n.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 _f(n,e){if(n?.isDeleted===!0)return null;let t=typeof n?.contract=="string"?n.contract.toLowerCase():"";if(!R(t))return null;let r=typeof n?.token=="string"&&R(n.token)?n.token.toLowerCase():t,o=Number(n?.rating?.balanceScore),s=n?.type?.trim()||"unknown";return{chain:e,name:n?.name?.trim()||"USDC lending market",protocol:n?.protocolId?.name?.trim()||"Unknown",protocolLabel:je(s),protocolUrl:n?.protocolId?.domain?.trim()||null,type:s,contract:t,token:r,platformScore:Number.isFinite(o)?o:null}}function sc(){return $e()}async function ai(n){let e=sc(),t=await Promise.all(e.map(r=>si(n,r)));return e.filter((r,o)=>t[o])}async function ii(n,e){let t=D(e);return t?si(n,t):!1}async function dd(n,e){let t=e.map(s=>D(s)).filter(s=>!!s),r=[...new Set(t)],o=await Promise.all(r.map(s=>si(n,s)));return r.filter((s,a)=>o[a])}function Kn(n){return Fs(n)}var pd=6;async function md(n,e,t){let r=e.map(w=>R(w)?w.toLowerCase():null);if(r.every(w=>w===null))return N("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let o=ti(n),s;try{N("discovery: probing 5 accessors per token",{chain:n,tokens:r,psm:o}),s=await Ae(n,[...r.flatMap(w=>w?Nf(w):[]),...o?Zu(o):[]])}catch(w){return N("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:n,message:w?.message}),e.map(()=>null)}let a=o?s.slice(s.length-ed):[],i=B(a[0])?.toLowerCase()??null,l=B(a[1]),c=B(a[2]),d=i&&l&&c?{susds:i,usds:l,oracle:c}:null;o&&N("discovery: PSM3 lookup",{psm:o,susds:i,usds:l,oracle:c});let u=0,p=r.map(w=>{if(!w)return null;let k=s.slice(u,u+pd);return u+=pd,N("discovery: probe answers",{token:w,"POOL()":B(k[0]),"UNDERLYING_ASSET_ADDRESS()":B(k[1]),"baseToken()":B(k[2]),"asset()":B(k[3]),"vsr()":ee(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 f=await Lf(n,[...m]);m.size>0&&N("discovery: Aave pool authentication",{claimed:[...m],genuine:[...f]});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 g=await If(n,h);h.size>0&&N("discovery: Maple manager authentication",{claimed:[...h.keys()],genuine:[...g]});let b=p.flatMap(w=>w?B(w.slice[0])&&B(w.slice[1])||B(w.slice[2])?[]:g.has(w.token)?[]:B(w.slice[3])?[w.token]:[]:[]),y=await Uf(n,[...new Set(b)],t);return b.length>0&&N("discovery: Morpho vault lookup",{asked:[...new Set(b)],recognised:[...y.keys()]}),p.map(w=>{if(!w)return null;let{token:k,slice:v}=w,P={chain:n,protocolUrl:null,token:k,platformScore:null};if(d&&k===d.susds)return N("discovery: classified",{token:k,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:d.oracle}),{...P,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:je("spark-l2-susds"),protocolUrl:Kn("spark-l2-susds"),type:"spark-l2-susds",contract:d.oracle,assetAddress:d.usds};let S=B(v[0]);if(S&&B(v[1])){let x=f.has(S.toLowerCase());return N("discovery: classified",{token:k,as:x?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:S}),x?{...P,name:"Aave v3",protocol:"AAVE",protocolLabel:je("aave-v3"),protocolUrl:Kn("aave-v3"),type:"aave-v3",contract:S}:null}if(B(v[2]))return N("discovery: classified",{token:k,as:"compound-v3"}),{...P,name:"Compound v3",protocol:"COMPOUND",protocolLabel:je("compound-v3"),protocolUrl:Kn("compound-v3"),type:"compound-v3",contract:k};if(B(v[3])){if(g.has(k))return N("discovery: classified",{token:k,as:"maple (manager round trip verified)"}),{...P,name:"Maple",protocol:"MAPLE",protocolLabel:je("maple"),protocolUrl:Kn("maple"),type:"maple",contract:k};if(y.has(k)){N("discovery: classified",{token:k,as:"morpho-v2"});let E=y.get(k)||"Morpho V2";return{...P,name:E,protocol:"MORPHO",protocolLabel:je("morpho-v2"),protocolUrl:Kn("morpho-v2"),type:"morpho-v2",contract:k}}let L=ee(v[4])!==null;return N("discovery: classified",{token:k,as:L?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),L?{...P,name:"Spark",protocol:"SPARK",protocolLabel:je("spark-ethereum"),protocolUrl:Kn("spark-ethereum"),type:"spark-ethereum",contract:k}:{...P,name:"Spark",protocol:"SPARK",protocolLabel:je("spark"),protocolUrl:Kn("spark"),type:"spark",contract:k}}return N("discovery: classified",{token:k,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function Nf(n){return[{target:n,callData:M({abi:qr,functionName:"POOL"})},{target:n,callData:M({abi:qr,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:n,callData:M({abi:Mt,functionName:"baseToken"})},{target:n,callData:M({abi:wt,functionName:"asset"})},{target:n,callData:M({abi:$r,functionName:"vsr"})},{target:n,callData:M({abi:Jl,functionName:"manager"})}]}async function Lf(n,e){if(e.length===0)return new Set;try{let t=await Ae(n,e.map(r=>({target:r,callData:M({abi:zl,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((r,o)=>B(t[o])!==null))}catch{return new Set}}async function If(n,e){if(e.size===0)return new Set;let t=[...e.entries()];try{let r=await Ae(n,t.map(([,o])=>({target:o,callData:M({abi:Zl,functionName:"pool"})})));return new Set(t.filter(([o],s)=>B(r[s])?.toLowerCase()===o.toLowerCase()).map(([o])=>o))}catch{return new Set}}async function Uf(n,e,t){let r=parseInt(n,16);if(e.length===0||!Number.isFinite(r))return new Map;let o=await Promise.all(e.map(async s=>{try{let a=await C.post(t,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:s,c:r}}),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 Df=.01;function Of(n){return n.reduce((e,t)=>t.conditions===null?e+t.apyPercent:e,0)}function Mf(n,e){if(typeof e!="string"||!e.trim())return;let t=e.trim(),r=Ps();r[n]!==t&&Dn({...r,[n]:t})}var lo=class{constructor(e,t,r){this.coinPoolBaseUrl=e;this.endpoints=t;this.describer=r}coinPoolBaseUrl;endpoints;describer;async describeReceiptTokens(e,t,r){let o=Date.now();N("describeReceiptTokens: START",{chain:e,tokens:t,hasRpcUrl:!!r});let s=Ft(e);s&&Mf(s,r);let a=s?Bs(s):null,i=[...new Set(t.filter(R).map(p=>p.toLowerCase()))];if(N("describeReceiptTokens: chain resolved",{hex:s,hasChainInfo:!!a,wanted:i}),!s||!a||i.length===0)return N("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:s,hasChainInfo:!!a,wantedCount:i.length}),new Map;N("describeReceiptTokens: on-chain discovery for",i);let l=await md(s,i,this.endpoints.morphoApiUrl),d=[...new Map(i.flatMap((p,m)=>{let f=l[m];return N("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 N("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-o}),new Map;N("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 N("describeReceiptTokens: DONE",{ms:Date.now()-o,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,r){if(N("findMarketByReceiptToken: called",{chain:e,receiptToken:t,hasRpcUrl:!!r}),!R(t))return N("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:t}),null;let s=(await this.describeReceiptTokens(e,[t],r)).get(t.toLowerCase())??null;return N("findMarketByReceiptToken: returning",{found:!!s}),s}async getSupplyPositions(e){if(!R(e.address))return[];let t=await dd(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 r=Ft(e),o=r?Bs(r):null;return r&&o?this.describer.describe(r,o,t):[]}async positionsForChain(e,t){let r=Bs(e),o=await Ws(this.coinPoolBaseUrl,e);if(!r||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,r,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<Df?[]:[{...l,suppliedUsdc:d,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:d*(l.avgApyPercent+Of(l.rewards))/100}]})}};var ac=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var co=class{constructor(e){this.coinPoolBaseUrl=e}coinPoolBaseUrl;async listChains(){return ai(this.coinPoolBaseUrl)}async isSupported(e){return ii(this.coinPoolBaseUrl,e)}async getMarkets(e){let t=D(e);return t?Ws(this.coinPoolBaseUrl,t):[]}async findMarket(e,t){let r=await this.getMarkets(e);return ud(r,t)}canSupply(e){return ac.includes(e.type)}async readReceiptToken(e,t){let r=pn(t).balanceIsUnderlying;try{let o=await Ae(e,[{target:t.token,callData:M({abi:q,functionName:"symbol"})},{target:t.token,callData:M({abi:q,functionName:"decimals"})}]);return{symbol:ur(o[0]),decimals:dr(o[1]),isUnderlying:r}}catch{return{symbol:null,decimals:null,isUnderlying:r}}}};var fd=6e5,li=new Map;async function hd(n){let e=li.get(n);if(e&&Date.now()-e.at<fd)return e.chains;let t=Hf(n);return li.set(n,{at:Date.now(),chains:t}),t.then(r=>{r===null&&li.delete(n)}),t}async function Ff(n){try{let e=n==="morpho"?await Bf():await qf();return!e||e.size===0?(N(`protocolChains: ${n} returned no chains`),null):(N(`protocolChains: ${n} live on`,[...e].sort((t,r)=>t-r)),e)}catch(e){return N(`protocolChains: ${n} FAILED`,e instanceof Error?e.message:e),null}}async function Bf(){let n=await C.post("https://api.morpho.org/graphql",{query:"{ chains { id network } }"});if(!n.ok)return null;let e=n.data?.data?.chains;if(!Array.isArray(e))return null;let t=new Set;for(let r of e)typeof r?.id=="number"&&Number.isInteger(r.id)&&r.id>0&&(t.add(r.id),typeof r.network=="string"&&r.network.trim()&&gd.set(r.id,r.network.trim()));return t}async function qf(){let n=await C.get("https://v3-api.compound.finance/market/all-networks/all-contracts/summary");if(!n.ok||!Array.isArray(n.data))return null;let e=new Set;for(let t of n.data)typeof t?.chain_id=="number"&&Number.isInteger(t.chain_id)&&t.chain_id>0&&e.add(t.chain_id);return e}var gd=new Map;function yd(n){return gd.get(n)??null}var $f=1500;async function bd(){let n=Promise.all([hd("morpho").catch(()=>null),hd("compound").catch(()=>null)]),e,t=new Promise(r=>{e=setTimeout(r,$f),e?.unref?.()});try{await Promise.race([n,t])}finally{e&&clearTimeout(e)}}function ic(n){let e=li.get(n);return!e||Date.now()-e.at>=fd?null:wd.get(e.chains)??null}var wd=new WeakMap;function Hf(n){let e=Ff(n);return e.then(t=>{t&&wd.set(e,t)}),e}var Vf={1:"ethereum",10:"opmainnet",130:"unichain",137:"polygon",143:"monad",480:"world-chain",988:"stable",999:"hyperevm",4217:"tempo",4663:"robinhood-chain",5042:"arc",8453:"base",42161:"arbitrum",747474:"katana"},Wf={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",100:"proto_gnosis_v3",137:"proto_polygon_v3",143:"proto_monad_v3",146:"proto_sonic_v3",196:"proto_xlayer_v3",324:"proto_zksync_v3",1088:"proto_metis_v3",1868:"proto_soneium_v3",4326:"proto_megaeth_v3",5e3:"proto_mantle_v3",8453:"proto_base_v3",9745:"proto_plasma_v3",42161:"proto_arbitrum_v3",42220:"proto_celo_v3",43114:"proto_avalanche_v3",57073:"proto_ink_v3",59144:"proto_linea_v3",534352:"proto_scroll_v3"},Yf={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},Gf={1:"mainnet",10:"op",130:"unichain",137:"polygon",2020:"ronin",5e3:"mantle",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function ci(n){let e=og(n.chain);return(e===null?null:Kf(n,e))??Fs(n.type)??rg(n,e)}function Kf(n,e){switch(n.type){case"morpho-v2":{let t=Vf[e]??Xf(e);if(!t||!n.contract)return null;let r=`https://app.morpho.org/${t}/vault/${lc(n.contract)}`,o=Qf(n.name);return o?`${r}/${o}`:r}case"aave-v3":{let t=Wf[e],r=jf(n);return!t||!r?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${lc(r)}&marketName=${t}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let t=Yf[e],r=tg(n);return!t||!r?null:`https://app.spark.finance/savings/${t}/${r}`}case"compound-v3":{if(Jf(e))return null;let t=Gf[e],r=Zf(n);return!t||!r?null:`https://app.compound.finance/?market=${r}-${t}`}default:return null}}function jf(n){let e=n.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var zf=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Xf(n){if(!ic("morpho")?.has(n))return null;let t=yd(n);return t&&t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Qf(n){let e=n?.trim().toLowerCase()||"";return!e||zf.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Jf(n){let e=ic("compound");return e!==null&&!e.has(n)}function Zf(n){let e=n.asset?.address?.trim().toLowerCase()||"",t=eg[e];if(t)return t;let r=n.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(r)&&r.length<=12?r:null}var eg={"0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"usdc.e","0xff970a61a04b1ca14834a43f5de4533ebddb5cc8":"usdc.e"};function tg(n){let e=n.shareSymbol?.trim().toLowerCase()||"";if(/^[a-z0-9]{2,12}$/.test(e))return e;let t=`${n.name||""} ${n.token||""}`.toLowerCase();for(let o of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(t.includes(o))return o;if(n.type==="spark-ethereum")return ng[n.contract?.trim().toLowerCase()||""]??null;let r=n.asset?.symbol?.trim().toLowerCase()||"";return!/^[a-z0-9]{2,11}$/.test(r)||r.startsWith("s")?null:`s${r}`}var ng={"0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f":"speth","0x80128dbb9f07b93dde62a6daeadb69ed14a7d354":"sppyusd","0xe2e7a17dff93280dec073c995595155283e3c372":"spusdt","0x28b3a8fb53b741a8fd78c0fb9a6b2393d896a43d":"spusdc","0x45d91340b3b7b96985a72b5c678f7d9e8d664b62":"spusdt","0xc358c90d32375721cb3924320fdc2f8b694347ca":"spusdt","0xde770c84fe66e063336b31737cfe9790f18c4087":"spusdg"};function rg(n,e){let t=n.protocolUrl?.trim();if(!t)return null;let r=/^https?:\/\//i.test(t)?t:`https://${t.replace(/^\/+/,"")}`;try{let o=new URL(r);return e!==null&&o.searchParams.set("chainId",String(e)),n.contract&&o.searchParams.set("contract",lc(n.contract)),o.toString()}catch{return r}}function lc(n){let e=n.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function og(n){let e=n?.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 sg=new Set(["spark","spark-ethereum"]),ag=8;function ig(n,e,t){if(n.market.type!=="spark-l2-susds")return ee(e);let r=ee(e);return r===null||n.tokenDecimals===null?null:Yn(n.rawBalance,r,n.tokenDecimals,t)}var ui=class{constructor(e){this.endpoints=e}endpoints;apyLimiter=new cc(ag);pantograph=new ye;async describe(e,t,r){if(r.length===0)return[];N("describe: START",{chain:e,count:r.length,types:r.map(l=>l.type)});let{assets:o,shareSymbols:s}=await this.resolveAssets(e,r);N("describe: assets resolved",o);let[a,i]=await Promise.all([this.readMarketState(e,r,o),Promise.all(r.map((l,c)=>this.apyLimiter.run(()=>this.fetchApy(l,t,o[c])))),bd()]);return N("describe: on-chain state",a),N("describe: APY fetched",i.map((l,c)=>({type:r[c].type,rawSamples:l.samples.length,sourceCurrent:l.current}))),r.map((l,c)=>{let{totalSuppliedUsdc:d,liveApyFraction:u}=a[c],p=i[c].sizeOverride??d,m=cg(i[c].samples,u??i[c].current,i[c].rewards,i[c].avgOverride??null);return N("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:o[c]?.symbol}),{...l,protocolUrl:ci({...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,r){let o=M({abi:q,functionName:"balanceOf",args:[t]}),s=M({abi:q,functionName:"decimals"}),a=r.flatMap(l=>[{target:l.token,callData:o},{target:l.token,callData:s}]),i=await Ae(e,a);return r.flatMap((l,c)=>{let d=ee(i[c*2]);return d===null||d<=0n?[]:[{market:l,rawBalance:d,tokenDecimals:dr(i[c*2+1])}]})}async convertToUnderlying(e,t,r){let o=[],s=t.map(i=>{let l=pn(i.market).convertToAssetsCall(i.market,i.rawBalance);return l?(o.push(l),o.length-1):-1}),a=await Ae(e,o);return t.map((i,l)=>{let c=r[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(s[l]<0)return tt(i.rawBalance,c);let d=ig(i,a[s[l]],c);return d===null?tt(i.rawBalance,i.tokenDecimals??c):tt(d,c)})}async resolveAssets(e,t){let r={address:Gn,decimals:NaN,symbol:null,logo:null},o=[],s=t.map(p=>{let m=pn(p).underlyingCall(p);return m?(o.push(m),o.length-1):-1}),a;try{let p=o.length>0?await Ae(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,d]=await Promise.all([this.readAssetMetadata(e,i),this.fetchAssetLogos(e,i),this.readShareSymbols(e,t)]);return{assets:a.map(p=>{if(!p)return r;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 r=M({abi:q,functionName:"symbol"}),o=[],s=t.map(a=>!sg.has(a.type)||!a.contract?-1:(o.push({target:a.contract,callData:r}),o.length-1));if(o.length===0)return t.map(()=>null);try{let a=await Ae(e,o);return s.map(i=>i<0?null:ur(a[i]))}catch{return t.map(()=>null)}}async readAssetMetadata(e,t){let r=new Map;if(t.length===0)return r;let o=M({abi:q,functionName:"decimals"}),s=M({abi:q,functionName:"symbol"});try{let a=await Ae(e,t.flatMap(i=>[{target:i,callData:o},{target:i,callData:s}]));t.forEach((i,l)=>{r.set(i,{decimals:dr(a[l*2]),symbol:ur(a[l*2+1])})})}catch{}return r}async fetchAssetLogos(e,t){let r=new Map;if(t.length===0)return r;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&&r.set(s.toLowerCase(),i)}}catch{}return N("resolveAssets: logos",{chain:e,requested:t.length,found:r.size}),r}async readMarketState(e,t,r){let o=[],s=t.map((d,u)=>{let p=pn(d),m=r[u],f={market:d,protocol:p,asset:m,size:o.length,rate:-1};o.push(p.sizeCall(d,m));let h=p.liveRateCall(d,m);return h&&(f.rate=o.length,o.push(h)),f}),a=await Ae(e,o),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 Ae(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,r){try{N("fetchApy: requesting",{market:e.name,type:e.type,asset:r?.symbol});let o=await pn(e).fetchApy(e,t,this.endpoints,r);return N("fetchApy: got",{market:e.name,samples:o.samples.length,current:o.current,avgOverride:o.avgOverride??null}),o}catch(o){return N("fetchApy: FAILED \u2014 market listed without APY",{market:e.name,type:e.type,message:o?.message}),{samples:[],current:null,rewards:[]}}}},cc=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 lg(n,e){let t=_s(Date.now()),r=new Map,o=null;for(let i of n)!Number.isFinite(i.timeMs)||!Number.isFinite(i.fraction)||i.fraction<0||_s(i.timeMs)>t||((!o||i.timeMs>o.timeMs)&&(o=i),r.set(i.timeMs,i.fraction));let s=[...r.entries()].sort((i,l)=>i[0]-l[0]).map(([i,l])=>({date:new Date(i).toISOString(),apyPercent:l*100})),a=e??(o&&_s(o.timeMs)===t?o.fraction:null);return{history:s,live:a}}function cg(n,e,t=[],r=null){let{history:o,live:s}=lg(n,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=r!==null&&Number.isFinite(r)?r*100:null;if(o.length===0)return{history:o,avgApyPercent:u,currentApyPercent:c,apyChangePercent:null,...d};let p=o.reduce((m,f)=>m+f.apyPercent,0);return{history:o,avgApyPercent:u??p/o.length,currentApyPercent:c,apyChangePercent:dg(o,a),...d}}var kd=3600*1e3,ug=kd/2;function dg(n,e){if(e===null)return null;let t=Date.now()-kd,r=null,o=Number.POSITIVE_INFINITY;for(let s=n.length-1;s>=0;s--){let a=Math.abs(Date.parse(n[s].date)-t);if(a>o)break;o=a,r=n[s]}return!r||o>ug?null:e-r.apyPercent}function vd(n,e){if(!Number.isFinite(n))return n;let t=10**e,r=Number((n*t).toPrecision(15));return(n<0?-Math.floor(-r):Math.floor(r))/t+0}var dt=class{read;supply;constructor(e={}){let t=e.coinPoolBaseUrl||"https://api.coinpool.app",r={lendingRatesBaseUrl:e.lendingRatesBaseUrl||"https://wallet-api.pantograph.app",aaveApiUrl:e.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:e.morphoApiUrl||"https://api.morpho.org/graphql"},o=new ui(r);this.read=new lo(t,r,o),this.supply=new co(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,r){return this.read.describeReceiptTokens(e,t,r)}async findMarketByReceiptToken(e,t,r){return this.read.findMarketByReceiptToken(e,t,r)}async describeResolvedMarkets(e,t){return this.read.describeResolvedMarkets(e,t)}async getMarketOverviews(e){return(await Promise.all(e.chains.map(async r=>this.read.describeResolvedMarkets(r,await this.getMarkets(r))))).flat().sort((r,o)=>(o.avgApyPercent??-1)-(r.avgApyPercent??-1))}async getSupplyPositions(e){return this.read.getSupplyPositions(e)}};var Ys="{market}",Pd=[{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}],pi=[{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}],Sd="[[LIST]]",xd=' 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.',Cd=' 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 Rd(n,e,t){let[r]=pg([n],e,t),[o]=n.canSupply?uc(n,e,t):[];return{name:n.name?.trim()||n.protocol,protocol:n.protocol,protocolUrl:n.protocolUrl,chain:t,apyPercent:n.apyPercent,detailPrompt:r?.prompt??"",detailLabel:r?.label??"",supplyPrompt:o?.prompt??"",supplyLabel:o?.label??""}}function pg(n,e,t){return Ed(n,{labelTemplate:di(e.detail_button_label),promptTemplate:di(e.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${Ys}`,...t===void 0?{}:{chainName:t}})}function uc(n,e,t){return Ed([n],{labelTemplate:di(e.supply_button_label),promptTemplate:di(e.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${Ys}`,promptFallback:`supply to ${Ys}`,...t===void 0?{}:{chainName:t},max:1})}function Ed(n,e){let t=typeof e.chainName=="string"?e.chainName.trim():"",r=[],o=new Set;for(let s of n){if(e.max!==void 0&&r.length>=e.max)break;let a=s.name?.trim();!a||o.has(a.toLowerCase())||(o.add(a.toLowerCase()),r.push({label:Td(e.labelTemplate,a,e.labelFallback,e.labelNamesMarket===!0),prompt:Td(mg(e.promptTemplate),a,e.promptFallback)+hg(s.contract,t)}))}return r}function mg(n){let[e,t]=[n[0],n[1]];return e===void 0||e===e.toLowerCase()||t!==void 0&&t!==t.toLowerCase()?n:e.toLowerCase()+n.slice(1)}function di(n){return typeof n=="string"?n:""}function hg(n,e){let t=n?.trim();if(!t||!/^0x[a-fA-F0-9]{40}$/.test(t))return"";let r=e?.trim();return r?` (market: ${t} - ${r})`:` (market: ${t})`}function Td(n,e,t,r=!0){let s=n&&(!r||n.includes(Ys))?n:t;return fg(s).split(Ys).join(e).replace(/\s+/g," ").trim()}var Ad="{chain}";function fg(n){if(!n.includes(Ad))return n;let e=Ad.replace(/[{}]/g,"\\$&");return n.replace(new RegExp(`\\s*\\S+\\s*${e}`,"g"),"").replace(new RegExp(`${e}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(e,"g"),"")}var mi=[{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"]}],pc=mi.map(n=>n.label),dc={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 _d(n){let e=typeof n=="string"?n.trim():"";if(!e)return{kind:"none"};let t=wg(e);if(!t)return{kind:"none"};let r=gg(t);if(r){let s=new Set(r.types);return{kind:"supported",label:r.label,matches:a=>s.has(a.type)}}let o=bg(t);return o?{kind:"unsupported",label:o,requested:e}:{kind:"unknown",requested:e}}function gg(n){let e=mi.filter(t=>t.aliases.includes(n));if(e.length===1)return e[0];if(e.length>1)return null;if(n.length>=3){let t=mi.filter(r=>r.aliases.some(o=>o.includes(n)||n.includes(o)));if(t.length===1)return t[0];if(t.length>1)return null}return yg(n)}function yg(n){let e=null,t=!1;for(let r of mi)for(let o of r.aliases){let s=Nd(o);if(s===0||Math.abs(o.length-n.length)>s)continue;let a=Ld(n,o,s);a>s||(!e||a<e.distance?(e={spec:r,distance:a},t=!1):a===e.distance&&r!==e.spec&&(t=!0))}return e&&!t?e.spec:null}function Nd(n){return n.length<=4?0:n.length<=9?2:3}function bg(n){let e=dc[n];if(e)return e;if(n.length>=4){let o=new Set(Object.entries(dc).filter(([s])=>s.length>=4&&(s.includes(n)||n.includes(s))).map(([,s])=>s));if(o.size===1)return[...o][0];if(o.size>1)return null}let t=null,r=!1;for(let[o,s]of Object.entries(dc)){let a=Nd(o);if(a===0||Math.abs(o.length-n.length)>a)continue;let i=Ld(n,o,a);i>a||(!t||i<t.distance?(t={label:s,distance:i},r=!1):i===t.distance&&s!==t.label&&(r=!0))}return t&&!r?t.label:null}function wg(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function Ld(n,e,t){if(n===e)return 0;if(!n.length)return e.length;if(!e.length)return n.length;let r=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<=n.length;a++){s[0]=a;let i=s[0];for(let c=1;c<=e.length;c++){let d=o[c-1]+(n[a-1]===e[c-1]?0:1),u=Math.min(s[c-1]+1,o[c]+1,d);a>1&&c>1&&n[a-1]===e[c-2]&&n[a-2]===e[c-1]&&(u=Math.min(u,r[c-2]+1)),s[c]=u,u<i&&(i=u)}if(i>t)return t+1;let l=r;r=o,o=s,s=l}return o[e.length]}function be(n,e){return n==null?null:vd(n,e)}var De=2,mn=2;function hi(n){let e=be(n.currentApyPercent,De),t=n.rewards.map(s=>({apyPercent:be(s.apyPercent,De)??0,tokenSymbol:s.tokenSymbol,conditions:s.conditions})),r=n.rewardApyPercent===null?null:t.reduce((s,a)=>s+Math.round(a.apyPercent*100),0)/100;if(r===null||e===null)return{currentApyPercent:e,rewardApyPercent:r,rewards:t,baseApyPercent:be(n.baseApyPercent,De)};let o=Math.round(e*100)-Math.round(r*100);return{currentApyPercent:e,rewardApyPercent:r,rewards:t,baseApyPercent:o/100}}var kg=["apy","score","size"],Id=3,Ud=40,uo=class extends A{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: ${pc.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-${Ud}. Default ${Id} \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},...Pd,...pi];service;constructor(e){super(),this.service=new dt(e)}async run(e,t){let r=K(e.chain,void 0),o=r?null:D(t?.chain),s=r??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=_d(e.protocol);if(l.kind==="unsupported"||l.kind==="unknown")return this.unsupportedProtocol(l);let c=s?[s]:i,d=Tg(e.sort),u=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 f=[...m].sort(vg[d]).slice(0,u),h=f.map(y=>Rd({name:y.name,contract:y.contract,protocol:y.protocol,protocolUrl:y.protocolUrl,apyPercent:be(y.currentApyPercent,De),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",r=t?e.label:`"${e.requested}"`;return{_instructions:`The user asked about ${r}, which has no lending markets here. In their language: tell them plainly that ${r} 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 ${r} 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:[...pc],marketCount:0,marketNames:[]}}instructions(e,t,r=!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 ${Sd} 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.",r?xd:""].filter(Boolean).join(" ")}},vg={apy:(n,e)=>(e.currentApyPercent??-1)-(n.currentApyPercent??-1),score:(n,e)=>(e.platformScore??-1)-(n.platformScore??-1),size:(n,e)=>(e.totalSuppliedUsdc??-1)-(n.totalSuppliedUsdc??-1)};function Tg(n){let e=typeof n=="string"?n.trim().toLowerCase():"";return kg.includes(e)?e:"apy"}function Ag(n){let e=typeof n=="number"?n:Number(n);return!Number.isFinite(e)||e<1?Id:Math.min(Math.floor(e),Ud)}function Dd(n){let{currentApyPercent:e,avgApyPercent:t,totalSuppliedUsdc:r,rewardApyPercent:o,baseApyPercent:s,platformScore:a}=n;return n.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"}:r!==null&&r<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&&r!==null&&r>=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"}:r!==null&&r>=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 fi(n){let e=typeof n=="string"?n.trim():"",t=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/i.exec(e);if(t)return t[1];let r=/0x[a-fA-F0-9]{40}/.exec(e);return r&&r[0]!==e?r[0]:e}var po=class extends A{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},...pi];service;constructor(e){super(),this.service=new dt(e)}async run(e,t){let o=K(e.chain,void 0)??D(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 u=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:T(o),chainsWithLendingMarkets:u.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=fi(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(u=>({marketName:u.name,protocol:u.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),d=c?uc({name:i.name,contract:i.contract},e,T(o)):[];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:be(l.totalSuppliedUsdc,mn),...hi(l),avgApyPercent:be(l.avgApyPercent,De),apyChangePercent:be(l.apyChangePercent,De),platformScore:l.platformScore,supplySupported:c}}async describeOne(e,t){try{let[r]=await this.service.describeResolvedMarkets(e,[t]);return r??null}catch{return null}}instructions(e,t,r){let o=Dd(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."',r?"":"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?Cd:""].filter(Boolean).join(" ")}};var mo=class extends A{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 dt(e)}async run(e,t){let r=ce(e.address,t);if(!R(r))return{error:`"${r}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=K(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:r,chain:T(o),positionCount:0,positions:[],chainsWithLendingMarkets:a.map(c=>T(c))};let i=o?[o]:a,l=await this.service.getSupplyPositions({address:r,chains:i});return{_instructions:this.instructions(l),walletAddress:r,chain:o?T(o):"all",chainsQueried:i.map(c=>T(c)),positionCount:l.length,totals:Pg(l),positions:l.map(c=>({marketName:c.name,protocol:c.protocol,protocolUrl:c.protocolUrl,chain:T(c.chain),suppliedUsdc:be(c.suppliedUsdc,mn),suppliedAssetSymbol:c.asset.symbol,avgApyPercent:be(c.avgApyPercent,De),...hi(c),apyChangePercent:be(c.apyChangePercent,De),estimatedAnnualYieldUsdc:be(c.estimatedAnnualYieldUsdc,mn),marketTotalSuppliedUsdc:be(c.totalSuppliedUsdc,mn),apyHistory:c.apyHistory.map(d=>({...d,apyPercent:be(d.apyPercent,De)})),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(r=>r.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 Pg(n){if(new Set(n.map(a=>a.asset.symbol??a.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let r=n.reduce((a,i)=>a+i.suppliedUsdc,0),o=n.filter(a=>a.avgApyPercent!==null),s=o.reduce((a,i)=>a+i.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:n[0]?.asset.symbol??null,suppliedUsdc:be(r,mn),estimatedAnnualYieldUsdc:be(n.reduce((a,i)=>a+(i.estimatedAnnualYieldUsdc??0),0),mn),weightedAvgApyPercent:be(s>0?o.reduce((a,i)=>a+i.suppliedUsdc*i.avgApyPercent,0)/s:null,De)}}var ho=class extends A{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 dt(e),this.moralis=new O(e?.moralis)}async run(e,t){let r=t?.walletAddress;if(!r)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=K(e.chain,void 0)??D(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=fi(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=Sg(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(r,s,d.address),this.service.readReceiptToken(s,l)]);if(u&&sn(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=xg(e.amount),f=m?Dt(m,d.decimals):null;if(f&&u&&sn(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:r,market:{name:l.name,type:l.type,protocol:l.protocol,protocolUrl:c?.protocolUrl??ci(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:be(h.market.apyPercent,De),assetSymbol:d.symbol,assetBalance:u?.amount??null,_instructions:this.instructions(l,d.symbol)}}async describeOne(e,t){try{let[r]=await this.service.describeResolvedMarkets(e,[t]);return r??null}catch{return null}}async assetBalance(e,t,r){try{let o=await this.moralis.getWalletTokenBalances({address:e,chain:t,tokenAddresses:[r]});if(!o.success)return null;let s=(o.data?.result??[]).find(i=>(i.token_address||"").toLowerCase()===r.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 Sg(n){let e=n?.asset;return!e?.address||e.address===Gn||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function xg(n){let e=typeof n=="string"?n.trim():typeof n=="number"?String(n):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}var gi="https://ipfs.pantograph.app/ipfs/",Od=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function jn(n){let e=n?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${gi}${t[1]}`:Od.test(e)?`${gi}${e}`:null}function Md(n){let e=n?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${gi}${t[1]}`:Od.test(e)?`${gi}${e}`:null}function Fd(n){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(n)}function mc(n){if(!n||typeof n!="object")return;let e=n,t=e.image??e.image_url??e.imageUrl;return typeof t=="string"&&t.trim()?t.trim():void 0}function Cg(n){if(typeof atob=="function"){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return new TextDecoder().decode(t)}if(typeof Buffer<"u")return Buffer.from(n,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function Rg(n){let e=n.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let t=e[1]??"",r=e[2]??"";try{let o=/;base64/i.test(t)?Cg(r):decodeURIComponent(r);return JSON.parse(o)}catch{try{return JSON.parse(r)}catch{return null}}}function Bd(n){let e=n?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=Rg(e);return t?jn(mc(t)):null}var Eg=12,_g=6e3;async function Ng(n,e,t){let r=new Array(n.length),o=0,s=new Array(Math.max(1,Math.min(e,n.length))).fill(0).map(async()=>{for(;o<n.length;){let a=o++;r[a]=await t(n[a],a)}});return await Promise.all(s),r}async function Lg(n,e){try{let t=await C.get(n,{timeout:e});if(!t.ok)return null;let r=t.data;if(r&&typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{return null}return null}catch{return null}}async function Ig(n,e){let t=n?.trim();if(!t)return null;if(/^data:/i.test(t))return Bd(t);let r=Md(t);if(!r)return null;if(Fd(r))return r;let o=await Lg(r,e);if(o){let s=jn(mc(o));if(s)return s}return null}async function yi(n,e,t){if(e.length===0)return[];let r=t?.concurrency??Eg,o=t?.timeoutMs??_g,s=await Lu(n,e,t?.rpcUrl);return Ng(s,r,a=>Ig(a,o))}var qd=100,Ug=100,fo="{name}",$d="{chain}",go=class extends A{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 O(e)}async run(e,t){let r=ce(e.address,t),o=K(e.chain,t),s=o?[o]:$e(),a=qg(e.contract_address),i=Wd(e.collection_name);return a||i?this.listNfts({address:r,chains:s,singleChain:!!o,contract:a,collectionName:i}):this.listCollections({address:r,chains:s,singleChain:!!o,args:e})}async listCollections(e){let{address:t,chains:r,singleChain:o,args:s}=e,a=await Promise.all(r.map(async c=>{let d=await this.service.getWalletNftCollections({address:t,chain:c,limit:qd});return{chain:c,rows:d.success?Hd(d.data?.result??[]):[],ok:d.success}}));if(o&&!a[0].ok)return{error:"Failed to fetch wallet NFT collections"};let i=a.flatMap(c=>c.rows.map(d=>({name:Og(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"+(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=Fg(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:r,singleChain:o,contract:s,collectionName:a}=e,i=await Promise.all(r.map(async m=>{let f=await this.service.getWalletNFTs({address:t,chain:m,limit:qd,...s?{tokenAddresses:[s]}:{}});return{chain:m,rows:f.success?Hd(f.data?.result??[]):[],ok:f.success}}));if(o&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(m=>m.rows.filter(f=>Dg(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??""}"`+(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,d=await this.resolveOnchainImages(l),u=l.map(({chain:m,row:f},h)=>{let g=Mg(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),r=new Map;e.forEach((o,s)=>{let a=r.get(o.chain)??[];a.push(s),r.set(o.chain,a)});try{await Promise.all([...r.entries()].map(async([o,s])=>{let a=s.map(l=>({contract:e[l].row.token_address,tokenId:e[l].row.token_id})),i=await yi(o,a);s.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function Hd(n){return n.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function Dg(n,e){if(e.contract)return n.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let t=e.collectionName.toLowerCase();return(n.name??"").toLowerCase().includes(t)}return!1}function Og(n){let e=n.name?.trim();if(e)return e;let t=n.token_address??"";return t.length>10?`${t.slice(0,6)}\u2026${t.slice(-4)}`:t}function Mg(n){return{name:n.normalized_metadata?.name||n.name||`#${n.token_id}`,tokenId:n.token_id,contractAddress:n.token_address,image:jn(n.normalized_metadata?.image||n.media?.original_media_url)}}function Fg(n,e){let t=typeof e.pick_button_label=="string"?e.pick_button_label:"",r=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",o=[];for(let s of n){if(o.length>=Ug)break;if(!s.contractAddress)continue;let a=typeof s.chain=="string"?s.chain.trim():"",i=a?`show my ${fo} NFTs on ${$d}`:`show my ${fo} NFTs`,l=Vd(r,{[fo]:s.name,[$d]:a},i);a&&!l.includes(a)&&(l=`${l} (${a})`),o.push({label:Bg(t,s.name,fo),prompt:`${l} (${s.contractAddress})`})}return o}function Vd(n,e,t){let r=n&&n.includes(fo)?n:t;for(let[o,s]of Object.entries(e))r=r.split(o).join(s);return r.replace(/\s+/g," ").trim()}function Bg(n,e,t){return Vd(n,{[fo]:e},t)}function Wd(n){if(typeof n!="string")return;let e=n.trim();return e||void 0}function qg(n){let e=Wd(n);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var $g="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.",St=class extends A{kind="data";category="nft";llm;constructor(e){super(),this.llm=new ve(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 r=await this.askGeminiWithSearch(t);return r?{_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:r}:{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:$g,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var yo=class extends St{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=St.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 bo=class extends St{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=St.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 hc={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"},fc="amazon.com";function Hg(n){return n?n.trim().toLowerCase().split(/[-_]/)[0]:""}function gc(n){let e=Hg(n);return hc[e]??fc}function bi(n){return`https://${gc(n)}/s?k=NFC%20Tag`}function wi(n){if(!n)return"";let e=n.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var Vg=720*60*1e3,Yd=new Map,Gd=3;function Wg(n){return[`A user in country "${n}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Gd} 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 Yg(n){if(!n)return[];let e=n.indexOf("["),t=n.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let r;try{r=JSON.parse(n.slice(e,t+1))}catch{return[]}if(!Array.isArray(r))return[];let o=[],s=new Set;for(let a of r){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>=Gd))break}return o}async function yc(n,e){let t=wi(n);if(!t||!e)return null;let r=Yd.get(t);if(r&&r.expires>Date.now())return r.links;let o=Date.now(),s=[{role:"user",content:Wg(t),timestamp:o}];try{let a=await e.chat(s,void 0,{googleSearch:!0,maxRetries:1}),i=Yg(a.text);if(i.length)return Yd.set(t,{links:i,expires:Date.now()+Vg}),i}catch{}return null}async function wo(n){let e=await yc(n.country,n.llm);return e&&e.length?e:[{label:"Amazon",url:bi(n.language)}]}function Gg(n){return n.length<=1?n.length===1?`[${n[0].label}](${n[0].url})`:"":n.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
|
|
43
|
-
`)}var
|
|
44
|
-
`),
|
|
42
|
+
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:r?T(r):"all",timeFrame:s??null,count:c.length,tokens:c}}};function Qr(n){if(!Number.isFinite(n))return"0.00";let e=n<0,[t,r=""]=Math.abs(n).toFixed(8).split(".");return`${e?"-":""}${t}.${(r+"00").slice(0,2)}`}function Jr(n){if(!(typeof n!="number"||!Number.isFinite(n)||n<=0))return`($${Qr(n)})`}var Zr=class extends A{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 O(e)}async run(e,t){let r=ue(e.address,t),o=K(e.chain,t);if(o){let i=await this.service.getWalletTokenBalances({address:r,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1});return i.success?this.renderBalances(r,o,i.data?.result||[]):{error:i.error||"Failed to fetch token balances"}}let s=$e(),a=await Promise.all(s.map(async i=>{let l=await this.service.getWalletTokenBalances({address:r,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(r,a)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",r=e.balance_formatted??"0",o=e.symbol||"",s=typeof e.usd_value=="number"?`$${Qr(e.usd_value)}`:"$-";return`- ${t}: ${r} ${o} (${s})`.replace(/\s+/g," ").trim()}renderBalances(e,t,r){let o=r.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:`$${Qr(o)}`,tokens:r.map(s=>this.toTokenLine(s))}}renderBalancesByChain(e,t){let r=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=r.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:`$${Qr(o)}`,chains:r.map(s=>({chain:s.chain,totalUsdValue:`$${Qr(s.total)}`,tokens:s.tokens.map(a=>this.toTokenLine(a))}))}}};var eo=class extends A{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 O(e)}async run(e,t){let r=ue(e.address,t),o=Pe(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:r,chain:o,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 P=Hu(o,v.hash);return P?{...v,explorerUrl:P}: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:r,chain:o||"default",pagination:{cursor:y.data?.cursor??null,hasMore:!!y.data?.cursor},transactionCount:k.length,transactions:k}}};function gf(n){if(n.value_decimal)return n.value_decimal;let e=parseInt(n.token_decimals??"18",10);if(isNaN(e)||e===0)return n.value;try{let t=BigInt(n.value),r=BigInt(10)**BigInt(e),o=t/r,a=(t%r).toString().padStart(e,"0").replace(/0+$/,"");return a?`${o}.${a}`:`${o}`}catch{return n.value}}var to=class extends A{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 O(e)}async run(e,t){let r=ue(e.address,t),o=Pe(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(E=>typeof E=="string"&&!!E).map(E=>E.trim()):void 0,y,w;if(g){let E=await this.resolveContractAddressBySymbol(g,r,o);E&&(b=[E.address],y=E.symbol,w=E.name)}let k=await this.service.getWalletTokenTransfers({address:r,chain:o,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=r.toLowerCase(),S=(k.data?.result||[]).map(E=>{let ke=E.from_address.toLowerCase()===v,V=ke?"send":"receive",z=ke?E.to_address:E.from_address,fe=ke?E.to_address_label??void 0:E.from_address_label??void 0,Ne=ke?E.to_address_entity??void 0:E.from_address_entity??void 0;return{...E,direction:V,amount_formatted:gf(E),counterparty:z,counterparty_label:fe,counterparty_entity:Ne}}),x=h==="all"?S:S.filter(E=>E.direction===h);if(g&&!b){let E=g.toLowerCase();x=x.filter(ke=>(ke.token_symbol??"").toLowerCase()===E)}let L=this.buildCounterparties(x);return{walletAddress:r,chain:o||"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:x.length,transfers:x,counterparties:L}}async resolveContractAddressBySymbol(e,t,r){let o=e.toLowerCase(),s=await this.service.getWalletTokenBalances({address:t,chain:r});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:r});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,r=new Map;for(let s of e){let a=s.direction==="send"?t:r,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(r)}}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 no=class extends A{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 O(e)}async run(e,t){let r=ue(e.address,t),o=Pe(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(x=>typeof x=="string"&&!!x).map(x=>x.trim()):void 0,y=await this.service.getWalletNftTransfers({address:r,chain:o,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=r.toLowerCase(),v=(y.data?.result||[]).map(x=>{let L=x.from_address.toLowerCase()===w,E=L?"send":"receive",ke=L?x.to_address:x.from_address,V=L?x.to_address_label??void 0:x.from_address_label??void 0,z=L?x.to_address_entity??void 0:x.from_address_entity??void 0;return{...x,direction:E,counterparty:ke,counterparty_label:V,counterparty_entity:z}}),P=g==="all"?v:v.filter(x=>x.direction===g),S=this.buildCounterparties(P);return{walletAddress:r,chain:o||"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:P.length,transfers:P,counterparties:S}}buildCounterparties(e){let t=new Map,r=new Map;for(let s of e){let a=s.direction==="send"?t:r,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(r)}}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 yf=["all","7","30","60","90"],ro=class extends A{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 O(e)}async run(e,t){let r=ue(e.address,t),o=K(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=yf.includes(s)?s:void 0;if(o){let h=await this.service.getWalletPnlSummary({address:r,chain:o,days:a});return h.success?{walletAddress:r,chain:o,days:a??"all",summary:this.mapSummary(h.data)}:{error:h.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all($e().map(async h=>{let g=await this.service.getWalletPnlSummary({address:r,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:r,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 bf=["all","7","30","60","90"],oi=25,oo=class extends A{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 ${oi}. 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 ${oi}.`,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 ${oi}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=ue(e.address,t),o=K(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=bf.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(o){let u=await this.fetchChainPnl(r,o,a,i,l);return u.ok?{walletAddress:r,chain:o,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($e().map(async u=>({chain:u,res:await this.fetchChainPnl(r,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:r,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,r,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=wf([...a.map(u=>u.address),...s]).slice(0,oi),c=l.length>0?l:void 0,d=await this.service.getWalletPnl({address:e,chain:t,days:r,tokenAddresses:c});return{ok:d.success,error:d.error,tokens:d.data?.result??[],tokenAddresses:c,resolvedFromSymbols:a,unresolvedSymbols:i}}async resolveContractAddress(e,t,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,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 wf(n){let e=new Set,t=[];for(let r of n){let o=r.toLowerCase();e.has(o)||(e.add(o),t.push(r))}return t}var kf=BigInt(2)**BigInt(255),so=class extends A{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 O(e)}async run(e,t){let r=ue(e.address,t),o=Pe(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:r,chain:o,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=>vf(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:r,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:u.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:f.length},approvals:u,riskyApprovals:f}}};function vf(n){let e=Tf(n.value);return{blockNumber:n.block_number,blockTimestamp:n.block_timestamp??null,transactionHash:n.transaction_hash??null,value:n.value,valueFormatted:n.value_formatted??null,isUnlimited:e,token:{address:n.token.address,addressLabel:n.token.address_label??null,name:n.token.name??null,symbol:n.token.symbol??null,logo:n.token.logo??null,possibleSpam:!!n.token.possible_spam,verifiedContract:n.token.verified_contract??null,currentBalance:n.token.current_balance??null,currentBalanceFormatted:n.token.current_balance_formatted??null,usdPrice:n.token.usd_price??null,usdAtRisk:n.token.usd_at_risk??null},spender:{address:n.spender.address,label:n.spender.address_label??null,entity:n.spender.entity??null,entityLogo:n.spender.entity_logo??null}}}function Tf(n){if(!n)return!1;try{return BigInt(n)>=kf}catch{return!1}}var sd=.01,ao=class extends A{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 O(e)}async run(e,t){let r=ue(e.address,t),o=K(e.chain,t);if(o){let i=await this.service.getWalletDefiPositions({address:r,chain:o});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=(i.data||[]).filter(ad);return{walletAddress:r,chain:o,positionCount:l.length,positions:l.map(id)}}let a=(await Promise.all($e().map(async i=>{let l=await this.service.getWalletDefiPositions({address:r,chain:i});return{chain:i,rows:l.success?(l.data||[]).filter(ad):[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:T(i.chain),positionCount:i.rows.length,positions:i.rows.map(id)}));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:r,chain:"all",positionCount:a.reduce((i,l)=>i+l.positionCount,0),chains:a}}};function ad(n){let e=n.position?.balance_usd,t=n.position?.total_unclaimed_usd_value;return typeof e!="number"||!Number.isFinite(e)||Math.abs(e)>=sd?!0:typeof t=="number"&&t>=sd}function id(n){return{protocolName:n.protocol_name,protocolId:n.protocol_id,protocolUrl:n.protocol_url,protocolLogo:n.protocol_logo,accountHealthFactor:n.account_data?.health_factor??null,position:Af(n.position)}}function Af(n){return{label:n.label,address:n.address,balanceUsd:n.balance_usd,totalUnclaimedUsdValue:n.total_unclaimed_usd_value,tokens:(n.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:n.position_details??null}}var io=class extends A{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 O(e)}async run(e,t){let r=e.protocol?.trim();if(!r)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let o=ue(e.address,t),s=K(e.chain,t);if(s){let l=await this.service.getWalletDefiProtocolPositions({address:o,protocol:r,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($e().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:r,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 ${r} 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:r,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(Pf)}}};function Pf(n){return{label:n.label,address:n.address,balanceUsd:n.balance_usd,totalUnclaimedUsdValue:n.total_unclaimed_usd_value,tokens:(n.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:n.position_details??null}}function Sf(n){try{return(Number(BigInt(n))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return n}}var lo=class extends A{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 O(e)}async run(e,t){let r=e.transactionHash;if(!r)return{error:"Transaction hash is required."};let o=Pe(e.chain,t),s=await this.service.getTransactionByHash({transactionHash:r,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:Sf(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 ld=new Map;function xf(n){let e=ld.get(n);if(e)return e;let t=rn({rpcUrl:n});return ld.set(n,t),t}async function cd(n,e,t=[]){let r=await xf(n).rpc(e,t);if(r===void 0)throw new Error(`RPC ${e}: empty result`);return r}function ud(n,e,t){return cd(n,"eth_call",[{to:e,data:t},"latest"])}async function Cf(n,e,t){let r=Dn(n);if(!r)return null;try{return await ud(r,e,t)}catch{return null}}function N(n,e){globalThis.__LENDING_DEBUG__!==!1&&(e===void 0?console.log(`[LEND] ${n}`):console.log(`[LEND] ${n}`,JSON.stringify(e,Rf)))}function Rf(n,e){return typeof e=="bigint"?`${e}n`:e}var Ef=6e4,oc=new Map;async function Ws(n,e){let t=Ft(e),r=t?parseInt(t,16):NaN;if(!t||!Number.isFinite(r))return[];let o=`${n}|${t}`,s=oc.get(o);if(s&&Date.now()-s.at<Ef)return s.markets;let a=_f(n,t,r),i=a.then(l=>l.markets);return oc.set(o,{at:Date.now(),markets:i}),a.then(l=>{l.answered||oc.delete(o)}),i}async function si(n,e){return(await Ws(n,e)).length>0}async function _f(n,e,t){try{let r=`${n}/supply/v2?chainId=${t}&limit=100&page=1`;N("catalog: GET",r);let o=await C.get(r);if(!o.ok){let a=o.status>=400&&o.status<500;return N(a?"catalog: chain not served":"catalog: FAILED",{chain:e,status:o.status,message:_(o)}),{markets:[],answered:a}}let s=(o.data?.data?.items||[]).flatMap(a=>{let i=Nf(a,e);return i?[i]:[]});return N("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(r){return N("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:e,message:r?.message}),{markets:[],answered:!1}}}function dd(n,e){let t=e.trim().toLowerCase();if(!t)return[];if(R(t))return n.filter(o=>o.contract===t||o.token===t);let r=n.filter(o=>o.name.trim().toLowerCase()===t);return r.length>0?r:n.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 Nf(n,e){if(n?.isDeleted===!0)return null;let t=typeof n?.contract=="string"?n.contract.toLowerCase():"";if(!R(t))return null;let r=typeof n?.token=="string"&&R(n.token)?n.token.toLowerCase():t,o=Number(n?.rating?.balanceScore),s=n?.type?.trim()||"unknown";return{chain:e,name:n?.name?.trim()||"USDC lending market",protocol:n?.protocolId?.name?.trim()||"Unknown",protocolLabel:ze(s),protocolUrl:n?.protocolId?.domain?.trim()||null,type:s,contract:t,token:r,platformScore:Number.isFinite(o)?o:null}}function sc(){return $e()}async function ai(n){let e=sc(),t=await Promise.all(e.map(r=>si(n,r)));return e.filter((r,o)=>t[o])}async function ii(n,e){let t=D(e);return t?si(n,t):!1}async function pd(n,e){let t=e.map(s=>D(s)).filter(s=>!!s),r=[...new Set(t)],o=await Promise.all(r.map(s=>si(n,s)));return r.filter((s,a)=>o[a])}function Yn(n){return Fs(n)}var md=6;async function hd(n,e,t){let r=e.map(w=>R(w)?w.toLowerCase():null);if(r.every(w=>w===null))return N("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let o=ti(n),s;try{N("discovery: probing 5 accessors per token",{chain:n,tokens:r,psm:o}),s=await Ae(n,[...r.flatMap(w=>w?Lf(w):[]),...o?Ju(o):[]])}catch(w){return N("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:n,message:w?.message}),e.map(()=>null)}let a=o?s.slice(s.length-Zu):[],i=B(a[0])?.toLowerCase()??null,l=B(a[1]),c=B(a[2]),d=i&&l&&c?{susds:i,usds:l,oracle:c}:null;o&&N("discovery: PSM3 lookup",{psm:o,susds:i,usds:l,oracle:c});let u=0,p=r.map(w=>{if(!w)return null;let k=s.slice(u,u+md);return u+=md,N("discovery: probe answers",{token:w,"POOL()":B(k[0]),"UNDERLYING_ASSET_ADDRESS()":B(k[1]),"baseToken()":B(k[2]),"asset()":B(k[3]),"vsr()":ee(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 f=await If(n,[...m]);m.size>0&&N("discovery: Aave pool authentication",{claimed:[...m],genuine:[...f]});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 g=await Uf(n,h);h.size>0&&N("discovery: Maple manager authentication",{claimed:[...h.keys()],genuine:[...g]});let b=p.flatMap(w=>w?B(w.slice[0])&&B(w.slice[1])||B(w.slice[2])?[]:g.has(w.token)?[]:B(w.slice[3])?[w.token]:[]:[]),y=await Df(n,[...new Set(b)],t);return b.length>0&&N("discovery: Morpho vault lookup",{asked:[...new Set(b)],recognised:[...y.keys()]}),p.map(w=>{if(!w)return null;let{token:k,slice:v}=w,P={chain:n,protocolUrl:null,token:k,platformScore:null};if(d&&k===d.susds)return N("discovery: classified",{token:k,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:d.oracle}),{...P,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:ze("spark-l2-susds"),protocolUrl:Yn("spark-l2-susds"),type:"spark-l2-susds",contract:d.oracle,assetAddress:d.usds};let S=B(v[0]);if(S&&B(v[1])){let x=f.has(S.toLowerCase());return N("discovery: classified",{token:k,as:x?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:S}),x?{...P,name:"Aave v3",protocol:"AAVE",protocolLabel:ze("aave-v3"),protocolUrl:Yn("aave-v3"),type:"aave-v3",contract:S}:null}if(B(v[2]))return N("discovery: classified",{token:k,as:"compound-v3"}),{...P,name:"Compound v3",protocol:"COMPOUND",protocolLabel:ze("compound-v3"),protocolUrl:Yn("compound-v3"),type:"compound-v3",contract:k};if(B(v[3])){if(g.has(k))return N("discovery: classified",{token:k,as:"maple (manager round trip verified)"}),{...P,name:"Maple",protocol:"MAPLE",protocolLabel:ze("maple"),protocolUrl:Yn("maple"),type:"maple",contract:k};if(y.has(k)){N("discovery: classified",{token:k,as:"morpho-v2"});let E=y.get(k)||"Morpho V2";return{...P,name:E,protocol:"MORPHO",protocolLabel:ze("morpho-v2"),protocolUrl:Yn("morpho-v2"),type:"morpho-v2",contract:k}}let L=ee(v[4])!==null;return N("discovery: classified",{token:k,as:L?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),L?{...P,name:"Spark",protocol:"SPARK",protocolLabel:ze("spark-ethereum"),protocolUrl:Yn("spark-ethereum"),type:"spark-ethereum",contract:k}:{...P,name:"Spark",protocol:"SPARK",protocolLabel:ze("spark"),protocolUrl:Yn("spark"),type:"spark",contract:k}}return N("discovery: classified",{token:k,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function Lf(n){return[{target:n,callData:M({abi:$r,functionName:"POOL"})},{target:n,callData:M({abi:$r,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:n,callData:M({abi:Mt,functionName:"baseToken"})},{target:n,callData:M({abi:wt,functionName:"asset"})},{target:n,callData:M({abi:Hr,functionName:"vsr"})},{target:n,callData:M({abi:Jl,functionName:"manager"})}]}async function If(n,e){if(e.length===0)return new Set;try{let t=await Ae(n,e.map(r=>({target:r,callData:M({abi:zl,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((r,o)=>B(t[o])!==null))}catch{return new Set}}async function Uf(n,e){if(e.size===0)return new Set;let t=[...e.entries()];try{let r=await Ae(n,t.map(([,o])=>({target:o,callData:M({abi:Zl,functionName:"pool"})})));return new Set(t.filter(([o],s)=>B(r[s])?.toLowerCase()===o.toLowerCase()).map(([o])=>o))}catch{return new Set}}async function Df(n,e,t){let r=parseInt(n,16);if(e.length===0||!Number.isFinite(r))return new Map;let o=await Promise.all(e.map(async s=>{try{let a=await C.post(t,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:s,c:r}}),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 Of=.01;function Mf(n){return n.reduce((e,t)=>t.conditions===null?e+t.apyPercent:e,0)}function Ff(n,e){if(typeof e!="string"||!e.trim())return;let t=e.trim(),r=Ps();r[n]!==t&&In({...r,[n]:t})}var co=class{constructor(e,t,r){this.coinPoolBaseUrl=e;this.endpoints=t;this.describer=r}coinPoolBaseUrl;endpoints;describer;async describeReceiptTokens(e,t,r){let o=Date.now();N("describeReceiptTokens: START",{chain:e,tokens:t,hasRpcUrl:!!r});let s=Ft(e);s&&Ff(s,r);let a=s?Bs(s):null,i=[...new Set(t.filter(R).map(p=>p.toLowerCase()))];if(N("describeReceiptTokens: chain resolved",{hex:s,hasChainInfo:!!a,wanted:i}),!s||!a||i.length===0)return N("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:s,hasChainInfo:!!a,wantedCount:i.length}),new Map;N("describeReceiptTokens: on-chain discovery for",i);let l=await hd(s,i,this.endpoints.morphoApiUrl),d=[...new Map(i.flatMap((p,m)=>{let f=l[m];return N("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 N("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-o}),new Map;N("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 N("describeReceiptTokens: DONE",{ms:Date.now()-o,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,r){if(N("findMarketByReceiptToken: called",{chain:e,receiptToken:t,hasRpcUrl:!!r}),!R(t))return N("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:t}),null;let s=(await this.describeReceiptTokens(e,[t],r)).get(t.toLowerCase())??null;return N("findMarketByReceiptToken: returning",{found:!!s}),s}async getSupplyPositions(e){if(!R(e.address))return[];let t=await pd(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 r=Ft(e),o=r?Bs(r):null;return r&&o?this.describer.describe(r,o,t):[]}async positionsForChain(e,t){let r=Bs(e),o=await Ws(this.coinPoolBaseUrl,e);if(!r||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,r,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<Of?[]:[{...l,suppliedUsdc:d,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:d*(l.avgApyPercent+Mf(l.rewards))/100}]})}};var ac=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var uo=class{constructor(e){this.coinPoolBaseUrl=e}coinPoolBaseUrl;async listChains(){return ai(this.coinPoolBaseUrl)}async isSupported(e){return ii(this.coinPoolBaseUrl,e)}async getMarkets(e){let t=D(e);return t?Ws(this.coinPoolBaseUrl,t):[]}async findMarket(e,t){let r=await this.getMarkets(e);return dd(r,t)}canSupply(e){return ac.includes(e.type)}async readReceiptToken(e,t){let r=dn(t).balanceIsUnderlying;try{let o=await Ae(e,[{target:t.token,callData:M({abi:q,functionName:"symbol"})},{target:t.token,callData:M({abi:q,functionName:"decimals"})}]);return{symbol:dr(o[0]),decimals:pr(o[1]),isUnderlying:r}}catch{return{symbol:null,decimals:null,isUnderlying:r}}}};var gd=6e5,li=new Map;async function fd(n){let e=li.get(n);if(e&&Date.now()-e.at<gd)return e.chains;let t=Vf(n);return li.set(n,{at:Date.now(),chains:t}),t.then(r=>{r===null&&li.delete(n)}),t}async function Bf(n){try{let e=n==="morpho"?await qf():await $f();return!e||e.size===0?(N(`protocolChains: ${n} returned no chains`),null):(N(`protocolChains: ${n} live on`,[...e].sort((t,r)=>t-r)),e)}catch(e){return N(`protocolChains: ${n} FAILED`,e instanceof Error?e.message:e),null}}async function qf(){let n=await C.post("https://api.morpho.org/graphql",{query:"{ chains { id network } }"});if(!n.ok)return null;let e=n.data?.data?.chains;if(!Array.isArray(e))return null;let t=new Set;for(let r of e)typeof r?.id=="number"&&Number.isInteger(r.id)&&r.id>0&&(t.add(r.id),typeof r.network=="string"&&r.network.trim()&&yd.set(r.id,r.network.trim()));return t}async function $f(){let n=await C.get("https://v3-api.compound.finance/market/all-networks/all-contracts/summary");if(!n.ok||!Array.isArray(n.data))return null;let e=new Set;for(let t of n.data)typeof t?.chain_id=="number"&&Number.isInteger(t.chain_id)&&t.chain_id>0&&e.add(t.chain_id);return e}var yd=new Map;function bd(n){return yd.get(n)??null}var Hf=1500;async function wd(){let n=Promise.all([fd("morpho").catch(()=>null),fd("compound").catch(()=>null)]),e,t=new Promise(r=>{e=setTimeout(r,Hf),e?.unref?.()});try{await Promise.race([n,t])}finally{e&&clearTimeout(e)}}function ic(n){let e=li.get(n);return!e||Date.now()-e.at>=gd?null:kd.get(e.chains)??null}var kd=new WeakMap;function Vf(n){let e=Bf(n);return e.then(t=>{t&&kd.set(e,t)}),e}var Wf={1:"ethereum",10:"opmainnet",130:"unichain",137:"polygon",143:"monad",480:"world-chain",988:"stable",999:"hyperevm",4217:"tempo",4663:"robinhood-chain",5042:"arc",8453:"base",42161:"arbitrum",747474:"katana"},Yf={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",100:"proto_gnosis_v3",137:"proto_polygon_v3",143:"proto_monad_v3",146:"proto_sonic_v3",196:"proto_xlayer_v3",324:"proto_zksync_v3",1088:"proto_metis_v3",1868:"proto_soneium_v3",4326:"proto_megaeth_v3",5e3:"proto_mantle_v3",8453:"proto_base_v3",9745:"proto_plasma_v3",42161:"proto_arbitrum_v3",42220:"proto_celo_v3",43114:"proto_avalanche_v3",57073:"proto_ink_v3",59144:"proto_linea_v3",534352:"proto_scroll_v3"},Gf={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},Kf={1:"mainnet",10:"op",130:"unichain",137:"polygon",2020:"ronin",5e3:"mantle",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function ci(n){let e=sg(n.chain);return(e===null?null:jf(n,e))??Fs(n.type)??og(n,e)}function jf(n,e){switch(n.type){case"morpho-v2":{let t=Wf[e]??Qf(e);if(!t||!n.contract)return null;let r=`https://app.morpho.org/${t}/vault/${lc(n.contract)}`,o=Jf(n.name);return o?`${r}/${o}`:r}case"aave-v3":{let t=Yf[e],r=zf(n);return!t||!r?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${lc(r)}&marketName=${t}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let t=Gf[e],r=ng(n);return!t||!r?null:`https://app.spark.finance/savings/${t}/${r}`}case"compound-v3":{if(Zf(e))return null;let t=Kf[e],r=eg(n);return!t||!r?null:`https://app.compound.finance/?market=${r}-${t}`}default:return null}}function zf(n){let e=n.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var Xf=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Qf(n){if(!ic("morpho")?.has(n))return null;let t=bd(n);return t&&t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Jf(n){let e=n?.trim().toLowerCase()||"";return!e||Xf.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Zf(n){let e=ic("compound");return e!==null&&!e.has(n)}function eg(n){let e=n.asset?.address?.trim().toLowerCase()||"",t=tg[e];if(t)return t;let r=n.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(r)&&r.length<=12?r:null}var tg={"0x2791bca1f2de4661ed88a30c99a7a9449aa84174":"usdc.e","0xff970a61a04b1ca14834a43f5de4533ebddb5cc8":"usdc.e"};function ng(n){let e=n.shareSymbol?.trim().toLowerCase()||"";if(/^[a-z0-9]{2,12}$/.test(e))return e;let t=`${n.name||""} ${n.token||""}`.toLowerCase();for(let o of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(t.includes(o))return o;if(n.type==="spark-ethereum")return rg[n.contract?.trim().toLowerCase()||""]??null;let r=n.asset?.symbol?.trim().toLowerCase()||"";return!/^[a-z0-9]{2,11}$/.test(r)||r.startsWith("s")?null:`s${r}`}var rg={"0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f":"speth","0x80128dbb9f07b93dde62a6daeadb69ed14a7d354":"sppyusd","0xe2e7a17dff93280dec073c995595155283e3c372":"spusdt","0x28b3a8fb53b741a8fd78c0fb9a6b2393d896a43d":"spusdc","0x45d91340b3b7b96985a72b5c678f7d9e8d664b62":"spusdt","0xc358c90d32375721cb3924320fdc2f8b694347ca":"spusdt","0xde770c84fe66e063336b31737cfe9790f18c4087":"spusdg"};function og(n,e){let t=n.protocolUrl?.trim();if(!t)return null;let r=/^https?:\/\//i.test(t)?t:`https://${t.replace(/^\/+/,"")}`;try{let o=new URL(r);return e!==null&&o.searchParams.set("chainId",String(e)),n.contract&&o.searchParams.set("contract",lc(n.contract)),o.toString()}catch{return r}}function lc(n){let e=n.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function sg(n){let e=n?.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 ag=new Set(["spark","spark-ethereum"]),ig=8;function lg(n,e,t){if(n.market.type!=="spark-l2-susds")return ee(e);let r=ee(e);return r===null||n.tokenDecimals===null?null:Vn(n.rawBalance,r,n.tokenDecimals,t)}var ui=class{constructor(e){this.endpoints=e}endpoints;apyLimiter=new cc(ig);pantograph=new ye;async describe(e,t,r){if(r.length===0)return[];N("describe: START",{chain:e,count:r.length,types:r.map(l=>l.type)});let{assets:o,shareSymbols:s}=await this.resolveAssets(e,r);N("describe: assets resolved",o);let[a,i]=await Promise.all([this.readMarketState(e,r,o),Promise.all(r.map((l,c)=>this.apyLimiter.run(()=>this.fetchApy(l,t,o[c])))),wd()]);return N("describe: on-chain state",a),N("describe: APY fetched",i.map((l,c)=>({type:r[c].type,rawSamples:l.samples.length,sourceCurrent:l.current}))),r.map((l,c)=>{let{totalSuppliedUsdc:d,liveApyFraction:u}=a[c],p=i[c].sizeOverride??d,m=ug(i[c].samples,u??i[c].current,i[c].rewards,i[c].avgOverride??null);return N("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:o[c]?.symbol}),{...l,protocolUrl:ci({...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,r){let o=M({abi:q,functionName:"balanceOf",args:[t]}),s=M({abi:q,functionName:"decimals"}),a=r.flatMap(l=>[{target:l.token,callData:o},{target:l.token,callData:s}]),i=await Ae(e,a);return r.flatMap((l,c)=>{let d=ee(i[c*2]);return d===null||d<=0n?[]:[{market:l,rawBalance:d,tokenDecimals:pr(i[c*2+1])}]})}async convertToUnderlying(e,t,r){let o=[],s=t.map(i=>{let l=dn(i.market).convertToAssetsCall(i.market,i.rawBalance);return l?(o.push(l),o.length-1):-1}),a=await Ae(e,o);return t.map((i,l)=>{let c=r[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(s[l]<0)return nt(i.rawBalance,c);let d=lg(i,a[s[l]],c);return d===null?nt(i.rawBalance,i.tokenDecimals??c):nt(d,c)})}async resolveAssets(e,t){let r={address:Wn,decimals:NaN,symbol:null,logo:null},o=[],s=t.map(p=>{let m=dn(p).underlyingCall(p);return m?(o.push(m),o.length-1):-1}),a;try{let p=o.length>0?await Ae(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,d]=await Promise.all([this.readAssetMetadata(e,i),this.fetchAssetLogos(e,i),this.readShareSymbols(e,t)]);return{assets:a.map(p=>{if(!p)return r;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 r=M({abi:q,functionName:"symbol"}),o=[],s=t.map(a=>!ag.has(a.type)||!a.contract?-1:(o.push({target:a.contract,callData:r}),o.length-1));if(o.length===0)return t.map(()=>null);try{let a=await Ae(e,o);return s.map(i=>i<0?null:dr(a[i]))}catch{return t.map(()=>null)}}async readAssetMetadata(e,t){let r=new Map;if(t.length===0)return r;let o=M({abi:q,functionName:"decimals"}),s=M({abi:q,functionName:"symbol"});try{let a=await Ae(e,t.flatMap(i=>[{target:i,callData:o},{target:i,callData:s}]));t.forEach((i,l)=>{r.set(i,{decimals:pr(a[l*2]),symbol:dr(a[l*2+1])})})}catch{}return r}async fetchAssetLogos(e,t){let r=new Map;if(t.length===0)return r;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&&r.set(s.toLowerCase(),i)}}catch{}return N("resolveAssets: logos",{chain:e,requested:t.length,found:r.size}),r}async readMarketState(e,t,r){let o=[],s=t.map((d,u)=>{let p=dn(d),m=r[u],f={market:d,protocol:p,asset:m,size:o.length,rate:-1};o.push(p.sizeCall(d,m));let h=p.liveRateCall(d,m);return h&&(f.rate=o.length,o.push(h)),f}),a=await Ae(e,o),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 Ae(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,r){try{N("fetchApy: requesting",{market:e.name,type:e.type,asset:r?.symbol});let o=await dn(e).fetchApy(e,t,this.endpoints,r);return N("fetchApy: got",{market:e.name,samples:o.samples.length,current:o.current,avgOverride:o.avgOverride??null}),o}catch(o){return N("fetchApy: FAILED \u2014 market listed without APY",{market:e.name,type:e.type,message:o?.message}),{samples:[],current:null,rewards:[]}}}},cc=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 cg(n,e){let t=_s(Date.now()),r=new Map,o=null;for(let i of n)!Number.isFinite(i.timeMs)||!Number.isFinite(i.fraction)||i.fraction<0||_s(i.timeMs)>t||((!o||i.timeMs>o.timeMs)&&(o=i),r.set(i.timeMs,i.fraction));let s=[...r.entries()].sort((i,l)=>i[0]-l[0]).map(([i,l])=>({date:new Date(i).toISOString(),apyPercent:l*100})),a=e??(o&&_s(o.timeMs)===t?o.fraction:null);return{history:s,live:a}}function ug(n,e,t=[],r=null){let{history:o,live:s}=cg(n,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=r!==null&&Number.isFinite(r)?r*100:null;if(o.length===0)return{history:o,avgApyPercent:u,currentApyPercent:c,apyChangePercent:null,...d};let p=o.reduce((m,f)=>m+f.apyPercent,0);return{history:o,avgApyPercent:u??p/o.length,currentApyPercent:c,apyChangePercent:pg(o,a),...d}}var vd=3600*1e3,dg=vd/2;function pg(n,e){if(e===null)return null;let t=Date.now()-vd,r=null,o=Number.POSITIVE_INFINITY;for(let s=n.length-1;s>=0;s--){let a=Math.abs(Date.parse(n[s].date)-t);if(a>o)break;o=a,r=n[s]}return!r||o>dg?null:e-r.apyPercent}function Td(n,e){if(!Number.isFinite(n))return n;let t=10**e,r=Number((n*t).toPrecision(15));return(n<0?-Math.floor(-r):Math.floor(r))/t+0}var dt=class{read;supply;constructor(e={}){let t=e.coinPoolBaseUrl||"https://api.coinpool.app",r={lendingRatesBaseUrl:e.lendingRatesBaseUrl||"https://wallet-api.pantograph.app",aaveApiUrl:e.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:e.morphoApiUrl||"https://api.morpho.org/graphql"},o=new ui(r);this.read=new co(t,r,o),this.supply=new uo(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,r){return this.read.describeReceiptTokens(e,t,r)}async findMarketByReceiptToken(e,t,r){return this.read.findMarketByReceiptToken(e,t,r)}async describeResolvedMarkets(e,t){return this.read.describeResolvedMarkets(e,t)}async getMarketOverviews(e){return(await Promise.all(e.chains.map(async r=>this.read.describeResolvedMarkets(r,await this.getMarkets(r))))).flat().sort((r,o)=>(o.avgApyPercent??-1)-(r.avgApyPercent??-1))}async getSupplyPositions(e){return this.read.getSupplyPositions(e)}};var Ys="{market}",Sd=[{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}],pi=[{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}],xd="[[LIST]]",Cd=' 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.',Rd=' 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 Ed(n,e,t){let[r]=mg([n],e,t),[o]=n.canSupply?uc(n,e,t):[];return{name:n.name?.trim()||n.protocol,protocol:n.protocol,protocolUrl:n.protocolUrl,chain:t,apyPercent:n.apyPercent,detailPrompt:r?.prompt??"",detailLabel:r?.label??"",supplyPrompt:o?.prompt??"",supplyLabel:o?.label??""}}function mg(n,e,t){return _d(n,{labelTemplate:di(e.detail_button_label),promptTemplate:di(e.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${Ys}`,...t===void 0?{}:{chainName:t}})}function uc(n,e,t){return _d([n],{labelTemplate:di(e.supply_button_label),promptTemplate:di(e.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${Ys}`,promptFallback:`supply to ${Ys}`,...t===void 0?{}:{chainName:t},max:1})}function _d(n,e){let t=typeof e.chainName=="string"?e.chainName.trim():"",r=[],o=new Set;for(let s of n){if(e.max!==void 0&&r.length>=e.max)break;let a=s.name?.trim();!a||o.has(a.toLowerCase())||(o.add(a.toLowerCase()),r.push({label:Ad(e.labelTemplate,a,e.labelFallback,e.labelNamesMarket===!0),prompt:Ad(hg(e.promptTemplate),a,e.promptFallback)+fg(s.contract,t)}))}return r}function hg(n){let[e,t]=[n[0],n[1]];return e===void 0||e===e.toLowerCase()||t!==void 0&&t!==t.toLowerCase()?n:e.toLowerCase()+n.slice(1)}function di(n){return typeof n=="string"?n:""}function fg(n,e){let t=n?.trim();if(!t||!/^0x[a-fA-F0-9]{40}$/.test(t))return"";let r=e?.trim();return r?` (market: ${t} - ${r})`:` (market: ${t})`}function Ad(n,e,t,r=!0){let s=n&&(!r||n.includes(Ys))?n:t;return gg(s).split(Ys).join(e).replace(/\s+/g," ").trim()}var Pd="{chain}";function gg(n){if(!n.includes(Pd))return n;let e=Pd.replace(/[{}]/g,"\\$&");return n.replace(new RegExp(`\\s*\\S+\\s*${e}`,"g"),"").replace(new RegExp(`${e}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(e,"g"),"")}var mi=[{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"]}],pc=mi.map(n=>n.label),dc={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 Nd(n){let e=typeof n=="string"?n.trim():"";if(!e)return{kind:"none"};let t=kg(e);if(!t)return{kind:"none"};let r=yg(t);if(r){let s=new Set(r.types);return{kind:"supported",label:r.label,matches:a=>s.has(a.type)}}let o=wg(t);return o?{kind:"unsupported",label:o,requested:e}:{kind:"unknown",requested:e}}function yg(n){let e=mi.filter(t=>t.aliases.includes(n));if(e.length===1)return e[0];if(e.length>1)return null;if(n.length>=3){let t=mi.filter(r=>r.aliases.some(o=>o.includes(n)||n.includes(o)));if(t.length===1)return t[0];if(t.length>1)return null}return bg(n)}function bg(n){let e=null,t=!1;for(let r of mi)for(let o of r.aliases){let s=Ld(o);if(s===0||Math.abs(o.length-n.length)>s)continue;let a=Id(n,o,s);a>s||(!e||a<e.distance?(e={spec:r,distance:a},t=!1):a===e.distance&&r!==e.spec&&(t=!0))}return e&&!t?e.spec:null}function Ld(n){return n.length<=4?0:n.length<=9?2:3}function wg(n){let e=dc[n];if(e)return e;if(n.length>=4){let o=new Set(Object.entries(dc).filter(([s])=>s.length>=4&&(s.includes(n)||n.includes(s))).map(([,s])=>s));if(o.size===1)return[...o][0];if(o.size>1)return null}let t=null,r=!1;for(let[o,s]of Object.entries(dc)){let a=Ld(o);if(a===0||Math.abs(o.length-n.length)>a)continue;let i=Id(n,o,a);i>a||(!t||i<t.distance?(t={label:s,distance:i},r=!1):i===t.distance&&s!==t.label&&(r=!0))}return t&&!r?t.label:null}function kg(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function Id(n,e,t){if(n===e)return 0;if(!n.length)return e.length;if(!e.length)return n.length;let r=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<=n.length;a++){s[0]=a;let i=s[0];for(let c=1;c<=e.length;c++){let d=o[c-1]+(n[a-1]===e[c-1]?0:1),u=Math.min(s[c-1]+1,o[c]+1,d);a>1&&c>1&&n[a-1]===e[c-2]&&n[a-2]===e[c-1]&&(u=Math.min(u,r[c-2]+1)),s[c]=u,u<i&&(i=u)}if(i>t)return t+1;let l=r;r=o,o=s,s=l}return o[e.length]}function be(n,e){return n==null?null:Td(n,e)}var De=2,pn=2;function hi(n){let e=be(n.currentApyPercent,De),t=n.rewards.map(s=>({apyPercent:be(s.apyPercent,De)??0,tokenSymbol:s.tokenSymbol,conditions:s.conditions})),r=n.rewardApyPercent===null?null:t.reduce((s,a)=>s+Math.round(a.apyPercent*100),0)/100;if(r===null||e===null)return{currentApyPercent:e,rewardApyPercent:r,rewards:t,baseApyPercent:be(n.baseApyPercent,De)};let o=Math.round(e*100)-Math.round(r*100);return{currentApyPercent:e,rewardApyPercent:r,rewards:t,baseApyPercent:o/100}}var vg=["apy","score","size"],Ud=3,Dd=40,po=class extends A{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: ${pc.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-${Dd}. Default ${Ud} \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},...Sd,...pi];service;constructor(e){super(),this.service=new dt(e)}async run(e,t){let r=K(e.chain,void 0),o=r?null:D(t?.chain),s=r??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=Nd(e.protocol);if(l.kind==="unsupported"||l.kind==="unknown")return this.unsupportedProtocol(l);let c=s?[s]:i,d=Ag(e.sort),u=Pg(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(Tg[d]).slice(0,u),h=f.map(y=>Ed({name:y.name,contract:y.contract,protocol:y.protocol,protocolUrl:y.protocolUrl,apyPercent:be(y.currentApyPercent,De),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",r=t?e.label:`"${e.requested}"`;return{_instructions:`The user asked about ${r}, which has no lending markets here. In their language: tell them plainly that ${r} 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 ${r} 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:[...pc],marketCount:0,marketNames:[]}}instructions(e,t,r=!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 ${xd} 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.",r?Cd:""].filter(Boolean).join(" ")}},Tg={apy:(n,e)=>(e.currentApyPercent??-1)-(n.currentApyPercent??-1),score:(n,e)=>(e.platformScore??-1)-(n.platformScore??-1),size:(n,e)=>(e.totalSuppliedUsdc??-1)-(n.totalSuppliedUsdc??-1)};function Ag(n){let e=typeof n=="string"?n.trim().toLowerCase():"";return vg.includes(e)?e:"apy"}function Pg(n){let e=typeof n=="number"?n:Number(n);return!Number.isFinite(e)||e<1?Ud:Math.min(Math.floor(e),Dd)}function Od(n){let{currentApyPercent:e,avgApyPercent:t,totalSuppliedUsdc:r,rewardApyPercent:o,baseApyPercent:s,platformScore:a}=n;return n.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"}:r!==null&&r<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&&r!==null&&r>=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"}:r!==null&&r>=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 fi(n){let e=typeof n=="string"?n.trim():"",t=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/i.exec(e);if(t)return t[1];let r=/0x[a-fA-F0-9]{40}/.exec(e);return r&&r[0]!==e?r[0]:e}var mo=class extends A{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},...pi];service;constructor(e){super(),this.service=new dt(e)}async run(e,t){let o=K(e.chain,void 0)??D(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 u=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:T(o),chainsWithLendingMarkets:u.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=fi(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(u=>({marketName:u.name,protocol:u.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),d=c?uc({name:i.name,contract:i.contract},e,T(o)):[];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:be(l.totalSuppliedUsdc,pn),...hi(l),avgApyPercent:be(l.avgApyPercent,De),apyChangePercent:be(l.apyChangePercent,De),platformScore:l.platformScore,supplySupported:c}}async describeOne(e,t){try{let[r]=await this.service.describeResolvedMarkets(e,[t]);return r??null}catch{return null}}instructions(e,t,r){let o=Od(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."',r?"":"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?Rd:""].filter(Boolean).join(" ")}};var ho=class extends A{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 dt(e)}async run(e,t){let r=ue(e.address,t);if(!R(r))return{error:`"${r}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=K(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:r,chain:T(o),positionCount:0,positions:[],chainsWithLendingMarkets:a.map(c=>T(c))};let i=o?[o]:a,l=await this.service.getSupplyPositions({address:r,chains:i});return{_instructions:this.instructions(l),walletAddress:r,chain:o?T(o):"all",chainsQueried:i.map(c=>T(c)),positionCount:l.length,totals:Sg(l),positions:l.map(c=>({marketName:c.name,protocol:c.protocol,protocolUrl:c.protocolUrl,chain:T(c.chain),suppliedUsdc:be(c.suppliedUsdc,pn),suppliedAssetSymbol:c.asset.symbol,avgApyPercent:be(c.avgApyPercent,De),...hi(c),apyChangePercent:be(c.apyChangePercent,De),estimatedAnnualYieldUsdc:be(c.estimatedAnnualYieldUsdc,pn),marketTotalSuppliedUsdc:be(c.totalSuppliedUsdc,pn),apyHistory:c.apyHistory.map(d=>({...d,apyPercent:be(d.apyPercent,De)})),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(r=>r.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 Sg(n){if(new Set(n.map(a=>a.asset.symbol??a.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let r=n.reduce((a,i)=>a+i.suppliedUsdc,0),o=n.filter(a=>a.avgApyPercent!==null),s=o.reduce((a,i)=>a+i.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:n[0]?.asset.symbol??null,suppliedUsdc:be(r,pn),estimatedAnnualYieldUsdc:be(n.reduce((a,i)=>a+(i.estimatedAnnualYieldUsdc??0),0),pn),weightedAvgApyPercent:be(s>0?o.reduce((a,i)=>a+i.suppliedUsdc*i.avgApyPercent,0)/s:null,De)}}var fo=class extends A{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 dt(e),this.moralis=new O(e?.moralis)}async run(e,t){let r=t?.walletAddress;if(!r)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=K(e.chain,void 0)??D(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=fi(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=xg(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(r,s,d.address),this.service.readReceiptToken(s,l)]);if(u&&on(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=Cg(e.amount),f=m?je(m,d.decimals):null;if(f&&u&&on(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:r,market:{name:l.name,type:l.type,protocol:l.protocol,protocolUrl:c?.protocolUrl??ci(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:be(h.market.apyPercent,De),assetSymbol:d.symbol,assetBalance:u?.amount??null,_instructions:this.instructions(l,d.symbol)}}async describeOne(e,t){try{let[r]=await this.service.describeResolvedMarkets(e,[t]);return r??null}catch{return null}}async assetBalance(e,t,r){try{let o=await this.moralis.getWalletTokenBalances({address:e,chain:t,tokenAddresses:[r]});if(!o.success)return null;let s=(o.data?.result??[]).find(i=>(i.token_address||"").toLowerCase()===r.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 xg(n){let e=n?.asset;return!e?.address||e.address===Wn||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function Cg(n){let e=typeof n=="string"?n.trim():typeof n=="number"?String(n):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}var gi="https://ipfs.pantograph.app/ipfs/",Md=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function Gn(n){let e=n?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${gi}${t[1]}`:Md.test(e)?`${gi}${e}`:null}function Fd(n){let e=n?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${gi}${t[1]}`:Md.test(e)?`${gi}${e}`:null}function Bd(n){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(n)}function mc(n){if(!n||typeof n!="object")return;let e=n,t=e.image??e.image_url??e.imageUrl;return typeof t=="string"&&t.trim()?t.trim():void 0}function Rg(n){if(typeof atob=="function"){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return new TextDecoder().decode(t)}if(typeof Buffer<"u")return Buffer.from(n,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function Eg(n){let e=n.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let t=e[1]??"",r=e[2]??"";try{let o=/;base64/i.test(t)?Rg(r):decodeURIComponent(r);return JSON.parse(o)}catch{try{return JSON.parse(r)}catch{return null}}}function qd(n){let e=n?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=Eg(e);return t?Gn(mc(t)):null}var _g=12,Ng=6e3;async function Lg(n,e,t){let r=new Array(n.length),o=0,s=new Array(Math.max(1,Math.min(e,n.length))).fill(0).map(async()=>{for(;o<n.length;){let a=o++;r[a]=await t(n[a],a)}});return await Promise.all(s),r}async function Ig(n,e){try{let t=await C.get(n,{timeout:e});if(!t.ok)return null;let r=t.data;if(r&&typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{return null}return null}catch{return null}}async function Ug(n,e){let t=n?.trim();if(!t)return null;if(/^data:/i.test(t))return qd(t);let r=Fd(t);if(!r)return null;if(Bd(r))return r;let o=await Ig(r,e);if(o){let s=Gn(mc(o));if(s)return s}return null}async function yi(n,e,t){if(e.length===0)return[];let r=t?.concurrency??_g,o=t?.timeoutMs??Ng,s=await Nu(n,e,t?.rpcUrl);return Lg(s,r,a=>Ug(a,o))}var $d=100,Dg=100,go="{name}",Hd="{chain}",yo=class extends A{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 O(e)}async run(e,t){let r=ue(e.address,t),o=K(e.chain,t),s=o?[o]:$e(),a=$g(e.contract_address),i=Yd(e.collection_name);return a||i?this.listNfts({address:r,chains:s,singleChain:!!o,contract:a,collectionName:i}):this.listCollections({address:r,chains:s,singleChain:!!o,args:e})}async listCollections(e){let{address:t,chains:r,singleChain:o,args:s}=e,a=await Promise.all(r.map(async c=>{let d=await this.service.getWalletNftCollections({address:t,chain:c,limit:$d});return{chain:c,rows:d.success?Vd(d.data?.result??[]):[],ok:d.success}}));if(o&&!a[0].ok)return{error:"Failed to fetch wallet NFT collections"};let i=a.flatMap(c=>c.rows.map(d=>({name:Mg(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"+(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=Bg(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:r,singleChain:o,contract:s,collectionName:a}=e,i=await Promise.all(r.map(async m=>{let f=await this.service.getWalletNFTs({address:t,chain:m,limit:$d,...s?{tokenAddresses:[s]}:{}});return{chain:m,rows:f.success?Vd(f.data?.result??[]):[],ok:f.success}}));if(o&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(m=>m.rows.filter(f=>Og(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??""}"`+(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,d=await this.resolveOnchainImages(l),u=l.map(({chain:m,row:f},h)=>{let g=Fg(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),r=new Map;e.forEach((o,s)=>{let a=r.get(o.chain)??[];a.push(s),r.set(o.chain,a)});try{await Promise.all([...r.entries()].map(async([o,s])=>{let a=s.map(l=>({contract:e[l].row.token_address,tokenId:e[l].row.token_id})),i=await yi(o,a);s.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function Vd(n){return n.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function Og(n,e){if(e.contract)return n.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let t=e.collectionName.toLowerCase();return(n.name??"").toLowerCase().includes(t)}return!1}function Mg(n){let e=n.name?.trim();if(e)return e;let t=n.token_address??"";return t.length>10?`${t.slice(0,6)}\u2026${t.slice(-4)}`:t}function Fg(n){return{name:n.normalized_metadata?.name||n.name||`#${n.token_id}`,tokenId:n.token_id,contractAddress:n.token_address,image:Gn(n.normalized_metadata?.image||n.media?.original_media_url)}}function Bg(n,e){let t=typeof e.pick_button_label=="string"?e.pick_button_label:"",r=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",o=[];for(let s of n){if(o.length>=Dg)break;if(!s.contractAddress)continue;let a=typeof s.chain=="string"?s.chain.trim():"",i=a?`show my ${go} NFTs on ${Hd}`:`show my ${go} NFTs`,l=Wd(r,{[go]:s.name,[Hd]:a},i);a&&!l.includes(a)&&(l=`${l} (${a})`),o.push({label:qg(t,s.name,go),prompt:`${l} (${s.contractAddress})`})}return o}function Wd(n,e,t){let r=n&&n.includes(go)?n:t;for(let[o,s]of Object.entries(e))r=r.split(o).join(s);return r.replace(/\s+/g," ").trim()}function qg(n,e,t){return Wd(n,{[go]:e},t)}function Yd(n){if(typeof n!="string")return;let e=n.trim();return e||void 0}function $g(n){let e=Yd(n);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var Hg="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.",xt=class extends A{kind="data";category="nft";llm;constructor(e){super(),this.llm=new ve(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 r=await this.askGeminiWithSearch(t);return r?{_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:r}:{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:Hg,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var bo=class extends xt{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=xt.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 wo=class extends xt{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=xt.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 hc={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"},fc="amazon.com";function Vg(n){return n?n.trim().toLowerCase().split(/[-_]/)[0]:""}function gc(n){let e=Vg(n);return hc[e]??fc}function bi(n){return`https://${gc(n)}/s?k=NFC%20Tag`}function wi(n){if(!n)return"";let e=n.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var Wg=720*60*1e3,Gd=new Map,Kd=3;function Yg(n){return[`A user in country "${n}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Kd} 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 Gg(n){if(!n)return[];let e=n.indexOf("["),t=n.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let r;try{r=JSON.parse(n.slice(e,t+1))}catch{return[]}if(!Array.isArray(r))return[];let o=[],s=new Set;for(let a of r){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>=Kd))break}return o}async function yc(n,e){let t=wi(n);if(!t||!e)return null;let r=Gd.get(t);if(r&&r.expires>Date.now())return r.links;let o=Date.now(),s=[{role:"user",content:Yg(t),timestamp:o}];try{let a=await e.chat(s,void 0,{googleSearch:!0,maxRetries:1}),i=Gg(a.text);if(i.length)return Gd.set(t,{links:i,expires:Date.now()+Wg}),i}catch{}return null}async function ko(n){let e=await yc(n.country,n.llm);return e&&e.length?e:[{label:"Amazon",url:bi(n.language)}]}function Kg(n){return n.length<=1?n.length===1?`[${n[0].label}](${n[0].url})`:"":n.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
|
|
43
|
+
`)}var jd=["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(`
|
|
44
|
+
`),vo=class extends A{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 ve(e))}async run(e,t){let r=typeof e.language=="string"&&e.language.trim()?e.language.trim():void 0,o=await ko({country:t?.country,language:r,llm:this.llm}),s=Kg(o),a=o.length>1;return{reference:jd,marketplaceLinks:o,_instructions:`Answer the user's NFC question as a knowledgeable, friendly expert, writing in the USER'S language (translate naturally \u2014 never leave it in English when they wrote another language). Draw on the reference below for the facts (do NOT invent anything beyond it), but write a polished, well-organized answer \u2014 not a terse one-liner. FORMAT: Use short Markdown section headings (bold or "##") and bullet points so it is easy to scan, similar to a great encyclopedia entry. For a broad question like "what is an NFC tag", give a thorough multi-section answer: open with a 1\u20132 sentence plain-language definition, then cover sections such as "How it works", "What's inside", "What it can store", "Common uses", "How to use one", and "Why they're popular" \u2014 include concrete specifics (the 13.56 MHz frequency, chip names + byte capacities, example payloads, numbered steps). Aim for genuinely useful depth, several short paragraphs/lists, not a wall of dense text. For a NARROW question (e.g. only "what can it store" or "how do I write one"), answer just that part in focused detail and skip the unrelated sections. Do not mention tools, this reference, or that anything is canned. AT THE END, add a short closing line telling them where they can buy NFC tags, then include EACH of these exact CLICKABLE Markdown links `+(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)):
|
|
45
45
|
${s}
|
|
46
46
|
Never show a raw URL on its own and never drop a link. Reference:
|
|
47
47
|
|
|
48
|
-
`+
|
|
49
|
-
`)}var
|
|
48
|
+
`+jd}}};function jg(n){return n.length<=1?n.length===1?`[${n[0].label}](${n[0].url})`:"":n.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
|
|
49
|
+
`)}var To=class extends A{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 ve(e))}async run(e,t){let r=typeof e.language=="string"&&e.language.trim()?e.language.trim():void 0,o=await ko({country:t?.country,language:r,llm:this.llm}),s=jg(o),a=o.length>1;return{marketplaceLinks:o,message:a?`You can buy NFC tags here:
|
|
50
50
|
${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:
|
|
51
|
-
${s}`}}};var
|
|
51
|
+
${s}`}}};var zg="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.",Ao=class extends A{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 ve(e??{})}async run(e,t){let r=typeof e.prompt=="string"?e.prompt.trim():"";if(!r)return{error:"Missing required parameter: prompt"};let o=[];t?.walletAddress&&o.push(`- Connected wallet address: ${t.walletAddress}`),t?.chain&&o.push(`- Current chain: ${t.chain}`),o.push("Use this context only when relevant to the question. Do not invent on-chain values.");let s=Date.now(),a=[{role:"system",content:zg,timestamp:s},{role:"system",content:`[USER CONTEXT]
|
|
52
52
|
${o.join(`
|
|
53
|
-
`)}`,timestamp:s},{role:"user",content:r,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
|
|
53
|
+
`)}`,timestamp:s},{role:"user",content:r,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 Xg=`You are a world-class DEX liquidity-pool master and analyst \u2014 the deepest pool expert there is.
|
|
54
54
|
You know everything about liquidity pools across protocols and chains: Uniswap V2/V3/V4, PancakeSwap, Curve, Balancer, SushiSwap, Aerodrome, and more.
|
|
55
55
|
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.
|
|
56
56
|
You answer ANY pool-related question \u2014 conceptual, strategic, comparative, or current-events \u2014 clearly and accurately.
|
|
57
57
|
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.
|
|
58
|
-
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.`,
|
|
58
|
+
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.`,Po=class extends A{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 ve(e??{})}async run(e,t){let r=typeof e.prompt=="string"?e.prompt.trim():"";if(!r)return{error:"Missing required parameter: prompt"};let o=[];t?.walletAddress&&o.push(`- Connected wallet address: ${t.walletAddress}`),t?.chain&&o.push(`- Current chain: ${t.chain}`),o.push("Use this context only when relevant to the question. Do not invent on-chain values.");let s=Date.now(),a=[{role:"system",content:Xg,timestamp:s},{role:"system",content:`[USER CONTEXT]
|
|
59
59
|
${o.join(`
|
|
60
|
-
`)}`,timestamp:s},{role:"user",content:r,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
|
|
60
|
+
`)}`,timestamp:s},{role:"user",content:r,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 mn(n){return n===8388608}function ki(n,e,t){return t==="V4"||typeof n!="number"||!Number.isFinite(n)||n<=0||mn(n)||typeof e!="number"||!Number.isFinite(e)||e<=0||e>=n?1:1-e/n}function vi(n,e,t=1){if(!(typeof n!="number"||!Number.isFinite(n))&&!(typeof e!="number"||!Number.isFinite(e))&&!mn(e))return n*e*t/1e6}function $(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var Qg="https://interface.gateway.uniswap.org",Jg="/v1/graphql",Zg="https://entry-gateway.backend-prod.api.uniswap.org",zd="/data.v1.SearchService/SearchTokens",ey="/data.v2.DataApiService/ListPools",Ti=100,ty=20,ny="https://liquidity.backend-prod.api.uniswap.org",ry="/uniswap.liquidity.v2.LiquidityService/GetPool",Ct=3,Gs=800,Xd=800,oy="0x0000000000000000000000000000000000000000",rp={"0x1":"ETHEREUM","0xa":"OPTIMISM","0x38":"BNB","0x89":"POLYGON","0x2105":"BASE","0xa4b1":"ARBITRUM","0xa86a":"AVALANCHE","0xe708":"LINEA"},sy=`query V3Pool($chain: Chain!, $address: String!) {
|
|
61
61
|
v3Pool(chain: $chain, address: $address) {
|
|
62
62
|
id
|
|
63
63
|
protocolVersion
|
|
@@ -90,7 +90,7 @@ fragment TokenPrice on Token {
|
|
|
90
90
|
id
|
|
91
91
|
market(currency: USD) { id price { id value __typename } __typename }
|
|
92
92
|
__typename
|
|
93
|
-
}`,
|
|
93
|
+
}`,op=`
|
|
94
94
|
fragment SimpleTokenDetails on Token {
|
|
95
95
|
...TokenBasicInfoParts
|
|
96
96
|
project { id isSpam logoUrl name safetyLevel __typename }
|
|
@@ -105,7 +105,7 @@ fragment TokenPrice on Token {
|
|
|
105
105
|
id
|
|
106
106
|
market(currency: USD) { id price { id value __typename } __typename }
|
|
107
107
|
__typename
|
|
108
|
-
}`,
|
|
108
|
+
}`,ay=`query V2Pair($chain: Chain!, $address: String!) {
|
|
109
109
|
v2Pair(chain: $chain, address: $address) {
|
|
110
110
|
id
|
|
111
111
|
protocolVersion
|
|
@@ -122,7 +122,7 @@ fragment TokenPrice on Token {
|
|
|
122
122
|
__typename
|
|
123
123
|
}
|
|
124
124
|
}
|
|
125
|
-
${
|
|
125
|
+
${op}`,iy=`query V4Pool($chain: Chain!, $poolId: String!) {
|
|
126
126
|
v4Pool(chain: $chain, poolId: $poolId) {
|
|
127
127
|
id
|
|
128
128
|
protocolVersion
|
|
@@ -143,7 +143,7 @@ ${rp}`,ay=`query V4Pool($chain: Chain!, $poolId: String!) {
|
|
|
143
143
|
__typename
|
|
144
144
|
}
|
|
145
145
|
}
|
|
146
|
-
${rp}`,fn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114,"0xe708":59144};function Ks(n){return new Promise(e=>setTimeout(e,n))}async function Xd(n,e,t){let r;return Promise.race([n,new Promise(o=>{r=setTimeout(()=>o(t),e)})]).finally(()=>clearTimeout(r))}function Ai(n){if(!n)return 1;let e=n.toLowerCase();return fn[e]??1}function bc(n){if(!n)return"ETHEREUM";let e=n.toLowerCase();return np[e]??"ETHEREUM"}var iy=Object.fromEntries(Object.entries(fn).map(([n,e])=>[e,n]));function op(n){if(typeof n!="number")return;let e=iy[n];return e?np[e]:void 0}function ly(n){if(typeof n!="string")return;let e=n.replace("PROTOCOL_VERSION_","").toUpperCase();return e==="V2"||e==="V3"||e==="V4"?e:void 0}function cy(n){switch(n){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 Qd(n){let e=n.pool,t=e?.poolId?.trim();if(!e||!t)return;let r=n.stats??{},o=ly(e.protocolVersion),s=op(e.chainId),a=ki(e.feeTier,e.protocolFee,o);return{id:t,chain:s,protocolVersion:o,feeTier:e.feeTier,isDynamicFee:e.isDynamicFee,totalLiquidity:gn(r.tvl),volume1Day:gn(r.volume1d),volume30Day:gn(r.volume30d),apr:$(r.apr),totalApr:$(r.totalApr),volumeToTvlRatio:typeof r.volume1dTvlRatio=="number"?r.volume1dTvlRatio:void 0,lpFeeShare:a,fee24hUsd:vi(r.volume1d,e.feeTier,a),token0:ep(e.token0),token1:ep(e.token1)}}function gn(n){return typeof n=="number"&&Number.isFinite(n)?{value:n,currency:"USD"}:void 0}function wc(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string"||n.trim()==="")return;let e=Number(n);return Number.isFinite(e)?e:void 0}function Jd(n,e,t,r){if(!n&&!e&&!r)return;let o=wc(t);return{...r,address:e??r?.address,symbol:n?.symbol??r?.symbol,name:n?.name??r?.name,decimals:n?.decimals??r?.decimals,logo:n?.logoUrl??r?.logo,price:gn(o)??r?.price,market:o!==void 0?{price:gn(o)}:r?.market,project:r?.project}}function Zd(n,e){let t=n.poolIdentifier,r=n.protocolVersion==="V4",o=n.hookAddress&&n.hookAddress!==ry?n.hookAddress:e?.hook?.address??void 0;return{id:e?.id,protocolVersion:n.protocolVersion??e?.protocolVersion,address:r?e?.address:t??e?.address,poolId:r?t??e?.poolId:e?.poolId,feeTier:n.feeTier??e?.feeTier,tickSpacing:n.tickSpacing??e?.tickSpacing,isDynamicFee:n.isDynamicFee??e?.isDynamicFee,hook:o?{address:o}:void 0,totalLiquidity:gn(n.tvlUsd)??e?.totalLiquidity,totalLiquidityPercentChange24h:gn(n.tvlUsdChange1d)??e?.totalLiquidityPercentChange24h,volume24h:gn(n.volumeUsd1d)??e?.volume24h,token0Supply:wc(n.token0Supply)??e?.token0Supply,token1Supply:wc(n.token1Supply)??e?.token1Supply,txCount:e?.txCount,historicalVolume:e?.historicalVolume,token0:Jd(n.token0Metadata,n.token0Address,n.token0PriceUsd,e?.token0),token1:Jd(n.token1Metadata,n.token1Address,n.token1PriceUsd,e?.token1),protocolFee:n.protocolFee,apr:$(n.apr),totalApr:$(n.totalApr),currentTick:n.currentTick,sqrtPriceX96:n.sqrtPriceX96,liquidity:n.liquidity}}function ep(n){if(n)return{chain:op(n.chainId),address:n.address,symbol:n.symbol,name:n.name,decimals:n.decimals,standard:n.type?.replace("TOKEN_TYPE_",""),logo:n.project?.logoUrl,project:n.project?.logoUrl?{logo:{url:n.project.logoUrl}}:void 0}}function tp(n,e){switch(e){case"volume1Day":return n.volume1Day?.value??0;case"volume1Week":return n.volume1Week?.value??0;case"volume30Day":return n.volume30Day?.value??0;case"txCount":return n.txCount??0;case"apr":return n.apr??n.totalApr??0;default:return n.totalLiquidity?.value??0}}var He=class{baseUrl;searchBaseUrl;liquidityBaseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Xg).replace(/\/$/,""),this.searchBaseUrl=(e?.searchBaseUrl??Jg).replace(/\/$/,""),this.liquidityBaseUrl=(e?.liquidityBaseUrl??ty).replace(/\/$/,"")}isSupported(e){if(!e)return!1;let t=D(e);return!!t&&Object.prototype.hasOwnProperty.call(fn,t)}listSupportedChains(){return Object.keys(fn).filter(e=>qe(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}${Zg}`,r=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),Ti),...e.pageToken?{pageToken:e.pageToken}:{}}}),o="Unknown error";for(let s=1;s<=xt;s++)try{let a=await C.post(t,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(!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){o=a instanceof Error?a.message:"Unknown error",s<xt&&await Ks(Gs)}return{success:!1,error:o}}async listAllPools(e){let t=[],r=new Set,o;for(let s=0;s<ey;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||r.has(i))break;r.add(i),o=i}return{success:!0,data:t}}async getTopPools(e){let t=e?.protocolVersion??"V3",r=e?.limit&&e.limit>0?Math.floor(e.limit):10,o=e?.sortBy??"tvl",s=e?.multichain?Object.values(fn):[Ai(e?.chain)],a=cy(o),i=a?Math.min(r,Ti):Ti,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=>Qd(u)).filter(u=>u!==void 0).sort((u,p)=>tp(p,o)-tp(u,o)).slice(0,r)}}async getPool(e){let t=e.addressOrId?.trim();if(!t)return{success:!1,error:"Pool address or id is required"};let r=`${this.liquidityBaseUrl}${ny}`,o=JSON.stringify({pool:{chainId:Ai(e.chain),addressOrId:t}}),s="Unknown error";for(let a=1;a<=xt;a++)try{let i=await C.post(r,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(_(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<xt&&await Ks(Gs)}return{success:!1,error:s}}async getV3PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V3Pool",query:oy,variables:{chain:bc(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:sy,variables:{chain:bc(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:ay,variables:{chain:bc(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 r=t.data;if(e.enrich===!1)return{success:!0,data:Zd(r,void 0)};let o=r.protocolVersion,s=r.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 Xd(a.then(l=>l.success?l.data:void 0).catch(()=>{}),zd,void 0);return{success:!0,data:Zd(r,i)}}async fetchPoolDetailGraphQL(e){let t=`${this.baseUrl}${Qg}`,r=JSON.stringify({operationName:e.operationName,variables:e.variables,query:e.query}),o="Unknown error";for(let s=1;s<=xt;s++)try{let a=await C.post(t,r,{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){o=a instanceof Error?a.message:"Unknown error",s<xt&&await Ks(Gs)}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 r=Array.from(new Set(e.filter(s=>typeof s=="string"&&R(s.trim())).map(s=>s.trim()))),o=new Map;return r.length===0||await Xd(Promise.all(r.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(()=>{}),zd,void 0),o}async fetchSearchTokens(e){let t=Ai(e.chain),r=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}${jd}`,a=JSON.stringify({searchQuery:e.query,chainIds:[t],searchType:"TOKEN",page:r,size:o}),i="Unknown error";for(let l=1;l<=xt;l++)try{let c=await C.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<xt&&await Ks(Gs)}return{success:!1,error:i}}async searchPools(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};let r=Ai(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}${jd}`,c=JSON.stringify({searchQuery:t,chainIds:[r],searchType:"POOL",page:o,size:s}),[d,u]=await Promise.allSettled([this.fetchSearchPools(l,c),this.listPools({chainIds:[r],protocolVersions:a==="ALL"?["V2","V3","V4"]:[a],orderBy:"POOLS_ORDER_BY_TVL",pageSize:Ti})]);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=Qd(y);if(!w||i!=null&&w.feeTier!==i)continue;let k=(w.token0?.symbol??"").toLowerCase(),v=(w.token1?.symbol??"").toLowerCase(),P=(w.token0?.name??"").toLowerCase(),S=(w.token1?.name??"").toLowerCase();if(!p.some(z=>k.includes(z)||v.includes(z)||P.includes(z)||S.includes(z)))continue;let L=w.id.toLowerCase(),E=w.totalLiquidity?.value,ke=w.volume1Day?.value,V=f.get(L);f.set(L,{...V??{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},...E!=null?{tvlUsd:E}:{},...ke!=null?{volume1DayUsd:ke}:{},...w.isDynamicFee===!0||hn(w.feeTier)?{isDynamicFee:!0}:{}}),h.set(L,w.chain),g.set(L,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=$(g.get(y));k!=null&&(w.apr=k)}return{success:!0,data:b.map(([,y])=>y)}}async fetchSearchPools(e,t){let r="Unknown error";for(let o=1;o<=xt;o++)try{let s=await C.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){r=s instanceof Error?s.message:"Unknown error",o<xt&&await Ks(Gs)}return{success:!1,error:r}}matchScore(e,t){let r=[e.token0?.symbol??"",e.token1?.symbol??""].map(s=>s.toLowerCase()),o=0;for(let s of t){let a=0;for(let i of r)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 sp=2n**96n;function Se(n,e=8){return!Number.isFinite(n)||n===0?n:Number(n.toPrecision(e))}function ap(n,e,t){let r=n*n,o=sp*sp,s=r*10n**18n/o;return Number(s)/1e18*Math.pow(10,e-t)}function pt(n,e,t){return Math.pow(1.0001,n)*Math.pow(10,e-t)}function zn(n,e,t){if(n<=0)throw new Error("priceToTick: price must be > 0");let r=n/Math.pow(10,e-t),o=Math.log(r)/Math.log(1.0001),s=Math.round(o);return Math.abs(o-s)<.001?s:Math.floor(o)}function So(n,e,t){let r={minPrice:n,maxPrice:e,inverted:!1};if(!Number.isFinite(n)||!Number.isFinite(e)||!Number.isFinite(t)||n<=0||e<=0||t<=0||n>=e)return r;let o={minPrice:1/e,maxPrice:1/n,inverted:!0},s=c=>t>=c.minPrice&&t<=c.maxPrice,a=s(r),i=s(o);if(a&&!i)return r;if(i&&!a)return o;let l=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/t));return l(o)<l(r)?o:r}function Ct(n,e,t="nearest"){let r=Math.abs(n-Math.round(n))<1e-6?Math.round(n):n,o=(r%e+e)%e;if(o===0)return r;let s=r-o,a=s+e;return t==="down"?s:t==="up"?a:r-s<a-r?s:a}var yn=-887272,Po=887272;function Rt(n){return n<yn?yn:n>Po?Po:n}var uy={"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"},dy={"0x1":"ethereum","0xa4b1":"arbitrum","0x89":"polygon","0x38":"bsc","0x2105":"base","0xa":"optimism","0xa86a":"avalanche"},py={"0x1":1,"0xa4b1":42161,"0x89":137,"0x38":56,"0x2105":8453,"0xa":10,"0xa86a":43114},ip={"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"},lp={100:.01,500:.05,3e3:.3,1e4:1},my={ethereum:"0x1","arbitrum one":"0xa4b1",arbitrum:"0xa4b1",polygon:"0x89",bsc:"0x38",base:"0x2105",optimism:"0xa","avalanche c-chain":"0xa86a",avalanche:"0xa86a"},hy=300*1e3,xe=class{apiKey;subgraphUrls;coinPoolBaseUrl;llamaCache=null;llamaCacheAt=0;constructor(e={}){this.apiKey=e.theGraphApiKey||"4c67ac7a75b21befbd28dc9120c709f1";let t={...uy,...e.subgraphUrls||{}};this.subgraphUrls=Object.fromEntries(Object.entries(t).filter(([r])=>qe(r))),this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}resolveChain(e){if(!e)return"0x1";let t=e.toLowerCase();return ip[t]||(this.subgraphUrls[t]?t:"0x1")}isSupported(e){if(!e)return!1;let t=e.toLowerCase(),r=ip[t];return!!(r&&this.subgraphUrls[r])}chainName(e){let t=this.resolveChain(e);return dy[t]||t}numericChainId(e){return py[this.resolveChain(e)]}listSupportedChains(){return Object.keys(this.subgraphUrls)}async querySubgraph(e,t){let r=this.resolveChain(e),o=this.subgraphUrls[r];if(!o)throw new Error(`No subgraph available for chain: ${e}`);let s=await C.post(o,{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`
|
|
146
|
+
${op}`,hn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114,"0xe708":59144};function Ks(n){return new Promise(e=>setTimeout(e,n))}async function Qd(n,e,t){let r;return Promise.race([n,new Promise(o=>{r=setTimeout(()=>o(t),e)})]).finally(()=>clearTimeout(r))}function Ai(n){if(!n)return 1;let e=n.toLowerCase();return hn[e]??1}function bc(n){if(!n)return"ETHEREUM";let e=n.toLowerCase();return rp[e]??"ETHEREUM"}var ly=Object.fromEntries(Object.entries(hn).map(([n,e])=>[e,n]));function sp(n){if(typeof n!="number")return;let e=ly[n];return e?rp[e]:void 0}function cy(n){if(typeof n!="string")return;let e=n.replace("PROTOCOL_VERSION_","").toUpperCase();return e==="V2"||e==="V3"||e==="V4"?e:void 0}function uy(n){switch(n){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 Jd(n){let e=n.pool,t=e?.poolId?.trim();if(!e||!t)return;let r=n.stats??{},o=cy(e.protocolVersion),s=sp(e.chainId),a=ki(e.feeTier,e.protocolFee,o);return{id:t,chain:s,protocolVersion:o,feeTier:e.feeTier,isDynamicFee:e.isDynamicFee,totalLiquidity:fn(r.tvl),volume1Day:fn(r.volume1d),volume30Day:fn(r.volume30d),apr:$(r.apr),totalApr:$(r.totalApr),volumeToTvlRatio:typeof r.volume1dTvlRatio=="number"?r.volume1dTvlRatio:void 0,lpFeeShare:a,fee24hUsd:vi(r.volume1d,e.feeTier,a),token0:tp(e.token0),token1:tp(e.token1)}}function fn(n){return typeof n=="number"&&Number.isFinite(n)?{value:n,currency:"USD"}:void 0}function wc(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string"||n.trim()==="")return;let e=Number(n);return Number.isFinite(e)?e:void 0}function Zd(n,e,t,r){if(!n&&!e&&!r)return;let o=wc(t);return{...r,address:e??r?.address,symbol:n?.symbol??r?.symbol,name:n?.name??r?.name,decimals:n?.decimals??r?.decimals,logo:n?.logoUrl??r?.logo,price:fn(o)??r?.price,market:o!==void 0?{price:fn(o)}:r?.market,project:r?.project}}function ep(n,e){let t=n.poolIdentifier,r=n.protocolVersion==="V4",o=n.hookAddress&&n.hookAddress!==oy?n.hookAddress:e?.hook?.address??void 0;return{id:e?.id,protocolVersion:n.protocolVersion??e?.protocolVersion,address:r?e?.address:t??e?.address,poolId:r?t??e?.poolId:e?.poolId,feeTier:n.feeTier??e?.feeTier,tickSpacing:n.tickSpacing??e?.tickSpacing,isDynamicFee:n.isDynamicFee??e?.isDynamicFee,hook:o?{address:o}:void 0,totalLiquidity:fn(n.tvlUsd)??e?.totalLiquidity,totalLiquidityPercentChange24h:fn(n.tvlUsdChange1d)??e?.totalLiquidityPercentChange24h,volume24h:fn(n.volumeUsd1d)??e?.volume24h,token0Supply:wc(n.token0Supply)??e?.token0Supply,token1Supply:wc(n.token1Supply)??e?.token1Supply,txCount:e?.txCount,historicalVolume:e?.historicalVolume,token0:Zd(n.token0Metadata,n.token0Address,n.token0PriceUsd,e?.token0),token1:Zd(n.token1Metadata,n.token1Address,n.token1PriceUsd,e?.token1),protocolFee:n.protocolFee,apr:$(n.apr),totalApr:$(n.totalApr),currentTick:n.currentTick,sqrtPriceX96:n.sqrtPriceX96,liquidity:n.liquidity}}function tp(n){if(n)return{chain:sp(n.chainId),address:n.address,symbol:n.symbol,name:n.name,decimals:n.decimals,standard:n.type?.replace("TOKEN_TYPE_",""),logo:n.project?.logoUrl,project:n.project?.logoUrl?{logo:{url:n.project.logoUrl}}:void 0}}function np(n,e){switch(e){case"volume1Day":return n.volume1Day?.value??0;case"volume1Week":return n.volume1Week?.value??0;case"volume30Day":return n.volume30Day?.value??0;case"txCount":return n.txCount??0;case"apr":return n.apr??n.totalApr??0;default:return n.totalLiquidity?.value??0}}var He=class{baseUrl;searchBaseUrl;liquidityBaseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Qg).replace(/\/$/,""),this.searchBaseUrl=(e?.searchBaseUrl??Zg).replace(/\/$/,""),this.liquidityBaseUrl=(e?.liquidityBaseUrl??ny).replace(/\/$/,"")}isSupported(e){if(!e)return!1;let t=D(e);return!!t&&Object.prototype.hasOwnProperty.call(hn,t)}listSupportedChains(){return Object.keys(hn).filter(e=>qe(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}${ey}`,r=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),Ti),...e.pageToken?{pageToken:e.pageToken}:{}}}),o="Unknown error";for(let s=1;s<=Ct;s++)try{let a=await C.post(t,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(!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){o=a instanceof Error?a.message:"Unknown error",s<Ct&&await Ks(Gs)}return{success:!1,error:o}}async listAllPools(e){let t=[],r=new Set,o;for(let s=0;s<ty;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||r.has(i))break;r.add(i),o=i}return{success:!0,data:t}}async getTopPools(e){let t=e?.protocolVersion??"V3",r=e?.limit&&e.limit>0?Math.floor(e.limit):10,o=e?.sortBy??"tvl",s=e?.multichain?Object.values(hn):[Ai(e?.chain)],a=uy(o),i=a?Math.min(r,Ti):Ti,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=>Jd(u)).filter(u=>u!==void 0).sort((u,p)=>np(p,o)-np(u,o)).slice(0,r)}}async getPool(e){let t=e.addressOrId?.trim();if(!t)return{success:!1,error:"Pool address or id is required"};let r=`${this.liquidityBaseUrl}${ry}`,o=JSON.stringify({pool:{chainId:Ai(e.chain),addressOrId:t}}),s="Unknown error";for(let a=1;a<=Ct;a++)try{let i=await C.post(r,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(_(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<Ct&&await Ks(Gs)}return{success:!1,error:s}}async getV3PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V3Pool",query:sy,variables:{chain:bc(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:ay,variables:{chain:bc(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:iy,variables:{chain:bc(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 r=t.data;if(e.enrich===!1)return{success:!0,data:ep(r,void 0)};let o=r.protocolVersion,s=r.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 Qd(a.then(l=>l.success?l.data:void 0).catch(()=>{}),Xd,void 0);return{success:!0,data:ep(r,i)}}async fetchPoolDetailGraphQL(e){let t=`${this.baseUrl}${Jg}`,r=JSON.stringify({operationName:e.operationName,variables:e.variables,query:e.query}),o="Unknown error";for(let s=1;s<=Ct;s++)try{let a=await C.post(t,r,{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){o=a instanceof Error?a.message:"Unknown error",s<Ct&&await Ks(Gs)}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 r=Array.from(new Set(e.filter(s=>typeof s=="string"&&R(s.trim())).map(s=>s.trim()))),o=new Map;return r.length===0||await Qd(Promise.all(r.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(()=>{}),Xd,void 0),o}async fetchSearchTokens(e){let t=Ai(e.chain),r=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}${zd}`,a=JSON.stringify({searchQuery:e.query,chainIds:[t],searchType:"TOKEN",page:r,size:o}),i="Unknown error";for(let l=1;l<=Ct;l++)try{let c=await C.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<Ct&&await Ks(Gs)}return{success:!1,error:i}}async searchPools(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};let r=Ai(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}${zd}`,c=JSON.stringify({searchQuery:t,chainIds:[r],searchType:"POOL",page:o,size:s}),[d,u]=await Promise.allSettled([this.fetchSearchPools(l,c),this.listPools({chainIds:[r],protocolVersions:a==="ALL"?["V2","V3","V4"]:[a],orderBy:"POOLS_ORDER_BY_TVL",pageSize:Ti})]);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=Jd(y);if(!w||i!=null&&w.feeTier!==i)continue;let k=(w.token0?.symbol??"").toLowerCase(),v=(w.token1?.symbol??"").toLowerCase(),P=(w.token0?.name??"").toLowerCase(),S=(w.token1?.name??"").toLowerCase();if(!p.some(z=>k.includes(z)||v.includes(z)||P.includes(z)||S.includes(z)))continue;let L=w.id.toLowerCase(),E=w.totalLiquidity?.value,ke=w.volume1Day?.value,V=f.get(L);f.set(L,{...V??{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},...E!=null?{tvlUsd:E}:{},...ke!=null?{volume1DayUsd:ke}:{},...w.isDynamicFee===!0||mn(w.feeTier)?{isDynamicFee:!0}:{}}),h.set(L,w.chain),g.set(L,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=$(g.get(y));k!=null&&(w.apr=k)}return{success:!0,data:b.map(([,y])=>y)}}async fetchSearchPools(e,t){let r="Unknown error";for(let o=1;o<=Ct;o++)try{let s=await C.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){r=s instanceof Error?s.message:"Unknown error",o<Ct&&await Ks(Gs)}return{success:!1,error:r}}matchScore(e,t){let r=[e.token0?.symbol??"",e.token1?.symbol??""].map(s=>s.toLowerCase()),o=0;for(let s of t){let a=0;for(let i of r)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 ap=2n**96n;function Se(n,e=8){return!Number.isFinite(n)||n===0?n:Number(n.toPrecision(e))}function ip(n,e,t){let r=n*n,o=ap*ap,s=r*10n**18n/o;return Number(s)/1e18*Math.pow(10,e-t)}function pt(n,e,t){return Math.pow(1.0001,n)*Math.pow(10,e-t)}function Kn(n,e,t){if(n<=0)throw new Error("priceToTick: price must be > 0");let r=n/Math.pow(10,e-t),o=Math.log(r)/Math.log(1.0001),s=Math.round(o);return Math.abs(o-s)<.001?s:Math.floor(o)}function xo(n,e,t){let r={minPrice:n,maxPrice:e,inverted:!1};if(!Number.isFinite(n)||!Number.isFinite(e)||!Number.isFinite(t)||n<=0||e<=0||t<=0||n>=e)return r;let o={minPrice:1/e,maxPrice:1/n,inverted:!0},s=c=>t>=c.minPrice&&t<=c.maxPrice,a=s(r),i=s(o);if(a&&!i)return r;if(i&&!a)return o;let l=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/t));return l(o)<l(r)?o:r}function Rt(n,e,t="nearest"){let r=Math.abs(n-Math.round(n))<1e-6?Math.round(n):n,o=(r%e+e)%e;if(o===0)return r;let s=r-o,a=s+e;return t==="down"?s:t==="up"?a:r-s<a-r?s:a}var gn=-887272,So=887272;function Et(n){return n<gn?gn:n>So?So:n}var dy={"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"},py={"0x1":"ethereum","0xa4b1":"arbitrum","0x89":"polygon","0x38":"bsc","0x2105":"base","0xa":"optimism","0xa86a":"avalanche"},my={"0x1":1,"0xa4b1":42161,"0x89":137,"0x38":56,"0x2105":8453,"0xa":10,"0xa86a":43114},lp={"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"},cp={100:.01,500:.05,3e3:.3,1e4:1},hy={ethereum:"0x1","arbitrum one":"0xa4b1",arbitrum:"0xa4b1",polygon:"0x89",bsc:"0x38",base:"0x2105",optimism:"0xa","avalanche c-chain":"0xa86a",avalanche:"0xa86a"},fy=300*1e3,xe=class{apiKey;subgraphUrls;coinPoolBaseUrl;llamaCache=null;llamaCacheAt=0;constructor(e={}){this.apiKey=e.theGraphApiKey||"4c67ac7a75b21befbd28dc9120c709f1";let t={...dy,...e.subgraphUrls||{}};this.subgraphUrls=Object.fromEntries(Object.entries(t).filter(([r])=>qe(r))),this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}resolveChain(e){if(!e)return"0x1";let t=e.toLowerCase();return lp[t]||(this.subgraphUrls[t]?t:"0x1")}isSupported(e){if(!e)return!1;let t=e.toLowerCase(),r=lp[t];return!!(r&&this.subgraphUrls[r])}chainName(e){let t=this.resolveChain(e);return py[t]||t}numericChainId(e){return my[this.resolveChain(e)]}listSupportedChains(){return Object.keys(this.subgraphUrls)}async querySubgraph(e,t){let r=this.resolveChain(e),o=this.subgraphUrls[r];if(!o)throw new Error(`No subgraph available for chain: ${e}`);let s=await C.post(o,{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`
|
|
147
147
|
id
|
|
148
148
|
token0 { id symbol name }
|
|
149
149
|
token1 { id symbol name }
|
|
@@ -160,7 +160,7 @@ ${rp}`,fn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0
|
|
|
160
160
|
volumeToken0
|
|
161
161
|
volumeToken1
|
|
162
162
|
}
|
|
163
|
-
`}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 r=e,o=Number(r.feeTier||0),s=
|
|
163
|
+
`}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 r=e,o=Number(r.feeTier||0),s=cp[o]??o/1e4,a=this.sanitize(parseFloat(r.totalValueLockedUSD||"0")),i=r.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:r.id,pair:`${r.token0.symbol}/${r.token1.symbol}`,token0:{symbol:r.token0.symbol,address:r.token0.id,name:r.token0.name},token1:{symbol:r.token1.symbol,address:r.token1.id,name:r.token1.name},tvl:a,volume24hUsd:l,fees24hUsd:c,apr:d,feeTierBps:o,feeTierPercent:s,liquidity:r.liquidity||"0",chain:this.chainName(t)}}async fetchDefiLlamaUniswap(){let e=Date.now();if(this.llamaCache&&e-this.llamaCacheAt<fy)return this.llamaCache;try{let t=await C.get("https://yields.llama.fi/pools");if(!t.ok)throw new Error(`DefiLlama: ${_(t)}`);let o=(t.data.data||[]).filter(s=>s.project==="uniswap-v3");return this.llamaCache=o,this.llamaCacheAt=e,o}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(r=>{let o=this.resolveChain(r.chain),s=r.feeTierBps,a=r.token0.address.toLowerCase(),i=r.token1.address.toLowerCase(),l=t.filter(p=>hy[p.chain.toLowerCase()]===o),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=r.token0.symbol.toUpperCase(),m=r.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 r;let d=c.apyBase??c.apy??null,u={...r};return $(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:r,sortBy:o,filters:s}=e,a=this.resolveChain(r),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";o==="volume"?c="volumeUSD":o==="fee"?c="feeTier":o==="liquidity"&&(c="liquidity");let d=o==="fee"?"asc":"desc",u=h=>h.length===1?`symbol: "${h[0]}"`:`symbol_in: [${h.map(g=>`"${g}"`).join(", ")}]`,p=(h,g)=>`{
|
|
164
164
|
pools(
|
|
165
165
|
first: ${g}
|
|
166
166
|
orderBy: ${c}
|
|
@@ -202,25 +202,25 @@ ${rp}`,fn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0
|
|
|
202
202
|
${this.poolFragment()}
|
|
203
203
|
}
|
|
204
204
|
}
|
|
205
|
-
}`,o=await this.querySubgraph(t,r);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,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 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 r=e.poolAddress.toLowerCase();return(await this.fetchCoinPoolV2Items(t)).filter(s=>s.poolId?.toLowerCase()===r).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`,r=await C.get(t);if(!r.ok)throw new Error(_(r));return r.data?.data?.items||[]}catch{return[]}}mapCoinPoolV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,r=e.token1.decimal??18,o=P=>P==null||!Number.isFinite(P)?0:Math.pow(1.0001,P)*Math.pow(10,t-r),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,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=lp[y]??y/1e4,k=$(e.apr)??$(e.aprAvg)??null,v=$(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:Se(u),maxPrice:Se(p),currentPrice:Se(m),baseToken:f,quoteToken:h}}}};var bn=class{config;constructor(e){this.config=e}withRoute(e){let t=Object.create(this);return t.getQuote=r=>this.getQuote({route:e,...r}),t}};var Et=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 fy="https://api.relay.link";function cp(n){return n===7565164||n==="7565164"?792703809:n}var xo=class extends bn{apiBaseUrl;apiKey;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??fy,this.apiKey=e.apiKey}getProviderName(){return"relay"}hasIntegratedApproval(){return!0}async getQuote(e){let{srcChainId:t,srcTokenAddress:r,srcTokenAmount:o,dstChainId:s,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c}=e,d=await wn.getAffiliateFee(this.getProviderName(),t,e.route),u={user:i||l,originChainId:cp(t),destinationChainId:cp(s),originCurrency:r,destinationCurrency:a,amount:o,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,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 r=(await this.request("/intents/status/v3","GET",{requestId:e.requestIdOrTxHash})).status??"";return r==="success"||r==="refunded"?{success:!0,status:"COMPLETED"}:r==="failure"||r==="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,r){let o={"Content-Type":"application/json"};this.apiKey&&(o["x-api-key"]=this.apiKey);let s=`${this.apiBaseUrl}${e}`,a;if(t==="GET"&&r){let l=Object.entries(r).map(([c,d])=>`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`).join("&");s=`${s}?${l}`}else t==="POST"&&r&&(a=r);let i=await C.request(t,s,a,{headers:o});if(!i.ok)throw new Error(_(i));return i.data}};var gy="https://api.coinpool.app/config/addresses",yy="https://api.coinpool.app/config/bridgeProviderByChain",up="createPoolProxyV3",by="nftPositionUniswap",wy=/^0x[0-9a-fA-F]{40}$/,js=class{addresses;providerMap;constructor(e=gy,t=yy){this.addresses=new Et(async()=>(await C.get(e,{headers:{Accept:"application/json"}})).data?.data??null),this.providerMap=new Et(async()=>(await C.get(t,{headers:{Accept:"application/json"}})).data?.data??null)}async getProviderByChain(e){let r=(await this.providerMap.get())?.[String(e)];return this.isProviderName(r)?r:null}async getGatewayAddress(e){return this.getAddress(up,e)}async getPositionManagerAddress(e){return this.getAddress(by,e)}async getGatewayChains(){return this.listChainsWithAddress(up)}async getAddress(e,t){let r=await this.addresses.get();if(!r)return;let o=this.toDecimalChainKey(t);if(o)return this.firstAddress(r[e]?.[o])}async listChainsWithAddress(e){let t=(await this.addresses.get())?.[e];if(!t||typeof t!="object")return[];let r=[];for(let[o,s]of Object.entries(t)){let a=this.firstAddress(s);a&&wy.test(a)&&r.push(o)}return r}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 r=Number.parseInt(t,16);return Number.isFinite(r)?String(r):null}return/^\d+$/.test(t)?t:null}isProviderName(e){return e==="debridge"||e==="relay"}},kn=new js;var Co=class{async resolve(e){try{return await this.resolveProvider(e)??Bt}catch{return Bt}}toNumericChainId(e){if(e==null)return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}},Ro=class extends Co{constructor(t=kn){super();this.config=t}config;route="pool";async resolveProvider({srcChainId:t}){let r=this.toNumericChainId(t);return r===null?null:this.config.getProviderByChain(r)}},Eo=class extends Co{constructor(t=wn){super();this.setting=t}setting;route="userSwap";async resolveProvider({srcChainId:t,dstChainId:r}){return this.setting.getBridgeProvider(t,r)}};var zs=class{routers=new Map;constructor(e=[new Ro,new Eo]){for(let t of e)this.routers.set(t.route,t)}async resolveProvider(e){return await this.routers.get(e.route)?.resolve(e)??Bt}},Pi=new zs;var Xs=class{configOverride;routersOverride;cache=new Map;constructor(e,t){this.configOverride=e,this.routersOverride=t}get providers(){return this.configOverride??No}get routers(){return this.routersOverride??Pi}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 r=this.createService(e);return this.cache.set(e,r),r}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 Lo(t);case"relay":return new xo(t);default:{let r=e;throw new Error(`Unknown swap provider: ${String(r)}`)}}}},_o=new Xs;var No={debridge:{apiBaseUrl:"https://dln.debridge.finance/v1.0",accessToken:"d6c45897b8f6"},relay:{apiBaseUrl:"https://api.relay.link"}},Bt="relay";function Si(n,e){let t={...No[n]??{},...e};for(let r of Object.keys(t))t[r]===void 0&&delete t[r];No[n]=t,_o.resetCache()}var ky="https://exchange-api.keyring.app/admin/setting?configs=others",vy="https://api.relay.link/chains",Ty="https://dln.debridge.finance/v1.0/supported-chains-info",Ay=14400*1e3,Py=300*1e3,Sy=new Set([728126428,7565164]),dp={relay:"relay",debridge:"deBridge"},Qs=class{setting;chainSupport;constructor(e=ky){this.setting=new Et(async()=>(await C.get(e,{headers:{Accept:"application/json"}})).data?.others??null,Py),this.chainSupport=new Et(async()=>this.fetchChainSupport(),Ay)}async getBridgeProvider(e,t){let r=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)??Bt;if(!r||!o||!a)return i;let l=this.requireChainKeys(s?.keyringV2,"debridge"),c=l.includes(r)||l.includes(o),d=a.debridge.has(r)&&a.debridge.has(o);return c&&d?"debridge":i}async getAffiliateFee(e,t,r="userSwap"){let o=await this.setting.get();if(!o)return null;let s=r==="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,r){return t==="debridge"?{recipient:this.parseRecipientMap(e.affiliateRecipient)?.[String(r)],percent:this.toPercent(e.AFFILIATE_FEE_PERENT)}:{recipient:e.RELAY_AFFILIATE_FEE_RECIPIENT,percent:this.toPercent(e.RELAY_AFFILIATE_FEE_PERCENT)}}resolveKeyringV2Fee(e,t,r){let o=e.keyringV2;if(!o)return{recipient:void 0,percent:0};let s=o[dp[t]],a=String(r);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([C.get(vy,{headers:{Accept:"application/json"}}),C.get(Ty,{headers:{Accept:"application/json"}})]),r=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&&r.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||Sy.has(a))continue;let i=this.toChainKey(a);i&&o.add(i)}return{relay:r,debridge:o}}requireChainKeys(e,t){return(e?.[dp[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 r=/^0x/i.test(t)?Number.parseInt(t,16):Number(t);return Number.isFinite(r)?String(r):null}toPercent(e){if(e==null)return 0;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:0}},wn=new Qs;function xi(n,e){return M({abi:q,functionName:"approve",args:[n,e]})}async function xy(n,e,t,r,o){try{return await Re(n).call({account:t,to:e,data:xi(r,o)}),!0}catch(s){return Cy(s)?!1:null}}function Cy(n){let e=n?.name??"";if(e==="ContractFunctionRevertedError"||e==="CallExecutionError")return!0;let t=n instanceof Error?n.message.toLowerCase():String(n??"").toLowerCase();return t.includes("revert")||t.includes("execution reverted")||t.includes("invalid opcode")||t.includes("out of gas")}async function Ci({chain:n,token:e,owner:t,spender:r,amount:o,allowance:s}){let a=l=>({to:e,from:t,data:xi(r,l),value:"0"});return s!=null&&s>=o?[]:s===0n||!n?[a(o)]:await xy(n,e,t,r,o)===!1?[a(0n),a(o)]:[a(o)]}var Ry="https://dln.debridge.finance/v1.0",Ey="0x0000000000000000000000000000000000000000",_y=new Set([429,500]),Ny=5,Ly=1e3,Iy=n=>new Promise(e=>setTimeout(e,n)),Lo=class extends bn{apiBaseUrl;accessToken;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Ry,this.accessToken=e.accessToken??"d6c45897b8f6"}getProviderName(){return"debridge"}hasIntegratedApproval(){return!1}async getQuote(e){let{srcChainId:t,srcTokenAddress:r,srcTokenAmount:o,dstChainId:s,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c,isCrossChain:d}=e,u=d??t!==s,p=await wn.getAffiliateFee(this.getProviderName(),t,e.route);try{if(u){let h={srcChainId:String(t),srcChainTokenIn:r,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 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:r,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 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:r,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()===Ey)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,r,a);if(l!==null&&l>=i)return{isNeeded:!1,integrated:!1,approvals:[],contractAddress:a,message:"Sufficient allowance already granted."};let c=await Ci({chain:t,token:o,owner:r,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,r,o){if(!e)return null;try{return await Re(e).readContract({address:t,abi:q,functionName:"allowance",args:[r,o]})}catch{return null}}async trackTransaction(e){let{requestIdOrTxHash:t}=e;try{let r=await this.get(`${this.apiBaseUrl}/dln/tx/${t}/order-ids`,{accesstoken:this.accessToken});if(!r.orderIds?.length)return{success:!1,status:"PENDING"};let o=r.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(r){return{success:!1,status:"ERROR",error:r instanceof Error?r.message:String(r)}}}async get(e,t){let r=Object.entries(t).map(([a,i])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(i))}`).join("&"),o=r?`${e}?${r}`:e,s=await C.get(o,{headers:{Accept:"application/json"}});for(let a=0;a<Ny&&_y.has(s.status);a++)await Iy(Ly),s=await C.get(o,{headers:{Accept:"application/json"}});return s.data}};function pp(n){let e=n.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 mp(n){if(n.errorMessage&&n.errorMessage.trim())return n.errorMessage.trim();let e=r=>{if(typeof r=="string"&&r.trim())return r.trim();if(r&&typeof r=="object"){let o=r;for(let s of[o.message,o.errorMessage,o.error])if(typeof s=="string"&&s.trim())return s.trim()}},t=n.raw??{};return e(n.error)??e(t.errorMessage)??e(t.error)??"The swap could not be quoted right now."}var Uy={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"},Dy=[{inputs:[],name:"globalFixedNativeFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}];function hp(n){if(n==null)return null;if(typeof n=="number")return Number.isFinite(n)?String(n):null;let e=n.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 Ri(n){let{provider:e,srcChainId:t}=n,r=hp(t),o=hp(n.dstChainId??t);if(!r||!o||r===o||e!=="debridge")return 0n;let s=Uy[r];if(!s)return 0n;try{let a=await Re(r).readContract({address:s,abi:Dy,functionName:"globalFixedNativeFee"});return typeof a=="bigint"&&a>0n?a:0n}catch{return 0n}}var ue="0x0000000000000000000000000000000000000000",fp={"0x1":{hexId:"0x1",name:"Ethereum",defaultRpc:Qe["0x1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa":{hexId:"0xa",name:"Optimism",defaultRpc:Qe["0xa"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0x38":{hexId:"0x38",name:"BNB Smart Chain",defaultRpc:Qe["0x38"],native:{symbol:"BNB",name:"BNB",decimals:18,coingeckoId:"binancecoin"},defaultMintGasLimit:12e5},"0x89":{hexId:"0x89",name:"Polygon",defaultRpc:Qe["0x89"],native:{symbol:"POL",name:"Polygon",decimals:18,coingeckoId:"matic-network"},defaultMintGasLimit:12e5},"0x2105":{hexId:"0x2105",name:"Base",defaultRpc:Qe["0x2105"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa4b1":{hexId:"0xa4b1",name:"Arbitrum One",defaultRpc:Qe["0xa4b1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:22e5},"0xa86a":{hexId:"0xa86a",name:"Avalanche",defaultRpc:Qe["0xa86a"],native:{symbol:"AVAX",name:"Avalanche",decimals:18,coingeckoId:"avalanche-2"},defaultMintGasLimit:12e5},"0xe708":{hexId:"0xe708",name:"Linea",defaultRpc:Qe["0xe708"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5}};function mt(n){return fp[n.toLowerCase()]}function Io(n){return mt(n)?.native}var gp="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";function kc(n){let e=n.stableTicks??3,t=n.widePercent??{down:50,up:100},r=pt(n.currentTick,n.token0Decimals,n.token1Decimals),o=Rt(Ct(n.currentTick-e*n.tickSpacing,n.tickSpacing,"down")),s=Rt(Ct(n.currentTick+e*n.tickSpacing,n.tickSpacing,"up")),a=r*(1-t.down/100),i=r*(1+t.up/100),l=zn(a,n.token0Decimals,n.token1Decimals),c=zn(i,n.token0Decimals,n.token1Decimals),d=Rt(Ct(l,n.tickSpacing,"down")),u=Rt(Ct(c,n.tickSpacing,"up")),p=(m,f,h,g,b)=>{let y=pt(g,n.token0Decimals,n.token1Decimals),w=pt(b,n.token0Decimals,n.token1Decimals);return{id:m,label:f,description:h,tickLower:g,tickUpper:b,minPrice:y,maxPrice:w,minPercentChange:(y-r)/r*100,maxPercentChange:(w-r)/r*100}};return[p("stable","Stable","Good for stablecoins or low volatility pairs",o,s),p("wide","Wide","Good for volatile pairs",d,u)]}var le=class{swapFactory;constructor(e){this.swapFactory=e?.swapFactory??_o}isSupported(e){if(!e)return!1;let t=D(e);return!!t&&!!mt(t)}listSupportedChains(){return Object.keys(fp).filter(e=>qe(e))}getRpcUrl(e){let t=Mn(e);if(t)return t;let r=mt(e);if(!r)throw new Error(`Unsupported chain: ${e}`);return r.defaultRpc}async getGatewayAddress(e){return kn.getGatewayAddress(e)}async isAddLiquiditySupported(e){return this.isSupported(e)&&!!await this.getGatewayAddress(e)}async listAddLiquiditySupportedChains(){let e=await kn.getGatewayChains(),t=[];for(let r of e){let o=D(r);o&&mt(o)&&!t.includes(o)&&t.push(o)}return t.length>0?t:this.listSupportedChains()}async getPositionManagerAddress(e){return kn.getPositionManagerAddress(e)}client(e){return Re(e)}async ethCall(e,t,r){let{data:o}=await this.client(e).call({to:t,data:r});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 r=await this.getPositionManagerAddress(e);if(!r)return null;let o=r.toLowerCase();for(let s of t.logs??[]){if((s.address??"").toLowerCase()!==o)continue;let a=s.topics??[];if(!(a.length<4||a[0]?.toLowerCase()!==gp||"0x"+a[1].slice(-40).toLowerCase()!==ue))try{return BigInt(a[3]).toString()}catch{return null}}return null}async estimateGasReserveWei(e){let t=mt(e);if(!t)throw new Error(`Unsupported chain: ${e}`);let r=await this.getGasPrice(e);return BigInt(t.defaultMintGasLimit)*r*18n/10n}async readPoolOnchain(e,t){let o={address:t,abi:jl},[s,a,i,l,c,d]=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}),[u,p]=s,m=c.toLowerCase(),f=d.toLowerCase(),[h,g]=await Promise.all([this.readErc20Decimals(e,m),this.readErc20Decimals(e,f)]),b=ap(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()===ue?18:this.client(e).readContract({address:t,abi:q,functionName:"decimals"})}async getNativePriceUsd(e){let t=mt(e);if(!t)return null;try{let r=`https://api.coingecko.com/api/v3/simple/price?ids=${t.native.coingeckoId}&vs_currencies=usd`,o=await C.get(r);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:r,tickLower:o,tickUpper:s,token0Decimals:a,token1Decimals:i}=e,l=2**96,c=Number(r.sqrtPriceX96)/l,d=Math.pow(1.0001,o/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))),P=t*v/k,S=t-P;return{ratio0:y,ratio1:w,amountInFor0Wei:P,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 Oy={"0x1":"ethereum","0xa":"optimism","0x38":"bnb","0x89":"polygon","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avalanche"},My=/^0x[a-fA-F0-9]{40}$/;function Js(n,e){if(typeof n!="string"||typeof e!="string")return null;let t=Oy[n.toLowerCase()];return!t||!My.test(e)?null:`https://app.uniswap.org/explore/pools/${t}/${e}`}function ht(n,e){let t=Js(n,e);return t?{uniswapUrl:t}:{}}var yp=Object.keys(fn),nt="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 Oe(){return yp.filter(n=>qe(n)).map(n=>T(n)).join(", ")}function rt(){return{kind:"info",async listSupported(){return yp.filter(n=>qe(n))},async isSupported(n){if(!n)return!1;let e=D(n);return!!e&&Object.prototype.hasOwnProperty.call(fn,e)}}}function vn(n){return{kind:"add-liquidity",listSupported:()=>n.listAddLiquiditySupportedChains(),isSupported:e=>n.isAddLiquiditySupported(e)}}function vc(n,e,t){let r=o=>typeof o=="string"&&o.trim()!=="";if(r(n))return D(n)??n.trim();if(r(e?.chain))return D(e.chain)??e.chain.trim();if(r(e?.walletAddress))throw new ge(typeof e?.query=="string"?e.query:void 0,t);return Be}async function te(n,e,t){let r=await n.listSupported(),o=vc(e,t,r);return await n.isSupported(o)?{ok:!0,chain:o}:{ok:!1,result:Tc(o,r,n.kind)}}function Tc(n,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(n),supportedChains:e.map(o=>T(o))}}var Ei="{pair}";var Ee=[{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}],de=' 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 pe(n,e,t){return Ac(n,typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",t)}function Ac(n,e,t,r){let o=typeof r=="string"?r.trim():"",s=[];for(let a of n){if(s.length>=5)break;let i=a.token0?.symbol?.trim(),l=a.token1?.symbol?.trim();if(!i||!l)continue;let c=By(i,l,a.feeTierPercent);s.push({label:bp(e,c,`Add liquidity to ${Ei}`),prompt:bp(t,c,`add liquidity to ${Ei}`)+Fy(a.address,o)})}return s}function Fy(n,e){let r=[typeof n=="string"&&n.trim()?`Pool: ${n.trim()}`:"",e].filter(Boolean);return r.length>0?` (${r.join(" - ")})`:""}function By(n,e,t){let r=`${n}/${e}`;return typeof t=="number"&&Number.isFinite(t)?`${r} ${qy(t)}%`:r}function qy(n){return Number(n.toFixed(4)).toString()}function bp(n,e,t){return(n&&n.includes(Ei)?n:t).split(Ei).join(e).replace(/\s+/g," ").trim()}var me="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. ",he='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. ',we="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. ",Y="End with a brief reminder that yields fluctuate and concentrated LPs face impermanent loss (informational, not financial advice). ",j=`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 $y=["tvl","volume1Day","volume30Day","apr"],Hy=["V2","V3","V4"],Uo=class extends A{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: `+Oe();category="blockchain-data";parameters=[{name:"chain",type:"string",description:nt,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},...Ee];service;subgraphFallback;pool;constructor(e,t){super(),this.service=new He(e),this.subgraphFallback=new xe(t),this.pool=new le}async run(e,t){let r=e.forAddLiquidity===!0,o=r?vn(this.pool):rt(),s=await o.listSupported(),a=vc(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=!r&&e.multichain===!0;if(!d&&!await o.isSupported(a))return Tc(a,s,o.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)?pe(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). `:"")+me+`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. `+he+"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. "+we+Y+"Mention the chain and the sort metric in the intro line. "+j+(h.length>0?de:""),chain:a,protocolVersion:i,sortBy:l,source:m,count:f.length,pools:f.map(w=>({...w,...ht(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 r=e.tvlUsd,o=e.volume1DayUsd,s=typeof r=="number"&&r>0&&typeof o=="number"?t(o/r):void 0;return{...e,volumeToTvlRatio:s}}async fetchV3Fallback(e,t,r){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,r)}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:$(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(Hy.includes(t))return t}return"V3"}parseSortKey(e){if(typeof e=="string"){let t=e.trim();if($y.includes(t))return t}return"tvl"}formatPool(e){let t=e.isDynamicFee===!0||hn(e.feeTier);return{apr:$(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 Pc={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114},Vy={100:.01,500:.05,3e3:.3,1e4:1},Tn=class{coinPoolBaseUrl;constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}isSupported(e){let t=D(e);return!!(t&&Pc[t])}listSupportedChains(){return Object.keys(Pc).filter(e=>D(e)===e)}numericChainId(e){let t=D(e);return t?Pc[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="",d=""]=l.pair.toUpperCase().split("/");return i(c,s)&&i(d,a)||i(c,a)&&i(d,s)})}return o}async getByAddress(e){let t=this.numericChainId(e.chain);if(!t)return[];let r=e.poolAddress.toLowerCase();return(await this.fetchV2Items(t)).filter(s=>s.poolId?.toLowerCase()===r).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`,r=await C.get(t);if(!r.ok)throw new Error(_(r));return r.data?.data?.items||[]}catch{return[]}}mapV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,r=e.token1.decimal??18,o=P=>P==null||!Number.isFinite(P)?0:Math.pow(1.0001,P)*Math.pow(10,t-r),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,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=Vy[y]??y/1e4,k=$(e.apr)??$(e.aprAvg)??null,v=$(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:Se(u),maxPrice:Se(p),currentPrice:Se(m),baseToken:f,quoteToken:h}}}};function Wy(n){if(!(!n||n.length===0))return n.map(e=>({timestamp:e.timestamp,volumeUsd:e.value}))}function Yy(n,e){if(!(typeof n!="number"||typeof e!="number"||e<=0))return Math.round(n/e*1e3)/1e3}function Xn(n,e){let t=e!==void 0&&Array.from(e.values()).some(i=>i.safetyLevel!=null),r=n.totalLiquidity?.value,o=n.volume24h?.value,s=n.feeTier,a=ki(s,n.protocolFee,n.protocolVersion);return{address:n.address??n.poolId,protocolVersion:n.protocolVersion,poolId:n.poolId,tickSpacing:n.tickSpacing,isDynamicFee:n.isDynamicFee,hookAddress:n.hook?.address,feeTierBps:s,feeTierPercent:typeof s=="number"?s/1e4:void 0,tvlUsd:r,tvlChange24hPercent:n.totalLiquidityPercentChange24h?.value,volume24hUsd:o,fees24hUsd:vi(o,s,a),lpFeeShare:a,aprPercent:$(n.apr),totalAprPercent:$(n.totalApr),volumeToTvlRatio:Yy(o,r),txCount:n.txCount,historicalVolumeWeek:Wy(n.historicalVolume),token0:wp(n.token0,n.token0Supply,e,t),token1:wp(n.token1,n.token1Supply,e,t)}}function wp(n,e,t,r){if(!n)return;let o=n.address?t?.get(n.address.toLowerCase()):void 0,s=r&&n.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:n.address,symbol:n.symbol,name:n.name,decimals:n.decimals,priceUsd:n.market?.price?.value??n.price?.value,reserve:e,isSpam:a??n.project?.isSpam??void 0,safetyLevel:o?.safetyLevel??n.project?.safetyLevel??void 0,transferFeeBps:c>0?c:void 0,isUnrecognizedToken:s||void 0}}var kp=/^0x[a-fA-F0-9]{40}$/,Gy=6,Do=class extends A{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: "+Oe();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:nt,required:!1},...Ee];service;coinPool;pool;constructor(e,t){super(),this.service=new He(e),this.coinPool=new Tn(t),this.pool=new le}async run(e,t){let r=await te(rt(),e.chain,t);if(!r.ok)return r.result;let o=r.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 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(o)}. Verify the symbols and fee tier with the user.`};if(p.length===1){let g=p[0];if(!g.id||!kp.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:o}),this.fetchPriceRanges(o,g.id,g.token0?.symbol,g.token1?.symbol),this.service.getTokenSafetyByAddress([g.token0?.address,g.token1?.address],o)]);if(!b.success||!b.data)return{error:b.error||"Failed to fetch pool detail"};let k={...Xn(b.data,w),...ht(o,g.id)},v=await this.pool.isAddLiquiditySupported(o)?pe([k],e,T(o)):[];return{priceRanges:y,_instructions:me+"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. "+he+we+'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. '+Y+j+(v.length>0?de:""),pairOrderMatched:m?"reversed":"ordered",pool:k,...v.length>0?{actionButtons:v}:{}}}if(a){let g=this.rankCandidates(p).slice(0,Gy),[b,y]=await Promise.all([Promise.all(g.map(async k=>{if(!k.id||!kp.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(g.flatMap(k=>[k.token0?.address,k.token1?.address]),o)]),w=b.filter(k=>k!=null).map(k=>({...Xn(k.detail,y),...ht(o,k.id)}));if(w.length>0){let k=await this.pool.isAddLiquiditySupported(o)?pe(w,e,T(o)):[];return{_instructions:me+"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. "+he+"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. "+we+Y+j+(k.length>0?de:""),chain:o,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,...ht(o,b.address)}}),h=await this.pool.isAddLiquiditySupported(o)?pe(f,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?de:""),chain:o,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,r,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(r){let c=r.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,r){let o=t?`${e}/${t}`:e;return r!=null?`${o} at fee tier ${r} bps`:o}candidateReason(e,t,r){return t?r==null?`Multiple fee tiers exist for ${e}/${t}. Ask the user which fee tier they want.`:`Multiple ${e}/${t} pools share fee tier ${r} 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 r=[];return e||r.push("token1Symbol"),t==null&&r.push("feeTier"),r}rankCandidates(e){return[...e].sort((t,r)=>(r.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,r,o){try{if(!this.coinPool.isSupported(e))return[];let s=await this.coinPool.getByAddress({chain:e,poolAddress:t});return s.length===0&&r&&o&&(s=await this.coinPool.getPairs({chain:e,tokens:[r,o]})),s.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}};var Ky=["V2","V3","V4","ALL"],Oo=class extends A{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: '+Oe();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:nt,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},...Ee];service;pool;constructor(e){super(),this.service=new He(e),this.pool=new le}async run(e,t){let r=typeof e.query=="string"?e.query.trim():"";if(!r)return{error:"Search query is required"};let o=await te(rt(),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,d=await this.service.searchPools({query:r,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)?pe(u,e,T(s)):[];return{_instructions:me+"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. "+he+we+"When several pools share the searched token, finish with a clear TOP PICK among them. "+Y+"Mention the search query and chain in the intro. "+j+(p.length>0?de:""),query:r,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,...ht(s,m.address)})),...p.length>0?{actionButtons:p}:{}}}parseProtocolFilter(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(Ky.includes(t))return t}return"V3"}formatPool(e){let t=e.isDynamicFee===!0||hn(e.feeTier),r={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=$(e.apr);o!=null&&(r.apr=o),e.tvlUsd!=null&&(r.tvlUsd=e.tvlUsd);let s=e.volume1DayUsd??e.volumeUsd24hr;s!=null&&(r.volume24hUsd=s),e.volumeUsd6hr!=null&&(r.volume6hUsd=e.volumeUsd6hr),e.volumeUsd12hr!=null&&(r.volume12hUsd=e.volumeUsd12hr),e.txCount!=null&&(r.txCount=e.txCount),e.tvlUsd!=null&&e.tvlUsd>0&&s!=null&&(r.volumeToTvlRatio=Math.round(s/e.tvlUsd*1e3)/1e3);let a=e.token0,i=e.token1;return a&&(r.token0={address:a.address,symbol:a.symbol,name:a.name,decimals:a.decimals}),i&&(r.token1={address:i.address,symbol:i.symbol,name:i.name,decimals:i.decimals}),r}};var Mo=class extends A{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: `+Oe();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:nt,required:!1},...Ee];service;pool;constructor(e){super(),this.service=new He(e),this.pool=new le}async run(e,t){let r=await te(rt(),e.chain,t);if(!r.ok)return r.result;let o=r.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,r){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={...Xn(o.data,s),...ht(t,e.id)},l=await this.pool.isAddLiquiditySupported(t)?pe([i],r,T(t)):[];return{_instructions:`The address is a Uniswap ${a} pool. `+me+"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. "+he+we+Y+j+(l.length>0?de:""),resolvedAs:"pool",chain:t,protocolVersion:a,pool:i,...l.length>0?{actionButtons:l}:{}}}async handleTokenHit(e,t,r){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(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),...ht(t,u.id)})),d=await this.pool.isAddLiquiditySupported(t)?pe(c,r,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?de:""),resolvedAs:"token",chain:t,protocolVersion:"V3",token:this.formatToken(e),poolCount:l.length,pools:c,...d.length>0?{actionButtons:d}:{}}}findPoolByAddress(e,t){let r=t.toLowerCase();return e.find(o=>(o.id??"").toLowerCase()===r)}findTokenByAddress(e,t){let r=t.toLowerCase();return e.find(o=>(o.address??"").toLowerCase()===r)}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 _i=class{uniswap;constructor(e){this.uniswap=new He(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 vp=/^0x[a-fA-F0-9]{40}$/,Tp=/^0x[a-fA-F0-9]{64}$/,Qn=class extends A{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 _i(e),this.pool=new le(e?.pool),this.coinPool=new Tn(e?.coinPool),this.minProvideUsd=e?.minProvideUsd??.01}async execute(e,t){let r=`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:r,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:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let r=await te(vn(this.pool),e.chain,t);if(!r.ok)return r.result;let o=r.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=vp.test(l)||Tp.test(l)?l.toLowerCase():"",d=Tp.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=mt(o);if(!y)return{error:"unsupported_chain",chain:o,_instructions:`Chain ${o} is not supported by the add-liquidity flow.`};let w=Io(o);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(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(d)return this.unsupportedVersionResult({protocolVersion:"V4",token0:{symbol:s},token1:{symbol:a}},s,a,y.name);let P=await this.resolver.resolveCandidates({chain:o,token0Symbol:s,token1Symbol:a,protocolVersion:"V3",feeTier:c?void 0:i});if(P===null)return{error:"pool_search_failed"};let S=c?P.find(G=>typeof G.id=="string"&&G.id.toLowerCase()===c):void 0;if(c&&!S){let G=await this.findUnsupportedVersionPool(o,s,a,i,c);if(G)return this.unsupportedVersionResult(G,s,a,y.name)}let x=S??P.find(G=>this.matchesPairExact(G,s,a,i)),L=x?[]:P.filter(G=>this.matchesPair(G,s,a,i));if(!x&&L.length===0){let G=await this.findUnsupportedVersionPool(o,s,a,i,c);return G?this.unsupportedVersionResult(G,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(!x&&L.length>1){let G=L.map(Te=>{let rr=Te.volume1DayUsd??Te.volumeUsd24hr,fa=Te.tvlUsd,Fc=typeof rr=="number"&&typeof fa=="number"&&fa>0?rr/fa:void 0;return{address:Te.id,token0Symbol:Te.token0?.symbol,token1Symbol:Te.token1?.symbol,feeTier:Te.feeTier,feeTierPercent:Te.feeTier!=null?Te.feeTier/1e4:void 0,volume24hUsd:rr,tvlUsd:fa,...Fc!=null?{volumeToTvlRatio:Fc}:void 0,...Te.apr?{apr:Te.apr}:void 0}}).sort((Te,rr)=>(rr.volumeToTvlRatio??rr.apr??-1/0)-(Te.volumeToTvlRatio??Te.apr??-1/0)).slice(0,5),Qi=Ac(G.map(Te=>({token0:{symbol:Te.token0Symbol},token1:{symbol:Te.token1Symbol},feeTierPercent:Te.feeTierPercent,address:Te.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:G,count:G.length,...Qi.length>0?{actionButtons:Qi}:{},_instructions:me+"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. "+he+"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). "+we+Y+j+(Qi.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 E=x??L[0];if(!E.id||!vp.test(E.id))return{error:"invalid_pool_address"};let ke=this.fetchPriceRanges(o,E.id,E.token0?.symbol,E.token1?.symbol),V=await this.pool.readPoolOnchain(o,E.id),[z,fe,Ne]=await Promise.all([this.pool.getNativeBalance(o,v),this.pool.estimateGasReserveWei(o),this.pool.getNativePriceUsd(o)]),W=z>fe?z-fe:0n,J=Io(o),Ht=Number(W)/10**J.decimals,nr=Number(z)/10**J.decimals,Le=Ne!=null?Ht*Ne:null,[Ge,Vt]=await Promise.all([this.pool.readErc20Decimals(o,V.token0),this.pool.readErc20Decimals(o,V.token1)]),Ke={min:pt(yn,Ge,Vt),max:pt(Po,Ge,Vt)},Xe=null;z===0n?Xe="no_balance":Le!=null&&Le<this.minProvideUsd&&(Xe="insufficient_balance");let Pn=E.token0,Sn=E.token1,ha=[25,50,75,100].map(G=>({percent:G,amountWei:(W*BigInt(G)/100n).toString(),amount:Ht*(G/100)})),Lt=null,at=null;if(u!=null){at=u;let G=BigInt(Math.floor(at*10**J.decimals));G>0n&&(Lt=G.toString())}else if(p!=null&&Ne!=null&&Ne>0){at=p/Ne;let G=BigInt(Math.floor(at*10**J.decimals));G>0n&&(Lt=G.toString())}let Oc={address:ue,isNative:!0,symbol:J.symbol,name:J.name,decimals:J.decimals,priceUsd:Ne,balanceWei:z.toString(),balance:nr,gasReserveWei:fe.toString(),spendableWei:W.toString(),spendable:Ht,spendableUsd:Le,quickRates:ha,minProvideUsd:this.minProvideUsd,warning:Xe,warningMessage:Xe==="no_balance"?`You have no ${J.symbol} on ${y.name}. Top up to add liquidity.`:Xe==="insufficient_balance"?`Spendable ${J.symbol} is below the $${this.minProvideUsd} minimum.`:null,prefillAmount:at,prefillAmountWei:Lt},Mc=this.computePrefillRange({explicitMinPrice:g,explicitMaxPrice:b,rangeStrategy:h,currentPrice:V.currentPrice,currentTick:V.currentTick,tickSpacing:V.tickSpacing,token0Decimals:Ge,token1Decimals:Vt,priceBounds:Ke}),Qp={component:"AddLiquidityForm",props:{chain:{hexId:o,name:y.name},pool:{address:V.poolAddress,fee:V.fee,feePercent:V.fee/1e4,tickSpacing:V.tickSpacing,currentTick:V.currentTick,currentPrice:Se(V.currentPrice),sqrtPriceX96:V.sqrtPriceX96.toString(),token0:{address:V.token0,symbol:Pn?.symbol,name:Pn?.name,logo:Pn?.logo},token1:{address:V.token1,symbol:Sn?.symbol,name:Sn?.name,logo:Sn?.logo}},inputToken:Oc,priceBounds:Ke,prefillRange:Mc,gatewayAddress:k}},Jp=this.orientRangesToForm(await ke,V.currentPrice,Pn?.symbol,Sn?.symbol);return{ui:Qp,suggestedRanges:Jp,summary:this.buildSummary({chainName:y.name,pair:`${Pn?.symbol??s}/${Sn?.symbol??a}`,feePercent:V.fee/1e4,warning:Xe,minProvideUsd:this.minProvideUsd,nativeSymbol:J.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. '+Y+"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,r,o){try{if(!this.coinPool.isSupported(e))return[];let s=await this.coinPool.getByAddress({chain:e,poolAddress:t});return s.length===0&&r&&o&&(s=await this.coinPool.getPairs({chain:e,tokens:[r,o]})),s.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}orientRangesToForm(e,t,r,o){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:$(a.apr),minPrice:Se(d),maxPrice:Se(u),currentPrice:Se(p),baseSymbol:r,quoteSymbol:o}}).filter(a=>s(a.minPrice)&&s(a.maxPrice)):[]}unsupportedVersionResult(e,t,r,o){let s=e.protocolVersion??"V4";return{error:"unsupported_protocol_version",protocolVersion:s,pair:`${e.token0?.symbol??t}/${e.token1?.symbol??r}`,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,r,o,s){try{let a=await this.resolver.resolveCandidates({chain:e,token0Symbol:t,token1Symbol:r,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,r,o))??i.find(l=>this.matchesPair(l,t,r,o))}catch{return}}matchesPairExact(e,t,r,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=r.toLowerCase();return s===i&&a===l||s===l&&a===i}matchesPair(e,t,r,o){if(o!=null&&e.feeTier!==o)return!1;let s=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=r.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:r,rangeStrategy:o,currentPrice:s,priceBounds:a}=e;if(t!=null&&r!=null&&r>t){let{minPrice:i,maxPrice:l}=So(t,r,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=kc({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 jy=/^0x[a-fA-F0-9]{40}$/,Jn=class extends A{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 le(e?.pool),this.defaultSlippageBps=e?.defaultSlippageBps??"auto",this.mintMinPercent=e?.mintMinPercent??80,this.pantograph=new ye}async execute(e,t){let r=`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:r,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:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let r=typeof e.poolAddress=="string"?e.poolAddress.trim():"",o=await te(vn(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(!r||!s||!Number.isFinite(l)||!Number.isFinite(a)||!Number.isFinite(i))return{error:"missing_inputs",_instructions:"poolAddress, chain, minPrice, maxPrice, nativeAmount are all required."};if(!jy.test(r))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=mt(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=Io(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,r),[g,b]=await Promise.all([this.pool.readErc20Decimals(s,h.token0),this.pool.readErc20Decimals(s,h.token1)]),{minPrice:y,maxPrice:w}=So(a,i,h.currentPrice),k=y===0?yn:zn(y,g,b),v=zn(w,g,b),P=y===0?Rt(Ct(yn,h.tickSpacing,"up")):Rt(Ct(k,h.tickSpacing,"down")),S=Rt(Ct(v,h.tickSpacing,"up"));if(P>=S||P<yn||S>Po)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:P,tickUpper:S};let x={tickLower:P,tickUpper:S,minPrice:Se(pt(P,g,b)),maxPrice:Se(pt(S,g,b))},L=h.currentTick;if(L<P||L>=S){let Z=L<P?"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 ${Z==="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:Se(h.currentPrice),requestedRange:{minPrice:x.minPrice,maxPrice:x.maxPrice},side:Z}}let[E,ke,V]=await Promise.all([this.pool.getNativeBalance(s,p),this.pool.estimateGasReserveWei(s),this.pool.getNativePriceUsd(s)]),z=f+ke;if(E<z)return{error:"insufficient_balance",_instructions:"User does not have enough native coin (amount + gas reserve). Tell them the shortfall in their language.",balanceWei:E.toString(),requiredWei:z.toString(),gasReserveWei:ke.toString()};let fe=this.pool.splitNativeAmountForRange({nativeAmountWei:f,pool:h,tickLower:P,tickUpper:S,token0Decimals:g,token1Decimals:b}),Ne=h.token0.toLowerCase()===ue,W=h.token1.toLowerCase()===ue,J=[];if(Ne||fe.amountInFor0Wei===0n)J.push({tokenIn:ue,tokenOut:h.token0,amountIn:fe.amountInFor0Wei,tx:{to:ue,data:"0x",value:"0"},minAmountOut:Ne?fe.amountInFor0Wei:0n});else{let Z=await this.pool.fetchSwapLeg({senderAddress:p,chainId:s,tokenIn:ue,tokenInAmount:fe.amountInFor0Wei.toString(),tokenOut:h.token0,tokenOutRecipient:u,slippage:typeof c=="number"?c:"auto"});J.push({tokenIn:ue,tokenOut:h.token0,amountIn:fe.amountInFor0Wei,tx:{to:Z.to,data:Z.data,value:Z.value},minAmountOut:BigInt(Z.minAmountOut||"0")})}if(W||fe.amountInFor1Wei===0n)J.push({tokenIn:ue,tokenOut:h.token1,amountIn:fe.amountInFor1Wei,tx:{to:ue,data:"0x",value:"0"},minAmountOut:W?fe.amountInFor1Wei:0n});else{let Z=await this.pool.fetchSwapLeg({senderAddress:p,chainId:s,tokenIn:ue,tokenInAmount:fe.amountInFor1Wei.toString(),tokenOut:h.token1,tokenOutRecipient:u,slippage:typeof c=="number"?c:"auto"});J.push({tokenIn:ue,tokenOut:h.token1,amountIn:fe.amountInFor1Wei,tx:{to:Z.to,data:Z.data,value:Z.value},minAmountOut:BigInt(Z.minAmountOut||"0")})}let Ht=Z=>Z*BigInt(this.mintMinPercent)/100n,nr=Ht(J[0].minAmountOut),Le=Ht(J[1].minAmountOut),Ge=J.map(Z=>({tokenIn:Z.tokenIn,tokenInAmount:BigInt(Z.amountIn),tokenOut:Z.tokenOut,tokenOutAmount:BigInt(Z.minAmountOut)})),Vt=J.map(Z=>({to:Z.tx.to,data:Z.tx.data,value:BigInt(Z.tx.value||"0")})),Ke=M({abi:Kl,functionName:"mint",args:[Ge,Vt,{fee:Number(h.fee),amount0Min:BigInt(nr),amount1Min:BigInt(Le),tickLower:P,tickUpper:S}]}),Xe=l,Pn={chainId:s,to:u,data:Ke,value:f.toString(),from:p},Sn={nativeIn:Xe,nativeSymbol:m.symbol,nativeInUsd:V!=null?Xe*V:null,ratio:{token0Percent:fe.ratio0,token1Percent:fe.ratio1},expectedToken0:Number(J[0].minAmountOut)/10**g,expectedToken1:Number(J[1].minAmountOut)/10**b,amount0Min:nr.toString(),amount1Min:Le.toString(),slippageBps:c},ha=await this.pantograph.getTokensMetadata([h.token0,h.token1],s),Lt=ha[h.token0],at=ha[h.token1];return{ui:{component:"ConfirmAddLiquidityTx",props:{chain:{hexId:s,name:d.name},unsignedTx:Pn,summary:Sn,pool:{...h,feePercent:h.fee/1e4,currentPrice:Se(h.currentPrice),token0:{address:h.token0,symbol:Lt?.auditGoplus?.token_symbol||Lt.symbol,name:Lt.name,decimals:Lt.decimals,logo:Lt.icon_image},token1:{address:h.token1,symbol:at?.auditGoplus?.token_symbol||at.symbol,name:at.name,decimals:at.decimals,logo:at.icon_image}},range:x,gatewayAddress:u}},summary:`Ready to add ${Xe} ${m.symbol} to pool ${h.token0}/${h.token1} ${h.fee/1e4}% on ${d.name}, range [${x.minPrice}, ${x.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 zy=365,Xy=1e3,Qy=/^0x[a-fA-F0-9]{40}$/;function Jy(n,e){return{depositUsd:n,aprPercent:e*100,dailyUsd:n*e/zy,weeklyUsd:n*e/52,monthlyUsd:n*e/12,yearlyUsd:n*e}}var Fo=class extends A{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):
|
|
205
|
+
}`,o=await this.querySubgraph(t,r);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,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 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 r=e.poolAddress.toLowerCase();return(await this.fetchCoinPoolV2Items(t)).filter(s=>s.poolId?.toLowerCase()===r).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`,r=await C.get(t);if(!r.ok)throw new Error(_(r));return r.data?.data?.items||[]}catch{return[]}}mapCoinPoolV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,r=e.token1.decimal??18,o=P=>P==null||!Number.isFinite(P)?0:Math.pow(1.0001,P)*Math.pow(10,t-r),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,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=cp[y]??y/1e4,k=$(e.apr)??$(e.aprAvg)??null,v=$(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:Se(u),maxPrice:Se(p),currentPrice:Se(m),baseToken:f,quoteToken:h}}}};var yn=class{config;constructor(e){this.config=e}withRoute(e){let t=Object.create(this);return t.getQuote=r=>this.getQuote({route:e,...r}),t}};var _t=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 gy="https://api.relay.link";function up(n){return n===7565164||n==="7565164"?792703809:n}var Co=class extends yn{apiBaseUrl;apiKey;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??gy,this.apiKey=e.apiKey}getProviderName(){return"relay"}hasIntegratedApproval(){return!0}async getQuote(e){let{srcChainId:t,srcTokenAddress:r,srcTokenAmount:o,dstChainId:s,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c}=e,d=await bn.getAffiliateFee(this.getProviderName(),t,e.route),u={user:i||l,originChainId:up(t),destinationChainId:up(s),originCurrency:r,destinationCurrency:a,amount:o,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,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 r=(await this.request("/intents/status/v3","GET",{requestId:e.requestIdOrTxHash})).status??"";return r==="success"||r==="refunded"?{success:!0,status:"COMPLETED"}:r==="failure"||r==="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,r){let o={"Content-Type":"application/json"};this.apiKey&&(o["x-api-key"]=this.apiKey);let s=`${this.apiBaseUrl}${e}`,a;if(t==="GET"&&r){let l=Object.entries(r).map(([c,d])=>`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`).join("&");s=`${s}?${l}`}else t==="POST"&&r&&(a=r);let i=await C.request(t,s,a,{headers:o});if(!i.ok)throw new Error(_(i));return i.data}};var yy="https://api.coinpool.app/config/addresses",by="https://api.coinpool.app/config/bridgeProviderByChain",dp="createPoolProxyV3",wy="nftPositionUniswap",ky=/^0x[0-9a-fA-F]{40}$/,js=class{addresses;providerMap;constructor(e=yy,t=by){this.addresses=new _t(async()=>(await C.get(e,{headers:{Accept:"application/json"}})).data?.data??null),this.providerMap=new _t(async()=>(await C.get(t,{headers:{Accept:"application/json"}})).data?.data??null)}async getProviderByChain(e){let r=(await this.providerMap.get())?.[String(e)];return this.isProviderName(r)?r:null}async getGatewayAddress(e){return this.getAddress(dp,e)}async getPositionManagerAddress(e){return this.getAddress(wy,e)}async getGatewayChains(){return this.listChainsWithAddress(dp)}async getAddress(e,t){let r=await this.addresses.get();if(!r)return;let o=this.toDecimalChainKey(t);if(o)return this.firstAddress(r[e]?.[o])}async listChainsWithAddress(e){let t=(await this.addresses.get())?.[e];if(!t||typeof t!="object")return[];let r=[];for(let[o,s]of Object.entries(t)){let a=this.firstAddress(s);a&&ky.test(a)&&r.push(o)}return r}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 r=Number.parseInt(t,16);return Number.isFinite(r)?String(r):null}return/^\d+$/.test(t)?t:null}isProviderName(e){return e==="debridge"||e==="relay"}},wn=new js;var Ro=class{async resolve(e){try{return await this.resolveProvider(e)??Bt}catch{return Bt}}toNumericChainId(e){if(e==null)return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}},Eo=class extends Ro{constructor(t=wn){super();this.config=t}config;route="pool";async resolveProvider({srcChainId:t}){let r=this.toNumericChainId(t);return r===null?null:this.config.getProviderByChain(r)}},_o=class extends Ro{constructor(t=bn){super();this.setting=t}setting;route="userSwap";async resolveProvider({srcChainId:t,dstChainId:r}){return this.setting.getBridgeProvider(t,r)}};var zs=class{routers=new Map;constructor(e=[new Eo,new _o]){for(let t of e)this.routers.set(t.route,t)}async resolveProvider(e){return await this.routers.get(e.route)?.resolve(e)??Bt}},Pi=new zs;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??Pi}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 r=this.createService(e);return this.cache.set(e,r),r}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 Io(t);case"relay":return new Co(t);default:{let r=e;throw new Error(`Unknown swap provider: ${String(r)}`)}}}},No=new Xs;var Lo={debridge:{apiBaseUrl:"https://dln.debridge.finance/v1.0",accessToken:"d6c45897b8f6"},relay:{apiBaseUrl:"https://api.relay.link"}},Bt="relay";function Si(n,e){let t={...Lo[n]??{},...e};for(let r of Object.keys(t))t[r]===void 0&&delete t[r];Lo[n]=t,No.resetCache()}var vy="https://exchange-api.keyring.app/admin/setting?configs=others",Ty="https://api.relay.link/chains",Ay="https://dln.debridge.finance/v1.0/supported-chains-info",Py=14400*1e3,Sy=300*1e3,xy=new Set([728126428,7565164]),pp={relay:"relay",debridge:"deBridge"},Qs=class{setting;chainSupport;constructor(e=vy){this.setting=new _t(async()=>(await C.get(e,{headers:{Accept:"application/json"}})).data?.others??null,Sy),this.chainSupport=new _t(async()=>this.fetchChainSupport(),Py)}async getBridgeProvider(e,t){let r=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)??Bt;if(!r||!o||!a)return i;let l=this.requireChainKeys(s?.keyringV2,"debridge"),c=l.includes(r)||l.includes(o),d=a.debridge.has(r)&&a.debridge.has(o);return c&&d?"debridge":i}async getAffiliateFee(e,t,r="userSwap"){let o=await this.setting.get();if(!o)return null;let s=r==="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,r){return t==="debridge"?{recipient:this.parseRecipientMap(e.affiliateRecipient)?.[String(r)],percent:this.toPercent(e.AFFILIATE_FEE_PERENT)}:{recipient:e.RELAY_AFFILIATE_FEE_RECIPIENT,percent:this.toPercent(e.RELAY_AFFILIATE_FEE_PERCENT)}}resolveKeyringV2Fee(e,t,r){let o=e.keyringV2;if(!o)return{recipient:void 0,percent:0};let s=o[pp[t]],a=String(r);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([C.get(Ty,{headers:{Accept:"application/json"}}),C.get(Ay,{headers:{Accept:"application/json"}})]),r=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&&r.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||xy.has(a))continue;let i=this.toChainKey(a);i&&o.add(i)}return{relay:r,debridge:o}}requireChainKeys(e,t){return(e?.[pp[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 r=/^0x/i.test(t)?Number.parseInt(t,16):Number(t);return Number.isFinite(r)?String(r):null}toPercent(e){if(e==null)return 0;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:0}},bn=new Qs;function xi(n,e){return M({abi:q,functionName:"approve",args:[n,e]})}async function Cy(n,e,t,r,o){try{return await Re(n).call({account:t,to:e,data:xi(r,o)}),!0}catch(s){return Ry(s)?!1:null}}function Ry(n){let e=n?.name??"";if(e==="ContractFunctionRevertedError"||e==="CallExecutionError")return!0;let t=n instanceof Error?n.message.toLowerCase():String(n??"").toLowerCase();return t.includes("revert")||t.includes("execution reverted")||t.includes("invalid opcode")||t.includes("out of gas")}async function Ci({chain:n,token:e,owner:t,spender:r,amount:o,allowance:s}){let a=l=>({to:e,from:t,data:xi(r,l),value:"0"});return s!=null&&s>=o?[]:s===0n||!n?[a(o)]:await Cy(n,e,t,r,o)===!1?[a(0n),a(o)]:[a(o)]}var Ey="https://dln.debridge.finance/v1.0",_y="0x0000000000000000000000000000000000000000",Ny=new Set([429,500]),Ly=5,Iy=1e3,Uy=n=>new Promise(e=>setTimeout(e,n)),Io=class extends yn{apiBaseUrl;accessToken;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Ey,this.accessToken=e.accessToken??"d6c45897b8f6"}getProviderName(){return"debridge"}hasIntegratedApproval(){return!1}async getQuote(e){let{srcChainId:t,srcTokenAddress:r,srcTokenAmount:o,dstChainId:s,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c,isCrossChain:d}=e,u=d??t!==s,p=await bn.getAffiliateFee(this.getProviderName(),t,e.route);try{if(u){let h={srcChainId:String(t),srcChainTokenIn:r,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 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:r,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 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:r,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()===_y)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,r,a);if(l!==null&&l>=i)return{isNeeded:!1,integrated:!1,approvals:[],contractAddress:a,message:"Sufficient allowance already granted."};let c=await Ci({chain:t,token:o,owner:r,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,r,o){if(!e)return null;try{return await Re(e).readContract({address:t,abi:q,functionName:"allowance",args:[r,o]})}catch{return null}}async trackTransaction(e){let{requestIdOrTxHash:t}=e;try{let r=await this.get(`${this.apiBaseUrl}/dln/tx/${t}/order-ids`,{accesstoken:this.accessToken});if(!r.orderIds?.length)return{success:!1,status:"PENDING"};let o=r.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(r){return{success:!1,status:"ERROR",error:r instanceof Error?r.message:String(r)}}}async get(e,t){let r=Object.entries(t).map(([a,i])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(i))}`).join("&"),o=r?`${e}?${r}`:e,s=await C.get(o,{headers:{Accept:"application/json"}});for(let a=0;a<Ly&&Ny.has(s.status);a++)await Uy(Iy),s=await C.get(o,{headers:{Accept:"application/json"}});return s.data}};function mp(n){let e=n.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 hp(n){if(n.errorMessage&&n.errorMessage.trim())return n.errorMessage.trim();let e=r=>{if(typeof r=="string"&&r.trim())return r.trim();if(r&&typeof r=="object"){let o=r;for(let s of[o.message,o.errorMessage,o.error])if(typeof s=="string"&&s.trim())return s.trim()}},t=n.raw??{};return e(n.error)??e(t.errorMessage)??e(t.error)??"The swap could not be quoted right now."}var Dy={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"},Oy=[{inputs:[],name:"globalFixedNativeFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}];function fp(n){if(n==null)return null;if(typeof n=="number")return Number.isFinite(n)?String(n):null;let e=n.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 Ri(n){let{provider:e,srcChainId:t}=n,r=fp(t),o=fp(n.dstChainId??t);if(!r||!o||r===o||e!=="debridge")return 0n;let s=Dy[r];if(!s)return 0n;try{let a=await Re(r).readContract({address:s,abi:Oy,functionName:"globalFixedNativeFee"});return typeof a=="bigint"&&a>0n?a:0n}catch{return 0n}}var le="0x0000000000000000000000000000000000000000",gp={"0x1":{hexId:"0x1",name:"Ethereum",defaultRpc:Je["0x1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa":{hexId:"0xa",name:"Optimism",defaultRpc:Je["0xa"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0x38":{hexId:"0x38",name:"BNB Smart Chain",defaultRpc:Je["0x38"],native:{symbol:"BNB",name:"BNB",decimals:18,coingeckoId:"binancecoin"},defaultMintGasLimit:12e5},"0x89":{hexId:"0x89",name:"Polygon",defaultRpc:Je["0x89"],native:{symbol:"POL",name:"Polygon",decimals:18,coingeckoId:"matic-network"},defaultMintGasLimit:12e5},"0x2105":{hexId:"0x2105",name:"Base",defaultRpc:Je["0x2105"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa4b1":{hexId:"0xa4b1",name:"Arbitrum One",defaultRpc:Je["0xa4b1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:22e5},"0xa86a":{hexId:"0xa86a",name:"Avalanche",defaultRpc:Je["0xa86a"],native:{symbol:"AVAX",name:"Avalanche",decimals:18,coingeckoId:"avalanche-2"},defaultMintGasLimit:12e5},"0xe708":{hexId:"0xe708",name:"Linea",defaultRpc:Je["0xe708"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5}};function mt(n){return gp[n.toLowerCase()]}function jn(n){return mt(n)?.native}var yp="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";function kc(n){let e=n.stableTicks??3,t=n.widePercent??{down:50,up:100},r=pt(n.currentTick,n.token0Decimals,n.token1Decimals),o=Et(Rt(n.currentTick-e*n.tickSpacing,n.tickSpacing,"down")),s=Et(Rt(n.currentTick+e*n.tickSpacing,n.tickSpacing,"up")),a=r*(1-t.down/100),i=r*(1+t.up/100),l=Kn(a,n.token0Decimals,n.token1Decimals),c=Kn(i,n.token0Decimals,n.token1Decimals),d=Et(Rt(l,n.tickSpacing,"down")),u=Et(Rt(c,n.tickSpacing,"up")),p=(m,f,h,g,b)=>{let y=pt(g,n.token0Decimals,n.token1Decimals),w=pt(b,n.token0Decimals,n.token1Decimals);return{id:m,label:f,description:h,tickLower:g,tickUpper:b,minPrice:y,maxPrice:w,minPercentChange:(y-r)/r*100,maxPercentChange:(w-r)/r*100}};return[p("stable","Stable","Good for stablecoins or low volatility pairs",o,s),p("wide","Wide","Good for volatile pairs",d,u)]}var ce=class{swapFactory;constructor(e){this.swapFactory=e?.swapFactory??No}isSupported(e){if(!e)return!1;let t=D(e);return!!t&&!!mt(t)}listSupportedChains(){return Object.keys(gp).filter(e=>qe(e))}getRpcUrl(e){let t=Dn(e);if(t)return t;let r=mt(e);if(!r)throw new Error(`Unsupported chain: ${e}`);return r.defaultRpc}async getGatewayAddress(e){return wn.getGatewayAddress(e)}async isAddLiquiditySupported(e){return this.isSupported(e)&&!!await this.getGatewayAddress(e)}async listAddLiquiditySupportedChains(){let e=await wn.getGatewayChains(),t=[];for(let r of e){let o=D(r);o&&mt(o)&&!t.includes(o)&&t.push(o)}return t.length>0?t:this.listSupportedChains()}async getPositionManagerAddress(e){return wn.getPositionManagerAddress(e)}client(e){return Re(e)}async ethCall(e,t,r){let{data:o}=await this.client(e).call({to:t,data:r});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 r=await this.getPositionManagerAddress(e);if(!r)return null;let o=r.toLowerCase();for(let s of t.logs??[]){if((s.address??"").toLowerCase()!==o)continue;let a=s.topics??[];if(!(a.length<4||a[0]?.toLowerCase()!==yp||"0x"+a[1].slice(-40).toLowerCase()!==le))try{return BigInt(a[3]).toString()}catch{return null}}return null}async estimateGasReserveWei(e){let t=mt(e);if(!t)throw new Error(`Unsupported chain: ${e}`);let r=await this.getGasPrice(e);return BigInt(t.defaultMintGasLimit)*r*18n/10n}async readPoolOnchain(e,t){let o={address:t,abi:jl},[s,a,i,l,c,d]=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}),[u,p]=s,m=c.toLowerCase(),f=d.toLowerCase(),[h,g]=await Promise.all([this.readErc20Decimals(e,m),this.readErc20Decimals(e,f)]),b=ip(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:q,functionName:"decimals"})}async getNativePriceUsd(e){let t=mt(e);if(!t)return null;try{let r=`https://api.coingecko.com/api/v3/simple/price?ids=${t.native.coingeckoId}&vs_currencies=usd`,o=await C.get(r);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:r,tickLower:o,tickUpper:s,token0Decimals:a,token1Decimals:i}=e,l=2**96,c=Number(r.sqrtPriceX96)/l,d=Math.pow(1.0001,o/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))),P=t*v/k,S=t-P;return{ratio0:y,ratio1:w,amountInFor0Wei:P,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 My={"0x1":"ethereum","0xa":"optimism","0x38":"bnb","0x89":"polygon","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avalanche"},Fy=/^0x[a-fA-F0-9]{40}$/;function Js(n,e){if(typeof n!="string"||typeof e!="string")return null;let t=My[n.toLowerCase()];return!t||!Fy.test(e)?null:`https://app.uniswap.org/explore/pools/${t}/${e}`}function ht(n,e){let t=Js(n,e);return t?{uniswapUrl:t}:{}}var bp=Object.keys(hn),rt="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 Oe(){return bp.filter(n=>qe(n)).map(n=>T(n)).join(", ")}function ot(){return{kind:"info",async listSupported(){return bp.filter(n=>qe(n))},async isSupported(n){if(!n)return!1;let e=D(n);return!!e&&Object.prototype.hasOwnProperty.call(hn,e)}}}function kn(n){return{kind:"add-liquidity",listSupported:()=>n.listAddLiquiditySupportedChains(),isSupported:e=>n.isAddLiquiditySupported(e)}}function vc(n,e,t){let r=o=>typeof o=="string"&&o.trim()!=="";if(r(n))return D(n)??n.trim();if(r(e?.chain))return D(e.chain)??e.chain.trim();if(r(e?.walletAddress))throw new ge(typeof e?.query=="string"?e.query:void 0,t);return Be}async function te(n,e,t){let r=await n.listSupported(),o=vc(e,t,r);return await n.isSupported(o)?{ok:!0,chain:o}:{ok:!1,result:Tc(o,r,n.kind)}}function Tc(n,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(n),supportedChains:e.map(o=>T(o))}}var Ei="{pair}";var Ee=[{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}],de=' 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 pe(n,e,t){return Ac(n,typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",t)}function Ac(n,e,t,r){let o=typeof r=="string"?r.trim():"",s=[];for(let a of n){if(s.length>=5)break;let i=a.token0?.symbol?.trim(),l=a.token1?.symbol?.trim();if(!i||!l)continue;let c=qy(i,l,a.feeTierPercent);s.push({label:wp(e,c,`Add liquidity to ${Ei}`),prompt:wp(t,c,`add liquidity to ${Ei}`)+By(a.address,o)})}return s}function By(n,e){let r=[typeof n=="string"&&n.trim()?`Pool: ${n.trim()}`:"",e].filter(Boolean);return r.length>0?` (${r.join(" - ")})`:""}function qy(n,e,t){let r=`${n}/${e}`;return typeof t=="number"&&Number.isFinite(t)?`${r} ${$y(t)}%`:r}function $y(n){return Number(n.toFixed(4)).toString()}function wp(n,e,t){return(n&&n.includes(Ei)?n:t).split(Ei).join(e).replace(/\s+/g," ").trim()}var me="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. ",he='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. ',we="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. ",Y="End with a brief reminder that yields fluctuate and concentrated LPs face impermanent loss (informational, not financial advice). ",j=`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 Hy=["tvl","volume1Day","volume30Day","apr"],Vy=["V2","V3","V4"],Uo=class extends A{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: `+Oe();category="blockchain-data";parameters=[{name:"chain",type:"string",description:rt,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},...Ee];service;subgraphFallback;pool;constructor(e,t){super(),this.service=new He(e),this.subgraphFallback=new xe(t),this.pool=new ce}async run(e,t){let r=e.forAddLiquidity===!0,o=r?kn(this.pool):ot(),s=await o.listSupported(),a=vc(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=!r&&e.multichain===!0;if(!d&&!await o.isSupported(a))return Tc(a,s,o.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)?pe(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). `:"")+me+`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. `+he+"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. "+we+Y+"Mention the chain and the sort metric in the intro line. "+j+(h.length>0?de:""),chain:a,protocolVersion:i,sortBy:l,source:m,count:f.length,pools:f.map(w=>({...w,...ht(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 r=e.tvlUsd,o=e.volume1DayUsd,s=typeof r=="number"&&r>0&&typeof o=="number"?t(o/r):void 0;return{...e,volumeToTvlRatio:s}}async fetchV3Fallback(e,t,r){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,r)}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:$(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(Vy.includes(t))return t}return"V3"}parseSortKey(e){if(typeof e=="string"){let t=e.trim();if(Hy.includes(t))return t}return"tvl"}formatPool(e){let t=e.isDynamicFee===!0||mn(e.feeTier);return{apr:$(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 Pc={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114},Wy={100:.01,500:.05,3e3:.3,1e4:1},vn=class{coinPoolBaseUrl;constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}isSupported(e){let t=D(e);return!!(t&&Pc[t])}listSupportedChains(){return Object.keys(Pc).filter(e=>D(e)===e)}numericChainId(e){let t=D(e);return t?Pc[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="",d=""]=l.pair.toUpperCase().split("/");return i(c,s)&&i(d,a)||i(c,a)&&i(d,s)})}return o}async getByAddress(e){let t=this.numericChainId(e.chain);if(!t)return[];let r=e.poolAddress.toLowerCase();return(await this.fetchV2Items(t)).filter(s=>s.poolId?.toLowerCase()===r).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`,r=await C.get(t);if(!r.ok)throw new Error(_(r));return r.data?.data?.items||[]}catch{return[]}}mapV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,r=e.token1.decimal??18,o=P=>P==null||!Number.isFinite(P)?0:Math.pow(1.0001,P)*Math.pow(10,t-r),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,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=Wy[y]??y/1e4,k=$(e.apr)??$(e.aprAvg)??null,v=$(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:Se(u),maxPrice:Se(p),currentPrice:Se(m),baseToken:f,quoteToken:h}}}};function Yy(n){if(!(!n||n.length===0))return n.map(e=>({timestamp:e.timestamp,volumeUsd:e.value}))}function Gy(n,e){if(!(typeof n!="number"||typeof e!="number"||e<=0))return Math.round(n/e*1e3)/1e3}function zn(n,e){let t=e!==void 0&&Array.from(e.values()).some(i=>i.safetyLevel!=null),r=n.totalLiquidity?.value,o=n.volume24h?.value,s=n.feeTier,a=ki(s,n.protocolFee,n.protocolVersion);return{address:n.address??n.poolId,protocolVersion:n.protocolVersion,poolId:n.poolId,tickSpacing:n.tickSpacing,isDynamicFee:n.isDynamicFee,hookAddress:n.hook?.address,feeTierBps:s,feeTierPercent:typeof s=="number"?s/1e4:void 0,tvlUsd:r,tvlChange24hPercent:n.totalLiquidityPercentChange24h?.value,volume24hUsd:o,fees24hUsd:vi(o,s,a),lpFeeShare:a,aprPercent:$(n.apr),totalAprPercent:$(n.totalApr),volumeToTvlRatio:Gy(o,r),txCount:n.txCount,historicalVolumeWeek:Yy(n.historicalVolume),token0:kp(n.token0,n.token0Supply,e,t),token1:kp(n.token1,n.token1Supply,e,t)}}function kp(n,e,t,r){if(!n)return;let o=n.address?t?.get(n.address.toLowerCase()):void 0,s=r&&n.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:n.address,symbol:n.symbol,name:n.name,decimals:n.decimals,priceUsd:n.market?.price?.value??n.price?.value,reserve:e,isSpam:a??n.project?.isSpam??void 0,safetyLevel:o?.safetyLevel??n.project?.safetyLevel??void 0,transferFeeBps:c>0?c:void 0,isUnrecognizedToken:s||void 0}}var vp=/^0x[a-fA-F0-9]{40}$/,Ky=6,Do=class extends A{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: "+Oe();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:rt,required:!1},...Ee];service;coinPool;pool;constructor(e,t){super(),this.service=new He(e),this.coinPool=new vn(t),this.pool=new ce}async run(e,t){let r=await te(ot(),e.chain,t);if(!r.ok)return r.result;let o=r.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 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(o)}. Verify the symbols and fee tier with the user.`};if(p.length===1){let g=p[0];if(!g.id||!vp.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:o}),this.fetchPriceRanges(o,g.id,g.token0?.symbol,g.token1?.symbol),this.service.getTokenSafetyByAddress([g.token0?.address,g.token1?.address],o)]);if(!b.success||!b.data)return{error:b.error||"Failed to fetch pool detail"};let k={...zn(b.data,w),...ht(o,g.id)},v=await this.pool.isAddLiquiditySupported(o)?pe([k],e,T(o)):[];return{priceRanges:y,_instructions:me+"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. "+he+we+'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. '+Y+j+(v.length>0?de:""),pairOrderMatched:m?"reversed":"ordered",pool:k,...v.length>0?{actionButtons:v}:{}}}if(a){let g=this.rankCandidates(p).slice(0,Ky),[b,y]=await Promise.all([Promise.all(g.map(async k=>{if(!k.id||!vp.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(g.flatMap(k=>[k.token0?.address,k.token1?.address]),o)]),w=b.filter(k=>k!=null).map(k=>({...zn(k.detail,y),...ht(o,k.id)}));if(w.length>0){let k=await this.pool.isAddLiquiditySupported(o)?pe(w,e,T(o)):[];return{_instructions:me+"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. "+he+"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. "+we+Y+j+(k.length>0?de:""),chain:o,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,...ht(o,b.address)}}),h=await this.pool.isAddLiquiditySupported(o)?pe(f,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?de:""),chain:o,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,r,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(r){let c=r.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,r){let o=t?`${e}/${t}`:e;return r!=null?`${o} at fee tier ${r} bps`:o}candidateReason(e,t,r){return t?r==null?`Multiple fee tiers exist for ${e}/${t}. Ask the user which fee tier they want.`:`Multiple ${e}/${t} pools share fee tier ${r} 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 r=[];return e||r.push("token1Symbol"),t==null&&r.push("feeTier"),r}rankCandidates(e){return[...e].sort((t,r)=>(r.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,r,o){try{if(!this.coinPool.isSupported(e))return[];let s=await this.coinPool.getByAddress({chain:e,poolAddress:t});return s.length===0&&r&&o&&(s=await this.coinPool.getPairs({chain:e,tokens:[r,o]})),s.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}};var jy=["V2","V3","V4","ALL"],Oo=class extends A{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: '+Oe();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:rt,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},...Ee];service;pool;constructor(e){super(),this.service=new He(e),this.pool=new ce}async run(e,t){let r=typeof e.query=="string"?e.query.trim():"";if(!r)return{error:"Search query is required"};let o=await te(ot(),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,d=await this.service.searchPools({query:r,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)?pe(u,e,T(s)):[];return{_instructions:me+"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. "+he+we+"When several pools share the searched token, finish with a clear TOP PICK among them. "+Y+"Mention the search query and chain in the intro. "+j+(p.length>0?de:""),query:r,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,...ht(s,m.address)})),...p.length>0?{actionButtons:p}:{}}}parseProtocolFilter(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(jy.includes(t))return t}return"V3"}formatPool(e){let t=e.isDynamicFee===!0||mn(e.feeTier),r={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=$(e.apr);o!=null&&(r.apr=o),e.tvlUsd!=null&&(r.tvlUsd=e.tvlUsd);let s=e.volume1DayUsd??e.volumeUsd24hr;s!=null&&(r.volume24hUsd=s),e.volumeUsd6hr!=null&&(r.volume6hUsd=e.volumeUsd6hr),e.volumeUsd12hr!=null&&(r.volume12hUsd=e.volumeUsd12hr),e.txCount!=null&&(r.txCount=e.txCount),e.tvlUsd!=null&&e.tvlUsd>0&&s!=null&&(r.volumeToTvlRatio=Math.round(s/e.tvlUsd*1e3)/1e3);let a=e.token0,i=e.token1;return a&&(r.token0={address:a.address,symbol:a.symbol,name:a.name,decimals:a.decimals}),i&&(r.token1={address:i.address,symbol:i.symbol,name:i.name,decimals:i.decimals}),r}};var Mo=class extends A{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: `+Oe();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:rt,required:!1},...Ee];service;pool;constructor(e){super(),this.service=new He(e),this.pool=new ce}async run(e,t){let r=await te(ot(),e.chain,t);if(!r.ok)return r.result;let o=r.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,r){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={...zn(o.data,s),...ht(t,e.id)},l=await this.pool.isAddLiquiditySupported(t)?pe([i],r,T(t)):[];return{_instructions:`The address is a Uniswap ${a} pool. `+me+"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. "+he+we+Y+j+(l.length>0?de:""),resolvedAs:"pool",chain:t,protocolVersion:a,pool:i,...l.length>0?{actionButtons:l}:{}}}async handleTokenHit(e,t,r){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(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),...ht(t,u.id)})),d=await this.pool.isAddLiquiditySupported(t)?pe(c,r,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?de:""),resolvedAs:"token",chain:t,protocolVersion:"V3",token:this.formatToken(e),poolCount:l.length,pools:c,...d.length>0?{actionButtons:d}:{}}}findPoolByAddress(e,t){let r=t.toLowerCase();return e.find(o=>(o.id??"").toLowerCase()===r)}findTokenByAddress(e,t){let r=t.toLowerCase();return e.find(o=>(o.address??"").toLowerCase()===r)}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 _i=class{uniswap;constructor(e){this.uniswap=new He(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 Tp=/^0x[a-fA-F0-9]{40}$/,Ap=/^0x[a-fA-F0-9]{64}$/,Xn=class extends A{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 _i(e),this.pool=new ce(e?.pool),this.coinPool=new vn(e?.coinPool),this.minProvideUsd=e?.minProvideUsd??.01}async execute(e,t){let r=`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:r,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:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let r=await te(kn(this.pool),e.chain,t);if(!r.ok)return r.result;let o=r.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=Tp.test(l)||Ap.test(l)?l.toLowerCase():"",d=Ap.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=mt(o);if(!y)return{error:"unsupported_chain",chain:o,_instructions:`Chain ${o} is not supported by the add-liquidity flow.`};let w=jn(o);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(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(d)return this.unsupportedVersionResult({protocolVersion:"V4",token0:{symbol:s},token1:{symbol:a}},s,a,y.name);let P=await this.resolver.resolveCandidates({chain:o,token0Symbol:s,token1Symbol:a,protocolVersion:"V3",feeTier:c?void 0:i});if(P===null)return{error:"pool_search_failed"};let S=c?P.find(G=>typeof G.id=="string"&&G.id.toLowerCase()===c):void 0;if(c&&!S){let G=await this.findUnsupportedVersionPool(o,s,a,i,c);if(G)return this.unsupportedVersionResult(G,s,a,y.name)}let x=S??P.find(G=>this.matchesPairExact(G,s,a,i)),L=x?[]:P.filter(G=>this.matchesPair(G,s,a,i));if(!x&&L.length===0){let G=await this.findUnsupportedVersionPool(o,s,a,i,c);return G?this.unsupportedVersionResult(G,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(!x&&L.length>1){let G=L.map(Te=>{let or=Te.volume1DayUsd??Te.volumeUsd24hr,fa=Te.tvlUsd,Mc=typeof or=="number"&&typeof fa=="number"&&fa>0?or/fa:void 0;return{address:Te.id,token0Symbol:Te.token0?.symbol,token1Symbol:Te.token1?.symbol,feeTier:Te.feeTier,feeTierPercent:Te.feeTier!=null?Te.feeTier/1e4:void 0,volume24hUsd:or,tvlUsd:fa,...Mc!=null?{volumeToTvlRatio:Mc}:void 0,...Te.apr?{apr:Te.apr}:void 0}}).sort((Te,or)=>(or.volumeToTvlRatio??or.apr??-1/0)-(Te.volumeToTvlRatio??Te.apr??-1/0)).slice(0,5),Qi=Ac(G.map(Te=>({token0:{symbol:Te.token0Symbol},token1:{symbol:Te.token1Symbol},feeTierPercent:Te.feeTierPercent,address:Te.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:G,count:G.length,...Qi.length>0?{actionButtons:Qi}:{},_instructions:me+"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. "+he+"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). "+we+Y+j+(Qi.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 E=x??L[0];if(!E.id||!Tp.test(E.id))return{error:"invalid_pool_address"};let ke=this.fetchPriceRanges(o,E.id,E.token0?.symbol,E.token1?.symbol),V=await this.pool.readPoolOnchain(o,E.id),[z,fe,Ne]=await Promise.all([this.pool.getNativeBalance(o,v),this.pool.estimateGasReserveWei(o),this.pool.getNativePriceUsd(o)]),W=z>fe?z-fe:0n,Z=jn(o),Ht=Number(W)/10**Z.decimals,tr=Number(z)/10**Z.decimals,Le=Ne!=null?Ht*Ne:null,[Ge,Vt]=await Promise.all([this.pool.readErc20Decimals(o,V.token0),this.pool.readErc20Decimals(o,V.token1)]),Ke={min:pt(gn,Ge,Vt),max:pt(So,Ge,Vt)},Qe=null;z===0n?Qe="no_balance":Le!=null&&Le<this.minProvideUsd&&(Qe="insufficient_balance");let An=E.token0,Pn=E.token1,ha=[25,50,75,100].map(G=>({percent:G,amountWei:(W*BigInt(G)/100n).toString(),amount:Ht*(G/100)})),nr=null,rr=null;if(u!=null){rr=u;let G=BigInt(Math.floor(rr*10**Z.decimals));G>0n&&(nr=G.toString())}else if(p!=null&&Ne!=null&&Ne>0){rr=p/Ne;let G=BigInt(Math.floor(rr*10**Z.decimals));G>0n&&(nr=G.toString())}let Oc={address:le,isNative:!0,symbol:Z.symbol,name:Z.name,decimals:Z.decimals,priceUsd:Ne,balanceWei:z.toString(),balance:tr,gasReserveWei:fe.toString(),spendableWei:W.toString(),spendable:Ht,spendableUsd:Le,quickRates:ha,minProvideUsd:this.minProvideUsd,warning:Qe,warningMessage:Qe==="no_balance"?`You have no ${Z.symbol} on ${y.name}. Top up to add liquidity.`:Qe==="insufficient_balance"?`Spendable ${Z.symbol} is below the $${this.minProvideUsd} minimum.`:null,prefillAmount:rr,prefillAmountWei:nr},X=this.computePrefillRange({explicitMinPrice:g,explicitMaxPrice:b,rangeStrategy:h,currentPrice:V.currentPrice,currentTick:V.currentTick,tickSpacing:V.tickSpacing,token0Decimals:Ge,token1Decimals:Vt,priceBounds:Ke}),Jp={component:"AddLiquidityForm",props:{chain:{hexId:o,name:y.name},pool:{address:V.poolAddress,fee:V.fee,feePercent:V.fee/1e4,tickSpacing:V.tickSpacing,currentTick:V.currentTick,currentPrice:Se(V.currentPrice),sqrtPriceX96:V.sqrtPriceX96.toString(),token0:{address:V.token0,symbol:An?.symbol,name:An?.name,logo:An?.logo},token1:{address:V.token1,symbol:Pn?.symbol,name:Pn?.name,logo:Pn?.logo}},inputToken:Oc,priceBounds:Ke,prefillRange:X,gatewayAddress:k}},Zp=this.orientRangesToForm(await ke,V.currentPrice,An?.symbol,Pn?.symbol);return{ui:Jp,suggestedRanges:Zp,summary:this.buildSummary({chainName:y.name,pair:`${An?.symbol??s}/${Pn?.symbol??a}`,feePercent:V.fee/1e4,warning:Qe,minProvideUsd:this.minProvideUsd,nativeSymbol:Z.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. '+Y+"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,r,o){try{if(!this.coinPool.isSupported(e))return[];let s=await this.coinPool.getByAddress({chain:e,poolAddress:t});return s.length===0&&r&&o&&(s=await this.coinPool.getPairs({chain:e,tokens:[r,o]})),s.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}orientRangesToForm(e,t,r,o){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:$(a.apr),minPrice:Se(d),maxPrice:Se(u),currentPrice:Se(p),baseSymbol:r,quoteSymbol:o}}).filter(a=>s(a.minPrice)&&s(a.maxPrice)):[]}unsupportedVersionResult(e,t,r,o){let s=e.protocolVersion??"V4";return{error:"unsupported_protocol_version",protocolVersion:s,pair:`${e.token0?.symbol??t}/${e.token1?.symbol??r}`,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,r,o,s){try{let a=await this.resolver.resolveCandidates({chain:e,token0Symbol:t,token1Symbol:r,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,r,o))??i.find(l=>this.matchesPair(l,t,r,o))}catch{return}}matchesPairExact(e,t,r,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=r.toLowerCase();return s===i&&a===l||s===l&&a===i}matchesPair(e,t,r,o){if(o!=null&&e.feeTier!==o)return!1;let s=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=r.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:r,rangeStrategy:o,currentPrice:s,priceBounds:a}=e;if(t!=null&&r!=null&&r>t){let{minPrice:i,maxPrice:l}=xo(t,r,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=kc({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 zy=/^0x[a-fA-F0-9]{40}$/,Qn=class extends A{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 ce(e?.pool),this.defaultSlippageBps=e?.defaultSlippageBps??"auto",this.mintMinPercent=e?.mintMinPercent??80,this.pantograph=new ye}async execute(e,t){let r=`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:r,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:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let r=typeof e.poolAddress=="string"?e.poolAddress.trim():"",o=await te(kn(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(!r||!s||!Number.isFinite(l)||!Number.isFinite(a)||!Number.isFinite(i))return{error:"missing_inputs",_instructions:"poolAddress, chain, minPrice, maxPrice, nativeAmount are all required."};if(!zy.test(r))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=mt(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=jn(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,r),[g,b]=await Promise.all([this.pool.readErc20Decimals(s,h.token0),this.pool.readErc20Decimals(s,h.token1)]),{minPrice:y,maxPrice:w}=xo(a,i,h.currentPrice),k=y===0?gn:Kn(y,g,b),v=Kn(w,g,b),P=y===0?Et(Rt(gn,h.tickSpacing,"up")):Et(Rt(k,h.tickSpacing,"down")),S=Et(Rt(v,h.tickSpacing,"up"));if(P>=S||P<gn||S>So)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:P,tickUpper:S};let x={tickLower:P,tickUpper:S,minPrice:Se(pt(P,g,b)),maxPrice:Se(pt(S,g,b))},L=h.currentTick;if(L<P||L>=S){let X=L<P?"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 ${X==="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:Se(h.currentPrice),requestedRange:{minPrice:x.minPrice,maxPrice:x.maxPrice},side:X}}let[E,ke,V]=await Promise.all([this.pool.getNativeBalance(s,p),this.pool.estimateGasReserveWei(s),this.pool.getNativePriceUsd(s)]),z=f+ke;if(E<z)return{error:"insufficient_balance",_instructions:"User does not have enough native coin (amount + gas reserve). Tell them the shortfall in their language.",balanceWei:E.toString(),requiredWei:z.toString(),gasReserveWei:ke.toString()};let fe=this.pool.splitNativeAmountForRange({nativeAmountWei:f,pool:h,tickLower:P,tickUpper:S,token0Decimals:g,token1Decimals:b}),Ne=h.token0.toLowerCase()===le,W=h.token1.toLowerCase()===le,Z=[];if(Ne||fe.amountInFor0Wei===0n)Z.push({tokenIn:le,tokenOut:h.token0,amountIn:fe.amountInFor0Wei,tx:{to:le,data:"0x",value:"0"},minAmountOut:Ne?fe.amountInFor0Wei:0n});else{let X=await this.pool.fetchSwapLeg({senderAddress:p,chainId:s,tokenIn:le,tokenInAmount:fe.amountInFor0Wei.toString(),tokenOut:h.token0,tokenOutRecipient:u,slippage:typeof c=="number"?c:"auto"});Z.push({tokenIn:le,tokenOut:h.token0,amountIn:fe.amountInFor0Wei,tx:{to:X.to,data:X.data,value:X.value},minAmountOut:BigInt(X.minAmountOut||"0")})}if(W||fe.amountInFor1Wei===0n)Z.push({tokenIn:le,tokenOut:h.token1,amountIn:fe.amountInFor1Wei,tx:{to:le,data:"0x",value:"0"},minAmountOut:W?fe.amountInFor1Wei:0n});else{let X=await this.pool.fetchSwapLeg({senderAddress:p,chainId:s,tokenIn:le,tokenInAmount:fe.amountInFor1Wei.toString(),tokenOut:h.token1,tokenOutRecipient:u,slippage:typeof c=="number"?c:"auto"});Z.push({tokenIn:le,tokenOut:h.token1,amountIn:fe.amountInFor1Wei,tx:{to:X.to,data:X.data,value:X.value},minAmountOut:BigInt(X.minAmountOut||"0")})}let Ht=X=>X*BigInt(this.mintMinPercent)/100n,tr=Ht(Z[0].minAmountOut),Le=Ht(Z[1].minAmountOut),Ge=Z.map(X=>({tokenIn:X.tokenIn,tokenInAmount:BigInt(X.amountIn),tokenOut:X.tokenOut,tokenOutAmount:BigInt(X.minAmountOut)})),Vt=Z.map(X=>({to:X.tx.to,data:X.tx.data,value:BigInt(X.tx.value||"0")})),Ke=M({abi:Kl,functionName:"mint",args:[Ge,Vt,{fee:Number(h.fee),amount0Min:BigInt(tr),amount1Min:BigInt(Le),tickLower:P,tickUpper:S}]}),Qe=l,An={chainId:s,to:u,data:Ke,value:f.toString(),from:p},Pn={nativeIn:Qe,nativeSymbol:m.symbol,nativeInUsd:V!=null?Qe*V:null,ratio:{token0Percent:fe.ratio0,token1Percent:fe.ratio1},expectedToken0:Number(Z[0].minAmountOut)/10**g,expectedToken1:Number(Z[1].minAmountOut)/10**b,amount0Min:tr.toString(),amount1Min:Le.toString(),slippageBps:c},[ha,nr]=await this.resolveTokenDisplays(s,[h.token0,h.token1],[g,b]);return{ui:{component:"ConfirmAddLiquidityTx",props:{chain:{hexId:s,name:d.name},unsignedTx:An,summary:Pn,pool:{...h,feePercent:h.fee/1e4,currentPrice:Se(h.currentPrice),token0:ha,token1:nr},range:x,gatewayAddress:u}},summary:`Ready to add ${Qe} ${m.symbol} to pool ${ha.symbol}/${nr.symbol} ${h.fee/1e4}% on ${d.name}, range [${x.minPrice}, ${x.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."}}async resolveTokenDisplays(e,t,r){let[o,s]=await Promise.all([At(e,t),this.pantograph.getTokensMetadata(t,e)]),a=jn(e)?.symbol,i=l=>typeof l=="string"&&l.trim()||void 0;return t.map((l,c)=>{let d=s[l.toLowerCase()],p=(l.toLowerCase()===le?a:o[c]?.symbol)||i(d?.auditGoplus?.token_symbol)||i(d?.symbol)||`${l.slice(0,6)}\u2026${l.slice(-4)}`;return{address:l,symbol:p,name:i(d?.name)||p,decimals:r[c],logo:i(d?.icon_image)}})}};var Xy=365,Qy=1e3,Jy=/^0x[a-fA-F0-9]{40}$/;function Zy(n,e){return{depositUsd:n,aprPercent:e*100,dailyUsd:n*e/Xy,weeklyUsd:n*e/52,monthlyUsd:n*e/12,yearlyUsd:n*e}}var Fo=class extends A{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):
|
|
206
206
|
\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.
|
|
207
207
|
\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.
|
|
208
208
|
\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.
|
|
209
209
|
\u2022 If chain is missing \u2192 default to userContext.chain or "0x1" (Ethereum).
|
|
210
|
-
Source: Uniswap Explore (live 24h data). Supports: `+Oe();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:nt,required:!1}];service;constructor(e){super(),this.service=new He(e)}async run(e,t){let r=await te(rt(),e.chain,t);if(!r.ok)return r.result;let o=r.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:Xy;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:o,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(o)}. 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(x=>({pair:x.token0?.symbol&&x.token1?.symbol?`${x.token0.symbol}/${x.token1.symbol}`:void 0,feeTierBps:x.feeTier,feeTierPercent:typeof x.feeTier=="number"?x.feeTier/1e4:void 0,volume24hUsd:x.volumeUsd24hr,address:x.id}))}}let h=f[0];if(!h.id||!Qy.test(h.id))return{error:"Resolved pool has no valid address."};let g=await this.service.getPoolDetailEnriched({addressOrId:h.id,chain:o,enrich:!1});if(!g.success||!g.data)return{error:g.error||"Failed to fetch pool detail."};let b=Xn(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: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=Jy(c,y);return{_instructions:me+"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. "+he+we+Y+"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,r,o){let s=t.toLowerCase(),a=r?r.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,r)=>(r.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}dedupeByFeeTier(e){let t=new Set,r=[];for(let o of e)typeof o.feeTier=="number"&&(t.has(o.feeTier)||(t.add(o.feeTier),r.push(o)));return r}describeQuery(e,t,r){let o=t?`${e}/${t}`:e;return r!=null?`${o} at ${r} bps`:o}};var Zn=class extends A{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: '+Oe()+".";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:nt,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 Tn(e),this.scope=e?.scope??rt(),e?.supportsLabel){let t=Oe();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(r=>r.name==="chain");t&&(t.description=e.chainParamDescription)}}async run(e,t){let r=(Array.isArray(e.tokens)?e.tokens:[]).filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim().toUpperCase());if(r.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let o=await te(this.scope,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:r});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:r,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. '+Y+"Do NOT mention tool or API names.",tokens:r,chain:s,count:l.length,pairs:l}}};var Ap="https://coinpool.app/my-liquidity",er=class extends A{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: ${Ap} \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:Ap,action:t}}};var Zy=["tvl","volume","apr","fee","liquidity"],Bo=class extends A{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 xe(e)}async run(e,t){let r=(Array.isArray(e.tokens)?e.tokens:[]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.trim().toUpperCase()),o=(Array.isArray(e.chains)?e.chains:[]).filter(f=>typeof f=="string"&&f.trim().length>0),s=o.filter(f=>!this.service.isSupported(f)),a=o.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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],l=typeof e.sortBy=="string"&&Zy.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(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(f=>this.service.searchPools({tokens:r,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 r.length===2&&(m=(await Promise.allSettled(i.map(h=>this.service.getCoinPoolPairs({chain:h,tokens:r})))).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:r,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:ze(e)}}};function ze(n){return`https://app.uniswap.org/explore/pools/${Zs[n.chain]||n.chain}/${n.poolAddress}`}var Zs={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};var qo=class extends A{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 xe(e)}async run(e,t){let r=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),o=r.filter(d=>!this.service.isSupported(d)),s=r.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(r.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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());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:o,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:ze(d)}))}}};var $o=class extends A{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 xe(e)}async run(e,t){let r=typeof e.poolAddress=="string"?e.poolAddress.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(r))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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());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:r,chain:a}),this.service.getCoinPoolByAddress({chain:a,poolAddress:r}).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:ze(i)}}:{error:`No pool found at ${r} on ${T(a)}.`}}};var Ho=class extends A{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 xe(e)}async run(e,t){let r=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(r))return{error:"positionId must be a numeric string."};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:"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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());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:r,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:r,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:ze(c)}}:{_instructions:"No pool found for this position id on the chosen chains. Ask the user to verify the id or chain.",positionId:r,chains:i,found:!1}}};var Vo=class extends A{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 xe(e)}async run(e,t){let r=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(r))return{error:"positionId must be a numeric string (Uniswap V3 NFT id)."};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:"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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());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:r,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:r,chains:i,found:!1};let d=Zs[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:r,position:{...c.position,uniswapPositionUrl:`https://app.uniswap.org/positions/v3/${d}/${c.position.positionId}`},pool:{...c.pool,uniswapUrl:ze(c.pool)}}}};var Wo=class extends A{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 xe(e)}async run(e,t){let r=(Array.isArray(e.tokens)?e.tokens:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim().toUpperCase());if(r.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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());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:r});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:r,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:r,chain:a,count:c.length,pairs:c}}};var Yo=class extends A{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 xe(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:
|
|
210
|
+
Source: Uniswap Explore (live 24h data). Supports: `+Oe();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:rt,required:!1}];service;constructor(e){super(),this.service=new He(e)}async run(e,t){let r=await te(ot(),e.chain,t);if(!r.ok)return r.result;let o=r.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:Qy;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:o,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(o)}. 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(x=>({pair:x.token0?.symbol&&x.token1?.symbol?`${x.token0.symbol}/${x.token1.symbol}`:void 0,feeTierBps:x.feeTier,feeTierPercent:typeof x.feeTier=="number"?x.feeTier/1e4:void 0,volume24hUsd:x.volumeUsd24hr,address:x.id}))}}let h=f[0];if(!h.id||!Jy.test(h.id))return{error:"Resolved pool has no valid address."};let g=await this.service.getPoolDetailEnriched({addressOrId:h.id,chain:o,enrich:!1});if(!g.success||!g.data)return{error:g.error||"Failed to fetch pool detail."};let b=zn(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: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=Zy(c,y);return{_instructions:me+"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. "+he+we+Y+"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,r,o){let s=t.toLowerCase(),a=r?r.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,r)=>(r.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}dedupeByFeeTier(e){let t=new Set,r=[];for(let o of e)typeof o.feeTier=="number"&&(t.has(o.feeTier)||(t.add(o.feeTier),r.push(o)));return r}describeQuery(e,t,r){let o=t?`${e}/${t}`:e;return r!=null?`${o} at ${r} bps`:o}};var Jn=class extends A{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: '+Oe()+".";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:rt,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 vn(e),this.scope=e?.scope??ot(),e?.supportsLabel){let t=Oe();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(r=>r.name==="chain");t&&(t.description=e.chainParamDescription)}}async run(e,t){let r=(Array.isArray(e.tokens)?e.tokens:[]).filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim().toUpperCase());if(r.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let o=await te(this.scope,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:r});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:r,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. '+Y+"Do NOT mention tool or API names.",tokens:r,chain:s,count:l.length,pairs:l}}};var Pp="https://coinpool.app/my-liquidity",Zn=class extends A{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: ${Pp} \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:Pp,action:t}}};var eb=["tvl","volume","apr","fee","liquidity"],Bo=class extends A{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 xe(e)}async run(e,t){let r=(Array.isArray(e.tokens)?e.tokens:[]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.trim().toUpperCase()),o=(Array.isArray(e.chains)?e.chains:[]).filter(f=>typeof f=="string"&&f.trim().length>0),s=o.filter(f=>!this.service.isSupported(f)),a=o.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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],l=typeof e.sortBy=="string"&&eb.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(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(f=>this.service.searchPools({tokens:r,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 r.length===2&&(m=(await Promise.allSettled(i.map(h=>this.service.getCoinPoolPairs({chain:h,tokens:r})))).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:r,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:Xe(e)}}};function Xe(n){return`https://app.uniswap.org/explore/pools/${Zs[n.chain]||n.chain}/${n.poolAddress}`}var Zs={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};var qo=class extends A{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 xe(e)}async run(e,t){let r=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),o=r.filter(d=>!this.service.isSupported(d)),s=r.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(r.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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());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:o,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:Xe(d)}))}}};var $o=class extends A{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 xe(e)}async run(e,t){let r=typeof e.poolAddress=="string"?e.poolAddress.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(r))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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());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:r,chain:a}),this.service.getCoinPoolByAddress({chain:a,poolAddress:r}).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:Xe(i)}}:{error:`No pool found at ${r} on ${T(a)}.`}}};var Ho=class extends A{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 xe(e)}async run(e,t){let r=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(r))return{error:"positionId must be a numeric string."};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:"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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());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:r,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:r,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:Xe(c)}}:{_instructions:"No pool found for this position id on the chosen chains. Ask the user to verify the id or chain.",positionId:r,chains:i,found:!1}}};var Vo=class extends A{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 xe(e)}async run(e,t){let r=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(r))return{error:"positionId must be a numeric string (Uniswap V3 NFT id)."};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:"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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());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:r,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:r,chains:i,found:!1};let d=Zs[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:r,position:{...c.position,uniswapPositionUrl:`https://app.uniswap.org/positions/v3/${d}/${c.position.positionId}`},pool:{...c.pool,uniswapUrl:Xe(c.pool)}}}};var Wo=class extends A{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 xe(e)}async run(e,t){let r=(Array.isArray(e.tokens)?e.tokens:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim().toUpperCase());if(r.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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());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:r});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:r,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:r,chain:a,count:c.length,pairs:c}}};var Yo=class extends A{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 xe(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:
|
|
211
211
|
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.
|
|
212
212
|
`+(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)+`
|
|
213
|
-
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 r=typeof e.poolAddress=="string"?e.poolAddress.trim():"",o=(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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());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(r){if(!/^0x[a-fA-F0-9]{40}$/.test(r))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:r,chain:l});return u?this.poolsResult([u],l,!0):{error:`No pool found at ${r} on ${T(l)}.`}}if(o.length>0){let u=await this.service.searchPools({tokens:o,chain:l,sortBy:"tvl",filters:{feeTier:s}});if(u.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(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((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,r,o=[]){let s=r?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:ze(e)}}};var Cp={"0x1":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0xa":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0x89":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0xa4b1":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0x38":"0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7","0x2105":"0x33128a8fC17869897dcE68Ed026d694621f6FDfD","0xa86a":"0x740b1c1de25031C31FF4fC9A62f554A55cdC1baD"},eb="e34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54",Pp=/^0x[a-fA-F0-9]{40}$/;function Ni(n){let e=n.startsWith("0x")?n.slice(2):n,t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++)t[r]=parseInt(e.slice(r*2,r*2+2),16);return t}function Sp(n){let e=new Uint8Array(32);return e.set(Ni(n.toLowerCase()),12),e}function tb(n){let e=new Uint8Array(32),t=BigInt(n);for(let r=31;r>=0&&t>0n;r--)e[r]=Number(t&0xffn),t>>=8n;return e}function xp(n){let e=n.reduce((o,s)=>o+s.length,0),t=new Uint8Array(e),r=0;for(let o of n)t.set(o,r),r+=o.length;return t}function Sc(n){return Object.prototype.hasOwnProperty.call(Cp,n.toLowerCase())}function xc(n,e,t,r){let o=Cp[n.toLowerCase()];if(!o||!Pp.test(e)||!Pp.test(t)||!Number.isInteger(r)||r<=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=xa(xp([Sp(i),Sp(l),tb(r)]));return`0x${xa(xp([new Uint8Array([255]),Ni(o),Ni(c),Ni(eb)])).slice(2).slice(24)}`}var Ep={"0x1":"Ethereum","0xa":"OP Mainnet","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche"},nb={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"},Rp={"uniswap-v2":"V2","uniswap-v3":"V3","uniswap-v4":"V4"},rb=new Set([100,200,300,400,500,1e3,2500,3e3,1e4,2e4]),ob="https://yields.llama.fi",sb=300*1e3,Go=Object.keys(Ep),Cc=new Map,Me=class{baseUrl;cacheTtlMs;constructor(e){this.baseUrl=(e?.baseUrl||ob).replace(/\/$/,""),this.cacheTtlMs=e?.cacheTtlMs??sb}get store(){let e=Cc.get(this.baseUrl);return e||(e={pools:null,fetchedAt:0,inflight:null},Cc.set(this.baseUrl,e)),e}isSupported(e){if(!e)return!1;let t=D(e);return!!t&&Object.prototype.hasOwnProperty.call(Ep,t)}listSupportedChains(){return Go.filter(e=>D(e)===e)}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 r=await C.get(`${this.baseUrl}/pools`);if(!r.ok)throw new Error(`DefiLlama: ${_(r)}`);let o=r.data,a=(Array.isArray(o?.data)?o.data:[]).filter(i=>i&&typeof i.project=="string"&&Rp[i.project]!==void 0).map(i=>this.normalize(i)).filter(i=>i!==null);return e.pools=a,e.fetchedAt=Date.now(),a}catch(r){if(e.pools)return e.pools;throw r}finally{e.inflight=null}})()),e.inflight)}clearCache(){Cc.delete(this.baseUrl)}parseFeeTierBps(e){if(typeof e!="string")return;let t=e.match(/([\d.]+)\s*%/);if(!t)return;let r=parseFloat(t[1]);if(!Number.isFinite(r)||r<=0)return;let o=Math.round(r*1e4);return rb.has(o)?o:void 0}normalize(e){let t=nb[String(e.chain).toLowerCase()];if(!t)return null;let r=Rp[e.project];if(!r)return null;let o=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=r==="V3"&&o&&a.length===2&&Sc(t)?xc(t,a[0],a[1],o)??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=$(e.apyBase??e.apy),u=$(e.apy)??d;return{id:e.pool,pair:s.length>=2?`${s[0]}/${s[1]}`:String(e.symbol||""),chain:t,protocolVersion:r,address:i,feeTierBps:o,feeTierPercent:o!==void 0?o/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&&o!==void 0?parseFloat((c*o/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((r,o)=>this.sortValue(o,t)-this.sortValue(r,t))}async getTopPools(e){try{let t=await this.snapshot(),r=e.protocolVersion??"V3",o=Math.min(Math.max(e.limit??10,1),50),s=t.filter(a=>a.chain===e.chain);return r!=="ALL"&&(s=s.filter(a=>a.protocolVersion===r)),e.forAddLiquidity&&(s=s.filter(a=>a.address!==void 0)),{success:!0,data:this.sorted(s,e.sortBy??"tvl").slice(0,o)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async searchPools(e){try{let t=await this.snapshot(),r=e.protocolVersion??"V3",o=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 r!=="ALL"&&(a=a.filter(i=>i.protocolVersion===r)),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,o)}}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(" "),r=await this.searchPools({chain:e.chain,query:t,limit:50,sortBy:"tvl",protocolVersion:e.protocolVersion??"V3"});return!r.success||!r.data?r:{success:!0,data:e.feeTierBps!==void 0?r.data.filter(s=>s.feeTierBps===e.feeTierBps):r.data}}async findByPoolAddress(e){try{let t=await this.snapshot(),r=e.address.toLowerCase();return{success:!0,data:t.find(s=>s.chain===e.chain&&s.address===r)??null}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async findPoolsByTokenAddress(e){try{let t=await this.snapshot(),r=e.address.toLowerCase(),o=t.filter(s=>s.chain===e.chain&&(s.token0?.address?.toLowerCase()===r||s.token1?.address?.toLowerCase()===r));return{success:!0,data:this.sorted(o,"tvl").slice(0,Math.min(e.limit??10,50))}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}};function Ve(){return{kind:"info",async listSupported(){return Go.filter(n=>qe(n))},async isSupported(n){if(!n)return!1;let e=D(n);return!!e&&Go.includes(e)}}}function We(){return Go.filter(n=>qe(n)).map(n=>T(n)).join(", ")}var Ye="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 ab=["V2","V3","V4"];function Ko(n){if(typeof n!="string")return"V3";let e=n.trim().toUpperCase();return e==="ALL"?"ALL":ab.includes(e)?e:"V3"}function ib(n){return Object.fromEntries(Object.entries(n).filter(([,e])=>e!=null))}function _e(n){let e=Js(n.chain,n.address);return ib({pair:n.pair,address:n.address,chain:n.chain,protocolVersion:n.protocolVersion,feeTierBps:n.feeTierBps,feeTierPercent:n.feeTierPercent,tvlUsd:n.tvlUsd,volume1DayUsd:n.volume1DayUsd,volume7DayUsd:n.volume7DayUsd,fee24hUsd:n.fee24hUsd,apr:n.apr,totalApr:n.totalApr!==void 0&&n.totalApr!==n.apr?n.totalApr:void 0,volumeToTvlRatio:n.volumeToTvlRatio,aprChange1D:n.aprChange1D,aprChange7D:n.aprChange7D,aprMean30d:n.aprMean30d,isStablecoin:n.isStablecoin,ilRisk:n.ilRisk,token0:n.token0,token1:n.token1,uniswapUrl:e??void 0,addLiquidityUnavailable:n.address===void 0?!0:void 0})}var ft='\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 lb=["tvl","volume1Day","volume7Day","apr"],jo=class extends A{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: `+We();category="blockchain-data";parameters=[{name:"chain",type:"string",description:Ye,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},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new le}async run(e,t){let r=e.forAddLiquidity===!0,o=await te(r?vn(this.pool):Ve(),e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=Ko(e.protocolVersion),i=typeof e.sortBy=="string"?e.sortBy:"tvl",l=lb.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:r});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(_e);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)?pe(u.filter(m=>m.address!==void 0),e,T(s)):[];return{_instructions:me+"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. "+he+ft+"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. "+we+Y+"Mention the chain and the sort metric in the intro line. "+j+(p.length>0?de:""),chain:s,protocolVersion:a,sortBy:l,count:u.length,pools:u,...p.length>0?{actionButtons:p}:{}}}};var cb=["tvl","volume1Day","volume7Day","apr"],zo=class extends A{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: '+We();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:Ye,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},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new le}async run(e,t){let r=await te(Ve(),e.chain,t);if(!r.ok)return r.result;let o=r.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=Ko(e.protocolVersion),i=typeof e.sortBy=="string"?e.sortBy:"tvl",l=cb.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:o,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(_e);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(o),query:s,count:0,pools:[]};let p=await this.pool.isAddLiquiditySupported(o)?pe(u.filter(m=>m.address!==void 0),e,T(o)):[];return{_instructions:me+`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. `+he+ft+"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. "+we+Y+j+(p.length>0?de:""),chain:o,query:s,sortBy:l,count:u.length,pools:u,...p.length>0?{actionButtons:p}:{}}}};var Xo=class extends A{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: '+We();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:Ye,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version: "V2", "V3", "V4", or "ALL". Default "V3".',required:!1,default:"V3"},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new le}async run(e,t){let r=await te(Ve(),e.chain,t);if(!r.ok)return r.result;let o=r.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=Ko(e.protocolVersion),c=await this.service.getPoolsByPair({chain:o,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(o),pair:u,pool:null};let p=await this.pool.isAddLiquiditySupported(o);if(d.length>1){let h=d.map(_e),g=p?pe(h.filter(b=>b.address!==void 0),e,T(o)):[];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. `+j+(g.length>0?de:""),chain:o,pair:u,count:h.length,candidates:h,...g.length>0?{actionButtons:g}:{}}}let m=_e(d[0]),f=p&&m.address!==void 0?pe([m],e,T(o)):[];return{_instructions:me+"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. "+he+ft+"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. "+we+Y+j+(f.length>0?de:""),chain:o,pair:u,pool:m,...f.length>0?{actionButtons:f}:{}}}};var ub=/^0x[a-fA-F0-9]{40}$/,Qo=class extends A{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: '+We();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:Ye,required:!1},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new le}async run(e,t){let r=await te(Ve(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.address=="string"?e.address.trim():"";if(!ub.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(o),l=await this.service.findByPoolAddress({chain:o,address:a});if(l.success&&l.data){let u=_e(l.data),p=i&&u.address!==void 0?pe([u],e,T(o)):[];return{_instructions:me+"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. "+he+ft+"Close by saying concretely whether this pool is worth providing liquidity in right now. "+we+Y+j+(p.length>0?de:""),chain:o,resolvedAs:"pool",pool:u,...p.length>0?{actionButtons:p}:{}}}let c=await this.service.findPoolsByTokenAddress({chain:o,address:a,limit:10});if(c.success&&c.data&&c.data.length>0){let u=c.data.map(_e),p=c.data[0],m=p.token0?.address?.toLowerCase()===a?p.token0?.symbol:p.token1?.symbol,f=i?pe(u.filter(h=>h.address!==void 0),e,T(o)):[];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. "+he+ft+j+(f.length>0?de:""),chain:o,resolvedAs:"token",token:{address:a,symbol:m},count:u.length,pools:u,...f.length>0?{actionButtons:f}:{}}}let d=await this.readPoolOnchain(o,a);if(d){let u=i?pe([d],e,T(o)):[];return{_instructions:me+"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. "+Y+j+(u.length>0?de:""),chain:o,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(o)}. 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(o),address:a,resolvedAs:null}}async readPoolOnchain(e,t){try{let r=await this.pool.readPoolOnchain(e,t),[o,s]=await on(e,[r.token0,r.token1]).catch(()=>[{symbol:null,decimals:null},{symbol:null,decimals:null}]),a=o?.symbol??void 0,i=s?.symbol??void 0,l=Js(e,t);return{pair:a&&i?`${a}/${i}`:void 0,address:t,chain:e,protocolVersion:"V3",feeTierBps:r.fee,feeTierPercent:r.fee/1e4,currentPrice:r.currentPrice,token0:{symbol:a,address:r.token0},token1:{symbol:i,address:r.token1},...l?{uniswapUrl:l}:{}}}catch{return null}}};var db=1e3,pb=365;function mb(n,e){let t=e/100;return{depositUsd:n,aprPercent:e,dailyUsd:n*t/pb,weeklyUsd:n*t/52,monthlyUsd:n*t/12,yearlyUsd:n*t}}var Jo=class extends A{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: `+We();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:Ye,required:!1}];service;constructor(e){super(),this.service=new Me(e)}async run(e,t){let r=await te(Ve(),e.chain,t);if(!r.ok)return r.result;let o=r.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:db,d=await this.service.getPoolsByPair({chain:o,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(o),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. `+j,chain:o,pair:u,candidates:y.map(_e)}}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. "+j,chain:o,pair:u,pool:_e(h),...g?{autoPickedReason:g}:{}};let b=mb(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. "+Y+j,chain:o,pair:u,pool:_e(h),depositMode:l?"user-specified":"default-1000-example",estimate:b,...g?{autoPickedReason:g}:{}}}dedupeByFeeTier(e){let t=new Map;for(let r of e){if(r.feeTierBps===void 0)continue;let o=t.get(r.feeTierBps);(!o||r.tvlUsd>o.tvlUsd)&&t.set(r.feeTierBps,r)}return[...t.values()].sort((r,o)=>o.tvlUsd-r.tvlUsd)}};var Zo=class{service;constructor(e){this.service=new Me(e)}async resolveCandidates(e){let t=e.protocolVersion==="ALL"?"ALL":"V3",r=await this.service.getPoolsByPair({chain:e.chain,token0Symbol:e.token0Symbol,token1Symbol:e.token1Symbol,feeTierBps:e.feeTier,protocolVersion:t});return r.success?(r.data??[]).filter(o=>o.protocolVersion==="V3"?o.address!==void 0:t==="ALL").map(o=>({id:o.address,protocolVersion:o.protocolVersion,feeTier:o.feeTierBps,token0:o.token0,token1:o.token1,tvlUsd:o.tvlUsd,volume1DayUsd:o.volume1DayUsd,apr:o.apr})):null}};function _t(n){if(typeof n=="number")return Number.isFinite(n)&&n>0?{kind:"token",value:n,raw:String(n)}:null;if(typeof n!="string")return null;let e=n.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 r=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(r){let s=parseFloat(r[1]??r[2]??r[3]??r[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 _p(n,e){switch(n.kind){case"token":return{ok:!0,amount:n.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*n.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:n.usd/e.usdPrice}}}function tr(n){let e=n?.trim();if(!e)return"";let t=T(e);return!t||t==="the requested chain"||t===e?"":` (${t})`}function Q(n){let e=tr(n).trim();return e?` on ${e.slice(1,-1)}`:" on this chain"}var Np={send:30000n,swap:1000000n};async function hb(n){try{let e=await Re(n).getGasPrice();return e>0n?e:0n}catch{return 0n}}function Lp(n,e){let t=Np[n],r=fb(e);return r!==null&&r>t?r:t}function fb(n){let e=n?.tx?.gas??n?.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 Rc(n,e,t={}){let[r,o]=await Promise.all([hb(n),t.provider?Ri({provider:t.provider,srcChainId:n,dstChainId:t.dstChainId??n}):Promise.resolve(0n)]);return(r>0n?Lp(e,t.quoteGas)*r:0n)+o}async function ea(n,e,t={}){return Rc(n,e,t)}function ta(n,e,t){if(e<=0n)return n;let r=Un(t)?.decimals;if(r===void 0)return n;let o=Number(e)/10**r;return!Number.isFinite(o)||o<=0?n:Math.max(0,n-o)}function Ec(n,e){let t=Un(e)?.decimals;if(t===void 0)return null;let r=Number(n)/10**t;return Number.isFinite(r)?r:null}function Ip(n){let{nativeBalance:e,feeWei:t,chainId:r}=n;if(t<=0n)return null;let o=Ec(t,r);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 na(n){let{chainId:e,gasKind:t,readNativeBalance:r,feeContext:o}=n;if(!e)return null;try{let[s,a]=await Promise.all([Rc(e,t,o??{}),r()]),i=Ip({nativeBalance:a?.balance??0,feeWei:s,chainId:e});return i===null?null:{shortfall:i,nativeSymbol:a?.symbol??Un(e)?.symbol??"the native coin",fee:Ec(s,e)??0}}catch{return null}}var ot=class extends A{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 O(e))}async resolveContractAddress(e,t,r){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(r){let l=await this.moralis.getWalletTokenBalances({address:r,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:r,decimalsArg:o,chain:s,walletAddress:a}=e,i=this.parseDecimals(o),l=typeof r=="string"&&r.trim()?r.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 K(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 r=parseFloat(t);return Number.isFinite(r)&&r>0?t:null}async resolveAmountInput(e){let{rawAmount:t,tokenAddress:r,chain:o,walletAddress:s,gasKind:a}=e,i=_t(t);if(!i)return null;let l=e.symbol??"the token",c=r.toLowerCase()==="native",d=!!a&&c&&!!o;if(i.kind==="token")return{amount:this.toPlainDecimal(i.value)};let u=await this.readTokenBalanceAndPrice(r,o,s),p=u?.balance;d&&u?.balance!==void 0&&(p=await this.computeNativeSpendable(o,a,u.balance));let m=_p(i,{balance:p,usdPrice:u?.usdPrice});return m.ok?{amount:this.toPlainDecimal(m.amount)}:m.reason==="no_balance"?{error:"amount_balance_unavailable",chain:o,_instructions:`Could not read the user's ${l} balance${Q(o)} 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",chain:o,_instructions:`Could not get a USD price for ${l}${Q(o)} 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,r){let o=await ea(e,t);return ta(r,o,e)}async resolveNativeSpendableFormatted(e,t,r){if(!(!e||!t))try{let o=await this.readTokenBalanceAndPrice("native",e,t);if(o?.balance===void 0)return;let s=await this.computeNativeSpendable(e,r,o.balance);return this.toPlainDecimal(s)}catch{return}}async readTokenBalanceAndPrice(e,t,r){if(!this.moralis||!r)return;let o=await this.moralis.getWalletTokenBalances({address:r,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=o.success?o.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 r=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.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+$/,"")),r?`-${d}`:d}formatSpendableUsd(e,t){if(e===void 0||t===void 0)return;let r=Number(e);if(!Number.isFinite(r)||!Number.isFinite(t)||t<=0)return;let o=r*t;if(!(!Number.isFinite(o)||o<=0))return this.toPlainDecimal(o)}async execute(e,t){let r=`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:r,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:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let r=this.requireWallet(t);if(!r.ok)return r.payload;let o=this.requireChain(e,t);if(!o){let h=typeof t?.query=="string"?t.query:void 0;return Br(this.actionType.replace(/_/g," "),h)}let s=await this.buildParameters(e,t);if(s&&typeof s=="object"&&"error"in s&&typeof s.error=="string"||s&&typeof s=="object"&&"actionButtons"in s&&Array.isArray(s.actionButtons)||s&&typeof s=="object"&&"ui"in s&&s.ui&&typeof s.ui=="object"&&typeof s.ui.component=="string")return s;let a=s,i=this.buildUI({parameters:a,chainId:o,walletAddress:r.address}),l=h=>{let g=a[h];return g!=null&&g!==""},c=this.userInputFields.filter(h=>!(Array.isArray(h.key)?h.key:[h.key]).some(l)).map(h=>h.label),d=this.userInputFields.map(h=>{let b=(Array.isArray(h.key)?h.key:[h.key]).find(l);return b?`${h.label}: ${a[b]}`:null}).filter(h=>h!=null),u=this.actionType.replace(/_/g," "),p='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.',m="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.",f=c.length>0?`The ${u} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${c.join(", ")}. `+(d.length>0?`Already provided: ${d.join("; ")}. `:"")+`${m} ${p}`:`The ${u} has all required details. In the user's language, briefly tell the user to review the details and submit to complete the ${u}. `+(d.length>0?`Details provided: ${d.join("; ")}. `:"")+`${m} ${p}`;return{ui:i,action:this.actionType,chainId:o,parameters:a,_instructions:f}}};var es=class extends ot{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 r=Wu(e.native_symbol);if(r)return super.run({...e,chain:r},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:Ze,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 r={},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 u=typeof e.native_symbol=="string"&&e.native_symbol.trim()?e.native_symbol.trim():void 0,p=a?.symbol||u||Ga(o)||"their native coin";return{error:"no_native_balance",chain:o,_instructions:`The user wants to send ${p} but their wallet holds 0 ${p}${Q(o)}. Tell them, in their language, that they do not have any ${p} to send${Q(o)} \u2014 name that network explicitly so they know which one is empty \u2014 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&&(r.native_symbol=i),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?r.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(r.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&&(r.amount=l.amount);let c=await this.resolveNativeSpendableFormatted(o,s,"send");c!==void 0&&(r.spendable=c);let d=this.formatSpendableUsd(c,a.usdPrice);return d!==void 0&&(r.spendableUsd=d),r}};var ts=class extends ot{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:Ze,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 r=this.normaliseAddress(e.contract_address)!=null,o=typeof e.token_symbol=="string"&&e.token_symbol.trim().length>0;if(!r&&!o&&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,P)=>(P.usd_value??0)-(v.usd_value??0)).slice(0,8);if(h.length===0)return{error:"no_token_holdings",chain:u,_instructions:`The wallet does not hold any sendable tokens${Q(u)}. Tell the user they have nothing to send${Q(u)}, naming that network explicitly, 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 P=v.symbol,S=v.balance_formatted?this.cleanAmountString(v.balance_formatted):"",x=v.name?v.name:"",L=Qr(v.usd_value)??"";return{label:`${x}:${S} ${P} ${L}`.trim(),prompt:this.buildSendPrompt(y,P,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,r){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||!r||!a){let m=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:t,walletAddress:r});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:r,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,chain:t,_instructions:`The user does not hold any ${p} in their wallet${Q(t)}, so there is nothing to send. Tell them (in their language) that they don't have any ${p} to send${Q(t)} \u2014 name that network explicitly so they know which one is empty \u2014 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,r,o,s){let i=(e&&e.includes("{symbol}")?e:"send {amount} {symbol} to {to} on {chain}").replace(/\{symbol\}/g,t).replace(/\{amount\}/g,r??"");return i=this.fillOrDropPhrase(i,"{to}",o),i=this.fillOrDropPhrase(i,"{chain}",s),i.replace(/\s+/g," ").trim()}fillOrDropPhrase(e,t,r){if(r)return e.split(t).join(r);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 ns=class extends ot{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:Ze,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 r=this.requireChain(e,t)??void 0,o=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:r,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 Li(n){let{action:e,fromSym:t,toSym:r,amount:o,spendable:s}=n,a=e==="swap"?`swap ${t} to ${r}`:`buy ${r} with ${t}`,i=e==="swap"?"swapping":"buying",l=e==="swap"?`swap ${o} ${t} to ${r}`:`buy ${r} 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 qt=n=>n.logo||n.icon_image||n.logoURI||n.thumbnail||void 0,Ii=n=>typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0;async function ra(n){let{moralis:e,tokenAddress:t,chain:r}=n;if(!e)return null;let o=t==="native"?ue:t;try{let s=await e.getTokenMetadata({address:o,chain:r});if(!s.success||!s.data)return null;let a=s.data,i=Vn(a);if(!i?.yieldProtocol)return Ii(a.usd_price)??null;if(Hr(i.yieldProtocol)&&!(a.decimals>0))return null;let l=await e.getUnderlyingPricesUSD(r,[i.yieldAsset]),c=await $s(r||Be,{address:o,decimals:a.decimals,price:Vr(i.yieldAsset,l,a.usd_price),yieldProtocol:i.yieldProtocol,yieldAsset:i.yieldAsset});return Ii(c??void 0)??null}catch{return null}}var gb=n=>Number.isFinite(n)?xs(parseFloat(n.toPrecision(8))):"0",yb=n=>{if(!/e/i.test(n))return n;let e=Number(n);return Number.isFinite(e)?xs(e):n};async function oa(n){let{moralis:e,walletAddress:t,tokenAddress:r,chain:o,kind:s="swap",feeContext:a,dbg:i}=n;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:r,chain:o,ok:l.success,count:c.length});let d=r.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:r}),null;let p=Number(u.balance_formatted);if(!Number.isFinite(p)||p<=0)return i?.("readSpendableBalance: zero/invalid balance \u2192 null",{tokenAddress:r,balance:u.balance_formatted}),null;if(d==="native"&&o){let m=await ea(o,s,a??{}),f=ta(p,m,o);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=gb(f),g=typeof u.decimals=="number"?u.decimals:18;return Up({balanceFormatted:h,balanceNum:f,symbol:u.symbol,decimals:g,logo:qt(u),usdPrice:Ii(u.usd_price)})}return i?.("readSpendableBalance: held",{tokenAddress:r,balance:u.balance_formatted,symbol:u.symbol}),Up({balanceFormatted:u.balance_formatted,balanceNum:p,symbol:u.symbol,decimals:typeof u.decimals=="number"?u.decimals:void 0,logo:qt(u),usdPrice:Ii(u.usd_price)})}function Up(n){let e=yb(n.balanceFormatted),t=n.decimals===void 0?null:Bn(e,n.decimals);return{...n,balanceFormatted:e,rawAmount:t?.toString()}}async function Ui(n,e){let t=n?Ce(n)?.nativeCurrency:void 0,r=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})),o=[];if(r.forEach((a,i)=>{if(!a||a.address==="native"||!R(a.address))return;let l=a.symbolIsOnchain===!0&&!!a.symbol?.trim(),c=typeof a.decimals=="number"&&Number.isFinite(a.decimals);l&&c||o.push({index:i,address:a.address})}),!n||o.length===0)return r;let s=await on(n,o.map(a=>a.address)).catch(()=>[]);return o.forEach((a,i)=>{let l=s[i];if(!l)return;let c=r[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)}),r}function Di(n,e){let t=n?.trim().toLowerCase(),r=e?.trim().toLowerCase();return!t||!r?!1:t===r}var rs=class extends A{name="open-buy-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new O(e),this.pantograph=new ye({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. CHAINS: when the user names a DIFFERENT network per side \u2014 "buy USDC on Base with ETH on Arbitrum" \u2014 you MUST put each one in `token_chain` and `pay_with_chain` (NOT in `chain`, and never drop one of them): that is a cross-chain request and the tool answers it with the correct unsupported message. Use the single `chain` parameter only when ONE network covers the whole request.';parameters=[{name:"chain",type:"string",description:Ze,required:!1},{name:"token_chain",type:"string",description:Fr("token being BOUGHT"),required:!1},{name:"pay_with_chain",type:"string",description:Fr("token being SPENT to pay"),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 r=`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:r,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:r,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=Ka(e.pay_with_chain,e.token_chain);if(o)return ja("buy",o);if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return Br("buy",a)}return this.buildResult(e,t)}async buildResult(e,t){this.correctAmountSide(e,t),this.dropUnmentionedPayToken(e,t),this.dropInventedAmounts(e,t);let r=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}),!r&&!o)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,r,s,a,"dest"),this.resolveSide(e.pay_with_address,e.pay_with_symbol,s,a,"pay")]),[c,d]=await Ui(s,[i.address?{...i,address:i.address}:void 0,l.address?{...l,address:l.address}:void 0]),u=i.address,p=c?.symbol??r,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=_t(e.pay_with_amount),v=!!k&&k.kind!=="token",P=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||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(Di(h,u))return this.dbg("\u2192 same token both sides",{payAddr:h,destContract:u,paySymbol:g,destSymbol:p}),{error:"same_token",_instructions:`The user asked to buy ${p} and pay with ${g??p} \u2014 the SAME token on both sides, which buys nothing and cannot be done. Tell them, in their language, that the token they pay with has to be different from the token they are buying, and ask which token they want to pay with instead. Do NOT proceed. Do NOT render the form. 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,P=y,v=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:w,derivedFromBuy:P})}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:P,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 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 r=t.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(!r)return null;let o=parseFloat(r[1]);return Number.isFinite(o)&&o>0?r[1]:null}correctAmountSide(e,t){let r=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(!r||!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 d=l?a:i,u=d.match(/[0-9]*\.?[0-9]+/)?.[0];if(!u)return;let p=this.nearestSymbolSide(r,u,o,s);p&&(p==="pay"&&l?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:d,buySym:o,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:o,paySym:s}),e.buy_amount=d,e.pay_with_amount=""))}dropUnmentionedPayToken(e,t){let r=typeof t?.query=="string"?t.query:"";if(!r)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=r.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?Un(m)?.symbol:void 0;f&&u.push(f.toLowerCase())}u.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 r=typeof t?.query=="string"?t.query:"";if(!r)return;let o=(r.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(d=>d===c)||(this.dbg(`dropInventedAmounts: clearing invented ${a}`,{val:i}),e[a]=""))};s("buy_amount"),s("pay_with_amount")}nearestSymbolSide(e,t,r,o){let s=e.toLowerCase(),a=s.indexOf(t.toLowerCase()),i=this.indexOfToken(s,r.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)),d=c(i,r.length),u=c(l,o.length);return u===d?null:u<d?"pay":"buy"}indexOfToken(e,t){if(!t)return-1;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=e.match(new RegExp(`(?:^|[^a-z0-9])(${r})(?:[^a-z0-9]|$)`));return o&&o.index!==void 0?o.index+o[0].indexOf(o[1]):-1}requireChain(e,t){return K(e.chain,t)}async resolveContractAddress(e,t,r){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(r){let l=await this.moralis.getWalletTokenBalances({address:r,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:qt(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:qt(c),symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}async resolveSide(e,t,r,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,d=m=>m.toLowerCase()===ue?"native":m,u=l??c??(a||void 0);if(!u)return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(u,r,o);return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,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:r,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(r);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){return ra({moralis:this.moralis,tokenAddress:e,chain:t})}async resolvePayAmountSpec(e,t,r,o,s,a){let i=_t(e);if(!i)return null;let l=d=>a===void 0?d:Dt(d,a);if(i.kind==="token")return l(qn(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!o)return null;let d=await this.readPayBalance(o,t,r);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):$n(d.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,u)}let c=await this.getUsdPrice(t,r);return this.dbg("resolvePayAmountSpec: usd",{usd:i.usd,paySymbol:s,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveBuyAmountSpec(e,t,r,o){let s=_t(e);if(!s)return null;if(s.kind==="token")return qn(e)??this.toPlainDecimal(s.value);if(s.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,r);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:r,destSymbol:o,destContract:s}=e,a=this.requireChain(t,r)??void 0,i=this.moralis,l=r.walletAddress,c=await i.getWalletTokenBalances({address:l,chain:a,excludeSpam:!1,excludeUnverifiedContracts:!1}),d=c.success?c.data?.result??[]:[],u=s?.toLowerCase(),p=o.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",chain:a,_instructions:`The wallet has no tokens that can pay for this purchase${Q(a)}. Tell the user to top up first, naming that network explicitly so they know which one is empty. 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)} `:"",P=Qr(y.usd_value),S=P?` ${P}`:"",x=`${k}: ${v}${w}${S}`,L=f?this.buildBuyWithPrompt(g,o,w,f,null,a):this.buildBuyWithPrompt(g,o,w,null,h,a);return{label:x,prompt:L}}),_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:r,chain:o,destSymbol:s,destContract:a,payAddr:i,payAmount:l,buyAmount:c,derivedFromBuy:d}=e,u=r.walletAddress,p=await this.readPayBalance(u,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:r,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}${Q(o)}. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${m}${Q(o)}, naming that network explicitly (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${m} tr\xEAn ${Q(o).replace(" on ","")}.'), 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 na({chainId:o,gasKind:"swap",readNativeBalance:()=>this.readNativeHeldBalance(u,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 f=p.decimals!==void 0?Dt(l,p.decimals):l;if(sn(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:"",...o===void 0?{}:{chain:o}}),b=d?`Buying ${d} ${s} needs about ${l} ${m}, but they only have ${h} ${m}${Q(o)} \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}${Q(o)} \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,r){return oa({moralis:this.moralis,walletAddress:e,tokenAddress:t,chain:r,kind:"swap",dbg:(o,s)=>this.dbg(o,s)})}async readNativeHeldBalance(e,t){if(!this.moralis)return{balance:0};try{let r=await this.moralis.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=(r.success?r.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:r,paySymbol:o,destSymbol:s,buyWithTemplate:a,chain:i}=e,l=r??18;return[25,50,75,100].map(d=>{let u=$n(this.cleanAmountString(t),BigInt(d),100n,l);return{label:`${d}%`,prompt:this.buildBuyWithPrompt(a,s,o,null,u,i)}})}async buildAmountForm(e){let{userContext:t,chain:r,destContract:o,destSymbol:s,destDecimals:a,destLogo:i,payAddr:l,payAmount:c}=e,d=t.walletAddress;if(!r)return null;let u=Ce(r);if(!u)return null;let p=await this.readPayBalance(d,l,r),m=e.paySymbol??p?.symbol;if(!m)return null;let f=l==="native",h=p?.decimals??e.payDecimals??(f?u.nativeCurrency.decimals??18:void 0);if(h===void 0)return null;let g=p?.balanceFormatted,b=p?.rawAmount??(g?Bn(g,h)?.toString():void 0),y=await this.getUsdPrice(o,r).catch(()=>null);return{ui:{component:"SwapTokenForm",props:{chain:{hexId:r,name:u.name},fromToken:{address:f?"native":l,symbol:m,decimals:h,amount:g,rawAmount:b??void 0,logo:p?.logo,usdPrice:p?.usdPrice},toToken:{address:o,symbol:s,decimals:a,logo:i,usdPrice:y??void 0},walletAddress:d,intent:"buy",initialAmount:c}},_instructions:Li({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 r=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.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+$/,"")),r?`-${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,r){return(e&&e.includes("{token}")?e:"buy {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()+tr(r)}buildBuyWithPrompt(e,t,r,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,r).replace(/\{buy_amount\}/g,o??"").replace(/\{pay_amount\}/g,s??"").replace(/\s+/g," ").trim()+tr(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 r=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:r,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,r)}}),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(`
|
|
213
|
+
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 r=typeof e.poolAddress=="string"?e.poolAddress.trim():"",o=(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 ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());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(r){if(!/^0x[a-fA-F0-9]{40}$/.test(r))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:r,chain:l});return u?this.poolsResult([u],l,!0):{error:`No pool found at ${r} on ${T(l)}.`}}if(o.length>0){let u=await this.service.searchPools({tokens:o,chain:l,sortBy:"tvl",filters:{feeTier:s}});if(u.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(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((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,r,o=[]){let s=r?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:Xe(e)}}};var Rp={"0x1":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0xa":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0x89":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0xa4b1":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0x38":"0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7","0x2105":"0x33128a8fC17869897dcE68Ed026d694621f6FDfD","0xa86a":"0x740b1c1de25031C31FF4fC9A62f554A55cdC1baD"},tb="e34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54",Sp=/^0x[a-fA-F0-9]{40}$/;function Ni(n){let e=n.startsWith("0x")?n.slice(2):n,t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++)t[r]=parseInt(e.slice(r*2,r*2+2),16);return t}function xp(n){let e=new Uint8Array(32);return e.set(Ni(n.toLowerCase()),12),e}function nb(n){let e=new Uint8Array(32),t=BigInt(n);for(let r=31;r>=0&&t>0n;r--)e[r]=Number(t&0xffn),t>>=8n;return e}function Cp(n){let e=n.reduce((o,s)=>o+s.length,0),t=new Uint8Array(e),r=0;for(let o of n)t.set(o,r),r+=o.length;return t}function Sc(n){return Object.prototype.hasOwnProperty.call(Rp,n.toLowerCase())}function xc(n,e,t,r){let o=Rp[n.toLowerCase()];if(!o||!Sp.test(e)||!Sp.test(t)||!Number.isInteger(r)||r<=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=xa(Cp([xp(i),xp(l),nb(r)]));return`0x${xa(Cp([new Uint8Array([255]),Ni(o),Ni(c),Ni(tb)])).slice(2).slice(24)}`}var _p={"0x1":"Ethereum","0xa":"OP Mainnet","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche"},rb={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"},Ep={"uniswap-v2":"V2","uniswap-v3":"V3","uniswap-v4":"V4"},ob=new Set([100,200,300,400,500,1e3,2500,3e3,1e4,2e4]),sb="https://yields.llama.fi",ab=300*1e3,Go=Object.keys(_p),Cc=new Map,Me=class{baseUrl;cacheTtlMs;constructor(e){this.baseUrl=(e?.baseUrl||sb).replace(/\/$/,""),this.cacheTtlMs=e?.cacheTtlMs??ab}get store(){let e=Cc.get(this.baseUrl);return e||(e={pools:null,fetchedAt:0,inflight:null},Cc.set(this.baseUrl,e)),e}isSupported(e){if(!e)return!1;let t=D(e);return!!t&&Object.prototype.hasOwnProperty.call(_p,t)}listSupportedChains(){return Go.filter(e=>D(e)===e)}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 r=await C.get(`${this.baseUrl}/pools`);if(!r.ok)throw new Error(`DefiLlama: ${_(r)}`);let o=r.data,a=(Array.isArray(o?.data)?o.data:[]).filter(i=>i&&typeof i.project=="string"&&Ep[i.project]!==void 0).map(i=>this.normalize(i)).filter(i=>i!==null);return e.pools=a,e.fetchedAt=Date.now(),a}catch(r){if(e.pools)return e.pools;throw r}finally{e.inflight=null}})()),e.inflight)}clearCache(){Cc.delete(this.baseUrl)}parseFeeTierBps(e){if(typeof e!="string")return;let t=e.match(/([\d.]+)\s*%/);if(!t)return;let r=parseFloat(t[1]);if(!Number.isFinite(r)||r<=0)return;let o=Math.round(r*1e4);return ob.has(o)?o:void 0}normalize(e){let t=rb[String(e.chain).toLowerCase()];if(!t)return null;let r=Ep[e.project];if(!r)return null;let o=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=r==="V3"&&o&&a.length===2&&Sc(t)?xc(t,a[0],a[1],o)??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=$(e.apyBase??e.apy),u=$(e.apy)??d;return{id:e.pool,pair:s.length>=2?`${s[0]}/${s[1]}`:String(e.symbol||""),chain:t,protocolVersion:r,address:i,feeTierBps:o,feeTierPercent:o!==void 0?o/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&&o!==void 0?parseFloat((c*o/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((r,o)=>this.sortValue(o,t)-this.sortValue(r,t))}async getTopPools(e){try{let t=await this.snapshot(),r=e.protocolVersion??"V3",o=Math.min(Math.max(e.limit??10,1),50),s=t.filter(a=>a.chain===e.chain);return r!=="ALL"&&(s=s.filter(a=>a.protocolVersion===r)),e.forAddLiquidity&&(s=s.filter(a=>a.address!==void 0)),{success:!0,data:this.sorted(s,e.sortBy??"tvl").slice(0,o)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async searchPools(e){try{let t=await this.snapshot(),r=e.protocolVersion??"V3",o=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 r!=="ALL"&&(a=a.filter(i=>i.protocolVersion===r)),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,o)}}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(" "),r=await this.searchPools({chain:e.chain,query:t,limit:50,sortBy:"tvl",protocolVersion:e.protocolVersion??"V3"});return!r.success||!r.data?r:{success:!0,data:e.feeTierBps!==void 0?r.data.filter(s=>s.feeTierBps===e.feeTierBps):r.data}}async findByPoolAddress(e){try{let t=await this.snapshot(),r=e.address.toLowerCase();return{success:!0,data:t.find(s=>s.chain===e.chain&&s.address===r)??null}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async findPoolsByTokenAddress(e){try{let t=await this.snapshot(),r=e.address.toLowerCase(),o=t.filter(s=>s.chain===e.chain&&(s.token0?.address?.toLowerCase()===r||s.token1?.address?.toLowerCase()===r));return{success:!0,data:this.sorted(o,"tvl").slice(0,Math.min(e.limit??10,50))}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}};function Ve(){return{kind:"info",async listSupported(){return Go.filter(n=>qe(n))},async isSupported(n){if(!n)return!1;let e=D(n);return!!e&&Go.includes(e)}}}function We(){return Go.filter(n=>qe(n)).map(n=>T(n)).join(", ")}var Ye="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 ib=["V2","V3","V4"];function Ko(n){if(typeof n!="string")return"V3";let e=n.trim().toUpperCase();return e==="ALL"?"ALL":ib.includes(e)?e:"V3"}function lb(n){return Object.fromEntries(Object.entries(n).filter(([,e])=>e!=null))}function _e(n){let e=Js(n.chain,n.address);return lb({pair:n.pair,address:n.address,chain:n.chain,protocolVersion:n.protocolVersion,feeTierBps:n.feeTierBps,feeTierPercent:n.feeTierPercent,tvlUsd:n.tvlUsd,volume1DayUsd:n.volume1DayUsd,volume7DayUsd:n.volume7DayUsd,fee24hUsd:n.fee24hUsd,apr:n.apr,totalApr:n.totalApr!==void 0&&n.totalApr!==n.apr?n.totalApr:void 0,volumeToTvlRatio:n.volumeToTvlRatio,aprChange1D:n.aprChange1D,aprChange7D:n.aprChange7D,aprMean30d:n.aprMean30d,isStablecoin:n.isStablecoin,ilRisk:n.ilRisk,token0:n.token0,token1:n.token1,uniswapUrl:e??void 0,addLiquidityUnavailable:n.address===void 0?!0:void 0})}var ft='\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 cb=["tvl","volume1Day","volume7Day","apr"],jo=class extends A{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: `+We();category="blockchain-data";parameters=[{name:"chain",type:"string",description:Ye,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},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new ce}async run(e,t){let r=e.forAddLiquidity===!0,o=await te(r?kn(this.pool):Ve(),e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=Ko(e.protocolVersion),i=typeof e.sortBy=="string"?e.sortBy:"tvl",l=cb.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:r});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(_e);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)?pe(u.filter(m=>m.address!==void 0),e,T(s)):[];return{_instructions:me+"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. "+he+ft+"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. "+we+Y+"Mention the chain and the sort metric in the intro line. "+j+(p.length>0?de:""),chain:s,protocolVersion:a,sortBy:l,count:u.length,pools:u,...p.length>0?{actionButtons:p}:{}}}};var ub=["tvl","volume1Day","volume7Day","apr"],zo=class extends A{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: '+We();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:Ye,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},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new ce}async run(e,t){let r=await te(Ve(),e.chain,t);if(!r.ok)return r.result;let o=r.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=Ko(e.protocolVersion),i=typeof e.sortBy=="string"?e.sortBy:"tvl",l=ub.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:o,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(_e);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(o),query:s,count:0,pools:[]};let p=await this.pool.isAddLiquiditySupported(o)?pe(u.filter(m=>m.address!==void 0),e,T(o)):[];return{_instructions:me+`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. `+he+ft+"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. "+we+Y+j+(p.length>0?de:""),chain:o,query:s,sortBy:l,count:u.length,pools:u,...p.length>0?{actionButtons:p}:{}}}};var Xo=class extends A{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: '+We();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:Ye,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version: "V2", "V3", "V4", or "ALL". Default "V3".',required:!1,default:"V3"},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new ce}async run(e,t){let r=await te(Ve(),e.chain,t);if(!r.ok)return r.result;let o=r.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=Ko(e.protocolVersion),c=await this.service.getPoolsByPair({chain:o,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(o),pair:u,pool:null};let p=await this.pool.isAddLiquiditySupported(o);if(d.length>1){let h=d.map(_e),g=p?pe(h.filter(b=>b.address!==void 0),e,T(o)):[];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. `+j+(g.length>0?de:""),chain:o,pair:u,count:h.length,candidates:h,...g.length>0?{actionButtons:g}:{}}}let m=_e(d[0]),f=p&&m.address!==void 0?pe([m],e,T(o)):[];return{_instructions:me+"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. "+he+ft+"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. "+we+Y+j+(f.length>0?de:""),chain:o,pair:u,pool:m,...f.length>0?{actionButtons:f}:{}}}};var db=/^0x[a-fA-F0-9]{40}$/,Qo=class extends A{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: '+We();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:Ye,required:!1},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new ce}async run(e,t){let r=await te(Ve(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.address=="string"?e.address.trim():"";if(!db.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(o),l=await this.service.findByPoolAddress({chain:o,address:a});if(l.success&&l.data){let u=_e(l.data),p=i&&u.address!==void 0?pe([u],e,T(o)):[];return{_instructions:me+"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. "+he+ft+"Close by saying concretely whether this pool is worth providing liquidity in right now. "+we+Y+j+(p.length>0?de:""),chain:o,resolvedAs:"pool",pool:u,...p.length>0?{actionButtons:p}:{}}}let c=await this.service.findPoolsByTokenAddress({chain:o,address:a,limit:10});if(c.success&&c.data&&c.data.length>0){let u=c.data.map(_e),p=c.data[0],m=p.token0?.address?.toLowerCase()===a?p.token0?.symbol:p.token1?.symbol,f=i?pe(u.filter(h=>h.address!==void 0),e,T(o)):[];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. "+he+ft+j+(f.length>0?de:""),chain:o,resolvedAs:"token",token:{address:a,symbol:m},count:u.length,pools:u,...f.length>0?{actionButtons:f}:{}}}let d=await this.readPoolOnchain(o,a);if(d){let u=i?pe([d],e,T(o)):[];return{_instructions:me+"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. "+Y+j+(u.length>0?de:""),chain:o,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(o)}. 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(o),address:a,resolvedAs:null}}async readPoolOnchain(e,t){try{let r=await this.pool.readPoolOnchain(e,t),[o,s]=await At(e,[r.token0,r.token1]).catch(()=>[{symbol:null,decimals:null},{symbol:null,decimals:null}]),a=o?.symbol??void 0,i=s?.symbol??void 0,l=Js(e,t);return{pair:a&&i?`${a}/${i}`:void 0,address:t,chain:e,protocolVersion:"V3",feeTierBps:r.fee,feeTierPercent:r.fee/1e4,currentPrice:r.currentPrice,token0:{symbol:a,address:r.token0},token1:{symbol:i,address:r.token1},...l?{uniswapUrl:l}:{}}}catch{return null}}};var pb=1e3,mb=365;function hb(n,e){let t=e/100;return{depositUsd:n,aprPercent:e,dailyUsd:n*t/mb,weeklyUsd:n*t/52,monthlyUsd:n*t/12,yearlyUsd:n*t}}var Jo=class extends A{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: `+We();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:Ye,required:!1}];service;constructor(e){super(),this.service=new Me(e)}async run(e,t){let r=await te(Ve(),e.chain,t);if(!r.ok)return r.result;let o=r.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:pb,d=await this.service.getPoolsByPair({chain:o,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(o),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. `+j,chain:o,pair:u,candidates:y.map(_e)}}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. "+j,chain:o,pair:u,pool:_e(h),...g?{autoPickedReason:g}:{}};let b=hb(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. "+Y+j,chain:o,pair:u,pool:_e(h),depositMode:l?"user-specified":"default-1000-example",estimate:b,...g?{autoPickedReason:g}:{}}}dedupeByFeeTier(e){let t=new Map;for(let r of e){if(r.feeTierBps===void 0)continue;let o=t.get(r.feeTierBps);(!o||r.tvlUsd>o.tvlUsd)&&t.set(r.feeTierBps,r)}return[...t.values()].sort((r,o)=>o.tvlUsd-r.tvlUsd)}};var Zo=class{service;constructor(e){this.service=new Me(e)}async resolveCandidates(e){let t=e.protocolVersion==="ALL"?"ALL":"V3",r=await this.service.getPoolsByPair({chain:e.chain,token0Symbol:e.token0Symbol,token1Symbol:e.token1Symbol,feeTierBps:e.feeTier,protocolVersion:t});return r.success?(r.data??[]).filter(o=>o.protocolVersion==="V3"?o.address!==void 0:t==="ALL").map(o=>({id:o.address,protocolVersion:o.protocolVersion,feeTier:o.feeTierBps,token0:o.token0,token1:o.token1,tvlUsd:o.tvlUsd,volume1DayUsd:o.volume1DayUsd,apr:o.apr})):null}};function Nt(n){if(typeof n=="number")return Number.isFinite(n)&&n>0?{kind:"token",value:n,raw:String(n)}:null;if(typeof n!="string")return null;let e=n.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 r=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(r){let s=parseFloat(r[1]??r[2]??r[3]??r[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 Np(n,e){switch(n.kind){case"token":return{ok:!0,amount:n.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*n.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:n.usd/e.usdPrice}}}function er(n){let e=n?.trim();if(!e)return"";let t=T(e);return!t||t==="the requested chain"||t===e?"":` (${t})`}function J(n){let e=er(n).trim();return e?` on ${e.slice(1,-1)}`:" on this chain"}var Lp={send:30000n,swap:1000000n};async function fb(n){try{let e=await Re(n).getGasPrice();return e>0n?e:0n}catch{return 0n}}function Ip(n,e){let t=Lp[n],r=gb(e);return r!==null&&r>t?r:t}function gb(n){let e=n?.tx?.gas??n?.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 Rc(n,e,t={}){let[r,o]=await Promise.all([fb(n),t.provider?Ri({provider:t.provider,srcChainId:n,dstChainId:t.dstChainId??n}):Promise.resolve(0n)]);return(r>0n?Ip(e,t.quoteGas)*r:0n)+o}async function ea(n,e,t={}){return Rc(n,e,t)}function ta(n,e,t){if(e<=0n)return n;let r=Dt(t)?.decimals;if(r===void 0)return n;let o=Number(e)/10**r;return!Number.isFinite(o)||o<=0?n:Math.max(0,n-o)}function Ec(n,e){let t=Dt(e)?.decimals;if(t===void 0)return null;let r=Number(n)/10**t;return Number.isFinite(r)?r:null}function Up(n){let{nativeBalance:e,feeWei:t,chainId:r}=n;if(t<=0n)return null;let o=Ec(t,r);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 na(n){let{chainId:e,gasKind:t,readNativeBalance:r,feeContext:o}=n;if(!e)return null;try{let[s,a]=await Promise.all([Rc(e,t,o??{}),r()]),i=Up({nativeBalance:a?.balance??0,feeWei:s,chainId:e});return i===null?null:{shortfall:i,nativeSymbol:a?.symbol??Dt(e)?.symbol??"the native coin",fee:Ec(s,e)??0}}catch{return null}}var st=class extends A{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 O(e))}async resolveContractAddress(e,t,r){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(r){let l=await this.moralis.getWalletTokenBalances({address:r,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:r,decimalsArg:o,chain:s,walletAddress:a}=e,i=this.parseDecimals(o),l=typeof r=="string"&&r.trim()?r.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 K(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 r=parseFloat(t);return Number.isFinite(r)&&r>0?t:null}async resolveAmountInput(e){let{rawAmount:t,tokenAddress:r,chain:o,walletAddress:s,gasKind:a}=e,i=Nt(t);if(!i)return null;let l=e.symbol??"the token",c=r.toLowerCase()==="native",d=!!a&&c&&!!o;if(i.kind==="token")return{amount:this.toPlainDecimal(i.value)};let u=await this.readTokenBalanceAndPrice(r,o,s),p=u?.balance;d&&u?.balance!==void 0&&(p=await this.computeNativeSpendable(o,a,u.balance));let m=Np(i,{balance:p,usdPrice:u?.usdPrice});return m.ok?{amount:this.floorToTokenDecimals(this.toPlainDecimal(m.amount),r,o,u?.decimals)}:m.reason==="no_balance"?{error:"amount_balance_unavailable",chain:o,_instructions:`Could not read the user's ${l} balance${J(o)} 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",chain:o,_instructions:`Could not get a USD price for ${l}${J(o)} 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,r){let o=await ea(e,t);return ta(r,o,e)}async resolveNativeSpendableFormatted(e,t,r){if(!(!e||!t))try{let o=await this.readTokenBalanceAndPrice("native",e,t);if(o?.balance===void 0)return;let s=await this.computeNativeSpendable(e,r,o.balance);return this.floorToTokenDecimals(this.toPlainDecimal(s),"native",e,o.decimals)}catch{return}}async readTokenBalanceAndPrice(e,t,r){if(!this.moralis||!r)return;let o=await this.moralis.getWalletTokenBalances({address:r,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=o.success?o.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,decimals:typeof l.decimals=="number"?l.decimals:void 0}}floorToTokenDecimals(e,t,r,o){let s=o??(t.toLowerCase()==="native"&&r?Dt(r)?.decimals:void 0);return s===void 0?e:je(e,s)}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 r=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.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+$/,"")),r?`-${d}`:d}formatSpendableUsd(e,t){if(e===void 0||t===void 0)return;let r=Number(e);if(!Number.isFinite(r)||!Number.isFinite(t)||t<=0)return;let o=r*t;if(!(!Number.isFinite(o)||o<=0))return this.toPlainDecimal(o)}async execute(e,t){let r=`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:r,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:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let r=this.requireWallet(t);if(!r.ok)return r.payload;let o=this.requireChain(e,t);if(!o){let h=typeof t?.query=="string"?t.query:void 0;return qr(this.actionType.replace(/_/g," "),h)}let s=await this.buildParameters(e,t);if(s&&typeof s=="object"&&"error"in s&&typeof s.error=="string"||s&&typeof s=="object"&&"actionButtons"in s&&Array.isArray(s.actionButtons)||s&&typeof s=="object"&&"ui"in s&&s.ui&&typeof s.ui=="object"&&typeof s.ui.component=="string")return s;let a=s,i=this.buildUI({parameters:a,chainId:o,walletAddress:r.address}),l=h=>{let g=a[h];return g!=null&&g!==""},c=this.userInputFields.filter(h=>!(Array.isArray(h.key)?h.key:[h.key]).some(l)).map(h=>h.label),d=this.userInputFields.map(h=>{let b=(Array.isArray(h.key)?h.key:[h.key]).find(l);return b?`${h.label}: ${a[b]}`:null}).filter(h=>h!=null),u=this.actionType.replace(/_/g," "),p='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.',m="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.",f=c.length>0?`The ${u} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${c.join(", ")}. `+(d.length>0?`Already provided: ${d.join("; ")}. `:"")+`${m} ${p}`:`The ${u} has all required details. In the user's language, briefly tell the user to review the details and submit to complete the ${u}. `+(d.length>0?`Details provided: ${d.join("; ")}. `:"")+`${m} ${p}`;return{ui:i,action:this.actionType,chainId:o,parameters:a,_instructions:f}}};var es=class extends st{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 r=Vu(e.native_symbol);if(r)return super.run({...e,chain:r},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:et,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 r={},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 u=typeof e.native_symbol=="string"&&e.native_symbol.trim()?e.native_symbol.trim():void 0,p=a?.symbol||u||Ga(o)||"their native coin";return{error:"no_native_balance",chain:o,_instructions:`The user wants to send ${p} but their wallet holds 0 ${p}${J(o)}. Tell them, in their language, that they do not have any ${p} to send${J(o)} \u2014 name that network explicitly so they know which one is empty \u2014 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&&(r.native_symbol=i),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?r.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(r.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&&(r.amount=l.amount);let c=await this.resolveNativeSpendableFormatted(o,s,"send");c!==void 0&&(r.spendable=c);let d=this.formatSpendableUsd(c,a.usdPrice);return d!==void 0&&(r.spendableUsd=d),r}};var ts=class extends st{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:et,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 r=this.normaliseAddress(e.contract_address)!=null,o=typeof e.token_symbol=="string"&&e.token_symbol.trim().length>0;if(!r&&!o&&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,P)=>(P.usd_value??0)-(v.usd_value??0)).slice(0,8);if(h.length===0)return{error:"no_token_holdings",chain:u,_instructions:`The wallet does not hold any sendable tokens${J(u)}. Tell the user they have nothing to send${J(u)}, naming that network explicitly, 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 P=v.symbol,S=v.balance_formatted?this.cleanAmountString(v.balance_formatted):"",x=v.name?v.name:"",L=Jr(v.usd_value)??"";return{label:`${x}:${S} ${P} ${L}`.trim(),prompt:this.buildSendPrompt(y,P,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,r){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||!r||!a){let m=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:t,walletAddress:r});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:r,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,chain:t,_instructions:`The user does not hold any ${p} in their wallet${J(t)}, so there is nothing to send. Tell them (in their language) that they don't have any ${p} to send${J(t)} \u2014 name that network explicitly so they know which one is empty \u2014 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,r,o,s){let i=(e&&e.includes("{symbol}")?e:"send {amount} {symbol} to {to} on {chain}").replace(/\{symbol\}/g,t).replace(/\{amount\}/g,r??"");return i=this.fillOrDropPhrase(i,"{to}",o),i=this.fillOrDropPhrase(i,"{chain}",s),i.replace(/\s+/g," ").trim()}fillOrDropPhrase(e,t,r){if(r)return e.split(t).join(r);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 ns=class extends st{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:et,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 r=this.requireChain(e,t)??void 0,o=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:r,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 Li(n){let{action:e,fromSym:t,toSym:r,amount:o,spendable:s}=n,a=e==="swap"?`swap ${t} to ${r}`:`buy ${r} with ${t}`,i=e==="swap"?"swapping":"buying",l=e==="swap"?`swap ${o} ${t} to ${r}`:`buy ${r} 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 qt=n=>n.logo||n.icon_image||n.logoURI||n.thumbnail||void 0,Ii=n=>typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0;async function ra(n){let{moralis:e,tokenAddress:t,chain:r}=n;if(!e)return null;let o=t==="native"?le:t;try{let s=await e.getTokenMetadata({address:o,chain:r});if(!s.success||!s.data)return null;let a=s.data,i=$n(a);if(!i?.yieldProtocol)return Ii(a.usd_price)??null;if(Vr(i.yieldProtocol)&&!(a.decimals>0))return null;let l=await e.getUnderlyingPricesUSD(r,[i.yieldAsset]),c=await $s(r||Be,{address:o,decimals:a.decimals,price:Wr(i.yieldAsset,l,a.usd_price),yieldProtocol:i.yieldProtocol,yieldAsset:i.yieldAsset});return Ii(c??void 0)??null}catch{return null}}var yb=n=>{if(!/e/i.test(n))return n;let e=Number(n);return Number.isFinite(e)?xs(e):n};async function oa(n){let{moralis:e,walletAddress:t,tokenAddress:r,chain:o,kind:s="swap",feeContext:a,dbg:i}=n;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:r,chain:o,ok:l.success,count:c.length});let d=r.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:r}),null;let p=Number(u.balance_formatted);if(!Number.isFinite(p)||p<=0)return i?.("readSpendableBalance: zero/invalid balance \u2192 null",{tokenAddress:r,balance:u.balance_formatted}),null;if(d==="native"&&o){let m=await ea(o,s,a??{}),f=ta(p,m,o);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=typeof u.decimals=="number"?u.decimals:18,g=je(xs(f),h);return Dp({balanceFormatted:g,balanceNum:f,symbol:u.symbol,decimals:h,logo:qt(u),usdPrice:Ii(u.usd_price)})}return i?.("readSpendableBalance: held",{tokenAddress:r,balance:u.balance_formatted,symbol:u.symbol}),Dp({balanceFormatted:u.balance_formatted,balanceNum:p,symbol:u.symbol,decimals:typeof u.decimals=="number"?u.decimals:void 0,logo:qt(u),usdPrice:Ii(u.usd_price)})}function Dp(n){let e=yb(n.balanceFormatted),t=n.decimals===void 0?null:Mn(e,n.decimals);return{...n,balanceFormatted:e,rawAmount:t?.toString()}}async function Ui(n,e){let t=n?Ce(n)?.nativeCurrency:void 0,r=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})),o=[];if(r.forEach((a,i)=>{if(!a||a.address==="native"||!R(a.address))return;let l=a.symbolIsOnchain===!0&&!!a.symbol?.trim(),c=typeof a.decimals=="number"&&Number.isFinite(a.decimals);l&&c||o.push({index:i,address:a.address})}),!n||o.length===0)return r;let s=await At(n,o.map(a=>a.address)).catch(()=>[]);return o.forEach((a,i)=>{let l=s[i];if(!l)return;let c=r[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)}),r}function Di(n,e){let t=n?.trim().toLowerCase(),r=e?.trim().toLowerCase();return!t||!r?!1:t===r}var rs=class extends A{name="open-buy-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new O(e),this.pantograph=new ye({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. CHAINS: when the user names a DIFFERENT network per side \u2014 "buy USDC on Base with ETH on Arbitrum" \u2014 you MUST put each one in `token_chain` and `pay_with_chain` (NOT in `chain`, and never drop one of them): that is a cross-chain request and the tool answers it with the correct unsupported message. Use the single `chain` parameter only when ONE network covers the whole request.';parameters=[{name:"chain",type:"string",description:et,required:!1},{name:"token_chain",type:"string",description:Br("token being BOUGHT"),required:!1},{name:"pay_with_chain",type:"string",description:Br("token being SPENT to pay"),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 r=`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:r,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:r,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=Ka(e.pay_with_chain,e.token_chain);if(o)return ja("buy",o);if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return qr("buy",a)}return this.buildResult(e,t)}async buildResult(e,t){this.correctAmountSide(e,t),this.dropUnmentionedPayToken(e,t),this.dropInventedAmounts(e,t);let r=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}),!r&&!o)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,r,s,a,"dest"),this.resolveSide(e.pay_with_address,e.pay_with_symbol,s,a,"pay")]),[c,d]=await Ui(s,[i.address?{...i,address:i.address}:void 0,l.address?{...l,address:l.address}:void 0]),u=i.address,p=c?.symbol??r,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=Nt(e.pay_with_amount),v=!!k&&k.kind!=="token",P=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||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(Di(h,u))return this.dbg("\u2192 same token both sides",{payAddr:h,destContract:u,paySymbol:g,destSymbol:p}),{error:"same_token",_instructions:`The user asked to buy ${p} and pay with ${g??p} \u2014 the SAME token on both sides, which buys nothing and cannot be done. Tell them, in their language, that the token they pay with has to be different from the token they are buying, and ask which token they want to pay with instead. Do NOT proceed. Do NOT render the form. 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,P=y,v=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:w,derivedFromBuy:P})}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:P,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 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 r=t.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(!r)return null;let o=parseFloat(r[1]);return Number.isFinite(o)&&o>0?r[1]:null}correctAmountSide(e,t){let r=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(!r||!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 d=l?a:i,u=d.match(/[0-9]*\.?[0-9]+/)?.[0];if(!u)return;let p=this.nearestSymbolSide(r,u,o,s);p&&(p==="pay"&&l?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:d,buySym:o,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:o,paySym:s}),e.buy_amount=d,e.pay_with_amount=""))}dropUnmentionedPayToken(e,t){let r=typeof t?.query=="string"?t.query:"";if(!r)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=r.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?Dt(m)?.symbol:void 0;f&&u.push(f.toLowerCase())}u.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 r=typeof t?.query=="string"?t.query:"";if(!r)return;let o=(r.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(d=>d===c)||(this.dbg(`dropInventedAmounts: clearing invented ${a}`,{val:i}),e[a]=""))};s("buy_amount"),s("pay_with_amount")}nearestSymbolSide(e,t,r,o){let s=e.toLowerCase(),a=s.indexOf(t.toLowerCase()),i=this.indexOfToken(s,r.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)),d=c(i,r.length),u=c(l,o.length);return u===d?null:u<d?"pay":"buy"}indexOfToken(e,t){if(!t)return-1;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=e.match(new RegExp(`(?:^|[^a-z0-9])(${r})(?:[^a-z0-9]|$)`));return o&&o.index!==void 0?o.index+o[0].indexOf(o[1]):-1}requireChain(e,t){return K(e.chain,t)}async resolveContractAddress(e,t,r){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(r){let l=await this.moralis.getWalletTokenBalances({address:r,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:qt(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:qt(c),symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}async resolveSide(e,t,r,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,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:r,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(u,r,o);return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,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:r,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(r);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){return ra({moralis:this.moralis,tokenAddress:e,chain:t})}async resolvePayAmountSpec(e,t,r,o,s,a){let i=Nt(e);if(!i)return null;let l=d=>a===void 0?d:je(d,a);if(i.kind==="token")return l(Fn(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!o)return null;let d=await this.readPayBalance(o,t,r);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):Bn(d.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,u)}let c=await this.getUsdPrice(t,r);return this.dbg("resolvePayAmountSpec: usd",{usd:i.usd,paySymbol:s,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveBuyAmountSpec(e,t,r,o){let s=Nt(e);if(!s)return null;if(s.kind==="token")return Fn(e)??this.toPlainDecimal(s.value);if(s.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,r);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:r,destSymbol:o,destContract:s}=e,a=this.requireChain(t,r)??void 0,i=this.moralis,l=r.walletAddress,c=await i.getWalletTokenBalances({address:l,chain:a,excludeSpam:!1,excludeUnverifiedContracts:!1}),d=c.success?c.data?.result??[]:[],u=s?.toLowerCase(),p=o.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",chain:a,_instructions:`The wallet has no tokens that can pay for this purchase${J(a)}. Tell the user to top up first, naming that network explicitly so they know which one is empty. 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)} `:"",P=Jr(y.usd_value),S=P?` ${P}`:"",x=`${k}: ${v}${w}${S}`,L=f?this.buildBuyWithPrompt(g,o,w,f,null,a):this.buildBuyWithPrompt(g,o,w,null,h,a);return{label:x,prompt:L}}),_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:r,chain:o,destSymbol:s,destContract:a,payAddr:i,payAmount:l,buyAmount:c,derivedFromBuy:d}=e,u=r.walletAddress,p=await this.readPayBalance(u,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:r,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}${J(o)}. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${m}${J(o)}, naming that network explicitly (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${m} tr\xEAn ${J(o).replace(" on ","")}.'), 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 na({chainId:o,gasKind:"swap",readNativeBalance:()=>this.readNativeHeldBalance(u,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 f=p.decimals!==void 0?je(l,p.decimals):l;if(on(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:"",...o===void 0?{}:{chain:o}}),b=d?`Buying ${d} ${s} needs about ${l} ${m}, but they only have ${h} ${m}${J(o)} \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}${J(o)} \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,r){return oa({moralis:this.moralis,walletAddress:e,tokenAddress:t,chain:r,kind:"swap",dbg:(o,s)=>this.dbg(o,s)})}async readNativeHeldBalance(e,t){if(!this.moralis)return{balance:0};try{let r=await this.moralis.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=(r.success?r.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:r,paySymbol:o,destSymbol:s,buyWithTemplate:a,chain:i}=e,l=r??18;return[25,50,75,100].map(d=>{let u=Bn(this.cleanAmountString(t),BigInt(d),100n,l);return{label:`${d}%`,prompt:this.buildBuyWithPrompt(a,s,o,null,u,i)}})}async buildAmountForm(e){let{userContext:t,chain:r,destContract:o,destSymbol:s,destDecimals:a,destLogo:i,payAddr:l,payAmount:c}=e,d=t.walletAddress;if(!r)return null;let u=Ce(r);if(!u)return null;let p=await this.readPayBalance(d,l,r),m=e.paySymbol??p?.symbol;if(!m)return null;let f=l==="native",h=p?.decimals??e.payDecimals??(f?u.nativeCurrency.decimals??18:void 0);if(h===void 0)return null;let g=p?.balanceFormatted,b=p?.rawAmount??(g?Mn(g,h)?.toString():void 0),y=await this.getUsdPrice(o,r).catch(()=>null);return{ui:{component:"SwapTokenForm",props:{chain:{hexId:r,name:u.name},fromToken:{address:f?"native":l,symbol:m,decimals:h,amount:g,rawAmount:b??void 0,logo:p?.logo,usdPrice:p?.usdPrice},toToken:{address:o,symbol:s,decimals:a,logo:i,usdPrice:y??void 0},walletAddress:d,intent:"buy",initialAmount:c}},_instructions:Li({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 r=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.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+$/,"")),r?`-${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,r){return(e&&e.includes("{token}")?e:"buy {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()+er(r)}buildBuyWithPrompt(e,t,r,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,r).replace(/\{buy_amount\}/g,o??"").replace(/\{pay_amount\}/g,s??"").replace(/\s+/g," ").trim()+er(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 r=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:r,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,r)}}),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(`
|
|
214
214
|
`)+`
|
|
215
215
|
|
|
216
216
|
Is there any token you want to buy?`;return{actionButtons:d,_instructions:`The trending tokens are on ${r?T(r):"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:
|
|
217
217
|
|
|
218
|
-
${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),r=t.match(/^0\.0*([1-9]\d{0,3})/);return r?t.slice(0,(r[0].length||0)+0):t}};var os=class extends A{name="open-swap-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new O(e),this.pantograph=new ye({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. CHAINS: when the user names a DIFFERENT network for each side \u2014 "swap ETH on Optimism to ETH on Base", "\u0111\u1ED5i ETH tr\xEAn OP sang ETH tr\xEAn Base" \u2014 you MUST put each one in `from_chain` and `to_chain` (NOT in `chain`, and never drop one of them): that is a cross-chain request and the tool answers it with the correct unsupported message. Use the single `chain` parameter only when ONE network covers the whole request.';parameters=[{name:"chain",type:"string",description:Ze,required:!1},{name:"from_chain",type:"string",description:Fr("SOURCE token being swapped FROM"),required:!1},{name:"to_chain",type:"string",description:Fr("DESTINATION token being received"),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 r=`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:r,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:r,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=Ka(e.from_chain,e.to_chain);if(o)return ja("swap",o);if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return Br("swap",a)}return this.buildResult(e,t)}async buildResult(e,t){let r=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}),!r&&!o){this.dbg("\u2192 Branch 0: source picker (no source token named)");let x=typeof e.to_address=="string"?e.to_address.trim():"",L=s||x;return await this.buildSourcePicker(e,t,L?{symbol:L,amount:this.normaliseAmount(e.to_amount)}:void 0)}let[l,c]=await Promise.all([this.resolveSide(e.from_address,r,a,i,"from"),this.resolveSide(e.to_address,s,a,i,"to")]),[d,u]=await Ui(a,[l.address?{...l,address:l.address}:void 0,c.address?{...c,address:c.address}:void 0]),p=l.address,m=d?.symbol??r,f=d?.decimals,h=c.address,g=u?.symbol??s,b=u?.decimals,y=c.logo;if(Di(p,h))return this.dbg("\u2192 same token both sides",{fromContract:p,toContract:h,fromSym:m,toSym:g}),{error:"same_token",_instructions:`The user asked to swap ${m} into ${g} \u2014 the SAME token on both sides, which is not a swap and cannot be done. Tell them, in their language, that the two tokens have to be different, and ask which token they want to receive instead. Do NOT proceed. Do NOT render the form. Do NOT mention tool names, UI, or forms.`};let 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=_t(e.from_amount),P=!!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||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(!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 x=await this.deriveFromAmountFromTo({chain:a,toAmount:w,toContract:h,toSym:g,fromContract:p,fromSym:m});if(!x)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=x,S=w,P=!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 x=await this.checkFromBalance({args:e,userContext:t,chain:a,fromContract:p,fromSym:m,toSym:g,fromAmount:k,toAmount:w,derivedFromTo:S,amountSizedToBalance:P});if(x)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:x.error,hasButtons:Array.isArray(x.actionButtons)}),x;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!w&&t?.walletAddress){this.dbg("Branch 1.5: building amount form",{fromAmount:k});let x=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(x)return this.dbg("\u2192 Branch 1.5: amount form returned"),x;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 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 r=parseFloat(t);return Number.isFinite(r)&&r>0?t:null}requireChain(e,t){return K(e.chain,t)}async resolveContractAddress(e,t,r){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(r){let l=await this.moralis.getWalletTokenBalances({address:r,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:qt(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:qt(c),symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}async resolveSide(e,t,r,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,d=m=>m.toLowerCase()===ue?"native":m,u=l??c??(a||void 0);if(!u)return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(u,r,o);return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,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:r,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(r);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){return ra({moralis:this.moralis,tokenAddress:e,chain:t})}async resolveFromAmountSpec(e,t,r,o,s,a){let i=_t(e);if(!i)return null;let l=d=>a===void 0?d:Dt(d,a);if(i.kind==="token")return l(qn(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!o)return null;let d=await this.readFromBalance(o,t,r);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):$n(d.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,u)}let c=await this.getUsdPrice(t,r);return this.dbg("resolveFromAmountSpec: usd",{usd:i.usd,fromSym:s,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveToAmountSpec(e,t,r,o){let s=_t(e);if(!s)return null;if(s.kind==="token")return qn(e)??this.toPlainDecimal(s.value);if(s.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,r);return this.dbg("resolveToAmountSpec: usd",{usd:s.usd,toSym:o,price:a}),a?this.trimAmount(s.usd/a):null}async buildSourcePicker(e,t,r){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,f)=>(f.usd_value??0)-(m.usd_value??0)).slice(0,8);if(l.length===0)return{error:"no_swap_holdings",chain:o,_instructions:`The wallet holds no tokens to swap${Q(o)}. Tell the user to top up first, naming that network explicitly so they know which one is empty. 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=Qr(m.usd_value),y=b?` ${b}`:"",w=`${h}: ${g}${f}${y}`,k=r?this.buildSwapToPrompt(d,f,r.symbol,null,r.amount??null,o):this.buildSwapFromPrompt(c,f,o);return{label:w,prompt:k}}),p=r?`state what the user wants to do, naming the destination they already gave (e.g., 'B\u1EA1n mu\u1ED1n swap sang ${r.symbol}.' / 'You want to swap to ${r.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:r,fromSym:o,fromContract:s}=e,a=this.requireChain(t,r)??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=o.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 ${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),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 P=v.symbol,S=h?this.buildSwapToPrompt(b,o,P,h,null,a):this.buildSwapToPrompt(b,o,P,null,g,a);return{label:P,prompt:S}}),k=f.map((v,P)=>{let S=v.name?.trim()||v.symbol,x=v.symbol,L=typeof v.usdPrice=="number"&&v.usdPrice>0?`$${this.formatPrice(v.usdPrice)}`:"N/A",E=v.pricePercentChange?.["24h"],ke=typeof E=="number"&&Number.isFinite(E)?` (${E>0?"+":E<0?"-":""}${this.formatPercent(Math.abs(E))}%)`:"";return`${P+1}. ${S} (${x}) \u2014 ${L}${ke}`}).join(`
|
|
218
|
+
${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),r=t.match(/^0\.0*([1-9]\d{0,3})/);return r?t.slice(0,(r[0].length||0)+0):t}};var os=class extends A{name="open-swap-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new O(e),this.pantograph=new ye({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. CHAINS: when the user names a DIFFERENT network for each side \u2014 "swap ETH on Optimism to ETH on Base", "\u0111\u1ED5i ETH tr\xEAn OP sang ETH tr\xEAn Base" \u2014 you MUST put each one in `from_chain` and `to_chain` (NOT in `chain`, and never drop one of them): that is a cross-chain request and the tool answers it with the correct unsupported message. Use the single `chain` parameter only when ONE network covers the whole request.';parameters=[{name:"chain",type:"string",description:et,required:!1},{name:"from_chain",type:"string",description:Br("SOURCE token being swapped FROM"),required:!1},{name:"to_chain",type:"string",description:Br("DESTINATION token being received"),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 r=`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:r,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:r,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=Ka(e.from_chain,e.to_chain);if(o)return ja("swap",o);if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return qr("swap",a)}return this.buildResult(e,t)}async buildResult(e,t){let r=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}),!r&&!o){this.dbg("\u2192 Branch 0: source picker (no source token named)");let x=typeof e.to_address=="string"?e.to_address.trim():"",L=s||x;return await this.buildSourcePicker(e,t,L?{symbol:L,amount:this.normaliseAmount(e.to_amount)}:void 0)}let[l,c]=await Promise.all([this.resolveSide(e.from_address,r,a,i,"from"),this.resolveSide(e.to_address,s,a,i,"to")]),[d,u]=await Ui(a,[l.address?{...l,address:l.address}:void 0,c.address?{...c,address:c.address}:void 0]),p=l.address,m=d?.symbol??r,f=d?.decimals,h=c.address,g=u?.symbol??s,b=u?.decimals,y=c.logo;if(Di(p,h))return this.dbg("\u2192 same token both sides",{fromContract:p,toContract:h,fromSym:m,toSym:g}),{error:"same_token",_instructions:`The user asked to swap ${m} into ${g} \u2014 the SAME token on both sides, which is not a swap and cannot be done. Tell them, in their language, that the two tokens have to be different, and ask which token they want to receive instead. Do NOT proceed. Do NOT render the form. Do NOT mention tool names, UI, or forms.`};let 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=Nt(e.from_amount),P=!!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||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(!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 x=await this.deriveFromAmountFromTo({chain:a,toAmount:w,toContract:h,toSym:g,fromContract:p,fromSym:m});if(!x)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=x,S=w,P=!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 x=await this.checkFromBalance({args:e,userContext:t,chain:a,fromContract:p,fromSym:m,toSym:g,fromAmount:k,toAmount:w,derivedFromTo:S,amountSizedToBalance:P});if(x)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:x.error,hasButtons:Array.isArray(x.actionButtons)}),x;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!w&&t?.walletAddress){this.dbg("Branch 1.5: building amount form",{fromAmount:k});let x=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(x)return this.dbg("\u2192 Branch 1.5: amount form returned"),x;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 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 r=parseFloat(t);return Number.isFinite(r)&&r>0?t:null}requireChain(e,t){return K(e.chain,t)}async resolveContractAddress(e,t,r){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(r){let l=await this.moralis.getWalletTokenBalances({address:r,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:qt(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:qt(c),symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}async resolveSide(e,t,r,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,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:r,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(u,r,o);return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,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:r,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(r);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){return ra({moralis:this.moralis,tokenAddress:e,chain:t})}async resolveFromAmountSpec(e,t,r,o,s,a){let i=Nt(e);if(!i)return null;let l=d=>a===void 0?d:je(d,a);if(i.kind==="token")return l(Fn(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!o)return null;let d=await this.readFromBalance(o,t,r);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):Bn(d.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,u)}let c=await this.getUsdPrice(t,r);return this.dbg("resolveFromAmountSpec: usd",{usd:i.usd,fromSym:s,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveToAmountSpec(e,t,r,o){let s=Nt(e);if(!s)return null;if(s.kind==="token")return Fn(e)??this.toPlainDecimal(s.value);if(s.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,r);return this.dbg("resolveToAmountSpec: usd",{usd:s.usd,toSym:o,price:a}),a?this.trimAmount(s.usd/a):null}async buildSourcePicker(e,t,r){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,f)=>(f.usd_value??0)-(m.usd_value??0)).slice(0,8);if(l.length===0)return{error:"no_swap_holdings",chain:o,_instructions:`The wallet holds no tokens to swap${J(o)}. Tell the user to top up first, naming that network explicitly so they know which one is empty. 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=Jr(m.usd_value),y=b?` ${b}`:"",w=`${h}: ${g}${f}${y}`,k=r?this.buildSwapToPrompt(d,f,r.symbol,null,r.amount??null,o):this.buildSwapFromPrompt(c,f,o);return{label:w,prompt:k}}),p=r?`state what the user wants to do, naming the destination they already gave (e.g., 'B\u1EA1n mu\u1ED1n swap sang ${r.symbol}.' / 'You want to swap to ${r.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:r,fromSym:o,fromContract:s}=e,a=this.requireChain(t,r)??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=o.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 ${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),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 P=v.symbol,S=h?this.buildSwapToPrompt(b,o,P,h,null,a):this.buildSwapToPrompt(b,o,P,null,g,a);return{label:P,prompt:S}}),k=f.map((v,P)=>{let S=v.name?.trim()||v.symbol,x=v.symbol,L=typeof v.usdPrice=="number"&&v.usdPrice>0?`$${this.formatPrice(v.usdPrice)}`:"N/A",E=v.pricePercentChange?.["24h"],ke=typeof E=="number"&&Number.isFinite(E)?` (${E>0?"+":E<0?"-":""}${this.formatPercent(Math.abs(E))}%)`:"";return`${P+1}. ${S} (${x}) \u2014 ${L}${ke}`}).join(`
|
|
219
219
|
`)+`
|
|
220
220
|
|
|
221
221
|
Which token do you want to receive?`;return{actionButtons:y,_instructions:`The user wants to swap ${o} 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 ${o} sang token kh\xE1c \u2014 \u0111\xE2y l\xE0 c\xE1c token \u0111ang trending tr\xEAn <chain name>:' / '\u{1F4C8} You want to swap ${o} \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:
|
|
222
222
|
|
|
223
|
-
${k}`}}async checkFromBalance(e){let{args:t,userContext:r,chain:o,fromContract:s,fromAmount:a,derivedFromTo:i}=e,l=r.walletAddress,c=await this.readFromBalance(l,s,o),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,r,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}${Q(o)}. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${d}${Q(o)}, naming that network explicitly (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${d} tr\xEAn ${Q(o).replace(" on ","")}.'), 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 na({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 ${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?Dt(a,c.decimals):a;if(sn(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:"",...o===void 0?{}:{chain:o}}),f=i?`Receiving ${i} of the destination token needs about ${a} ${d}, but they only have ${p} ${d}${Q(o)} \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}${Q(o)} \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,r){return oa({moralis:this.moralis,walletAddress:e,tokenAddress:t,chain:r,kind:"swap",dbg:(o,s)=>this.dbg(o,s)})}async readNativeHeldBalance(e,t){if(!this.moralis)return{balance:0};try{let r=await this.moralis.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=(r.success?r.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:r,fromSym:o,toSym:s,swapToTemplate:a,chain:i}=e,l=r??18;return[25,50,75,100].map(d=>{let u=$n(this.cleanAmountString(t),BigInt(d),100n,l);return{label:`${d}%`,prompt:this.buildSwapToPrompt(a,o,s,u,null,i)}})}async buildAmountForm(e){let{userContext:t,chain:r,fromContract:o,toContract:s,toSym:a,toDecimals:i,toLogo:l,fromAmount:c}=e,d=t.walletAddress;if(!r)return null;let u=Ce(r);if(!u)return null;let p=await this.readFromBalance(d,o,r),m=e.fromSym??p?.symbol;if(!m)return null;let f=o==="native",h=p?.decimals??e.fromDecimals??(f?u.nativeCurrency.decimals??18:void 0);if(h===void 0)return null;let g=p?.balanceFormatted,b=p?.rawAmount??(g?Bn(g,h)?.toString():void 0),y=await this.getUsdPrice(s,r).catch(()=>null);return{ui:{component:"SwapTokenForm",props:{chain:{hexId:r,name:u.name},fromToken:{address:f?"native":o,symbol:m,decimals:h,amount:g,rawAmount:b??void 0,logo:p?.logo,usdPrice:p?.usdPrice},toToken:{address:s,symbol:a,decimals:i,logo:l,usdPrice:y??void 0},walletAddress:d,intent:"swap",initialAmount:c}},_instructions:Li({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 r=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.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+$/,"")),r?`-${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,r){return(e&&e.includes("{token}")?e:"swap {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()+tr(r)}buildSwapToPrompt(e,t,r,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,r).replace(/\{from_amount\}/g,o??"").replace(/\{to_amount\}/g,s??"").replace(/\s+/g," ").trim()+tr(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),r=t.match(/^0\.0*([1-9]\d{0,3})/);return r?t.slice(0,(r[0].length||0)+0):t}};var _c="{name}",ss=class extends ot{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:Ze,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 r=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),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||!o)return this.paramsFromInputs({contract:s,tokenId:a,toAddress:l,standardArg:c,nftName:i,amountInt:d});let u=await this.moralis.getWalletNFTs({address:o,chain:r,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(r);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:r,args:e,toAddress:l,amountInt:d,walletAddress:o,nftName:i})}async buildPicker(e,t){let{chain:r,args:o,toAddress:s,amountInt:a,walletAddress:i,nftName:l}=t,c=await this.resolveImages(e,r),d=this.normaliseString(o.pick_prompt_template),u=T(r),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]??jn(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:r,nft:o,toAddress:s,amountInt:a}=t,l=[`${(e?.includes(_c)?e:`send my ${_c}`).split(_c).join(r).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 r=await yi(t,e.map(o=>({contract:o.token_address,tokenId:o.token_id})));return e.map((o,s)=>r[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 r=e.token_address??"";return r.length>10?`${r.slice(0,6)}\u2026${r.slice(-4)}`:r}matchNfts(e,t){let r=t.contract?t.contract.toLowerCase():void 0,o=t.nftName?t.nftName.toLowerCase():void 0;return e.filter(s=>{if(r&&s.token_address.toLowerCase()!==r||t.tokenId&&s.token_id!==t.tokenId)return!1;if(o&&!r&&!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 r=(e.contract_type||"").toUpperCase(),o=e.amount&&e.amount.trim()?e.amount.trim():"1",s=r==="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:r||"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 sa=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:
|
|
223
|
+
${k}`}}async checkFromBalance(e){let{args:t,userContext:r,chain:o,fromContract:s,fromAmount:a,derivedFromTo:i}=e,l=r.walletAddress,c=await this.readFromBalance(l,s,o),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,r,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}${J(o)}. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${d}${J(o)}, naming that network explicitly (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${d} tr\xEAn ${J(o).replace(" on ","")}.'), 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 na({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 ${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?je(a,c.decimals):a;if(on(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:"",...o===void 0?{}:{chain:o}}),f=i?`Receiving ${i} of the destination token needs about ${a} ${d}, but they only have ${p} ${d}${J(o)} \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}${J(o)} \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,r){return oa({moralis:this.moralis,walletAddress:e,tokenAddress:t,chain:r,kind:"swap",dbg:(o,s)=>this.dbg(o,s)})}async readNativeHeldBalance(e,t){if(!this.moralis)return{balance:0};try{let r=await this.moralis.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=(r.success?r.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:r,fromSym:o,toSym:s,swapToTemplate:a,chain:i}=e,l=r??18;return[25,50,75,100].map(d=>{let u=Bn(this.cleanAmountString(t),BigInt(d),100n,l);return{label:`${d}%`,prompt:this.buildSwapToPrompt(a,o,s,u,null,i)}})}async buildAmountForm(e){let{userContext:t,chain:r,fromContract:o,toContract:s,toSym:a,toDecimals:i,toLogo:l,fromAmount:c}=e,d=t.walletAddress;if(!r)return null;let u=Ce(r);if(!u)return null;let p=await this.readFromBalance(d,o,r),m=e.fromSym??p?.symbol;if(!m)return null;let f=o==="native",h=p?.decimals??e.fromDecimals??(f?u.nativeCurrency.decimals??18:void 0);if(h===void 0)return null;let g=p?.balanceFormatted,b=p?.rawAmount??(g?Mn(g,h)?.toString():void 0),y=await this.getUsdPrice(s,r).catch(()=>null);return{ui:{component:"SwapTokenForm",props:{chain:{hexId:r,name:u.name},fromToken:{address:f?"native":o,symbol:m,decimals:h,amount:g,rawAmount:b??void 0,logo:p?.logo,usdPrice:p?.usdPrice},toToken:{address:s,symbol:a,decimals:i,logo:l,usdPrice:y??void 0},walletAddress:d,intent:"swap",initialAmount:c}},_instructions:Li({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 r=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.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+$/,"")),r?`-${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,r){return(e&&e.includes("{token}")?e:"swap {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()+er(r)}buildSwapToPrompt(e,t,r,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,r).replace(/\{from_amount\}/g,o??"").replace(/\{to_amount\}/g,s??"").replace(/\s+/g," ").trim()+er(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),r=t.match(/^0\.0*([1-9]\d{0,3})/);return r?t.slice(0,(r[0].length||0)+0):t}};var _c="{name}",ss=class extends st{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:et,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 r=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),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||!o)return this.paramsFromInputs({contract:s,tokenId:a,toAddress:l,standardArg:c,nftName:i,amountInt:d});let u=await this.moralis.getWalletNFTs({address:o,chain:r,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(r);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:r,args:e,toAddress:l,amountInt:d,walletAddress:o,nftName:i})}async buildPicker(e,t){let{chain:r,args:o,toAddress:s,amountInt:a,walletAddress:i,nftName:l}=t,c=await this.resolveImages(e,r),d=this.normaliseString(o.pick_prompt_template),u=T(r),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]??Gn(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:r,nft:o,toAddress:s,amountInt:a}=t,l=[`${(e?.includes(_c)?e:`send my ${_c}`).split(_c).join(r).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 r=await yi(t,e.map(o=>({contract:o.token_address,tokenId:o.token_id})));return e.map((o,s)=>r[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 r=e.token_address??"";return r.length>10?`${r.slice(0,6)}\u2026${r.slice(-4)}`:r}matchNfts(e,t){let r=t.contract?t.contract.toLowerCase():void 0,o=t.nftName?t.nftName.toLowerCase():void 0;return e.filter(s=>{if(r&&s.token_address.toLowerCase()!==r||t.tokenId&&s.token_id!==t.tokenId)return!1;if(o&&!r&&!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 r=(e.contract_type||"").toUpperCase(),o=e.amount&&e.amount.trim()?e.amount.trim():"1",s=r==="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:r||"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 sa=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:
|
|
224
224
|
|
|
225
225
|
`+this.message},duration:0}}};function Oi(n,e,t){let r=t?.[e.name];n.register(r?new sa(e,r):e)}var as=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 is=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 r=t.map(a=>`${a.role==="user"?"User":"Assistant"}: ${a.content}`).join(`
|
|
226
226
|
`),o=[{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:
|
|
@@ -243,9 +243,9 @@ FAQ ENTRIES:
|
|
|
243
243
|
`,ls=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 r=this.entries.map((s,a)=>`[${a}] ${s.question}`).join(`
|
|
244
244
|
`),o=[{role:"user",content:bb+r+`
|
|
245
245
|
|
|
246
|
-
USER QUERY: ${e}`,timestamp:0}];try{let i=(await this.llm.chat(o)).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,r){let o=this.tokenize(e);if(o.size===0)return[];let s=[];for(let a of this.entries){let i=this.tokenize(a.question),l=this.jaccardSimilarity(o,i);l>=r&&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(r=>r.length>1);return new Set(t)}jaccardSimilarity(e,t){if(e.size===0||t.size===0)return 0;let r=0;for(let s of e)t.has(s)&&r++;let o=e.size+t.size-r;return o===0?0:r/o}};var aa=require("@upstash/vector"),wb="https://perfect-octopus-59684-us1-vector.upstash.io",kb="ABkFMHBlcmZlY3Qtb2N0b3B1cy01OTY4NC11czFhZG1pbk56WXdOV0k0T0RndFpUaGtOeTAwWWpjMkxXRmtNRFV0WW1WaU9UaGtOMlV5T0ROaQ==",
|
|
246
|
+
USER QUERY: ${e}`,timestamp:0}];try{let i=(await this.llm.chat(o)).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,r){let o=this.tokenize(e);if(o.size===0)return[];let s=[];for(let a of this.entries){let i=this.tokenize(a.question),l=this.jaccardSimilarity(o,i);l>=r&&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(r=>r.length>1);return new Set(t)}jaccardSimilarity(e,t){if(e.size===0||t.size===0)return 0;let r=0;for(let s of e)t.has(s)&&r++;let o=e.size+t.size-r;return o===0?0:r/o}};var aa=require("@upstash/vector"),wb="https://perfect-octopus-59684-us1-vector.upstash.io",kb="ABkFMHBlcmZlY3Qtb2N0b3B1cy01OTY4NC11czFhZG1pbk56WXdOV0k0T0RndFpUaGtOeTAwWWpjMkxXRmtNRFV0WW1WaU9UaGtOMlV5T0ROaQ==",Tn=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)??wb,r=e.token??(typeof process<"u"?process.env.UPSTASH_VECTOR_REST_TOKEN:void 0)??kb;this.index=new aa.Index({url:t,token:r}),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"?aa.FusionAlgorithm.RRF:aa.FusionAlgorithm.DBSF,this.debug=e.debug??!1}async search(e,t,r){let o=r?.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(o&&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) `+(o?`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,r=await Promise.all(e.map(async o=>({id:o.id??await this.deriveId(o.question),data:this.buildEmbedText(o),metadata:{question:o.question,answer:o.answer,...o.metadata??{}}})));return await t.upsert(r),this.debug&&console.log(`[UpstashKnowledgeBase] upserted ${r.length} entr${r.length===1?"y":"ies"} (strategy=${this.embedStrategy})`),{count:r.length}}buildEmbedText(e){return this.embedStrategy==="question-and-answer"?`${e.question}
|
|
247
247
|
|
|
248
|
-
${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()),r=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}};function
|
|
248
|
+
${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()),r=await globalThis.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}};function Lt(n){return n.filter(e=>e.role!=="tool"&&!(e.role==="assistant"&&e.toolCalls&&e.toolCalls.length>0)&&!e._intermediate)}function Op(n,e){let t=[];for(let r=0;r<n.length;r++){let o=n[r];if(o.role==="assistant"&&o.toolCalls&&o.toolCalls.length>0){if(o.toolCalls.every(l=>e.has(l.toolName))){t.push(o);continue}let a=o.toolCalls.map(l=>l.toolName).join(", ");t.push({role:"assistant",content:`(Previously called external tools: ${a} \u2014 results not visible here.)`,timestamp:o.timestamp});let i=new Set(o.toolCalls.map(l=>l.callId));for(;r+1<n.length;){let l=n[r+1];if(l.role==="tool"&&l.toolCallId&&i.has(l.toolCallId))r++;else break}continue}if(o.role==="tool"){o.toolName&&e.has(o.toolName)&&t.push(o);continue}t.push(o)}return t}function $t(n,e){if(n.length<=e)return[...n];let t=n.length-e;for(;t>0;){if(n[t].role==="tool"){t--;continue}break}let r=n.slice(t),o=0;for(;o<r.length&&r[o].role==="tool";)o++;return r.slice(o)}function Mp(n,e){return $t(n,e)}function Fp(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(t.role==="assistant"&&!(t.toolCalls&&t.toolCalls.length>0))return t.subagents&&t.subagents.length>0?[...t.subagents]:[]}return[]}function Bp(n,e=5){let t=n.filter(a=>a.role==="tool").slice(-e);if(t.length===0)return"";let r=[],o=[];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&&o.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")?r.push(u.hash):typeof u.transaction_hash=="string"&&u.transaction_hash.startsWith("0x")&&r.push(u.transaction_hash)}if(r.length===0&&o.length===0)return"";let s=["[Tool data available from previous calls:]"];if(r.length>0&&s.push(`Transaction hashes (use EXACT values): ${r.slice(0,10).join(", ")}`),o.length>0){let a=o[o.length-1];s.push(`Pagination cursor from ${a.toolName}: ${a.cursor}`)}return s.join(`
|
|
249
249
|
`)}var vb=`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).
|
|
250
250
|
|
|
251
251
|
OUTPUT CONTRACT \u2014 overrides everything below:
|
|
@@ -296,13 +296,13 @@ User context:
|
|
|
296
296
|
${i.join(`
|
|
297
297
|
`)}`:"",c=s.length>0?`
|
|
298
298
|
|
|
299
|
-
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=
|
|
299
|
+
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=Lt(t),u=$t(d,this.historyMessages);this.debug&&(console.log(`
|
|
300
300
|
[Router] history window (${u.length} msg${u.length===1?"":"s"}):`),console.log(`[Router] user query: "${e}"`));let p=[{role:"system",content:vb,timestamp:0},...u,{role:"user",content:`Available subagents:
|
|
301
301
|
${a}${l}${c}
|
|
302
302
|
|
|
303
303
|
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(P){g=P,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(r.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(`
|
|
304
304
|
[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,r,o){if(e.assignments.length===0)return[];this.debug&&console.log(`
|
|
305
|
-
[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},r,o);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(r){let o=t.match(/\{[\s\S]*\}/);if(o)return JSON.parse(o[0]);throw r}}};var Tb=1024,
|
|
305
|
+
[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},r,o);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(r){let o=t.match(/\{[\s\S]*\}/);if(o)return JSON.parse(o[0]);throw r}}};var Tb=1024,qp=1536,Ab=`
|
|
306
306
|
|
|
307
307
|
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.`,Pb=`
|
|
308
308
|
|
|
@@ -313,7 +313,7 @@ DATA INTEGRITY: NEVER invent, guess, round, or estimate on-chain or market value
|
|
|
313
313
|
${u.join(`
|
|
314
314
|
`)}`:"",g=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.`:"",b=[h,g,`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(`
|
|
315
315
|
|
|
316
|
-
`),y=
|
|
316
|
+
`),y=Op(t,this.toolNames),w=$t(y,this.historyMessages),k=[{role:"system",content:this.systemPrompt,timestamp:0},...w,{role:"user",content:b,timestamp:Date.now()}],v=6e3,P=this.maxToolCalls+1;for(let x=0;x<P;x++){let L=c<this.maxToolCalls,E=L?o:void 0,ke=L&&this.mustCallTool&&c===0,V=E?Tb:qp,z=await this.llm.chat(k,E,{maxOutputTokens:V,...ke?{forceToolUse:!0}:{}});if(z.toolCalls.length===0){if(c===0&&this.cortexFallbackTool&&L){this.debug&&console.log(` [${this.name}] no tool called \u2014 re-prompting to act via a tool (AI fallback: ${this.cortexFallbackTool})`),k.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; when the user named NO network, chain = the connected chain, else Ethereum \u2014 but when they DID name one, pass THAT network, never the connected one) 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&&L&&!d){d=!0,this.debug&&console.log(` [${this.name}] no tool called \u2014 forcing the LLM to pick a tool`),k.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: "${z.text.slice(0,80)}\u2026"`),{subagentName:this.name,steps:s,finalAnswer:z.text,toolResults:a,toolMessages:i}}let fe={role:"assistant",content:z.text||"",toolCalls:z.toolCalls,timestamp:Date.now()};k.push(fe);let Ne=[];for(let W of z.toolCalls){if(!this.toolNames.has(W.toolName)){let Ke=`Tool "${W.toolName}" is not owned by ${this.name}`;this.debug&&console.log(` [${this.name}] WARN: ${Ke}`),s.push({phase:"observe",content:Ke,timestamp:Date.now()}),k.push({role:"tool",content:Ke,toolName:W.toolName,toolCallId:W.callId,timestamp:Date.now()});continue}let Z=`${W.toolName}::${JSON.stringify(W.args)}`;if(l.has(Z)){let Ke=`Skipped duplicate call: ${W.toolName}`;this.debug&&console.log(` [${this.name}] SKIP duplicate: ${W.toolName}`),s.push({phase:"observe",content:Ke,timestamp:Date.now()}),k.push({role:"tool",content:Ke,toolName:W.toolName,toolCallId:W.callId,timestamp:Date.now()});continue}l.add(Z),c++,this.debug&&console.log(` [${this.name}] call #${c}: ${W.toolName} ${JSON.stringify(W.args)}`),s.push({phase:"think",content:z.text||`Calling ${W.toolName}`,timestamp:Date.now()}),s.push({phase:"act",content:`Calling tool: ${W.toolName}`,toolCall:{toolName:W.toolName,args:W.args},timestamp:Date.now()});let Ht=Date.now(),tr={...r,query:e.query},Le=await this.registry.execute(W.toolName,W.args,tr);a.push(Le);let Ge=Le.success?JSON.stringify(Le.data):`Error: ${Le.error}`;if(this.debug){let Ke=Le.success?"OK":"ERR",Qe=Le.success?`${Ge.slice(0,120)}${Ge.length>120?"\u2026":""}`:Le.error;console.log(` [${this.name}] ${Ke} (${Date.now()-Ht}ms): ${Qe}`)}s.push({phase:"observe",content:Ge,toolResult:Le,timestamp:Date.now()});let Vt={role:"tool",content:Ge,toolName:W.toolName,toolCallId:W.callId,timestamp:Date.now()};k.push(Vt),Ne.push({...Vt,content:Ge.length>v?Ge.slice(0,v)+"\u2026[truncated]":Ge})}Ne.length>0&&(i.push(fe),i.push(...Ne))}this.debug&&console.log(` [${this.name}] budget exhausted after ${c} calls, forcing final answer`),k.push({role:"user",content:"Tool budget reached. Give your best answer now based on the data gathered.",timestamp:Date.now()});let S=await this.llm.chat(k,void 0,{maxOutputTokens:qp});return{subagentName:this.name,steps:s,finalAnswer:S.text,toolResults:a,toolMessages:i}}};var xb=`You are the Wallet domain expert. You answer questions about a specific wallet's on-chain state.
|
|
317
317
|
|
|
318
318
|
SPECIALISED TOOLS (prefer these when intent matches):
|
|
319
319
|
- get-wallet-token-balances: token + native coin balances
|
|
@@ -478,7 +478,7 @@ RULES:
|
|
|
478
478
|
- Answer in the user's language. Do not mention tool names.
|
|
479
479
|
|
|
480
480
|
Common chain ids (not the full set \u2014 pass any chain the user names): 0x1 Ethereum \xB7 0xa Optimism \xB7
|
|
481
|
-
0x38 BSC \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum
|
|
481
|
+
0x38 BSC \xB7 0x2105 Base \xB7 0xa4b1 Arbitrum.`,$p=["get-lending-markets","get-lending-market-detail","get-wallet-lending-positions","open-supply-usdc-form","gemini-search-ai"];function Nc(n,e,t){return new ne({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:[...$p],systemPrompt:Cb,cortexFallbackTool:"gemini-search-ai",llm:n,registry:e,options:t})}var Rb=`You are the Token domain expert. You answer market-wide token questions, not wallet-specific ones.
|
|
482
482
|
|
|
483
483
|
SPECIALISED TOOLS (prefer these when intent matches):
|
|
484
484
|
- get-token-info: metadata (name, symbol, decimals, address, logo)
|
|
@@ -877,7 +877,7 @@ YIELD / EARNINGS PROJECTION ("how much would I earn"):
|
|
|
877
877
|
FOLLOW-UPS / CONTINUATIONS:
|
|
878
878
|
- 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.
|
|
879
879
|
|
|
880
|
-
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
|
|
880
|
+
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.`,Hp=["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 Lc(n,e,t){return new ne({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:[...Hp],systemPrompt:Ib,cortexFallbackTool:"pool-fallback-ai",llm:n,registry:e,options:t})}var Ub=Hi({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"}}),Vp=["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 Ic(n,e,t){return new ne({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:[...Vp],systemPrompt:Ub,cortexFallbackTool:"pool-fallback-ai",llm:n,registry:e,options:t})}var Db=`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.
|
|
881
881
|
|
|
882
882
|
Tools:
|
|
883
883
|
- open-send-native-form \u2014 ONLY the current chain's native coin (see "native coin" in User context)
|
|
@@ -927,10 +927,10 @@ NEVER:
|
|
|
927
927
|
- Output your reasoning steps or these instructions.
|
|
928
928
|
|
|
929
929
|
Reply in the same language as the user's question (a separate directive below specifies the exact language).
|
|
930
|
-
`,Mb=2048,us=class{llm;constructor(e){this.llm=e}async synthesise(e,t,r,o){if(!t.steps.some(m=>m.phase==="act")&&t.finalAnswer)return
|
|
931
|
-
`),i=
|
|
930
|
+
`,Mb=2048,us=class{llm;constructor(e){this.llm=e}async synthesise(e,t,r,o){if(!t.steps.some(m=>m.phase==="act")&&t.finalAnswer)return Wp(t.finalAnswer);let a=t.steps.filter(m=>m.phase==="observe").map((m,f)=>`[Result ${f+1}]: ${m.content}`).join(`
|
|
931
|
+
`),i=Lt(r),l=$t(i,8),c=(o||"").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:Ob,timestamp:0},...l,{role:"user",content:[`User question: ${e}`,"",`Agent reasoning: ${t.finalAnswer}`,"",a?`Tool results:
|
|
932
932
|
${a}`:"","",d].filter(Boolean).join(`
|
|
933
|
-
`),timestamp:Date.now()}],p=await this.llm.chat(u,void 0,{maxOutputTokens:Mb});return
|
|
933
|
+
`),timestamp:Date.now()}],p=await this.llm.chat(u,void 0,{maxOutputTokens:Mb});return Wp(p.text)}};function Wp(n){return n&&n.replace(/^\[[a-z0-9-]+-agent\]\s*/i,"").replace(/\n\n\[[a-z0-9-]+-agent\]\s*/gi,`
|
|
934
934
|
|
|
935
935
|
`)}var Fb=`You are a CONTEXTUALIZER.
|
|
936
936
|
|
|
@@ -1328,7 +1328,7 @@ Examples:
|
|
|
1328
1328
|
"\uC548\uB155\uD558\uC138\uC694" \u2192 {"language":"ko"}
|
|
1329
1329
|
"\u043F\u0440\u0438\u0432\u0435\u0442" \u2192 {"language":"ru"}
|
|
1330
1330
|
"\u0E2A\u0E27\u0E31\u0E2A\u0E14\u0E35" \u2192 {"language":"th"}
|
|
1331
|
-
"123" \u2192 {"language":""}`,Gi=class{llm;historyMessages;debug;constructor(e,t){this.llm=e,this.historyMessages=t?.historyMessages??8,this.debug=t?.debug??!1}async rewrite(e,t,r=[]){let o=t.some(w=>w.role==="user"||w.role==="assistant"),s=
|
|
1331
|
+
"123" \u2192 {"language":""}`,Gi=class{llm;historyMessages;debug;constructor(e,t){this.llm=e,this.historyMessages=t?.historyMessages??8,this.debug=t?.debug??!1}async rewrite(e,t,r=[]){let o=t.some(w=>w.role==="user"||w.role==="assistant"),s=Bp(t),a=Lt(t),i=$t(a,this.historyMessages),l=[];r.length>0&&l.push(`Domain hint: the previous assistant turn was handled by ${r.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?`
|
|
1332
1332
|
|
|
1333
1333
|
${l.join(`
|
|
1334
1334
|
|
|
@@ -1336,18 +1336,18 @@ ${l.join(`
|
|
|
1336
1336
|
${e}${c}
|
|
1337
1337
|
|
|
1338
1338
|
Return JSON only.`,timestamp:Date.now()}],p=[{role:"system",content:Bb,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:o&&!b,rewrittenQuery:typeof h.rewrittenQuery=="string"&&h.rewrittenQuery.trim()?h.rewrittenQuery.trim():e,topicChanged:o&&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(`
|
|
1339
|
-
[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 r=t.match(/\{[\s\S]*\}/);return r&&(t=r[0]),JSON.parse(t)}};var H=require("@langchain/langgraph");function Ki(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var
|
|
1339
|
+
[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 r=t.match(/\{[\s\S]*\}/);return r&&(t=r[0]),JSON.parse(t)}};var H=require("@langchain/langgraph");function Ki(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Yp="\\s*/\\s*";function Uc(n){return[n.symA.toLowerCase(),n.symB.toLowerCase()].sort().join("|")}function Gp(n){return`(${n.symA}${Yp}${n.symB}|${n.symB}${Yp}${n.symA})`}function qb(n){let e=Ki(String(n));return`(?<![\\d.])${Number.isInteger(n)?`${e}(?:\\.0+)?`:`${e}0*`}`}function Dc(n,e,t,r){return`${n.slice(0,e)}[${t}](${r})${n.slice(e+t.length)}`}function $b(n,e){let r=new RegExp(`(?<!\\[)\\b${Gp(e)}\\b`,"i").exec(n);return r?Dc(n,r.index,r[1]??r[0],e.url):null}function Hb(n,e){if(e.feePercent==null)return null;let r=new RegExp(`(?<!\\[)\\b${Gp(e)}\\b[^\\n\\]]{0,16}?${qb(e.feePercent)}\\s*%`,"i").exec(n);return r?Dc(n,r.index,r[1]??"",e.url):null}var Vb=n=>{let e=[],t=r=>{if(!r||typeof r!="object")return;let o=r,s=typeof o.uniswapUrl=="string"?o.uniswapUrl:void 0,a=o.token0?.symbol,i=o.token1?.symbol;if(s&&typeof a=="string"&&a&&typeof i=="string"&&i){let l=o.feeTierPercent;e.push({url:s,symA:Ki(a),symB:Ki(i),feePercent:typeof l=="number"&&Number.isFinite(l)?l:void 0})}};t(n),t(n.pool);for(let r of["pools","candidates"]){let o=n[r];Array.isArray(o)&&o.forEach(t)}return e},Wb=[Vb],Yb=n=>{let e=[],t=n.marketplaceLinks;if(Array.isArray(t))for(let o of t){if(!o||typeof o!="object")continue;let{label:s,url:a}=o;typeof s=="string"&&s&&typeof a=="string"&&a&&e.push({url:a,label:s})}let r=typeof n.amazonBuyUrl=="string"?n.amazonBuyUrl:void 0;return r&&e.push({url:r,label:"Amazon"}),e},Gb=[Yb];function Kb(n,e){let r=new RegExp(`(?<!\\[)\\b${Ki(e.label)}\\b`,"i").exec(n);return r?Dc(n,r.index,r[0],e.url):null}function ji(n,e){if(!n)return n;let t=[],r=[];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 Wb)t.push(...d(c));for(let d of Gb)r.push(...d(c))}if(t.length===0&&r.length===0)return n;let o=new Map;for(let i of t)o.set(Uc(i),(o.get(Uc(i))??0)+1);let s=n,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=(o.get(Uc(i))??0)>1?Hb(s,i):$b(s,i);c&&(s=c,a.add(i.url))}for(let i of r){if(a.has(i.url))continue;if(s.includes(i.url)){a.add(i.url);continue}let l=Kb(s,i);l&&(s=l,a.add(i.url))}return s}var at=n=>({reducer:(e,t)=>t,default:n}),jb=H.Annotation.Root({userMessage:(0,H.Annotation)(),overrideLang:(0,H.Annotation)(at(()=>"")),conversationMessages:(0,H.Annotation)(at(()=>[])),lastSubagents:(0,H.Annotation)(at(()=>[])),messageId:(0,H.Annotation)(at(()=>"")),rewrite:(0,H.Annotation)(at(()=>null)),effectiveQuery:(0,H.Annotation)(at(()=>"")),turnLanguage:(0,H.Annotation)(at(()=>"")),kbContext:(0,H.Annotation)(at(()=>"")),decision:(0,H.Annotation)(at(()=>null)),assignment:(0,H.Annotation)(at(()=>null)),assignmentIndex:(0,H.Annotation)(at(()=>0)),subResults:(0,H.Annotation)({reducer:(n,e)=>n.concat(e),default:()=>[]}),response:(0,H.Annotation)(at(()=>null))});function Kp(n){let e=async u=>{n.addUserMessage(u.userMessage),n.needsSummary()&&await n.compactHistory();let p=n.conversationForTurn(),m=n.lastAssistantSubagents(p);return n.debug&&m.length>0&&console.log(`[AgentCore] previous turn handled by: ${m.join(", ")}`),{conversationMessages:p,lastSubagents:m,messageId:n.generateMessageId()}},t=async u=>{let p=await n.rewrite(u.userMessage,u.conversationMessages,u.lastSubagents),m=u.overrideLang||p.language||"";return{rewrite:p,effectiveQuery:p.rewrittenQuery,turnLanguage:m}},r=async u=>{let p=u.rewrite,m=p.isFollowUp?u.effectiveQuery:u.userMessage,f=await n.searchKB(m),h=n.formatKBContext(f),g=await n.tryAnswerFromKB(u.userMessage,f,h,u.messageId);return g?{kbContext:h,response:{...g,messageId:u.messageId,rewrite:p}}:{kbContext:h}},o=async u=>({decision:await n.route(u.effectiveQuery,u.conversationMessages,n.subagentCards(),u.lastSubagents)}),s=async u=>{let p=await n.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 n.runSubagent(u.assignment,u.conversationMessages,u.turnLanguage,(u.rewrite?.mentionedChain??"").trim());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);n.persistToolMessages(p);let m=n.mergeTrace(p),f=await n.synthesise(u.userMessage,m,n.synthesiserHistory(),u.turnLanguage||void 0),h=ji(f,p),g=p.map(k=>k.subagentName),b=n.collectUiActions(p,u.turnLanguage||null),y=n.collectActionButtons(p,u.turnLanguage||null);return{response:{...await n.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(n.connectedChain()??"")).trim(),m=new Map(n.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")?Oe():void 0;return{response:{...await n.answerUnsupportedChain(p,u.turnLanguage,u.messageId,g),messageId:u.messageId,routerDecision:u.decision,rewrite:u.rewrite}}},c=u=>u.response?H.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||n.connectedChain()||"").trim();return m&&f!==""&&!qe(f)?"unsupportedChain":p.map((h,g)=>new H.Send("subagent",{...u,assignment:h,assignmentIndex:g}))};return new H.StateGraph(jb).addNode("setup",e).addNode("contextualize",t).addNode("kb",r).addNode("route",o).addNode("direct",s).addNode("subagent",a).addNode("synthesize",i).addNode("unsupportedChain",l).addEdge(H.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",c,["route","direct",H.END]).addConditionalEdges("route",d,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",H.END).addEdge("direct",H.END).addEdge("subagent","synthesize").addEdge("synthesize",H.END).compile()}var jp=require("js-sha3");function ds(){let n=Date.now().toString(16),e=Math.floor(Math.random()*65535).toString(16).padStart(4,"0");return(n+e).slice(-8)}var zb="You are a helpful AI assistant for crypto and DeFi. Answer the user accurately and concisely. Respond in the same language as the user.",Xb=`
|
|
1340
1340
|
|
|
1341
1341
|
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.`,Qb=`
|
|
1342
1342
|
|
|
1343
|
-
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.`,zi=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(),
|
|
1343
|
+
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.`,zi=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(),In(e.rpcUrls),e.swapProviders)for(let[p,m]of Object.entries(e.swapProviders))m&&Si(p,m);La({debug:e.debug??!1}),Va(e.excludeChains),this.llm=new ve(e.llm),this.registry=new Dr,this.history=new as(e.maxHistoryMessages??50),this.summarizer=new is(this.llm),this.synthesizer=new us(this.llm),this.systemPrompt=(e.systemPrompt??zb)+Xb+Qb,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 ls(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new Tn({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 r=e.kbAnswerThreshold;if(typeof r=="number"?this.kbAnswerThreshold=r: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 Zr(p)),this.registry.register(new Yr({...p,llm:e.llm})),this.registry.register(new eo(p)),this.registry.register(new to(p)),this.registry.register(new no(p)),this.registry.register(new Gr(p)),this.registry.register(new ro(p)),this.registry.register(new oo(p)),this.registry.register(new lo(p)),this.registry.register(new ao(p)),this.registry.register(new io(p)),this.registry.register(new so(p)),this.registry.register(new zr(p)),this.registry.register(new Xr(p)),this.registry.register(new Kr(p)),this.registry.register(new jr(p)),this.registry.register(new yo(p))}if(e.lending!==!1){let p=typeof e.lending=="object"?e.lending:void 0;this.registry.register(new po(p)),this.registry.register(new mo(p)),this.registry.register(new ho(p)),this.registry.register(new fo({...p,moralis:typeof e.moralis=="object"?e.moralis:void 0}))}this.registry.register(new bo(e.llm)),this.registry.register(new wo(e.llm)),e.subagents?.nfc===!0&&(this.registry.register(new vo(e.llm)),this.registry.register(new To(e.llm))),this.registry.register(new Ao(e.llm));let o=e.subagents?.["pool-subgraph"]===!0,s=e.subagents?.["pool-defillama"]===!0,a=e.subagents?.["pool-uniswap"],i=o||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 Uo(p,m)),this.registry.register(new Do(p)),this.registry.register(new Oo(p)),this.registry.register(new Mo(p)),this.registry.register(new Fo(p)),this.registry.register(new Xn({baseUrl:p?.baseUrl,minProvideUsd:p?.minProvideUsd})),this.registry.register(new Qn),this.registry.register(new Jn),this.registry.register(new Zn)}if((i||o||s)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new Po(e.llm)),o&&e.subgraph!==!1){let p=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Bo(p)),this.registry.register(new qo(p)),this.registry.register(new $o(p)),this.registry.register(new Ho(p)),this.registry.register(new Vo(p)),this.registry.register(new Wo(p)),this.registry.register(new Yo(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 jo(m)),this.registry.register(new Xo(m)),this.registry.register(new zo(m)),this.registry.register(new Qo(m)),this.registry.register(new Jo(m)),this.registry.register(new Xn({minProvideUsd:p?.minProvideUsd,resolver:new Zo(m)})),this.registry.register(new Qn),this.registry.register(new Jn({scope:Ve(),supportsLabel:We(),chainParamDescription:Ye})),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=>Oi(this.registry,h,m);f(new es(p)),f(new ts(p)),f(new ss(p)),f(new ns(p)),f(new rs(p,{debug:this.debug})),f(new os(p,{debug:this.debug}))}this.router=new cs(this.llm,{debug:this.debug}),this.rewriter=new Gi(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=Yi(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=Kp(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,r){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(e))return{answer:`Unknown tool: "${e}".`,messageId:ds()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(t)}`);let s=r?.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=ds(),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,r){this.assertLicense(),await this.loadHistory();let o=ds();if(!this.registry.has(e))return{answer:`Unknown tool: "${e}".`,messageId:o};this.debug&&console.log(`[AgentCore] runTool ${e} ${JSON.stringify(t)}`);let s=r?.userMessage?.trim()||`[run ${e}]`,a=typeof r?.language=="string"&&r.language.trim()?r.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}=Vl(c,r?.signal);this.llm.setRequestSignal?.(d),ps(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});Cs(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=ji(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:o}),messageId:o,trace:b,subagentResults:g,...k.length>0?{uiActions:k}:{},...v.length>0?{actionButtons:v}:{}}}catch(m){throw qn(m)||d.aborted?(this.history.restore(p),new sn):(this.history.restore(p),m)}finally{u(),this.llm.setRequestSignal?.(void 0),ps(void 0),this.currentAbortController===c&&(this.currentAbortController=null)}}setX402Signer(e){this.x402Signer=e,$c(e?Hl({getPayer:()=>this.userContext?.walletAddress||"",getSigner:()=>this.x402Signer}):null)}async submitX402Payment(e,t,r){this.assertLicense(),await this.loadHistory();let o=ds(),s=e,a=r?.userQuery||s?.userQuery||"the previous request";this.history.add({role:"user",content:"[x402 payment authorized]",timestamp:Date.now()});let i;try{i=await ql(C,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:o}),await this.persistHistory(),{answer:u,messageId:o}}return{...await this.synthesizeFromPaidData(a,i,o),messageId:o}}async synthesizeFromPaidData(e,t,r){let o=typeof t=="string"?t:JSON.stringify(t),s=this.systemPrompt+this.capabilitiesSummary(),a=`The user's question was: "${e}".
|
|
1344
1344
|
|
|
1345
1345
|
A paid API returned this data:
|
|
1346
1346
|
${o}
|
|
1347
1347
|
|
|
1348
|
-
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:r})}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,
|
|
1349
|
-
${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let s=new AbortController;this.currentAbortController=s;let{signal:a,cleanup:i}=Vl(s,t?.signal);this.llm.setRequestSignal?.(a),ps(a);let l=this.history.serialise(),c=this.chatGraph.invoke({userMessage:e,overrideLang:r},{signal:a});this.inFlightTurn=c;let d;try{d=await c}catch(u){throw
|
|
1350
|
-
`)),d.response??{answer:"",messageId:ds()}}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=>
|
|
1348
|
+
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:r})}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,jp.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 r=typeof t?.language=="string"&&t.language.trim()?t.language.trim():"";await this.loadHistory(),await this.maybeAutoIngest(this.autoIngestEnabled);let o=Date.now();this.debug&&(console.log(`
|
|
1349
|
+
${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let s=new AbortController;this.currentAbortController=s;let{signal:a,cleanup:i}=Vl(s,t?.signal);this.llm.setRequestSignal?.(a),ps(a);let l=this.history.serialise(),c=this.chatGraph.invoke({userMessage:e,overrideLang:r},{signal:a});this.inFlightTurn=c;let d;try{d=await c}catch(u){throw qn(u)||a.aborted?(this.history.restore(l),new sn):u}finally{i(),this.llm.setRequestSignal?.(void 0),ps(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()-o}ms total`),console.log(`${"\u2500".repeat(60)}
|
|
1350
|
+
`)),d.response??{answer:"",messageId:ds()}}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=>Fp(e),generateMessageId:()=>ds(),rewrite:(e,t,r)=>this.rewriter.rewrite(e,t,r),searchKB:e=>this.searchKB(e),formatKBContext:e=>this.formatKBContext(e),tryAnswerFromKB:(e,t,r,o)=>this.tryAnswerFromKB(e,t,r,o),subagentCards:()=>Array.from(this.subagents.values()).map(e=>e.getCard()),route:(e,t,r,o)=>this.router.route(e,t,r,this.userContext,o),connectedChain:()=>this.userContext.chain,answerUnsupportedChain:(e,t,r,o)=>this.answerUnsupportedChain(e,t,r,o),answerDirectly:(e,t,r,o,s)=>this.answerDirectly(e,t,r,o,s),runSubagent:async(e,t,r,o)=>{let s=this.subagents.get(e.subagent);if(!s)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 a=Date.now(),i=await s.run({query:e.query,reasoning:e.reasoning,language:r,...o?{mentionedChain:o}:{}},t,this.userContext);if(this.debug){let l=i.toolResults.map(c=>c.toolName).join(", ")||"\u2014";console.log(`[AgentCore] ${e.subagent} done in ${Date.now()-a}ms | tools: ${l}`)}return i},persistToolMessages:e=>this.persistToolMessages(e),synthesiserHistory:()=>this.synthesiserHistory(),mergeTrace:e=>this.mergeTrace(e),synthesise:(e,t,r,o)=>this.synthesizer.synthesise(e,t,r,o),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 r=new Map,o=[];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=r.get(l);d?c.label.length>d.label.length&&r.set(l,c):(r.set(l,c),o.push(l))}return o.map(s=>r.get(s))}collectUiActions(e,t){let r=[];for(let o of e)for(let s of o.toolResults)s.success&&s.ui&&typeof s.ui=="object"&&typeof s.ui.component=="string"&&r.push(this.stampLanguage(s.ui,t));if(this.debug&&r.length>0){let o=r.map(s=>`${s.component}=${s.language}`).join(", ");console.log(`[AgentCore] uiActions stamped (rewrite.language="${t??""}"): ${o}`)}return r}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 r=t.slice(0,3).map(o=>`${o.score.toFixed(3)} ${this.snippet(o.entry.question,60)}`).join(" | ");console.log(`[AgentCore] KB hits (${t.length}): ${r}`)}return t}snippet(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}formatKBContext(e){let t=e.filter(r=>r.score>=this.kbAnswerThreshold);return t.length===0?"":t.map((r,o)=>`[Reference ${o+1}]
|
|
1351
1351
|
Q: ${r.entry.question}
|
|
1352
1352
|
A: ${r.entry.answer}`).join(`
|
|
1353
1353
|
|
|
@@ -1393,9 +1393,9 @@ REFERENCE MATERIAL:
|
|
|
1393
1393
|
`+r+`
|
|
1394
1394
|
---`:this.systemPrompt)+this.capabilitiesSummary()+a+`
|
|
1395
1395
|
|
|
1396
|
-
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=
|
|
1396
|
+
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=Lt(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:o})}async answerUnsupportedChain(e,t,r,o){this.debug&&console.log(`[AgentCore] connected chain "${e}" is not supported \u2192 short-circuit with notice`);let s=(t||"").trim(),a=o&&o.trim()||Fr,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:r})}synthesiserHistory(){let e=this.history.getConversation(),t=e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e;return Lt(t)}mergeTrace(e){let t=[];for(let o of e)t.push({phase:"think",content:`[${o.subagentName}] begin`,timestamp:Date.now()}),t.push(...o.steps),t.push({phase:"observe",content:`[${o.subagentName}] answer: ${o.finalAnswer}`,timestamp:Date.now()});let r=e.map(o=>`[${o.subagentName}] ${o.finalAnswer}`).join(`
|
|
1397
1397
|
|
|
1398
|
-
`);return{steps:t,finalAnswer:r}}async finaliseAnswer(e){let{answer:t,subagents:r,uiActions:o,actionButtons:s,messageId:a}=e??{},i={role:"assistant",content:t,timestamp:Date.now()};return r&&r.length>0&&(i.subagents=r),o&&o.length>0&&(i.uiActions=o),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,r=0,o=e.length;for(let p=e.length-1;p>=0;p--)if(e[p].role==="user"&&(r++,r>=t)){o=p;break}let s=e.slice(o),a=
|
|
1398
|
+
`);return{steps:t,finalAnswer:r}}async finaliseAnswer(e){let{answer:t,subagents:r,uiActions:o,actionButtons:s,messageId:a}=e??{},i={role:"assistant",content:t,timestamp:Date.now()};return r&&r.length>0&&(i.subagents=r),o&&o.length>0&&(i.uiActions=o),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,r=0,o=e.length;for(let p=e.length-1;p>=0;p--)if(e[p].role==="user"&&(r++,r>=t)){o=p;break}let s=e.slice(o),a=Mp(s,s.length),i=e.length-a.length,l=Lt(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 Xp=require("js-sha3"),Jb="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.",zp='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.',Xi=class{llm;debug;ecosystem;secretKey;ownGeminiKey;licenseChecked=!1;constructor(e={}){this.llm=e.provider??new ve({temperature:.5,...e.llm}),this.debug=e.debug??!1,this.ecosystem=e.ecosystemContext?.trim()||Jb,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,Xp.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 r=this.normalizeSite(t),o=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(r,{isPhishing:!1,trusted:!0,description:m,reasons:[],keyFeatures:f},o,s),b={currentSite:t,isPhishing:!1};return g.length>0&&(b.keyFeatures=g),{answer:h,extraData:b}}let a=await this.investigate(t,r,s),i=this.buildVerdict(r,a),l=a.keyFeatures;!i.isPhishing&&l.length===0&&(l=await this.gatherKeyFeatures(t,s)),this.debug&&(console.log("[WebsiteTrustKeyringAgent] domain:",r),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(r,{isPhishing:i.isPhishing,description:a.description,copiedSite:i.copiedSite,reasons:i.reasons,keyFeatures:l},o,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 r=t.officialDomain,o=r?t.affiliatedDomains.filter(f=>!this.looksLikeSquatOf(f,r)):t.affiliatedDomains,s=[t.officialDomain,...o].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,r){let o=`Domain under test (analyze EXACTLY as written \u2014 do NOT autocorrect): ${t}
|
|
1399
1399
|
URL: ${e}
|
|
1400
1400
|
|
|
1401
1401
|
Investigate, using web search, whether this EXACT domain is a legitimate official site or a phishing / look-alike / scam site. Work through:
|
|
@@ -1461,4 +1461,4 @@ LANGUAGE (MANDATORY): write "answer", every "reasons" item AND every "keyFeature
|
|
|
1461
1461
|
|
|
1462
1462
|
Return ONLY this JSON: { "answer": string, "reasons": string[], "keyFeatures": string[] }`,c=await this.askJson(l,{signal:o,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"},r=e.trim().toLowerCase();return t[r]??t[r.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}
|
|
1463
1463
|
|
|
1464
|
-
${
|
|
1464
|
+
${zp}`}async askJson(e,t={}){let{signal:r,googleSearch:o=!0,system:s=zp,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:o,maxRetries:a,maxOutputTokens:i,thinkingBudget:l,signal:r}),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}`,r=new URL(t).hostname||e;return this.decodeIdn(r)}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 P=k<=h?1:k>=h+26?26:k-h;if(v<P)break;y*=36-P}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 r=this.toHost(e),o=this.toHost(t);return!r||!o?!1:r===o||r.endsWith(`.${o}`)}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 r=e.length,o=t.length;if(!r)return o;if(!o)return r;let s=Array.from({length:o+1},(a,i)=>i);for(let a=1;a<=r;a++){let i=[a];for(let l=1;l<=o;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[o]}isNearMiss(e,t){if(!e||!t||e===t)return!1;let r=Math.max(e.length,t.length);if(r<4||Math.abs(e.length-t.length)>2)return!1;let o=this.editDistance(e,t);return o>=1&&o<=(r>=8?2:1)}carriesBrandName(e,t,r){let o=this.alnum(this.toHost(e));if(!o)return!1;let s=this.hostLabels(e);return[t?this.brandCore(t):"",this.alnum(r??"")].filter(i=>i.length>=4).some(i=>o.includes(i)||s.some(l=>this.isNearMiss(l,i)))}looksLikeSquatOf(e,t){if(this.isSameRegistrableDomain(e,t))return!1;let r=this.brandCore(t);if(r.length<4)return!1;let o=this.hostLabels(e);return o.includes(r)?!1:o.some(s=>this.isNearMiss(s,r)||s.length>r.length&&s.includes(r))}describeLookAlike(e,t){let r=this.toHost(e),o=this.toHost(t);if(!r||!o||r===o)return;if(/[^\u0020-\u007E]/.test(r))return`The address "${r}" uses look-alike (non-standard) characters to imitate the official ${o}; to the eye it reads the same, but it is a different address.`;let s=r.lastIndexOf("."),a=o.lastIndexOf(".");if(s>0&&a>0){let c=r.slice(0,s),d=o.slice(0,a),u=r.slice(s+1),p=o.slice(a+1);if(c===d&&u!==p)return`The address keeps the official name but changes the ending from ".${p}" to ".${u}" (${r} vs ${o}) \u2014 a look-alike that is easy to miss at a glance.`}let i=this.brandCore(o),l=this.hostLabels(r).find(c=>this.isNearMiss(c,i));if(l){let c=this.editDistance(l,i);return`The address "${r}" is a near-copy of the official ${o} \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(r).includes(i))return`The address "${r}" reuses the "${i}" name with extra text added to look affiliated with the official ${o}, but it is a different, unofficial domain.`}parseJson(e){if(!e)return null;let t=e.replace(/```(?:json)?/gi,"").trim(),r=t.indexOf("{"),o=t.lastIndexOf("}");if(r===-1||o===-1||o<=r)return null;try{return JSON.parse(t.slice(r,o+1))}catch{return null}}cleanStr(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;let r=t.toLowerCase();if(!(r==="null"||r==="none"||r==="n/a"||r==="undefined"))return t}cleanStrArray(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(/\r?\n|(?:^|\s)[-•]\s+/):[],r=[];for(let o of t){let s=this.coerceToStr(o);s&&r.push(s)}return r}coerceToStr(e){if(typeof e=="string")return this.cleanStr(e);if(!e||typeof e!="object")return;let t=e,r=this.cleanStr(t.feature)??this.cleanStr(t.name)??this.cleanStr(t.title),o=this.cleanStr(t.description)??this.cleanStr(t.detail)??this.cleanStr(t.text)??this.cleanStr(t.value);return r&&o?r===o?r:`${r} \u2014 ${o}`:r||o?r??o:Object.values(t).map(a=>this.cleanStr(a)).filter(a=>!!a).join(" \u2014 ")||void 0}dedupe(e){let t=new Set,r=[];for(let o of e){let s=o.toLowerCase();t.has(s)||(t.add(s),r.push(o))}return r}};var Zb=n=>{let e=JSON.parse(n),t=Array.isArray(e)?e:e?.entries;if(!Array.isArray(t))throw new Error("JSON must be an array or { entries: [...] }");return t.map((r,o)=>{if(!r||typeof r.question!="string"||typeof r.answer!="string")throw new Error(`Entry #${o} is missing "question" or "answer"`);return r})};async function Qp(n,e){let t=n.entries??(n.json?Zb(n.json):[]);return t.length===0?{count:0}:new Tn(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,fetchUnderlyingPricesUSD,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,readTokenUsdPrice,registerMaybeNoForm,requestWithX402,resolveGasLimit,resolveNfcShopLinks,resolveRawYieldAsset,resolveRawYieldIdentity,resolveRawYieldProtocol,resolveRpcUrl,resolveRpcUrls,resolveTokenPriceUSD,roundTickToSpacing,rpcCall,setRpcOverrides,spendableNative,swapProviderFactory,swapRouterRegistry,tickToPrice,toEventSelector,toFunctionSelector,toPantographChain,toPlainDecimal,unitPriceUSD,valueYieldTokens,weiToHuman});
|