keyring-agent-core 0.2.52 → 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.js CHANGED
@@ -1,4 +1,4 @@
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.52";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(`
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
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
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):
@@ -183,7 +183,7 @@ ${La}`,pn={"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 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}, 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,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):
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.