keyring-agent-core 0.2.50 → 0.2.53
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 +15 -7
- package/dist/index.js +26 -26
- package/dist/index.native.js +75 -75
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,42 +1,42 @@
|
|
|
1
|
-
"use strict";var gi=Object.create;var vo=Object.defineProperty;var fi=Object.getOwnPropertyDescriptor;var yi=Object.getOwnPropertyNames;var bi=Object.getPrototypeOf,wi=Object.prototype.hasOwnProperty;var ki=(s,e)=>{for(var t in e)vo(s,t,{get:e[t],enumerable:!0})},ps=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of yi(e))!wi.call(s,r)&&r!==t&&vo(s,r,{get:()=>e[r],enumerable:!(n=fi(e,r))||n.enumerable});return s};var Ti=(s,e,t)=>(t=s!=null?gi(bi(s)):{},ps(e||!s||!s.__esModule?vo(t,"default",{value:s,enumerable:!0}):t,s)),vi=s=>ps(vo({},"__esModule",{value:!0}),s);var Kd={};ki(Kd,{AI_AGENT_TOOL_NAMES:()=>er,AbortError:()=>Je,AgentCore:()=>ir,ApproveTokenTool:()=>qn,BaseNftAiTool:()=>Me,BaseSwapService:()=>rt,BaseTool:()=>A,BaseWalletActionTool:()=>Pe,BuyTokenTool:()=>Bn,ChatHistory:()=>Vn,DEFAULT_CHAIN:()=>Te,DEFAULT_PROVIDER:()=>io,DEFAULT_RPC_BY_CHAIN:()=>ke,DebridgeAdapter:()=>gn,EstimatePoolYieldTool:()=>Pn,GeminiProvider:()=>J,GeminiSearchAiTool:()=>dn,HEX_TO_PANTOGRAPH:()=>Ks,KnowledgeBase:()=>Yn,LendingMarketsTool:()=>en,LendingService:()=>Ye,ManageLiquidityRedirectTool:()=>Cn,MoralisService:()=>D,NFC_AGENT_TOOL_NAMES:()=>Zo,NFC_AMAZON_DEFAULT_DOMAIN:()=>jr,NFC_AMAZON_DOMAINS:()=>Kr,NFTContractInfoTool:()=>sn,NFTMetadataTool:()=>an,NFT_AGENT_TOOL_NAMES:()=>Jo,NfcBuyTool:()=>un,NfcInfoTool:()=>cn,NoFormTool:()=>uo,OpenAddLiquidityFormTool:()=>An,OpenSupplyFormTool:()=>nn,POOL_AGENT_TOOL_NAMES:()=>tr,PantographService:()=>ue,PoolByAddressTool:()=>vn,PoolDetailTool:()=>kn,PoolFallbackAiTool:()=>pn,PoolPriceRangesTool:()=>xn,PoolSearchTool:()=>Tn,PoolService:()=>de,PreviewAddLiquidityTool:()=>Sn,RelayAdapter:()=>fn,Router:()=>Gn,SUPPORTED_CHAINS:()=>Ut,SUPPORTED_CHAINS_LABEL:()=>Lt,SWAP_PROVIDER_CONFIG:()=>Ho,SendNativeTool:()=>Mn,SendNftTool:()=>Hn,SendTokenTool:()=>Fn,Subagent:()=>X,SubgraphAddPoolTool:()=>Ln,SubgraphCoinPoolPairsTool:()=>In,SubgraphPoolByAddressTool:()=>Nn,SubgraphPoolByPositionIdTool:()=>Rn,SubgraphPoolSearchTool:()=>_n,SubgraphPositionDetailTool:()=>Un,SubgraphTrendingPoolsTool:()=>En,Summarizer:()=>Wn,SwapServiceFactory:()=>At,SwapTokenTool:()=>$n,Synthesizer:()=>Kn,TOKEN_AGENT_TOOL_NAMES:()=>Qo,TRANSFER_TOPIC:()=>Va,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>js,TokenAnalyticsTool:()=>qt,TokenHoldersTool:()=>Ft,TokenInfoTool:()=>Mt,TokenScoreTool:()=>Bt,ToolRegistry:()=>Rt,TopGainersTool:()=>Ht,TopPoolsTool:()=>wn,TransactionByHashTool:()=>Jt,TrendingTokensTool:()=>$t,UNISWAP_CHAIN_SLUG:()=>co,UpstashKnowledgeBase:()=>it,WALLET_ACTION_AGENT_TOOL_NAMES:()=>nr,WALLET_AGENT_TOOL_NAMES:()=>Xo,WalletApprovalsTool:()=>zt,WalletDefiPositionsTool:()=>Xt,WalletDefiProtocolPositionsTool:()=>Qt,WalletHistoryTool:()=>Wt,WalletLendingPositionsTool:()=>tn,WalletNFTsTool:()=>rn,WalletNftTransfersTool:()=>Gt,WalletPnlSummaryTool:()=>Kt,WalletPnlTool:()=>jt,WalletTokenBalancesTool:()=>Vt,WalletTokenTransfersTool:()=>Yt,WebsiteTrustKeyringAgent:()=>lr,ZERO_ADDRESS:()=>$,amazonDomainForLanguage:()=>zr,apiClient:()=>x,applyYieldConversions:()=>Yd,buildChallenge:()=>Sr,buildRangePresets:()=>Zr,buildUniswapPoolUrl:()=>we,clampTick:()=>De,completeX402:()=>Pr,configureSupportedChains:()=>Eo,createAiAgent:()=>yo,createDefaultSubagents:()=>or,createNfcAgent:()=>fo,createNftAgent:()=>go,createPoolAgent:()=>bo,createTokenAgent:()=>ho,createWalletActionAgent:()=>wo,createWalletAgent:()=>mo,createX402SignatureProvider:()=>Cr,displayFromChallenge:()=>Fs,encodeSignedHeader:()=>xr,ethCallAt:()=>So,ethCallByChain:()=>Tr,fetchTopMarketplaces:()=>Xr,getAffiliateFee:()=>hn,getChainMeta:()=>se,getDefaultRpcUrl:()=>Mi,getGatewayAddress:()=>Wo,getGatewayChains:()=>Yo,getNativeTokenInfo:()=>yn,getPositionManagerAddress:()=>Go,getProviderByChain:()=>$o,ingestKnowledgeBase:()=>hi,isAbortError:()=>yt,isPaymentRequired:()=>ml,isShareBasedProtocol:()=>di,isShareBasedYieldToken:()=>mi,nfcAmazonSearchUrl:()=>Oo,normaliseCountry:()=>Mo,normalizePriceRangeToPool:()=>_t,planYieldTokenConversions:()=>Wd,priceToTick:()=>ht,readPaymentError:()=>Os,readPaymentRequired:()=>xo,readReceipt:()=>Ms,registerMaybeNoForm:()=>zo,requestWithX402:()=>pl,resolveNfcShopLinks:()=>ln,resolveRpcUrl:()=>Xe,roundTickToSpacing:()=>Le,rpcCall:()=>He,setRpcOverrides:()=>kr,swapServiceFactory:()=>Fe,tickToPrice:()=>Ce,toPantographChain:()=>Rl});module.exports=vi(Kd);var hs=Ti(require("axios"));var ms="0.2.50";var Si=`keyring-agent-core/${ms} (Keyring Chatbot Agent; +https://keyring.app)`,ur=null;function gs(s){ur=s}var Pi=["payment-signature","x-payment"];function xi(s){return s?Object.keys(s).some(e=>Pi.includes(e.toLowerCase())):!1}var fs;function Qn(s){fs=s}var Ci=3e4,_i=typeof process<"u"&&process.versions?.node!=null,dr=class{instance;constructor(e={}){this.instance=hs.default.create({baseURL:e.baseURL,timeout:e.timeout??Ci,validateStatus:()=>!0,headers:{Accept:"application/json",..._i?{"User-Agent":e.userAgent??Si}:{},...e.headers}})}async request(e,t,n,r={}){let o=r.signal??fs,a=await this.instance.request({...r,signal:o,method:e,url:t,data:n}),i={};for(let[c,u]of Object.entries(a.headers??{}))u!=null&&(i[c.toLowerCase()]=String(u));let l={ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:i};if(l.status===402&&ur&&!xi(r.headers)){let c=await ur(l,{url:t,method:String(e),body:n,headers:r.headers});if(c)return this.request(e,t,n,{...r,headers:{...r.headers,...c}})}return l}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},x=new dr;function R(s){let{data:e,status:t,statusText:n}=s,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,i=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of i)if(typeof l=="string"&&l.trim())return l.trim()}return r}var ys=require("js-sha3");function F(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/.test(s)}function Ei(s){return new Uint8Array(ys.keccak256.arrayBuffer(s))}function Jn(s){let e=s.startsWith("0x")?s.slice(2):s,t=e.length%2?"0"+e:e,n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function bs(s){return"0x"+Array.from(s).map(e=>e.toString(16).padStart(2,"0")).join("")}function ws(s){return new TextEncoder().encode(s)}function mt(...s){let e=s.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of s)t.set(r,n),n+=r.length;return t}function Ni(s,e=32){let t=new Uint8Array(e);return t.set(s,e-s.length),t}function Ri(s,e=32){let t=new Uint8Array(e);return t.set(s),t}function ks(s){let e=((s%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return Jn(e)}function Zn(s){return ks(BigInt(s))}function Ts(s){return s==="uint"?"uint256":s==="int"?"int256":s.match(/^uint$/)?"uint256":s.match(/^int$/)?"int256":s.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function vs(s){let e=Ts(s.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(s.components??[]).map(vs).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function Ui(s){let e=(s.inputs??[]).map(vs).join(",");return`${s.name??""}(${e})`}function pr(s,e){let t=Di(s.type);if(t){let[r,o]=t;return Ii({...s,type:o},e,r)}if(s.type==="tuple")return Li(s,e);if(s.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:Ni(Jn(o.toLowerCase()))}}if(s.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=Ts(s.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:Zn(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:ks(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?Jn(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:Ri(o)}}if(n==="bytes"){let r=typeof e=="string"?Jn(e):e,o=Math.ceil(r.length/32)*32,a=new Uint8Array(o);return a.set(r),{dynamic:!0,encoded:mt(Zn(r.length),a)}}if(n==="string"){let r=typeof e=="string"?ws(e):e,o=Math.ceil(r.length/32)*32,a=new Uint8Array(o);return a.set(r),{dynamic:!0,encoded:mt(Zn(r.length),a)}}throw new Error(`Unsupported ABI type: ${s.type}`)}function mr(s){let e=0;for(let{dynamic:o,encoded:a}of s)e+=o?32:a.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:a}of s)o?(t.push(Zn(e+r)),n.push(a),r+=a.length):t.push(a);return mt(...t,...n)}function Ii(s,e,t){let n=t===null;if(!n&&e.length!==t)throw new Error(`Array length mismatch: expected ${t}, got ${e.length}`);let r=!1,o=[];for(let a of e){let i=pr(s,a);i.dynamic&&(r=!0),o.push(i)}if(n||r){let a=mr(o);if(n){let i=Zn(o.length);return{dynamic:!0,encoded:o.length>0?mt(i,a):i}}return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:mt(...o.map(a=>a.encoded))}}function Li(s,e){let t=s.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let a=t[o],i=Array.isArray(e)?e[o]:e[a.name??""],l=pr(a,i);l.dynamic&&(n=!0),r.push(l)}return{dynamic:n,encoded:n?mr(r):mt(...r.map(o=>o.encoded))}}function Di(s){let e=s.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function hr(s,e){if(s.length!==e.length)throw new Error(`Expected ${s.length} values, got ${e.length}`);if(s.length===0)return"0x";let t=s.map((r,o)=>pr(r,e[o])),n=mr(t);return bs(n)}function xt({abi:s,functionName:e,args:t=[]}){let n=s.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=Ui(n),o=Ei(ws(r)).slice(0,4),a=n.inputs??[],i=a.length===0||t.length===0?new Uint8Array(0):Jn(hr(a,t).slice(2));return bs(mt(o,i))}var gr=require("js-sha3"),As=2n**96n;function ne(s,e=8){return!Number.isFinite(s)||s===0?s:Number(s.toPrecision(e))}function Ss(s,e,t){let n=s*s,r=As*As,o=n*10n**18n/r;return Number(o)/1e18*Math.pow(10,e-t)}function Ce(s,e,t){return Math.pow(1.0001,s)*Math.pow(10,e-t)}function ht(s,e,t){if(s<=0)throw new Error("priceToTick: price must be > 0");let n=s/Math.pow(10,e-t),r=Math.log(n)/Math.log(1.0001),o=Math.round(r);return Math.abs(r-o)<.001?o:Math.floor(r)}function _t(s,e,t){let n={minPrice:s,maxPrice:e,inverted:!1};if(!Number.isFinite(s)||!Number.isFinite(e)||!Number.isFinite(t)||s<=0||e<=0||t<=0||s>=e)return n;let r={minPrice:1/e,maxPrice:1/s,inverted:!0},o=c=>t>=c.minPrice&&t<=c.maxPrice,a=o(n),i=o(r);if(a&&!i)return n;if(i&&!a)return r;let l=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/t));return l(r)<l(n)?r:n}function Le(s,e,t="nearest"){let n=Math.abs(s-Math.round(s))<1e-6?Math.round(s):s,r=(n%e+e)%e;if(r===0)return n;let o=n-r,a=o+e;return t==="down"?o:t==="up"?a:n-o<a-n?o:a}var je=-887272,Ct=887272;function De(s){return s<je?je:s>Ct?Ct:s}var fr=/^0x[0-9a-f]+$/i;function G(s){return s.startsWith("0x")||s.startsWith("0X")?s.slice(2):s}function Ao(s){let e=G(s).toLowerCase();if(e.length>64)throw new Error(`pad32: input too long (${e.length})`);return e.padStart(64,"0")}function ze(s){if(!fr.test(s)||G(s).length!==40)throw new Error(`encodeAddress: invalid address ${s}`);return Ao(s.toLowerCase())}function ae(s,e=256){let t=typeof s=="bigint"?s:BigInt(s);if(t<0n)throw new Error("encodeUint: negative");let n=t.toString(16);if(n.length>e/4)throw new Error(`encodeUint: overflow ${e}`);return Ao(n)}function yr(s){let e=typeof s=="bigint"?s:BigInt(s);if(e>=0n)return Ao(e.toString(16));let t=1n<<256n;return Ao((t+e).toString(16))}function Ps(s){return"0x"+(0,gr.keccak_256)(Oi(s))}function Oi(s){let e=G(s),t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substring(n*2,n*2+2),16);return t}function K(s){return"0x"+(0,gr.keccak_256)(new TextEncoder().encode(s)).slice(0,8)}function Oe(s,e){let t=s.substring(e,e+64);return t?BigInt("0x"+t):0n}function br(s,e){let t=s.substring(e,e+64),n=BigInt("0x"+t),r=1n<<256n,o=1n<<23n;return n>=1n<<255n?Number(n-r):(n<o,Number(n))}function wr(s,e){return"0x"+s.substring(e+24,e+64).toLowerCase()}var ke={"0x1":"https://ethereum-rpc.publicnode.com","0xa":"https://mainnet.optimism.io","0x38":"https://bsc-dataseed.binance.org","0x89":"https://polygon-bor-rpc.publicnode.com","0x2105":"https://mainnet.base.org","0xa4b1":"https://arb1.arbitrum.io/rpc","0xa86a":"https://avalanche-c-chain-rpc.publicnode.com","0xe708":"https://rpc.linea.build","0x64":"https://gnosis-rpc.publicnode.com","0x3e7":"https://rpc.hyperliquid.xyz/evm","0x1388":"https://rpc.mantle.xyz","0x8f":"https://rpc.monad.xyz"};function Mi(s){return ke[s.toLowerCase()]}var xs={};function kr(s){let e={};if(s)for(let[t,n]of Object.entries(s))typeof n=="string"&&n.trim()&&(e[t.toLowerCase()]=n.trim());xs=e}function Xe(s){let e=s.toLowerCase();return xs[e]??ke[e]}async function He(s,e,t){for(let r=0;r<=5;r++){let o=await x.post(s,{jsonrpc:"2.0",id:Date.now(),method:e,params:t},{headers:{"Content-Type":"application/json"}});if(o.status===429&&r<5){await new Promise(i=>setTimeout(i,2**r*500));continue}if(!o.ok)throw new Error(`RPC ${e}: ${R(o)}`);let a=o.data;if(a.error)throw new Error(`RPC ${e}: ${a.error.message}`);if(a.result===void 0)throw new Error(`RPC ${e}: empty result`);return a.result}throw new Error(`RPC ${e}: exceeded max retries (429)`)}function So(s,e,t){return He(s,"eth_call",[{to:e,data:t},"latest"])}async function Tr(s,e,t){let n=Xe(s);if(!n)return null;try{return await So(n,e,t)}catch{return null}}var Fi="0xcA11bde05977b3631167028862bE2a173976CA11",qi={};function Bi(s){return qi[s.toLowerCase()]??Fi}var $i=K("aggregate3((address,bool,bytes)[])"),Hi=[{type:"tuple[]",components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}]}],Vi=K("tokenURI(uint256)"),Wi=K("symbol()"),Yi=K("decimals()"),Cs=50,Gi=/^0x[0-9a-fA-F]{40}$/;function Ve(s,e){return s.slice(e*2,e*2+64)}function We(s){return s?Number(BigInt("0x"+s)):0}function Ki(s){try{return Vi+ae(BigInt(s))}catch{return null}}function ji(s){let e=hr(Hi,[s]);return $i+G(e)}function zi(s,e){let t=G(s);if(t.length<64)return[];let n=We(Ve(t,0)),r=We(Ve(t,n)),o=Math.min(r,e),a=n+32,i=[];for(let l=0;l<o;l++){let c=a+We(Ve(t,a+l*32)),u=We(Ve(t,c))===1,d=c+We(Ve(t,c+32)),p=We(Ve(t,d)),h=t.slice((d+32)*2,(d+32)*2+p*2);i.push({success:u,returnData:"0x"+h})}return i}function _s(s){let e=G(s);if(e.length<128)return null;let t=We(Ve(e,0)),n=We(Ve(e,t));if(n<=0)return null;let r=e.slice((t+32)*2,(t+32)*2+n*2);if(r.length<n*2)return null;let o=new Uint8Array(n);for(let i=0;i<n;i++)o[i]=parseInt(r.slice(i*2,i*2+2),16);return new TextDecoder().decode(o).replace(/\0+$/,"").trim()||null}function Xi(s){let e=_s(s);if(e)return e;let t=G(s);if(t.length!==64)return null;let n=[];for(let o=0;o<32;o++){let a=parseInt(t.slice(o*2,o*2+2),16);if(a===0)break;n.push(a)}return new TextDecoder().decode(new Uint8Array(n)).trim()||null}function Qi(s){let e=G(s);if(e.length<64)return null;let t=We(Ve(e,0));return Number.isFinite(t)&&t>=0&&t<=36?t:null}async function gt(s,e,t){let n=new Array(e.length).fill(null),r=t?.trim()||Xe(s);if(!r||e.length===0)return n;let o=Bi(s),a=[];e.forEach((l,c)=>{!Gi.test(l.target)||!fr.test(l.callData)||a.push({index:c,call:{target:l.target,allowFailure:!0,callData:l.callData}})});let i=[];for(let l=0;l<a.length;l+=Cs)i.push(a.slice(l,l+Cs));return await Promise.all(i.map(async l=>{try{let c=await So(r,o,ji(l.map(u=>u.call)));zi(c,l.length).forEach((u,d)=>{u.success&&(n[l[d].index]=u.returnData)})}catch{}})),n}async function Es(s,e,t){let n=e.map(()=>({symbol:null,decimals:null}));if(e.length===0)return n;let r=e.flatMap((a,i)=>[{index:i,field:"symbol",target:a,callData:Wi},{index:i,field:"decimals",target:a,callData:Yi}]);return(await gt(s,r,t)).forEach((a,i)=>{if(a===null)return;let l=r[i];l.field==="symbol"?n[l.index].symbol=Xi(a):n[l.index].decimals=Qi(a)}),n}async function Ns(s,e,t){let n=new Array(e.length).fill(null);if(e.length===0)return n;let r=[];return e.forEach((a,i)=>{let l=Ki(a.tokenId);l!==null&&r.push({index:i,target:a.contract,callData:l})}),(await gt(s,r,t)).forEach((a,i)=>{a!==null&&(n[r[i].index]=_s(a))}),n}function Ji(s){return Po(String(s))??"0"}function Po(s){let e=s.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let t=e[1]==="-"?"-":"",n=e[2]??"",r=e[3]??"";if(n===""&&r==="")return null;let o=e[4]?parseInt(e[4],10):0,a=n+r,i=n.length+o,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 vr(s){let e=Po(s);if(e===null||e.startsWith("-"))return null;let[t,n=""]=e.split(".");return{mant:BigInt(t+n),frac:n.length}}function Ar(s,e){let t=s<0n,n=(t?-s:s).toString(),r;if(e===0)r=n;else{let o=n.padStart(e+1,"0"),a=o.length-e;r=`${o.slice(0,a)}.${o.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return t?`-${r}`:r}function Et(s){if(typeof s=="number")return Number.isFinite(s)&&s>0?Ji(s):null;if(typeof s!="string")return null;let e=s.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=Po(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function Qe(s,e){let t=Po(s);if(t===null||e<0)return s;let n=t.startsWith("-"),[r,o=""]=(n?t.slice(1):t).split(".");if(o.length<=e)return t;let a=e===0?r:`${r}.${o.slice(0,e)}`,i=a.includes(".")?a.replace(/0+$/,"").replace(/\.$/,""):a;return n?`-${i}`:i}function Nt(s,e,t,n){let r=vr(s);if(!r||t<=0n||n<0)return s;let o=r.mant*e*10n**BigInt(n)/(t*10n**BigInt(r.frac));return Ar(o,n)}function ft(s,e){let t=vr(s),n=vr(e);if(!t||!n){let i=Number(s),l=Number(e);return i<l?-1:i>l?1:0}let r=Math.max(t.frac,n.frac),o=t.mant*10n**BigInt(r-t.frac),a=n.mant*10n**BigInt(r-n.frac);return o<a?-1:o>a?1:0}var Zi={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"}]},el="payment-required",tl="PAYMENT-SIGNATURE",nl="X-PAYMENT",ol="payment-response",rl="x-payment-response",sl=600,al=300,il={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 Rs(s){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(s),t=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(t)}return Buffer.from(s,"utf8").toString("base64")}function Is(s){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(s),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(t)}return Buffer.from(s,"base64").toString("utf8")}function ll(){let s=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(s);else for(let t=0;t<32;t++)s[t]=Math.floor(Math.random()*256);return"0x"+Array.from(s,t=>t.toString(16).padStart(2,"0")).join("")}function Ls(s){let e=String(s);if(e.includes(":")){let[n,r]=e.split(":"),o=parseInt(r,10);if(n!=="eip155"||Number.isNaN(o))throw new Error(`Unsupported x402 network: ${s} (only EVM "eip155:*" is supported)`);return o}let t=il[e.toLowerCase()];if(t===void 0)throw new Error(`Unsupported x402 network: ${s}`);return t}function Ds(s){if(!s.query||Object.keys(s.query).length===0)return s.url;let e=Object.entries(s.query).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&");return s.url.includes("?")?`${s.url}&${e}`:`${s.url}?${e}`}function xo(s){let e=s.headers[el];if(e){let r=Us(cl(e));return r&&Array.isArray(r.accepts)?{version:2,payload:r}:null}let t=s.data,n=t&&typeof t=="object"?t:Us(t);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function Us(s){if(typeof s!="string")return null;try{let e=JSON.parse(s);return e&&typeof e=="object"?e:null}catch{return null}}function cl(s){try{return Is(s)}catch{return null}}function ul(s){let e=s.amount??s.maxAmountRequired;return typeof s.scheme!="string"||typeof s.network!="string"||e==null||typeof s.asset!="string"||typeof s.payTo!="string"?null:{scheme:s.scheme,network:s.network,amount:String(e),asset:s.asset,payTo:s.payTo,...typeof s.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:s.maxTimeoutSeconds}:{},...s.extra&&typeof s.extra=="object"?{extra:s.extra}:{},...typeof s.resource=="string"?{resource:s.resource}:{},...typeof s.description=="string"?{description:s.description}:{},...typeof s.mimeType=="string"?{mimeType:s.mimeType}:{},...s.outputSchema!=null?{outputSchema:s.outputSchema}:{}}}function dl(s){let e=null;for(let t of s){let n=ul(t);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return Ls(n.network),n}catch(r){e=r instanceof Error?r.message:String(r)}}}throw new Error(e?`No payable x402 requirement offered (${e}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function Sr(s,e,t,n){let r=xo(s);if(!r)throw new Error("402 response carries no x402 payment requirements");let{version:o,payload:a}=r,i=dl(a.accepts??[]);if(!t)throw new Error("No connected wallet address to build the payment from");let l=Ls(i.network),c=Math.floor(Date.now()/1e3),u={from:t,to:i.payTo,value:String(i.amount),validAfter:String(Math.max(0,c-sl)),validBefore:String(c+(i.maxTimeoutSeconds??al)),nonce:ll()},d={domain:{name:i.extra?.name,version:i.extra?.version,chainId:l,verifyingContract:i.asset},types:Zi,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:Ds(e),method:e.method??"GET",body:e.body,headers:e.headers},x402Version:o,requirements:i,authorization:u,typedData:d,chainId:l,...a.resource!=null?{resource:a.resource}:{},...a.extensions!=null?{extensions:a.extensions}:{},...n?{userQuery:n}:{}}}async function pl(s,e,t,n){let r=Ds(e),o=await s.request(e.method??"GET",r,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:Sr(o,e,t,n)};if(!o.ok)throw new Error(R(o));return{status:"ok",data:o.data}}async function Pr(s,e,t){let{url:n,method:r,body:o,headers:a}=e.request,i=await s.request(r,n,o,{headers:{...a??{},...xr(e,t)}});if(i.ok)return i.data;throw new Error(hl(i)??R(i))}function ml(s){return xo(s)!==null}function Os(s){let e=Ms(s);return e?.errorReason?e.errorReason:xo(s)?.payload.error??null}function hl(s){let e=Os(s);return e?`x402 payment rejected: ${e}`:null}var gl={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 xr(s,e){let{requirements:t,authorization:n}=s,r={signature:e,authorization:n};if(s.x402Version===1){let a={x402Version:1,scheme:t.scheme,network:t.network,payload:r};return{[nl]:Rs(JSON.stringify(a))}}let o={x402Version:2,...s.resource!=null?{resource:s.resource}:{},accepted:fl(t),payload:r,...s.extensions!=null?{extensions:s.extensions}:{}};return{[tl]:Rs(JSON.stringify(o))}}function fl(s){let{resource:e,description:t,mimeType:n,outputSchema:r,...o}=s;return o}function Ms(s){let e=s.headers[ol]??s.headers[rl];if(!e)return null;try{return JSON.parse(Is(e))}catch{return null}}function yl(s,e){return s==null?e:gl[s]??`Chain ${s}`}async function Fs(s){let e=s.requirements,n=s.resource?.description||e.description,r=s.chainId??null,o=null,a=null;if(r!=null){let[l]=await Es("0x"+r.toString(16),[e.asset]);o=l?.symbol??null,a=l?.decimals??null}let i=String(e.amount);if(a!==null)try{i=Ar(BigInt(e.amount),a)}catch{}return{amount:i,asset:o||e.extra?.name||"USDC",amountRaw:String(e.amount),decimals:a,assetAddress:e.asset,network:r!=null?`eip155:${r}`:e.network,networkRaw:e.network,chainId:r,networkLabel:yl(r,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:s.request.url}}function Cr(s){return async(e,t)=>{let n=s.getPayer(),r=s.getSigner();if(!n||!r)return null;let o;try{o=Sr(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},n)}catch{return null}let a;try{a=await r({typedData:o.typedData,display:await Fs(o)})}catch{a=null}return a?xr(o,a):null}}var Je=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function yt(s){if(!s||typeof s!="object")return!1;let e=s;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function eo(s){if(s?.aborted)throw new Je}function _r(s,e){if(!e)return{signal:s.signal,cleanup:()=>{}};if(e.aborted)return s.abort(),{signal:s.signal,cleanup:()=>{}};let t=()=>s.abort();return e.addEventListener("abort",t),{signal:s.signal,cleanup:()=>e.removeEventListener("abort",t)}}var qs={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},bl="https://nft.keyring.app/api/gemini-stable",wl="https://generativelanguage.googleapis.com",kl=new Set([408,429,500,502,503,504]),Bs=3e4,Co=s=>new Promise(e=>setTimeout(e,s));function _o(s,e,t){if(t!=null&&t>0)return Math.min(t,Bs);let n=Math.min(e*2**(s-1),Bs);return n/2+Math.random()*(n/2)}function Tl(s){if(!s)return null;let e=Number(s);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(s);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var J=class{model;maxTokens;temperature;baseUrl;apiKey;requestSignal;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.apiKey=e.apiKey?.trim()??"",this.baseUrl=(e.baseUrl??(this.apiKey?wl:bl)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:a=5,retryDelayMs:i=1e3}=n??{},l=n?.signal??this.requestSignal;eo(l);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of c){let g=m.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${g}]`)}}let u=n?.thinkingBudget??(n?.maxOutputTokens!=null?0:void 0),d={maxOutputTokens:n?.maxOutputTokens??this.maxTokens,temperature:this.temperature};u!=null&&(d.thinkingConfig={thinkingBudget:u});let p={contents:c,generationConfig:d};r&&(p.systemInstruction=r),t?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(p.tools=[{googleSearch:{}}]);let h=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,f="Unknown error";for(let m=1;m<=a;m++){eo(l);let g;try{g=await x.post(h,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(S){if(yt(S))throw S;if(f=S instanceof Error?S.message:String(S),m>=a)break;await Co(_o(m,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}`,!kl.has(g.status))throw new Error(f);if(m>=a)break;let _=Tl(g.headers["retry-after"]??null);await Co(_o(m,i,_));continue}if(g.data==null||typeof g.data!="object"){if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,m>=a)break;await Co(_o(m,i));continue}let y=g.data,b=y.candidates?.[0];if(!b)return{text:"",toolCalls:[]};let w="",k=[],T=b.content?.parts;if(!Array.isArray(T)||T.length===0){let S=b.finishReason;if(!(S==="SAFETY"||S==="RECITATION")&&m<a){f=`Gemini returned an empty turn (finishReason=${S??"none"})`,await Co(_o(m,i));continue}return{text:"",toolCalls:[]}}for(let S of T)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=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:w,toolCalls:k,usage:P}}throw new Error(f)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let l=r[r.length-1],c=i.parts.some(d=>d.functionCall),u=l?.parts.some(d=>d.functionCall);l&&l.role===i.role&&!c&&!u?l.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let o=[];for(let i=0;i<r.length;i++){let l=r[i],c=o[o.length-1];l.role==="function"&&!c?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(r[i+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
|
|
2
|
-
`)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(t=>{let n={},r=[];for(let o of t.parameters){let a={type:qs[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:qs[o.items?.type??"string"]??"STRING"}),n[o.name]=a,o.required&&r.push(o.name)}return{name:t.name,description:t.description,parameters:{type:"OBJECT",properties:n,required:r}}})}};var Rt=class{tools=new Map;register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(t=>t.category===e)}async execute(e,t,n){let r=this.tools.get(e);if(!r)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let o=Date.now();try{return{...await r.execute(t,n),duration:Date.now()-o}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};var Ut=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],vl=new Set(Ut),Ze=[...Ut],Er=new Set(Ze),Te="0x1",Lt="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function Al(s){return s.map(e=>It[e]??e).join(", ")}function Eo(s){let e=new Set;if(s)for(let n of s){let r=No(n);r&&e.add(r)}let t=Ut.filter(n=>!e.has(n));Ze=t.length>0?[...t]:[...Ut],Er=new Set(Ze),Te=Ze.includes("0x1")?"0x1":Ze[0],Lt=Al(Ze)}var Sl={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function M(s){let e=No(s);return e&&Er.has(e)?e:null}function No(s){if(typeof s!="string")return null;let e=s.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=Sl[e];if(t)return t;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&vl.has(n)?n:null}function _e(s){return M(s)!==null}function ve(){return[...Ze]}var tt=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${Lt}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},et=s=>typeof s=="string"&&s.trim()!=="";function Z(s,e){if(et(s)){let t=M(s);if(t)return t;throw new tt(s.trim())}if(et(e?.chain)){let t=M(e.chain);if(t)return t;throw new tt(e.chain.trim())}return null}function Ro(s,e){return M(s)??M(e?.chain)??void 0}var It={"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 v(s){let e=No(s);return e&&It[e]?It[e]:typeof s=="string"&&s.trim()?s.trim():"the requested chain"}var Pl={"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 $s(s,e){let t=No(s),n=t?Pl[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var xl={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function Hs(s){if(typeof s!="string")return null;let e=s.trim().toLowerCase();return e?xl[e]??null:null}var Cl={"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 Vs(s){let e=M(s);return e?Cl[e]??null:null}function Dt(s,e){if(!et(s))return null;let t=M(s),n=M(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:It[t]??t,connectedLabel:It[n]??n}}function Ws(s,e){let t=typeof s=="string"?s.trim():"",n=e&&e.length?e.filter(o=>Er.has(o)):[];return(n.length?n:Ze).map(o=>{let a=It[o]??o;return{label:a,prompt:t?`${t} (${a})`:a}})}function Ot(s,e){return{actionButtons:Ws(e),_instructions:`The user wants to ${s} 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 Q=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=Ws(e,t)}},to=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 j(s,e){if(et(s))return s.trim();if(et(e?.walletAddress))return e.walletAddress.trim();throw new to}function oe(s,e,t){if(et(s)){let n=M(s);if(n)return n;throw new tt(s.trim())}if(et(e?.chain)){let n=M(e.chain);if(n)return n;throw new tt(e.chain.trim())}if(et(e?.walletAddress))throw new Q(typeof e?.query=="string"?e.query:void 0,t);return Te}var A=class{category;async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),a=_l(o);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-r,...a.actionButtons?{actionButtons:a.actionButtons}:{},...a.ui?{ui:a.ui}:{}}}catch(o){return o instanceof Q?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-r,actionButtons:o.buttons}:o instanceof to?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-r}:{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}};function _l(s){if(!s||typeof s!="object")return{data:s};let e=s,t=e.actionButtons,n=Array.isArray(t)&&t.length>0?t:void 0,r=e.ui,o=r&&typeof r=="object"&&typeof r.component=="string"?r:void 0;if(!n&&!o)return{data:s};let{actionButtons:a,ui:i,...l}=e;return{data:l,...n?{actionButtons:n}:{},...o?{ui:o}:{}}}var El="https://wallet-api.pantograph.app",Nl="0x0000000000000000000000000000000000000000",Ks={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},js={"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 Rl(s){return Ks[s.toLowerCase()]||s}function Ys(s){let e=[];for(let[t,n]of Object.entries(s))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function Nr(s){let e=s,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,r=e.price,o=r!=null?parseFloat(String(r)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function Rr(s){if(Array.isArray(s))return s;let e=s;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function ce(s){if(s==null)return null;let e=typeof s=="number"?s:parseFloat(String(s));return Number.isFinite(e)?e:null}function Gs(s,e){let t=s.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=ce(s.price_change_percentage_24h)??ce(s.priceChange24h)??ce(s.usd_price_24hr_percent_change)??ce(s.price_change_24h)??ce(s.priceChange);return{chainId:e,tokenAddress:s.address??s.token_address??"",name:s.name??null,symbol:s.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:s.logoURI??s.icon_image??s.logo??null,usdPrice:ce(s.price)??ce(s.usd_price),marketCap:ce(s.market_cap)??ce(s.marketCap),totalVolume:{"24h":ce(s.total_volume)??ce(s.volume24h)},pricePercentChange:{"24h":r}}}var ue=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??El).replace(/\/+$/,"")}tokensUrl(e,t){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(t)}`}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),r=this.tokensUrl(t,n),o=await x.get(r);if(!o.ok)return;let a=Rr(o.data),i=new Map;for(let l of a)l.address&&i.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let c=i.get(e[l].token_address.toLowerCase());c&&(c.icon_image&&(e[l].logo=c.icon_image,e[l].thumbnail=c.icon_image),isNaN(c.price)||(e[l].usd_price=c.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*c.price))}}catch{}}async getTokenMetadata(e,t){try{let n=this.tokensUrl(t,e),r=await x.get(n);if(!r.ok)return null;let o=Rr(r.data),a=e.toLowerCase()===Nl,i=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return i?Nr(i):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=this.tokensUrl(t,e.join(",")),o=await x.get(r);if(!o.ok)return n;let a=Rr(o.data),i=new Set(e.map(l=>l.toLowerCase()));for(let l of a){let c=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);c&&i.has(c)&&(n[c]=Nr(l))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let o=parseInt(n||Te,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=Ys({chainId:o,key:t}),i=`${this.baseUrl}/token-list/all?${a}`,l=await x.get(i);if(!l.ok)throw new Error(R(l));let c=l.data,u=c?.result??c?.data??c,d=[];return Array.isArray(u)?d=u:u&&typeof u=="object"&&(d=Object.values(u).flat()),{success:!0,data:d.map(Nr)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||Te,n=5,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=js[t.toLowerCase()]??[],a=r!=null?r+o.length:n+o.length,[i,l]=await Promise.allSettled([this.fetchTopGainers(t,a),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],u=l.status==="fulfilled"?o.map(m=>l.value[m.toLowerCase()]).filter(m=>m!=null).map(m=>Gs(m,t)):[],d=new Set,p=[];for(let m of u){let g=m.tokenAddress?.toLowerCase();!g||d.has(g)||(d.add(g),p.push(m))}let h=[];for(let m of c){let g=m.tokenAddress?.toLowerCase();!g||d.has(g)||(d.add(g),h.push(m))}let f=r!=null?[...p,...h].slice(0,r):[...p,...h.slice(0,n)];return await this.enrichTrendingMarketData(f,t),{success:!0,data:f}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let r=await this.getTokensMetadata(n.map(o=>o.tokenAddress),t);for(let o of n){let a=r[o.tokenAddress.toLowerCase()];a&&(o.marketCap==null&&(o.marketCap=ce(a.market_cap)??ce(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":ce(a.total_volume)??ce(a.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=parseInt(e,16),o=Ys({chainId:r,duration:n,limit:t}),a=`${this.baseUrl}/token-list/all/top-gainers${o?`?${o}`:""}`,i=[];for(let l=0;l<5;l++){let c=await x.get(a);if(!c.ok)throw new Error(R(c));let u=c.data;if(i=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],i.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return i.map(l=>Gs(l,e))}async getTopGainers(e){let t=e?.chain||Te,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,r=e?.duration||"24h";try{let o=await this.fetchTopGainers(t,n,r);return await this.enrichTrendingMarketData(o,t),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var Ul="https://nft.keyring.app",Il="https://nft.keyring.app",Ll=.01,U=5,H=1e3,Dl=25,Ol="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Ml="0x0000000000000000000000000000000000000000",I=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function z(s){return s||Te}function V(s){let e=[];for(let[t,n]of Object.entries(s))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function W(s){return new Promise(e=>setTimeout(e,s))}function Fl(s){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!s||typeof s!="object")return e;let t=s;if("active_protocols"in t||"total_usd_value"in t){let r=t;return{...e,...r,protocols:r.protocols||[]}}let n=t.result;return!n||typeof n!="object"?e:{active_protocols:n.activeProtocols??0,total_positions:n.totalPositions??0,total_usd_value:n.totalUsd??0,total_unclaimed_usd_value:n.totalUnclaimedUsd??0,protocols:(n.protocols||[]).map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",positions:r.positionCount??0,total_usd_value:r.totalUsd??0,total_unclaimed_usd_value:r.totalUnclaimedUsd??0,account_health_factor:r.accountHealthFactor??null}))}}function ql(s){if(Array.isArray(s))return s;if(s&&typeof s=="object"){let e=s;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function Ur(s){if(Array.isArray(s))return s;if(s&&typeof s=="object"){let e=s;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var D=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Ul).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Il).replace(/\/+$/,""),this.pantograph=new ue({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:r,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!t)return{success:!1,error:"Address is required"};let i=z(n),l="Unknown error";for(let c=1;c<=U;c++)try{let u={chain:i,exclude_spam:o,exclude_unverified_contracts:a,limit:100};r&&(u.token_addresses=r);let d=[],p=null;do{p&&(u.cursor=p);let f=V(u),m=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${f}`,g=await x.get(m);if(!g.ok)throw new I(g.status,R(g));let y=g.data,b=y?.data??y;b?.result?.length>0&&d.push(...b.result),p=b?.cursor??null}while(p);let h={result:d};return h?.result?.length>0&&(h.result=h.result.filter(f=>parseFloat(f.balance||"0")>0),h.result=h.result.map(f=>({...f,token_address:f.token_address.toLowerCase()===Ol?Ml:f.token_address})),await this.enrichTokenPrices(h.result,i),h.result=h.result.filter(f=>f.usd_value==null||f.usd_value>=Ll)),{success:!0,data:h}}catch(u){if(l=u instanceof Error?u.message:"Unknown error",u instanceof I&&u.status===400)break;c<U&&await W(H)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=z(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(t,r);if(a)return{success:!0,data:a};for(let i=1;i<=U;i++)try{let[l,c]=await Promise.allSettled([x.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${V({chain:r,addresses:[t]})}`),x.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${V({chain:r,include:"percent_change"})}`)]),u=null;if(l.status==="fulfilled"&&l.value.ok){let p=l.value.data;u=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!u){o="Token metadata not found",i<U&&await W(H);continue}let d=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;d=p?.data??p}return{success:!0,data:{...u,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof I&&l.status===400)break;i<U&&await W(H)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=100,excludeSpam:o=!1,cursor:a,tokenAddresses:i,includePrices:l,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let u=z(n),d=[],p=a,h,f;for(let m=0;m<Dl;m++){let g=await this.fetchWalletNftsPage({address:t,moralisChain:u,limit:r,excludeSpam:o,cursor:p,tokenAddresses:i,includePrices:l,format:c});if(!g.success){if(d.length===0)return g;break}let y=g.data;if(!y)break;let{result:b,cursor:w,page:k,page_size:T}=y;if(Array.isArray(b)&&d.push(...b),h=k,f=T,p=typeof w=="string"&&w.trim()?w:void 0,!p)break}return{success:!0,data:{result:d,cursor:p,page:h,page_size:f}}}async fetchWalletNftsPage(e){let{address:t,moralisChain:n,limit:r,excludeSpam:o,cursor:a,tokenAddresses:i,includePrices:l,format:c}=e,u="Unknown error";for(let d=1;d<=U;d++)try{let p={chain:n,format:c,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(p.cursor=a),l&&(p.include_prices=!0),i&&i.length>0&&(p.token_addresses=i);let h=V(p),f=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${h}`,m=await x.get(f);if(!m.ok)throw new I(m.status,R(m));let g=m.data;return{success:!0,data:g?.data??g}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof I&&p.status===400)break;d<U&&await W(H)}return{success:!1,error:u}}async getWalletNftCollections(e){let{address:t,chain:n,limit:r=100,excludeSpam:o=!0,cursor:a}=e;if(!t)return{success:!1,error:"Address is required"};let i=z(n),l="Unknown error";for(let c=1;c<=U;c++)try{let u={chain:i,limit:r,exclude_spam:o};a&&(u.cursor=a);let d=V(u),p=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/collections?${d}`,h=await x.get(p);if(!h.ok)throw new I(h.status,R(h));let f=h.data;return{success:!0,data:f?.data??f}}catch(u){if(l=u instanceof Error?u.message:"Unknown error",u instanceof I&&u.status===400)break;c<U&&await W(H)}return{success:!1,error:l}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:a=!0,mediaItems:i=!0,include:l}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!F(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=z(r),u="Unknown error";for(let d=1;d<=U;d++)try{let p={chain:c,format:o,normalizeMetadata:a,media_items:i};l&&(p.include=l);let h=V(p),f=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${h}`,m=await x.get(f);if(!m.ok)throw new I(m.status,R(m));let g=m.data;return{success:!0,data:g?.data??g}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof I&&p.status===400)break;d<U&&await W(H)}return{success:!1,error:u}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:o,toDate:a,fromBlock:i,toBlock:l,cursor:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let h=z(n),f=Math.max(1,Math.min(100,Math.floor(r))),m="Unknown error";for(let g=1;g<=U;g++)try{let y={chain:h,limit:f,order:u};o&&(y.from_date=o),a&&(y.to_date=a),i!=null&&(y.from_block=i),l!=null&&(y.to_block=l),c&&(y.cursor=c),d!=null&&(y.include_internal_transactions=d),p!=null&&(y.nft_metadata=p);let b=V(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,k=await x.get(w);if(!k.ok)throw new I(k.status,R(k));let T=k.data;return{success:!0,data:T?.data??T}}catch(y){if(m=y instanceof Error?y.message:"Unknown error",y instanceof I&&y.status===400)break;g<U&&await W(H)}return{success:!1,error:m}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:u,order:d="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=z(n),h=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let m=1;m<=U;m++)try{let g={chain:p,limit:h,order:d};a&&(g.from_date=a),i&&(g.to_date=i),l!=null&&(g.from_block=l),c!=null&&(g.to_block=c),u&&(g.cursor=u),r?.length&&(g.contract_addresses=r);let y=V(g),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await x.get(b);if(!w.ok)throw new I(w.status,R(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 I&&g.status===400)break;m<U&&await W(H)}return{success:!1,error:f}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:u,order:d="DESC",includePrices:p,format:h="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let f=z(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=U;y++)try{let b={chain:f,limit:m,order:d,format:h};a&&(b.from_date=a),i&&(b.to_date=i),l!=null&&(b.from_block=l),c!=null&&(b.to_block=c),u&&(b.cursor=u),r?.length&&(b.contract_addresses=r),p!=null&&(b.include_prices=p);let w=V(b),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,T=await x.get(k);if(!T.ok)throw new I(T.status,R(T));let P=T.data;return{success:!0,data:P?.data??P}}catch(b){if(g=b instanceof Error?b.message:"Unknown error",b instanceof I&&b.status===400)break;y<U&&await W(H)}return{success:!1,error:g}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!F(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:t,chain:n,days:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=z(n),a="Unknown error";for(let i=1;i<=U;i++)try{let l={chain:o};r&&(l.days=r);let c=V(l),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,d=await x.get(u);if(!d.ok)throw new I(d.status,R(d));let p=d.data;return{success:!0,data:p?.data??p}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof I&&l.status===400)break;i<U&&await W(H)}return{success:!1,error:a}}async getWalletPnl(e){let{address:t,chain:n,days:r,tokenAddresses:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=z(n),i="Unknown error";for(let l=1;l<=U;l++)try{let c={chain:a};r&&(c.days=r),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let u=V(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${u}`,p=await x.get(d);if(!p.ok)throw new I(p.status,R(p));let h=p.data;return{success:!0,data:h?.data??h}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof I&&c.status===400)break;l<U&&await W(H)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:t,chain:n,limit:r,cursor:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=z(n),i="Unknown error";for(let l=1;l<=U;l++)try{let c={chain:a};r!=null&&(c.limit=r),o&&(c.cursor=o);let u=V(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${u}`,p=await x.get(d);if(!p.ok)throw new I(p.status,R(p));let h=p.data;return{success:!0,data:h?.data??h}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof I&&c.status===400)break;l<U&&await W(H)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data,d=u?.data??u;return{success:!0,data:Fl(d)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data,d=u?.data??u;return{success:!0,data:ql(d)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:n,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!F(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=z(r),a="Unknown error";for(let i=1;i<=U;i++)try{let l=V({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${l}`,u=await x.get(c);if(!u.ok)throw new I(u.status,R(u));let h=u.data.result;return{success:!0,data:{protocol_id:h.protocolId,protocol_name:h.protocolName,protocol_url:h.protocolUrl??"",protocol_logo:h.protocolLogo??"",total_usd_value:h.totalUsd??0,total_unclaimed_usd_value:h.totalUnclaimedUsd??null,positions:h.positions.map(m=>({label:m.label,address:m.address,balance_usd:m.balanceUsd??0,total_unclaimed_usd_value:m.unclaimedUsd??0,position_details:m.details,tokens:m.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 I&&l.status===400)break;i<U&&await W(H)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!F(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getTokenScore(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!F(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let o=1;o<=U;o++)try{let a={};t&&(a.chain=z(t)),n!=null&&(a.limit=n);let i=V(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data,d=u?.data??u;return{success:!0,data:Ur(d)}}catch(a){if(r=a instanceof Error?a.message:"Unknown error",a instanceof I&&a.status===400)break;o<U&&await W(H)}return{success:!1,error:r}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},a="Unknown error";for(let i=1;i<=U;i++)try{let l={};t&&(l.chain=z(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=V(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await x.get(u);if(!d.ok)throw new I(d.status,R(d));let p=d.data,h=p?.data??p;return{success:!0,data:Ur(h)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof I&&l.status===400)break;i<U&&await W(H)}return{success:!1,error:a}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},a="Unknown error";for(let i=1;i<=U;i++)try{let l={};t&&(l.chain=z(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=V(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await x.get(u);if(!d.ok)throw new I(d.status,R(d));let p=d.data,h=p?.data??p;return{success:!0,data:Ur(h)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof I&&l.status===400)break;i<U&&await W(H)}return{success:!1,error:a}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var Mt=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 D(e),this.llm=new J(e?.llm??{})}async run(e,t){let n=e.keyword||"",r=e.prompt||"",o=t?.walletAddress||void 0;if(!n)return{error:"Missing required parameter: keyword"};let a;try{a=oe(e.chain,t)}catch(i){if(i instanceof tt)return await this.researchTokenChainAgnostic(n,r,o);throw i}return await this.searchToken(n,a,r,o)}async researchTokenChainAgnostic(e,t,n){let r=[n?`User's connected wallet address: ${n}`:null,"The user's connected chain is not one this app supports on-chain, so answer using web research only \u2014 do not assume a specific chain; identify the token across whichever chain(s) it actually exists on."].filter(Boolean).join(`
|
|
1
|
+
"use strict";var gi=Object.create;var vo=Object.defineProperty;var fi=Object.getOwnPropertyDescriptor;var yi=Object.getOwnPropertyNames;var bi=Object.getPrototypeOf,wi=Object.prototype.hasOwnProperty;var ki=(s,e)=>{for(var t in e)vo(s,t,{get:e[t],enumerable:!0})},ps=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of yi(e))!wi.call(s,r)&&r!==t&&vo(s,r,{get:()=>e[r],enumerable:!(n=fi(e,r))||n.enumerable});return s};var Ti=(s,e,t)=>(t=s!=null?gi(bi(s)):{},ps(e||!s||!s.__esModule?vo(t,"default",{value:s,enumerable:!0}):t,s)),vi=s=>ps(vo({},"__esModule",{value:!0}),s);var Kd={};ki(Kd,{AI_AGENT_TOOL_NAMES:()=>er,AbortError:()=>Je,AgentCore:()=>ir,ApproveTokenTool:()=>Fn,BaseNftAiTool:()=>Me,BaseSwapService:()=>rt,BaseTool:()=>A,BaseWalletActionTool:()=>Pe,BuyTokenTool:()=>qn,ChatHistory:()=>Hn,DEFAULT_CHAIN:()=>Te,DEFAULT_PROVIDER:()=>io,DEFAULT_RPC_BY_CHAIN:()=>ke,DebridgeAdapter:()=>hn,EstimatePoolYieldTool:()=>Sn,GeminiProvider:()=>J,GeminiSearchAiTool:()=>un,HEX_TO_PANTOGRAPH:()=>Ks,KnowledgeBase:()=>Wn,LendingMarketsTool:()=>Zt,LendingService:()=>Ye,ManageLiquidityRedirectTool:()=>xn,MoralisService:()=>D,NFC_AGENT_TOOL_NAMES:()=>Zo,NFC_AMAZON_DEFAULT_DOMAIN:()=>jr,NFC_AMAZON_DOMAINS:()=>Kr,NFTContractInfoTool:()=>rn,NFTMetadataTool:()=>sn,NFT_AGENT_TOOL_NAMES:()=>Jo,NfcBuyTool:()=>cn,NfcInfoTool:()=>ln,NoFormTool:()=>uo,OpenAddLiquidityFormTool:()=>vn,OpenSupplyFormTool:()=>tn,POOL_AGENT_TOOL_NAMES:()=>tr,PantographService:()=>ue,PoolByAddressTool:()=>Tn,PoolDetailTool:()=>wn,PoolFallbackAiTool:()=>dn,PoolPriceRangesTool:()=>Pn,PoolSearchTool:()=>kn,PoolService:()=>de,PreviewAddLiquidityTool:()=>An,RelayAdapter:()=>gn,Router:()=>Yn,SUPPORTED_CHAINS:()=>Rt,SUPPORTED_CHAINS_LABEL:()=>It,SWAP_PROVIDER_CONFIG:()=>Ho,SendNativeTool:()=>On,SendNftTool:()=>$n,SendTokenTool:()=>Mn,Subagent:()=>X,SubgraphAddPoolTool:()=>In,SubgraphCoinPoolPairsTool:()=>Un,SubgraphPoolByAddressTool:()=>En,SubgraphPoolByPositionIdTool:()=>Nn,SubgraphPoolSearchTool:()=>Cn,SubgraphPositionDetailTool:()=>Rn,SubgraphTrendingPoolsTool:()=>_n,Summarizer:()=>Vn,SwapServiceFactory:()=>vt,SwapTokenTool:()=>Bn,Synthesizer:()=>Gn,TOKEN_AGENT_TOOL_NAMES:()=>Qo,TRANSFER_TOPIC:()=>Va,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>js,TokenAnalyticsTool:()=>Ft,TokenHoldersTool:()=>Mt,TokenInfoTool:()=>Ot,TokenScoreTool:()=>qt,ToolRegistry:()=>Nt,TopGainersTool:()=>$t,TopPoolsTool:()=>bn,TransactionByHashTool:()=>Qt,TrendingTokensTool:()=>Bt,UNISWAP_CHAIN_SLUG:()=>co,UpstashKnowledgeBase:()=>it,WALLET_ACTION_AGENT_TOOL_NAMES:()=>nr,WALLET_AGENT_TOOL_NAMES:()=>Xo,WalletApprovalsTool:()=>jt,WalletDefiPositionsTool:()=>zt,WalletDefiProtocolPositionsTool:()=>Xt,WalletHistoryTool:()=>Vt,WalletLendingPositionsTool:()=>en,WalletNFTsTool:()=>on,WalletNftTransfersTool:()=>Yt,WalletPnlSummaryTool:()=>Gt,WalletPnlTool:()=>Kt,WalletTokenBalancesTool:()=>Ht,WalletTokenTransfersTool:()=>Wt,WebsiteTrustKeyringAgent:()=>lr,ZERO_ADDRESS:()=>$,amazonDomainForLanguage:()=>zr,apiClient:()=>x,applyYieldConversions:()=>Yd,buildChallenge:()=>Sr,buildRangePresets:()=>Zr,buildUniswapPoolUrl:()=>we,clampTick:()=>De,completeX402:()=>Pr,configureSupportedChains:()=>Eo,createAiAgent:()=>yo,createDefaultSubagents:()=>or,createNfcAgent:()=>fo,createNftAgent:()=>go,createPoolAgent:()=>bo,createTokenAgent:()=>ho,createWalletActionAgent:()=>wo,createWalletAgent:()=>mo,createX402SignatureProvider:()=>Cr,displayFromChallenge:()=>Fs,encodeSignedHeader:()=>xr,ethCallAt:()=>So,ethCallByChain:()=>Tr,fetchTopMarketplaces:()=>Xr,getAffiliateFee:()=>mn,getChainMeta:()=>se,getDefaultRpcUrl:()=>Mi,getGatewayAddress:()=>Wo,getGatewayChains:()=>Yo,getNativeTokenInfo:()=>fn,getPositionManagerAddress:()=>Go,getProviderByChain:()=>$o,ingestKnowledgeBase:()=>hi,isAbortError:()=>yt,isPaymentRequired:()=>ml,isShareBasedProtocol:()=>di,isShareBasedYieldToken:()=>mi,nfcAmazonSearchUrl:()=>Oo,normaliseCountry:()=>Mo,normalizePriceRangeToPool:()=>Ct,planYieldTokenConversions:()=>Wd,priceToTick:()=>ht,readPaymentError:()=>Os,readPaymentRequired:()=>xo,readReceipt:()=>Ms,registerMaybeNoForm:()=>zo,requestWithX402:()=>pl,resolveNfcShopLinks:()=>an,resolveRpcUrl:()=>Xe,roundTickToSpacing:()=>Le,rpcCall:()=>He,setRpcOverrides:()=>kr,swapServiceFactory:()=>Fe,tickToPrice:()=>Ce,toPantographChain:()=>Rl});module.exports=vi(Kd);var hs=Ti(require("axios"));var ms="0.2.53";var Si=`keyring-agent-core/${ms} (Keyring Chatbot Agent; +https://keyring.app)`,ur=null;function gs(s){ur=s}var Pi=["payment-signature","x-payment"];function xi(s){return s?Object.keys(s).some(e=>Pi.includes(e.toLowerCase())):!1}var fs;function Xn(s){fs=s}var Ci=3e4,_i=typeof process<"u"&&process.versions?.node!=null,dr=class{instance;constructor(e={}){this.instance=hs.default.create({baseURL:e.baseURL,timeout:e.timeout??Ci,validateStatus:()=>!0,headers:{Accept:"application/json",..._i?{"User-Agent":e.userAgent??Si}:{},...e.headers}})}async request(e,t,n,r={}){let o=r.signal??fs,a=await this.instance.request({...r,signal:o,method:e,url:t,data:n}),i={};for(let[c,u]of Object.entries(a.headers??{}))u!=null&&(i[c.toLowerCase()]=String(u));let l={ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:i};if(l.status===402&&ur&&!xi(r.headers)){let c=await ur(l,{url:t,method:String(e),body:n,headers:r.headers});if(c)return this.request(e,t,n,{...r,headers:{...r.headers,...c}})}return l}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},x=new dr;function R(s){let{data:e,status:t,statusText:n}=s,r=n?`HTTP ${t} ${n}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||r;if(e&&typeof e=="object"){let o=e,a=l=>l&&typeof l=="object"?l.message:void 0,i=[o.message,o.errorMessage,o.error,o.error_description,o.detail,a(o.error),a(o.data)];for(let l of i)if(typeof l=="string"&&l.trim())return l.trim()}return r}var ys=require("js-sha3");function F(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/.test(s)}function Ei(s){return new Uint8Array(ys.keccak256.arrayBuffer(s))}function Qn(s){let e=s.startsWith("0x")?s.slice(2):s,t=e.length%2?"0"+e:e,n=new Uint8Array(t.length/2);for(let r=0;r<n.length;r++)n[r]=parseInt(t.slice(r*2,r*2+2),16);return n}function bs(s){return"0x"+Array.from(s).map(e=>e.toString(16).padStart(2,"0")).join("")}function ws(s){return new TextEncoder().encode(s)}function mt(...s){let e=s.reduce((r,o)=>r+o.length,0),t=new Uint8Array(e),n=0;for(let r of s)t.set(r,n),n+=r.length;return t}function Ni(s,e=32){let t=new Uint8Array(e);return t.set(s,e-s.length),t}function Ri(s,e=32){let t=new Uint8Array(e);return t.set(s),t}function ks(s){let e=((s%(1n<<256n)+(1n<<256n))%(1n<<256n)).toString(16).padStart(64,"0");return Qn(e)}function Jn(s){return ks(BigInt(s))}function Ts(s){return s==="uint"?"uint256":s==="int"?"int256":s.match(/^uint$/)?"uint256":s.match(/^int$/)?"int256":s.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1")}function vs(s){let e=Ts(s.type);if(e==="tuple"||e.startsWith("tuple[")){let t=(s.components??[]).map(vs).join(","),n=e.startsWith("tuple[")?e.slice(5):"";return`(${t})${n}`}return e}function Ui(s){let e=(s.inputs??[]).map(vs).join(",");return`${s.name??""}(${e})`}function pr(s,e){let t=Di(s.type);if(t){let[r,o]=t;return Ii({...s,type:o},e,r)}if(s.type==="tuple")return Li(s,e);if(s.type==="address"){let r=String(e),o=r.startsWith("0x")?r.slice(2):r;return{dynamic:!1,encoded:Ni(Qn(o.toLowerCase()))}}if(s.type==="bool"){let r=new Uint8Array(32);return r[31]=e?1:0,{dynamic:!1,encoded:r}}let n=Ts(s.type);if(/^uint\d*$/.test(n))return{dynamic:!1,encoded:Jn(BigInt(e))};if(/^int\d*$/.test(n)){let r=BigInt(e);return r<0n&&(r=r+(1n<<256n)),{dynamic:!1,encoded:ks(r)}}if(/^bytes(\d+)$/.test(n)){let r=parseInt(n.slice(5),10),o=typeof e=="string"?Qn(e):e;if(o.length!==r)throw new Error(`bytes${r} expects exactly ${r} bytes, got ${o.length}`);return{dynamic:!1,encoded:Ri(o)}}if(n==="bytes"){let r=typeof e=="string"?Qn(e):e,o=Math.ceil(r.length/32)*32,a=new Uint8Array(o);return a.set(r),{dynamic:!0,encoded:mt(Jn(r.length),a)}}if(n==="string"){let r=typeof e=="string"?ws(e):e,o=Math.ceil(r.length/32)*32,a=new Uint8Array(o);return a.set(r),{dynamic:!0,encoded:mt(Jn(r.length),a)}}throw new Error(`Unsupported ABI type: ${s.type}`)}function mr(s){let e=0;for(let{dynamic:o,encoded:a}of s)e+=o?32:a.length;let t=[],n=[],r=0;for(let{dynamic:o,encoded:a}of s)o?(t.push(Jn(e+r)),n.push(a),r+=a.length):t.push(a);return mt(...t,...n)}function Ii(s,e,t){let n=t===null;if(!n&&e.length!==t)throw new Error(`Array length mismatch: expected ${t}, got ${e.length}`);let r=!1,o=[];for(let a of e){let i=pr(s,a);i.dynamic&&(r=!0),o.push(i)}if(n||r){let a=mr(o);if(n){let i=Jn(o.length);return{dynamic:!0,encoded:o.length>0?mt(i,a):i}}return{dynamic:!0,encoded:a}}return{dynamic:!1,encoded:mt(...o.map(a=>a.encoded))}}function Li(s,e){let t=s.components??[],n=!1,r=[];for(let o=0;o<t.length;o++){let a=t[o],i=Array.isArray(e)?e[o]:e[a.name??""],l=pr(a,i);l.dynamic&&(n=!0),r.push(l)}return{dynamic:n,encoded:n?mr(r):mt(...r.map(o=>o.encoded))}}function Di(s){let e=s.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function hr(s,e){if(s.length!==e.length)throw new Error(`Expected ${s.length} values, got ${e.length}`);if(s.length===0)return"0x";let t=s.map((r,o)=>pr(r,e[o])),n=mr(t);return bs(n)}function Pt({abi:s,functionName:e,args:t=[]}){let n=s.find(l=>(l.type==="function"||l.type===void 0)&&l.name===e);if(!n)throw new Error(`Function "${e}" not found in ABI`);let r=Ui(n),o=Ei(ws(r)).slice(0,4),a=n.inputs??[],i=a.length===0||t.length===0?new Uint8Array(0):Qn(hr(a,t).slice(2));return bs(mt(o,i))}var gr=require("js-sha3"),As=2n**96n;function ne(s,e=8){return!Number.isFinite(s)||s===0?s:Number(s.toPrecision(e))}function Ss(s,e,t){let n=s*s,r=As*As,o=n*10n**18n/r;return Number(o)/1e18*Math.pow(10,e-t)}function Ce(s,e,t){return Math.pow(1.0001,s)*Math.pow(10,e-t)}function ht(s,e,t){if(s<=0)throw new Error("priceToTick: price must be > 0");let n=s/Math.pow(10,e-t),r=Math.log(n)/Math.log(1.0001),o=Math.round(r);return Math.abs(r-o)<.001?o:Math.floor(r)}function Ct(s,e,t){let n={minPrice:s,maxPrice:e,inverted:!1};if(!Number.isFinite(s)||!Number.isFinite(e)||!Number.isFinite(t)||s<=0||e<=0||t<=0||s>=e)return n;let r={minPrice:1/e,maxPrice:1/s,inverted:!0},o=c=>t>=c.minPrice&&t<=c.maxPrice,a=o(n),i=o(r);if(a&&!i)return n;if(i&&!a)return r;let l=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/t));return l(r)<l(n)?r:n}function Le(s,e,t="nearest"){let n=Math.abs(s-Math.round(s))<1e-6?Math.round(s):s,r=(n%e+e)%e;if(r===0)return n;let o=n-r,a=o+e;return t==="down"?o:t==="up"?a:n-o<a-n?o:a}var je=-887272,xt=887272;function De(s){return s<je?je:s>xt?xt:s}var fr=/^0x[0-9a-f]+$/i;function G(s){return s.startsWith("0x")||s.startsWith("0X")?s.slice(2):s}function Ao(s){let e=G(s).toLowerCase();if(e.length>64)throw new Error(`pad32: input too long (${e.length})`);return e.padStart(64,"0")}function ze(s){if(!fr.test(s)||G(s).length!==40)throw new Error(`encodeAddress: invalid address ${s}`);return Ao(s.toLowerCase())}function ae(s,e=256){let t=typeof s=="bigint"?s:BigInt(s);if(t<0n)throw new Error("encodeUint: negative");let n=t.toString(16);if(n.length>e/4)throw new Error(`encodeUint: overflow ${e}`);return Ao(n)}function yr(s){let e=typeof s=="bigint"?s:BigInt(s);if(e>=0n)return Ao(e.toString(16));let t=1n<<256n;return Ao((t+e).toString(16))}function Ps(s){return"0x"+(0,gr.keccak_256)(Oi(s))}function Oi(s){let e=G(s),t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substring(n*2,n*2+2),16);return t}function K(s){return"0x"+(0,gr.keccak_256)(new TextEncoder().encode(s)).slice(0,8)}function Oe(s,e){let t=s.substring(e,e+64);return t?BigInt("0x"+t):0n}function br(s,e){let t=s.substring(e,e+64),n=BigInt("0x"+t),r=1n<<256n,o=1n<<23n;return n>=1n<<255n?Number(n-r):(n<o,Number(n))}function wr(s,e){return"0x"+s.substring(e+24,e+64).toLowerCase()}var ke={"0x1":"https://ethereum-rpc.publicnode.com","0xa":"https://mainnet.optimism.io","0x38":"https://bsc-dataseed.binance.org","0x89":"https://polygon-bor-rpc.publicnode.com","0x2105":"https://mainnet.base.org","0xa4b1":"https://arb1.arbitrum.io/rpc","0xa86a":"https://avalanche-c-chain-rpc.publicnode.com","0xe708":"https://rpc.linea.build","0x64":"https://gnosis-rpc.publicnode.com","0x3e7":"https://rpc.hyperliquid.xyz/evm","0x1388":"https://rpc.mantle.xyz","0x8f":"https://rpc.monad.xyz"};function Mi(s){return ke[s.toLowerCase()]}var xs={};function kr(s){let e={};if(s)for(let[t,n]of Object.entries(s))typeof n=="string"&&n.trim()&&(e[t.toLowerCase()]=n.trim());xs=e}function Xe(s){let e=s.toLowerCase();return xs[e]??ke[e]}async function He(s,e,t){for(let r=0;r<=5;r++){let o=await x.post(s,{jsonrpc:"2.0",id:Date.now(),method:e,params:t},{headers:{"Content-Type":"application/json"}});if(o.status===429&&r<5){await new Promise(i=>setTimeout(i,2**r*500));continue}if(!o.ok)throw new Error(`RPC ${e}: ${R(o)}`);let a=o.data;if(a.error)throw new Error(`RPC ${e}: ${a.error.message}`);if(a.result===void 0)throw new Error(`RPC ${e}: empty result`);return a.result}throw new Error(`RPC ${e}: exceeded max retries (429)`)}function So(s,e,t){return He(s,"eth_call",[{to:e,data:t},"latest"])}async function Tr(s,e,t){let n=Xe(s);if(!n)return null;try{return await So(n,e,t)}catch{return null}}var Fi="0xcA11bde05977b3631167028862bE2a173976CA11",qi={};function Bi(s){return qi[s.toLowerCase()]??Fi}var $i=K("aggregate3((address,bool,bytes)[])"),Hi=[{type:"tuple[]",components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}]}],Vi=K("tokenURI(uint256)"),Wi=K("symbol()"),Yi=K("decimals()"),Cs=50,Gi=/^0x[0-9a-fA-F]{40}$/;function Ve(s,e){return s.slice(e*2,e*2+64)}function We(s){return s?Number(BigInt("0x"+s)):0}function Ki(s){try{return Vi+ae(BigInt(s))}catch{return null}}function ji(s){let e=hr(Hi,[s]);return $i+G(e)}function zi(s,e){let t=G(s);if(t.length<64)return[];let n=We(Ve(t,0)),r=We(Ve(t,n)),o=Math.min(r,e),a=n+32,i=[];for(let l=0;l<o;l++){let c=a+We(Ve(t,a+l*32)),u=We(Ve(t,c))===1,d=c+We(Ve(t,c+32)),p=We(Ve(t,d)),h=t.slice((d+32)*2,(d+32)*2+p*2);i.push({success:u,returnData:"0x"+h})}return i}function _s(s){let e=G(s);if(e.length<128)return null;let t=We(Ve(e,0)),n=We(Ve(e,t));if(n<=0)return null;let r=e.slice((t+32)*2,(t+32)*2+n*2);if(r.length<n*2)return null;let o=new Uint8Array(n);for(let i=0;i<n;i++)o[i]=parseInt(r.slice(i*2,i*2+2),16);return new TextDecoder().decode(o).replace(/\0+$/,"").trim()||null}function Xi(s){let e=_s(s);if(e)return e;let t=G(s);if(t.length!==64)return null;let n=[];for(let o=0;o<32;o++){let a=parseInt(t.slice(o*2,o*2+2),16);if(a===0)break;n.push(a)}return new TextDecoder().decode(new Uint8Array(n)).trim()||null}function Qi(s){let e=G(s);if(e.length<64)return null;let t=We(Ve(e,0));return Number.isFinite(t)&&t>=0&&t<=36?t:null}async function gt(s,e,t){let n=new Array(e.length).fill(null),r=t?.trim()||Xe(s);if(!r||e.length===0)return n;let o=Bi(s),a=[];e.forEach((l,c)=>{!Gi.test(l.target)||!fr.test(l.callData)||a.push({index:c,call:{target:l.target,allowFailure:!0,callData:l.callData}})});let i=[];for(let l=0;l<a.length;l+=Cs)i.push(a.slice(l,l+Cs));return await Promise.all(i.map(async l=>{try{let c=await So(r,o,ji(l.map(u=>u.call)));zi(c,l.length).forEach((u,d)=>{u.success&&(n[l[d].index]=u.returnData)})}catch{}})),n}async function Es(s,e,t){let n=e.map(()=>({symbol:null,decimals:null}));if(e.length===0)return n;let r=e.flatMap((a,i)=>[{index:i,field:"symbol",target:a,callData:Wi},{index:i,field:"decimals",target:a,callData:Yi}]);return(await gt(s,r,t)).forEach((a,i)=>{if(a===null)return;let l=r[i];l.field==="symbol"?n[l.index].symbol=Xi(a):n[l.index].decimals=Qi(a)}),n}async function Ns(s,e,t){let n=new Array(e.length).fill(null);if(e.length===0)return n;let r=[];return e.forEach((a,i)=>{let l=Ki(a.tokenId);l!==null&&r.push({index:i,target:a.contract,callData:l})}),(await gt(s,r,t)).forEach((a,i)=>{a!==null&&(n[r[i].index]=_s(a))}),n}function Ji(s){return Po(String(s))??"0"}function Po(s){let e=s.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let t=e[1]==="-"?"-":"",n=e[2]??"",r=e[3]??"";if(n===""&&r==="")return null;let o=e[4]?parseInt(e[4],10):0,a=n+r,i=n.length+o,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 vr(s){let e=Po(s);if(e===null||e.startsWith("-"))return null;let[t,n=""]=e.split(".");return{mant:BigInt(t+n),frac:n.length}}function Ar(s,e){let t=s<0n,n=(t?-s:s).toString(),r;if(e===0)r=n;else{let o=n.padStart(e+1,"0"),a=o.length-e;r=`${o.slice(0,a)}.${o.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return t?`-${r}`:r}function _t(s){if(typeof s=="number")return Number.isFinite(s)&&s>0?Ji(s):null;if(typeof s!="string")return null;let e=s.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=Po(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function Qe(s,e){let t=Po(s);if(t===null||e<0)return s;let n=t.startsWith("-"),[r,o=""]=(n?t.slice(1):t).split(".");if(o.length<=e)return t;let a=e===0?r:`${r}.${o.slice(0,e)}`,i=a.includes(".")?a.replace(/0+$/,"").replace(/\.$/,""):a;return n?`-${i}`:i}function Et(s,e,t,n){let r=vr(s);if(!r||t<=0n||n<0)return s;let o=r.mant*e*10n**BigInt(n)/(t*10n**BigInt(r.frac));return Ar(o,n)}function ft(s,e){let t=vr(s),n=vr(e);if(!t||!n){let i=Number(s),l=Number(e);return i<l?-1:i>l?1:0}let r=Math.max(t.frac,n.frac),o=t.mant*10n**BigInt(r-t.frac),a=n.mant*10n**BigInt(r-n.frac);return o<a?-1:o>a?1:0}var Zi={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"}]},el="payment-required",tl="PAYMENT-SIGNATURE",nl="X-PAYMENT",ol="payment-response",rl="x-payment-response",sl=600,al=300,il={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 Rs(s){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(s),t=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(t)}return Buffer.from(s,"utf8").toString("base64")}function Is(s){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(s),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(t)}return Buffer.from(s,"base64").toString("utf8")}function ll(){let s=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(s);else for(let t=0;t<32;t++)s[t]=Math.floor(Math.random()*256);return"0x"+Array.from(s,t=>t.toString(16).padStart(2,"0")).join("")}function Ls(s){let e=String(s);if(e.includes(":")){let[n,r]=e.split(":"),o=parseInt(r,10);if(n!=="eip155"||Number.isNaN(o))throw new Error(`Unsupported x402 network: ${s} (only EVM "eip155:*" is supported)`);return o}let t=il[e.toLowerCase()];if(t===void 0)throw new Error(`Unsupported x402 network: ${s}`);return t}function Ds(s){if(!s.query||Object.keys(s.query).length===0)return s.url;let e=Object.entries(s.query).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&");return s.url.includes("?")?`${s.url}&${e}`:`${s.url}?${e}`}function xo(s){let e=s.headers[el];if(e){let r=Us(cl(e));return r&&Array.isArray(r.accepts)?{version:2,payload:r}:null}let t=s.data,n=t&&typeof t=="object"?t:Us(t);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function Us(s){if(typeof s!="string")return null;try{let e=JSON.parse(s);return e&&typeof e=="object"?e:null}catch{return null}}function cl(s){try{return Is(s)}catch{return null}}function ul(s){let e=s.amount??s.maxAmountRequired;return typeof s.scheme!="string"||typeof s.network!="string"||e==null||typeof s.asset!="string"||typeof s.payTo!="string"?null:{scheme:s.scheme,network:s.network,amount:String(e),asset:s.asset,payTo:s.payTo,...typeof s.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:s.maxTimeoutSeconds}:{},...s.extra&&typeof s.extra=="object"?{extra:s.extra}:{},...typeof s.resource=="string"?{resource:s.resource}:{},...typeof s.description=="string"?{description:s.description}:{},...typeof s.mimeType=="string"?{mimeType:s.mimeType}:{},...s.outputSchema!=null?{outputSchema:s.outputSchema}:{}}}function dl(s){let e=null;for(let t of s){let n=ul(t);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return Ls(n.network),n}catch(r){e=r instanceof Error?r.message:String(r)}}}throw new Error(e?`No payable x402 requirement offered (${e}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function Sr(s,e,t,n){let r=xo(s);if(!r)throw new Error("402 response carries no x402 payment requirements");let{version:o,payload:a}=r,i=dl(a.accepts??[]);if(!t)throw new Error("No connected wallet address to build the payment from");let l=Ls(i.network),c=Math.floor(Date.now()/1e3),u={from:t,to:i.payTo,value:String(i.amount),validAfter:String(Math.max(0,c-sl)),validBefore:String(c+(i.maxTimeoutSeconds??al)),nonce:ll()},d={domain:{name:i.extra?.name,version:i.extra?.version,chainId:l,verifyingContract:i.asset},types:Zi,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:Ds(e),method:e.method??"GET",body:e.body,headers:e.headers},x402Version:o,requirements:i,authorization:u,typedData:d,chainId:l,...a.resource!=null?{resource:a.resource}:{},...a.extensions!=null?{extensions:a.extensions}:{},...n?{userQuery:n}:{}}}async function pl(s,e,t,n){let r=Ds(e),o=await s.request(e.method??"GET",r,e.body,{headers:e.headers});if(o.status===402)return{status:"payment_required",challenge:Sr(o,e,t,n)};if(!o.ok)throw new Error(R(o));return{status:"ok",data:o.data}}async function Pr(s,e,t){let{url:n,method:r,body:o,headers:a}=e.request,i=await s.request(r,n,o,{headers:{...a??{},...xr(e,t)}});if(i.ok)return i.data;throw new Error(hl(i)??R(i))}function ml(s){return xo(s)!==null}function Os(s){let e=Ms(s);return e?.errorReason?e.errorReason:xo(s)?.payload.error??null}function hl(s){let e=Os(s);return e?`x402 payment rejected: ${e}`:null}var gl={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 xr(s,e){let{requirements:t,authorization:n}=s,r={signature:e,authorization:n};if(s.x402Version===1){let a={x402Version:1,scheme:t.scheme,network:t.network,payload:r};return{[nl]:Rs(JSON.stringify(a))}}let o={x402Version:2,...s.resource!=null?{resource:s.resource}:{},accepted:fl(t),payload:r,...s.extensions!=null?{extensions:s.extensions}:{}};return{[tl]:Rs(JSON.stringify(o))}}function fl(s){let{resource:e,description:t,mimeType:n,outputSchema:r,...o}=s;return o}function Ms(s){let e=s.headers[ol]??s.headers[rl];if(!e)return null;try{return JSON.parse(Is(e))}catch{return null}}function yl(s,e){return s==null?e:gl[s]??`Chain ${s}`}async function Fs(s){let e=s.requirements,n=s.resource?.description||e.description,r=s.chainId??null,o=null,a=null;if(r!=null){let[l]=await Es("0x"+r.toString(16),[e.asset]);o=l?.symbol??null,a=l?.decimals??null}let i=String(e.amount);if(a!==null)try{i=Ar(BigInt(e.amount),a)}catch{}return{amount:i,asset:o||e.extra?.name||"USDC",amountRaw:String(e.amount),decimals:a,assetAddress:e.asset,network:r!=null?`eip155:${r}`:e.network,networkRaw:e.network,chainId:r,networkLabel:yl(r,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:s.request.url}}function Cr(s){return async(e,t)=>{let n=s.getPayer(),r=s.getSigner();if(!n||!r)return null;let o;try{o=Sr(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},n)}catch{return null}let a;try{a=await r({typedData:o.typedData,display:await Fs(o)})}catch{a=null}return a?xr(o,a):null}}var Je=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function yt(s){if(!s||typeof s!="object")return!1;let e=s;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function Zn(s){if(s?.aborted)throw new Je}function _r(s,e){if(!e)return{signal:s.signal,cleanup:()=>{}};if(e.aborted)return s.abort(),{signal:s.signal,cleanup:()=>{}};let t=()=>s.abort();return e.addEventListener("abort",t),{signal:s.signal,cleanup:()=>e.removeEventListener("abort",t)}}var qs={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},bl="https://nft.keyring.app/api/gemini-stable",wl="https://generativelanguage.googleapis.com",kl=new Set([408,429,500,502,503,504]),Bs=3e4,Co=s=>new Promise(e=>setTimeout(e,s));function _o(s,e,t){if(t!=null&&t>0)return Math.min(t,Bs);let n=Math.min(e*2**(s-1),Bs);return n/2+Math.random()*(n/2)}function Tl(s){if(!s)return null;let e=Number(s);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(s);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var J=class{model;maxTokens;temperature;baseUrl;apiKey;requestSignal;constructor(e){this.model=e.model??"gemini-2.5-flash-lite",this.maxTokens=e.maxTokens??4096,this.temperature=e.temperature??.7,this.apiKey=e.apiKey?.trim()??"",this.baseUrl=(e.baseUrl??(this.apiKey?wl:bl)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:r,contents:o}=this.toContents(e),{maxRetries:a=5,retryDelayMs:i=1e3}=n??{},l=n?.signal??this.requestSignal;Zn(l);let c=o.length>0?o:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let m of c){let g=m.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${m.role}: [${g}]`)}}let u=n?.thinkingBudget??(n?.maxOutputTokens!=null?0:void 0),d={maxOutputTokens:n?.maxOutputTokens??this.maxTokens,temperature:this.temperature};u!=null&&(d.thinkingConfig={thinkingBudget:u});let p={contents:c,generationConfig:d};r&&(p.systemInstruction=r),t?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(p.tools=[{googleSearch:{}}]);let h=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,f="Unknown error";for(let m=1;m<=a;m++){Zn(l);let g;try{g=await x.post(h,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(S){if(yt(S))throw S;if(f=S instanceof Error?S.message:String(S),m>=a)break;await Co(_o(m,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}`,!kl.has(g.status))throw new Error(f);if(m>=a)break;let _=Tl(g.headers["retry-after"]??null);await Co(_o(m,i,_));continue}if(g.data==null||typeof g.data!="object"){if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,m>=a)break;await Co(_o(m,i));continue}let y=g.data,b=y.candidates?.[0];if(!b)return{text:"",toolCalls:[]};let w="",k=[],T=b.content?.parts;if(!Array.isArray(T)||T.length===0){let S=b.finishReason;if(!(S==="SAFETY"||S==="RECITATION")&&m<a){f=`Gemini returned an empty turn (finishReason=${S??"none"})`,await Co(_o(m,i));continue}return{text:"",toolCalls:[]}}for(let S of T)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=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:w,toolCalls:k,usage:P}}throw new Error(f)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let r=[];for(let i of n){let l=r[r.length-1],c=i.parts.some(d=>d.functionCall),u=l?.parts.some(d=>d.functionCall);l&&l.role===i.role&&!c&&!u?l.parts.push(...i.parts):r.push({...i,parts:[...i.parts]})}let o=[];for(let i=0;i<r.length;i++){let l=r[i],c=o[o.length-1];l.role==="function"&&!c?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(r[i+1]?.role==="function")||o.push(l)}for(;o.length>0&&o[0].role!=="user";)o.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
|
|
2
|
+
`)}]}:null,contents:o}}toFunctionDeclarations(e){return e.map(t=>{let n={},r=[];for(let o of t.parameters){let a={type:qs[o.type]??"STRING",description:o.description};o.type==="array"&&(a.items={type:qs[o.items?.type??"string"]??"STRING"}),n[o.name]=a,o.required&&r.push(o.name)}return{name:t.name,description:t.description,parameters:{type:"OBJECT",properties:n,required:r}}})}};var Nt=class{tools=new Map;register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(t=>t.category===e)}async execute(e,t,n){let r=this.tools.get(e);if(!r)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let o=Date.now();try{return{...await r.execute(t,n),duration:Date.now()-o}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-o}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};var Rt=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],vl=new Set(Rt),Ze=[...Rt],Er=new Set(Ze),Te="0x1",It="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function Al(s){return s.map(e=>Ut[e]??e).join(", ")}function Eo(s){let e=new Set;if(s)for(let n of s){let r=No(n);r&&e.add(r)}let t=Rt.filter(n=>!e.has(n));Ze=t.length>0?[...t]:[...Rt],Er=new Set(Ze),Te=Ze.includes("0x1")?"0x1":Ze[0],It=Al(Ze)}var Sl={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function M(s){let e=No(s);return e&&Er.has(e)?e:null}function No(s){if(typeof s!="string")return null;let e=s.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=Sl[e];if(t)return t;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&vl.has(n)?n:null}function _e(s){return M(s)!==null}function ve(){return[...Ze]}var tt=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${It}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},et=s=>typeof s=="string"&&s.trim()!=="";function Z(s,e){if(et(s)){let t=M(s);if(t)return t;throw new tt(s.trim())}if(et(e?.chain)){let t=M(e.chain);if(t)return t;throw new tt(e.chain.trim())}return null}function Ro(s,e){return M(s)??M(e?.chain)??void 0}var Ut={"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 v(s){let e=No(s);return e&&Ut[e]?Ut[e]:typeof s=="string"&&s.trim()?s.trim():"the requested chain"}var Pl={"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 $s(s,e){let t=No(s),n=t?Pl[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var xl={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function Hs(s){if(typeof s!="string")return null;let e=s.trim().toLowerCase();return e?xl[e]??null:null}var Cl={"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 Vs(s){let e=M(s);return e?Cl[e]??null:null}function Lt(s,e){if(!et(s))return null;let t=M(s),n=M(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:Ut[t]??t,connectedLabel:Ut[n]??n}}function Ws(s,e){let t=typeof s=="string"?s.trim():"",n=e&&e.length?e.filter(o=>Er.has(o)):[];return(n.length?n:Ze).map(o=>{let a=Ut[o]??o;return{label:a,prompt:t?`${t} (${a})`:a}})}function Dt(s,e){return{actionButtons:Ws(e),_instructions:`The user wants to ${s} 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 Q=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=Ws(e,t)}},eo=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 j(s,e){if(et(s))return s.trim();if(et(e?.walletAddress))return e.walletAddress.trim();throw new eo}function oe(s,e,t){if(et(s)){let n=M(s);if(n)return n;throw new tt(s.trim())}if(et(e?.chain)){let n=M(e.chain);if(n)return n;throw new tt(e.chain.trim())}if(et(e?.walletAddress))throw new Q(typeof e?.query=="string"?e.query:void 0,t);return Te}var A=class{category;async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),a=_l(o);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-r,...a.actionButtons?{actionButtons:a.actionButtons}:{},...a.ui?{ui:a.ui}:{}}}catch(o){return o instanceof Q?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-r,actionButtons:o.buttons}:o instanceof eo?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-r}:{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}};function _l(s){if(!s||typeof s!="object")return{data:s};let e=s,t=e.actionButtons,n=Array.isArray(t)&&t.length>0?t:void 0,r=e.ui,o=r&&typeof r=="object"&&typeof r.component=="string"?r:void 0;if(!n&&!o)return{data:s};let{actionButtons:a,ui:i,...l}=e;return{data:l,...n?{actionButtons:n}:{},...o?{ui:o}:{}}}var El="https://wallet-api.pantograph.app",Nl="0x0000000000000000000000000000000000000000",Ks={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},js={"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 Rl(s){return Ks[s.toLowerCase()]||s}function Ys(s){let e=[];for(let[t,n]of Object.entries(s))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function Nr(s){let e=s,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,r=e.price,o=r!=null?parseFloat(String(r)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(o)?{usd_price:o}:{}}}function Rr(s){if(Array.isArray(s))return s;let e=s;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function ce(s){if(s==null)return null;let e=typeof s=="number"?s:parseFloat(String(s));return Number.isFinite(e)?e:null}function Gs(s,e){let t=s.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,r=ce(s.price_change_percentage_24h)??ce(s.priceChange24h)??ce(s.usd_price_24hr_percent_change)??ce(s.price_change_24h)??ce(s.priceChange);return{chainId:e,tokenAddress:s.address??s.token_address??"",name:s.name??null,symbol:s.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:s.logoURI??s.icon_image??s.logo??null,usdPrice:ce(s.price)??ce(s.usd_price),marketCap:ce(s.market_cap)??ce(s.marketCap),totalVolume:{"24h":ce(s.total_volume)??ce(s.volume24h)},pricePercentChange:{"24h":r}}}var ue=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??El).replace(/\/+$/,"")}tokensUrl(e,t){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(t)}`}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),r=this.tokensUrl(t,n),o=await x.get(r);if(!o.ok)return;let a=Rr(o.data),i=new Map;for(let l of a)l.address&&i.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let c=i.get(e[l].token_address.toLowerCase());c&&(c.icon_image&&(e[l].logo=c.icon_image,e[l].thumbnail=c.icon_image),isNaN(c.price)||(e[l].usd_price=c.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*c.price))}}catch{}}async getTokenMetadata(e,t){try{let n=this.tokensUrl(t,e),r=await x.get(n);if(!r.ok)return null;let o=Rr(r.data),a=e.toLowerCase()===Nl,i=o.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return i?Nr(i):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let r=this.tokensUrl(t,e.join(",")),o=await x.get(r);if(!o.ok)return n;let a=Rr(o.data),i=new Set(e.map(l=>l.toLowerCase()));for(let l of a){let c=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);c&&i.has(c)&&(n[c]=Nr(l))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let o=parseInt(n||Te,16);if(isNaN(o))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=Ys({chainId:o,key:t}),i=`${this.baseUrl}/token-list/all?${a}`,l=await x.get(i);if(!l.ok)throw new Error(R(l));let c=l.data,u=c?.result??c?.data??c,d=[];return Array.isArray(u)?d=u:u&&typeof u=="object"&&(d=Object.values(u).flat()),{success:!0,data:d.map(Nr)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||Te,n=5,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let o=js[t.toLowerCase()]??[],a=r!=null?r+o.length:n+o.length,[i,l]=await Promise.allSettled([this.fetchTopGainers(t,a),o.length>0?this.getTokensMetadata(o,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],u=l.status==="fulfilled"?o.map(m=>l.value[m.toLowerCase()]).filter(m=>m!=null).map(m=>Gs(m,t)):[],d=new Set,p=[];for(let m of u){let g=m.tokenAddress?.toLowerCase();!g||d.has(g)||(d.add(g),p.push(m))}let h=[];for(let m of c){let g=m.tokenAddress?.toLowerCase();!g||d.has(g)||(d.add(g),h.push(m))}let f=r!=null?[...p,...h].slice(0,r):[...p,...h.slice(0,n)];return await this.enrichTrendingMarketData(f,t),{success:!0,data:f}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(o=>o.tokenAddress&&(o.marketCap==null||o.totalVolume?.["24h"]==null));if(n.length===0)return;let r=await this.getTokensMetadata(n.map(o=>o.tokenAddress),t);for(let o of n){let a=r[o.tokenAddress.toLowerCase()];a&&(o.marketCap==null&&(o.marketCap=ce(a.market_cap)??ce(a.marketCap)),o.totalVolume?.["24h"]==null&&(o.totalVolume={"24h":ce(a.total_volume)??ce(a.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let r=parseInt(e,16),o=Ys({chainId:r,duration:n,limit:t}),a=`${this.baseUrl}/token-list/all/top-gainers${o?`?${o}`:""}`,i=[];for(let l=0;l<5;l++){let c=await x.get(a);if(!c.ok)throw new Error(R(c));let u=c.data;if(i=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],i.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return i.map(l=>Gs(l,e))}async getTopGainers(e){let t=e?.chain||Te,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,r=e?.duration||"24h";try{let o=await this.fetchTopGainers(t,n,r);return await this.enrichTrendingMarketData(o,t),{success:!0,data:o}}catch(o){return{success:!1,error:o instanceof Error?o.message:"Unknown error"}}}};var Ul="https://nft.keyring.app",Il="https://nft.keyring.app",Ll=.01,U=5,H=1e3,Dl=25,Ol="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Ml="0x0000000000000000000000000000000000000000",I=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function z(s){return s||Te}function V(s){let e=[];for(let[t,n]of Object.entries(s))if(n!=null)if(Array.isArray(n))for(let r of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function W(s){return new Promise(e=>setTimeout(e,s))}function Fl(s){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!s||typeof s!="object")return e;let t=s;if("active_protocols"in t||"total_usd_value"in t){let r=t;return{...e,...r,protocols:r.protocols||[]}}let n=t.result;return!n||typeof n!="object"?e:{active_protocols:n.activeProtocols??0,total_positions:n.totalPositions??0,total_usd_value:n.totalUsd??0,total_unclaimed_usd_value:n.totalUnclaimedUsd??0,protocols:(n.protocols||[]).map(r=>({protocol_id:r.protocolId,protocol_name:r.protocolName,protocol_url:r.protocolUrl??"",protocol_logo:r.protocolLogo??"",positions:r.positionCount??0,total_usd_value:r.totalUsd??0,total_unclaimed_usd_value:r.totalUnclaimedUsd??0,account_health_factor:r.accountHealthFactor??null}))}}function ql(s){if(Array.isArray(s))return s;if(s&&typeof s=="object"){let e=s;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function Ur(s){if(Array.isArray(s))return s;if(s&&typeof s=="object"){let e=s;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var D=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Ul).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Il).replace(/\/+$/,""),this.pantograph=new ue({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:r,excludeSpam:o=!1,excludeUnverifiedContracts:a=!1}=e;if(!t)return{success:!1,error:"Address is required"};let i=z(n),l="Unknown error";for(let c=1;c<=U;c++)try{let u={chain:i,exclude_spam:o,exclude_unverified_contracts:a,limit:100};r&&(u.token_addresses=r);let d=[],p=null;do{p&&(u.cursor=p);let f=V(u),m=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${f}`,g=await x.get(m);if(!g.ok)throw new I(g.status,R(g));let y=g.data,b=y?.data??y;b?.result?.length>0&&d.push(...b.result),p=b?.cursor??null}while(p);let h={result:d};return h?.result?.length>0&&(h.result=h.result.filter(f=>parseFloat(f.balance||"0")>0),h.result=h.result.map(f=>({...f,token_address:f.token_address.toLowerCase()===Ol?Ml:f.token_address})),await this.enrichTokenPrices(h.result,i),h.result=h.result.filter(f=>f.usd_value==null||f.usd_value>=Ll)),{success:!0,data:h}}catch(u){if(l=u instanceof Error?u.message:"Unknown error",u instanceof I&&u.status===400)break;c<U&&await W(H)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let r=z(n),o="Unknown error",a=await this.pantograph.getTokenMetadata(t,r);if(a)return{success:!0,data:a};for(let i=1;i<=U;i++)try{let[l,c]=await Promise.allSettled([x.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${V({chain:r,addresses:[t]})}`),x.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${V({chain:r,include:"percent_change"})}`)]),u=null;if(l.status==="fulfilled"&&l.value.ok){let p=l.value.data;u=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!u){o="Token metadata not found",i<U&&await W(H);continue}let d=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;d=p?.data??p}return{success:!0,data:{...u,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(o=l instanceof Error?l.message:"Unknown error",l instanceof I&&l.status===400)break;i<U&&await W(H)}return{success:!1,error:o}}async getWalletNFTs(e){let{address:t,chain:n,limit:r=100,excludeSpam:o=!1,cursor:a,tokenAddresses:i,includePrices:l,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let u=z(n),d=[],p=a,h,f;for(let m=0;m<Dl;m++){let g=await this.fetchWalletNftsPage({address:t,moralisChain:u,limit:r,excludeSpam:o,cursor:p,tokenAddresses:i,includePrices:l,format:c});if(!g.success){if(d.length===0)return g;break}let y=g.data;if(!y)break;let{result:b,cursor:w,page:k,page_size:T}=y;if(Array.isArray(b)&&d.push(...b),h=k,f=T,p=typeof w=="string"&&w.trim()?w:void 0,!p)break}return{success:!0,data:{result:d,cursor:p,page:h,page_size:f}}}async fetchWalletNftsPage(e){let{address:t,moralisChain:n,limit:r,excludeSpam:o,cursor:a,tokenAddresses:i,includePrices:l,format:c}=e,u="Unknown error";for(let d=1;d<=U;d++)try{let p={chain:n,format:c,limit:r,exclude_spam:o,media_items:!0,normalizeMetadata:!0};a&&(p.cursor=a),l&&(p.include_prices=!0),i&&i.length>0&&(p.token_addresses=i);let h=V(p),f=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${h}`,m=await x.get(f);if(!m.ok)throw new I(m.status,R(m));let g=m.data;return{success:!0,data:g?.data??g}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof I&&p.status===400)break;d<U&&await W(H)}return{success:!1,error:u}}async getWalletNftCollections(e){let{address:t,chain:n,limit:r=100,excludeSpam:o=!0,cursor:a}=e;if(!t)return{success:!1,error:"Address is required"};let i=z(n),l="Unknown error";for(let c=1;c<=U;c++)try{let u={chain:i,limit:r,exclude_spam:o};a&&(u.cursor=a);let d=V(u),p=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/collections?${d}`,h=await x.get(p);if(!h.ok)throw new I(h.status,R(h));let f=h.data;return{success:!0,data:f?.data??f}}catch(u){if(l=u instanceof Error?u.message:"Unknown error",u instanceof I&&u.status===400)break;c<U&&await W(H)}return{success:!1,error:l}}async getNftMetadata(e){let{address:t,tokenId:n,chain:r,format:o="decimal",normalizeMetadata:a=!0,mediaItems:i=!0,include:l}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!F(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=z(r),u="Unknown error";for(let d=1;d<=U;d++)try{let p={chain:c,format:o,normalizeMetadata:a,media_items:i};l&&(p.include=l);let h=V(p),f=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${h}`,m=await x.get(f);if(!m.ok)throw new I(m.status,R(m));let g=m.data;return{success:!0,data:g?.data??g}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof I&&p.status===400)break;d<U&&await W(H)}return{success:!1,error:u}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getWalletHistory(e){let{address:t,chain:n,limit:r=25,fromDate:o,toDate:a,fromBlock:i,toBlock:l,cursor:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let h=z(n),f=Math.max(1,Math.min(100,Math.floor(r))),m="Unknown error";for(let g=1;g<=U;g++)try{let y={chain:h,limit:f,order:u};o&&(y.from_date=o),a&&(y.to_date=a),i!=null&&(y.from_block=i),l!=null&&(y.to_block=l),c&&(y.cursor=c),d!=null&&(y.include_internal_transactions=d),p!=null&&(y.nft_metadata=p);let b=V(y),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,k=await x.get(w);if(!k.ok)throw new I(k.status,R(k));let T=k.data;return{success:!0,data:T?.data??T}}catch(y){if(m=y instanceof Error?y.message:"Unknown error",y instanceof I&&y.status===400)break;g<U&&await W(H)}return{success:!1,error:m}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:u,order:d="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=z(n),h=Math.max(1,Math.min(100,Math.floor(o))),f="Unknown error";for(let m=1;m<=U;m++)try{let g={chain:p,limit:h,order:d};a&&(g.from_date=a),i&&(g.to_date=i),l!=null&&(g.from_block=l),c!=null&&(g.to_block=c),u&&(g.cursor=u),r?.length&&(g.contract_addresses=r);let y=V(g),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,w=await x.get(b);if(!w.ok)throw new I(w.status,R(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 I&&g.status===400)break;m<U&&await W(H)}return{success:!1,error:f}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:r,limit:o=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:u,order:d="DESC",includePrices:p,format:h="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let f=z(n),m=Math.max(1,Math.min(100,Math.floor(o))),g="Unknown error";for(let y=1;y<=U;y++)try{let b={chain:f,limit:m,order:d,format:h};a&&(b.from_date=a),i&&(b.to_date=i),l!=null&&(b.from_block=l),c!=null&&(b.to_block=c),u&&(b.cursor=u),r?.length&&(b.contract_addresses=r),p!=null&&(b.include_prices=p);let w=V(b),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,T=await x.get(k);if(!T.ok)throw new I(T.status,R(T));let P=T.data;return{success:!0,data:P?.data??P}}catch(b){if(g=b instanceof Error?b.message:"Unknown error",b instanceof I&&b.status===400)break;y<U&&await W(H)}return{success:!1,error:g}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!F(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getWalletPnlSummary(e){let{address:t,chain:n,days:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let o=z(n),a="Unknown error";for(let i=1;i<=U;i++)try{let l={chain:o};r&&(l.days=r);let c=V(l),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,d=await x.get(u);if(!d.ok)throw new I(d.status,R(d));let p=d.data;return{success:!0,data:p?.data??p}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof I&&l.status===400)break;i<U&&await W(H)}return{success:!1,error:a}}async getWalletPnl(e){let{address:t,chain:n,days:r,tokenAddresses:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=z(n),i="Unknown error";for(let l=1;l<=U;l++)try{let c={chain:a};r&&(c.days=r),o&&o.length>0&&(c.token_addresses=o.slice(0,25));let u=V(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${u}`,p=await x.get(d);if(!p.ok)throw new I(p.status,R(p));let h=p.data;return{success:!0,data:h?.data??h}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof I&&c.status===400)break;l<U&&await W(H)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getWalletApprovals(e){let{address:t,chain:n,limit:r,cursor:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=z(n),i="Unknown error";for(let l=1;l<=U;l++)try{let c={chain:a};r!=null&&(c.limit=r),o&&(c.cursor=o);let u=V(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${u}`,p=await x.get(d);if(!p.ok)throw new I(p.status,R(p));let h=p.data;return{success:!0,data:h?.data??h}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof I&&c.status===400)break;l<U&&await W(H)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data,d=u?.data??u;return{success:!0,data:Fl(d)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!F(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chains:r}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data,d=u?.data??u;return{success:!0,data:ql(d)}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:n,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!F(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let o=z(r),a="Unknown error";for(let i=1;i<=U;i++)try{let l=V({chains:o}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${l}`,u=await x.get(c);if(!u.ok)throw new I(u.status,R(u));let h=u.data.result;return{success:!0,data:{protocol_id:h.protocolId,protocol_name:h.protocolName,protocol_url:h.protocolUrl??"",protocol_logo:h.protocolLogo??"",total_usd_value:h.totalUsd??0,total_unclaimed_usd_value:h.totalUnclaimedUsd??null,positions:h.positions.map(m=>({label:m.label,address:m.address,balance_usd:m.balanceUsd??0,total_unclaimed_usd_value:m.unclaimedUsd??0,position_details:m.details,tokens:m.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 I&&l.status===400)break;i<U&&await W(H)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!F(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getTokenScore(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!F(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let r=z(n),o="Unknown error";for(let a=1;a<=U;a++)try{let i=V({chain:r}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(o=i instanceof Error?i.message:"Unknown error",i instanceof I&&i.status===400)break;a<U&&await W(H)}return{success:!1,error:o}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,r="Unknown error";for(let o=1;o<=U;o++)try{let a={};t&&(a.chain=z(t)),n!=null&&(a.limit=n);let i=V(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await x.get(l);if(!c.ok)throw new I(c.status,R(c));let u=c.data,d=u?.data??u;return{success:!0,data:Ur(d)}}catch(a){if(r=a instanceof Error?a.message:"Unknown error",a instanceof I&&a.status===400)break;o<U&&await W(H)}return{success:!1,error:r}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},a="Unknown error";for(let i=1;i<=U;i++)try{let l={};t&&(l.chain=z(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=V(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await x.get(u);if(!d.ok)throw new I(d.status,R(d));let p=d.data,h=p?.data??p;return{success:!0,data:Ur(h)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof I&&l.status===400)break;i<U&&await W(H)}return{success:!1,error:a}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:r,securityScore:o}=e??{},a="Unknown error";for(let i=1;i<=U;i++)try{let l={};t&&(l.chain=z(t)),n&&(l.time_frame=n),r!=null&&(l.min_market_cap=r),o!=null&&(l.security_score=o);let c=V(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await x.get(u);if(!d.ok)throw new I(d.status,R(d));let p=d.data,h=p?.data??p;return{success:!0,data:Ur(h)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof I&&l.status===400)break;i<U&&await W(H)}return{success:!1,error:a}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var Ot=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 D(e),this.llm=new J(e?.llm??{})}async run(e,t){let n=e.keyword||"",r=e.prompt||"",o=t?.walletAddress||void 0;if(!n)return{error:"Missing required parameter: keyword"};let a;try{a=oe(e.chain,t)}catch(i){if(i instanceof tt)return await this.researchTokenChainAgnostic(n,r,o);throw i}return await this.searchToken(n,a,r,o)}async researchTokenChainAgnostic(e,t,n){let r=[n?`User's connected wallet address: ${n}`:null,"The user's connected chain is not one this app supports on-chain, so answer using web research only \u2014 do not assume a specific chain; identify the token across whichever chain(s) it actually exists on."].filter(Boolean).join(`
|
|
3
3
|
`),o=t?await this.askGeminiWithSearch(t,r):null;return{_instructions:'The token info comes from web research only (the user is on a chain this app does not support on-chain). Present a clear summary of the token using the research: what it is, current USD price and 24h change, market data, recent news and the catalyst behind any price move, and a brief, clearly-hedged sense of market direction (no financial advice). Do NOT add a labelled "AI Analysis" heading and do NOT mention that the analysis came from AI \u2014 write it as a normal token summary. If a field is unknown, omit it. Do NOT mention chains, tools, or that anything is unsupported; just answer the question.',keyword:e,token:null,userHoldsToken:!1,research:o}}async searchToken(e,t,n,r){let o=[r?`User's connected wallet address: ${r}`:null,t?`Current chain (hex chain ID): ${t}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
|
|
4
|
-
`),[a,i,l]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),r?this.findTokenInWallet(r,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,o):Promise.resolve(null)]),c=a.success&&a.data?Array.isArray(a.data)?a.data:[]:[],u=e.toLowerCase(),d=g=>g.symbol?.toLowerCase()===u||g.token_address?.toLowerCase()===u,p=[...c].sort((g,y)=>(d(g)?0:1)-(d(y)?0:1)),h=null,f=p[0];if(f?.token_address){let g=await this.service.getTokenMetadata({address:f.token_address,chain:t});g.success&&g.data&&(h=g.data)}return!h&&f&&(h={...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:h,...c.length>1?{searchResults:p.slice(0,10)}:{},research:l}}async askGeminiWithSearch(e,t){let n=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:n}]:[],{role:"user",content:e,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,n){if(!n)return null;let r=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1});if(!r.success||!r.data?.result)return null;let o=n.toLowerCase(),a=r.data.result.find(i=>i.token_address.toLowerCase()===o||i.symbol?.toLowerCase()===o||i.name?.toLowerCase().includes(o));return a||null}};var Ft=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 D(e)}async run(e,t){let n=oe(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!a)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let i,l;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?v(n):"the selected chain"}. Try passing contractAddress directly.`};a=d.address,i=d.symbol,l=d.name}let c=await this.service.getTokenHolders({address:a,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let u=c.data;return{token:{symbol:i??o??null,name:l??null,contractAddress:a,chain:n||"default"},totalHolders:u.totalHolders,holdersByAcquisition:u.holdersByAcquisition,holderChange:u.holderChange,holderSupply:u.holderSupply,holderDistribution:u.holderDistribution}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var qt=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 D(e)}async run(e,t){let n=oe(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!a)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?v(n):"the selected chain"}. Try passing contractAddress directly.`};a=d.address,i=d.symbol,l=d.name}let c=await this.service.getTokenAnalytics({address:a,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let u=c.data??{};return{token:{symbol:i??o??null,name:l??null,contractAddress:a,chain:n||"default"},usdPrice:u.usdPrice??null,totalLiquidity:u.totalLiquidity??null,totalFullyDilutedValuation:u.totalFullyDilutedValuation??null,totalBuyVolume:u.totalBuyVolume??null,totalSellVolume:u.totalSellVolume??null,totalBuyers:u.totalBuyers??null,totalSellers:u.totalSellers??null,totalBuys:u.totalBuys??null,totalSells:u.totalSells??null,uniqueWallets:u.uniqueWallets??null,pricePercentChange:u.pricePercentChange??null}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Bt=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 D(e)}async run(e,t){let n=oe(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!a)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(o){let p=await this.resolveContractAddress(o,n,r);if(!p)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?v(n):"the selected chain"}. Try passing contractAddress directly.`};a=p.address,i=p.symbol,l=p.name}let c=await this.service.getTokenScore({address:a,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token score"};let u=c.data??{},d=u.metrics??{};return{token:{symbol:i??o??null,name:l??null,contractAddress:a,chain:n||"default"},score:u.score??null,updatedAt:u.updatedAt??null,metrics:{usdPrice:d.usdPrice??null,liquidityUsd:d.liquidityUsd??null,volumeUsd:d.volumeUsd??null,transactions:d.transactions??null,supply:d.supply??null}}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var $t=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 ue({baseUrl:e?.pantographUrl})}async run(e,t){let n=Ro(e.chain,t),r=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,o=await this.service.getTrendingTokens({chain:n,limit:r});if(!o.success)return{error:o.error||"Failed to fetch trending tokens"};let a=o.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):
|
|
4
|
+
`),[a,i,l]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),r?this.findTokenInWallet(r,t,e):Promise.resolve(null),n?this.askGeminiWithSearch(n,o):Promise.resolve(null)]),c=a.success&&a.data?Array.isArray(a.data)?a.data:[]:[],u=e.toLowerCase(),d=g=>g.symbol?.toLowerCase()===u||g.token_address?.toLowerCase()===u,p=[...c].sort((g,y)=>(d(g)?0:1)-(d(y)?0:1)),h=null,f=p[0];if(f?.token_address){let g=await this.service.getTokenMetadata({address:f.token_address,chain:t});g.success&&g.data&&(h=g.data)}return!h&&f&&(h={...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:h,...c.length>1?{searchResults:p.slice(0,10)}:{},research:l}}async askGeminiWithSearch(e,t){let n=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:n}]:[],{role:"user",content:e,timestamp:n}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,n){if(!n)return null;let r=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1});if(!r.success||!r.data?.result)return null;let o=n.toLowerCase(),a=r.data.result.find(i=>i.token_address.toLowerCase()===o||i.symbol?.toLowerCase()===o||i.name?.toLowerCase().includes(o));return a||null}};var Mt=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 D(e)}async run(e,t){let n=oe(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!a)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let i,l;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?v(n):"the selected chain"}. Try passing contractAddress directly.`};a=d.address,i=d.symbol,l=d.name}let c=await this.service.getTokenHolders({address:a,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let u=c.data;return{token:{symbol:i??o??null,name:l??null,contractAddress:a,chain:n||"default"},totalHolders:u.totalHolders,holdersByAcquisition:u.holdersByAcquisition,holderChange:u.holderChange,holderSupply:u.holderSupply,holderDistribution:u.holderDistribution}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Ft=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 D(e)}async run(e,t){let n=oe(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!a)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(o){let d=await this.resolveContractAddress(o,n,r);if(!d)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?v(n):"the selected chain"}. Try passing contractAddress directly.`};a=d.address,i=d.symbol,l=d.name}let c=await this.service.getTokenAnalytics({address:a,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let u=c.data??{};return{token:{symbol:i??o??null,name:l??null,contractAddress:a,chain:n||"default"},usdPrice:u.usdPrice??null,totalLiquidity:u.totalLiquidity??null,totalFullyDilutedValuation:u.totalFullyDilutedValuation??null,totalBuyVolume:u.totalBuyVolume??null,totalSellVolume:u.totalSellVolume??null,totalBuyers:u.totalBuyers??null,totalSellers:u.totalSellers??null,totalBuys:u.totalBuys??null,totalSells:u.totalSells??null,uniqueWallets:u.uniqueWallets??null,pricePercentChange:u.pricePercentChange??null}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var qt=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 D(e)}async run(e,t){let n=oe(e.chain,t),r=t?.walletAddress||void 0,o=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!o&&!a)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(o){let p=await this.resolveContractAddress(o,n,r);if(!p)return{error:`Cannot resolve token symbol "${o}" to a contract address on ${n?v(n):"the selected chain"}. Try passing contractAddress directly.`};a=p.address,i=p.symbol,l=p.name}let c=await this.service.getTokenScore({address:a,chain:n});if(!c.success)return{error:c.error||"Failed to fetch token score"};let u=c.data??{},d=u.metrics??{};return{token:{symbol:i??o??null,name:l??null,contractAddress:a,chain:n||"default"},score:u.score??null,updatedAt:u.updatedAt??null,metrics:{usdPrice:d.usdPrice??null,liquidityUsd:d.liquidityUsd??null,volumeUsd:d.volumeUsd??null,transactions:d.transactions??null,supply:d.supply??null}}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Bt=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 ue({baseUrl:e?.pantographUrl})}async run(e,t){let n=Ro(e.chain,t),r=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,o=await this.service.getTrendingTokens({chain:n,limit:r});if(!o.success)return{error:o.error||"Failed to fetch trending tokens"};let a=o.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):
|
|
5
5
|
<rank>. <name> (<symbol>)
|
|
6
6
|
- Price: <usdPrice>
|
|
7
7
|
- Market Cap: <marketCap>
|
|
8
8
|
- 24h Price Change: <pricePercentChange.24h>
|
|
9
9
|
- 24h Volume: <totalVolume.24h>
|
|
10
|
-
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+3.56%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:n?v(n):"all",count:a.length,tokens:a}}};var Xs={"1h":"1h","1d":"24h","1w":"7d","1M":"30d"},zs=Object.keys(Xs)
|
|
10
|
+
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+3.56%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:n?v(n):"all",count:a.length,tokens:a}}};var Xs={"1h":"1h","1d":"24h","1w":"7d","1M":"30d"},zs=Object.keys(Xs),$t=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 ue({baseUrl:e?.pantographUrl})}async run(e,t){let n=Ro(e.chain,t),r=typeof e.timeFrame=="string"?e.timeFrame.trim():void 0;if(r&&!zs.includes(r))return{error:`Invalid timeFrame "${r}". Allowed values: ${zs.join(", ")}.`};let o=r||void 0,a=o?Xs[o]:void 0,i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,l=await this.service.getTopGainers({chain:n,limit:i,duration:a});if(!l.success)return{error:l.error||"Failed to fetch top gainers"};let c=l.data??[];return{_instructions:`Start with a one-line header like "Here are the top gainers on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
|
|
11
11
|
<rank>. <name> (<symbol>)
|
|
12
12
|
- Price: <usdPrice>
|
|
13
13
|
- Market Cap: <marketCap>
|
|
14
14
|
- Price Change: <pricePercentChange.24h> (prefix "+" for positive, "-" for negative)
|
|
15
15
|
- 24h Volume: <totalVolume.24h>
|
|
16
|
-
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:n?v(n):"all",timeFrame:o??null,count:c.length,tokens:c}}};var Vt=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 D(e)}truncateUsd(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[n,r=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${n}.${(r+"00").slice(0,2)}`}async run(e,t){let n=j(e.address,t),r=Z(e.chain,t);if(r){let i=await this.service.getWalletTokenBalances({address:n,chain:r,excludeSpam:!1,excludeUnverifiedContracts:!1});return i.success?this.renderBalances(n,r,i.data?.result||[]):{error:i.error||"Failed to fetch token balances"}}let o=ve(),a=await Promise.all(o.map(async i=>{let l=await this.service.getWalletTokenBalances({address:n,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(n,a)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",n=e.balance_formatted??"0",r=e.symbol||"",o=typeof e.usd_value=="number"?`$${this.truncateUsd(e.usd_value)}`:"$-";return`- ${t}: ${n} ${r} (${o})`.replace(/\s+/g," ").trim()}renderBalances(e,t,n){let r=n.reduce((o,a)=>o+(a.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:e,chain:t,totalUsdValue:`$${this.truncateUsd(r)}`,tokens:n.map(o=>this.toTokenLine(o))}}renderBalancesByChain(e,t){let n=t.map(o=>{let a=o.tokens.reduce((l,c)=>l+(c.usd_value||0),0),i=o.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:v(o.chain),total:a,tokens:i}}).filter(o=>o.tokens.length>0).sort((o,a)=>a.total-o.total),r=n.reduce((o,a)=>o+a.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:e,chain:"all",totalUsdValue:`$${this.truncateUsd(r)}`,chains:n.map(o=>({chain:o.chain,totalUsdValue:`$${this.truncateUsd(o.total)}`,tokens:o.tokens.map(a=>this.toTokenLine(a))}))}}};var Wt=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 D(e)}async run(e,t){let n=j(e.address,t),r=oe(e.chain,t),o=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,a=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,i=typeof e.fromBlock=="number"?e.fromBlock:typeof e.fromBlock=="string"&&e.fromBlock?Number(e.fromBlock):void 0,l=typeof e.toBlock=="number"?e.toBlock:typeof e.toBlock=="string"&&e.toBlock?Number(e.toBlock):void 0,c=Number.isFinite(i)?i:void 0,u=Number.isFinite(l)?l:void 0,d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,h=(typeof e.order=="string"?e.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",f=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,m=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,g=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,y=Number.isFinite(g)&&g>0?g:10,b=await this.service.getWalletHistory({address:n,chain:r,limit:y,fromDate:o,toDate:a,fromBlock:c,toBlock:u,cursor:d,order:h,includeInternalTransactions:f,nftMetadata:m});if(!b.success)return{error:b.error||"Failed to fetch wallet history"};let k=(b.data?.result||[]).map(T=>{let P=$s(r,T.hash);return P?{...T,explorerUrl:P}:T});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:n,chain:r||"default",pagination:{cursor:b.data?.cursor??null,hasMore:!!b.data?.cursor},transactionCount:k.length,transactions:k}}};function Bl(s){if(s.value_decimal)return s.value_decimal;let e=parseInt(s.token_decimals??"18",10);if(isNaN(e)||e===0)return s.value;try{let t=BigInt(s.value),n=BigInt(10)**BigInt(e),r=t/n,a=(t%n).toString().padStart(e,"0").replace(/0+$/,"");return a?`${r}.${a}`:`${r}`}catch{return s.value}}var Yt=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 D(e)}async run(e,t){let n=j(e.address,t),r=oe(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,h=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",m=f==="send"?"send":f==="receive"?"receive":"all",g=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(C=>typeof C=="string"&&!!C).map(C=>C.trim()):void 0,b,w;if(g){let C=await this.resolveContractAddressBySymbol(g,n,r);C&&(y=[C.address],b=C.symbol,w=C.name)}let k=await this.service.getWalletTokenTransfers({address:n,chain:r,contractAddresses:y,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:h});if(!k.success)return{error:k.error||"Failed to fetch token transfers"};let T=n.toLowerCase(),S=(k.data?.result||[]).map(C=>{let q=C.from_address.toLowerCase()===T,E=q?"send":"receive",ee=q?C.to_address:C.from_address,O=q?C.to_address_label??void 0:C.from_address_label??void 0,Ie=q?C.to_address_entity??void 0:C.from_address_entity??void 0;return{...C,direction:E,amount_formatted:Bl(C),counterparty:ee,counterparty_label:O,counterparty_entity:Ie}}),_=m==="all"?S:S.filter(C=>C.direction===m);if(g&&!y){let C=g.toLowerCase();_=_.filter(q=>(q.token_symbol??"").toLowerCase()===C)}let N=this.buildCounterparties(_);return{walletAddress:n,chain:r||"default",resolvedToken:b?{symbol:b,name:w,contractAddress:y?.[0]}:null,filters:{tokenSymbol:g||null,contractAddresses:y||null,direction:m,limit:a,order:h,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:u??null},pagination:{cursor:k.data?.cursor??null,pageSize:k.data?.page_size??a,page:k.data?.page??null,hasMore:!!k.data?.cursor},transferCount:_.length,transfers:_,counterparties:N}}async resolveContractAddressBySymbol(e,t,n){let r=e.toLowerCase(),o=await this.service.getWalletTokenBalances({address:t,chain:n});if(o.success&&o.data?.result?.length){let i=o.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}let a=await this.service.searchTokensByKey({key:e,chain:n});if(a.success&&a.data?.length){let l=a.data.find(c=>(c.symbol??"").toLowerCase()===r)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}buildCounterparties(e){let t=new Map,n=new Map;for(let o of e){let a=o.direction==="send"?t:n,i=o.counterparty.toLowerCase(),l=parseFloat(o.amount_formatted)||0,c=a.get(i);c?(c.total+=l,c.count+=1,!c.label&&o.counterparty_label&&(c.label=o.counterparty_label),!c.entity&&o.counterparty_entity&&(c.entity=o.counterparty_entity),o.block_timestamp<c.first&&(c.first=o.block_timestamp),o.block_timestamp>c.last&&(c.last=o.block_timestamp)):a.set(i,{label:o.counterparty_label,entity:o.counterparty_entity,total:l,count:1,first:o.block_timestamp,last:o.block_timestamp})}let r=o=>Array.from(o.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,total_amount:i.total.toFixed(6).replace(/\.?0+$/,""),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:r(t),received:r(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Gt=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 D(e)}async run(e,t){let n=j(e.address,t),r=oe(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,h=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.includePrices=="boolean"?e.includePrices:void 0,m=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",g=m==="send"?"send":m==="receive"?"receive":"all",y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(_=>typeof _=="string"&&!!_).map(_=>_.trim()):void 0,b=await this.service.getWalletNftTransfers({address:n,chain:r,contractAddresses:y,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:h,includePrices:f});if(!b.success)return{error:b.error||"Failed to fetch NFT transfers"};let w=n.toLowerCase(),T=(b.data?.result||[]).map(_=>{let N=_.from_address.toLowerCase()===w,C=N?"send":"receive",q=N?_.to_address:_.from_address,E=N?_.to_address_label??void 0:_.from_address_label??void 0,ee=N?_.to_address_entity??void 0:_.from_address_entity??void 0;return{..._,direction:C,counterparty:q,counterparty_label:E,counterparty_entity:ee}}),P=g==="all"?T:T.filter(_=>_.direction===g),S=this.buildCounterparties(P);return{walletAddress:n,chain:r||"default",filters:{contractAddresses:y||null,direction:g,limit:a,order:h,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:u??null,includePrices:f??null},pagination:{cursor:b.data?.cursor??null,pageSize:b.data?.page_size??a,page:b.data?.page??null,hasMore:!!b.data?.cursor},transferCount:P.length,transfers:P,counterparties:S}}buildCounterparties(e){let t=new Map,n=new Map;for(let o of e){let a=o.direction==="send"?t:n,i=o.counterparty.toLowerCase(),l=o.token_name??o.token_address,c=a.get(i);c?(c.tokenIds.add(o.token_id),c.collections.add(l),c.count+=1,!c.label&&o.counterparty_label&&(c.label=o.counterparty_label),!c.entity&&o.counterparty_entity&&(c.entity=o.counterparty_entity),o.block_timestamp<c.first&&(c.first=o.block_timestamp),o.block_timestamp>c.last&&(c.last=o.block_timestamp)):a.set(i,{label:o.counterparty_label,entity:o.counterparty_entity,tokenIds:new Set([o.token_id]),collections:new Set([l]),count:1,first:o.block_timestamp,last:o.block_timestamp})}let r=o=>Array.from(o.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,token_ids:Array.from(i.tokenIds),collections:Array.from(i.collections),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:r(t),received:r(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var $l=["all","7","30","60","90"],Kt=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 D(e)}async run(e,t){let n=j(e.address,t),r=Z(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=$l.includes(o)?o:void 0;if(r){let m=await this.service.getWalletPnlSummary({address:n,chain:r,days:a});return m.success?{walletAddress:n,chain:r,days:a??"all",summary:this.mapSummary(m.data)}:{error:m.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(ve().map(async m=>{let g=await this.service.getWalletPnlSummary({address:n,chain:m,days:a});return{chain:m,data:g.success?g.data:void 0}}))).flatMap(m=>m.data&&m.data.total_count_of_trades>0?[{chain:m.chain,data:m.data}]:[]),c=l.map(m=>({chain:v(m.chain),summary:this.mapSummary(m.data)})),u=l.reduce((m,g)=>m+Number(g.data.total_realized_profit_usd||0),0),d=l.reduce((m,g)=>m+Number(g.data.total_bought_volume_usd||0),0),p=l.reduce((m,g)=>m+Number(g.data.total_sold_volume_usd||0),0),h=l.reduce((m,g)=>m+Number(g.data.total_trade_volume||0),0),f={totalCountOfTrades:l.reduce((m,g)=>m+g.data.total_count_of_trades,0),totalTradeVolume:h,totalRealizedProfitUsd:u,totalRealizedProfitPercentage:d>0?u/d*100:0,totalBuys:l.reduce((m,g)=>m+g.data.total_buys,0),totalSells:l.reduce((m,g)=>m+g.data.total_sells,0),totalBoughtVolumeUsd:d,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:a??"all",summary: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 Hl=["all","7","30","60","90"],Uo=25,jt=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 ${Uo}. 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 ${Uo}.`,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 ${Uo}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=j(e.address,t),r=Z(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=Hl.includes(o)?o:void 0,i=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[],l=Array.isArray(e.tokenAddresses)?e.tokenAddresses.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[];if(r){let d=await this.fetchChainPnl(n,r,a,i,l);return d.ok?{walletAddress:n,chain:r,days:a??"all",filters:{tokenAddresses:d.tokenAddresses??null,resolvedSymbols:d.resolvedFromSymbols.length>0?d.resolvedFromSymbols:null,unresolvedSymbols:d.unresolvedSymbols.length>0?d.unresolvedSymbols:null},tokenCount:d.tokens.length,tokens:d.tokens}:{error:d.error||"Failed to fetch wallet PnL"}}let u=(await Promise.all(ve().map(async d=>({chain:d,res:await this.fetchChainPnl(n,d,a,i,l)})))).filter(d=>d.res.ok&&d.res.tokens.length>0).map(d=>({chain:v(d.chain),tokenCount:d.res.tokens.length,tokens:d.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:a??"all",filters:{requestedSymbols:i.length>0?i:null,requestedAddresses:l.length>0?l:null},tokenCount:u.reduce((d,p)=>d+p.tokenCount,0),chains:u}}async fetchChainPnl(e,t,n,r,o){let a=[],i=[];r.length>0&&(await Promise.all(r.map(p=>this.resolveContractAddress(p,t,e)))).forEach((p,h)=>{p?a.push({symbol:r[h],address:p.address}):i.push(r[h])});let l=Vl([...a.map(d=>d.address),...o]).slice(0,Uo),c=l.length>0?l:void 0,u=await this.service.getWalletPnl({address:e,chain:t,days:n,tokenAddresses:c});return{ok:u.success,error:u.error,tokens:u.data?.result??[],tokenAddresses:c,resolvedFromSymbols:a,unresolvedSymbols:i}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};function Vl(s){let e=new Set,t=[];for(let n of s){let r=n.toLowerCase();e.has(r)||(e.add(r),t.push(n))}return t}var Wl=BigInt(2)**BigInt(255),zt=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 D(e)}async run(e,t){let n=j(e.address,t),r=oe(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):100,i=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,l=await this.service.getWalletApprovals({address:n,chain:r,limit:a,cursor:i});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,d=(c.result||[]).map(m=>Yl(m)),p=0,h=0,f=[];for(let m of d){m.isUnlimited&&(h+=1);let g=parseFloat(m.token.usdAtRisk??"");Number.isFinite(g)&&(p+=g);let y=m.token.possibleSpam||m.token.verifiedContract===!1,b=!m.spender.label&&!m.spender.entity;(y||m.isUnlimited&&b)&&f.push(m)}return{walletAddress:n,chain:r||"default",filters:{limit:a,cursor:i??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??a,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:d.length,unlimitedApprovals:h,totalUsdAtRisk:p,riskyApprovalCount:f.length},approvals:d,riskyApprovals:f}}};function Yl(s){let e=Gl(s.value);return{blockNumber:s.block_number,blockTimestamp:s.block_timestamp??null,transactionHash:s.transaction_hash??null,value:s.value,valueFormatted:s.value_formatted??null,isUnlimited:e,token:{address:s.token.address,addressLabel:s.token.address_label??null,name:s.token.name??null,symbol:s.token.symbol??null,logo:s.token.logo??null,possibleSpam:!!s.token.possible_spam,verifiedContract:s.token.verified_contract??null,currentBalance:s.token.current_balance??null,currentBalanceFormatted:s.token.current_balance_formatted??null,usdPrice:s.token.usd_price??null,usdAtRisk:s.token.usd_at_risk??null},spender:{address:s.spender.address,label:s.spender.address_label??null,entity:s.spender.entity??null,entityLogo:s.spender.entity_logo??null}}}function Gl(s){if(!s)return!1;try{return BigInt(s)>=Wl}catch{return!1}}var Xt=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 D(e)}async run(e,t){let n=j(e.address,t),r=Z(e.chain,t);if(r){let i=await this.service.getWalletDefiPositions({address:n,chain:r});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=i.data||[];return{walletAddress:n,chain:r,positionCount:l.length,positions:l.map(Qs)}}let a=(await Promise.all(ve().map(async i=>{let l=await this.service.getWalletDefiPositions({address:n,chain:i});return{chain:i,rows:l.success?l.data||[]:[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:v(i.chain),positionCount:i.rows.length,positions:i.rows.map(Qs)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:n,chain:"all",positionCount:a.reduce((i,l)=>i+l.positionCount,0),chains:a}}};function Qs(s){return{protocolName:s.protocol_name,protocolId:s.protocol_id,protocolUrl:s.protocol_url,protocolLogo:s.protocol_logo,accountHealthFactor:s.account_data?.health_factor??null,position:Kl(s.position)}}function Kl(s){return{label:s.label,address:s.address,balanceUsd:s.balance_usd,totalUnclaimedUsdValue:s.total_unclaimed_usd_value,tokens:(s.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:s.position_details??null}}var Qt=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 D(e)}async run(e,t){let n=e.protocol?.trim();if(!n)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let r=j(e.address,t),o=Z(e.chain,t);if(o){let l=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:o});return l.success?l.data?{walletAddress:r,chain:o,...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(ve().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:v(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${n} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:r,chain:"all",protocol:n,totalUsdValue:i.reduce((l,c)=>l+c.totalUsdValue,0),chains:i}}protocolFields(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,accountHealthFactor:e.account_data?.health_factor??null,positionCount:(e.positions||[]).length,positions:(e.positions||[]).map(jl)}}};function jl(s){return{label:s.label,address:s.address,balanceUsd:s.balance_usd,totalUnclaimedUsdValue:s.total_unclaimed_usd_value,tokens:(s.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:s.position_details??null}}function zl(s){try{return(Number(BigInt(s))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return s}}var Jt=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 D(e)}async run(e,t){let n=e.transactionHash;if(!n)return{error:"Transaction hash is required."};let r=oe(e.chain,t),o=await this.service.getTransactionByHash({transactionHash:n,chain:r});if(!o.success||!o.data)return{error:o.error||"Failed to fetch transaction"};let a=o.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:zl(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 Fr=7,ea=K("totalSupply()"),Xl=K("totalAssets()"),Ql=K("getReserveData(address)"),ta=K("balanceOf(address)"),qr=K("decimals()"),na=K("symbol()"),Br=K("convertToAssets(uint256)"),Js=2,Jl=1e27,Zl=10,ec=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!) {
|
|
16
|
+
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:n?v(n):"all",timeFrame:o??null,count:c.length,tokens:c}}};var Ht=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 D(e)}truncateUsd(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[n,r=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${n}.${(r+"00").slice(0,2)}`}async run(e,t){let n=j(e.address,t),r=Z(e.chain,t);if(r){let i=await this.service.getWalletTokenBalances({address:n,chain:r,excludeSpam:!1,excludeUnverifiedContracts:!1});return i.success?this.renderBalances(n,r,i.data?.result||[]):{error:i.error||"Failed to fetch token balances"}}let o=ve(),a=await Promise.all(o.map(async i=>{let l=await this.service.getWalletTokenBalances({address:n,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(n,a)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",n=e.balance_formatted??"0",r=e.symbol||"",o=typeof e.usd_value=="number"?`$${this.truncateUsd(e.usd_value)}`:"$-";return`- ${t}: ${n} ${r} (${o})`.replace(/\s+/g," ").trim()}renderBalances(e,t,n){let r=n.reduce((o,a)=>o+(a.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:e,chain:t,totalUsdValue:`$${this.truncateUsd(r)}`,tokens:n.map(o=>this.toTokenLine(o))}}renderBalancesByChain(e,t){let n=t.map(o=>{let a=o.tokens.reduce((l,c)=>l+(c.usd_value||0),0),i=o.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:v(o.chain),total:a,tokens:i}}).filter(o=>o.tokens.length>0).sort((o,a)=>a.total-o.total),r=n.reduce((o,a)=>o+a.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:e,chain:"all",totalUsdValue:`$${this.truncateUsd(r)}`,chains:n.map(o=>({chain:o.chain,totalUsdValue:`$${this.truncateUsd(o.total)}`,tokens:o.tokens.map(a=>this.toTokenLine(a))}))}}};var Vt=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 D(e)}async run(e,t){let n=j(e.address,t),r=oe(e.chain,t),o=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,a=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,i=typeof e.fromBlock=="number"?e.fromBlock:typeof e.fromBlock=="string"&&e.fromBlock?Number(e.fromBlock):void 0,l=typeof e.toBlock=="number"?e.toBlock:typeof e.toBlock=="string"&&e.toBlock?Number(e.toBlock):void 0,c=Number.isFinite(i)?i:void 0,u=Number.isFinite(l)?l:void 0,d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,h=(typeof e.order=="string"?e.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",f=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,m=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,g=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,y=Number.isFinite(g)&&g>0?g:10,b=await this.service.getWalletHistory({address:n,chain:r,limit:y,fromDate:o,toDate:a,fromBlock:c,toBlock:u,cursor:d,order:h,includeInternalTransactions:f,nftMetadata:m});if(!b.success)return{error:b.error||"Failed to fetch wallet history"};let k=(b.data?.result||[]).map(T=>{let P=$s(r,T.hash);return P?{...T,explorerUrl:P}:T});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:n,chain:r||"default",pagination:{cursor:b.data?.cursor??null,hasMore:!!b.data?.cursor},transactionCount:k.length,transactions:k}}};function Bl(s){if(s.value_decimal)return s.value_decimal;let e=parseInt(s.token_decimals??"18",10);if(isNaN(e)||e===0)return s.value;try{let t=BigInt(s.value),n=BigInt(10)**BigInt(e),r=t/n,a=(t%n).toString().padStart(e,"0").replace(/0+$/,"");return a?`${r}.${a}`:`${r}`}catch{return s.value}}var Wt=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 D(e)}async run(e,t){let n=j(e.address,t),r=oe(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,h=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",m=f==="send"?"send":f==="receive"?"receive":"all",g=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(C=>typeof C=="string"&&!!C).map(C=>C.trim()):void 0,b,w;if(g){let C=await this.resolveContractAddressBySymbol(g,n,r);C&&(y=[C.address],b=C.symbol,w=C.name)}let k=await this.service.getWalletTokenTransfers({address:n,chain:r,contractAddresses:y,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:h});if(!k.success)return{error:k.error||"Failed to fetch token transfers"};let T=n.toLowerCase(),S=(k.data?.result||[]).map(C=>{let q=C.from_address.toLowerCase()===T,E=q?"send":"receive",ee=q?C.to_address:C.from_address,O=q?C.to_address_label??void 0:C.from_address_label??void 0,Ie=q?C.to_address_entity??void 0:C.from_address_entity??void 0;return{...C,direction:E,amount_formatted:Bl(C),counterparty:ee,counterparty_label:O,counterparty_entity:Ie}}),_=m==="all"?S:S.filter(C=>C.direction===m);if(g&&!y){let C=g.toLowerCase();_=_.filter(q=>(q.token_symbol??"").toLowerCase()===C)}let N=this.buildCounterparties(_);return{walletAddress:n,chain:r||"default",resolvedToken:b?{symbol:b,name:w,contractAddress:y?.[0]}:null,filters:{tokenSymbol:g||null,contractAddresses:y||null,direction:m,limit:a,order:h,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:u??null},pagination:{cursor:k.data?.cursor??null,pageSize:k.data?.page_size??a,page:k.data?.page??null,hasMore:!!k.data?.cursor},transferCount:_.length,transfers:_,counterparties:N}}async resolveContractAddressBySymbol(e,t,n){let r=e.toLowerCase(),o=await this.service.getWalletTokenBalances({address:t,chain:n});if(o.success&&o.data?.result?.length){let i=o.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}let a=await this.service.searchTokensByKey({key:e,chain:n});if(a.success&&a.data?.length){let l=a.data.find(c=>(c.symbol??"").toLowerCase()===r)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}buildCounterparties(e){let t=new Map,n=new Map;for(let o of e){let a=o.direction==="send"?t:n,i=o.counterparty.toLowerCase(),l=parseFloat(o.amount_formatted)||0,c=a.get(i);c?(c.total+=l,c.count+=1,!c.label&&o.counterparty_label&&(c.label=o.counterparty_label),!c.entity&&o.counterparty_entity&&(c.entity=o.counterparty_entity),o.block_timestamp<c.first&&(c.first=o.block_timestamp),o.block_timestamp>c.last&&(c.last=o.block_timestamp)):a.set(i,{label:o.counterparty_label,entity:o.counterparty_entity,total:l,count:1,first:o.block_timestamp,last:o.block_timestamp})}let r=o=>Array.from(o.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,total_amount:i.total.toFixed(6).replace(/\.?0+$/,""),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:r(t),received:r(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Yt=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 D(e)}async run(e,t){let n=j(e.address,t),r=oe(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,h=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.includePrices=="boolean"?e.includePrices:void 0,m=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",g=m==="send"?"send":m==="receive"?"receive":"all",y=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(_=>typeof _=="string"&&!!_).map(_=>_.trim()):void 0,b=await this.service.getWalletNftTransfers({address:n,chain:r,contractAddresses:y,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:h,includePrices:f});if(!b.success)return{error:b.error||"Failed to fetch NFT transfers"};let w=n.toLowerCase(),T=(b.data?.result||[]).map(_=>{let N=_.from_address.toLowerCase()===w,C=N?"send":"receive",q=N?_.to_address:_.from_address,E=N?_.to_address_label??void 0:_.from_address_label??void 0,ee=N?_.to_address_entity??void 0:_.from_address_entity??void 0;return{..._,direction:C,counterparty:q,counterparty_label:E,counterparty_entity:ee}}),P=g==="all"?T:T.filter(_=>_.direction===g),S=this.buildCounterparties(P);return{walletAddress:n,chain:r||"default",filters:{contractAddresses:y||null,direction:g,limit:a,order:h,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:u??null,includePrices:f??null},pagination:{cursor:b.data?.cursor??null,pageSize:b.data?.page_size??a,page:b.data?.page??null,hasMore:!!b.data?.cursor},transferCount:P.length,transfers:P,counterparties:S}}buildCounterparties(e){let t=new Map,n=new Map;for(let o of e){let a=o.direction==="send"?t:n,i=o.counterparty.toLowerCase(),l=o.token_name??o.token_address,c=a.get(i);c?(c.tokenIds.add(o.token_id),c.collections.add(l),c.count+=1,!c.label&&o.counterparty_label&&(c.label=o.counterparty_label),!c.entity&&o.counterparty_entity&&(c.entity=o.counterparty_entity),o.block_timestamp<c.first&&(c.first=o.block_timestamp),o.block_timestamp>c.last&&(c.last=o.block_timestamp)):a.set(i,{label:o.counterparty_label,entity:o.counterparty_entity,tokenIds:new Set([o.token_id]),collections:new Set([l]),count:1,first:o.block_timestamp,last:o.block_timestamp})}let r=o=>Array.from(o.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,token_ids:Array.from(i.tokenIds),collections:Array.from(i.collections),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:r(t),received:r(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var $l=["all","7","30","60","90"],Gt=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 D(e)}async run(e,t){let n=j(e.address,t),r=Z(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=$l.includes(o)?o:void 0;if(r){let m=await this.service.getWalletPnlSummary({address:n,chain:r,days:a});return m.success?{walletAddress:n,chain:r,days:a??"all",summary:this.mapSummary(m.data)}:{error:m.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(ve().map(async m=>{let g=await this.service.getWalletPnlSummary({address:n,chain:m,days:a});return{chain:m,data:g.success?g.data:void 0}}))).flatMap(m=>m.data&&m.data.total_count_of_trades>0?[{chain:m.chain,data:m.data}]:[]),c=l.map(m=>({chain:v(m.chain),summary:this.mapSummary(m.data)})),u=l.reduce((m,g)=>m+Number(g.data.total_realized_profit_usd||0),0),d=l.reduce((m,g)=>m+Number(g.data.total_bought_volume_usd||0),0),p=l.reduce((m,g)=>m+Number(g.data.total_sold_volume_usd||0),0),h=l.reduce((m,g)=>m+Number(g.data.total_trade_volume||0),0),f={totalCountOfTrades:l.reduce((m,g)=>m+g.data.total_count_of_trades,0),totalTradeVolume:h,totalRealizedProfitUsd:u,totalRealizedProfitPercentage:d>0?u/d*100:0,totalBuys:l.reduce((m,g)=>m+g.data.total_buys,0),totalSells:l.reduce((m,g)=>m+g.data.total_sells,0),totalBoughtVolumeUsd:d,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:a??"all",summary: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 Hl=["all","7","30","60","90"],Uo=25,Kt=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 ${Uo}. 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 ${Uo}.`,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 ${Uo}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new D(e)}async run(e,t){let n=j(e.address,t),r=Z(e.chain,t),o=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=Hl.includes(o)?o:void 0,i=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[],l=Array.isArray(e.tokenAddresses)?e.tokenAddresses.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[];if(r){let d=await this.fetchChainPnl(n,r,a,i,l);return d.ok?{walletAddress:n,chain:r,days:a??"all",filters:{tokenAddresses:d.tokenAddresses??null,resolvedSymbols:d.resolvedFromSymbols.length>0?d.resolvedFromSymbols:null,unresolvedSymbols:d.unresolvedSymbols.length>0?d.unresolvedSymbols:null},tokenCount:d.tokens.length,tokens:d.tokens}:{error:d.error||"Failed to fetch wallet PnL"}}let u=(await Promise.all(ve().map(async d=>({chain:d,res:await this.fetchChainPnl(n,d,a,i,l)})))).filter(d=>d.res.ok&&d.res.tokens.length>0).map(d=>({chain:v(d.chain),tokenCount:d.res.tokens.length,tokens:d.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:a??"all",filters:{requestedSymbols:i.length>0?i:null,requestedAddresses:l.length>0?l:null},tokenCount:u.reduce((d,p)=>d+p.tokenCount,0),chains:u}}async fetchChainPnl(e,t,n,r,o){let a=[],i=[];r.length>0&&(await Promise.all(r.map(p=>this.resolveContractAddress(p,t,e)))).forEach((p,h)=>{p?a.push({symbol:r[h],address:p.address}):i.push(r[h])});let l=Vl([...a.map(d=>d.address),...o]).slice(0,Uo),c=l.length>0?l:void 0,u=await this.service.getWalletPnl({address:e,chain:t,days:n,tokenAddresses:c});return{ok:u.success,error:u.error,tokens:u.data?.result??[],tokenAddresses:c,resolvedFromSymbols:a,unresolvedSymbols:i}}async resolveContractAddress(e,t,n){let r=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===r);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let o=await this.service.searchTokensByKey({key:e,chain:t});if(o.success&&o.data?.length){let i=o.data.find(l=>(l.symbol??"").toLowerCase()===r)??o.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};function Vl(s){let e=new Set,t=[];for(let n of s){let r=n.toLowerCase();e.has(r)||(e.add(r),t.push(n))}return t}var Wl=BigInt(2)**BigInt(255),jt=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 D(e)}async run(e,t){let n=j(e.address,t),r=oe(e.chain,t),o=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(o)&&o>0?Math.min(100,Math.floor(o)):100,i=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,l=await this.service.getWalletApprovals({address:n,chain:r,limit:a,cursor:i});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,d=(c.result||[]).map(m=>Yl(m)),p=0,h=0,f=[];for(let m of d){m.isUnlimited&&(h+=1);let g=parseFloat(m.token.usdAtRisk??"");Number.isFinite(g)&&(p+=g);let y=m.token.possibleSpam||m.token.verifiedContract===!1,b=!m.spender.label&&!m.spender.entity;(y||m.isUnlimited&&b)&&f.push(m)}return{walletAddress:n,chain:r||"default",filters:{limit:a,cursor:i??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??a,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:d.length,unlimitedApprovals:h,totalUsdAtRisk:p,riskyApprovalCount:f.length},approvals:d,riskyApprovals:f}}};function Yl(s){let e=Gl(s.value);return{blockNumber:s.block_number,blockTimestamp:s.block_timestamp??null,transactionHash:s.transaction_hash??null,value:s.value,valueFormatted:s.value_formatted??null,isUnlimited:e,token:{address:s.token.address,addressLabel:s.token.address_label??null,name:s.token.name??null,symbol:s.token.symbol??null,logo:s.token.logo??null,possibleSpam:!!s.token.possible_spam,verifiedContract:s.token.verified_contract??null,currentBalance:s.token.current_balance??null,currentBalanceFormatted:s.token.current_balance_formatted??null,usdPrice:s.token.usd_price??null,usdAtRisk:s.token.usd_at_risk??null},spender:{address:s.spender.address,label:s.spender.address_label??null,entity:s.spender.entity??null,entityLogo:s.spender.entity_logo??null}}}function Gl(s){if(!s)return!1;try{return BigInt(s)>=Wl}catch{return!1}}var zt=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 D(e)}async run(e,t){let n=j(e.address,t),r=Z(e.chain,t);if(r){let i=await this.service.getWalletDefiPositions({address:n,chain:r});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=i.data||[];return{walletAddress:n,chain:r,positionCount:l.length,positions:l.map(Qs)}}let a=(await Promise.all(ve().map(async i=>{let l=await this.service.getWalletDefiPositions({address:n,chain:i});return{chain:i,rows:l.success?l.data||[]:[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:v(i.chain),positionCount:i.rows.length,positions:i.rows.map(Qs)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:n,chain:"all",positionCount:a.reduce((i,l)=>i+l.positionCount,0),chains:a}}};function Qs(s){return{protocolName:s.protocol_name,protocolId:s.protocol_id,protocolUrl:s.protocol_url,protocolLogo:s.protocol_logo,accountHealthFactor:s.account_data?.health_factor??null,position:Kl(s.position)}}function Kl(s){return{label:s.label,address:s.address,balanceUsd:s.balance_usd,totalUnclaimedUsdValue:s.total_unclaimed_usd_value,tokens:(s.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:s.position_details??null}}var Xt=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 D(e)}async run(e,t){let n=e.protocol?.trim();if(!n)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let r=j(e.address,t),o=Z(e.chain,t);if(o){let l=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:o});return l.success?l.data?{walletAddress:r,chain:o,...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(ve().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:r,protocol:n,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:v(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${n} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:r,chain:"all",protocol:n,totalUsdValue:i.reduce((l,c)=>l+c.totalUsdValue,0),chains:i}}protocolFields(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,accountHealthFactor:e.account_data?.health_factor??null,positionCount:(e.positions||[]).length,positions:(e.positions||[]).map(jl)}}};function jl(s){return{label:s.label,address:s.address,balanceUsd:s.balance_usd,totalUnclaimedUsdValue:s.total_unclaimed_usd_value,tokens:(s.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:s.position_details??null}}function zl(s){try{return(Number(BigInt(s))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return s}}var Qt=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 D(e)}async run(e,t){let n=e.transactionHash;if(!n)return{error:"Transaction hash is required."};let r=oe(e.chain,t),o=await this.service.getTransactionByHash({transactionHash:n,chain:r});if(!o.success||!o.data)return{error:o.error||"Failed to fetch transaction"};let a=o.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:zl(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 Fr=7,ea=K("totalSupply()"),Xl=K("totalAssets()"),Ql=K("getReserveData(address)"),ta=K("balanceOf(address)"),qr=K("decimals()"),na=K("symbol()"),Br=K("convertToAssets(uint256)"),Js=2,Jl=1e27,Zl=10,ec=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!) {
|
|
17
17
|
value: supplyAPYHistory(request: $request) { date avgRate { value } }
|
|
18
18
|
}`,tc=`query VaultV2ByAddress($address: String!, $chainId: Int!, $options: TimeseriesOptions) {
|
|
19
19
|
vaultV2ByAddress(address: $address, chainId: $chainId) {
|
|
20
20
|
netApyExcludingRewards
|
|
21
21
|
historicalState { avgNetApy(options: $options) { x y } }
|
|
22
22
|
}
|
|
23
|
-
}`,no=class{liveRateCall(e,t){return null}decodeSize(e,t){let n=wt(e);return n===null?null:nt(n,t.usdcDecimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,t){return this.balanceIsUnderlying?null:{target:e.contract,callData:Br+ae(t)}}},oo=class extends no{type="spark";balanceIsUnderlying=!1;sizeCall(e){return{target:e.contract,callData:Xl}}fetchApy(e,t,n){return oa(e,t,n)}},Ir=class extends oo{type="spark"},Lr=class extends oo{type="spark-ethereum"},Dr=class extends no{type="aave-v3";balanceIsUnderlying=!0;sizeCall(e){return{target:e.token,callData:ea}}liveRateCall(e,t){return{target:e.contract,callData:Ql+ze(t.usdc)}}decodeLiveRate(e){if(!e)return null;let t=G(e);if(t.length<(Js+1)*64)return null;let n=Number(Oe(t,Js*64))/Jl;return Number.isFinite(n)&&n>=0&&n<=Zl?n:null}async fetchApy(e,t,n){let r=await x.post(n.aaveApiUrl,{operationName:"SupplyAPYHistory",query:ec,variables:{request:{chainId:t.chainId,market:e.contract,underlyingToken:t.usdc,window:"LAST_WEEK"}}});if(!r.ok)throw new Error(R(r));return{samples:(r.data?.data?.value||[]).map(o=>({timeMs:Date.parse(o?.date??""),fraction:Number(o?.avgRate?.value)})),current:null}}},Or=class extends no{type="compound-v3";balanceIsUnderlying=!0;sizeCall(e){return{target:e.token,callData:ea}}fetchApy(e,t,n){return oa(e,t,n)}},Mr=class extends oo{type="morpho-v2";async fetchApy(e,t,n){let r=oc(Date.now()),o=await x.post(n.morphoApiUrl,{operationName:"VaultV2ByAddress",query:tc,variables:{address:e.contract,chainId:t.chainId,options:{startTimestamp:Math.floor(r/1e3)-(Fr-1)*86400,endTimestamp:Math.floor(r/1e3)-86400}}});if(!o.ok)throw new Error(R(o));let a=o.data?.data?.vaultV2ByAddress,i=Number(a?.netApyExcludingRewards);return{samples:(a?.historicalState?.avgNetApy||[]).map(l=>({timeMs:Number(l?.x)*1e3,fraction:Number(l?.y)})),current:Number.isFinite(i)?i:null}}};async function oa(s,e,t){let n=`${t.coinPoolBaseUrl}/supply/rates/history?chainId=${e.chainId}&token=${s.token}`,r=await x.get(n);if(!r.ok)throw new Error(R(r));return{samples:(r.data?.data||[]).map(o=>({timeMs:Date.parse(o?.date??""),fraction:Number(o?.rate)})),current:null}}var ra={"aave-v3":new Dr,"compound-v3":new Or,spark:new Ir,"spark-ethereum":new Lr,"morpho-v2":new Mr},nc=ra.spark;function bt(s){return ra[s.type]??nc}function wt(s){if(!s)return null;let e=G(s);if(e.length<64)return null;try{return Oe(e,0)}catch{return null}}function sa(s){if(!s)return null;let e=G(s);if(e.length<64)return null;try{if(e.length>=128){let t=Number(Oe(e,0)),n=t*2;if(Number.isFinite(t)&&t>0&&e.length>=n+64){let r=Number(Oe(e,n)),o=n+64;return r>0&&e.length>=o+r*2?Zs(e.slice(o,o+r*2)):null}return null}return Zs(e.slice(0,64))||null}catch{return null}}function Zs(s){let e=s.match(/.{2}/g)??[];return Buffer.from(e.join(""),"hex").toString("utf8").replace(/[^\x20-\x7e]/g,"").trim()}function nt(s,e){return Number(s)/10**e}function ro(s){return new Date(s).toISOString().slice(0,10)}function oc(s){return Date.parse(`${ro(s)}T00:00:00.000Z`)}var kt={"0x1":{chainId:1,usdc:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",usdcDecimals:6},"0xa":{chainId:10,usdc:"0x0b2c639c533813f4aa9d7837caf62653d097ff85",usdcDecimals:6},"0x38":{chainId:56,usdc:"0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d",usdcDecimals:18},"0x2105":{chainId:8453,usdc:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",usdcDecimals:6},"0xa4b1":{chainId:42161,usdc:"0xaf88d065e77c8cc2239327c5edb3a432268e5831",usdcDecimals:6}},rc=.01,sc=8,Ye=class{coinPoolBaseUrl;apiEndpoints;apyLimiter=new $r(sc);constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app",this.apiEndpoints={coinPoolBaseUrl:this.coinPoolBaseUrl,aaveApiUrl:e.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:e.morphoApiUrl||"https://api.morpho.org/graphql"}}listSupportedChains(){return Object.keys(kt).filter(e=>M(e)===e)}isSupported(e){let t=M(e);return!!(t&&kt[t])}async getMarkets(e){let t=M(e),n=t?kt[t]:void 0;if(!t||!n)return[];try{let r=`${this.coinPoolBaseUrl}/supply/v2?chainId=${n.chainId}&limit=100&page=1`,o=await x.get(r);if(!o.ok)throw new Error(R(o));return(o.data?.data?.items||[]).flatMap(a=>{let i=ac(a,t);return i?[i]:[]})}catch{return[]}}getUsdc(e){let t=M(e),n=t?kt[t]:void 0;return n?{address:n.usdc,decimals:n.usdcDecimals}:null}async readReceiptToken(e,t){let n=bt(t).balanceIsUnderlying;try{let r=await gt(e,[{target:t.token,callData:na},{target:t.token,callData:qr}]);return{symbol:sa(r[0]),decimals:ia(r[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}async findMarket(e,t){let n=t.trim().toLowerCase();if(!n)return[];let r=await this.getMarkets(e);if(F(n))return r.filter(a=>a.contract===n||a.token===n);let o=r.filter(a=>a.name.trim().toLowerCase()===n);return o.length>0?o:r.filter(a=>{let i=a.name.trim().toLowerCase(),l=a.protocol.trim().toLowerCase();return i.includes(n)||n.includes(i)||l.includes(n)||n.includes(l)})}async describeResolvedMarkets(e,t){let n=M(e);return n?this.describeMarkets(n,t):[]}async getMarketOverviews(e){return(await Promise.all(aa(e.chains).map(async n=>this.describeMarkets(n,await this.getMarkets(n))))).flat().sort((n,r)=>(r.avgApyPercent??-1)-(n.avgApyPercent??-1))}async getSupplyPositions(e){return F(e.address)?(await Promise.all(aa(e.chains).map(n=>this.positionsForChain(n,e.address)))).flat().sort((n,r)=>r.suppliedUsdc-n.suppliedUsdc||(r.avgApyPercent??0)-(n.avgApyPercent??0)):[]}async positionsForChain(e,t){let n=kt[e],r=await this.getMarkets(e);if(!n||r.length===0)return[];let o=await this.readBalances(e,t,r);if(o.length===0)return[];let[a,i]=await Promise.all([this.describeMarkets(e,o.map(l=>l.market)),this.convertToUnderlying(e,n,o)]);return a.flatMap((l,c)=>{let u=i[c];return u<rc?[]:[{...l,suppliedUsdc:Tt(u,6),estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:Tt(u*l.avgApyPercent/100,2)}]})}async describeMarkets(e,t){let n=kt[e];if(!n||t.length===0)return[];let[r,o]=await Promise.all([this.readMarketState(e,n,t),Promise.all(t.map(a=>this.apyLimiter.run(()=>this.fetchApySamples(a,n))))]);return t.map((a,i)=>{let{totalSuppliedUsdc:l,liveApyFraction:c}=r[i],u=ic(o[i].samples,c??o[i].current);return{...a,totalSuppliedUsdc:l===null?null:Tt(l,2),avgApyPercent:u.avgApyPercent,currentApyPercent:u.currentApyPercent,apyChangePercent:u.apyChangePercent,apyHistory:u.history}})}async readBalances(e,t,n){let r=ze(t),o=n.flatMap(i=>[{target:i.token,callData:ta+r},{target:i.token,callData:qr}]),a=await gt(e,o);return n.flatMap((i,l)=>{let c=wt(a[l*2]);return c===null||c<=0n?[]:[{market:i,rawBalance:c,tokenDecimals:ia(a[l*2+1])}]})}async readMarketState(e,t,n){let r=[],o=n.map(i=>{let l=bt(i),c={protocol:l,size:r.length,rate:-1};r.push(l.sizeCall(i,t));let u=l.liveRateCall(i,t);return u&&(c.rate=r.length,r.push(u)),c}),a=await gt(e,r);return o.map(i=>({totalSuppliedUsdc:i.protocol.decodeSize(a[i.size],t),liveApyFraction:i.rate<0?null:i.protocol.decodeLiveRate(a[i.rate])}))}async convertToUnderlying(e,t,n){let r=[],o=n.map(i=>{let l=bt(i.market).convertToAssetsCall(i.market,i.rawBalance);return l?(r.push(l),r.length-1):-1}),a=await gt(e,r);return n.map((i,l)=>{if(o[l]<0)return nt(i.rawBalance,t.usdcDecimals);let c=wt(a[o[l]]);return c===null?nt(i.rawBalance,i.tokenDecimals??t.usdcDecimals):nt(c,t.usdcDecimals)})}async fetchApySamples(e,t){try{return await bt(e).fetchApy(e,t,this.apiEndpoints)}catch{return{samples:[],current:null}}}},$r=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 aa(s){let e=s.map(t=>M(t)).filter(t=>!!t);return[...new Set(e)].filter(t=>!!kt[t])}function ac(s,e){if(s?.isDeleted===!0)return null;let t=typeof s?.contract=="string"?s.contract.toLowerCase():"";if(!F(t))return null;let n=typeof s?.token=="string"&&F(s.token)?s.token.toLowerCase():t,r=Number(s?.rating?.balanceScore);return{chain:e,name:s?.name?.trim()||"USDC lending market",protocol:s?.protocolId?.name?.trim()||"Unknown",protocolUrl:s?.protocolId?.domain?.trim()||null,type:s?.type?.trim()||"unknown",contract:t,token:n,platformScore:Number.isFinite(r)?r:null}}function ic(s,e){let t=ro(Date.now()),n=new Map,r=null;for(let u of s){if(!Number.isFinite(u.timeMs)||!Number.isFinite(u.fraction)||u.fraction<0||((!r||u.timeMs>r.timeMs)&&(r=u),!lc(u.timeMs)))continue;let d=ro(u.timeMs);d>=t||n.set(d,u.fraction)}let o=[...n.entries()].sort((u,d)=>u[0]<d[0]?-1:1).slice(-Fr).map(([u,d])=>({date:u,apyPercent:Tt(d*100,2)})),a=e??(r&&ro(r.timeMs)===t?r.fraction:null),i=a===null?null:Tt(a*100,2);if(i!==null&&o.push({date:t,apyPercent:i}),o.length===0)return{history:o,avgApyPercent:null,currentApyPercent:null,apyChangePercent:null};let l=o.reduce((u,d)=>u+d.apyPercent,0),c=o[o.length-1].apyPercent;return{history:o,avgApyPercent:Tt(l/o.length,2),currentApyPercent:i,apyChangePercent:o.length>=2?Tt(c-o[o.length-2].apyPercent,2):null}}function ia(s){let e=wt(s);if(e===null)return null;let t=Number(e);return Number.isFinite(t)&&t>=0&&t<=36?t:null}function Tt(s,e){let t=10**e;return Math.round(s*t)/t}function lc(s){let e=new Date(s);return e.getUTCHours()===0&&e.getUTCMinutes()===0&&e.getUTCSeconds()===0}var so="{market}",ca="{chain}";var ua=[{name:"supply_button_label",type:"string",description:`Label template for the per-market "Supply" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Use the exact placeholder "{market}" (do not translate the braces); it is replaced per market with its name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply USDC" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use BOTH exact placeholders (do not translate the braces): "{market}" is replaced with the market name, "{chain}" with the chain name it lives on. Write the connecting words around {chain} in the user's language \u2014 that is why it is a placeholder and not appended for you. English example: "supply USDC to {market} on {chain}". Vietnamese example: "n\u1EA1p USDC v\xE0o {market} tr\xEAn {chain}". Always include BOTH {market} and {chain}. Do NOT write a chain name or a contract address literally \u2014 the exact market identifier is appended automatically.`,required:!1}],da=' A clickable "Supply" button is shown below your reply for each market automatically \u2014 do NOT list, number, or repeat those buttons in your text, and do NOT tell the user to tap one; just deliver the list and your suggestion.';function pa(s,e,t){return cc(s,typeof e.supply_button_label=="string"?e.supply_button_label:"",typeof e.supply_prompt_template=="string"?e.supply_prompt_template:"",t)}function cc(s,e,t,n){let r=typeof n=="string"?n.trim():"",o=[],a=new Set;for(let i of s){if(o.length>=10)break;let l=i.name?.trim();!l||a.has(l.toLowerCase())||(a.add(l.toLowerCase()),o.push({label:la(e,l,"",`Supply ${so}`),prompt:la(t,l,r,uc(r))+dc(i.contract)}))}return o}function uc(s){return s?`supply USDC to ${so} on ${ca}`:`supply USDC to ${so}`}function dc(s){let e=s?.trim();return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?` (market: ${e})`:""}function la(s,e,t,n){return(s&&s.includes(so)?s:n).split(so).join(e).split(ca).join(t).replace(/\s+/g," ").trim()}var pc={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},mc={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",130:"proto_unichain_v3",137:"proto_polygon_v3",5e3:"proto_mantle_v3",8453:"proto_base_v3",9745:"proto_plasma_v3",42161:"proto_arbitrum_v3",57073:"proto_ink_v3"},hc={1:"mainnet",10:"optimism",56:"bnb",130:"unichain",8453:"base",42161:"arbitrum",43114:"avalanche"},gc={1:"usdc-mainnet",10:"usdc-op",56:"usdc-bnb",130:"usdc-unichain",137:"usdc-polygon",8453:"usdc-basemainnet",42161:"usdc-arb"},fc={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",10:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",56:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",130:"0x078D782b760474a361dDA0AF3839290b0EF57AD6",137:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"};function Zt(s){let e=kc(s.chain);return(e===null?null:yc(s,e))??wc(s,e)}function yc(s,e){switch(s.type){case"morpho-v2":{let t=pc[e];return!t||!s.contract?null:`https://app.morpho.org/${t}/vault/${Hr(s.contract)}`}case"aave-v3":{let t=mc[e],n=fc[e];return!t||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${Hr(n)}&marketName=${t}`}case"spark":case"spark-ethereum":{let t=hc[e];return t?`https://app.spark.fi/savings/${t}/${bc(s,e)}`:null}case"compound-v3":{let t=gc[e];return t?`https://app.compound.finance/?market=${t}`:null}default:return null}}function bc(s,e){let t=`${s.name||""} ${s.token||""}`.toLowerCase();return t.includes("spusdc")?"spusdc":t.includes("susds")?"susds":t.includes("susdc")?"susdc":e===1?"spusdc":"susdc"}function wc(s,e){let t=s.protocolUrl?.trim();if(!t)return null;let n=/^https?:\/\//i.test(t)?t:`https://${t.replace(/^\/+/,"")}`;try{let r=new URL(n);return e!==null&&r.searchParams.set("chainId",String(e)),s.contract&&r.searchParams.set("contract",Hr(s.contract)),r.toString()}catch{return n}}function Hr(s){let e=s.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function kc(s){let e=s?.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 Io=[{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"]}],Wr=Io.map(s=>s.label),Vr={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 ma(s){let e=typeof s=="string"?s.trim():"";if(!e)return{kind:"none"};let t=Sc(e);if(!t)return{kind:"none"};let n=Tc(t);if(n){let o=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>o.has(a.type)}}let r=Ac(t);return r?{kind:"unsupported",label:r,requested:e}:{kind:"unknown",requested:e}}function Tc(s){let e=Io.filter(t=>t.aliases.includes(s));if(e.length===1)return e[0];if(e.length>1)return null;if(s.length>=3){let t=Io.filter(n=>n.aliases.some(r=>r.includes(s)||s.includes(r)));if(t.length===1)return t[0];if(t.length>1)return null}return vc(s)}function vc(s){let e=null,t=!1;for(let n of Io)for(let r of n.aliases){let o=ha(r);if(o===0||Math.abs(r.length-s.length)>o)continue;let a=ga(s,r,o);a>o||(!e||a<e.distance?(e={spec:n,distance:a},t=!1):a===e.distance&&n!==e.spec&&(t=!0))}return e&&!t?e.spec:null}function ha(s){return s.length<=4?0:s.length<=9?2:3}function Ac(s){let e=Vr[s];if(e)return e;if(s.length>=4){let r=new Set(Object.entries(Vr).filter(([o])=>o.length>=4&&(o.includes(s)||s.includes(o))).map(([,o])=>o));if(r.size===1)return[...r][0];if(r.size>1)return null}let t=null,n=!1;for(let[r,o]of Object.entries(Vr)){let a=ha(r);if(a===0||Math.abs(r.length-s.length)>a)continue;let i=ga(s,r,a);i>a||(!t||i<t.distance?(t={label:o,distance:i},n=!1):i===t.distance&&o!==t.label&&(n=!0))}return t&&!n?t.label:null}function Sc(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function ga(s,e,t){if(s===e)return 0;if(!s.length)return e.length;if(!e.length)return s.length;let n=new Array(e.length+1),r=Array.from({length:e.length+1},(a,i)=>i),o=new Array(e.length+1);for(let a=1;a<=s.length;a++){o[0]=a;let i=o[0];for(let c=1;c<=e.length;c++){let u=r[c-1]+(s[a-1]===e[c-1]?0:1),d=Math.min(o[c-1]+1,r[c]+1,u);a>1&&c>1&&s[a-1]===e[c-2]&&s[a-2]===e[c-1]&&(d=Math.min(d,n[c-2]+1)),o[c]=d,d<i&&(i=d)}if(i>t)return t+1;let l=n;n=r,r=o,o=l}return r[e.length]}var xc=["apy","score","size"],fa=5,ya=40,en=class extends A{name="get-lending-markets";description='List the USDC LENDING / SUPPLY markets available to deposit into and earn yield on: protocol (Aave v3, Compound v3, Spark, Morpho vaults), market name, chain, total USDC supplied to that market, the live supply APY plus the average over the last week and its daily change, and a 0\u201310 platform score. Ranked by the live protocol APY by default, and filterable to ONE protocol via `protocol`. Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. Supports: Ethereum, Optimism, BSC, Base, Arbitrum. Do NOT use for: 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 of a chain with USDC lending markets: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x2105" Base, "0xa4b1" Arbitrum. 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: ${Wr.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-${ya}. Default ${fa} \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},...ua];service;constructor(e){super(),this.service=new Ye(e)}async run(e,t){let n=this.service.listSupportedChains(),r=Z(e.chain,void 0),o=r?null:M(t?.chain),a=r??o;if(a&&!n.includes(a))return{_instructions:`There are no USDC lending markets on ${v(a)}`+(o?", the chain the wallet is currently connected to":"")+". Tell the user that in their language and name the chains that DO have them (in `chainsWithLendingMarkets`), offering to list those instead. Do NOT mention tool names.",chain:v(a),connectedChainHasNoMarkets:o!==null,marketCount:0,markets:[],chainsWithLendingMarkets:n.map(m=>v(m))};let i=ma(e.protocol);if(i.kind==="unsupported"||i.kind==="unknown")return this.unsupportedProtocol(i);let l=a?[a]:n,c=_c(e.sort),u=Ec(e.limit),d=await this.service.getMarketOverviews({chains:l}),p=i.kind==="supported"?d.filter(m=>i.matches(m)):d;if(i.kind==="supported"&&p.length===0&&d.length>0)return{_instructions:`There are no ${i.label} USDC lending markets on ${a?v(a):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${i.label} market. Do NOT mention tool names.`,requestedProtocol:i.label,chain:a?v(a):"all",marketCount:0,markets:[],protocolsAvailable:[...new Set(d.map(m=>m.protocol))]};let h=[...p].sort(Cc[c]).slice(0,u),f=h.slice(0,10).flatMap(m=>pa([{name:m.name,contract:m.contract}],e,v(m.chain)));return{_instructions:this.instructions(h,c,f.length>0,i.kind==="supported"?i.label:null),...f.length>0?{actionButtons:f}:{},chain:a?v(a):"all",chainsQueried:l.map(m=>v(m)),...i.kind==="supported"?{protocolFilter:i.label}:{},sortedBy:c,marketCount:h.length,totalMarketsAvailable:p.length,markets:h.map(m=>({marketName:m.name,protocol:m.protocol,protocolUrl:Zt(m),chain:v(m.chain),avgApyPercent:m.avgApyPercent,avgApyDays:m.apyHistory.length,currentApyPercent:m.currentApyPercent,apyChangePercent:m.apyChangePercent,totalSuppliedUsdc:m.totalSuppliedUsdc,platformScore:m.platformScore}))}}unsupportedProtocol(e){let t=e.kind==="unsupported",n=t?e.label:`"${e.requested}"`;return{_instructions:`The user asked about ${n}, which has no USDC lending markets here. In their language: tell them plainly that ${n} is ${t?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${n} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:t?e.label:e.requested,protocolSupported:!1,supportedProtocols:[...Wr],marketCount:0,markets:[]}}instructions(e,t,n=!1,r=null){if(e.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let o={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[t];return[r?`These are the ${r} USDC lending markets the user can supply to, ${o}. The list is SCOPED to ${r} because that is what they asked about \u2014 present it as such, and do not imply it is every lending market available.`:`These are USDC lending markets the user can supply to, ${o}.`,"Present them as a NUMBERED list. Each entry starts with `marketName` as a markdown link to that","market's `protocolUrl` in bold \u2014 **[marketName](protocolUrl)** \u2014 so the name opens that market's page on","the protocol.","When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it.",'Under each name put exactly three bullet points, in this order: "Total supplied" = `totalSuppliedUsdc`,','"Protocol APY" = `currentApyPercent` (the live rate), and "Avg APY" = `avgApyPercent` labelled as the',"average over the last `avgApyDays` days. Do NOT add other bullets.","Amounts are USDC, so format them as US dollars, compactly ($100.12M, $23.45M).","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage \u2014 mention it only when the user","asks which market is safest. A null APY means that rate was unavailable \u2014 say so rather than showing 0.",new Set(e.map(a=>a.chain)).size>1?"The markets span several chains \u2014 put each one's `chain` on the title line, after the linked name, so the user knows where it lives.":"All markets are on one chain \u2014 state the chain name once before the list, not per market.","Close with one short sentence naming the best option for the ranking used and why.","This is information, NOT financial advice \u2014 say so briefly.","Do NOT mention tool names.",n?da:""].filter(Boolean).join(" ")}},Cc={apy:(s,e)=>(e.currentApyPercent??-1)-(s.currentApyPercent??-1),score:(s,e)=>(e.platformScore??-1)-(s.platformScore??-1),size:(s,e)=>(e.totalSuppliedUsdc??-1)-(s.totalSuppliedUsdc??-1)};function _c(s){let e=typeof s=="string"?s.trim().toLowerCase():"";return xc.includes(e)?e:"apy"}function Ec(s){let e=typeof s=="number"?s:Number(s);return!Number.isFinite(e)||e<1?fa:Math.min(Math.floor(e),ya)}var tn=class extends A{name="get-wallet-lending-positions";description=`Get a wallet's own LENDING / SUPPLY (earn, deposit, savings) positions in USDC lending markets: which protocol and market the wallet supplies to (Aave v3, Compound v3, Spark, Morpho vaults), how much USDC 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. Covers USDC only, on Aave v3, Compound v3, Spark and Morpho vaults, on Ethereum, Optimism, BSC, Base, Arbitrum. For supplied assets OTHER than USDC (DAI, USDT, ETH\u2026), for protocols outside that list (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 of a chain with USDC lending markets: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x2105" Base, "0xa4b1" Arbitrum. 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 Ye(e)}async run(e,t){let n=j(e.address,t);if(!F(n))return{error:`"${n}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let r=Z(e.chain,t),o=this.service.listSupportedChains();if(r&&!o.includes(r))return{_instructions:`There are no USDC lending markets on ${v(r)}, so the wallet cannot have a supply position there. Tell the user that in their language and name the chains that DO have lending markets (listed in \`chainsWithLendingMarkets\`). Do NOT mention tool names.`,walletAddress:n,chain:v(r),positionCount:0,positions:[],chainsWithLendingMarkets:o.map(l=>v(l))};let a=r?[r]:o,i=await this.service.getSupplyPositions({address:n,chains:a});return{_instructions:this.instructions(i),walletAddress:n,chain:r?v(r):"all",chainsQueried:a.map(l=>v(l)),positionCount:i.length,totals:Nc(i),positions:i.map(l=>({marketName:l.name,protocol:l.protocol,protocolUrl:Zt(l),chain:v(l.chain),suppliedUsdc:l.suppliedUsdc,avgApyPercent:l.avgApyPercent,currentApyPercent:l.currentApyPercent,apyChangePercent:l.apyChangePercent,estimatedAnnualYieldUsdc:l.estimatedAnnualYieldUsdc,marketTotalSuppliedUsdc:l.totalSuppliedUsdc,apyHistory:l.apyHistory,platformScore:l.platformScore}))}}instructions(e){return e.length===0?"The wallet supplies USDC 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 check covers USDC only, so if the user believes they have a deposit it may be in another asset; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the daily samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","All amounts are USDC, so format them as US dollars, compactly ($1.23M, $45.6K, $12.34).","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(e.map(n=>n.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals`. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function Nc(s){let e=s.reduce((r,o)=>r+o.suppliedUsdc,0),t=s.filter(r=>r.avgApyPercent!==null),n=t.reduce((r,o)=>r+o.suppliedUsdc,0);return{suppliedUsdc:Yr(e,6),estimatedAnnualYieldUsdc:Yr(s.reduce((r,o)=>r+(o.estimatedAnnualYieldUsdc??0),0),2),weightedAvgApyPercent:n>0?Yr(t.reduce((r,o)=>r+o.suppliedUsdc*o.avgApyPercent,0)/n,2):null}}function Yr(s,e){let t=10**e;return Math.round(s*t)/t}var Rc=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"],Uc=s=>Rc.includes(s),nn=class extends A{name="open-supply-usdc-form";kind="ui";category="lending-action";description='Open the SUPPLY USDC form so the user can DEPOSIT USDC 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. USDC is the only asset this deposits, so a message that names no asset is still this tool \u2014 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 Ethereum, Optimism, BSC, Base and Arbitrum. 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)" hint, pass THAT address verbatim as this argument and ignore the market name in the sentence \u2014 the address identifies the exact market they picked, while a name may match several vaults of the same protocol.`,required:!0},{name:"chain",type:"string",description:`Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x2105" Base, "0xa4b1" Arbitrum. Set it ONLY when the user names a chain; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:'USDC amount to pre-fill, 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 Ye(e),this.moralis=new D(e?.moralis)}async run(e,t){let n=t?.walletAddress;if(!n)return{error:"wallet_not_connected",_instructions:"Supplying moves real funds, so it needs a connected wallet. Ask the user to connect one, in their language. Do NOT render a form and do NOT mention tool names."};let o=Z(e.chain,void 0)??M(t?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for the supply. Ask the user which chain they want to supply on, naming the supported ones. Do NOT mention tool names."};let a=this.service.listSupportedChains();if(!a.includes(o))return{error:"unsupported_chain",chain:v(o),chainsWithLendingMarkets:a.map(b=>v(b)),_instructions:`There are no USDC lending markets on ${v(o)}, 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 i=Ic(e.market);if(!i)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let l=await this.service.findMarket(o,i);if(l.length===0)return{error:"market_not_found",market:i,chain:v(o),_instructions:`No USDC lending market matching "${i}" exists on ${v(o)}. Tell the user in their language and offer to list the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(l.length>1)return{error:"ambiguous_market",market:i,chain:v(o),candidates:l.map(b=>({marketName:b.name,protocol:b.protocol})),_instructions:`"${i}" matches ${l.length} different markets on ${v(o)}, 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="`+i+`" and chain for ${v(o)}, plus the localized supply-button templates \u2014 that shows the user each market with its APY, size and score, each with its own Supply button to tap. Write no message of your own before that call.`};let c=l[0];if(!Uc(c.type))return{error:"unsupported_protocol",marketName:c.name,protocol:c.protocol,_instructions:`Supplying to ${c.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let u=this.service.getUsdc(o);if(!u)return{error:"unsupported_chain",chain:v(o),_instructions:`No USDC is configured for ${v(o)}. Tell the user supplying is unavailable there.`};let[d,p,h]=await Promise.all([this.describeOne(o,c),this.usdcBalance(n,o,u.address),this.service.readReceiptToken(o,c)]);if(p&&ft(p.amount,"0")<=0)return{error:"no_usdc_balance",marketName:c.name,chain:v(o),usdcBalance:"0",_instructions:`The user has no USDC available to supply to ${c.name} on ${v(o)}. In the user's language, tell them plainly that they have no USDC 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 f=Lc(e.amount),m=f?Qe(f,u.decimals):null;if(m&&p&&ft(m,p.amount)>0)return{error:"insufficient_usdc_balance",marketName:c.name,chain:v(o),requestedAmount:f,usdcBalance:p.amount,_instructions:`The user wants to supply ${f} USDC to ${c.name}, but they only hold ${p.amount} USDC on ${v(o)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${f} USDC exceeds their balance of ${p.amount} USDC on this chain, then ask them to enter a smaller amount or add more USDC. 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 g={action:"supply_usdc",chainId:o,chainName:v(o),walletAddress:n,market:{name:c.name,type:c.type,protocol:c.protocol,protocolUrl:Zt(c),contract:c.contract,token:c.token,apyPercent:d?.currentApyPercent??d?.avgApyPercent??null,receiptToken:h},asset:{address:u.address,symbol:"USDC",decimals:u.decimals},...m?{prefillAmount:m}:{},...p?{spendable:p.amount}:{},...p?.usd?{spendableUsd:p.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:g},marketName:c.name,protocol:c.protocol,chain:v(o),apyPercent:g.market.apyPercent,usdcBalance:p?.amount??null,_instructions:this.instructions(c)}}async describeOne(e,t){try{let[n]=await this.service.describeResolvedMarkets(e,[t]);return n??null}catch{return null}}async usdcBalance(e,t,n){try{let r=await this.moralis.getWalletTokenBalances({address:e,chain:t,tokenAddresses:[n]});if(!r.success)return null;let o=(r.data?.result??[]).find(i=>(i.token_address||"").toLowerCase()===n.toLowerCase());if(!o?.balance_formatted)return{amount:"0",usd:null};let a=typeof o.usd_value=="number"?String(o.usd_value):null;return{amount:String(o.balance_formatted),usd:a}}catch{return null}}instructions(e){return[`The supply action for ${e.name} is ready.`,"In the user's language, invite them to enter the amount of USDC they want to supply, naming the market and","the chain.",'Speak ONLY of the action the USER takes (supplying / depositing USDC). 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 Ic(s){let e=typeof s=="string"?s.trim():"",t=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})\s*[\])]/i.exec(e);if(t)return t[1];let n=/0x[a-fA-F0-9]{40}/.exec(e);return n&&n[0]!==e?n[0]:e}function Lc(s){let e=typeof s=="string"?s.trim():typeof s=="number"?String(s):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}var Lo="https://ipfs.pantograph.app/ipfs/",ba=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function vt(s){let e=s?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${Lo}${t[1]}`:ba.test(e)?`${Lo}${e}`:null}function wa(s){let e=s?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${Lo}${t[1]}`:ba.test(e)?`${Lo}${e}`:null}function ka(s){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(s)}function Gr(s){if(!s||typeof s!="object")return;let e=s,t=e.image??e.image_url??e.imageUrl;return typeof t=="string"&&t.trim()?t.trim():void 0}function Dc(s){if(typeof atob=="function"){let e=atob(s),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder().decode(t)}if(typeof Buffer<"u")return Buffer.from(s,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function Oc(s){let e=s.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let t=e[1]??"",n=e[2]??"";try{let r=/;base64/i.test(t)?Dc(n):decodeURIComponent(n);return JSON.parse(r)}catch{try{return JSON.parse(n)}catch{return null}}}function Ta(s){let e=s?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=Oc(e);return t?vt(Gr(t)):null}var Mc=12,Fc=6e3;async function qc(s,e,t){let n=new Array(s.length),r=0,o=new Array(Math.max(1,Math.min(e,s.length))).fill(0).map(async()=>{for(;r<s.length;){let a=r++;n[a]=await t(s[a],a)}});return await Promise.all(o),n}async function Bc(s,e){try{let t=await x.get(s,{timeout:e});if(!t.ok)return null;let n=t.data;if(n&&typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return null}return null}catch{return null}}async function $c(s,e){let t=s?.trim();if(!t)return null;if(/^data:/i.test(t))return Ta(t);let n=wa(t);if(!n)return null;if(ka(n))return n;let r=await Bc(n,e);if(r){let o=vt(Gr(r));if(o)return o}return null}async function Do(s,e,t){if(e.length===0)return[];let n=t?.concurrency??Mc,r=t?.timeoutMs??Fc,o=await Ns(s,e,t?.rpcUrl);return qc(o,n,a=>$c(a,r))}var va=100,Hc=100,on="{name}",Aa="{chain}",rn=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 D(e)}async run(e,t){let n=j(e.address,t),r=Z(e.chain,t),o=r?[r]:ve(),a=jc(e.contract_address),i=xa(e.collection_name);return a||i?this.listNfts({address:n,chains:o,singleChain:!!r,contract:a,collectionName:i}):this.listCollections({address:n,chains:o,singleChain:!!r,args:e})}async listCollections(e){let{address:t,chains:n,singleChain:r,args:o}=e,a=await Promise.all(n.map(async c=>{let u=await this.service.getWalletNftCollections({address:t,chain:c,limit:va});return{chain:c,rows:u.success?Sa(u.data?.result??[]):[],ok:u.success}}));if(r&&!a[0].ok)return{error:"Failed to fetch wallet NFT collections"};let i=a.flatMap(c=>c.rows.map(u=>({name:Wc(u),contractAddress:u.token_address,chain:v(c.chain),nftCount:u.count??null})));if(i.length===0)return{_instructions:"The wallet holds no NFT collections"+(r?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:t,collectionCount:0,collections:[]};let l=Gc(i,o);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:t,collectionCount:i.length,collections:i,...l.length>0?{actionButtons:l}:{}}}async listNfts(e){let{address:t,chains:n,singleChain:r,contract:o,collectionName:a}=e,i=await Promise.all(n.map(async h=>{let f=await this.service.getWalletNFTs({address:t,chain:h,limit:va,...o?{tokenAddresses:[o]}:{}});return{chain:h,rows:f.success?Sa(f.data?.result??[]):[],ok:f.success}}));if(r&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(h=>h.rows.filter(f=>Vc(f,{contract:o,collectionName:a})).map(f=>({chain:h.chain,row:f})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${a??o??""}"`+(r?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||a||l[0].row.token_address,u=await this.resolveOnchainImages(l),d=l.map(({chain:h,row:f},m)=>{let g=Yc(f);return{name:g.name,tokenId:g.tokenId,contractAddress:g.contractAddress,image:u[m]??g.image,chain:v(h)}});return{ui:{component:"WalletNftList",props:{walletAddress:t,collectionName:c,nfts:d}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:t,collectionName:c,nftCount:l.length}}async resolveOnchainImages(e){let t=new Array(e.length).fill(null),n=new Map;e.forEach((r,o)=>{let a=n.get(r.chain)??[];a.push(o),n.set(r.chain,a)});try{await Promise.all([...n.entries()].map(async([r,o])=>{let a=o.map(l=>({contract:e[l].row.token_address,tokenId:e[l].row.token_id})),i=await Do(r,a);o.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function Sa(s){return s.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function Vc(s,e){if(e.contract)return s.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let t=e.collectionName.toLowerCase();return(s.name??"").toLowerCase().includes(t)}return!1}function Wc(s){let e=s.name?.trim();if(e)return e;let t=s.token_address??"";return t.length>10?`${t.slice(0,6)}\u2026${t.slice(-4)}`:t}function Yc(s){return{name:s.normalized_metadata?.name||s.name||`#${s.token_id}`,tokenId:s.token_id,contractAddress:s.token_address,image:vt(s.normalized_metadata?.image||s.media?.original_media_url)}}function Gc(s,e){let t=typeof e.pick_button_label=="string"?e.pick_button_label:"",n=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",r=[];for(let o of s){if(r.length>=Hc)break;if(!o.contractAddress)continue;let a=typeof o.chain=="string"?o.chain.trim():"",i=a?`show my ${on} NFTs on ${Aa}`:`show my ${on} NFTs`,l=Pa(n,{[on]:o.name,[Aa]:a},i);a&&!l.includes(a)&&(l=`${l} (${a})`),r.push({label:Kc(t,o.name,on),prompt:`${l} (${o.contractAddress})`})}return r}function Pa(s,e,t){let n=s&&s.includes(on)?s:t;for(let[r,o]of Object.entries(e))n=n.split(r).join(o);return n.replace(/\s+/g," ").trim()}function Kc(s,e,t){return Pa(s,{[on]:e},t)}function xa(s){if(typeof s!="string")return;let e=s.trim();return e||void 0}function jc(s){let e=xa(s);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var zc="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.",Me=class extends A{kind="data";category="nft";llm;constructor(e){super(),this.llm=new J(e??{})}static promptParams(e){return[{name:"prompt",type:"string",description:e,required:!0}]}async run(e){let t=typeof e.prompt=="string"?e.prompt.trim():"";if(!t)return{error:"Missing required parameter: prompt"};let n=await this.askGeminiWithSearch(t);return n?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:n}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(e){let t=Date.now();try{return(await this.llm.chat([{role:"system",content:zc,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var sn=class extends Me{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=Me.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 an=class extends Me{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=Me.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 Kr={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"},jr="amazon.com";function Xc(s){return s?s.trim().toLowerCase().split(/[-_]/)[0]:""}function zr(s){let e=Xc(s);return Kr[e]??jr}function Oo(s){return`https://${zr(s)}/s?k=NFC%20Tag`}function Mo(s){if(!s)return"";let e=s.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var Qc=720*60*1e3,Ca=new Map,_a=3;function Jc(s){return[`A user in country "${s}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${_a} 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 Zc(s){if(!s)return[];let e=s.indexOf("["),t=s.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let n;try{n=JSON.parse(s.slice(e,t+1))}catch{return[]}if(!Array.isArray(n))return[];let r=[],o=new Set;for(let a of n){if(!a||typeof a!="object")continue;let i=a.label,l=a.url;if(typeof i!="string"||!i.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!o.has(c)&&(o.add(c),r.push({label:i.trim(),url:l.trim()}),r.length>=_a))break}return r}async function Xr(s,e){let t=Mo(s);if(!t||!e)return null;let n=Ca.get(t);if(n&&n.expires>Date.now())return n.links;let r=Date.now(),o=[{role:"user",content:Jc(t),timestamp:r}];try{let a=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),i=Zc(a.text);if(i.length)return Ca.set(t,{links:i,expires:Date.now()+Qc}),i}catch{}return null}async function ln(s){let e=await Xr(s.country,s.llm);return e&&e.length?e:[{label:"Amazon",url:Oo(s.language)}]}function eu(s){return s.length<=1?s.length===1?`[${s[0].label}](${s[0].url})`:"":s.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
|
|
23
|
+
}`,to=class{liveRateCall(e,t){return null}decodeSize(e,t){let n=bt(e);return n===null?null:nt(n,t.usdcDecimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,t){return this.balanceIsUnderlying?null:{target:e.contract,callData:Br+ae(t)}}},no=class extends to{type="spark";balanceIsUnderlying=!1;sizeCall(e){return{target:e.contract,callData:Xl}}fetchApy(e,t,n){return oa(e,t,n)}},Ir=class extends no{type="spark"},Lr=class extends no{type="spark-ethereum"},Dr=class extends to{type="aave-v3";balanceIsUnderlying=!0;sizeCall(e){return{target:e.token,callData:ea}}liveRateCall(e,t){return{target:e.contract,callData:Ql+ze(t.usdc)}}decodeLiveRate(e){if(!e)return null;let t=G(e);if(t.length<(Js+1)*64)return null;let n=Number(Oe(t,Js*64))/Jl;return Number.isFinite(n)&&n>=0&&n<=Zl?n:null}async fetchApy(e,t,n){let r=await x.post(n.aaveApiUrl,{operationName:"SupplyAPYHistory",query:ec,variables:{request:{chainId:t.chainId,market:e.contract,underlyingToken:t.usdc,window:"LAST_WEEK"}}});if(!r.ok)throw new Error(R(r));return{samples:(r.data?.data?.value||[]).map(o=>({timeMs:Date.parse(o?.date??""),fraction:Number(o?.avgRate?.value)})),current:null}}},Or=class extends to{type="compound-v3";balanceIsUnderlying=!0;sizeCall(e){return{target:e.token,callData:ea}}fetchApy(e,t,n){return oa(e,t,n)}},Mr=class extends no{type="morpho-v2";async fetchApy(e,t,n){let r=oc(Date.now()),o=await x.post(n.morphoApiUrl,{operationName:"VaultV2ByAddress",query:tc,variables:{address:e.contract,chainId:t.chainId,options:{startTimestamp:Math.floor(r/1e3)-(Fr-1)*86400,endTimestamp:Math.floor(r/1e3)-86400}}});if(!o.ok)throw new Error(R(o));let a=o.data?.data?.vaultV2ByAddress,i=Number(a?.netApyExcludingRewards);return{samples:(a?.historicalState?.avgNetApy||[]).map(l=>({timeMs:Number(l?.x)*1e3,fraction:Number(l?.y)})),current:Number.isFinite(i)?i:null}}};async function oa(s,e,t){let n=`${t.coinPoolBaseUrl}/supply/rates/history?chainId=${e.chainId}&token=${s.token}`,r=await x.get(n);if(!r.ok)throw new Error(R(r));return{samples:(r.data?.data||[]).map(o=>({timeMs:Date.parse(o?.date??""),fraction:Number(o?.rate)})),current:null}}var ra={"aave-v3":new Dr,"compound-v3":new Or,spark:new Ir,"spark-ethereum":new Lr,"morpho-v2":new Mr},nc=ra.spark;function oo(s){return ra[s.type]??nc}function bt(s){if(!s)return null;let e=G(s);if(e.length<64)return null;try{return Oe(e,0)}catch{return null}}function sa(s){if(!s)return null;let e=G(s);if(e.length<64)return null;try{if(e.length>=128){let t=Number(Oe(e,0)),n=t*2;if(Number.isFinite(t)&&t>0&&e.length>=n+64){let r=Number(Oe(e,n)),o=n+64;return r>0&&e.length>=o+r*2?Zs(e.slice(o,o+r*2)):null}return null}return Zs(e.slice(0,64))||null}catch{return null}}function Zs(s){let e=s.match(/.{2}/g)??[];return Buffer.from(e.join(""),"hex").toString("utf8").replace(/[^\x20-\x7e]/g,"").trim()}function nt(s,e){return Number(s)/10**e}function ro(s){return new Date(s).toISOString().slice(0,10)}function oc(s){return Date.parse(`${ro(s)}T00:00:00.000Z`)}var wt={"0x1":{chainId:1,usdc:"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",usdcDecimals:6},"0xa":{chainId:10,usdc:"0x0b2c639c533813f4aa9d7837caf62653d097ff85",usdcDecimals:6},"0x38":{chainId:56,usdc:"0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d",usdcDecimals:18},"0x2105":{chainId:8453,usdc:"0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",usdcDecimals:6},"0xa4b1":{chainId:42161,usdc:"0xaf88d065e77c8cc2239327c5edb3a432268e5831",usdcDecimals:6}},rc=.01,sc=8,Ye=class{coinPoolBaseUrl;apiEndpoints;apyLimiter=new $r(sc);constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app",this.apiEndpoints={coinPoolBaseUrl:this.coinPoolBaseUrl,aaveApiUrl:e.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:e.morphoApiUrl||"https://api.morpho.org/graphql"}}listSupportedChains(){return Object.keys(wt).filter(e=>M(e)===e)}isSupported(e){let t=M(e);return!!(t&&wt[t])}async getMarkets(e){let t=M(e),n=t?wt[t]:void 0;if(!t||!n)return[];try{let r=`${this.coinPoolBaseUrl}/supply/v2?chainId=${n.chainId}&limit=100&page=1`,o=await x.get(r);if(!o.ok)throw new Error(R(o));return(o.data?.data?.items||[]).flatMap(a=>{let i=ac(a,t);return i?[i]:[]})}catch{return[]}}getUsdc(e){let t=M(e),n=t?wt[t]:void 0;return n?{address:n.usdc,decimals:n.usdcDecimals}:null}async readReceiptToken(e,t){let n=oo(t).balanceIsUnderlying;try{let r=await gt(e,[{target:t.token,callData:na},{target:t.token,callData:qr}]);return{symbol:sa(r[0]),decimals:ia(r[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}async findMarket(e,t){let n=t.trim().toLowerCase();if(!n)return[];let r=await this.getMarkets(e);if(F(n))return r.filter(a=>a.contract===n||a.token===n);let o=r.filter(a=>a.name.trim().toLowerCase()===n);return o.length>0?o:r.filter(a=>{let i=a.name.trim().toLowerCase(),l=a.protocol.trim().toLowerCase();return i.includes(n)||n.includes(i)||l.includes(n)||n.includes(l)})}async describeResolvedMarkets(e,t){let n=M(e);return n?this.describeMarkets(n,t):[]}async getMarketOverviews(e){return(await Promise.all(aa(e.chains).map(async n=>this.describeMarkets(n,await this.getMarkets(n))))).flat().sort((n,r)=>(r.avgApyPercent??-1)-(n.avgApyPercent??-1))}async getSupplyPositions(e){return F(e.address)?(await Promise.all(aa(e.chains).map(n=>this.positionsForChain(n,e.address)))).flat().sort((n,r)=>r.suppliedUsdc-n.suppliedUsdc||(r.avgApyPercent??0)-(n.avgApyPercent??0)):[]}async positionsForChain(e,t){let n=wt[e],r=await this.getMarkets(e);if(!n||r.length===0)return[];let o=await this.readBalances(e,t,r);if(o.length===0)return[];let[a,i]=await Promise.all([this.describeMarkets(e,o.map(l=>l.market)),this.convertToUnderlying(e,n,o)]);return a.flatMap((l,c)=>{let u=i[c];return u<rc?[]:[{...l,suppliedUsdc:kt(u,6),estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:kt(u*l.avgApyPercent/100,2)}]})}async describeMarkets(e,t){let n=wt[e];if(!n||t.length===0)return[];let[r,o]=await Promise.all([this.readMarketState(e,n,t),Promise.all(t.map(a=>this.apyLimiter.run(()=>this.fetchApySamples(a,n))))]);return t.map((a,i)=>{let{totalSuppliedUsdc:l,liveApyFraction:c}=r[i],u=ic(o[i].samples,c??o[i].current);return{...a,totalSuppliedUsdc:l===null?null:kt(l,2),avgApyPercent:u.avgApyPercent,currentApyPercent:u.currentApyPercent,apyChangePercent:u.apyChangePercent,apyHistory:u.history}})}async readBalances(e,t,n){let r=ze(t),o=n.flatMap(i=>[{target:i.token,callData:ta+r},{target:i.token,callData:qr}]),a=await gt(e,o);return n.flatMap((i,l)=>{let c=bt(a[l*2]);return c===null||c<=0n?[]:[{market:i,rawBalance:c,tokenDecimals:ia(a[l*2+1])}]})}async readMarketState(e,t,n){let r=[],o=n.map(i=>{let l=oo(i),c={protocol:l,size:r.length,rate:-1};r.push(l.sizeCall(i,t));let u=l.liveRateCall(i,t);return u&&(c.rate=r.length,r.push(u)),c}),a=await gt(e,r);return o.map(i=>({totalSuppliedUsdc:i.protocol.decodeSize(a[i.size],t),liveApyFraction:i.rate<0?null:i.protocol.decodeLiveRate(a[i.rate])}))}async convertToUnderlying(e,t,n){let r=[],o=n.map(i=>{let l=oo(i.market).convertToAssetsCall(i.market,i.rawBalance);return l?(r.push(l),r.length-1):-1}),a=await gt(e,r);return n.map((i,l)=>{if(o[l]<0)return nt(i.rawBalance,t.usdcDecimals);let c=bt(a[o[l]]);return c===null?nt(i.rawBalance,i.tokenDecimals??t.usdcDecimals):nt(c,t.usdcDecimals)})}async fetchApySamples(e,t){try{return await oo(e).fetchApy(e,t,this.apiEndpoints)}catch{return{samples:[],current:null}}}},$r=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 aa(s){let e=s.map(t=>M(t)).filter(t=>!!t);return[...new Set(e)].filter(t=>!!wt[t])}function ac(s,e){if(s?.isDeleted===!0)return null;let t=typeof s?.contract=="string"?s.contract.toLowerCase():"";if(!F(t))return null;let n=typeof s?.token=="string"&&F(s.token)?s.token.toLowerCase():t,r=Number(s?.rating?.balanceScore);return{chain:e,name:s?.name?.trim()||"USDC lending market",protocol:s?.protocolId?.name?.trim()||"Unknown",protocolUrl:s?.protocolId?.domain?.trim()||null,type:s?.type?.trim()||"unknown",contract:t,token:n,platformScore:Number.isFinite(r)?r:null}}function ic(s,e){let t=ro(Date.now()),n=new Map,r=null;for(let u of s){if(!Number.isFinite(u.timeMs)||!Number.isFinite(u.fraction)||u.fraction<0||((!r||u.timeMs>r.timeMs)&&(r=u),!lc(u.timeMs)))continue;let d=ro(u.timeMs);d>=t||n.set(d,u.fraction)}let o=[...n.entries()].sort((u,d)=>u[0]<d[0]?-1:1).slice(-Fr).map(([u,d])=>({date:u,apyPercent:kt(d*100,2)})),a=e??(r&&ro(r.timeMs)===t?r.fraction:null),i=a===null?null:kt(a*100,2);if(i!==null&&o.push({date:t,apyPercent:i}),o.length===0)return{history:o,avgApyPercent:null,currentApyPercent:null,apyChangePercent:null};let l=o.reduce((u,d)=>u+d.apyPercent,0),c=o[o.length-1].apyPercent;return{history:o,avgApyPercent:kt(l/o.length,2),currentApyPercent:i,apyChangePercent:o.length>=2?kt(c-o[o.length-2].apyPercent,2):null}}function ia(s){let e=bt(s);if(e===null)return null;let t=Number(e);return Number.isFinite(t)&&t>=0&&t<=36?t:null}function kt(s,e){let t=10**e;return Math.round(s*t)/t}function lc(s){let e=new Date(s);return e.getUTCHours()===0&&e.getUTCMinutes()===0&&e.getUTCSeconds()===0}var so="{market}",ca="{chain}";var ua=[{name:"supply_button_label",type:"string",description:`Label template for the per-market "Supply" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Use the exact placeholder "{market}" (do not translate the braces); it is replaced per market with its name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply USDC" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use BOTH exact placeholders (do not translate the braces): "{market}" is replaced with the market name, "{chain}" with the chain name it lives on. Write the connecting words around {chain} in the user's language \u2014 that is why it is a placeholder and not appended for you. English example: "supply USDC to {market} on {chain}". Vietnamese example: "n\u1EA1p USDC v\xE0o {market} tr\xEAn {chain}". Always include BOTH {market} and {chain}. Do NOT write a chain name or a contract address literally \u2014 the exact market identifier is appended automatically.`,required:!1}],da=' A clickable "Supply" button is shown below your reply for each market automatically \u2014 do NOT list, number, or repeat those buttons in your text, and do NOT tell the user to tap one; just deliver the list and your suggestion.';function pa(s,e,t){return cc(s,typeof e.supply_button_label=="string"?e.supply_button_label:"",typeof e.supply_prompt_template=="string"?e.supply_prompt_template:"",t)}function cc(s,e,t,n){let r=typeof n=="string"?n.trim():"",o=[],a=new Set;for(let i of s){if(o.length>=10)break;let l=i.name?.trim();!l||a.has(l.toLowerCase())||(a.add(l.toLowerCase()),o.push({label:la(e,l,"",`Supply ${so}`),prompt:la(t,l,r,uc(r))+dc(i.contract)}))}return o}function uc(s){return s?`supply USDC to ${so} on ${ca}`:`supply USDC to ${so}`}function dc(s){let e=s?.trim();return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?` (market: ${e})`:""}function la(s,e,t,n){return(s&&s.includes(so)?s:n).split(so).join(e).split(ca).join(t).replace(/\s+/g," ").trim()}var pc={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},mc={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",130:"proto_unichain_v3",137:"proto_polygon_v3",5e3:"proto_mantle_v3",8453:"proto_base_v3",9745:"proto_plasma_v3",42161:"proto_arbitrum_v3",57073:"proto_ink_v3"},hc={1:"mainnet",10:"optimism",56:"bnb",130:"unichain",8453:"base",42161:"arbitrum",43114:"avalanche"},gc={1:"usdc-mainnet",10:"usdc-op",56:"usdc-bnb",130:"usdc-unichain",137:"usdc-polygon",8453:"usdc-basemainnet",42161:"usdc-arb"},fc={1:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",10:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",56:"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",130:"0x078D782b760474a361dDA0AF3839290b0EF57AD6",137:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",8453:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",42161:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831"};function Jt(s){let e=kc(s.chain);return(e===null?null:yc(s,e))??wc(s,e)}function yc(s,e){switch(s.type){case"morpho-v2":{let t=pc[e];return!t||!s.contract?null:`https://app.morpho.org/${t}/vault/${Hr(s.contract)}`}case"aave-v3":{let t=mc[e],n=fc[e];return!t||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${Hr(n)}&marketName=${t}`}case"spark":case"spark-ethereum":{let t=hc[e];return t?`https://app.spark.fi/savings/${t}/${bc(s,e)}`:null}case"compound-v3":{let t=gc[e];return t?`https://app.compound.finance/?market=${t}`:null}default:return null}}function bc(s,e){let t=`${s.name||""} ${s.token||""}`.toLowerCase();return t.includes("spusdc")?"spusdc":t.includes("susds")?"susds":t.includes("susdc")?"susdc":e===1?"spusdc":"susdc"}function wc(s,e){let t=s.protocolUrl?.trim();if(!t)return null;let n=/^https?:\/\//i.test(t)?t:`https://${t.replace(/^\/+/,"")}`;try{let r=new URL(n);return e!==null&&r.searchParams.set("chainId",String(e)),s.contract&&r.searchParams.set("contract",Hr(s.contract)),r.toString()}catch{return n}}function Hr(s){let e=s.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function kc(s){let e=s?.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 Io=[{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"]}],Wr=Io.map(s=>s.label),Vr={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 ma(s){let e=typeof s=="string"?s.trim():"";if(!e)return{kind:"none"};let t=Sc(e);if(!t)return{kind:"none"};let n=Tc(t);if(n){let o=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>o.has(a.type)}}let r=Ac(t);return r?{kind:"unsupported",label:r,requested:e}:{kind:"unknown",requested:e}}function Tc(s){let e=Io.filter(t=>t.aliases.includes(s));if(e.length===1)return e[0];if(e.length>1)return null;if(s.length>=3){let t=Io.filter(n=>n.aliases.some(r=>r.includes(s)||s.includes(r)));if(t.length===1)return t[0];if(t.length>1)return null}return vc(s)}function vc(s){let e=null,t=!1;for(let n of Io)for(let r of n.aliases){let o=ha(r);if(o===0||Math.abs(r.length-s.length)>o)continue;let a=ga(s,r,o);a>o||(!e||a<e.distance?(e={spec:n,distance:a},t=!1):a===e.distance&&n!==e.spec&&(t=!0))}return e&&!t?e.spec:null}function ha(s){return s.length<=4?0:s.length<=9?2:3}function Ac(s){let e=Vr[s];if(e)return e;if(s.length>=4){let r=new Set(Object.entries(Vr).filter(([o])=>o.length>=4&&(o.includes(s)||s.includes(o))).map(([,o])=>o));if(r.size===1)return[...r][0];if(r.size>1)return null}let t=null,n=!1;for(let[r,o]of Object.entries(Vr)){let a=ha(r);if(a===0||Math.abs(r.length-s.length)>a)continue;let i=ga(s,r,a);i>a||(!t||i<t.distance?(t={label:o,distance:i},n=!1):i===t.distance&&o!==t.label&&(n=!0))}return t&&!n?t.label:null}function Sc(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function ga(s,e,t){if(s===e)return 0;if(!s.length)return e.length;if(!e.length)return s.length;let n=new Array(e.length+1),r=Array.from({length:e.length+1},(a,i)=>i),o=new Array(e.length+1);for(let a=1;a<=s.length;a++){o[0]=a;let i=o[0];for(let c=1;c<=e.length;c++){let u=r[c-1]+(s[a-1]===e[c-1]?0:1),d=Math.min(o[c-1]+1,r[c]+1,u);a>1&&c>1&&s[a-1]===e[c-2]&&s[a-2]===e[c-1]&&(d=Math.min(d,n[c-2]+1)),o[c]=d,d<i&&(i=d)}if(i>t)return t+1;let l=n;n=r,r=o,o=l}return r[e.length]}var xc=["apy","score","size"],fa=5,ya=40,Zt=class extends A{name="get-lending-markets";description='List the USDC LENDING / SUPPLY markets available to deposit into and earn yield on: protocol (Aave v3, Compound v3, Spark, Morpho vaults), market name, chain, total USDC supplied to that market, the live supply APY plus the average over the last week and its daily change, and a 0\u201310 platform score. Ranked by the live protocol APY by default, and filterable to ONE protocol via `protocol`. Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. Supports: Ethereum, Optimism, BSC, Base, Arbitrum. Do NOT use for: 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 of a chain with USDC lending markets: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x2105" Base, "0xa4b1" Arbitrum. 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: ${Wr.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-${ya}. Default ${fa} \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},...ua];service;constructor(e){super(),this.service=new Ye(e)}async run(e,t){let n=this.service.listSupportedChains(),r=Z(e.chain,void 0),o=r?null:M(t?.chain),a=r??o;if(a&&!n.includes(a))return{_instructions:`There are no USDC lending markets on ${v(a)}`+(o?", the chain the wallet is currently connected to":"")+". Tell the user that in their language and name the chains that DO have them (in `chainsWithLendingMarkets`), offering to list those instead. Do NOT mention tool names.",chain:v(a),connectedChainHasNoMarkets:o!==null,marketCount:0,markets:[],chainsWithLendingMarkets:n.map(m=>v(m))};let i=ma(e.protocol);if(i.kind==="unsupported"||i.kind==="unknown")return this.unsupportedProtocol(i);let l=a?[a]:n,c=_c(e.sort),u=Ec(e.limit),d=await this.service.getMarketOverviews({chains:l}),p=i.kind==="supported"?d.filter(m=>i.matches(m)):d;if(i.kind==="supported"&&p.length===0&&d.length>0)return{_instructions:`There are no ${i.label} USDC lending markets on ${a?v(a):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${i.label} market. Do NOT mention tool names.`,requestedProtocol:i.label,chain:a?v(a):"all",marketCount:0,markets:[],protocolsAvailable:[...new Set(d.map(m=>m.protocol))]};let h=[...p].sort(Cc[c]).slice(0,u),f=h.slice(0,10).flatMap(m=>pa([{name:m.name,contract:m.contract}],e,v(m.chain)));return{_instructions:this.instructions(h,c,f.length>0,i.kind==="supported"?i.label:null),...f.length>0?{actionButtons:f}:{},chain:a?v(a):"all",chainsQueried:l.map(m=>v(m)),...i.kind==="supported"?{protocolFilter:i.label}:{},sortedBy:c,marketCount:h.length,totalMarketsAvailable:p.length,markets:h.map(m=>({marketName:m.name,protocol:m.protocol,protocolUrl:Jt(m),chain:v(m.chain),avgApyPercent:m.avgApyPercent,avgApyDays:m.apyHistory.length,currentApyPercent:m.currentApyPercent,apyChangePercent:m.apyChangePercent,totalSuppliedUsdc:m.totalSuppliedUsdc,platformScore:m.platformScore}))}}unsupportedProtocol(e){let t=e.kind==="unsupported",n=t?e.label:`"${e.requested}"`;return{_instructions:`The user asked about ${n}, which has no USDC lending markets here. In their language: tell them plainly that ${n} is ${t?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${n} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:t?e.label:e.requested,protocolSupported:!1,supportedProtocols:[...Wr],marketCount:0,markets:[]}}instructions(e,t,n=!1,r=null){if(e.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let o={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[t];return[r?`These are the ${r} USDC lending markets the user can supply to, ${o}. The list is SCOPED to ${r} because that is what they asked about \u2014 present it as such, and do not imply it is every lending market available.`:`These are USDC lending markets the user can supply to, ${o}.`,"Present them as a NUMBERED list. Each entry starts with `marketName` as a markdown link to that","market's `protocolUrl` in bold \u2014 **[marketName](protocolUrl)** \u2014 so the name opens that market's page on","the protocol.","When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it.",'Under each name put exactly three bullet points, in this order: "Total supplied" = `totalSuppliedUsdc`,','"Protocol APY" = `currentApyPercent` (the live rate), and "Avg APY" = `avgApyPercent` labelled as the',"average over the last `avgApyDays` days. Do NOT add other bullets.","Amounts are USDC, so format them as US dollars, compactly ($100.12M, $23.45M).","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage \u2014 mention it only when the user","asks which market is safest. A null APY means that rate was unavailable \u2014 say so rather than showing 0.",new Set(e.map(a=>a.chain)).size>1?"The markets span several chains \u2014 put each one's `chain` on the title line, after the linked name, so the user knows where it lives.":"All markets are on one chain \u2014 state the chain name once before the list, not per market.","Close with one short sentence naming the best option for the ranking used and why.","This is information, NOT financial advice \u2014 say so briefly.","Do NOT mention tool names.",n?da:""].filter(Boolean).join(" ")}},Cc={apy:(s,e)=>(e.currentApyPercent??-1)-(s.currentApyPercent??-1),score:(s,e)=>(e.platformScore??-1)-(s.platformScore??-1),size:(s,e)=>(e.totalSuppliedUsdc??-1)-(s.totalSuppliedUsdc??-1)};function _c(s){let e=typeof s=="string"?s.trim().toLowerCase():"";return xc.includes(e)?e:"apy"}function Ec(s){let e=typeof s=="number"?s:Number(s);return!Number.isFinite(e)||e<1?fa:Math.min(Math.floor(e),ya)}var en=class extends A{name="get-wallet-lending-positions";description=`Get a wallet's own LENDING / SUPPLY (earn, deposit, savings) positions in USDC lending markets: which protocol and market the wallet supplies to (Aave v3, Compound v3, Spark, Morpho vaults), how much USDC 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. Covers USDC only, on Aave v3, Compound v3, Spark and Morpho vaults, on Ethereum, Optimism, BSC, Base, Arbitrum. For supplied assets OTHER than USDC (DAI, USDT, ETH\u2026), for protocols outside that list (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 of a chain with USDC lending markets: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x2105" Base, "0xa4b1" Arbitrum. 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 Ye(e)}async run(e,t){let n=j(e.address,t);if(!F(n))return{error:`"${n}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let r=Z(e.chain,t),o=this.service.listSupportedChains();if(r&&!o.includes(r))return{_instructions:`There are no USDC lending markets on ${v(r)}, so the wallet cannot have a supply position there. Tell the user that in their language and name the chains that DO have lending markets (listed in \`chainsWithLendingMarkets\`). Do NOT mention tool names.`,walletAddress:n,chain:v(r),positionCount:0,positions:[],chainsWithLendingMarkets:o.map(l=>v(l))};let a=r?[r]:o,i=await this.service.getSupplyPositions({address:n,chains:a});return{_instructions:this.instructions(i),walletAddress:n,chain:r?v(r):"all",chainsQueried:a.map(l=>v(l)),positionCount:i.length,totals:Nc(i),positions:i.map(l=>({marketName:l.name,protocol:l.protocol,protocolUrl:Jt(l),chain:v(l.chain),suppliedUsdc:l.suppliedUsdc,avgApyPercent:l.avgApyPercent,currentApyPercent:l.currentApyPercent,apyChangePercent:l.apyChangePercent,estimatedAnnualYieldUsdc:l.estimatedAnnualYieldUsdc,marketTotalSuppliedUsdc:l.totalSuppliedUsdc,apyHistory:l.apyHistory,platformScore:l.platformScore}))}}instructions(e){return e.length===0?"The wallet supplies USDC 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 check covers USDC only, so if the user believes they have a deposit it may be in another asset; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the daily samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","All amounts are USDC, so format them as US dollars, compactly ($1.23M, $45.6K, $12.34).","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(e.map(n=>n.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals`. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function Nc(s){let e=s.reduce((r,o)=>r+o.suppliedUsdc,0),t=s.filter(r=>r.avgApyPercent!==null),n=t.reduce((r,o)=>r+o.suppliedUsdc,0);return{suppliedUsdc:Yr(e,6),estimatedAnnualYieldUsdc:Yr(s.reduce((r,o)=>r+(o.estimatedAnnualYieldUsdc??0),0),2),weightedAvgApyPercent:n>0?Yr(t.reduce((r,o)=>r+o.suppliedUsdc*o.avgApyPercent,0)/n,2):null}}function Yr(s,e){let t=10**e;return Math.round(s*t)/t}var Rc=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"],Uc=s=>Rc.includes(s),tn=class extends A{name="open-supply-usdc-form";kind="ui";category="lending-action";description='Open the SUPPLY USDC form so the user can DEPOSIT USDC 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. USDC is the only asset this deposits, so a message that names no asset is still this tool \u2014 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 Ethereum, Optimism, BSC, Base and Arbitrum. 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)" hint, pass THAT address verbatim as this argument and ignore the market name in the sentence \u2014 the address identifies the exact market they picked, while a name may match several vaults of the same protocol.`,required:!0},{name:"chain",type:"string",description:`Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x2105" Base, "0xa4b1" Arbitrum. Set it ONLY when the user names a chain; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:'USDC amount to pre-fill, 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 Ye(e),this.moralis=new D(e?.moralis)}async run(e,t){let n=t?.walletAddress;if(!n)return{error:"wallet_not_connected",_instructions:"Supplying moves real funds, so it needs a connected wallet. Ask the user to connect one, in their language. Do NOT render a form and do NOT mention tool names."};let o=Z(e.chain,void 0)??M(t?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for the supply. Ask the user which chain they want to supply on, naming the supported ones. Do NOT mention tool names."};let a=this.service.listSupportedChains();if(!a.includes(o))return{error:"unsupported_chain",chain:v(o),chainsWithLendingMarkets:a.map(b=>v(b)),_instructions:`There are no USDC lending markets on ${v(o)}, 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 i=Ic(e.market);if(!i)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let l=await this.service.findMarket(o,i);if(l.length===0)return{error:"market_not_found",market:i,chain:v(o),_instructions:`No USDC lending market matching "${i}" exists on ${v(o)}. Tell the user in their language and offer to list the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(l.length>1)return{error:"ambiguous_market",market:i,chain:v(o),candidates:l.map(b=>({marketName:b.name,protocol:b.protocol})),_instructions:`"${i}" matches ${l.length} different markets on ${v(o)}, 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="`+i+`" and chain for ${v(o)}, plus the localized supply-button templates \u2014 that shows the user each market with its APY, size and score, each with its own Supply button to tap. Write no message of your own before that call.`};let c=l[0];if(!Uc(c.type))return{error:"unsupported_protocol",marketName:c.name,protocol:c.protocol,_instructions:`Supplying to ${c.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let u=this.service.getUsdc(o);if(!u)return{error:"unsupported_chain",chain:v(o),_instructions:`No USDC is configured for ${v(o)}. Tell the user supplying is unavailable there.`};let[d,p,h]=await Promise.all([this.describeOne(o,c),this.usdcBalance(n,o,u.address),this.service.readReceiptToken(o,c)]);if(p&&ft(p.amount,"0")<=0)return{error:"no_usdc_balance",marketName:c.name,chain:v(o),usdcBalance:"0",_instructions:`The user has no USDC available to supply to ${c.name} on ${v(o)}. In the user's language, tell them plainly that they have no USDC 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 f=Lc(e.amount),m=f?Qe(f,u.decimals):null;if(m&&p&&ft(m,p.amount)>0)return{error:"insufficient_usdc_balance",marketName:c.name,chain:v(o),requestedAmount:f,usdcBalance:p.amount,_instructions:`The user wants to supply ${f} USDC to ${c.name}, but they only hold ${p.amount} USDC on ${v(o)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${f} USDC exceeds their balance of ${p.amount} USDC on this chain, then ask them to enter a smaller amount or add more USDC. 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 g={action:"supply_usdc",chainId:o,chainName:v(o),walletAddress:n,market:{name:c.name,type:c.type,protocol:c.protocol,protocolUrl:Jt(c),contract:c.contract,token:c.token,apyPercent:d?.currentApyPercent??d?.avgApyPercent??null,receiptToken:h},asset:{address:u.address,symbol:"USDC",decimals:u.decimals},...m?{prefillAmount:m}:{},...p?{spendable:p.amount}:{},...p?.usd?{spendableUsd:p.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:g},marketName:c.name,protocol:c.protocol,chain:v(o),apyPercent:g.market.apyPercent,usdcBalance:p?.amount??null,_instructions:this.instructions(c)}}async describeOne(e,t){try{let[n]=await this.service.describeResolvedMarkets(e,[t]);return n??null}catch{return null}}async usdcBalance(e,t,n){try{let r=await this.moralis.getWalletTokenBalances({address:e,chain:t,tokenAddresses:[n]});if(!r.success)return null;let o=(r.data?.result??[]).find(i=>(i.token_address||"").toLowerCase()===n.toLowerCase());if(!o?.balance_formatted)return{amount:"0",usd:null};let a=typeof o.usd_value=="number"?String(o.usd_value):null;return{amount:String(o.balance_formatted),usd:a}}catch{return null}}instructions(e){return[`The supply action for ${e.name} is ready.`,"In the user's language, invite them to enter the amount of USDC they want to supply, naming the market and","the chain.",'Speak ONLY of the action the USER takes (supplying / depositing USDC). 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 Ic(s){let e=typeof s=="string"?s.trim():"",t=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})\s*[\])]/i.exec(e);if(t)return t[1];let n=/0x[a-fA-F0-9]{40}/.exec(e);return n&&n[0]!==e?n[0]:e}function Lc(s){let e=typeof s=="string"?s.trim():typeof s=="number"?String(s):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}var Lo="https://ipfs.pantograph.app/ipfs/",ba=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function Tt(s){let e=s?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${Lo}${t[1]}`:ba.test(e)?`${Lo}${e}`:null}function wa(s){let e=s?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${Lo}${t[1]}`:ba.test(e)?`${Lo}${e}`:null}function ka(s){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(s)}function Gr(s){if(!s||typeof s!="object")return;let e=s,t=e.image??e.image_url??e.imageUrl;return typeof t=="string"&&t.trim()?t.trim():void 0}function Dc(s){if(typeof atob=="function"){let e=atob(s),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder().decode(t)}if(typeof Buffer<"u")return Buffer.from(s,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function Oc(s){let e=s.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let t=e[1]??"",n=e[2]??"";try{let r=/;base64/i.test(t)?Dc(n):decodeURIComponent(n);return JSON.parse(r)}catch{try{return JSON.parse(n)}catch{return null}}}function Ta(s){let e=s?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=Oc(e);return t?Tt(Gr(t)):null}var Mc=12,Fc=6e3;async function qc(s,e,t){let n=new Array(s.length),r=0,o=new Array(Math.max(1,Math.min(e,s.length))).fill(0).map(async()=>{for(;r<s.length;){let a=r++;n[a]=await t(s[a],a)}});return await Promise.all(o),n}async function Bc(s,e){try{let t=await x.get(s,{timeout:e});if(!t.ok)return null;let n=t.data;if(n&&typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return null}return null}catch{return null}}async function $c(s,e){let t=s?.trim();if(!t)return null;if(/^data:/i.test(t))return Ta(t);let n=wa(t);if(!n)return null;if(ka(n))return n;let r=await Bc(n,e);if(r){let o=Tt(Gr(r));if(o)return o}return null}async function Do(s,e,t){if(e.length===0)return[];let n=t?.concurrency??Mc,r=t?.timeoutMs??Fc,o=await Ns(s,e,t?.rpcUrl);return qc(o,n,a=>$c(a,r))}var va=100,Hc=100,nn="{name}",Aa="{chain}",on=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 D(e)}async run(e,t){let n=j(e.address,t),r=Z(e.chain,t),o=r?[r]:ve(),a=jc(e.contract_address),i=xa(e.collection_name);return a||i?this.listNfts({address:n,chains:o,singleChain:!!r,contract:a,collectionName:i}):this.listCollections({address:n,chains:o,singleChain:!!r,args:e})}async listCollections(e){let{address:t,chains:n,singleChain:r,args:o}=e,a=await Promise.all(n.map(async c=>{let u=await this.service.getWalletNftCollections({address:t,chain:c,limit:va});return{chain:c,rows:u.success?Sa(u.data?.result??[]):[],ok:u.success}}));if(r&&!a[0].ok)return{error:"Failed to fetch wallet NFT collections"};let i=a.flatMap(c=>c.rows.map(u=>({name:Wc(u),contractAddress:u.token_address,chain:v(c.chain),nftCount:u.count??null})));if(i.length===0)return{_instructions:"The wallet holds no NFT collections"+(r?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:t,collectionCount:0,collections:[]};let l=Gc(i,o);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:t,collectionCount:i.length,collections:i,...l.length>0?{actionButtons:l}:{}}}async listNfts(e){let{address:t,chains:n,singleChain:r,contract:o,collectionName:a}=e,i=await Promise.all(n.map(async h=>{let f=await this.service.getWalletNFTs({address:t,chain:h,limit:va,...o?{tokenAddresses:[o]}:{}});return{chain:h,rows:f.success?Sa(f.data?.result??[]):[],ok:f.success}}));if(r&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(h=>h.rows.filter(f=>Vc(f,{contract:o,collectionName:a})).map(f=>({chain:h.chain,row:f})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${a??o??""}"`+(r?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||a||l[0].row.token_address,u=await this.resolveOnchainImages(l),d=l.map(({chain:h,row:f},m)=>{let g=Yc(f);return{name:g.name,tokenId:g.tokenId,contractAddress:g.contractAddress,image:u[m]??g.image,chain:v(h)}});return{ui:{component:"WalletNftList",props:{walletAddress:t,collectionName:c,nfts:d}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:t,collectionName:c,nftCount:l.length}}async resolveOnchainImages(e){let t=new Array(e.length).fill(null),n=new Map;e.forEach((r,o)=>{let a=n.get(r.chain)??[];a.push(o),n.set(r.chain,a)});try{await Promise.all([...n.entries()].map(async([r,o])=>{let a=o.map(l=>({contract:e[l].row.token_address,tokenId:e[l].row.token_id})),i=await Do(r,a);o.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function Sa(s){return s.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function Vc(s,e){if(e.contract)return s.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let t=e.collectionName.toLowerCase();return(s.name??"").toLowerCase().includes(t)}return!1}function Wc(s){let e=s.name?.trim();if(e)return e;let t=s.token_address??"";return t.length>10?`${t.slice(0,6)}\u2026${t.slice(-4)}`:t}function Yc(s){return{name:s.normalized_metadata?.name||s.name||`#${s.token_id}`,tokenId:s.token_id,contractAddress:s.token_address,image:Tt(s.normalized_metadata?.image||s.media?.original_media_url)}}function Gc(s,e){let t=typeof e.pick_button_label=="string"?e.pick_button_label:"",n=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",r=[];for(let o of s){if(r.length>=Hc)break;if(!o.contractAddress)continue;let a=typeof o.chain=="string"?o.chain.trim():"",i=a?`show my ${nn} NFTs on ${Aa}`:`show my ${nn} NFTs`,l=Pa(n,{[nn]:o.name,[Aa]:a},i);a&&!l.includes(a)&&(l=`${l} (${a})`),r.push({label:Kc(t,o.name,nn),prompt:`${l} (${o.contractAddress})`})}return r}function Pa(s,e,t){let n=s&&s.includes(nn)?s:t;for(let[r,o]of Object.entries(e))n=n.split(r).join(o);return n.replace(/\s+/g," ").trim()}function Kc(s,e,t){return Pa(s,{[nn]:e},t)}function xa(s){if(typeof s!="string")return;let e=s.trim();return e||void 0}function jc(s){let e=xa(s);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var zc="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.",Me=class extends A{kind="data";category="nft";llm;constructor(e){super(),this.llm=new J(e??{})}static promptParams(e){return[{name:"prompt",type:"string",description:e,required:!0}]}async run(e){let t=typeof e.prompt=="string"?e.prompt.trim():"";if(!t)return{error:"Missing required parameter: prompt"};let n=await this.askGeminiWithSearch(t);return n?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:n}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(e){let t=Date.now();try{return(await this.llm.chat([{role:"system",content:zc,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var rn=class extends Me{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=Me.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 sn=class extends Me{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=Me.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 Kr={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"},jr="amazon.com";function Xc(s){return s?s.trim().toLowerCase().split(/[-_]/)[0]:""}function zr(s){let e=Xc(s);return Kr[e]??jr}function Oo(s){return`https://${zr(s)}/s?k=NFC%20Tag`}function Mo(s){if(!s)return"";let e=s.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var Qc=720*60*1e3,Ca=new Map,_a=3;function Jc(s){return[`A user in country "${s}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${_a} 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 Zc(s){if(!s)return[];let e=s.indexOf("["),t=s.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let n;try{n=JSON.parse(s.slice(e,t+1))}catch{return[]}if(!Array.isArray(n))return[];let r=[],o=new Set;for(let a of n){if(!a||typeof a!="object")continue;let i=a.label,l=a.url;if(typeof i!="string"||!i.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!o.has(c)&&(o.add(c),r.push({label:i.trim(),url:l.trim()}),r.length>=_a))break}return r}async function Xr(s,e){let t=Mo(s);if(!t||!e)return null;let n=Ca.get(t);if(n&&n.expires>Date.now())return n.links;let r=Date.now(),o=[{role:"user",content:Jc(t),timestamp:r}];try{let a=await e.chat(o,void 0,{googleSearch:!0,maxRetries:1}),i=Zc(a.text);if(i.length)return Ca.set(t,{links:i,expires:Date.now()+Qc}),i}catch{}return null}async function an(s){let e=await Xr(s.country,s.llm);return e&&e.length?e:[{label:"Amazon",url:Oo(s.language)}]}function eu(s){return s.length<=1?s.length===1?`[${s[0].label}](${s[0].url})`:"":s.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
|
|
24
24
|
`)}var Ea=["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(`
|
|
25
|
-
`),
|
|
25
|
+
`),ln=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 J(e))}async run(e,t){let n=typeof e.language=="string"&&e.language.trim()?e.language.trim():void 0,r=await an({country:t?.country,language:n,llm:this.llm}),o=eu(r),a=r.length>1;return{reference:Ea,marketplaceLinks:r,_instructions:`Answer the user's NFC question as a knowledgeable, friendly expert, writing in the USER'S language (translate naturally \u2014 never leave it in English when they wrote another language). Draw on the reference below for the facts (do NOT invent anything beyond it), but write a polished, well-organized answer \u2014 not a terse one-liner. FORMAT: Use short Markdown section headings (bold or "##") and bullet points so it is easy to scan, similar to a great encyclopedia entry. For a broad question like "what is an NFC tag", give a thorough multi-section answer: open with a 1\u20132 sentence plain-language definition, then cover sections such as "How it works", "What's inside", "What it can store", "Common uses", "How to use one", and "Why they're popular" \u2014 include concrete specifics (the 13.56 MHz frequency, chip names + byte capacities, example payloads, numbered steps). Aim for genuinely useful depth, several short paragraphs/lists, not a wall of dense text. For a NARROW question (e.g. only "what can it store" or "how do I write one"), answer just that part in focused detail and skip the unrelated sections. Do not mention tools, this reference, or that anything is canned. AT THE END, add a short closing line telling them where they can buy NFC tags, then include EACH of these exact CLICKABLE Markdown links `+(a?"as a NUMBERED Markdown list (1., 2., 3.), ONE store per line, in this exact order and numbering":"inline")+` (keep every URL byte-for-byte; localize only the visible text; keep the form [text](url)):
|
|
26
26
|
${o}
|
|
27
27
|
Never show a raw URL on its own and never drop a link. Reference:
|
|
28
28
|
|
|
29
29
|
`+Ea}}};function tu(s){return s.length<=1?s.length===1?`[${s[0].label}](${s[0].url})`:"":s.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
|
|
30
|
-
`)}var
|
|
30
|
+
`)}var cn=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 J(e))}async run(e,t){let n=typeof e.language=="string"&&e.language.trim()?e.language.trim():void 0,r=await an({country:t?.country,language:n,llm:this.llm}),o=tu(r),a=r.length>1;return{marketplaceLinks:r,message:a?`You can buy NFC tags here:
|
|
31
31
|
${o}`:`You can buy NFC tags on ${o}.`,_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:
|
|
32
|
-
${o}`}}};var nu="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.",
|
|
32
|
+
${o}`}}};var nu="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.",un=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 J(e??{})}async run(e,t){let n=typeof e.prompt=="string"?e.prompt.trim():"";if(!n)return{error:"Missing required parameter: prompt"};let r=[];t?.walletAddress&&r.push(`- Connected wallet address: ${t.walletAddress}`),t?.chain&&r.push(`- Current chain: ${t.chain}`),r.push("Use this context only when relevant to the question. Do not invent on-chain values.");let o=Date.now(),a=[{role:"system",content:nu,timestamp:o},{role:"system",content:`[USER CONTEXT]
|
|
33
33
|
${r.join(`
|
|
34
34
|
`)}`,timestamp:o},{role:"user",content:n,timestamp:o}];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 ou=`You are a world-class DEX liquidity-pool master and analyst \u2014 the deepest pool expert there is.
|
|
35
35
|
You know everything about liquidity pools across protocols and chains: Uniswap V2/V3/V4, PancakeSwap, Curve, Balancer, SushiSwap, Aerodrome, and more.
|
|
36
36
|
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.
|
|
37
37
|
You answer ANY pool-related question \u2014 conceptual, strategic, comparative, or current-events \u2014 clearly and accurately.
|
|
38
38
|
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.
|
|
39
|
-
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.`,
|
|
39
|
+
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.`,dn=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 J(e??{})}async run(e,t){let n=typeof e.prompt=="string"?e.prompt.trim():"";if(!n)return{error:"Missing required parameter: prompt"};let r=[];t?.walletAddress&&r.push(`- Connected wallet address: ${t.walletAddress}`),t?.chain&&r.push(`- Current chain: ${t.chain}`),r.push("Use this context only when relevant to the question. Do not invent on-chain values.");let o=Date.now(),a=[{role:"system",content:ou,timestamp:o},{role:"system",content:`[USER CONTEXT]
|
|
40
40
|
${r.join(`
|
|
41
41
|
`)}`,timestamp:o},{role:"user",content:n,timestamp:o}];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)}}}};var ru="https://interface.gateway.uniswap.org",su="/v2/uniswap.explore.v1.ExploreStatsService/ExploreStats",Na="/v2/Search.v1.SearchService/SearchTokens",au="/v1/graphql",ot=3,Fo=800,iu={"0x1":"ETHEREUM","0xa":"OPTIMISM","0x38":"BNB","0x89":"POLYGON","0x2105":"BASE","0xa4b1":"ARBITRUM","0xa86a":"AVALANCHE","0xe708":"LINEA"},lu=`query V3Pool($chain: Chain!, $address: String!) {
|
|
42
42
|
v3Pool(chain: $chain, address: $address) {
|
|
@@ -124,7 +124,7 @@ ${La}`,uu=`query V4Pool($chain: Chain!, $poolId: String!) {
|
|
|
124
124
|
__typename
|
|
125
125
|
}
|
|
126
126
|
}
|
|
127
|
-
${La}`,mn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114,"0xe708":59144};function qo(s){return new Promise(e=>setTimeout(e,s))}function Qr(s){if(!s)return 1;let e=s.toLowerCase();return mn[e]??1}function Jr(s){if(!s)return"ETHEREUM";let e=s.toLowerCase();return iu[e]??"ETHEREUM"}function Ra(s,e){if(!s)return[];switch(e){case"V2":return s.poolStatsV2??[];case"V3":return s.poolStatsV3??[];case"V4":return s.poolStatsV4??[]}}function Ua(s,e){switch(e){case"volume1Day":return s.volume1Day?.value??0;case"volume1Week":return s.volume1Week?.value??0;case"volume30Day":return s.volume30Day?.value??0;case"txCount":return s.txCount??0;case"apr":return s.apr??0;default:return s.totalLiquidity?.value??0}}function Ia(s){let e=s.volume1Day?.value,t=s.totalLiquidity?.value;return typeof s.feeTier!="number"||!e||!t?void 0:s.feeTier/1e4*e/t*365}var pe=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??ru).replace(/\/$/,"")}isSupported(e){if(!e)return!1;let t=M(e)??e.toLowerCase();return Object.prototype.hasOwnProperty.call(mn,t)}listSupportedChains(){return Object.keys(mn).filter(e=>_e(e))}async getExploreStats(e){let t=Qr(e?.chain),n=e?.multichain===!0,r=encodeURIComponent(JSON.stringify({chainId:String(t),multichain:n})),o=`${this.baseUrl}${su}?connect=v1&encoding=json&message=${r}`,a="Unknown error";for(let i=1;i<=ot;i++)try{let l=await x.get(o,{headers:{accept:"*/*",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!l.ok)throw new Error(R(l));return{success:!0,data:l.data}}catch(l){a=l instanceof Error?l.message:"Unknown error",i<ot&&await qo(Fo)}return{success:!1,error:a}}async getTopPools(e){let t=e?.protocolVersion??"V3",n=e?.limit&&e.limit>0?Math.floor(e.limit):10,r=e?.sortBy??"tvl",o=await this.getExploreStats({chain:e?.chain,multichain:e?.multichain});return!o.success||!o.data?{success:!1,error:o.error||"Failed to fetch ExploreStats"}:{success:!0,data:Ra(o.data.stats,t).map(l=>({...l,apr:Ia(l),fee24hUsd:l.volume1Day?.value&&l.feeTier?l.feeTier/1e4*l.volume1Day.value:void 0})).sort((l,c)=>Ua(c,r)-Ua(l,r)).slice(0,n)}}async getV3PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V3Pool",query:lu,variables:{chain:Jr(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:cu,variables:{chain:Jr(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:uu,variables:{chain:Jr(e.chain),poolId:t},pickField:"v4Pool"}):{success:!1,error:"V4 poolId is required"}}async fetchPoolDetailGraphQL(e){let t=`${this.baseUrl}${au}`,n=JSON.stringify({operationName:e.operationName,variables:e.variables,query:e.query}),r="Unknown error";for(let o=1;o<=ot;o++)try{let a=await x.post(t,n,{headers:{accept:"*/*","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web","_dd-custom-header-graph-ql-operation-name":e.operationName,"_dd-custom-header-graph-ql-operation-type":"query"}});if(!a.ok)throw new Error(R(a));let i=a.data;if(i.errors)throw new Error(`GraphQL error: ${JSON.stringify(i.errors)}`);let l=i.data?.[e.pickField]??void 0;return l?{success:!0,data:l}:{success:!1,error:"Pool not found"}}catch(a){r=a instanceof Error?a.message:"Unknown error",o<ot&&await qo(Fo)}return{success:!1,error:r}}async searchTokens(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};if(F(t))return{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."};let n=Qr(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,a=`${this.baseUrl}${Na}`,i=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"TOKEN",page:r,size:o}),l="Unknown error";for(let c=1;c<=ot;c++)try{let u=await x.post(a,i,{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(!u.ok)throw new Error(R(u));return{success:!0,data:u.data.tokens??[]}}catch(u){l=u instanceof Error?u.message:"Unknown error",c<ot&&await qo(Fo)}return{success:!1,error:l}}async searchPools(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};let n=Qr(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,a=e.protocolVersion??"V3",i=e.feeTier&&e.feeTier>0?Math.floor(e.feeTier):void 0,l=`${this.baseUrl}${Na}`,c=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"POOL",page:r,size:o}),[u,d]=await Promise.allSettled([this.fetchSearchPools(l,c),this.getExploreStats({chain:e.chain})]);if(u.status==="rejected"||!u.value.success)return{success:!1,error:u.status==="rejected"?String(u.reason):u.value.error??"Failed to search pools"};let p=t.toLowerCase().split(/\s+/).filter(Boolean),h=u.value.data??[];a!=="ALL"&&(h=h.filter(g=>g.protocolVersion===a)),i!=null&&(h=h.filter(g=>g.feeTier===i));let f=new Map;for(let g of h)g.id&&f.set(g.id.toLowerCase(),g);if(d.status==="fulfilled"&&d.value.success&&d.value.data){let g=d.value.data.stats,y=a==="ALL"?["V2","V3","V4"]:[a];for(let b of y)for(let w of Ra(g,b)){if(!w.id||i!=null&&w.feeTier!==i)continue;let k=(w.token0?.symbol??"").toLowerCase(),T=(w.token1?.symbol??"").toLowerCase(),P=(w.token0?.name??"").toLowerCase(),S=(w.token1?.name??"").toLowerCase();if(!p.some(E=>k.includes(E)||T.includes(E)||P.includes(E)||S.includes(E)))continue;let N=Ia(w),C=w.id.toLowerCase(),q=f.get(C);q?f.set(C,{...q,...N!=null?{apr:N}:{},...w.totalLiquidity?.value!=null?{tvlUsd:w.totalLiquidity.value}:{},...w.volume1Day?.value!=null?{volume1DayUsd:w.volume1Day.value}:{},...w.txCount!=null?{txCount:w.txCount}:{}}):f.set(C,{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,...N!=null?{apr:N}:{},...w.totalLiquidity?.value!=null?{tvlUsd:w.totalLiquidity.value}:{},...w.volume1Day?.value!=null?{volume1DayUsd:w.volume1Day.value}:{},...w.txCount!=null?{txCount:w.txCount}:{}})}}return{success:!0,data:Array.from(f.values()).sort((g,y)=>this.matchScore(y,p)-this.matchScore(g,p))}}async fetchSearchPools(e,t){let n="Unknown error";for(let r=1;r<=ot;r++)try{let o=await x.post(e,t,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!o.ok)throw new Error(R(o));return{success:!0,data:o.data.pools??[]}}catch(o){n=o instanceof Error?o.message:"Unknown error",r<ot&&await qo(Fo)}return{success:!1,error:n}}matchScore(e,t){let n=[e.token0?.symbol??"",e.token1?.symbol??""].map(o=>o.toLowerCase()),r=0;for(let o of t){let a=0;for(let i of n)i===o?a=Math.max(a,3):i.startsWith(o)?a=Math.max(a,2):i.includes(o)&&(a=Math.max(a,1));r+=a}return r}};var du={"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"},pu={"0x1":"ethereum","0xa4b1":"arbitrum","0x89":"polygon","0x38":"bsc","0x2105":"base","0xa":"optimism","0xa86a":"avalanche"},mu={"0x1":1,"0xa4b1":42161,"0x89":137,"0x38":56,"0x2105":8453,"0xa":10,"0xa86a":43114},Da={"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"},Oa={100:.01,500:.05,3e3:.3,1e4:1},hu={ethereum:"0x1","arbitrum one":"0xa4b1",arbitrum:"0xa4b1",polygon:"0x89",bsc:"0x38",base:"0x2105",optimism:"0xa","avalanche c-chain":"0xa86a",avalanche:"0xa86a"},gu=300*1e3,re=class{apiKey;subgraphUrls;coinPoolBaseUrl;llamaCache=null;llamaCacheAt=0;constructor(e={}){this.apiKey=e.theGraphApiKey||"4c67ac7a75b21befbd28dc9120c709f1";let t={...du,...e.subgraphUrls||{}};this.subgraphUrls=Object.fromEntries(Object.entries(t).filter(([n])=>_e(n))),this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}resolveChain(e){if(!e)return"0x1";let t=e.toLowerCase();return Da[t]||(this.subgraphUrls[t]?t:"0x1")}isSupported(e){if(!e)return!1;let t=e.toLowerCase(),n=Da[t];return!!(n&&this.subgraphUrls[n])}chainName(e){let t=this.resolveChain(e);return pu[t]||t}numericChainId(e){return mu[this.resolveChain(e)]}listSupportedChains(){return Object.keys(this.subgraphUrls)}async querySubgraph(e,t){let n=this.resolveChain(e),r=this.subgraphUrls[n];if(!r)throw new Error(`No subgraph available for chain: ${e}`);let o=await x.post(r,{query:t},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!o.ok)throw new Error(`Subgraph query failed: ${R(o)}`);let a=o.data;if(a.errors&&a.errors.length>0)throw new Error(`Subgraph error: ${a.errors[0].message||"Unknown"}`);return a.data}poolFragment(){return`
|
|
127
|
+
${La}`,pn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114,"0xe708":59144};function qo(s){return new Promise(e=>setTimeout(e,s))}function Qr(s){if(!s)return 1;let e=s.toLowerCase();return pn[e]??1}function Jr(s){if(!s)return"ETHEREUM";let e=s.toLowerCase();return iu[e]??"ETHEREUM"}function Ra(s,e){if(!s)return[];switch(e){case"V2":return s.poolStatsV2??[];case"V3":return s.poolStatsV3??[];case"V4":return s.poolStatsV4??[]}}function Ua(s,e){switch(e){case"volume1Day":return s.volume1Day?.value??0;case"volume1Week":return s.volume1Week?.value??0;case"volume30Day":return s.volume30Day?.value??0;case"txCount":return s.txCount??0;case"apr":return s.apr??0;default:return s.totalLiquidity?.value??0}}function Ia(s){let e=s.volume1Day?.value,t=s.totalLiquidity?.value;return typeof s.feeTier!="number"||!e||!t?void 0:s.feeTier/1e4*e/t*365}var pe=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??ru).replace(/\/$/,"")}isSupported(e){if(!e)return!1;let t=M(e)??e.toLowerCase();return Object.prototype.hasOwnProperty.call(pn,t)}listSupportedChains(){return Object.keys(pn).filter(e=>_e(e))}async getExploreStats(e){let t=Qr(e?.chain),n=e?.multichain===!0,r=encodeURIComponent(JSON.stringify({chainId:String(t),multichain:n})),o=`${this.baseUrl}${su}?connect=v1&encoding=json&message=${r}`,a="Unknown error";for(let i=1;i<=ot;i++)try{let l=await x.get(o,{headers:{accept:"*/*",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!l.ok)throw new Error(R(l));return{success:!0,data:l.data}}catch(l){a=l instanceof Error?l.message:"Unknown error",i<ot&&await qo(Fo)}return{success:!1,error:a}}async getTopPools(e){let t=e?.protocolVersion??"V3",n=e?.limit&&e.limit>0?Math.floor(e.limit):10,r=e?.sortBy??"tvl",o=await this.getExploreStats({chain:e?.chain,multichain:e?.multichain});return!o.success||!o.data?{success:!1,error:o.error||"Failed to fetch ExploreStats"}:{success:!0,data:Ra(o.data.stats,t).map(l=>({...l,apr:Ia(l),fee24hUsd:l.volume1Day?.value&&l.feeTier?l.feeTier/1e4*l.volume1Day.value:void 0})).sort((l,c)=>Ua(c,r)-Ua(l,r)).slice(0,n)}}async getV3PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V3Pool",query:lu,variables:{chain:Jr(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:cu,variables:{chain:Jr(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:uu,variables:{chain:Jr(e.chain),poolId:t},pickField:"v4Pool"}):{success:!1,error:"V4 poolId is required"}}async fetchPoolDetailGraphQL(e){let t=`${this.baseUrl}${au}`,n=JSON.stringify({operationName:e.operationName,variables:e.variables,query:e.query}),r="Unknown error";for(let o=1;o<=ot;o++)try{let a=await x.post(t,n,{headers:{accept:"*/*","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web","_dd-custom-header-graph-ql-operation-name":e.operationName,"_dd-custom-header-graph-ql-operation-type":"query"}});if(!a.ok)throw new Error(R(a));let i=a.data;if(i.errors)throw new Error(`GraphQL error: ${JSON.stringify(i.errors)}`);let l=i.data?.[e.pickField]??void 0;return l?{success:!0,data:l}:{success:!1,error:"Pool not found"}}catch(a){r=a instanceof Error?a.message:"Unknown error",o<ot&&await qo(Fo)}return{success:!1,error:r}}async searchTokens(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};if(F(t))return{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."};let n=Qr(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,a=`${this.baseUrl}${Na}`,i=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"TOKEN",page:r,size:o}),l="Unknown error";for(let c=1;c<=ot;c++)try{let u=await x.post(a,i,{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(!u.ok)throw new Error(R(u));return{success:!0,data:u.data.tokens??[]}}catch(u){l=u instanceof Error?u.message:"Unknown error",c<ot&&await qo(Fo)}return{success:!1,error:l}}async searchPools(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};let n=Qr(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,a=e.protocolVersion??"V3",i=e.feeTier&&e.feeTier>0?Math.floor(e.feeTier):void 0,l=`${this.baseUrl}${Na}`,c=JSON.stringify({searchQuery:t,chainIds:[n],searchType:"POOL",page:r,size:o}),[u,d]=await Promise.allSettled([this.fetchSearchPools(l,c),this.getExploreStats({chain:e.chain})]);if(u.status==="rejected"||!u.value.success)return{success:!1,error:u.status==="rejected"?String(u.reason):u.value.error??"Failed to search pools"};let p=t.toLowerCase().split(/\s+/).filter(Boolean),h=u.value.data??[];a!=="ALL"&&(h=h.filter(g=>g.protocolVersion===a)),i!=null&&(h=h.filter(g=>g.feeTier===i));let f=new Map;for(let g of h)g.id&&f.set(g.id.toLowerCase(),g);if(d.status==="fulfilled"&&d.value.success&&d.value.data){let g=d.value.data.stats,y=a==="ALL"?["V2","V3","V4"]:[a];for(let b of y)for(let w of Ra(g,b)){if(!w.id||i!=null&&w.feeTier!==i)continue;let k=(w.token0?.symbol??"").toLowerCase(),T=(w.token1?.symbol??"").toLowerCase(),P=(w.token0?.name??"").toLowerCase(),S=(w.token1?.name??"").toLowerCase();if(!p.some(E=>k.includes(E)||T.includes(E)||P.includes(E)||S.includes(E)))continue;let N=Ia(w),C=w.id.toLowerCase(),q=f.get(C);q?f.set(C,{...q,...N!=null?{apr:N}:{},...w.totalLiquidity?.value!=null?{tvlUsd:w.totalLiquidity.value}:{},...w.volume1Day?.value!=null?{volume1DayUsd:w.volume1Day.value}:{},...w.txCount!=null?{txCount:w.txCount}:{}}):f.set(C,{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,...N!=null?{apr:N}:{},...w.totalLiquidity?.value!=null?{tvlUsd:w.totalLiquidity.value}:{},...w.volume1Day?.value!=null?{volume1DayUsd:w.volume1Day.value}:{},...w.txCount!=null?{txCount:w.txCount}:{}})}}return{success:!0,data:Array.from(f.values()).sort((g,y)=>this.matchScore(y,p)-this.matchScore(g,p))}}async fetchSearchPools(e,t){let n="Unknown error";for(let r=1;r<=ot;r++)try{let o=await x.post(e,t,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!o.ok)throw new Error(R(o));return{success:!0,data:o.data.pools??[]}}catch(o){n=o instanceof Error?o.message:"Unknown error",r<ot&&await qo(Fo)}return{success:!1,error:n}}matchScore(e,t){let n=[e.token0?.symbol??"",e.token1?.symbol??""].map(o=>o.toLowerCase()),r=0;for(let o of t){let a=0;for(let i of n)i===o?a=Math.max(a,3):i.startsWith(o)?a=Math.max(a,2):i.includes(o)&&(a=Math.max(a,1));r+=a}return r}};var du={"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"},pu={"0x1":"ethereum","0xa4b1":"arbitrum","0x89":"polygon","0x38":"bsc","0x2105":"base","0xa":"optimism","0xa86a":"avalanche"},mu={"0x1":1,"0xa4b1":42161,"0x89":137,"0x38":56,"0x2105":8453,"0xa":10,"0xa86a":43114},Da={"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"},Oa={100:.01,500:.05,3e3:.3,1e4:1},hu={ethereum:"0x1","arbitrum one":"0xa4b1",arbitrum:"0xa4b1",polygon:"0x89",bsc:"0x38",base:"0x2105",optimism:"0xa","avalanche c-chain":"0xa86a",avalanche:"0xa86a"},gu=300*1e3,re=class{apiKey;subgraphUrls;coinPoolBaseUrl;llamaCache=null;llamaCacheAt=0;constructor(e={}){this.apiKey=e.theGraphApiKey||"4c67ac7a75b21befbd28dc9120c709f1";let t={...du,...e.subgraphUrls||{}};this.subgraphUrls=Object.fromEntries(Object.entries(t).filter(([n])=>_e(n))),this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}resolveChain(e){if(!e)return"0x1";let t=e.toLowerCase();return Da[t]||(this.subgraphUrls[t]?t:"0x1")}isSupported(e){if(!e)return!1;let t=e.toLowerCase(),n=Da[t];return!!(n&&this.subgraphUrls[n])}chainName(e){let t=this.resolveChain(e);return pu[t]||t}numericChainId(e){return mu[this.resolveChain(e)]}listSupportedChains(){return Object.keys(this.subgraphUrls)}async querySubgraph(e,t){let n=this.resolveChain(e),r=this.subgraphUrls[n];if(!r)throw new Error(`No subgraph available for chain: ${e}`);let o=await x.post(r,{query:t},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!o.ok)throw new Error(`Subgraph query failed: ${R(o)}`);let a=o.data;if(a.errors&&a.errors.length>0)throw new Error(`Subgraph error: ${a.errors[0].message||"Unknown"}`);return a.data}poolFragment(){return`
|
|
128
128
|
id
|
|
129
129
|
token0 { id symbol name }
|
|
130
130
|
token1 { id symbol name }
|
|
@@ -183,27 +183,27 @@ ${La}`,mn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0
|
|
|
183
183
|
${this.poolFragment()}
|
|
184
184
|
}
|
|
185
185
|
}
|
|
186
|
-
}`,r=await this.querySubgraph(t,n);if(!r?.position?.pool)return null;let o=r.position,a=this.mapPool(o.pool,t),i=await this.fetchDefiLlamaUniswap(),l=i.length>0?this.enrichWithLlama([a],i)[0]:a,c=l.feeTierBps,u=l.feeTierPercent;return{position:{positionId:o.id,poolAddress:l.poolAddress,pair:l.pair,token0:{symbol:l.token0.symbol,address:l.token0.address},token1:{symbol:l.token1.symbol,address:l.token1.address},feeTierBps:c,feeTierPercent:u,chain:l.chain,liquidity:o.liquidity,depositedToken0:o.depositedToken0,depositedToken1:o.depositedToken1,withdrawnToken0:o.withdrawnToken0,withdrawnToken1:o.withdrawnToken1,collectedFeesToken0:o.collectedFeesToken0,collectedFeesToken1:o.collectedFeesToken1},pool:l}}async getCoinPoolPairs(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let r=(await this.fetchCoinPoolV2Items(t)).map(o=>this.mapCoinPoolV2Item(o)).filter(o=>o!==null);if(e.tokens&&e.tokens.length>=2){let o=e.tokens[0].toUpperCase(),a=e.tokens[1].toUpperCase();r=r.filter(i=>{let[l="",c=""]=i.pair.toUpperCase().split("/");return l.includes(o)&&c.includes(a)||l.includes(a)&&c.includes(o)})}return r}async getCoinPoolByAddress(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let n=e.poolAddress.toLowerCase();return(await this.fetchCoinPoolV2Items(t)).filter(o=>o.poolId?.toLowerCase()===n).map(o=>this.mapCoinPoolV2Item(o)).filter(o=>o!==null).sort((o,a)=>(a.apr??-1/0)-(o.apr??-1/0))}async fetchCoinPoolV2Items(e){if(!this.coinPoolBaseUrl)return[];try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,n=await x.get(t);if(!n.ok)throw new Error(R(n));return n.data?.data?.items||[]}catch{return[]}}mapCoinPoolV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,n=e.token1.decimal??18,r=P=>P==null||!Number.isFinite(P)?0:Math.pow(1.0001,P)*Math.pow(10,t-n),o=r(e.minTick),a=r(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,u=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),d=u?o:a>0?1/a:0,p=u?a:o>0?1/o:0,h=u?c:c>0?1/c:0,f=u?e.token0.symbol:e.token1.symbol,m=u?e.token1.symbol:e.token0.symbol;if(!h||!d&&!p)return null;let g=Math.min(d,p),y=Math.max(d,p);if(h<g||h>y)return null;let b=Number(e.fee),w=Oa[b]??b/1e4,k=typeof e.apr=="number"?e.apr:typeof e.aprAvg=="number"?e.aprAvg:null,T=typeof e.aprAvg=="number"?e.aprAvg:null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:T,token0Price:i,token1Price:l,priceRange:{minPrice:ne(d),maxPrice:ne(p),currentPrice:ne(h),baseToken:f,quoteToken:m}}}};var rt=class{config;constructor(e){this.config=e}hasIntegratedApproval(){return!1}};var fu="https://exchange-api.keyring.app/admin/setting?configs=others",yu="https://api.coinpool.app/config/bridgeProviderByChain",bu="https://coinpool-api-op.bacoor-test001.xyz/config/bridgeProviderByChain";function wu(s){let e=null,t=null;return async()=>e||t||(t=(async()=>{try{return e=await s(),e}catch{return null}finally{t=null}})(),t)}async function Fa(s){return(await x.get(s,{headers:{Accept:"application/json"}})).data}var ku=wu(async()=>(await Fa(fu))?.others??null),Bo={prod:null,dev:null},ao={prod:null,dev:null};async function Tu(s){let e=s?"prod":"dev";if(Bo[e])return Bo[e];if(ao[e])return ao[e];let t=s?yu:bu;return ao[e]=(async()=>{try{let n=await Fa(t);return Bo[e]=n?.data??null,Bo[e]}catch{return null}finally{ao[e]=null}})(),ao[e]}function vu(s){if(!s)return null;try{let e=JSON.parse(s);return e&&typeof e=="object"?e:null}catch{return null}}function Ma(s){if(s==null)return 0;let e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:0}function Au(s){return s==="debridge"||s==="relay"}async function $o(s,e){let n=(await Tu(e))?.[String(s)];return Au(n)?n:null}async function hn(s,e){let t=await ku();if(!t)return null;let n,r;if(s==="debridge")n=vu(t.affiliateRecipient)?.[String(e)],r=Ma(t.AFFILIATE_FEE_PERENT);else if(s==="relay")n=t.RELAY_AFFILIATE_FEE_RECIPIENT,r=Ma(t.RELAY_AFFILIATE_FEE_PERCENT);else return null;return!n||r<=0?null:{affiliateFeeRecipient:n,affiliateFeePercent:r}}var Su="https://dln.debridge.finance/v1.0",Pu="0x0000000000000000000000000000000000000000",xu=new Set([429,500]),Cu=5,_u=1e3,Eu=s=>new Promise(e=>setTimeout(e,s)),gn=class extends rt{apiBaseUrl;accessToken;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Su,this.accessToken=e.accessToken??"d6c45897b8f6"}getProviderName(){return"debridge"}hasIntegratedApproval(){return!1}async getQuote(e){let{srcChainId:t,srcTokenAddress:n,srcTokenAmount:r,dstChainId:o,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c,isCrossChain:u}=e,d=u??t!==o,p=await hn(this.getProviderName(),t);try{if(d){let m={srcChainId:String(t),srcChainTokenIn:n,srcChainTokenInAmount:r,dstChainId:String(o),dstChainTokenOut:a,dstChainTokenOutRecipient:i,srcChainOrderAuthorityAddress:l,dstChainOrderAuthorityAddress:i,accesstoken:this.accessToken};p&&(m.affiliateFeeRecipient=p.affiliateFeeRecipient,m.affiliateFeePercent=p.affiliateFeePercent);let g=await this.get(`${this.apiBaseUrl}/dln/order/create-tx`,m);return g.error||g.errorMessage?{success:!1,error:g.error??g.errorMessage,errorMessage:g.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:g.tx,estimation:g.estimation,isCrossChain:!0,srcChainId:t,dstChainId:o,raw:g}}let h={chainId:String(t),tokenIn:n,tokenInAmount:r,tokenOut:a,tokenOutRecipient:i,accesstoken:this.accessToken};p&&(h.affiliateFeeRecipient=p.affiliateFeeRecipient,h.affiliateFeePercent=p.affiliateFeePercent),c!==void 0&&(h.slippage=c);let f=await this.get(`${this.apiBaseUrl}/chain/transaction`,h);return f.error||f.errorMessage?{success:!1,error:f.error??f.errorMessage,errorMessage:f.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:f.tx,isCrossChain:!1,srcChainId:t,dstChainId:t,raw:f}}catch(h){return{success:!1,error:h,errorMessage:h instanceof Error?h.message:"Failed to fetch quote"}}}async checkApproval(e){let{chain:t,userAddress:n,tokenAddress:r,amount:o}=e,a=e.quoteData?.tx?.to;if(!a)return{isNeeded:!1,error:"No contract address found in quote"};if(!r||r.toLowerCase()===Pu)return{isNeeded:!1,integrated:!1,contractAddress:a,message:"Native coin needs no approval."};let i=await this.readAllowance(t,r,n,a);if(i===null)return{isNeeded:!0,integrated:!1,contractAddress:a,message:"Could not read allowance; approval required before the swap."};let l;try{l=BigInt(o)}catch{l=0n}return i>=l?{isNeeded:!1,integrated:!1,contractAddress:a,message:"Sufficient allowance already granted."}:{isNeeded:!0,integrated:!1,contractAddress:a,message:"Approval required: current allowance is below the swap amount."}}async readAllowance(e,t,n,r){if(!e)return null;let o=l=>l.toLowerCase().replace(/^0x/,"").padStart(64,"0"),a=`0xdd62ed3e${o(n)}${o(r)}`,i=await Tr(e,t,a);if(typeof i!="string"||!/^0x[0-9a-fA-F]*$/.test(i)||i==="0x")return null;try{return BigInt(i)}catch{return null}}async executeSwap(e){let{quoteData:t}=e;return{success:!0,provider:"debridge",txData:t.tx??void 0,estimation:t.estimation}}async trackTransaction(e){let{requestIdOrTxHash:t}=e;try{let n=await this.get(`${this.apiBaseUrl}/dln/tx/${t}/order-ids`,{accesstoken:this.accessToken});if(!n.orderIds?.length)return{success:!1,status:"PENDING"};let r=n.orderIds[0];switch(((await this.get(`${this.apiBaseUrl}/dln/order/${r}/status`,{accesstoken:this.accessToken})).status??"").toUpperCase()){case"FULFILLED":case"SENTUNLOCK":case"CLAIMEDUNLOCK":return{success:!0,status:"COMPLETED"};case"ORDERCANCELLED":case"SENTORDERCANCEL":case"CLAIMEDORDERCANCEL":return{success:!0,status:"FAILED"};default:return{success:!0,status:"PENDING"}}}catch(n){return{success:!1,status:"ERROR",error:n instanceof Error?n.message:String(n)}}}async get(e,t){let n=Object.entries(t).map(([a,i])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(i))}`).join("&"),r=n?`${e}?${n}`:e,o=await x.get(r,{headers:{Accept:"application/json"}});for(let a=0;a<Cu&&xu.has(o.status);a++)await Eu(_u),o=await x.get(r,{headers:{Accept:"application/json"}});return o.data}};var Nu="https://api.relay.link";function qa(s){return s===7565164||s==="7565164"?792703809:s}var fn=class extends rt{apiBaseUrl;apiKey;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Nu,this.apiKey=e.apiKey}getProviderName(){return"relay"}hasIntegratedApproval(){return!0}async getQuote(e){let{srcChainId:t,srcTokenAddress:n,srcTokenAmount:r,dstChainId:o,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c}=e,u=await hn(this.getProviderName(),t),d={user:i||l,originChainId:qa(t),destinationChainId:qa(o),originCurrency:n,destinationCurrency:a,amount:r,recipient:i||l,tradeType:"EXACT_INPUT"};u&&(d.appFees=[{recipient:u.affiliateFeeRecipient,fee:Math.floor(u.affiliateFeePercent*100)}]),typeof c=="number"&&Number.isFinite(c)&&(d.slippageTolerance=Math.floor(c*100).toString());try{let p=await this.request("/quote/v2","POST",d);if(!p||p.error)return{success:!1,error:p?.error??"Unknown error",errorMessage:p?.message??"Failed to fetch quote from Relay"};let h=p.steps?.find(b=>b.id==="approve"),f=p.steps?.find(b=>b.id==="swap"||b.id==="deposit"),m=f?.items?.[0]?.data,g=Array.isArray(m?.instructions);return{success:!0,provider:"relay",tx:m?g?{data:{instructions:m.instructions??[],addressLookupTableAddresses:m.addressLookupTableAddresses??[]},chainId:m.chainId}:{from:m.from,to:m.to,data:m.data,value:m.value,chainId:m.chainId,maxFeePerGas:m.maxFeePerGas,maxPriorityFeePerGas:m.maxPriorityFeePerGas}:null,isCrossChain:t!==o,srcChainId:t,dstChainId:o,raw:{steps:p.steps,fees:p.fees,details:p.details,approveStep:h,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?.approveStep;if(t){let n=t.items?.[0]?.data;return{isNeeded:!0,integrated:!0,approvalData:n,contractAddress:n?.to,message:"Approval step is included in quote and will be executed first."}}return{isNeeded:!1,integrated:!0,message:"No approval needed or already approved"}}async executeSwap(e){let{quoteData:t}=e,n=t.raw;return n?.steps?{success:!0,provider:"relay",steps:n.steps,estimation:t.estimation}:{success:!1,error:"Invalid quote data"}}async trackTransaction(e){try{let n=(await this.request("/intents/status/v3","GET",{requestId:e.requestIdOrTxHash})).status??"";return n==="success"||n==="refunded"?{success:!0,status:"COMPLETED"}:n==="failure"||n==="expired"?{success:!0,status:"FAILED"}:{success:!0,status:"PENDING"}}catch(t){return{success:!1,status:"ERROR",error:t instanceof Error?t.message:String(t)}}}async request(e,t,n){let r={"Content-Type":"application/json"};this.apiKey&&(r["x-api-key"]=this.apiKey);let o=`${this.apiBaseUrl}${e}`,a;if(t==="GET"&&n){let l=Object.entries(n).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(String(u))}`).join("&");o=`${o}?${l}`}else t==="POST"&&n&&(a=n);let i=await x.request(t,o,a,{headers:r});if(!i.ok)throw new Error(R(i));return i.data}};var Ho={debridge:{apiBaseUrl:"https://dln.debridge.finance/v1.0",accessToken:"d6c45897b8f6"},relay:{apiBaseUrl:"https://api.relay.link"}},io="debridge";function Ru(s){if(s==null)return null;let e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:null}var At=class{providerConfig;isProduction;cache=new Map;constructor(e=Ho,t=!0){this.providerConfig=e,this.isProduction=t}async getService(e){let t=await this.getActiveProvider(e),n=this.cache.get(t);if(n)return n;let r=this.createService(t);return this.cache.set(t,r),r}async getServiceByProvider(e){let t=this.cache.get(e);if(t)return t;let n=this.createService(e);return this.cache.set(e,n),n}async getActiveProvider(e){let t=Ru(e);return t===null?io:await $o(t,this.isProduction)??io}async isProviderActive(e,t){return await this.getActiveProvider(t)===e}getAvailableProviders(){return Object.keys(this.providerConfig)}clearCache(){this.cache.clear()}createService(e){let t=this.providerConfig[e]??{};switch(e){case"debridge":return new gn(t);case"relay":return new fn(t);default:{let n=e;throw new Error(`Unknown swap provider: ${String(n)}`)}}}},Fe=new At;var Uu="https://api.coinpool.app/config/addresses",Iu="https://coinpool-api-op.bacoor-test001.xyz/config/addresses",Vo={prod:null,dev:null},lo={prod:null,dev:null};async function Ba(s){let e=s?"prod":"dev";if(Vo[e])return Vo[e];if(lo[e])return lo[e];let t=s?Uu:Iu;return lo[e]=(async()=>{try{let r=(await x.get(t,{headers:{Accept:"application/json"}})).data;return Vo[e]=r?.data??null,Vo[e]}catch{return null}finally{lo[e]=null}})(),lo[e]}function Lu(s){let e=s.trim();if(/^0x[0-9a-fA-F]+$/.test(e)){let t=Number.parseInt(e,16);return Number.isFinite(t)?String(t):null}return/^\d+$/.test(e)?e:null}async function $a(s,e,t){let n=await Ba(t);if(!n)return;let r=Lu(e);if(!r)return;let o=n[s]?.[r];return Array.isArray(o)?o[0]:typeof o=="string"?o:void 0}async function Wo(s,e){return $a("createPoolProxyV3",s,e)}var Du=/^0x[0-9a-fA-F]{40}$/;async function Ou(s,e){let n=(await Ba(e))?.[s];if(!n||typeof n!="object")return[];let r=[];for(let[o,a]of Object.entries(n)){let i=Array.isArray(a)?a[0]:a;typeof i=="string"&&Du.test(i.trim())&&r.push(o)}return r}async function Yo(s){return Ou("createPoolProxyV3",s)}async function Go(s,e){return $a("nftPositionUniswap",s,e)}var $="0x0000000000000000000000000000000000000000",Ha={"0x1":{hexId:"0x1",name:"Ethereum",defaultRpc:ke["0x1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa":{hexId:"0xa",name:"Optimism",defaultRpc:ke["0xa"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0x38":{hexId:"0x38",name:"BNB Smart Chain",defaultRpc:ke["0x38"],native:{symbol:"BNB",name:"BNB",decimals:18,coingeckoId:"binancecoin"},defaultMintGasLimit:12e5},"0x89":{hexId:"0x89",name:"Polygon",defaultRpc:ke["0x89"],native:{symbol:"POL",name:"Polygon",decimals:18,coingeckoId:"matic-network"},defaultMintGasLimit:12e5},"0x2105":{hexId:"0x2105",name:"Base",defaultRpc:ke["0x2105"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa4b1":{hexId:"0xa4b1",name:"Arbitrum One",defaultRpc:ke["0xa4b1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:22e5},"0xa86a":{hexId:"0xa86a",name:"Avalanche",defaultRpc:ke["0xa86a"],native:{symbol:"AVAX",name:"Avalanche",decimals:18,coingeckoId:"avalanche-2"},defaultMintGasLimit:12e5},"0xe708":{hexId:"0xe708",name:"Linea",defaultRpc:ke["0xe708"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5}};function se(s){return Ha[s.toLowerCase()]}function yn(s){return se(s)?.native}var Va="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";function Zr(s){let e=s.stableTicks??3,t=s.widePercent??{down:50,up:100},n=Ce(s.currentTick,s.token0Decimals,s.token1Decimals),r=De(Le(s.currentTick-e*s.tickSpacing,s.tickSpacing,"down")),o=De(Le(s.currentTick+e*s.tickSpacing,s.tickSpacing,"up")),a=n*(1-t.down/100),i=n*(1+t.up/100),l=ht(a,s.token0Decimals,s.token1Decimals),c=ht(i,s.token0Decimals,s.token1Decimals),u=De(Le(l,s.tickSpacing,"down")),d=De(Le(c,s.tickSpacing,"up")),p=(h,f,m,g,y)=>{let b=Ce(g,s.token0Decimals,s.token1Decimals),w=Ce(y,s.token0Decimals,s.token1Decimals);return{id:h,label:f,description:m,tickLower:g,tickUpper:y,minPrice:b,maxPrice:w,minPercentChange:(b-n)/n*100,maxPercentChange:(w-n)/n*100}};return[p("stable","Stable","Good for stablecoins or low volatility pairs",r,o),p("wide","Wide","Good for volatile pairs",u,d)]}var Mu=K("slot0()"),Fu=K("liquidity()"),qu=K("tickSpacing()"),Bu=K("fee()"),$u=K("token0()"),Hu=K("token1()"),Vu=K("decimals()"),de=class{swapFactory;isProduction;constructor(e){this.isProduction=e?.isProduction??!0,this.swapFactory=e?.swapFactory??(this.isProduction?Fe:new At(void 0,!1))}isSupported(e){if(!e)return!1;let t=M(e)??e.toLowerCase();return!!se(t)}listSupportedChains(){return Object.keys(Ha).filter(e=>_e(e))}getRpcUrl(e){let t=Xe(e);if(t)return t;let n=se(e);if(!n)throw new Error(`Unsupported chain: ${e}`);return n.defaultRpc}async getGatewayAddress(e){return Wo(e,this.isProduction)}async isAddLiquiditySupported(e){return this.isSupported(e)&&!!await this.getGatewayAddress(e)}async listAddLiquiditySupportedChains(){let e=await Yo(this.isProduction),t=[];for(let n of e){let r=M(n);r&&se(r)&&!t.includes(r)&&t.push(r)}return t.length>0?t:this.listSupportedChains()}async getPositionManagerAddress(e){return Go(e,this.isProduction)}async ethCall(e,t,n){return He(this.getRpcUrl(e),"eth_call",[{to:t,data:n},"latest"])}async getNativeBalance(e,t){let n=await He(this.getRpcUrl(e),"eth_getBalance",[t,"latest"]);return BigInt(n)}async getGasPrice(e){let t=await He(this.getRpcUrl(e),"eth_gasPrice",[]);return BigInt(t)}async getTransactionReceipt(e,t){return await He(this.getRpcUrl(e),"eth_getTransactionReceipt",[t])}async extractMintedNftId(e,t){let n=await this.getPositionManagerAddress(e);if(!n)return null;let r=n.toLowerCase();for(let o of t.logs??[]){if((o.address??"").toLowerCase()!==r)continue;let a=o.topics??[];if(!(a.length<4||a[0]?.toLowerCase()!==Va||"0x"+a[1].slice(-40).toLowerCase()!==$))try{return BigInt(a[3]).toString()}catch{return null}}return null}async estimateGasReserveWei(e){let t=se(e);if(!t)throw new Error(`Unsupported chain: ${e}`);let n=await this.getGasPrice(e);return BigInt(t.defaultMintGasLimit)*n*18n/10n}async readPoolOnchain(e,t){let[n,r,o,a,i,l]=await Promise.all([this.ethCall(e,t,Mu),this.ethCall(e,t,Fu),this.ethCall(e,t,qu),this.ethCall(e,t,Bu),this.ethCall(e,t,$u),this.ethCall(e,t,Hu)]),c=G(n),u=Oe(c,0),d=br(c,64),p=Oe(G(r),0),h=Number(br(G(o),0)),f=Number(Oe(G(a),0)),m=wr(G(i),0),g=wr(G(l),0),[y,b]=await Promise.all([this.readErc20Decimals(e,m),this.readErc20Decimals(e,g)]),w=Ss(u,y,b);return{poolAddress:t,chainId:e,fee:f,tickSpacing:h,liquidity:p,sqrtPriceX96:u,currentTick:d,token0:m,token1:g,currentPrice:w}}async readErc20Decimals(e,t){if(t.toLowerCase()===$)return 18;let n=await this.ethCall(e,t,Vu);return Number(Oe(G(n),0))}async getNativePriceUsd(e){let t=se(e);if(!t)return null;try{let n=`https://api.coingecko.com/api/v3/simple/price?ids=${t.native.coingeckoId}&vs_currencies=usd`,r=await x.get(n);if(!r.ok)return null;let a=r.data[t.native.coingeckoId]?.usd;return typeof a=="number"?a:null}catch{return null}}splitNativeAmountForRange(e){let{nativeAmountWei:t,pool:n,tickLower:r,tickUpper:o,token0Decimals:a,token1Decimals:i}=e,l=2**96,c=Number(n.sqrtPriceX96)/l,u=Math.pow(1.0001,r/2),d=Math.pow(1.0001,o/2);if(c<=u)return{ratio0:1,ratio1:0,amountInFor0Wei:t,amountInFor1Wei:0n};if(c>=d)return{ratio0:0,ratio1:1,amountInFor0Wei:0n,amountInFor1Wei:t};let p=1/c-1/d,h=c-u,f=c*c,m=p*f,y=m+h;if(!Number.isFinite(y)||y<=0)throw new Error("splitNativeAmountForRange: invalid total value");let b=m/y,w=1-b,k=1000000000000000n,T=BigInt(Math.floor(b*Number(k))),P=t*T/k,S=t-P;return{ratio0:b,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 r=await(await this.swapFactory.getService(t)).getQuote({srcChainId:t,srcTokenAddress:e.tokenIn,srcTokenAmount:e.tokenInAmount,dstChainId:t,dstTokenAddress:e.tokenOut,recipientAddress:e.tokenOutRecipient,senderAddress:e.senderAddress??e.tokenOutRecipient,slippage:e.slippage,isCrossChain:!1});if(!r.success||!r.tx)throw new Error(r.errorMessage??"Swap quote failed");let o=r.tx;if(!o.to||typeof o.data!="string")throw new Error("Swap quote returned an unsupported tx shape (non-EVM payload?)");let a=r.raw??{},i=a.tokenOut?.minAmount??a.details?.currencyOut?.minimumAmount??"0";return{to:o.to,data:o.data,value:o.value??"0",minAmountOut:i}}encodeMintCalldata(e){if(e.paymentInfo.length!==2||e.exchanges.length!==2)throw new Error("encodeMintCalldata: paymentInfo and exchanges must each have length 2");let t=K("mint((address,uint256,address,uint256)[2],(address,bytes,uint256)[2],(uint24,uint256,uint256,int24,int24))"),n=e.paymentInfo.map(f=>ze(f.tokenIn)+ae(f.tokenInAmount)+ze(f.tokenOut)+ae(f.tokenOutAmount)).join(""),o=e.exchanges.map(f=>{let m=G(f.data||"0x"),g=m.length/2,y=ae(g),b=(64-m.length%64)%64,w=m+"0".repeat(b);return{head:ze(f.to)+ae(96)+ae(f.value),body:y+w}}).map(f=>f.head+f.body),a=o.length*32,i=[];for(let f of o)i.push(ae(a)),a+=f.length/2;let l=i.join("")+o.join(""),c=ae(e.fee,24)+ae(e.amount0Min)+ae(e.amount1Min)+yr(e.tickLower)+yr(e.tickUpper),p=256+32+160,h=n+ae(p)+c+l;return t+h}_keccak(e){return Ps(e)}};var Wu={"0x1":"ethereum","0xa":"optimism","0x38":"bnb","0x89":"polygon","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avalanche"},Yu=/^0x[a-fA-F0-9]{40}$/;function Gu(s,e){if(typeof s!="string"||typeof e!="string")return null;let t=Wu[s.toLowerCase()];return!t||!Yu.test(e)?null:`https://app.uniswap.org/explore/pools/${t}/${e}`}function Ee(s,e){let t=Gu(s,e);return t?{uniswapUrl:t}:{}}var Wa=Object.keys(mn),Ae="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 me(){return Wa.filter(s=>_e(s)).map(s=>v(s)).join(", ")}function Se(){return{kind:"info",async listSupported(){return Wa.filter(s=>_e(s))},async isSupported(s){if(!s)return!1;let e=M(s)??s.toLowerCase();return Object.prototype.hasOwnProperty.call(mn,e)}}}function bn(s){return{kind:"add-liquidity",listSupported:()=>s.listAddLiquiditySupportedChains(),isSupported:e=>s.isAddLiquiditySupported(e)}}function es(s,e,t){let n=r=>typeof r=="string"&&r.trim()!=="";if(n(s))return M(s)??s.trim();if(n(e?.chain))return M(e.chain)??e.chain.trim();if(n(e?.walletAddress))throw new Q(typeof e?.query=="string"?e.query:void 0,t);return Te}async function he(s,e,t){let n=await s.listSupported(),r=es(e,t,n);return await s.isSupported(r)?{ok:!0,chain:r}:{ok:!1,result:ts(r,n,s.kind)}}function ts(s,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:v(s),supportedChains:e.map(r=>v(r))}}var Ko="{pair}";var st=[{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 yourself \u2014 the chain these pools are on is appended automatically.`,required:!1}],Ne=' 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 Re(s,e,t){return ns(s,typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",t)}function ns(s,e,t,n){let r=typeof n=="string"&&n.trim()?` (${n.trim()})`:"",o=[];for(let a of s){if(o.length>=5)break;let i=a.token0?.symbol?.trim(),l=a.token1?.symbol?.trim();if(!i||!l)continue;let c=Ku(i,l,a.feeTierPercent);o.push({label:Ya(e,c,`Add liquidity to ${Ko}`),prompt:Ya(t,c,`add liquidity to ${Ko}`)+r})}return o}function Ku(s,e,t){let n=`${s}/${e}`;return typeof t=="number"&&Number.isFinite(t)?`${n} ${ju(t)}%`:n}function ju(s){return Number(s.toFixed(4)).toString()}function Ya(s,e,t){return(s&&s.includes(Ko)?s:t).split(Ko).join(e).replace(/\s+/g," ").trim()}var fe="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. ",ye="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. \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. ",be="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. ",ie="End with a brief reminder that yields fluctuate and concentrated LPs face impermanent loss (informational, not financial advice). ",Ue=`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 zu=["tvl","volume1Day","volume1Week","volume30Day","txCount","apr"],Xu=["V2","V3","V4"],wn=class extends A{name="get-top-pools";description=`List the top Uniswap liquidity pools on a given EVM chain, ranked by TVL by default. Returns each pool's address, fee tier, protocol version, both tokens (symbol, name, address, decimals), TVL, transaction count, and rolling volume buckets (1d / 1w / 30d). 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 (ExploreStats gateway). Supports: `+me();category="blockchain-data";parameters=[{name:"chain",type:"string",description:Ae,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", "volume1Week", "volume30Day", "txCount", or "apr" (estimated annualized fee yield). 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},...st];service;subgraphFallback;pool;constructor(e,t){super(),this.service=new pe(e),this.subgraphFallback=new re(t),this.pool=new de({isProduction:e?.isProduction})}async run(e,t){let n=e.forAddLiquidity===!0,r=n?bn(this.pool):Se(),o=await r.listSupported(),a=es(e.chain,t,o),i=this.parseProtocolVersion(e.protocolVersion),l=this.parseSortKey(e.sortBy),c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,u=!n&&e.multichain===!0;if(!u&&!await r.isSupported(a))return ts(a,o,r.kind);let d=await this.service.getTopPools({chain:a,protocolVersion:i,sortBy:l,limit:c,multichain:u});if(!d.success)return{error:d.error||"Failed to fetch top pools"};let p=(d.data??[]).map(w=>this.formatPool(w)),h="uniswap";if(p.length===0&&i==="V3"){let w=await this.fetchV3Fallback(a,l,c);w.length>0&&(p=w,h="subgraph")}let f=p.map(w=>this.withExpertSignals(w)),m=await this.pool.isAddLiquiditySupported(a)?Re(f,e,v(a)):[],g=h==="subgraph",y=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). `:"")+fe+`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, ${y}, 24h fee revenue, 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. `+ye+"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. "+be+ie+"Mention the chain and the sort metric in the intro line. "+Ue+(m.length>0?Ne:""),chain:a,protocolVersion:i,sortBy:l,source:h,count:f.length,pools:f.map(w=>({...w,...Ee(a,w.address)})),...m.length>0?{actionButtons:m}:{}}}withExpertSignals(e){let t=e.tvlUsd,n=e.volume1DayUsd,r=typeof t=="number"&&t>0&&typeof n=="number"?Math.round(n/t*1e3)/1e3:void 0;return{...e,volumeToTvlRatio:r}}async fetchV3Fallback(e,t,n){try{return(await this.subgraphFallback.getTrendingPools({chain:e})).map(i=>this.formatSubgraphPool(i,e)).sort((i,l)=>this.fallbackSortValue(l,t)-this.fallbackSortValue(i,t)).slice(0,n)}catch{return[]}}fallbackSortValue(e,t){switch(t){case"apr":return e.apr??0;case"volume1Day":case"volume1Week":case"volume30Day":return e.volume1DayUsd??0;default:return e.tvlUsd??0}}formatSubgraphPool(e,t){return{apr:e.apr??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,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(Xu.includes(t))return t}return"V3"}parseSortKey(e){if(typeof e=="string"){let t=e.trim();if(zu.includes(t))return t}return"tvl"}formatPool(e){return{apr:e.apr,address:e.id,chain:e.chain,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,tvlUsd:e.totalLiquidity?.value,fee24hUsd:e.fee24hUsd,volume1DayUsd:e.volume1Day?.value,volume1WeekUsd:e.volume1Week?.value,volume30DayUsd:e.volume30Day?.value,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 os={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114},Qu={100:.01,500:.05,3e3:.3,1e4:1},at=class{coinPoolBaseUrl;constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}isSupported(e){let t=M(e);return!!(t&&os[t])}listSupportedChains(){return Object.keys(os).filter(e=>M(e)===e)}numericChainId(e){let t=M(e);return t?os[t]:void 0}async getPairs(e){let t=this.numericChainId(e.chain);if(!t)return[];let r=(await this.fetchV2Items(t)).map(o=>this.mapV2Item(o)).filter(o=>o!==null);if(e.tokens&&e.tokens.length>=2){let o=e.tokens[0].toUpperCase(),a=e.tokens[1].toUpperCase(),i=(l,c)=>l.includes(c)||c.includes(l);r=r.filter(l=>{let[c="",u=""]=l.pair.toUpperCase().split("/");return i(c,o)&&i(u,a)||i(c,a)&&i(u,o)})}return r}async getByAddress(e){let t=this.numericChainId(e.chain);if(!t)return[];let n=e.poolAddress.toLowerCase();return(await this.fetchV2Items(t)).filter(o=>o.poolId?.toLowerCase()===n).map(o=>this.mapV2Item(o)).filter(o=>o!==null).sort((o,a)=>(a.apr??-1/0)-(o.apr??-1/0))}async fetchV2Items(e){try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,n=await x.get(t);if(!n.ok)throw new Error(R(n));return n.data?.data?.items||[]}catch{return[]}}mapV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,n=e.token1.decimal??18,r=P=>P==null||!Number.isFinite(P)?0:Math.pow(1.0001,P)*Math.pow(10,t-n),o=r(e.minTick),a=r(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,u=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),d=u?o:a>0?1/a:0,p=u?a:o>0?1/o:0,h=u?c:c>0?1/c:0,f=u?e.token0.symbol:e.token1.symbol,m=u?e.token1.symbol:e.token0.symbol;if(!h||!d&&!p)return null;let g=Math.min(d,p),y=Math.max(d,p);if(h<g||h>y)return null;let b=Number(e.fee),w=Qu[b]??b/1e4,k=typeof e.apr=="number"?e.apr:typeof e.aprAvg=="number"?e.aprAvg:null,T=typeof e.aprAvg=="number"?e.aprAvg:null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:T,token0Price:i,token1Price:l,priceRange:{minPrice:ne(d),maxPrice:ne(p),currentPrice:ne(h),baseToken:f,quoteToken:m}}}};var Ju=365,Ga=/^0x[a-fA-F0-9]{40}$/,Zu=6,kn=class extends A{name="get-pool-detail";description="Get detailed stats for a Uniswap V3 pool by token pair (and optional fee tier). Always runs a search first and filters by the provided symbols + fee tier. When the filter resolves to exactly one pool, returns its full detail. When the pair is fully named but NO fee tier is given, returns detail plus a comparative analysis of ALL the pair's fee-tier variants (no need to ask the user to pick). When only one token is given (so the matches are different pairs), returns a `candidates` list \u2014 show it and ask which pair they want, then re-call this tool with the missing info. Detail response includes: pool address, fee tier (bps and %), both tokens (symbol, name, address, decimals, USD price), token0/token1 reserves, total TVL with 24h % change, 24h volume, weekly historical volume series, total tx count, and a derived APR estimate (fees \xF7 TVL \xD7 365). 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: "+me();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:Ae,required:!1},...st];service;coinPool;pool;constructor(e,t){super(),this.service=new pe(e),this.coinPool=new at(t),this.pool=new de({isProduction:e?.isProduction})}async run(e,t){let n=await he(Se(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=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(!o)return{error:"token0Symbol is required. Provide at least one token symbol; add token1Symbol and feeTier to narrow the result."};let l=a?`${o} ${a}`:o,c=await this.service.searchPools({query:l,chain:r,page:1,size:100,protocolVersion:"V3"});if(!c.success)return{error:c.error||"Pool search failed"};let u=c.data??[],p=u.filter(g=>this.matchesFilter(g,o,a,i,"ordered")),h=!1;if(p.length===0&&a){let g=u.filter(y=>this.matchesFilter(y,o,a,i,"reversed"));g.length>0&&(p=g,h=!0)}if(p.length===0)return{error:`No V3 pool matched ${this.describeQuery(o,a,i)} on ${v(r)}. Verify the symbols and fee tier with the user.`};if(p.length===1){let g=p[0];if(!g.id||!Ga.test(g.id))return{error:"Resolved pool has no valid address"};let[y,b]=await Promise.all([this.service.getV3PoolDetail({address:g.id,chain:r}),this.fetchPriceRanges(r,g.id,g.token0?.symbol,g.token1?.symbol)]);if(!y.success||!y.data)return{error:y.error||"Failed to fetch pool detail"};let w={...this.formatPool(y.data),...Ee(r,g.id)},k=await this.pool.isAddLiquiditySupported(r)?Re([w],e,v(r)):[];return{priceRanges:b,_instructions:fe+"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. "+ye+be+'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`. 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. '+ie+Ue+(k.length>0?Ne:""),pairOrderMatched:h?"reversed":"ordered",pool:w,...k.length>0?{actionButtons:k}:{}}}if(a){let g=this.rankCandidates(p).slice(0,Zu),b=(await Promise.all(g.map(async w=>{if(!w.id||!Ga.test(w.id))return;let k=await this.service.getV3PoolDetail({address:w.id,chain:r});if(!(!k.success||!k.data))return{...this.formatPool(k.data),...Ee(r,w.id)}}))).filter(w=>w!=null);if(b.length>0){let w=await this.pool.isAddLiquiditySupported(r)?Re(b,e,v(r)):[];return{_instructions:fe+"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. "+ye+"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. "+be+ie+Ue+(w.length>0?Ne:""),chain:r,pairOrderMatched:h?"reversed":"ordered",multiFeeTier:!0,count:b.length,pools:b,...w.length>0?{actionButtons:w}:{}}}}let f=this.rankCandidates(p).slice(0,10).map(g=>{let y=this.formatCandidate(g);return{...y,...Ee(r,y.address)}}),m=await this.pool.isAddLiquiditySupported(r)?Re(f,e,v(r)):[];return{_instructions:"The filter matched multiple pools. Render them as a numbered list (pair, fee tier %, 24h volume) and ask the user which one they want to see. Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. When they answer, re-call this tool with their selection \u2014 pass token0Symbol + token1Symbol + feeTier (use the exact feeTier in bps from the chosen candidate). Format numbers human-readably (e.g. $12.5M, 0.05%). Do NOT mention tool/API names."+(m.length>0?Ne:""),chain:r,pairOrderMatched:h?"reversed":"ordered",reason:this.candidateReason(o,a,i),missing:this.missingFields(a,i),candidates:f,...m.length>0?{actionButtons:m}:{}}}matchesFilter(e,t,n,r,o){if(r!=null&&e.feeTier!==r)return!1;let a=(e.token0?.symbol??"").toLowerCase(),i=(e.token1?.symbol??"").toLowerCase(),l=t.toLowerCase();if(n){let c=n.toLowerCase();return o==="reversed"?this.symbolIncludes(a,c)&&this.symbolIncludes(i,l):this.symbolIncludes(a,l)&&this.symbolIncludes(i,c)}return this.symbolIncludes(a,l)||this.symbolIncludes(i,l)}symbolIncludes(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}describeQuery(e,t,n){let r=t?`${e}/${t}`:e;return n!=null?`${r} at fee tier ${n} bps`:r}candidateReason(e,t,n){return t?n==null?`Multiple fee tiers exist for ${e}/${t}. Ask the user which fee tier they want.`:`Multiple ${e}/${t} pools share fee tier ${n} bps. Ask the user which one they meant.`:`Multiple pools contain ${e}. Ask the user for the other token (and fee tier).`}missingFields(e,t){let n=[];return e||n.push("token1Symbol"),t==null&&n.push("feeTier"),n}rankCandidates(e){return[...e].sort((t,n)=>(n.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}formatCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}async fetchPriceRanges(e,t,n,r){try{if(!this.coinPool.isSupported(e))return[];let o=await this.coinPool.getByAddress({chain:e,poolAddress:t});return o.length===0&&n&&r&&(o=await this.coinPool.getPairs({chain:e,tokens:[n,r]})),o.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}formatPool(e){let t=e.totalLiquidity?.value,n=e.volume24h?.value,r=e.feeTier,o=typeof r=="number"?r/1e4:void 0,a=typeof n=="number"&&typeof o=="number"?n*o/100:void 0,i=typeof a=="number"&&typeof t=="number"&&t>0?a/t*Ju*100:void 0,l=typeof n=="number"&&typeof t=="number"&&t>0?Math.round(n/t*1e3)/1e3:void 0;return{address:e.address,protocolVersion:e.protocolVersion,feeTierBps:r,feeTierPercent:o,tvlUsd:t,tvlChange24hPercent:e.totalLiquidityPercentChange24h?.value,volume24hUsd:n,fees24hUsd:a,aprPercent:i,volumeToTvlRatio:l,txCount:e.txCount,historicalVolumeWeek:this.formatHistorical(e.historicalVolume),token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.market?.price?.value??e.token0.price?.value,reserve:e.token0Supply,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.market?.price?.value??e.token1.price?.value,reserve:e.token1Supply,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}formatHistorical(e){if(!(!e||e.length===0))return e.map(t=>({timestamp:t.timestamp,volumeUsd:t.value}))}};var ed=["V2","V3","V4","ALL"],Tn=class extends A{name="search-pools";description='Search Uniswap liquidity pools on a given chain by free-text query \u2014 a SINGLE token symbol or token name. Returns matching pools with: pool address, fee tier (bps + %), protocol version, both tokens (symbol, name, address, decimals, logo), and short-window USD volume buckets (6h / 12h / 24h). Use this tool when the user names ONE token and wants pools related to it: "find WBTC pools on Optimism", "pools containing PEPE on Ethereum", "show USDC pools". Do NOT use for: (a) two-symbol pair lookups like "USDC/WETH 0.05%" \u2014 use get-pool-detail; (b) raw 0x addresses (token or pool) \u2014 use lookup-pool-by-address; (c) chain-wide rankings with no token mentioned \u2014 use get-top-pools. Source: https://app.uniswap.org search. Supports: '+me();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:Ae,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},...st];service;pool;constructor(e){super(),this.service=new pe(e),this.pool=new de({isProduction:e?.isProduction})}async run(e,t){let n=typeof e.query=="string"?e.query.trim():"";if(!n)return{error:"Search query is required"};let r=await he(Se(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,a=typeof e.page=="number"&&Number.isFinite(e.page)&&e.page>0?Math.floor(e.page):1,i=typeof e.size=="number"&&Number.isFinite(e.size)&&e.size>0?Math.min(Math.floor(e.size),50):5,l=this.parseProtocolFilter(e.protocolVersion),c=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.floor(e.feeTier):void 0,u=await this.service.searchPools({query:n,chain:o,page:a,size:i,protocolVersion:l,feeTier:c});if(!u.success)return{error:u.error||"Failed to search pools"};let d=(u.data??[]).map(h=>this.formatPool(h)),p=await this.pool.isAddLiquiditySupported(o)?Re(d,e,v(o)):[];return{_instructions:fe+"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. "+ye+be+"When several pools share the searched token, finish with a clear TOP PICK among them. "+ie+"Mention the search query and chain in the intro. "+Ue+(p.length>0?Ne:""),query:n,chain:o,protocolVersion:l,feeTierBps:c,feeTierPercent:c!=null?c/1e4:void 0,page:a,size:i,count:d.length,pools:d.map(h=>({...h,...Ee(o,h.address)})),...p.length>0?{actionButtons:p}:{}}}parseProtocolFilter(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(ed.includes(t))return t}return"V3"}formatPool(e){let t={address:e.id,chainId:e.chainId,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0};e.apr!=null&&(t.apr=e.apr),e.tvlUsd!=null&&(t.tvlUsd=e.tvlUsd);let n=e.volume1DayUsd??e.volumeUsd24hr;n!=null&&(t.volume24hUsd=n),e.volumeUsd6hr!=null&&(t.volume6hUsd=e.volumeUsd6hr),e.volumeUsd12hr!=null&&(t.volume12hUsd=e.volumeUsd12hr),e.txCount!=null&&(t.txCount=e.txCount),e.tvlUsd!=null&&e.tvlUsd>0&&n!=null&&(t.volumeToTvlRatio=Math.round(n/e.tvlUsd*1e3)/1e3);let r=e.token0,o=e.token1;return r&&(t.token0={address:r.address,symbol:r.symbol,name:r.name,decimals:r.decimals}),o&&(t.token1={address:o.address,symbol:o.symbol,name:o.name,decimals:o.decimals}),t}};var td=365,Ka=/^0x[a-fA-F0-9]{40}$/,vn=class extends A{name="lookup-pool-by-address";description='Resolve an unknown 0x address as either a Uniswap pool or a token, then return the appropriate data: pool detail when the address is a pool, or the list of pools containing that token when the address is a token. Use this tool when the user pastes a single address and asks about "the pool" without saying which kind. For pool detail (when the address is a pool): pair, fee tier, TVL with 24h % change, 24h volume, 24h fees, estimated APR, token reserves with USD prices, and weekly volume series. 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: '+me();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:Ae,required:!1},...st];service;pool;constructor(e){super(),this.service=new pe(e),this.pool=new de({isProduction:e?.isProduction})}async run(e,t){let n=await he(Se(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=typeof e.address=="string"?e.address.trim():"",[a,i]=await Promise.all([this.service.searchPools({query:o,chain:r,page:1,size:5,protocolVersion:"ALL"}),this.service.searchTokens({query:o,chain:r,page:1,size:5})]),l=a.success?this.findPoolByAddress(a.data??[],o):void 0;if(l)return this.handlePoolHit(l,r,e);let c=i.success?this.findTokenByAddress(i.data??[],o):void 0;return c?this.handleTokenHit(c,r,e):!a.success&&!i.success?{error:a.error||i.error||"Failed to resolve address"}:{error:`Address ${o} did not match any pool or token Uniswap knows on ${v(r)}. Verify the chain (the address may exist on a different network) or ask the user for context.`}}async handlePoolHit(e,t,n){if(!e.id)return{error:"Resolved pool has no identifier"};let r=e.protocolVersion??"V3",o=r==="V4"?await this.service.getV4PoolDetail({poolId:e.id,chain:t}):r==="V2"?Ka.test(e.id)?await this.service.getV2PoolDetail({address:e.id,chain:t}):{success:!1,error:"Resolved V2 pair has no valid address"}:Ka.test(e.id)?await this.service.getV3PoolDetail({address:e.id,chain:t}):{success:!1,error:"Resolved V3 pool has no valid address"};if(!o.success||!o.data)return{error:o.error||"Failed to fetch pool detail"};let a={...this.formatPoolDetail(o.data),...Ee(t,e.id)},i=await this.pool.isAddLiquiditySupported(t)?Re([a],n,v(t)):[];return{_instructions:`The address is a Uniswap ${r} pool. `+fe+"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, token1 reserve + USD price, and total tx count. 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. "+ye+be+ie+Ue+(i.length>0?Ne:""),resolvedAs:"pool",chain:t,protocolVersion:r,pool:a,...i.length>0?{actionButtons:i}:{}}}async handleTokenHit(e,t,n){let r=e.symbol?.trim();if(!r)return{error:"Resolved token has no symbol \u2014 cannot search related pools."};let o=await this.service.searchPools({query:r,chain:t,page:1,size:100,protocolVersion:"V3"});if(!o.success)return{error:o.error||"Failed to fetch pools for resolved token"};let a=(e.address??"").toLowerCase(),l=[...(o.data??[]).filter(d=>{let p=(d.token0?.address??"").toLowerCase(),h=(d.token1?.address??"").toLowerCase();return p===a||h===a})].sort((d,p)=>(p.volumeUsd24hr??0)-(d.volumeUsd24hr??0)).slice(0,10),c=l.map(d=>({...this.formatPoolCandidate(d),...Ee(t,d.id)})),u=await this.pool.isAddLiquiditySupported(t)?Re(c,n,v(t)):[];return{_instructions:"The address is a token, not a pool. Tell the user which token it is (symbol + name), then render the matching pools as a numbered list: pair (token0/token1 symbols), fee tier (%), protocol version, 24h volume (USD). Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. Ask which pool they want detail on; when they answer, re-call this tool with that pool address to fetch the detail. Format numbers human-readably. Omit null fields. Do NOT mention tool/API names."+(u.length>0?Ne:""),resolvedAs:"token",chain:t,protocolVersion:"V3",token:this.formatToken(e),poolCount:l.length,pools:c,...u.length>0?{actionButtons:u}:{}}}findPoolByAddress(e,t){let n=t.toLowerCase();return e.find(r=>(r.id??"").toLowerCase()===n)}findTokenByAddress(e,t){let n=t.toLowerCase();return e.find(r=>(r.address??"").toLowerCase()===n)}formatToken(e){return{address:e.address,symbol:e.symbol,name:e.name,decimals:e.decimals,chainId:e.chainId,isSpam:e.isSpam,safetyLevel:e.safetyLevel}}formatPoolCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}formatPoolDetail(e){let t=e.totalLiquidity?.value,n=e.volume24h?.value,r=e.feeTier,o=typeof r=="number"?r/1e4:void 0,a=typeof n=="number"&&typeof o=="number"?n*o/100:void 0,i=typeof a=="number"&&typeof t=="number"&&t>0?a/t*td*100:void 0,l=typeof n=="number"&&typeof t=="number"&&t>0?Math.round(n/t*1e3)/1e3:void 0;return{address:e.address??e.poolId,protocolVersion:e.protocolVersion,poolId:e.poolId,tickSpacing:e.tickSpacing,isDynamicFee:e.isDynamicFee,hookAddress:e.hook?.address,feeTierBps:r,feeTierPercent:o,tvlUsd:t,tvlChange24hPercent:e.totalLiquidityPercentChange24h?.value,volume24hUsd:n,fees24hUsd:a,aprPercent:i,volumeToTvlRatio:l,txCount:e.txCount,historicalVolumeWeek:this.formatHistorical(e.historicalVolume),token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.market?.price?.value??e.token0.price?.value,reserve:e.token0Supply,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.market?.price?.value??e.token1.price?.value,reserve:e.token1Supply,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}formatHistorical(e){if(!(!e||e.length===0))return e.map(t=>({timestamp:t.timestamp,volumeUsd:t.value}))}};var nd=/^0x[a-fA-F0-9]{40}$/,An=class extends A{name="open-add-liquidity-form";kind="ui";category="pool-action";description='Open the Add-Liquidity form for a specific Uniswap V3 pool. Use this when the user wants to provide liquidity / add LP / farm / stake / deposit into a pool \u2014 natural-language verbs in any language all map here. Resolves the pool by 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.';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:"feeTier",type:"number",description:"Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. Omit when unknown \u2014 the tool will resolve the best match automatically.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prefillNativeAmount",type:"number",description:"Optional NATIVE-COIN amount (human-readable) to pre-fill the form's input field. ONLY pass this when the user named an amount in the chain's native coin itself \u2014 ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche. Example: \"add 0.1 ETH to USDC/WETH on Base\". Pass the plain decimal number (e.g. 0.1 for 0.1 ETH). DO NOT convert a non-native amount (USDC, USDT, DAI, WBTC, \u2026) into native here \u2014 pass `requestedNonNativeToken` instead so the tool can reject. Mutually exclusive with prefillUsdAmount \u2014 pass one or neither.",required:!1},{name:"prefillUsdAmount",type:"number",description:'Optional USD amount to pre-fill the form\'s input field. Use this ONLY when the user explicitly speaks in USD/dollars \u2014 e.g. "add $10 to this pool", "10 dollars", "10 \u0111\xF4". The tool converts the USD value to native amount automatically using the current native-token price. DO NOT use this as a workaround for non-native token amounts (e.g. "5 USDT" is NOT $5 \u2014 USDT may de-peg, and even if 1:1 the user asked for a token, not USD). For non-native token amounts pass `requestedNonNativeToken` instead. Mutually exclusive with prefillNativeAmount \u2014 pass one or neither.',required:!1},{name:"requestedNonNativeToken",type:"string",description:`Set this ONLY when the user named an AMOUNT in a non-native token \u2014 e.g. "add pool with 5 USDT", "add 100 USDC to USDC/WETH", "th\xEAm 5 USDT v\xE0o pool". The trigger is "<number> <non-native-symbol>" in the user's message, NOT the mere appearance of the symbol. Pass the symbol the user attached the amount to (e.g. "USDT", "USDC", "DAI"). CRITICAL: If the user also names a NATIVE amount in the same message (e.g. "add USDC/WETH with 0.1 ETH", "th\xEAm pool USDC/WETH 0.3% v\u1EDBi 0.000005 ETH"), the native amount is the input \u2014 leave this EMPTY and use prefillNativeAmount. The pool pair symbols (the two tokens after "pool" / "to") are NEVER the input token by themselves \u2014 they only identify which pool. The tool will return error="unsupported_input_token" so the agent can tell the user that only the chain's native coin is accepted as input. DO NOT silently convert the user's non-native amount into a native amount or USD amount \u2014 the user explicitly named a different asset and must be informed, not auto-corrected. Leave empty when the user did name a native amount, a USD amount, or no amount at all.`,required:!1},{name:"rangeStrategy",type:"string",description:'Optional preset that pre-fills the min/max price inputs (FE keeps them editable). One of: "stable" \u2014 \xB13 tickSpacing around the current price (narrow, higher yield, higher out-of-range risk; pick for stablecoin / low-volatility pairs and when the user says "safe", "tight", "high yield", "t\u1EADp trung"); "wide" \u2014 currentPrice \xD7 [0.5, 2.0] (broad, lower yield, less rebalancing; pick when the user says "wide", "set and forget", "r\u1ED9ng"); "full" \u2014 full V3 tick range (V2-style, lowest yield, never goes out of range; pick when the user says "full range", "v2-style", "kh\xF4ng lo out of range"). Omit when the user did not signal a preference AND did not provide explicit minPrice/maxPrice. Mutually exclusive with minPrice/maxPrice \u2014 if both are passed, explicit prices win.',required:!1},{name:"minPrice",type:"number",description:'Optional explicit lower bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 minPrice=1800. Must be paired with maxPrice. When set, overrides rangeStrategy.',required:!1},{name:"maxPrice",type:"number",description:'Optional explicit upper bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 maxPrice=2200. Must be paired with minPrice. When set, overrides rangeStrategy.',required:!1},{name:"add_button_label",type:"string",description:`Label template for the per-fee-tier "Add liquidity" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. ALWAYS pass this when you call the tool with a pair but NO feeTier (the tool may return several fee-tier variants for the pair, and each gets a one-tap button). Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:'A short "add liquidity" command template IN THE USER\'S CURRENT LANGUAGE, submitted as the next user turn when a fee-tier button is clicked \u2014 it carries the chosen fee tier so the tool resolves that exact pool. ALWAYS pass this alongside `add_button_label` when calling with a pair but no feeTier. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name yourself \u2014 the chain this pair is on is appended to the prompt automatically.',required:!1}];uniswap;pool;coinPool;minProvideUsd;constructor(e){super(),this.uniswap=new pe(e),this.pool=new de(e?.pool),this.coinPool=new at(e?.coinPool),this.minProvideUsd=e?.minProvideUsd??.01}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(a.ui=o.ui),o&&typeof o=="object"&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(a.actionButtons=o.actionButtons),a}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){let n=await he(bn(this.pool),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=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.prefillNativeAmount=="number"&&Number.isFinite(e.prefillNativeAmount)&&e.prefillNativeAmount>0?e.prefillNativeAmount:null,c=typeof e.prefillUsdAmount=="number"&&Number.isFinite(e.prefillUsdAmount)&&e.prefillUsdAmount>0?e.prefillUsdAmount:null,u=typeof e.requestedNonNativeToken=="string"&&e.requestedNonNativeToken.trim()?e.requestedNonNativeToken.trim():null,d=u&&l!=null&&(u.toLowerCase()===o.toLowerCase()||u.toLowerCase()===a.toLowerCase())?null:u,p=this.parseRangeStrategy(e.rangeStrategy),h=typeof e.minPrice=="number"&&Number.isFinite(e.minPrice)&&e.minPrice>0?e.minPrice:null,f=typeof e.maxPrice=="number"&&Number.isFinite(e.maxPrice)&&e.maxPrice>0?e.maxPrice:null;if(!o||!a)return{error:"missing_pool_identifier",_instructions:"token0Symbol and token1Symbol are required. Ask the user for the missing token symbol."};let m=se(r);if(!m)return{error:"unsupported_chain",chain:r,_instructions:`Chain ${r} is not supported by the add-liquidity flow.`};let g=yn(r);if(d&&g&&d.toLowerCase()!==g.symbol.toLowerCase())return{error:"unsupported_input_token",requestedToken:d,nativeSymbol:g.symbol,chainName:m.name,_instructions:`The user asked to add liquidity using ${d}, but this app only supports the chain's native coin (${g.symbol} on ${m.name}) as the input. Tell the user this in their language and ask them to either restate the amount in ${g.symbol} or in USD. DO NOT silently convert their ${d} amount, do NOT pre-fill the form, and do NOT call this tool again until the user provides a native or USD amount.`};let y=await this.pool.getGatewayAddress(r);if(!y)return{error:"no_gateway_configured",chain:r,_instructions:`No gateway contract is configured for chain ${r} (${m.name}). Tell the user this chain is not yet supported for add-liquidity in this app.`};let b=t?.walletAddress;if(!b)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."};let w=await this.uniswap.searchPools({query:`${o} ${a}`,chain:r,page:1,size:100,protocolVersion:"V3",feeTier:i});if(!w.success)return{error:w.error||"pool_search_failed"};let k=w.data??[],T=k.find(L=>this.matchesPairExact(L,o,a,i)),P=T?[]:k.filter(L=>this.matchesPair(L,o,a,i));if(!T&&P.length===0)return{error:"pool_not_found",_instructions:`No V3 pool found for ${o}/${a}${i!=null?` at ${i}bps`:""} on ${m.name}. Verify the inputs with the user.`};if(!T&&P.length>1){let L=P.map(te=>{let Pt=te.volume1DayUsd??te.volumeUsd24hr,To=te.tvlUsd,ds=typeof Pt=="number"&&typeof To=="number"&&To>0?Pt/To: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:Pt,tvlUsd:To,...ds!=null?{volumeToTvlRatio:ds}:void 0,...te.apr?{apr:te.apr}:void 0}}).sort((te,Pt)=>(Pt.volumeToTvlRatio??Pt.apr??-1/0)-(te.volumeToTvlRatio??te.apr??-1/0)).slice(0,5),cr=ns(L.map(te=>({token0:{symbol:te.token0Symbol},token1:{symbol:te.token1Symbol},feeTierPercent:te.feeTierPercent})),typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",v(r));return{relatedPools:L,count:L.length,...cr.length>0?{actionButtons:cr}:{},_instructions:fe+"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. "+ye+"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). "+be+ie+Ue+(cr.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 S=T??P[0];if(!S.id||!nd.test(S.id))return{error:"invalid_pool_address"};let _=this.fetchPriceRanges(r,S.id,S.token0?.symbol,S.token1?.symbol),N=await this.pool.readPoolOnchain(r,S.id),[C,q,E]=await Promise.all([this.pool.getNativeBalance(r,b),this.pool.estimateGasReserveWei(r),this.pool.getNativePriceUsd(r)]),ee=C>q?C-q:0n,O=yn(r),Ie=Number(ee)/10**O.decimals,ge=Number(C)/10**O.decimals,Y=E!=null?Ie*E:null,[$e,le]=await Promise.all([this.pool.readErc20Decimals(r,N.token0),this.pool.readErc20Decimals(r,N.token1)]),lt={min:Ce(je,$e,le),max:Ce(Ct,$e,le)},Ke=null;C===0n?Ke="no_balance":Y!=null&&Y<this.minProvideUsd&&(Ke="insufficient_balance");let ct=S.token0,ut=S.token1,zn=[25,50,75,100].map(L=>({percent:L,amountWei:(ee*BigInt(L)/100n).toString(),amount:Ie*(L/100)})),Xn=null,dt=null;if(l!=null){dt=l;let L=BigInt(Math.floor(dt*10**O.decimals));L>0n&&(Xn=L.toString())}else if(c!=null&&E!=null&&E>0){dt=c/E;let L=BigInt(Math.floor(dt*10**O.decimals));L>0n&&(Xn=L.toString())}let ko={address:$,isNative:!0,symbol:O.symbol,name:O.name,decimals:O.decimals,priceUsd:E,balanceWei:C.toString(),balance:ge,gasReserveWei:q.toString(),spendableWei:ee.toString(),spendable:Ie,spendableUsd:Y,quickRates:zn,minProvideUsd:this.minProvideUsd,warning:Ke,warningMessage:Ke==="no_balance"?`You have no ${O.symbol} on ${m.name}. Top up to add liquidity.`:Ke==="insufficient_balance"?`Spendable ${O.symbol} is below the $${this.minProvideUsd} minimum.`:null,prefillAmount:dt,prefillAmountWei:Xn},pt=this.computePrefillRange({explicitMinPrice:h,explicitMaxPrice:f,rangeStrategy:p,currentPrice:N.currentPrice,currentTick:N.currentTick,tickSpacing:N.tickSpacing,token0Decimals:$e,token1Decimals:le,priceBounds:lt}),cs={component:"AddLiquidityForm",props:{chain:{hexId:r,name:m.name},pool:{address:N.poolAddress,fee:N.fee,feePercent:N.fee/1e4,tickSpacing:N.tickSpacing,currentTick:N.currentTick,currentPrice:ne(N.currentPrice),sqrtPriceX96:N.sqrtPriceX96.toString(),token0:{address:N.token0,symbol:ct?.symbol,name:ct?.name,logo:ct?.logo},token1:{address:N.token1,symbol:ut?.symbol,name:ut?.name,logo:ut?.logo}},inputToken:ko,priceBounds:lt,prefillRange:pt,gatewayAddress:y}},us=this.orientRangesToForm(await _,N.currentPrice,ct?.symbol,ut?.symbol);return{ui:cs,suggestedRanges:us,summary:this.buildSummary({chainName:m.name,pair:`${ct?.symbol??o}/${ut?.symbol??a}`,feePercent:N.fee/1e4,warning:Ke,minProvideUsd:this.minProvideUsd,nativeSymbol:O.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`. 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. '+ie+"Do NOT mention balance amounts, deBridge, native coin mechanics, UI, forms, data sources, or internal tool names. Wait for the user to fill in amount + price range before proceeding."}}async fetchPriceRanges(e,t,n,r){try{if(!this.coinPool.isSupported(e))return[];let o=await this.coinPool.getByAddress({chain:e,poolAddress:t});return o.length===0&&n&&r&&(o=await this.coinPool.getPairs({chain:e,tokens:[n,r]})),o.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}orientRangesToForm(e,t,n,r){let o=a=>Number.isFinite(a)&&a>0;return o(t)?e.map(a=>{let{minPrice:i,maxPrice:l,currentPrice:c}=a.priceRange,u=i,d=l,p=c;if(o(c)){let h=Math.abs(Math.log(c/t));Math.abs(Math.log(c*t))<h&&(u=o(l)?1/l:0,d=o(i)?1/i:0,p=1/c)}return{fee:a.fee,apr:a.apr,minPrice:ne(u),maxPrice:ne(d),currentPrice:ne(p),baseSymbol:n,quoteSymbol:r}}).filter(a=>o(a.minPrice)&&o(a.maxPrice)):[]}matchesPairExact(e,t,n,r){if(!r||r!=null&&e.feeTier!==r)return!1;let o=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=n.toLowerCase();return o===i&&a===l||o===l&&a===i}matchesPair(e,t,n,r){if(r!=null&&e.feeTier!==r)return!1;let o=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=n.toLowerCase(),c=this.symMatch(o,i)&&this.symMatch(a,l),u=this.symMatch(o,l)&&this.symMatch(a,i);return c||u}symMatch(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}parseRangeStrategy(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="stable"||t==="wide"||t==="full"?t:null}computePrefillRange(e){let{explicitMinPrice:t,explicitMaxPrice:n,rangeStrategy:r,currentPrice:o,priceBounds:a}=e;if(t!=null&&n!=null&&n>t){let{minPrice:i,maxPrice:l}=_t(t,n,o);return{strategy:"user",minPrice:Math.max(i,a.min),maxPrice:Math.min(l,a.max)}}if(r==="full")return{strategy:"full",minPrice:a.min,maxPrice:a.max};if(r==="stable"||r==="wide"){let l=Zr({currentTick:e.currentTick,tickSpacing:e.tickSpacing,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals}).find(c=>c.id===r);if(l)return{strategy:r,minPrice:l.minPrice,maxPrice:l.maxPrice}}return null}buildSummary(e){let t=[`Ready to add liquidity to the ${e.pair} ${e.feePercent}% pool on ${e.chainName}. Enter an amount and a price range to continue.`];return e.warning==="no_balance"?t.push(`You'll need some ${e.nativeSymbol} on ${e.chainName} first \u2014 top up to continue.`):e.warning==="insufficient_balance"&&t.push(`Your spendable ${e.nativeSymbol} is below the $${e.minProvideUsd} minimum \u2014 top up before continuing.`),t.join(" ")}};var ja=[{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"}]}],jo=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"",type:"uint256"}]}];var od=/^0x[a-fA-F0-9]{40}$/,Sn=class extends A{name="preview-add-liquidity";kind="action";category="pool-action";description='Preview the add-liquidity transaction. Call this whenever a concrete pool ADDRESS, a native amount, and BOTH min and max price (in token1 per token0) are known \u2014 whether the user filled the AddLiquidityForm OR stated all of them directly in chat (e.g. "add to USDC/WETH with 0.01 ETH, range 0.0005-0.0007, pool=0x\u2026"). Do NOT require the form to have been opened first. The tool converts prices \u2192 ticks (rounded to tickSpacing), fetches deBridge swap quotes for both legs, encodes the gateway.mint call, and returns an unsigned tx the FE will sign. REQUIRES the exact poolAddress (from open-add-liquidity-form props.pool.address or given by the user) \u2014 if only token symbols / a fee tier are known, resolve the pool via open-add-liquidity-form first.';parameters=[{name:"poolAddress",type:"string",description:"V3 pool contract address (returned by open-add-liquidity-form in props.pool.address).",required:!0},{name:"chain",type:"string",description:`Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea .Must match the pool's chain. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.`,required:!1},{name:"minPrice",type:"number",description:`Lower bound of the position price range, in token1-per-token0 units (decimal-adjusted \u2014 the SAME unit as pool.currentPrice from open-add-liquidity-form). Example: if currentPrice is 1800 (USDC per WETH), minPrice 900 means "the position is in-range while WETH \u2265 900 USDC". Must be >= 0 and < maxPrice. Pass 0 for a "full-range lower" position (the range extends down to price 0, i.e. Uniswap's MIN_TICK). CRITICAL: copy the number the user gave VERBATIM \u2014 every digit and every leading zero. Do NOT add or drop a zero, round, or rescale it. Tiny decimals like 0.000533 are easy to mis-transcribe (0.000533 must stay 0.000533, NEVER 0.0000533). If unsure, prefer the user's exact characters over your own reformatting.`,required:!0},{name:"maxPrice",type:"number",description:`Upper bound of the position price range, in the same units as minPrice. Must be > minPrice. Pass a very large number (or props.priceBounds.max) for a "full range upper" position. CRITICAL: copy the user's number VERBATIM \u2014 every digit and leading zero; never add/drop a zero, round, or rescale.`,required:!0},{name:"nativeAmount",type:"number",description:"Native amount the user wants to spend, as a human-readable decimal number (e.g. 0.1 for 0.1 ETH). The tool converts to wei internally.",required:!0},{name:"slippageBps",type:"number",description:"Slippage tolerance in basis points (100 = 1%). Optional \u2014 defaults to 100.",required:!1}];pool;defaultSlippageBps;mintMinPercent;pantograph;constructor(e){super(),this.pool=new de(e?.pool),this.defaultSlippageBps=e?.defaultSlippageBps??"auto",this.mintMinPercent=e?.mintMinPercent??80,this.pantograph=new ue}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(a.ui=o.ui),a}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"",r=await he(bn(this.pool),e.chain,t);if(!r.ok)return r.result;let o=r.chain,a=Number(e.minPrice),i=Number(e.maxPrice),l=typeof e.nativeAmount=="number"&&Number.isFinite(e.nativeAmount)?e.nativeAmount:NaN,c=typeof e.slippageBps=="number"&&Number.isFinite(e.slippageBps)&&String(e.slippageBps)!=="auto"?Math.floor(e.slippageBps)/100:String(this.defaultSlippageBps);if(!n||!o||!Number.isFinite(l)||!Number.isFinite(a)||!Number.isFinite(i))return{error:"missing_inputs",_instructions:"poolAddress, chain, minPrice, maxPrice, nativeAmount are all required."};if(!od.test(n))return{error:"invalid_pool_address",_instructions:"poolAddress is not a valid EVM address. Re-open the add-liquidity form to get the correct pool address."};if(a<0||i<=0||a>=i)return{error:"invalid_price_range",_instructions:"minPrice must be >= 0 (0 = full-range lower), maxPrice must be > 0, and minPrice must be strictly less than maxPrice."};if(l<=0)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let u=se(o);if(!u)return{error:"unsupported_chain",chain:o};let d=await this.pool.getGatewayAddress(o);if(!d)return{error:"no_gateway_configured",chain:o};let p=t?.walletAddress;if(!p)return{error:"wallet_not_connected"};let h=yn(o),f=BigInt(Math.floor(l*10**h.decimals));if(f<=0n)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let m=await this.pool.readPoolOnchain(o,n),[g,y]=await Promise.all([this.pool.readErc20Decimals(o,m.token0),this.pool.readErc20Decimals(o,m.token1)]),{minPrice:b,maxPrice:w}=_t(a,i,m.currentPrice),k=b===0?je:ht(b,g,y),T=ht(w,g,y),P=b===0?De(Le(je,m.tickSpacing,"up")):De(Le(k,m.tickSpacing,"down")),S=De(Le(T,m.tickSpacing,"up"));if(P>=S||P<je||S>Ct)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:T,tickLower:P,tickUpper:S};let _={tickLower:P,tickUpper:S,minPrice:ne(Ce(P,g,y)),maxPrice:ne(Ce(S,g,y))},N=m.currentTick;if(N<P||N>=S){let L=N<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 ${L==="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:ne(m.currentPrice),requestedRange:{minPrice:_.minPrice,maxPrice:_.maxPrice},side:L}}let[C,q,E]=await Promise.all([this.pool.getNativeBalance(o,p),this.pool.estimateGasReserveWei(o),this.pool.getNativePriceUsd(o)]),ee=f+q;if(C<ee)return{error:"insufficient_balance",_instructions:"User does not have enough native coin (amount + gas reserve). Tell them the shortfall in their language.",balanceWei:C.toString(),requiredWei:ee.toString(),gasReserveWei:q.toString()};let O=this.pool.splitNativeAmountForRange({nativeAmountWei:f,pool:m,tickLower:P,tickUpper:S,token0Decimals:g,token1Decimals:y}),Ie=m.token0.toLowerCase()===$,ge=m.token1.toLowerCase()===$,Y=[];if(Ie||O.amountInFor0Wei===0n)Y.push({tokenIn:$,tokenOut:m.token0,amountIn:O.amountInFor0Wei,tx:{to:$,data:"0x",value:"0"},minAmountOut:Ie?O.amountInFor0Wei:0n});else{let L=await this.pool.fetchSwapLeg({senderAddress:p,chainId:o,tokenIn:$,tokenInAmount:O.amountInFor0Wei.toString(),tokenOut:m.token0,tokenOutRecipient:d,slippage:typeof c=="number"?c:"auto"});Y.push({tokenIn:$,tokenOut:m.token0,amountIn:O.amountInFor0Wei,tx:{to:L.to,data:L.data,value:L.value},minAmountOut:BigInt(L.minAmountOut||"0")})}if(ge||O.amountInFor1Wei===0n)Y.push({tokenIn:$,tokenOut:m.token1,amountIn:O.amountInFor1Wei,tx:{to:$,data:"0x",value:"0"},minAmountOut:ge?O.amountInFor1Wei:0n});else{let L=await this.pool.fetchSwapLeg({senderAddress:p,chainId:o,tokenIn:$,tokenInAmount:O.amountInFor1Wei.toString(),tokenOut:m.token1,tokenOutRecipient:d,slippage:typeof c=="number"?c:"auto"});Y.push({tokenIn:$,tokenOut:m.token1,amountIn:O.amountInFor1Wei,tx:{to:L.to,data:L.data,value:L.value},minAmountOut:BigInt(L.minAmountOut||"0")})}let $e=L=>L*BigInt(this.mintMinPercent)/100n,le=$e(Y[0].minAmountOut),lt=$e(Y[1].minAmountOut),Ke=Y.map(L=>({tokenIn:L.tokenIn,tokenInAmount:BigInt(L.amountIn),tokenOut:L.tokenOut,tokenOutAmount:BigInt(L.minAmountOut)})),ct=Y.map(L=>({to:L.tx.to,data:L.tx.data,value:BigInt(L.tx.value||"0")})),ut=xt({abi:ja,functionName:"mint",args:[Ke,ct,{fee:Number(m.fee),amount0Min:BigInt(le),amount1Min:BigInt(lt),tickLower:P,tickUpper:S}]}),zn=l,Xn={chainId:o,to:d,data:ut,value:f.toString(),from:p},dt={nativeIn:zn,nativeSymbol:h.symbol,nativeInUsd:E!=null?zn*E:null,ratio:{token0Percent:O.ratio0,token1Percent:O.ratio1},expectedToken0:Number(Y[0].minAmountOut)/10**g,expectedToken1:Number(Y[1].minAmountOut)/10**y,amount0Min:le.toString(),amount1Min:lt.toString(),slippageBps:c},ko=await this.pantograph.getTokensMetadata([m.token0,m.token1],o),pt=ko[m.token0],St=ko[m.token1];return{ui:{component:"ConfirmAddLiquidityTx",props:{chain:{hexId:o,name:u.name},unsignedTx:Xn,summary:dt,pool:{...m,feePercent:m.fee/1e4,currentPrice:ne(m.currentPrice),token0:{address:m.token0,symbol:pt?.auditGoplus?.token_symbol||pt.symbol,name:pt.name,decimals:pt.decimals,logo:pt.icon_image},token1:{address:m.token1,symbol:St?.auditGoplus?.token_symbol||St.symbol,name:St.name,decimals:St.decimals,logo:St.icon_image}},range:_,gatewayAddress:d}},summary:`Ready to add ${zn} ${h.symbol} to pool ${m.token0}/${m.token1} ${m.fee/1e4}% on ${u.name}, range [${_.minPrice}, ${_.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 za=365,rd=1e3,sd=/^0x[a-fA-F0-9]{40}$/;function ad(s,e){return{depositUsd:s,aprPercent:e*100,dailyUsd:s*e/za,weeklyUsd:s*e/52,monthlyUsd:s*e/12,yearlyUsd:s*e}}var Pn=class extends A{name="estimate-pool-yield";description=`Estimate daily / weekly / monthly / yearly fee yield for a USD deposit into a Uniswap V3 pool. Answers questions like: "If I put $1000 into the USDC/WETH 0.05% pool, how much per day?", "b\u1ECF 500$ v\xE0o pool ETH/USDC 0.3% m\u1ED7i ng\xE0y l\u1EDDi bao nhi\xEAu?", "APR of WBTC/ETH 0.3% on Arbitrum". BEHAVIOR (designed to minimize back-and-forth with the user):
|
|
186
|
+
}`,r=await this.querySubgraph(t,n);if(!r?.position?.pool)return null;let o=r.position,a=this.mapPool(o.pool,t),i=await this.fetchDefiLlamaUniswap(),l=i.length>0?this.enrichWithLlama([a],i)[0]:a,c=l.feeTierBps,u=l.feeTierPercent;return{position:{positionId:o.id,poolAddress:l.poolAddress,pair:l.pair,token0:{symbol:l.token0.symbol,address:l.token0.address},token1:{symbol:l.token1.symbol,address:l.token1.address},feeTierBps:c,feeTierPercent:u,chain:l.chain,liquidity:o.liquidity,depositedToken0:o.depositedToken0,depositedToken1:o.depositedToken1,withdrawnToken0:o.withdrawnToken0,withdrawnToken1:o.withdrawnToken1,collectedFeesToken0:o.collectedFeesToken0,collectedFeesToken1:o.collectedFeesToken1},pool:l}}async getCoinPoolPairs(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let r=(await this.fetchCoinPoolV2Items(t)).map(o=>this.mapCoinPoolV2Item(o)).filter(o=>o!==null);if(e.tokens&&e.tokens.length>=2){let o=e.tokens[0].toUpperCase(),a=e.tokens[1].toUpperCase();r=r.filter(i=>{let[l="",c=""]=i.pair.toUpperCase().split("/");return l.includes(o)&&c.includes(a)||l.includes(a)&&c.includes(o)})}return r}async getCoinPoolByAddress(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let n=e.poolAddress.toLowerCase();return(await this.fetchCoinPoolV2Items(t)).filter(o=>o.poolId?.toLowerCase()===n).map(o=>this.mapCoinPoolV2Item(o)).filter(o=>o!==null).sort((o,a)=>(a.apr??-1/0)-(o.apr??-1/0))}async fetchCoinPoolV2Items(e){if(!this.coinPoolBaseUrl)return[];try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,n=await x.get(t);if(!n.ok)throw new Error(R(n));return n.data?.data?.items||[]}catch{return[]}}mapCoinPoolV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,n=e.token1.decimal??18,r=P=>P==null||!Number.isFinite(P)?0:Math.pow(1.0001,P)*Math.pow(10,t-n),o=r(e.minTick),a=r(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,u=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),d=u?o:a>0?1/a:0,p=u?a:o>0?1/o:0,h=u?c:c>0?1/c:0,f=u?e.token0.symbol:e.token1.symbol,m=u?e.token1.symbol:e.token0.symbol;if(!h||!d&&!p)return null;let g=Math.min(d,p),y=Math.max(d,p);if(h<g||h>y)return null;let b=Number(e.fee),w=Oa[b]??b/1e4,k=typeof e.apr=="number"?e.apr:typeof e.aprAvg=="number"?e.aprAvg:null,T=typeof e.aprAvg=="number"?e.aprAvg:null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:T,token0Price:i,token1Price:l,priceRange:{minPrice:ne(d),maxPrice:ne(p),currentPrice:ne(h),baseToken:f,quoteToken:m}}}};var rt=class{config;constructor(e){this.config=e}hasIntegratedApproval(){return!1}};var fu="https://exchange-api.keyring.app/admin/setting?configs=others",yu="https://api.coinpool.app/config/bridgeProviderByChain",bu="https://coinpool-api-op.bacoor-test001.xyz/config/bridgeProviderByChain";function wu(s){let e=null,t=null;return async()=>e||t||(t=(async()=>{try{return e=await s(),e}catch{return null}finally{t=null}})(),t)}async function Fa(s){return(await x.get(s,{headers:{Accept:"application/json"}})).data}var ku=wu(async()=>(await Fa(fu))?.others??null),Bo={prod:null,dev:null},ao={prod:null,dev:null};async function Tu(s){let e=s?"prod":"dev";if(Bo[e])return Bo[e];if(ao[e])return ao[e];let t=s?yu:bu;return ao[e]=(async()=>{try{let n=await Fa(t);return Bo[e]=n?.data??null,Bo[e]}catch{return null}finally{ao[e]=null}})(),ao[e]}function vu(s){if(!s)return null;try{let e=JSON.parse(s);return e&&typeof e=="object"?e:null}catch{return null}}function Ma(s){if(s==null)return 0;let e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:0}function Au(s){return s==="debridge"||s==="relay"}async function $o(s,e){let n=(await Tu(e))?.[String(s)];return Au(n)?n:null}async function mn(s,e){let t=await ku();if(!t)return null;let n,r;if(s==="debridge")n=vu(t.affiliateRecipient)?.[String(e)],r=Ma(t.AFFILIATE_FEE_PERENT);else if(s==="relay")n=t.RELAY_AFFILIATE_FEE_RECIPIENT,r=Ma(t.RELAY_AFFILIATE_FEE_PERCENT);else return null;return!n||r<=0?null:{affiliateFeeRecipient:n,affiliateFeePercent:r}}var Su="https://dln.debridge.finance/v1.0",Pu="0x0000000000000000000000000000000000000000",xu=new Set([429,500]),Cu=5,_u=1e3,Eu=s=>new Promise(e=>setTimeout(e,s)),hn=class extends rt{apiBaseUrl;accessToken;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Su,this.accessToken=e.accessToken??"d6c45897b8f6"}getProviderName(){return"debridge"}hasIntegratedApproval(){return!1}async getQuote(e){let{srcChainId:t,srcTokenAddress:n,srcTokenAmount:r,dstChainId:o,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c,isCrossChain:u}=e,d=u??t!==o,p=await mn(this.getProviderName(),t);try{if(d){let m={srcChainId:String(t),srcChainTokenIn:n,srcChainTokenInAmount:r,dstChainId:String(o),dstChainTokenOut:a,dstChainTokenOutRecipient:i,srcChainOrderAuthorityAddress:l,dstChainOrderAuthorityAddress:i,accesstoken:this.accessToken};p&&(m.affiliateFeeRecipient=p.affiliateFeeRecipient,m.affiliateFeePercent=p.affiliateFeePercent);let g=await this.get(`${this.apiBaseUrl}/dln/order/create-tx`,m);return g.error||g.errorMessage?{success:!1,error:g.error??g.errorMessage,errorMessage:g.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:g.tx,estimation:g.estimation,isCrossChain:!0,srcChainId:t,dstChainId:o,raw:g}}let h={chainId:String(t),tokenIn:n,tokenInAmount:r,tokenOut:a,tokenOutRecipient:i,accesstoken:this.accessToken};p&&(h.affiliateFeeRecipient=p.affiliateFeeRecipient,h.affiliateFeePercent=p.affiliateFeePercent),c!==void 0&&(h.slippage=c);let f=await this.get(`${this.apiBaseUrl}/chain/transaction`,h);return f.error||f.errorMessage?{success:!1,error:f.error??f.errorMessage,errorMessage:f.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:f.tx,isCrossChain:!1,srcChainId:t,dstChainId:t,raw:f}}catch(h){return{success:!1,error:h,errorMessage:h instanceof Error?h.message:"Failed to fetch quote"}}}async checkApproval(e){let{chain:t,userAddress:n,tokenAddress:r,amount:o}=e,a=e.quoteData?.tx?.to;if(!a)return{isNeeded:!1,error:"No contract address found in quote"};if(!r||r.toLowerCase()===Pu)return{isNeeded:!1,integrated:!1,contractAddress:a,message:"Native coin needs no approval."};let i=await this.readAllowance(t,r,n,a);if(i===null)return{isNeeded:!0,integrated:!1,contractAddress:a,message:"Could not read allowance; approval required before the swap."};let l;try{l=BigInt(o)}catch{l=0n}return i>=l?{isNeeded:!1,integrated:!1,contractAddress:a,message:"Sufficient allowance already granted."}:{isNeeded:!0,integrated:!1,contractAddress:a,message:"Approval required: current allowance is below the swap amount."}}async readAllowance(e,t,n,r){if(!e)return null;let o=l=>l.toLowerCase().replace(/^0x/,"").padStart(64,"0"),a=`0xdd62ed3e${o(n)}${o(r)}`,i=await Tr(e,t,a);if(typeof i!="string"||!/^0x[0-9a-fA-F]*$/.test(i)||i==="0x")return null;try{return BigInt(i)}catch{return null}}async executeSwap(e){let{quoteData:t}=e;return{success:!0,provider:"debridge",txData:t.tx??void 0,estimation:t.estimation}}async trackTransaction(e){let{requestIdOrTxHash:t}=e;try{let n=await this.get(`${this.apiBaseUrl}/dln/tx/${t}/order-ids`,{accesstoken:this.accessToken});if(!n.orderIds?.length)return{success:!1,status:"PENDING"};let r=n.orderIds[0];switch(((await this.get(`${this.apiBaseUrl}/dln/order/${r}/status`,{accesstoken:this.accessToken})).status??"").toUpperCase()){case"FULFILLED":case"SENTUNLOCK":case"CLAIMEDUNLOCK":return{success:!0,status:"COMPLETED"};case"ORDERCANCELLED":case"SENTORDERCANCEL":case"CLAIMEDORDERCANCEL":return{success:!0,status:"FAILED"};default:return{success:!0,status:"PENDING"}}}catch(n){return{success:!1,status:"ERROR",error:n instanceof Error?n.message:String(n)}}}async get(e,t){let n=Object.entries(t).map(([a,i])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(i))}`).join("&"),r=n?`${e}?${n}`:e,o=await x.get(r,{headers:{Accept:"application/json"}});for(let a=0;a<Cu&&xu.has(o.status);a++)await Eu(_u),o=await x.get(r,{headers:{Accept:"application/json"}});return o.data}};var Nu="https://api.relay.link";function qa(s){return s===7565164||s==="7565164"?792703809:s}var gn=class extends rt{apiBaseUrl;apiKey;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??Nu,this.apiKey=e.apiKey}getProviderName(){return"relay"}hasIntegratedApproval(){return!0}async getQuote(e){let{srcChainId:t,srcTokenAddress:n,srcTokenAmount:r,dstChainId:o,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c}=e,u=await mn(this.getProviderName(),t),d={user:i||l,originChainId:qa(t),destinationChainId:qa(o),originCurrency:n,destinationCurrency:a,amount:r,recipient:i||l,tradeType:"EXACT_INPUT"};u&&(d.appFees=[{recipient:u.affiliateFeeRecipient,fee:Math.floor(u.affiliateFeePercent*100)}]),typeof c=="number"&&Number.isFinite(c)&&(d.slippageTolerance=Math.floor(c*100).toString());try{let p=await this.request("/quote/v2","POST",d);if(!p||p.error)return{success:!1,error:p?.error??"Unknown error",errorMessage:p?.message??"Failed to fetch quote from Relay"};let h=p.steps?.find(b=>b.id==="approve"),f=p.steps?.find(b=>b.id==="swap"||b.id==="deposit"),m=f?.items?.[0]?.data,g=Array.isArray(m?.instructions);return{success:!0,provider:"relay",tx:m?g?{data:{instructions:m.instructions??[],addressLookupTableAddresses:m.addressLookupTableAddresses??[]},chainId:m.chainId}:{from:m.from,to:m.to,data:m.data,value:m.value,chainId:m.chainId,maxFeePerGas:m.maxFeePerGas,maxPriorityFeePerGas:m.maxPriorityFeePerGas}:null,isCrossChain:t!==o,srcChainId:t,dstChainId:o,raw:{steps:p.steps,fees:p.fees,details:p.details,approveStep:h,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?.approveStep;if(t){let n=t.items?.[0]?.data;return{isNeeded:!0,integrated:!0,approvalData:n,contractAddress:n?.to,message:"Approval step is included in quote and will be executed first."}}return{isNeeded:!1,integrated:!0,message:"No approval needed or already approved"}}async executeSwap(e){let{quoteData:t}=e,n=t.raw;return n?.steps?{success:!0,provider:"relay",steps:n.steps,estimation:t.estimation}:{success:!1,error:"Invalid quote data"}}async trackTransaction(e){try{let n=(await this.request("/intents/status/v3","GET",{requestId:e.requestIdOrTxHash})).status??"";return n==="success"||n==="refunded"?{success:!0,status:"COMPLETED"}:n==="failure"||n==="expired"?{success:!0,status:"FAILED"}:{success:!0,status:"PENDING"}}catch(t){return{success:!1,status:"ERROR",error:t instanceof Error?t.message:String(t)}}}async request(e,t,n){let r={"Content-Type":"application/json"};this.apiKey&&(r["x-api-key"]=this.apiKey);let o=`${this.apiBaseUrl}${e}`,a;if(t==="GET"&&n){let l=Object.entries(n).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(String(u))}`).join("&");o=`${o}?${l}`}else t==="POST"&&n&&(a=n);let i=await x.request(t,o,a,{headers:r});if(!i.ok)throw new Error(R(i));return i.data}};var Ho={debridge:{apiBaseUrl:"https://dln.debridge.finance/v1.0",accessToken:"d6c45897b8f6"},relay:{apiBaseUrl:"https://api.relay.link"}},io="debridge";function Ru(s){if(s==null)return null;let e=typeof s=="number"?s:Number(s);return Number.isFinite(e)?e:null}var vt=class{providerConfig;isProduction;cache=new Map;constructor(e=Ho,t=!0){this.providerConfig=e,this.isProduction=t}async getService(e){let t=await this.getActiveProvider(e),n=this.cache.get(t);if(n)return n;let r=this.createService(t);return this.cache.set(t,r),r}async getServiceByProvider(e){let t=this.cache.get(e);if(t)return t;let n=this.createService(e);return this.cache.set(e,n),n}async getActiveProvider(e){let t=Ru(e);return t===null?io:await $o(t,this.isProduction)??io}async isProviderActive(e,t){return await this.getActiveProvider(t)===e}getAvailableProviders(){return Object.keys(this.providerConfig)}clearCache(){this.cache.clear()}createService(e){let t=this.providerConfig[e]??{};switch(e){case"debridge":return new hn(t);case"relay":return new gn(t);default:{let n=e;throw new Error(`Unknown swap provider: ${String(n)}`)}}}},Fe=new vt;var Uu="https://api.coinpool.app/config/addresses",Iu="https://coinpool-api-op.bacoor-test001.xyz/config/addresses",Vo={prod:null,dev:null},lo={prod:null,dev:null};async function Ba(s){let e=s?"prod":"dev";if(Vo[e])return Vo[e];if(lo[e])return lo[e];let t=s?Uu:Iu;return lo[e]=(async()=>{try{let r=(await x.get(t,{headers:{Accept:"application/json"}})).data;return Vo[e]=r?.data??null,Vo[e]}catch{return null}finally{lo[e]=null}})(),lo[e]}function Lu(s){let e=s.trim();if(/^0x[0-9a-fA-F]+$/.test(e)){let t=Number.parseInt(e,16);return Number.isFinite(t)?String(t):null}return/^\d+$/.test(e)?e:null}async function $a(s,e,t){let n=await Ba(t);if(!n)return;let r=Lu(e);if(!r)return;let o=n[s]?.[r];return Array.isArray(o)?o[0]:typeof o=="string"?o:void 0}async function Wo(s,e){return $a("createPoolProxyV3",s,e)}var Du=/^0x[0-9a-fA-F]{40}$/;async function Ou(s,e){let n=(await Ba(e))?.[s];if(!n||typeof n!="object")return[];let r=[];for(let[o,a]of Object.entries(n)){let i=Array.isArray(a)?a[0]:a;typeof i=="string"&&Du.test(i.trim())&&r.push(o)}return r}async function Yo(s){return Ou("createPoolProxyV3",s)}async function Go(s,e){return $a("nftPositionUniswap",s,e)}var $="0x0000000000000000000000000000000000000000",Ha={"0x1":{hexId:"0x1",name:"Ethereum",defaultRpc:ke["0x1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa":{hexId:"0xa",name:"Optimism",defaultRpc:ke["0xa"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0x38":{hexId:"0x38",name:"BNB Smart Chain",defaultRpc:ke["0x38"],native:{symbol:"BNB",name:"BNB",decimals:18,coingeckoId:"binancecoin"},defaultMintGasLimit:12e5},"0x89":{hexId:"0x89",name:"Polygon",defaultRpc:ke["0x89"],native:{symbol:"POL",name:"Polygon",decimals:18,coingeckoId:"matic-network"},defaultMintGasLimit:12e5},"0x2105":{hexId:"0x2105",name:"Base",defaultRpc:ke["0x2105"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa4b1":{hexId:"0xa4b1",name:"Arbitrum One",defaultRpc:ke["0xa4b1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:22e5},"0xa86a":{hexId:"0xa86a",name:"Avalanche",defaultRpc:ke["0xa86a"],native:{symbol:"AVAX",name:"Avalanche",decimals:18,coingeckoId:"avalanche-2"},defaultMintGasLimit:12e5},"0xe708":{hexId:"0xe708",name:"Linea",defaultRpc:ke["0xe708"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5}};function se(s){return Ha[s.toLowerCase()]}function fn(s){return se(s)?.native}var Va="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";function Zr(s){let e=s.stableTicks??3,t=s.widePercent??{down:50,up:100},n=Ce(s.currentTick,s.token0Decimals,s.token1Decimals),r=De(Le(s.currentTick-e*s.tickSpacing,s.tickSpacing,"down")),o=De(Le(s.currentTick+e*s.tickSpacing,s.tickSpacing,"up")),a=n*(1-t.down/100),i=n*(1+t.up/100),l=ht(a,s.token0Decimals,s.token1Decimals),c=ht(i,s.token0Decimals,s.token1Decimals),u=De(Le(l,s.tickSpacing,"down")),d=De(Le(c,s.tickSpacing,"up")),p=(h,f,m,g,y)=>{let b=Ce(g,s.token0Decimals,s.token1Decimals),w=Ce(y,s.token0Decimals,s.token1Decimals);return{id:h,label:f,description:m,tickLower:g,tickUpper:y,minPrice:b,maxPrice:w,minPercentChange:(b-n)/n*100,maxPercentChange:(w-n)/n*100}};return[p("stable","Stable","Good for stablecoins or low volatility pairs",r,o),p("wide","Wide","Good for volatile pairs",u,d)]}var Mu=K("slot0()"),Fu=K("liquidity()"),qu=K("tickSpacing()"),Bu=K("fee()"),$u=K("token0()"),Hu=K("token1()"),Vu=K("decimals()"),de=class{swapFactory;isProduction;constructor(e){this.isProduction=e?.isProduction??!0,this.swapFactory=e?.swapFactory??(this.isProduction?Fe:new vt(void 0,!1))}isSupported(e){if(!e)return!1;let t=M(e)??e.toLowerCase();return!!se(t)}listSupportedChains(){return Object.keys(Ha).filter(e=>_e(e))}getRpcUrl(e){let t=Xe(e);if(t)return t;let n=se(e);if(!n)throw new Error(`Unsupported chain: ${e}`);return n.defaultRpc}async getGatewayAddress(e){return Wo(e,this.isProduction)}async isAddLiquiditySupported(e){return this.isSupported(e)&&!!await this.getGatewayAddress(e)}async listAddLiquiditySupportedChains(){let e=await Yo(this.isProduction),t=[];for(let n of e){let r=M(n);r&&se(r)&&!t.includes(r)&&t.push(r)}return t.length>0?t:this.listSupportedChains()}async getPositionManagerAddress(e){return Go(e,this.isProduction)}async ethCall(e,t,n){return He(this.getRpcUrl(e),"eth_call",[{to:t,data:n},"latest"])}async getNativeBalance(e,t){let n=await He(this.getRpcUrl(e),"eth_getBalance",[t,"latest"]);return BigInt(n)}async getGasPrice(e){let t=await He(this.getRpcUrl(e),"eth_gasPrice",[]);return BigInt(t)}async getTransactionReceipt(e,t){return await He(this.getRpcUrl(e),"eth_getTransactionReceipt",[t])}async extractMintedNftId(e,t){let n=await this.getPositionManagerAddress(e);if(!n)return null;let r=n.toLowerCase();for(let o of t.logs??[]){if((o.address??"").toLowerCase()!==r)continue;let a=o.topics??[];if(!(a.length<4||a[0]?.toLowerCase()!==Va||"0x"+a[1].slice(-40).toLowerCase()!==$))try{return BigInt(a[3]).toString()}catch{return null}}return null}async estimateGasReserveWei(e){let t=se(e);if(!t)throw new Error(`Unsupported chain: ${e}`);let n=await this.getGasPrice(e);return BigInt(t.defaultMintGasLimit)*n*18n/10n}async readPoolOnchain(e,t){let[n,r,o,a,i,l]=await Promise.all([this.ethCall(e,t,Mu),this.ethCall(e,t,Fu),this.ethCall(e,t,qu),this.ethCall(e,t,Bu),this.ethCall(e,t,$u),this.ethCall(e,t,Hu)]),c=G(n),u=Oe(c,0),d=br(c,64),p=Oe(G(r),0),h=Number(br(G(o),0)),f=Number(Oe(G(a),0)),m=wr(G(i),0),g=wr(G(l),0),[y,b]=await Promise.all([this.readErc20Decimals(e,m),this.readErc20Decimals(e,g)]),w=Ss(u,y,b);return{poolAddress:t,chainId:e,fee:f,tickSpacing:h,liquidity:p,sqrtPriceX96:u,currentTick:d,token0:m,token1:g,currentPrice:w}}async readErc20Decimals(e,t){if(t.toLowerCase()===$)return 18;let n=await this.ethCall(e,t,Vu);return Number(Oe(G(n),0))}async getNativePriceUsd(e){let t=se(e);if(!t)return null;try{let n=`https://api.coingecko.com/api/v3/simple/price?ids=${t.native.coingeckoId}&vs_currencies=usd`,r=await x.get(n);if(!r.ok)return null;let a=r.data[t.native.coingeckoId]?.usd;return typeof a=="number"?a:null}catch{return null}}splitNativeAmountForRange(e){let{nativeAmountWei:t,pool:n,tickLower:r,tickUpper:o,token0Decimals:a,token1Decimals:i}=e,l=2**96,c=Number(n.sqrtPriceX96)/l,u=Math.pow(1.0001,r/2),d=Math.pow(1.0001,o/2);if(c<=u)return{ratio0:1,ratio1:0,amountInFor0Wei:t,amountInFor1Wei:0n};if(c>=d)return{ratio0:0,ratio1:1,amountInFor0Wei:0n,amountInFor1Wei:t};let p=1/c-1/d,h=c-u,f=c*c,m=p*f,y=m+h;if(!Number.isFinite(y)||y<=0)throw new Error("splitNativeAmountForRange: invalid total value");let b=m/y,w=1-b,k=1000000000000000n,T=BigInt(Math.floor(b*Number(k))),P=t*T/k,S=t-P;return{ratio0:b,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 r=await(await this.swapFactory.getService(t)).getQuote({srcChainId:t,srcTokenAddress:e.tokenIn,srcTokenAmount:e.tokenInAmount,dstChainId:t,dstTokenAddress:e.tokenOut,recipientAddress:e.tokenOutRecipient,senderAddress:e.senderAddress??e.tokenOutRecipient,slippage:e.slippage,isCrossChain:!1});if(!r.success||!r.tx)throw new Error(r.errorMessage??"Swap quote failed");let o=r.tx;if(!o.to||typeof o.data!="string")throw new Error("Swap quote returned an unsupported tx shape (non-EVM payload?)");let a=r.raw??{},i=a.tokenOut?.minAmount??a.details?.currencyOut?.minimumAmount??"0";return{to:o.to,data:o.data,value:o.value??"0",minAmountOut:i}}encodeMintCalldata(e){if(e.paymentInfo.length!==2||e.exchanges.length!==2)throw new Error("encodeMintCalldata: paymentInfo and exchanges must each have length 2");let t=K("mint((address,uint256,address,uint256)[2],(address,bytes,uint256)[2],(uint24,uint256,uint256,int24,int24))"),n=e.paymentInfo.map(f=>ze(f.tokenIn)+ae(f.tokenInAmount)+ze(f.tokenOut)+ae(f.tokenOutAmount)).join(""),o=e.exchanges.map(f=>{let m=G(f.data||"0x"),g=m.length/2,y=ae(g),b=(64-m.length%64)%64,w=m+"0".repeat(b);return{head:ze(f.to)+ae(96)+ae(f.value),body:y+w}}).map(f=>f.head+f.body),a=o.length*32,i=[];for(let f of o)i.push(ae(a)),a+=f.length/2;let l=i.join("")+o.join(""),c=ae(e.fee,24)+ae(e.amount0Min)+ae(e.amount1Min)+yr(e.tickLower)+yr(e.tickUpper),p=256+32+160,h=n+ae(p)+c+l;return t+h}_keccak(e){return Ps(e)}};var Wu={"0x1":"ethereum","0xa":"optimism","0x38":"bnb","0x89":"polygon","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avalanche"},Yu=/^0x[a-fA-F0-9]{40}$/;function Gu(s,e){if(typeof s!="string"||typeof e!="string")return null;let t=Wu[s.toLowerCase()];return!t||!Yu.test(e)?null:`https://app.uniswap.org/explore/pools/${t}/${e}`}function Ee(s,e){let t=Gu(s,e);return t?{uniswapUrl:t}:{}}var Wa=Object.keys(pn),Ae="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 me(){return Wa.filter(s=>_e(s)).map(s=>v(s)).join(", ")}function Se(){return{kind:"info",async listSupported(){return Wa.filter(s=>_e(s))},async isSupported(s){if(!s)return!1;let e=M(s)??s.toLowerCase();return Object.prototype.hasOwnProperty.call(pn,e)}}}function yn(s){return{kind:"add-liquidity",listSupported:()=>s.listAddLiquiditySupportedChains(),isSupported:e=>s.isAddLiquiditySupported(e)}}function es(s,e,t){let n=r=>typeof r=="string"&&r.trim()!=="";if(n(s))return M(s)??s.trim();if(n(e?.chain))return M(e.chain)??e.chain.trim();if(n(e?.walletAddress))throw new Q(typeof e?.query=="string"?e.query:void 0,t);return Te}async function he(s,e,t){let n=await s.listSupported(),r=es(e,t,n);return await s.isSupported(r)?{ok:!0,chain:r}:{ok:!1,result:ts(r,n,s.kind)}}function ts(s,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:v(s),supportedChains:e.map(r=>v(r))}}var Ko="{pair}";var st=[{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 yourself \u2014 the chain these pools are on is appended automatically.`,required:!1}],Ne=' 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 Re(s,e,t){return ns(s,typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",t)}function ns(s,e,t,n){let r=typeof n=="string"&&n.trim()?` (${n.trim()})`:"",o=[];for(let a of s){if(o.length>=5)break;let i=a.token0?.symbol?.trim(),l=a.token1?.symbol?.trim();if(!i||!l)continue;let c=Ku(i,l,a.feeTierPercent);o.push({label:Ya(e,c,`Add liquidity to ${Ko}`),prompt:Ya(t,c,`add liquidity to ${Ko}`)+r})}return o}function Ku(s,e,t){let n=`${s}/${e}`;return typeof t=="number"&&Number.isFinite(t)?`${n} ${ju(t)}%`:n}function ju(s){return Number(s.toFixed(4)).toString()}function Ya(s,e,t){return(s&&s.includes(Ko)?s:t).split(Ko).join(e).replace(/\s+/g," ").trim()}var fe="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. ",ye="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. \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. ",be="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. ",ie="End with a brief reminder that yields fluctuate and concentrated LPs face impermanent loss (informational, not financial advice). ",Ue=`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 zu=["tvl","volume1Day","volume1Week","volume30Day","txCount","apr"],Xu=["V2","V3","V4"],bn=class extends A{name="get-top-pools";description=`List the top Uniswap liquidity pools on a given EVM chain, ranked by TVL by default. Returns each pool's address, fee tier, protocol version, both tokens (symbol, name, address, decimals), TVL, transaction count, and rolling volume buckets (1d / 1w / 30d). 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 (ExploreStats gateway). Supports: `+me();category="blockchain-data";parameters=[{name:"chain",type:"string",description:Ae,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", "volume1Week", "volume30Day", "txCount", or "apr" (estimated annualized fee yield). 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},...st];service;subgraphFallback;pool;constructor(e,t){super(),this.service=new pe(e),this.subgraphFallback=new re(t),this.pool=new de({isProduction:e?.isProduction})}async run(e,t){let n=e.forAddLiquidity===!0,r=n?yn(this.pool):Se(),o=await r.listSupported(),a=es(e.chain,t,o),i=this.parseProtocolVersion(e.protocolVersion),l=this.parseSortKey(e.sortBy),c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,u=!n&&e.multichain===!0;if(!u&&!await r.isSupported(a))return ts(a,o,r.kind);let d=await this.service.getTopPools({chain:a,protocolVersion:i,sortBy:l,limit:c,multichain:u});if(!d.success)return{error:d.error||"Failed to fetch top pools"};let p=(d.data??[]).map(w=>this.formatPool(w)),h="uniswap";if(p.length===0&&i==="V3"){let w=await this.fetchV3Fallback(a,l,c);w.length>0&&(p=w,h="subgraph")}let f=p.map(w=>this.withExpertSignals(w)),m=await this.pool.isAddLiquiditySupported(a)?Re(f,e,v(a)):[],g=h==="subgraph",y=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). `:"")+fe+`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, ${y}, 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. `+ye+"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. "+be+ie+"Mention the chain and the sort metric in the intro line. "+Ue+(m.length>0?Ne:""),chain:a,protocolVersion:i,sortBy:l,source:h,count:f.length,pools:f.map(w=>({...w,...Ee(a,w.address)})),...m.length>0?{actionButtons:m}:{}}}withExpertSignals(e){let t=e.tvlUsd,n=e.volume1DayUsd,r=typeof t=="number"&&t>0&&typeof n=="number"?Math.round(n/t*1e3)/1e3:void 0;return{...e,volumeToTvlRatio:r}}async fetchV3Fallback(e,t,n){try{return(await this.subgraphFallback.getTrendingPools({chain:e})).map(i=>this.formatSubgraphPool(i,e)).sort((i,l)=>this.fallbackSortValue(l,t)-this.fallbackSortValue(i,t)).slice(0,n)}catch{return[]}}fallbackSortValue(e,t){switch(t){case"apr":return e.apr??0;case"volume1Day":case"volume1Week":case"volume30Day":return e.volume1DayUsd??0;default:return e.tvlUsd??0}}formatSubgraphPool(e,t){return{apr:e.apr??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,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(Xu.includes(t))return t}return"V3"}parseSortKey(e){if(typeof e=="string"){let t=e.trim();if(zu.includes(t))return t}return"tvl"}formatPool(e){return{apr:e.apr,address:e.id,chain:e.chain,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,tvlUsd:e.totalLiquidity?.value,fee24hUsd:e.fee24hUsd,volume1DayUsd:e.volume1Day?.value,volume1WeekUsd:e.volume1Week?.value,volume30DayUsd:e.volume30Day?.value,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 os={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114},Qu={100:.01,500:.05,3e3:.3,1e4:1},at=class{coinPoolBaseUrl;constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}isSupported(e){let t=M(e);return!!(t&&os[t])}listSupportedChains(){return Object.keys(os).filter(e=>M(e)===e)}numericChainId(e){let t=M(e);return t?os[t]:void 0}async getPairs(e){let t=this.numericChainId(e.chain);if(!t)return[];let r=(await this.fetchV2Items(t)).map(o=>this.mapV2Item(o)).filter(o=>o!==null);if(e.tokens&&e.tokens.length>=2){let o=e.tokens[0].toUpperCase(),a=e.tokens[1].toUpperCase(),i=(l,c)=>l.includes(c)||c.includes(l);r=r.filter(l=>{let[c="",u=""]=l.pair.toUpperCase().split("/");return i(c,o)&&i(u,a)||i(c,a)&&i(u,o)})}return r}async getByAddress(e){let t=this.numericChainId(e.chain);if(!t)return[];let n=e.poolAddress.toLowerCase();return(await this.fetchV2Items(t)).filter(o=>o.poolId?.toLowerCase()===n).map(o=>this.mapV2Item(o)).filter(o=>o!==null).sort((o,a)=>(a.apr??-1/0)-(o.apr??-1/0))}async fetchV2Items(e){try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,n=await x.get(t);if(!n.ok)throw new Error(R(n));return n.data?.data?.items||[]}catch{return[]}}mapV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,n=e.token1.decimal??18,r=P=>P==null||!Number.isFinite(P)?0:Math.pow(1.0001,P)*Math.pow(10,t-n),o=r(e.minTick),a=r(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,u=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),d=u?o:a>0?1/a:0,p=u?a:o>0?1/o:0,h=u?c:c>0?1/c:0,f=u?e.token0.symbol:e.token1.symbol,m=u?e.token1.symbol:e.token0.symbol;if(!h||!d&&!p)return null;let g=Math.min(d,p),y=Math.max(d,p);if(h<g||h>y)return null;let b=Number(e.fee),w=Qu[b]??b/1e4,k=typeof e.apr=="number"?e.apr:typeof e.aprAvg=="number"?e.aprAvg:null,T=typeof e.aprAvg=="number"?e.aprAvg:null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:T,token0Price:i,token1Price:l,priceRange:{minPrice:ne(d),maxPrice:ne(p),currentPrice:ne(h),baseToken:f,quoteToken:m}}}};var Ju=365,Ga=/^0x[a-fA-F0-9]{40}$/,Zu=6,wn=class extends A{name="get-pool-detail";description="Get detailed stats for a Uniswap V3 pool by token pair (and optional fee tier). Always runs a search first and filters by the provided symbols + fee tier. When the filter resolves to exactly one pool, returns its full detail. When the pair is fully named but NO fee tier is given, returns detail plus a comparative analysis of ALL the pair's fee-tier variants (no need to ask the user to pick). When only one token is given (so the matches are different pairs), returns a `candidates` list \u2014 show it and ask which pair they want, then re-call this tool with the missing info. Detail response includes: pool address, fee tier (bps and %), both tokens (symbol, name, address, decimals, USD price), token0/token1 reserves, total TVL with 24h % change, 24h volume, weekly historical volume series, total tx count, and a derived APR estimate (fees \xF7 TVL \xD7 365). 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: "+me();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:Ae,required:!1},...st];service;coinPool;pool;constructor(e,t){super(),this.service=new pe(e),this.coinPool=new at(t),this.pool=new de({isProduction:e?.isProduction})}async run(e,t){let n=await he(Se(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=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(!o)return{error:"token0Symbol is required. Provide at least one token symbol; add token1Symbol and feeTier to narrow the result."};let l=a?`${o} ${a}`:o,c=await this.service.searchPools({query:l,chain:r,page:1,size:100,protocolVersion:"V3"});if(!c.success)return{error:c.error||"Pool search failed"};let u=c.data??[],p=u.filter(g=>this.matchesFilter(g,o,a,i,"ordered")),h=!1;if(p.length===0&&a){let g=u.filter(y=>this.matchesFilter(y,o,a,i,"reversed"));g.length>0&&(p=g,h=!0)}if(p.length===0)return{error:`No V3 pool matched ${this.describeQuery(o,a,i)} on ${v(r)}. Verify the symbols and fee tier with the user.`};if(p.length===1){let g=p[0];if(!g.id||!Ga.test(g.id))return{error:"Resolved pool has no valid address"};let[y,b]=await Promise.all([this.service.getV3PoolDetail({address:g.id,chain:r}),this.fetchPriceRanges(r,g.id,g.token0?.symbol,g.token1?.symbol)]);if(!y.success||!y.data)return{error:y.error||"Failed to fetch pool detail"};let w={...this.formatPool(y.data),...Ee(r,g.id)},k=await this.pool.isAddLiquiditySupported(r)?Re([w],e,v(r)):[];return{priceRanges:b,_instructions:fe+"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. "+ye+be+'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`. 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. '+ie+Ue+(k.length>0?Ne:""),pairOrderMatched:h?"reversed":"ordered",pool:w,...k.length>0?{actionButtons:k}:{}}}if(a){let g=this.rankCandidates(p).slice(0,Zu),b=(await Promise.all(g.map(async w=>{if(!w.id||!Ga.test(w.id))return;let k=await this.service.getV3PoolDetail({address:w.id,chain:r});if(!(!k.success||!k.data))return{...this.formatPool(k.data),...Ee(r,w.id)}}))).filter(w=>w!=null);if(b.length>0){let w=await this.pool.isAddLiquiditySupported(r)?Re(b,e,v(r)):[];return{_instructions:fe+"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. "+ye+"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. "+be+ie+Ue+(w.length>0?Ne:""),chain:r,pairOrderMatched:h?"reversed":"ordered",multiFeeTier:!0,count:b.length,pools:b,...w.length>0?{actionButtons:w}:{}}}}let f=this.rankCandidates(p).slice(0,10).map(g=>{let y=this.formatCandidate(g);return{...y,...Ee(r,y.address)}}),m=await this.pool.isAddLiquiditySupported(r)?Re(f,e,v(r)):[];return{_instructions:"The filter matched multiple pools. Render them as a numbered list (pair, fee tier %, 24h volume) and ask the user which one they want to see. Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. When they answer, re-call this tool with their selection \u2014 pass token0Symbol + token1Symbol + feeTier (use the exact feeTier in bps from the chosen candidate). Format numbers human-readably (e.g. $12.5M, 0.05%). Do NOT mention tool/API names."+(m.length>0?Ne:""),chain:r,pairOrderMatched:h?"reversed":"ordered",reason:this.candidateReason(o,a,i),missing:this.missingFields(a,i),candidates:f,...m.length>0?{actionButtons:m}:{}}}matchesFilter(e,t,n,r,o){if(r!=null&&e.feeTier!==r)return!1;let a=(e.token0?.symbol??"").toLowerCase(),i=(e.token1?.symbol??"").toLowerCase(),l=t.toLowerCase();if(n){let c=n.toLowerCase();return o==="reversed"?this.symbolIncludes(a,c)&&this.symbolIncludes(i,l):this.symbolIncludes(a,l)&&this.symbolIncludes(i,c)}return this.symbolIncludes(a,l)||this.symbolIncludes(i,l)}symbolIncludes(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}describeQuery(e,t,n){let r=t?`${e}/${t}`:e;return n!=null?`${r} at fee tier ${n} bps`:r}candidateReason(e,t,n){return t?n==null?`Multiple fee tiers exist for ${e}/${t}. Ask the user which fee tier they want.`:`Multiple ${e}/${t} pools share fee tier ${n} bps. Ask the user which one they meant.`:`Multiple pools contain ${e}. Ask the user for the other token (and fee tier).`}missingFields(e,t){let n=[];return e||n.push("token1Symbol"),t==null&&n.push("feeTier"),n}rankCandidates(e){return[...e].sort((t,n)=>(n.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}formatCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}async fetchPriceRanges(e,t,n,r){try{if(!this.coinPool.isSupported(e))return[];let o=await this.coinPool.getByAddress({chain:e,poolAddress:t});return o.length===0&&n&&r&&(o=await this.coinPool.getPairs({chain:e,tokens:[n,r]})),o.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}formatPool(e){let t=e.totalLiquidity?.value,n=e.volume24h?.value,r=e.feeTier,o=typeof r=="number"?r/1e4:void 0,a=typeof n=="number"&&typeof o=="number"?n*o/100:void 0,i=typeof a=="number"&&typeof t=="number"&&t>0?a/t*Ju*100:void 0,l=typeof n=="number"&&typeof t=="number"&&t>0?Math.round(n/t*1e3)/1e3:void 0;return{address:e.address,protocolVersion:e.protocolVersion,feeTierBps:r,feeTierPercent:o,tvlUsd:t,tvlChange24hPercent:e.totalLiquidityPercentChange24h?.value,volume24hUsd:n,fees24hUsd:a,aprPercent:i,volumeToTvlRatio:l,txCount:e.txCount,historicalVolumeWeek:this.formatHistorical(e.historicalVolume),token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.market?.price?.value??e.token0.price?.value,reserve:e.token0Supply,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.market?.price?.value??e.token1.price?.value,reserve:e.token1Supply,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}formatHistorical(e){if(!(!e||e.length===0))return e.map(t=>({timestamp:t.timestamp,volumeUsd:t.value}))}};var ed=["V2","V3","V4","ALL"],kn=class extends A{name="search-pools";description='Search Uniswap liquidity pools on a given chain by free-text query \u2014 a SINGLE token symbol or token name. Returns matching pools with: pool address, fee tier (bps + %), protocol version, both tokens (symbol, name, address, decimals, logo), and short-window USD volume buckets (6h / 12h / 24h). Use this tool when the user names ONE token and wants pools related to it: "find WBTC pools on Optimism", "pools containing PEPE on Ethereum", "show USDC pools". Do NOT use for: (a) two-symbol pair lookups like "USDC/WETH 0.05%" \u2014 use get-pool-detail; (b) raw 0x addresses (token or pool) \u2014 use lookup-pool-by-address; (c) chain-wide rankings with no token mentioned \u2014 use get-top-pools. Source: https://app.uniswap.org search. Supports: '+me();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:Ae,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},...st];service;pool;constructor(e){super(),this.service=new pe(e),this.pool=new de({isProduction:e?.isProduction})}async run(e,t){let n=typeof e.query=="string"?e.query.trim():"";if(!n)return{error:"Search query is required"};let r=await he(Se(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,a=typeof e.page=="number"&&Number.isFinite(e.page)&&e.page>0?Math.floor(e.page):1,i=typeof e.size=="number"&&Number.isFinite(e.size)&&e.size>0?Math.min(Math.floor(e.size),50):5,l=this.parseProtocolFilter(e.protocolVersion),c=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.floor(e.feeTier):void 0,u=await this.service.searchPools({query:n,chain:o,page:a,size:i,protocolVersion:l,feeTier:c});if(!u.success)return{error:u.error||"Failed to search pools"};let d=(u.data??[]).map(h=>this.formatPool(h)),p=await this.pool.isAddLiquiditySupported(o)?Re(d,e,v(o)):[];return{_instructions:fe+"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. "+ye+be+"When several pools share the searched token, finish with a clear TOP PICK among them. "+ie+"Mention the search query and chain in the intro. "+Ue+(p.length>0?Ne:""),query:n,chain:o,protocolVersion:l,feeTierBps:c,feeTierPercent:c!=null?c/1e4:void 0,page:a,size:i,count:d.length,pools:d.map(h=>({...h,...Ee(o,h.address)})),...p.length>0?{actionButtons:p}:{}}}parseProtocolFilter(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(ed.includes(t))return t}return"V3"}formatPool(e){let t={address:e.id,chainId:e.chainId,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0};e.apr!=null&&(t.apr=e.apr),e.tvlUsd!=null&&(t.tvlUsd=e.tvlUsd);let n=e.volume1DayUsd??e.volumeUsd24hr;n!=null&&(t.volume24hUsd=n),e.volumeUsd6hr!=null&&(t.volume6hUsd=e.volumeUsd6hr),e.volumeUsd12hr!=null&&(t.volume12hUsd=e.volumeUsd12hr),e.txCount!=null&&(t.txCount=e.txCount),e.tvlUsd!=null&&e.tvlUsd>0&&n!=null&&(t.volumeToTvlRatio=Math.round(n/e.tvlUsd*1e3)/1e3);let r=e.token0,o=e.token1;return r&&(t.token0={address:r.address,symbol:r.symbol,name:r.name,decimals:r.decimals}),o&&(t.token1={address:o.address,symbol:o.symbol,name:o.name,decimals:o.decimals}),t}};var td=365,Ka=/^0x[a-fA-F0-9]{40}$/,Tn=class extends A{name="lookup-pool-by-address";description='Resolve an unknown 0x address as either a Uniswap pool or a token, then return the appropriate data: pool detail when the address is a pool, or the list of pools containing that token when the address is a token. Use this tool when the user pastes a single address and asks about "the pool" without saying which kind. For pool detail (when the address is a pool): pair, fee tier, TVL with 24h % change, 24h volume, 24h fees, estimated APR, token reserves with USD prices, and weekly volume series. 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: '+me();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:Ae,required:!1},...st];service;pool;constructor(e){super(),this.service=new pe(e),this.pool=new de({isProduction:e?.isProduction})}async run(e,t){let n=await he(Se(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=typeof e.address=="string"?e.address.trim():"",[a,i]=await Promise.all([this.service.searchPools({query:o,chain:r,page:1,size:5,protocolVersion:"ALL"}),this.service.searchTokens({query:o,chain:r,page:1,size:5})]),l=a.success?this.findPoolByAddress(a.data??[],o):void 0;if(l)return this.handlePoolHit(l,r,e);let c=i.success?this.findTokenByAddress(i.data??[],o):void 0;return c?this.handleTokenHit(c,r,e):!a.success&&!i.success?{error:a.error||i.error||"Failed to resolve address"}:{error:`Address ${o} did not match any pool or token Uniswap knows on ${v(r)}. Verify the chain (the address may exist on a different network) or ask the user for context.`}}async handlePoolHit(e,t,n){if(!e.id)return{error:"Resolved pool has no identifier"};let r=e.protocolVersion??"V3",o=r==="V4"?await this.service.getV4PoolDetail({poolId:e.id,chain:t}):r==="V2"?Ka.test(e.id)?await this.service.getV2PoolDetail({address:e.id,chain:t}):{success:!1,error:"Resolved V2 pair has no valid address"}:Ka.test(e.id)?await this.service.getV3PoolDetail({address:e.id,chain:t}):{success:!1,error:"Resolved V3 pool has no valid address"};if(!o.success||!o.data)return{error:o.error||"Failed to fetch pool detail"};let a={...this.formatPoolDetail(o.data),...Ee(t,e.id)},i=await this.pool.isAddLiquiditySupported(t)?Re([a],n,v(t)):[];return{_instructions:`The address is a Uniswap ${r} pool. `+fe+"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, token1 reserve + USD price, and total tx count. 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. "+ye+be+ie+Ue+(i.length>0?Ne:""),resolvedAs:"pool",chain:t,protocolVersion:r,pool:a,...i.length>0?{actionButtons:i}:{}}}async handleTokenHit(e,t,n){let r=e.symbol?.trim();if(!r)return{error:"Resolved token has no symbol \u2014 cannot search related pools."};let o=await this.service.searchPools({query:r,chain:t,page:1,size:100,protocolVersion:"V3"});if(!o.success)return{error:o.error||"Failed to fetch pools for resolved token"};let a=(e.address??"").toLowerCase(),l=[...(o.data??[]).filter(d=>{let p=(d.token0?.address??"").toLowerCase(),h=(d.token1?.address??"").toLowerCase();return p===a||h===a})].sort((d,p)=>(p.volumeUsd24hr??0)-(d.volumeUsd24hr??0)).slice(0,10),c=l.map(d=>({...this.formatPoolCandidate(d),...Ee(t,d.id)})),u=await this.pool.isAddLiquiditySupported(t)?Re(c,n,v(t)):[];return{_instructions:"The address is a token, not a pool. Tell the user which token it is (symbol + name), then render the matching pools as a numbered list: pair (token0/token1 symbols), fee tier (%), protocol version, 24h volume (USD). Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. Ask which pool they want detail on; when they answer, re-call this tool with that pool address to fetch the detail. Format numbers human-readably. Omit null fields. Do NOT mention tool/API names."+(u.length>0?Ne:""),resolvedAs:"token",chain:t,protocolVersion:"V3",token:this.formatToken(e),poolCount:l.length,pools:c,...u.length>0?{actionButtons:u}:{}}}findPoolByAddress(e,t){let n=t.toLowerCase();return e.find(r=>(r.id??"").toLowerCase()===n)}findTokenByAddress(e,t){let n=t.toLowerCase();return e.find(r=>(r.address??"").toLowerCase()===n)}formatToken(e){return{address:e.address,symbol:e.symbol,name:e.name,decimals:e.decimals,chainId:e.chainId,isSpam:e.isSpam,safetyLevel:e.safetyLevel}}formatPoolCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}formatPoolDetail(e){let t=e.totalLiquidity?.value,n=e.volume24h?.value,r=e.feeTier,o=typeof r=="number"?r/1e4:void 0,a=typeof n=="number"&&typeof o=="number"?n*o/100:void 0,i=typeof a=="number"&&typeof t=="number"&&t>0?a/t*td*100:void 0,l=typeof n=="number"&&typeof t=="number"&&t>0?Math.round(n/t*1e3)/1e3:void 0;return{address:e.address??e.poolId,protocolVersion:e.protocolVersion,poolId:e.poolId,tickSpacing:e.tickSpacing,isDynamicFee:e.isDynamicFee,hookAddress:e.hook?.address,feeTierBps:r,feeTierPercent:o,tvlUsd:t,tvlChange24hPercent:e.totalLiquidityPercentChange24h?.value,volume24hUsd:n,fees24hUsd:a,aprPercent:i,volumeToTvlRatio:l,txCount:e.txCount,historicalVolumeWeek:this.formatHistorical(e.historicalVolume),token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.market?.price?.value??e.token0.price?.value,reserve:e.token0Supply,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.market?.price?.value??e.token1.price?.value,reserve:e.token1Supply,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}formatHistorical(e){if(!(!e||e.length===0))return e.map(t=>({timestamp:t.timestamp,volumeUsd:t.value}))}};var nd=/^0x[a-fA-F0-9]{40}$/,vn=class extends A{name="open-add-liquidity-form";kind="ui";category="pool-action";description='Open the Add-Liquidity form for a specific Uniswap V3 pool. Use this when the user wants to provide liquidity / add LP / farm / stake / deposit into a pool \u2014 natural-language verbs in any language all map here. Resolves the pool by 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.';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:"feeTier",type:"number",description:"Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. Omit when unknown \u2014 the tool will resolve the best match automatically.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prefillNativeAmount",type:"number",description:"Optional NATIVE-COIN amount (human-readable) to pre-fill the form's input field. ONLY pass this when the user named an amount in the chain's native coin itself \u2014 ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche. Example: \"add 0.1 ETH to USDC/WETH on Base\". Pass the plain decimal number (e.g. 0.1 for 0.1 ETH). DO NOT convert a non-native amount (USDC, USDT, DAI, WBTC, \u2026) into native here \u2014 pass `requestedNonNativeToken` instead so the tool can reject. Mutually exclusive with prefillUsdAmount \u2014 pass one or neither.",required:!1},{name:"prefillUsdAmount",type:"number",description:'Optional USD amount to pre-fill the form\'s input field. Use this ONLY when the user explicitly speaks in USD/dollars \u2014 e.g. "add $10 to this pool", "10 dollars", "10 \u0111\xF4". The tool converts the USD value to native amount automatically using the current native-token price. DO NOT use this as a workaround for non-native token amounts (e.g. "5 USDT" is NOT $5 \u2014 USDT may de-peg, and even if 1:1 the user asked for a token, not USD). For non-native token amounts pass `requestedNonNativeToken` instead. Mutually exclusive with prefillNativeAmount \u2014 pass one or neither.',required:!1},{name:"requestedNonNativeToken",type:"string",description:`Set this ONLY when the user named an AMOUNT in a non-native token \u2014 e.g. "add pool with 5 USDT", "add 100 USDC to USDC/WETH", "th\xEAm 5 USDT v\xE0o pool". The trigger is "<number> <non-native-symbol>" in the user's message, NOT the mere appearance of the symbol. Pass the symbol the user attached the amount to (e.g. "USDT", "USDC", "DAI"). CRITICAL: If the user also names a NATIVE amount in the same message (e.g. "add USDC/WETH with 0.1 ETH", "th\xEAm pool USDC/WETH 0.3% v\u1EDBi 0.000005 ETH"), the native amount is the input \u2014 leave this EMPTY and use prefillNativeAmount. The pool pair symbols (the two tokens after "pool" / "to") are NEVER the input token by themselves \u2014 they only identify which pool. The tool will return error="unsupported_input_token" so the agent can tell the user that only the chain's native coin is accepted as input. DO NOT silently convert the user's non-native amount into a native amount or USD amount \u2014 the user explicitly named a different asset and must be informed, not auto-corrected. Leave empty when the user did name a native amount, a USD amount, or no amount at all.`,required:!1},{name:"rangeStrategy",type:"string",description:'Optional preset that pre-fills the min/max price inputs (FE keeps them editable). One of: "stable" \u2014 \xB13 tickSpacing around the current price (narrow, higher yield, higher out-of-range risk; pick for stablecoin / low-volatility pairs and when the user says "safe", "tight", "high yield", "t\u1EADp trung"); "wide" \u2014 currentPrice \xD7 [0.5, 2.0] (broad, lower yield, less rebalancing; pick when the user says "wide", "set and forget", "r\u1ED9ng"); "full" \u2014 full V3 tick range (V2-style, lowest yield, never goes out of range; pick when the user says "full range", "v2-style", "kh\xF4ng lo out of range"). Omit when the user did not signal a preference AND did not provide explicit minPrice/maxPrice. Mutually exclusive with minPrice/maxPrice \u2014 if both are passed, explicit prices win.',required:!1},{name:"minPrice",type:"number",description:'Optional explicit lower bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 minPrice=1800. Must be paired with maxPrice. When set, overrides rangeStrategy.',required:!1},{name:"maxPrice",type:"number",description:'Optional explicit upper bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 maxPrice=2200. Must be paired with minPrice. When set, overrides rangeStrategy.',required:!1},{name:"add_button_label",type:"string",description:`Label template for the per-fee-tier "Add liquidity" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. ALWAYS pass this when you call the tool with a pair but NO feeTier (the tool may return several fee-tier variants for the pair, and each gets a one-tap button). Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:'A short "add liquidity" command template IN THE USER\'S CURRENT LANGUAGE, submitted as the next user turn when a fee-tier button is clicked \u2014 it carries the chosen fee tier so the tool resolves that exact pool. ALWAYS pass this alongside `add_button_label` when calling with a pair but no feeTier. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name yourself \u2014 the chain this pair is on is appended to the prompt automatically.',required:!1}];uniswap;pool;coinPool;minProvideUsd;constructor(e){super(),this.uniswap=new pe(e),this.pool=new de(e?.pool),this.coinPool=new at(e?.coinPool),this.minProvideUsd=e?.minProvideUsd??.01}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(a.ui=o.ui),o&&typeof o=="object"&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(a.actionButtons=o.actionButtons),a}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){let n=await he(yn(this.pool),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=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.prefillNativeAmount=="number"&&Number.isFinite(e.prefillNativeAmount)&&e.prefillNativeAmount>0?e.prefillNativeAmount:null,c=typeof e.prefillUsdAmount=="number"&&Number.isFinite(e.prefillUsdAmount)&&e.prefillUsdAmount>0?e.prefillUsdAmount:null,u=typeof e.requestedNonNativeToken=="string"&&e.requestedNonNativeToken.trim()?e.requestedNonNativeToken.trim():null,d=u&&l!=null&&(u.toLowerCase()===o.toLowerCase()||u.toLowerCase()===a.toLowerCase())?null:u,p=this.parseRangeStrategy(e.rangeStrategy),h=typeof e.minPrice=="number"&&Number.isFinite(e.minPrice)&&e.minPrice>0?e.minPrice:null,f=typeof e.maxPrice=="number"&&Number.isFinite(e.maxPrice)&&e.maxPrice>0?e.maxPrice:null;if(!o||!a)return{error:"missing_pool_identifier",_instructions:"token0Symbol and token1Symbol are required. Ask the user for the missing token symbol."};let m=se(r);if(!m)return{error:"unsupported_chain",chain:r,_instructions:`Chain ${r} is not supported by the add-liquidity flow.`};let g=fn(r);if(d&&g&&d.toLowerCase()!==g.symbol.toLowerCase())return{error:"unsupported_input_token",requestedToken:d,nativeSymbol:g.symbol,chainName:m.name,_instructions:`The user asked to add liquidity using ${d}, but this app only supports the chain's native coin (${g.symbol} on ${m.name}) as the input. Tell the user this in their language and ask them to either restate the amount in ${g.symbol} or in USD. DO NOT silently convert their ${d} amount, do NOT pre-fill the form, and do NOT call this tool again until the user provides a native or USD amount.`};let y=await this.pool.getGatewayAddress(r);if(!y)return{error:"no_gateway_configured",chain:r,_instructions:`No gateway contract is configured for chain ${r} (${m.name}). Tell the user this chain is not yet supported for add-liquidity in this app.`};let b=t?.walletAddress;if(!b)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."};let w=await this.uniswap.searchPools({query:`${o} ${a}`,chain:r,page:1,size:100,protocolVersion:"V3",feeTier:i});if(!w.success)return{error:w.error||"pool_search_failed"};let k=w.data??[],T=k.find(L=>this.matchesPairExact(L,o,a,i)),P=T?[]:k.filter(L=>this.matchesPair(L,o,a,i));if(!T&&P.length===0)return{error:"pool_not_found",_instructions:`No V3 pool found for ${o}/${a}${i!=null?` at ${i}bps`:""} on ${m.name}. Verify the inputs with the user.`};if(!T&&P.length>1){let L=P.map(te=>{let St=te.volume1DayUsd??te.volumeUsd24hr,To=te.tvlUsd,ds=typeof St=="number"&&typeof To=="number"&&To>0?St/To: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:St,tvlUsd:To,...ds!=null?{volumeToTvlRatio:ds}:void 0,...te.apr?{apr:te.apr}:void 0}}).sort((te,St)=>(St.volumeToTvlRatio??St.apr??-1/0)-(te.volumeToTvlRatio??te.apr??-1/0)).slice(0,5),cr=ns(L.map(te=>({token0:{symbol:te.token0Symbol},token1:{symbol:te.token1Symbol},feeTierPercent:te.feeTierPercent})),typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",v(r));return{relatedPools:L,count:L.length,...cr.length>0?{actionButtons:cr}:{},_instructions:fe+"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. "+ye+"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). "+be+ie+Ue+(cr.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 S=T??P[0];if(!S.id||!nd.test(S.id))return{error:"invalid_pool_address"};let _=this.fetchPriceRanges(r,S.id,S.token0?.symbol,S.token1?.symbol),N=await this.pool.readPoolOnchain(r,S.id),[C,q,E]=await Promise.all([this.pool.getNativeBalance(r,b),this.pool.estimateGasReserveWei(r),this.pool.getNativePriceUsd(r)]),ee=C>q?C-q:0n,O=fn(r),Ie=Number(ee)/10**O.decimals,ge=Number(C)/10**O.decimals,Y=E!=null?Ie*E:null,[$e,le]=await Promise.all([this.pool.readErc20Decimals(r,N.token0),this.pool.readErc20Decimals(r,N.token1)]),lt={min:Ce(je,$e,le),max:Ce(xt,$e,le)},Ke=null;C===0n?Ke="no_balance":Y!=null&&Y<this.minProvideUsd&&(Ke="insufficient_balance");let ct=S.token0,ut=S.token1,jn=[25,50,75,100].map(L=>({percent:L,amountWei:(ee*BigInt(L)/100n).toString(),amount:Ie*(L/100)})),zn=null,dt=null;if(l!=null){dt=l;let L=BigInt(Math.floor(dt*10**O.decimals));L>0n&&(zn=L.toString())}else if(c!=null&&E!=null&&E>0){dt=c/E;let L=BigInt(Math.floor(dt*10**O.decimals));L>0n&&(zn=L.toString())}let ko={address:$,isNative:!0,symbol:O.symbol,name:O.name,decimals:O.decimals,priceUsd:E,balanceWei:C.toString(),balance:ge,gasReserveWei:q.toString(),spendableWei:ee.toString(),spendable:Ie,spendableUsd:Y,quickRates:jn,minProvideUsd:this.minProvideUsd,warning:Ke,warningMessage:Ke==="no_balance"?`You have no ${O.symbol} on ${m.name}. Top up to add liquidity.`:Ke==="insufficient_balance"?`Spendable ${O.symbol} is below the $${this.minProvideUsd} minimum.`:null,prefillAmount:dt,prefillAmountWei:zn},pt=this.computePrefillRange({explicitMinPrice:h,explicitMaxPrice:f,rangeStrategy:p,currentPrice:N.currentPrice,currentTick:N.currentTick,tickSpacing:N.tickSpacing,token0Decimals:$e,token1Decimals:le,priceBounds:lt}),cs={component:"AddLiquidityForm",props:{chain:{hexId:r,name:m.name},pool:{address:N.poolAddress,fee:N.fee,feePercent:N.fee/1e4,tickSpacing:N.tickSpacing,currentTick:N.currentTick,currentPrice:ne(N.currentPrice),sqrtPriceX96:N.sqrtPriceX96.toString(),token0:{address:N.token0,symbol:ct?.symbol,name:ct?.name,logo:ct?.logo},token1:{address:N.token1,symbol:ut?.symbol,name:ut?.name,logo:ut?.logo}},inputToken:ko,priceBounds:lt,prefillRange:pt,gatewayAddress:y}},us=this.orientRangesToForm(await _,N.currentPrice,ct?.symbol,ut?.symbol);return{ui:cs,suggestedRanges:us,summary:this.buildSummary({chainName:m.name,pair:`${ct?.symbol??o}/${ut?.symbol??a}`,feePercent:N.fee/1e4,warning:Ke,minProvideUsd:this.minProvideUsd,nativeSymbol:O.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`. 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. '+ie+"Do NOT mention balance amounts, deBridge, native coin mechanics, UI, forms, data sources, or internal tool names. Wait for the user to fill in amount + price range before proceeding."}}async fetchPriceRanges(e,t,n,r){try{if(!this.coinPool.isSupported(e))return[];let o=await this.coinPool.getByAddress({chain:e,poolAddress:t});return o.length===0&&n&&r&&(o=await this.coinPool.getPairs({chain:e,tokens:[n,r]})),o.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}orientRangesToForm(e,t,n,r){let o=a=>Number.isFinite(a)&&a>0;return o(t)?e.map(a=>{let{minPrice:i,maxPrice:l,currentPrice:c}=a.priceRange,u=i,d=l,p=c;if(o(c)){let h=Math.abs(Math.log(c/t));Math.abs(Math.log(c*t))<h&&(u=o(l)?1/l:0,d=o(i)?1/i:0,p=1/c)}return{fee:a.fee,apr:a.apr,minPrice:ne(u),maxPrice:ne(d),currentPrice:ne(p),baseSymbol:n,quoteSymbol:r}}).filter(a=>o(a.minPrice)&&o(a.maxPrice)):[]}matchesPairExact(e,t,n,r){if(!r||r!=null&&e.feeTier!==r)return!1;let o=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=n.toLowerCase();return o===i&&a===l||o===l&&a===i}matchesPair(e,t,n,r){if(r!=null&&e.feeTier!==r)return!1;let o=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=n.toLowerCase(),c=this.symMatch(o,i)&&this.symMatch(a,l),u=this.symMatch(o,l)&&this.symMatch(a,i);return c||u}symMatch(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}parseRangeStrategy(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="stable"||t==="wide"||t==="full"?t:null}computePrefillRange(e){let{explicitMinPrice:t,explicitMaxPrice:n,rangeStrategy:r,currentPrice:o,priceBounds:a}=e;if(t!=null&&n!=null&&n>t){let{minPrice:i,maxPrice:l}=Ct(t,n,o);return{strategy:"user",minPrice:Math.max(i,a.min),maxPrice:Math.min(l,a.max)}}if(r==="full")return{strategy:"full",minPrice:a.min,maxPrice:a.max};if(r==="stable"||r==="wide"){let l=Zr({currentTick:e.currentTick,tickSpacing:e.tickSpacing,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals}).find(c=>c.id===r);if(l)return{strategy:r,minPrice:l.minPrice,maxPrice:l.maxPrice}}return null}buildSummary(e){let t=[`Ready to add liquidity to the ${e.pair} ${e.feePercent}% pool on ${e.chainName}. Enter an amount and a price range to continue.`];return e.warning==="no_balance"?t.push(`You'll need some ${e.nativeSymbol} on ${e.chainName} first \u2014 top up to continue.`):e.warning==="insufficient_balance"&&t.push(`Your spendable ${e.nativeSymbol} is below the $${e.minProvideUsd} minimum \u2014 top up before continuing.`),t.join(" ")}};var ja=[{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"}]}],jo=[{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"",type:"uint256"}]}];var od=/^0x[a-fA-F0-9]{40}$/,An=class extends A{name="preview-add-liquidity";kind="action";category="pool-action";description='Preview the add-liquidity transaction. Call this whenever a concrete pool ADDRESS, a native amount, and BOTH min and max price (in token1 per token0) are known \u2014 whether the user filled the AddLiquidityForm OR stated all of them directly in chat (e.g. "add to USDC/WETH with 0.01 ETH, range 0.0005-0.0007, pool=0x\u2026"). Do NOT require the form to have been opened first. The tool converts prices \u2192 ticks (rounded to tickSpacing), fetches deBridge swap quotes for both legs, encodes the gateway.mint call, and returns an unsigned tx the FE will sign. REQUIRES the exact poolAddress (from open-add-liquidity-form props.pool.address or given by the user) \u2014 if only token symbols / a fee tier are known, resolve the pool via open-add-liquidity-form first.';parameters=[{name:"poolAddress",type:"string",description:"V3 pool contract address (returned by open-add-liquidity-form in props.pool.address).",required:!0},{name:"chain",type:"string",description:`Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea .Must match the pool's chain. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.`,required:!1},{name:"minPrice",type:"number",description:`Lower bound of the position price range, in token1-per-token0 units (decimal-adjusted \u2014 the SAME unit as pool.currentPrice from open-add-liquidity-form). Example: if currentPrice is 1800 (USDC per WETH), minPrice 900 means "the position is in-range while WETH \u2265 900 USDC". Must be >= 0 and < maxPrice. Pass 0 for a "full-range lower" position (the range extends down to price 0, i.e. Uniswap's MIN_TICK). CRITICAL: copy the number the user gave VERBATIM \u2014 every digit and every leading zero. Do NOT add or drop a zero, round, or rescale it. Tiny decimals like 0.000533 are easy to mis-transcribe (0.000533 must stay 0.000533, NEVER 0.0000533). If unsure, prefer the user's exact characters over your own reformatting.`,required:!0},{name:"maxPrice",type:"number",description:`Upper bound of the position price range, in the same units as minPrice. Must be > minPrice. Pass a very large number (or props.priceBounds.max) for a "full range upper" position. CRITICAL: copy the user's number VERBATIM \u2014 every digit and leading zero; never add/drop a zero, round, or rescale.`,required:!0},{name:"nativeAmount",type:"number",description:"Native amount the user wants to spend, as a human-readable decimal number (e.g. 0.1 for 0.1 ETH). The tool converts to wei internally.",required:!0},{name:"slippageBps",type:"number",description:"Slippage tolerance in basis points (100 = 1%). Optional \u2014 defaults to 100.",required:!1}];pool;defaultSlippageBps;mintMinPercent;pantograph;constructor(e){super(),this.pool=new de(e?.pool),this.defaultSlippageBps=e?.defaultSlippageBps??"auto",this.mintMinPercent=e?.mintMinPercent??80,this.pantograph=new ue}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(a.ui=o.ui),a}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"",r=await he(yn(this.pool),e.chain,t);if(!r.ok)return r.result;let o=r.chain,a=Number(e.minPrice),i=Number(e.maxPrice),l=typeof e.nativeAmount=="number"&&Number.isFinite(e.nativeAmount)?e.nativeAmount:NaN,c=typeof e.slippageBps=="number"&&Number.isFinite(e.slippageBps)&&String(e.slippageBps)!=="auto"?Math.floor(e.slippageBps)/100:String(this.defaultSlippageBps);if(!n||!o||!Number.isFinite(l)||!Number.isFinite(a)||!Number.isFinite(i))return{error:"missing_inputs",_instructions:"poolAddress, chain, minPrice, maxPrice, nativeAmount are all required."};if(!od.test(n))return{error:"invalid_pool_address",_instructions:"poolAddress is not a valid EVM address. Re-open the add-liquidity form to get the correct pool address."};if(a<0||i<=0||a>=i)return{error:"invalid_price_range",_instructions:"minPrice must be >= 0 (0 = full-range lower), maxPrice must be > 0, and minPrice must be strictly less than maxPrice."};if(l<=0)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let u=se(o);if(!u)return{error:"unsupported_chain",chain:o};let d=await this.pool.getGatewayAddress(o);if(!d)return{error:"no_gateway_configured",chain:o};let p=t?.walletAddress;if(!p)return{error:"wallet_not_connected"};let h=fn(o),f=BigInt(Math.floor(l*10**h.decimals));if(f<=0n)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let m=await this.pool.readPoolOnchain(o,n),[g,y]=await Promise.all([this.pool.readErc20Decimals(o,m.token0),this.pool.readErc20Decimals(o,m.token1)]),{minPrice:b,maxPrice:w}=Ct(a,i,m.currentPrice),k=b===0?je:ht(b,g,y),T=ht(w,g,y),P=b===0?De(Le(je,m.tickSpacing,"up")):De(Le(k,m.tickSpacing,"down")),S=De(Le(T,m.tickSpacing,"up"));if(P>=S||P<je||S>xt)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:T,tickLower:P,tickUpper:S};let _={tickLower:P,tickUpper:S,minPrice:ne(Ce(P,g,y)),maxPrice:ne(Ce(S,g,y))},N=m.currentTick;if(N<P||N>=S){let L=N<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 ${L==="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:ne(m.currentPrice),requestedRange:{minPrice:_.minPrice,maxPrice:_.maxPrice},side:L}}let[C,q,E]=await Promise.all([this.pool.getNativeBalance(o,p),this.pool.estimateGasReserveWei(o),this.pool.getNativePriceUsd(o)]),ee=f+q;if(C<ee)return{error:"insufficient_balance",_instructions:"User does not have enough native coin (amount + gas reserve). Tell them the shortfall in their language.",balanceWei:C.toString(),requiredWei:ee.toString(),gasReserveWei:q.toString()};let O=this.pool.splitNativeAmountForRange({nativeAmountWei:f,pool:m,tickLower:P,tickUpper:S,token0Decimals:g,token1Decimals:y}),Ie=m.token0.toLowerCase()===$,ge=m.token1.toLowerCase()===$,Y=[];if(Ie||O.amountInFor0Wei===0n)Y.push({tokenIn:$,tokenOut:m.token0,amountIn:O.amountInFor0Wei,tx:{to:$,data:"0x",value:"0"},minAmountOut:Ie?O.amountInFor0Wei:0n});else{let L=await this.pool.fetchSwapLeg({senderAddress:p,chainId:o,tokenIn:$,tokenInAmount:O.amountInFor0Wei.toString(),tokenOut:m.token0,tokenOutRecipient:d,slippage:typeof c=="number"?c:"auto"});Y.push({tokenIn:$,tokenOut:m.token0,amountIn:O.amountInFor0Wei,tx:{to:L.to,data:L.data,value:L.value},minAmountOut:BigInt(L.minAmountOut||"0")})}if(ge||O.amountInFor1Wei===0n)Y.push({tokenIn:$,tokenOut:m.token1,amountIn:O.amountInFor1Wei,tx:{to:$,data:"0x",value:"0"},minAmountOut:ge?O.amountInFor1Wei:0n});else{let L=await this.pool.fetchSwapLeg({senderAddress:p,chainId:o,tokenIn:$,tokenInAmount:O.amountInFor1Wei.toString(),tokenOut:m.token1,tokenOutRecipient:d,slippage:typeof c=="number"?c:"auto"});Y.push({tokenIn:$,tokenOut:m.token1,amountIn:O.amountInFor1Wei,tx:{to:L.to,data:L.data,value:L.value},minAmountOut:BigInt(L.minAmountOut||"0")})}let $e=L=>L*BigInt(this.mintMinPercent)/100n,le=$e(Y[0].minAmountOut),lt=$e(Y[1].minAmountOut),Ke=Y.map(L=>({tokenIn:L.tokenIn,tokenInAmount:BigInt(L.amountIn),tokenOut:L.tokenOut,tokenOutAmount:BigInt(L.minAmountOut)})),ct=Y.map(L=>({to:L.tx.to,data:L.tx.data,value:BigInt(L.tx.value||"0")})),ut=Pt({abi:ja,functionName:"mint",args:[Ke,ct,{fee:Number(m.fee),amount0Min:BigInt(le),amount1Min:BigInt(lt),tickLower:P,tickUpper:S}]}),jn=l,zn={chainId:o,to:d,data:ut,value:f.toString(),from:p},dt={nativeIn:jn,nativeSymbol:h.symbol,nativeInUsd:E!=null?jn*E:null,ratio:{token0Percent:O.ratio0,token1Percent:O.ratio1},expectedToken0:Number(Y[0].minAmountOut)/10**g,expectedToken1:Number(Y[1].minAmountOut)/10**y,amount0Min:le.toString(),amount1Min:lt.toString(),slippageBps:c},ko=await this.pantograph.getTokensMetadata([m.token0,m.token1],o),pt=ko[m.token0],At=ko[m.token1];return{ui:{component:"ConfirmAddLiquidityTx",props:{chain:{hexId:o,name:u.name},unsignedTx:zn,summary:dt,pool:{...m,feePercent:m.fee/1e4,currentPrice:ne(m.currentPrice),token0:{address:m.token0,symbol:pt?.auditGoplus?.token_symbol||pt.symbol,name:pt.name,decimals:pt.decimals,logo:pt.icon_image},token1:{address:m.token1,symbol:At?.auditGoplus?.token_symbol||At.symbol,name:At.name,decimals:At.decimals,logo:At.icon_image}},range:_,gatewayAddress:d}},summary:`Ready to add ${jn} ${h.symbol} to pool ${m.token0}/${m.token1} ${m.fee/1e4}% on ${u.name}, range [${_.minPrice}, ${_.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 za=365,rd=1e3,sd=/^0x[a-fA-F0-9]{40}$/;function ad(s,e){return{depositUsd:s,aprPercent:e*100,dailyUsd:s*e/za,weeklyUsd:s*e/52,monthlyUsd:s*e/12,yearlyUsd:s*e}}var Sn=class extends A{name="estimate-pool-yield";description=`Estimate daily / weekly / monthly / yearly fee yield for a USD deposit into a Uniswap V3 pool. Answers questions like: "If I put $1000 into the USDC/WETH 0.05% pool, how much per day?", "b\u1ECF 500$ v\xE0o pool ETH/USDC 0.3% m\u1ED7i ng\xE0y l\u1EDDi bao nhi\xEAu?", "APR of WBTC/ETH 0.3% on Arbitrum". BEHAVIOR (designed to minimize back-and-forth with the user):
|
|
187
187
|
\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.
|
|
188
188
|
\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.
|
|
189
189
|
\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.
|
|
190
190
|
\u2022 If chain is missing \u2192 default to userContext.chain or "0x1" (Ethereum).
|
|
191
|
-
Source: Uniswap ExploreStats (live 24h data). Supports: `+me();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:Ae,required:!1}];service;constructor(e){super(),this.service=new pe(e)}async run(e,t){let n=await he(Se(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=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:rd;if(!o)return{error:"token0Symbol is required. Ask the user which pool / token they want to estimate yield for."};let u=a?`${o} ${a}`:o,d=await this.service.searchPools({query:u,chain:r,page:1,size:50,protocolVersion:"V3"});if(!d.success)return{error:d.error||"Pool search failed"};let p=d.data??[],h=this.filterPools(p,o,a,i);if(h.length===0)return{error:`No V3 pool found for ${this.describeQuery(o,a,i)} on ${v(r)}. Verify the token symbols with the user.`};let f=this.rankByVolume(h);if(a&&i==null&&new Set(f.map(ee=>ee.feeTier).filter(ee=>typeof ee=="number")).size>1){let ee=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:`${o}/${a} exists across multiple fee tiers \u2014 user choice required.`,missing:["feeTier"],candidates:ee.map(O=>({pair:O.token0?.symbol&&O.token1?.symbol?`${O.token0.symbol}/${O.token1.symbol}`:void 0,feeTierBps:O.feeTier,feeTierPercent:typeof O.feeTier=="number"?O.feeTier/1e4:void 0,volume24hUsd:O.volumeUsd24hr,address:O.id}))}}let m=f[0];if(!m.id||!sd.test(m.id))return{error:"Resolved pool has no valid address."};let g=await this.service.getV3PoolDetail({address:m.id,chain:r});if(!g.success||!g.data)return{error:g.error||"Failed to fetch pool detail."};let y=g.data,b=y.totalLiquidity?.value,w=y.volume24h?.value,k=y.feeTier,T=typeof k=="number"?k/1e4:void 0,P=typeof w=="number"&&typeof T=="number"?w*T/100:void 0,S=typeof P=="number"&&typeof b=="number"&&b>0?P/b*za:void 0,_=typeof w=="number"&&typeof b=="number"&&b>0?w/b:void 0,N={address:y.address,pair:y.token0?.symbol&&y.token1?.symbol?`${y.token0.symbol}/${y.token1.symbol}`:void 0,feeTierBps:k,feeTierPercent:T,tvlUsd:b,volume24hUsd:w,fees24hUsd:P,volumeToTvlRatio:_,aprPercent:typeof S=="number"?S*100:void 0,chain:r,token0:y.token0?{symbol:y.token0.symbol}:void 0,token1:y.token1?{symbol:y.token1.symbol}:void 0},C=a?void 0:`User only provided ${o}; auto-picked the highest-volume V3 pool containing it.`;if(S==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:N,autoPickedReason:C,aprUnavailableReason:b?"Volume data unavailable":"TVL is zero or unavailable"};let q=ad(c,S);return{_instructions:fe+"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. ')+(C?'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. "+ye+be+ie+"Format USD numbers with 2 decimal places (e.g. $3.45/day). Do NOT mention tool names.",pool:N,estimate:q,depositMode:l?"user-specified":"default-1000-example",autoPickedReason:C,disclaimer:"Fee yield is based on the pool's 24h volume snapshot and assumes full-range liquidity. Actual returns vary with price movement, volume changes, and impermanent loss."}}filterPools(e,t,n,r){let o=t.toLowerCase(),a=n?n.toLowerCase():"";return e.filter(i=>{if(r!=null&&i.feeTier!==r)return!1;let l=(i.token0?.symbol??"").toLowerCase(),c=(i.token1?.symbol??"").toLowerCase();return a?this.sym(l,o)&&this.sym(c,a)||this.sym(l,a)&&this.sym(c,o):this.sym(l,o)||this.sym(c,o)})}sym(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}rankByVolume(e){return[...e].sort((t,n)=>(n.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}dedupeByFeeTier(e){let t=new Set,n=[];for(let r of e)typeof r.feeTier=="number"&&(t.has(r.feeTier)||(t.add(r.feeTier),n.push(r)));return n}describeQuery(e,t,n){let r=t?`${e}/${t}`:e;return n!=null?`${r} at ${n} bps`:r}};var xn=class extends A{name="get-pool-price-ranges";description='List CoinPool concentrated-liquidity price-range candidates for a token pair on a given EVM chain. Each entry shows: pair, fee tier, min/max price range, current price, and the APR earned WITHIN that range (strictly per-range \u2014 NOT the overall pool APR). Use ONLY for questions about price ranges or which range to pick: "what price range should I use for ETH/USDC?", "best range for USDC/WETH on Arbitrum", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC". Do NOT use for general "show me ETH/USDC pools" \u2014 use get-pool-detail or search-pools for that. Source: CoinPool. Supports: '+me()+".";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:Ae,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 at(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let r=await he(Se(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,a=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,i=await this.service.getPairs({chain:o,tokens:n});if(i.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and offer the pool's overall stats instead (via get-pool-detail).",tokens:n,chain:o,pairs:[],count:0};let l=[...i].sort((c,u)=>(u.apr??-1/0)-(c.apr??-1/0)).slice(0,a);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk. '+ie+"Do NOT mention tool or API names.",tokens:n,chain:o,count:l.length,pairs:l}}};var Xa="https://coinpool.app/my-liquidity",Cn=class extends A{name="manage-liquidity-redirect";description='Use when the user wants to MANAGE an EXISTING liquidity position rather than open a new one \u2014 specifically: collecting / claiming earned fees or rewards ("collect earnings", "claim my fees", "thu ph\xED", "r\xFAt l\xE3i"), or closing / removing / withdrawing a position ("close the pair", "close my position", "remove liquidity", "withdraw liquidity", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n", "\u0111\xF3ng c\u1EB7p"). This tool does NOT perform the action \u2014 it returns a link to the CoinPool management page where the user does it themselves. Do NOT use this for ADDING liquidity (use the add-liquidity form) or for pool data/analysis questions.';category="pool-action";parameters=[{name:"action",type:"string",description:'What the user wants to do \u2014 one of: "collect" (collect/claim earned fees) or "close" (close/remove the position). Optional \u2014 used only to tailor the wording. Omit if unclear.',required:!1}];async run(e){let t=e.action==="collect"||e.action==="close"?e.action:void 0;return{_instructions:`Managing an existing position is not available in-app yet. Tell the user (in their language) that to ${t==="collect"?"collect their earned fees":t==="close"?"close / remove their position":"manage their existing position (collect earnings or close the pair)"}, they need to visit the CoinPool management page and do it there. Give them the link as plain text: ${Xa} \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:Xa,action:t}}};var id=["tvl","volume","apr","fee","liquidity"],_n=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 re(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.trim().toUpperCase()),r=(Array.isArray(e.chains)?e.chains:[]).filter(f=>typeof f=="string"&&f.trim().length>0),o=r.filter(f=>!this.service.isSupported(f)),a=r.filter(f=>this.service.isSupported(f)).map(f=>this.service.resolveChain(f));if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new Q(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],l=typeof e.sortBy=="string"&&id.includes(e.sortBy)?e.sortBy:"tvl",c={minTVL:typeof e.minTVL=="number"?e.minTVL:void 0,maxTVL:typeof e.maxTVL=="number"?e.maxTVL:void 0,minAPR:typeof e.minAPR=="number"?e.minAPR:void 0,maxAPR:typeof e.maxAPR=="number"?e.maxAPR:void 0,feeTier:typeof e.feeTier=="number"?e.feeTier:void 0},u=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5;if(r.length>0&&a.length===0)return{_instructions:"The user requested chains we do not support via The Graph subgraph. Politely list the unsupported chains and the supported chains. Do not show any pool data.",unsupportedChains:o.map(v),supportedChains:this.service.listSupportedChains().map(v),pools:[],count:0};let p=(await Promise.allSettled(i.map(f=>this.service.searchPools({tokens:n,chain:f,sortBy:l,filters:c})))).flatMap(f=>f.status==="fulfilled"?f.value:[]);l==="apr"?p.sort((f,m)=>(m.apr??0)-(f.apr??0)):l==="tvl"?p.sort((f,m)=>m.tvl-f.tvl):l==="volume"?p.sort((f,m)=>m.volume24hUsd-f.volume24hUsd):l==="fee"&&p.sort((f,m)=>f.feeTierBps-m.feeTierBps),p=p.slice(0,u);let h=[];return n.length===2&&(h=(await Promise.allSettled(i.map(m=>this.service.getCoinPoolPairs({chain:m,tokens:n})))).flatMap((m,g)=>m.status==="fulfilled"?m.value.map(y=>({...y,chain:v(i[g])})):[]),h.sort((m,g)=>(g.apr??-1/0)-(m.apr??-1/0)),h=h.slice(0,u)),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). Then list the pools with: pair (e.g. USDC/WETH), fee tier (%), TVL (USD), volume past day (USD), APR (%). Format USD human-readably ($12.5M, $450K). Mention chain and sort metric briefly. If a pool has no APR (null), skip the APR field rather than showing zero. For EACH pool, render the provided uniswapUrl as a clickable markdown link \u2014 e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)". Never omit this link. Do not invent URLs. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: the APR in coinPoolPairs is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the list, add a brief, natural read on the pools \u2014 conversational, like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4CA} Evaluation"); vary your wording each time and only mention what actually stands out in THIS data. Reason ONLY from the numbers shown \u2014 never invent figures. Touch on, as it fits: which pool looks strongest and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; a high volume-to-TVL ratio signals an active, fee-generating pool); whether the fee tier fits the pair (0.05% for stable/correlated, 0.30% for typical volatile, 1% for exotic/low-liquidity); any pool to be cautious about (thin TVL/volume, or an eye-catching APR that is likely volatile/unsustainable rather than a sure thing); and the key risks in a line (APR is variable, high APR usually means higher risk, impermanent loss for LPs on volatile pairs). Keep it short and human \u2014 a sentence or two or a couple of light bullets. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, no stock disclaimer). If unsupportedChains is non-empty, mention them once at the end.',tokens:n,chains:i.map(v),unsupportedChains:o.map(v),sortBy:l,filters:c,count:p.length,pools:p.map(f=>this.formatPool(f)),coinPoolPairs:h}}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:we(e)}}};function we(s){return`https://app.uniswap.org/explore/pools/${co[s.chain]||s.chain}/${s.poolAddress}`}var co={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};var En=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 re(e)}async run(e,t){let n=(Array.isArray(e.chains)?e.chains:[]).filter(u=>typeof u=="string"&&u.trim().length>0),r=n.filter(u=>!this.service.isSupported(u)),o=n.filter(u=>this.service.isSupported(u)).map(u=>this.service.resolveChain(u));if(n.length>0&&o.length===0)return{_instructions:"User requested unsupported chains. Politely list them and the supported chains; do not show pool data.",unsupportedChains:r,supportedChains:this.service.listSupportedChains(),pools:[],count:0};if(o.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new Q(typeof t?.query=="string"?t.query:void 0);let a=o.length>0?o:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5,c=(await Promise.allSettled(a.map(u=>this.service.getTrendingPools({chain:u})))).flatMap(u=>u.status==="fulfilled"?u.value:[]);return c.sort((u,d)=>d.volume24hUsd-u.volume24hUsd),c=c.slice(0,i),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). List pools ranked by volume past day. For each: pair, fee %, volume past day, TVL, APR (skip if null). For EACH pool render the provided uniswapUrl as a clickable markdown link (e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)"). Never omit it. Do not invent URLs.',chains:a,unsupportedChains:r,count:c.length,pools:c.map(u=>({pair:u.pair,poolAddress:u.poolAddress,chain:u.chain,feeTierBps:u.feeTierBps,feeTierPercent:u.feeTierPercent,tvlUsd:u.tvl,volumePastDayUsd:u.volume24hUsd,fees24hUsd:u.fees24hUsd,apr:u.apr,token0:u.token0,token1:u.token1,uniswapUrl:we(u)}))}}};var Nn=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 re(e)}async run(e,t){let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{error:"This only supports Uniswap V3 pools. Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address)."};let r=typeof e.chain=="string"&&e.chain.trim();if(!r&&!t?.chain&&t?.walletAddress)throw new Q(typeof t?.query=="string"?t.query:void 0);let o=r?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(o))return{_instructions:"The requested chain is not supported by the Subgraph pool service. List the supported chains briefly.",unsupportedChains:[o],supportedChains:this.service.listSupportedChains()};let a=this.service.resolveChain(o),[i,l]=await Promise.all([this.service.getPoolByAddress({poolAddress:n,chain:a}),this.service.getCoinPoolByAddress({chain:a,poolAddress:n}).catch(()=>[])]);return i?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3,'+(l.length>0?" enriched with CoinPool range data,":"")+'" (translate naturally; keep "Subgraph" and "CoinPool" as-is). First show the pool snapshot: pair, fee tier (%), TVL, volume past day, 24h fees, APR (skip if null), and the pool address. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: a range APR is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Then give a genuine evaluation of THIS pool \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading; vary the wording each time and only cover what is actually relevant to this pool and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: liquidity depth & activity (higher TVL + volume past day = deeper liquidity, more fees, less slippage; thin TVL/volume is a red flag); fee-tier fit (0.05% suits stable/correlated pairs, 0.30% typical volatile pairs, 1% exotic/low-liquidity ones \u2014 flag a mismatch); whether the APR looks attractive vs. how sustainable it is (fee-driven and steady vs. thin-TVL spikes that can vanish); if coinPoolPairs is present, which price range makes sense \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Close with a short, natural overall take (e.g. solid / decent-with-caveats / risky) and a brief nudge that it is informational, not financial advice \u2014 phrase it differently each time, do not paste a stock disclaimer. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs. Do NOT mention tool names, UI, or forms.',chain:a,coinPoolPairs:l,pool:{pair:i.pair,poolAddress:i.poolAddress,chain:i.chain,feeTierBps:i.feeTierBps,feeTierPercent:i.feeTierPercent,tvlUsd:i.tvl,volumePastDayUsd:i.volume24hUsd,fees24hUsd:i.fees24hUsd,apr:i.apr,token0:i.token0,token1:i.token1,uniswapUrl:we(i)}}:{error:`No pool found at ${n} on ${v(a)}.`}}};var Rn=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 re(e)}async run(e,t){let n=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(n))return{error:"positionId must be a numeric string."};let r=(Array.isArray(e.chains)?e.chains:[]).filter(u=>typeof u=="string"&&u.trim().length>0),o=r.filter(u=>!this.service.isSupported(u)),a=r.filter(u=>this.service.isSupported(u)).map(u=>this.service.resolveChain(u));if(r.length>0&&a.length===0)return{_instructions:"Requested chains are not supported. List the supported chains.",unsupportedChains:o,supportedChains:this.service.listSupportedChains()};if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new Q(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(u=>this.service.getPoolByPositionId({positionId:n,chain:u})))).map(u=>u.status==="fulfilled"?u.value:null).find(u=>u!=null);return c?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). Show the pool of that position: pair, fee %, TVL, volume past day, APR. Mention the position id. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs.',positionId:n,pool:{pair:c.pair,poolAddress:c.poolAddress,chain:c.chain,feeTierBps:c.feeTierBps,feeTierPercent:c.feeTierPercent,tvlUsd:c.tvl,volumePastDayUsd:c.volume24hUsd,fees24hUsd:c.fees24hUsd,apr:c.apr,token0:c.token0,token1:c.token1,uniswapUrl:we(c)}}:{_instructions:"No pool found for this position id on the chosen chains. Ask the user to verify the id or chain.",positionId:n,chains:i,found:!1}}};var Un=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 re(e)}async run(e,t){let n=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(n))return{error:"positionId must be a numeric string (Uniswap V3 NFT id)."};let r=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),o=r.filter(d=>!this.service.isSupported(d)),a=r.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(r.length>0&&a.length===0)return{_instructions:"User asked about a position on chains we do not support. List unsupported + supported chains.",unsupportedChains:o,supportedChains:this.service.listSupportedChains()};if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new Q(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(d=>this.service.getPositionDetail({positionId:n,chain:d})))).map(d=>d.status==="fulfilled"?d.value:null).find(d=>d!=null);if(!c)return{_instructions:"No position with this id was found on the chosen chains. Suggest the user double-check the id or specify another chain.",positionId:n,chains:i,found:!1};let u=co[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). End the response with TWO clickable markdown links from the data: position.uniswapPositionUrl as "[View position on Uniswap](uniswapPositionUrl)" and pool.uniswapUrl as "[View pool on Uniswap](uniswapUrl)". Never omit them. Do not invent URLs.',positionId:n,position:{...c.position,uniswapPositionUrl:`https://app.uniswap.org/positions/v3/${u}/${c.position.positionId}`},pool:{...c.pool,uniswapUrl:we(c.pool)}}}};var In=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 re(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let r=typeof e.chain=="string"&&e.chain.trim();if(!r&&!t?.chain&&t?.walletAddress)throw new Q(typeof t?.query=="string"?t.query:void 0);let o=r?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(o))return{_instructions:"Requested chain not supported. Mention supported chains.",unsupportedChains:[o],supportedChains:this.service.listSupportedChains()};let a=this.service.resolveChain(o),i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,l=await this.service.getCoinPoolPairs({chain:a,tokens:n});if(l.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and suggest using general pool data instead (via subgraph-search-pools).",tokens:n,chain:a,pairs:[],count:0};let c=[...l].sort((u,d)=>(d.apr??-1/0)-(u.apr??-1/0)).slice(0,i);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk.',tokens:n,chain:a,count:c.length,pairs:c}}};var Ln=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 re(e),this.linkAddLiquidity=e?.linkAddLiquidity?.trim()||void 0}async run(e,t){if(e.howTo===!0){let d=this.linkAddLiquidity??null,p=typeof e.chain=="string"&&e.chain.trim()||t?.chain||"0x1",h="",f=[];if(this.service.isSupported(p)){h=this.service.resolveChain(p);try{f=(await this.service.searchPools({tokens:[],chain:h,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:
|
|
191
|
+
Source: Uniswap ExploreStats (live 24h data). Supports: `+me();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:Ae,required:!1}];service;constructor(e){super(),this.service=new pe(e)}async run(e,t){let n=await he(Se(),e.chain,t);if(!n.ok)return n.result;let r=n.chain,o=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:rd;if(!o)return{error:"token0Symbol is required. Ask the user which pool / token they want to estimate yield for."};let u=a?`${o} ${a}`:o,d=await this.service.searchPools({query:u,chain:r,page:1,size:50,protocolVersion:"V3"});if(!d.success)return{error:d.error||"Pool search failed"};let p=d.data??[],h=this.filterPools(p,o,a,i);if(h.length===0)return{error:`No V3 pool found for ${this.describeQuery(o,a,i)} on ${v(r)}. Verify the token symbols with the user.`};let f=this.rankByVolume(h);if(a&&i==null&&new Set(f.map(ee=>ee.feeTier).filter(ee=>typeof ee=="number")).size>1){let ee=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:`${o}/${a} exists across multiple fee tiers \u2014 user choice required.`,missing:["feeTier"],candidates:ee.map(O=>({pair:O.token0?.symbol&&O.token1?.symbol?`${O.token0.symbol}/${O.token1.symbol}`:void 0,feeTierBps:O.feeTier,feeTierPercent:typeof O.feeTier=="number"?O.feeTier/1e4:void 0,volume24hUsd:O.volumeUsd24hr,address:O.id}))}}let m=f[0];if(!m.id||!sd.test(m.id))return{error:"Resolved pool has no valid address."};let g=await this.service.getV3PoolDetail({address:m.id,chain:r});if(!g.success||!g.data)return{error:g.error||"Failed to fetch pool detail."};let y=g.data,b=y.totalLiquidity?.value,w=y.volume24h?.value,k=y.feeTier,T=typeof k=="number"?k/1e4:void 0,P=typeof w=="number"&&typeof T=="number"?w*T/100:void 0,S=typeof P=="number"&&typeof b=="number"&&b>0?P/b*za:void 0,_=typeof w=="number"&&typeof b=="number"&&b>0?w/b:void 0,N={address:y.address,pair:y.token0?.symbol&&y.token1?.symbol?`${y.token0.symbol}/${y.token1.symbol}`:void 0,feeTierBps:k,feeTierPercent:T,tvlUsd:b,volume24hUsd:w,fees24hUsd:P,volumeToTvlRatio:_,aprPercent:typeof S=="number"?S*100:void 0,chain:r,token0:y.token0?{symbol:y.token0.symbol}:void 0,token1:y.token1?{symbol:y.token1.symbol}:void 0},C=a?void 0:`User only provided ${o}; auto-picked the highest-volume V3 pool containing it.`;if(S==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:N,autoPickedReason:C,aprUnavailableReason:b?"Volume data unavailable":"TVL is zero or unavailable"};let q=ad(c,S);return{_instructions:fe+"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. ')+(C?'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. "+ye+be+ie+"Format USD numbers with 2 decimal places (e.g. $3.45/day). Do NOT mention tool names.",pool:N,estimate:q,depositMode:l?"user-specified":"default-1000-example",autoPickedReason:C,disclaimer:"Fee yield is based on the pool's 24h volume snapshot and assumes full-range liquidity. Actual returns vary with price movement, volume changes, and impermanent loss."}}filterPools(e,t,n,r){let o=t.toLowerCase(),a=n?n.toLowerCase():"";return e.filter(i=>{if(r!=null&&i.feeTier!==r)return!1;let l=(i.token0?.symbol??"").toLowerCase(),c=(i.token1?.symbol??"").toLowerCase();return a?this.sym(l,o)&&this.sym(c,a)||this.sym(l,a)&&this.sym(c,o):this.sym(l,o)||this.sym(c,o)})}sym(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}rankByVolume(e){return[...e].sort((t,n)=>(n.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}dedupeByFeeTier(e){let t=new Set,n=[];for(let r of e)typeof r.feeTier=="number"&&(t.has(r.feeTier)||(t.add(r.feeTier),n.push(r)));return n}describeQuery(e,t,n){let r=t?`${e}/${t}`:e;return n!=null?`${r} at ${n} bps`:r}};var Pn=class extends A{name="get-pool-price-ranges";description='List CoinPool concentrated-liquidity price-range candidates for a token pair on a given EVM chain. Each entry shows: pair, fee tier, min/max price range, current price, and the APR earned WITHIN that range (strictly per-range \u2014 NOT the overall pool APR). Use ONLY for questions about price ranges or which range to pick: "what price range should I use for ETH/USDC?", "best range for USDC/WETH on Arbitrum", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC". Do NOT use for general "show me ETH/USDC pools" \u2014 use get-pool-detail or search-pools for that. Source: CoinPool. Supports: '+me()+".";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:Ae,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 at(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let r=await he(Se(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,a=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,i=await this.service.getPairs({chain:o,tokens:n});if(i.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and offer the pool's overall stats instead (via get-pool-detail).",tokens:n,chain:o,pairs:[],count:0};let l=[...i].sort((c,u)=>(u.apr??-1/0)-(c.apr??-1/0)).slice(0,a);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk. '+ie+"Do NOT mention tool or API names.",tokens:n,chain:o,count:l.length,pairs:l}}};var Xa="https://coinpool.app/my-liquidity",xn=class extends A{name="manage-liquidity-redirect";description='Use when the user wants to MANAGE an EXISTING liquidity position rather than open a new one \u2014 specifically: collecting / claiming earned fees or rewards ("collect earnings", "claim my fees", "thu ph\xED", "r\xFAt l\xE3i"), or closing / removing / withdrawing a position ("close the pair", "close my position", "remove liquidity", "withdraw liquidity", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n", "\u0111\xF3ng c\u1EB7p"). This tool does NOT perform the action \u2014 it returns a link to the CoinPool management page where the user does it themselves. Do NOT use this for ADDING liquidity (use the add-liquidity form) or for pool data/analysis questions.';category="pool-action";parameters=[{name:"action",type:"string",description:'What the user wants to do \u2014 one of: "collect" (collect/claim earned fees) or "close" (close/remove the position). Optional \u2014 used only to tailor the wording. Omit if unclear.',required:!1}];async run(e){let t=e.action==="collect"||e.action==="close"?e.action:void 0;return{_instructions:`Managing an existing position is not available in-app yet. Tell the user (in their language) that to ${t==="collect"?"collect their earned fees":t==="close"?"close / remove their position":"manage their existing position (collect earnings or close the pair)"}, they need to visit the CoinPool management page and do it there. Give them the link as plain text: ${Xa} \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:Xa,action:t}}};var id=["tvl","volume","apr","fee","liquidity"],Cn=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 re(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.trim().toUpperCase()),r=(Array.isArray(e.chains)?e.chains:[]).filter(f=>typeof f=="string"&&f.trim().length>0),o=r.filter(f=>!this.service.isSupported(f)),a=r.filter(f=>this.service.isSupported(f)).map(f=>this.service.resolveChain(f));if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new Q(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],l=typeof e.sortBy=="string"&&id.includes(e.sortBy)?e.sortBy:"tvl",c={minTVL:typeof e.minTVL=="number"?e.minTVL:void 0,maxTVL:typeof e.maxTVL=="number"?e.maxTVL:void 0,minAPR:typeof e.minAPR=="number"?e.minAPR:void 0,maxAPR:typeof e.maxAPR=="number"?e.maxAPR:void 0,feeTier:typeof e.feeTier=="number"?e.feeTier:void 0},u=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5;if(r.length>0&&a.length===0)return{_instructions:"The user requested chains we do not support via The Graph subgraph. Politely list the unsupported chains and the supported chains. Do not show any pool data.",unsupportedChains:o.map(v),supportedChains:this.service.listSupportedChains().map(v),pools:[],count:0};let p=(await Promise.allSettled(i.map(f=>this.service.searchPools({tokens:n,chain:f,sortBy:l,filters:c})))).flatMap(f=>f.status==="fulfilled"?f.value:[]);l==="apr"?p.sort((f,m)=>(m.apr??0)-(f.apr??0)):l==="tvl"?p.sort((f,m)=>m.tvl-f.tvl):l==="volume"?p.sort((f,m)=>m.volume24hUsd-f.volume24hUsd):l==="fee"&&p.sort((f,m)=>f.feeTierBps-m.feeTierBps),p=p.slice(0,u);let h=[];return n.length===2&&(h=(await Promise.allSettled(i.map(m=>this.service.getCoinPoolPairs({chain:m,tokens:n})))).flatMap((m,g)=>m.status==="fulfilled"?m.value.map(y=>({...y,chain:v(i[g])})):[]),h.sort((m,g)=>(g.apr??-1/0)-(m.apr??-1/0)),h=h.slice(0,u)),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). Then list the pools with: pair (e.g. USDC/WETH), fee tier (%), TVL (USD), volume past day (USD), APR (%). Format USD human-readably ($12.5M, $450K). Mention chain and sort metric briefly. If a pool has no APR (null), skip the APR field rather than showing zero. For EACH pool, render the provided uniswapUrl as a clickable markdown link \u2014 e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)". Never omit this link. Do not invent URLs. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: the APR in coinPoolPairs is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the list, add a brief, natural read on the pools \u2014 conversational, like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4CA} Evaluation"); vary your wording each time and only mention what actually stands out in THIS data. Reason ONLY from the numbers shown \u2014 never invent figures. Touch on, as it fits: which pool looks strongest and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; a high volume-to-TVL ratio signals an active, fee-generating pool); whether the fee tier fits the pair (0.05% for stable/correlated, 0.30% for typical volatile, 1% for exotic/low-liquidity); any pool to be cautious about (thin TVL/volume, or an eye-catching APR that is likely volatile/unsustainable rather than a sure thing); and the key risks in a line (APR is variable, high APR usually means higher risk, impermanent loss for LPs on volatile pairs). Keep it short and human \u2014 a sentence or two or a couple of light bullets. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, no stock disclaimer). If unsupportedChains is non-empty, mention them once at the end.',tokens:n,chains:i.map(v),unsupportedChains:o.map(v),sortBy:l,filters:c,count:p.length,pools:p.map(f=>this.formatPool(f)),coinPoolPairs:h}}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:we(e)}}};function we(s){return`https://app.uniswap.org/explore/pools/${co[s.chain]||s.chain}/${s.poolAddress}`}var co={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};var _n=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 re(e)}async run(e,t){let n=(Array.isArray(e.chains)?e.chains:[]).filter(u=>typeof u=="string"&&u.trim().length>0),r=n.filter(u=>!this.service.isSupported(u)),o=n.filter(u=>this.service.isSupported(u)).map(u=>this.service.resolveChain(u));if(n.length>0&&o.length===0)return{_instructions:"User requested unsupported chains. Politely list them and the supported chains; do not show pool data.",unsupportedChains:r,supportedChains:this.service.listSupportedChains(),pools:[],count:0};if(o.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new Q(typeof t?.query=="string"?t.query:void 0);let a=o.length>0?o:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5,c=(await Promise.allSettled(a.map(u=>this.service.getTrendingPools({chain:u})))).flatMap(u=>u.status==="fulfilled"?u.value:[]);return c.sort((u,d)=>d.volume24hUsd-u.volume24hUsd),c=c.slice(0,i),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). List pools ranked by volume past day. For each: pair, fee %, volume past day, TVL, APR (skip if null). For EACH pool render the provided uniswapUrl as a clickable markdown link (e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)"). Never omit it. Do not invent URLs.',chains:a,unsupportedChains:r,count:c.length,pools:c.map(u=>({pair:u.pair,poolAddress:u.poolAddress,chain:u.chain,feeTierBps:u.feeTierBps,feeTierPercent:u.feeTierPercent,tvlUsd:u.tvl,volumePastDayUsd:u.volume24hUsd,fees24hUsd:u.fees24hUsd,apr:u.apr,token0:u.token0,token1:u.token1,uniswapUrl:we(u)}))}}};var En=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 re(e)}async run(e,t){let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{error:"This only supports Uniswap V3 pools. Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address)."};let r=typeof e.chain=="string"&&e.chain.trim();if(!r&&!t?.chain&&t?.walletAddress)throw new Q(typeof t?.query=="string"?t.query:void 0);let o=r?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(o))return{_instructions:"The requested chain is not supported by the Subgraph pool service. List the supported chains briefly.",unsupportedChains:[o],supportedChains:this.service.listSupportedChains()};let a=this.service.resolveChain(o),[i,l]=await Promise.all([this.service.getPoolByAddress({poolAddress:n,chain:a}),this.service.getCoinPoolByAddress({chain:a,poolAddress:n}).catch(()=>[])]);return i?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3,'+(l.length>0?" enriched with CoinPool range data,":"")+'" (translate naturally; keep "Subgraph" and "CoinPool" as-is). First show the pool snapshot: pair, fee tier (%), TVL, volume past day, 24h fees, APR (skip if null), and the pool address. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: a range APR is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Then give a genuine evaluation of THIS pool \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading; vary the wording each time and only cover what is actually relevant to this pool and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: liquidity depth & activity (higher TVL + volume past day = deeper liquidity, more fees, less slippage; thin TVL/volume is a red flag); fee-tier fit (0.05% suits stable/correlated pairs, 0.30% typical volatile pairs, 1% exotic/low-liquidity ones \u2014 flag a mismatch); whether the APR looks attractive vs. how sustainable it is (fee-driven and steady vs. thin-TVL spikes that can vanish); if coinPoolPairs is present, which price range makes sense \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Close with a short, natural overall take (e.g. solid / decent-with-caveats / risky) and a brief nudge that it is informational, not financial advice \u2014 phrase it differently each time, do not paste a stock disclaimer. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs. Do NOT mention tool names, UI, or forms.',chain:a,coinPoolPairs:l,pool:{pair:i.pair,poolAddress:i.poolAddress,chain:i.chain,feeTierBps:i.feeTierBps,feeTierPercent:i.feeTierPercent,tvlUsd:i.tvl,volumePastDayUsd:i.volume24hUsd,fees24hUsd:i.fees24hUsd,apr:i.apr,token0:i.token0,token1:i.token1,uniswapUrl:we(i)}}:{error:`No pool found at ${n} on ${v(a)}.`}}};var Nn=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 re(e)}async run(e,t){let n=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(n))return{error:"positionId must be a numeric string."};let r=(Array.isArray(e.chains)?e.chains:[]).filter(u=>typeof u=="string"&&u.trim().length>0),o=r.filter(u=>!this.service.isSupported(u)),a=r.filter(u=>this.service.isSupported(u)).map(u=>this.service.resolveChain(u));if(r.length>0&&a.length===0)return{_instructions:"Requested chains are not supported. List the supported chains.",unsupportedChains:o,supportedChains:this.service.listSupportedChains()};if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new Q(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(u=>this.service.getPoolByPositionId({positionId:n,chain:u})))).map(u=>u.status==="fulfilled"?u.value:null).find(u=>u!=null);return c?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). Show the pool of that position: pair, fee %, TVL, volume past day, APR. Mention the position id. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs.',positionId:n,pool:{pair:c.pair,poolAddress:c.poolAddress,chain:c.chain,feeTierBps:c.feeTierBps,feeTierPercent:c.feeTierPercent,tvlUsd:c.tvl,volumePastDayUsd:c.volume24hUsd,fees24hUsd:c.fees24hUsd,apr:c.apr,token0:c.token0,token1:c.token1,uniswapUrl:we(c)}}:{_instructions:"No pool found for this position id on the chosen chains. Ask the user to verify the id or chain.",positionId:n,chains:i,found:!1}}};var Rn=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 re(e)}async run(e,t){let n=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(n))return{error:"positionId must be a numeric string (Uniswap V3 NFT id)."};let r=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),o=r.filter(d=>!this.service.isSupported(d)),a=r.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(r.length>0&&a.length===0)return{_instructions:"User asked about a position on chains we do not support. List unsupported + supported chains.",unsupportedChains:o,supportedChains:this.service.listSupportedChains()};if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new Q(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(d=>this.service.getPositionDetail({positionId:n,chain:d})))).map(d=>d.status==="fulfilled"?d.value:null).find(d=>d!=null);if(!c)return{_instructions:"No position with this id was found on the chosen chains. Suggest the user double-check the id or specify another chain.",positionId:n,chains:i,found:!1};let u=co[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). End the response with TWO clickable markdown links from the data: position.uniswapPositionUrl as "[View position on Uniswap](uniswapPositionUrl)" and pool.uniswapUrl as "[View pool on Uniswap](uniswapUrl)". Never omit them. Do not invent URLs.',positionId:n,position:{...c.position,uniswapPositionUrl:`https://app.uniswap.org/positions/v3/${u}/${c.position.positionId}`},pool:{...c.pool,uniswapUrl:we(c.pool)}}}};var Un=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 re(e)}async run(e,t){let n=(Array.isArray(e.tokens)?e.tokens:[]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toUpperCase());if(n.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let r=typeof e.chain=="string"&&e.chain.trim();if(!r&&!t?.chain&&t?.walletAddress)throw new Q(typeof t?.query=="string"?t.query:void 0);let o=r?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(o))return{_instructions:"Requested chain not supported. Mention supported chains.",unsupportedChains:[o],supportedChains:this.service.listSupportedChains()};let a=this.service.resolveChain(o),i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,l=await this.service.getCoinPoolPairs({chain:a,tokens:n});if(l.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and suggest using general pool data instead (via subgraph-search-pools).",tokens:n,chain:a,pairs:[],count:0};let c=[...l].sort((u,d)=>(d.apr??-1/0)-(u.apr??-1/0)).slice(0,i);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk.',tokens:n,chain:a,count:c.length,pairs:c}}};var In=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 re(e),this.linkAddLiquidity=e?.linkAddLiquidity?.trim()||void 0}async run(e,t){if(e.howTo===!0){let d=this.linkAddLiquidity??null,p=typeof e.chain=="string"&&e.chain.trim()||t?.chain||"0x1",h="",f=[];if(this.service.isSupported(p)){h=this.service.resolveChain(p);try{f=(await this.service.searchPools({tokens:[],chain:h,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:
|
|
192
192
|
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.
|
|
193
193
|
`+(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(d)+`
|
|
194
|
-
Do NOT mention tool names, UI, or forms.`,howTo:!0,chain:h||void 0,addLiquidityLink:d,count:f.length,pools:f.map(m=>this.formatPool(m))}}let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"",r=(Array.isArray(e.tokens)?e.tokens:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim().toUpperCase()),o=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 Q(typeof t?.query=="string"?t.query:void 0);let i=a?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(i))return{_instructions:"The requested chain is not supported by the Subgraph pool service. Tell the user, in their language, that add-liquidity is not available on that network and list the supported chains briefly. Do NOT mention tool names.",unsupportedChains:[v(i)],supportedChains:this.service.listSupportedChains().map(v)};let l=this.service.resolveChain(i);if(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{error:"Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address) to add liquidity to it."};let d=await this.service.getPoolByAddress({poolAddress:n,chain:l});return d?this.poolsResult([d],l,!0):{error:`No pool found at ${n} on ${v(l)}.`}}if(r.length>0){let d=await this.service.searchPools({tokens:r,chain:l,sortBy:"tvl",filters:{feeTier:o}});if(d.length===0)return{error:`No Uniswap V3 pool found for ${r.join("/")}${o!=null?` at ${o}bps`:""} on ${v(l)}. Ask the user to check the token symbols, or try a different pair.`};let p=r.length===2?await this.fetchCoinPoolPairs(l,r):[];return this.poolsResult(d.slice(0,8),l,!0,p)}let c=await this.service.searchPools({tokens:[],chain:l,sortBy:"tvl"}),u=this.linkAddLiquidity??null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity but has not named a pool yet. Briefly list these top pools (pair, fee tier %, TVL, APR \u2014 skip APR if null) as suggestions, render each `uniswapUrl` as a clickable markdown link, then ask the user which token pair (or pool) they want to add liquidity to. '+this.linkInstruction(u)+"Do NOT mention tool names, UI, or forms.",chain:l,needsSelection:!0,addLiquidityLink:u,count:c.length,pools:c.slice(0,6).map(d=>this.formatPool(d))}}async fetchCoinPoolPairs(e,t){try{return[...await this.service.getCoinPoolPairs({chain:e,tokens:t})].sort((r,o)=>(o.apr??-1/0)-(r.apr??-1/0)).slice(0,10)}catch{return[]}}linkInstruction(e){return e?`ALWAYS finish by inviting the user to add liquidity on the website, as ONE short sentence that shows the FULL link in plain view \u2014 display the entire URL verbatim (${e}) as the visible link text, do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${e}](${e}). For example: "You can add liquidity here: [${e}](${e})". Use the URL verbatim; never invent one, and never use a pool's uniswapUrl here. `:"No add-liquidity website is configured, so do not show or invent any link. "}poolsResult(e,t,n,r=[]){let o=n?this.linkAddLiquidity??null:null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity. Show the resolved pool(s): pair (e.g. USDC/WETH), fee tier (%), TVL, volume past day, APR (skip if null), and the pool address. For EACH pool, render the provided `uniswapUrl` as a clickable markdown link. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)", to help the user choose a range when adding liquidity. CRITICAL: that APR is for the SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the data, give a genuine, conversational recommendation \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4A1} Recommendation"); vary your wording naturally each time and only cover what is actually relevant to THIS pair and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: which pool/fee tier looks best and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; fee-tier fit: 0.05% for stable/correlated pairs, 0.30% for typical volatile pairs, 1% for exotic/low-liquidity ones); which price range makes sense (from coinPoolPairs if present) \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; anything worth avoiding (thin TVL/volume, ranges far from current price, chasing the top APR blindly); and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Keep it short and human \u2014 a sentence or two or a couple of light bullets, tailored to whether the pair is stable or volatile. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, do not paste a stock disclaimer). '+(o?`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. [${o}](${o}). For example: "If you'd like to add liquidity to one of these pools, you can do it here: [${o}](${o})." 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:o,count:e.length,pools:e.map(i=>this.formatPool(i)),coinPoolPairs:r}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:we(e)}}};function qe(s){if(typeof s=="number")return Number.isFinite(s)&&s>0?{kind:"token",value:s,raw:String(s)}:null;if(typeof s!="string")return null;let e=s.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 o=parseFloat(t[1]??t[2]);return Number.isFinite(o)&&o>0?{kind:"percent",percent:o,raw:e}:null}let n=e.match(/^\$\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*\$$|^(?:usd)\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*usd$/i);if(n){let o=parseFloat(n[1]??n[2]??n[3]??n[4]);return Number.isFinite(o)&&o>0?{kind:"usd",usd:o,raw:e}:null}let r=e.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(r){let o=parseFloat(r[1]);return Number.isFinite(o)&&o>0?{kind:"token",value:o,raw:e}:null}return null}function Qa(s,e){switch(s.kind){case"token":return{ok:!0,amount:s.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*s.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:s.usd/e.usdPrice}}}var ld={send:30000n,swap:1000000n},cd={"0x1":["https://ethereum-rpc.publicnode.com","https://eth.drpc.org","https://1rpc.io/eth"],"0xa":["https://optimism-rpc.publicnode.com","https://optimism.drpc.org"],"0x38":["https://bsc-rpc.publicnode.com","https://bsc.drpc.org"],"0x89":["https://polygon-bor-rpc.publicnode.com","https://polygon.drpc.org"],"0x2105":["https://base-rpc.publicnode.com","https://base.drpc.org"],"0xa4b1":["https://arbitrum-one-rpc.publicnode.com","https://arbitrum.drpc.org"],"0xa86a":["https://avalanche-c-chain-rpc.publicnode.com","https://avalanche.drpc.org"],"0xe708":["https://linea-rpc.publicnode.com","https://linea.drpc.org"],"0x64":["https://gnosis-rpc.publicnode.com","https://gnosis.drpc.org"],"0x3e7":["https://rpc.hyperliquid.xyz/evm"],"0x1388":["https://mantle-rpc.publicnode.com","https://rpc.mantle.xyz"],"0x8f":["https://rpc.monad.xyz"]};async function ud(s){let e=s.toLowerCase(),n=[Xe(s),...cd[e]??[]].filter(r=>!!r);for(let r of n)try{let o=await He(r,"eth_gasPrice",[]),a=BigInt(o);if(a>0n)return a}catch{}return 0n}async function Dn(s,e){let t=await ud(s);return t<=0n?0n:ld[e]*t}function On(s,e,t){if(e<=0n)return s;let n=se(t)?.native.decimals;if(n===void 0)return s;let r=Number(e)/10**n;return!Number.isFinite(r)||r<=0?s:Math.max(0,s-r)}var Pe=class extends A{kind="ui";category="wallet-action";buildUI(e){let t={action:this.actionType,chainId:e.chainId,chainName:v(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 D(e))}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=F(e.trim()),a=l=>o?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}parseDecimals(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isInteger(t)&&t>=0)return t}}async resolveTokenRef(e){let{contractArg:t,symbolArg:n,decimalsArg:r,chain:o,walletAddress:a}=e,i=this.parseDecimals(r),l=typeof n=="string"&&n.trim()?n.trim():void 0,c=this.normaliseAddress(t),u=typeof t=="string"&&t.trim()?t.trim():void 0,d=c??l??u;if(!d)return{token:void 0};let p=await this.resolveContractAddress(d,o,a);return p?{token:{address:p.address,symbol:l??p.symbol,name:p.name,decimals:i??p.decimals}}:c?{token:{address:c,symbol:l,decimals:i}}:{error:"token_not_found",key:d}}requireWallet(e){let t=e?.walletAddress;return t?{ok:!0,address:t}:{ok:!1,payload:{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before submitting the action. Do NOT render the form."}}}requireChain(e,t){return Z(e.chain,t)}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return F(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=parseFloat(t);return Number.isFinite(n)&&n>0?t:null}async resolveAmountInput(e){let{rawAmount:t,tokenAddress:n,chain:r,walletAddress:o,gasKind:a}=e,i=qe(t);if(!i)return null;let l=e.symbol??"the token",c=n.toLowerCase()==="native",u=!!a&&c&&!!r;if(i.kind==="token")return{amount:this.toPlainDecimal(i.value)};let d=await this.readTokenBalanceAndPrice(n,r,o),p=d?.balance;u&&d?.balance!==void 0&&(p=await this.computeNativeSpendable(r,a,d.balance));let h=Qa(i,{balance:p,usdPrice:d?.usdPrice});return h.ok?{amount:this.toPlainDecimal(h.amount)}:h.reason==="no_balance"?{error:"amount_balance_unavailable",_instructions:`Could not read the user's ${l} balance to work out ${i.raw} right now. Tell them, in their language, that the balance couldn't be fetched at the moment and ask them to enter an exact ${l} amount instead. Do NOT invent a balance or amount. Do NOT mention tool names, UI, or forms.`}:{error:"amount_price_unavailable",_instructions:`Could not get a USD price for ${l} to work out ${i.raw} right now. Tell them, in their language, that the price couldn't be fetched at the moment and ask them to enter an exact ${l} amount instead. Do NOT invent a price or amount. Do NOT mention tool names, UI, or forms.`}}async computeNativeSpendable(e,t,n){let r=await Dn(e,t);return On(n,r,e)}async resolveNativeSpendableFormatted(e,t,n){if(!(!e||!t))try{let r=await this.readTokenBalanceAndPrice("native",e,t);if(r?.balance===void 0)return;let o=await this.computeNativeSpendable(e,n,r.balance);return this.toPlainDecimal(o)}catch{return}}async readTokenBalanceAndPrice(e,t,n){if(!this.moralis||!n)return;let r=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),o=r.success?r.data?.result??[]:[],a=e.toLowerCase()==="native",i=e.toLowerCase(),l=o.find(u=>a?u.native_token===!0:(u.token_address??"").toLowerCase()===i);if(!l)return;let c=l.balance_formatted!=null?Number(l.balance_formatted):void 0;return{balance:Number.isFinite(c)?c:void 0,usdPrice:typeof l.usd_price=="number"&&l.usd_price>0?l.usd_price:void 0,balanceFormatted:l.balance_formatted,symbol:l.symbol}}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,o]=Math.abs(e).toString().split("e"),a=Number(o),[i,l=""]=r.split("."),c=i+l,u;if(a>=0){let d=i.length+a;u=d>=c.length?c.padEnd(d,"0"):`${c.slice(0,d)}.${c.slice(d)}`}else u=`0.${"0".repeat(-a-i.length)}${c}`;return u.includes(".")&&(u=u.replace(/\.?0+$/,"")),n?`-${u}`:u}formatSpendableUsd(e,t){if(e===void 0||t===void 0)return;let n=Number(e);if(!Number.isFinite(n)||!Number.isFinite(t)||t<=0)return;let r=n*t;if(!(!Number.isFinite(r)||r<=0))return this.toPlainDecimal(r)}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(a.ui=o.ui),o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(a.actionButtons=o.actionButtons),a}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){let n=this.requireWallet(t);if(!n.ok)return n.payload;let r=Dt(e.chain,t);if(r){let g=this.actionType.replace(/_/g," ");return{error:"wrong_chain",_instructions:`The user asked to ${g} on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to ${g} on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can ${g} on ${r.connectedLabel} (their current network) instead. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}let o=this.requireChain(e,t);if(!o){let g=typeof t?.query=="string"?t.query:void 0;return Ot(this.actionType.replace(/_/g," "),g)}let a=await this.buildParameters(e,t);if(a&&typeof a=="object"&&"error"in a&&typeof a.error=="string"||a&&typeof a=="object"&&"actionButtons"in a&&Array.isArray(a.actionButtons)||a&&typeof a=="object"&&"ui"in a&&a.ui&&typeof a.ui=="object"&&typeof a.ui.component=="string")return a;let i=a,l=this.buildUI({parameters:i,chainId:o,walletAddress:n.address}),c=g=>{let y=i[g];return y!=null&&y!==""},u=this.userInputFields.filter(g=>!(Array.isArray(g.key)?g.key:[g.key]).some(c)).map(g=>g.label),d=this.userInputFields.map(g=>{let b=(Array.isArray(g.key)?g.key:[g.key]).find(c);return b?`${g.label}: ${i[b]}`:null}).filter(g=>g!=null),p=this.actionType.replace(/_/g," "),h='NEVER invent, guess, or insert a placeholder (e.g. "[recipient address]") for any detail the user has not actually provided \u2014 only state values listed as already provided. Do NOT mention tool names, UI, or forms.',f="The user completes this themselves and it is submitted right away \u2014 do NOT ask them to reply to confirm, do NOT say you will send it for them, and do NOT announce the result. This turn ends after your message.",m=u.length>0?`The ${p} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${u.join(", ")}. `+(d.length>0?`Already provided: ${d.join("; ")}. `:"")+`${f} ${h}`:`The ${p} has all required details. In the user's language, briefly tell the user to review the details and submit to complete the ${p}. `+(d.length>0?`Details provided: ${d.join("; ")}. `:"")+`${f} ${h}`;return{ui:l,action:this.actionType,chainId:o,parameters:i,_instructions:m}}};var Mn=class extends Pe{name="open-send-native-form";actionType="send_native";component="SendNativeForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}async run(e,t){if(e.chain==null||e.chain===""){let n=Hs(e.native_symbol);if(n)return super.run({...e,chain:n},t)}return super.run(e,t)}description=`Open the SEND NATIVE form for the chain's native coin (ETH/BNB/MATIC/AVAX/\u2026). Use for ANY native-send intent: "send eth", "send 0.1 ETH", "transfer 1 BNB to vitalik.eth", "g\u1EEDi ETH". Call EVEN IF the user did not name an amount or recipient \u2014 the form prompts for them. Do NOT use for ERC-20 tokens \u2014 use open-send-token-form instead.`;parameters=[{name:"chain",type:"string",description:'Hex chain id: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. Defaults to connected chain.',required:!1},{name:"native_symbol",type:"string",description:'The native coin the user named to send, VERBATIM (e.g. "ETH", "BNB", "MATIC", "AVAX"). ALWAYS set this when the user names the coin ("send bnb" \u2192 native_symbol="BNB"); leave blank only when they say just "send" with no coin. A coin that belongs to one specific chain (BNB\u2192BSC, MATIC/POL\u2192Polygon, AVAX\u2192Avalanche, XDAI\u2192Gnosis, HYPE\u2192HyperEVM, MNT\u2192Mantle, MON\u2192Monad) selects that chain, so the tool can detect when the wallet is connected elsewhere.',required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Amount of native coin to send. Accepted forms: a plain amount ("0.1"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become the literal "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself (and for the native coin always leaves enough to cover the network fee). Omit when unknown.',required:!1}];async buildParameters(e,t){let n={},r=this.requireChain(e,t)??void 0,o=t?.walletAddress??void 0,a=await this.readTokenBalanceAndPrice("native",r,o);if(!a||a.balance==null||a.balance<=0){let d=a?.symbol||"the native coin";return{error:"no_native_balance",_instructions:`The user wants to send ${d} but their wallet holds 0 ${d} on this chain. Tell them, in their language, that they do not have any ${d} to send and suggest they top up first. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}let i=a.symbol||(typeof e.native_symbol=="string"&&e.native_symbol.trim()?e.native_symbol.trim():void 0);if(i&&(n.native_symbol=i),e.to_address!=null){let d=this.normaliseAddress(e.to_address);d?n.to_address=d:typeof e.to_address=="string"&&e.to_address.trim()&&(n.to_address=e.to_address.trim())}let l=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:"native",symbol:"the native coin",chain:r,walletAddress:o,gasKind:"send"});if(l&&"error"in l)return l;l&&(n.amount=l.amount);let c=await this.resolveNativeSpendableFormatted(r,o,"send");c!==void 0&&(n.spendable=c);let u=this.formatSpendableUsd(c,a.usdPrice);return u!==void 0&&(n.spendableUsd=u),n}};var Fn=class extends Pe{name="open-send-token-form";actionType="send_token";component="SendTokenForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}description=`Open the SEND TOKEN (ERC-20) form. Use for ANY ERC-20 send/transfer intent: "send token", "send USDC", "transfer 50 DAI to 0x\u2026", "g\u1EEDi 10 USDT". Call this tool EVEN IF the user did not name a token, amount, or recipient \u2014 the tool handles missing token via a picker, the form prompts for the rest. Do NOT use for the chain's native coin (ETH/BNB/MATIC/AVAX) \u2014 use open-send-native-form instead.`;parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol \u2014 the tool will look up the address.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). ALWAYS set this whenever the user names a token to send ("send usdc" \u2192 token_symbol="USDC"); only leave it blank when the user names NO token at all ("send token"), so the tool can show a wallet picker. Used to auto-resolve the contract address and to display the symbol in the form. (Pass either this or contract_address.)',required:!1},{name:"decimals",type:"number",description:"Token decimals (e.g. 6 for USDC, 18 for most ERC-20s). Optional.",required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown.",required:!1},{name:"amount",type:"string",description:'Amount of the token to send. Accepted forms: a plain amount ("100"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself. Omit when unknown.',required:!1},{name:"send_prompt_template",type:"string",description:`A short imperative "send" command IN THE USER'S LANGUAGE, used as the label/command when the user has not yet picked which token to send (token-picker buttons). Write it in the SAME language the user is using right now. Use these exact placeholders (do not translate the braces): "{symbol}" for the token, "{amount}" for the amount, "{to}" for the recipient address, "{chain}" for the chain name. Put the localized verb, the "to" preposition, and the "on <chain>" preposition directly in the text. English example: "send {amount} {symbol} to {to} on {chain}". Vietnamese example: "g\u1EEDi {amount} {symbol} \u0111\u1EBFn {to} tr\xEAn {chain}". Japanese example: "{chain} \u3067 {to} \u306B {amount} {symbol} \u3092\u9001\u308B". Always include {symbol}. Include {amount}/{to}/{chain} too \u2014 the tool removes any whose value is unknown.`,required:!0}];async buildParameters(e,t){let n=this.normaliseAddress(e.contract_address)!=null,r=typeof e.token_symbol=="string"&&e.token_symbol.trim().length>0;if(!n&&!r&&this.moralis){let d=this.requireChain(e,t)??void 0,p=t?.walletAddress;if(p){let h=await this.moralis.getWalletTokenBalances({address:p,chain:d,excludeSpam:!1,excludeUnverifiedContracts:!1}),m=(h.success?h.data?.result??[]:[]).filter(T=>T.symbol&&(T.native_token||T.token_address)).sort((T,P)=>(P.usd_value??0)-(T.usd_value??0)).slice(0,8);if(m.length===0)return{error:"no_token_holdings",_instructions:"The wallet does not hold any sendable tokens on this chain. Tell the user they have nothing to send and suggest they top up first. Do NOT open the form."};let g=e.to_address!=null?this.normaliseAddress(e.to_address):null,y=this.normaliseAmount(e.amount),b=typeof e.send_prompt_template=="string"?e.send_prompt_template:"",w=d?v(d):null;return{actionButtons:m.map(T=>{let P=T.symbol,S=T.balance_formatted?this.cleanAmountString(T.balance_formatted):"",_=T.name?T.name:"",N=T.usd_value?`($${T.usd_value.toFixed(2)})`:"";return{label:`${_}:${S} ${P} ${N}`.trim(),prompt:this.buildSendPrompt(b,P,y,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 o=this.requireChain(e,t)??void 0,a=t?.walletAddress??void 0,i=await this.findOwnedTokenForSend(e,o,a);if(i&&"error"in i)return i;let l=i?.token,c={};l?.address&&(c.contract_address=l.address),l?.symbol&&(c.token_symbol=l.symbol),l?.decimals!==void 0&&(c.decimals=String(l.decimals)),i?.spendable!==void 0&&(c.spendable=i.spendable);let u=this.formatSpendableUsd(i?.spendable,i?.usdPrice);if(u!==void 0&&(c.spendableUsd=u),e.to_address!=null){let d=this.normaliseAddress(e.to_address);d?c.to_address=d:typeof e.to_address=="string"&&e.to_address.trim()&&(c.to_address=e.to_address.trim())}if(l?.address){let d=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:l.address,symbol:l.symbol,chain:o,walletAddress:a});if(d&&"error"in d)return d;d&&(c.amount=d.amount)}else{let d=this.normaliseAmount(e.amount);d&&(c.amount=d)}return c}async findOwnedTokenForSend(e,t,n){let r=this.normaliseAddress(e.contract_address),o=typeof e.token_symbol=="string"&&e.token_symbol.trim()?e.token_symbol.trim():void 0,a=r??o;if(!this.moralis||!n||!a){let h=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:t,walletAddress:n});return"error"in h?{error:"token_not_found",symbol:h.key,_instructions:`Could not resolve token "${h.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`}:{token:h.token}}let i=a.toLowerCase(),l=r!=null,c=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),d=(c.success?c.data?.result??[]:[]).find(h=>l?(h.token_address??"").toLowerCase()===i:(h.symbol??"").toLowerCase()===i);if(d&&d.balance&&!/^0*$/.test(d.balance.trim())){let h=this.parseDecimals(e.decimals);return{token:{address:d.token_address,symbol:d.symbol??o,name:d.name,decimals:h??(typeof d.decimals=="number"?d.decimals:void 0)},spendable:d.balance_formatted?this.cleanAmountString(d.balance_formatted):void 0,usdPrice:typeof d.usd_price=="number"&&d.usd_price>0?d.usd_price:void 0}}let p=d?.symbol??o??a;return{error:"no_balance",symbol:p,_instructions:`The user does not hold any ${p} in their wallet on this chain, so there is nothing to send. Tell them (in their language) that they don't have any ${p} to send, and suggest they top up or pick another token. Do NOT open a form. Do NOT mention tool names, UI, or forms.`}}buildSendPrompt(e,t,n,r,o){let i=(e&&e.includes("{symbol}")?e:"send {amount} {symbol} to {to} on {chain}").replace(/\{symbol\}/g,t).replace(/\{amount\}/g,n??"");return i=this.fillOrDropPhrase(i,"{to}",r),i=this.fillOrDropPhrase(i,"{chain}",o),i.replace(/\s+/g," ").trim()}fillOrDropPhrase(e,t,n){if(n)return e.split(t).join(n);let r=t.replace(/[{}]/g,"\\$&");return e.replace(new RegExp(`\\s*\\S+\\s*${r}`,"g"),"").replace(new RegExp(`${r}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(r,"g"),"")}};var qn=class extends Pe{name="open-approve-token-form";actionType="approve_token";component="ApproveTokenForm";userInputFields=[{key:"spender_address",label:"the spender address to approve"}];constructor(e){super(e)}description='Open the APPROVE TOKEN form so the user can grant a spender allowance on an ERC-20 token. Use when the user says "approve USDC for Uniswap", "c\u1EA5p quy\u1EC1n 100 USDT cho 0x\u2026", "revoke approval". Pass `contract_address` when you have it; otherwise pass `token_symbol` (e.g. "USDC") and the tool auto-resolves the contract. Always pass `spender_address` (the contract being approved). Pass `amount` for a specific allowance; omit for unlimited (max uint256). For approving 0 to revoke, pass amount="0".';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). Required when contract_address is not given. Used to auto-resolve the contract.',required:!1},{name:"decimals",type:"number",description:"Token decimals.",required:!1},{name:"spender_address",type:"string",description:"EVM address of the spender contract being approved (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Human-readable allowance amount. Omit for UNLIMITED (max uint256). Pass "0" to revoke.',required:!1}];async buildParameters(e,t){let n=this.requireChain(e,t)??void 0,r=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:n,walletAddress:t?.walletAddress??void 0});if("error"in r)return{error:"token_not_found",symbol:r.key,_instructions:`Could not resolve token "${r.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`};let o=r.token,a=this.normaliseAddress(e.spender_address),i={};if(o?.address&&(i.contract_address=o.address),a&&(i.spender_address=a),o?.symbol&&(i.token_symbol=o.symbol),o?.decimals!==void 0&&(i.decimals=String(o.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}};var Bn=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 D(e),this.pantograph=new ue({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[BuyTokenTool] ${e}`):console.log(`[BuyTokenTool] ${e}`,JSON.stringify(t)))}description='Open the BUY TOKEN flow for ANY buy/purchase intent. Handles both cases: (a) the user NAMED a token \u2014 "buy PEPE", "mua DOGE", "buy 100 USDC with ETH": pass `token_symbol` (the destination); if you also know the pay token, fill `pay_with_symbol` (or `pay_with_address`), else leave pay_with_* blank and the tool returns a wallet picker. (b) the user did NOT name a token \u2014 "buy a trending token", "mua token trending", "buy something pumping", "buy hot tokens", "mua token t\u0103ng m\u1EA1nh": leave `token_symbol` blank and the tool returns buttons of the chain\'s current trending tokens so the user picks one. Amount: `buy_amount` = destination to RECEIVE; `pay_with_amount` = payment to SPEND. Never both.';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"token_symbol",type:"string",description:'Symbol of the token the user wants to BUY (e.g. "PEPE"). Leave EMPTY when the user did not name a token (e.g. "buy a trending token") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"contract_address",type:"string",description:`Destination token address (0x\u2026), or "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from token_symbol.`,required:!1},{name:"buy_amount",type:"string",description:`Quantity of the DESTINATION token (the one being bought) the user wants to RECEIVE. Set this when the amount sits next to the token being bought: "buy 5 PEPE", "mua 5 PEPE", "buy 0.02 PCM with USDC" \u2192 buy_amount = the number next to PEPE/PCM. May also be a USD value when the user sizes the buy in dollars ("buy $5 of PEPE" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$" to a token quantity). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with pay_with_amount \u2014 set at most ONE of the two.`,required:!1},{name:"pay_with_symbol",type:"string",description:'Symbol of the payment token (e.g. "USDC", "ETH"). Set ONLY when the user actually named a token to pay with. Leave EMPTY when they did not \u2014 do NOT default to the native coin / ETH; the tool then returns a picker of the tokens the wallet holds.',required:!1},{name:"pay_with_address",type:"string",description:`Address of the payment token (0x\u2026), OR "native" for the chain's native coin. Set ONLY when the user named the payment token. Leave EMPTY when they did not \u2014 do NOT invent an address or default to native.`,required:!1},{name:"pay_with_amount",type:"string",description:'Quantity of the PAYMENT token (the one being spent) the user wants to SPEND. Set this when the amount sits next to the payment token: "buy PEPE with 10 USDC", "mua PEPE b\u1EB1ng 10 USDC", "spend 0.5 ETH on DOGE" \u2192 pay_with_amount = the number next to USDC/ETH. May also be a PERCENT of the pay-token balance ("buy USDC with 50% USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("buy USDC with 5$ USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set pay_with_symbol to the payment token ("ETH" in "buy USDC with max ETH"). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with buy_amount \u2014 set at most ONE of the two.',required:!1},{name:"limit",type:"number",description:"Only used when no token is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the trending-token picker (when the user named no token). Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_with_prompt_template",type:"string",description:`A short "buy X with Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the pay-token picker and the percentage-spend buttons. Use these exact placeholders (do not translate the braces): "{token}" = token being bought, "{pay}" = payment token, "{buy_amount}" = quantity of the BOUGHT token (place it next to {token}), "{pay_amount}" = quantity of the PAYMENT token (place it next to {pay}). Put the localized verb and the "with" preposition directly in the text. English example: "buy {buy_amount} {token} with {pay_amount} {pay}". Vietnamese example: "mua {buy_amount} {token} b\u1EB1ng {pay_amount} {pay}". Japanese example: "{pay_amount} {pay} \u3067 {buy_amount} {token} \u8CFC\u5165". Always include {token} and {pay}. Include both {buy_amount} and {pay_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount).`,required:!0}];async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(a.ui=o.ui),o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(a.actionButtons=o.actionButtons),a}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before buying. Do NOT proceed."};let r=Dt(e.chain,t);if(r)return{error:"wrong_chain",_instructions:`The user asked to buy on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to buy on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can buy on ${r.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return Ot("buy",a)}return this.buildResult(e,t)}async buildResult(e,t){this.correctAmountSide(e,t),this.dropUnmentionedPayToken(e,t),this.dropInventedAmounts(e,t);let n=typeof e.token_symbol=="string"?e.token_symbol.trim():"",r=typeof e.contract_address=="string"?e.contract_address.trim():"",o=this.requireChain(e,t)??void 0,a=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:o,walletAddress:a,hasMoralis:!!this.moralis}),!n&&!r)return this.dbg("\u2192 Branch 0: trending picker (no token named)"),await this.buildTrendingPicker(e,t);let i=await this.resolveSide(e.contract_address,n,o,a,"dest"),l=i.address,c=i.symbol??n,u=i.decimals,d=await this.resolveSide(e.pay_with_address,e.pay_with_symbol,o,a,"pay"),p=d.address,h=d.symbol,f=d.decimals,m=await this.resolveBuyAmountSpec(e.buy_amount,l,o,c),g=p?await this.resolvePayAmountSpec(e.pay_with_amount,p,o,a,h,f??(p==="native"?18:void 0)):this.normaliseAmount(e.pay_with_amount),y=qe(e.pay_with_amount),b=!!y&&y.kind!=="token",w=null;if(this.dbg("resolved sides",{dest:{destContract:l,destSymbol:c,destDecimals:u},pay:{payAddr:p,paySymbol:h,payDecimals:f},buyAmount:m,payAmount:g}),!l)return this.dbg("\u2192 dest token not resolved"),{error:"dest_token_not_found",_instructions:`Could not find the token "${c||r}" to buy on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(!p&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: pay picker (pay token missing)"),await this.buildPayWithPicker({args:e,userContext:t,destSymbol:c,destContract:l,buyAmount:m,payAmount:g});if(!p)return{error:"pay_token_missing",_instructions:`Ask the user, in their language, which token they want to spend to buy ${c}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(m&&!g){this.dbg("Branch 1.3: deriving pay amount from buy amount",{buyAmount:m,destSymbol:c,paySymbol:h});let k=await this.derivePayAmountFromBuy({chain:o,buyAmount:m,destContract:l,destSymbol:c,payAddr:p,paySymbol:h});if(!k)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs pay amount"),{error:"needs_pay_amount",_instructions:`Could not work out how much ${h??"of the payment token"} equals ${m} ${c} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${h??"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.`};g=k,w=m,b=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:g,derivedFromBuy:w})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking pay balance",{payAddr:p,paySymbol:h,payAmount:g});let k=await this.checkPayBalance({args:e,userContext:t,chain:o,destSymbol:c,destContract:l,payAddr:p,paySymbol:h,payAmount:g,buyAmount:m,derivedFromBuy:w,amountSizedToBalance:b});if(k)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:k.error,hasButtons:Array.isArray(k.actionButtons)}),k;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!m&&!g&&this.moralis&&t?.walletAddress){this.dbg("Branch 1.5: building amount picker");let k=await this.buildAmountPicker({userContext:t,chain:o,destSymbol:c,payAddr:p,paySymbol:h,buyWithTemplate:typeof e.buy_with_prompt_template=="string"?e.buy_with_prompt_template:""});if(k)return this.dbg("\u2192 Branch 1.5: amount picker returned"),k;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(g&&(f!==void 0||p==="native")){this.dbg("Branch 1.75: building confirm tx");let k=await this.buildConfirmTx({userContext:t,chain:o,destContract:l,destSymbol:c,destDecimals:u,payAddr:p,paySymbol:h,payDecimals:f,payAmount:g});return k&&"ui"in k?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),k):k&&"quoteError"in k?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:k.quoteError}),{error:"quote_failed",quoteError:k.quoteError,_instructions:`Could not quote buying ${c} with ${h??"the selected token"}. The swap provider reported: "${k.quoteError}". Tell the user, in their language, exactly that reason (translate the wording, keep any numbers/limits verbatim) and suggest they adjust the amount or try again shortly. Do NOT invent numbers or a different reason. Do NOT mention tool names, UI, or forms.`}):(this.dbg("Branch 1.75: confirm tx unavailable (null)"),{error:"quote_failed",_instructions:`Could not get a quote to buy ${c} with ${h??"the selected token"} right now. Tell the user, in their language, that the swap could not be quoted at the moment and ask them to try again shortly or with a different amount. Do NOT invent numbers. Do NOT mention tool names, UI, or forms.`})}return this.dbg("\u2192 needs pay amount"),{error:"needs_pay_amount",_instructions:`Ask the user, in their language, how much ${h??"of the payment token"} they want to spend to buy ${c}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return F(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=t.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(!n)return null;let r=parseFloat(n[1]);return Number.isFinite(r)&&r>0?n[1]:null}correctAmountSide(e,t){let n=typeof t?.query=="string"?t.query:"",r=typeof e.token_symbol=="string"?e.token_symbol.trim():"",o=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"";if(!n||!r||!o)return;let a=typeof e.buy_amount=="string"?e.buy_amount.trim():"",i=typeof e.pay_with_amount=="string"?e.pay_with_amount.trim():"",l=a.length>0,c=i.length>0;if(l===c)return;let u=l?a:i,d=u.match(/[0-9]*\.?[0-9]+/)?.[0];if(!d)return;let p=this.nearestSymbolSide(n,d,r,o);p&&(p==="pay"&&l?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:u,buySym:r,paySym:o}),e.pay_with_amount=u,e.buy_amount=""):p==="buy"&&c&&(this.dbg("correctAmountSide: pay_with_amount \u2192 buy_amount",{amount:u,buySym:r,paySym:o}),e.buy_amount=u,e.pay_with_amount=""))}dropUnmentionedPayToken(e,t){let n=typeof t?.query=="string"?t.query:"";if(!n)return;let r=typeof e.token_symbol=="string"?e.token_symbol.trim():"";if(!r)return;let o=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"",a=typeof e.pay_with_address=="string"?e.pay_with_address.trim():"";if(!o&&!a)return;let i=n.toLowerCase(),l=o.toLowerCase(),c=a.toLowerCase(),u=l==="native"||c==="native",d=[];if(o&&l!=="native"&&d.push(l),c&&c!=="native"&&d.push(c),u){d.push("native");let h=this.requireChain(e,t)??void 0,f=h?se(h)?.native.symbol:void 0;f&&d.push(f.toLowerCase())}d.some(h=>F(h)?i.includes(h):this.indexOfToken(i,h)>=0)||(this.dbg("dropUnmentionedPayToken: clearing invented pay token",{paySym:o,payAddr:a,buySym:r}),e.pay_with_symbol="",e.pay_with_address="")}dropInventedAmounts(e,t){let n=typeof t?.query=="string"?t.query:"";if(!n)return;let r=(n.match(/[0-9]*\.?[0-9]+/g)??[]).map(parseFloat).filter(Number.isFinite),o=a=>{let i=typeof e[a]=="string"?e[a].trim():"";if(!i)return;let l=i.match(/[0-9]*\.?[0-9]+/)?.[0];if(l===void 0)return;let c=parseFloat(l);Number.isFinite(c)&&(r.some(u=>u===c)||(this.dbg(`dropInventedAmounts: clearing invented ${a}`,{val:i}),e[a]=""))};o("buy_amount"),o("pay_with_amount")}nearestSymbolSide(e,t,n,r){let o=e.toLowerCase(),a=o.indexOf(t.toLowerCase()),i=this.indexOfToken(o,n.toLowerCase()),l=this.indexOfToken(o,r.toLowerCase());if(a<0||i<0||l<0)return null;let c=(p,h)=>Math.max(0,p-(a+t.length),a-(p+h)),u=c(i,n.length),d=c(l,r.length);return d===u?null:d<u?"pay":"buy"}indexOfToken(e,t){if(!t)return-1;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|[^a-z0-9])(${n})(?:[^a-z0-9]|$)`));return r&&r.index!==void 0?r.index+r[0].indexOf(r[1]):-1}requireChain(e,t){let n=typeof e.chain=="string"&&e.chain.trim()?e.chain.trim():null;return n||(typeof t?.chain=="string"&&t.chain.trim()?t.chain.trim():null)}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=F(e.trim()),a=l=>o?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}async resolveSide(e,t,n,r,o="side"){let a=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(a.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,u=h=>h.toLowerCase()===$?"native":h,d=l??c??(a||void 0);if(!d)return this.dbg(`resolveSide:${o}`,{refStr:a,symbolStr:i,chain:n,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(d,n,r);return this.dbg(`resolveSide:${o}`,{refStr:a,symbolStr:i,chain:n,key:d,lookup:p}),p?{address:u(p.address),symbol:c??p.symbol,decimals:p.decimals}:l?{address:u(l),symbol:c}:{address:null,symbol:c}}async buildConfirmTx(e){let{userContext:t,chain:n,destContract:r,destSymbol:o,destDecimals:a,payAddr:i,paySymbol:l,payDecimals:c,payAmount:u}=e,d=t?.walletAddress;if(!d||!n||!r)return null;let p=se(n),h=Number.parseInt(n,16);if(!p||!Number.isFinite(h))return null;let f=i==="native",m=f?p.native.decimals??18:c;if(m===void 0)return null;let g=this.toRawAmount(u,m);if(!g)return null;let y=f?$:i,b=r==="native"?$:r,w;try{w=await(await Fe.getServiceByProvider("debridge")).getQuote({srcChainId:h,srcTokenAddress:y,srcTokenAmount:g,dstChainId:h,dstTokenAddress:b,recipientAddress:d,senderAddress:d,slippage:"auto",isCrossChain:!1})}catch(E){return{quoteError:E instanceof Error?E.message:String(E)}}if(!w.success)return this.dbg("buildConfirmTx: quote failed",{error:w.error,errorMessage:w.errorMessage}),{quoteError:this.extractQuoteError(w)};if(!w.tx)return{quoteError:"No route available for this swap."};let k=w.tx;if(!k.to||typeof k.data!="string")return null;let T={chainId:n,to:k.to,data:k.data,value:k.value??"0",from:d},P=this.extractOutRaw(w),S=P&&a!==void 0?this.trimAmount(Number(P)/10**a):void 0,_;f||(_=await this.buildApproveTx({chain:n,walletAddress:d,payAddr:i,payDec:m,rawAmount:g,quote:w}));let C={component:"BuyTokenConfirmTx",props:{chain:{hexId:n,name:p.name},payToken:{address:f?"native":i,symbol:l,decimals:m,amount:u,rawAmount:g},buyToken:{address:r,symbol:o,decimals:a,amount:S,rawAmount:P},estimatedOut:S,estimatedOutRaw:P,provider:w.provider,swapTx:T,approveTx:_}},q=S?` They will receive about ${S} ${o}.`:"";return{ui:C,_instructions:`The purchase of ${o} with ${u} ${l??"the selected token"} is ready for the user to confirm.${q} Briefly tell the user, in their language, the amount they are spending and the estimated amount they will receive, and ask them to review and confirm to complete the purchase. The estimate is approximate \u2014 say "about"/"estimated", never a guaranteed amount. Speak only of the user's action (buying) \u2014 NEVER say you "opened" a panel/form/window or describe any UI being shown. NEVER invent numbers not provided here. Do NOT mention tool names, UI, forms, or internal steps like approval.`}}async derivePayAmountFromBuy(e){let{chain:t,buyAmount:n,destContract:r,payAddr:o}=e,[a,i]=await Promise.all([this.getUsdPrice(r,t),this.getUsdPrice(o,t)]);if(this.dbg("derivePayAmountFromBuy: prices",{destPrice:a,payPrice:i}),!a||!i)return null;let l=Number(n);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,u=l*a/i;return!Number.isFinite(u)||u<=0?null:this.trimAmount(u*c)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?$:e,r=await this.moralis.getTokenMetadata({address:n,chain:t}),o=r.success?r.data?.usd_price:void 0;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}async resolvePayAmountSpec(e,t,n,r,o,a){let i=qe(e);if(!i)return null;let l=u=>a===void 0?u:Qe(u,a);if(i.kind==="token")return l(Et(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!r)return null;let u=await this.readPayBalance(r,t,n);if(this.dbg("resolvePayAmountSpec: percent",{percent:i.percent,paySymbol:o,bal:u?.balanceNum}),!u||!Number.isFinite(u.balanceNum)||u.balanceNum<=0)return null;let d=u.decimals??a??18;return i.percent>=100?this.cleanAmountString(u.balanceFormatted):Nt(u.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,d)}let c=await this.getUsdPrice(t,n);return this.dbg("resolvePayAmountSpec: usd",{usd:i.usd,paySymbol:o,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveBuyAmountSpec(e,t,n,r){let o=qe(e);if(!o)return null;if(o.kind==="token")return Et(e)??this.toPlainDecimal(o.value);if(o.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,n);return this.dbg("resolveBuyAmountSpec: usd",{usd:o.usd,destSymbol:r,price:a}),a?this.trimAmount(o.usd/a):null}async buildApproveTx(e){let{chain:t,walletAddress:n,payAddr:r,payDec:o,rawAmount:a,quote:i}=e;try{let c=await(await Fe.getServiceByProvider("debridge")).checkApproval({chain:t,userAddress:n,tokenAddress:r,amount:a,tokenDecimals:o,quoteData:i});if(!c.isNeeded)return;let u=c.approvalData??{};if(u.to&&typeof u.data=="string")return{chainId:t,to:u.to,data:u.data,value:u.value??"0",from:n};let d=c.contractAddress;if(!d)return;let p=xt({abi:jo,functionName:"approve",args:[d,BigInt(a)]});return{chainId:t,to:r,data:p,value:"0",from:n}}catch{return}}toRawAmount(e,t){let n=e.trim();if(!/^\d*\.?\d+$/.test(n))return null;let[r,o=""]=n.split("."),a=o.slice(0,t).padEnd(t,"0");try{let i=BigInt(r||"0")*10n**BigInt(t)+BigInt(a||"0");return i<=0n?null:i.toString()}catch{return null}}extractQuoteError(e){if(e.errorMessage&&e.errorMessage.trim())return e.errorMessage.trim();let t=r=>{if(typeof r=="string"&&r.trim())return r.trim();if(r&&typeof r=="object"){let o=r;for(let a of[o.message,o.errorMessage,o.error])if(typeof a=="string"&&a.trim())return a.trim()}},n=e.raw??{};return t(e.error)??t(n.errorMessage)??t(n.error)??"The swap could not be quoted right now."}extractOutRaw(e){let t=e.raw??{},n=t.tokenOut?.amount??t.tokenOut?.minAmount??t.details?.currencyOut?.amount??t.details?.currencyOut?.minimumAmount??t.estimation?.dstChainTokenOut?.recommendedAmount??t.estimation?.dstChainTokenOut?.amount;return n&&/^\d+$/.test(n)?n:void 0}async buildPayWithPicker(e){let{args:t,userContext:n,destSymbol:r,destContract:o}=e,a=this.requireChain(t,n)??void 0,i=this.moralis,l=n.walletAddress,c=await i.getWalletTokenBalances({address:l,chain:a,excludeSpam:!1,excludeUnverifiedContracts:!1}),u=c.success?c.data?.result??[]:[],d=o?.toLowerCase(),p=r.trim().toLowerCase(),h=u.filter(b=>!b.symbol||p&&b.symbol.toLowerCase()===p?!1:b.native_token?d!=="native":!(!b.token_address||d&&b.token_address.toLowerCase()===d)).sort((b,w)=>(w.usd_value??0)-(b.usd_value??0)).slice(0,8);if(h.length===0)return{error:"no_pay_token_holdings",_instructions:"The wallet has no tokens that can pay for this purchase on this chain. Tell the user to top up first. Do NOT mention tool names, UI, or forms."};let f=e.buyAmount??this.normaliseAmount(t.buy_amount),m=e.payAmount??this.normaliseAmount(t.pay_with_amount),g=typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"";return{actionButtons:h.map(b=>{let w=b.symbol,k=b.name?.trim()||w,T=b.balance_formatted?`${this.cleanAmountString(b.balance_formatted)} `:"",P=typeof b.usd_value=="number"&&b.usd_value>0?` ($${b.usd_value.toFixed(2)})`:"",S=`${k}: ${T}${w}${P}`,_=f?this.buildBuyWithPrompt(g,r,w,f,null):this.buildBuyWithPrompt(g,r,w,null,m);return{label:S,prompt:_}}),_instructions:`Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n mua ${r}.' / 'You want to buy ${r}.'), then ask them to choose which token they want to spend to buy ${r} from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua.' / 'Please choose the token to spend.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms.`}}async checkPayBalance(e){let{args:t,userContext:n,chain:r,destSymbol:o,destContract:a,payAddr:i,payAmount:l,buyAmount:c,derivedFromBuy:u}=e,d=n.walletAddress,p=await this.readPayBalance(d,i,r),h=e.paySymbol??p?.symbol??"the selected token";if(!p){this.dbg("checkPayBalance: NOT held \u2192 pay picker fallback",{paySymbol:h});let b=await this.buildPayWithPicker({args:t,userContext:n,destSymbol:o,destContract:a,buyAmount:c,payAmount:l});return"actionButtons"in b?{error:"no_pay_balance",actionButtons:b.actionButtons,_instructions:`The user wanted to spend ${h} to buy ${o}, but their wallet holds no ${h} on this chain. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${h} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${h} tr\xEAn m\u1EA1ng n\xE0y.'), then ask them to choose one of the tokens they already hold to pay with (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua ${o} 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.`}:b}if(!l||e.amountSizedToBalance)return null;let f=p.decimals!==void 0?Qe(l,p.decimals):l;if(ft(f,p.balanceFormatted)<=0)return null;let m=this.cleanAmountString(p.balanceFormatted),g=this.percentSpendButtons({balanceFormatted:p.balanceFormatted,balanceNum:p.balanceNum,decimals:p.decimals,paySymbol:h,destSymbol:o,buyWithTemplate:typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:""}),y=u?`Buying ${u} ${o} needs about ${l} ${h}, but they only have ${m} ${h} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them that buying ${u} ${o} would cost about ${l} ${h}, which is more than their balance of ${m} ${h}, then ask them to choose a smaller amount or spend less \u2014 `:`The user wants to spend ${l} ${h} to buy ${o}, but they only have ${m} ${h} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${l} ${h} exceeds their balance of ${m} ${h}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_pay_balance",actionButtons:g,_instructions:y+'invite them to choose one of the options below (sized to their balance) or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT invent numbers, and do NOT mention tool names, UI, buttons, or forms.'}}async readPayBalance(e,t,n){if(!this.moralis)return null;let r=await this.moralis.getWalletTokenBalances({address:e,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),o=r.success?r.data?.result??[]:[];this.dbg("readPayBalance",{payAddr:t,chain:n,ok:r.success,count:o.length,held:o.map(c=>({sym:c.symbol,addr:c.token_address,bal:c.balance_formatted}))});let a=t.toLowerCase(),i=o.find(c=>a==="native"?c.native_token===!0:c.token_address?.toLowerCase()===a);if(!i?.balance_formatted)return this.dbg("readPayBalance: pay token NOT held \u2192 null",{payAddr:t}),null;let l=Number(i.balance_formatted);if(!Number.isFinite(l)||l<=0)return this.dbg("readPayBalance: zero/invalid balance \u2192 null",{payAddr:t,balance:i.balance_formatted}),null;if(a==="native"&&n){let c=await Dn(n,"swap"),u=On(l,c,n);if(this.dbg("readPayBalance: native spendable",{balanceNum:l,spendable:u}),u<=0)return this.dbg("readPayBalance: native spendable \u2264 0 \u2192 null",{balanceNum:l}),null;let d=this.trimAmount(u),p=typeof i.decimals=="number"?i.decimals:18;return{balanceFormatted:d,balanceNum:u,symbol:i.symbol,decimals:p}}return this.dbg("readPayBalance: held",{payAddr:t,balance:i.balance_formatted,symbol:i.symbol}),{balanceFormatted:i.balance_formatted,balanceNum:l,symbol:i.symbol,decimals:typeof i.decimals=="number"?i.decimals:void 0}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,paySymbol:r,destSymbol:o,buyWithTemplate:a}=e,i=n??18;return[25,50,75,100].map(c=>{let u=Nt(this.cleanAmountString(t),BigInt(c),100n,i);return{label:`${c}%`,prompt:this.buildBuyWithPrompt(a,o,r,null,u)}})}async buildAmountPicker(e){let{userContext:t,chain:n,destSymbol:r,payAddr:o,buyWithTemplate:a}=e,i=t.walletAddress,l=await this.readPayBalance(i,o,n),c=e.paySymbol??l?.symbol;if(!l||!c)return null;let u=this.percentSpendButtons({balanceFormatted:l.balanceFormatted,balanceNum:l.balanceNum,decimals:l.decimals,paySymbol:c,destSymbol:r,buyWithTemplate:a}),d=this.cleanAmountString(l.balanceFormatted);return{actionButtons:u,_instructions:`The user's spendable balance is ${d} ${c}. Reply briefly in the user's language using the pattern 'state intent + balance \u2192 ask to choose': first state what the user wants and their spendable ${c} balance (e.g., 'B\u1EA1n mu\u1ED1n mua ${r} b\u1EB1ng ${c}, hi\u1EC7n c\xF3 ${d} ${c} c\xF3 th\u1EC3 d\xF9ng.' / 'You want to buy ${r} with ${c}; you have ${d} ${c} available.'), then ask how much they want to spend and invite them to choose one of the options below or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT mention tool names, UI, buttons, or forms.`}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,o]=Math.abs(e).toString().split("e"),a=Number(o),[i,l=""]=r.split("."),c=i+l,u;if(a>=0){let d=i.length+a;u=d>=c.length?c.padEnd(d,"0"):`${c.slice(0,d)}.${c.slice(d)}`}else u=`0.${"0".repeat(-a-i.length)}${c}`;return u.includes(".")&&(u=u.replace(/\.?0+$/,"")),n?`-${u}`:u}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildBuyPrompt(e,t){return(e&&e.includes("{token}")?e:"buy {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}buildBuyWithPrompt(e,t,n,r,o){return(e&&e.includes("{token}")&&e.includes("{pay}")?e:"buy {buy_amount} {token} with {pay_amount} {pay}").replace(/\{token\}/g,t).replace(/\{pay\}/g,n).replace(/\{buy_amount\}/g,r??"").replace(/\{pay_amount\}/g,o??"").replace(/\s+/g," ").trim()}async buildTrendingPicker(e,t){if(!this.pantograph)return{error:"trending_unavailable",_instructions:"Trending tokens are unavailable in this build (service not configured). Tell the user briefly and ask them to name a token to buy."};let n=this.requireChain(e,t)??void 0,r=typeof e.limit=="number"&&Number.isFinite(e.limit)?Math.floor(e.limit):6,o=Math.max(1,Math.min(10,r)),a=await this.pantograph.getTrendingTokens({chain:n,limit:o}),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(h=>h.symbol),c=typeof e.buy_prompt_template=="string"?e.buy_prompt_template:"",u=l.map(h=>{let f=h.symbol;return{label:f,prompt:this.buildBuyPrompt(c,f)}}),p=l.map((h,f)=>{let m=h.name?.trim()||h.symbol,g=h.symbol,y=typeof h.usdPrice=="number"&&h.usdPrice>0?`$${this.formatPrice(h.usdPrice)}`:"N/A",b=h.pricePercentChange?.["24h"],w=typeof b=="number"&&Number.isFinite(b)?` (${b>0?"+":b<0?"-":""}${this.formatPercent(Math.abs(b))}%)`:"";return`${f+1}. ${m} (${g}) \u2014 ${y}${w}`}).join(`
|
|
194
|
+
Do NOT mention tool names, UI, or forms.`,howTo:!0,chain:h||void 0,addLiquidityLink:d,count:f.length,pools:f.map(m=>this.formatPool(m))}}let n=typeof e.poolAddress=="string"?e.poolAddress.trim():"",r=(Array.isArray(e.tokens)?e.tokens:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim().toUpperCase()),o=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 Q(typeof t?.query=="string"?t.query:void 0);let i=a?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(i))return{_instructions:"The requested chain is not supported by the Subgraph pool service. Tell the user, in their language, that add-liquidity is not available on that network and list the supported chains briefly. Do NOT mention tool names.",unsupportedChains:[v(i)],supportedChains:this.service.listSupportedChains().map(v)};let l=this.service.resolveChain(i);if(n){if(!/^0x[a-fA-F0-9]{40}$/.test(n))return{error:"Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address) to add liquidity to it."};let d=await this.service.getPoolByAddress({poolAddress:n,chain:l});return d?this.poolsResult([d],l,!0):{error:`No pool found at ${n} on ${v(l)}.`}}if(r.length>0){let d=await this.service.searchPools({tokens:r,chain:l,sortBy:"tvl",filters:{feeTier:o}});if(d.length===0)return{error:`No Uniswap V3 pool found for ${r.join("/")}${o!=null?` at ${o}bps`:""} on ${v(l)}. Ask the user to check the token symbols, or try a different pair.`};let p=r.length===2?await this.fetchCoinPoolPairs(l,r):[];return this.poolsResult(d.slice(0,8),l,!0,p)}let c=await this.service.searchPools({tokens:[],chain:l,sortBy:"tvl"}),u=this.linkAddLiquidity??null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity but has not named a pool yet. Briefly list these top pools (pair, fee tier %, TVL, APR \u2014 skip APR if null) as suggestions, render each `uniswapUrl` as a clickable markdown link, then ask the user which token pair (or pool) they want to add liquidity to. '+this.linkInstruction(u)+"Do NOT mention tool names, UI, or forms.",chain:l,needsSelection:!0,addLiquidityLink:u,count:c.length,pools:c.slice(0,6).map(d=>this.formatPool(d))}}async fetchCoinPoolPairs(e,t){try{return[...await this.service.getCoinPoolPairs({chain:e,tokens:t})].sort((r,o)=>(o.apr??-1/0)-(r.apr??-1/0)).slice(0,10)}catch{return[]}}linkInstruction(e){return e?`ALWAYS finish by inviting the user to add liquidity on the website, as ONE short sentence that shows the FULL link in plain view \u2014 display the entire URL verbatim (${e}) as the visible link text, do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${e}](${e}). For example: "You can add liquidity here: [${e}](${e})". Use the URL verbatim; never invent one, and never use a pool's uniswapUrl here. `:"No add-liquidity website is configured, so do not show or invent any link. "}poolsResult(e,t,n,r=[]){let o=n?this.linkAddLiquidity??null:null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity. Show the resolved pool(s): pair (e.g. USDC/WETH), fee tier (%), TVL, volume past day, APR (skip if null), and the pool address. For EACH pool, render the provided `uniswapUrl` as a clickable markdown link. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)", to help the user choose a range when adding liquidity. CRITICAL: that APR is for the SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the data, give a genuine, conversational recommendation \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4A1} Recommendation"); vary your wording naturally each time and only cover what is actually relevant to THIS pair and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: which pool/fee tier looks best and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; fee-tier fit: 0.05% for stable/correlated pairs, 0.30% for typical volatile pairs, 1% for exotic/low-liquidity ones); which price range makes sense (from coinPoolPairs if present) \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; anything worth avoiding (thin TVL/volume, ranges far from current price, chasing the top APR blindly); and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Keep it short and human \u2014 a sentence or two or a couple of light bullets, tailored to whether the pair is stable or volatile. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, do not paste a stock disclaimer). '+(o?`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. [${o}](${o}). For example: "If you'd like to add liquidity to one of these pools, you can do it here: [${o}](${o})." 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:o,count:e.length,pools:e.map(i=>this.formatPool(i)),coinPoolPairs:r}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:we(e)}}};function qe(s){if(typeof s=="number")return Number.isFinite(s)&&s>0?{kind:"token",value:s,raw:String(s)}:null;if(typeof s!="string")return null;let e=s.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 o=parseFloat(t[1]??t[2]);return Number.isFinite(o)&&o>0?{kind:"percent",percent:o,raw:e}:null}let n=e.match(/^\$\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*\$$|^(?:usd)\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*usd$/i);if(n){let o=parseFloat(n[1]??n[2]??n[3]??n[4]);return Number.isFinite(o)&&o>0?{kind:"usd",usd:o,raw:e}:null}let r=e.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(r){let o=parseFloat(r[1]);return Number.isFinite(o)&&o>0?{kind:"token",value:o,raw:e}:null}return null}function Qa(s,e){switch(s.kind){case"token":return{ok:!0,amount:s.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*s.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:s.usd/e.usdPrice}}}var ld={send:30000n,swap:1000000n},cd={"0x1":["https://ethereum-rpc.publicnode.com","https://eth.drpc.org","https://1rpc.io/eth"],"0xa":["https://optimism-rpc.publicnode.com","https://optimism.drpc.org"],"0x38":["https://bsc-rpc.publicnode.com","https://bsc.drpc.org"],"0x89":["https://polygon-bor-rpc.publicnode.com","https://polygon.drpc.org"],"0x2105":["https://base-rpc.publicnode.com","https://base.drpc.org"],"0xa4b1":["https://arbitrum-one-rpc.publicnode.com","https://arbitrum.drpc.org"],"0xa86a":["https://avalanche-c-chain-rpc.publicnode.com","https://avalanche.drpc.org"],"0xe708":["https://linea-rpc.publicnode.com","https://linea.drpc.org"],"0x64":["https://gnosis-rpc.publicnode.com","https://gnosis.drpc.org"],"0x3e7":["https://rpc.hyperliquid.xyz/evm"],"0x1388":["https://mantle-rpc.publicnode.com","https://rpc.mantle.xyz"],"0x8f":["https://rpc.monad.xyz"]};async function ud(s){let e=s.toLowerCase(),n=[Xe(s),...cd[e]??[]].filter(r=>!!r);for(let r of n)try{let o=await He(r,"eth_gasPrice",[]),a=BigInt(o);if(a>0n)return a}catch{}return 0n}async function Ln(s,e){let t=await ud(s);return t<=0n?0n:ld[e]*t}function Dn(s,e,t){if(e<=0n)return s;let n=se(t)?.native.decimals;if(n===void 0)return s;let r=Number(e)/10**n;return!Number.isFinite(r)||r<=0?s:Math.max(0,s-r)}var Pe=class extends A{kind="ui";category="wallet-action";buildUI(e){let t={action:this.actionType,chainId:e.chainId,chainName:v(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 D(e))}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=F(e.trim()),a=l=>o?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}parseDecimals(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isInteger(t)&&t>=0)return t}}async resolveTokenRef(e){let{contractArg:t,symbolArg:n,decimalsArg:r,chain:o,walletAddress:a}=e,i=this.parseDecimals(r),l=typeof n=="string"&&n.trim()?n.trim():void 0,c=this.normaliseAddress(t),u=typeof t=="string"&&t.trim()?t.trim():void 0,d=c??l??u;if(!d)return{token:void 0};let p=await this.resolveContractAddress(d,o,a);return p?{token:{address:p.address,symbol:l??p.symbol,name:p.name,decimals:i??p.decimals}}:c?{token:{address:c,symbol:l,decimals:i}}:{error:"token_not_found",key:d}}requireWallet(e){let t=e?.walletAddress;return t?{ok:!0,address:t}:{ok:!1,payload:{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before submitting the action. Do NOT render the form."}}}requireChain(e,t){return Z(e.chain,t)}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return F(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=parseFloat(t);return Number.isFinite(n)&&n>0?t:null}async resolveAmountInput(e){let{rawAmount:t,tokenAddress:n,chain:r,walletAddress:o,gasKind:a}=e,i=qe(t);if(!i)return null;let l=e.symbol??"the token",c=n.toLowerCase()==="native",u=!!a&&c&&!!r;if(i.kind==="token")return{amount:this.toPlainDecimal(i.value)};let d=await this.readTokenBalanceAndPrice(n,r,o),p=d?.balance;u&&d?.balance!==void 0&&(p=await this.computeNativeSpendable(r,a,d.balance));let h=Qa(i,{balance:p,usdPrice:d?.usdPrice});return h.ok?{amount:this.toPlainDecimal(h.amount)}:h.reason==="no_balance"?{error:"amount_balance_unavailable",_instructions:`Could not read the user's ${l} balance to work out ${i.raw} right now. Tell them, in their language, that the balance couldn't be fetched at the moment and ask them to enter an exact ${l} amount instead. Do NOT invent a balance or amount. Do NOT mention tool names, UI, or forms.`}:{error:"amount_price_unavailable",_instructions:`Could not get a USD price for ${l} to work out ${i.raw} right now. Tell them, in their language, that the price couldn't be fetched at the moment and ask them to enter an exact ${l} amount instead. Do NOT invent a price or amount. Do NOT mention tool names, UI, or forms.`}}async computeNativeSpendable(e,t,n){let r=await Ln(e,t);return Dn(n,r,e)}async resolveNativeSpendableFormatted(e,t,n){if(!(!e||!t))try{let r=await this.readTokenBalanceAndPrice("native",e,t);if(r?.balance===void 0)return;let o=await this.computeNativeSpendable(e,n,r.balance);return this.toPlainDecimal(o)}catch{return}}async readTokenBalanceAndPrice(e,t,n){if(!this.moralis||!n)return;let r=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),o=r.success?r.data?.result??[]:[],a=e.toLowerCase()==="native",i=e.toLowerCase(),l=o.find(u=>a?u.native_token===!0:(u.token_address??"").toLowerCase()===i);if(!l)return;let c=l.balance_formatted!=null?Number(l.balance_formatted):void 0;return{balance:Number.isFinite(c)?c:void 0,usdPrice:typeof l.usd_price=="number"&&l.usd_price>0?l.usd_price:void 0,balanceFormatted:l.balance_formatted,symbol:l.symbol}}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,o]=Math.abs(e).toString().split("e"),a=Number(o),[i,l=""]=r.split("."),c=i+l,u;if(a>=0){let d=i.length+a;u=d>=c.length?c.padEnd(d,"0"):`${c.slice(0,d)}.${c.slice(d)}`}else u=`0.${"0".repeat(-a-i.length)}${c}`;return u.includes(".")&&(u=u.replace(/\.?0+$/,"")),n?`-${u}`:u}formatSpendableUsd(e,t){if(e===void 0||t===void 0)return;let n=Number(e);if(!Number.isFinite(n)||!Number.isFinite(t)||t<=0)return;let r=n*t;if(!(!Number.isFinite(r)||r<=0))return this.toPlainDecimal(r)}async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(a.ui=o.ui),o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(a.actionButtons=o.actionButtons),a}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){let n=this.requireWallet(t);if(!n.ok)return n.payload;let r=Lt(e.chain,t);if(r){let g=this.actionType.replace(/_/g," ");return{error:"wrong_chain",_instructions:`The user asked to ${g} on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to ${g} on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can ${g} on ${r.connectedLabel} (their current network) instead. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}let o=this.requireChain(e,t);if(!o){let g=typeof t?.query=="string"?t.query:void 0;return Dt(this.actionType.replace(/_/g," "),g)}let a=await this.buildParameters(e,t);if(a&&typeof a=="object"&&"error"in a&&typeof a.error=="string"||a&&typeof a=="object"&&"actionButtons"in a&&Array.isArray(a.actionButtons)||a&&typeof a=="object"&&"ui"in a&&a.ui&&typeof a.ui=="object"&&typeof a.ui.component=="string")return a;let i=a,l=this.buildUI({parameters:i,chainId:o,walletAddress:n.address}),c=g=>{let y=i[g];return y!=null&&y!==""},u=this.userInputFields.filter(g=>!(Array.isArray(g.key)?g.key:[g.key]).some(c)).map(g=>g.label),d=this.userInputFields.map(g=>{let b=(Array.isArray(g.key)?g.key:[g.key]).find(c);return b?`${g.label}: ${i[b]}`:null}).filter(g=>g!=null),p=this.actionType.replace(/_/g," "),h='NEVER invent, guess, or insert a placeholder (e.g. "[recipient address]") for any detail the user has not actually provided \u2014 only state values listed as already provided. Do NOT mention tool names, UI, or forms.',f="The user completes this themselves and it is submitted right away \u2014 do NOT ask them to reply to confirm, do NOT say you will send it for them, and do NOT announce the result. This turn ends after your message.",m=u.length>0?`The ${p} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${u.join(", ")}. `+(d.length>0?`Already provided: ${d.join("; ")}. `:"")+`${f} ${h}`:`The ${p} has all required details. In the user's language, briefly tell the user to review the details and submit to complete the ${p}. `+(d.length>0?`Details provided: ${d.join("; ")}. `:"")+`${f} ${h}`;return{ui:l,action:this.actionType,chainId:o,parameters:i,_instructions:m}}};var On=class extends Pe{name="open-send-native-form";actionType="send_native";component="SendNativeForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}async run(e,t){if(e.chain==null||e.chain===""){let n=Hs(e.native_symbol);if(n)return super.run({...e,chain:n},t)}return super.run(e,t)}description=`Open the SEND NATIVE form for the chain's native coin (ETH/BNB/MATIC/AVAX/\u2026). Use for ANY native-send intent: "send eth", "send 0.1 ETH", "transfer 1 BNB to vitalik.eth", "g\u1EEDi ETH". Call EVEN IF the user did not name an amount or recipient \u2014 the form prompts for them. Do NOT use for ERC-20 tokens \u2014 use open-send-token-form instead.`;parameters=[{name:"chain",type:"string",description:'Hex chain id: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. Defaults to connected chain.',required:!1},{name:"native_symbol",type:"string",description:'The native coin the user named to send, VERBATIM (e.g. "ETH", "BNB", "MATIC", "AVAX"). ALWAYS set this when the user names the coin ("send bnb" \u2192 native_symbol="BNB"); leave blank only when they say just "send" with no coin. A coin that belongs to one specific chain (BNB\u2192BSC, MATIC/POL\u2192Polygon, AVAX\u2192Avalanche, XDAI\u2192Gnosis, HYPE\u2192HyperEVM, MNT\u2192Mantle, MON\u2192Monad) selects that chain, so the tool can detect when the wallet is connected elsewhere.',required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Amount of native coin to send. Accepted forms: a plain amount ("0.1"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become the literal "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself (and for the native coin always leaves enough to cover the network fee). Omit when unknown.',required:!1}];async buildParameters(e,t){let n={},r=this.requireChain(e,t)??void 0,o=t?.walletAddress??void 0,a=await this.readTokenBalanceAndPrice("native",r,o);if(!a||a.balance==null||a.balance<=0){let d=a?.symbol||"the native coin";return{error:"no_native_balance",_instructions:`The user wants to send ${d} but their wallet holds 0 ${d} on this chain. Tell them, in their language, that they do not have any ${d} to send and suggest they top up first. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}let i=a.symbol||(typeof e.native_symbol=="string"&&e.native_symbol.trim()?e.native_symbol.trim():void 0);if(i&&(n.native_symbol=i),e.to_address!=null){let d=this.normaliseAddress(e.to_address);d?n.to_address=d:typeof e.to_address=="string"&&e.to_address.trim()&&(n.to_address=e.to_address.trim())}let l=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:"native",symbol:"the native coin",chain:r,walletAddress:o,gasKind:"send"});if(l&&"error"in l)return l;l&&(n.amount=l.amount);let c=await this.resolveNativeSpendableFormatted(r,o,"send");c!==void 0&&(n.spendable=c);let u=this.formatSpendableUsd(c,a.usdPrice);return u!==void 0&&(n.spendableUsd=u),n}};var Mn=class extends Pe{name="open-send-token-form";actionType="send_token";component="SendTokenForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}description=`Open the SEND TOKEN (ERC-20) form. Use for ANY ERC-20 send/transfer intent: "send token", "send USDC", "transfer 50 DAI to 0x\u2026", "g\u1EEDi 10 USDT". Call this tool EVEN IF the user did not name a token, amount, or recipient \u2014 the tool handles missing token via a picker, the form prompts for the rest. Do NOT use for the chain's native coin (ETH/BNB/MATIC/AVAX) \u2014 use open-send-native-form instead.`;parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol \u2014 the tool will look up the address.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). ALWAYS set this whenever the user names a token to send ("send usdc" \u2192 token_symbol="USDC"); only leave it blank when the user names NO token at all ("send token"), so the tool can show a wallet picker. Used to auto-resolve the contract address and to display the symbol in the form. (Pass either this or contract_address.)',required:!1},{name:"decimals",type:"number",description:"Token decimals (e.g. 6 for USDC, 18 for most ERC-20s). Optional.",required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown.",required:!1},{name:"amount",type:"string",description:'Amount of the token to send. Accepted forms: a plain amount ("100"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself. Omit when unknown.',required:!1},{name:"send_prompt_template",type:"string",description:`A short imperative "send" command IN THE USER'S LANGUAGE, used as the label/command when the user has not yet picked which token to send (token-picker buttons). Write it in the SAME language the user is using right now. Use these exact placeholders (do not translate the braces): "{symbol}" for the token, "{amount}" for the amount, "{to}" for the recipient address, "{chain}" for the chain name. Put the localized verb, the "to" preposition, and the "on <chain>" preposition directly in the text. English example: "send {amount} {symbol} to {to} on {chain}". Vietnamese example: "g\u1EEDi {amount} {symbol} \u0111\u1EBFn {to} tr\xEAn {chain}". Japanese example: "{chain} \u3067 {to} \u306B {amount} {symbol} \u3092\u9001\u308B". Always include {symbol}. Include {amount}/{to}/{chain} too \u2014 the tool removes any whose value is unknown.`,required:!0}];async buildParameters(e,t){let n=this.normaliseAddress(e.contract_address)!=null,r=typeof e.token_symbol=="string"&&e.token_symbol.trim().length>0;if(!n&&!r&&this.moralis){let d=this.requireChain(e,t)??void 0,p=t?.walletAddress;if(p){let h=await this.moralis.getWalletTokenBalances({address:p,chain:d,excludeSpam:!1,excludeUnverifiedContracts:!1}),m=(h.success?h.data?.result??[]:[]).filter(T=>T.symbol&&(T.native_token||T.token_address)).sort((T,P)=>(P.usd_value??0)-(T.usd_value??0)).slice(0,8);if(m.length===0)return{error:"no_token_holdings",_instructions:"The wallet does not hold any sendable tokens on this chain. Tell the user they have nothing to send and suggest they top up first. Do NOT open the form."};let g=e.to_address!=null?this.normaliseAddress(e.to_address):null,y=this.normaliseAmount(e.amount),b=typeof e.send_prompt_template=="string"?e.send_prompt_template:"",w=d?v(d):null;return{actionButtons:m.map(T=>{let P=T.symbol,S=T.balance_formatted?this.cleanAmountString(T.balance_formatted):"",_=T.name?T.name:"",N=T.usd_value?`($${T.usd_value.toFixed(2)})`:"";return{label:`${_}:${S} ${P} ${N}`.trim(),prompt:this.buildSendPrompt(b,P,y,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 o=this.requireChain(e,t)??void 0,a=t?.walletAddress??void 0,i=await this.findOwnedTokenForSend(e,o,a);if(i&&"error"in i)return i;let l=i?.token,c={};l?.address&&(c.contract_address=l.address),l?.symbol&&(c.token_symbol=l.symbol),l?.decimals!==void 0&&(c.decimals=String(l.decimals)),i?.spendable!==void 0&&(c.spendable=i.spendable);let u=this.formatSpendableUsd(i?.spendable,i?.usdPrice);if(u!==void 0&&(c.spendableUsd=u),e.to_address!=null){let d=this.normaliseAddress(e.to_address);d?c.to_address=d:typeof e.to_address=="string"&&e.to_address.trim()&&(c.to_address=e.to_address.trim())}if(l?.address){let d=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:l.address,symbol:l.symbol,chain:o,walletAddress:a});if(d&&"error"in d)return d;d&&(c.amount=d.amount)}else{let d=this.normaliseAmount(e.amount);d&&(c.amount=d)}return c}async findOwnedTokenForSend(e,t,n){let r=this.normaliseAddress(e.contract_address),o=typeof e.token_symbol=="string"&&e.token_symbol.trim()?e.token_symbol.trim():void 0,a=r??o;if(!this.moralis||!n||!a){let h=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:t,walletAddress:n});return"error"in h?{error:"token_not_found",symbol:h.key,_instructions:`Could not resolve token "${h.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`}:{token:h.token}}let i=a.toLowerCase(),l=r!=null,c=await this.moralis.getWalletTokenBalances({address:n,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),d=(c.success?c.data?.result??[]:[]).find(h=>l?(h.token_address??"").toLowerCase()===i:(h.symbol??"").toLowerCase()===i);if(d&&d.balance&&!/^0*$/.test(d.balance.trim())){let h=this.parseDecimals(e.decimals);return{token:{address:d.token_address,symbol:d.symbol??o,name:d.name,decimals:h??(typeof d.decimals=="number"?d.decimals:void 0)},spendable:d.balance_formatted?this.cleanAmountString(d.balance_formatted):void 0,usdPrice:typeof d.usd_price=="number"&&d.usd_price>0?d.usd_price:void 0}}let p=d?.symbol??o??a;return{error:"no_balance",symbol:p,_instructions:`The user does not hold any ${p} in their wallet on this chain, so there is nothing to send. Tell them (in their language) that they don't have any ${p} to send, and suggest they top up or pick another token. Do NOT open a form. Do NOT mention tool names, UI, or forms.`}}buildSendPrompt(e,t,n,r,o){let i=(e&&e.includes("{symbol}")?e:"send {amount} {symbol} to {to} on {chain}").replace(/\{symbol\}/g,t).replace(/\{amount\}/g,n??"");return i=this.fillOrDropPhrase(i,"{to}",r),i=this.fillOrDropPhrase(i,"{chain}",o),i.replace(/\s+/g," ").trim()}fillOrDropPhrase(e,t,n){if(n)return e.split(t).join(n);let r=t.replace(/[{}]/g,"\\$&");return e.replace(new RegExp(`\\s*\\S+\\s*${r}`,"g"),"").replace(new RegExp(`${r}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(r,"g"),"")}};var Fn=class extends Pe{name="open-approve-token-form";actionType="approve_token";component="ApproveTokenForm";userInputFields=[{key:"spender_address",label:"the spender address to approve"}];constructor(e){super(e)}description='Open the APPROVE TOKEN form so the user can grant a spender allowance on an ERC-20 token. Use when the user says "approve USDC for Uniswap", "c\u1EA5p quy\u1EC1n 100 USDT cho 0x\u2026", "revoke approval". Pass `contract_address` when you have it; otherwise pass `token_symbol` (e.g. "USDC") and the tool auto-resolves the contract. Always pass `spender_address` (the contract being approved). Pass `amount` for a specific allowance; omit for unlimited (max uint256). For approving 0 to revoke, pass amount="0".';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). Required when contract_address is not given. Used to auto-resolve the contract.',required:!1},{name:"decimals",type:"number",description:"Token decimals.",required:!1},{name:"spender_address",type:"string",description:"EVM address of the spender contract being approved (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Human-readable allowance amount. Omit for UNLIMITED (max uint256). Pass "0" to revoke.',required:!1}];async buildParameters(e,t){let n=this.requireChain(e,t)??void 0,r=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:n,walletAddress:t?.walletAddress??void 0});if("error"in r)return{error:"token_not_found",symbol:r.key,_instructions:`Could not resolve token "${r.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`};let o=r.token,a=this.normaliseAddress(e.spender_address),i={};if(o?.address&&(i.contract_address=o.address),a&&(i.spender_address=a),o?.symbol&&(i.token_symbol=o.symbol),o?.decimals!==void 0&&(i.decimals=String(o.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}};var qn=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 D(e),this.pantograph=new ue({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[BuyTokenTool] ${e}`):console.log(`[BuyTokenTool] ${e}`,JSON.stringify(t)))}description='Open the BUY TOKEN flow for ANY buy/purchase intent. Handles both cases: (a) the user NAMED a token \u2014 "buy PEPE", "mua DOGE", "buy 100 USDC with ETH": pass `token_symbol` (the destination); if you also know the pay token, fill `pay_with_symbol` (or `pay_with_address`), else leave pay_with_* blank and the tool returns a wallet picker. (b) the user did NOT name a token \u2014 "buy a trending token", "mua token trending", "buy something pumping", "buy hot tokens", "mua token t\u0103ng m\u1EA1nh": leave `token_symbol` blank and the tool returns buttons of the chain\'s current trending tokens so the user picks one. Amount: `buy_amount` = destination to RECEIVE; `pay_with_amount` = payment to SPEND. Never both.';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"token_symbol",type:"string",description:'Symbol of the token the user wants to BUY (e.g. "PEPE"). Leave EMPTY when the user did not name a token (e.g. "buy a trending token") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"contract_address",type:"string",description:`Destination token address (0x\u2026), or "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from token_symbol.`,required:!1},{name:"buy_amount",type:"string",description:`Quantity of the DESTINATION token (the one being bought) the user wants to RECEIVE. Set this when the amount sits next to the token being bought: "buy 5 PEPE", "mua 5 PEPE", "buy 0.02 PCM with USDC" \u2192 buy_amount = the number next to PEPE/PCM. May also be a USD value when the user sizes the buy in dollars ("buy $5 of PEPE" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$" to a token quantity). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with pay_with_amount \u2014 set at most ONE of the two.`,required:!1},{name:"pay_with_symbol",type:"string",description:'Symbol of the payment token (e.g. "USDC", "ETH"). Set ONLY when the user actually named a token to pay with. Leave EMPTY when they did not \u2014 do NOT default to the native coin / ETH; the tool then returns a picker of the tokens the wallet holds.',required:!1},{name:"pay_with_address",type:"string",description:`Address of the payment token (0x\u2026), OR "native" for the chain's native coin. Set ONLY when the user named the payment token. Leave EMPTY when they did not \u2014 do NOT invent an address or default to native.`,required:!1},{name:"pay_with_amount",type:"string",description:'Quantity of the PAYMENT token (the one being spent) the user wants to SPEND. Set this when the amount sits next to the payment token: "buy PEPE with 10 USDC", "mua PEPE b\u1EB1ng 10 USDC", "spend 0.5 ETH on DOGE" \u2192 pay_with_amount = the number next to USDC/ETH. May also be a PERCENT of the pay-token balance ("buy USDC with 50% USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("buy USDC with 5$ USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set pay_with_symbol to the payment token ("ETH" in "buy USDC with max ETH"). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with buy_amount \u2014 set at most ONE of the two.',required:!1},{name:"limit",type:"number",description:"Only used when no token is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the trending-token picker (when the user named no token). Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}.`,required:!0},{name:"buy_with_prompt_template",type:"string",description:`A short "buy X with Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the pay-token picker and the percentage-spend buttons. Use these exact placeholders (do not translate the braces): "{token}" = token being bought, "{pay}" = payment token, "{buy_amount}" = quantity of the BOUGHT token (place it next to {token}), "{pay_amount}" = quantity of the PAYMENT token (place it next to {pay}). Put the localized verb and the "with" preposition directly in the text. English example: "buy {buy_amount} {token} with {pay_amount} {pay}". Vietnamese example: "mua {buy_amount} {token} b\u1EB1ng {pay_amount} {pay}". Japanese example: "{pay_amount} {pay} \u3067 {buy_amount} {token} \u8CFC\u5165". Always include {token} and {pay}. Include both {buy_amount} and {pay_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount).`,required:!0}];async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(a.ui=o.ui),o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(a.actionButtons=o.actionButtons),a}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before buying. Do NOT proceed."};let r=Lt(e.chain,t);if(r)return{error:"wrong_chain",_instructions:`The user asked to buy on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to buy on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can buy on ${r.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return Dt("buy",a)}return this.buildResult(e,t)}async buildResult(e,t){this.correctAmountSide(e,t),this.dropUnmentionedPayToken(e,t),this.dropInventedAmounts(e,t);let n=typeof e.token_symbol=="string"?e.token_symbol.trim():"",r=typeof e.contract_address=="string"?e.contract_address.trim():"",o=this.requireChain(e,t)??void 0,a=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:o,walletAddress:a,hasMoralis:!!this.moralis}),!n&&!r)return this.dbg("\u2192 Branch 0: trending picker (no token named)"),await this.buildTrendingPicker(e,t);let i=await this.resolveSide(e.contract_address,n,o,a,"dest"),l=i.address,c=i.symbol??n,u=i.decimals,d=await this.resolveSide(e.pay_with_address,e.pay_with_symbol,o,a,"pay"),p=d.address,h=d.symbol,f=d.decimals,m=await this.resolveBuyAmountSpec(e.buy_amount,l,o,c),g=p?await this.resolvePayAmountSpec(e.pay_with_amount,p,o,a,h,f??(p==="native"?18:void 0)):this.normaliseAmount(e.pay_with_amount),y=qe(e.pay_with_amount),b=!!y&&y.kind!=="token",w=null;if(this.dbg("resolved sides",{dest:{destContract:l,destSymbol:c,destDecimals:u},pay:{payAddr:p,paySymbol:h,payDecimals:f},buyAmount:m,payAmount:g}),!l)return this.dbg("\u2192 dest token not resolved"),{error:"dest_token_not_found",_instructions:`Could not find the token "${c||r}" to buy on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(!p&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: pay picker (pay token missing)"),await this.buildPayWithPicker({args:e,userContext:t,destSymbol:c,destContract:l,buyAmount:m,payAmount:g});if(!p)return{error:"pay_token_missing",_instructions:`Ask the user, in their language, which token they want to spend to buy ${c}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(m&&!g){this.dbg("Branch 1.3: deriving pay amount from buy amount",{buyAmount:m,destSymbol:c,paySymbol:h});let k=await this.derivePayAmountFromBuy({chain:o,buyAmount:m,destContract:l,destSymbol:c,payAddr:p,paySymbol:h});if(!k)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs pay amount"),{error:"needs_pay_amount",_instructions:`Could not work out how much ${h??"of the payment token"} equals ${m} ${c} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${h??"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.`};g=k,w=m,b=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:g,derivedFromBuy:w})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking pay balance",{payAddr:p,paySymbol:h,payAmount:g});let k=await this.checkPayBalance({args:e,userContext:t,chain:o,destSymbol:c,destContract:l,payAddr:p,paySymbol:h,payAmount:g,buyAmount:m,derivedFromBuy:w,amountSizedToBalance:b});if(k)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:k.error,hasButtons:Array.isArray(k.actionButtons)}),k;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!m&&!g&&this.moralis&&t?.walletAddress){this.dbg("Branch 1.5: building amount picker");let k=await this.buildAmountPicker({userContext:t,chain:o,destSymbol:c,payAddr:p,paySymbol:h,buyWithTemplate:typeof e.buy_with_prompt_template=="string"?e.buy_with_prompt_template:""});if(k)return this.dbg("\u2192 Branch 1.5: amount picker returned"),k;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(g&&(f!==void 0||p==="native")){this.dbg("Branch 1.75: building confirm tx");let k=await this.buildConfirmTx({userContext:t,chain:o,destContract:l,destSymbol:c,destDecimals:u,payAddr:p,paySymbol:h,payDecimals:f,payAmount:g});return k&&"ui"in k?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),k):k&&"quoteError"in k?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:k.quoteError}),{error:"quote_failed",quoteError:k.quoteError,_instructions:`Could not quote buying ${c} with ${h??"the selected token"}. The swap provider reported: "${k.quoteError}". Tell the user, in their language, exactly that reason (translate the wording, keep any numbers/limits verbatim) and suggest they adjust the amount or try again shortly. Do NOT invent numbers or a different reason. Do NOT mention tool names, UI, or forms.`}):(this.dbg("Branch 1.75: confirm tx unavailable (null)"),{error:"quote_failed",_instructions:`Could not get a quote to buy ${c} with ${h??"the selected token"} right now. Tell the user, in their language, that the swap could not be quoted at the moment and ask them to try again shortly or with a different amount. Do NOT invent numbers. Do NOT mention tool names, UI, or forms.`})}return this.dbg("\u2192 needs pay amount"),{error:"needs_pay_amount",_instructions:`Ask the user, in their language, how much ${h??"of the payment token"} they want to spend to buy ${c}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return F(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=t.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(!n)return null;let r=parseFloat(n[1]);return Number.isFinite(r)&&r>0?n[1]:null}correctAmountSide(e,t){let n=typeof t?.query=="string"?t.query:"",r=typeof e.token_symbol=="string"?e.token_symbol.trim():"",o=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"";if(!n||!r||!o)return;let a=typeof e.buy_amount=="string"?e.buy_amount.trim():"",i=typeof e.pay_with_amount=="string"?e.pay_with_amount.trim():"",l=a.length>0,c=i.length>0;if(l===c)return;let u=l?a:i,d=u.match(/[0-9]*\.?[0-9]+/)?.[0];if(!d)return;let p=this.nearestSymbolSide(n,d,r,o);p&&(p==="pay"&&l?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:u,buySym:r,paySym:o}),e.pay_with_amount=u,e.buy_amount=""):p==="buy"&&c&&(this.dbg("correctAmountSide: pay_with_amount \u2192 buy_amount",{amount:u,buySym:r,paySym:o}),e.buy_amount=u,e.pay_with_amount=""))}dropUnmentionedPayToken(e,t){let n=typeof t?.query=="string"?t.query:"";if(!n)return;let r=typeof e.token_symbol=="string"?e.token_symbol.trim():"";if(!r)return;let o=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"",a=typeof e.pay_with_address=="string"?e.pay_with_address.trim():"";if(!o&&!a)return;let i=n.toLowerCase(),l=o.toLowerCase(),c=a.toLowerCase(),u=l==="native"||c==="native",d=[];if(o&&l!=="native"&&d.push(l),c&&c!=="native"&&d.push(c),u){d.push("native");let h=this.requireChain(e,t)??void 0,f=h?se(h)?.native.symbol:void 0;f&&d.push(f.toLowerCase())}d.some(h=>F(h)?i.includes(h):this.indexOfToken(i,h)>=0)||(this.dbg("dropUnmentionedPayToken: clearing invented pay token",{paySym:o,payAddr:a,buySym:r}),e.pay_with_symbol="",e.pay_with_address="")}dropInventedAmounts(e,t){let n=typeof t?.query=="string"?t.query:"";if(!n)return;let r=(n.match(/[0-9]*\.?[0-9]+/g)??[]).map(parseFloat).filter(Number.isFinite),o=a=>{let i=typeof e[a]=="string"?e[a].trim():"";if(!i)return;let l=i.match(/[0-9]*\.?[0-9]+/)?.[0];if(l===void 0)return;let c=parseFloat(l);Number.isFinite(c)&&(r.some(u=>u===c)||(this.dbg(`dropInventedAmounts: clearing invented ${a}`,{val:i}),e[a]=""))};o("buy_amount"),o("pay_with_amount")}nearestSymbolSide(e,t,n,r){let o=e.toLowerCase(),a=o.indexOf(t.toLowerCase()),i=this.indexOfToken(o,n.toLowerCase()),l=this.indexOfToken(o,r.toLowerCase());if(a<0||i<0||l<0)return null;let c=(p,h)=>Math.max(0,p-(a+t.length),a-(p+h)),u=c(i,n.length),d=c(l,r.length);return d===u?null:d<u?"pay":"buy"}indexOfToken(e,t){if(!t)return-1;let n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=e.match(new RegExp(`(?:^|[^a-z0-9])(${n})(?:[^a-z0-9]|$)`));return r&&r.index!==void 0?r.index+r[0].indexOf(r[1]):-1}requireChain(e,t){let n=typeof e.chain=="string"&&e.chain.trim()?e.chain.trim():null;return n||(typeof t?.chain=="string"&&t.chain.trim()?t.chain.trim():null)}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=F(e.trim()),a=l=>o?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}async resolveSide(e,t,n,r,o="side"){let a=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(a.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,u=h=>h.toLowerCase()===$?"native":h,d=l??c??(a||void 0);if(!d)return this.dbg(`resolveSide:${o}`,{refStr:a,symbolStr:i,chain:n,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(d,n,r);return this.dbg(`resolveSide:${o}`,{refStr:a,symbolStr:i,chain:n,key:d,lookup:p}),p?{address:u(p.address),symbol:c??p.symbol,decimals:p.decimals}:l?{address:u(l),symbol:c}:{address:null,symbol:c}}async buildConfirmTx(e){let{userContext:t,chain:n,destContract:r,destSymbol:o,destDecimals:a,payAddr:i,paySymbol:l,payDecimals:c,payAmount:u}=e,d=t?.walletAddress;if(!d||!n||!r)return null;let p=se(n),h=Number.parseInt(n,16);if(!p||!Number.isFinite(h))return null;let f=i==="native",m=f?p.native.decimals??18:c;if(m===void 0)return null;let g=this.toRawAmount(u,m);if(!g)return null;let y=f?$:i,b=r==="native"?$:r,w;try{w=await(await Fe.getServiceByProvider("debridge")).getQuote({srcChainId:h,srcTokenAddress:y,srcTokenAmount:g,dstChainId:h,dstTokenAddress:b,recipientAddress:d,senderAddress:d,slippage:"auto",isCrossChain:!1})}catch(E){return{quoteError:E instanceof Error?E.message:String(E)}}if(!w.success)return this.dbg("buildConfirmTx: quote failed",{error:w.error,errorMessage:w.errorMessage}),{quoteError:this.extractQuoteError(w)};if(!w.tx)return{quoteError:"No route available for this swap."};let k=w.tx;if(!k.to||typeof k.data!="string")return null;let T={chainId:n,to:k.to,data:k.data,value:k.value??"0",from:d},P=this.extractOutRaw(w),S=P&&a!==void 0?this.trimAmount(Number(P)/10**a):void 0,_;f||(_=await this.buildApproveTx({chain:n,walletAddress:d,payAddr:i,payDec:m,rawAmount:g,quote:w}));let C={component:"BuyTokenConfirmTx",props:{chain:{hexId:n,name:p.name},payToken:{address:f?"native":i,symbol:l,decimals:m,amount:u,rawAmount:g},buyToken:{address:r,symbol:o,decimals:a,amount:S,rawAmount:P},estimatedOut:S,estimatedOutRaw:P,provider:w.provider,swapTx:T,approveTx:_}},q=S?` They will receive about ${S} ${o}.`:"";return{ui:C,_instructions:`The purchase of ${o} with ${u} ${l??"the selected token"} is ready for the user to confirm.${q} Briefly tell the user, in their language, the amount they are spending and the estimated amount they will receive, and ask them to review and confirm to complete the purchase. The estimate is approximate \u2014 say "about"/"estimated", never a guaranteed amount. Speak only of the user's action (buying) \u2014 NEVER say you "opened" a panel/form/window or describe any UI being shown. NEVER invent numbers not provided here. Do NOT mention tool names, UI, forms, or internal steps like approval.`}}async derivePayAmountFromBuy(e){let{chain:t,buyAmount:n,destContract:r,payAddr:o}=e,[a,i]=await Promise.all([this.getUsdPrice(r,t),this.getUsdPrice(o,t)]);if(this.dbg("derivePayAmountFromBuy: prices",{destPrice:a,payPrice:i}),!a||!i)return null;let l=Number(n);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,u=l*a/i;return!Number.isFinite(u)||u<=0?null:this.trimAmount(u*c)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?$:e,r=await this.moralis.getTokenMetadata({address:n,chain:t}),o=r.success?r.data?.usd_price:void 0;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}async resolvePayAmountSpec(e,t,n,r,o,a){let i=qe(e);if(!i)return null;let l=u=>a===void 0?u:Qe(u,a);if(i.kind==="token")return l(_t(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!r)return null;let u=await this.readPayBalance(r,t,n);if(this.dbg("resolvePayAmountSpec: percent",{percent:i.percent,paySymbol:o,bal:u?.balanceNum}),!u||!Number.isFinite(u.balanceNum)||u.balanceNum<=0)return null;let d=u.decimals??a??18;return i.percent>=100?this.cleanAmountString(u.balanceFormatted):Et(u.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,d)}let c=await this.getUsdPrice(t,n);return this.dbg("resolvePayAmountSpec: usd",{usd:i.usd,paySymbol:o,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveBuyAmountSpec(e,t,n,r){let o=qe(e);if(!o)return null;if(o.kind==="token")return _t(e)??this.toPlainDecimal(o.value);if(o.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,n);return this.dbg("resolveBuyAmountSpec: usd",{usd:o.usd,destSymbol:r,price:a}),a?this.trimAmount(o.usd/a):null}async buildApproveTx(e){let{chain:t,walletAddress:n,payAddr:r,payDec:o,rawAmount:a,quote:i}=e;try{let c=await(await Fe.getServiceByProvider("debridge")).checkApproval({chain:t,userAddress:n,tokenAddress:r,amount:a,tokenDecimals:o,quoteData:i});if(!c.isNeeded)return;let u=c.approvalData??{};if(u.to&&typeof u.data=="string")return{chainId:t,to:u.to,data:u.data,value:u.value??"0",from:n};let d=c.contractAddress;if(!d)return;let p=Pt({abi:jo,functionName:"approve",args:[d,BigInt(a)]});return{chainId:t,to:r,data:p,value:"0",from:n}}catch{return}}toRawAmount(e,t){let n=e.trim();if(!/^\d*\.?\d+$/.test(n))return null;let[r,o=""]=n.split("."),a=o.slice(0,t).padEnd(t,"0");try{let i=BigInt(r||"0")*10n**BigInt(t)+BigInt(a||"0");return i<=0n?null:i.toString()}catch{return null}}extractQuoteError(e){if(e.errorMessage&&e.errorMessage.trim())return e.errorMessage.trim();let t=r=>{if(typeof r=="string"&&r.trim())return r.trim();if(r&&typeof r=="object"){let o=r;for(let a of[o.message,o.errorMessage,o.error])if(typeof a=="string"&&a.trim())return a.trim()}},n=e.raw??{};return t(e.error)??t(n.errorMessage)??t(n.error)??"The swap could not be quoted right now."}extractOutRaw(e){let t=e.raw??{},n=t.tokenOut?.amount??t.tokenOut?.minAmount??t.details?.currencyOut?.amount??t.details?.currencyOut?.minimumAmount??t.estimation?.dstChainTokenOut?.recommendedAmount??t.estimation?.dstChainTokenOut?.amount;return n&&/^\d+$/.test(n)?n:void 0}async buildPayWithPicker(e){let{args:t,userContext:n,destSymbol:r,destContract:o}=e,a=this.requireChain(t,n)??void 0,i=this.moralis,l=n.walletAddress,c=await i.getWalletTokenBalances({address:l,chain:a,excludeSpam:!1,excludeUnverifiedContracts:!1}),u=c.success?c.data?.result??[]:[],d=o?.toLowerCase(),p=r.trim().toLowerCase(),h=u.filter(b=>!b.symbol||p&&b.symbol.toLowerCase()===p?!1:b.native_token?d!=="native":!(!b.token_address||d&&b.token_address.toLowerCase()===d)).sort((b,w)=>(w.usd_value??0)-(b.usd_value??0)).slice(0,8);if(h.length===0)return{error:"no_pay_token_holdings",_instructions:"The wallet has no tokens that can pay for this purchase on this chain. Tell the user to top up first. Do NOT mention tool names, UI, or forms."};let f=e.buyAmount??this.normaliseAmount(t.buy_amount),m=e.payAmount??this.normaliseAmount(t.pay_with_amount),g=typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"";return{actionButtons:h.map(b=>{let w=b.symbol,k=b.name?.trim()||w,T=b.balance_formatted?`${this.cleanAmountString(b.balance_formatted)} `:"",P=typeof b.usd_value=="number"&&b.usd_value>0?` ($${b.usd_value.toFixed(2)})`:"",S=`${k}: ${T}${w}${P}`,_=f?this.buildBuyWithPrompt(g,r,w,f,null):this.buildBuyWithPrompt(g,r,w,null,m);return{label:S,prompt:_}}),_instructions:`Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n mua ${r}.' / 'You want to buy ${r}.'), then ask them to choose which token they want to spend to buy ${r} from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua.' / 'Please choose the token to spend.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms.`}}async checkPayBalance(e){let{args:t,userContext:n,chain:r,destSymbol:o,destContract:a,payAddr:i,payAmount:l,buyAmount:c,derivedFromBuy:u}=e,d=n.walletAddress,p=await this.readPayBalance(d,i,r),h=e.paySymbol??p?.symbol??"the selected token";if(!p){this.dbg("checkPayBalance: NOT held \u2192 pay picker fallback",{paySymbol:h});let b=await this.buildPayWithPicker({args:t,userContext:n,destSymbol:o,destContract:a,buyAmount:c,payAmount:l});return"actionButtons"in b?{error:"no_pay_balance",actionButtons:b.actionButtons,_instructions:`The user wanted to spend ${h} to buy ${o}, but their wallet holds no ${h} on this chain. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${h} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${h} tr\xEAn m\u1EA1ng n\xE0y.'), then ask them to choose one of the tokens they already hold to pay with (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua ${o} 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.`}:b}if(!l||e.amountSizedToBalance)return null;let f=p.decimals!==void 0?Qe(l,p.decimals):l;if(ft(f,p.balanceFormatted)<=0)return null;let m=this.cleanAmountString(p.balanceFormatted),g=this.percentSpendButtons({balanceFormatted:p.balanceFormatted,balanceNum:p.balanceNum,decimals:p.decimals,paySymbol:h,destSymbol:o,buyWithTemplate:typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:""}),y=u?`Buying ${u} ${o} needs about ${l} ${h}, but they only have ${m} ${h} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them that buying ${u} ${o} would cost about ${l} ${h}, which is more than their balance of ${m} ${h}, then ask them to choose a smaller amount or spend less \u2014 `:`The user wants to spend ${l} ${h} to buy ${o}, but they only have ${m} ${h} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${l} ${h} exceeds their balance of ${m} ${h}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_pay_balance",actionButtons:g,_instructions:y+'invite them to choose one of the options below (sized to their balance) or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT invent numbers, and do NOT mention tool names, UI, buttons, or forms.'}}async readPayBalance(e,t,n){if(!this.moralis)return null;let r=await this.moralis.getWalletTokenBalances({address:e,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),o=r.success?r.data?.result??[]:[];this.dbg("readPayBalance",{payAddr:t,chain:n,ok:r.success,count:o.length,held:o.map(c=>({sym:c.symbol,addr:c.token_address,bal:c.balance_formatted}))});let a=t.toLowerCase(),i=o.find(c=>a==="native"?c.native_token===!0:c.token_address?.toLowerCase()===a);if(!i?.balance_formatted)return this.dbg("readPayBalance: pay token NOT held \u2192 null",{payAddr:t}),null;let l=Number(i.balance_formatted);if(!Number.isFinite(l)||l<=0)return this.dbg("readPayBalance: zero/invalid balance \u2192 null",{payAddr:t,balance:i.balance_formatted}),null;if(a==="native"&&n){let c=await Ln(n,"swap"),u=Dn(l,c,n);if(this.dbg("readPayBalance: native spendable",{balanceNum:l,spendable:u}),u<=0)return this.dbg("readPayBalance: native spendable \u2264 0 \u2192 null",{balanceNum:l}),null;let d=this.trimAmount(u),p=typeof i.decimals=="number"?i.decimals:18;return{balanceFormatted:d,balanceNum:u,symbol:i.symbol,decimals:p}}return this.dbg("readPayBalance: held",{payAddr:t,balance:i.balance_formatted,symbol:i.symbol}),{balanceFormatted:i.balance_formatted,balanceNum:l,symbol:i.symbol,decimals:typeof i.decimals=="number"?i.decimals:void 0}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,paySymbol:r,destSymbol:o,buyWithTemplate:a}=e,i=n??18;return[25,50,75,100].map(c=>{let u=Et(this.cleanAmountString(t),BigInt(c),100n,i);return{label:`${c}%`,prompt:this.buildBuyWithPrompt(a,o,r,null,u)}})}async buildAmountPicker(e){let{userContext:t,chain:n,destSymbol:r,payAddr:o,buyWithTemplate:a}=e,i=t.walletAddress,l=await this.readPayBalance(i,o,n),c=e.paySymbol??l?.symbol;if(!l||!c)return null;let u=this.percentSpendButtons({balanceFormatted:l.balanceFormatted,balanceNum:l.balanceNum,decimals:l.decimals,paySymbol:c,destSymbol:r,buyWithTemplate:a}),d=this.cleanAmountString(l.balanceFormatted);return{actionButtons:u,_instructions:`The user's spendable balance is ${d} ${c}. Reply briefly in the user's language using the pattern 'state intent + balance \u2192 ask to choose': first state what the user wants and their spendable ${c} balance (e.g., 'B\u1EA1n mu\u1ED1n mua ${r} b\u1EB1ng ${c}, hi\u1EC7n c\xF3 ${d} ${c} c\xF3 th\u1EC3 d\xF9ng.' / 'You want to buy ${r} with ${c}; you have ${d} ${c} available.'), then ask how much they want to spend and invite them to choose one of the options below or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT mention tool names, UI, buttons, or forms.`}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,o]=Math.abs(e).toString().split("e"),a=Number(o),[i,l=""]=r.split("."),c=i+l,u;if(a>=0){let d=i.length+a;u=d>=c.length?c.padEnd(d,"0"):`${c.slice(0,d)}.${c.slice(d)}`}else u=`0.${"0".repeat(-a-i.length)}${c}`;return u.includes(".")&&(u=u.replace(/\.?0+$/,"")),n?`-${u}`:u}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildBuyPrompt(e,t){return(e&&e.includes("{token}")?e:"buy {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}buildBuyWithPrompt(e,t,n,r,o){return(e&&e.includes("{token}")&&e.includes("{pay}")?e:"buy {buy_amount} {token} with {pay_amount} {pay}").replace(/\{token\}/g,t).replace(/\{pay\}/g,n).replace(/\{buy_amount\}/g,r??"").replace(/\{pay_amount\}/g,o??"").replace(/\s+/g," ").trim()}async buildTrendingPicker(e,t){if(!this.pantograph)return{error:"trending_unavailable",_instructions:"Trending tokens are unavailable in this build (service not configured). Tell the user briefly and ask them to name a token to buy."};let n=this.requireChain(e,t)??void 0,r=typeof e.limit=="number"&&Number.isFinite(e.limit)?Math.floor(e.limit):6,o=Math.max(1,Math.min(10,r)),a=await this.pantograph.getTrendingTokens({chain:n,limit:o}),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(h=>h.symbol),c=typeof e.buy_prompt_template=="string"?e.buy_prompt_template:"",u=l.map(h=>{let f=h.symbol;return{label:f,prompt:this.buildBuyPrompt(c,f)}}),p=l.map((h,f)=>{let m=h.name?.trim()||h.symbol,g=h.symbol,y=typeof h.usdPrice=="number"&&h.usdPrice>0?`$${this.formatPrice(h.usdPrice)}`:"N/A",b=h.pricePercentChange?.["24h"],w=typeof b=="number"&&Number.isFinite(b)?` (${b>0?"+":b<0?"-":""}${this.formatPercent(Math.abs(b))}%)`:"";return`${f+1}. ${m} (${g}) \u2014 ${y}${w}`}).join(`
|
|
195
195
|
`)+`
|
|
196
196
|
|
|
197
197
|
Is there any token you want to buy?`;return{actionButtons:u,_instructions:`The trending tokens are on ${n?v(n):"the connected chain"}. Reply in the user's language using the pattern 'state intent \u2192 ask to choose'. Start with a one-line header that states the user's intent (e.g., 'B\u1EA1n mu\u1ED1n mua token \u2014 \u0111\xE2y l\xE0 c\xE1c token \u0111ang trending tr\xEAn <chain name>:' / '\u{1F4C8} You want to buy a token \u2014 here are the tokens currently trending upwards on <chain name>:'), then output EXACTLY the following list, preserving the line breaks, ordering, prices, and percentages verbatim (translate only the wording, never the numbers). The list already ends with a 'choose' prompt. Do NOT add or remove tokens, and do NOT mention tool names, UI, or forms:
|
|
198
198
|
|
|
199
|
-
${p}`}}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),n=t.match(/^0\.0*([1-9]\d{0,3})/);return n?t.slice(0,(n[0].length||0)+0):t}};var $n=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 D(e),this.pantograph=new ue({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[SwapTokenTool] ${e}`):console.log(`[SwapTokenTool] ${e}`,JSON.stringify(t)))}description='Open the SWAP TOKEN flow for ANY swap/exchange/convert intent where the user swaps a token they ALREADY HOLD into another token \u2014 "swap USDC to USDT", "swap USDC", "\u0111\u1ED5i USDC sang ETH", "convert DAI to USDC", "exchange 10 USDC for PEPE". The FROM token is the user\'s own holding (the source). Handles both cases: (a) the user named the destination \u2014 "swap USDC to USDT": pass `from_symbol` (the source, e.g. "USDC") and `to_symbol` (the destination, e.g. "USDT"). (b) the user named only the source \u2014 "swap USDC": pass `from_symbol` and leave `to_symbol` blank; the tool returns buttons of the chain\'s current trending tokens so the user picks what to receive. If the user named NO token at all \u2014 "swap" / "\u0111\u1ED5i token": leave both blank and the tool returns the wallet\'s holdings so the user picks what to swap FROM. Amount: `from_amount` = source to SPEND; `to_amount` = destination to RECEIVE. Never both.';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"from_symbol",type:"string",description:`Symbol of the SOURCE token the user wants to swap FROM \u2014 a token they already hold (e.g. "USDC"). Leave EMPTY only when the user named no token at all (e.g. "swap") \u2014 the tool then returns the wallet's holdings to pick the source from.`,required:!1},{name:"from_address",type:"string",description:`Source token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from from_symbol.`,required:!1},{name:"from_amount",type:"string",description:'Quantity of the SOURCE token (the one being swapped FROM / spent) the user wants to SPEND. Set this when the amount sits next to the source token: "swap 10 USDC to USDT", "\u0111\u1ED5i 10 USDC sang ETH" \u2192 from_amount = the number next to USDC. May also be a PERCENT of the source balance ("swap 50% USDC to USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("swap $5 USDC to USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set from_symbol to the source token ("ETH" in "swap max ETH to USDC"). Mutually exclusive with to_amount \u2014 set at most ONE of the two.',required:!1},{name:"to_symbol",type:"string",description:'Symbol of the DESTINATION token the user wants to RECEIVE (e.g. "USDT"). Leave EMPTY when the user did not name a destination (e.g. "swap USDC") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"to_address",type:"string",description:`Destination token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from to_symbol.`,required:!1},{name:"to_amount",type:"string",description:`Quantity of the DESTINATION token (the one being received) the user wants to RECEIVE. Set this when the amount sits next to the destination token: "swap USDC to 5 USDT" \u2192 to_amount = the number next to USDT. May also be a USD value ("swap USDC to $5 USDT" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$"). Mutually exclusive with from_amount \u2014 set at most ONE.`,required:!1},{name:"limit",type:"number",description:"Only used when no destination is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"swap_from_prompt_template",type:"string",description:`A short "swap {token}" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the source picker (when the user named no token). 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}.`,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 and the percentage-spend buttons. 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).`,required:!0}];async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(a.ui=o.ui),o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(a.actionButtons=o.actionButtons),a}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before swapping. Do NOT proceed."};let r=Dt(e.chain,t);if(r)return{error:"wrong_chain",_instructions:`The user asked to swap on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to swap on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can swap on ${r.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return Ot("swap",a)}return this.buildResult(e,t)}async buildResult(e,t){let n=typeof e.from_symbol=="string"?e.from_symbol.trim():"",r=typeof e.from_address=="string"?e.from_address.trim():"",o=typeof e.to_symbol=="string"?e.to_symbol.trim():"",a=this.requireChain(e,t)??void 0,i=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:a,walletAddress:i,hasMoralis:!!this.moralis}),!n&&!r)return this.dbg("\u2192 Branch 0: source picker (no source token named)"),await this.buildSourcePicker(e,t);let l=await this.resolveSide(e.from_address,n,a,i,"from"),c=l.address,u=l.symbol??n,d=l.decimals,p=await this.resolveSide(e.to_address,o,a,i,"to"),h=p.address,f=p.symbol??o,m=p.decimals,g=await this.resolveToAmountSpec(e.to_amount,h,a,f),y=c?await this.resolveFromAmountSpec(e.from_amount,c,a,i,u,d??(c==="native"?18:void 0)):this.normaliseAmount(e.from_amount),b=qe(e.from_amount),w=!!b&&b.kind!=="token",k=null;if(this.dbg("resolved sides",{from:{fromContract:c,fromSym:u,fromDecimals:d},to:{toContract:h,toSym:f,toDecimals:m},fromAmount:y,toAmount:g}),!c)return this.dbg("\u2192 source token not resolved"),{error:"from_token_not_found",_instructions:`Could not find the token "${u||r}" to swap from on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(!h&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: destination picker (dest token missing)"),await this.buildToTrendingPicker({args:e,userContext:t,fromSym:u,fromContract:c,fromAmount:y,toAmount:g});if(!h)return{error:"to_token_missing",_instructions:`Ask the user, in their language, which token they want to receive when swapping ${u}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(g&&!y){this.dbg("Branch 1.3: deriving from amount from to amount",{toAmount:g,fromSym:u,toSym:f});let T=await this.deriveFromAmountFromTo({chain:a,toAmount:g,toContract:h,toSym:f,fromContract:c,fromSym:u});if(!T)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs from amount"),{error:"needs_from_amount",_instructions:`Could not work out how much ${u??"of the source token"} equals ${g} ${f} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${u??"of the source token"} they want to swap instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};y=T,k=g,w=!1,this.dbg("\u2192 Branch 1.3: derived from amount",{fromAmount:y,derivedFromTo:k})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking source balance",{fromContract:c,fromSym:u,fromAmount:y});let T=await this.checkFromBalance({args:e,userContext:t,chain:a,fromContract:c,fromSym:u,fromAmount:y,toAmount:g,derivedFromTo:k,amountSizedToBalance:w});if(T)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:T.error,hasButtons:Array.isArray(T.actionButtons)}),T;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!y&&!g&&this.moralis&&t?.walletAddress){this.dbg("Branch 1.5: building amount picker");let T=await this.buildAmountPicker({userContext:t,chain:a,fromContract:c,fromSym:u,toSym:f,swapToTemplate:typeof e.swap_to_prompt_template=="string"?e.swap_to_prompt_template:""});if(T)return this.dbg("\u2192 Branch 1.5: amount picker returned"),T;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(y&&(d!==void 0||c==="native")){this.dbg("Branch 1.75: building confirm tx");let T=await this.buildConfirmTx({userContext:t,chain:a,toContract:h,toSym:f,toDecimals:m,fromContract:c,fromSym:u,fromDecimals:d,fromAmount:y});return T&&"ui"in T?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),T):T&&"quoteError"in T?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:T.quoteError}),{error:"quote_failed",quoteError:T.quoteError,_instructions:`Could not quote swapping ${u??"the source token"} to ${f}. The swap provider reported: "${T.quoteError}". Tell the user, in their language, exactly that reason (translate the wording, keep any numbers/limits verbatim) and suggest they adjust the amount or try again shortly. Do NOT invent numbers or a different reason. Do NOT mention tool names, UI, or forms.`}):(this.dbg("Branch 1.75: confirm tx unavailable (null)"),{error:"quote_failed",_instructions:`Could not get a quote to swap ${u??"the source token"} to ${f} right now. Tell the user, in their language, that the swap could not be quoted at the moment and ask them to try again shortly or with a different amount. Do NOT invent numbers. Do NOT mention tool names, UI, or forms.`})}return this.dbg("\u2192 needs from amount"),{error:"needs_from_amount",_instructions:`Ask the user, in their language, how much ${u??"of the source token"} they want to swap to ${f}. 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 F(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=parseFloat(t);return Number.isFinite(n)&&n>0?t:null}requireChain(e,t){let n=typeof e.chain=="string"&&e.chain.trim()?e.chain.trim():null;return n||(typeof t?.chain=="string"&&t.chain.trim()?t.chain.trim():null)}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=F(e.trim()),a=l=>o?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}async resolveSide(e,t,n,r,o="side"){let a=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(a.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,u=h=>h.toLowerCase()===$?"native":h,d=l??c??(a||void 0);if(!d)return this.dbg(`resolveSide:${o}`,{refStr:a,symbolStr:i,chain:n,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(d,n,r);return this.dbg(`resolveSide:${o}`,{refStr:a,symbolStr:i,chain:n,key:d,lookup:p}),p?{address:u(p.address),symbol:c??p.symbol,decimals:p.decimals}:l?{address:u(l),symbol:c}:{address:null,symbol:c}}async buildConfirmTx(e){let{userContext:t,chain:n,toContract:r,toSym:o,toDecimals:a,fromContract:i,fromSym:l,fromDecimals:c,fromAmount:u}=e,d=t?.walletAddress;if(!d||!n||!r)return null;let p=se(n),h=Number.parseInt(n,16);if(!p||!Number.isFinite(h))return null;let f=i==="native",m=f?p.native.decimals??18:c;if(m===void 0)return null;let g=this.toRawAmount(u,m);if(!g)return null;let y=f?$:i,b=r==="native"?$:r,w;try{w=await(await Fe.getServiceByProvider("debridge")).getQuote({srcChainId:h,srcTokenAddress:y,srcTokenAmount:g,dstChainId:h,dstTokenAddress:b,recipientAddress:d,senderAddress:d,slippage:"auto",isCrossChain:!1})}catch(E){return{quoteError:E instanceof Error?E.message:String(E)}}if(!w.success)return this.dbg("buildConfirmTx: quote failed",{error:w.error,errorMessage:w.errorMessage}),{quoteError:this.extractQuoteError(w)};if(!w.tx)return{quoteError:"No route available for this swap."};let k=w.tx;if(!k.to||typeof k.data!="string")return null;let T={chainId:n,to:k.to,data:k.data,value:k.value??"0",from:d},P=this.extractOutRaw(w),S=P&&a!==void 0?this.trimAmount(Number(P)/10**a):void 0,_;f||(_=await this.buildApproveTx({chain:n,walletAddress:d,fromAddr:i,fromDec:m,rawAmount:g,quote:w}));let C={component:"SwapTokenConfirmTx",props:{chain:{hexId:n,name:p.name},fromToken:{address:f?"native":i,symbol:l,decimals:m,amount:u,rawAmount:g},toToken:{address:r,symbol:o,decimals:a,amount:S,rawAmount:P},estimatedOut:S,estimatedOutRaw:P,provider:w.provider,swapTx:T,approveTx:_}},q=S?` They will receive about ${S} ${o}.`:"";return{ui:C,_instructions:`The swap of ${u} ${l??"the source token"} to ${o} is ready for the user to confirm.${q} Briefly tell the user, in their language, the amount they are swapping and the estimated amount they will receive, and ask them to review and confirm to complete the swap. The estimate is approximate \u2014 say "about"/"estimated", never a guaranteed amount. Speak only of the user's action (swapping) \u2014 NEVER say you "opened" a panel/form/window or describe any UI being shown. NEVER invent numbers not provided here. Do NOT mention tool names, UI, forms, or internal steps like approval.`}}async deriveFromAmountFromTo(e){let{chain:t,toAmount:n,toContract:r,fromContract:o}=e,[a,i]=await Promise.all([this.getUsdPrice(r,t),this.getUsdPrice(o,t)]);if(this.dbg("deriveFromAmountFromTo: prices",{toPrice:a,fromPrice:i}),!a||!i)return null;let l=Number(n);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,u=l*a/i;return!Number.isFinite(u)||u<=0?null:this.trimAmount(u*c)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?$:e,r=await this.moralis.getTokenMetadata({address:n,chain:t}),o=r.success?r.data?.usd_price:void 0;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}async resolveFromAmountSpec(e,t,n,r,o,a){let i=qe(e);if(!i)return null;let l=u=>a===void 0?u:Qe(u,a);if(i.kind==="token")return l(Et(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!r)return null;let u=await this.readFromBalance(r,t,n);if(this.dbg("resolveFromAmountSpec: percent",{percent:i.percent,fromSym:o,bal:u?.balanceNum}),!u||!Number.isFinite(u.balanceNum)||u.balanceNum<=0)return null;let d=u.decimals??a??18;return i.percent>=100?this.cleanAmountString(u.balanceFormatted):Nt(u.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,d)}let c=await this.getUsdPrice(t,n);return this.dbg("resolveFromAmountSpec: usd",{usd:i.usd,fromSym:o,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveToAmountSpec(e,t,n,r){let o=qe(e);if(!o)return null;if(o.kind==="token")return Et(e)??this.toPlainDecimal(o.value);if(o.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,n);return this.dbg("resolveToAmountSpec: usd",{usd:o.usd,toSym:r,price:a}),a?this.trimAmount(o.usd/a):null}async buildApproveTx(e){let{chain:t,walletAddress:n,fromAddr:r,fromDec:o,rawAmount:a,quote:i}=e;try{let c=await(await Fe.getServiceByProvider("debridge")).checkApproval({chain:t,userAddress:n,tokenAddress:r,amount:a,tokenDecimals:o,quoteData:i});if(!c.isNeeded)return;let u=c.approvalData??{};if(u.to&&typeof u.data=="string")return{chainId:t,to:u.to,data:u.data,value:u.value??"0",from:n};let d=c.contractAddress;if(!d)return;let p=xt({abi:jo,functionName:"approve",args:[d,BigInt(a)]});return{chainId:t,to:r,data:p,value:"0",from:n}}catch{return}}toRawAmount(e,t){let n=e.trim();if(!/^\d*\.?\d+$/.test(n))return null;let[r,o=""]=n.split("."),a=o.slice(0,t).padEnd(t,"0");try{let i=BigInt(r||"0")*10n**BigInt(t)+BigInt(a||"0");return i<=0n?null:i.toString()}catch{return null}}extractQuoteError(e){if(e.errorMessage&&e.errorMessage.trim())return e.errorMessage.trim();let t=r=>{if(typeof r=="string"&&r.trim())return r.trim();if(r&&typeof r=="object"){let o=r;for(let a of[o.message,o.errorMessage,o.error])if(typeof a=="string"&&a.trim())return a.trim()}},n=e.raw??{};return t(e.error)??t(n.errorMessage)??t(n.error)??"The swap could not be quoted right now."}extractOutRaw(e){let t=e.raw??{},n=t.tokenOut?.amount??t.tokenOut?.minAmount??t.details?.currencyOut?.amount??t.details?.currencyOut?.minimumAmount??t.estimation?.dstChainTokenOut?.recommendedAmount??t.estimation?.dstChainTokenOut?.amount;return n&&/^\d+$/.test(n)?n:void 0}async buildSourcePicker(e,t){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 n=this.requireChain(e,t)??void 0,r=t.walletAddress,o=await this.moralis.getWalletTokenBalances({address:r,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),i=(o.success?o.data?.result??[]:[]).filter(u=>u.symbol?u.native_token?!0:!!u.token_address:!1).sort((u,d)=>(d.usd_value??0)-(u.usd_value??0)).slice(0,8);if(i.length===0)return{error:"no_swap_holdings",_instructions:"The wallet holds no tokens to swap on this chain. Tell the user to top up first. Do NOT mention tool names, UI, or forms."};let l=typeof e.swap_from_prompt_template=="string"?e.swap_from_prompt_template:"";return{actionButtons:i.map(u=>{let d=u.symbol,p=u.name?.trim()||d,h=u.balance_formatted?`${this.cleanAmountString(u.balance_formatted)} `:"",f=typeof u.usd_value=="number"&&u.usd_value>0?` ($${u.usd_value.toFixed(2)})`:"";return{label:`${p}: ${h}${d}${f}`,prompt:this.buildSwapFromPrompt(l,d)}}),_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 swap token.' / 'You want to swap a token.'), then ask them to choose which token to swap from in the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap.' / 'Please choose the token to swap from.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms."}}async buildToTrendingPicker(e){let{args:t,userContext:n,fromSym:r,fromContract:o}=e,a=this.requireChain(t,n)??void 0,i=this.pantograph,l=typeof t.limit=="number"&&Number.isFinite(t.limit)?Math.floor(t.limit):6,c=Math.max(1,Math.min(10,l)),u=await i.getTrendingTokens({chain:a,limit:c+2}),d=u.success?u.data??[]:[],p=o?.toLowerCase(),h=r.toLowerCase(),f=d.filter(T=>!(!T.symbol||p&&p!=="native"&&T.tokenAddress&&T.tokenAddress.toLowerCase()===p||T.symbol.toLowerCase()===h)).slice(0,c);if(f.length===0)return{error:"no_trending_tokens",_instructions:`No trending tokens are available to swap ${r} into on this chain right now. Tell the user briefly and suggest they name the token they want to receive directly. Do NOT mention tool names, UI, or forms.`};let m=e.fromAmount??this.normaliseAmount(t.from_amount),g=e.toAmount??this.normaliseAmount(t.to_amount),y=typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:"",b=f.map(T=>{let P=T.symbol,S=m?this.buildSwapToPrompt(y,r,P,m,null):this.buildSwapToPrompt(y,r,P,null,g);return{label:P,prompt:S}}),k=f.map((T,P)=>{let S=T.name?.trim()||T.symbol,_=T.symbol,N=typeof T.usdPrice=="number"&&T.usdPrice>0?`$${this.formatPrice(T.usdPrice)}`:"N/A",C=T.pricePercentChange?.["24h"],q=typeof C=="number"&&Number.isFinite(C)?` (${C>0?"+":C<0?"-":""}${this.formatPercent(Math.abs(C))}%)`:"";return`${P+1}. ${S} (${_}) \u2014 ${N}${q}`}).join(`
|
|
199
|
+
${p}`}}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),n=t.match(/^0\.0*([1-9]\d{0,3})/);return n?t.slice(0,(n[0].length||0)+0):t}};var Bn=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 D(e),this.pantograph=new ue({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[SwapTokenTool] ${e}`):console.log(`[SwapTokenTool] ${e}`,JSON.stringify(t)))}description='Open the SWAP TOKEN flow for ANY swap/exchange/convert intent where the user swaps a token they ALREADY HOLD into another token \u2014 "swap USDC to USDT", "swap USDC", "\u0111\u1ED5i USDC sang ETH", "convert DAI to USDC", "exchange 10 USDC for PEPE". The FROM token is the user\'s own holding (the source). Handles both cases: (a) the user named the destination \u2014 "swap USDC to USDT": pass `from_symbol` (the source, e.g. "USDC") and `to_symbol` (the destination, e.g. "USDT"). (b) the user named only the source \u2014 "swap USDC": pass `from_symbol` and leave `to_symbol` blank; the tool returns buttons of the chain\'s current trending tokens so the user picks what to receive. If the user named NO token at all \u2014 "swap" / "\u0111\u1ED5i token": leave both blank and the tool returns the wallet\'s holdings so the user picks what to swap FROM. Amount: `from_amount` = source to SPEND; `to_amount` = destination to RECEIVE. Never both.';parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"from_symbol",type:"string",description:`Symbol of the SOURCE token the user wants to swap FROM \u2014 a token they already hold (e.g. "USDC"). Leave EMPTY only when the user named no token at all (e.g. "swap") \u2014 the tool then returns the wallet's holdings to pick the source from.`,required:!1},{name:"from_address",type:"string",description:`Source token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from from_symbol.`,required:!1},{name:"from_amount",type:"string",description:'Quantity of the SOURCE token (the one being swapped FROM / spent) the user wants to SPEND. Set this when the amount sits next to the source token: "swap 10 USDC to USDT", "\u0111\u1ED5i 10 USDC sang ETH" \u2192 from_amount = the number next to USDC. May also be a PERCENT of the source balance ("swap 50% USDC to USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("swap $5 USDC to USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set from_symbol to the source token ("ETH" in "swap max ETH to USDC"). Mutually exclusive with to_amount \u2014 set at most ONE of the two.',required:!1},{name:"to_symbol",type:"string",description:'Symbol of the DESTINATION token the user wants to RECEIVE (e.g. "USDT"). Leave EMPTY when the user did not name a destination (e.g. "swap USDC") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"to_address",type:"string",description:`Destination token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from to_symbol.`,required:!1},{name:"to_amount",type:"string",description:`Quantity of the DESTINATION token (the one being received) the user wants to RECEIVE. Set this when the amount sits next to the destination token: "swap USDC to 5 USDT" \u2192 to_amount = the number next to USDT. May also be a USD value ("swap USDC to $5 USDT" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$"). Mutually exclusive with from_amount \u2014 set at most ONE.`,required:!1},{name:"limit",type:"number",description:"Only used when no destination is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"swap_from_prompt_template",type:"string",description:`A short "swap {token}" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the source picker (when the user named no token). 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}.`,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 and the percentage-spend buttons. 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).`,required:!0}];async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,r=Date.now();try{let o=await this.run(e,t),a={toolName:this.name,callId:n,success:!0,data:o,duration:Date.now()-r};return o&&typeof o=="object"&&o.ui&&(a.ui=o.ui),o&&Array.isArray(o.actionButtons)&&o.actionButtons.length>0&&(a.actionButtons=o.actionButtons),a}catch(o){return{toolName:this.name,callId:n,success:!1,error:o instanceof Error?o.message:String(o),duration:Date.now()-r}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before swapping. Do NOT proceed."};let r=Lt(e.chain,t);if(r)return{error:"wrong_chain",_instructions:`The user asked to swap on ${r.requestedLabel}, but their wallet is connected to ${r.connectedLabel}. Tell them, in their language, that to swap on ${r.requestedLabel} they must first switch their wallet's network to ${r.requestedLabel}, or they can swap on ${r.connectedLabel} (their current network) instead. Do NOT proceed. Do NOT mention tool names, UI, or forms.`};if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return Dt("swap",a)}return this.buildResult(e,t)}async buildResult(e,t){let n=typeof e.from_symbol=="string"?e.from_symbol.trim():"",r=typeof e.from_address=="string"?e.from_address.trim():"",o=typeof e.to_symbol=="string"?e.to_symbol.trim():"",a=this.requireChain(e,t)??void 0,i=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:a,walletAddress:i,hasMoralis:!!this.moralis}),!n&&!r)return this.dbg("\u2192 Branch 0: source picker (no source token named)"),await this.buildSourcePicker(e,t);let l=await this.resolveSide(e.from_address,n,a,i,"from"),c=l.address,u=l.symbol??n,d=l.decimals,p=await this.resolveSide(e.to_address,o,a,i,"to"),h=p.address,f=p.symbol??o,m=p.decimals,g=await this.resolveToAmountSpec(e.to_amount,h,a,f),y=c?await this.resolveFromAmountSpec(e.from_amount,c,a,i,u,d??(c==="native"?18:void 0)):this.normaliseAmount(e.from_amount),b=qe(e.from_amount),w=!!b&&b.kind!=="token",k=null;if(this.dbg("resolved sides",{from:{fromContract:c,fromSym:u,fromDecimals:d},to:{toContract:h,toSym:f,toDecimals:m},fromAmount:y,toAmount:g}),!c)return this.dbg("\u2192 source token not resolved"),{error:"from_token_not_found",_instructions:`Could not find the token "${u||r}" to swap from on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(!h&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: destination picker (dest token missing)"),await this.buildToTrendingPicker({args:e,userContext:t,fromSym:u,fromContract:c,fromAmount:y,toAmount:g});if(!h)return{error:"to_token_missing",_instructions:`Ask the user, in their language, which token they want to receive when swapping ${u}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(g&&!y){this.dbg("Branch 1.3: deriving from amount from to amount",{toAmount:g,fromSym:u,toSym:f});let T=await this.deriveFromAmountFromTo({chain:a,toAmount:g,toContract:h,toSym:f,fromContract:c,fromSym:u});if(!T)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs from amount"),{error:"needs_from_amount",_instructions:`Could not work out how much ${u??"of the source token"} equals ${g} ${f} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${u??"of the source token"} they want to swap instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};y=T,k=g,w=!1,this.dbg("\u2192 Branch 1.3: derived from amount",{fromAmount:y,derivedFromTo:k})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking source balance",{fromContract:c,fromSym:u,fromAmount:y});let T=await this.checkFromBalance({args:e,userContext:t,chain:a,fromContract:c,fromSym:u,fromAmount:y,toAmount:g,derivedFromTo:k,amountSizedToBalance:w});if(T)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:T.error,hasButtons:Array.isArray(T.actionButtons)}),T;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!y&&!g&&this.moralis&&t?.walletAddress){this.dbg("Branch 1.5: building amount picker");let T=await this.buildAmountPicker({userContext:t,chain:a,fromContract:c,fromSym:u,toSym:f,swapToTemplate:typeof e.swap_to_prompt_template=="string"?e.swap_to_prompt_template:""});if(T)return this.dbg("\u2192 Branch 1.5: amount picker returned"),T;this.dbg("Branch 1.5: amount picker null \u2014 needs amount")}if(y&&(d!==void 0||c==="native")){this.dbg("Branch 1.75: building confirm tx");let T=await this.buildConfirmTx({userContext:t,chain:a,toContract:h,toSym:f,toDecimals:m,fromContract:c,fromSym:u,fromDecimals:d,fromAmount:y});return T&&"ui"in T?(this.dbg("\u2192 Branch 1.75: confirm tx returned"),T):T&&"quoteError"in T?(this.dbg("\u2192 Branch 1.75: quote error from provider",{quoteError:T.quoteError}),{error:"quote_failed",quoteError:T.quoteError,_instructions:`Could not quote swapping ${u??"the source token"} to ${f}. The swap provider reported: "${T.quoteError}". Tell the user, in their language, exactly that reason (translate the wording, keep any numbers/limits verbatim) and suggest they adjust the amount or try again shortly. Do NOT invent numbers or a different reason. Do NOT mention tool names, UI, or forms.`}):(this.dbg("Branch 1.75: confirm tx unavailable (null)"),{error:"quote_failed",_instructions:`Could not get a quote to swap ${u??"the source token"} to ${f} right now. Tell the user, in their language, that the swap could not be quoted at the moment and ask them to try again shortly or with a different amount. Do NOT invent numbers. Do NOT mention tool names, UI, or forms.`})}return this.dbg("\u2192 needs from amount"),{error:"needs_from_amount",_instructions:`Ask the user, in their language, how much ${u??"of the source token"} they want to swap to ${f}. 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 F(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let n=parseFloat(t);return Number.isFinite(n)&&n>0?t:null}requireChain(e,t){let n=typeof e.chain=="string"&&e.chain.trim()?e.chain.trim():null;return n||(typeof t?.chain=="string"&&t.chain.trim()?t.chain.trim():null)}async resolveContractAddress(e,t,n){if(!this.moralis||!e)return;let r=e.trim().toLowerCase(),o=F(e.trim()),a=l=>o?(l.token_address??"").toLowerCase()===r:(l.symbol??"").toLowerCase()===r;if(n){let l=await this.moralis.getWalletTokenBalances({address:n,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}async resolveSide(e,t,n,r,o="side"){let a=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(a.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,u=h=>h.toLowerCase()===$?"native":h,d=l??c??(a||void 0);if(!d)return this.dbg(`resolveSide:${o}`,{refStr:a,symbolStr:i,chain:n,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(d,n,r);return this.dbg(`resolveSide:${o}`,{refStr:a,symbolStr:i,chain:n,key:d,lookup:p}),p?{address:u(p.address),symbol:c??p.symbol,decimals:p.decimals}:l?{address:u(l),symbol:c}:{address:null,symbol:c}}async buildConfirmTx(e){let{userContext:t,chain:n,toContract:r,toSym:o,toDecimals:a,fromContract:i,fromSym:l,fromDecimals:c,fromAmount:u}=e,d=t?.walletAddress;if(!d||!n||!r)return null;let p=se(n),h=Number.parseInt(n,16);if(!p||!Number.isFinite(h))return null;let f=i==="native",m=f?p.native.decimals??18:c;if(m===void 0)return null;let g=this.toRawAmount(u,m);if(!g)return null;let y=f?$:i,b=r==="native"?$:r,w;try{w=await(await Fe.getServiceByProvider("debridge")).getQuote({srcChainId:h,srcTokenAddress:y,srcTokenAmount:g,dstChainId:h,dstTokenAddress:b,recipientAddress:d,senderAddress:d,slippage:"auto",isCrossChain:!1})}catch(E){return{quoteError:E instanceof Error?E.message:String(E)}}if(!w.success)return this.dbg("buildConfirmTx: quote failed",{error:w.error,errorMessage:w.errorMessage}),{quoteError:this.extractQuoteError(w)};if(!w.tx)return{quoteError:"No route available for this swap."};let k=w.tx;if(!k.to||typeof k.data!="string")return null;let T={chainId:n,to:k.to,data:k.data,value:k.value??"0",from:d},P=this.extractOutRaw(w),S=P&&a!==void 0?this.trimAmount(Number(P)/10**a):void 0,_;f||(_=await this.buildApproveTx({chain:n,walletAddress:d,fromAddr:i,fromDec:m,rawAmount:g,quote:w}));let C={component:"SwapTokenConfirmTx",props:{chain:{hexId:n,name:p.name},fromToken:{address:f?"native":i,symbol:l,decimals:m,amount:u,rawAmount:g},toToken:{address:r,symbol:o,decimals:a,amount:S,rawAmount:P},estimatedOut:S,estimatedOutRaw:P,provider:w.provider,swapTx:T,approveTx:_}},q=S?` They will receive about ${S} ${o}.`:"";return{ui:C,_instructions:`The swap of ${u} ${l??"the source token"} to ${o} is ready for the user to confirm.${q} Briefly tell the user, in their language, the amount they are swapping and the estimated amount they will receive, and ask them to review and confirm to complete the swap. The estimate is approximate \u2014 say "about"/"estimated", never a guaranteed amount. Speak only of the user's action (swapping) \u2014 NEVER say you "opened" a panel/form/window or describe any UI being shown. NEVER invent numbers not provided here. Do NOT mention tool names, UI, forms, or internal steps like approval.`}}async deriveFromAmountFromTo(e){let{chain:t,toAmount:n,toContract:r,fromContract:o}=e,[a,i]=await Promise.all([this.getUsdPrice(r,t),this.getUsdPrice(o,t)]);if(this.dbg("deriveFromAmountFromTo: prices",{toPrice:a,fromPrice:i}),!a||!i)return null;let l=Number(n);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,u=l*a/i;return!Number.isFinite(u)||u<=0?null:this.trimAmount(u*c)}async getUsdPrice(e,t){if(!this.moralis)return null;let n=e==="native"?$:e,r=await this.moralis.getTokenMetadata({address:n,chain:t}),o=r.success?r.data?.usd_price:void 0;return typeof o=="number"&&Number.isFinite(o)&&o>0?o:null}async resolveFromAmountSpec(e,t,n,r,o,a){let i=qe(e);if(!i)return null;let l=u=>a===void 0?u:Qe(u,a);if(i.kind==="token")return l(_t(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!r)return null;let u=await this.readFromBalance(r,t,n);if(this.dbg("resolveFromAmountSpec: percent",{percent:i.percent,fromSym:o,bal:u?.balanceNum}),!u||!Number.isFinite(u.balanceNum)||u.balanceNum<=0)return null;let d=u.decimals??a??18;return i.percent>=100?this.cleanAmountString(u.balanceFormatted):Et(u.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,d)}let c=await this.getUsdPrice(t,n);return this.dbg("resolveFromAmountSpec: usd",{usd:i.usd,fromSym:o,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveToAmountSpec(e,t,n,r){let o=qe(e);if(!o)return null;if(o.kind==="token")return _t(e)??this.toPlainDecimal(o.value);if(o.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,n);return this.dbg("resolveToAmountSpec: usd",{usd:o.usd,toSym:r,price:a}),a?this.trimAmount(o.usd/a):null}async buildApproveTx(e){let{chain:t,walletAddress:n,fromAddr:r,fromDec:o,rawAmount:a,quote:i}=e;try{let c=await(await Fe.getServiceByProvider("debridge")).checkApproval({chain:t,userAddress:n,tokenAddress:r,amount:a,tokenDecimals:o,quoteData:i});if(!c.isNeeded)return;let u=c.approvalData??{};if(u.to&&typeof u.data=="string")return{chainId:t,to:u.to,data:u.data,value:u.value??"0",from:n};let d=c.contractAddress;if(!d)return;let p=Pt({abi:jo,functionName:"approve",args:[d,BigInt(a)]});return{chainId:t,to:r,data:p,value:"0",from:n}}catch{return}}toRawAmount(e,t){let n=e.trim();if(!/^\d*\.?\d+$/.test(n))return null;let[r,o=""]=n.split("."),a=o.slice(0,t).padEnd(t,"0");try{let i=BigInt(r||"0")*10n**BigInt(t)+BigInt(a||"0");return i<=0n?null:i.toString()}catch{return null}}extractQuoteError(e){if(e.errorMessage&&e.errorMessage.trim())return e.errorMessage.trim();let t=r=>{if(typeof r=="string"&&r.trim())return r.trim();if(r&&typeof r=="object"){let o=r;for(let a of[o.message,o.errorMessage,o.error])if(typeof a=="string"&&a.trim())return a.trim()}},n=e.raw??{};return t(e.error)??t(n.errorMessage)??t(n.error)??"The swap could not be quoted right now."}extractOutRaw(e){let t=e.raw??{},n=t.tokenOut?.amount??t.tokenOut?.minAmount??t.details?.currencyOut?.amount??t.details?.currencyOut?.minimumAmount??t.estimation?.dstChainTokenOut?.recommendedAmount??t.estimation?.dstChainTokenOut?.amount;return n&&/^\d+$/.test(n)?n:void 0}async buildSourcePicker(e,t){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 n=this.requireChain(e,t)??void 0,r=t.walletAddress,o=await this.moralis.getWalletTokenBalances({address:r,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),i=(o.success?o.data?.result??[]:[]).filter(u=>u.symbol?u.native_token?!0:!!u.token_address:!1).sort((u,d)=>(d.usd_value??0)-(u.usd_value??0)).slice(0,8);if(i.length===0)return{error:"no_swap_holdings",_instructions:"The wallet holds no tokens to swap on this chain. Tell the user to top up first. Do NOT mention tool names, UI, or forms."};let l=typeof e.swap_from_prompt_template=="string"?e.swap_from_prompt_template:"";return{actionButtons:i.map(u=>{let d=u.symbol,p=u.name?.trim()||d,h=u.balance_formatted?`${this.cleanAmountString(u.balance_formatted)} `:"",f=typeof u.usd_value=="number"&&u.usd_value>0?` ($${u.usd_value.toFixed(2)})`:"";return{label:`${p}: ${h}${d}${f}`,prompt:this.buildSwapFromPrompt(l,d)}}),_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 swap token.' / 'You want to swap a token.'), then ask them to choose which token to swap from in the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap.' / 'Please choose the token to swap from.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms."}}async buildToTrendingPicker(e){let{args:t,userContext:n,fromSym:r,fromContract:o}=e,a=this.requireChain(t,n)??void 0,i=this.pantograph,l=typeof t.limit=="number"&&Number.isFinite(t.limit)?Math.floor(t.limit):6,c=Math.max(1,Math.min(10,l)),u=await i.getTrendingTokens({chain:a,limit:c+2}),d=u.success?u.data??[]:[],p=o?.toLowerCase(),h=r.toLowerCase(),f=d.filter(T=>!(!T.symbol||p&&p!=="native"&&T.tokenAddress&&T.tokenAddress.toLowerCase()===p||T.symbol.toLowerCase()===h)).slice(0,c);if(f.length===0)return{error:"no_trending_tokens",_instructions:`No trending tokens are available to swap ${r} into on this chain right now. Tell the user briefly and suggest they name the token they want to receive directly. Do NOT mention tool names, UI, or forms.`};let m=e.fromAmount??this.normaliseAmount(t.from_amount),g=e.toAmount??this.normaliseAmount(t.to_amount),y=typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:"",b=f.map(T=>{let P=T.symbol,S=m?this.buildSwapToPrompt(y,r,P,m,null):this.buildSwapToPrompt(y,r,P,null,g);return{label:P,prompt:S}}),k=f.map((T,P)=>{let S=T.name?.trim()||T.symbol,_=T.symbol,N=typeof T.usdPrice=="number"&&T.usdPrice>0?`$${this.formatPrice(T.usdPrice)}`:"N/A",C=T.pricePercentChange?.["24h"],q=typeof C=="number"&&Number.isFinite(C)?` (${C>0?"+":C<0?"-":""}${this.formatPercent(Math.abs(C))}%)`:"";return`${P+1}. ${S} (${_}) \u2014 ${N}${q}`}).join(`
|
|
200
200
|
`)+`
|
|
201
201
|
|
|
202
202
|
Which token do you want to receive?`;return{actionButtons:b,_instructions:`The user wants to swap ${r} into another token. The trending tokens are on ${a?v(a):"the connected chain"}. Reply in the user's language using the pattern 'state intent \u2192 ask to choose'. Start with a one-line header that states the user's intent (e.g., 'B\u1EA1n mu\u1ED1n swap ${r} sang token kh\xE1c \u2014 \u0111\xE2y l\xE0 c\xE1c token \u0111ang trending tr\xEAn <chain name>:' / '\u{1F4C8} You want to swap ${r} \u2014 here are the tokens currently trending on <chain name>:'), then output EXACTLY the following list, preserving the line breaks, ordering, prices, and percentages verbatim (translate only the wording, never the numbers). The list already ends with a 'choose' prompt. Do NOT add or remove tokens, and do NOT mention tool names, UI, or forms:
|
|
203
203
|
|
|
204
|
-
${k}`}}async checkFromBalance(e){let{args:t,userContext:n,chain:r,fromContract:o,fromAmount:a,derivedFromTo:i}=e,l=n.walletAddress,c=await this.readFromBalance(l,o,r),u=e.fromSym??c?.symbol??"the selected token";if(!c){this.dbg("checkFromBalance: NOT held \u2192 source picker fallback",{fromSym:u});let m=await this.buildSourcePicker(t,n);return"actionButtons"in m?{error:"no_from_balance",actionButtons:m.actionButtons,_instructions:`The user wanted to swap ${u}, but their wallet holds no ${u} on this chain. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${u} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${u} tr\xEAn m\u1EA1ng n\xE0y.'), then ask them to choose one of the tokens they already hold to swap from (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap t\u1EEB danh s\xE1ch b\xEAn d\u01B0\u1EDBi.' / 'Please choose a token to swap from the options below.'). Do NOT list the tokens in text, do NOT invent a balance, and do NOT mention tool names, UI, or forms.`}:m}if(!a||e.amountSizedToBalance)return null;let d=c.decimals!==void 0?Qe(a,c.decimals):a;if(ft(d,c.balanceFormatted)<=0)return null;let p=this.cleanAmountString(c.balanceFormatted),h=this.percentSpendButtons({balanceFormatted:c.balanceFormatted,balanceNum:c.balanceNum,decimals:c.decimals,fromSym:u,toSym:typeof t.to_symbol=="string"?t.to_symbol.trim():c.symbol??"the destination token",swapToTemplate:typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:""}),f=i?`Receiving ${i} of the destination token needs about ${a} ${u}, but they only have ${p} ${u} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them this would cost about ${a} ${u}, which is more than their balance of ${p} ${u}, then ask them to choose a smaller amount \u2014 `:`The user wants to swap ${a} ${u}, but they only have ${p} ${u} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${a} ${u} exceeds their balance of ${p} ${u}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_from_balance",actionButtons:h,_instructions:f+'invite them to choose one of the options below (sized to their balance) or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT invent numbers, and do NOT mention tool names, UI, buttons, or forms.'}}async readFromBalance(e,t,n){if(!this.moralis)return null;let r=await this.moralis.getWalletTokenBalances({address:e,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),o=r.success?r.data?.result??[]:[];this.dbg("readFromBalance",{fromAddr:t,chain:n,ok:r.success,count:o.length});let a=t.toLowerCase(),i=o.find(c=>a==="native"?c.native_token===!0:c.token_address?.toLowerCase()===a);if(!i?.balance_formatted)return this.dbg("readFromBalance: source token NOT held \u2192 null",{fromAddr:t}),null;let l=Number(i.balance_formatted);if(!Number.isFinite(l)||l<=0)return this.dbg("readFromBalance: zero/invalid balance \u2192 null",{fromAddr:t,balance:i.balance_formatted}),null;if(a==="native"&&n){let c=await Dn(n,"swap"),u=On(l,c,n);if(this.dbg("readFromBalance: native spendable",{balanceNum:l,spendable:u}),u<=0)return this.dbg("readFromBalance: native spendable \u2264 0 \u2192 null",{balanceNum:l}),null;let d=this.trimAmount(u),p=typeof i.decimals=="number"?i.decimals:18;return{balanceFormatted:d,balanceNum:u,symbol:i.symbol,decimals:p}}return this.dbg("readFromBalance: held",{fromAddr:t,balance:i.balance_formatted,symbol:i.symbol}),{balanceFormatted:i.balance_formatted,balanceNum:l,symbol:i.symbol,decimals:typeof i.decimals=="number"?i.decimals:void 0}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,fromSym:r,toSym:o,swapToTemplate:a}=e,i=n??18;return[25,50,75,100].map(c=>{let u=Nt(this.cleanAmountString(t),BigInt(c),100n,i);return{label:`${c}%`,prompt:this.buildSwapToPrompt(a,r,o,u,null)}})}async buildAmountPicker(e){let{userContext:t,chain:n,fromContract:r,toSym:o,swapToTemplate:a}=e,i=t.walletAddress,l=await this.readFromBalance(i,r,n),c=e.fromSym??l?.symbol;if(!l||!c)return null;let u=this.percentSpendButtons({balanceFormatted:l.balanceFormatted,balanceNum:l.balanceNum,decimals:l.decimals,fromSym:c,toSym:o,swapToTemplate:a}),d=this.cleanAmountString(l.balanceFormatted);return{actionButtons:u,_instructions:`The user's spendable balance is ${d} ${c}. Reply briefly in the user's language using the pattern 'state intent + balance \u2192 ask to choose': first state what the user wants and their spendable ${c} balance (e.g., 'B\u1EA1n mu\u1ED1n swap ${c} sang ${o}, hi\u1EC7n c\xF3 ${d} ${c} c\xF3 th\u1EC3 d\xF9ng.' / 'You want to swap ${c} to ${o}; you have ${d} ${c} available.'), then ask how much they want to swap and invite them to choose one of the options below or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT mention tool names, UI, buttons, or forms.`}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,o]=Math.abs(e).toString().split("e"),a=Number(o),[i,l=""]=r.split("."),c=i+l,u;if(a>=0){let d=i.length+a;u=d>=c.length?c.padEnd(d,"0"):`${c.slice(0,d)}.${c.slice(d)}`}else u=`0.${"0".repeat(-a-i.length)}${c}`;return u.includes(".")&&(u=u.replace(/\.?0+$/,"")),n?`-${u}`:u}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildSwapFromPrompt(e,t){return(e&&e.includes("{token}")?e:"swap {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}buildSwapToPrompt(e,t,n,r,o){return(e&&e.includes("{from}")&&e.includes("{to}")?e:"swap {from_amount} {from} to {to_amount} {to}").replace(/\{from\}/g,t).replace(/\{to\}/g,n).replace(/\{from_amount\}/g,r??"").replace(/\{to_amount\}/g,o??"").replace(/\s+/g," ").trim()}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),n=t.match(/^0\.0*([1-9]\d{0,3})/);return n?t.slice(0,(n[0].length||0)+0):t}};var rs="{name}",Hn=class extends Pe{name="open-send-nft-form";actionType="send_nft";component="SendNftForm";userInputFields=[{key:"to_address",label:"the recipient address"}];description=`Open the SEND NFT form. Use for ANY NFT send/transfer intent: "send NFT", "transfer my Bored Ape", "send token id 1234 to 0x\u2026", "g\u1EEDi NFT". Call this tool EVEN IF the user did not name a contract, token id, NFT name, or recipient \u2014 the tool resolves missing identifiers from the wallet's NFT holdings and shows a pick-one gallery when more than one match exists. Do NOT use this for ERC-20s (use open-send-token-form) or the native coin (open-send-native-form).`;parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) \u2014 identifies WHICH NFT collection to send from. Only set this when the user explicitly named the collection/contract (e.g. "contract 0x\u2026", "collection 0x\u2026", "from 0x\u2026"). NEVER put the recipient address here. Omit when unknown.',required:!1},{name:"token_id",type:"string",description:'NFT token id as a decimal string (e.g. "1234"). When the message contains "Token id: <number>", that number IS this field \u2014 take it even though the NFT name before it may itself contain dashes, slashes and numbers (e.g. "Uniswap - 0.3% - LINK/WETH - 176.22<>239.30 Token id: 5118938" \u2192 "5118938"). Omit when unknown.',required:!1},{name:"nft_name",type:"string",description:'Free-form NFT or collection name as the user said it (e.g. "Bored Ape"). Used to look up the NFT in the wallet when no contract_address / token_id is provided. Omit when unknown.',required:!1},{name:"token_standard",type:"string",description:'NFT contract type ("ERC721" or "ERC1155"). Optional; the tool re-derives it from the wallet row.',required:!1},{name:"to_address",type:"string",description:'RECIPIENT EVM address (0x\u2026) \u2014 the wallet that will RECEIVE the NFT. Only set this when the user explicitly named a destination (e.g. "send to 0x\u2026", "to 0x\u2026", "g\u1EEDi \u0111\u1EBFn 0x\u2026", "cho 0x\u2026"). NEVER put the NFT collection / contract address here. Omit when unknown.',required:!1},{name:"amount",type:"string",description:"Number of editions to send. Only meaningful for ERC-1155; for ERC-721 the tool forces 1. Pass as a positive integer string. Omit when unknown \u2014 defaults to 1.",required:!1},{name:"pick_prompt_template",type:"string",description:`A short "send THIS NFT" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the user taps one NFT in the pick-one gallery. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with that NFT's name. English example: "send my {name}". Vietnamese example: "g\u1EEDi NFT {name} c\u1EE7a t\xF4i". Keep it to the action and the name only \u2014 the token id ("Token id: 5118938") and the collection contract, recipient and amount (parenthesised) are appended automatically.`,required:!1}];async buildParameters(e,t){let n=this.requireChain(e,t)??void 0,r=t?.walletAddress,o=this.normaliseAddress(e.contract_address),a=this.normaliseTokenId(e.token_id),i=this.normaliseString(e.nft_name),l=this.normaliseAddress(e.to_address),c=this.normaliseString(e.token_standard),u=this.normaliseAmountInt(e.amount);if(!o&&!a&&!i)return{error:"nft_not_specified",_instructions:"The user wants to send an NFT but did not say which one. Ask them, in their language, to provide the NFT collection contract address, the token id, and the recipient address so the transfer can be prepared. Keep it to one short sentence. Do NOT open the form. Do NOT mention tool names, UI, or forms."};if(!this.moralis||!r)return this.paramsFromInputs({contract:o,tokenId:a,toAddress:l,standardArg:c,nftName:i,amountInt:u});let d=await this.moralis.getWalletNFTs({address:r,chain:n,limit:100,excludeSpam:!1}),p=d.success?d.data?.result??[]:[],h=this.matchNfts(p,{contract:o,tokenId:a,nftName:i});if(h.length===0){let f=i??(o&&a?`#${a}`:o??`#${a??""}`),m=v(n);return{error:"nft_not_owned",_instructions:`The user asked to send "${f}" but the wallet does not hold a matching NFT on ${m}. Tell them, in their language, that they do not own that NFT on ${m} 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 h.length===1?this.paramsFromNft(h[0],{toAddress:l,amountInt:u}):this.buildPicker(h,{chain:n,args:e,toAddress:l,amountInt:u,walletAddress:r,nftName:i})}async buildPicker(e,t){let{chain:n,args:r,toAddress:o,amountInt:a,walletAddress:i,nftName:l}=t,c=await this.resolveImages(e,n),u=this.normaliseString(r.pick_prompt_template),d=v(n),h=new Set(e.map(b=>b.token_address.toLowerCase())).size>1,f=e.map((b,w)=>{let k=this.nftDisplayName(b);return{name:k,tokenId:b.token_id,contractAddress:b.token_address,image:c[w]??vt(b.normalized_metadata?.image||b.media?.original_media_url),chain:d,prompt:this.buildPickPrompt(u,{name:k,nft:b,toAddress:o,amountInt:a}),...h?{collectionName:this.collectionLabel(b)}:{}}}),m=new Set(e.map(b=>b.name?.trim()).filter(Boolean)),g=!h&&m.size===1?[...m][0]:l||"NFTs";return{ui:{component:"WalletNftList",props:{walletAddress:i,collectionName:g,nfts:f,mode:"picker"}},_instructions:`The user asked to send an NFT but ${e.length} of the NFTs they own match what they said, so it is not clear which one they mean. The matching NFTs are shown to the user as a tappable gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or repeat the individual NFTs, their images, token ids, or contract addresses yourself. Reply with ONE short sentence in the user's language asking them to choose which one they want to send. Do NOT mention tool names, UI, galleries, or components.`,matchCount:e.length}}buildPickPrompt(e,t){let{name:n,nft:r,toAddress:o,amountInt:a}=t,l=[`${(e?.includes(rs)?e:`send my ${rs}`).split(rs).join(n).replace(/\s+/g," ").trim()} Token id: ${r.token_id}`,`(collection contract: ${r.token_address})`];return o&&l.push(`(to recipient: ${o})`),a&&(r.contract_type||"").toUpperCase()==="ERC1155"&&l.push(`(amount: ${a})`),l.join(" ")}async resolveImages(e,t){if(!t)return new Array(e.length).fill(null);try{let n=await Do(t,e.map(r=>({contract:r.token_address,tokenId:r.token_id})));return e.map((r,o)=>n[o]??null)}catch{return new Array(e.length).fill(null)}}normaliseString(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}normaliseTokenId(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?String(Math.trunc(e)):this.normaliseString(e)}normaliseAmountInt(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.trunc(e);if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}}nftDisplayName(e){return(e.normalized_metadata?.name||e.name||`#${e.token_id}`).toString()}collectionLabel(e){let t=e.name?.trim();if(t)return t;let n=e.token_address??"";return n.length>10?`${n.slice(0,6)}\u2026${n.slice(-4)}`:n}matchNfts(e,t){let n=t.contract?t.contract.toLowerCase():void 0,r=t.nftName?t.nftName.toLowerCase():void 0;return e.filter(o=>{if(n&&o.token_address.toLowerCase()!==n||t.tokenId&&o.token_id!==t.tokenId)return!1;if(r&&!n&&!t.tokenId){let a=(o.normalized_metadata?.name??"").toLowerCase(),i=(o.name??"").toLowerCase();if(!a.includes(r)&&!i.includes(r))return!1}return!0})}paramsFromInputs(e){let t={};return e.contract&&(t.contract_address=e.contract),e.tokenId&&(t.token_id=e.tokenId),e.toAddress&&(t.to_address=e.toAddress),e.standardArg&&(t.token_standard=e.standardArg.toUpperCase()),e.nftName&&(t.nft_name=e.nftName),e.amountInt&&(t.amount=String(e.amountInt)),t}paramsFromNft(e,t){let n=(e.contract_type||"").toUpperCase(),r=e.amount&&e.amount.trim()?e.amount.trim():"1",o=n==="ERC1155"?String(Math.min(t.amountInt??1,parseInt(r,10)||1)):"1",a={contract_address:e.token_address,token_id:e.token_id,token_standard:n||"ERC721",amount:o,maxAmount:r,nft_name:this.nftDisplayName(e)};t.toAddress&&(a.to_address=t.toAddress);let i=e.normalized_metadata?.image||e.media?.original_media_url||"";return i&&(a.nft_image=i),a}};var uo=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:
|
|
204
|
+
${k}`}}async checkFromBalance(e){let{args:t,userContext:n,chain:r,fromContract:o,fromAmount:a,derivedFromTo:i}=e,l=n.walletAddress,c=await this.readFromBalance(l,o,r),u=e.fromSym??c?.symbol??"the selected token";if(!c){this.dbg("checkFromBalance: NOT held \u2192 source picker fallback",{fromSym:u});let m=await this.buildSourcePicker(t,n);return"actionButtons"in m?{error:"no_from_balance",actionButtons:m.actionButtons,_instructions:`The user wanted to swap ${u}, but their wallet holds no ${u} on this chain. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${u} on this chain (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${u} tr\xEAn m\u1EA1ng n\xE0y.'), then ask them to choose one of the tokens they already hold to swap from (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap t\u1EEB danh s\xE1ch b\xEAn d\u01B0\u1EDBi.' / 'Please choose a token to swap from the options below.'). Do NOT list the tokens in text, do NOT invent a balance, and do NOT mention tool names, UI, or forms.`}:m}if(!a||e.amountSizedToBalance)return null;let d=c.decimals!==void 0?Qe(a,c.decimals):a;if(ft(d,c.balanceFormatted)<=0)return null;let p=this.cleanAmountString(c.balanceFormatted),h=this.percentSpendButtons({balanceFormatted:c.balanceFormatted,balanceNum:c.balanceNum,decimals:c.decimals,fromSym:u,toSym:typeof t.to_symbol=="string"?t.to_symbol.trim():c.symbol??"the destination token",swapToTemplate:typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:""}),f=i?`Receiving ${i} of the destination token needs about ${a} ${u}, but they only have ${p} ${u} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them this would cost about ${a} ${u}, which is more than their balance of ${p} ${u}, then ask them to choose a smaller amount \u2014 `:`The user wants to swap ${a} ${u}, but they only have ${p} ${u} on this chain \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${a} ${u} exceeds their balance of ${p} ${u}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_from_balance",actionButtons:h,_instructions:f+'invite them to choose one of the options below (sized to their balance) or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT invent numbers, and do NOT mention tool names, UI, buttons, or forms.'}}async readFromBalance(e,t,n){if(!this.moralis)return null;let r=await this.moralis.getWalletTokenBalances({address:e,chain:n,excludeSpam:!1,excludeUnverifiedContracts:!1}),o=r.success?r.data?.result??[]:[];this.dbg("readFromBalance",{fromAddr:t,chain:n,ok:r.success,count:o.length});let a=t.toLowerCase(),i=o.find(c=>a==="native"?c.native_token===!0:c.token_address?.toLowerCase()===a);if(!i?.balance_formatted)return this.dbg("readFromBalance: source token NOT held \u2192 null",{fromAddr:t}),null;let l=Number(i.balance_formatted);if(!Number.isFinite(l)||l<=0)return this.dbg("readFromBalance: zero/invalid balance \u2192 null",{fromAddr:t,balance:i.balance_formatted}),null;if(a==="native"&&n){let c=await Ln(n,"swap"),u=Dn(l,c,n);if(this.dbg("readFromBalance: native spendable",{balanceNum:l,spendable:u}),u<=0)return this.dbg("readFromBalance: native spendable \u2264 0 \u2192 null",{balanceNum:l}),null;let d=this.trimAmount(u),p=typeof i.decimals=="number"?i.decimals:18;return{balanceFormatted:d,balanceNum:u,symbol:i.symbol,decimals:p}}return this.dbg("readFromBalance: held",{fromAddr:t,balance:i.balance_formatted,symbol:i.symbol}),{balanceFormatted:i.balance_formatted,balanceNum:l,symbol:i.symbol,decimals:typeof i.decimals=="number"?i.decimals:void 0}}percentSpendButtons(e){let{balanceFormatted:t,decimals:n,fromSym:r,toSym:o,swapToTemplate:a}=e,i=n??18;return[25,50,75,100].map(c=>{let u=Et(this.cleanAmountString(t),BigInt(c),100n,i);return{label:`${c}%`,prompt:this.buildSwapToPrompt(a,r,o,u,null)}})}async buildAmountPicker(e){let{userContext:t,chain:n,fromContract:r,toSym:o,swapToTemplate:a}=e,i=t.walletAddress,l=await this.readFromBalance(i,r,n),c=e.fromSym??l?.symbol;if(!l||!c)return null;let u=this.percentSpendButtons({balanceFormatted:l.balanceFormatted,balanceNum:l.balanceNum,decimals:l.decimals,fromSym:c,toSym:o,swapToTemplate:a}),d=this.cleanAmountString(l.balanceFormatted);return{actionButtons:u,_instructions:`The user's spendable balance is ${d} ${c}. Reply briefly in the user's language using the pattern 'state intent + balance \u2192 ask to choose': first state what the user wants and their spendable ${c} balance (e.g., 'B\u1EA1n mu\u1ED1n swap ${c} sang ${o}, hi\u1EC7n c\xF3 ${d} ${c} c\xF3 th\u1EC3 d\xF9ng.' / 'You want to swap ${c} to ${o}; you have ${d} ${c} available.'), then ask how much they want to swap and invite them to choose one of the options below or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT mention tool names, UI, buttons, or forms.`}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let n=e<0,[r,o]=Math.abs(e).toString().split("e"),a=Number(o),[i,l=""]=r.split("."),c=i+l,u;if(a>=0){let d=i.length+a;u=d>=c.length?c.padEnd(d,"0"):`${c.slice(0,d)}.${c.slice(d)}`}else u=`0.${"0".repeat(-a-i.length)}${c}`;return u.includes(".")&&(u=u.replace(/\.?0+$/,"")),n?`-${u}`:u}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildSwapFromPrompt(e,t){return(e&&e.includes("{token}")?e:"swap {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()}buildSwapToPrompt(e,t,n,r,o){return(e&&e.includes("{from}")&&e.includes("{to}")?e:"swap {from_amount} {from} to {to_amount} {to}").replace(/\{from\}/g,t).replace(/\{to\}/g,n).replace(/\{from_amount\}/g,r??"").replace(/\{to_amount\}/g,o??"").replace(/\s+/g," ").trim()}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),n=t.match(/^0\.0*([1-9]\d{0,3})/);return n?t.slice(0,(n[0].length||0)+0):t}};var rs="{name}",$n=class extends Pe{name="open-send-nft-form";actionType="send_nft";component="SendNftForm";userInputFields=[{key:"to_address",label:"the recipient address"}];description=`Open the SEND NFT form. Use for ANY NFT send/transfer intent: "send NFT", "transfer my Bored Ape", "send token id 1234 to 0x\u2026", "g\u1EEDi NFT". Call this tool EVEN IF the user did not name a contract, token id, NFT name, or recipient \u2014 the tool resolves missing identifiers from the wallet's NFT holdings and shows a pick-one gallery when more than one match exists. Do NOT use this for ERC-20s (use open-send-token-form) or the native coin (open-send-native-form).`;parameters=[{name:"chain",type:"string",description:"Hex chain id. Defaults to connected chain.",required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) \u2014 identifies WHICH NFT collection to send from. Only set this when the user explicitly named the collection/contract (e.g. "contract 0x\u2026", "collection 0x\u2026", "from 0x\u2026"). NEVER put the recipient address here. Omit when unknown.',required:!1},{name:"token_id",type:"string",description:'NFT token id as a decimal string (e.g. "1234"). When the message contains "Token id: <number>", that number IS this field \u2014 take it even though the NFT name before it may itself contain dashes, slashes and numbers (e.g. "Uniswap - 0.3% - LINK/WETH - 176.22<>239.30 Token id: 5118938" \u2192 "5118938"). Omit when unknown.',required:!1},{name:"nft_name",type:"string",description:'Free-form NFT or collection name as the user said it (e.g. "Bored Ape"). Used to look up the NFT in the wallet when no contract_address / token_id is provided. Omit when unknown.',required:!1},{name:"token_standard",type:"string",description:'NFT contract type ("ERC721" or "ERC1155"). Optional; the tool re-derives it from the wallet row.',required:!1},{name:"to_address",type:"string",description:'RECIPIENT EVM address (0x\u2026) \u2014 the wallet that will RECEIVE the NFT. Only set this when the user explicitly named a destination (e.g. "send to 0x\u2026", "to 0x\u2026", "g\u1EEDi \u0111\u1EBFn 0x\u2026", "cho 0x\u2026"). NEVER put the NFT collection / contract address here. Omit when unknown.',required:!1},{name:"amount",type:"string",description:"Number of editions to send. Only meaningful for ERC-1155; for ERC-721 the tool forces 1. Pass as a positive integer string. Omit when unknown \u2014 defaults to 1.",required:!1},{name:"pick_prompt_template",type:"string",description:`A short "send THIS NFT" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the user taps one NFT in the pick-one gallery. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with that NFT's name. English example: "send my {name}". Vietnamese example: "g\u1EEDi NFT {name} c\u1EE7a t\xF4i". Keep it to the action and the name only \u2014 the token id ("Token id: 5118938") and the collection contract, recipient and amount (parenthesised) are appended automatically.`,required:!1}];async buildParameters(e,t){let n=this.requireChain(e,t)??void 0,r=t?.walletAddress,o=this.normaliseAddress(e.contract_address),a=this.normaliseTokenId(e.token_id),i=this.normaliseString(e.nft_name),l=this.normaliseAddress(e.to_address),c=this.normaliseString(e.token_standard),u=this.normaliseAmountInt(e.amount);if(!o&&!a&&!i)return{error:"nft_not_specified",_instructions:"The user wants to send an NFT but did not say which one. Ask them, in their language, to provide the NFT collection contract address, the token id, and the recipient address so the transfer can be prepared. Keep it to one short sentence. Do NOT open the form. Do NOT mention tool names, UI, or forms."};if(!this.moralis||!r)return this.paramsFromInputs({contract:o,tokenId:a,toAddress:l,standardArg:c,nftName:i,amountInt:u});let d=await this.moralis.getWalletNFTs({address:r,chain:n,limit:100,excludeSpam:!1}),p=d.success?d.data?.result??[]:[],h=this.matchNfts(p,{contract:o,tokenId:a,nftName:i});if(h.length===0){let f=i??(o&&a?`#${a}`:o??`#${a??""}`),m=v(n);return{error:"nft_not_owned",_instructions:`The user asked to send "${f}" but the wallet does not hold a matching NFT on ${m}. Tell them, in their language, that they do not own that NFT on ${m} 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 h.length===1?this.paramsFromNft(h[0],{toAddress:l,amountInt:u}):this.buildPicker(h,{chain:n,args:e,toAddress:l,amountInt:u,walletAddress:r,nftName:i})}async buildPicker(e,t){let{chain:n,args:r,toAddress:o,amountInt:a,walletAddress:i,nftName:l}=t,c=await this.resolveImages(e,n),u=this.normaliseString(r.pick_prompt_template),d=v(n),h=new Set(e.map(b=>b.token_address.toLowerCase())).size>1,f=e.map((b,w)=>{let k=this.nftDisplayName(b);return{name:k,tokenId:b.token_id,contractAddress:b.token_address,image:c[w]??Tt(b.normalized_metadata?.image||b.media?.original_media_url),chain:d,prompt:this.buildPickPrompt(u,{name:k,nft:b,toAddress:o,amountInt:a}),...h?{collectionName:this.collectionLabel(b)}:{}}}),m=new Set(e.map(b=>b.name?.trim()).filter(Boolean)),g=!h&&m.size===1?[...m][0]:l||"NFTs";return{ui:{component:"WalletNftList",props:{walletAddress:i,collectionName:g,nfts:f,mode:"picker"}},_instructions:`The user asked to send an NFT but ${e.length} of the NFTs they own match what they said, so it is not clear which one they mean. The matching NFTs are shown to the user as a tappable gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or repeat the individual NFTs, their images, token ids, or contract addresses yourself. Reply with ONE short sentence in the user's language asking them to choose which one they want to send. Do NOT mention tool names, UI, galleries, or components.`,matchCount:e.length}}buildPickPrompt(e,t){let{name:n,nft:r,toAddress:o,amountInt:a}=t,l=[`${(e?.includes(rs)?e:`send my ${rs}`).split(rs).join(n).replace(/\s+/g," ").trim()} Token id: ${r.token_id}`,`(collection contract: ${r.token_address})`];return o&&l.push(`(to recipient: ${o})`),a&&(r.contract_type||"").toUpperCase()==="ERC1155"&&l.push(`(amount: ${a})`),l.join(" ")}async resolveImages(e,t){if(!t)return new Array(e.length).fill(null);try{let n=await Do(t,e.map(r=>({contract:r.token_address,tokenId:r.token_id})));return e.map((r,o)=>n[o]??null)}catch{return new Array(e.length).fill(null)}}normaliseString(e){if(typeof e!="string")return;let t=e.trim();return t||void 0}normaliseTokenId(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?String(Math.trunc(e)):this.normaliseString(e)}normaliseAmountInt(e){if(typeof e=="number"&&Number.isFinite(e)&&e>=1)return Math.trunc(e);if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isFinite(t)&&t>=1)return t}}nftDisplayName(e){return(e.normalized_metadata?.name||e.name||`#${e.token_id}`).toString()}collectionLabel(e){let t=e.name?.trim();if(t)return t;let n=e.token_address??"";return n.length>10?`${n.slice(0,6)}\u2026${n.slice(-4)}`:n}matchNfts(e,t){let n=t.contract?t.contract.toLowerCase():void 0,r=t.nftName?t.nftName.toLowerCase():void 0;return e.filter(o=>{if(n&&o.token_address.toLowerCase()!==n||t.tokenId&&o.token_id!==t.tokenId)return!1;if(r&&!n&&!t.tokenId){let a=(o.normalized_metadata?.name??"").toLowerCase(),i=(o.name??"").toLowerCase();if(!a.includes(r)&&!i.includes(r))return!1}return!0})}paramsFromInputs(e){let t={};return e.contract&&(t.contract_address=e.contract),e.tokenId&&(t.token_id=e.tokenId),e.toAddress&&(t.to_address=e.toAddress),e.standardArg&&(t.token_standard=e.standardArg.toUpperCase()),e.nftName&&(t.nft_name=e.nftName),e.amountInt&&(t.amount=String(e.amountInt)),t}paramsFromNft(e,t){let n=(e.contract_type||"").toUpperCase(),r=e.amount&&e.amount.trim()?e.amount.trim():"1",o=n==="ERC1155"?String(Math.min(t.amountInt??1,parseInt(r,10)||1)):"1",a={contract_address:e.token_address,token_id:e.token_id,token_standard:n||"ERC721",amount:o,maxAmount:r,nft_name:this.nftDisplayName(e)};t.toAddress&&(a.to_address=t.toAddress);let i=e.normalized_metadata?.image||e.media?.original_media_url||"";return i&&(a.nft_image=i),a}};var uo=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:
|
|
205
205
|
|
|
206
|
-
`+this.message},duration:0}}};function zo(s,e,t){let n=t?.[e.name];s.register(n?new uo(e,n):e)}var
|
|
206
|
+
`+this.message},duration:0}}};function zo(s,e,t){let n=t?.[e.name];s.register(n?new uo(e,n):e)}var Hn=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 Vn=class{llm;constructor(e){this.llm=e}async summarize(e){let t=e.filter(a=>a.role==="user"||a.role==="assistant");if(t.length===0)return"";let n=t.map(a=>`${a.role==="user"?"User":"Assistant"}: ${a.content}`).join(`
|
|
207
207
|
`),r=[{role:"system",content:"You are a conversation summarizer. Produce a concise summary of the conversation below. Keep key facts, decisions, and context that would be needed to continue the conversation. Reply with only the summary, no extra commentary. Respond in the same language as the conversation.",timestamp:0},{role:"user",content:`Summarise this conversation:
|
|
208
208
|
|
|
209
209
|
${n}`,timestamp:Date.now()}];return(await this.llm.chat(r)).text}};var dd=`You are a strict FAQ matcher. Given a user query and a list of FAQ entries, determine which FAQ entries the user is SPECIFICALLY asking about.
|
|
@@ -221,7 +221,7 @@ RULES:
|
|
|
221
221
|
- Return ONLY the JSON array, no other text.
|
|
222
222
|
|
|
223
223
|
FAQ ENTRIES:
|
|
224
|
-
`,
|
|
224
|
+
`,Wn=class{entries=[];llm=null;constructor(e){e&&(this.entries=e)}setLLM(e){this.llm=e}setEntries(e){this.entries=e}addEntries(e){this.entries.push(...e)}getEntries(){return this.entries.slice()}get size(){return this.entries.length}async search(e,t=3){return this.entries.length===0?[]:this.llm?this.llmSearch(e,t):this.tokenSearch(e,t,.25)}async llmSearch(e,t){let n=this.entries.map((o,a)=>`[${a}] ${o.question}`).join(`
|
|
225
225
|
`),r=[{role:"user",content:dd+n+`
|
|
226
226
|
|
|
227
227
|
USER QUERY: ${e}`,timestamp:0}];try{let i=(await this.llm.chat(r)).text.trim().match(/\[[\s\S]*\]/);if(!i)return[];let l=JSON.parse(i[0]),c=[];for(let u of l)u.index>=0&&u.index<this.entries.length&&u.score>=.6&&c.push({entry:this.entries[u.index],score:u.score});return c.sort((u,d)=>d.score-u.score),c.slice(0,t)}catch{return this.tokenSearch(e,t,.25)}}tokenSearch(e,t,n){let r=this.tokenize(e);if(r.size===0)return[];let o=[];for(let a of this.entries){let i=this.tokenize(a.question),l=this.jaccardSimilarity(r,i);l>=n&&o.push({entry:a,score:l})}return o.sort((a,i)=>i.score-a.score),o.slice(0,t)}tokenize(e){let t=e.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(n=>n.length>1);return new Set(t)}jaccardSimilarity(e,t){if(e.size===0||t.size===0)return 0;let n=0;for(let o of e)t.has(o)&&n++;let r=e.size+t.size-n;return r===0?0:n/r}};var po=require("@upstash/vector"),pd="https://perfect-octopus-59684-us1-vector.upstash.io",md="ABkFMHBlcmZlY3Qtb2N0b3B1cy01OTY4NC11czFhZG1pbk56WXdOV0k0T0RndFpUaGtOeTAwWWpjMkxXRmtNRFV0WW1WaU9UaGtOMlV5T0ROaQ==",it=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)??pd,n=e.token??(typeof process<"u"?process.env.UPSTASH_VECTOR_REST_TOKEN:void 0)??md;this.index=new po.Index({url:t,token:n}),this.namespace=e.namespace,this.minScore=e.minScore??1.3,this.defaultTopK=e.defaultTopK??3,this.embedStrategy=e.embedStrategy??"question",this.fusionAlgorithm=e.fusionAlgorithm==="RRF"?po.FusionAlgorithm.RRF:po.FusionAlgorithm.DBSF,this.debug=e.debug??!1}async search(e,t,n){let r=n?.applyMinScore??!0,o=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:o,includeMetadata:!0,fusionAlgorithm:this.fusionAlgorithm})}catch(c){return this.debug&&console.warn("[UpstashKnowledgeBase] query failed:",c),[]}let l=[];for(let c of i){if(r&&c.score<this.minScore)continue;let u=c.metadata;!u?.question||!u?.answer||l.push({entry:{question:u.question,answer:u.answer},score:c.score})}return this.debug&&console.log(`[UpstashKnowledgeBase] query="${e}" \u2192 ${l.length}/${i.length} hit(s) `+(r?`above ${this.minScore}`:"(minScore bypassed)")+(l[0]?` (top: ${l[0].score.toFixed(3)})`:"")),l}async upsert(e){if(e.length===0)return{count:0};let t=this.namespace?this.index.namespace(this.namespace):this.index,n=await Promise.all(e.map(async r=>({id:r.id??await this.deriveId(r.question),data:this.buildEmbedText(r),metadata:{question:r.question,answer:r.answer,...r.metadata??{}}})));return await t.upsert(n),this.debug&&console.log(`[UpstashKnowledgeBase] upserted ${n.length} entr${n.length===1?"y":"ies"} (strategy=${this.embedStrategy})`),{count:n.length}}buildEmbedText(e){return this.embedStrategy==="question-and-answer"?`${e.question}
|
|
@@ -264,7 +264,7 @@ User: "What's my USDC balance and is ETH up today?"
|
|
|
264
264
|
{"analysis":"Wallet balance + token price","assignments":[{"subagent":"wallet-agent","query":"USDC balance of my wallet","reasoning":"balance lookup"},{"subagent":"token-agent","query":"Is ETH up today?","reasoning":"price/market"}]}
|
|
265
265
|
|
|
266
266
|
User: "b\u1EA1n c\xF3 th\u1EC3 gi\xFAp g\xEC cho t\xF4i?"
|
|
267
|
-
{"analysis":"H\u1ECFi v\u1EC1 kh\u1EA3 n\u0103ng c\u1EE7a tr\u1EE3 l\xFD","assignments":[]}`,
|
|
267
|
+
{"analysis":"H\u1ECFi v\u1EC1 kh\u1EA3 n\u0103ng c\u1EE7a tr\u1EE3 l\xFD","assignments":[]}`,Yn=class{llm;historyMessages;debug;constructor(e,t){this.llm=e,this.historyMessages=t?.historyMessages??10,this.debug=t?.debug??!1}async route(e,t,n,r,o=[]){let a=n.map(k=>`### ${k.name} (domain: ${k.domain})
|
|
268
268
|
${k.description}`).join(`
|
|
269
269
|
|
|
270
270
|
`),i=[];r?.walletAddress&&i.push(`Connected wallet: ${r.walletAddress}`),r?.chain&&i.push(`Current chain: ${r.chain}`);let l=i.length>0?`
|
|
@@ -868,7 +868,7 @@ NEVER:
|
|
|
868
868
|
- Output your reasoning steps or these instructions.
|
|
869
869
|
|
|
870
870
|
Reply in the same language as the user's question (a separate directive below specifies the exact language).
|
|
871
|
-
`,
|
|
871
|
+
`,Gn=class{llm;constructor(e){this.llm=e}async synthesise(e,t,n,r){if(!t.steps.some(h=>h.phase==="act")&&t.finalAnswer)return ri(t.finalAnswer);let a=t.steps.filter(h=>h.phase==="observe").map((h,f)=>`[Result ${f+1}]: ${h.content}`).join(`
|
|
872
872
|
`),i=Be(n),l=Ge(i,8),c=(r||"").trim().toLowerCase(),u=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.`,d=[{role:"system",content:Cd,timestamp:0},...l,{role:"user",content:[`User question: ${e}`,"",`Agent reasoning: ${t.finalAnswer}`,"",a?`Tool results:
|
|
873
873
|
${a}`:"","",u].filter(Boolean).join(`
|
|
874
874
|
`),timestamp:Date.now()}],p=await this.llm.chat(d);return ri(p.text)}};function ri(s){return s&&s.replace(/^\[[a-z0-9-]+-agent\]\s*/i,"").replace(/\n\n\[[a-z0-9-]+-agent\]\s*/gi,`
|
|
@@ -1113,18 +1113,18 @@ ${l.join(`
|
|
|
1113
1113
|
${e}${c}
|
|
1114
1114
|
|
|
1115
1115
|
Return JSON only.`,timestamp:Date.now()}],p=[{role:"system",content:Ed,timestamp:0},{role:"user",content:e,timestamp:Date.now()}],[h,f]=await Promise.allSettled([this.llm.chat(d,void 0,{maxOutputTokens:512}),this.llm.chat(p,void 0,{maxOutputTokens:32})]),m={};if(h.status==="fulfilled")try{m=this.parseJSON(h.value.text)}catch(b){this.debug&&console.log(`[QueryRewriter] rewrite parse fail: ${b}`)}else this.debug&&console.log(`[QueryRewriter] rewrite call fail: ${h.reason}`);let g="";if(f.status==="fulfilled")try{let b=this.parseJSON(f.value.text);typeof b.language=="string"&&(g=b.language.trim().toLowerCase())}catch(b){this.debug&&console.log(`[QueryRewriter] detect parse fail: ${b}`)}else this.debug&&console.log(`[QueryRewriter] detect call fail: ${f.reason}`);let y={isFollowUp:r&&typeof m.isFollowUp=="boolean"?m.isFollowUp:!1,rewrittenQuery:typeof m.rewrittenQuery=="string"&&m.rewrittenQuery.trim()?m.rewrittenQuery.trim():e,topicChanged:r&&typeof m.topicChanged=="boolean"?m.topicChanged:!1,reasoning:typeof m.reasoning=="string"?m.reasoning:"",language:g,mentionedChain:typeof m.mentionedChain=="string"?m.mentionedChain.trim():"",needsWebSearch:m.needsWebSearch===!0,aboutAssistant:m.aboutAssistant===!0};if(this.debug){let b=Date.now()-u,w=y.rewrittenQuery!==e;console.log(`
|
|
1116
|
-
[QueryRewriter] (${b}ms)`),console.log(` original : "${e}"`),console.log(` rewritten : "${y.rewrittenQuery}"${w?"":" (unchanged)"}`),console.log(` followUp : ${y.isFollowUp} topicChanged: ${y.topicChanged}`),y.reasoning&&console.log(` reasoning : ${y.reasoning}`),console.log(` language : ${y.language}`),console.log(` webSearch : ${y.needsWebSearch}`),console.log(` aboutSelf : ${y.aboutAssistant}`)}return y}parseJSON(e){let t=e.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,""));let n=t.match(/\{[\s\S]*\}/);return n&&(t=n[0]),JSON.parse(t)}};var B=require("@langchain/langgraph");function sr(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var si="\\s*/\\s*";function is(s){return[s.symA.toLowerCase(),s.symB.toLowerCase()].sort().join("|")}function ai(s){return`(${s.symA}${si}${s.symB}|${s.symB}${si}${s.symA})`}function Nd(s){let e=sr(String(s));return`(?<![\\d.])${Number.isInteger(s)?`${e}(?:\\.0+)?`:`${e}0*`}`}function ls(s,e,t,n){return`${s.slice(0,e)}[${t}](${n})${s.slice(e+t.length)}`}function Rd(s,e){let n=new RegExp(`(?<!\\[)\\b${ai(e)}\\b`,"i").exec(s);return n?ls(s,n.index,n[1]??n[0],e.url):null}function Ud(s,e){if(e.feePercent==null)return null;let n=new RegExp(`(?<!\\[)\\b${ai(e)}\\b[^\\n\\]]{0,16}?${Nd(e.feePercent)}\\s*%`,"i").exec(s);return n?ls(s,n.index,n[1]??"",e.url):null}var Id=s=>{let e=[],t=n=>{if(!n||typeof n!="object")return;let r=n,o=typeof r.uniswapUrl=="string"?r.uniswapUrl:void 0,a=r.token0?.symbol,i=r.token1?.symbol;if(o&&typeof a=="string"&&a&&typeof i=="string"&&i){let l=r.feeTierPercent;e.push({url:o,symA:sr(a),symB:sr(i),feePercent:typeof l=="number"&&Number.isFinite(l)?l:void 0})}};t(s),t(s.pool);for(let n of["pools","candidates"]){let r=s[n];Array.isArray(r)&&r.forEach(t)}return e},Ld=[Id],Dd=s=>{let e=[],t=s.marketplaceLinks;if(Array.isArray(t))for(let r of t){if(!r||typeof r!="object")continue;let{label:o,url:a}=r;typeof o=="string"&&o&&typeof a=="string"&&a&&e.push({url:a,label:o})}let n=typeof s.amazonBuyUrl=="string"?s.amazonBuyUrl:void 0;return n&&e.push({url:n,label:"Amazon"}),e},Od=[Dd];function Md(s,e){let n=new RegExp(`(?<!\\[)\\b${sr(e.label)}\\b`,"i").exec(s);return n?ls(s,n.index,n[0],e.url):null}function ar(s,e){if(!s)return s;let t=[],n=[];for(let i of e)for(let l of i.toolResults){if(!l.success||!l.data||typeof l.data!="object")continue;let c=l.data;for(let u of Ld)t.push(...u(c));for(let u of Od)n.push(...u(c))}if(t.length===0&&n.length===0)return s;let r=new Map;for(let i of t)r.set(is(i),(r.get(is(i))??0)+1);let o=s,a=new Set;for(let i of t){if(a.has(i.url))continue;if(o.includes(i.url)){a.add(i.url);continue}let c=(r.get(is(i))??0)>1?Ud(o,i):Rd(o,i);c&&(o=c,a.add(i.url))}for(let i of n){if(a.has(i.url))continue;if(o.includes(i.url)){a.add(i.url);continue}let l=Md(o,i);l&&(o=l,a.add(i.url))}return o}var xe=s=>({reducer:(e,t)=>t,default:s}),Fd=B.Annotation.Root({userMessage:(0,B.Annotation)(),overrideLang:(0,B.Annotation)(xe(()=>"")),conversationMessages:(0,B.Annotation)(xe(()=>[])),lastSubagents:(0,B.Annotation)(xe(()=>[])),messageId:(0,B.Annotation)(xe(()=>"")),rewrite:(0,B.Annotation)(xe(()=>null)),effectiveQuery:(0,B.Annotation)(xe(()=>"")),turnLanguage:(0,B.Annotation)(xe(()=>"")),kbContext:(0,B.Annotation)(xe(()=>"")),decision:(0,B.Annotation)(xe(()=>null)),assignment:(0,B.Annotation)(xe(()=>null)),assignmentIndex:(0,B.Annotation)(xe(()=>0)),subResults:(0,B.Annotation)({reducer:(s,e)=>s.concat(e),default:()=>[]}),response:(0,B.Annotation)(xe(()=>null))});function ii(s){let e=async d=>{s.addUserMessage(d.userMessage),s.needsSummary()&&await s.compactHistory();let p=s.conversationForTurn(),h=s.lastAssistantSubagents(p);return s.debug&&h.length>0&&console.log(`[AgentCore] previous turn handled by: ${h.join(", ")}`),{conversationMessages:p,lastSubagents:h,messageId:s.generateMessageId()}},t=async d=>{let p=await s.rewrite(d.userMessage,d.conversationMessages,d.lastSubagents),h=d.overrideLang||p.language||"";return{rewrite:p,effectiveQuery:p.rewrittenQuery,turnLanguage:h}},n=async d=>{let p=d.rewrite,h=p.isFollowUp?d.effectiveQuery:d.userMessage,f=await s.searchKB(h),m=s.formatKBContext(f),g=await s.tryAnswerFromKB(d.userMessage,f,m,d.messageId);return g?{kbContext:m,response:{...g,messageId:d.messageId,rewrite:p}}:{kbContext:m}},r=async d=>({decision:await s.route(d.effectiveQuery,d.conversationMessages,s.subagentCards(),d.lastSubagents)}),o=async d=>{let p=await s.answerDirectly(d.effectiveQuery,d.conversationMessages,d.kbContext,d.messageId,d.rewrite?.needsWebSearch??!1),h=d.decision??{analysis:d.rewrite?.reasoning??"",assignments:[]};return{response:{...p,messageId:d.messageId,routerDecision:h,rewrite:d.rewrite}}},a=async d=>{let p=await s.runSubagent(d.assignment,d.conversationMessages,d.turnLanguage);return{subResults:[{i:d.assignmentIndex,result:p}]}},i=async d=>{let p=d.subResults.slice().sort((k,T)=>k.i-T.i).map(k=>k.result);s.persistToolMessages(p);let h=s.mergeTrace(p),f=await s.synthesise(d.userMessage,h,s.synthesiserHistory(),d.turnLanguage||void 0),m=ar(f,p),g=p.map(k=>k.subagentName),y=s.collectUiActions(p,d.turnLanguage||null),b=s.collectActionButtons(p,d.turnLanguage||null);return{response:{...await s.finaliseAnswer({userMessage:d.userMessage,answer:m,subagents:g,uiActions:y,actionButtons:b,messageId:d.messageId}),messageId:d.messageId,trace:h,routerDecision:d.decision,subagentResults:p,rewrite:d.rewrite,...y.length>0?{uiActions:y}:{},...b.length>0?{actionButtons:b}:{}}}},l=async d=>{let p=(d.rewrite?.mentionedChain||String(s.connectedChain()??"")).trim(),h=new Map(s.subagentCards().map(b=>[b.name,b.domain])),f=(d.decision?.assignments??[]).filter(b=>b.subagent!=="ai-agent"),g=f.length>0&&f.every(b=>h.get(b.subagent)==="pool")?me():void 0;return{response:{...await s.answerUnsupportedChain(p,d.turnLanguage,d.messageId,g),messageId:d.messageId,routerDecision:d.decision,rewrite:d.rewrite}}},c=d=>d.response?B.END:d.rewrite?.aboutAssistant?"direct":"route",u=d=>{let p=d.decision?.assignments??[];if(p.length===0)return"direct";let h=p.some(m=>m.subagent!=="ai-agent"),f=(d.rewrite?.mentionedChain||s.connectedChain()||"").trim();return h&&f!==""&&!_e(f)?"unsupportedChain":p.map((m,g)=>new B.Send("subagent",{...d,assignment:m,assignmentIndex:g}))};return new B.StateGraph(Fd).addNode("setup",e).addNode("contextualize",t).addNode("kb",n).addNode("route",r).addNode("direct",o).addNode("subagent",a).addNode("synthesize",i).addNode("unsupportedChain",l).addEdge(B.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",c,["route","direct",B.END]).addConditionalEdges("route",u,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",B.END).addEdge("direct",B.END).addEdge("subagent","synthesize").addEdge("synthesize",B.END).compile()}var li=require("js-sha3");function
|
|
1116
|
+
[QueryRewriter] (${b}ms)`),console.log(` original : "${e}"`),console.log(` rewritten : "${y.rewrittenQuery}"${w?"":" (unchanged)"}`),console.log(` followUp : ${y.isFollowUp} topicChanged: ${y.topicChanged}`),y.reasoning&&console.log(` reasoning : ${y.reasoning}`),console.log(` language : ${y.language}`),console.log(` webSearch : ${y.needsWebSearch}`),console.log(` aboutSelf : ${y.aboutAssistant}`)}return y}parseJSON(e){let t=e.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*/,"").replace(/```\s*$/,""));let n=t.match(/\{[\s\S]*\}/);return n&&(t=n[0]),JSON.parse(t)}};var B=require("@langchain/langgraph");function sr(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var si="\\s*/\\s*";function is(s){return[s.symA.toLowerCase(),s.symB.toLowerCase()].sort().join("|")}function ai(s){return`(${s.symA}${si}${s.symB}|${s.symB}${si}${s.symA})`}function Nd(s){let e=sr(String(s));return`(?<![\\d.])${Number.isInteger(s)?`${e}(?:\\.0+)?`:`${e}0*`}`}function ls(s,e,t,n){return`${s.slice(0,e)}[${t}](${n})${s.slice(e+t.length)}`}function Rd(s,e){let n=new RegExp(`(?<!\\[)\\b${ai(e)}\\b`,"i").exec(s);return n?ls(s,n.index,n[1]??n[0],e.url):null}function Ud(s,e){if(e.feePercent==null)return null;let n=new RegExp(`(?<!\\[)\\b${ai(e)}\\b[^\\n\\]]{0,16}?${Nd(e.feePercent)}\\s*%`,"i").exec(s);return n?ls(s,n.index,n[1]??"",e.url):null}var Id=s=>{let e=[],t=n=>{if(!n||typeof n!="object")return;let r=n,o=typeof r.uniswapUrl=="string"?r.uniswapUrl:void 0,a=r.token0?.symbol,i=r.token1?.symbol;if(o&&typeof a=="string"&&a&&typeof i=="string"&&i){let l=r.feeTierPercent;e.push({url:o,symA:sr(a),symB:sr(i),feePercent:typeof l=="number"&&Number.isFinite(l)?l:void 0})}};t(s),t(s.pool);for(let n of["pools","candidates"]){let r=s[n];Array.isArray(r)&&r.forEach(t)}return e},Ld=[Id],Dd=s=>{let e=[],t=s.marketplaceLinks;if(Array.isArray(t))for(let r of t){if(!r||typeof r!="object")continue;let{label:o,url:a}=r;typeof o=="string"&&o&&typeof a=="string"&&a&&e.push({url:a,label:o})}let n=typeof s.amazonBuyUrl=="string"?s.amazonBuyUrl:void 0;return n&&e.push({url:n,label:"Amazon"}),e},Od=[Dd];function Md(s,e){let n=new RegExp(`(?<!\\[)\\b${sr(e.label)}\\b`,"i").exec(s);return n?ls(s,n.index,n[0],e.url):null}function ar(s,e){if(!s)return s;let t=[],n=[];for(let i of e)for(let l of i.toolResults){if(!l.success||!l.data||typeof l.data!="object")continue;let c=l.data;for(let u of Ld)t.push(...u(c));for(let u of Od)n.push(...u(c))}if(t.length===0&&n.length===0)return s;let r=new Map;for(let i of t)r.set(is(i),(r.get(is(i))??0)+1);let o=s,a=new Set;for(let i of t){if(a.has(i.url))continue;if(o.includes(i.url)){a.add(i.url);continue}let c=(r.get(is(i))??0)>1?Ud(o,i):Rd(o,i);c&&(o=c,a.add(i.url))}for(let i of n){if(a.has(i.url))continue;if(o.includes(i.url)){a.add(i.url);continue}let l=Md(o,i);l&&(o=l,a.add(i.url))}return o}var xe=s=>({reducer:(e,t)=>t,default:s}),Fd=B.Annotation.Root({userMessage:(0,B.Annotation)(),overrideLang:(0,B.Annotation)(xe(()=>"")),conversationMessages:(0,B.Annotation)(xe(()=>[])),lastSubagents:(0,B.Annotation)(xe(()=>[])),messageId:(0,B.Annotation)(xe(()=>"")),rewrite:(0,B.Annotation)(xe(()=>null)),effectiveQuery:(0,B.Annotation)(xe(()=>"")),turnLanguage:(0,B.Annotation)(xe(()=>"")),kbContext:(0,B.Annotation)(xe(()=>"")),decision:(0,B.Annotation)(xe(()=>null)),assignment:(0,B.Annotation)(xe(()=>null)),assignmentIndex:(0,B.Annotation)(xe(()=>0)),subResults:(0,B.Annotation)({reducer:(s,e)=>s.concat(e),default:()=>[]}),response:(0,B.Annotation)(xe(()=>null))});function ii(s){let e=async d=>{s.addUserMessage(d.userMessage),s.needsSummary()&&await s.compactHistory();let p=s.conversationForTurn(),h=s.lastAssistantSubagents(p);return s.debug&&h.length>0&&console.log(`[AgentCore] previous turn handled by: ${h.join(", ")}`),{conversationMessages:p,lastSubagents:h,messageId:s.generateMessageId()}},t=async d=>{let p=await s.rewrite(d.userMessage,d.conversationMessages,d.lastSubagents),h=d.overrideLang||p.language||"";return{rewrite:p,effectiveQuery:p.rewrittenQuery,turnLanguage:h}},n=async d=>{let p=d.rewrite,h=p.isFollowUp?d.effectiveQuery:d.userMessage,f=await s.searchKB(h),m=s.formatKBContext(f),g=await s.tryAnswerFromKB(d.userMessage,f,m,d.messageId);return g?{kbContext:m,response:{...g,messageId:d.messageId,rewrite:p}}:{kbContext:m}},r=async d=>({decision:await s.route(d.effectiveQuery,d.conversationMessages,s.subagentCards(),d.lastSubagents)}),o=async d=>{let p=await s.answerDirectly(d.effectiveQuery,d.conversationMessages,d.kbContext,d.messageId,d.rewrite?.needsWebSearch??!1),h=d.decision??{analysis:d.rewrite?.reasoning??"",assignments:[]};return{response:{...p,messageId:d.messageId,routerDecision:h,rewrite:d.rewrite}}},a=async d=>{let p=await s.runSubagent(d.assignment,d.conversationMessages,d.turnLanguage);return{subResults:[{i:d.assignmentIndex,result:p}]}},i=async d=>{let p=d.subResults.slice().sort((k,T)=>k.i-T.i).map(k=>k.result);s.persistToolMessages(p);let h=s.mergeTrace(p),f=await s.synthesise(d.userMessage,h,s.synthesiserHistory(),d.turnLanguage||void 0),m=ar(f,p),g=p.map(k=>k.subagentName),y=s.collectUiActions(p,d.turnLanguage||null),b=s.collectActionButtons(p,d.turnLanguage||null);return{response:{...await s.finaliseAnswer({userMessage:d.userMessage,answer:m,subagents:g,uiActions:y,actionButtons:b,messageId:d.messageId}),messageId:d.messageId,trace:h,routerDecision:d.decision,subagentResults:p,rewrite:d.rewrite,...y.length>0?{uiActions:y}:{},...b.length>0?{actionButtons:b}:{}}}},l=async d=>{let p=(d.rewrite?.mentionedChain||String(s.connectedChain()??"")).trim(),h=new Map(s.subagentCards().map(b=>[b.name,b.domain])),f=(d.decision?.assignments??[]).filter(b=>b.subagent!=="ai-agent"),g=f.length>0&&f.every(b=>h.get(b.subagent)==="pool")?me():void 0;return{response:{...await s.answerUnsupportedChain(p,d.turnLanguage,d.messageId,g),messageId:d.messageId,routerDecision:d.decision,rewrite:d.rewrite}}},c=d=>d.response?B.END:d.rewrite?.aboutAssistant?"direct":"route",u=d=>{let p=d.decision?.assignments??[];if(p.length===0)return"direct";let h=p.some(m=>m.subagent!=="ai-agent"),f=(d.rewrite?.mentionedChain||s.connectedChain()||"").trim();return h&&f!==""&&!_e(f)?"unsupportedChain":p.map((m,g)=>new B.Send("subagent",{...d,assignment:m,assignmentIndex:g}))};return new B.StateGraph(Fd).addNode("setup",e).addNode("contextualize",t).addNode("kb",n).addNode("route",r).addNode("direct",o).addNode("subagent",a).addNode("synthesize",i).addNode("unsupportedChain",l).addEdge(B.START,"setup").addEdge("setup","contextualize").addEdge("contextualize","kb").addConditionalEdges("kb",c,["route","direct",B.END]).addConditionalEdges("route",u,["direct","subagent","unsupportedChain"]).addEdge("unsupportedChain",B.END).addEdge("direct",B.END).addEdge("subagent","synthesize").addEdge("synthesize",B.END).compile()}var li=require("js-sha3");function Kn(){let s=Date.now().toString(16),e=Math.floor(Math.random()*65535).toString(16).padStart(4,"0");return(s+e).slice(-8)}var qd="You are a helpful AI assistant for crypto and DeFi. Answer the user accurately and concisely. Respond in the same language as the user.",Bd=`
|
|
1117
1117
|
|
|
1118
1118
|
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.`,$d=`
|
|
1119
1119
|
|
|
1120
|
-
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.`,ir=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){this.secretKey=e.secretKey??"",this.ownGeminiKey=!!e.llm?.apiKey?.trim(),kr(e.rpcUrls),Eo(e.excludeChains),this.llm=new J(e.llm),this.registry=new
|
|
1120
|
+
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.`,ir=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){this.secretKey=e.secretKey??"",this.ownGeminiKey=!!e.llm?.apiKey?.trim(),kr(e.rpcUrls),Eo(e.excludeChains),this.llm=new J(e.llm),this.registry=new Nt,this.history=new Hn(e.maxHistoryMessages??50),this.summarizer=new Vn(this.llm),this.synthesizer=new Gn(this.llm),this.systemPrompt=(e.systemPrompt??qd)+Bd+$d,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 Wn(e.knowledgeBase),this.kbEntries.setLLM(this.llm);let t=e.vectorKB;t?.enabled?(t.provider?this.kb=t.provider:(this.vectorKB=new it({url:t.url,token:t.token,namespace:t.namespace,minScore:t.minScore,defaultTopK:t.defaultTopK,debug:this.debug}),this.kb=this.vectorKB,this.autoIngestEnabled=t.autoIngest===!0),this.debug&&console.log(`[AgentCore] vector KB enabled (${t.provider?"custom provider":"Upstash"}`+(t.namespace?`, ns=${t.namespace}`:"")+")")):this.kb=this.kbEntries;let n=e.kbAnswerThreshold;if(typeof n=="number"?this.kbAnswerThreshold=n:t?.enabled&&!t.provider?this.kbAnswerThreshold=t.minScore??1.3:this.kbAnswerThreshold=.8,this.debug&&console.log(`[AgentCore] kbAnswerThreshold = ${this.kbAnswerThreshold}`),e.moralis!==!1){let u=typeof e.moralis=="object"?e.moralis:void 0;this.registry.register(new Ht(u)),this.registry.register(new Ot({...u,llm:e.llm})),this.registry.register(new Vt(u)),this.registry.register(new Wt(u)),this.registry.register(new Yt(u)),this.registry.register(new Mt(u)),this.registry.register(new Gt(u)),this.registry.register(new Kt(u)),this.registry.register(new Qt(u)),this.registry.register(new zt(u)),this.registry.register(new Xt(u)),this.registry.register(new jt(u)),this.registry.register(new Bt(u)),this.registry.register(new $t(u)),this.registry.register(new Ft(u)),this.registry.register(new qt(u)),this.registry.register(new on(u))}if(e.lending!==!1){let u=typeof e.lending=="object"?e.lending:void 0;this.registry.register(new Zt(u)),this.registry.register(new en(u)),this.registry.register(new tn({...u,moralis:typeof e.moralis=="object"?e.moralis:void 0}))}this.registry.register(new rn(e.llm)),this.registry.register(new sn(e.llm)),e.subagents?.nfc===!0&&(this.registry.register(new ln(e.llm)),this.registry.register(new cn(e.llm))),this.registry.register(new un(e.llm));let r=e.subagents?.["pool-subgraph"]===!0,o=r?e.subagents?.pool===!0:e.subagents?.pool!==!1;if(o&&e.uniswap!==!1){let u=typeof e.uniswap=="object"?e.uniswap:void 0,d=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new bn(u,d)),this.registry.register(new wn(u)),this.registry.register(new kn(u)),this.registry.register(new Tn(u)),this.registry.register(new Sn(u));let p=u?{isProduction:u.isProduction}:void 0;this.registry.register(new vn({baseUrl:u?.baseUrl,pool:p,minProvideUsd:u?.minProvideUsd})),this.registry.register(new An({pool:p})),this.registry.register(new Pn),this.registry.register(new xn)}if((o||r)&&!this.registry.has("pool-fallback-ai")&&this.registry.register(new dn(e.llm)),r&&e.subgraph!==!1){let u=typeof e.subgraph=="object"?e.subgraph:void 0;this.registry.register(new Cn(u)),this.registry.register(new _n(u)),this.registry.register(new En(u)),this.registry.register(new Nn(u)),this.registry.register(new Rn(u)),this.registry.register(new Un(u)),this.registry.register(new In(u))}if(e.subagents?.["wallet-action"]!==!1){let u=e.moralis===!1?void 0:typeof e.moralis=="object"?e.moralis:{},d=e.noFormTools,p=h=>zo(this.registry,h,d);p(new On(u)),p(new Mn(u)),p(new $n(u)),p(new Fn(u)),p(new qn(u,{debug:this.debug})),p(new Bn(u,{debug:this.debug}))}this.router=new Yn(this.llm,{debug:this.debug}),this.rewriter=new rr(this.llm,{debug:this.debug});let i=typeof e.subgraph=="object"?e.subgraph:void 0,l=e.lending===!1&&e.subagents?.lending!==!0?{...e.subagents,lending:!1}:e.subagents,c=or(this.llm,this.registry,{maxToolCalls:e.maxIterations??5,debug:this.debug,linkAddLiquidity:i?.linkAddLiquidity},l);this.subagents=new Map(c.map(u=>[u.name,u])),this.chatGraph=ii(this.createGraphHost()),this.historyReady=this.loadHistory()}registerTool(e){this.registry.register(e)}registerTools(e){for(let t of e)this.registry.register(t)}unregisterTool(e){return this.registry.unregister(e)}listTools(){return this.registry.listNames()}async invokeTool(e,t,n){if(this.assertLicense(),await this.loadHistory(),!this.registry.get(e))return{answer:`Unknown tool: "${e}".`,messageId:Kn()};this.debug&&console.log(`[AgentCore] invokeTool ${e} ${JSON.stringify(t)}`);let o=n?.userMessage??`[invoke ${e}]`;this.history.add({role:"user",content:o,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=Kn(),u=a.success&&a.ui?[this.stampLanguage(a.ui,null)]:[],d={role:"assistant",content:l,timestamp:Date.now(),subagents:["direct-invoke"],messageId:c};return u.length>0&&(d.uiActions=u),this.history.add(d),await this.persistHistory(),{answer:l,messageId:c,...u.length>0?{uiActions:u}:{}}}async runTool(e,t,n){this.assertLicense(),await this.loadHistory();let r=Kn();if(!this.registry.has(e))return{answer:`Unknown tool: "${e}".`,messageId:r};this.debug&&console.log(`[AgentCore] runTool ${e} ${JSON.stringify(t)}`);let o=n?.userMessage?.trim()||`[run ${e}]`,a=typeof n?.language=="string"&&n.language.trim()?n.language.trim():null,i=Array.from(this.subagents.values()).filter(h=>h.ownsTool(e)).map(h=>h.name),l=i.length>0?i:["direct"],c=new AbortController;this.currentAbortController=c;let{signal:u,cleanup:d}=_r(c,n?.signal);this.llm.setRequestSignal?.(u),Xn(u);let p=this.history.serialise();try{this.history.add({role:"user",content:o,timestamp:Date.now()});let h=await this.registry.execute(e,t,{...this.userContext,query:o});Zn(u);let f=h.success?JSON.stringify(h.data):`Error: ${h.error}`,m=Date.now(),g=[{subagentName:l[0],steps:[{phase:"act",content:`Calling tool: ${e}`,toolCall:{toolName:e,args:t},timestamp:m},{phase:"observe",content:f,toolResult:h,timestamp:m}],finalAnswer:"",toolResults:[h],toolMessages:[]}],y=this.mergeTrace(g),b=await this.synthesizer.synthesise(o,y,this.synthesiserHistory(),a??void 0),w=ar(b,g),k=this.collectUiActions(g,a),T=this.collectActionButtons(g,a);return{...await this.finaliseAnswer({userMessage:o,answer:w,subagents:l,uiActions:k,actionButtons:T,messageId:r}),messageId:r,trace:y,subagentResults:g,...k.length>0?{uiActions:k}:{},...T.length>0?{actionButtons:T}:{}}}catch(h){throw yt(h)||u.aborted?(this.history.restore(p),new Je):(this.history.restore(p),h)}finally{d(),this.llm.setRequestSignal?.(void 0),Xn(void 0),this.currentAbortController===c&&(this.currentAbortController=null)}}setX402Signer(e){this.x402Signer=e,gs(e?Cr({getPayer:()=>this.userContext?.walletAddress||"",getSigner:()=>this.x402Signer}):null)}async submitX402Payment(e,t,n){this.assertLicense(),await this.loadHistory();let r=Kn(),o=e,a=n?.userQuery||o?.userQuery||"the previous request";this.history.add({role:"user",content:"[x402 payment authorized]",timestamp:Date.now()});let i;try{i=await Pr(x,o,t)}catch(c){let d=`The payment couldn't be completed: ${c instanceof Error?c.message:String(c)}. Please try again.`;return this.history.add({role:"assistant",content:d,timestamp:Date.now(),messageId:r}),await this.persistHistory(),{answer:d,messageId:r}}return{...await this.synthesizeFromPaidData(a,i,r),messageId:r}}async synthesizeFromPaidData(e,t,n){let r=typeof t=="string"?t:JSON.stringify(t),o=this.systemPrompt+this.capabilitiesSummary(),a=`The user's question was: "${e}".
|
|
1121
1121
|
|
|
1122
1122
|
A paid API returned this data:
|
|
1123
1123
|
${r}
|
|
1124
1124
|
|
|
1125
1125
|
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:o,timestamp:0},{role:"user",content:a,timestamp:Date.now()}],void 0,{});return await this.finaliseAnswer({userMessage:e,answer:i.text,messageId:n})}registerSubagent(e){this.subagents.set(e.name,e)}unregisterSubagent(e){return this.subagents.delete(e)}listSubagents(){return Array.from(this.subagents.keys())}setKnowledgeBase(e){this.kbEntries.setEntries(e),this.vectorKBAutoIngested=!1}addKnowledgeBase(e){this.kbEntries.addEntries(e),this.vectorKBAutoIngested=!1}async ingestKnowledgeBase(){if(!this.vectorKB)return{count:0};let e=this.kbEntries.getEntries();if(e.length===0)return{count:0};let t=await this.vectorKB.upsert(e);return this.vectorKBAutoIngested=!0,t}async maybeAutoIngest(e){if(!(!e||!this.vectorKB||this.vectorKBAutoIngested)){if(this.vectorKBAutoIngestPromise)return this.vectorKBAutoIngestPromise;this.vectorKBAutoIngestPromise=(async()=>{try{let{count:t}=await this.ingestKnowledgeBase();this.debug&&t>0&&console.log(`[AgentCore] auto-ingested ${t} KB entr${t===1?"y":"ies"} to vector store`)}catch(t){this.debug&&console.warn("[AgentCore] auto-ingest failed:",t)}finally{this.vectorKBAutoIngestPromise=null}})(),await this.vectorKBAutoIngestPromise}}setUserContext(e){this.userContext={...e}}getUserContext(){return{...this.userContext}}async loadHistory(){if(!this.historyLoaded){if(this.historyLoadingPromise)return this.historyLoadingPromise;this.historyLoadingPromise=this._doLoadHistory(),await this.historyLoadingPromise}}async _doLoadHistory(){if(!this.storage){this.debug&&console.log("[AgentCore] loadHistory: no storage configured"),this.historyLoaded=!0;return}if(!this.persistHistoryEnabled){this.debug&&console.log("[AgentCore] loadHistory: persistHistory disabled \u2014 starting fresh session");try{await this.storage.removeItem(this.storageKey)}catch(e){this.debug&&console.warn("[AgentCore] failed to clear stale history:",e)}this.historyLoaded=!0;return}try{let e=await this.storage.getItem(this.storageKey);if(this.debug&&console.log(`[AgentCore] loadHistory: storage key "${this.storageKey}" ${e?`has ${e.length} chars`:"is empty"}`),e){let t=JSON.parse(e);this.history.restore(t),this.debug&&console.log(`[AgentCore] Restored ${this.history.length} messages from storage`)}}catch(e){this.debug&&console.warn("[AgentCore] Failed to load history from storage:",e)}finally{this.historyLoaded=!0}}async persistHistory(){if(this.storage&&this.persistHistoryEnabled)try{let e=JSON.stringify(this.history.serialise());await this.storage.setItem(this.storageKey,e)}catch(e){this.debug&&console.warn("[AgentCore] Failed to persist history to storage:",e)}}assertLicense(){if(this.licenseChecked)return;if(this.ownGeminiKey){this.licenseChecked=!0;return}let e="d00d67291d3c660a5034b01c0b2afbc8d4ac5552099a04f28a92d75fdb44c188";if(e&&(!this.secretKey||(0,li.sha3_256)(this.secretKey)!==e))throw new Error("AgentCore: invalid or missing secretKey. Pass a valid secretKey to use the Keyring Gemini proxy, or supply your own Gemini key via llm.apiKey to call the Gemini API directly.");this.licenseChecked=!0}async chat(e,t){this.assertLicense();let n=typeof t?.language=="string"&&t.language.trim()?t.language.trim():"";await this.loadHistory(),await this.maybeAutoIngest(this.autoIngestEnabled);let r=Date.now();this.debug&&(console.log(`
|
|
1126
|
-
${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let o=new AbortController;this.currentAbortController=o;let{signal:a,cleanup:i}=_r(o,t?.signal);this.llm.setRequestSignal?.(a),
|
|
1127
|
-
`)),u.response??{answer:"",messageId:
|
|
1126
|
+
${"\u2500".repeat(60)}`),console.log(`[AgentCore] query: "${e}"`));let o=new AbortController;this.currentAbortController=o;let{signal:a,cleanup:i}=_r(o,t?.signal);this.llm.setRequestSignal?.(a),Xn(a);let l=this.history.serialise(),c=this.chatGraph.invoke({userMessage:e,overrideLang:n},{signal:a});this.inFlightTurn=c;let u;try{u=await c}catch(d){throw yt(d)||a.aborted?(this.history.restore(l),new Je):d}finally{i(),this.llm.setRequestSignal?.(void 0),Xn(void 0),this.currentAbortController===o&&(this.currentAbortController=null),this.inFlightTurn===c&&(this.inFlightTurn=null)}return this.debug&&(console.log(`[AgentCore] turn done in ${Date.now()-r}ms total`),console.log(`${"\u2500".repeat(60)}
|
|
1127
|
+
`)),u.response??{answer:"",messageId:Kn()}}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=>ei(e),generateMessageId:()=>Kn(),rewrite:(e,t,n)=>this.rewriter.rewrite(e,t,n),searchKB:e=>this.searchKB(e),formatKBContext:e=>this.formatKBContext(e),tryAnswerFromKB:(e,t,n,r)=>this.tryAnswerFromKB(e,t,n,r),subagentCards:()=>Array.from(this.subagents.values()).map(e=>e.getCard()),route:(e,t,n,r)=>this.router.route(e,t,n,this.userContext,r),connectedChain:()=>this.userContext.chain,answerUnsupportedChain:(e,t,n,r)=>this.answerUnsupportedChain(e,t,n,r),answerDirectly:(e,t,n,r,o)=>this.answerDirectly(e,t,n,r,o),runSubagent:async(e,t,n)=>{let r=this.subagents.get(e.subagent);if(!r)return this.debug&&console.log(`[AgentCore] WARN: subagent "${e.subagent}" not registered`),{subagentName:e.subagent,steps:[],finalAnswer:`Subagent "${e.subagent}" is not registered.`,toolResults:[],toolMessages:[]};let o=Date.now(),a=await r.run({query:e.query,reasoning:e.reasoning,language:n},t,this.userContext);if(this.debug){let i=a.toolResults.map(l=>l.toolName).join(", ")||"\u2014";console.log(`[AgentCore] ${e.subagent} done in ${Date.now()-o}ms | tools: ${i}`)}return a},persistToolMessages:e=>this.persistToolMessages(e),synthesiserHistory:()=>this.synthesiserHistory(),mergeTrace:e=>this.mergeTrace(e),synthesise:(e,t,n,r)=>this.synthesizer.synthesise(e,t,n,r),collectUiActions:(e,t)=>this.collectUiActions(e,t),collectActionButtons:(e,t)=>this.collectActionButtons(e,t),finaliseAnswer:e=>this.finaliseAnswer(e)}}capitalizeFirst(e){if(!e)return e;let t=Array.from(e);return t[0]=t[0].toLocaleUpperCase(),t.join("")}collectActionButtons(e,t){let n=new Map,r=[];for(let o of e)for(let a of o.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}:{}},u=n.get(l);u?c.label.length>u.label.length&&n.set(l,c):(n.set(l,c),r.push(l))}return r.map(o=>n.get(o))}collectUiActions(e,t){let n=[];for(let r of e)for(let o of r.toolResults)o.success&&o.ui&&typeof o.ui=="object"&&typeof o.ui.component=="string"&&n.push(this.stampLanguage(o.ui,t));if(this.debug&&n.length>0){let r=n.map(o=>`${o.component}=${o.language}`).join(", ");console.log(`[AgentCore] uiActions stamped (rewrite.language="${t??""}"): ${r}`)}return n}stampLanguage(e,t){return!t||e.language?e:{...e,language:t}}addUserMessage(e){this.history.add({role:"user",content:e,timestamp:Date.now()})}async searchKB(e){let t=this.vectorKB?await this.vectorKB.search(e,void 0,{applyMinScore:!1}):await this.kb.search(e);if(this.debug)if(t.length===0)console.log(`[AgentCore] KB no hits for "${e}"`);else{let n=t.slice(0,3).map(r=>`${r.score.toFixed(3)} ${this.snippet(r.entry.question,60)}`).join(" | ");console.log(`[AgentCore] KB hits (${t.length}): ${n}`)}return t}snippet(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}formatKBContext(e){let t=e.filter(n=>n.score>=this.kbAnswerThreshold);return t.length===0?"":t.map((n,r)=>`[Reference ${r+1}]
|
|
1128
1128
|
Q: ${n.entry.question}
|
|
1129
1129
|
A: ${n.entry.answer}`).join(`
|
|
1130
1130
|
|
|
@@ -1170,7 +1170,7 @@ REFERENCE MATERIAL:
|
|
|
1170
1170
|
`+n+`
|
|
1171
1171
|
---`:this.systemPrompt)+this.capabilitiesSummary()+a+`
|
|
1172
1172
|
|
|
1173
|
-
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=Be(t),u=[{role:"system",content:l,timestamp:0},...c,{role:"user",content:e,timestamp:Date.now()}],d=await this.llm.chat(u,void 0,{googleSearch:o});return await this.finaliseAnswer({userMessage:e,answer:d.text,messageId:r})}async answerUnsupportedChain(e,t,n,r){this.debug&&console.log(`[AgentCore] connected chain "${e}" is not supported \u2192 short-circuit with notice`);let o=(t||"").trim(),a=r&&r.trim()||
|
|
1173
|
+
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=Be(t),u=[{role:"system",content:l,timestamp:0},...c,{role:"user",content:e,timestamp:Date.now()}],d=await this.llm.chat(u,void 0,{googleSearch:o});return await this.finaliseAnswer({userMessage:e,answer:d.text,messageId:r})}async answerUnsupportedChain(e,t,n,r){this.debug&&console.log(`[AgentCore] connected chain "${e}" is not supported \u2192 short-circuit with notice`);let o=(t||"").trim(),a=r&&r.trim()||It,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. `+(o?`Reply in BCP-47 language "${o}".`:"Reply in the same language the user has been using.")+" Do NOT mention tools or internal implementation details.",timestamp:0},{role:"user",content:"Is my currently connected network supported?",timestamp:Date.now()}],c=(await this.llm.chat(i)).text?.trim()||`Your currently connected network is not supported yet. Supported networks: ${a}.`;return await this.finaliseAnswer({userMessage:`[unsupported chain: ${e}]`,answer:c,messageId:n})}synthesiserHistory(){let e=this.history.getConversation(),t=e.length>0&&e[e.length-1].role==="user"?e.slice(0,-1):e;return Be(t)}mergeTrace(e){let t=[];for(let r of e)t.push({phase:"think",content:`[${r.subagentName}] begin`,timestamp:Date.now()}),t.push(...r.steps),t.push({phase:"observe",content:`[${r.subagentName}] answer: ${r.finalAnswer}`,timestamp:Date.now()});let n=e.map(r=>`[${r.subagentName}] ${r.finalAnswer}`).join(`
|
|
1174
1174
|
|
|
1175
1175
|
`);return{steps:t,finalAnswer:n}}async finaliseAnswer(e){let{answer:t,subagents:n,uiActions:r,actionButtons:o,messageId:a}=e??{},i={role:"assistant",content:t,timestamp:Date.now()};return n&&n.length>0&&(i.subagents=n),r&&r.length>0&&(i.uiActions=r),o&&o.length>0&&(i.actionButtons=o),a&&(i.messageId=a),this.history.add(i),await this.persistHistory(),{answer:t,...o&&o.length>0?{actionButtons:o}:{}}}getHistory(){return this.history.getAllFull()}getDisplayHistory(){return this.history.getAllFull().filter(e=>!(e.role!=="user"&&e.role!=="assistant"||e._intermediate||e.role==="assistant"&&!e.content?.trim()))}async clearHistory(){if(this.historyLoadingPromise)try{await this.historyLoadingPromise}catch{}if(this.inFlightTurn)try{await this.inFlightTurn}catch{}this.history.clear(),this.historyLoaded=!0,this.historyLoadingPromise=null,await this.persistHistory()}restoreHistory(e){this.history.restore(e)}serialiseHistory(){return this.history.serialise()}async compactHistory(){this.debug&&console.log("[AgentCore] Summarizing conversation history\u2026");let e=this.history.getAll(),t=6,n=0,r=e.length;for(let p=e.length-1;p>=0;p--)if(e[p].role==="user"&&(n++,n>=t)){r=p;break}let o=e.slice(r),a=Za(o,o.length),i=e.length-a.length,l=Be(e.slice(0,i)),c=this.history.getSummary(),u=[];c&&u.push({role:"user",content:`[Previous context summary]: ${c}`,timestamp:0}),u.push(...l);let d=await this.summarizer.summarize(u);this.history.compactWith(d,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 ui=require("js-sha3"),Hd="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.",ci='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.',lr=class{llm;debug;ecosystem;secretKey;ownGeminiKey;licenseChecked=!1;constructor(e={}){this.llm=e.provider??new J({temperature:.5,...e.llm}),this.debug=e.debug??!1,this.ecosystem=e.ecosystemContext?.trim()||Hd,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,ui.sha3_256)(this.secretKey)!==e))throw new Error("WebsiteTrustKeyringAgent: invalid or missing secretKey. Pass a valid secretKey to use the Keyring Gemini proxy, or supply your own Gemini key via llm.apiKey to call the Gemini API directly.");this.licenseChecked=!0}async chat(e){this.assertLicense();let t=(e?.url??"").trim();if(!t)throw new Error("WebsiteTrustKeyringAgent.chat: `url` is required");let n=this.normalizeSite(t),r=e.language?.trim()||"English",o=e.signal;try{if(e.isMarkOfficial){let{description:h,keyFeatures:f}=await this.describeOfficial(t,o),{answer:m,keyFeatures:g}=await this.present(n,{isPhishing:!1,trusted:!0,description:h,reasons:[],keyFeatures:f},r,o),y={currentSite:t,isPhishing:!1};return g.length>0&&(y.keyFeatures=g),{answer:m,extraData:y}}let a=await this.investigate(t,n,o),i=this.buildVerdict(n,a),l=a.keyFeatures;!i.isPhishing&&l.length===0&&(l=await this.gatherKeyFeatures(t,o)),this.debug&&(console.log("[WebsiteTrustKeyringAgent] domain:",n),console.log("[WebsiteTrustKeyringAgent] investigation:",a),console.log("[WebsiteTrustKeyringAgent] verdict:",i),console.log("[WebsiteTrustKeyringAgent] keyFeaturesEvidence:",l));let{answer:c,reasons:u,keyFeatures:d}=await this.present(n,{isPhishing:i.isPhishing,description:a.description,copiedSite:i.copiedSite,reasons:i.reasons,keyFeatures:l},r,o),p={currentSite:t,isPhishing:i.isPhishing};return i.copiedSite&&(p.copiedSite=i.copiedSite),i.isPhishing&&u.length>0&&(p.reasons=u),!i.isPhishing&&d.length>0&&(p.keyFeatures=d),{answer:c,extraData:p}}catch(a){throw new Error(`WebsiteTrustKeyringAgent.chat failed: ${a instanceof Error?a.message:String(a)}`,{cause:a})}}buildVerdict(e,t){let n=t.officialDomain,r=n?t.affiliatedDomains.filter(f=>!this.looksLikeSquatOf(f,n)):t.affiliatedDomains,o=[t.officialDomain,...r].filter(f=>!!f),a=o.length>0?o.some(f=>this.isSameRegistrableDomain(e,f)):t.exactMatchOfficial,l=(t.resemblesBrand||this.carriesBrandName(e,t.officialDomain,t.brand))&&!a&&t.brandIsWellKnown&&(o.length>0||!t.hasOwnLegitPresence),u=!(a||t.hasOwnLegitPresence&&!l)&&t.scamReports.length>0,d=l||u;if(!d)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.`)}u&&p.push(...t.scamReports);let h=l?t.officialUrl??t.officialDomain??t.brand:void 0;return{isPhishing:d,copiedSite:h,reasons:this.dedupe(p)}}async investigate(e,t,n){let r=`Domain under test (analyze EXACTLY as written \u2014 do NOT autocorrect): ${t}
|
|
1176
1176
|
URL: ${e}
|
|
@@ -1238,4 +1238,4 @@ LANGUAGE (MANDATORY): write "answer", every "reasons" item AND every "keyFeature
|
|
|
1238
1238
|
|
|
1239
1239
|
Return ONLY this JSON: { "answer": string, "reasons": string[], "keyFeatures": string[] }`,c=await this.askJson(l,{signal:r,googleSearch:!1,system:this.presentationSystem(o),maxRetries:2,maxOutputTokens:1536}),u=this.cleanStr(c?.answer)??(t.description||e),d=this.cleanStrArray(c?.reasons),p=this.cleanStrArray(c?.keyFeatures);return{answer:u,reasons:d.length>0?d.slice(0,5):t.reasons.slice(0,5),keyFeatures:a?(p.length>0?p:t.keyFeatures).slice(0,5):[]}}languageLabel(e){let t={vi:"Vietnamese",en:"English",ja:"Japanese",ko:"Korean",zh:"Chinese","zh-cn":"Simplified Chinese","zh-tw":"Traditional Chinese",th:"Thai",id:"Indonesian",ms:"Malay",fr:"French",es:"Spanish",de:"German",pt:"Portuguese",ru:"Russian",hi:"Hindi",ar:"Arabic"},n=e.trim().toLowerCase();return t[n]??t[n.split("-")[0]]??e}presentationSystem(e){return`You are a senior web-security analyst writing directly for an end user. ABSOLUTE REQUIREMENT: write EVERY word of natural-language output in ${e} \u2014 every sentence and every list item. Even though your source material, the domain and brand names may be in other languages, the prose you produce MUST be entirely in ${e}; keep domain names, URLs and brand names verbatim. Reply with a SINGLE valid JSON object and NOTHING else \u2014 no markdown fences, no commentary.`}gatherSystem(){return`${this.ecosystem}
|
|
1240
1240
|
|
|
1241
|
-
${ci}`}async askJson(e,t={}){let{signal:n,googleSearch:r=!0,system:o=ci,maxRetries:a=2,maxOutputTokens:i,thinkingBudget:l}=t,c=Date.now(),u=[{role:"system",content:o,timestamp:c},{role:"user",content:e,timestamp:c}],d=await this.llm.chat(u,void 0,{googleSearch:r,maxRetries:a,maxOutputTokens:i,thinkingBudget:l,signal:n}),p=this.parseJson(d.text?.trim()??"");return this.debug&&!p&&console.log("[WebsiteTrustKeyringAgent] unparseable step reply:",(d.text??"").slice(0,200)),p}normalizeSite(e){try{let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`https://${e}`,n=new URL(t).hostname||e;return this.decodeIdn(n)}catch{return e}}toHost(e){return this.normalizeSite(e.trim()).toLowerCase().replace(/^www\./,"")}decodeIdn(e){return e.includes("xn--")?e.split(".").map(t=>t.startsWith("xn--")?this.punycodeDecodeLabel(t.slice(4)):t).join("."):e}punycodeDecodeLabel(e){let c=(d,p,h)=>{d=h?Math.floor(d/700):d>>1,d+=Math.floor(d/p);let f=0;for(;d>455;)d=Math.floor(d/35),f+=36;return f+Math.floor(36*d/(d+38))},u=d=>d-48<10?d-22:d-65<26?d-65:d-97<26?d-97:36;try{let d=[],p=e.lastIndexOf("-");for(let y=0;y<Math.max(0,p);y++){let b=e.charCodeAt(y);if(b>=128)return e;d.push(b)}let h=0,f=128,m=72,g=p<0?0:p+1;for(;g<e.length;){let y=h,b=1;for(let k=36;;k+=36){if(g>=e.length)return e;let T=u(e.charCodeAt(g++));if(T>=36)return e;h+=T*b;let P=k<=m?1:k>=m+26?26:k-m;if(T<P)break;b*=36-P}let w=d.length+1;m=c(h-y,w,y===0),f+=Math.floor(h/w),h%=w,d.splice(h,0,f),h++}return String.fromCodePoint(...d)}catch{return e}}isSameRegistrableDomain(e,t){let n=this.toHost(e),r=this.toHost(t);return!n||!r?!1:n===r||n.endsWith(`.${r}`)}alnum(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}hostLabels(e){return this.toHost(e).split(".").map(t=>this.alnum(t)).filter(Boolean)}brandCore(e){return this.hostLabels(e)[0]??""}editDistance(e,t){let n=e.length,r=t.length;if(!n)return r;if(!r)return n;let o=Array.from({length:r+1},(a,i)=>i);for(let a=1;a<=n;a++){let i=[a];for(let l=1;l<=r;l++){let c=e[a-1]===t[l-1]?0:1;i[l]=Math.min(o[l]+1,i[l-1]+1,o[l-1]+c)}o=i}return o[r]}isNearMiss(e,t){if(!e||!t||e===t)return!1;let n=Math.max(e.length,t.length);if(n<4||Math.abs(e.length-t.length)>2)return!1;let r=this.editDistance(e,t);return r>=1&&r<=(n>=8?2:1)}carriesBrandName(e,t,n){let r=this.alnum(this.toHost(e));if(!r)return!1;let o=this.hostLabels(e);return[t?this.brandCore(t):"",this.alnum(n??"")].filter(i=>i.length>=4).some(i=>r.includes(i)||o.some(l=>this.isNearMiss(l,i)))}looksLikeSquatOf(e,t){if(this.isSameRegistrableDomain(e,t))return!1;let n=this.brandCore(t);if(n.length<4)return!1;let r=this.hostLabels(e);return r.includes(n)?!1:r.some(o=>this.isNearMiss(o,n)||o.length>n.length&&o.includes(n))}describeLookAlike(e,t){let n=this.toHost(e),r=this.toHost(t);if(!n||!r||n===r)return;if(/[^\u0020-\u007E]/.test(n))return`The address "${n}" uses look-alike (non-standard) characters to imitate the official ${r}; to the eye it reads the same, but it is a different address.`;let o=n.lastIndexOf("."),a=r.lastIndexOf(".");if(o>0&&a>0){let c=n.slice(0,o),u=r.slice(0,a),d=n.slice(o+1),p=r.slice(a+1);if(c===u&&d!==p)return`The address keeps the official name but changes the ending from ".${p}" to ".${d}" (${n} vs ${r}) \u2014 a look-alike that is easy to miss at a glance.`}let i=this.brandCore(r),l=this.hostLabels(n).find(c=>this.isNearMiss(c,i));if(l){let c=this.editDistance(l,i);return`The address "${n}" is a near-copy of the official ${r} \u2014 its name differs by only ${c} letter${c>1?"s":""} ("${l}" vs "${i}"), a typo that is easy to overlook.`}if(i.length>=4&&this.alnum(n).includes(i))return`The address "${n}" reuses the "${i}" name with extra text added to look affiliated with the official ${r}, but it is a different, unofficial domain.`}parseJson(e){if(!e)return null;let t=e.replace(/```(?:json)?/gi,"").trim(),n=t.indexOf("{"),r=t.lastIndexOf("}");if(n===-1||r===-1||r<=n)return null;try{return JSON.parse(t.slice(n,r+1))}catch{return null}}cleanStr(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;let n=t.toLowerCase();if(!(n==="null"||n==="none"||n==="n/a"||n==="undefined"))return t}cleanStrArray(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(/\r?\n|(?:^|\s)[-•]\s+/):[],n=[];for(let r of t){let o=this.coerceToStr(r);o&&n.push(o)}return n}coerceToStr(e){if(typeof e=="string")return this.cleanStr(e);if(!e||typeof e!="object")return;let t=e,n=this.cleanStr(t.feature)??this.cleanStr(t.name)??this.cleanStr(t.title),r=this.cleanStr(t.description)??this.cleanStr(t.detail)??this.cleanStr(t.text)??this.cleanStr(t.value);return n&&r?n===r?n:`${n} \u2014 ${r}`:n||r?n??r:Object.values(t).map(a=>this.cleanStr(a)).filter(a=>!!a).join(" \u2014 ")||void 0}dedupe(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}};var Vd=new Set(["spark","spark-ethereum","morpho-v2"]);function di(s){return!!s&&Vd.has(s)}var pi=s=>{if(s==null||s==="")return null;let e=Number(s);return!Number.isInteger(e)||e<0||e>36?null:e};function mi(s){
|
|
1241
|
+
${ci}`}async askJson(e,t={}){let{signal:n,googleSearch:r=!0,system:o=ci,maxRetries:a=2,maxOutputTokens:i,thinkingBudget:l}=t,c=Date.now(),u=[{role:"system",content:o,timestamp:c},{role:"user",content:e,timestamp:c}],d=await this.llm.chat(u,void 0,{googleSearch:r,maxRetries:a,maxOutputTokens:i,thinkingBudget:l,signal:n}),p=this.parseJson(d.text?.trim()??"");return this.debug&&!p&&console.log("[WebsiteTrustKeyringAgent] unparseable step reply:",(d.text??"").slice(0,200)),p}normalizeSite(e){try{let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?e:`https://${e}`,n=new URL(t).hostname||e;return this.decodeIdn(n)}catch{return e}}toHost(e){return this.normalizeSite(e.trim()).toLowerCase().replace(/^www\./,"")}decodeIdn(e){return e.includes("xn--")?e.split(".").map(t=>t.startsWith("xn--")?this.punycodeDecodeLabel(t.slice(4)):t).join("."):e}punycodeDecodeLabel(e){let c=(d,p,h)=>{d=h?Math.floor(d/700):d>>1,d+=Math.floor(d/p);let f=0;for(;d>455;)d=Math.floor(d/35),f+=36;return f+Math.floor(36*d/(d+38))},u=d=>d-48<10?d-22:d-65<26?d-65:d-97<26?d-97:36;try{let d=[],p=e.lastIndexOf("-");for(let y=0;y<Math.max(0,p);y++){let b=e.charCodeAt(y);if(b>=128)return e;d.push(b)}let h=0,f=128,m=72,g=p<0?0:p+1;for(;g<e.length;){let y=h,b=1;for(let k=36;;k+=36){if(g>=e.length)return e;let T=u(e.charCodeAt(g++));if(T>=36)return e;h+=T*b;let P=k<=m?1:k>=m+26?26:k-m;if(T<P)break;b*=36-P}let w=d.length+1;m=c(h-y,w,y===0),f+=Math.floor(h/w),h%=w,d.splice(h,0,f),h++}return String.fromCodePoint(...d)}catch{return e}}isSameRegistrableDomain(e,t){let n=this.toHost(e),r=this.toHost(t);return!n||!r?!1:n===r||n.endsWith(`.${r}`)}alnum(e){return e.toLowerCase().replace(/[^a-z0-9]/g,"")}hostLabels(e){return this.toHost(e).split(".").map(t=>this.alnum(t)).filter(Boolean)}brandCore(e){return this.hostLabels(e)[0]??""}editDistance(e,t){let n=e.length,r=t.length;if(!n)return r;if(!r)return n;let o=Array.from({length:r+1},(a,i)=>i);for(let a=1;a<=n;a++){let i=[a];for(let l=1;l<=r;l++){let c=e[a-1]===t[l-1]?0:1;i[l]=Math.min(o[l]+1,i[l-1]+1,o[l-1]+c)}o=i}return o[r]}isNearMiss(e,t){if(!e||!t||e===t)return!1;let n=Math.max(e.length,t.length);if(n<4||Math.abs(e.length-t.length)>2)return!1;let r=this.editDistance(e,t);return r>=1&&r<=(n>=8?2:1)}carriesBrandName(e,t,n){let r=this.alnum(this.toHost(e));if(!r)return!1;let o=this.hostLabels(e);return[t?this.brandCore(t):"",this.alnum(n??"")].filter(i=>i.length>=4).some(i=>r.includes(i)||o.some(l=>this.isNearMiss(l,i)))}looksLikeSquatOf(e,t){if(this.isSameRegistrableDomain(e,t))return!1;let n=this.brandCore(t);if(n.length<4)return!1;let r=this.hostLabels(e);return r.includes(n)?!1:r.some(o=>this.isNearMiss(o,n)||o.length>n.length&&o.includes(n))}describeLookAlike(e,t){let n=this.toHost(e),r=this.toHost(t);if(!n||!r||n===r)return;if(/[^\u0020-\u007E]/.test(n))return`The address "${n}" uses look-alike (non-standard) characters to imitate the official ${r}; to the eye it reads the same, but it is a different address.`;let o=n.lastIndexOf("."),a=r.lastIndexOf(".");if(o>0&&a>0){let c=n.slice(0,o),u=r.slice(0,a),d=n.slice(o+1),p=r.slice(a+1);if(c===u&&d!==p)return`The address keeps the official name but changes the ending from ".${p}" to ".${d}" (${n} vs ${r}) \u2014 a look-alike that is easy to miss at a glance.`}let i=this.brandCore(r),l=this.hostLabels(n).find(c=>this.isNearMiss(c,i));if(l){let c=this.editDistance(l,i);return`The address "${n}" is a near-copy of the official ${r} \u2014 its name differs by only ${c} letter${c>1?"s":""} ("${l}" vs "${i}"), a typo that is easy to overlook.`}if(i.length>=4&&this.alnum(n).includes(i))return`The address "${n}" reuses the "${i}" name with extra text added to look affiliated with the official ${r}, but it is a different, unofficial domain.`}parseJson(e){if(!e)return null;let t=e.replace(/```(?:json)?/gi,"").trim(),n=t.indexOf("{"),r=t.lastIndexOf("}");if(n===-1||r===-1||r<=n)return null;try{return JSON.parse(t.slice(n,r+1))}catch{return null}}cleanStr(e){if(typeof e!="string")return;let t=e.trim();if(!t)return;let n=t.toLowerCase();if(!(n==="null"||n==="none"||n==="n/a"||n==="undefined"))return t}cleanStrArray(e){let t=Array.isArray(e)?e:typeof e=="string"?e.split(/\r?\n|(?:^|\s)[-•]\s+/):[],n=[];for(let r of t){let o=this.coerceToStr(r);o&&n.push(o)}return n}coerceToStr(e){if(typeof e=="string")return this.cleanStr(e);if(!e||typeof e!="object")return;let t=e,n=this.cleanStr(t.feature)??this.cleanStr(t.name)??this.cleanStr(t.title),r=this.cleanStr(t.description)??this.cleanStr(t.detail)??this.cleanStr(t.text)??this.cleanStr(t.value);return n&&r?n===r?n:`${n} \u2014 ${r}`:n||r?n??r:Object.values(t).map(a=>this.cleanStr(a)).filter(a=>!!a).join(" \u2014 ")||void 0}dedupe(e){let t=new Set,n=[];for(let r of e){let o=r.toLowerCase();t.has(o)||(t.add(o),n.push(r))}return n}};var Vd=new Set(["spark","spark-ethereum","morpho-v2"]);function di(s){return!!s&&Vd.has(s)}var pi=s=>{if(s==null||s==="")return null;let e=Number(s);return!Number.isInteger(e)||e<0||e>36?null:e};function mi(s){return!di(s.yieldProtocol)||pi(s.yieldAsset?.decimals)===null?!1:Number.isFinite(s.priceUSD)&&s.priceUSD>0}function Wd(s){let e=[];for(let t of s)t.rawBalance<=0n||mi(t)&&e.push({key:t.key,target:t.address,callData:Br+ae(t.rawBalance)});return{calls:e}}function Yd(s,e,t){let n=new Map;e.calls.forEach((o,a)=>{let i=bt(t[a]??null);i!==null&&n.set(o.key,i)});let r=new Map;for(let o of s){let a=nt(o.rawBalance,o.decimals),i=Number.isFinite(o.priceUSD)?o.priceUSD:0,l=n.get(o.key),c={underlyingAmount:a,valueUSD:a*i,pricePerTokenUSD:i,converted:!1};if(l===void 0){r.set(o.key,c);continue}let u=pi(o.yieldAsset?.decimals);if(u===null){r.set(o.key,c);continue}let d=nt(l,u),p=d*i;r.set(o.key,{underlyingAmount:d,valueUSD:p,pricePerTokenUSD:a>0?p/a:i,converted:!0})}return r}var Gd=s=>{let e=JSON.parse(s),t=Array.isArray(e)?e:e?.entries;if(!Array.isArray(t))throw new Error("JSON must be an array or { entries: [...] }");return t.map((n,r)=>{if(!n||typeof n.question!="string"||typeof n.answer!="string")throw new Error(`Entry #${r} is missing "question" or "answer"`);return n})};async function hi(s,e){let t=s.entries??(s.json?Gd(s.json):[]);return t.length===0?{count:0}:new it(e).upsert(t)}0&&(module.exports={AI_AGENT_TOOL_NAMES,AbortError,AgentCore,ApproveTokenTool,BaseNftAiTool,BaseSwapService,BaseTool,BaseWalletActionTool,BuyTokenTool,ChatHistory,DEFAULT_CHAIN,DEFAULT_PROVIDER,DEFAULT_RPC_BY_CHAIN,DebridgeAdapter,EstimatePoolYieldTool,GeminiProvider,GeminiSearchAiTool,HEX_TO_PANTOGRAPH,KnowledgeBase,LendingMarketsTool,LendingService,ManageLiquidityRedirectTool,MoralisService,NFC_AGENT_TOOL_NAMES,NFC_AMAZON_DEFAULT_DOMAIN,NFC_AMAZON_DOMAINS,NFTContractInfoTool,NFTMetadataTool,NFT_AGENT_TOOL_NAMES,NfcBuyTool,NfcInfoTool,NoFormTool,OpenAddLiquidityFormTool,OpenSupplyFormTool,POOL_AGENT_TOOL_NAMES,PantographService,PoolByAddressTool,PoolDetailTool,PoolFallbackAiTool,PoolPriceRangesTool,PoolSearchTool,PoolService,PreviewAddLiquidityTool,RelayAdapter,Router,SUPPORTED_CHAINS,SUPPORTED_CHAINS_LABEL,SWAP_PROVIDER_CONFIG,SendNativeTool,SendNftTool,SendTokenTool,Subagent,SubgraphAddPoolTool,SubgraphCoinPoolPairsTool,SubgraphPoolByAddressTool,SubgraphPoolByPositionIdTool,SubgraphPoolSearchTool,SubgraphPositionDetailTool,SubgraphTrendingPoolsTool,Summarizer,SwapServiceFactory,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,UpstashKnowledgeBase,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,buildChallenge,buildRangePresets,buildUniswapPoolUrl,clampTick,completeX402,configureSupportedChains,createAiAgent,createDefaultSubagents,createNfcAgent,createNftAgent,createPoolAgent,createTokenAgent,createWalletActionAgent,createWalletAgent,createX402SignatureProvider,displayFromChallenge,encodeSignedHeader,ethCallAt,ethCallByChain,fetchTopMarketplaces,getAffiliateFee,getChainMeta,getDefaultRpcUrl,getGatewayAddress,getGatewayChains,getNativeTokenInfo,getPositionManagerAddress,getProviderByChain,ingestKnowledgeBase,isAbortError,isPaymentRequired,isShareBasedProtocol,isShareBasedYieldToken,nfcAmazonSearchUrl,normaliseCountry,normalizePriceRangeToPool,planYieldTokenConversions,priceToTick,readPaymentError,readPaymentRequired,readReceipt,registerMaybeNoForm,requestWithX402,resolveNfcShopLinks,resolveRpcUrl,roundTickToSpacing,rpcCall,setRpcOverrides,swapServiceFactory,tickToPrice,toPantographChain});
|