keyring-agent-core 0.3.10 → 0.3.11

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,7 +1,7 @@
1
- "use strict";var Op=Object.create;var la=Object.defineProperty;var Mp=Object.getOwnPropertyDescriptor;var Fp=Object.getOwnPropertyNames;var Bp=Object.getPrototypeOf,qp=Object.prototype.hasOwnProperty;var $p=(n,e)=>{for(var t in e)la(n,t,{get:e[t],enumerable:!0})},Ec=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fp(e))!qp.call(n,o)&&o!==t&&la(n,o,{get:()=>e[o],enumerable:!(r=Mp(e,o))||r.enumerable});return n};var Hp=(n,e,t)=>(t=n!=null?Op(Bp(n)):{},Ec(e||!n||!n.__esModule?la(t,"default",{value:n,enumerable:!0}):t,n)),Vp=n=>Ec(la({},"__esModule",{value:!0}),n);var xb={};$p(xb,{AI_AGENT_TOOL_NAMES:()=>Ni,AbortError:()=>an,AgentCore:()=>Bi,ApproveTokenTool:()=>Qo,BaseNftAiTool:()=>St,BaseSwapProvider:()=>bn,BaseTool:()=>A,BaseWalletActionTool:()=>ot,BuyTokenTool:()=>Jo,CachedResource:()=>Et,ChatHistory:()=>ts,CoinpoolConfigApi:()=>qs,DEFAULT_CHAIN:()=>Je,DEFAULT_PROVIDER:()=>Bt,DEFAULT_RPC_BY_CHAIN:()=>Xe,DEFILLAMA_EXTRA_SIGNALS:()=>ft,DEFILLAMA_POOL_CHAIN_HEXES:()=>$o,DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION:()=>We,DebridgeProvider:()=>Co,DefiLlamaEstimatePoolYieldTool:()=>Ko,DefiLlamaPoolByAddressTool:()=>Go,DefiLlamaPoolCandidateResolver:()=>jo,DefiLlamaPoolDetailTool:()=>Yo,DefiLlamaPoolSearchTool:()=>Wo,DefiLlamaPoolService:()=>Me,DefiLlamaTopPoolsTool:()=>Vo,EstimatePoolYieldTool:()=>Io,GeminiProvider:()=>ke,GeminiSearchAiTool:()=>yo,HEX_TO_PANTOGRAPH:()=>Bu,KeyringSettingApi:()=>Vs,KnowledgeBase:()=>rs,LendingMarketDetailTool:()=>ao,LendingMarketsTool:()=>so,LendingReadService:()=>ro,LendingService:()=>dt,LendingSupplyService:()=>oo,MULTICALL3_ADDRESS:()=>re,ManageLiquidityRedirectTool:()=>Zn,MoralisService:()=>O,NATIVE_GAS_LIMIT:()=>hp,NFC_AGENT_TOOL_NAMES:()=>_i,NFC_AMAZON_DEFAULT_DOMAIN:()=>oc,NFC_AMAZON_DOMAINS:()=>rc,NFTContractInfoTool:()=>po,NFTMetadataTool:()=>mo,NFT_AGENT_TOOL_NAMES:()=>Ei,NfcBuyTool:()=>go,NfcInfoTool:()=>fo,NoFormTool:()=>Qs,OpenAddLiquidityFormTool:()=>Xn,OpenSupplyFormTool:()=>lo,POOL_UNISWAP_AGENT_TOOL_NAMES:()=>Ii,PantographService:()=>Ae,PoolByAddressTool:()=>Lo,PoolDetailTool:()=>_o,PoolFallbackAiTool:()=>bo,PoolPriceRangesTool:()=>Jn,PoolSearchTool:()=>No,PoolService:()=>ie,PoolSwapRouter:()=>Ao,PreviewAddLiquidityTool:()=>Qn,PublicClient:()=>Fn,RelayProvider:()=>vo,Router:()=>os,SUPPLIABLE_TYPES:()=>Xl,SUPPORTED_CHAINS:()=>Ur,SUPPORTED_CHAINS_LABEL:()=>Or,SWAP_PROVIDER_CONFIG:()=>xo,SendNativeTool:()=>zo,SendNftTool:()=>es,SendTokenTool:()=>Xo,Subagent:()=>ne,SubgraphAddPoolTool:()=>qo,SubgraphCoinPoolPairsTool:()=>Bo,SubgraphPoolByAddressTool:()=>Oo,SubgraphPoolByPositionIdTool:()=>Mo,SubgraphPoolSearchTool:()=>Uo,SubgraphPositionDetailTool:()=>Fo,SubgraphTrendingPoolsTool:()=>Do,Summarizer:()=>ns,SwapProviderFactory:()=>Hs,SwapRouter:()=>To,SwapRouterRegistry:()=>$s,SwapTokenTool:()=>Zo,Synthesizer:()=>ss,TOKEN_AGENT_TOOL_NAMES:()=>Ri,TRANSFER_TOPIC:()=>Zd,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>qu,TokenAnalyticsTool:()=>Vr,TokenHoldersTool:()=>Hr,TokenInfoTool:()=>$r,TokenScoreTool:()=>Wr,ToolRegistry:()=>Ir,TopGainersTool:()=>Gr,TopPoolsTool:()=>Eo,TransactionByHashTool:()=>no,TrendingTokensTool:()=>Yr,UNISWAP_CHAIN_SLUG:()=>Ys,UNRESOLVED_ASSET:()=>Yn,UpstashKnowledgeBase:()=>An,UserSwapRouter:()=>Po,WALLET_ACTION_AGENT_TOOL_NAMES:()=>Ui,WALLET_AGENT_TOOL_NAMES:()=>Ci,WalletApprovalsTool:()=>Zr,WalletDefiPositionsTool:()=>eo,WalletDefiProtocolPositionsTool:()=>to,WalletHistoryTool:()=>jr,WalletLendingPositionsTool:()=>io,WalletNFTsTool:()=>uo,WalletNftTransfersTool:()=>Xr,WalletPnlSummaryTool:()=>Qr,WalletPnlTool:()=>Jr,WalletTokenBalancesTool:()=>Kr,WalletTokenTransfersTool:()=>zr,WebsiteTrustKeyringAgent:()=>qi,ZERO_ADDRESS:()=>ue,amazonDomainForLanguage:()=>sc,apiClient:()=>C,applyYieldConversions:()=>ja,buildApprovals:()=>bi,buildChallenge:()=>El,buildRangePresets:()=>cc,buildUniswapPoolUrl:()=>je,call:()=>kt,canDeriveV3PoolAddress:()=>hc,chains:()=>Nn,checkNativeGasAffordable:()=>js,checksumAddress:()=>ar,clampTick:()=>Rt,clearPublicClientCache:()=>Ea,coinpoolConfigApi:()=>kn,compareDecimal:()=>sn,completeX402:()=>_l,configureSupportedChains:()=>Da,configureSwapProvider:()=>gi,convertSusdsShares:()=>Wn,createAiAgent:()=>ra,createDefaultSubagents:()=>Di,createNfcAgent:()=>na,createNftAgent:()=>ta,createPoolUniswapAgent:()=>oa,createPublicClient:()=>rn,createTokenAgent:()=>ea,createTransport:()=>tn,createWalletActionAgent:()=>sa,createWalletAgent:()=>Zs,createX402SignatureProvider:()=>Ll,decodeAbiParameters:()=>Ie,decodeErrorResult:()=>dr,decodeFunctionData:()=>ol,decodeFunctionResult:()=>yt,defiLlamaPoolInfoScope:()=>He,defiLlamaPoolSupportsLabel:()=>Ve,deriveV3PoolAddress:()=>fc,displayFromChallenge:()=>_u,effectivePriceUSD:()=>Ds,encodeAbiParameters:()=>lr,encodeApprove:()=>yi,encodeErrorResult:()=>Zi,encodeFunctionData:()=>M,encodeSignedHeader:()=>Nl,erc1155Abi:()=>Aa,erc20Abi:()=>q,erc20Abi_bytes32:()=>kr,erc721Abi:()=>vr,estimateGas:()=>br,estimateNativeGasReserveWei:()=>Gs,estimateTransactionFeeWei:()=>yc,ethCallAt:()=>Ju,ethCallByChain:()=>sf,exactAmountString:()=>qn,extractOutRaw:()=>zd,extractQuoteError:()=>Xd,fallback:()=>nn,feeWeiToNative:()=>bc,fetchTopMarketplaces:()=>ac,floorToDecimals:()=>Dt,formatDefiLlamaPool:()=>_e,getAbiItem:()=>Xt,getAddress:()=>ji,getBalance:()=>hr,getBlock:()=>wr,getBlockNumber:()=>pr,getChain:()=>Ce,getChainContractAddress:()=>fs,getChainId:()=>mr,getChainMeta:()=>mt,getCode:()=>Qt,getDefaultRpcUrl:()=>wl,getGasPrice:()=>yr,getNativeTokenInfo:()=>Ro,getPublicClient:()=>Re,getRevertReason:()=>ds,getRpcOverrides:()=>ws,getStorageAt:()=>fr,getTokenPriceUSD:()=>Wa,getTransactionCount:()=>gr,http:()=>ut,humanToWei:()=>Bn,ingestKnowledgeBase:()=>Ip,isAbortError:()=>Hn,isAddress:()=>R,isAddressEqual:()=>zi,isPaymentRequired:()=>Jm,isShareBasedProtocol:()=>Ka,isShareBasedYieldToken:()=>Wu,isSupplyChain:()=>Za,keyringSettingApi:()=>wn,listCandidateChains:()=>zl,listSupplyChains:()=>Ja,mulDivFloor:()=>$n,multicall:()=>Nr,multicall3Abi:()=>ct,multicallRaw:()=>Zt,nativeGasShortfall:()=>gp,nfcAmazonSearchUrl:()=>ci,normaliseCountry:()=>ui,normalizeDecimal:()=>Lr,normalizePriceRangeToPool:()=>ko,parseAbi:()=>ll,parseAbiItem:()=>va,parseAbiParameters:()=>ms,pickLogo:()=>qt,planYieldTokenConversions:()=>Gl,priceToTick:()=>jn,protocolLabelFor:()=>Ke,psm3For:()=>Ga,readContract:()=>vt,readPaymentError:()=>Ru,readPaymentRequired:()=>La,readProtocolFeeWei:()=>wi,readReceipt:()=>Eu,readSpendableBalance:()=>Xs,readTokenUsdPrice:()=>zs,registerMaybeNoForm:()=>xi,requestWithX402:()=>Qm,resolveGasLimit:()=>fp,resolveNfcShopLinks:()=>ho,resolveRpcUrl:()=>Mn,resolveRpcUrls:()=>On,resolveTokenPriceUSD:()=>Gu,roundTickToSpacing:()=>Ct,rpcCall:()=>Qu,setRpcOverrides:()=>Dn,spendableNative:()=>Ks,swapProviderFactory:()=>So,swapRouterRegistry:()=>fi,tickToPrice:()=>pt,toEventSelector:()=>Xi,toFunctionSelector:()=>Ut,toPantographChain:()=>gh,toPlainDecimal:()=>vs,valueYieldTokens:()=>za,weiToHuman:()=>Na});module.exports=Vp(xb);var Nc=Hp(require("axios"));var _c="0.3.10";var Yp=`keyring-agent-core/${_c} (Keyring Chatbot Agent; +https://keyring.app)`,Hi=null;function Lc(n){Hi=n}var Gp=["payment-signature","x-payment"];function Kp(n){return n?Object.keys(n).some(e=>Gp.includes(e.toLowerCase())):!1}var Ic;function is(n){Ic=n}var jp=3e4,zp=typeof process<"u"&&process.versions?.node!=null,Vi=class{instance;constructor(e={}){this.instance=Nc.default.create({baseURL:e.baseURL,timeout:e.timeout??jp,validateStatus:()=>!0,headers:{Accept:"application/json",...zp?{"Accept-Encoding":"gzip, deflate, br","User-Agent":e.userAgent??Yp}:{},...e.headers}})}async request(e,t,r,o={}){let s=o.signal??Ic,a=await this.instance.request({...o,signal:s,method:e,url:t,data:r}),i={};for(let[c,d]of Object.entries(a.headers??{}))d!=null&&(i[c.toLowerCase()]=String(d));let l={ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:i};if(l.status===402&&Hi&&!Kp(o.headers)){let c=await Hi(l,{url:t,method:String(e),body:r,headers:o.headers});if(c)return this.request(e,t,r,{...o,headers:{...o.headers,...c}})}return l}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,r){return this.request("POST",e,t,r)}put(e,t,r){return this.request("PUT",e,t,r)}patch(e,t,r){return this.request("PATCH",e,t,r)}delete(e,t){return this.request("DELETE",e,void 0,t)}},C=new Vi;function _(n){let{data:e,status:t,statusText:r}=n,o=r?`HTTP ${t} ${r}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||o;if(e&&typeof e=="object"){let s=e,a=l=>l&&typeof l=="object"?l.message:void 0,i=[s.message,s.errorMessage,s.error,s.error_description,s.detail,a(s.error),a(s.data)];for(let l of i)if(typeof l=="string"&&l.trim())return l.trim()}return o}function Xp(n){return n instanceof F?n.details||n.shortMessage:n instanceof Error?n.message:typeof n=="string"?n:""}var F=class extends Error{name="BaseError";shortMessage;details;metaMessages;constructor(e,t={}){let r=t.details??Xp(t.cause),o=t.metaMessages??[],s=[e||"An error occurred.",...o.length>0?["",...o]:[],...r?["",`Details: ${r}`]:[]].join(`
1
+ "use strict";var Op=Object.create;var la=Object.defineProperty;var Mp=Object.getOwnPropertyDescriptor;var Fp=Object.getOwnPropertyNames;var Bp=Object.getPrototypeOf,qp=Object.prototype.hasOwnProperty;var $p=(n,e)=>{for(var t in e)la(n,t,{get:e[t],enumerable:!0})},Ec=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fp(e))!qp.call(n,o)&&o!==t&&la(n,o,{get:()=>e[o],enumerable:!(r=Mp(e,o))||r.enumerable});return n};var Hp=(n,e,t)=>(t=n!=null?Op(Bp(n)):{},Ec(e||!n||!n.__esModule?la(t,"default",{value:n,enumerable:!0}):t,n)),Vp=n=>Ec(la({},"__esModule",{value:!0}),n);var xb={};$p(xb,{AI_AGENT_TOOL_NAMES:()=>Ni,AbortError:()=>an,AgentCore:()=>Bi,ApproveTokenTool:()=>Qo,BaseNftAiTool:()=>St,BaseSwapProvider:()=>bn,BaseTool:()=>A,BaseWalletActionTool:()=>ot,BuyTokenTool:()=>Jo,CachedResource:()=>Et,ChatHistory:()=>ts,CoinpoolConfigApi:()=>qs,DEFAULT_CHAIN:()=>Je,DEFAULT_PROVIDER:()=>Bt,DEFAULT_RPC_BY_CHAIN:()=>Xe,DEFILLAMA_EXTRA_SIGNALS:()=>ft,DEFILLAMA_POOL_CHAIN_HEXES:()=>$o,DEFILLAMA_POOL_CHAIN_PARAM_DESCRIPTION:()=>We,DebridgeProvider:()=>Co,DefiLlamaEstimatePoolYieldTool:()=>Ko,DefiLlamaPoolByAddressTool:()=>Go,DefiLlamaPoolCandidateResolver:()=>jo,DefiLlamaPoolDetailTool:()=>Yo,DefiLlamaPoolSearchTool:()=>Wo,DefiLlamaPoolService:()=>Me,DefiLlamaTopPoolsTool:()=>Vo,EstimatePoolYieldTool:()=>Io,GeminiProvider:()=>ke,GeminiSearchAiTool:()=>yo,HEX_TO_PANTOGRAPH:()=>Bu,KeyringSettingApi:()=>Vs,KnowledgeBase:()=>rs,LendingMarketDetailTool:()=>ao,LendingMarketsTool:()=>so,LendingReadService:()=>ro,LendingService:()=>dt,LendingSupplyService:()=>oo,MULTICALL3_ADDRESS:()=>re,ManageLiquidityRedirectTool:()=>Zn,MoralisService:()=>O,NATIVE_GAS_LIMIT:()=>hp,NFC_AGENT_TOOL_NAMES:()=>_i,NFC_AMAZON_DEFAULT_DOMAIN:()=>oc,NFC_AMAZON_DOMAINS:()=>rc,NFTContractInfoTool:()=>po,NFTMetadataTool:()=>mo,NFT_AGENT_TOOL_NAMES:()=>Ei,NfcBuyTool:()=>go,NfcInfoTool:()=>fo,NoFormTool:()=>Qs,OpenAddLiquidityFormTool:()=>Xn,OpenSupplyFormTool:()=>lo,POOL_UNISWAP_AGENT_TOOL_NAMES:()=>Ii,PantographService:()=>Ae,PoolByAddressTool:()=>Lo,PoolDetailTool:()=>_o,PoolFallbackAiTool:()=>bo,PoolPriceRangesTool:()=>Jn,PoolSearchTool:()=>No,PoolService:()=>ie,PoolSwapRouter:()=>Ao,PreviewAddLiquidityTool:()=>Qn,PublicClient:()=>Fn,RelayProvider:()=>vo,Router:()=>os,SUPPLIABLE_TYPES:()=>Xl,SUPPORTED_CHAINS:()=>Ur,SUPPORTED_CHAINS_LABEL:()=>Or,SWAP_PROVIDER_CONFIG:()=>xo,SendNativeTool:()=>zo,SendNftTool:()=>es,SendTokenTool:()=>Xo,Subagent:()=>ne,SubgraphAddPoolTool:()=>qo,SubgraphCoinPoolPairsTool:()=>Bo,SubgraphPoolByAddressTool:()=>Oo,SubgraphPoolByPositionIdTool:()=>Mo,SubgraphPoolSearchTool:()=>Uo,SubgraphPositionDetailTool:()=>Fo,SubgraphTrendingPoolsTool:()=>Do,Summarizer:()=>ns,SwapProviderFactory:()=>Hs,SwapRouter:()=>To,SwapRouterRegistry:()=>$s,SwapTokenTool:()=>Zo,Synthesizer:()=>ss,TOKEN_AGENT_TOOL_NAMES:()=>Ri,TRANSFER_TOPIC:()=>Zd,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>qu,TokenAnalyticsTool:()=>Vr,TokenHoldersTool:()=>Hr,TokenInfoTool:()=>$r,TokenScoreTool:()=>Wr,ToolRegistry:()=>Ir,TopGainersTool:()=>Gr,TopPoolsTool:()=>Eo,TransactionByHashTool:()=>no,TrendingTokensTool:()=>Yr,UNISWAP_CHAIN_SLUG:()=>Ys,UNRESOLVED_ASSET:()=>Yn,UpstashKnowledgeBase:()=>An,UserSwapRouter:()=>Po,WALLET_ACTION_AGENT_TOOL_NAMES:()=>Ui,WALLET_AGENT_TOOL_NAMES:()=>Ci,WalletApprovalsTool:()=>Zr,WalletDefiPositionsTool:()=>eo,WalletDefiProtocolPositionsTool:()=>to,WalletHistoryTool:()=>jr,WalletLendingPositionsTool:()=>io,WalletNFTsTool:()=>uo,WalletNftTransfersTool:()=>Xr,WalletPnlSummaryTool:()=>Qr,WalletPnlTool:()=>Jr,WalletTokenBalancesTool:()=>Kr,WalletTokenTransfersTool:()=>zr,WebsiteTrustKeyringAgent:()=>qi,ZERO_ADDRESS:()=>ue,amazonDomainForLanguage:()=>sc,apiClient:()=>C,applyYieldConversions:()=>ja,buildApprovals:()=>bi,buildChallenge:()=>El,buildRangePresets:()=>cc,buildUniswapPoolUrl:()=>je,call:()=>kt,canDeriveV3PoolAddress:()=>hc,chains:()=>Nn,checkNativeGasAffordable:()=>js,checksumAddress:()=>ar,clampTick:()=>Rt,clearPublicClientCache:()=>Ea,coinpoolConfigApi:()=>kn,compareDecimal:()=>sn,completeX402:()=>_l,configureSupportedChains:()=>Da,configureSwapProvider:()=>gi,convertSusdsShares:()=>Wn,createAiAgent:()=>ra,createDefaultSubagents:()=>Di,createNfcAgent:()=>na,createNftAgent:()=>ta,createPoolUniswapAgent:()=>oa,createPublicClient:()=>rn,createTokenAgent:()=>ea,createTransport:()=>tn,createWalletActionAgent:()=>sa,createWalletAgent:()=>Zs,createX402SignatureProvider:()=>Ll,decodeAbiParameters:()=>Ie,decodeErrorResult:()=>dr,decodeFunctionData:()=>ol,decodeFunctionResult:()=>yt,defiLlamaPoolInfoScope:()=>He,defiLlamaPoolSupportsLabel:()=>Ve,deriveV3PoolAddress:()=>fc,displayFromChallenge:()=>_u,effectivePriceUSD:()=>Ds,encodeAbiParameters:()=>lr,encodeApprove:()=>yi,encodeErrorResult:()=>Zi,encodeFunctionData:()=>M,encodeSignedHeader:()=>Nl,erc1155Abi:()=>Aa,erc20Abi:()=>q,erc20Abi_bytes32:()=>kr,erc721Abi:()=>vr,estimateGas:()=>br,estimateNativeGasReserveWei:()=>Gs,estimateTransactionFeeWei:()=>yc,ethCallAt:()=>Ju,ethCallByChain:()=>sf,exactAmountString:()=>qn,extractOutRaw:()=>zd,extractQuoteError:()=>Xd,fallback:()=>nn,feeWeiToNative:()=>bc,fetchTopMarketplaces:()=>ac,floorToDecimals:()=>Dt,formatDefiLlamaPool:()=>_e,getAbiItem:()=>Xt,getAddress:()=>ji,getBalance:()=>hr,getBlock:()=>wr,getBlockNumber:()=>pr,getChain:()=>Ce,getChainContractAddress:()=>fs,getChainId:()=>mr,getChainMeta:()=>mt,getCode:()=>Qt,getDefaultRpcUrl:()=>wl,getGasPrice:()=>yr,getNativeTokenInfo:()=>Ro,getPublicClient:()=>Re,getRevertReason:()=>ds,getRpcOverrides:()=>ws,getStorageAt:()=>fr,getTokenPriceUSD:()=>Wa,getTransactionCount:()=>gr,http:()=>ut,humanToWei:()=>Bn,ingestKnowledgeBase:()=>Ip,isAbortError:()=>Hn,isAddress:()=>R,isAddressEqual:()=>zi,isPaymentRequired:()=>Jm,isShareBasedProtocol:()=>Ka,isShareBasedYieldToken:()=>Wu,isSupplyChain:()=>Za,keyringSettingApi:()=>wn,listCandidateChains:()=>zl,listSupplyChains:()=>Ja,mulDivFloor:()=>$n,multicall:()=>Nr,multicall3Abi:()=>ct,multicallRaw:()=>Zt,nativeGasShortfall:()=>gp,nfcAmazonSearchUrl:()=>ci,normaliseCountry:()=>ui,normalizeDecimal:()=>Lr,normalizePriceRangeToPool:()=>ko,parseAbi:()=>ll,parseAbiItem:()=>va,parseAbiParameters:()=>ms,pickLogo:()=>qt,planYieldTokenConversions:()=>Gl,priceToTick:()=>jn,protocolLabelFor:()=>Ke,psm3For:()=>Ga,readContract:()=>vt,readPaymentError:()=>Ru,readPaymentRequired:()=>La,readProtocolFeeWei:()=>wi,readReceipt:()=>Eu,readSpendableBalance:()=>Xs,readTokenUsdPrice:()=>zs,registerMaybeNoForm:()=>xi,requestWithX402:()=>Qm,resolveGasLimit:()=>fp,resolveNfcShopLinks:()=>ho,resolveRpcUrl:()=>Mn,resolveRpcUrls:()=>On,resolveTokenPriceUSD:()=>Gu,roundTickToSpacing:()=>Ct,rpcCall:()=>Qu,setRpcOverrides:()=>Dn,spendableNative:()=>Ks,swapProviderFactory:()=>So,swapRouterRegistry:()=>fi,tickToPrice:()=>pt,toEventSelector:()=>Xi,toFunctionSelector:()=>Ut,toPantographChain:()=>gh,toPlainDecimal:()=>vs,valueYieldTokens:()=>za,weiToHuman:()=>Na});module.exports=Vp(xb);var Nc=Hp(require("axios"));var _c="0.3.11";var Yp=`keyring-agent-core/${_c} (Keyring Chatbot Agent; +https://keyring.app)`,Hi=null;function Lc(n){Hi=n}var Gp=["payment-signature","x-payment"];function Kp(n){return n?Object.keys(n).some(e=>Gp.includes(e.toLowerCase())):!1}var Ic;function is(n){Ic=n}var jp=3e4,zp=typeof process<"u"&&process.versions?.node!=null,Vi=class{instance;constructor(e={}){this.instance=Nc.default.create({baseURL:e.baseURL,timeout:e.timeout??jp,validateStatus:()=>!0,headers:{Accept:"application/json",...zp?{"Accept-Encoding":"gzip, deflate, br","User-Agent":e.userAgent??Yp}:{},...e.headers}})}async request(e,t,r,o={}){let s=o.signal??Ic,a=await this.instance.request({...o,signal:s,method:e,url:t,data:r}),i={};for(let[c,d]of Object.entries(a.headers??{}))d!=null&&(i[c.toLowerCase()]=String(d));let l={ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:i};if(l.status===402&&Hi&&!Kp(o.headers)){let c=await Hi(l,{url:t,method:String(e),body:r,headers:o.headers});if(c)return this.request(e,t,r,{...o,headers:{...o.headers,...c}})}return l}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,r){return this.request("POST",e,t,r)}put(e,t,r){return this.request("PUT",e,t,r)}patch(e,t,r){return this.request("PATCH",e,t,r)}delete(e,t){return this.request("DELETE",e,void 0,t)}},C=new Vi;function _(n){let{data:e,status:t,statusText:r}=n,o=r?`HTTP ${t} ${r}`:`HTTP ${t}`;if(typeof e=="string")return e.trim()||o;if(e&&typeof e=="object"){let s=e,a=l=>l&&typeof l=="object"?l.message:void 0,i=[s.message,s.errorMessage,s.error,s.error_description,s.detail,a(s.error),a(s.data)];for(let l of i)if(typeof l=="string"&&l.trim())return l.trim()}return o}function Xp(n){return n instanceof F?n.details||n.shortMessage:n instanceof Error?n.message:typeof n=="string"?n:""}var F=class extends Error{name="BaseError";shortMessage;details;metaMessages;constructor(e,t={}){let r=t.details??Xp(t.cause),o=t.metaMessages??[],s=[e||"An error occurred.",...o.length>0?["",...o]:[],...r?["",`Details: ${r}`]:[]].join(`
2
2
  `);super(s,t.cause!==void 0?{cause:t.cause}:void 0),this.shortMessage=e,this.details=r,this.metaMessages=o,t.name&&(this.name=t.name)}walk(e){return Uc(this,e)}};function Uc(n,e){if(e?.(n))return n;let t=n&&typeof n=="object"?n.cause:void 0;return t!=null?Uc(t,e):e?null:n}var Wt=class extends F{name="AbiParameterTypeError";constructor(e){super(`Type "${e}" is not a valid ABI type.`,{metaMessages:["Supported: address, bool, string, bytes, bytesN, (u)intN, tuple, and arrays of those."]})}},ca=class extends F{name="AbiEncodingLengthMismatchError";constructor({expectedLength:e,givenLength:t}){super("ABI encoding parameters/values length mismatch.",{metaMessages:[`Expected length (parameters): ${e}`,`Given length (values): ${t}`]})}},ua=class extends F{name="AbiEncodingArrayLengthMismatchError";constructor({expectedLength:e,givenLength:t,type:r}){super(`ABI encoding array length mismatch for type ${r}.`,{metaMessages:[`Expected length: ${e}`,`Given length: ${t}`]})}},it=class extends F{name="InvalidAbiValueError";constructor({type:e,value:t,reason:r}){super(`Invalid value for ABI type "${e}".`,{metaMessages:[`Value: ${Dc(t)}`,`Reason: ${r}`]})}},da=class extends F{name="IntegerOutOfRangeError";constructor({type:e,value:t,min:r,max:o}){super(`Number "${t}" is not in safe ${e} range.`,{metaMessages:[`Range: ${r} \u2026 ${o}`]})}},rr=class extends F{name="InvalidAddressError";constructor(e){super(`Address "${Dc(e)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]})}};function Dc(n){if(typeof n=="bigint")return n.toString();if(typeof n=="string")return n;try{return JSON.stringify(n)??String(n)}catch{return String(n)}}var pa=class extends F{name="AbiEncodingBytesSizeMismatchError";constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" does not match expected size of bytes${e}.`)}},Yt=class extends F{name="AbiDecodingZeroDataError";constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{metaMessages:["The contract returned no data. Usually this means:","- the address is not a contract on this chain,","- the function does not exist on it, or","- the call was made before the contract was deployed."]})}},ma=class extends F{name="AbiDecodingDataSizeTooSmallError";data;params;size;constructor({data:e,params:t,size:r}){super(`Data size of ${r} bytes is too small for given parameters.`,{metaMessages:[`Params: (${t.map(o=>o.type).join(", ")})`,`Data: ${e} (${r} bytes)`]}),this.data=e,this.params=t,this.size=r}},or=class extends F{name="AbiDecodingOutOfBoundsError";constructor({position:e,length:t}){super(`Position ${e} is out of bounds (${t} bytes).`,{metaMessages:["The return data is truncated or not ABI-encoded."]})}},ha=class extends F{name="AbiItemNotFoundError";constructor({name:e,type:t="function"}){super(`${t[0].toUpperCase()}${t.slice(1)} "${e}" not found on ABI.`,{metaMessages:["Make sure you are using the correct ABI and that the item exists on it."]})}},Gt=class extends F{name="InvalidAbiSignatureError";constructor(e,t){super(`Invalid ABI signature: "${e}".`,{metaMessages:t?[t]:['Expected e.g. "function balanceOf(address owner) view returns (uint256)".']})}};var Qp=/^0x[0-9a-fA-F]*$/;function xn(n,{strict:e=!0}={}){return typeof n!="string"?!1:e?Qp.test(n):n.startsWith("0x")}function gt(n){return n.startsWith("0x")||n.startsWith("0X")?n.slice(2):n}function ls(n){return typeof n=="string"?Math.ceil(gt(n).length/2):n.length}function Cn(n,e,t){let r=gt(n),o=(e??0)*2,s=t===void 0?r.length:t*2;return`0x${r.slice(o,s)}`}function fa(n){return`0x${n.map(gt).join("")}`}function Rn(n){let e=new Uint8Array(n.reduce((r,o)=>r+o.length,0)),t=0;for(let r of n)e.set(r,t),t+=r.length;return e}function Kt(n){let e=gt(n),t=e.length%2?`0${e}`:e,r=new Uint8Array(t.length/2);for(let o=0;o<r.length;o++)r[o]=parseInt(t.slice(o*2,o*2+2),16);return r}function It(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`0x${e}`}function Wi(n){return new TextEncoder().encode(n)}function Yi(n){return new TextDecoder().decode(n)}function Fe(n,e={}){let{size:t,signed:r}=e,o=BigInt(n);if(o<0n){if(!t)throw new Error("numberToHex: negative values require a `size`");o+=1n<<BigInt(t*8)}else if(r&&t){let a=(1n<<BigInt(t*8-1))-1n;if(o>a)throw new Error(`numberToHex: ${n} overflows int${t*8}`)}let s=o.toString(16);if(!t)return`0x${s}`;if(s.length>t*2)throw new Error(`numberToHex: ${n} overflows ${t} bytes`);return`0x${s.padStart(t*2,"0")}`}function Gi(n,e=32){if(n.length>e)throw new Error(`padLeft: ${n.length} bytes exceeds ${e}`);let t=new Uint8Array(e);return t.set(n,e-n.length),t}function Ki(n,e=32){if(n.length>e)throw new Error(`padRight: ${n.length} bytes exceeds ${e}`);let t=new Uint8Array(e);return t.set(n),t}function En(n){let e=1n<<256n,t=(n%e+e)%e;return Kt(t.toString(16).padStart(64,"0"))}function sr(n,{signed:e=!1}={}){let t=BigInt(It(n));if(!e)return t;let r=BigInt(n.length*8);return t>=1n<<r-1n?t-(1n<<r):t}function lt(n,{signed:e=!1}={}){return gt(n)?sr(Kt(n),{signed:e}):0n}function ga(n,e={}){return Number(lt(n,e))}var Oc=require("js-sha3");var Jp=/^0x[0-9a-fA-F]{40}$/;function R(n){return typeof n=="string"&&Jp.test(n)}function ar(n){let e=gt(n).toLowerCase(),t=(0,Oc.keccak_256)(e),r="";for(let o=0;o<e.length;o++)r+=parseInt(t[o],16)>=8?e[o].toUpperCase():e[o];return`0x${r}`}function ji(n){if(!R(n))throw new Error(`Address "${n}" is invalid.`);return ar(n)}function zi(n,e){return R(n)&&R(e)&&n.toLowerCase()===e.toLowerCase()}var ya=require("js-sha3");function ba(n){return`0x${(0,ya.keccak_256)(n)}`}function Mc(n){return`0x${(0,ya.keccak_256)(new TextEncoder().encode(n))}`}function jt(n){let e=n.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function zt(n){return n.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1").replace(/^byte(\[|$)/,"bytes1$1")}function cs(n){let e=zt(n.type);return e==="tuple"||e.startsWith("tuple[")?`(${(n.components??[]).map(cs).join(",")})${e.slice(5)}`:e}function ir(n){return`${n.name??""}(${(n.inputs??[]).map(cs).join(",")})`}function Ut(n){let e=typeof n=="string"?n:ir(n);return`0x${(0,ya.keccak_256)(new TextEncoder().encode(e)).slice(0,8)}`}function Xi(n){let e=typeof n=="string"?n:ir(n);return Mc(e)}function Fc(n,e){let t=zt(e.type),r=jt(t);if(r){let[o,s]=r;return!Array.isArray(n)||o!==null&&n.length!==o?!1:n.every(a=>Fc(a,{...e,type:s}))}if(t==="tuple"){let o=e.components??[];return Array.isArray(n)?n.length===o.length:typeof n=="object"&&n!==null}return t==="address"?typeof n=="string"&&/^0x[0-9a-fA-F]{40}$/.test(n):t==="bool"?typeof n=="boolean":t==="string"?typeof n=="string":t.startsWith("bytes")?typeof n=="string"||n instanceof Uint8Array:t.startsWith("uint")||t.startsWith("int")?typeof n=="number"||typeof n=="bigint"||typeof n=="string":!0}function Xt({abi:n,name:e,args:t,type:r}){let o=r??"function",s=n.filter(i=>(i.type??"function")===o);if(e.startsWith("0x")&&e.length===10)return s.find(i=>Ut(i)===e.toLowerCase());if(e.includes("("))return s.find(i=>ir(i)===e);let a=s.filter(i=>i.name===e);return a.length<=1||!t?a[0]:a.find(i=>{let l=i.inputs??[];return l.length===t.length&&l.every((c,d)=>Fc(t[d],c))})??a[0]}function _n(n){let e=Xt(n);if(!e)throw new ha({name:n.name,type:n.type??"function"});return e}function Bc(n){let e=new Uint8Array(Math.ceil(n.length/32)*32);return e.set(n),{dynamic:!0,encoded:Rn([En(BigInt(n.length)),e])}}function qc(n,e){let t=n.slice(e.length),r=t===""?256:Number(t);if(!Number.isInteger(r)||r<8||r>256||r%8!==0)throw new Wt(n);return r}function $c(n,e){if(typeof n=="bigint")return n;if(typeof n=="number"){if(!Number.isInteger(n))throw new it({type:e,value:n,reason:"expected an integer, got a fractional number"});return BigInt(n)}if(typeof n=="string"&&n.trim()!=="")try{return BigInt(n.trim())}catch{throw new it({type:e,value:n,reason:"string is not a valid integer"})}throw new it({type:e,value:n,reason:"expected a bigint, number or numeric string"})}function Hc(n,{bits:e,signed:t,type:r}){let o=t?(1n<<BigInt(e-1))-1n:(1n<<BigInt(e))-1n,s=t?-(1n<<BigInt(e-1)):0n;if(n<s||n>o)throw new da({type:r,value:n,min:s,max:o})}function Vc(n,e){if(n instanceof Uint8Array)return n;if(typeof n=="string"){if(!xn(n))throw new it({type:e,value:n,reason:"expected 0x-prefixed hex"});return Kt(n)}throw new it({type:e,value:n,reason:"expected a hex string or Uint8Array"})}function Qi(n,e){let t=jt(n.type);if(t){let[o,s]=t;if(!Array.isArray(e))throw new it({type:n.type,value:e,reason:"expected an array"});return Zp({...n,type:s},e,o,n.type)}if(n.type==="tuple")return em(n,e);let r=zt(n.type);if(r==="address"){if(!R(e))throw new rr(e);return{dynamic:!1,encoded:Gi(Kt(gt(e).toLowerCase()))}}if(r==="bool"){if(typeof e!="boolean")throw new it({type:r,value:e,reason:"expected a boolean"});let o=new Uint8Array(32);return o[31]=e?1:0,{dynamic:!1,encoded:o}}if(/^uint\d*$/.test(r)){let o=$c(e,r);return Hc(o,{bits:qc(r,"uint"),signed:!1,type:r}),{dynamic:!1,encoded:En(o)}}if(/^int\d*$/.test(r)){let o=$c(e,r);return Hc(o,{bits:qc(r,"int"),signed:!0,type:r}),o<0n&&(o+=1n<<256n),{dynamic:!1,encoded:En(o)}}if(/^bytes\d+$/.test(r)){let o=Number(r.slice(5));if(o<1||o>32)throw new Wt(n.type);let s=Vc(e,r);if(s.length!==o)throw new pa({expectedSize:o,value:String(e)});return{dynamic:!1,encoded:Ki(s)}}if(r==="bytes")return Bc(Vc(e,r));if(r==="string"){if(typeof e!="string"&&!(e instanceof Uint8Array))throw new it({type:r,value:e,reason:"expected a string"});return Bc(typeof e=="string"?Wi(e):e)}throw new Wt(n.type)}function Ji(n){let e=0;for(let{dynamic:s,encoded:a}of n)e+=s?32:a.length;let t=[],r=[],o=0;for(let{dynamic:s,encoded:a}of n)s?(t.push(En(BigInt(e+o))),r.push(a),o+=a.length):t.push(a);return Rn([...t,...r])}function Zp(n,e,t,r){let o=t===null;if(!o&&e.length!==t)throw new ua({expectedLength:t,givenLength:e.length,type:r});let s=!1,a=[];for(let i of e){let l=Qi(n,i);l.dynamic&&(s=!0),a.push(l)}if(o||s){let i=Ji(a);if(!o)return{dynamic:!0,encoded:i};let l=En(BigInt(a.length));return{dynamic:!0,encoded:a.length>0?Rn([l,i]):l}}return{dynamic:!1,encoded:Rn(a.map(i=>i.encoded))}}function em(n,e){let t=n.components??[],r=!1,o=[];for(let s=0;s<t.length;s++){let a=t[s],i=Qi(a,Array.isArray(e)?e[s]:e[a.name??""]);i.dynamic&&(r=!0),o.push(i)}return{dynamic:r,encoded:r?Ji(o):Rn(o.map(s=>s.encoded))}}function lr(n,e){if(n.length!==e.length)throw new ca({expectedLength:n.length,givenLength:e.length});return n.length===0?"0x":It(Ji(n.map((t,r)=>Qi(t,e[r]))))}function M({abi:n,functionName:e,args:t=[]}){let r=_n({abi:n,name:e,args:t,type:"function"}),o=Ut(r),s=r.inputs??[];return s.length===0?o:fa([o,lr(s,t)])}function Zi({abi:n,errorName:e,args:t=[]}){let r=_n({abi:n,name:e,args:t,type:"error"}),o=r.inputs??[],s=Ut(r);return o.length===0?s:fa([s,lr(o,t)])}function tm(n){let e=n.replace(/^u?int/,"");return e?Number(e):256}function us(n,e){if(e<0||e+32>n.length)throw new or({position:e,length:n.length});return n.subarray(e,e+32)}function nl(n,e){let t=sr(us(n,e));if(t>BigInt(n.length))throw new or({position:Number(t),length:n.length});return Number(t)}function el(n){let e=jt(n.type);if(e){let[r,o]=e;return r===null||el({...n,type:o})}if(n.type==="tuple")return(n.components??[]).some(el);let t=zt(n.type);return t==="bytes"||t==="string"}function tl(n){let e=jt(n.type);if(e){let[t,r]=e;return t===null?32:t*tl({...n,type:r})}return n.type==="tuple"?(n.components??[]).reduce((t,r)=>t+tl(r),0):32}function rl(n,e,t){let r=[],o=e;for(let s of t)el(s)?(r.push(Wc(n,e+nl(n,o),s)),o+=32):(r.push(Wc(n,o,s)),o+=tl(s));return r}function nm(n,e,t,r){let o=r===null?nl(n,e):r,s=r===null?e+32:e;return rl(n,s,new Array(o).fill(t))}function rm(n,e,t){let r=t.components??[],o=rl(n,e,r);if(r.length===0||r.some(i=>!i.name))return o;let a={};return r.forEach((i,l)=>{a[i.name]=o[l]}),a}function Wc(n,e,t){let r=jt(t.type);if(r){let[s,a]=r;return nm(n,e,{...t,type:a},s)}if(t.type==="tuple")return rm(n,e,t);let o=zt(t.type);if(o==="address")return ar(It(us(n,e).subarray(12)));if(o==="bool")return sr(us(n,e))!==0n;if(/^u?int\d*$/.test(o)){let s=o.startsWith("int"),a=sr(us(n,e),{signed:s});return tm(o)>48?a:Number(a)}if(/^bytes\d+$/.test(o)){let s=Number(o.slice(5));return It(us(n,e).subarray(0,s))}if(o==="bytes"||o==="string"){let s=nl(n,e),a=e+32;if(a+s>n.length)throw new or({position:a+s,length:n.length});let i=n.subarray(a,a+s);return o==="bytes"?It(i):Yi(i)}throw new Wt(t.type)}function Ie(n,e){let t=typeof e=="string"?Kt(e):e;if(t.length===0){if(n.length>0)throw new Yt;return[]}if(t.length<32)throw new ma({data:typeof e=="string"?e:It(e),params:n,size:t.length});return rl(t,0,n)}function ee(n){if(!n)return null;try{let[e]=Ie([{type:"uint256"}],n);return e}catch{return null}}function B(n){if(!n)return null;try{let[e]=Ie([{type:"address"}],n),t=e;return/^0x0{40}$/i.test(t)?null:t}catch{return null}}function cr(n){if(!n)return null;try{let[e]=Ie([{type:"string"}],n),t=Yc(e);if(t)return t}catch{}try{let[e]=Ie([{type:"bytes32"}],n);return ka(e)}catch{return null}}function ur(n){return wa(ee(n))}function wa(n){let e=typeof n=="bigint"?Number(n):typeof n=="number"?n:NaN;return Number.isFinite(e)&&e>=0&&e<=36?e:null}function ka(n){return typeof n!="string"||!n.startsWith("0x")?null:Yc(Buffer.from(n.slice(2),"hex").toString("utf8"))||null}function Yc(n){return n.replace(/[^\x20-\x7e]/g,"").trim()}function yt({abi:n,functionName:e,args:t,data:r}){let s=_n({abi:n,name:e,args:t,type:"function"}).outputs??[],a=Ie(s,r);if(a.length!==0)return a.length===1?a[0]:a}function ol({abi:n,data:e}){let t=Cn(e,0,4),r=_n({abi:n,name:t,type:"function"}),o=r.inputs??[];return{functionName:r.name,args:o.length===0||ls(e)<=4?[]:Ie(o,Cn(e,4))}}var Gc={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},Kc={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},jc={1:"An `assert` condition failed.",17:"Arithmetic operation resulted in underflow or overflow.",18:"Division or modulo by zero (e.g. `5 / 0`).",33:"Attempted to convert to an invalid type.",34:"Attempted to access a storage byte array that is incorrectly encoded.",49:"Performed `.pop()` on an empty array.",50:"Array index is out of bounds.",65:"Allocated too much memory or created an array which is too large.",81:"Attempted to call a zero-initialized variable of internal function type."};function dr({abi:n=[],data:e}){let t=Cn(e,0,4);if(ls(e)<4)throw new Error(`Cannot decode error result: "${e}" is too short.`);let r=[...n,Gc,Kc],o=Xt({abi:r,name:t,type:"error"})??r.find(a=>(a.type??"")==="error"&&Ut(a)===t);if(!o)throw new Error(`Unknown error selector "${t}".`);let s=o.inputs??[];return{abiItem:o,errorName:o.name,args:s.length>0?Ie(s,Cn(e,4)):void 0}}function ds({abi:n,data:e}){if(!(!e||e==="0x"))try{let{errorName:t,args:r}=dr({abi:n,data:e});if(t==="Error")return String(r?.[0]??"");if(t==="Panic"){let o=Number(r?.[0]??0);return jc[o]??`Panic code ${o}.`}return!r||r.length===0?t:`${t}(${r.map(o=>String(o)).join(", ")})`}catch{return}}var om=new Set(["pure","view","nonpayable","payable"]),sm=new Set(["external","public","internal","private","calldata","memory","storage"]);function al(n,e){let t=0;for(let r=e;r<n.length;r++)if(n[r]==="(")t++;else if(n[r]===")"&&(t--,t===0))return r;throw new Gt(n,"Unbalanced parentheses.")}function Xc(n){let e=[],t=0,r="";for(let o of n){if(o==="("&&t++,o===")"&&t--,o===","&&t===0){e.push(r),r="";continue}r+=o}return r.trim()&&e.push(r),e.map(o=>o.trim()).filter(Boolean)}function am(n){let e=n.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:e?.[1]??"",rest:(e?.[2]??"").trim()}}function zc(n,e){let t=!1,r;for(let o of n)o==="indexed"?t=!0:sm.has(o)||(r=o);return{...e,...r?{name:r}:{},...t?{indexed:!0}:{}}}function il(n){let e=n.trim();if(e.startsWith("(")){let o=al(e,0),s=Xc(e.slice(1,o)).map(il),{suffix:a,rest:i}=am(e.slice(o+1).trim());return zc(i.split(/\s+/).filter(Boolean),{type:`tuple${a}`,components:s})}let[t,...r]=e.split(/\s+/).filter(Boolean);if(!t)throw new Gt(n,"Missing parameter type.");return zc(r,{type:t})}function ms(n){return Xc(n).map(il)}function ps(n,e,t){let r=n.indexOf("(",e);if(r===-1)throw new Gt(t,"Missing parameter list.");let o=al(n,r);return{name:n.slice(e,r).trim(),params:ms(n.slice(r+1,o)),rest:n.slice(o+1).trim()}}function sl(n,e){return n.split(/[\s()]+/).find(r=>om.has(r))??e}function va(n){let e=n.trim();if(e.startsWith("function ")){let{name:t,params:r,rest:o}=ps(e,9,n),s=o.indexOf("returns"),a=s===-1?o:o.slice(0,s),i=[];if(s!==-1){let l=o.indexOf("(",s);if(l===-1)throw new Gt(n,"`returns` without a parameter list.");i=ms(o.slice(l+1,al(o,l)))}return{type:"function",name:t,inputs:r,outputs:i,stateMutability:sl(a,"nonpayable")}}if(e.startsWith("event ")){let{name:t,params:r}=ps(e,6,n);return{type:"event",name:t,inputs:r}}if(e.startsWith("error ")){let{name:t,params:r}=ps(e,6,n);return{type:"error",name:t,inputs:r}}if(e.startsWith("constructor")){let{params:t,rest:r}=ps(e,11,n);return{type:"constructor",inputs:t,stateMutability:sl(r,"nonpayable")}}if(e.startsWith("fallback")){let{rest:t}=ps(e,8,n);return{type:"fallback",stateMutability:sl(t,"nonpayable")}}if(e.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new Gt(n,"Expected function, event, error, constructor, fallback or receive.")}function ll(n){return n.map(va)}function bt({blockNumber:n,blockTag:e="latest"}={}){return n!==void 0?Fe(n):e}function hs(n){let{account:e,to:t,data:r,value:o,gas:s,gasPrice:a,maxFeePerGas:i,maxPriorityFeePerGas:l,nonce:c}=n,d={};return e&&(d.from=e),t&&(d.to=t),r&&(d.data=r),o!==void 0&&(d.value=Fe(o)),s!==void 0&&(d.gas=Fe(s)),a!==void 0&&(d.gasPrice=Fe(a)),i!==void 0&&(d.maxFeePerGas=Fe(i)),l!==void 0&&(d.maxPriorityFeePerGas=Fe(l)),c!==void 0&&(d.nonce=Fe(c)),d}function cl(n){let e={};for(let[t,r]of Object.entries(n)){let o={};r.balance!==void 0&&(o.balance=Fe(r.balance)),r.nonce!==void 0&&(o.nonce=Fe(r.nonce)),r.code!==void 0&&(o.code=r.code),r.state&&(o.state=r.state),r.stateDiff&&(o.stateDiff=r.stateDiff),e[t]=o}return e}async function pr(n){return lt(await n.request({method:"eth_blockNumber"}))}async function mr(n){return ga(await n.request({method:"eth_chainId"}))}async function hr(n,{address:e,...t}){return lt(await n.request({method:"eth_getBalance",params:[e,bt(t)]}))}async function Qt(n,{address:e,...t}){let r=await n.request({method:"eth_getCode",params:[e,bt(t)]});return!r||r==="0x"?void 0:r}async function fr(n,{address:e,slot:t,...r}){return await n.request({method:"eth_getStorageAt",params:[e,t,bt(r)]})??void 0}async function gr(n,{address:e,...t}){return ga(await n.request({method:"eth_getTransactionCount",params:[e,bt(t)]}))}async function yr(n){return lt(await n.request({method:"eth_gasPrice"}))}async function Ta(n){return lt(await n.request({method:"eth_maxPriorityFeePerGas"}))}async function br(n,{blockNumber:e,blockTag:t,...r}){return lt(await n.request({method:"eth_estimateGas",params:[hs(r),bt({blockNumber:e,blockTag:t})]}))}async function wr(n,{includeTransactions:e=!1,...t}={}){let r=await n.request({method:"eth_getBlockByNumber",params:[bt(t),e]});return r?{...r,blockNumber:r.number?lt(r.number):void 0,blockTimestamp:r.timestamp?lt(r.timestamp):void 0,baseFee:r.baseFeePerGas?lt(r.baseFeePerGas):void 0}:null}var re="0xcA11bde05977b3631167028862bE2a173976CA11",Qc={id:1,hexId:"0x1",name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://ethereum-rpc.publicnode.com","https://eth.drpc.org","https://1rpc.io/eth"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io"}},contracts:{multicall3:{address:re,blockCreated:14353601}}},Jc={id:10,hexId:"0xa",name:"Optimism",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.optimism.io","https://optimism-rpc.publicnode.com","https://optimism.drpc.org"]}},blockExplorers:{default:{name:"Optimistic Etherscan",url:"https://optimistic.etherscan.io"}},contracts:{multicall3:{address:re,blockCreated:4286263}}},Zc={id:56,hexId:"0x38",name:"BSC",nativeCurrency:{name:"BNB",symbol:"BNB",decimals:18},rpcUrls:{default:{http:["https://bsc-dataseed.binance.org","https://bsc-rpc.publicnode.com","https://bsc.drpc.org"]}},blockExplorers:{default:{name:"BscScan",url:"https://bscscan.com"}},contracts:{multicall3:{address:re}}},eu={id:137,hexId:"0x89",name:"Polygon",nativeCurrency:{name:"POL",symbol:"POL",decimals:18},rpcUrls:{default:{http:["https://polygon-bor-rpc.publicnode.com","https://polygon.drpc.org"]}},blockExplorers:{default:{name:"PolygonScan",url:"https://polygonscan.com"}},contracts:{multicall3:{address:re,blockCreated:25770160}}},tu={id:8453,hexId:"0x2105",name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org","https://base-rpc.publicnode.com","https://base.drpc.org"]}},blockExplorers:{default:{name:"BaseScan",url:"https://basescan.org"}},contracts:{multicall3:{address:re,blockCreated:5022}}},nu={id:42161,hexId:"0xa4b1",name:"Arbitrum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc","https://arbitrum-one-rpc.publicnode.com","https://arbitrum.drpc.org"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io"}},contracts:{multicall3:{address:re,blockCreated:7654707}}},ru={id:43114,hexId:"0xa86a",name:"Avalanche",nativeCurrency:{name:"Avalanche",symbol:"AVAX",decimals:18},rpcUrls:{default:{http:["https://avalanche-c-chain-rpc.publicnode.com","https://avalanche.drpc.org"]}},blockExplorers:{default:{name:"SnowTrace",url:"https://snowtrace.io"}},contracts:{multicall3:{address:re}}},ou={id:59144,hexId:"0xe708",name:"Linea",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.linea.build","https://linea-rpc.publicnode.com","https://linea.drpc.org"]}},blockExplorers:{default:{name:"LineaScan",url:"https://lineascan.build"}},contracts:{multicall3:{address:re}}},su={id:100,hexId:"0x64",name:"Gnosis",nativeCurrency:{name:"xDAI",symbol:"XDAI",decimals:18},rpcUrls:{default:{http:["https://gnosis-rpc.publicnode.com","https://gnosis.drpc.org"]}},blockExplorers:{default:{name:"Gnosisscan",url:"https://gnosisscan.io"}},contracts:{multicall3:{address:re}}},au={id:999,hexId:"0x3e7",name:"HyperEVM",nativeCurrency:{name:"HYPE",symbol:"HYPE",decimals:18},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}},contracts:{multicall3:{address:re}}},iu={id:5e3,hexId:"0x1388",name:"Mantle",nativeCurrency:{name:"Mantle",symbol:"MNT",decimals:18},rpcUrls:{default:{http:["https://rpc.mantle.xyz","https://mantle-rpc.publicnode.com"]}},blockExplorers:{default:{name:"Mantle Explorer",url:"https://explorer.mantle.xyz"}},contracts:{multicall3:{address:re}}},lu={id:143,hexId:"0x8f",name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://rpc.monad.xyz"]}},contracts:{multicall3:{address:re}}},Nn=[Qc,Jc,Zc,eu,tu,nu,ru,ou,su,au,iu,lu];var cu=new Map,ul=new Map;function im(n,e){return`${n??"unknown"}|${e.toLowerCase()}`}async function uu(n,e=re){let t=im(n.chain?.id??n.chain?.hexId,e),r=cu.get(t);if(r!==void 0)return r;let o=ul.get(t);if(o)return o;let s=(async()=>{try{let i=await Qt(n,{address:e})!==void 0;return cu.set(t,i),i}catch{return!0}finally{ul.delete(t)}})();return ul.set(t,s),s}async function Ln(n,e,t=!1){return t||typeof n.batch?.multicall=="object"&&n.batch.multicall.assumeMulticall3?!0:uu(n,e)}var ct=[{type:"function",name:"aggregate3",stateMutability:"payable",inputs:[{name:"calls",type:"tuple[]",components:[{name:"target",type:"address"},{name:"allowFailure",type:"bool"},{name:"callData",type:"bytes"}]}],outputs:[{name:"returnData",type:"tuple[]",components:[{name:"success",type:"bool"},{name:"returnData",type:"bytes"}]}]},{type:"function",name:"getEthBalance",stateMutability:"view",inputs:[{name:"addr",type:"address"}],outputs:[{name:"balance",type:"uint256"}]},{type:"function",name:"getBlockNumber",stateMutability:"view",inputs:[],outputs:[{name:"blockNumber",type:"uint256"}]},{type:"function",name:"getCurrentBlockTimestamp",stateMutability:"view",inputs:[],outputs:[{name:"timestamp",type:"uint256"}]}];var q=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"decimals",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint8"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"allowance",stateMutability:"view",inputs:[{name:"owner",type:"address"},{name:"spender",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"approve",stateMutability:"nonpayable",inputs:[{name:"spender",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transfer",stateMutability:"nonpayable",inputs:[{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"function",name:"transferFrom",stateMutability:"nonpayable",inputs:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"amount",type:"uint256"}],outputs:[{name:"",type:"bool"}]},{type:"event",name:"Transfer",inputs:[{name:"from",type:"address",indexed:!0},{name:"to",type:"address",indexed:!0},{name:"value",type:"uint256",indexed:!1}]},{type:"event",name:"Approval",inputs:[{name:"owner",type:"address",indexed:!0},{name:"spender",type:"address",indexed:!0},{name:"value",type:"uint256",indexed:!1}]}],kr=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]}];var vr=[{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"owner",type:"address"}],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"ownerOf",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"address"}]},{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"string"}]},{type:"function",name:"tokenURI",stateMutability:"view",inputs:[{name:"tokenId",type:"uint256"}],outputs:[{name:"",type:"string"}]},{type:"function",name:"totalSupply",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]}];var Aa=[{type:"function",name:"uri",stateMutability:"view",inputs:[{name:"id",type:"uint256"}],outputs:[{name:"",type:"string"}]},{type:"function",name:"balanceOf",stateMutability:"view",inputs:[{name:"account",type:"address"},{name:"id",type:"uint256"}],outputs:[{name:"",type:"uint256"}]}];var wt=[{type:"function",name:"asset",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"totalAssets",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint256"}]},{type:"function",name:"convertToAssets",stateMutability:"view",inputs:[{name:"shares",type:"uint256"}],outputs:[{name:"assets",type:"uint256"}]},{type:"function",name:"convertToShares",stateMutability:"view",inputs:[{name:"assets",type:"uint256"}],outputs:[{name:"shares",type:"uint256"}]}];var Tr=class extends F{name="ChainNotFoundError";constructor(e){super(`Chain "${e}" is not supported.`,{metaMessages:["Add it to `chain/chains/definitions.ts`, or pass an explicit `transport`/`rpcUrl`."]})}},In=class extends F{name="ClientChainNotConfiguredError";constructor(){super("No chain was configured on the client.",{metaMessages:["Pass `chain` to createPublicClient(), or pass the address the action needs explicitly."]})}},Jt=class extends F{name="ChainDoesNotSupportContractError";constructor({chain:e,contract:t,blockNumber:r}){super(r!==void 0?`Chain "${e}" does not support contract "${t}" at block ${r}.`:`Chain "${e}" does not support contract "${t}".`,{metaMessages:["Pass the contract address explicitly to use it on this chain."]})}};async function dl(n,e,t){let r=new Array(n.length);if(n.length===0)return r;let o=0,s=Math.max(1,Math.min(e>0?e:n.length,n.length));async function a(){for(;;){let i=o++;if(i>=n.length)return;try{r[i]={status:"fulfilled",value:await t(n[i],i)}}catch(l){r[i]={status:"rejected",reason:l}}}}return await Promise.all(Array.from({length:s},a)),r}function fs({blockNumber:n,chain:e,contract:t}){let r=e.contracts?.[t];if(!r)throw new Jt({chain:e.name,contract:t});if(n!==void 0&&r.blockCreated!==void 0&&r.blockCreated>Number(n))throw new Jt({blockNumber:n,chain:e.name,contract:t});return r.address}var Ar=class extends F{name="RawContractError";data;constructor({data:e,shortMessage:t="The contract call reverted."}){super(t),this.data=e}},pl=class extends F{name="ContractFunctionRevertedError";errorName;errorArgs;reason;data;constructor({abi:e,data:t,functionName:r}){let o=t?ds({abi:e,data:t}):void 0,s,a;if(t&&t!=="0x")try{let i=dr({abi:e,data:t});s=i.errorName,a=i.args}catch{}super(o?`The contract function "${r??"call"}" reverted with the following reason:
3
- ${o}`:`The contract function "${r??"call"}" reverted.`,{metaMessages:t&&t!=="0x"?[`Revert data: ${t}`]:[]}),this.reason=o,this.errorName=s,this.errorArgs=a,this.data=t}},ml=class extends F{name="ContractFunctionZeroDataError";constructor({functionName:e}){super(`The contract function "${e??"call"}" returned no data ("0x").`,{metaMessages:["This usually means:","- the address is not a contract on this chain,","- the ABI does not match the deployed contract, or","- the block predates the contract deployment."]})}},hl=class extends F{name="ContractFunctionExecutionError";abi;address;args;functionName;constructor(e,{abi:t,address:r,args:o,functionName:s,sender:a}){let i=t&&s?Xt({abi:t,name:s,args:o}):void 0,l=i?ir(i):s,c=o&&o.length>0?` args: (${o.map(u=>lm(u)).join(", ")})`:void 0,d=i?.inputs?.length?`(${i.inputs.map(cs).join(", ")})`:"()";super(e instanceof F?e.shortMessage:`An error occurred calling "${s??"contract"}".`,{cause:e,metaMessages:[...r?[`Contract: ${r}`]:[],...l?[`Function: ${l}${i?"":d}`]:[],...c?[c]:[],...a?[`Sender: ${a}`]:[]]}),this.abi=t,this.address=r,this.args=o,this.functionName=s}},gs=class extends F{name="CallExecutionError";constructor(e,{to:t,data:r}){super(e instanceof F?e.shortMessage:"The call failed.",{cause:e,metaMessages:[...t?[`To: ${t}`]:[],...r?[`Data: ${r}`]:[]]})}};function lm(n){if(typeof n=="bigint")return n.toString();if(typeof n=="string")return n;try{return JSON.stringify(n,(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return String(n)}}function du(n){if(!n||typeof n!="object")return;let e=n,t=e.data;if(typeof t=="string"&&t.startsWith("0x"))return t;if(t&&typeof t=="object"){let r=t.data;if(typeof r=="string"&&r.startsWith("0x"))return r}return e.cause?du(e.cause):void 0}function Pr(n,{abi:e,address:t,args:r,functionName:o,sender:s}){let a=du(n),i=n instanceof Yt?new ml({functionName:o}):a!==void 0?new pl({abi:e,data:a,functionName:o}):n;return new hl(i,{abi:e,address:t,args:r,functionName:o,sender:s})}var fl=new Map;function ys({fn:n,id:e,shouldSplitBatch:t,wait:r=0}){let o=()=>fl.get(e)??void 0,s=i=>fl.set(e,i),a=async i=>{o()===i&&fl.delete(e);try{let l=await n(i.map(c=>c.item));i.forEach((c,d)=>c.resolve(l[d]))}catch(l){i.forEach(c=>c.reject(l))}};return{schedule(i){return new Promise((l,c)=>{let d={item:i,resolve:l,reject:c},u=o();if(u)if(t?.([...u.map(m=>m.item),i]))a(u);else{u.push(d);return}let p=[d];s(p),setTimeout(()=>{a(p)},r)})}}}function cm(n){return!!(n.data&&n.to&&!n.account&&!n.value&&!n.gas&&!n.gasPrice&&!n.maxFeePerGas&&!n.maxPriorityFeePerGas&&n.nonce===void 0&&!n.stateOverride)}async function um(n,e){let{batchSize:t=1024,wait:r=0}=typeof n.batch?.multicall=="object"?n.batch.multicall:{},{blockNumber:o,blockTag:s="latest",data:a,to:i}=e;if(!n.chain)throw new In;let l=fs({blockNumber:o,chain:n.chain,contract:"multicall3"});if(!await Ln(n,l,!1))throw new Jt({chain:n.chain.name,contract:"multicall3"});let c=o!==void 0?Fe(o):s,{schedule:d}=ys({id:`${n.uid}.call.${c}`,wait:r,shouldSplitBatch:m=>m.reduce((f,h)=>f+(h.data.length-2)/2,0)>t,fn:async m=>{let f=M({abi:ct,functionName:"aggregate3",args:[m.map(g=>({allowFailure:!0,callData:g.data,target:g.to}))]}),h=await n.request({method:"eth_call",params:[{to:l,data:f},c]});return yt({abi:ct,functionName:"aggregate3",data:h})}}),{returnData:u,success:p}=await d({data:a,to:i});if(!p)throw new Ar({data:u});return u}async function kt(n,e){let{blockNumber:t,blockTag:r,stateOverride:o,skipBatch:s,...a}=e;if(n.batch?.multicall&&!s&&cm(e))try{let l=await um(n,{blockNumber:t,blockTag:r,data:a.data,to:a.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof In||l instanceof Jt))throw new gs(l,{to:a.to,data:a.data})}let i=[hs(a),bt({blockNumber:t,blockTag:r})];o&&i.push(cl(o));try{let l=await n.request({method:"eth_call",params:i});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new gs(l,{to:a.to,data:a.data})}}var gl=8;function pu(n,e){if(e!==void 0&&e>0)return e;let t=typeof n.batch?.multicall=="object"?n.batch.multicall.fallbackConcurrency:void 0;return t!==void 0&&t>0?t:gl}function bs(n,e,t){if(e)return e;if(!n.chain)throw new In;let r=n.chain.contracts?.multicall3;return r?t!==void 0&&r.blockCreated!==void 0&&r.blockCreated>Number(t)?re:r.address:re}async function Sr(n,e,t={}){let{concurrency:r,account:o,blockNumber:s,blockTag:a,stateOverride:i}=t;return(await dl(e,pu(n,r),async c=>{let{data:d}=await kt(n,{to:c.target,data:c.callData,account:o,blockNumber:s,blockTag:a,stateOverride:i,skipBatch:!0});return d??"0x"})).map(c=>c.status==="fulfilled"?{success:!0,returnData:c.value}:{success:!1,returnData:"0x",error:c.reason})}async function vt(n,e){let{abi:t,address:r,functionName:o,args:s,...a}=e;try{let i=M({abi:t,functionName:o,args:s}),{data:l}=await kt(n,{...a,to:r,data:i});return yt({abi:t,functionName:o,args:s,data:l??"0x"})}catch(i){throw Pr(i,{abi:t,address:r,args:s,functionName:o,sender:a.account})}}var dm=1024,pm=50;async function Zt(n,e){let{calls:t,account:r,blockNumber:o,blockTag:s,batchSize:a=dm,maxCalls:i=pm,multicallAddress:l,stateOverride:c,fallbackConcurrency:d}=e,u=t.map(()=>({success:!1,returnData:"0x"}));if(t.length===0)return u;let p=bs(n,l,o),m=[];if(t.forEach((b,y)=>{R(b.target)&&xn(b.callData)&&m.push({index:y,call:b})}),m.length===0)return u;if(!await Ln(n,p,l!==void 0))return(await Sr(n,m.map(y=>y.call),{account:r,blockNumber:o,blockTag:s,stateOverride:c,concurrency:d})).forEach((y,w)=>{u[m[w].index]={success:y.success,returnData:y.returnData}}),u;let f=[],h;return m.forEach(({call:b,index:y})=>{let w=(b.callData.length-2)/2,k=a>0&&h!==void 0&&h.size+w>a,v=i>0&&h!==void 0&&h.calls.length>=i;(!h||(k||v)&&h.calls.length>0)&&(h={calls:[],indexes:[],size:0},f.push(h)),h.calls.push(b),h.indexes.push(y),h.size+=w}),(await Promise.allSettled(f.map(b=>vt(n,{abi:ct,address:p,functionName:"aggregate3",args:[b.calls.map(y=>({target:y.target,allowFailure:!0,callData:y.callData}))],account:r,blockNumber:o,blockTag:s,stateOverride:c})))).forEach((b,y)=>{b.status==="fulfilled"&&f[y].indexes.forEach((w,k)=>{let v=b.value[k];v&&(u[w]={success:!!v.success,returnData:v.returnData??"0x"})})}),u}var mu="https://wallet-api.pantograph.app/keyring/chains_v6",mm=6,hm=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,hu={},xr=null;function fm(n){let e=Array.isArray(n.rpcs)?n.rpcs:[],t=typeof n.linkProvider=="string"?[n.linkProvider]:[],r=[];for(let o of[...t,...e]){if(typeof o!="string")continue;let s=o.trim();if(!(!s.startsWith("https://")||hm.test(s))&&(r.includes(s)||r.push(s),r.length>=mm))break}return r}function fu(n){if(!n||typeof n!="object"||Array.isArray(n))return{};let e={};for(let[t,r]of Object.entries(n)){if(!r||typeof r!="object")continue;let o=r,s=Tt(t)??(typeof o.chainId=="number"?Tt(o.chainId):void 0);if(!s)continue;let a=fm(o);a.length>0&&(e[s]=a)}return e}function gu(n){hu=n}function yl(n){let e=Tt(n);return e?hu[e]??[]:[]}function bl(){xr||Pa()}function Pa(n={}){let{url:e=mu,force:t=!1,debug:r=!1}=n;return xr&&!t||(xr=(async()=>{try{let o=await C.get(e);if(!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);let s=fu(o.data),a=Object.keys(s).length;if(a===0)throw new Error("catalogue contained no usable RPC endpoints");return gu(s),r&&console.log(`[chains] loaded RPC endpoints for ${a} chains from ${e}`),!0}catch(o){if(r){let s=o instanceof Error?o.message:String(o);console.warn(`[chains] remote RPC catalogue unavailable (${s}); using built-in endpoints`)}return xr=null,!1}})()),xr}var gm=new Map(Nn.map(n=>[n.hexId.toLowerCase(),n])),ym=new Map(Nn.map(n=>[n.id,n]));function Tt(n){if(typeof n=="number")return Number.isFinite(n)&&n>=0?`0x${n.toString(16)}`:void 0;let e=n.trim().toLowerCase();if(e)return e.startsWith("0x")?/^0x[0-9a-f]+$/.test(e)?e:void 0:/^\d+$/.test(e)?`0x${Number(e).toString(16)}`:void 0}function Ce(n){if(typeof n=="number")return ym.get(n);let e=Tt(n);return e?gm.get(e):void 0}function Un(n){return Ce(n)?.nativeCurrency}var Xe=Object.fromEntries(Nn.map(n=>[n.hexId,n.rpcUrls.default.http[0]]));function wl(n){return Ce(n)?.rpcUrls.default.http[0]}var kl={};function Dn(n){let e={};if(n)for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=Tt(t)??t.toLowerCase();e[o]=r.trim()}kl=e}function ws(){return{...kl}}function On(n){bl();let e=Tt(n),t=e?kl[e]:void 0,r=yl(n),o=Ce(n)?.rpcUrls.default.http??[];return[...new Set([...t?[t]:[],...r,...o])]}function Mn(n){return On(n)[0]}function vl(n){let e=Ce(n);if(!e)return;let t=On(n),r=e.rpcUrls.default.http;return t.length===0||t.length===r.length&&t.every((o,s)=>o===r[s])?e:{...e,rpcUrls:{default:{http:t}}}}var en=class extends F{name="HttpRequestError";status;url;body;headers;constructor({body:e,details:t,headers:r,status:o,url:s}){super("HTTP request failed.",{details:t,metaMessages:[`URL: ${s}`,...o?[`Status: ${o}`]:[],...e?[`Request body: ${JSON.stringify(e)}`]:[]]}),this.status=o,this.url=s,this.body=e,this.headers=r}},Cr=class extends F{name="TimeoutError";constructor({body:e,url:t,timeout:r}){super("The request took too long to respond.",{details:`The request timed out after ${r}ms.`,metaMessages:[`URL: ${t}`,...e?[`Request body: ${JSON.stringify(e)}`]:[]]})}},Rr=class extends F{name="NetworkError";constructor({cause:e,url:t}){super("Could not reach the RPC endpoint.",{cause:e,metaMessages:[`URL: ${t}`]})}},Sa=class extends F{name="UrlRequiredError";constructor(){super("No RPC URL was provided.",{metaMessages:['Pass one to the transport \u2014 http("https://\u2026") \u2014 or give the client a chain that has a default RPC URL.']})}},ks=class extends F{name="FallbackTransportError";constructor({cause:e,count:t}){super(`All ${t} fallback transports failed.`,{cause:e})}};var Er=class extends F{name="RpcRequestError";code;data;constructor({body:e,error:t,url:r,shortMessage:o}){super(o??"RPC request failed.",{details:t.message,metaMessages:[...r?[`URL: ${r}`]:[],...e?[`Request body: ${JSON.stringify(e)}`]:[],`Error code: ${t.code}`]}),this.code=t.code,this.data=t.data}};function Qe(n,e,t){return class extends Er{static code=e;name=n;constructor(r){super({...r,shortMessage:t})}}}var bm=Qe("ParseRpcError",-32700,"The node could not parse the JSON request."),wm=Qe("InvalidRequestRpcError",-32600,"The JSON request is not valid."),km=Qe("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),vm=Qe("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),Tm=Qe("InternalRpcError",-32603,"The node reported an internal error."),Am=Qe("InvalidInputRpcError",-32e3,"The RPC input is not valid."),Pm=Qe("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),Sm=Qe("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),xm=Qe("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),Cm=Qe("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),Tl=Qe("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),Rm=Qe("UserRejectedRequestError",4001,"The user rejected the request."),Em=new Map([[-32700,bm],[-32600,wm],[-32601,km],[-32602,vm],[-32603,Tm],[-32e3,Am],[-32001,Pm],[-32002,Sm],[-32003,xm],[-32004,Cm],[-32005,Tl],[4001,Rm]]);function yu(n){let e=Em.get(n.error.code);return e?new e(n):new Er(n)}function bu(n){return new Promise(e=>setTimeout(e,n))}async function Al(n,{retryCount:e=2,delay:t=150,shouldRetry:r=()=>!0}={}){let o=0;for(;;)try{return await n()}catch(s){if(o++,o>e||!r({count:o,error:s}))throw s;let a=typeof t=="function"?t({count:o,error:s}):t*2**(o-1);a>0&&await bu(a)}}function Pl(n){let e=n?.["retry-after"];if(!e)return;let t=Number(e);if(Number.isFinite(t))return t*1e3;let r=Date.parse(e);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var _m=new Set([408,413,429,500,502,503,504]),Nm=new Set([401,402,403]);function xa(n){return n instanceof Cr||n instanceof Rr?!0:n instanceof en?n.status?_m.has(n.status)||n.status>=500:!0:n instanceof Tl?!0:n instanceof Er?n.code===-32603:!1}function Ca(n){return n instanceof en&&n.status&&Nm.has(n.status)?!0:xa(n)}function Ra(n,{retryCount:e=3,retryDelay:t=150}={}){return function(o,s={}){return Al(()=>n(o),{retryCount:s.retryCount??e,shouldRetry:({error:a})=>xa(a),delay:({count:a,error:i})=>{let l=i instanceof en?Pl(i.headers):void 0;return l!==void 0?l:(s.retryDelay??t)*2**(a-1)}})}}function tn({key:n,name:e,type:t,request:r,retryCount:o=3,retryDelay:s=150,timeout:a=1e4},i){return{config:{key:n,name:e,type:t,request:r,retryCount:o,retryDelay:s,timeout:a},request:Ra(r,{retryCount:o,retryDelay:s}),value:i}}function nn(n,e={}){let{key:t="fallback",name:r="Fallback",retryCount:o=0,retryDelay:s,onTransportError:a}=e;return(i={})=>{let l=n.map(d=>d(i));if(l.length===0)throw new ks({count:0});return tn({key:t,name:r,type:"fallback",request:async d=>{let u;for(let p=0;p<l.length;p++)try{return await l[p].request(d)}catch(m){if(u=m,a?.({error:m,index:p,method:d.method}),!Ca(m))throw m}throw new ks({cause:u,count:l.length})},retryCount:o,retryDelay:s,timeout:i.timeout},{transports:l})}}var wu=0;function ku(){return wu+=1,wu}function Lm(n){let e=n?.code;if(e==="ECONNABORTED"||e==="ETIMEDOUT")return!0;let t=n?.message??"";return/timeout/i.test(t)}var _r=class{url;timeout;fetchOptions;constructor(e,{timeout:t=1e4,fetchOptions:r={}}={}){this.url=e,this.timeout=t,this.fetchOptions=r}async post(e){let t;try{t=await C.post(this.url,e,{...this.fetchOptions,timeout:this.timeout,headers:{"Content-Type":"application/json",...this.fetchOptions.headers}})}catch(r){throw Lm(r)?new Cr({body:e,url:this.url,timeout:this.timeout}):new Rr({cause:r,url:this.url})}if(!t.ok)throw new en({body:e,details:_(t),headers:t.headers,status:t.status,url:this.url});return t.data}async request(e){let t={jsonrpc:"2.0",id:ku(),...e};return await this.post(t)??{id:t.id}}async requestBatch(e){let t=e.map(s=>({jsonrpc:"2.0",id:ku(),...s})),r=await this.post(t);if(!Array.isArray(r))return t.map(s=>({id:s.id,error:r?.error??{code:-32603,message:"Malformed batch response."}}));let o=new Map(r.map(s=>[s.id,s]));return t.map((s,a)=>o.get(s.id)??r[a]??{id:s.id,error:{code:-32603,message:"Missing response for batched request."}})}};function vu(n,e,t){if(n.error)throw yu({body:e,error:n.error,url:t});return n.result}function ut(n,e={}){let{batch:t,fetchOptions:r,key:o="http",name:s="HTTP JSON-RPC",retryCount:a,retryDelay:i,timeout:l}=e;return({chain:c,retryCount:d,retryDelay:u,timeout:p}={})=>{let{batchSize:m=1e3,wait:f=0}=typeof t=="object"?t:{},h=l??p??1e4,g=n??c?.rpcUrls.default.http[0];if(!g)throw new Sa;let b=new _r(g,{timeout:h,fetchOptions:r});return tn({key:o,name:s,type:"http",retryCount:a??d,retryDelay:i??u,timeout:h,async request({method:y,params:w}){let k={method:y,params:w};if(t){let{schedule:v}=ys({id:`${g}:${m}:${f}`,wait:f,shouldSplitBatch:S=>S.length>m,fn:S=>b.requestBatch(S)});return vu(await v(k),k,g)}return vu(await b.request(k),k,g)}},{url:g})}}var Im=1024;async function Nr(n,e){let{contracts:t,allowFailure:r=!0,account:o,blockNumber:s,blockTag:a,multicallAddress:i,stateOverride:l,fallbackConcurrency:c}=e,d=e.batchSize??(typeof n.batch?.multicall=="object"&&n.batch.multicall.batchSize||Im),u=new Array(t.length);if(t.length===0)return r?u:[];let p=bs(n,i,s),m=[],f;t.forEach((b,y)=>{let{abi:w,address:k,functionName:v,args:S}=b,P;try{if(!R(k))throw new rr(k);P=M({abi:w,functionName:v,args:S})}catch(I){let E=Pr(I,{abi:w,address:k,args:S,functionName:v,sender:o});if(!r)throw E;u[y]={status:"failure",error:E};return}let x=(P.length-2)/2;(!f||d>0&&f.size+x>d&&f.calls.length>0)&&(f={calls:[],indexes:[],size:0},m.push(f)),f.calls.push({target:k,allowFailure:!0,callData:P}),f.indexes.push(y),f.size+=x}),(await Ln(n,p,i!==void 0)?await Promise.allSettled(m.map(b=>vt(n,{abi:ct,address:p,functionName:"aggregate3",args:[b.calls],account:o,blockNumber:s,blockTag:a,stateOverride:l}))):await(async()=>{let b=m.flatMap(w=>w.calls.map((k,v)=>({target:k.target,callData:k.callData,index:w.indexes[v]}))),y=await Sr(n,b,{account:o,blockNumber:s,blockTag:a,stateOverride:l,concurrency:c});return m.length=0,y.map((w,k)=>(m.push({calls:[],indexes:[b[k].index],size:0}),w.success?{status:"fulfilled",value:[{success:!0,returnData:w.returnData}]}:{status:"rejected",reason:w.error}))})()).forEach((b,y)=>{let w=m[y];if(b.status==="rejected"){for(let k of w.indexes){let v=t[k],S=Pr(b.reason,{abi:v.abi,address:v.address,args:v.args,functionName:v.functionName,sender:o});if(!r)throw S;u[k]={status:"failure",error:S}}return}w.indexes.forEach((k,v)=>{let S=t[k],P=b.value[v];try{if(!P)throw new Error("Multicall returned fewer results than calls.");if(!P.success)throw new Ar({data:P.returnData});if(!P.returnData||P.returnData==="0x")throw new Yt;let x=yt({abi:S.abi,functionName:S.functionName,args:S.args,data:P.returnData});u[k]={status:"success",result:x}}catch(x){let I=Pr(x,{abi:S.abi,address:S.address,args:S.args,functionName:S.functionName,sender:o});if(!r)throw I;u[k]={status:"failure",error:I}}})});for(let b=0;b<t.length;b++){if(u[b])continue;let y=new Error("Multicall returned no result for this call.");if(!r)throw y;u[b]={status:"failure",error:y}}return r?u:u.map(b=>b.result)}var Um=0,Fn=class{key;name;uid;chain;transport;batch;request;constructor(e={}){let{batch:t,key:r="public",name:o="Public Client",retryCount:s,retryDelay:a,timeout:i}=e;this.chain=Om(e.chain),this.key=r,this.name=o,this.batch=t,this.uid=`${r}-${++Um}-${Math.random().toString(36).slice(2,8)}`;let c=(e.transport??Dm(e.rpcUrl,this.chain))({chain:this.chain,retryCount:s,retryDelay:a,timeout:i});this.transport={...c.config,...c.value},this.request=c.request}call(e){return kt(this,e)}readContract(e){return vt(this,e)}multicall(e){return Nr(this,e)}multicallRaw(e){return Zt(this,e)}getBlockNumber(){return pr(this)}getChainId(){return mr(this)}getBalance(e){return hr(this,e)}getCode(e){return Qt(this,e)}getStorageAt(e){return fr(this,e)}getTransactionCount(e){return gr(this,e)}getGasPrice(){return yr(this)}estimateMaxPriorityFeePerGas(){return Ta(this)}estimateGas(e){return br(this,e)}getBlock(e){return wr(this,e)}rpc(e,t){return this.request({method:e,params:t})}extend(e){let t=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return Object.assign(t,e(t))}};function Dm(n,e){if(n)return ut(n);let t=e?.rpcUrls.default.http??[];return t.length>1?nn(t.map(r=>ut(r,{retryCount:1}))):ut(t[0])}function Om(n){if(n===void 0)return;if(typeof n=="object")return n;let e=vl(n);if(!e)throw new Tr(n);return e}function rn(n={}){return new Fn(n)}var Sl=new Map;function Mm(n,e){return{id:parseInt(n,16),hexId:n,name:`Chain ${parseInt(n,16)}`,nativeCurrency:{name:"Native",symbol:"ETH",decimals:18},rpcUrls:{default:{http:e}},contracts:{multicall3:{address:re}}}}function Re(n,e={}){let{batch:t=!0,pinRpcUrl:r=!1,fallbackConcurrency:o,assumeMulticall3:s}=e,a=Tt(n),i=e.rpcUrl?.trim(),l=a?On(a):[],c=i?r?[i]:[...new Set([i,...l])]:l;if(c.length===0)throw new Tr(n);let d=`${a??n}|${c.join(",")}|${t?1:0}|${o??""}|${s?1:0}`,u=Sl.get(d);if(u)return u;let p=rn({chain:a&&!Ce(a)?Mm(a,c):a,transport:c.length===1?ut(c[0]):nn(c.map(m=>ut(m,{retryCount:1}))),batch:t?{multicall:{fallbackConcurrency:o,assumeMulticall3:s}}:void 0});return Sl.set(d,p),p}function Ea(){Sl.clear()}function Cl(n,e){try{return Re(n,{rpcUrl:e?.trim()||void 0})}catch{return null}}async function Te(n,e,t){let r=new Array(e.length).fill(null),o=e.length>0?Cl(n,t):null;if(!o)return r;let s=[];if(e.forEach((a,i)=>{!R(a.target)||!xn(a.callData)||s.push({index:i,target:a.target,callData:a.callData})}),s.length===0)return r;try{(await Zt(o,{calls:s})).forEach((i,l)=>{i.success&&(r[s[l].index]=i.returnData)})}catch{}return r}function _a(n){return n?.status==="success"?n.result:void 0}async function xl(n,e){try{return await n.multicall({contracts:e})}catch{return[]}}async function on(n,e,t){let r=e.map(()=>({symbol:null,decimals:null})),o=e.length>0?Cl(n,t):null;if(!o)return r;let s=[];if(e.forEach((l,c)=>{R(l)&&s.push({index:c,address:l})}),s.length===0)return r;let a=await xl(o,s.flatMap(l=>[{address:l.address,abi:q,functionName:"symbol"},{address:l.address,abi:q,functionName:"decimals"}]));s.forEach((l,c)=>{let d=_a(a[c*2]);typeof d=="string"&&d.trim()&&(r[l.index].symbol=d.trim()),r[l.index].decimals=wa(_a(a[c*2+1]))});let i=s.filter(l=>r[l.index].symbol===null);if(i.length>0){let l=await xl(o,i.map(c=>({address:c.address,abi:kr,functionName:"symbol"})));i.forEach((c,d)=>{r[c.index].symbol=ka(_a(l[d]))})}return r}async function Tu(n,e,t){let r=new Array(e.length).fill(null),o=e.length>0?Cl(n,t):null;if(!o)return r;let s=[];return e.forEach((i,l)=>{if(R(i.contract))try{s.push({index:l,address:i.contract,tokenId:BigInt(i.tokenId)})}catch{}}),s.length===0||(await xl(o,s.map(i=>({address:i.address,abi:vr,functionName:"tokenURI",args:[i.tokenId]})))).forEach((i,l)=>{let c=_a(i);if(typeof c!="string")return;let d=c.replace(/\0+$/,"").trim();d&&(r[s[l].index]=d)}),r}function vs(n){return Lr(String(n))??"0"}function Lr(n){let e=n.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let t=e[1]==="-"?"-":"",r=e[2]??"",o=e[3]??"";if(r===""&&o==="")return null;let s=e[4]?parseInt(e[4],10):0,a=r+o,i=r.length+s,l;return i<=0?l=`0.${"0".repeat(-i)}${a}`:i>=a.length?l=a+"0".repeat(i-a.length):l=`${a.slice(0,i)}.${a.slice(i)}`,l=l.replace(/^0+(?=\d)/,""),l.includes(".")&&(l=l.replace(/0+$/,"").replace(/\.$/,"")),(l===""||l==="-")&&(l="0"),l==="0"?"0":t+l}function Rl(n){let e=Lr(n);if(e===null||e.startsWith("-"))return null;let[t,r=""]=e.split(".");return{mant:BigInt(t+r),frac:r.length}}function Na(n,e){let t=n<0n,r=(t?-n:n).toString(),o;if(e===0)o=r;else{let s=r.padStart(e+1,"0"),a=s.length-e;o=`${s.slice(0,a)}.${s.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return t?`-${o}`:o}function Bn(n,e){let t=Lr(n);if(t===null||t.startsWith("-"))return null;let[r,o=""]=t.split("."),s=o.slice(0,e).padEnd(e,"0");try{let a=BigInt(r||"0")*10n**BigInt(e)+BigInt(s||"0");return a>0n?a:null}catch{return null}}function qn(n){if(typeof n=="number")return Number.isFinite(n)&&n>0?vs(n):null;if(typeof n!="string")return null;let e=n.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=Lr(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function Dt(n,e){let t=Lr(n);if(t===null||e<0)return n;let r=t.startsWith("-"),[o,s=""]=(r?t.slice(1):t).split(".");if(s.length<=e)return t;let a=e===0?o:`${o}.${s.slice(0,e)}`,i=a.includes(".")?a.replace(/0+$/,"").replace(/\.$/,""):a;return r?`-${i}`:i}function $n(n,e,t,r){let o=Rl(n);if(!o||t<=0n||r<0)return n;let s=o.mant*e*10n**BigInt(r)/(t*10n**BigInt(o.frac));return Na(s,r)}function sn(n,e){let t=Rl(n),r=Rl(e);if(!t||!r){let i=Number(n),l=Number(e);return i<l?-1:i>l?1:0}let o=Math.max(t.frac,r.frac),s=t.mant*10n**BigInt(o-t.frac),a=r.mant*10n**BigInt(o-r.frac);return s<a?-1:s>a?1:0}var Fm={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"}]},Bm="payment-required",qm="PAYMENT-SIGNATURE",$m="X-PAYMENT",Hm="payment-response",Vm="x-payment-response",Wm=600,Ym=300,Gm={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 Au(n){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(n),t=Array.from(e,r=>String.fromCharCode(r)).join("");return globalThis.btoa(t)}return Buffer.from(n,"utf8").toString("base64")}function Su(n){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return new TextDecoder("utf-8").decode(t)}return Buffer.from(n,"base64").toString("utf8")}function Km(){let n=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(n);else for(let t=0;t<32;t++)n[t]=Math.floor(Math.random()*256);return"0x"+Array.from(n,t=>t.toString(16).padStart(2,"0")).join("")}function xu(n){let e=String(n);if(e.includes(":")){let[r,o]=e.split(":"),s=parseInt(o,10);if(r!=="eip155"||Number.isNaN(s))throw new Error(`Unsupported x402 network: ${n} (only EVM "eip155:*" is supported)`);return s}let t=Gm[e.toLowerCase()];if(t===void 0)throw new Error(`Unsupported x402 network: ${n}`);return t}function Cu(n){if(!n.query||Object.keys(n.query).length===0)return n.url;let e=Object.entries(n.query).map(([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(r)}`).join("&");return n.url.includes("?")?`${n.url}&${e}`:`${n.url}?${e}`}function La(n){let e=n.headers[Bm];if(e){let o=Pu(jm(e));return o&&Array.isArray(o.accepts)?{version:2,payload:o}:null}let t=n.data,r=t&&typeof t=="object"?t:Pu(t);return r&&Array.isArray(r.accepts)?{version:1,payload:r}:null}function Pu(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e&&typeof e=="object"?e:null}catch{return null}}function jm(n){try{return Su(n)}catch{return null}}function zm(n){let e=n.amount??n.maxAmountRequired;return typeof n.scheme!="string"||typeof n.network!="string"||e==null||typeof n.asset!="string"||typeof n.payTo!="string"?null:{scheme:n.scheme,network:n.network,amount:String(e),asset:n.asset,payTo:n.payTo,...typeof n.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:n.maxTimeoutSeconds}:{},...n.extra&&typeof n.extra=="object"?{extra:n.extra}:{},...typeof n.resource=="string"?{resource:n.resource}:{},...typeof n.description=="string"?{description:n.description}:{},...typeof n.mimeType=="string"?{mimeType:n.mimeType}:{},...n.outputSchema!=null?{outputSchema:n.outputSchema}:{}}}function Xm(n){let e=null;for(let t of n){let r=zm(t);if(r){if(r.scheme!=="exact"){e=`unsupported scheme "${r.scheme}"`;continue}try{return xu(r.network),r}catch(o){e=o instanceof Error?o.message:String(o)}}}throw new Error(e?`No payable x402 requirement offered (${e}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function El(n,e,t,r){let o=La(n);if(!o)throw new Error("402 response carries no x402 payment requirements");let{version:s,payload:a}=o,i=Xm(a.accepts??[]);if(!t)throw new Error("No connected wallet address to build the payment from");let l=xu(i.network),c=Math.floor(Date.now()/1e3),d={from:t,to:i.payTo,value:String(i.amount),validAfter:String(Math.max(0,c-Wm)),validBefore:String(c+(i.maxTimeoutSeconds??Ym)),nonce:Km()},u={domain:{name:i.extra?.name,version:i.extra?.version,chainId:l,verifyingContract:i.asset},types:Fm,primaryType:"TransferWithAuthorization",message:{...d}};return{request:{url:Cu(e),method:e.method??"GET",body:e.body,headers:e.headers},x402Version:s,requirements:i,authorization:d,typedData:u,chainId:l,...a.resource!=null?{resource:a.resource}:{},...a.extensions!=null?{extensions:a.extensions}:{},...r?{userQuery:r}:{}}}async function Qm(n,e,t,r){let o=Cu(e),s=await n.request(e.method??"GET",o,e.body,{headers:e.headers});if(s.status===402)return{status:"payment_required",challenge:El(s,e,t,r)};if(!s.ok)throw new Error(_(s));return{status:"ok",data:s.data}}async function _l(n,e,t){let{url:r,method:o,body:s,headers:a}=e.request,i=await n.request(o,r,s,{headers:{...a??{},...Nl(e,t)}});if(i.ok)return i.data;throw new Error(Zm(i)??_(i))}function Jm(n){return La(n)!==null}function Ru(n){let e=Eu(n);return e?.errorReason?e.errorReason:La(n)?.payload.error??null}function Zm(n){let e=Ru(n);return e?`x402 payment rejected: ${e}`:null}var eh={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 Nl(n,e){let{requirements:t,authorization:r}=n,o={signature:e,authorization:r};if(n.x402Version===1){let a={x402Version:1,scheme:t.scheme,network:t.network,payload:o};return{[$m]:Au(JSON.stringify(a))}}let s={x402Version:2,...n.resource!=null?{resource:n.resource}:{},accepted:th(t),payload:o,...n.extensions!=null?{extensions:n.extensions}:{}};return{[qm]:Au(JSON.stringify(s))}}function th(n){let{resource:e,description:t,mimeType:r,outputSchema:o,...s}=n;return s}function Eu(n){let e=n.headers[Hm]??n.headers[Vm];if(!e)return null;try{return JSON.parse(Su(e))}catch{return null}}function nh(n,e){return n==null?e:eh[n]??`Chain ${n}`}async function _u(n){let e=n.requirements,r=n.resource?.description||e.description,o=n.chainId??null,s=null,a=null;if(o!=null){let[l]=await on("0x"+o.toString(16),[e.asset]);s=l?.symbol??null,a=l?.decimals??null}let i=String(e.amount);if(a!==null)try{i=Na(BigInt(e.amount),a)}catch{}return{amount:i,asset:s||e.extra?.name||"USDC",amountRaw:String(e.amount),decimals:a,assetAddress:e.asset,network:o!=null?`eip155:${o}`:e.network,networkRaw:e.network,chainId:o,networkLabel:nh(o,e.network),payTo:e.payTo,...r?{description:r}:{},resourceUrl:n.request.url}}function Ll(n){return async(e,t)=>{let r=n.getPayer(),o=n.getSigner();if(!r||!o)return null;let s;try{s=El(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},r)}catch{return null}let a;try{a=await o({typedData:s.typedData,display:await _u(s)})}catch{a=null}return a?Nl(s,a):null}}var an=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Hn(n){if(!n||typeof n!="object")return!1;let e=n;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function Ts(n){if(n?.aborted)throw new an}function Il(n,e){if(!e)return{signal:n.signal,cleanup:()=>{}};if(e.aborted)return n.abort(),{signal:n.signal,cleanup:()=>{}};let t=()=>n.abort();return e.addEventListener("abort",t),{signal:n.signal,cleanup:()=>e.removeEventListener("abort",t)}}var Nu={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},rh="https://nft.keyring.app/api/gemini-stable",oh="https://generativelanguage.googleapis.com",sh=new Set([408,429,500,502,503,504]),Lu=3e4,Ia=n=>new Promise(e=>setTimeout(e,n));function Ua(n,e,t){if(t!=null&&t>0)return Math.min(t,Lu);let r=Math.min(e*2**(n-1),Lu);return r/2+Math.random()*(r/2)}function ah(n){if(!n)return null;let e=Number(n);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(n);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var ke=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?oh:rh)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,t,r){let{systemInstruction:o,contents:s}=this.toContents(e),{maxRetries:a=5,retryDelayMs:i=1e3}=r??{},l=r?.signal??this.requestSignal;Ts(l);let c=s.length>0?s:[{role:"user",parts:[{text:"(continue)"}]}];if(r?._debug){console.log("[GeminiProvider] turn sequence:");for(let h of c){let g=h.parts.map(b=>b.functionCall?`fc:${b.functionCall.name}`:b.functionResponse?`fr:${b.functionResponse.name}`:`text:${(b.text??"").slice(0,40)}`).join(", ");console.log(` ${h.role}: [${g}]`)}}let d=r?.thinkingBudget??(r?.maxOutputTokens!=null?0:void 0),u={maxOutputTokens:r?.maxOutputTokens??this.maxTokens,temperature:this.temperature};d!=null&&(u.thinkingConfig={thinkingBudget:d});let p={contents:c,generationConfig:u};o&&(p.systemInstruction=o),t?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],r?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):r?.googleSearch&&(p.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,f="Unknown error";for(let h=1;h<=a;h++){Ts(l);let g;try{g=await C.post(m,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(P){if(Hn(P))throw P;if(f=P instanceof Error?P.message:String(P),h>=a)break;await Ia(Ua(h,i));continue}if(!g.ok){let P=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${g.status}: ${P}`,!sh.has(g.status))throw new Error(f);if(h>=a)break;let x=ah(g.headers["retry-after"]??null);await Ia(Ua(h,i,x));continue}if(g.data==null||typeof g.data!="object"){if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,h>=a)break;await Ia(Ua(h,i));continue}let b=g.data,y=b.candidates?.[0];if(!y)return{text:"",toolCalls:[]};let w="",k=[],v=y.content?.parts;if(!Array.isArray(v)||v.length===0){let P=y.finishReason;if(!(P==="SAFETY"||P==="RECITATION")&&h<a){f=`Gemini returned an empty turn (finishReason=${P??"none"})`,await Ia(Ua(h,i));continue}return{text:"",toolCalls:[]}}for(let P of v)P.text&&(w+=P.text),P.functionCall&&k.push({toolName:P.functionCall.name,args:P.functionCall.args??{},callId:P.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let S=b.usageMetadata?{promptTokens:b.usageMetadata.promptTokenCount??0,completionTokens:b.usageMetadata.candidatesTokenCount??0,totalTokens:b.usageMetadata.totalTokenCount??0}:void 0;return{text:w,toolCalls:k,usage:S}}throw new Error(f)}toContents(e){let t=[],r=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){r.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){r.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o=[];for(let i of r){let l=o[o.length-1],c=i.parts.some(u=>u.functionCall),d=l?.parts.some(u=>u.functionCall);l&&l.role===i.role&&!c&&!d?l.parts.push(...i.parts):o.push({...i,parts:[...i.parts]})}let s=[];for(let i=0;i<o.length;i++){let l=o[i],c=s[s.length-1];l.role==="function"&&!c?.parts.some(u=>u.functionCall)||l.role==="model"&&l.parts.some(u=>u.functionCall)&&!(o[i+1]?.role==="function")||s.push(l)}for(;s.length>0&&s[0].role!=="user";)s.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
4
- `)}]}:null,contents:s}}toFunctionDeclarations(e){return e.map(t=>{let r={},o=[];for(let s of t.parameters){let a={type:Nu[s.type]??"STRING",description:s.description};s.type==="array"&&(a.items={type:Nu[s.items?.type??"string"]??"STRING"}),r[s.name]=a,s.required&&o.push(s.name)}return{name:t.name,description:t.description,parameters:{type:"OBJECT",properties:r,required:o}}})}};var Ir=class{tools=new Map;register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(t=>t.category===e)}async execute(e,t,r){let o=this.tools.get(e);if(!o)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let s=Date.now();try{return{...await o.execute(t,r),duration:Date.now()-s}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-s}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};var Ur=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],ih=new Set(Ur),ln=[...Ur],Ul=new Set(ln),Je="0x1",Or="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function lh(n){return n.map(e=>Dr[e]??e).join(", ")}function Da(n){let e=new Set;if(n)for(let r of n){let o=Oa(r);o&&e.add(o)}let t=Ur.filter(r=>!e.has(r));ln=t.length>0?[...t]:[...Ur],Ul=new Set(ln),Je=ln.includes("0x1")?"0x1":ln[0],Or=lh(ln)}var ch={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function D(n){let e=Oa(n);return e&&Ul.has(e)?e:null}function Oa(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=ch[e];if(t)return t;let r=null;return/^0x[0-9a-f]+$/.test(e)?r=e:/^[0-9]+$/.test(e)&&(r="0x"+Number(e).toString(16)),r&&ih.has(r)?r:null}function Be(n){return D(n)!==null}function qe(){return[...ln]}var cn=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${Or}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Ot=n=>typeof n=="string"&&n.trim()!=="";function K(n,e){if(Ot(n)){let t=D(n);if(t)return t;throw new cn(n.trim())}if(Ot(e?.chain)){let t=D(e.chain);if(t)return t;throw new cn(e.chain.trim())}return null}function Ma(n,e){return D(n)??D(e?.chain)??void 0}var Dr={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea","0x64":"Gnosis","0x3e7":"HyperEVM","0x1388":"Mantle","0x8f":"Monad"};function T(n){let e=Oa(n);return e&&Dr[e]?Dr[e]:typeof n=="string"&&n.trim()?n.trim():"the requested chain"}var uh={"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 Iu(n,e){let t=Oa(n),r=t?uh[t]:void 0;return!r||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${r}/tx/${e.trim()}`}var dh={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function Uu(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return e?dh[e]??null:null}var ph={"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 Fa(n){let e=D(n);return e?ph[e]??null:null}function Ba(n,e){if(!Ot(n)||!Ot(e))return null;let t=D(n),r=D(e);return!t||!r||t===r?null:{from:t,to:r,fromLabel:Dr[t]??t,toLabel:Dr[r]??r}}function Mr(n){return`Hex chain ID of the ${n} \u2014 same ids as \`chain\` (e.g. "0xa" Optimism, "0x2105" Base). ONLY set this when the user names a chain FOR THIS SIDE SPECIFICALLY, i.e. they named a chain per token \u2014 "swap ETH on Optimism to ETH on Base", "buy USDC on Base using ETH on Arbitrum". When the user names ONE chain for the whole request (or none), leave this EMPTY and use \`chain\` instead. Never copy the same chain into both sides.`}function qa(n,e){return{error:"cross_chain_not_supported",_instructions:`The user asked to ${n} from ${e.fromLabel} to ${e.toLabel} \u2014 that is a CROSS-CHAIN (bridge) request, which is NOT supported: a ${n} happens entirely on ONE network. Tell them, in their language, that ${n}ping between two different networks isn't supported yet, and that they can ${n} between tokens that are both on ${e.fromLabel}, or both on ${e.toLabel} (switching their wallet's network first). Do NOT proceed. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var Ze=`Hex chain ID \u2014 e.g. "0xa" Optimism, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0x38" BSC, "0x1" Ethereum, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. Set this WHENEVER the user names a network anywhere in their request \u2014 "swap USDC on Optimism", "buy PEPE on Base", "\u0111\u1ED5i USDC tr\xEAn Optimism", "mua PEPE tr\xEAn Base" \u2014 by mapping that name to its hex id from the list above. Do this EVEN IF it differs from the wallet's currently connected chain: that is a normal request, and the wallet is asked to switch networks when the transaction is signed. NEVER substitute the connected chain for a network the user named, and never leave this empty just because the two differ. OMIT it only when the user names no network at all \u2014 the connected wallet chain is then used automatically.`;function Du(n,e){let t=typeof n=="string"?n.trim():"",r=e&&e.length?e.filter(s=>Ul.has(s)):[];return(r.length?r:ln).map(s=>{let a=Dr[s]??s;return{label:a,prompt:t?`${t} (${a})`:a}})}function Fr(n,e){return{actionButtons:Du(e),_instructions:`The user wants to ${n} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var ge=class extends Error{code="needs_chain_selection";buttons;constructor(e,t){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=Du(e,t)}},As=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 le(n,e){if(Ot(n))return n.trim();if(Ot(e?.walletAddress))return e.walletAddress.trim();throw new As}function Pe(n,e,t){if(Ot(n)){let r=D(n);if(r)return r;throw new cn(n.trim())}if(Ot(e?.chain)){let r=D(e.chain);if(r)return r;throw new cn(e.chain.trim())}if(Ot(e?.walletAddress))throw new ge(typeof e?.query=="string"?e.query:void 0,t);return Je}var A=class{category;async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a=mh(s);return{toolName:this.name,callId:r,success:!0,data:a.data,duration:Date.now()-o,...a.actionButtons?{actionButtons:a.actionButtons}:{},...a.ui?{ui:a.ui}:{}}}catch(s){return s instanceof ge?{toolName:this.name,callId:r,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-o,actionButtons:s.buttons}:s instanceof As?{toolName:this.name,callId:r,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-o}:{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}};function mh(n){if(!n||typeof n!="object")return{data:n};let e=n,t=e.actionButtons,r=Array.isArray(t)&&t.length>0?t:void 0,o=e.ui,s=o&&typeof o=="object"&&typeof o.component=="string"?o:void 0;if(!r&&!s)return{data:n};let{actionButtons:a,ui:i,...l}=e;return{data:l,...r?{actionButtons:r}:{},...s?{ui:s}:{}}}var hh="https://wallet-api.pantograph.app",fh="0x0000000000000000000000000000000000000000",Bu={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},qu={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"],"0x3e7":["0xbe6727b535545c67d5caa73dea54865b92cf7907","0x9fdbda0a5e284c32744d2f17ee5c74b284993463"],"0x1388":["0xdeaddeaddeaddeaddeaddeaddeaddeaddead1111","0xcabae6f6ea1ecab08ad02fe02ce9a44f09aebfa2"],"0x8f":["0xee8c0e9f1bffb4eb878d8f15f368a02a35481242","0x0555e30da8f98308edb960aa94c0db47230d2b9c"]};function gh(n){return Bu[n.toLowerCase()]||n}function Ou(n){let e=[];for(let[t,r]of Object.entries(n))if(r!=null)if(Array.isArray(r))for(let o of r)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);return e.join("&")}function Dl(n){let e=n,t=e.decimals,r=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,o=e.price,s=o!=null?parseFloat(String(o)):NaN,a=typeof e.symbolOnchain=="string"?e.symbolOnchain.trim():"";return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(r)?r:0,...a?{symbol:a}:{},...Number.isFinite(s)?{usd_price:s}:{}}}function Mu(n){if(Array.isArray(n))return n;let e=n;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function Ue(n){if(n==null)return null;let e=typeof n=="number"?n:parseFloat(String(n));return Number.isFinite(e)?e:null}function Fu(n,e){let t=n.decimals,r=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,o=Ue(n.price_change_percentage_24h)??Ue(n.priceChange24h)??Ue(n.usd_price_24hr_percent_change)??Ue(n.price_change_24h)??Ue(n.priceChange);return{chainId:e,tokenAddress:n.address??n.token_address??"",name:n.name??null,symbol:typeof n.symbolOnchain=="string"&&n.symbolOnchain.trim()||n.symbol||null,decimals:r!=null&&Number.isFinite(r)?r:null,logo:n.logoURI??n.icon_image??n.logo??null,usdPrice:Ue(n.price)??Ue(n.usd_price),marketCap:Ue(n.market_cap)??Ue(n.marketCap),totalVolume:{"24h":Ue(n.total_volume)??Ue(n.volume24h)},pricePercentChange:{"24h":o}}}var yh=100;function bh(n,e){let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t}var Ae=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??hh).replace(/\/+$/,"")}tokensUrl(e,t){let r=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${r}?addresses=${encodeURIComponent(t)}`}async fetchTokensAll(e,t){let r=bh(t,yh);return(await Promise.all(r.map(async s=>{try{let a=`${this.baseUrl}/keyrings/tokens/all/${e}?addresses=${encodeURIComponent(s.join(","))}`,i=await C.get(a);return i.ok?Mu(i.data):[]}catch{return[]}}))).flat()}async enrichTokenPrices(e,t){let r=new Map;if(e.length===0)return r;try{let o=e.map(i=>i.token_address),s=await this.fetchTokensAll(parseInt(t,16),o),a=new Map;for(let i of s)if(i.address){let l=i.address.toLowerCase(),c=typeof i.symbolOnchain=="string"?i.symbolOnchain.trim():"";a.set(l,{price:i.price!=null?parseFloat(String(i.price)):NaN,icon_image:i.icon_image,...c?{symbolOnchain:c}:{}}),("yieldProtocol"in i||"yieldAsset"in i)&&r.set(l,{yieldProtocol:i.yieldProtocol,yieldAsset:i.yieldAsset})}for(let i=0;i<e.length;i++){let l=a.get(e[i].token_address.toLowerCase());l&&(l.icon_image&&(e[i].logo=l.icon_image,e[i].thumbnail=l.icon_image),l.symbolOnchain&&(e[i].symbol=l.symbolOnchain),isNaN(l.price)||(e[i].usd_price=l.price,e[i].usd_value=parseFloat(e[i].balance_formatted||"0")*l.price))}}catch{}return r}async getYieldPricingTokens(e,t){let r=(t??[]).map(s=>String(s??"").trim()).filter(Boolean);if(r.length===0)return[];let o=typeof e=="number"?e:String(e).startsWith("0x")?parseInt(String(e),16):parseInt(String(e),10);if(!Number.isFinite(o))return[];try{return await this.fetchTokensAll(o,r)}catch{return[]}}async getTokenMetadata(e,t){try{let r=this.tokensUrl(t,e),o=await C.get(r);if(!o.ok)return null;let s=Mu(o.data),a=e.toLowerCase()===fh,i=s.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return i?Dl(i):null}catch{return null}}async getTokensMetadata(e,t){let r={};if(e.length===0)return r;try{let o=await this.fetchTokensAll(parseInt(t,16),e),s=new Set(e.map(a=>a.toLowerCase()));for(let a of o){let i=a.address?.toLowerCase()||a.token_address?.toLowerCase()||(a.address===""?"":null);i&&s.has(i)&&(r[i]=Dl(a))}}catch{}return r}async searchTokensByKey(e){let{key:t,chain:r}=e;if(!t)return{success:!1,error:"Search key is required"};let s=parseInt(r||Je,16);if(isNaN(s))return{success:!1,error:`Invalid hex chain: ${r}`};try{let a=Ou({chainId:s,key:t}),i=`${this.baseUrl}/token-list/all?${a}`,l=await C.get(i);if(!l.ok)throw new Error(_(l));let c=l.data,d=c?.result??c?.data??c,u=[];return Array.isArray(d)?u=d:d&&typeof d=="object"&&(u=Object.values(d).flat()),{success:!0,data:u.map(Dl)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||Je,r=5,o=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let s=qu[t.toLowerCase()]??[],a=o!=null?o+s.length:r+s.length,[i,l]=await Promise.allSettled([this.fetchTopGainers(t,a),s.length>0?this.getTokensMetadata(s,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],d=l.status==="fulfilled"?s.map(h=>l.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>Fu(h,t)):[],u=new Set,p=[];for(let h of d){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),p.push(h))}let m=[];for(let h of c){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),m.push(h))}let f=o!=null?[...p,...m].slice(0,o):[...p,...m.slice(0,r)];return await this.enrichTrendingMarketData(f,t),{success:!0,data:f}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let r=e.filter(s=>s.tokenAddress&&(s.marketCap==null||s.totalVolume?.["24h"]==null));if(r.length===0)return;let o=await this.getTokensMetadata(r.map(s=>s.tokenAddress),t);for(let s of r){let a=o[s.tokenAddress.toLowerCase()];a&&(s.marketCap==null&&(s.marketCap=Ue(a.market_cap)??Ue(a.marketCap)),s.totalVolume?.["24h"]==null&&(s.totalVolume={"24h":Ue(a.total_volume)??Ue(a.volume24h)}))}}async fetchTopGainers(e,t,r="24h"){let o=parseInt(e,16),s=Ou({chainId:o,duration:r,limit:t}),a=`${this.baseUrl}/token-list/all/top-gainers${s?`?${s}`:""}`,i=[];for(let l=0;l<5;l++){let c=await C.get(a);if(!c.ok)throw new Error(_(c));let d=c.data;if(i=Array.isArray(d)?d:Array.isArray(d.data)?d.data:[],i.length>0)break;l<4&&await new Promise(u=>setTimeout(u,2e3))}return i.map(l=>Fu(l,e))}async getTopGainers(e){let t=e?.chain||Je,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,o=e?.duration||"24h";try{let s=await this.fetchTopGainers(t,r,o);return await this.enrichTrendingMarketData(s,t),{success:!0,data:s}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}};function X(n,e,t,r=[]){return{target:n,callData:M({abi:e,functionName:t,args:r})}}var Vn=1e27,$a=10n**27n,Ps=31536e3,wh=10;function et(n){return Number.isFinite(n)&&n>=0&&n<=wh?n:null}function Ol(n){return Math.expm1(n)}function tt(n,e){return Number(n)/10**e}function Ss(n){return new Date(n).toISOString().slice(0,10)}async function un(n,e,t){let r=`${t.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${n.token}?range=h&day=${7}`,o=await C.get(r);if(!o.ok)throw new Error(_(o));return{samples:(Array.isArray(o.data)?o.data:o.data?.data||[]).filter(a=>a?.rate!==null&&a?.rate!==void 0).map(a=>({timeMs:Date.parse(a?.date??""),fraction:Number(a?.rate)})),current:null,rewards:[]}}var At=class{underlyingCall(e){return X(e.contract,wt,"asset")}liveRateCall(e,t){return null}followUpRateCall(e,t){return null}decodeSize(e,t){if(!Number.isInteger(t.decimals)||t.decimals<0)return null;let r=ee(e);return r===null?null:tt(r,t.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,t){return this.balanceIsUnderlying?null:X(e.contract,wt,"convertToAssets",[t])}},Pt=class extends At{type="spark";balanceIsUnderlying=!1;sizeCall(e){return X(e.contract,wt,"totalAssets")}fetchApy(e,t,r,o){return un(e,t,r)}};var Ml=[{type:"constructor",inputs:[{name:"owner_",type:"address",internalType:"address"},{name:"supportedRouter_",type:"address",internalType:"address"},{name:"nonfungiblePositionManager_",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"NATIVE_TOKEN",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getSupportedRouters",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"increaseLiquidity",inputs:[{name:"tokenId_",type:"uint256",internalType:"uint256"},{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"increaseLiquidityData_",type:"tuple",internalType:"struct CoinPoolGateway.IncreaseLiquidityData",components:[{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"mint",inputs:[{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"mintData_",type:"tuple",internalType:"struct CoinPoolGateway.MintData",components:[{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickLower",type:"int24",internalType:"int24"},{name:"tickUpper",type:"int24",internalType:"int24"},{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"nonfungiblePositionManager",inputs:[],outputs:[{name:"",type:"address",internalType:"contract INonfungiblePositionManager"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"pause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"paused",inputs:[],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"renounceOwnership",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"rescue",inputs:[{name:"token_",type:"address",internalType:"address"},{name:"amount_",type:"uint256",internalType:"uint256"},{name:"recipient_",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"transferOwnership",inputs:[{name:"newOwner",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unpause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"updateSupportedRouters",inputs:[{name:"routers_",type:"address[]",internalType:"address[]"},{name:"isSupported_",type:"bool[]",internalType:"bool[]"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"LiquidityIncreased",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Minted",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"Paused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"SupportedRoutersUpdated",inputs:[{name:"routers",type:"address[]",indexed:!1,internalType:"address[]"},{name:"isSupported",type:"bool[]",indexed:!1,internalType:"bool[]"}],anonymous:!1},{type:"event",name:"Unpaused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"EnforcedPause",inputs:[]},{type:"error",name:"ExpectedPause",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InsufficientAmountOut",inputs:[]},{type:"error",name:"InsufficientBalance",inputs:[{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidAmountIn",inputs:[]},{type:"error",name:"InvalidLength",inputs:[]},{type:"error",name:"InvalidRefundUnusedToken",inputs:[]},{type:"error",name:"InvalidSwapAction",inputs:[]},{type:"error",name:"InvalidTokenInInfo",inputs:[]},{type:"error",name:"InvalidTokenOutInfo",inputs:[]},{type:"error",name:"InvalidTotalAmountIn",inputs:[]},{type:"error",name:"NotSupportedRouter",inputs:[]},{type:"error",name:"OwnableInvalidOwner",inputs:[{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"OwnableUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"}]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedDecreaseAllowance",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"currentAllowance",type:"uint256",internalType:"uint256"},{name:"requestedDecrease",type:"uint256",internalType:"uint256"}]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}];var Fl=[{type:"function",name:"slot0",stateMutability:"view",inputs:[],outputs:[{name:"sqrtPriceX96",type:"uint160"},{name:"tick",type:"int24"},{name:"observationIndex",type:"uint16"},{name:"observationCardinality",type:"uint16"},{name:"observationCardinalityNext",type:"uint16"},{name:"feeProtocol",type:"uint8"},{name:"unlocked",type:"bool"}]},{type:"function",name:"liquidity",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint128"}]},{type:"function",name:"tickSpacing",stateMutability:"view",inputs:[],outputs:[{name:"",type:"int24"}]},{type:"function",name:"fee",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint24"}]},{type:"function",name:"token0",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"token1",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var Va=[{type:"function",name:"getReserveData",stateMutability:"view",inputs:[{name:"asset",type:"address"}],outputs:[{name:"reserveData",type:"tuple",components:[{name:"configuration",type:"uint256"},{name:"liquidityIndex",type:"uint128"},{name:"currentLiquidityRate",type:"uint128"}]}]}],Br=[{type:"function",name:"UNDERLYING_ASSET_ADDRESS",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"POOL",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}],Bl=[{type:"function",name:"ADDRESSES_PROVIDER",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var Mt=[{inputs:[],name:"getUtilization",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseToken",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"utilization",type:"uint256"}],name:"getSupplyRate",outputs:[{name:"",type:"uint64"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseTrackingSupplySpeed",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseIndexScale",outputs:[{name:"",type:"uint64"}],stateMutability:"pure",type:"function"}],ql=[{inputs:[{name:"comet",type:"address"}],name:"rewardConfig",outputs:[{name:"token",type:"address"},{name:"rescaleFactor",type:"uint64"},{name:"shouldUpscale",type:"bool"}],stateMutability:"view",type:"function"}];var qr=[{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"vsr",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],dn=[{inputs:[],name:"getAPR",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getConversionRate",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],$l=[{inputs:[],name:"susds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"usds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var Hl=[{inputs:[],name:"manager",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}],Vl=[{inputs:[],name:"pool",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var Th=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!, $reserve: ReserveRequest!) {
3
+ ${o}`:`The contract function "${r??"call"}" reverted.`,{metaMessages:t&&t!=="0x"?[`Revert data: ${t}`]:[]}),this.reason=o,this.errorName=s,this.errorArgs=a,this.data=t}},ml=class extends F{name="ContractFunctionZeroDataError";constructor({functionName:e}){super(`The contract function "${e??"call"}" returned no data ("0x").`,{metaMessages:["This usually means:","- the address is not a contract on this chain,","- the ABI does not match the deployed contract, or","- the block predates the contract deployment."]})}},hl=class extends F{name="ContractFunctionExecutionError";abi;address;args;functionName;constructor(e,{abi:t,address:r,args:o,functionName:s,sender:a}){let i=t&&s?Xt({abi:t,name:s,args:o}):void 0,l=i?ir(i):s,c=o&&o.length>0?` args: (${o.map(u=>lm(u)).join(", ")})`:void 0,d=i?.inputs?.length?`(${i.inputs.map(cs).join(", ")})`:"()";super(e instanceof F?e.shortMessage:`An error occurred calling "${s??"contract"}".`,{cause:e,metaMessages:[...r?[`Contract: ${r}`]:[],...l?[`Function: ${l}${i?"":d}`]:[],...c?[c]:[],...a?[`Sender: ${a}`]:[]]}),this.abi=t,this.address=r,this.args=o,this.functionName=s}},gs=class extends F{name="CallExecutionError";constructor(e,{to:t,data:r}){super(e instanceof F?e.shortMessage:"The call failed.",{cause:e,metaMessages:[...t?[`To: ${t}`]:[],...r?[`Data: ${r}`]:[]]})}};function lm(n){if(typeof n=="bigint")return n.toString();if(typeof n=="string")return n;try{return JSON.stringify(n,(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return String(n)}}function du(n){if(!n||typeof n!="object")return;let e=n,t=e.data;if(typeof t=="string"&&t.startsWith("0x"))return t;if(t&&typeof t=="object"){let r=t.data;if(typeof r=="string"&&r.startsWith("0x"))return r}return e.cause?du(e.cause):void 0}function Pr(n,{abi:e,address:t,args:r,functionName:o,sender:s}){let a=du(n),i=n instanceof Yt?new ml({functionName:o}):a!==void 0?new pl({abi:e,data:a,functionName:o}):n;return new hl(i,{abi:e,address:t,args:r,functionName:o,sender:s})}var fl=new Map;function ys({fn:n,id:e,shouldSplitBatch:t,wait:r=0}){let o=()=>fl.get(e)??void 0,s=i=>fl.set(e,i),a=async i=>{o()===i&&fl.delete(e);try{let l=await n(i.map(c=>c.item));i.forEach((c,d)=>c.resolve(l[d]))}catch(l){i.forEach(c=>c.reject(l))}};return{schedule(i){return new Promise((l,c)=>{let d={item:i,resolve:l,reject:c},u=o();if(u)if(t?.([...u.map(m=>m.item),i]))a(u);else{u.push(d);return}let p=[d];s(p),setTimeout(()=>{a(p)},r)})}}}function cm(n){return!!(n.data&&n.to&&!n.account&&!n.value&&!n.gas&&!n.gasPrice&&!n.maxFeePerGas&&!n.maxPriorityFeePerGas&&n.nonce===void 0&&!n.stateOverride)}async function um(n,e){let{batchSize:t=1024,wait:r=0}=typeof n.batch?.multicall=="object"?n.batch.multicall:{},{blockNumber:o,blockTag:s="latest",data:a,to:i}=e;if(!n.chain)throw new In;let l=fs({blockNumber:o,chain:n.chain,contract:"multicall3"});if(!await Ln(n,l,!1))throw new Jt({chain:n.chain.name,contract:"multicall3"});let c=o!==void 0?Fe(o):s,{schedule:d}=ys({id:`${n.uid}.call.${c}`,wait:r,shouldSplitBatch:m=>m.reduce((f,h)=>f+(h.data.length-2)/2,0)>t,fn:async m=>{let f=M({abi:ct,functionName:"aggregate3",args:[m.map(g=>({allowFailure:!0,callData:g.data,target:g.to}))]}),h=await n.request({method:"eth_call",params:[{to:l,data:f},c]});return yt({abi:ct,functionName:"aggregate3",data:h})}}),{returnData:u,success:p}=await d({data:a,to:i});if(!p)throw new Ar({data:u});return u}async function kt(n,e){let{blockNumber:t,blockTag:r,stateOverride:o,skipBatch:s,...a}=e;if(n.batch?.multicall&&!s&&cm(e))try{let l=await um(n,{blockNumber:t,blockTag:r,data:a.data,to:a.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof In||l instanceof Jt))throw new gs(l,{to:a.to,data:a.data})}let i=[hs(a),bt({blockNumber:t,blockTag:r})];o&&i.push(cl(o));try{let l=await n.request({method:"eth_call",params:i});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new gs(l,{to:a.to,data:a.data})}}var gl=8;function pu(n,e){if(e!==void 0&&e>0)return e;let t=typeof n.batch?.multicall=="object"?n.batch.multicall.fallbackConcurrency:void 0;return t!==void 0&&t>0?t:gl}function bs(n,e,t){if(e)return e;if(!n.chain)throw new In;let r=n.chain.contracts?.multicall3;return r?t!==void 0&&r.blockCreated!==void 0&&r.blockCreated>Number(t)?re:r.address:re}async function Sr(n,e,t={}){let{concurrency:r,account:o,blockNumber:s,blockTag:a,stateOverride:i}=t;return(await dl(e,pu(n,r),async c=>{let{data:d}=await kt(n,{to:c.target,data:c.callData,account:o,blockNumber:s,blockTag:a,stateOverride:i,skipBatch:!0});return d??"0x"})).map(c=>c.status==="fulfilled"?{success:!0,returnData:c.value}:{success:!1,returnData:"0x",error:c.reason})}async function vt(n,e){let{abi:t,address:r,functionName:o,args:s,...a}=e;try{let i=M({abi:t,functionName:o,args:s}),{data:l}=await kt(n,{...a,to:r,data:i});return yt({abi:t,functionName:o,args:s,data:l??"0x"})}catch(i){throw Pr(i,{abi:t,address:r,args:s,functionName:o,sender:a.account})}}var dm=1024,pm=50;async function Zt(n,e){let{calls:t,account:r,blockNumber:o,blockTag:s,batchSize:a=dm,maxCalls:i=pm,multicallAddress:l,stateOverride:c,fallbackConcurrency:d}=e,u=t.map(()=>({success:!1,returnData:"0x"}));if(t.length===0)return u;let p=bs(n,l,o),m=[];if(t.forEach((b,y)=>{R(b.target)&&xn(b.callData)&&m.push({index:y,call:b})}),m.length===0)return u;if(!await Ln(n,p,l!==void 0))return(await Sr(n,m.map(y=>y.call),{account:r,blockNumber:o,blockTag:s,stateOverride:c,concurrency:d})).forEach((y,w)=>{u[m[w].index]={success:y.success,returnData:y.returnData}}),u;let f=[],h;return m.forEach(({call:b,index:y})=>{let w=(b.callData.length-2)/2,k=a>0&&h!==void 0&&h.size+w>a,v=i>0&&h!==void 0&&h.calls.length>=i;(!h||(k||v)&&h.calls.length>0)&&(h={calls:[],indexes:[],size:0},f.push(h)),h.calls.push(b),h.indexes.push(y),h.size+=w}),(await Promise.allSettled(f.map(b=>vt(n,{abi:ct,address:p,functionName:"aggregate3",args:[b.calls.map(y=>({target:y.target,allowFailure:!0,callData:y.callData}))],account:r,blockNumber:o,blockTag:s,stateOverride:c})))).forEach((b,y)=>{b.status==="fulfilled"&&f[y].indexes.forEach((w,k)=>{let v=b.value[k];v&&(u[w]={success:!!v.success,returnData:v.returnData??"0x"})})}),u}var mu="https://wallet-api.pantograph.app/keyring/chains_v6",mm=6,hm=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,hu={},xr=null;function fm(n){let e=Array.isArray(n.rpcs)?n.rpcs:[],t=typeof n.linkProvider=="string"?[n.linkProvider]:[],r=[];for(let o of[...t,...e]){if(typeof o!="string")continue;let s=o.trim();if(!(!s.startsWith("https://")||hm.test(s))&&(r.includes(s)||r.push(s),r.length>=mm))break}return r}function fu(n){if(!n||typeof n!="object"||Array.isArray(n))return{};let e={};for(let[t,r]of Object.entries(n)){if(!r||typeof r!="object")continue;let o=r,s=Tt(t)??(typeof o.chainId=="number"?Tt(o.chainId):void 0);if(!s)continue;let a=fm(o);a.length>0&&(e[s]=a)}return e}function gu(n){hu=n}function yl(n){let e=Tt(n);return e?hu[e]??[]:[]}function bl(){xr||Pa()}function Pa(n={}){let{url:e=mu,force:t=!1,debug:r=!1}=n;return xr&&!t||(xr=(async()=>{try{let o=await C.get(e);if(!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);let s=fu(o.data),a=Object.keys(s).length;if(a===0)throw new Error("catalogue contained no usable RPC endpoints");return gu(s),r&&console.log(`[chains] loaded RPC endpoints for ${a} chains from ${e}`),!0}catch(o){if(r){let s=o instanceof Error?o.message:String(o);console.warn(`[chains] remote RPC catalogue unavailable (${s}); using built-in endpoints`)}return xr=null,!1}})()),xr}var gm=new Map(Nn.map(n=>[n.hexId.toLowerCase(),n])),ym=new Map(Nn.map(n=>[n.id,n]));function Tt(n){if(typeof n=="number")return Number.isFinite(n)&&n>=0?`0x${n.toString(16)}`:void 0;let e=n.trim().toLowerCase();if(e)return e.startsWith("0x")?/^0x[0-9a-f]+$/.test(e)?e:void 0:/^\d+$/.test(e)?`0x${Number(e).toString(16)}`:void 0}function Ce(n){if(typeof n=="number")return ym.get(n);let e=Tt(n);return e?gm.get(e):void 0}function Un(n){return Ce(n)?.nativeCurrency}var Xe=Object.fromEntries(Nn.map(n=>[n.hexId,n.rpcUrls.default.http[0]]));function wl(n){return Ce(n)?.rpcUrls.default.http[0]}var kl={};function Dn(n){let e={};if(n)for(let[t,r]of Object.entries(n)){if(typeof r!="string"||!r.trim())continue;let o=Tt(t)??t.toLowerCase();e[o]=r.trim()}kl=e}function ws(){return{...kl}}function On(n){bl();let e=Tt(n),t=e?kl[e]:void 0,r=yl(n),o=Ce(n)?.rpcUrls.default.http??[];return[...new Set([...t?[t]:[],...r,...o])]}function Mn(n){return On(n)[0]}function vl(n){let e=Ce(n);if(!e)return;let t=On(n),r=e.rpcUrls.default.http;return t.length===0||t.length===r.length&&t.every((o,s)=>o===r[s])?e:{...e,rpcUrls:{default:{http:t}}}}var en=class extends F{name="HttpRequestError";status;url;body;headers;constructor({body:e,details:t,headers:r,status:o,url:s}){super("HTTP request failed.",{details:t,metaMessages:[`URL: ${s}`,...o?[`Status: ${o}`]:[],...e?[`Request body: ${JSON.stringify(e)}`]:[]]}),this.status=o,this.url=s,this.body=e,this.headers=r}},Cr=class extends F{name="TimeoutError";constructor({body:e,url:t,timeout:r}){super("The request took too long to respond.",{details:`The request timed out after ${r}ms.`,metaMessages:[`URL: ${t}`,...e?[`Request body: ${JSON.stringify(e)}`]:[]]})}},Rr=class extends F{name="NetworkError";constructor({cause:e,url:t}){super("Could not reach the RPC endpoint.",{cause:e,metaMessages:[`URL: ${t}`]})}},Sa=class extends F{name="UrlRequiredError";constructor(){super("No RPC URL was provided.",{metaMessages:['Pass one to the transport \u2014 http("https://\u2026") \u2014 or give the client a chain that has a default RPC URL.']})}},ks=class extends F{name="FallbackTransportError";constructor({cause:e,count:t}){super(`All ${t} fallback transports failed.`,{cause:e})}};var Er=class extends F{name="RpcRequestError";code;data;constructor({body:e,error:t,url:r,shortMessage:o}){super(o??"RPC request failed.",{details:t.message,metaMessages:[...r?[`URL: ${r}`]:[],...e?[`Request body: ${JSON.stringify(e)}`]:[],`Error code: ${t.code}`]}),this.code=t.code,this.data=t.data}};function Qe(n,e,t){return class extends Er{static code=e;name=n;constructor(r){super({...r,shortMessage:t})}}}var bm=Qe("ParseRpcError",-32700,"The node could not parse the JSON request."),wm=Qe("InvalidRequestRpcError",-32600,"The JSON request is not valid."),km=Qe("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),vm=Qe("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),Tm=Qe("InternalRpcError",-32603,"The node reported an internal error."),Am=Qe("InvalidInputRpcError",-32e3,"The RPC input is not valid."),Pm=Qe("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),Sm=Qe("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),xm=Qe("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),Cm=Qe("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),Tl=Qe("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),Rm=Qe("UserRejectedRequestError",4001,"The user rejected the request."),Em=new Map([[-32700,bm],[-32600,wm],[-32601,km],[-32602,vm],[-32603,Tm],[-32e3,Am],[-32001,Pm],[-32002,Sm],[-32003,xm],[-32004,Cm],[-32005,Tl],[4001,Rm]]);function yu(n){let e=Em.get(n.error.code);return e?new e(n):new Er(n)}function bu(n){return new Promise(e=>setTimeout(e,n))}async function Al(n,{retryCount:e=2,delay:t=150,shouldRetry:r=()=>!0}={}){let o=0;for(;;)try{return await n()}catch(s){if(o++,o>e||!r({count:o,error:s}))throw s;let a=typeof t=="function"?t({count:o,error:s}):t*2**(o-1);a>0&&await bu(a)}}function Pl(n){let e=n?.["retry-after"];if(!e)return;let t=Number(e);if(Number.isFinite(t))return t*1e3;let r=Date.parse(e);return Number.isNaN(r)?void 0:Math.max(0,r-Date.now())}var _m=new Set([408,413,429,500,502,503,504]),Nm=new Set([401,402,403]);function xa(n){return n instanceof Cr||n instanceof Rr?!0:n instanceof en?n.status?_m.has(n.status)||n.status>=500:!0:n instanceof Tl?!0:n instanceof Er?n.code===-32603:!1}function Ca(n){return n instanceof en&&n.status&&Nm.has(n.status)?!0:xa(n)}function Ra(n,{retryCount:e=3,retryDelay:t=150}={}){return function(o,s={}){return Al(()=>n(o),{retryCount:s.retryCount??e,shouldRetry:({error:a})=>xa(a),delay:({count:a,error:i})=>{let l=i instanceof en?Pl(i.headers):void 0;return l!==void 0?l:(s.retryDelay??t)*2**(a-1)}})}}function tn({key:n,name:e,type:t,request:r,retryCount:o=3,retryDelay:s=150,timeout:a=1e4},i){return{config:{key:n,name:e,type:t,request:r,retryCount:o,retryDelay:s,timeout:a},request:Ra(r,{retryCount:o,retryDelay:s}),value:i}}function nn(n,e={}){let{key:t="fallback",name:r="Fallback",retryCount:o=0,retryDelay:s,onTransportError:a}=e;return(i={})=>{let l=n.map(d=>d(i));if(l.length===0)throw new ks({count:0});return tn({key:t,name:r,type:"fallback",request:async d=>{let u;for(let p=0;p<l.length;p++)try{return await l[p].request(d)}catch(m){if(u=m,a?.({error:m,index:p,method:d.method}),!Ca(m))throw m}throw new ks({cause:u,count:l.length})},retryCount:o,retryDelay:s,timeout:i.timeout},{transports:l})}}var wu=0;function ku(){return wu+=1,wu}function Lm(n){let e=n?.code;if(e==="ECONNABORTED"||e==="ETIMEDOUT")return!0;let t=n?.message??"";return/timeout/i.test(t)}var _r=class{url;timeout;fetchOptions;constructor(e,{timeout:t=1e4,fetchOptions:r={}}={}){this.url=e,this.timeout=t,this.fetchOptions=r}async post(e){let t;try{t=await C.post(this.url,e,{...this.fetchOptions,timeout:this.timeout,headers:{"Content-Type":"application/json",...this.fetchOptions.headers}})}catch(r){throw Lm(r)?new Cr({body:e,url:this.url,timeout:this.timeout}):new Rr({cause:r,url:this.url})}if(!t.ok)throw new en({body:e,details:_(t),headers:t.headers,status:t.status,url:this.url});return t.data}async request(e){let t={jsonrpc:"2.0",id:ku(),...e};return await this.post(t)??{id:t.id}}async requestBatch(e){let t=e.map(s=>({jsonrpc:"2.0",id:ku(),...s})),r=await this.post(t);if(!Array.isArray(r))return t.map(s=>({id:s.id,error:r?.error??{code:-32603,message:"Malformed batch response."}}));let o=new Map(r.map(s=>[s.id,s]));return t.map((s,a)=>o.get(s.id)??r[a]??{id:s.id,error:{code:-32603,message:"Missing response for batched request."}})}};function vu(n,e,t){if(n.error)throw yu({body:e,error:n.error,url:t});return n.result}function ut(n,e={}){let{batch:t,fetchOptions:r,key:o="http",name:s="HTTP JSON-RPC",retryCount:a,retryDelay:i,timeout:l}=e;return({chain:c,retryCount:d,retryDelay:u,timeout:p}={})=>{let{batchSize:m=1e3,wait:f=0}=typeof t=="object"?t:{},h=l??p??1e4,g=n??c?.rpcUrls.default.http[0];if(!g)throw new Sa;let b=new _r(g,{timeout:h,fetchOptions:r});return tn({key:o,name:s,type:"http",retryCount:a??d,retryDelay:i??u,timeout:h,async request({method:y,params:w}){let k={method:y,params:w};if(t){let{schedule:v}=ys({id:`${g}:${m}:${f}`,wait:f,shouldSplitBatch:S=>S.length>m,fn:S=>b.requestBatch(S)});return vu(await v(k),k,g)}return vu(await b.request(k),k,g)}},{url:g})}}var Im=1024;async function Nr(n,e){let{contracts:t,allowFailure:r=!0,account:o,blockNumber:s,blockTag:a,multicallAddress:i,stateOverride:l,fallbackConcurrency:c}=e,d=e.batchSize??(typeof n.batch?.multicall=="object"&&n.batch.multicall.batchSize||Im),u=new Array(t.length);if(t.length===0)return r?u:[];let p=bs(n,i,s),m=[],f;t.forEach((b,y)=>{let{abi:w,address:k,functionName:v,args:S}=b,P;try{if(!R(k))throw new rr(k);P=M({abi:w,functionName:v,args:S})}catch(U){let E=Pr(U,{abi:w,address:k,args:S,functionName:v,sender:o});if(!r)throw E;u[y]={status:"failure",error:E};return}let x=(P.length-2)/2;(!f||d>0&&f.size+x>d&&f.calls.length>0)&&(f={calls:[],indexes:[],size:0},m.push(f)),f.calls.push({target:k,allowFailure:!0,callData:P}),f.indexes.push(y),f.size+=x}),(await Ln(n,p,i!==void 0)?await Promise.allSettled(m.map(b=>vt(n,{abi:ct,address:p,functionName:"aggregate3",args:[b.calls],account:o,blockNumber:s,blockTag:a,stateOverride:l}))):await(async()=>{let b=m.flatMap(w=>w.calls.map((k,v)=>({target:k.target,callData:k.callData,index:w.indexes[v]}))),y=await Sr(n,b,{account:o,blockNumber:s,blockTag:a,stateOverride:l,concurrency:c});return m.length=0,y.map((w,k)=>(m.push({calls:[],indexes:[b[k].index],size:0}),w.success?{status:"fulfilled",value:[{success:!0,returnData:w.returnData}]}:{status:"rejected",reason:w.error}))})()).forEach((b,y)=>{let w=m[y];if(b.status==="rejected"){for(let k of w.indexes){let v=t[k],S=Pr(b.reason,{abi:v.abi,address:v.address,args:v.args,functionName:v.functionName,sender:o});if(!r)throw S;u[k]={status:"failure",error:S}}return}w.indexes.forEach((k,v)=>{let S=t[k],P=b.value[v];try{if(!P)throw new Error("Multicall returned fewer results than calls.");if(!P.success)throw new Ar({data:P.returnData});if(!P.returnData||P.returnData==="0x")throw new Yt;let x=yt({abi:S.abi,functionName:S.functionName,args:S.args,data:P.returnData});u[k]={status:"success",result:x}}catch(x){let U=Pr(x,{abi:S.abi,address:S.address,args:S.args,functionName:S.functionName,sender:o});if(!r)throw U;u[k]={status:"failure",error:U}}})});for(let b=0;b<t.length;b++){if(u[b])continue;let y=new Error("Multicall returned no result for this call.");if(!r)throw y;u[b]={status:"failure",error:y}}return r?u:u.map(b=>b.result)}var Um=0,Fn=class{key;name;uid;chain;transport;batch;request;constructor(e={}){let{batch:t,key:r="public",name:o="Public Client",retryCount:s,retryDelay:a,timeout:i}=e;this.chain=Om(e.chain),this.key=r,this.name=o,this.batch=t,this.uid=`${r}-${++Um}-${Math.random().toString(36).slice(2,8)}`;let c=(e.transport??Dm(e.rpcUrl,this.chain))({chain:this.chain,retryCount:s,retryDelay:a,timeout:i});this.transport={...c.config,...c.value},this.request=c.request}call(e){return kt(this,e)}readContract(e){return vt(this,e)}multicall(e){return Nr(this,e)}multicallRaw(e){return Zt(this,e)}getBlockNumber(){return pr(this)}getChainId(){return mr(this)}getBalance(e){return hr(this,e)}getCode(e){return Qt(this,e)}getStorageAt(e){return fr(this,e)}getTransactionCount(e){return gr(this,e)}getGasPrice(){return yr(this)}estimateMaxPriorityFeePerGas(){return Ta(this)}estimateGas(e){return br(this,e)}getBlock(e){return wr(this,e)}rpc(e,t){return this.request({method:e,params:t})}extend(e){let t=Object.assign(Object.create(Object.getPrototypeOf(this)),this);return Object.assign(t,e(t))}};function Dm(n,e){if(n)return ut(n);let t=e?.rpcUrls.default.http??[];return t.length>1?nn(t.map(r=>ut(r,{retryCount:1}))):ut(t[0])}function Om(n){if(n===void 0)return;if(typeof n=="object")return n;let e=vl(n);if(!e)throw new Tr(n);return e}function rn(n={}){return new Fn(n)}var Sl=new Map;function Mm(n,e){return{id:parseInt(n,16),hexId:n,name:`Chain ${parseInt(n,16)}`,nativeCurrency:{name:"Native",symbol:"ETH",decimals:18},rpcUrls:{default:{http:e}},contracts:{multicall3:{address:re}}}}function Re(n,e={}){let{batch:t=!0,pinRpcUrl:r=!1,fallbackConcurrency:o,assumeMulticall3:s}=e,a=Tt(n),i=e.rpcUrl?.trim(),l=a?On(a):[],c=i?r?[i]:[...new Set([i,...l])]:l;if(c.length===0)throw new Tr(n);let d=`${a??n}|${c.join(",")}|${t?1:0}|${o??""}|${s?1:0}`,u=Sl.get(d);if(u)return u;let p=rn({chain:a&&!Ce(a)?Mm(a,c):a,transport:c.length===1?ut(c[0]):nn(c.map(m=>ut(m,{retryCount:1}))),batch:t?{multicall:{fallbackConcurrency:o,assumeMulticall3:s}}:void 0});return Sl.set(d,p),p}function Ea(){Sl.clear()}function Cl(n,e){try{return Re(n,{rpcUrl:e?.trim()||void 0})}catch{return null}}async function Te(n,e,t){let r=new Array(e.length).fill(null),o=e.length>0?Cl(n,t):null;if(!o)return r;let s=[];if(e.forEach((a,i)=>{!R(a.target)||!xn(a.callData)||s.push({index:i,target:a.target,callData:a.callData})}),s.length===0)return r;try{(await Zt(o,{calls:s})).forEach((i,l)=>{i.success&&(r[s[l].index]=i.returnData)})}catch{}return r}function _a(n){return n?.status==="success"?n.result:void 0}async function xl(n,e){try{return await n.multicall({contracts:e})}catch{return[]}}async function on(n,e,t){let r=e.map(()=>({symbol:null,decimals:null})),o=e.length>0?Cl(n,t):null;if(!o)return r;let s=[];if(e.forEach((l,c)=>{R(l)&&s.push({index:c,address:l})}),s.length===0)return r;let a=await xl(o,s.flatMap(l=>[{address:l.address,abi:q,functionName:"symbol"},{address:l.address,abi:q,functionName:"decimals"}]));s.forEach((l,c)=>{let d=_a(a[c*2]);typeof d=="string"&&d.trim()&&(r[l.index].symbol=d.trim()),r[l.index].decimals=wa(_a(a[c*2+1]))});let i=s.filter(l=>r[l.index].symbol===null);if(i.length>0){let l=await xl(o,i.map(c=>({address:c.address,abi:kr,functionName:"symbol"})));i.forEach((c,d)=>{r[c.index].symbol=ka(_a(l[d]))})}return r}async function Tu(n,e,t){let r=new Array(e.length).fill(null),o=e.length>0?Cl(n,t):null;if(!o)return r;let s=[];return e.forEach((i,l)=>{if(R(i.contract))try{s.push({index:l,address:i.contract,tokenId:BigInt(i.tokenId)})}catch{}}),s.length===0||(await xl(o,s.map(i=>({address:i.address,abi:vr,functionName:"tokenURI",args:[i.tokenId]})))).forEach((i,l)=>{let c=_a(i);if(typeof c!="string")return;let d=c.replace(/\0+$/,"").trim();d&&(r[s[l].index]=d)}),r}function vs(n){return Lr(String(n))??"0"}function Lr(n){let e=n.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let t=e[1]==="-"?"-":"",r=e[2]??"",o=e[3]??"";if(r===""&&o==="")return null;let s=e[4]?parseInt(e[4],10):0,a=r+o,i=r.length+s,l;return i<=0?l=`0.${"0".repeat(-i)}${a}`:i>=a.length?l=a+"0".repeat(i-a.length):l=`${a.slice(0,i)}.${a.slice(i)}`,l=l.replace(/^0+(?=\d)/,""),l.includes(".")&&(l=l.replace(/0+$/,"").replace(/\.$/,"")),(l===""||l==="-")&&(l="0"),l==="0"?"0":t+l}function Rl(n){let e=Lr(n);if(e===null||e.startsWith("-"))return null;let[t,r=""]=e.split(".");return{mant:BigInt(t+r),frac:r.length}}function Na(n,e){let t=n<0n,r=(t?-n:n).toString(),o;if(e===0)o=r;else{let s=r.padStart(e+1,"0"),a=s.length-e;o=`${s.slice(0,a)}.${s.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return t?`-${o}`:o}function Bn(n,e){let t=Lr(n);if(t===null||t.startsWith("-"))return null;let[r,o=""]=t.split("."),s=o.slice(0,e).padEnd(e,"0");try{let a=BigInt(r||"0")*10n**BigInt(e)+BigInt(s||"0");return a>0n?a:null}catch{return null}}function qn(n){if(typeof n=="number")return Number.isFinite(n)&&n>0?vs(n):null;if(typeof n!="string")return null;let e=n.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=Lr(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function Dt(n,e){let t=Lr(n);if(t===null||e<0)return n;let r=t.startsWith("-"),[o,s=""]=(r?t.slice(1):t).split(".");if(s.length<=e)return t;let a=e===0?o:`${o}.${s.slice(0,e)}`,i=a.includes(".")?a.replace(/0+$/,"").replace(/\.$/,""):a;return r?`-${i}`:i}function $n(n,e,t,r){let o=Rl(n);if(!o||t<=0n||r<0)return n;let s=o.mant*e*10n**BigInt(r)/(t*10n**BigInt(o.frac));return Na(s,r)}function sn(n,e){let t=Rl(n),r=Rl(e);if(!t||!r){let i=Number(n),l=Number(e);return i<l?-1:i>l?1:0}let o=Math.max(t.frac,r.frac),s=t.mant*10n**BigInt(o-t.frac),a=r.mant*10n**BigInt(o-r.frac);return s<a?-1:s>a?1:0}var Fm={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"}]},Bm="payment-required",qm="PAYMENT-SIGNATURE",$m="X-PAYMENT",Hm="payment-response",Vm="x-payment-response",Wm=600,Ym=300,Gm={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 Au(n){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(n),t=Array.from(e,r=>String.fromCharCode(r)).join("");return globalThis.btoa(t)}return Buffer.from(n,"utf8").toString("base64")}function Su(n){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return new TextDecoder("utf-8").decode(t)}return Buffer.from(n,"base64").toString("utf8")}function Km(){let n=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(n);else for(let t=0;t<32;t++)n[t]=Math.floor(Math.random()*256);return"0x"+Array.from(n,t=>t.toString(16).padStart(2,"0")).join("")}function xu(n){let e=String(n);if(e.includes(":")){let[r,o]=e.split(":"),s=parseInt(o,10);if(r!=="eip155"||Number.isNaN(s))throw new Error(`Unsupported x402 network: ${n} (only EVM "eip155:*" is supported)`);return s}let t=Gm[e.toLowerCase()];if(t===void 0)throw new Error(`Unsupported x402 network: ${n}`);return t}function Cu(n){if(!n.query||Object.keys(n.query).length===0)return n.url;let e=Object.entries(n.query).map(([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(r)}`).join("&");return n.url.includes("?")?`${n.url}&${e}`:`${n.url}?${e}`}function La(n){let e=n.headers[Bm];if(e){let o=Pu(jm(e));return o&&Array.isArray(o.accepts)?{version:2,payload:o}:null}let t=n.data,r=t&&typeof t=="object"?t:Pu(t);return r&&Array.isArray(r.accepts)?{version:1,payload:r}:null}function Pu(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e&&typeof e=="object"?e:null}catch{return null}}function jm(n){try{return Su(n)}catch{return null}}function zm(n){let e=n.amount??n.maxAmountRequired;return typeof n.scheme!="string"||typeof n.network!="string"||e==null||typeof n.asset!="string"||typeof n.payTo!="string"?null:{scheme:n.scheme,network:n.network,amount:String(e),asset:n.asset,payTo:n.payTo,...typeof n.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:n.maxTimeoutSeconds}:{},...n.extra&&typeof n.extra=="object"?{extra:n.extra}:{},...typeof n.resource=="string"?{resource:n.resource}:{},...typeof n.description=="string"?{description:n.description}:{},...typeof n.mimeType=="string"?{mimeType:n.mimeType}:{},...n.outputSchema!=null?{outputSchema:n.outputSchema}:{}}}function Xm(n){let e=null;for(let t of n){let r=zm(t);if(r){if(r.scheme!=="exact"){e=`unsupported scheme "${r.scheme}"`;continue}try{return xu(r.network),r}catch(o){e=o instanceof Error?o.message:String(o)}}}throw new Error(e?`No payable x402 requirement offered (${e}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function El(n,e,t,r){let o=La(n);if(!o)throw new Error("402 response carries no x402 payment requirements");let{version:s,payload:a}=o,i=Xm(a.accepts??[]);if(!t)throw new Error("No connected wallet address to build the payment from");let l=xu(i.network),c=Math.floor(Date.now()/1e3),d={from:t,to:i.payTo,value:String(i.amount),validAfter:String(Math.max(0,c-Wm)),validBefore:String(c+(i.maxTimeoutSeconds??Ym)),nonce:Km()},u={domain:{name:i.extra?.name,version:i.extra?.version,chainId:l,verifyingContract:i.asset},types:Fm,primaryType:"TransferWithAuthorization",message:{...d}};return{request:{url:Cu(e),method:e.method??"GET",body:e.body,headers:e.headers},x402Version:s,requirements:i,authorization:d,typedData:u,chainId:l,...a.resource!=null?{resource:a.resource}:{},...a.extensions!=null?{extensions:a.extensions}:{},...r?{userQuery:r}:{}}}async function Qm(n,e,t,r){let o=Cu(e),s=await n.request(e.method??"GET",o,e.body,{headers:e.headers});if(s.status===402)return{status:"payment_required",challenge:El(s,e,t,r)};if(!s.ok)throw new Error(_(s));return{status:"ok",data:s.data}}async function _l(n,e,t){let{url:r,method:o,body:s,headers:a}=e.request,i=await n.request(o,r,s,{headers:{...a??{},...Nl(e,t)}});if(i.ok)return i.data;throw new Error(Zm(i)??_(i))}function Jm(n){return La(n)!==null}function Ru(n){let e=Eu(n);return e?.errorReason?e.errorReason:La(n)?.payload.error??null}function Zm(n){let e=Ru(n);return e?`x402 payment rejected: ${e}`:null}var eh={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 Nl(n,e){let{requirements:t,authorization:r}=n,o={signature:e,authorization:r};if(n.x402Version===1){let a={x402Version:1,scheme:t.scheme,network:t.network,payload:o};return{[$m]:Au(JSON.stringify(a))}}let s={x402Version:2,...n.resource!=null?{resource:n.resource}:{},accepted:th(t),payload:o,...n.extensions!=null?{extensions:n.extensions}:{}};return{[qm]:Au(JSON.stringify(s))}}function th(n){let{resource:e,description:t,mimeType:r,outputSchema:o,...s}=n;return s}function Eu(n){let e=n.headers[Hm]??n.headers[Vm];if(!e)return null;try{return JSON.parse(Su(e))}catch{return null}}function nh(n,e){return n==null?e:eh[n]??`Chain ${n}`}async function _u(n){let e=n.requirements,r=n.resource?.description||e.description,o=n.chainId??null,s=null,a=null;if(o!=null){let[l]=await on("0x"+o.toString(16),[e.asset]);s=l?.symbol??null,a=l?.decimals??null}let i=String(e.amount);if(a!==null)try{i=Na(BigInt(e.amount),a)}catch{}return{amount:i,asset:s||e.extra?.name||"USDC",amountRaw:String(e.amount),decimals:a,assetAddress:e.asset,network:o!=null?`eip155:${o}`:e.network,networkRaw:e.network,chainId:o,networkLabel:nh(o,e.network),payTo:e.payTo,...r?{description:r}:{},resourceUrl:n.request.url}}function Ll(n){return async(e,t)=>{let r=n.getPayer(),o=n.getSigner();if(!r||!o)return null;let s;try{s=El(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},r)}catch{return null}let a;try{a=await o({typedData:s.typedData,display:await _u(s)})}catch{a=null}return a?Nl(s,a):null}}var an=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function Hn(n){if(!n||typeof n!="object")return!1;let e=n;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function Ts(n){if(n?.aborted)throw new an}function Il(n,e){if(!e)return{signal:n.signal,cleanup:()=>{}};if(e.aborted)return n.abort(),{signal:n.signal,cleanup:()=>{}};let t=()=>n.abort();return e.addEventListener("abort",t),{signal:n.signal,cleanup:()=>e.removeEventListener("abort",t)}}var Nu={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},rh="https://nft.keyring.app/api/gemini-stable",oh="https://generativelanguage.googleapis.com",sh=new Set([408,429,500,502,503,504]),Lu=3e4,Ia=n=>new Promise(e=>setTimeout(e,n));function Ua(n,e,t){if(t!=null&&t>0)return Math.min(t,Lu);let r=Math.min(e*2**(n-1),Lu);return r/2+Math.random()*(r/2)}function ah(n){if(!n)return null;let e=Number(n);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(n);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var ke=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?oh:rh)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,t,r){let{systemInstruction:o,contents:s}=this.toContents(e),{maxRetries:a=5,retryDelayMs:i=1e3}=r??{},l=r?.signal??this.requestSignal;Ts(l);let c=s.length>0?s:[{role:"user",parts:[{text:"(continue)"}]}];if(r?._debug){console.log("[GeminiProvider] turn sequence:");for(let h of c){let g=h.parts.map(b=>b.functionCall?`fc:${b.functionCall.name}`:b.functionResponse?`fr:${b.functionResponse.name}`:`text:${(b.text??"").slice(0,40)}`).join(", ");console.log(` ${h.role}: [${g}]`)}}let d=r?.thinkingBudget??(r?.maxOutputTokens!=null?0:void 0),u={maxOutputTokens:r?.maxOutputTokens??this.maxTokens,temperature:this.temperature};d!=null&&(u.thinkingConfig={thinkingBudget:d});let p={contents:c,generationConfig:u};o&&(p.systemInstruction=o),t?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],r?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):r?.googleSearch&&(p.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,f="Unknown error";for(let h=1;h<=a;h++){Ts(l);let g;try{g=await C.post(m,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(P){if(Hn(P))throw P;if(f=P instanceof Error?P.message:String(P),h>=a)break;await Ia(Ua(h,i));continue}if(!g.ok){let P=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${g.status}: ${P}`,!sh.has(g.status))throw new Error(f);if(h>=a)break;let x=ah(g.headers["retry-after"]??null);await Ia(Ua(h,i,x));continue}if(g.data==null||typeof g.data!="object"){if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,h>=a)break;await Ia(Ua(h,i));continue}let b=g.data,y=b.candidates?.[0];if(!y)return{text:"",toolCalls:[]};let w="",k=[],v=y.content?.parts;if(!Array.isArray(v)||v.length===0){let P=y.finishReason;if(!(P==="SAFETY"||P==="RECITATION")&&h<a){f=`Gemini returned an empty turn (finishReason=${P??"none"})`,await Ia(Ua(h,i));continue}return{text:"",toolCalls:[]}}for(let P of v)P.text&&(w+=P.text),P.functionCall&&k.push({toolName:P.functionCall.name,args:P.functionCall.args??{},callId:P.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let S=b.usageMetadata?{promptTokens:b.usageMetadata.promptTokenCount??0,completionTokens:b.usageMetadata.candidatesTokenCount??0,totalTokens:b.usageMetadata.totalTokenCount??0}:void 0;return{text:w,toolCalls:k,usage:S}}throw new Error(f)}toContents(e){let t=[],r=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){r.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){r.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}r.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o=[];for(let i of r){let l=o[o.length-1],c=i.parts.some(u=>u.functionCall),d=l?.parts.some(u=>u.functionCall);l&&l.role===i.role&&!c&&!d?l.parts.push(...i.parts):o.push({...i,parts:[...i.parts]})}let s=[];for(let i=0;i<o.length;i++){let l=o[i],c=s[s.length-1];l.role==="function"&&!c?.parts.some(u=>u.functionCall)||l.role==="model"&&l.parts.some(u=>u.functionCall)&&!(o[i+1]?.role==="function")||s.push(l)}for(;s.length>0&&s[0].role!=="user";)s.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
4
+ `)}]}:null,contents:s}}toFunctionDeclarations(e){return e.map(t=>{let r={},o=[];for(let s of t.parameters){let a={type:Nu[s.type]??"STRING",description:s.description};s.type==="array"&&(a.items={type:Nu[s.items?.type??"string"]??"STRING"}),r[s.name]=a,s.required&&o.push(s.name)}return{name:t.name,description:t.description,parameters:{type:"OBJECT",properties:r,required:o}}})}};var Ir=class{tools=new Map;register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(t=>t.category===e)}async execute(e,t,r){let o=this.tools.get(e);if(!o)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let s=Date.now();try{return{...await o.execute(t,r),duration:Date.now()-s}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-s}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};var Ur=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],ih=new Set(Ur),ln=[...Ur],Ul=new Set(ln),Je="0x1",Or="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function lh(n){return n.map(e=>Dr[e]??e).join(", ")}function Da(n){let e=new Set;if(n)for(let r of n){let o=Oa(r);o&&e.add(o)}let t=Ur.filter(r=>!e.has(r));ln=t.length>0?[...t]:[...Ur],Ul=new Set(ln),Je=ln.includes("0x1")?"0x1":ln[0],Or=lh(ln)}var ch={"0x1":"0x1",1:"0x1",eth:"0x1",ether:"0x1",ethereum:"0x1","ethereum mainnet":"0x1",mainnet:"0x1","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa",optimistic:"0xa","op mainnet":"0xa","optimism mainnet":"0xa","optimistic ethereum":"0xa","0x38":"0x38",56:"0x38",bsc:"0x38",bnb:"0x38",binance:"0x38","bnb chain":"0x38","bnb smart chain":"0x38","binance chain":"0x38","binance smart chain":"0x38","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","polygon mainnet":"0x89","polygon pos":"0x89","0x2105":"0x2105",8453:"0x2105",base:"0x2105","base mainnet":"0x2105","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","arbitrum one":"0xa4b1","arbitrum mainnet":"0xa4b1","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a","avalanche c-chain":"0xa86a","avalanche cchain":"0xa86a","avax c-chain":"0xa86a","0xe708":"0xe708",59144:"0xe708",linea:"0xe708","linea mainnet":"0xe708","0x64":"0x64",100:"0x64",gnosis:"0x64","gnosis chain":"0x64","gnosis mainnet":"0x64",xdai:"0x64","xdai chain":"0x64","0x3e7":"0x3e7",999:"0x3e7",hyperevm:"0x3e7","hyper evm":"0x3e7",hyperliquid:"0x3e7","hyperliquid evm":"0x3e7","0x1388":"0x1388",5e3:"0x1388",mantle:"0x1388","mantle mainnet":"0x1388","0x8f":"0x8f",143:"0x8f",monad:"0x8f","monad mainnet":"0x8f"};function I(n){let e=Oa(n);return e&&Ul.has(e)?e:null}function Oa(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=ch[e];if(t)return t;let r=null;return/^0x[0-9a-f]+$/.test(e)?r=e:/^[0-9]+$/.test(e)&&(r="0x"+Number(e).toString(16)),r&&ih.has(r)?r:null}function Be(n){return I(n)!==null}function qe(){return[...ln]}var cn=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${Or}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Ot=n=>typeof n=="string"&&n.trim()!=="";function K(n,e){if(Ot(n)){let t=I(n);if(t)return t;throw new cn(n.trim())}if(Ot(e?.chain)){let t=I(e.chain);if(t)return t;throw new cn(e.chain.trim())}return null}function Ma(n,e){return I(n)??I(e?.chain)??void 0}var Dr={"0x1":"Ethereum","0xa":"Optimism","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche","0xe708":"Linea","0x64":"Gnosis","0x3e7":"HyperEVM","0x1388":"Mantle","0x8f":"Monad"};function T(n){let e=Oa(n);return e&&Dr[e]?Dr[e]:typeof n=="string"&&n.trim()?n.trim():"the requested chain"}var uh={"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 Iu(n,e){let t=Oa(n),r=t?uh[t]:void 0;return!r||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${r}/tx/${e.trim()}`}var dh={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function Uu(n){if(typeof n!="string")return null;let e=n.trim().toLowerCase();return e?dh[e]??null:null}var ph={"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 Fa(n){let e=I(n);return e?ph[e]??null:null}function Ba(n,e){if(!Ot(n)||!Ot(e))return null;let t=I(n),r=I(e);return!t||!r||t===r?null:{from:t,to:r,fromLabel:Dr[t]??t,toLabel:Dr[r]??r}}function Mr(n){return`Hex chain ID of the ${n} \u2014 same ids as \`chain\` (e.g. "0xa" Optimism, "0x2105" Base). ONLY set this when the user names a chain FOR THIS SIDE SPECIFICALLY, i.e. they named a chain per token \u2014 "swap ETH on Optimism to ETH on Base", "buy USDC on Base using ETH on Arbitrum". When the user names ONE chain for the whole request (or none), leave this EMPTY and use \`chain\` instead. Never copy the same chain into both sides.`}function qa(n,e){return{error:"cross_chain_not_supported",_instructions:`The user asked to ${n} from ${e.fromLabel} to ${e.toLabel} \u2014 that is a CROSS-CHAIN (bridge) request, which is NOT supported: a ${n} happens entirely on ONE network. Tell them, in their language, that ${n}ping between two different networks isn't supported yet, and that they can ${n} between tokens that are both on ${e.fromLabel}, or both on ${e.toLabel} (switching their wallet's network first). Do NOT proceed. Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var Ze=`Hex chain ID \u2014 e.g. "0xa" Optimism, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0x38" BSC, "0x1" Ethereum, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. Set this WHENEVER the user names a network anywhere in their request \u2014 "swap USDC on Optimism", "buy PEPE on Base", "\u0111\u1ED5i USDC tr\xEAn Optimism", "mua PEPE tr\xEAn Base" \u2014 by mapping that name to its hex id from the list above. Do this EVEN IF it differs from the wallet's currently connected chain: that is a normal request, and the wallet is asked to switch networks when the transaction is signed. NEVER substitute the connected chain for a network the user named, and never leave this empty just because the two differ. OMIT it only when the user names no network at all \u2014 the connected wallet chain is then used automatically.`;function Du(n,e){let t=typeof n=="string"?n.trim():"",r=e&&e.length?e.filter(s=>Ul.has(s)):[];return(r.length?r:ln).map(s=>{let a=Dr[s]??s;return{label:a,prompt:t?`${t} (${a})`:a}})}function Fr(n,e){return{actionButtons:Du(e),_instructions:`The user wants to ${n} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var ge=class extends Error{code="needs_chain_selection";buttons;constructor(e,t){super("Wallet is connected but no chain is set \u2014 ask the user to pick one."),this.name="NeedsChainSelectionError",this.buttons=Du(e,t)}},As=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 le(n,e){if(Ot(n))return n.trim();if(Ot(e?.walletAddress))return e.walletAddress.trim();throw new As}function Pe(n,e,t){if(Ot(n)){let r=I(n);if(r)return r;throw new cn(n.trim())}if(Ot(e?.chain)){let r=I(e.chain);if(r)return r;throw new cn(e.chain.trim())}if(Ot(e?.walletAddress))throw new ge(typeof e?.query=="string"?e.query:void 0,t);return Je}var A=class{category;async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a=mh(s);return{toolName:this.name,callId:r,success:!0,data:a.data,duration:Date.now()-o,...a.actionButtons?{actionButtons:a.actionButtons}:{},...a.ui?{ui:a.ui}:{}}}catch(s){return s instanceof ge?{toolName:this.name,callId:r,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-o,actionButtons:s.buttons}:s instanceof As?{toolName:this.name,callId:r,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-o}:{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}};function mh(n){if(!n||typeof n!="object")return{data:n};let e=n,t=e.actionButtons,r=Array.isArray(t)&&t.length>0?t:void 0,o=e.ui,s=o&&typeof o=="object"&&typeof o.component=="string"?o:void 0;if(!r&&!s)return{data:n};let{actionButtons:a,ui:i,...l}=e;return{data:l,...r?{actionButtons:r}:{},...s?{ui:s}:{}}}var hh="https://wallet-api.pantograph.app",fh="0x0000000000000000000000000000000000000000",Bu={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},qu={"0x1":["0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2","0x2260fac5e5542a773aa44fbcfedf7c193bc2c599"],"0xa":["0x4200000000000000000000000000000000000006","0x68f180fcce6836688e9084f035309e29bf0a2095","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0x38":["0x2170ed0880ac9a755fd29b2688956bd959f933f8","0x7130d2a12b9bcbfae4f2634d864a1ee1ce3ead9c"],"0x89":["0x7ceb23fd6bc0add59e62ac25578270cff1b9f619","0x1bfd67037b42cf73acf2047067bd4f2c47d9bfd6"],"0x2105":["0x4200000000000000000000000000000000000006","0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf","0xc47da4cb96ce65a96844a01bfae509f9d5454534"],"0xa4b1":["0x82af49447d8a07e3bd95bd0d56f35241523fbab1","0x2f2a2543b76a4166549f7aab2e75bef0aefc5b0f"],"0xa86a":["0x49d5c2bdffac6ce2bfdb6640f4f80f226bc10bab","0x0555e30da8f98308edb960aa94c0db47230d2b9c"],"0xe708":["0xe5d7c2a44ffddf6b295a15c148167daaaf5cf34f","0x3aab2285ddcddad8edf438c1bab47e1a9d05a9b4"],"0x3e7":["0xbe6727b535545c67d5caa73dea54865b92cf7907","0x9fdbda0a5e284c32744d2f17ee5c74b284993463"],"0x1388":["0xdeaddeaddeaddeaddeaddeaddeaddeaddead1111","0xcabae6f6ea1ecab08ad02fe02ce9a44f09aebfa2"],"0x8f":["0xee8c0e9f1bffb4eb878d8f15f368a02a35481242","0x0555e30da8f98308edb960aa94c0db47230d2b9c"]};function gh(n){return Bu[n.toLowerCase()]||n}function Ou(n){let e=[];for(let[t,r]of Object.entries(n))if(r!=null)if(Array.isArray(r))for(let o of r)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);return e.join("&")}function Dl(n){let e=n,t=e.decimals,r=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,o=e.price,s=o!=null?parseFloat(String(o)):NaN,a=typeof e.symbolOnchain=="string"?e.symbolOnchain.trim():"";return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(r)?r:0,...a?{symbol:a}:{},...Number.isFinite(s)?{usd_price:s}:{}}}function Mu(n){if(Array.isArray(n))return n;let e=n;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function Ue(n){if(n==null)return null;let e=typeof n=="number"?n:parseFloat(String(n));return Number.isFinite(e)?e:null}function Fu(n,e){let t=n.decimals,r=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,o=Ue(n.price_change_percentage_24h)??Ue(n.priceChange24h)??Ue(n.usd_price_24hr_percent_change)??Ue(n.price_change_24h)??Ue(n.priceChange);return{chainId:e,tokenAddress:n.address??n.token_address??"",name:n.name??null,symbol:typeof n.symbolOnchain=="string"&&n.symbolOnchain.trim()||n.symbol||null,decimals:r!=null&&Number.isFinite(r)?r:null,logo:n.logoURI??n.icon_image??n.logo??null,usdPrice:Ue(n.price)??Ue(n.usd_price),marketCap:Ue(n.market_cap)??Ue(n.marketCap),totalVolume:{"24h":Ue(n.total_volume)??Ue(n.volume24h)},pricePercentChange:{"24h":o}}}var yh=100;function bh(n,e){let t=[];for(let r=0;r<n.length;r+=e)t.push(n.slice(r,r+e));return t}var Ae=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??hh).replace(/\/+$/,"")}tokensUrl(e,t){let r=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${r}?addresses=${encodeURIComponent(t)}`}async fetchTokensAll(e,t){let r=bh(t,yh);return(await Promise.all(r.map(async s=>{try{let a=`${this.baseUrl}/keyrings/tokens/all/${e}?addresses=${encodeURIComponent(s.join(","))}`,i=await C.get(a);return i.ok?Mu(i.data):[]}catch{return[]}}))).flat()}async enrichTokenPrices(e,t){let r=new Map;if(e.length===0)return r;try{let o=e.map(i=>i.token_address),s=await this.fetchTokensAll(parseInt(t,16),o),a=new Map;for(let i of s)if(i.address){let l=i.address.toLowerCase(),c=typeof i.symbolOnchain=="string"?i.symbolOnchain.trim():"";a.set(l,{price:i.price!=null?parseFloat(String(i.price)):NaN,icon_image:i.icon_image,...c?{symbolOnchain:c}:{}}),("yieldProtocol"in i||"yieldAsset"in i)&&r.set(l,{yieldProtocol:i.yieldProtocol,yieldAsset:i.yieldAsset})}for(let i=0;i<e.length;i++){let l=a.get(e[i].token_address.toLowerCase());l&&(l.icon_image&&(e[i].logo=l.icon_image,e[i].thumbnail=l.icon_image),l.symbolOnchain&&(e[i].symbol=l.symbolOnchain),isNaN(l.price)||(e[i].usd_price=l.price,e[i].usd_value=parseFloat(e[i].balance_formatted||"0")*l.price))}}catch{}return r}async getYieldPricingTokens(e,t){let r=(t??[]).map(s=>String(s??"").trim()).filter(Boolean);if(r.length===0)return[];let o=typeof e=="number"?e:String(e).startsWith("0x")?parseInt(String(e),16):parseInt(String(e),10);if(!Number.isFinite(o))return[];try{return await this.fetchTokensAll(o,r)}catch{return[]}}async getTokenMetadata(e,t){try{let r=this.tokensUrl(t,e),o=await C.get(r);if(!o.ok)return null;let s=Mu(o.data),a=e.toLowerCase()===fh,i=s.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return i?Dl(i):null}catch{return null}}async getTokensMetadata(e,t){let r={};if(e.length===0)return r;try{let o=await this.fetchTokensAll(parseInt(t,16),e),s=new Set(e.map(a=>a.toLowerCase()));for(let a of o){let i=a.address?.toLowerCase()||a.token_address?.toLowerCase()||(a.address===""?"":null);i&&s.has(i)&&(r[i]=Dl(a))}}catch{}return r}async searchTokensByKey(e){let{key:t,chain:r}=e;if(!t)return{success:!1,error:"Search key is required"};let s=parseInt(r||Je,16);if(isNaN(s))return{success:!1,error:`Invalid hex chain: ${r}`};try{let a=Ou({chainId:s,key:t}),i=`${this.baseUrl}/token-list/all?${a}`,l=await C.get(i);if(!l.ok)throw new Error(_(l));let c=l.data,d=c?.result??c?.data??c,u=[];return Array.isArray(d)?u=d:d&&typeof d=="object"&&(u=Object.values(d).flat()),{success:!0,data:u.map(Dl)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||Je,r=5,o=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let s=qu[t.toLowerCase()]??[],a=o!=null?o+s.length:r+s.length,[i,l]=await Promise.allSettled([this.fetchTopGainers(t,a),s.length>0?this.getTokensMetadata(s,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],d=l.status==="fulfilled"?s.map(h=>l.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>Fu(h,t)):[],u=new Set,p=[];for(let h of d){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),p.push(h))}let m=[];for(let h of c){let g=h.tokenAddress?.toLowerCase();!g||u.has(g)||(u.add(g),m.push(h))}let f=o!=null?[...p,...m].slice(0,o):[...p,...m.slice(0,r)];return await this.enrichTrendingMarketData(f,t),{success:!0,data:f}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let r=e.filter(s=>s.tokenAddress&&(s.marketCap==null||s.totalVolume?.["24h"]==null));if(r.length===0)return;let o=await this.getTokensMetadata(r.map(s=>s.tokenAddress),t);for(let s of r){let a=o[s.tokenAddress.toLowerCase()];a&&(s.marketCap==null&&(s.marketCap=Ue(a.market_cap)??Ue(a.marketCap)),s.totalVolume?.["24h"]==null&&(s.totalVolume={"24h":Ue(a.total_volume)??Ue(a.volume24h)}))}}async fetchTopGainers(e,t,r="24h"){let o=parseInt(e,16),s=Ou({chainId:o,duration:r,limit:t}),a=`${this.baseUrl}/token-list/all/top-gainers${s?`?${s}`:""}`,i=[];for(let l=0;l<5;l++){let c=await C.get(a);if(!c.ok)throw new Error(_(c));let d=c.data;if(i=Array.isArray(d)?d:Array.isArray(d.data)?d.data:[],i.length>0)break;l<4&&await new Promise(u=>setTimeout(u,2e3))}return i.map(l=>Fu(l,e))}async getTopGainers(e){let t=e?.chain||Je,r=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,o=e?.duration||"24h";try{let s=await this.fetchTopGainers(t,r,o);return await this.enrichTrendingMarketData(s,t),{success:!0,data:s}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}};function X(n,e,t,r=[]){return{target:n,callData:M({abi:e,functionName:t,args:r})}}var Vn=1e27,$a=10n**27n,Ps=31536e3,wh=10;function et(n){return Number.isFinite(n)&&n>=0&&n<=wh?n:null}function Ol(n){return Math.expm1(n)}function tt(n,e){return Number(n)/10**e}function Ss(n){return new Date(n).toISOString().slice(0,10)}async function un(n,e,t){let r=`${t.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${n.token}?range=h&day=${7}`,o=await C.get(r);if(!o.ok)throw new Error(_(o));return{samples:(Array.isArray(o.data)?o.data:o.data?.data||[]).filter(a=>a?.rate!==null&&a?.rate!==void 0).map(a=>({timeMs:Date.parse(a?.date??""),fraction:Number(a?.rate)})),current:null,rewards:[]}}var At=class{underlyingCall(e){return X(e.contract,wt,"asset")}liveRateCall(e,t){return null}followUpRateCall(e,t){return null}decodeSize(e,t){if(!Number.isInteger(t.decimals)||t.decimals<0)return null;let r=ee(e);return r===null?null:tt(r,t.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,t){return this.balanceIsUnderlying?null:X(e.contract,wt,"convertToAssets",[t])}},Pt=class extends At{type="spark";balanceIsUnderlying=!1;sizeCall(e){return X(e.contract,wt,"totalAssets")}fetchApy(e,t,r,o){return un(e,t,r)}};var Ml=[{type:"constructor",inputs:[{name:"owner_",type:"address",internalType:"address"},{name:"supportedRouter_",type:"address",internalType:"address"},{name:"nonfungiblePositionManager_",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"NATIVE_TOKEN",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getSupportedRouters",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"increaseLiquidity",inputs:[{name:"tokenId_",type:"uint256",internalType:"uint256"},{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"increaseLiquidityData_",type:"tuple",internalType:"struct CoinPoolGateway.IncreaseLiquidityData",components:[{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"mint",inputs:[{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"mintData_",type:"tuple",internalType:"struct CoinPoolGateway.MintData",components:[{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickLower",type:"int24",internalType:"int24"},{name:"tickUpper",type:"int24",internalType:"int24"},{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"nonfungiblePositionManager",inputs:[],outputs:[{name:"",type:"address",internalType:"contract INonfungiblePositionManager"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"pause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"paused",inputs:[],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"renounceOwnership",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"rescue",inputs:[{name:"token_",type:"address",internalType:"address"},{name:"amount_",type:"uint256",internalType:"uint256"},{name:"recipient_",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"transferOwnership",inputs:[{name:"newOwner",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unpause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"updateSupportedRouters",inputs:[{name:"routers_",type:"address[]",internalType:"address[]"},{name:"isSupported_",type:"bool[]",internalType:"bool[]"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"LiquidityIncreased",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Minted",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"Paused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"SupportedRoutersUpdated",inputs:[{name:"routers",type:"address[]",indexed:!1,internalType:"address[]"},{name:"isSupported",type:"bool[]",indexed:!1,internalType:"bool[]"}],anonymous:!1},{type:"event",name:"Unpaused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"EnforcedPause",inputs:[]},{type:"error",name:"ExpectedPause",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InsufficientAmountOut",inputs:[]},{type:"error",name:"InsufficientBalance",inputs:[{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidAmountIn",inputs:[]},{type:"error",name:"InvalidLength",inputs:[]},{type:"error",name:"InvalidRefundUnusedToken",inputs:[]},{type:"error",name:"InvalidSwapAction",inputs:[]},{type:"error",name:"InvalidTokenInInfo",inputs:[]},{type:"error",name:"InvalidTokenOutInfo",inputs:[]},{type:"error",name:"InvalidTotalAmountIn",inputs:[]},{type:"error",name:"NotSupportedRouter",inputs:[]},{type:"error",name:"OwnableInvalidOwner",inputs:[{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"OwnableUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"}]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedDecreaseAllowance",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"currentAllowance",type:"uint256",internalType:"uint256"},{name:"requestedDecrease",type:"uint256",internalType:"uint256"}]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}];var Fl=[{type:"function",name:"slot0",stateMutability:"view",inputs:[],outputs:[{name:"sqrtPriceX96",type:"uint160"},{name:"tick",type:"int24"},{name:"observationIndex",type:"uint16"},{name:"observationCardinality",type:"uint16"},{name:"observationCardinalityNext",type:"uint16"},{name:"feeProtocol",type:"uint8"},{name:"unlocked",type:"bool"}]},{type:"function",name:"liquidity",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint128"}]},{type:"function",name:"tickSpacing",stateMutability:"view",inputs:[],outputs:[{name:"",type:"int24"}]},{type:"function",name:"fee",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint24"}]},{type:"function",name:"token0",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"token1",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var Va=[{type:"function",name:"getReserveData",stateMutability:"view",inputs:[{name:"asset",type:"address"}],outputs:[{name:"reserveData",type:"tuple",components:[{name:"configuration",type:"uint256"},{name:"liquidityIndex",type:"uint128"},{name:"currentLiquidityRate",type:"uint128"}]}]}],Br=[{type:"function",name:"UNDERLYING_ASSET_ADDRESS",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"POOL",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}],Bl=[{type:"function",name:"ADDRESSES_PROVIDER",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var Mt=[{inputs:[],name:"getUtilization",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseToken",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"utilization",type:"uint256"}],name:"getSupplyRate",outputs:[{name:"",type:"uint64"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseTrackingSupplySpeed",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseIndexScale",outputs:[{name:"",type:"uint64"}],stateMutability:"pure",type:"function"}],ql=[{inputs:[{name:"comet",type:"address"}],name:"rewardConfig",outputs:[{name:"token",type:"address"},{name:"rescaleFactor",type:"uint64"},{name:"shouldUpscale",type:"bool"}],stateMutability:"view",type:"function"}];var qr=[{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"vsr",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],dn=[{inputs:[],name:"getAPR",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getConversionRate",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],$l=[{inputs:[],name:"susds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"usds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var Hl=[{inputs:[],name:"manager",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}],Vl=[{inputs:[],name:"pool",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"factory",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var Th=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!, $reserve: ReserveRequest!) {
5
5
  value: supplyAPYHistory(request: $request) { date avgRate { value } }
6
6
  reserve(request: $reserve) {
7
7
  incentives {
@@ -22,7 +22,7 @@ ${o}`:`The contract function "${r??"call"}" reverted.`,{metaMessages:t&&t!=="0x"
22
22
  avgNetApy(lookback: SEVEN_DAYS)
23
23
  historicalState { avgNetApy(options: $options) { x y } }
24
24
  }
25
- }`,Es=class extends Pt{type="morpho-v2";async fetchApy(e,t,r){let o=Math.floor(Date.now()/1e3),s=await C.post(r.morphoApiUrl,{operationName:"VaultV2ByAddress",query:Ih,variables:{address:e.contract,chainId:t.chainId,options:{startTimestamp:o-7*86400,endTimestamp:o,interval:"HOUR"}}});if(!s.ok)throw new Error(_(s));let a=s.data?.data?.vaultV2ByAddress,i=Number(a?.netApy),l=Number(a?.avgNetApy);return{avgOverride:Number.isFinite(l)?l:null,samples:(a?.historicalState?.avgNetApy||[]).filter(c=>c?.y!==null&&c?.y!==void 0).map(c=>({timeMs:Number(c?.x)*1e3,fraction:Number(c?.y)})),current:Number.isFinite(i)?i:null,rewards:[]}}};var _s=class extends Pt{type="spark";liveRateCall(e){return X(e.contract,qr,"rateProvider")}followUpRateCall(e,t){let r=B(t);return r===null?null:X(r,dn,"getAPR")}decodeLiveRate(e){let t=ee(e);return t===null?null:et(Math.expm1(Number(t)/Vn))}},Ns=class extends Pt{type="spark-ethereum";liveRateCall(e){return X(e.contract,qr,"vsr")}decodeLiveRate(e){let t=ee(e);if(t===null||t<=0n)return null;let r=Number(t-$a)/Vn;return r>-1?et(Math.expm1(Math.log1p(r)*Ps)):null}};var Ls=class extends At{type="spark-l2-susds";balanceIsUnderlying=!1;underlyingCall(){return null}sizeCall(e){return X(e.token,q,"totalSupply")}liveRateCall(e){return X(e.contract,dn,"getAPR")}decodeLiveRate(e){let t=ee(e);return t===null?null:et(Math.expm1(Number(t)/Vn))}convertToAssetsCall(e){return X(e.contract,dn,"getConversionRate")}fetchApy(e,t,r){return un(e,t,r)}};function Wn(n,e,t,r){if(e<=0n||!Number.isInteger(t)||!Number.isInteger(r)||t<0||r<0)return null;let o=n*e/$a,s=r-t;return s===0?o:s>0?o*10n**BigInt(s):o/10n**BigInt(-s)}var Ya={"aave-v3":{protocol:new xs,label:"Aave V3",home:"https://app.aave.com"},"compound-v3":{protocol:new Cs,label:"Compound V3",home:"https://app.compound.finance"},spark:{protocol:new _s,label:"Spark",home:"https://app.spark.fi"},"spark-ethereum":{protocol:new Ns,label:"Spark",home:"https://app.spark.fi"},"spark-l2-susds":{protocol:new Ls,label:"Spark",home:"https://app.spark.fi"},"morpho-v2":{protocol:new Es,label:"Morpho V2",home:"https://app.morpho.org"},maple:{protocol:new Rs,label:"Maple",home:"https://app.maple.finance"}},Uh=Ya.spark.protocol;function pn(n){return Ya[n.type]?.protocol??Uh}function Ke(n){return Ya[n]?.label??null}function Is(n){return Ya[n]?.home??null}var Yn="0x0000000000000000000000000000000000000000";function Us(n){let e=parseInt(n,16);return Number.isFinite(e)?{chainId:e}:null}function Ft(n){if(typeof n=="number")return Number.isInteger(n)&&n>0?`0x${n.toString(16)}`:null;if(typeof n!="string")return null;let e=n.trim().toLowerCase();if(!e)return null;if(!/^(0x[0-9a-f]+|\d+)$/.test(e))return D(e);let t=e.startsWith("0x")?parseInt(e,16):Number(e);return Number.isInteger(t)&&t>0?`0x${t.toString(16)}`:null}var Dh={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function Ga(n){let e=Ft(n);return e?Dh[e]??null:null}function $u(n){return["susds","usds","rateProvider"].map(e=>({target:n,callData:M({abi:$l,functionName:e})}))}var Hu=3,Oh={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function Wl(n){let e=Ft(n),t=e?Oh[e]:void 0;return t?{target:t,callData:M({abi:dn,functionName:"getConversionRate"})}:null}var Mh=new Set(["spark","spark-ethereum","spark-l2-susds","morpho-v2","maple"]),Vu="spark-l2-susds";function Ka(n){return!!n&&Mh.has(n)}var Yl=n=>{if(n==null||n==="")return null;let e=Number(n);return!Number.isInteger(e)||e<0||e>36?null:e},Fh=n=>{if(n==null||n==="")return null;let e=Number(n);return Number.isFinite(e)&&e>0?e:null};function Ds(n){let e=Fh(n.yieldAsset?.fixedPrice);return e!==null?e:Number.isFinite(n.priceUSD)?n.priceUSD:0}function Wu(n){if(!Ka(n.yieldProtocol)||Yl(n.yieldAsset?.decimals)===null||n.yieldProtocol===Vu&&!Wl(n.chain))return!1;let e=Ds(n);return Number.isFinite(e)&&e>0}function Gl(n){let e=[],t=[];for(let r of n)if(!(r.rawBalance<=0n)&&Wu(r)){if(r.yieldProtocol===Vu){let o=Wl(r.chain);if(!o)continue;e.push({key:r.key,...o}),t.push(r.key);continue}e.push({key:r.key,target:r.address,callData:M({abi:wt,functionName:"convertToAssets",args:[r.rawBalance]})})}return{calls:e,rateKeys:t}}function ja(n,e,t){let r=new Map(n.map(i=>[i.key,i])),o=new Set(e.rateKeys),s=new Map;e.calls.forEach((i,l)=>{let c=ee(t[l]??null);if(c===null)return;if(!o.has(i.key)){s.set(i.key,c);return}let d=r.get(i.key),u=Yl(d?.yieldAsset?.decimals);if(!d||u===null)return;let p=Wn(d.rawBalance,c,d.decimals,u);p!==null&&s.set(i.key,p)});let a=new Map;for(let i of n){let l=tt(i.rawBalance,i.decimals),c=Ds(i),d=s.get(i.key),u={underlyingAmount:l,valueUSD:l*c,pricePerTokenUSD:c,converted:!1};if(d===void 0){a.set(i.key,u);continue}let p=Yl(i.yieldAsset?.decimals);if(p===null){a.set(i.key,u);continue}let m=tt(d,p),f=m*c;a.set(i.key,{underlyingAmount:m,valueUSD:f,pricePerTokenUSD:l>0?f/l:c,converted:!0})}return a}async function za(n,e,t={}){let r=e.map(a=>a.chain==null?{...a,chain:n}:a),o=Gl(r);if(o.calls.length===0)return ja(r,o,[]);let s=await Te(String(n),o.calls,t.rpcUrl);return ja(r,o,s)}async function Wa(n,e,t={}){let r=await Bh(n,e,t.apiBaseUrl);return r?Gu(n,r,t):null}async function Gu(n,e,t={}){let r=Yu(e?.price),o=l=>l!=null&&l>0?l:null;if(!Ka(e?.yieldProtocol))return o(r);let s=Ds({key:"price",address:"",rawBalance:0n,decimals:0,priceUSD:r??0,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:n});if(!(s>0))return null;let a=Math.trunc(Yu(e?.decimals)??18);if(!Number.isInteger(a)||a<0||a>36)return o(r);let i={key:"price",address:String(e?.address??"").toLowerCase(),rawBalance:10n**BigInt(a),decimals:a,priceUSD:s,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:n};try{let c=(await za(n,[i],t)).get(i.key);return c?.converted?o(c.pricePerTokenUSD):null}catch{return null}}async function Bh(n,e,t){let r=String(e??"").toLowerCase();if(!r)return null;try{return(await new Ae(t?{baseUrl:t}:void 0).getYieldPricingTokens(n,[r])).find(a=>String(a?.address??"").toLowerCase()===r)??null}catch{return null}}function Yu(n){if(n==null||n==="")return null;let e=typeof n=="number"?n:Number(n);return Number.isFinite(e)?e:null}var qh="https://nft.keyring.app",$h="https://nft.keyring.app",Hh=.01,N=5,oe=1e3,Vh=25,Wh="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Yh="0x0000000000000000000000000000000000000000",L=class extends Error{constructor(t,r){super(r);this.status=t;this.name="MoralisHttpError"}status};function ce(n){return n||Je}function se(n){let e=[];for(let[t,r]of Object.entries(n))if(r!=null)if(Array.isArray(r))for(let o of r)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);return e.join("&")}function ae(n){return new Promise(e=>setTimeout(e,n))}function Gh(n){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!n||typeof n!="object")return e;let t=n;if("active_protocols"in t||"total_usd_value"in t){let o=t;return{...e,...o,protocols:o.protocols||[]}}let r=t.result;return!r||typeof r!="object"?e:{active_protocols:r.activeProtocols??0,total_positions:r.totalPositions??0,total_usd_value:r.totalUsd??0,total_unclaimed_usd_value:r.totalUnclaimedUsd??0,protocols:(r.protocols||[]).map(o=>({protocol_id:o.protocolId,protocol_name:o.protocolName,protocol_url:o.protocolUrl??"",protocol_logo:o.protocolLogo??"",positions:o.positionCount??0,total_usd_value:o.totalUsd??0,total_unclaimed_usd_value:o.totalUnclaimedUsd??0,account_health_factor:o.accountHealthFactor??null}))}}function Kh(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(r=>({token_type:r.tokenType,address:r.address,contract_address:r.address,name:r.name??"",symbol:r.symbol??"",decimals:r.decimals??18,logo:r.logo,balance:r.balance??"0",balance_formatted:r.balanceFormatted??"0",usd_price:r.usdPrice,usd_value:r.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,r)=>Number(t)-Number(r)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function Kl(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,r)=>Number(t)-Number(r)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var O=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??qh).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??$h).replace(/\/+$/,""),this.pantograph=new Ae({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:r,tokenAddresses:o,excludeSpam:s=!1,excludeUnverifiedContracts:a=!1,convertYieldValues:i=!0}=e;if(!t)return{success:!1,error:"Address is required"};let l=ce(r),c="Unknown error";for(let d=1;d<=N;d++)try{let u={chain:l,exclude_spam:s,exclude_unverified_contracts:a,limit:100};o&&(u.token_addresses=o);let p=[],m=null;do{m&&(u.cursor=m);let h=se(u),g=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${h}`,b=await C.get(g);if(!b.ok)throw new L(b.status,_(b));let y=b.data,w=y?.data??y;w?.result?.length>0&&p.push(...w.result),m=w?.cursor??null}while(m);let f={result:p};if(f?.result?.length>0){f.result=f.result.filter(g=>parseFloat(g.balance||"0")>0),f.result=f.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===Wh?Yh:g.token_address}));let h=await this.enrichTokenPrices(f.result,l);i&&await this.applyYieldValues(f.result,l,h),f.result=f.result.filter(g=>g.usd_value==null||g.usd_value>=Hh)}return{success:!0,data:f}}catch(u){if(c=u instanceof Error?u.message:"Unknown error",u instanceof L&&u.status===400)break;d<N&&await ae(oe)}return{success:!1,error:c}}async getTokenMetadata(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Token address is required"};let o=ce(r),s="Unknown error",a=await this.pantograph.getTokenMetadata(t,o);if(a)return{success:!0,data:a};for(let i=1;i<=N;i++)try{let[l,c]=await Promise.allSettled([C.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${se({chain:o,addresses:[t]})}`),C.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${se({chain:o,include:"percent_change"})}`)]),d=null;if(l.status==="fulfilled"&&l.value.ok){let p=l.value.data;d=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!d){s="Token metadata not found",i<N&&await ae(oe);continue}let u=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;u=p?.data??p}return{success:!0,data:{...d,...u?.usd_price?{usd_price:u.usd_price}:{},...u?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:u.usd_price_change_percentage_24h}:{}}}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await ae(oe)}return{success:!1,error:s}}async getWalletNFTs(e){let{address:t,chain:r,limit:o=100,excludeSpam:s=!1,cursor:a,tokenAddresses:i,includePrices:l,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let d=ce(r),u=[],p=a,m,f;for(let h=0;h<Vh;h++){let g=await this.fetchWalletNftsPage({address:t,moralisChain:d,limit:o,excludeSpam:s,cursor:p,tokenAddresses:i,includePrices:l,format:c});if(!g.success){if(u.length===0)return g;break}let b=g.data;if(!b)break;let{result:y,cursor:w,page:k,page_size:v}=b;if(Array.isArray(y)&&u.push(...y),m=k,f=v,p=typeof w=="string"&&w.trim()?w:void 0,!p)break}return{success:!0,data:{result:u,cursor:p,page:m,page_size:f}}}async fetchWalletNftsPage(e){let{address:t,moralisChain:r,limit:o,excludeSpam:s,cursor:a,tokenAddresses:i,includePrices:l,format:c}=e,d="Unknown error";for(let u=1;u<=N;u++)try{let p={chain:r,format:c,limit:o,exclude_spam:s,media_items:!0,normalizeMetadata:!0};a&&(p.cursor=a),l&&(p.include_prices=!0),i&&i.length>0&&(p.token_addresses=i);let m=se(p),f=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${m}`,h=await C.get(f);if(!h.ok)throw new L(h.status,_(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(d=p instanceof Error?p.message:"Unknown error",p instanceof L&&p.status===400)break;u<N&&await ae(oe)}return{success:!1,error:d}}async getWalletNftCollections(e){let{address:t,chain:r,limit:o=100,excludeSpam:s=!0,cursor:a}=e;if(!t)return{success:!1,error:"Address is required"};let i=ce(r),l="Unknown error";for(let c=1;c<=N;c++)try{let d={chain:i,limit:o,exclude_spam:s};a&&(d.cursor=a);let u=se(d),p=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/collections?${u}`,m=await C.get(p);if(!m.ok)throw new L(m.status,_(m));let f=m.data;return{success:!0,data:f?.data??f}}catch(d){if(l=d instanceof Error?d.message:"Unknown error",d instanceof L&&d.status===400)break;c<N&&await ae(oe)}return{success:!1,error:l}}async getNftMetadata(e){let{address:t,tokenId:r,chain:o,format:s="decimal",normalizeMetadata:a=!0,mediaItems:i=!0,include:l}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(r==null||r==="")return{success:!1,error:"Token ID is required"};if(!R(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=ce(o),d="Unknown error";for(let u=1;u<=N;u++)try{let p={chain:c,format:s,normalizeMetadata:a,media_items:i};l&&(p.include=l);let m=se(p),f=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(r)}?${m}`,h=await C.get(f);if(!h.ok)throw new L(h.status,_(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(d=p instanceof Error?p.message:"Unknown error",p instanceof L&&p.status===400)break;u<N&&await ae(oe)}return{success:!1,error:d}}async getNftContractMetadata(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Contract address is required"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getWalletHistory(e){let{address:t,chain:r,limit:o=25,fromDate:s,toDate:a,fromBlock:i,toBlock:l,cursor:c,order:d="DESC",includeInternalTransactions:u,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=ce(r),f=Math.max(1,Math.min(100,Math.floor(o))),h="Unknown error";for(let g=1;g<=N;g++)try{let b={chain:m,limit:f,order:d};s&&(b.from_date=s),a&&(b.to_date=a),i!=null&&(b.from_block=i),l!=null&&(b.to_block=l),c&&(b.cursor=c),u!=null&&(b.include_internal_transactions=u),p!=null&&(b.nft_metadata=p);let y=se(b),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${y}`,k=await C.get(w);if(!k.ok)throw new L(k.status,_(k));let v=k.data;return{success:!0,data:v?.data??v}}catch(b){if(h=b instanceof Error?b.message:"Unknown error",b instanceof L&&b.status===400)break;g<N&&await ae(oe)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:r,contractAddresses:o,limit:s=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:d,order:u="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=ce(r),m=Math.max(1,Math.min(100,Math.floor(s))),f="Unknown error";for(let h=1;h<=N;h++)try{let g={chain:p,limit:m,order:u};a&&(g.from_date=a),i&&(g.to_date=i),l!=null&&(g.from_block=l),c!=null&&(g.to_block=c),d&&(g.cursor=d),o?.length&&(g.contract_addresses=o);let b=se(g),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${b}`,w=await C.get(y);if(!w.ok)throw new L(w.status,_(w));let k=w.data;return{success:!0,data:k?.data??k}}catch(g){if(f=g instanceof Error?g.message:"Unknown error",g instanceof L&&g.status===400)break;h<N&&await ae(oe)}return{success:!1,error:f}}async getWalletNftTransfers(e){let{address:t,chain:r,contractAddresses:o,limit:s=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:d,order:u="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let f=ce(r),h=Math.max(1,Math.min(100,Math.floor(s))),g="Unknown error";for(let b=1;b<=N;b++)try{let y={chain:f,limit:h,order:u,format:m};a&&(y.from_date=a),i&&(y.to_date=i),l!=null&&(y.from_block=l),c!=null&&(y.to_block=c),d&&(y.cursor=d),o?.length&&(y.contract_addresses=o),p!=null&&(y.include_prices=p);let w=se(y),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,v=await C.get(k);if(!v.ok)throw new L(v.status,_(v));let S=v.data;return{success:!0,data:S?.data??S}}catch(y){if(g=y instanceof Error?y.message:"Unknown error",y instanceof L&&y.status===400)break;b<N&&await ae(oe)}return{success:!1,error:g}}async getTokenHolders(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!R(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getWalletPnlSummary(e){let{address:t,chain:r,days:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let s=ce(r),a="Unknown error";for(let i=1;i<=N;i++)try{let l={chain:s};o&&(l.days=o);let c=se(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,u=await C.get(d);if(!u.ok)throw new L(u.status,_(u));let p=u.data;return{success:!0,data:p?.data??p}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await ae(oe)}return{success:!1,error:a}}async getWalletPnl(e){let{address:t,chain:r,days:o,tokenAddresses:s}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=ce(r),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:a};o&&(c.days=o),s&&s.length>0&&(c.token_addresses=s.slice(0,25));let d=se(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${d}`,p=await C.get(u);if(!p.ok)throw new L(p.status,_(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof L&&c.status===400)break;l<N&&await ae(oe)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:r}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getWalletApprovals(e){let{address:t,chain:r,limit:o,cursor:s}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=ce(r),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:a};o!=null&&(c.limit=o),s&&(c.cursor=s);let d=se(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${d}`,p=await C.get(u);if(!p.ok)throw new L(p.status,_(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof L&&c.status===400)break;l<N&&await ae(oe)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:Gh(u)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getWalletDefiPositions(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:Kh(u)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:r,chain:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!r)return{success:!1,error:"Protocol identifier is required"};if(!R(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let s=ce(o),a="Unknown error";for(let i=1;i<=N;i++)try{let l=se({chains:s}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(r)}/positions?${l}`,d=await C.get(c);if(!d.ok)throw new L(d.status,_(d));let m=d.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(h=>({label:h.label,address:h.address,balance_usd:h.balanceUsd??0,total_unclaimed_usd_value:h.unclaimedUsd??0,position_details:h.details,tokens:h.tokens.map(g=>({token_type:g.tokenType,address:g.address,contract_address:g.address,name:g.name??"",symbol:g.symbol??"",decimals:g.decimals??18,logo:g.logo,balance:g.balance??"0",balance_formatted:g.balanceFormatted??"0",usd_price:g.usdPrice,usd_value:g.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await ae(oe)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!R(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getTokenScore(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!R(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getTrendingTokens(e){let t=e?.chain,r=e?.limit,o="Unknown error";for(let s=1;s<=N;s++)try{let a={};t&&(a.chain=ce(t)),r!=null&&(a.limit=r);let i=se(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:Kl(u)}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof L&&a.status===400)break;s<N&&await ae(oe)}return{success:!1,error:o}}async getTopGainers(e){let{chain:t,timeFrame:r,minMarketCap:o,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=ce(t)),r&&(l.time_frame=r),o!=null&&(l.min_market_cap=o),s!=null&&(l.security_score=s);let c=se(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,u=await C.get(d);if(!u.ok)throw new L(u.status,_(u));let p=u.data,m=p?.data??p;return{success:!0,data:Kl(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await ae(oe)}return{success:!1,error:a}}async getTopLosers(e){let{chain:t,timeFrame:r,minMarketCap:o,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=ce(t)),r&&(l.time_frame=r),o!=null&&(l.min_market_cap=o),s!=null&&(l.security_score=s);let c=se(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,u=await C.get(d);if(!u.ok)throw new L(u.status,_(u));let p=u.data,m=p?.data??p;return{success:!0,data:Kl(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await ae(oe)}return{success:!1,error:a}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}async applyYieldValues(e,t,r){if(e.length===0||r.size===0)return;let o=[],s=new Map;if(e.forEach((a,i)=>{let l=r.get(a.token_address.toLowerCase());if(!l?.yieldProtocol||!/^\d+$/.test(a.balance??""))return;let c=BigInt(a.balance);if(c<=0n)return;let d=String(i);s.set(d,a),o.push({key:d,address:a.token_address,rawBalance:c,decimals:a.decimals,priceUSD:a.usd_price??0,yieldProtocol:l.yieldProtocol,yieldAsset:l.yieldAsset,chain:t})}),o.length!==0)try{let a=await za(t,o);for(let[i,l]of a){let c=s.get(i);c&&(!Number.isFinite(l.valueUSD)||!Number.isFinite(l.pricePerTokenUSD)||l.pricePerTokenUSD<=0||(c.usd_value=l.valueUSD,c.usd_price=l.pricePerTokenUSD))}}catch{}}};var $r=class extends A{name="get-token-info";description='Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad';category="blockchain-data";parameters=[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}];service;llm;constructor(e){super(),this.service=new O(e),this.llm=new ke(e?.llm??{})}async run(e,t){let r=e.keyword||"",o=e.prompt||"",s=t?.walletAddress||void 0;if(!r)return{error:"Missing required parameter: keyword"};let a;try{a=Pe(e.chain,t)}catch(i){if(i instanceof cn)return await this.researchTokenChainAgnostic(r,o,s);throw i}return await this.searchToken(r,a,o,s)}async researchTokenChainAgnostic(e,t,r){let o=[r?`User's connected wallet address: ${r}`:null,"The user's connected chain is not one this app supports on-chain, so answer using web research only \u2014 do not assume a specific chain; identify the token across whichever chain(s) it actually exists on."].filter(Boolean).join(`
25
+ }`,Es=class extends Pt{type="morpho-v2";async fetchApy(e,t,r){let o=Math.floor(Date.now()/1e3),s=await C.post(r.morphoApiUrl,{operationName:"VaultV2ByAddress",query:Ih,variables:{address:e.contract,chainId:t.chainId,options:{startTimestamp:o-7*86400,endTimestamp:o,interval:"HOUR"}}});if(!s.ok)throw new Error(_(s));let a=s.data?.data?.vaultV2ByAddress,i=Number(a?.netApy),l=Number(a?.avgNetApy);return{avgOverride:Number.isFinite(l)?l:null,samples:(a?.historicalState?.avgNetApy||[]).filter(c=>c?.y!==null&&c?.y!==void 0).map(c=>({timeMs:Number(c?.x)*1e3,fraction:Number(c?.y)})),current:Number.isFinite(i)?i:null,rewards:[]}}};var _s=class extends Pt{type="spark";liveRateCall(e){return X(e.contract,qr,"rateProvider")}followUpRateCall(e,t){let r=B(t);return r===null?null:X(r,dn,"getAPR")}decodeLiveRate(e){let t=ee(e);return t===null?null:et(Math.expm1(Number(t)/Vn))}},Ns=class extends Pt{type="spark-ethereum";liveRateCall(e){return X(e.contract,qr,"vsr")}decodeLiveRate(e){let t=ee(e);if(t===null||t<=0n)return null;let r=Number(t-$a)/Vn;return r>-1?et(Math.expm1(Math.log1p(r)*Ps)):null}};var Ls=class extends At{type="spark-l2-susds";balanceIsUnderlying=!1;underlyingCall(){return null}sizeCall(e){return X(e.token,q,"totalSupply")}liveRateCall(e){return X(e.contract,dn,"getAPR")}decodeLiveRate(e){let t=ee(e);return t===null?null:et(Math.expm1(Number(t)/Vn))}convertToAssetsCall(e){return X(e.contract,dn,"getConversionRate")}fetchApy(e,t,r){return un(e,t,r)}};function Wn(n,e,t,r){if(e<=0n||!Number.isInteger(t)||!Number.isInteger(r)||t<0||r<0)return null;let o=n*e/$a,s=r-t;return s===0?o:s>0?o*10n**BigInt(s):o/10n**BigInt(-s)}var Ya={"aave-v3":{protocol:new xs,label:"Aave V3",home:"https://app.aave.com"},"compound-v3":{protocol:new Cs,label:"Compound V3",home:"https://app.compound.finance"},spark:{protocol:new _s,label:"Spark",home:"https://app.spark.fi"},"spark-ethereum":{protocol:new Ns,label:"Spark",home:"https://app.spark.fi"},"spark-l2-susds":{protocol:new Ls,label:"Spark",home:"https://app.spark.fi"},"morpho-v2":{protocol:new Es,label:"Morpho V2",home:"https://app.morpho.org"},maple:{protocol:new Rs,label:"Maple",home:"https://app.maple.finance"}},Uh=Ya.spark.protocol;function pn(n){return Ya[n.type]?.protocol??Uh}function Ke(n){return Ya[n]?.label??null}function Is(n){return Ya[n]?.home??null}var Yn="0x0000000000000000000000000000000000000000";function Us(n){let e=parseInt(n,16);return Number.isFinite(e)?{chainId:e}:null}function Ft(n){if(typeof n=="number")return Number.isInteger(n)&&n>0?`0x${n.toString(16)}`:null;if(typeof n!="string")return null;let e=n.trim().toLowerCase();if(!e)return null;if(!/^(0x[0-9a-f]+|\d+)$/.test(e))return I(e);let t=e.startsWith("0x")?parseInt(e,16):Number(e);return Number.isInteger(t)&&t>0?`0x${t.toString(16)}`:null}var Dh={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function Ga(n){let e=Ft(n);return e?Dh[e]??null:null}function $u(n){return["susds","usds","rateProvider"].map(e=>({target:n,callData:M({abi:$l,functionName:e})}))}var Hu=3,Oh={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function Wl(n){let e=Ft(n),t=e?Oh[e]:void 0;return t?{target:t,callData:M({abi:dn,functionName:"getConversionRate"})}:null}var Mh=new Set(["spark","spark-ethereum","spark-l2-susds","morpho-v2","maple"]),Vu="spark-l2-susds";function Ka(n){return!!n&&Mh.has(n)}var Yl=n=>{if(n==null||n==="")return null;let e=Number(n);return!Number.isInteger(e)||e<0||e>36?null:e},Fh=n=>{if(n==null||n==="")return null;let e=Number(n);return Number.isFinite(e)&&e>0?e:null};function Ds(n){let e=Fh(n.yieldAsset?.fixedPrice);return e!==null?e:Number.isFinite(n.priceUSD)?n.priceUSD:0}function Wu(n){if(!Ka(n.yieldProtocol)||Yl(n.yieldAsset?.decimals)===null||n.yieldProtocol===Vu&&!Wl(n.chain))return!1;let e=Ds(n);return Number.isFinite(e)&&e>0}function Gl(n){let e=[],t=[];for(let r of n)if(!(r.rawBalance<=0n)&&Wu(r)){if(r.yieldProtocol===Vu){let o=Wl(r.chain);if(!o)continue;e.push({key:r.key,...o}),t.push(r.key);continue}e.push({key:r.key,target:r.address,callData:M({abi:wt,functionName:"convertToAssets",args:[r.rawBalance]})})}return{calls:e,rateKeys:t}}function ja(n,e,t){let r=new Map(n.map(i=>[i.key,i])),o=new Set(e.rateKeys),s=new Map;e.calls.forEach((i,l)=>{let c=ee(t[l]??null);if(c===null)return;if(!o.has(i.key)){s.set(i.key,c);return}let d=r.get(i.key),u=Yl(d?.yieldAsset?.decimals);if(!d||u===null)return;let p=Wn(d.rawBalance,c,d.decimals,u);p!==null&&s.set(i.key,p)});let a=new Map;for(let i of n){let l=tt(i.rawBalance,i.decimals),c=Ds(i),d=s.get(i.key),u={underlyingAmount:l,valueUSD:l*c,pricePerTokenUSD:c,converted:!1};if(d===void 0){a.set(i.key,u);continue}let p=Yl(i.yieldAsset?.decimals);if(p===null){a.set(i.key,u);continue}let m=tt(d,p),f=m*c;a.set(i.key,{underlyingAmount:m,valueUSD:f,pricePerTokenUSD:l>0?f/l:c,converted:!0})}return a}async function za(n,e,t={}){let r=e.map(a=>a.chain==null?{...a,chain:n}:a),o=Gl(r);if(o.calls.length===0)return ja(r,o,[]);let s=await Te(String(n),o.calls,t.rpcUrl);return ja(r,o,s)}async function Wa(n,e,t={}){let r=await Bh(n,e,t.apiBaseUrl);return r?Gu(n,r,t):null}async function Gu(n,e,t={}){let r=Yu(e?.price),o=l=>l!=null&&l>0?l:null;if(!Ka(e?.yieldProtocol))return o(r);let s=Ds({key:"price",address:"",rawBalance:0n,decimals:0,priceUSD:r??0,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:n});if(!(s>0))return null;let a=Math.trunc(Yu(e?.decimals)??18);if(!Number.isInteger(a)||a<0||a>36)return o(r);let i={key:"price",address:String(e?.address??"").toLowerCase(),rawBalance:10n**BigInt(a),decimals:a,priceUSD:s,yieldProtocol:e?.yieldProtocol??null,yieldAsset:e?.yieldAsset??null,chain:n};try{let c=(await za(n,[i],t)).get(i.key);return c?.converted?o(c.pricePerTokenUSD):null}catch{return null}}async function Bh(n,e,t){let r=String(e??"").toLowerCase();if(!r)return null;try{return(await new Ae(t?{baseUrl:t}:void 0).getYieldPricingTokens(n,[r])).find(a=>String(a?.address??"").toLowerCase()===r)??null}catch{return null}}function Yu(n){if(n==null||n==="")return null;let e=typeof n=="number"?n:Number(n);return Number.isFinite(e)?e:null}var qh="https://nft.keyring.app",$h="https://nft.keyring.app",Hh=.01,N=5,oe=1e3,Vh=25,Wh="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",Yh="0x0000000000000000000000000000000000000000",L=class extends Error{constructor(t,r){super(r);this.status=t;this.name="MoralisHttpError"}status};function ce(n){return n||Je}function se(n){let e=[];for(let[t,r]of Object.entries(n))if(r!=null)if(Array.isArray(r))for(let o of r)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(r))}`);return e.join("&")}function ae(n){return new Promise(e=>setTimeout(e,n))}function Gh(n){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!n||typeof n!="object")return e;let t=n;if("active_protocols"in t||"total_usd_value"in t){let o=t;return{...e,...o,protocols:o.protocols||[]}}let r=t.result;return!r||typeof r!="object"?e:{active_protocols:r.activeProtocols??0,total_positions:r.totalPositions??0,total_usd_value:r.totalUsd??0,total_unclaimed_usd_value:r.totalUnclaimedUsd??0,protocols:(r.protocols||[]).map(o=>({protocol_id:o.protocolId,protocol_name:o.protocolName,protocol_url:o.protocolUrl??"",protocol_logo:o.protocolLogo??"",positions:o.positionCount??0,total_usd_value:o.totalUsd??0,total_unclaimed_usd_value:o.totalUnclaimedUsd??0,account_health_factor:o.accountHealthFactor??null}))}}function Kh(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(r=>({token_type:r.tokenType,address:r.address,contract_address:r.address,name:r.name??"",symbol:r.symbol??"",decimals:r.decimals??18,logo:r.logo,balance:r.balance??"0",balance_formatted:r.balanceFormatted??"0",usd_price:r.usdPrice,usd_value:r.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,r)=>Number(t)-Number(r)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function Kl(n){if(Array.isArray(n))return n;if(n&&typeof n=="object"){let e=n;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,r)=>Number(t)-Number(r)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var O=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??qh).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??$h).replace(/\/+$/,""),this.pantograph=new Ae({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:r,tokenAddresses:o,excludeSpam:s=!1,excludeUnverifiedContracts:a=!1,convertYieldValues:i=!0}=e;if(!t)return{success:!1,error:"Address is required"};let l=ce(r),c="Unknown error";for(let d=1;d<=N;d++)try{let u={chain:l,exclude_spam:s,exclude_unverified_contracts:a,limit:100};o&&(u.token_addresses=o);let p=[],m=null;do{m&&(u.cursor=m);let h=se(u),g=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${h}`,b=await C.get(g);if(!b.ok)throw new L(b.status,_(b));let y=b.data,w=y?.data??y;w?.result?.length>0&&p.push(...w.result),m=w?.cursor??null}while(m);let f={result:p};if(f?.result?.length>0){f.result=f.result.filter(g=>parseFloat(g.balance||"0")>0),f.result=f.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===Wh?Yh:g.token_address}));let h=await this.enrichTokenPrices(f.result,l);i&&await this.applyYieldValues(f.result,l,h),f.result=f.result.filter(g=>g.usd_value==null||g.usd_value>=Hh)}return{success:!0,data:f}}catch(u){if(c=u instanceof Error?u.message:"Unknown error",u instanceof L&&u.status===400)break;d<N&&await ae(oe)}return{success:!1,error:c}}async getTokenMetadata(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Token address is required"};let o=ce(r),s="Unknown error",a=await this.pantograph.getTokenMetadata(t,o);if(a)return{success:!0,data:a};for(let i=1;i<=N;i++)try{let[l,c]=await Promise.allSettled([C.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${se({chain:o,addresses:[t]})}`),C.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${se({chain:o,include:"percent_change"})}`)]),d=null;if(l.status==="fulfilled"&&l.value.ok){let p=l.value.data;d=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!d){s="Token metadata not found",i<N&&await ae(oe);continue}let u=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;u=p?.data??p}return{success:!0,data:{...d,...u?.usd_price?{usd_price:u.usd_price}:{},...u?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:u.usd_price_change_percentage_24h}:{}}}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await ae(oe)}return{success:!1,error:s}}async getWalletNFTs(e){let{address:t,chain:r,limit:o=100,excludeSpam:s=!1,cursor:a,tokenAddresses:i,includePrices:l,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let d=ce(r),u=[],p=a,m,f;for(let h=0;h<Vh;h++){let g=await this.fetchWalletNftsPage({address:t,moralisChain:d,limit:o,excludeSpam:s,cursor:p,tokenAddresses:i,includePrices:l,format:c});if(!g.success){if(u.length===0)return g;break}let b=g.data;if(!b)break;let{result:y,cursor:w,page:k,page_size:v}=b;if(Array.isArray(y)&&u.push(...y),m=k,f=v,p=typeof w=="string"&&w.trim()?w:void 0,!p)break}return{success:!0,data:{result:u,cursor:p,page:m,page_size:f}}}async fetchWalletNftsPage(e){let{address:t,moralisChain:r,limit:o,excludeSpam:s,cursor:a,tokenAddresses:i,includePrices:l,format:c}=e,d="Unknown error";for(let u=1;u<=N;u++)try{let p={chain:r,format:c,limit:o,exclude_spam:s,media_items:!0,normalizeMetadata:!0};a&&(p.cursor=a),l&&(p.include_prices=!0),i&&i.length>0&&(p.token_addresses=i);let m=se(p),f=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${m}`,h=await C.get(f);if(!h.ok)throw new L(h.status,_(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(d=p instanceof Error?p.message:"Unknown error",p instanceof L&&p.status===400)break;u<N&&await ae(oe)}return{success:!1,error:d}}async getWalletNftCollections(e){let{address:t,chain:r,limit:o=100,excludeSpam:s=!0,cursor:a}=e;if(!t)return{success:!1,error:"Address is required"};let i=ce(r),l="Unknown error";for(let c=1;c<=N;c++)try{let d={chain:i,limit:o,exclude_spam:s};a&&(d.cursor=a);let u=se(d),p=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/collections?${u}`,m=await C.get(p);if(!m.ok)throw new L(m.status,_(m));let f=m.data;return{success:!0,data:f?.data??f}}catch(d){if(l=d instanceof Error?d.message:"Unknown error",d instanceof L&&d.status===400)break;c<N&&await ae(oe)}return{success:!1,error:l}}async getNftMetadata(e){let{address:t,tokenId:r,chain:o,format:s="decimal",normalizeMetadata:a=!0,mediaItems:i=!0,include:l}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(r==null||r==="")return{success:!1,error:"Token ID is required"};if(!R(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=ce(o),d="Unknown error";for(let u=1;u<=N;u++)try{let p={chain:c,format:s,normalizeMetadata:a,media_items:i};l&&(p.include=l);let m=se(p),f=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(r)}?${m}`,h=await C.get(f);if(!h.ok)throw new L(h.status,_(h));let g=h.data;return{success:!0,data:g?.data??g}}catch(p){if(d=p instanceof Error?p.message:"Unknown error",p instanceof L&&p.status===400)break;u<N&&await ae(oe)}return{success:!1,error:d}}async getNftContractMetadata(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Contract address is required"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getWalletHistory(e){let{address:t,chain:r,limit:o=25,fromDate:s,toDate:a,fromBlock:i,toBlock:l,cursor:c,order:d="DESC",includeInternalTransactions:u,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=ce(r),f=Math.max(1,Math.min(100,Math.floor(o))),h="Unknown error";for(let g=1;g<=N;g++)try{let b={chain:m,limit:f,order:d};s&&(b.from_date=s),a&&(b.to_date=a),i!=null&&(b.from_block=i),l!=null&&(b.to_block=l),c&&(b.cursor=c),u!=null&&(b.include_internal_transactions=u),p!=null&&(b.nft_metadata=p);let y=se(b),w=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${y}`,k=await C.get(w);if(!k.ok)throw new L(k.status,_(k));let v=k.data;return{success:!0,data:v?.data??v}}catch(b){if(h=b instanceof Error?b.message:"Unknown error",b instanceof L&&b.status===400)break;g<N&&await ae(oe)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:r,contractAddresses:o,limit:s=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:d,order:u="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=ce(r),m=Math.max(1,Math.min(100,Math.floor(s))),f="Unknown error";for(let h=1;h<=N;h++)try{let g={chain:p,limit:m,order:u};a&&(g.from_date=a),i&&(g.to_date=i),l!=null&&(g.from_block=l),c!=null&&(g.to_block=c),d&&(g.cursor=d),o?.length&&(g.contract_addresses=o);let b=se(g),y=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${b}`,w=await C.get(y);if(!w.ok)throw new L(w.status,_(w));let k=w.data;return{success:!0,data:k?.data??k}}catch(g){if(f=g instanceof Error?g.message:"Unknown error",g instanceof L&&g.status===400)break;h<N&&await ae(oe)}return{success:!1,error:f}}async getWalletNftTransfers(e){let{address:t,chain:r,contractAddresses:o,limit:s=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:d,order:u="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let f=ce(r),h=Math.max(1,Math.min(100,Math.floor(s))),g="Unknown error";for(let b=1;b<=N;b++)try{let y={chain:f,limit:h,order:u,format:m};a&&(y.from_date=a),i&&(y.to_date=i),l!=null&&(y.from_block=l),c!=null&&(y.to_block=c),d&&(y.cursor=d),o?.length&&(y.contract_addresses=o),p!=null&&(y.include_prices=p);let w=se(y),k=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${w}`,v=await C.get(k);if(!v.ok)throw new L(v.status,_(v));let S=v.data;return{success:!0,data:S?.data??S}}catch(y){if(g=y instanceof Error?y.message:"Unknown error",y instanceof L&&y.status===400)break;b<N&&await ae(oe)}return{success:!1,error:g}}async getTokenHolders(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!R(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getWalletPnlSummary(e){let{address:t,chain:r,days:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let s=ce(r),a="Unknown error";for(let i=1;i<=N;i++)try{let l={chain:s};o&&(l.days=o);let c=se(l),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,u=await C.get(d);if(!u.ok)throw new L(u.status,_(u));let p=u.data;return{success:!0,data:p?.data??p}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await ae(oe)}return{success:!1,error:a}}async getWalletPnl(e){let{address:t,chain:r,days:o,tokenAddresses:s}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=ce(r),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:a};o&&(c.days=o),s&&s.length>0&&(c.token_addresses=s.slice(0,25));let d=se(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${d}`,p=await C.get(u);if(!p.ok)throw new L(p.status,_(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof L&&c.status===400)break;l<N&&await ae(oe)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:r}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getWalletApprovals(e){let{address:t,chain:r,limit:o,cursor:s}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=ce(r),i="Unknown error";for(let l=1;l<=N;l++)try{let c={chain:a};o!=null&&(c.limit=o),s&&(c.cursor=s);let d=se(c),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${d}`,p=await C.get(u);if(!p.ok)throw new L(p.status,_(p));let m=p.data;return{success:!0,data:m?.data??m}}catch(c){if(i=c instanceof Error?c.message:"Unknown error",c instanceof L&&c.status===400)break;l<N&&await ae(oe)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:Gh(u)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getWalletDefiPositions(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Address is required"};if(!R(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:Kh(u)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:r,chain:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!r)return{success:!1,error:"Protocol identifier is required"};if(!R(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let s=ce(o),a="Unknown error";for(let i=1;i<=N;i++)try{let l=se({chains:s}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(r)}/positions?${l}`,d=await C.get(c);if(!d.ok)throw new L(d.status,_(d));let m=d.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(h=>({label:h.label,address:h.address,balance_usd:h.balanceUsd??0,total_unclaimed_usd_value:h.unclaimedUsd??0,position_details:h.details,tokens:h.tokens.map(g=>({token_type:g.tokenType,address:g.address,contract_address:g.address,name:g.name??"",symbol:g.symbol??"",decimals:g.decimals??18,logo:g.logo,balance:g.balance??"0",balance_formatted:g.balanceFormatted??"0",usd_price:g.usdPrice,usd_value:g.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await ae(oe)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!R(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getTokenScore(e){let{address:t,chain:r}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!R(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let o=ce(r),s="Unknown error";for(let a=1;a<=N;a++)try{let i=se({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data;return{success:!0,data:d?.data??d}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<N&&await ae(oe)}return{success:!1,error:s}}async getTrendingTokens(e){let t=e?.chain,r=e?.limit,o="Unknown error";for(let s=1;s<=N;s++)try{let a={};t&&(a.chain=ce(t)),r!=null&&(a.limit=r);let i=se(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await C.get(l);if(!c.ok)throw new L(c.status,_(c));let d=c.data,u=d?.data??d;return{success:!0,data:Kl(u)}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof L&&a.status===400)break;s<N&&await ae(oe)}return{success:!1,error:o}}async getTopGainers(e){let{chain:t,timeFrame:r,minMarketCap:o,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=ce(t)),r&&(l.time_frame=r),o!=null&&(l.min_market_cap=o),s!=null&&(l.security_score=s);let c=se(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,u=await C.get(d);if(!u.ok)throw new L(u.status,_(u));let p=u.data,m=p?.data??p;return{success:!0,data:Kl(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await ae(oe)}return{success:!1,error:a}}async getTopLosers(e){let{chain:t,timeFrame:r,minMarketCap:o,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=N;i++)try{let l={};t&&(l.chain=ce(t)),r&&(l.time_frame=r),o!=null&&(l.min_market_cap=o),s!=null&&(l.security_score=s);let c=se(l),d=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,u=await C.get(d);if(!u.ok)throw new L(u.status,_(u));let p=u.data,m=p?.data??p;return{success:!0,data:Kl(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<N&&await ae(oe)}return{success:!1,error:a}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}async applyYieldValues(e,t,r){if(e.length===0||r.size===0)return;let o=[],s=new Map;if(e.forEach((a,i)=>{let l=r.get(a.token_address.toLowerCase());if(!l?.yieldProtocol||!/^\d+$/.test(a.balance??""))return;let c=BigInt(a.balance);if(c<=0n)return;let d=String(i);s.set(d,a),o.push({key:d,address:a.token_address,rawBalance:c,decimals:a.decimals,priceUSD:a.usd_price??0,yieldProtocol:l.yieldProtocol,yieldAsset:l.yieldAsset,chain:t})}),o.length!==0)try{let a=await za(t,o);for(let[i,l]of a){let c=s.get(i);c&&(!Number.isFinite(l.valueUSD)||!Number.isFinite(l.pricePerTokenUSD)||l.pricePerTokenUSD<=0||(c.usd_value=l.valueUSD,c.usd_price=l.pricePerTokenUSD))}}catch{}}};var $r=class extends A{name="get-token-info";description='Get information about a specific cryptocurrency token: price, metadata, 24h change, market data, and user holdings. Use this when the user asks about: token price, token info, "what is X token", "tell me about X", "how much is X worth", or any token-specific question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad';category="blockchain-data";parameters=[{name:"keyword",type:"string",description:'Token symbol, name, or contract address (e.g. "USDC", "Pepe", "ETH", "0x1234\u2026"). If a 0x address is provided, performs a precise contract lookup. Otherwise searches by name/symbol.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prompt",type:"string",description:`A rich, multi-angle research prompt sent to Gemini with Google Search grounding (real-time web access). The prompt must be self-contained \u2014 Gemini does NOT see the user's original message, only this prompt. ALWAYS include: the token symbol/name, the chain, and an instruction to use web search for up-to-date info. When the user asks an open/broad question (e.g. "show me X", "tell me about X", "what is X"), expand the prompt to cover ALL of these angles in one request: (1) what the token/project is and its core utility, (2) current USD price, 24h change, market cap, FDV, 24h volume, (3) recent news, announcements, or notable events in the last 7-30 days \u2014 each with an approximate DATE and the source/outlet, (4) WHY the price has been moving \u2014 name the concrete catalyst(s) behind the latest pump or dump (listing, unlock, partnership, hack, macro move, whale flows, narrative rotation) rather than just stating the % change, (5) on-chain activity signals (holders, liquidity, unusual flows), (6) team/protocol updates or roadmap items, (7) key risks, red flags, or controversies, (8) overall sentiment plus a brief, clearly-hedged short/medium-term outlook (bullish / bearish / neutral and the key levels or events to watch). When the user asks a narrow question (e.g. "price of X"), still include 2-3 supporting angles for context. When the user explicitly asks WHY a token moved or about news/market direction, lead with the catalyst and recent news angles. Aim for 4-8 sentences. Be specific to the token and cite dates. Do not use generic filler, and do not fabricate news \u2014 if no clear catalyst is found, say the move is not tied to a specific identifiable event. Example for "show me JPYT": "Research the JPYT token on Ethereum using up-to-date web sources. Cover: what JPYT is and who issues it; current USD price, 24h change, market cap, FDV, and 24h volume; recent news or announcements in the last 30 days with dates and sources; the concrete reason behind any recent price move; on-chain signals such as holder count, liquidity, and unusual volume patterns; team or protocol updates; key risks or red flags; and overall sentiment with a brief, hedged short-term outlook."`,required:!0}];service;llm;constructor(e){super(),this.service=new O(e),this.llm=new ke(e?.llm??{})}async run(e,t){let r=e.keyword||"",o=e.prompt||"",s=t?.walletAddress||void 0;if(!r)return{error:"Missing required parameter: keyword"};let a;try{a=Pe(e.chain,t)}catch(i){if(i instanceof cn)return await this.researchTokenChainAgnostic(r,o,s);throw i}return await this.searchToken(r,a,o,s)}async researchTokenChainAgnostic(e,t,r){let o=[r?`User's connected wallet address: ${r}`:null,"The user's connected chain is not one this app supports on-chain, so answer using web research only \u2014 do not assume a specific chain; identify the token across whichever chain(s) it actually exists on."].filter(Boolean).join(`
26
26
  `),s=t?await this.askGeminiWithSearch(t,o):null;return{_instructions:'The token info comes from web research only (the user is on a chain this app does not support on-chain). Present a clear summary of the token using the research: what it is, current USD price and 24h change, market data, recent news and the catalyst behind any price move, and a brief, clearly-hedged sense of market direction (no financial advice). Do NOT add a labelled "AI Analysis" heading and do NOT mention that the analysis came from AI \u2014 write it as a normal token summary. If a field is unknown, omit it. Do NOT mention chains, tools, or that anything is unsupported; just answer the question.',keyword:e,token:null,userHoldsToken:!1,research:s}}async searchToken(e,t,r,o){let s=[o?`User's connected wallet address: ${o}`:null,t?`Current chain (hex chain ID): ${t}, only consider tokens on this chain`:null,"Use this context to personalize your answer where relevant (e.g. whether the user holds the token, chain-specific data)."].filter(Boolean).join(`
27
27
  `),[a,i,l]=await Promise.all([this.service.searchTokensByKey({key:e,chain:t}),o?this.findTokenInWallet(o,t,e):Promise.resolve(null),r?this.askGeminiWithSearch(r,s):Promise.resolve(null)]),c=a.success&&a.data?Array.isArray(a.data)?a.data:[]:[],d=e.toLowerCase(),u=g=>g.symbol?.toLowerCase()===d||g.token_address?.toLowerCase()===d,p=[...c].sort((g,b)=>(u(g)?0:1)-(u(b)?0:1)),m=null,f=p[0];if(f?.token_address){let g=await this.service.getTokenMetadata({address:f.token_address,chain:t});g.success&&g.data&&(m=g.data)}return!m&&f&&(m={...f}),{_instructions:'Present the token info in a clear summary. Include: token name & symbol, contract address (shortened), current USD price, 24h price change % (prefix "+" for positive, "-" for negative), market cap, fully diluted valuation, 24h trading volume, liquidity, and holder count (if available). If the user holds this token, prominently show their balance and USD value. If research is present, weave its substance naturally into your answer \u2014 fold the relevant points into the description, context, and any notable news or risks. When the research explains WHY the price moved, surface that catalyst clearly (what happened, roughly when), summarize the most relevant recent news, and close with a brief, clearly-hedged sense of market direction (do not give financial advice or price predictions). Do NOT add a labelled "AI Analysis" section or any similar heading, and do NOT mention that the analysis came from AI; just write it as part of the token summary. Format numbers in a human-readable way (e.g. $1.23, +5.67%, $12.5M). If a field is null, omit it.',chain:t,userHoldsToken:!!i,walletBalance:i,token:m,...c.length>1?{searchResults:p.slice(0,10)}:{},research:l}}async askGeminiWithSearch(e,t){let r=Date.now();try{return(await this.llm.chat([...t?[{role:"system",content:t,timestamp:r}]:[],{role:"user",content:e,timestamp:r}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}async findTokenInWallet(e,t,r){if(!r)return null;let o=await this.service.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1});if(!o.success||!o.data?.result)return null;let s=r.toLowerCase(),a=o.data.result.find(i=>i.token_address.toLowerCase()===s||i.symbol?.toLowerCase()===s||i.name?.toLowerCase().includes(s));return a||null}};var Hr=class extends A{name="get-token-holders";description='Get holder statistics and analytics for an ERC-20 token. Returns: total holder count, holder count changes over time (5min/1h/6h/24h/3d/7d/30d), how holders acquired the token (swap/transfer/airdrop), supply concentration (% held by top 10/25/50/100/250/500 holders), and holder size distribution (whales, sharks, dolphins, fish, octopus, crabs, shrimps). Use tokenSymbol (e.g. "USDC") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How many holders does USDC have?" (tokenSymbol=USDC), "Is USDC gaining or losing holders?" (tokenSymbol=USDC \u2192 holderChange), "How many new holders did ETH get in the last 7 days?" (tokenSymbol=WETH), "How concentrated is USDC ownership?" (tokenSymbol=USDC \u2192 holderSupply), "What % of supply do the top 10 holders control?" (tokenSymbol=USDC), "How many whales hold USDT?" (tokenSymbol=USDT \u2192 holderDistribution), "Did most holders buy via swap or transfer?" (tokenSymbol=USDC \u2192 holdersByAcquisition). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=Pe(e.chain,t),o=t?.walletAddress||void 0,s=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!s&&!a)return{error:'Provide either tokenSymbol (e.g. "USDC") or contractAddress (0x\u2026).'};let i,l;if(s){let u=await this.resolveContractAddress(s,r,o);if(!u)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${r?T(r):"the selected chain"}. Try passing contractAddress directly.`};a=u.address,i=u.symbol,l=u.name}let c=await this.service.getTokenHolders({address:a,chain:r});if(!c.success)return{error:c.error||"Failed to fetch token holder stats"};let d=c.data;return{token:{symbol:i??s??null,name:l??null,contractAddress:a,chain:r||"default"},totalHolders:d.totalHolders,holdersByAcquisition:d.holdersByAcquisition,holderChange:d.holderChange,holderSupply:d.holderSupply,holderDistribution:d.holderDistribution}}async resolveContractAddress(e,t,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Vr=class extends A{name="get-token-analytics";description=`Get detailed trading analytics for a single ERC-20 token, broken down across 5min / 1h / 6h / 24h windows. Returns: buy volume, sell volume, unique buyers, unique sellers, buy/sell transaction counts, unique wallets, price % change, current USD price, total liquidity and fully-diluted valuation (FDV). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "How is PEPE trading today?" (tokenSymbol=PEPE), "24h buy vs sell volume for USDC?" (tokenSymbol=USDC \u2192 totalBuyVolume vs totalSellVolume), "Is buying or selling pressure stronger for this token?", "How many unique wallets touched this token in the last hour?" (\u2192 uniqueWallets.1h), "What's the FDV and liquidity of X?" (\u2192 totalFullyDilutedValuation, totalLiquidity), "Price change over 6h?" (\u2192 pricePercentChange.6h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=Pe(e.chain,t),o=t?.walletAddress||void 0,s=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!s&&!a)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(s){let u=await this.resolveContractAddress(s,r,o);if(!u)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${r?T(r):"the selected chain"}. Try passing contractAddress directly.`};a=u.address,i=u.symbol,l=u.name}let c=await this.service.getTokenAnalytics({address:a,chain:r});if(!c.success)return{error:c.error||"Failed to fetch token analytics"};let d=c.data??{};return{token:{symbol:i??s??null,name:l??null,contractAddress:a,chain:r||"default"},usdPrice:d.usdPrice??null,totalLiquidity:d.totalLiquidity??null,totalFullyDilutedValuation:d.totalFullyDilutedValuation??null,totalBuyVolume:d.totalBuyVolume??null,totalSellVolume:d.totalSellVolume??null,totalBuyers:d.totalBuyers??null,totalSellers:d.totalSellers??null,totalBuys:d.totalBuys??null,totalSells:d.totalSells??null,uniqueWallets:d.uniqueWallets??null,pricePercentChange:d.pricePercentChange??null}}async resolveContractAddress(e,t,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Wr=class extends A{name="get-token-score";description=`Get a composite 0\u2013100 health/safety score for a single ERC-20 token, plus the metrics behind it. Returns: overall score, last-updated timestamp, current USD price, paired liquidity, multi-timeframe volume buckets (10m / 30m / 1h / 4h / 12h / 1d / 7d / 30d), same buckets for transaction counts, and supply info (total supply + % held by top 10 holders). Use tokenSymbol (e.g. "PEPE") to look up by name \u2014 the tool auto-resolves the contract address. Use contractAddress when you already have the exact 0x address. Use this tool for questions like: "Is PEPE a safe token?" (tokenSymbol=PEPE \u2192 score), "What's the health/score of USDC?", "How concentrated is X's supply among whales?" (\u2192 metrics.supply.top10Percent), "How much volume did this token do over the last 7 days?" (\u2192 metrics.volumeUsd.7d), "Transaction count for this token in the last hour?" (\u2192 metrics.transactions.1h). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.`;category="blockchain-data";parameters=[{name:"tokenSymbol",type:"string",description:`Token symbol (e.g. "PEPE", "USDC", "WETH"). The tool resolves the contract address automatically: first checks the connected wallet's balances, then searches by symbol. Takes precedence over contractAddress when both are given.`,required:!1},{name:"contractAddress",type:"string",description:"ERC-20 token contract address (0x\u2026). Use when the exact address is already known. Ignored if tokenSymbol is provided.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=Pe(e.chain,t),o=t?.walletAddress||void 0,s=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,a=typeof e.contractAddress=="string"&&e.contractAddress?e.contractAddress.trim():void 0;if(!s&&!a)return{error:'Provide either tokenSymbol (e.g. "PEPE") or contractAddress (0x\u2026).'};let i,l;if(s){let p=await this.resolveContractAddress(s,r,o);if(!p)return{error:`Cannot resolve token symbol "${s}" to a contract address on ${r?T(r):"the selected chain"}. Try passing contractAddress directly.`};a=p.address,i=p.symbol,l=p.name}let c=await this.service.getTokenScore({address:a,chain:r});if(!c.success)return{error:c.error||"Failed to fetch token score"};let d=c.data??{},u=d.metrics??{};return{token:{symbol:i??s??null,name:l??null,contractAddress:a,chain:r||"default"},score:d.score??null,updatedAt:d.updatedAt??null,metrics:{usdPrice:u.usdPrice??null,liquidityUsd:u.liquidityUsd??null,volumeUsd:u.volumeUsd??null,transactions:u.transactions??null,supply:u.supply??null}}}async resolveContractAddress(e,t,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};var Yr=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 Ae({baseUrl:e?.pantographUrl})}async run(e,t){let r=Ma(e.chain,t),o=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.floor(e.limit):void 0,s=await this.service.getTrendingTokens({chain:r,limit:o});if(!s.success)return{error:s.error||"Failed to fetch trending tokens"};let a=s.data??[];return{_instructions:`Start with a one-line header like "Here are some of the top trending tokens on <chain name> right now:". Then present the tokens as a numbered list. For EACH token render exactly these lines (omit any line whose value is null):
28
28
  <rank>. <name> (<symbol>)
@@ -36,7 +36,7 @@ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-ce
36
36
  - Market Cap: <marketCap>
37
37
  - Price Change: <pricePercentChange.24h> (prefix "+" for positive, "-" for negative)
38
38
  - 24h Volume: <totalVolume.24h>
39
- Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:r?T(r):"all",timeFrame:s??null,count:c.length,tokens:c}}};var Kr=class extends A{name="get-wallet-token-balances";description='Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new O(e)}truncateUsd(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[r,o=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${r}.${(o+"00").slice(0,2)}`}async run(e,t){let r=le(e.address,t),o=K(e.chain,t);if(o){let i=await this.service.getWalletTokenBalances({address:r,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1});return i.success?this.renderBalances(r,o,i.data?.result||[]):{error:i.error||"Failed to fetch token balances"}}let s=qe(),a=await Promise.all(s.map(async i=>{let l=await this.service.getWalletTokenBalances({address:r,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(r,a)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",r=e.balance_formatted??"0",o=e.symbol||"",s=typeof e.usd_value=="number"?`$${this.truncateUsd(e.usd_value)}`:"$-";return`- ${t}: ${r} ${o} (${s})`.replace(/\s+/g," ").trim()}renderBalances(e,t,r){let o=r.reduce((s,a)=>s+(a.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:e,chain:t,totalUsdValue:`$${this.truncateUsd(o)}`,tokens:r.map(s=>this.toTokenLine(s))}}renderBalancesByChain(e,t){let r=t.map(s=>{let a=s.tokens.reduce((l,c)=>l+(c.usd_value||0),0),i=s.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:T(s.chain),total:a,tokens:i}}).filter(s=>s.tokens.length>0).sort((s,a)=>a.total-s.total),o=r.reduce((s,a)=>s+a.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:e,chain:"all",totalUsdValue:`$${this.truncateUsd(o)}`,chains:r.map(s=>({chain:s.chain,totalUsdValue:`$${this.truncateUsd(s.total)}`,tokens:s.tokens.map(a=>this.toTokenLine(a))}))}}};var jr=class extends A{name="get-wallet-history";description=`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=Pe(e.chain,t),s=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,a=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,i=typeof e.fromBlock=="number"?e.fromBlock:typeof e.fromBlock=="string"&&e.fromBlock?Number(e.fromBlock):void 0,l=typeof e.toBlock=="number"?e.toBlock:typeof e.toBlock=="string"&&e.toBlock?Number(e.toBlock):void 0,c=Number.isFinite(i)?i:void 0,d=Number.isFinite(l)?l:void 0,u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",f=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,h=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,g=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,b=Number.isFinite(g)&&g>0?g:10,y=await this.service.getWalletHistory({address:r,chain:o,limit:b,fromDate:s,toDate:a,fromBlock:c,toBlock:d,cursor:u,order:m,includeInternalTransactions:f,nftMetadata:h});if(!y.success)return{error:y.error||"Failed to fetch wallet history"};let k=(y.data?.result||[]).map(v=>{let S=Iu(o,v.hash);return S?{...v,explorerUrl:S}:v});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:r,chain:o||"default",pagination:{cursor:y.data?.cursor??null,hasMore:!!y.data?.cursor},transactionCount:k.length,transactions:k}}};function jh(n){if(n.value_decimal)return n.value_decimal;let e=parseInt(n.token_decimals??"18",10);if(isNaN(e)||e===0)return n.value;try{let t=BigInt(n.value),r=BigInt(10)**BigInt(e),o=t/r,a=(t%r).toString().padStart(e,"0").replace(/0+$/,"");return a?`${o}.${a}`:`${o}`}catch{return n.value}}var zr=class extends A{name="get-wallet-token-transfers";description=`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=Pe(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),d=this.parseBlock(e.toBlock),u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",h=f==="send"?"send":f==="receive"?"receive":"all",g=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,b=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(E=>typeof E=="string"&&!!E).map(E=>E.trim()):void 0,y,w;if(g){let E=await this.resolveContractAddressBySymbol(g,r,o);E&&(b=[E.address],y=E.symbol,w=E.name)}let k=await this.service.getWalletTokenTransfers({address:r,chain:o,contractAddresses:b,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:d,cursor:u,order:m});if(!k.success)return{error:k.error||"Failed to fetch token transfers"};let v=r.toLowerCase(),P=(k.data?.result||[]).map(E=>{let we=E.from_address.toLowerCase()===v,V=we?"send":"receive",z=we?E.to_address:E.from_address,fe=we?E.to_address_label??void 0:E.from_address_label??void 0,Ne=we?E.to_address_entity??void 0:E.from_address_entity??void 0;return{...E,direction:V,amount_formatted:jh(E),counterparty:z,counterparty_label:fe,counterparty_entity:Ne}}),x=h==="all"?P:P.filter(E=>E.direction===h);if(g&&!b){let E=g.toLowerCase();x=x.filter(we=>(we.token_symbol??"").toLowerCase()===E)}let I=this.buildCounterparties(x);return{walletAddress:r,chain:o||"default",resolvedToken:y?{symbol:y,name:w,contractAddress:b?.[0]}:null,filters:{tokenSymbol:g||null,contractAddresses:b||null,direction:h,limit:a,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:d??null},pagination:{cursor:k.data?.cursor??null,pageSize:k.data?.page_size??a,page:k.data?.page??null,hasMore:!!k.data?.cursor},transferCount:x.length,transfers:x,counterparties:I}}async resolveContractAddressBySymbol(e,t,r){let o=e.toLowerCase(),s=await this.service.getWalletTokenBalances({address:t,chain:r});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}let a=await this.service.searchTokensByKey({key:e,chain:r});if(a.success&&a.data?.length){let l=a.data.find(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}buildCounterparties(e){let t=new Map,r=new Map;for(let s of e){let a=s.direction==="send"?t:r,i=s.counterparty.toLowerCase(),l=parseFloat(s.amount_formatted)||0,c=a.get(i);c?(c.total+=l,c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):a.set(i,{label:s.counterparty_label,entity:s.counterparty_entity,total:l,count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,total_amount:i.total.toFixed(6).replace(/\.?0+$/,""),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:o(t),received:o(r)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Xr=class extends A{name="get-wallet-nft-transfers";description=`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=Pe(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),d=this.parseBlock(e.toBlock),u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.includePrices=="boolean"?e.includePrices:void 0,h=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",g=h==="send"?"send":h==="receive"?"receive":"all",b=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(x=>typeof x=="string"&&!!x).map(x=>x.trim()):void 0,y=await this.service.getWalletNftTransfers({address:r,chain:o,contractAddresses:b,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:d,cursor:u,order:m,includePrices:f});if(!y.success)return{error:y.error||"Failed to fetch NFT transfers"};let w=r.toLowerCase(),v=(y.data?.result||[]).map(x=>{let I=x.from_address.toLowerCase()===w,E=I?"send":"receive",we=I?x.to_address:x.from_address,V=I?x.to_address_label??void 0:x.from_address_label??void 0,z=I?x.to_address_entity??void 0:x.from_address_entity??void 0;return{...x,direction:E,counterparty:we,counterparty_label:V,counterparty_entity:z}}),S=g==="all"?v:v.filter(x=>x.direction===g),P=this.buildCounterparties(S);return{walletAddress:r,chain:o||"default",filters:{contractAddresses:b||null,direction:g,limit:a,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:d??null,includePrices:f??null},pagination:{cursor:y.data?.cursor??null,pageSize:y.data?.page_size??a,page:y.data?.page??null,hasMore:!!y.data?.cursor},transferCount:S.length,transfers:S,counterparties:P}}buildCounterparties(e){let t=new Map,r=new Map;for(let s of e){let a=s.direction==="send"?t:r,i=s.counterparty.toLowerCase(),l=s.token_name??s.token_address,c=a.get(i);c?(c.tokenIds.add(s.token_id),c.collections.add(l),c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):a.set(i,{label:s.counterparty_label,entity:s.counterparty_entity,tokenIds:new Set([s.token_id]),collections:new Set([l]),count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,token_ids:Array.from(i.tokenIds),collections:Array.from(i.collections),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:o(t),received:o(r)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var zh=["all","7","30","60","90"],Qr=class extends A{name="get-wallet-pnl-summary";description=`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=K(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=zh.includes(s)?s:void 0;if(o){let h=await this.service.getWalletPnlSummary({address:r,chain:o,days:a});return h.success?{walletAddress:r,chain:o,days:a??"all",summary:this.mapSummary(h.data)}:{error:h.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(qe().map(async h=>{let g=await this.service.getWalletPnlSummary({address:r,chain:h,days:a});return{chain:h,data:g.success?g.data:void 0}}))).flatMap(h=>h.data&&h.data.total_count_of_trades>0?[{chain:h.chain,data:h.data}]:[]),c=l.map(h=>({chain:T(h.chain),summary:this.mapSummary(h.data)})),d=l.reduce((h,g)=>h+Number(g.data.total_realized_profit_usd||0),0),u=l.reduce((h,g)=>h+Number(g.data.total_bought_volume_usd||0),0),p=l.reduce((h,g)=>h+Number(g.data.total_sold_volume_usd||0),0),m=l.reduce((h,g)=>h+Number(g.data.total_trade_volume||0),0),f={totalCountOfTrades:l.reduce((h,g)=>h+g.data.total_count_of_trades,0),totalTradeVolume:m,totalRealizedProfitUsd:d,totalRealizedProfitPercentage:u>0?d/u*100:0,totalBuys:l.reduce((h,g)=>h+g.data.total_buys,0),totalSells:l.reduce((h,g)=>h+g.data.total_sells,0),totalBoughtVolumeUsd:u,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:r,chain:"all",days:a??"all",summary:f,chains:c}}mapSummary(e){return{totalCountOfTrades:e.total_count_of_trades,totalTradeVolume:e.total_trade_volume,totalRealizedProfitUsd:e.total_realized_profit_usd,totalRealizedProfitPercentage:e.total_realized_profit_percentage,totalBuys:e.total_buys,totalSells:e.total_sells,totalBoughtVolumeUsd:e.total_bought_volume_usd,totalSoldVolumeUsd:e.total_sold_volume_usd}}};var Xh=["all","7","30","60","90"],Xa=25,Jr=class extends A{name="get-wallet-pnl";description=`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${Xa}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${Xa}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${Xa}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=K(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=Xh.includes(s)?s:void 0,i=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[],l=Array.isArray(e.tokenAddresses)?e.tokenAddresses.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[];if(o){let u=await this.fetchChainPnl(r,o,a,i,l);return u.ok?{walletAddress:r,chain:o,days:a??"all",filters:{tokenAddresses:u.tokenAddresses??null,resolvedSymbols:u.resolvedFromSymbols.length>0?u.resolvedFromSymbols:null,unresolvedSymbols:u.unresolvedSymbols.length>0?u.unresolvedSymbols:null},tokenCount:u.tokens.length,tokens:u.tokens}:{error:u.error||"Failed to fetch wallet PnL"}}let d=(await Promise.all(qe().map(async u=>({chain:u,res:await this.fetchChainPnl(r,u,a,i,l)})))).filter(u=>u.res.ok&&u.res.tokens.length>0).map(u=>({chain:T(u.chain),tokenCount:u.res.tokens.length,tokens:u.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:r,chain:"all",days:a??"all",filters:{requestedSymbols:i.length>0?i:null,requestedAddresses:l.length>0?l:null},tokenCount:d.reduce((u,p)=>u+p.tokenCount,0),chains:d}}async fetchChainPnl(e,t,r,o,s){let a=[],i=[];o.length>0&&(await Promise.all(o.map(p=>this.resolveContractAddress(p,t,e)))).forEach((p,m)=>{p?a.push({symbol:o[m],address:p.address}):i.push(o[m])});let l=Qh([...a.map(u=>u.address),...s]).slice(0,Xa),c=l.length>0?l:void 0,d=await this.service.getWalletPnl({address:e,chain:t,days:r,tokenAddresses:c});return{ok:d.success,error:d.error,tokens:d.data?.result??[],tokenAddresses:c,resolvedFromSymbols:a,unresolvedSymbols:i}}async resolveContractAddress(e,t,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};function Qh(n){let e=new Set,t=[];for(let r of n){let o=r.toLowerCase();e.has(o)||(e.add(o),t.push(r))}return t}var Jh=BigInt(2)**BigInt(255),Zr=class extends A{name="get-wallet-approvals";description=`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=Pe(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):100,i=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,l=await this.service.getWalletApprovals({address:r,chain:o,limit:a,cursor:i});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,u=(c.result||[]).map(h=>Zh(h)),p=0,m=0,f=[];for(let h of u){h.isUnlimited&&(m+=1);let g=parseFloat(h.token.usdAtRisk??"");Number.isFinite(g)&&(p+=g);let b=h.token.possibleSpam||h.token.verifiedContract===!1,y=!h.spender.label&&!h.spender.entity;(b||h.isUnlimited&&y)&&f.push(h)}return{walletAddress:r,chain:o||"default",filters:{limit:a,cursor:i??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??a,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:u.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:f.length},approvals:u,riskyApprovals:f}}};function Zh(n){let e=ef(n.value);return{blockNumber:n.block_number,blockTimestamp:n.block_timestamp??null,transactionHash:n.transaction_hash??null,value:n.value,valueFormatted:n.value_formatted??null,isUnlimited:e,token:{address:n.token.address,addressLabel:n.token.address_label??null,name:n.token.name??null,symbol:n.token.symbol??null,logo:n.token.logo??null,possibleSpam:!!n.token.possible_spam,verifiedContract:n.token.verified_contract??null,currentBalance:n.token.current_balance??null,currentBalanceFormatted:n.token.current_balance_formatted??null,usdPrice:n.token.usd_price??null,usdAtRisk:n.token.usd_at_risk??null},spender:{address:n.spender.address,label:n.spender.address_label??null,entity:n.spender.entity??null,entityLogo:n.spender.entity_logo??null}}}function ef(n){if(!n)return!1;try{return BigInt(n)>=Jh}catch{return!1}}var eo=class extends A{name="get-wallet-defi-positions";description=`The BROAD, cross-protocol inventory of every DeFi position a wallet holds \u2014 liquidity provision, staking, borrowing AND supply/lending alike \u2014 with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Any APY here is the LIVE SPOT rate. Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "What is my health factor?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited funds \u2014 "what am I earning", "my supply APY", "my savings/deposits", "my Aave supply" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Use this tool for supply positions only as part of a full portfolio sweep, or for assets it does not cover (it handles USDC only). Never report both tools' APY for the same position. Also not for: positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=K(e.chain,t);if(o){let i=await this.service.getWalletDefiPositions({address:r,chain:o});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=i.data||[];return{walletAddress:r,chain:o,positionCount:l.length,positions:l.map(zu)}}let a=(await Promise.all(qe().map(async i=>{let l=await this.service.getWalletDefiPositions({address:r,chain:i});return{chain:i,rows:l.success?l.data||[]:[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:T(i.chain),positionCount:i.rows.length,positions:i.rows.map(zu)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:r,chain:"all",positionCount:a.reduce((i,l)=>i+l.positionCount,0),chains:a}}};function zu(n){return{protocolName:n.protocol_name,protocolId:n.protocol_id,protocolUrl:n.protocol_url,protocolLogo:n.protocol_logo,accountHealthFactor:n.account_data?.health_factor??null,position:tf(n.position)}}function tf(n){return{label:n.label,address:n.address,balanceUsd:n.balance_usd,totalUnclaimedUsdValue:n.total_unclaimed_usd_value,tokens:(n.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:n.position_details??null}}var to=class extends A{name="get-wallet-defi-protocol-positions";description=`Get every position a wallet holds inside ONE specific DeFi protocol \u2014 liquidity provision, staking, borrowing and supply alike \u2014 with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Any APY here is the LIVE SPOT rate. Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "show my Lido staking", "my Curve pools", "Pendle positions", "how much did I borrow on Aave", "what do I have on Aave v3". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited USDC \u2014 "my Aave v3 supply", "what am I earning on Spark", "my Compound deposit" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Come back here for that protocol's borrow / LP / staking side, or for supplied assets other than USDC. Never report both tools' APY for the same position. Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-positions to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=e.protocol?.trim();if(!r)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let o=le(e.address,t),s=K(e.chain,t);if(s){let l=await this.service.getWalletDefiProtocolPositions({address:o,protocol:r,chain:s});return l.success?l.data?{walletAddress:o,chain:s,...this.protocolFields(l.data)}:{error:"No data returned for this protocol"}:{error:l.error||"Failed to fetch wallet DeFi protocol positions"}}let i=(await Promise.all(qe().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:r,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:T(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${r} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:o,chain:"all",protocol:r,totalUsdValue:i.reduce((l,c)=>l+c.totalUsdValue,0),chains:i}}protocolFields(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,accountHealthFactor:e.account_data?.health_factor??null,positionCount:(e.positions||[]).length,positions:(e.positions||[]).map(nf)}}};function nf(n){return{label:n.label,address:n.address,balanceUsd:n.balance_usd,totalUnclaimedUsdValue:n.total_unclaimed_usd_value,tokens:(n.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:n.position_details??null}}function rf(n){try{return(Number(BigInt(n))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return n}}var no=class extends A{name="get-transaction-by-hash";description='Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.';category="blockchain-data";parameters=[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=e.transactionHash;if(!r)return{error:"Transaction hash is required."};let o=Pe(e.chain,t),s=await this.service.getTransactionByHash({transactionHash:r,chain:o});if(!s.success||!s.data)return{error:s.error||"Failed to fetch transaction"};let a=s.data,i=(a.logs??[]).filter(c=>!!c.decoded_event).map(c=>({contract:c.address,signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params})),l=a.logs.map(c=>({address:c.address,decodedEvent:c.decoded_event?{signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params}:null}));return{hash:a.hash,status:a.receipt_status==="1"?"success":a.receipt_status==="0"?"failed":"unknown",timestamp:a.block_timestamp,blockNumber:a.block_number,from:{address:a.from_address,label:a.from_address_label||null,entity:a.from_address_entity||null},to:a.to_address?{address:a.to_address,label:a.to_address_label||null,entity:a.to_address_entity||null}:null,valueEth:rf(a.value||"0"),fee:a.transaction_fee,gasUsed:a.receipt_gas_used,gasPriceGwei:a.gas_price?(Number(a.gas_price)/1e9).toFixed(4):null,decodedCall:a.decoded_call?{signature:a.decoded_call.signature,label:a.decoded_call.label,params:a.decoded_call.params}:null,decodedEvents:i,contractCreated:a.receipt_contract_address||null,logs:l}}};var Xu=new Map;function of(n){let e=Xu.get(n);if(e)return e;let t=rn({rpcUrl:n});return Xu.set(n,t),t}async function Qu(n,e,t=[]){let r=await of(n).rpc(e,t);if(r===void 0)throw new Error(`RPC ${e}: empty result`);return r}function Ju(n,e,t){return Qu(n,"eth_call",[{to:e,data:t},"latest"])}async function sf(n,e,t){let r=Mn(n);if(!r)return null;try{return await Ju(r,e,t)}catch{return null}}function U(n,e){globalThis.__LENDING_DEBUG__!==!1&&(e===void 0?console.log(`[LEND] ${n}`):console.log(`[LEND] ${n}`,JSON.stringify(e,af)))}function af(n,e){return typeof e=="bigint"?`${e}n`:e}var lf=6e4,jl=new Map;async function Os(n,e){let t=Ft(e),r=t?parseInt(t,16):NaN;if(!t||!Number.isFinite(r))return[];let o=`${n}|${t}`,s=jl.get(o);if(s&&Date.now()-s.at<lf)return s.markets;let a=cf(n,t,r),i=a.then(l=>l.markets);return jl.set(o,{at:Date.now(),markets:i}),a.then(l=>{l.answered||jl.delete(o)}),i}async function Qa(n,e){return(await Os(n,e)).length>0}async function cf(n,e,t){try{let r=`${n}/supply/v2?chainId=${t}&limit=100&page=1`;U("catalog: GET",r);let o=await C.get(r);if(!o.ok){let a=o.status>=400&&o.status<500;return U(a?"catalog: chain not served":"catalog: FAILED",{chain:e,status:o.status,message:_(o)}),{markets:[],answered:a}}let s=(o.data?.data?.items||[]).flatMap(a=>{let i=uf(a,e);return i?[i]:[]});return U("catalog: got markets",{chain:e,rawItems:o.data?.data?.items?.length??0,usable:s.length,tokens:s.map(a=>a.token)}),{markets:s,answered:!0}}catch(r){return U("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:e,message:r?.message}),{markets:[],answered:!1}}}function Zu(n,e){let t=e.trim().toLowerCase();if(!t)return[];if(R(t))return n.filter(o=>o.contract===t||o.token===t);let r=n.filter(o=>o.name.trim().toLowerCase()===t);return r.length>0?r:n.filter(o=>{let s=o.name.trim().toLowerCase(),a=o.protocol.trim().toLowerCase();return s.includes(t)||t.includes(s)||a.includes(t)||t.includes(a)})}function uf(n,e){if(n?.isDeleted===!0)return null;let t=typeof n?.contract=="string"?n.contract.toLowerCase():"";if(!R(t))return null;let r=typeof n?.token=="string"&&R(n.token)?n.token.toLowerCase():t,o=Number(n?.rating?.balanceScore),s=n?.type?.trim()||"unknown";return{chain:e,name:n?.name?.trim()||"USDC lending market",protocol:n?.protocolId?.name?.trim()||"Unknown",protocolLabel:Ke(s),protocolUrl:n?.protocolId?.domain?.trim()||null,type:s,contract:t,token:r,platformScore:Number.isFinite(o)?o:null}}function zl(){return qe()}async function Ja(n){let e=zl(),t=await Promise.all(e.map(r=>Qa(n,r)));return e.filter((r,o)=>t[o])}async function Za(n,e){let t=D(e);return t?Qa(n,t):!1}async function ed(n,e){let t=e.map(s=>D(s)).filter(s=>!!s),r=[...new Set(t)],o=await Promise.all(r.map(s=>Qa(n,s)));return r.filter((s,a)=>o[a])}function Gn(n){return Is(n)}var td=6;async function nd(n,e,t){let r=e.map(w=>R(w)?w.toLowerCase():null);if(r.every(w=>w===null))return U("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let o=Ga(n),s;try{U("discovery: probing 5 accessors per token",{chain:n,tokens:r,psm:o}),s=await Te(n,[...r.flatMap(w=>w?df(w):[]),...o?$u(o):[]])}catch(w){return U("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:n,message:w?.message}),e.map(()=>null)}let a=o?s.slice(s.length-Hu):[],i=B(a[0])?.toLowerCase()??null,l=B(a[1]),c=B(a[2]),d=i&&l&&c?{susds:i,usds:l,oracle:c}:null;o&&U("discovery: PSM3 lookup",{psm:o,susds:i,usds:l,oracle:c});let u=0,p=r.map(w=>{if(!w)return null;let k=s.slice(u,u+td);return u+=td,U("discovery: probe answers",{token:w,"POOL()":B(k[0]),"UNDERLYING_ASSET_ADDRESS()":B(k[1]),"baseToken()":B(k[2]),"asset()":B(k[3]),"vsr()":ee(k[4])?.toString()??null,"manager()":B(k[5])}),{token:w,slice:k}}),m=new Set;for(let w of p){if(!w)continue;let k=B(w.slice[0]);k&&B(w.slice[1])&&m.add(k.toLowerCase())}let f=await pf(n,[...m]);m.size>0&&U("discovery: Aave pool authentication",{claimed:[...m],genuine:[...f]});let h=new Map;for(let w of p){if(!w||B(w.slice[0])&&B(w.slice[1])||B(w.slice[2])||!B(w.slice[3]))continue;let v=B(w.slice[5]);v&&h.set(w.token,v.toLowerCase())}let g=await mf(n,h);h.size>0&&U("discovery: Maple manager authentication",{claimed:[...h.keys()],genuine:[...g]});let b=p.flatMap(w=>w?B(w.slice[0])&&B(w.slice[1])||B(w.slice[2])?[]:g.has(w.token)?[]:B(w.slice[3])?[w.token]:[]:[]),y=await hf(n,[...new Set(b)],t);return b.length>0&&U("discovery: Morpho vault lookup",{asked:[...new Set(b)],recognised:[...y.keys()]}),p.map(w=>{if(!w)return null;let{token:k,slice:v}=w,S={chain:n,protocolUrl:null,token:k,platformScore:null};if(d&&k===d.susds)return U("discovery: classified",{token:k,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:d.oracle}),{...S,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:Ke("spark-l2-susds"),protocolUrl:Gn("spark-l2-susds"),type:"spark-l2-susds",contract:d.oracle,assetAddress:d.usds};let P=B(v[0]);if(P&&B(v[1])){let x=f.has(P.toLowerCase());return U("discovery: classified",{token:k,as:x?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:P}),x?{...S,name:"Aave v3",protocol:"AAVE",protocolLabel:Ke("aave-v3"),protocolUrl:Gn("aave-v3"),type:"aave-v3",contract:P}:null}if(B(v[2]))return U("discovery: classified",{token:k,as:"compound-v3"}),{...S,name:"Compound v3",protocol:"COMPOUND",protocolLabel:Ke("compound-v3"),protocolUrl:Gn("compound-v3"),type:"compound-v3",contract:k};if(B(v[3])){if(g.has(k))return U("discovery: classified",{token:k,as:"maple (manager round trip verified)"}),{...S,name:"Maple",protocol:"MAPLE",protocolLabel:Ke("maple"),protocolUrl:Gn("maple"),type:"maple",contract:k};if(y.has(k)){U("discovery: classified",{token:k,as:"morpho-v2"});let E=y.get(k)||"Morpho V2";return{...S,name:E,protocol:"MORPHO",protocolLabel:Ke("morpho-v2"),protocolUrl:Gn("morpho-v2"),type:"morpho-v2",contract:k}}let I=ee(v[4])!==null;return U("discovery: classified",{token:k,as:I?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),I?{...S,name:"Spark",protocol:"SPARK",protocolLabel:Ke("spark-ethereum"),protocolUrl:Gn("spark-ethereum"),type:"spark-ethereum",contract:k}:{...S,name:"Spark",protocol:"SPARK",protocolLabel:Ke("spark"),protocolUrl:Gn("spark"),type:"spark",contract:k}}return U("discovery: classified",{token:k,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function df(n){return[{target:n,callData:M({abi:Br,functionName:"POOL"})},{target:n,callData:M({abi:Br,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:n,callData:M({abi:Mt,functionName:"baseToken"})},{target:n,callData:M({abi:wt,functionName:"asset"})},{target:n,callData:M({abi:qr,functionName:"vsr"})},{target:n,callData:M({abi:Hl,functionName:"manager"})}]}async function pf(n,e){if(e.length===0)return new Set;try{let t=await Te(n,e.map(r=>({target:r,callData:M({abi:Bl,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((r,o)=>B(t[o])!==null))}catch{return new Set}}async function mf(n,e){if(e.size===0)return new Set;let t=[...e.entries()];try{let r=await Te(n,t.map(([,o])=>({target:o,callData:M({abi:Vl,functionName:"pool"})})));return new Set(t.filter(([o],s)=>B(r[s])?.toLowerCase()===o.toLowerCase()).map(([o])=>o))}catch{return new Set}}async function hf(n,e,t){let r=parseInt(n,16);if(e.length===0||!Number.isFinite(r))return new Map;let o=await Promise.all(e.map(async s=>{try{let a=await C.post(t,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:s,c:r}}),i=a.ok?a.data?.data?.vaultV2ByAddress:null;return i?[s,i.name?.trim()||""]:null}catch{return null}}));return new Map(o.filter(s=>s!==null))}var ff=.01;function gf(n){return n.reduce((e,t)=>t.conditions===null?e+t.apyPercent:e,0)}function yf(n,e){if(typeof e!="string"||!e.trim())return;let t=e.trim(),r=ws();r[n]!==t&&Dn({...r,[n]:t})}var ro=class{constructor(e,t,r){this.coinPoolBaseUrl=e;this.endpoints=t;this.describer=r}coinPoolBaseUrl;endpoints;describer;async describeReceiptTokens(e,t,r){let o=Date.now();U("describeReceiptTokens: START",{chain:e,tokens:t,hasRpcUrl:!!r});let s=Ft(e);s&&yf(s,r);let a=s?Us(s):null,i=[...new Set(t.filter(R).map(p=>p.toLowerCase()))];if(U("describeReceiptTokens: chain resolved",{hex:s,hasChainInfo:!!a,wanted:i}),!s||!a||i.length===0)return U("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:s,hasChainInfo:!!a,wantedCount:i.length}),new Map;U("describeReceiptTokens: on-chain discovery for",i);let l=await nd(s,i,this.endpoints.morphoApiUrl),d=[...new Map(i.flatMap((p,m)=>{let f=l[m];return U("describeReceiptTokens: discovery result",{token:p,found:!!f,protocol:f?.protocol,type:f?.type,contract:f?.contract}),f?[[p,f]]:[]})).entries()];if(d.length===0)return U("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-o}),new Map;U("describeReceiptTokens: describing markets",{count:d.length,markets:d.map(([p,m])=>({token:p,type:m.type,contract:m.contract}))});let u=await this.describer.describe(s,a,d.map(([,p])=>p));return U("describeReceiptTokens: DONE",{ms:Date.now()-o,overviews:u.map(p=>({name:p.name,protocol:p.protocol,asset:p.asset?.symbol,assetDecimals:p.asset?.decimals,currentApyPercent:p.currentApyPercent,baseApyPercent:p.baseApyPercent,rewardApyPercent:p.rewardApyPercent,avgApyPercent:p.avgApyPercent,apyChangePercent:p.apyChangePercent,totalSuppliedUsdc:p.totalSuppliedUsdc,apyHistoryPoints:p.apyHistory?.length??0}))}),new Map(u.map((p,m)=>[d[m][0],p]))}async findMarketByReceiptToken(e,t,r){if(U("findMarketByReceiptToken: called",{chain:e,receiptToken:t,hasRpcUrl:!!r}),!R(t))return U("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:t}),null;let s=(await this.describeReceiptTokens(e,[t],r)).get(t.toLowerCase())??null;return U("findMarketByReceiptToken: returning",{found:!!s}),s}async getSupplyPositions(e){if(!R(e.address))return[];let t=await ed(this.coinPoolBaseUrl,e.chains);return(await Promise.all(t.map(o=>this.positionsForChain(o,e.address)))).flat().sort((o,s)=>s.suppliedUsdc-o.suppliedUsdc||(s.avgApyPercent??0)-(o.avgApyPercent??0))}async describeResolvedMarkets(e,t){let r=Ft(e),o=r?Us(r):null;return r&&o?this.describer.describe(r,o,t):[]}async positionsForChain(e,t){let r=Us(e),o=await Os(this.coinPoolBaseUrl,e);if(!r||o.length===0)return[];let s=await this.describer.readBalances(e,t,o);if(s.length===0)return[];let a=await this.describer.describe(e,r,s.map(l=>l.market)),i=await this.describer.convertToUnderlying(e,s,a.map(l=>l.asset));return a.flatMap((l,c)=>{let d=i[c];return d<ff?[]:[{...l,suppliedUsdc:d,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:d*(l.avgApyPercent+gf(l.rewards))/100}]})}};var Xl=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var oo=class{constructor(e){this.coinPoolBaseUrl=e}coinPoolBaseUrl;async listChains(){return Ja(this.coinPoolBaseUrl)}async isSupported(e){return Za(this.coinPoolBaseUrl,e)}async getMarkets(e){let t=D(e);return t?Os(this.coinPoolBaseUrl,t):[]}async findMarket(e,t){let r=await this.getMarkets(e);return Zu(r,t)}canSupply(e){return Xl.includes(e.type)}async readReceiptToken(e,t){let r=pn(t).balanceIsUnderlying;try{let o=await Te(e,[{target:t.token,callData:M({abi:q,functionName:"symbol"})},{target:t.token,callData:M({abi:q,functionName:"decimals"})}]);return{symbol:cr(o[0]),decimals:ur(o[1]),isUnderlying:r}}catch{return{symbol:null,decimals:null,isUnderlying:r}}}};var bf={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},wf={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",100:"proto_gnosis_v3",130:"proto_unichain_v3",137:"proto_polygon_v3",143:"proto_monad_v3",146:"proto_sonic_v3",196:"proto_xlayer_v3",324:"proto_zksync_v3",1088:"proto_metis_v3",1868:"proto_soneium_v3",4326:"proto_megaeth_v3",5e3:"proto_mantle_v3",8453:"proto_base_v3",9745:"proto_plasma_v3",42161:"proto_arbitrum_v3",42220:"proto_celo_v3",43114:"proto_avalanche_v3",57073:"proto_ink_v3",59144:"proto_linea_v3",534352:"proto_scroll_v3"},kf={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},vf={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function ei(n){let e=_f(n.chain);return(e===null?null:Tf(n,e))??Is(n.type)??Ef(n,e)}function Tf(n,e){switch(n.type){case"morpho-v2":{let t=bf[e];if(!t||!n.contract)return null;let r=`https://app.morpho.org/${t}/vault/${Ql(n.contract)}`,o=Sf(n.name);return o?`${r}/${o}`:r}case"aave-v3":{let t=wf[e],r=Af(n);return!t||!r?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${Ql(r)}&marketName=${t}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let t=kf[e],r=Cf(n);return!t||!r?null:`https://app.spark.fi/savings/${t}/${r}`}case"compound-v3":{let t=vf[e],r=xf(n);return!t||!r?null:`https://app.compound.finance/?market=${r}-${t}`}default:return null}}function Af(n){let e=n.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var Pf=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Sf(n){let e=n?.trim().toLowerCase()||"";return!e||Pf.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function xf(n){let e=n.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function Cf(n){let e=n.shareSymbol?.trim().toLowerCase()||"";if(/^[a-z0-9]{2,12}$/.test(e))return e;let t=`${n.name||""} ${n.token||""}`.toLowerCase();for(let o of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(t.includes(o))return o;if(n.type==="spark-ethereum")return Rf[n.contract?.trim().toLowerCase()||""]??null;let r=n.asset?.symbol?.trim().toLowerCase()||"";return!/^[a-z0-9]{2,11}$/.test(r)||r.startsWith("s")?null:`s${r}`}var Rf={"0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f":"speth","0x80128dbb9f07b93dde62a6daeadb69ed14a7d354":"sppyusd","0xe2e7a17dff93280dec073c995595155283e3c372":"spusdt","0x28b3a8fb53b741a8fd78c0fb9a6b2393d896a43d":"spusdc","0x45d91340b3b7b96985a72b5c678f7d9e8d664b62":"spusdt","0xc358c90d32375721cb3924320fdc2f8b694347ca":"spusdt","0xde770c84fe66e063336b31737cfe9790f18c4087":"spusdg"};function Ef(n,e){let t=n.protocolUrl?.trim();if(!t)return null;let r=/^https?:\/\//i.test(t)?t:`https://${t.replace(/^\/+/,"")}`;try{let o=new URL(r);return e!==null&&o.searchParams.set("chainId",String(e)),n.contract&&o.searchParams.set("contract",Ql(n.contract)),o.toString()}catch{return r}}function Ql(n){let e=n.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function _f(n){let e=n?.trim();if(!e)return null;let t=/^0x/i.test(e)?Number.parseInt(e,16):Number(e);return Number.isFinite(t)&&t>0?t:null}var Nf=new Set(["spark","spark-ethereum"]),Lf=8;function If(n,e,t){if(n.market.type!=="spark-l2-susds")return ee(e);let r=ee(e);return r===null||n.tokenDecimals===null?null:Wn(n.rawBalance,r,n.tokenDecimals,t)}var ti=class{constructor(e){this.endpoints=e}endpoints;apyLimiter=new Jl(Lf);pantograph=new Ae;async describe(e,t,r){if(r.length===0)return[];U("describe: START",{chain:e,count:r.length,types:r.map(l=>l.type)});let{assets:o,shareSymbols:s}=await this.resolveAssets(e,r);U("describe: assets resolved",o);let[a,i]=await Promise.all([this.readMarketState(e,r,o),Promise.all(r.map((l,c)=>this.apyLimiter.run(()=>this.fetchApy(l,t,o[c]))))]);return U("describe: on-chain state",a),U("describe: APY fetched",i.map((l,c)=>({type:r[c].type,rawSamples:l.samples.length,sourceCurrent:l.current}))),r.map((l,c)=>{let{totalSuppliedUsdc:d,liveApyFraction:u}=a[c],p=i[c].sizeOverride??d,m=Df(i[c].samples,u??i[c].current,i[c].rewards,i[c].avgOverride??null);return U("describe: summarised",{market:l.name,type:l.type,liveFrom:u!==null?"on-chain":i[c].current!==null?"api":"none",rawSamples:i[c].samples.length,historyPoints:m.history.length,currentApyPercent:m.currentApyPercent,avgApyPercent:m.avgApyPercent,apyChangePercent:m.apyChangePercent,totalSuppliedUsdc:p,asset:o[c]?.symbol}),{...l,protocolUrl:ei({...l,asset:o[c],shareSymbol:s[c]}),asset:o[c],totalSuppliedUsdc:p,avgApyPercent:m.avgApyPercent,currentApyPercent:m.currentApyPercent,baseApyPercent:m.baseApyPercent,rewardApyPercent:m.rewardApyPercent,rewards:m.rewards,apyChangePercent:m.apyChangePercent,apyHistory:m.history}})}async readBalances(e,t,r){let o=M({abi:q,functionName:"balanceOf",args:[t]}),s=M({abi:q,functionName:"decimals"}),a=r.flatMap(l=>[{target:l.token,callData:o},{target:l.token,callData:s}]),i=await Te(e,a);return r.flatMap((l,c)=>{let d=ee(i[c*2]);return d===null||d<=0n?[]:[{market:l,rawBalance:d,tokenDecimals:ur(i[c*2+1])}]})}async convertToUnderlying(e,t,r){let o=[],s=t.map(i=>{let l=pn(i.market).convertToAssetsCall(i.market,i.rawBalance);return l?(o.push(l),o.length-1):-1}),a=await Te(e,o);return t.map((i,l)=>{let c=r[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(s[l]<0)return tt(i.rawBalance,c);let d=If(i,a[s[l]],c);return d===null?tt(i.rawBalance,i.tokenDecimals??c):tt(d,c)})}async resolveAssets(e,t){let r={address:Yn,decimals:NaN,symbol:null,logo:null},o=[],s=t.map(p=>{let m=pn(p).underlyingCall(p);return m?(o.push(m),o.length-1):-1}),a;try{let p=o.length>0?await Te(e,o):[];a=s.map(m=>m<0?null:B(p[m]))}catch{a=t.map(()=>null)}a=a.map((p,m)=>p??t[m]?.assetAddress??null);let i=[...new Set(a.filter(p=>!!p).map(p=>p.toLowerCase()))],[l,c,d]=await Promise.all([this.readAssetMetadata(e,i),this.fetchAssetLogos(e,i),this.readShareSymbols(e,t)]);return{assets:a.map(p=>{if(!p)return r;let m=p.toLowerCase(),f=l.get(m),h=c.get(m)??null;return f?.decimals!==null&&f?.decimals!==void 0?{address:p,decimals:f.decimals,symbol:f.symbol??null,logo:h}:{address:p,decimals:NaN,symbol:null,logo:h}}),shareSymbols:d}}async readShareSymbols(e,t){let r=M({abi:q,functionName:"symbol"}),o=[],s=t.map(a=>!Nf.has(a.type)||!a.contract?-1:(o.push({target:a.contract,callData:r}),o.length-1));if(o.length===0)return t.map(()=>null);try{let a=await Te(e,o);return s.map(i=>i<0?null:cr(a[i]))}catch{return t.map(()=>null)}}async readAssetMetadata(e,t){let r=new Map;if(t.length===0)return r;let o=M({abi:q,functionName:"decimals"}),s=M({abi:q,functionName:"symbol"});try{let a=await Te(e,t.flatMap(i=>[{target:i,callData:o},{target:i,callData:s}]));t.forEach((i,l)=>{r.set(i,{decimals:ur(a[l*2]),symbol:cr(a[l*2+1])})})}catch{}return r}async fetchAssetLogos(e,t){let r=new Map;if(t.length===0)return r;try{let o=await this.pantograph.getTokensMetadata(t,e);for(let[s,a]of Object.entries(o)){let i=a.icon_image||a.logo||a.logoURI;i&&r.set(s.toLowerCase(),i)}}catch{}return U("resolveAssets: logos",{chain:e,requested:t.length,found:r.size}),r}async readMarketState(e,t,r){let o=[],s=t.map((d,u)=>{let p=pn(d),m=r[u],f={market:d,protocol:p,asset:m,size:o.length,rate:-1};o.push(p.sizeCall(d,m));let h=p.liveRateCall(d,m);return h&&(f.rate=o.length,o.push(h)),f}),a=await Te(e,o),i=[],l=s.map(d=>{if(d.rate<0)return-1;let u=d.protocol.followUpRateCall(d.market,a[d.rate]);return u?(i.push(u),i.length-1):-1}),c=i.length>0?await Te(e,i):[];return s.map((d,u)=>{let p=d.rate<0?null:a[d.rate],m=l[u]>=0?c[l[u]]:p;return{totalSuppliedUsdc:d.protocol.decodeSize(a[d.size],d.asset),liveApyFraction:m===null?null:d.protocol.decodeLiveRate(m)}})}async fetchApy(e,t,r){try{U("fetchApy: requesting",{market:e.name,type:e.type,asset:r?.symbol});let o=await pn(e).fetchApy(e,t,this.endpoints,r);return U("fetchApy: got",{market:e.name,samples:o.samples.length,current:o.current,avgOverride:o.avgOverride??null}),o}catch(o){return U("fetchApy: FAILED \u2014 market listed without APY",{market:e.name,type:e.type,message:o?.message}),{samples:[],current:null,rewards:[]}}}},Jl=class{constructor(e){this.limit=e}limit;active=0;waiting=[];async run(e){this.active>=this.limit?await new Promise(t=>this.waiting.push(t)):this.active++;try{return await e()}finally{let t=this.waiting.shift();t?t():this.active--}}};function Uf(n,e){let t=Ss(Date.now()),r=new Map,o=null;for(let i of n)!Number.isFinite(i.timeMs)||!Number.isFinite(i.fraction)||i.fraction<0||Ss(i.timeMs)>t||((!o||i.timeMs>o.timeMs)&&(o=i),r.set(i.timeMs,i.fraction));let s=[...r.entries()].sort((i,l)=>i[0]-l[0]).map(([i,l])=>({date:new Date(i).toISOString(),apyPercent:l*100})),a=e??(o&&Ss(o.timeMs)===t?o.fraction:null);return{history:s,live:a}}function Df(n,e,t=[],r=null){let{history:o,live:s}=Uf(n,e),a=s===null?null:s*100,i=t.map(m=>({apyPercent:m.fraction*100,tokenSymbol:m.tokenSymbol,conditions:m.conditions})),l=i.length===0?null:i.reduce((m,f)=>m+f.apyPercent,0),c=a===null?null:a+(l??0),d={baseApyPercent:a,rewardApyPercent:l,rewards:i},u=r!==null&&Number.isFinite(r)?r*100:null;if(o.length===0)return{history:o,avgApyPercent:u,currentApyPercent:c,apyChangePercent:null,...d};let p=o.reduce((m,f)=>m+f.apyPercent,0);return{history:o,avgApyPercent:u??p/o.length,currentApyPercent:c,apyChangePercent:Mf(o,a),...d}}var rd=3600*1e3,Of=rd/2;function Mf(n,e){if(e===null)return null;let t=Date.now()-rd,r=null,o=Number.POSITIVE_INFINITY;for(let s=n.length-1;s>=0;s--){let a=Math.abs(Date.parse(n[s].date)-t);if(a>o)break;o=a,r=n[s]}return!r||o>Of?null:e-r.apyPercent}function od(n,e){if(!Number.isFinite(n))return n;let t=10**e,r=Number((n*t).toPrecision(15));return(n<0?-Math.floor(-r):Math.floor(r))/t+0}var dt=class{read;supply;constructor(e={}){let t=e.coinPoolBaseUrl||"https://api.coinpool.app",r={lendingRatesBaseUrl:e.lendingRatesBaseUrl||"https://wallet-api.pantograph.app",aaveApiUrl:e.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:e.morphoApiUrl||"https://api.morpho.org/graphql"},o=new ti(r);this.read=new ro(t,r,o),this.supply=new oo(t)}async listSupportedChains(){return this.supply.listChains()}async isSupported(e){return this.supply.isSupported(e)}async getMarkets(e){return this.supply.getMarkets(e)}async findMarket(e,t){return this.supply.findMarket(e,t)}canSupply(e){return this.supply.canSupply(e)}async readReceiptToken(e,t){return this.supply.readReceiptToken(e,t)}async describeReceiptTokens(e,t,r){return this.read.describeReceiptTokens(e,t,r)}async findMarketByReceiptToken(e,t,r){return this.read.findMarketByReceiptToken(e,t,r)}async describeResolvedMarkets(e,t){return this.read.describeResolvedMarkets(e,t)}async getMarketOverviews(e){return(await Promise.all(e.chains.map(async r=>this.read.describeResolvedMarkets(r,await this.getMarkets(r))))).flat().sort((r,o)=>(o.avgApyPercent??-1)-(r.avgApyPercent??-1))}async getSupplyPositions(e){return this.read.getSupplyPositions(e)}};var Ms="{market}",id=[{name:"detail_button_label",type:"string",description:`Label for the per-market "More detail" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Just the words "More detail" translated: English "More detail", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the market in it and do NOT use the "{market}" placeholder \u2014 each button is rendered on that market's own card with its name directly above, so repeating the name only makes every card wordier. Keep it to one or two words so it fits on one line.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this market in detail" request template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "show me details of {market}". Vietnamese example: "xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng {market}". Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],ri=[{name:"supply_button_label",type:"string",description:`Label template for the "Supply" button \u2014 shown on EVERY market you list, and on the single market you describe \u2014 IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it; the button is rendered automatically. Unlike the "More detail" label, this one DOES name the market: it is the button that moves money. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". IN JAPANESE the label MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 render "supply" as the katakana \u30B5\u30D7\u30E9\u30A4, NEVER as \u4F9B\u7D66, \u9810\u3051\u5165\u308C, \u5165\u91D1 or any other kanji wording. Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "supply to {market}". Vietnamese example: "n\u1EA1p v\xE0o {market}". IN JAPANESE it MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 use the katakana \u30B5\u30D7\u30E9\u30A4, NEVER \u4F9B\u7D66 or another kanji wording. Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],ld="[[LIST]]",cd=' The market list is ALREADY RENDERED as cards below your reply \u2014 each card is numbered and shows the market name (linked to its page), its chain and its live APY, with its own "More detail" and "Supply" buttons. Do NOT write the list out in your text: no numbered list, no bullet list, no per-market lines, no links, and no mention of the buttons or of tapping one. Anything you write is shown ABOVE the cards, so repeating them just prints the same list twice. Naming the ONE market that tops the ordering, with its rate, is not repeating the list and is allowed where your other instructions say so \u2014 what is banned is walking through the markets one by one. Do NOT tell the user to supply, or push them toward it: the button is there if they want it, and this step has not shown them enough to judge a market.',ud=' A clickable "Supply" button for this market is shown below your reply automatically \u2014 do NOT repeat it in your text, do NOT tell the user to tap it, and do NOT describe it as a button, form or screen; just deliver the analysis.';function dd(n,e,t){let[r]=Ff([n],e,t),[o]=n.canSupply?Zl(n,e,t):[];return{name:n.name?.trim()||n.protocol,protocol:n.protocol,protocolUrl:n.protocolUrl,chain:t,apyPercent:n.apyPercent,detailPrompt:r?.prompt??"",detailLabel:r?.label??"",supplyPrompt:o?.prompt??"",supplyLabel:o?.label??""}}function Ff(n,e,t){return pd(n,{labelTemplate:ni(e.detail_button_label),promptTemplate:ni(e.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${Ms}`,...t===void 0?{}:{chainName:t}})}function Zl(n,e,t){return pd([n],{labelTemplate:ni(e.supply_button_label),promptTemplate:ni(e.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${Ms}`,promptFallback:`supply to ${Ms}`,...t===void 0?{}:{chainName:t},max:1})}function pd(n,e){let t=typeof e.chainName=="string"?e.chainName.trim():"",r=[],o=new Set;for(let s of n){if(e.max!==void 0&&r.length>=e.max)break;let a=s.name?.trim();!a||o.has(a.toLowerCase())||(o.add(a.toLowerCase()),r.push({label:sd(e.labelTemplate,a,e.labelFallback,e.labelNamesMarket===!0),prompt:sd(Bf(e.promptTemplate),a,e.promptFallback)+qf(s.contract,t)}))}return r}function Bf(n){let[e,t]=[n[0],n[1]];return e===void 0||e===e.toLowerCase()||t!==void 0&&t!==t.toLowerCase()?n:e.toLowerCase()+n.slice(1)}function ni(n){return typeof n=="string"?n:""}function qf(n,e){let t=n?.trim();if(!t||!/^0x[a-fA-F0-9]{40}$/.test(t))return"";let r=e?.trim();return r?` (market: ${t} - ${r})`:` (market: ${t})`}function sd(n,e,t,r=!0){let s=n&&(!r||n.includes(Ms))?n:t;return $f(s).split(Ms).join(e).replace(/\s+/g," ").trim()}var ad="{chain}";function $f(n){if(!n.includes(ad))return n;let e=ad.replace(/[{}]/g,"\\$&");return n.replace(new RegExp(`\\s*\\S+\\s*${e}`,"g"),"").replace(new RegExp(`${e}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(e,"g"),"")}var oi=[{id:"aave-v3",label:"Aave v3",types:["aave-v3"],aliases:["aave","aavev3","aave3","ave"]},{id:"compound-v3",label:"Compound v3",types:["compound-v3"],aliases:["compound","compoundv3","compound3","comet","comp"]},{id:"spark-any",label:"Spark",types:["spark","spark-ethereum"],aliases:["spark","sparkfi","sparklend","sparkprotocol"]},{id:"morpho-v2",label:"Morpho",types:["morpho-v2"],aliases:["morpho","morphov2","morpho2","morphoblue","metamorpho"]}],tc=oi.map(n=>n.label),ec={euler:"Euler",venus:"Venus",radiant:"Radiant",benqi:"Benqi",qi:"Benqi",fluid:"Fluid",instadapp:"Fluid",silo:"Silo",moonwell:"Moonwell",sonne:"Sonne",granary:"Granary",ironbank:"Iron Bank",cream:"Cream",maker:"Maker",makerdao:"Maker",sky:"Sky",justlend:"JustLend",kamino:"Kamino",solend:"Solend",marginfi:"marginfi",save:"Save",curve:"Curve",yearn:"Yearn",convex:"Convex",pendle:"Pendle",ethena:"Ethena",gearbox:"Gearbox",notional:"Notional",exactly:"Exactly",seamless:"Seamless",zerolend:"ZeroLend",dforce:"dForce",tectonic:"Tectonic",liqee:"Liqee"};function md(n){let e=typeof n=="string"?n.trim():"";if(!e)return{kind:"none"};let t=Yf(e);if(!t)return{kind:"none"};let r=Hf(t);if(r){let s=new Set(r.types);return{kind:"supported",label:r.label,matches:a=>s.has(a.type)}}let o=Wf(t);return o?{kind:"unsupported",label:o,requested:e}:{kind:"unknown",requested:e}}function Hf(n){let e=oi.filter(t=>t.aliases.includes(n));if(e.length===1)return e[0];if(e.length>1)return null;if(n.length>=3){let t=oi.filter(r=>r.aliases.some(o=>o.includes(n)||n.includes(o)));if(t.length===1)return t[0];if(t.length>1)return null}return Vf(n)}function Vf(n){let e=null,t=!1;for(let r of oi)for(let o of r.aliases){let s=hd(o);if(s===0||Math.abs(o.length-n.length)>s)continue;let a=fd(n,o,s);a>s||(!e||a<e.distance?(e={spec:r,distance:a},t=!1):a===e.distance&&r!==e.spec&&(t=!0))}return e&&!t?e.spec:null}function hd(n){return n.length<=4?0:n.length<=9?2:3}function Wf(n){let e=ec[n];if(e)return e;if(n.length>=4){let o=new Set(Object.entries(ec).filter(([s])=>s.length>=4&&(s.includes(n)||n.includes(s))).map(([,s])=>s));if(o.size===1)return[...o][0];if(o.size>1)return null}let t=null,r=!1;for(let[o,s]of Object.entries(ec)){let a=hd(o);if(a===0||Math.abs(o.length-n.length)>a)continue;let i=fd(n,o,a);i>a||(!t||i<t.distance?(t={label:s,distance:i},r=!1):i===t.distance&&s!==t.label&&(r=!0))}return t&&!r?t.label:null}function Yf(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function fd(n,e,t){if(n===e)return 0;if(!n.length)return e.length;if(!e.length)return n.length;let r=new Array(e.length+1),o=Array.from({length:e.length+1},(a,i)=>i),s=new Array(e.length+1);for(let a=1;a<=n.length;a++){s[0]=a;let i=s[0];for(let c=1;c<=e.length;c++){let d=o[c-1]+(n[a-1]===e[c-1]?0:1),u=Math.min(s[c-1]+1,o[c]+1,d);a>1&&c>1&&n[a-1]===e[c-2]&&n[a-2]===e[c-1]&&(u=Math.min(u,r[c-2]+1)),s[c]=u,u<i&&(i=u)}if(i>t)return t+1;let l=r;r=o,o=s,s=l}return o[e.length]}function ye(n,e){return n==null?null:od(n,e)}var De=2,mn=2;function si(n){let e=ye(n.currentApyPercent,De),t=n.rewards.map(s=>({apyPercent:ye(s.apyPercent,De)??0,tokenSymbol:s.tokenSymbol,conditions:s.conditions})),r=n.rewardApyPercent===null?null:t.reduce((s,a)=>s+Math.round(a.apyPercent*100),0)/100;if(r===null||e===null)return{currentApyPercent:e,rewardApyPercent:r,rewards:t,baseApyPercent:ye(n.baseApyPercent,De)};let o=Math.round(e*100)-Math.round(r*100);return{currentApyPercent:e,rewardApyPercent:r,rewards:t,baseApyPercent:o/100}}var Gf=["apy","score","size"],gd=3,yd=40,so=class extends A{name="get-lending-markets";kind="ui";description='BROWSE the LENDING / SUPPLY markets available to deposit into and earn yield on (Aave v3, Compound v3, Spark, Morpho vaults). Returns a deliberately SHORT shortlist row per market: its name, its page on the protocol, and its live supply APY \u2014 nothing else. Ranked by that live APY by default, and filterable to ONE protocol via `protocol`. Each market gets a "More detail" button \u2014 how the user reaches its size, recent average APY, reward split and platform score \u2014 and a "Supply" button that starts a deposit. So this tool answers "what is out there", NOT "is this one worth it". Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. The same applies to CHAINS and ASSETS: the market list is fetched live, so never answer "we have no markets on X" or "we only support USDC" from memory \u2014 call the tool and report what it returns. Do NOT use for: everything about ONE named market (size, score, average APY, rewards, whether it is a good place to put money) \u2192 get-lending-market-detail; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:`Hex chain ID to scope the list to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry markets is resolved at call time, so never filter the request against a list you remember. Set it ONLY when the user names a chain; otherwise OMIT it \u2014 the connected wallet's chain is used, or every chain at once when no wallet is connected. Never guess a chain to work around a wallet connected to one without lending markets.`,required:!1},{name:"protocol",type:"string",description:`Scope the list to ONE lending protocol. Supported: ${tc.join(", ")}. Set it whenever the user names a protocol \u2014 "supply aave", "morpho vaults", "l\xE3i su\u1EA5t b\xEAn Compound" \u2014 and pass what they wrote, VERBATIM. Do NOT correct their spelling, do NOT translate it, and do NOT map it to a name from the supported list yourself: misspellings are resolved for you, and a protocol that is NOT supported is reported back so you can tell the user. Pass it even when you believe the protocol is unsupported \u2014 that is how the user gets told. OMIT it when the user named no protocol; never guess one to narrow a list they asked for in full.`,required:!1},{name:"limit",type:"number",description:`How many markets to return, 1-${yd}. Default ${gd} \u2014 the top markets by the chosen ranking, which answers "where can I earn on my USDC" on its own. Raise it ONLY when the user asks for more than that, for the full list, or to compare broadly; lower it when they want a shorter shortlist.`,required:!1},{name:"sort",type:"string",description:'Ranking: "apy" (default, highest live protocol APY first), "score" (safest / best-rated first \u2014 use when the user asks for safe, reliable or trusted markets), or "size" (largest market first \u2014 use when the user asks for the biggest or most liquid markets).',required:!1},...id,...ri];service;constructor(e){super(),this.service=new dt(e)}async run(e,t){let r=K(e.chain,void 0),o=r?null:D(t?.chain),s=r??o,a=s?await this.service.isSupported(s):!1,i=a?[]:await this.service.listSupportedChains();if(s&&!a)return{_instructions:`There are no lending markets on ${T(s)}`+(o?", the chain the wallet is currently connected to":"")+". Tell the user that in their language and name the chains that DO have them (in `chainsWithLendingMarkets`), offering to list those instead. Do NOT mention tool names.",chain:T(s),connectedChainHasNoMarkets:o!==null,marketCount:0,marketNames:[],chainsWithLendingMarkets:i.map(y=>T(y))};let l=md(e.protocol);if(l.kind==="unsupported"||l.kind==="unknown")return this.unsupportedProtocol(l);let c=s?[s]:i,d=jf(e.sort),u=zf(e.limit),p=await this.service.getMarketOverviews({chains:c}),m=l.kind==="supported"?p.filter(y=>l.matches(y)):p;if(l.kind==="supported"&&m.length===0&&p.length>0)return{_instructions:`There are no ${l.label} lending markets on ${s?T(s):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${l.label} market. Do NOT mention tool names.`,requestedProtocol:l.label,chain:s?T(s):"all",marketCount:0,marketNames:[],protocolsAvailable:[...new Set(p.map(y=>y.protocol))]};let f=[...m].sort(Kf[d]).slice(0,u),h=f.map(y=>dd({name:y.name,contract:y.contract,protocol:y.protocol,protocolUrl:y.protocolUrl,apyPercent:ye(y.currentApyPercent,De),canSupply:this.service.supply.canSupply(y)},e,T(y.chain))),b={component:"LendingMarketList",props:{chain:s?T(s):"all",multiChain:new Set(h.map(y=>y.chain)).size>1,markets:h}};return{...h.length>0?{ui:b}:{},_instructions:this.instructions(f,d,h.length>0,l.kind==="supported"?l.label:null),chain:s?T(s):"all",chainsQueried:c.map(y=>T(y)),...l.kind==="supported"?{protocolFilter:l.label}:{},sortedBy:d,marketCount:h.length,totalMarketsAvailable:m.length,marketNames:h.map(y=>y.name)}}unsupportedProtocol(e){let t=e.kind==="unsupported",r=t?e.label:`"${e.requested}"`;return{_instructions:`The user asked about ${r}, which has no lending markets here. In their language: tell them plainly that ${r} is ${t?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${r} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:t?e.label:e.requested,protocolSupported:!1,supportedProtocols:[...tc],marketCount:0,marketNames:[]}}instructions(e,t,r=!1,o=null){if(e.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let s={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[t];return[o?`These are the ${o} lending markets the user can supply to, ${s}. The list is SCOPED to ${o} because that is what they asked about \u2014 say so, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${s}.`,`Write your reply in TWO parts separated by a line containing exactly ${ld} and nothing`,"else. Include that marker EXACTLY ONCE, on its own line. Do not translate it, style it, or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: at most two short sentences \u2014 the takeaway, then the caveats below.","Do not retell the markets in either part; they are already on screen.",t==="apy"?"In part two you MAY name the market at the top of the list and the live APY shown on its card, as the plain observation that it currently leads on rate. Write it in your own words. Do not add anything else about that market, and do not present it as a recommendation.":"Do NOT say which market pays the most: this list is NOT ordered by APY, so its first entry is not the highest-paying one.",new Set(e.map(a=>a.chain)).size>1?"The markets span several chains; each one shows its own chain.":`All of them are on ${T(e[0].chain)} \u2014 you may name that chain in your sentence.`,"You have NOT been given the market size, the platform score, the average APY, the daily change,","or the interest/reward split \u2014 they are not in this result. Do NOT state, estimate, or imply ANY of them,","for the list as a whole or for any single market.",`Saying the list is ${s} is allowed and expected \u2014 that is what the ordering means.`,"What you must NOT do is make a QUALITY claim about a market: do not call any one of them safe, safest,","stable, reliable, biggest or best-rated. Naming which market tops the ordering is fine \u2014 that is just",'reading the list back. Calling it the best one is not, because "best" rests on the figures this step',"does not have.",'So do NOT recommend one market over the others and do NOT name a "best option" \u2014 the figures that would',"justify a pick are exactly the ones this step omits. Point the user at a card instead: the full figures","are one tap away.","Part two MUST end by noting, in your own words, that APYs move constantly so a rate shown now is not a","promise of future yield, and that this is information rather than financial advice. Phrase it naturally","in the user's language \u2014 never omit it, however short the user asked you to be.","Do NOT mention tool names.",r?cd:""].filter(Boolean).join(" ")}},Kf={apy:(n,e)=>(e.currentApyPercent??-1)-(n.currentApyPercent??-1),score:(n,e)=>(e.platformScore??-1)-(n.platformScore??-1),size:(n,e)=>(e.totalSuppliedUsdc??-1)-(n.totalSuppliedUsdc??-1)};function jf(n){let e=typeof n=="string"?n.trim().toLowerCase():"";return Gf.includes(e)?e:"apy"}function zf(n){let e=typeof n=="number"?n:Number(n);return!Number.isFinite(e)||e<1?gd:Math.min(Math.floor(e),yd)}function bd(n){let{currentApyPercent:e,avgApyPercent:t,totalSuppliedUsdc:r,rewardApyPercent:o,baseApyPercent:s,platformScore:a}=n;return n.rewards.find(l=>l.conditions)?{id:"conditional-reward",lead:"the headline rate is not what a plain deposit earns \u2014 a reward programme with conditions attached makes up part of it, and the user meets those conditions only by doing something extra",order:"split the rate first and say what a plain deposit actually earns, then the conditions in plain words, and only afterwards the market itself and who this genuinely suits"}:o!==null&&s!==null&&o>s*1?{id:"reward-dominant",lead:"most of this rate is incentive rewards rather than interest paid by borrowers, so it depends on a programme that can be cut or expire",order:"where the yield really comes from first, then how durable that makes it, then the market and protocol underneath it"}:e!==null&&t!==null&&t>0&&e>t*1.5?{id:"spiked-rate",lead:"the live rate sits well above its own recent average, so it has caught a spike rather than settled there and should not be read as the rate to expect",order:"the gap between live and average first and what usually causes it, then what a supplier would more realistically earn, then the market and protocol"}:r!==null&&r<1e7?{id:"thin-market",lead:"this market is small, so its size is the first thing to weigh: a few large withdrawals can move things, and position sizing matters more here than the rate does",order:"size and what it implies for getting money back out first, then the protocol and who runs it, and the rate last"}:a!==null&&a<6?{id:"weak-score",lead:"the platform score is on the low side, which is the first thing to square before the rate matters",order:"what the score does and does not tell them first, then the protocol itself, then size and rate"}:a!==null&&a>=8.5&&r!==null&&r>=25e7?{id:"blue-chip",lead:"this is one of the most established places to lend this asset \u2014 depth and track record are the real argument here, and the rate is almost a detail",order:"how proven and deep it is first, then what that means for getting money in and out, then the rate and what moves it"}:r!==null&&r>=25e7?{id:"deep-market",lead:"the market is deep enough that the user's deposit is a drop in it \u2014 they can come and go without moving the rate",order:"depth and liquidity first, then where the yield comes from, then the protocol"}:{id:"ordinary",lead:"nothing here is dramatic, and that is the finding: it is an ordinary, steady place to park this asset, which is exactly what suits a first lending position",order:"the absence of surprises first and why that is a virtue, then what is actually earned and from whom, then the protocol behind it"}}function ai(n){let e=typeof n=="string"?n.trim():"",t=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/i.exec(e);if(t)return t[1];let r=/0x[a-fA-F0-9]{40}/.exec(e);return r&&r[0]!==e?r[0]:e}var ao=class extends A{name="get-lending-market-detail";category="blockchain-data";description='Everything about ONE lending / supply market, for when the user has picked a market and wants to know whether it is worth depositing into: its size, the live supply APY split into interest vs reward incentives (with any conditions attached to those incentives), the recent average APY and how the rate has moved, the asset it lends, its 0\u201310 platform score, and its page on the protocol. This is the tool for a tapped "More detail" button, and for any question aimed at a SINGLE named market: "tell me more about Aave v3 USDC", "is Morpho Gauntlet USDC safe?", "how big is the Spark vault", "chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng Compound v3", "what is the real APY on that one". Pass `market` \u2014 the market name, the protocol, or the market contract address. When the message carries a "(market: 0x\u2026 - <chain>)" hint, pass THAT address as `market` and THAT chain as `chain` \u2014 together they name the exact market. Needs NO wallet: it reads and describes, it does not deposit. Do NOT use for: LISTING or comparing several markets \u2192 get-lending-markets; actually depositing into this market \u2192 open-supply-usdc-form; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to describe \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID the market lives on (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the message names \u2014 INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},...ri];service;constructor(e){super(),this.service=new dt(e)}async run(e,t){let o=K(e.chain,void 0)??D(t?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for this market, so it cannot be looked up. Ask the user which chain the market is on. Do NOT mention tool names."};if(!await this.service.isSupported(o)){let u=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:T(o),chainsWithLendingMarkets:u.map(p=>T(p)),_instructions:`There are no lending markets on ${T(o)}, so there is no market to describe there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let s=ai(e.market);if(!s)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to know about \u2014 do not pick one for them. Do NOT mention tool names."};let a=await this.service.findMarket(o,s);if(a.length===0)return{error:"market_not_found",market:s,chain:T(o),_instructions:`No lending market matching "${s}" exists on ${T(o)}. Tell the user in their language and offer to show the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(a.length>1)return{error:"ambiguous_market",market:s,chain:T(o),candidates:a.map(u=>({marketName:u.name,protocol:u.protocol})),_instructions:`"${s}" matches ${a.length} different markets on ${T(o)}, so there is no single one to describe. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+s+`" and chain for ${T(o)}, plus the localized button templates \u2014 that shows the user each market as a card to tap. Write no message of your own before that call.`};let i=a[0],l=await this.describeOne(o,i);if(!l)return{error:"market_unavailable",marketName:i.name,chain:T(o),_instructions:`${i.name}'s current figures could not be read just now. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT quote any rate, size or score from memory, and do NOT mention tool names.`};let c=this.service.supply.canSupply(i),d=c?Zl({name:i.name,contract:i.contract},e,T(o)):[];return{_instructions:this.instructions(l,d.length>0,c),...d.length>0?{actionButtons:d}:{},marketName:l.name,protocol:l.protocolLabel??l.protocol,protocolUrl:l.protocolUrl,chain:T(l.chain),suppliedAssetSymbol:l.asset.symbol,totalSuppliedUsdc:ye(l.totalSuppliedUsdc,mn),...si(l),avgApyPercent:ye(l.avgApyPercent,De),apyChangePercent:ye(l.apyChangePercent,De),platformScore:l.platformScore,supplySupported:c}}async describeOne(e,t){try{let[r]=await this.service.describeResolvedMarkets(e,[t]);return r??null}catch{return null}}instructions(e,t,r){let o=bd(e);return[`This is the full picture of ONE lending market, ${e.name}, which the user asked about.`,"Lead with `marketName` in bold as PLAIN TEXT \u2014 **marketName** \u2014 not as a link, and name its `chain`.",'Go straight from that line into the bullets: do NOT write an introductory sentence before them ("Here is','a closer look at this market", "Here are the details", "Below is an overview"). Such a line says nothing',"the title has not already said and reads as boilerplate when every market opens with it.","Give a short bullet list, in this order. The FIRST bullet is nothing but a markdown link whose TEXT",'is the single word "Website" (translated into the user\'s language) and whose target is `protocolUrl` \u2014','exactly "- [Website](protocolUrl)". Do NOT put a label, a colon or any other word before or after that','link on the bullet: never "Website: [Website](\u2026)". NEVER print the raw URL as visible text, and NEVER use',"the market name as the link text. When `protocolUrl` is null, OMIT this bullet entirely; never invent a","URL.",'Then "Total supplied" = `totalSuppliedUsdc`, "Current APY" = `currentApyPercent`, "Avg APY" =',"`avgApyPercent`, and \u2014 only when the user asked about safety or the number helps your verdict \u2014",'"Platform score" = `platformScore`.',"Label `avgApyPercent` simply as the RECENT average. You have NOT been told what period it covers, so do",'NOT say "7-day", "past week", "last 30 days" or name any window or number of days for it.',"When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: write the",'"Current APY" bullet as the total followed by the split in parentheses \u2014 e.g. "2.11% (1.60% interest +','0.51% rewards)" \u2014 naming the reward token from `rewards[].tokenSymbol` when there is one. When it IS',"null, write `currentApyPercent` plainly and say NOTHING about rewards.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL \u2014 the user earns it only by meeting","those requirements, which a plain deposit usually does not. You MUST add a short plain-language warning","saying the reward part needs conditions and summarising them, so the total is never presented as what a","simple deposit earns. Never omit this to keep the answer short, and never quote such a total as if it","were guaranteed.",'Note that "Avg APY" covers the interest rate only, since reward history is not published \u2014 do not add',"`rewardApyPercent` to it, and if the average sits below the current rate, say that is why.","Compare the live rate against the average: a `currentApyPercent` well above `avgApyPercent` is a SPIKE,","not the rate to expect \u2014 say so plainly rather than quoting the live figure flat. `apyChangePercent` is","the move in the INTEREST rate over the LAST HOUR in percentage POINTS, rewards excluded; mention it","only when it is large enough to matter.","Format `totalSuppliedUsdc` compactly (100.12M, 23.45M). It is denominated in `suppliedAssetSymbol`:","when that is a dollar stablecoin (USDC, USDT, DAI) write it as dollars ($100.12M); otherwise append the","symbol instead (93.31K WETH). NEVER write a non-stablecoin amount with a $ sign.","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage. A null APY, size or score means","that figure was unavailable \u2014 say so rather than showing 0.",'Then, after the bullets, write a short heading line meaning "Reasons to consider supplying',"`suppliedAssetSymbol` to this lending market\", in the user's language and naming the actual asset \u2014","plain bold text, not a markdown heading. Under it, argue the case for supplying here as a bulleted list","of AT LEAST 6 points, each point its own bullet.",`The most important true thing about THIS market, for someone about to put money in, is that ${o.lead}.`,"Open the list by establishing exactly that, in your own words \u2014 it is bullet one, and every later bullet",`defends, qualifies or completes it. Then ${o.order}.`,"Follow that running order rather than any habit of listing rate, then size, then score.","Study how these two differ \u2014 not their numbers, their SHAPE:",'<example market="deep, unremarkable USDC market">',"- Nothing here is dramatic, and for a first lending position that is the point: a steady rate on a stable","asset, no strings attached.","- At $412M supplied, your deposit is a drop in the pool \u2014 you can pull it out whenever you want without","moving the rate.","- The 4.1% comes from real borrowers paying interest, not from a token giveaway that expires.","- Aave has run this market through several crashes now. That's the strongest argument it has.","- The rate drifts with borrowing demand, so treat 4.1% as roughly where it sits, not a fixed return.","- If you want the highest number on screen, this is not it. If you want somewhere boring to leave USDC,","it is hard to beat.","</example>",'<example market="small vault, conditional reward, spiked rate">',"- Read the 12.4% carefully: only 3.2% is interest. The other 9.2% is a reward programme, and it only pays","if you also borrow against your deposit \u2014 a plain deposit earns the 3.2%.","- Today's rate is also well above its recent average, so it caught a spike rather than settled there.","- The vault holds $6.8M. That is small enough that a few large withdrawals could move things, so size","your position with that in mind.","- A curator picks which loans this vault makes, so you are trusting their judgement on top of the code.","- A score of 5.6 is middling \u2014 not alarming, not proven either.","- Someone who understands the borrow leg and wants the incentive can do well here. Anyone looking for a","place to park stablecoins should look at a plainer market.","</example>","Note what changed: one opens on the absence of drama, the other on a number that misleads. One reassures","about size, the other warns about it. Neither walks APY, then size, then score. Match that variability \u2014","do NOT reuse these sentences.","Each bullet MUST carry a judgement, not a figure. Every number is already listed above, so delete the","number from a bullet and it must still say something. Cite a figure only as evidence.","Where the data cuts against the market, that belongs in the list, not omitted.","At least one bullet MUST judge `protocol` itself, since that is who holds the money: how established and","used it is, who ultimately pays the yield, and what a depositor is really exposed to (contract risk, the","asset, a vault curator). This comes from your own knowledge, so keep it qualitative \u2014 NO invented TVL,","launch date, audit count or incident history, and no numbers beyond those given. If you do not reliably","know the protocol, say so and point to its site.","Voice: an experienced analyst talking to a friend who has never lent on-chain. Plain sentences, no","jargon, no marketing tone; explain any unavoidable DeFi term (supply, incentives, vault) in the same","breath.","Ground every judgement in the given numbers: never invent a fact or a risk figure, and never promise a","return.","Close with a short reminder that this is information, not financial advice, worded to fit what you just",'said and DIFFERENT every time \u2014 e.g. "None of this is advice \u2014 check the numbers yourself before you','commit." / "Worth doing your own reading before you deposit; this is information only." / "That is the','picture as the data has it, not a recommendation." NEVER paste a stock line such as "This information is','for informational purposes only and not financial advice."',r?"":"Depositing into this market is NOT supported in the app yet. Say that plainly at the end, and do not invite the user to supply here.","Do NOT mention tool names.",t?ud:""].filter(Boolean).join(" ")}};var io=class extends A{name="get-wallet-lending-positions";description='Get a wallet\'s own LENDING / SUPPLY (earn, deposit, savings) positions in the curated lending markets: which protocol and market the wallet supplies to (Aave v3, Compound v3, Spark, Morpho vaults), how much it has supplied there, the AVERAGE supply APY over the last week (plus the live rate and the day-over-day change), the estimated yearly yield on that balance, and the market total supplied. Balances are read on-chain, so they match the app. Use for questions like: "Which protocols am I supplying on?", "Show my lending positions", "How much am I earning on my USDC?", "What APY am I getting?", "Where is my USDC deposited?", "My Aave / Compound / Spark / Morpho supply", "what am I earning on Aave", "my savings positions". This is the PREFERRED tool for any "what am I earning / supplying / depositing" question, even when the user names a protocol ("my Aave v3 supply", "my Spark deposit") \u2014 it is the only source of the 7-day average APY, the estimated yearly yield and the platform safety score. Each position reports its OWN asset, which is usually USDC but need not be \u2014 never assume the amounts are dollars without checking `suppliedAssetSymbol`. Chains and markets come from the live catalogue, so do not rule a chain out from memory: call the tool and let it answer. For protocols outside Aave v3 / Compound v3 / Spark / Morpho (Aave v2, MakerDAO\u2026), or when this tool reports nothing but the user insists they have a deposit, fall back to get-wallet-defi-positions. Do NOT use for: markets the wallet has NOT supplied to yet \u2014 where to deposit, best available APY, "promising lending" \u2192 get-lending-markets; the BORROW side of these same protocols, plus LP / staking \u2192 get-wallet-defi-positions (or get-wallet-defi-protocol-positions for one named protocol); plain token balances \u2192 get-wallet-token-balances.';category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:`Hex chain ID to scope to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry lending markets is resolved at call time, so do NOT filter the request against a list you remember. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 positions are then read on the connected wallet's own chain.`,required:!1}];service;constructor(e){super(),this.service=new dt(e)}async run(e,t){let r=le(e.address,t);if(!R(r))return{error:`"${r}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=K(e.chain,t),s=o?await this.service.isSupported(o):!1,a=s?[]:await this.service.listSupportedChains();if(o&&!s)return{_instructions:`There are no lending markets on ${T(o)}, so the wallet cannot have a supply position there. Tell the user that in their language and name the chains that DO have lending markets (listed in \`chainsWithLendingMarkets\`). Do NOT mention tool names.`,walletAddress:r,chain:T(o),positionCount:0,positions:[],chainsWithLendingMarkets:a.map(c=>T(c))};let i=o?[o]:a,l=await this.service.getSupplyPositions({address:r,chains:i});return{_instructions:this.instructions(l),walletAddress:r,chain:o?T(o):"all",chainsQueried:i.map(c=>T(c)),positionCount:l.length,totals:Xf(l),positions:l.map(c=>({marketName:c.name,protocol:c.protocol,protocolUrl:c.protocolUrl,chain:T(c.chain),suppliedUsdc:ye(c.suppliedUsdc,mn),suppliedAssetSymbol:c.asset.symbol,avgApyPercent:ye(c.avgApyPercent,De),...si(c),apyChangePercent:ye(c.apyChangePercent,De),estimatedAnnualYieldUsdc:ye(c.estimatedAnnualYieldUsdc,mn),marketTotalSuppliedUsdc:ye(c.totalSuppliedUsdc,mn),apyHistory:c.apyHistory.map(d=>({...d,apyPercent:ye(d.apyPercent,De)})),platformScore:c.platformScore}))}}instructions(e){return e.length===0?"The wallet supplies to NONE of the curated markets (Aave v3, Compound v3, Spark, Morpho) on the chains in `chainsQueried`. Say exactly that in the user's language \u2014 do not guess at other protocols and do not imply an error. This covers the curated markets only, so if the user believes they have a deposit it may be in a protocol outside that set; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the timestamped samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: say so when",'you quote that market`s APY, giving the split \u2014 e.g. "2.11% total (1.60% interest + 0.51% rewards)" \u2014 and',"naming the reward token from `rewards[].tokenSymbol` when there is one. Say nothing about rewards when it","is null. `avgApyPercent` covers the interest rate only, as reward history is not published.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL: the wallet earns that part only","while it meets those requirements. Say so briefly and summarise them, rather than reporting the total as","income the position is already receiving.","`estimatedAnnualYieldUsdc` deliberately counts only the interest and any UNCONDITIONAL reward, so on a","market with a conditional programme it is the floor, not the ceiling. If the user asks about yearly","earnings there, give that figure and add that meeting the reward conditions would raise it.","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(e.map(r=>r.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals` \u2014 but ONLY when `totals.mixedAssets` is false; when it is true","the positions are in different assets and cannot be added up, so give no portfolio total and let the","per-position amounts stand. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function Xf(n){if(new Set(n.map(a=>a.asset.symbol??a.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let r=n.reduce((a,i)=>a+i.suppliedUsdc,0),o=n.filter(a=>a.avgApyPercent!==null),s=o.reduce((a,i)=>a+i.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:n[0]?.asset.symbol??null,suppliedUsdc:ye(r,mn),estimatedAnnualYieldUsdc:ye(n.reduce((a,i)=>a+(i.estimatedAnnualYieldUsdc??0),0),mn),weightedAvgApyPercent:ye(s>0?o.reduce((a,i)=>a+i.suppliedUsdc*i.avgApyPercent,0)/s:null,De)}}var lo=class extends A{name="open-supply-usdc-form";kind="ui";category="lending-action";description='Open the SUPPLY form so the user can DEPOSIT into a specific lending market and start earning yield. This is the tool for a supply COMMAND: the user names a market and tells you to act on it, in any wording and any language \u2014 "supply USDC to Aave", "deposit 100 USDC into Compound", "n\u1EA1p USDC v\xE0o Morpho", a bare "Supply Aave", or a tapped "Supply \u2026" button. A supply verb plus a market name is already a complete command; terseness is not ambiguity, and the words the user left out are supplied by context rather than looked up. Each market deposits its OWN asset (usually USDC), resolved from the market itself \u2014 so a message that names no asset is still this tool: resolve the market from whatever the user did name. An amount is optional. Pass `market` \u2014 the market name or protocol exactly as it was shown to them (e.g. "Aave v3 USDC", "Spark"), and `amount` ONLY when they named one. Supports Aave v3, Compound v3, Spark and Morpho vaults, on whichever chains currently carry them \u2014 that set is resolved at call time, so never refuse a chain from memory. PRECONDITION: a connected wallet. The boundary is command vs question: use this to ACT on one market; to LIST or compare markets \u2192 get-lending-markets; for what the wallet already supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to supply to \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the message names, INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for; whether it carries markets is checked at call time. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`Amount to pre-fill, in the market's own asset, as a plain decimal ("100", "25.5"). Pass ONLY when the user named an amount. Omit otherwise \u2014 the user types it in the form. Never invent or convert an amount.`,required:!1}];service;moralis;constructor(e){super(),this.service=new dt(e),this.moralis=new O(e?.moralis)}async run(e,t){let r=t?.walletAddress;if(!r)return{error:"wallet_not_connected",_instructions:"Supplying moves real funds, so it needs a connected wallet. Ask the user to connect one, in their language. Do NOT render a form and do NOT mention tool names."};let s=K(e.chain,void 0)??D(t?.chain);if(!s)return{error:"no_chain",_instructions:"No chain could be determined for the supply. Ask the user which chain they want to supply on, naming the supported ones. Do NOT mention tool names."};if(!await this.service.isSupported(s)){let b=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:T(s),chainsWithLendingMarkets:b.map(y=>T(y)),_instructions:`There are no lending markets on ${T(s)}, so nothing can be supplied there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let a=ai(e.market);if(!a)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let i=await this.service.findMarket(s,a);if(i.length===0)return{error:"market_not_found",market:a,chain:T(s),_instructions:`No lending market matching "${a}" exists on ${T(s)}. Tell the user in their language and offer to list the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(i.length>1)return{error:"ambiguous_market",market:a,chain:T(s),candidates:i.map(b=>({marketName:b.name,protocol:b.protocol})),_instructions:`"${a}" matches ${i.length} different markets on ${T(s)}, so the supply cannot target one yet. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+a+`" and chain for ${T(s)}, plus the localized detail-button templates \u2014 that shows the user each market as a card with its live APY. Tapping one opens that market's full figures, and the supply is started from there. Write no message of your own before that call.`};let l=i[0];if(!this.service.supply.canSupply(l))return{error:"unsupported_protocol",marketName:l.name,protocol:l.protocol,_instructions:`Supplying to ${l.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let c=await this.describeOne(s,l),d=Qf(c);if(!d)return{error:"asset_unresolved",marketName:l.name,chain:T(s),_instructions:`The asset ${l.name} lends could not be read just now, so the supply cannot be prepared safely. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT guess the asset, do NOT name USDC, and do NOT mention tool names.`};let[u,p]=await Promise.all([this.assetBalance(r,s,d.address),this.service.readReceiptToken(s,l)]);if(u&&sn(u.amount,"0")<=0)return{error:"no_asset_balance",marketName:l.name,chain:T(s),assetSymbol:d.symbol,assetBalance:"0",_instructions:`The user has no ${d.symbol} available to supply to ${l.name} on ${T(s)}. In the user's language, tell them plainly that they have no ${d.symbol} available on this chain and need to add some before they can supply. Do NOT show any amount form, do NOT invent a balance, and do NOT state a specific balance figure. Keep it to one or two short sentences. Do NOT mention tool names.`};let m=Jf(e.amount),f=m?Dt(m,d.decimals):null;if(f&&u&&sn(f,u.amount)>0)return{error:"insufficient_asset_balance",marketName:l.name,chain:T(s),assetSymbol:d.symbol,requestedAmount:m,assetBalance:u.amount,_instructions:`The user wants to supply ${m} ${d.symbol} to ${l.name}, but they only hold ${u.amount} ${d.symbol} on ${T(s)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${m} ${d.symbol} exceeds their balance of ${u.amount} ${d.symbol} on this chain, then ask them to enter a smaller amount or add more. Do NOT open any amount form and do NOT invent figures. Keep it to one or two short sentences. Do NOT mention tool names.`};let h={action:"supply_usdc",chainId:s,chainName:T(s),walletAddress:r,market:{name:l.name,type:l.type,protocol:l.protocol,protocolUrl:c?.protocolUrl??ei(l),contract:l.contract,token:l.token,apyPercent:c?.currentApyPercent??c?.avgApyPercent??null,receiptToken:p},asset:d,...f?{prefillAmount:f}:{},...u?{spendable:u.amount}:{},...u?.usd?{spendableUsd:u.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:h},marketName:l.name,protocol:l.protocol,chain:T(s),apyPercent:ye(h.market.apyPercent,De),assetSymbol:d.symbol,assetBalance:u?.amount??null,_instructions:this.instructions(l,d.symbol)}}async describeOne(e,t){try{let[r]=await this.service.describeResolvedMarkets(e,[t]);return r??null}catch{return null}}async assetBalance(e,t,r){try{let o=await this.moralis.getWalletTokenBalances({address:e,chain:t,tokenAddresses:[r]});if(!o.success)return null;let s=(o.data?.result??[]).find(i=>(i.token_address||"").toLowerCase()===r.toLowerCase());if(!s?.balance_formatted)return{amount:"0",usd:null};let a=typeof s.usd_value=="number"?String(s.usd_value):null;return{amount:String(s.balance_formatted),usd:a}}catch{return null}}instructions(e,t){return[`The supply action for ${e.name} is ready.`,`In the user's language, invite them to enter the amount of ${t} they want to supply, naming the`,"market and the chain.",`Speak ONLY of the action the USER takes (supplying / depositing ${t}). NEVER say you "opened a form",`,'"opened" anything, or describe any screen, form, window or UI \u2014 phrase it as their next step, not something',"you did.","Do NOT state their balance, the contract address or any figure from the form; it is all on screen already.","Keep it to one or two short sentences. Add a brief note that supplying carries protocol risk and rates","float \u2014 information, not financial advice.","Do NOT mention tool names."].join(" ")}};function Qf(n){let e=n?.asset;return!e?.address||e.address===Yn||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function Jf(n){let e=typeof n=="string"?n.trim():typeof n=="number"?String(n):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}var ii="https://ipfs.pantograph.app/ipfs/",wd=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function Kn(n){let e=n?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${ii}${t[1]}`:wd.test(e)?`${ii}${e}`:null}function kd(n){let e=n?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${ii}${t[1]}`:wd.test(e)?`${ii}${e}`:null}function vd(n){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(n)}function nc(n){if(!n||typeof n!="object")return;let e=n,t=e.image??e.image_url??e.imageUrl;return typeof t=="string"&&t.trim()?t.trim():void 0}function Zf(n){if(typeof atob=="function"){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return new TextDecoder().decode(t)}if(typeof Buffer<"u")return Buffer.from(n,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function eg(n){let e=n.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let t=e[1]??"",r=e[2]??"";try{let o=/;base64/i.test(t)?Zf(r):decodeURIComponent(r);return JSON.parse(o)}catch{try{return JSON.parse(r)}catch{return null}}}function Td(n){let e=n?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=eg(e);return t?Kn(nc(t)):null}var tg=12,ng=6e3;async function rg(n,e,t){let r=new Array(n.length),o=0,s=new Array(Math.max(1,Math.min(e,n.length))).fill(0).map(async()=>{for(;o<n.length;){let a=o++;r[a]=await t(n[a],a)}});return await Promise.all(s),r}async function og(n,e){try{let t=await C.get(n,{timeout:e});if(!t.ok)return null;let r=t.data;if(r&&typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{return null}return null}catch{return null}}async function sg(n,e){let t=n?.trim();if(!t)return null;if(/^data:/i.test(t))return Td(t);let r=kd(t);if(!r)return null;if(vd(r))return r;let o=await og(r,e);if(o){let s=Kn(nc(o));if(s)return s}return null}async function li(n,e,t){if(e.length===0)return[];let r=t?.concurrency??tg,o=t?.timeoutMs??ng,s=await Tu(n,e,t?.rpcUrl);return rg(s,r,a=>sg(a,o))}var Ad=100,ag=100,co="{name}",Pd="{chain}",uo=class extends A{name="get-wallet-nfts";description=`Show the NFTs a wallet holds. Call with NO contract_address for a general request ("my NFTs", "show my NFTs", "what NFTs do I own") \u2014 it lists the wallet's NFT collections and renders a picker button per collection. Call WITH contract_address (and collection_name when known) once the user has named or picked a collection \u2014 it then lists that collection's NFTs with image, name and token id. Do NOT use for: sending an NFT \u2192 open-send-nft-form; details about one specific NFT \u2192 get-nft-metadata; info about a collection the wallet does not hold \u2192 get-nft-contract-info.`;category="nft";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID (e.g. "0x1" Ethereum, "0x89" Polygon, "0x2105" Base). ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, all supported chains are queried.',required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) to list the NFTs of. Set this ONLY when the user named a specific collection or clicked a collection button (their message then contains the address). OMIT it for a general "show my NFTs" request \u2014 that lists the collections to pick from.',required:!1},{name:"collection_name",type:"string",description:'Collection name as the user said it (e.g. "Bored Ape Yacht Club"). Used to find the collection when the user named one WITHOUT an address. Omit when unknown.',required:!1},{name:"pick_button_label",type:"string",description:`Label template for the per-collection picker buttons, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with the collection name. The label should be JUST the name \u2014 pass "{name}" unless a different wording is clearly better.`,required:!1},{name:"pick_prompt_template",type:"string",description:`A short "show this collection" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a collection button is clicked. Use TWO exact placeholders (do not translate the braces): "{name}" (the collection name) and "{chain}" (the network name, e.g. Optimism). Place {chain} where it reads naturally in the user's language, with the connector word in THAT language. English example: "show my {name} NFTs on {chain}". Vietnamese example: "xem NFT {name} c\u1EE7a t\xF4i tr\xEAn {chain}". Always include BOTH {name} and {chain}. Do NOT add the contract address yourself \u2014 it is appended automatically.`,required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=K(e.chain,t),s=o?[o]:qe(),a=pg(e.contract_address),i=Cd(e.collection_name);return a||i?this.listNfts({address:r,chains:s,singleChain:!!o,contract:a,collectionName:i}):this.listCollections({address:r,chains:s,singleChain:!!o,args:e})}async listCollections(e){let{address:t,chains:r,singleChain:o,args:s}=e,a=await Promise.all(r.map(async c=>{let d=await this.service.getWalletNftCollections({address:t,chain:c,limit:Ad});return{chain:c,rows:d.success?Sd(d.data?.result??[]):[],ok:d.success}}));if(o&&!a[0].ok)return{error:"Failed to fetch wallet NFT collections"};let i=a.flatMap(c=>c.rows.map(d=>({name:lg(d),contractAddress:d.token_address,chain:T(c.chain),nftCount:d.count??null})));if(i.length===0)return{_instructions:"The wallet holds no NFT collections"+(o?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:t,collectionCount:0,collections:[]};let l=ug(i,s);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:t,collectionCount:i.length,collections:i,...l.length>0?{actionButtons:l}:{}}}async listNfts(e){let{address:t,chains:r,singleChain:o,contract:s,collectionName:a}=e,i=await Promise.all(r.map(async m=>{let f=await this.service.getWalletNFTs({address:t,chain:m,limit:Ad,...s?{tokenAddresses:[s]}:{}});return{chain:m,rows:f.success?Sd(f.data?.result??[]):[],ok:f.success}}));if(o&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(m=>m.rows.filter(f=>ig(f,{contract:s,collectionName:a})).map(f=>({chain:m.chain,row:f})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${a??s??""}"`+(o?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||a||l[0].row.token_address,d=await this.resolveOnchainImages(l),u=l.map(({chain:m,row:f},h)=>{let g=cg(f);return{name:g.name,tokenId:g.tokenId,contractAddress:g.contractAddress,image:d[h]??g.image,chain:T(m)}});return{ui:{component:"WalletNftList",props:{walletAddress:t,collectionName:c,nfts:u}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:t,collectionName:c,nftCount:l.length}}async resolveOnchainImages(e){let t=new Array(e.length).fill(null),r=new Map;e.forEach((o,s)=>{let a=r.get(o.chain)??[];a.push(s),r.set(o.chain,a)});try{await Promise.all([...r.entries()].map(async([o,s])=>{let a=s.map(l=>({contract:e[l].row.token_address,tokenId:e[l].row.token_id})),i=await li(o,a);s.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function Sd(n){return n.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function ig(n,e){if(e.contract)return n.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let t=e.collectionName.toLowerCase();return(n.name??"").toLowerCase().includes(t)}return!1}function lg(n){let e=n.name?.trim();if(e)return e;let t=n.token_address??"";return t.length>10?`${t.slice(0,6)}\u2026${t.slice(-4)}`:t}function cg(n){return{name:n.normalized_metadata?.name||n.name||`#${n.token_id}`,tokenId:n.token_id,contractAddress:n.token_address,image:Kn(n.normalized_metadata?.image||n.media?.original_media_url)}}function ug(n,e){let t=typeof e.pick_button_label=="string"?e.pick_button_label:"",r=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",o=[];for(let s of n){if(o.length>=ag)break;if(!s.contractAddress)continue;let a=typeof s.chain=="string"?s.chain.trim():"",i=a?`show my ${co} NFTs on ${Pd}`:`show my ${co} NFTs`,l=xd(r,{[co]:s.name,[Pd]:a},i);a&&!l.includes(a)&&(l=`${l} (${a})`),o.push({label:dg(t,s.name,co),prompt:`${l} (${s.contractAddress})`})}return o}function xd(n,e,t){let r=n&&n.includes(co)?n:t;for(let[o,s]of Object.entries(e))r=r.split(o).join(s);return r.replace(/\s+/g," ").trim()}function dg(n,e,t){return xd(n,{[co]:e},t)}function Cd(n){if(typeof n!="string")return;let e=n.trim();return e||void 0}function pg(n){let e=Cd(n);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var mg="You are an NFT research analyst with live Google Search grounding. Base every factual claim (floor price, volume, holders, traits, sales, dates) on up-to-date search results and note the source. NEVER invent floor prices, volumes, token ids, or contract addresses \u2014 if the data is not available, state that plainly rather than guessing.",St=class extends A{kind="data";category="nft";llm;constructor(e){super(),this.llm=new ke(e??{})}static promptParams(e){return[{name:"prompt",type:"string",description:e,required:!0}]}async run(e){let t=typeof e.prompt=="string"?e.prompt.trim():"";if(!t)return{error:"Missing required parameter: prompt"};let r=await this.askGeminiWithSearch(t);return r?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:r}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(e){let t=Date.now();try{return(await this.llm.chat([{role:"system",content:mg,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var po=class extends St{name="get-nft-contract-info";description='Get information about an NFT COLLECTION / contract \u2014 name, symbol, token standard (ERC-721/1155), current floor price, total supply, holder count, recent trading volume, and official website / socials. Use when the user asks about a collection ("tell me about Bored Apes", "floor of Azuki", "is X collection legit"). Answers from live web data via the `prompt`.';parameters=St.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the collection. Cover the collection: its contract address, token standard, current floor price, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks. Example: "Research the Azuki NFT collection on Ethereum using up-to-date web sources. Report its contract address, token standard, current floor price in ETH, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks."`);presentInstructions="Present the collection info clearly: name, contract address, token standard, current floor price, total supply, holder count, recent volume, official links, and any notable news or risks."};var mo=class extends St{name="get-nft-metadata";description='Get details about a SPECIFIC NFT \u2014 its traits, rarity, image, the collection it belongs to, current floor price, and recent sales. Use when the user asks about ONE NFT ("show NFT #1234 of collection X", "traits of this NFT", "floor price of this NFT"). Answers from live web data via the `prompt`.';parameters=St.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address and the token id, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the NFT. Cover the specific NFT: its traits/attributes and rarity, the collection it belongs to, the current collection floor price, and the most recent sale price if available. Example: "Look up NFT #1234 in the Bored Ape Yacht Club collection (contract 0xBC4CA0E\u2026) on Ethereum using up-to-date web sources. Report its traits and rarity rank, the current collection floor price in ETH, the most recent sale price if available, and any notable details about this specific token."`);presentInstructions="Present the NFT details clearly: the collection and token id, its traits/rarity, the current floor price, recent sale(s), and any notable points."};var rc={en:"amazon.com",zh:"amazon.cn",ja:"amazon.co.jp",de:"amazon.de",es:"amazon.es",fr:"amazon.fr",it:"amazon.it",ko:"amazon.com",nl:"amazon.nl",pl:"amazon.pl",pt:"amazon.es",ru:"amazon.com",th:"amazon.com",tr:"amazon.com.tr",vi:"amazon.com"},oc="amazon.com";function hg(n){return n?n.trim().toLowerCase().split(/[-_]/)[0]:""}function sc(n){let e=hg(n);return rc[e]??oc}function ci(n){return`https://${sc(n)}/s?k=NFC%20Tag`}function ui(n){if(!n)return"";let e=n.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var fg=720*60*1e3,Rd=new Map,Ed=3;function gg(n){return[`A user in country "${n}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Ed} LARGEST / most popular e-commerce marketplaces in`,"THAT country where a regular consumer can buy NFC tags. For each store give its brand name and a","search URL that, opened TODAY, lands directly on a page LISTING NFC-tag products for sale.","CRITICAL about the URL:","- Use the store's CURRENT, official, live domain. Do NOT use domains that have been shut down,"," merged, rebranded or moved (e.g. an old service folded into a new one) \u2014 verify via search that"," the domain still serves search results today.","- Use that site's real, current search endpoint and query parameter (e.g. Amazon /s?k=, Shopee"," /search?keyword=, Rakuten /search/mall/<query>/). Prefer the simplest official search URL.","- The URL must return actual product results for the query, not a homepage, category page, login,"," 404 or empty page. Prefer the local storefront/domain for that country. URL-encode the query.","Return ONLY a compact JSON array, no prose, no markdown fences, of the form:",'[{"label":"Shopee","url":"https://shopee.vn/search?keyword=NFC%20Tag"}]',"Use https URLs only. Do not invent stores or URLs you cannot confirm operate in that country."].join(" ")}function yg(n){if(!n)return[];let e=n.indexOf("["),t=n.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let r;try{r=JSON.parse(n.slice(e,t+1))}catch{return[]}if(!Array.isArray(r))return[];let o=[],s=new Set;for(let a of r){if(!a||typeof a!="object")continue;let i=a.label,l=a.url;if(typeof i!="string"||!i.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!s.has(c)&&(s.add(c),o.push({label:i.trim(),url:l.trim()}),o.length>=Ed))break}return o}async function ac(n,e){let t=ui(n);if(!t||!e)return null;let r=Rd.get(t);if(r&&r.expires>Date.now())return r.links;let o=Date.now(),s=[{role:"user",content:gg(t),timestamp:o}];try{let a=await e.chat(s,void 0,{googleSearch:!0,maxRetries:1}),i=yg(a.text);if(i.length)return Rd.set(t,{links:i,expires:Date.now()+fg}),i}catch{}return null}async function ho(n){let e=await ac(n.country,n.llm);return e&&e.length?e:[{label:"Amazon",url:ci(n.language)}]}function bg(n){return n.length<=1?n.length===1?`[${n[0].label}](${n[0].url})`:"":n.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
39
+ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:r?T(r):"all",timeFrame:s??null,count:c.length,tokens:c}}};var Kr=class extends A{name="get-wallet-token-balances";description='Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new O(e)}truncateUsd(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[r,o=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${r}.${(o+"00").slice(0,2)}`}async run(e,t){let r=le(e.address,t),o=K(e.chain,t);if(o){let i=await this.service.getWalletTokenBalances({address:r,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1});return i.success?this.renderBalances(r,o,i.data?.result||[]):{error:i.error||"Failed to fetch token balances"}}let s=qe(),a=await Promise.all(s.map(async i=>{let l=await this.service.getWalletTokenBalances({address:r,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(r,a)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",r=e.balance_formatted??"0",o=e.symbol||"",s=typeof e.usd_value=="number"?`$${this.truncateUsd(e.usd_value)}`:"$-";return`- ${t}: ${r} ${o} (${s})`.replace(/\s+/g," ").trim()}renderBalances(e,t,r){let o=r.reduce((s,a)=>s+(a.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:e,chain:t,totalUsdValue:`$${this.truncateUsd(o)}`,tokens:r.map(s=>this.toTokenLine(s))}}renderBalancesByChain(e,t){let r=t.map(s=>{let a=s.tokens.reduce((l,c)=>l+(c.usd_value||0),0),i=s.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:T(s.chain),total:a,tokens:i}}).filter(s=>s.tokens.length>0).sort((s,a)=>a.total-s.total),o=r.reduce((s,a)=>s+a.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:e,chain:"all",totalUsdValue:`$${this.truncateUsd(o)}`,chains:r.map(s=>({chain:s.chain,totalUsdValue:`$${this.truncateUsd(s.total)}`,tokens:s.tokens.map(a=>this.toTokenLine(a))}))}}};var jr=class extends A{name="get-wallet-history";description=`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=Pe(e.chain,t),s=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,a=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,i=typeof e.fromBlock=="number"?e.fromBlock:typeof e.fromBlock=="string"&&e.fromBlock?Number(e.fromBlock):void 0,l=typeof e.toBlock=="number"?e.toBlock:typeof e.toBlock=="string"&&e.toBlock?Number(e.toBlock):void 0,c=Number.isFinite(i)?i:void 0,d=Number.isFinite(l)?l:void 0,u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",f=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,h=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,g=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,b=Number.isFinite(g)&&g>0?g:10,y=await this.service.getWalletHistory({address:r,chain:o,limit:b,fromDate:s,toDate:a,fromBlock:c,toBlock:d,cursor:u,order:m,includeInternalTransactions:f,nftMetadata:h});if(!y.success)return{error:y.error||"Failed to fetch wallet history"};let k=(y.data?.result||[]).map(v=>{let S=Iu(o,v.hash);return S?{...v,explorerUrl:S}:v});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:r,chain:o||"default",pagination:{cursor:y.data?.cursor??null,hasMore:!!y.data?.cursor},transactionCount:k.length,transactions:k}}};function jh(n){if(n.value_decimal)return n.value_decimal;let e=parseInt(n.token_decimals??"18",10);if(isNaN(e)||e===0)return n.value;try{let t=BigInt(n.value),r=BigInt(10)**BigInt(e),o=t/r,a=(t%r).toString().padStart(e,"0").replace(/0+$/,"");return a?`${o}.${a}`:`${o}`}catch{return n.value}}var zr=class extends A{name="get-wallet-token-transfers";description=`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=Pe(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),d=this.parseBlock(e.toBlock),u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",h=f==="send"?"send":f==="receive"?"receive":"all",g=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,b=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(E=>typeof E=="string"&&!!E).map(E=>E.trim()):void 0,y,w;if(g){let E=await this.resolveContractAddressBySymbol(g,r,o);E&&(b=[E.address],y=E.symbol,w=E.name)}let k=await this.service.getWalletTokenTransfers({address:r,chain:o,contractAddresses:b,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:d,cursor:u,order:m});if(!k.success)return{error:k.error||"Failed to fetch token transfers"};let v=r.toLowerCase(),P=(k.data?.result||[]).map(E=>{let we=E.from_address.toLowerCase()===v,V=we?"send":"receive",z=we?E.to_address:E.from_address,fe=we?E.to_address_label??void 0:E.from_address_label??void 0,Ne=we?E.to_address_entity??void 0:E.from_address_entity??void 0;return{...E,direction:V,amount_formatted:jh(E),counterparty:z,counterparty_label:fe,counterparty_entity:Ne}}),x=h==="all"?P:P.filter(E=>E.direction===h);if(g&&!b){let E=g.toLowerCase();x=x.filter(we=>(we.token_symbol??"").toLowerCase()===E)}let U=this.buildCounterparties(x);return{walletAddress:r,chain:o||"default",resolvedToken:y?{symbol:y,name:w,contractAddress:b?.[0]}:null,filters:{tokenSymbol:g||null,contractAddresses:b||null,direction:h,limit:a,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:d??null},pagination:{cursor:k.data?.cursor??null,pageSize:k.data?.page_size??a,page:k.data?.page??null,hasMore:!!k.data?.cursor},transferCount:x.length,transfers:x,counterparties:U}}async resolveContractAddressBySymbol(e,t,r){let o=e.toLowerCase(),s=await this.service.getWalletTokenBalances({address:t,chain:r});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}let a=await this.service.searchTokensByKey({key:e,chain:r});if(a.success&&a.data?.length){let l=a.data.find(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}buildCounterparties(e){let t=new Map,r=new Map;for(let s of e){let a=s.direction==="send"?t:r,i=s.counterparty.toLowerCase(),l=parseFloat(s.amount_formatted)||0,c=a.get(i);c?(c.total+=l,c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):a.set(i,{label:s.counterparty_label,entity:s.counterparty_entity,total:l,count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,total_amount:i.total.toFixed(6).replace(/\.?0+$/,""),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:o(t),received:o(r)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Xr=class extends A{name="get-wallet-nft-transfers";description=`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=Pe(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),d=this.parseBlock(e.toBlock),u=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.includePrices=="boolean"?e.includePrices:void 0,h=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",g=h==="send"?"send":h==="receive"?"receive":"all",b=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(x=>typeof x=="string"&&!!x).map(x=>x.trim()):void 0,y=await this.service.getWalletNftTransfers({address:r,chain:o,contractAddresses:b,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:d,cursor:u,order:m,includePrices:f});if(!y.success)return{error:y.error||"Failed to fetch NFT transfers"};let w=r.toLowerCase(),v=(y.data?.result||[]).map(x=>{let U=x.from_address.toLowerCase()===w,E=U?"send":"receive",we=U?x.to_address:x.from_address,V=U?x.to_address_label??void 0:x.from_address_label??void 0,z=U?x.to_address_entity??void 0:x.from_address_entity??void 0;return{...x,direction:E,counterparty:we,counterparty_label:V,counterparty_entity:z}}),S=g==="all"?v:v.filter(x=>x.direction===g),P=this.buildCounterparties(S);return{walletAddress:r,chain:o||"default",filters:{contractAddresses:b||null,direction:g,limit:a,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:d??null,includePrices:f??null},pagination:{cursor:y.data?.cursor??null,pageSize:y.data?.page_size??a,page:y.data?.page??null,hasMore:!!y.data?.cursor},transferCount:S.length,transfers:S,counterparties:P}}buildCounterparties(e){let t=new Map,r=new Map;for(let s of e){let a=s.direction==="send"?t:r,i=s.counterparty.toLowerCase(),l=s.token_name??s.token_address,c=a.get(i);c?(c.tokenIds.add(s.token_id),c.collections.add(l),c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):a.set(i,{label:s.counterparty_label,entity:s.counterparty_entity,tokenIds:new Set([s.token_id]),collections:new Set([l]),count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,token_ids:Array.from(i.tokenIds),collections:Array.from(i.collections),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:o(t),received:o(r)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var zh=["all","7","30","60","90"],Qr=class extends A{name="get-wallet-pnl-summary";description=`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=K(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=zh.includes(s)?s:void 0;if(o){let h=await this.service.getWalletPnlSummary({address:r,chain:o,days:a});return h.success?{walletAddress:r,chain:o,days:a??"all",summary:this.mapSummary(h.data)}:{error:h.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(qe().map(async h=>{let g=await this.service.getWalletPnlSummary({address:r,chain:h,days:a});return{chain:h,data:g.success?g.data:void 0}}))).flatMap(h=>h.data&&h.data.total_count_of_trades>0?[{chain:h.chain,data:h.data}]:[]),c=l.map(h=>({chain:T(h.chain),summary:this.mapSummary(h.data)})),d=l.reduce((h,g)=>h+Number(g.data.total_realized_profit_usd||0),0),u=l.reduce((h,g)=>h+Number(g.data.total_bought_volume_usd||0),0),p=l.reduce((h,g)=>h+Number(g.data.total_sold_volume_usd||0),0),m=l.reduce((h,g)=>h+Number(g.data.total_trade_volume||0),0),f={totalCountOfTrades:l.reduce((h,g)=>h+g.data.total_count_of_trades,0),totalTradeVolume:m,totalRealizedProfitUsd:d,totalRealizedProfitPercentage:u>0?d/u*100:0,totalBuys:l.reduce((h,g)=>h+g.data.total_buys,0),totalSells:l.reduce((h,g)=>h+g.data.total_sells,0),totalBoughtVolumeUsd:u,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:r,chain:"all",days:a??"all",summary:f,chains:c}}mapSummary(e){return{totalCountOfTrades:e.total_count_of_trades,totalTradeVolume:e.total_trade_volume,totalRealizedProfitUsd:e.total_realized_profit_usd,totalRealizedProfitPercentage:e.total_realized_profit_percentage,totalBuys:e.total_buys,totalSells:e.total_sells,totalBoughtVolumeUsd:e.total_bought_volume_usd,totalSoldVolumeUsd:e.total_sold_volume_usd}}};var Xh=["all","7","30","60","90"],Xa=25,Jr=class extends A{name="get-wallet-pnl";description=`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${Xa}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${Xa}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${Xa}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=K(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=Xh.includes(s)?s:void 0,i=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[],l=Array.isArray(e.tokenAddresses)?e.tokenAddresses.filter(u=>typeof u=="string"&&!!u.trim()).map(u=>u.trim()):[];if(o){let u=await this.fetchChainPnl(r,o,a,i,l);return u.ok?{walletAddress:r,chain:o,days:a??"all",filters:{tokenAddresses:u.tokenAddresses??null,resolvedSymbols:u.resolvedFromSymbols.length>0?u.resolvedFromSymbols:null,unresolvedSymbols:u.unresolvedSymbols.length>0?u.unresolvedSymbols:null},tokenCount:u.tokens.length,tokens:u.tokens}:{error:u.error||"Failed to fetch wallet PnL"}}let d=(await Promise.all(qe().map(async u=>({chain:u,res:await this.fetchChainPnl(r,u,a,i,l)})))).filter(u=>u.res.ok&&u.res.tokens.length>0).map(u=>({chain:T(u.chain),tokenCount:u.res.tokens.length,tokens:u.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:r,chain:"all",days:a??"all",filters:{requestedSymbols:i.length>0?i:null,requestedAddresses:l.length>0?l:null},tokenCount:d.reduce((u,p)=>u+p.tokenCount,0),chains:d}}async fetchChainPnl(e,t,r,o,s){let a=[],i=[];o.length>0&&(await Promise.all(o.map(p=>this.resolveContractAddress(p,t,e)))).forEach((p,m)=>{p?a.push({symbol:o[m],address:p.address}):i.push(o[m])});let l=Qh([...a.map(u=>u.address),...s]).slice(0,Xa),c=l.length>0?l:void 0,d=await this.service.getWalletPnl({address:e,chain:t,days:r,tokenAddresses:c});return{ok:d.success,error:d.error,tokens:d.data?.result??[],tokenAddresses:c,resolvedFromSymbols:a,unresolvedSymbols:i}}async resolveContractAddress(e,t,r){let o=e.toLowerCase();if(r){let a=await this.service.getWalletTokenBalances({address:r,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};function Qh(n){let e=new Set,t=[];for(let r of n){let o=r.toLowerCase();e.has(o)||(e.add(o),t.push(r))}return t}var Jh=BigInt(2)**BigInt(255),Zr=class extends A{name="get-wallet-approvals";description=`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=Pe(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):100,i=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,l=await this.service.getWalletApprovals({address:r,chain:o,limit:a,cursor:i});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,u=(c.result||[]).map(h=>Zh(h)),p=0,m=0,f=[];for(let h of u){h.isUnlimited&&(m+=1);let g=parseFloat(h.token.usdAtRisk??"");Number.isFinite(g)&&(p+=g);let b=h.token.possibleSpam||h.token.verifiedContract===!1,y=!h.spender.label&&!h.spender.entity;(b||h.isUnlimited&&y)&&f.push(h)}return{walletAddress:r,chain:o||"default",filters:{limit:a,cursor:i??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??a,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:u.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:f.length},approvals:u,riskyApprovals:f}}};function Zh(n){let e=ef(n.value);return{blockNumber:n.block_number,blockTimestamp:n.block_timestamp??null,transactionHash:n.transaction_hash??null,value:n.value,valueFormatted:n.value_formatted??null,isUnlimited:e,token:{address:n.token.address,addressLabel:n.token.address_label??null,name:n.token.name??null,symbol:n.token.symbol??null,logo:n.token.logo??null,possibleSpam:!!n.token.possible_spam,verifiedContract:n.token.verified_contract??null,currentBalance:n.token.current_balance??null,currentBalanceFormatted:n.token.current_balance_formatted??null,usdPrice:n.token.usd_price??null,usdAtRisk:n.token.usd_at_risk??null},spender:{address:n.spender.address,label:n.spender.address_label??null,entity:n.spender.entity??null,entityLogo:n.spender.entity_logo??null}}}function ef(n){if(!n)return!1;try{return BigInt(n)>=Jh}catch{return!1}}var eo=class extends A{name="get-wallet-defi-positions";description=`The BROAD, cross-protocol inventory of every DeFi position a wallet holds \u2014 liquidity provision, staking, borrowing AND supply/lending alike \u2014 with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Any APY here is the LIVE SPOT rate. Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "What is my health factor?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited funds \u2014 "what am I earning", "my supply APY", "my savings/deposits", "my Aave supply" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Use this tool for supply positions only as part of a full portfolio sweep, or for assets it does not cover (it handles USDC only). Never report both tools' APY for the same position. Also not for: positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=K(e.chain,t);if(o){let i=await this.service.getWalletDefiPositions({address:r,chain:o});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=i.data||[];return{walletAddress:r,chain:o,positionCount:l.length,positions:l.map(zu)}}let a=(await Promise.all(qe().map(async i=>{let l=await this.service.getWalletDefiPositions({address:r,chain:i});return{chain:i,rows:l.success?l.data||[]:[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:T(i.chain),positionCount:i.rows.length,positions:i.rows.map(zu)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:r,chain:"all",positionCount:a.reduce((i,l)=>i+l.positionCount,0),chains:a}}};function zu(n){return{protocolName:n.protocol_name,protocolId:n.protocol_id,protocolUrl:n.protocol_url,protocolLogo:n.protocol_logo,accountHealthFactor:n.account_data?.health_factor??null,position:tf(n.position)}}function tf(n){return{label:n.label,address:n.address,balanceUsd:n.balance_usd,totalUnclaimedUsdValue:n.total_unclaimed_usd_value,tokens:(n.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:n.position_details??null}}var to=class extends A{name="get-wallet-defi-protocol-positions";description=`Get every position a wallet holds inside ONE specific DeFi protocol \u2014 liquidity provision, staking, borrowing and supply alike \u2014 with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Any APY here is the LIVE SPOT rate. Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "show my Lido staking", "my Curve pools", "Pendle positions", "how much did I borrow on Aave", "what do I have on Aave v3". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited USDC \u2014 "my Aave v3 supply", "what am I earning on Spark", "my Compound deposit" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Come back here for that protocol's borrow / LP / staking side, or for supplied assets other than USDC. Never report both tools' APY for the same position. Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-positions to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=e.protocol?.trim();if(!r)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let o=le(e.address,t),s=K(e.chain,t);if(s){let l=await this.service.getWalletDefiProtocolPositions({address:o,protocol:r,chain:s});return l.success?l.data?{walletAddress:o,chain:s,...this.protocolFields(l.data)}:{error:"No data returned for this protocol"}:{error:l.error||"Failed to fetch wallet DeFi protocol positions"}}let i=(await Promise.all(qe().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:r,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:T(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${r} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:o,chain:"all",protocol:r,totalUsdValue:i.reduce((l,c)=>l+c.totalUsdValue,0),chains:i}}protocolFields(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,accountHealthFactor:e.account_data?.health_factor??null,positionCount:(e.positions||[]).length,positions:(e.positions||[]).map(nf)}}};function nf(n){return{label:n.label,address:n.address,balanceUsd:n.balance_usd,totalUnclaimedUsdValue:n.total_unclaimed_usd_value,tokens:(n.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:n.position_details??null}}function rf(n){try{return(Number(BigInt(n))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return n}}var no=class extends A{name="get-transaction-by-hash";description='Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.';category="blockchain-data";parameters=[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=e.transactionHash;if(!r)return{error:"Transaction hash is required."};let o=Pe(e.chain,t),s=await this.service.getTransactionByHash({transactionHash:r,chain:o});if(!s.success||!s.data)return{error:s.error||"Failed to fetch transaction"};let a=s.data,i=(a.logs??[]).filter(c=>!!c.decoded_event).map(c=>({contract:c.address,signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params})),l=a.logs.map(c=>({address:c.address,decodedEvent:c.decoded_event?{signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params}:null}));return{hash:a.hash,status:a.receipt_status==="1"?"success":a.receipt_status==="0"?"failed":"unknown",timestamp:a.block_timestamp,blockNumber:a.block_number,from:{address:a.from_address,label:a.from_address_label||null,entity:a.from_address_entity||null},to:a.to_address?{address:a.to_address,label:a.to_address_label||null,entity:a.to_address_entity||null}:null,valueEth:rf(a.value||"0"),fee:a.transaction_fee,gasUsed:a.receipt_gas_used,gasPriceGwei:a.gas_price?(Number(a.gas_price)/1e9).toFixed(4):null,decodedCall:a.decoded_call?{signature:a.decoded_call.signature,label:a.decoded_call.label,params:a.decoded_call.params}:null,decodedEvents:i,contractCreated:a.receipt_contract_address||null,logs:l}}};var Xu=new Map;function of(n){let e=Xu.get(n);if(e)return e;let t=rn({rpcUrl:n});return Xu.set(n,t),t}async function Qu(n,e,t=[]){let r=await of(n).rpc(e,t);if(r===void 0)throw new Error(`RPC ${e}: empty result`);return r}function Ju(n,e,t){return Qu(n,"eth_call",[{to:e,data:t},"latest"])}async function sf(n,e,t){let r=Mn(n);if(!r)return null;try{return await Ju(r,e,t)}catch{return null}}function D(n,e){globalThis.__LENDING_DEBUG__!==!1&&(e===void 0?console.log(`[LEND] ${n}`):console.log(`[LEND] ${n}`,JSON.stringify(e,af)))}function af(n,e){return typeof e=="bigint"?`${e}n`:e}var lf=6e4,jl=new Map;async function Os(n,e){let t=Ft(e),r=t?parseInt(t,16):NaN;if(!t||!Number.isFinite(r))return[];let o=`${n}|${t}`,s=jl.get(o);if(s&&Date.now()-s.at<lf)return s.markets;let a=cf(n,t,r),i=a.then(l=>l.markets);return jl.set(o,{at:Date.now(),markets:i}),a.then(l=>{l.answered||jl.delete(o)}),i}async function Qa(n,e){return(await Os(n,e)).length>0}async function cf(n,e,t){try{let r=`${n}/supply/v2?chainId=${t}&limit=100&page=1`;D("catalog: GET",r);let o=await C.get(r);if(!o.ok){let a=o.status>=400&&o.status<500;return D(a?"catalog: chain not served":"catalog: FAILED",{chain:e,status:o.status,message:_(o)}),{markets:[],answered:a}}let s=(o.data?.data?.items||[]).flatMap(a=>{let i=uf(a,e);return i?[i]:[]});return D("catalog: got markets",{chain:e,rawItems:o.data?.data?.items?.length??0,usable:s.length,tokens:s.map(a=>a.token)}),{markets:s,answered:!0}}catch(r){return D("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:e,message:r?.message}),{markets:[],answered:!1}}}function Zu(n,e){let t=e.trim().toLowerCase();if(!t)return[];if(R(t))return n.filter(o=>o.contract===t||o.token===t);let r=n.filter(o=>o.name.trim().toLowerCase()===t);return r.length>0?r:n.filter(o=>{let s=o.name.trim().toLowerCase(),a=o.protocol.trim().toLowerCase();return s.includes(t)||t.includes(s)||a.includes(t)||t.includes(a)})}function uf(n,e){if(n?.isDeleted===!0)return null;let t=typeof n?.contract=="string"?n.contract.toLowerCase():"";if(!R(t))return null;let r=typeof n?.token=="string"&&R(n.token)?n.token.toLowerCase():t,o=Number(n?.rating?.balanceScore),s=n?.type?.trim()||"unknown";return{chain:e,name:n?.name?.trim()||"USDC lending market",protocol:n?.protocolId?.name?.trim()||"Unknown",protocolLabel:Ke(s),protocolUrl:n?.protocolId?.domain?.trim()||null,type:s,contract:t,token:r,platformScore:Number.isFinite(o)?o:null}}function zl(){return qe()}async function Ja(n){let e=zl(),t=await Promise.all(e.map(r=>Qa(n,r)));return e.filter((r,o)=>t[o])}async function Za(n,e){let t=I(e);return t?Qa(n,t):!1}async function ed(n,e){let t=e.map(s=>I(s)).filter(s=>!!s),r=[...new Set(t)],o=await Promise.all(r.map(s=>Qa(n,s)));return r.filter((s,a)=>o[a])}function Gn(n){return Is(n)}var td=6;async function nd(n,e,t){let r=e.map(w=>R(w)?w.toLowerCase():null);if(r.every(w=>w===null))return D("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let o=Ga(n),s;try{D("discovery: probing 5 accessors per token",{chain:n,tokens:r,psm:o}),s=await Te(n,[...r.flatMap(w=>w?df(w):[]),...o?$u(o):[]])}catch(w){return D("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:n,message:w?.message}),e.map(()=>null)}let a=o?s.slice(s.length-Hu):[],i=B(a[0])?.toLowerCase()??null,l=B(a[1]),c=B(a[2]),d=i&&l&&c?{susds:i,usds:l,oracle:c}:null;o&&D("discovery: PSM3 lookup",{psm:o,susds:i,usds:l,oracle:c});let u=0,p=r.map(w=>{if(!w)return null;let k=s.slice(u,u+td);return u+=td,D("discovery: probe answers",{token:w,"POOL()":B(k[0]),"UNDERLYING_ASSET_ADDRESS()":B(k[1]),"baseToken()":B(k[2]),"asset()":B(k[3]),"vsr()":ee(k[4])?.toString()??null,"manager()":B(k[5])}),{token:w,slice:k}}),m=new Set;for(let w of p){if(!w)continue;let k=B(w.slice[0]);k&&B(w.slice[1])&&m.add(k.toLowerCase())}let f=await pf(n,[...m]);m.size>0&&D("discovery: Aave pool authentication",{claimed:[...m],genuine:[...f]});let h=new Map;for(let w of p){if(!w||B(w.slice[0])&&B(w.slice[1])||B(w.slice[2])||!B(w.slice[3]))continue;let v=B(w.slice[5]);v&&h.set(w.token,v.toLowerCase())}let g=await mf(n,h);h.size>0&&D("discovery: Maple manager authentication",{claimed:[...h.keys()],genuine:[...g]});let b=p.flatMap(w=>w?B(w.slice[0])&&B(w.slice[1])||B(w.slice[2])?[]:g.has(w.token)?[]:B(w.slice[3])?[w.token]:[]:[]),y=await hf(n,[...new Set(b)],t);return b.length>0&&D("discovery: Morpho vault lookup",{asked:[...new Set(b)],recognised:[...y.keys()]}),p.map(w=>{if(!w)return null;let{token:k,slice:v}=w,S={chain:n,protocolUrl:null,token:k,platformScore:null};if(d&&k===d.susds)return D("discovery: classified",{token:k,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:d.oracle}),{...S,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:Ke("spark-l2-susds"),protocolUrl:Gn("spark-l2-susds"),type:"spark-l2-susds",contract:d.oracle,assetAddress:d.usds};let P=B(v[0]);if(P&&B(v[1])){let x=f.has(P.toLowerCase());return D("discovery: classified",{token:k,as:x?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:P}),x?{...S,name:"Aave v3",protocol:"AAVE",protocolLabel:Ke("aave-v3"),protocolUrl:Gn("aave-v3"),type:"aave-v3",contract:P}:null}if(B(v[2]))return D("discovery: classified",{token:k,as:"compound-v3"}),{...S,name:"Compound v3",protocol:"COMPOUND",protocolLabel:Ke("compound-v3"),protocolUrl:Gn("compound-v3"),type:"compound-v3",contract:k};if(B(v[3])){if(g.has(k))return D("discovery: classified",{token:k,as:"maple (manager round trip verified)"}),{...S,name:"Maple",protocol:"MAPLE",protocolLabel:Ke("maple"),protocolUrl:Gn("maple"),type:"maple",contract:k};if(y.has(k)){D("discovery: classified",{token:k,as:"morpho-v2"});let E=y.get(k)||"Morpho V2";return{...S,name:E,protocol:"MORPHO",protocolLabel:Ke("morpho-v2"),protocolUrl:Gn("morpho-v2"),type:"morpho-v2",contract:k}}let U=ee(v[4])!==null;return D("discovery: classified",{token:k,as:U?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),U?{...S,name:"Spark",protocol:"SPARK",protocolLabel:Ke("spark-ethereum"),protocolUrl:Gn("spark-ethereum"),type:"spark-ethereum",contract:k}:{...S,name:"Spark",protocol:"SPARK",protocolLabel:Ke("spark"),protocolUrl:Gn("spark"),type:"spark",contract:k}}return D("discovery: classified",{token:k,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function df(n){return[{target:n,callData:M({abi:Br,functionName:"POOL"})},{target:n,callData:M({abi:Br,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:n,callData:M({abi:Mt,functionName:"baseToken"})},{target:n,callData:M({abi:wt,functionName:"asset"})},{target:n,callData:M({abi:qr,functionName:"vsr"})},{target:n,callData:M({abi:Hl,functionName:"manager"})}]}async function pf(n,e){if(e.length===0)return new Set;try{let t=await Te(n,e.map(r=>({target:r,callData:M({abi:Bl,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((r,o)=>B(t[o])!==null))}catch{return new Set}}async function mf(n,e){if(e.size===0)return new Set;let t=[...e.entries()];try{let r=await Te(n,t.map(([,o])=>({target:o,callData:M({abi:Vl,functionName:"pool"})})));return new Set(t.filter(([o],s)=>B(r[s])?.toLowerCase()===o.toLowerCase()).map(([o])=>o))}catch{return new Set}}async function hf(n,e,t){let r=parseInt(n,16);if(e.length===0||!Number.isFinite(r))return new Map;let o=await Promise.all(e.map(async s=>{try{let a=await C.post(t,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:s,c:r}}),i=a.ok?a.data?.data?.vaultV2ByAddress:null;return i?[s,i.name?.trim()||""]:null}catch{return null}}));return new Map(o.filter(s=>s!==null))}var ff=.01;function gf(n){return n.reduce((e,t)=>t.conditions===null?e+t.apyPercent:e,0)}function yf(n,e){if(typeof e!="string"||!e.trim())return;let t=e.trim(),r=ws();r[n]!==t&&Dn({...r,[n]:t})}var ro=class{constructor(e,t,r){this.coinPoolBaseUrl=e;this.endpoints=t;this.describer=r}coinPoolBaseUrl;endpoints;describer;async describeReceiptTokens(e,t,r){let o=Date.now();D("describeReceiptTokens: START",{chain:e,tokens:t,hasRpcUrl:!!r});let s=Ft(e);s&&yf(s,r);let a=s?Us(s):null,i=[...new Set(t.filter(R).map(p=>p.toLowerCase()))];if(D("describeReceiptTokens: chain resolved",{hex:s,hasChainInfo:!!a,wanted:i}),!s||!a||i.length===0)return D("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:s,hasChainInfo:!!a,wantedCount:i.length}),new Map;D("describeReceiptTokens: on-chain discovery for",i);let l=await nd(s,i,this.endpoints.morphoApiUrl),d=[...new Map(i.flatMap((p,m)=>{let f=l[m];return D("describeReceiptTokens: discovery result",{token:p,found:!!f,protocol:f?.protocol,type:f?.type,contract:f?.contract}),f?[[p,f]]:[]})).entries()];if(d.length===0)return D("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-o}),new Map;D("describeReceiptTokens: describing markets",{count:d.length,markets:d.map(([p,m])=>({token:p,type:m.type,contract:m.contract}))});let u=await this.describer.describe(s,a,d.map(([,p])=>p));return D("describeReceiptTokens: DONE",{ms:Date.now()-o,overviews:u.map(p=>({name:p.name,protocol:p.protocol,asset:p.asset?.symbol,assetDecimals:p.asset?.decimals,currentApyPercent:p.currentApyPercent,baseApyPercent:p.baseApyPercent,rewardApyPercent:p.rewardApyPercent,avgApyPercent:p.avgApyPercent,apyChangePercent:p.apyChangePercent,totalSuppliedUsdc:p.totalSuppliedUsdc,apyHistoryPoints:p.apyHistory?.length??0}))}),new Map(u.map((p,m)=>[d[m][0],p]))}async findMarketByReceiptToken(e,t,r){if(D("findMarketByReceiptToken: called",{chain:e,receiptToken:t,hasRpcUrl:!!r}),!R(t))return D("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:t}),null;let s=(await this.describeReceiptTokens(e,[t],r)).get(t.toLowerCase())??null;return D("findMarketByReceiptToken: returning",{found:!!s}),s}async getSupplyPositions(e){if(!R(e.address))return[];let t=await ed(this.coinPoolBaseUrl,e.chains);return(await Promise.all(t.map(o=>this.positionsForChain(o,e.address)))).flat().sort((o,s)=>s.suppliedUsdc-o.suppliedUsdc||(s.avgApyPercent??0)-(o.avgApyPercent??0))}async describeResolvedMarkets(e,t){let r=Ft(e),o=r?Us(r):null;return r&&o?this.describer.describe(r,o,t):[]}async positionsForChain(e,t){let r=Us(e),o=await Os(this.coinPoolBaseUrl,e);if(!r||o.length===0)return[];let s=await this.describer.readBalances(e,t,o);if(s.length===0)return[];let a=await this.describer.describe(e,r,s.map(l=>l.market)),i=await this.describer.convertToUnderlying(e,s,a.map(l=>l.asset));return a.flatMap((l,c)=>{let d=i[c];return d<ff?[]:[{...l,suppliedUsdc:d,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:d*(l.avgApyPercent+gf(l.rewards))/100}]})}};var Xl=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var oo=class{constructor(e){this.coinPoolBaseUrl=e}coinPoolBaseUrl;async listChains(){return Ja(this.coinPoolBaseUrl)}async isSupported(e){return Za(this.coinPoolBaseUrl,e)}async getMarkets(e){let t=I(e);return t?Os(this.coinPoolBaseUrl,t):[]}async findMarket(e,t){let r=await this.getMarkets(e);return Zu(r,t)}canSupply(e){return Xl.includes(e.type)}async readReceiptToken(e,t){let r=pn(t).balanceIsUnderlying;try{let o=await Te(e,[{target:t.token,callData:M({abi:q,functionName:"symbol"})},{target:t.token,callData:M({abi:q,functionName:"decimals"})}]);return{symbol:cr(o[0]),decimals:ur(o[1]),isUnderlying:r}}catch{return{symbol:null,decimals:null,isUnderlying:r}}}};var bf={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},wf={1:"proto_mainnet_v3",10:"proto_optimism_v3",56:"proto_bnb_v3",100:"proto_gnosis_v3",130:"proto_unichain_v3",137:"proto_polygon_v3",143:"proto_monad_v3",146:"proto_sonic_v3",196:"proto_xlayer_v3",324:"proto_zksync_v3",1088:"proto_metis_v3",1868:"proto_soneium_v3",4326:"proto_megaeth_v3",5e3:"proto_mantle_v3",8453:"proto_base_v3",9745:"proto_plasma_v3",42161:"proto_arbitrum_v3",42220:"proto_celo_v3",43114:"proto_avalanche_v3",57073:"proto_ink_v3",59144:"proto_linea_v3",534352:"proto_scroll_v3"},kf={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},vf={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function ei(n){let e=_f(n.chain);return(e===null?null:Tf(n,e))??Is(n.type)??Ef(n,e)}function Tf(n,e){switch(n.type){case"morpho-v2":{let t=bf[e];if(!t||!n.contract)return null;let r=`https://app.morpho.org/${t}/vault/${Ql(n.contract)}`,o=Sf(n.name);return o?`${r}/${o}`:r}case"aave-v3":{let t=wf[e],r=Af(n);return!t||!r?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${Ql(r)}&marketName=${t}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let t=kf[e],r=Cf(n);return!t||!r?null:`https://app.spark.fi/savings/${t}/${r}`}case"compound-v3":{let t=vf[e],r=xf(n);return!t||!r?null:`https://app.compound.finance/?market=${r}-${t}`}default:return null}}function Af(n){let e=n.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var Pf=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Sf(n){let e=n?.trim().toLowerCase()||"";return!e||Pf.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function xf(n){let e=n.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function Cf(n){let e=n.shareSymbol?.trim().toLowerCase()||"";if(/^[a-z0-9]{2,12}$/.test(e))return e;let t=`${n.name||""} ${n.token||""}`.toLowerCase();for(let o of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(t.includes(o))return o;if(n.type==="spark-ethereum")return Rf[n.contract?.trim().toLowerCase()||""]??null;let r=n.asset?.symbol?.trim().toLowerCase()||"";return!/^[a-z0-9]{2,11}$/.test(r)||r.startsWith("s")?null:`s${r}`}var Rf={"0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f":"speth","0x80128dbb9f07b93dde62a6daeadb69ed14a7d354":"sppyusd","0xe2e7a17dff93280dec073c995595155283e3c372":"spusdt","0x28b3a8fb53b741a8fd78c0fb9a6b2393d896a43d":"spusdc","0x45d91340b3b7b96985a72b5c678f7d9e8d664b62":"spusdt","0xc358c90d32375721cb3924320fdc2f8b694347ca":"spusdt","0xde770c84fe66e063336b31737cfe9790f18c4087":"spusdg"};function Ef(n,e){let t=n.protocolUrl?.trim();if(!t)return null;let r=/^https?:\/\//i.test(t)?t:`https://${t.replace(/^\/+/,"")}`;try{let o=new URL(r);return e!==null&&o.searchParams.set("chainId",String(e)),n.contract&&o.searchParams.set("contract",Ql(n.contract)),o.toString()}catch{return r}}function Ql(n){let e=n.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function _f(n){let e=n?.trim();if(!e)return null;let t=/^0x/i.test(e)?Number.parseInt(e,16):Number(e);return Number.isFinite(t)&&t>0?t:null}var Nf=new Set(["spark","spark-ethereum"]),Lf=8;function If(n,e,t){if(n.market.type!=="spark-l2-susds")return ee(e);let r=ee(e);return r===null||n.tokenDecimals===null?null:Wn(n.rawBalance,r,n.tokenDecimals,t)}var ti=class{constructor(e){this.endpoints=e}endpoints;apyLimiter=new Jl(Lf);pantograph=new Ae;async describe(e,t,r){if(r.length===0)return[];D("describe: START",{chain:e,count:r.length,types:r.map(l=>l.type)});let{assets:o,shareSymbols:s}=await this.resolveAssets(e,r);D("describe: assets resolved",o);let[a,i]=await Promise.all([this.readMarketState(e,r,o),Promise.all(r.map((l,c)=>this.apyLimiter.run(()=>this.fetchApy(l,t,o[c]))))]);return D("describe: on-chain state",a),D("describe: APY fetched",i.map((l,c)=>({type:r[c].type,rawSamples:l.samples.length,sourceCurrent:l.current}))),r.map((l,c)=>{let{totalSuppliedUsdc:d,liveApyFraction:u}=a[c],p=i[c].sizeOverride??d,m=Df(i[c].samples,u??i[c].current,i[c].rewards,i[c].avgOverride??null);return D("describe: summarised",{market:l.name,type:l.type,liveFrom:u!==null?"on-chain":i[c].current!==null?"api":"none",rawSamples:i[c].samples.length,historyPoints:m.history.length,currentApyPercent:m.currentApyPercent,avgApyPercent:m.avgApyPercent,apyChangePercent:m.apyChangePercent,totalSuppliedUsdc:p,asset:o[c]?.symbol}),{...l,protocolUrl:ei({...l,asset:o[c],shareSymbol:s[c]}),asset:o[c],totalSuppliedUsdc:p,avgApyPercent:m.avgApyPercent,currentApyPercent:m.currentApyPercent,baseApyPercent:m.baseApyPercent,rewardApyPercent:m.rewardApyPercent,rewards:m.rewards,apyChangePercent:m.apyChangePercent,apyHistory:m.history}})}async readBalances(e,t,r){let o=M({abi:q,functionName:"balanceOf",args:[t]}),s=M({abi:q,functionName:"decimals"}),a=r.flatMap(l=>[{target:l.token,callData:o},{target:l.token,callData:s}]),i=await Te(e,a);return r.flatMap((l,c)=>{let d=ee(i[c*2]);return d===null||d<=0n?[]:[{market:l,rawBalance:d,tokenDecimals:ur(i[c*2+1])}]})}async convertToUnderlying(e,t,r){let o=[],s=t.map(i=>{let l=pn(i.market).convertToAssetsCall(i.market,i.rawBalance);return l?(o.push(l),o.length-1):-1}),a=await Te(e,o);return t.map((i,l)=>{let c=r[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(s[l]<0)return tt(i.rawBalance,c);let d=If(i,a[s[l]],c);return d===null?tt(i.rawBalance,i.tokenDecimals??c):tt(d,c)})}async resolveAssets(e,t){let r={address:Yn,decimals:NaN,symbol:null,logo:null},o=[],s=t.map(p=>{let m=pn(p).underlyingCall(p);return m?(o.push(m),o.length-1):-1}),a;try{let p=o.length>0?await Te(e,o):[];a=s.map(m=>m<0?null:B(p[m]))}catch{a=t.map(()=>null)}a=a.map((p,m)=>p??t[m]?.assetAddress??null);let i=[...new Set(a.filter(p=>!!p).map(p=>p.toLowerCase()))],[l,c,d]=await Promise.all([this.readAssetMetadata(e,i),this.fetchAssetLogos(e,i),this.readShareSymbols(e,t)]);return{assets:a.map(p=>{if(!p)return r;let m=p.toLowerCase(),f=l.get(m),h=c.get(m)??null;return f?.decimals!==null&&f?.decimals!==void 0?{address:p,decimals:f.decimals,symbol:f.symbol??null,logo:h}:{address:p,decimals:NaN,symbol:null,logo:h}}),shareSymbols:d}}async readShareSymbols(e,t){let r=M({abi:q,functionName:"symbol"}),o=[],s=t.map(a=>!Nf.has(a.type)||!a.contract?-1:(o.push({target:a.contract,callData:r}),o.length-1));if(o.length===0)return t.map(()=>null);try{let a=await Te(e,o);return s.map(i=>i<0?null:cr(a[i]))}catch{return t.map(()=>null)}}async readAssetMetadata(e,t){let r=new Map;if(t.length===0)return r;let o=M({abi:q,functionName:"decimals"}),s=M({abi:q,functionName:"symbol"});try{let a=await Te(e,t.flatMap(i=>[{target:i,callData:o},{target:i,callData:s}]));t.forEach((i,l)=>{r.set(i,{decimals:ur(a[l*2]),symbol:cr(a[l*2+1])})})}catch{}return r}async fetchAssetLogos(e,t){let r=new Map;if(t.length===0)return r;try{let o=await this.pantograph.getTokensMetadata(t,e);for(let[s,a]of Object.entries(o)){let i=a.icon_image||a.logo||a.logoURI;i&&r.set(s.toLowerCase(),i)}}catch{}return D("resolveAssets: logos",{chain:e,requested:t.length,found:r.size}),r}async readMarketState(e,t,r){let o=[],s=t.map((d,u)=>{let p=pn(d),m=r[u],f={market:d,protocol:p,asset:m,size:o.length,rate:-1};o.push(p.sizeCall(d,m));let h=p.liveRateCall(d,m);return h&&(f.rate=o.length,o.push(h)),f}),a=await Te(e,o),i=[],l=s.map(d=>{if(d.rate<0)return-1;let u=d.protocol.followUpRateCall(d.market,a[d.rate]);return u?(i.push(u),i.length-1):-1}),c=i.length>0?await Te(e,i):[];return s.map((d,u)=>{let p=d.rate<0?null:a[d.rate],m=l[u]>=0?c[l[u]]:p;return{totalSuppliedUsdc:d.protocol.decodeSize(a[d.size],d.asset),liveApyFraction:m===null?null:d.protocol.decodeLiveRate(m)}})}async fetchApy(e,t,r){try{D("fetchApy: requesting",{market:e.name,type:e.type,asset:r?.symbol});let o=await pn(e).fetchApy(e,t,this.endpoints,r);return D("fetchApy: got",{market:e.name,samples:o.samples.length,current:o.current,avgOverride:o.avgOverride??null}),o}catch(o){return D("fetchApy: FAILED \u2014 market listed without APY",{market:e.name,type:e.type,message:o?.message}),{samples:[],current:null,rewards:[]}}}},Jl=class{constructor(e){this.limit=e}limit;active=0;waiting=[];async run(e){this.active>=this.limit?await new Promise(t=>this.waiting.push(t)):this.active++;try{return await e()}finally{let t=this.waiting.shift();t?t():this.active--}}};function Uf(n,e){let t=Ss(Date.now()),r=new Map,o=null;for(let i of n)!Number.isFinite(i.timeMs)||!Number.isFinite(i.fraction)||i.fraction<0||Ss(i.timeMs)>t||((!o||i.timeMs>o.timeMs)&&(o=i),r.set(i.timeMs,i.fraction));let s=[...r.entries()].sort((i,l)=>i[0]-l[0]).map(([i,l])=>({date:new Date(i).toISOString(),apyPercent:l*100})),a=e??(o&&Ss(o.timeMs)===t?o.fraction:null);return{history:s,live:a}}function Df(n,e,t=[],r=null){let{history:o,live:s}=Uf(n,e),a=s===null?null:s*100,i=t.map(m=>({apyPercent:m.fraction*100,tokenSymbol:m.tokenSymbol,conditions:m.conditions})),l=i.length===0?null:i.reduce((m,f)=>m+f.apyPercent,0),c=a===null?null:a+(l??0),d={baseApyPercent:a,rewardApyPercent:l,rewards:i},u=r!==null&&Number.isFinite(r)?r*100:null;if(o.length===0)return{history:o,avgApyPercent:u,currentApyPercent:c,apyChangePercent:null,...d};let p=o.reduce((m,f)=>m+f.apyPercent,0);return{history:o,avgApyPercent:u??p/o.length,currentApyPercent:c,apyChangePercent:Mf(o,a),...d}}var rd=3600*1e3,Of=rd/2;function Mf(n,e){if(e===null)return null;let t=Date.now()-rd,r=null,o=Number.POSITIVE_INFINITY;for(let s=n.length-1;s>=0;s--){let a=Math.abs(Date.parse(n[s].date)-t);if(a>o)break;o=a,r=n[s]}return!r||o>Of?null:e-r.apyPercent}function od(n,e){if(!Number.isFinite(n))return n;let t=10**e,r=Number((n*t).toPrecision(15));return(n<0?-Math.floor(-r):Math.floor(r))/t+0}var dt=class{read;supply;constructor(e={}){let t=e.coinPoolBaseUrl||"https://api.coinpool.app",r={lendingRatesBaseUrl:e.lendingRatesBaseUrl||"https://wallet-api.pantograph.app",aaveApiUrl:e.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:e.morphoApiUrl||"https://api.morpho.org/graphql"},o=new ti(r);this.read=new ro(t,r,o),this.supply=new oo(t)}async listSupportedChains(){return this.supply.listChains()}async isSupported(e){return this.supply.isSupported(e)}async getMarkets(e){return this.supply.getMarkets(e)}async findMarket(e,t){return this.supply.findMarket(e,t)}canSupply(e){return this.supply.canSupply(e)}async readReceiptToken(e,t){return this.supply.readReceiptToken(e,t)}async describeReceiptTokens(e,t,r){return this.read.describeReceiptTokens(e,t,r)}async findMarketByReceiptToken(e,t,r){return this.read.findMarketByReceiptToken(e,t,r)}async describeResolvedMarkets(e,t){return this.read.describeResolvedMarkets(e,t)}async getMarketOverviews(e){return(await Promise.all(e.chains.map(async r=>this.read.describeResolvedMarkets(r,await this.getMarkets(r))))).flat().sort((r,o)=>(o.avgApyPercent??-1)-(r.avgApyPercent??-1))}async getSupplyPositions(e){return this.read.getSupplyPositions(e)}};var Ms="{market}",id=[{name:"detail_button_label",type:"string",description:`Label for the per-market "More detail" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Just the words "More detail" translated: English "More detail", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the market in it and do NOT use the "{market}" placeholder \u2014 each button is rendered on that market's own card with its name directly above, so repeating the name only makes every card wordier. Keep it to one or two words so it fits on one line.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this market in detail" request template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "show me details of {market}". Vietnamese example: "xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng {market}". Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],ri=[{name:"supply_button_label",type:"string",description:`Label template for the "Supply" button \u2014 shown on EVERY market you list, and on the single market you describe \u2014 IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it; the button is rendered automatically. Unlike the "More detail" label, this one DOES name the market: it is the button that moves money. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". IN JAPANESE the label MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 render "supply" as the katakana \u30B5\u30D7\u30E9\u30A4, NEVER as \u4F9B\u7D66, \u9810\u3051\u5165\u308C, \u5165\u91D1 or any other kanji wording. Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "supply to {market}". Vietnamese example: "n\u1EA1p v\xE0o {market}". IN JAPANESE it MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 use the katakana \u30B5\u30D7\u30E9\u30A4, NEVER \u4F9B\u7D66 or another kanji wording. Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],ld="[[LIST]]",cd=' The market list is ALREADY RENDERED as cards below your reply \u2014 each card is numbered and shows the market name (linked to its page), its chain and its live APY, with its own "More detail" and "Supply" buttons. Do NOT write the list out in your text: no numbered list, no bullet list, no per-market lines, no links, and no mention of the buttons or of tapping one. Anything you write is shown ABOVE the cards, so repeating them just prints the same list twice. Naming the ONE market that tops the ordering, with its rate, is not repeating the list and is allowed where your other instructions say so \u2014 what is banned is walking through the markets one by one. Do NOT tell the user to supply, or push them toward it: the button is there if they want it, and this step has not shown them enough to judge a market.',ud=' A clickable "Supply" button for this market is shown below your reply automatically \u2014 do NOT repeat it in your text, do NOT tell the user to tap it, and do NOT describe it as a button, form or screen; just deliver the analysis.';function dd(n,e,t){let[r]=Ff([n],e,t),[o]=n.canSupply?Zl(n,e,t):[];return{name:n.name?.trim()||n.protocol,protocol:n.protocol,protocolUrl:n.protocolUrl,chain:t,apyPercent:n.apyPercent,detailPrompt:r?.prompt??"",detailLabel:r?.label??"",supplyPrompt:o?.prompt??"",supplyLabel:o?.label??""}}function Ff(n,e,t){return pd(n,{labelTemplate:ni(e.detail_button_label),promptTemplate:ni(e.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${Ms}`,...t===void 0?{}:{chainName:t}})}function Zl(n,e,t){return pd([n],{labelTemplate:ni(e.supply_button_label),promptTemplate:ni(e.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${Ms}`,promptFallback:`supply to ${Ms}`,...t===void 0?{}:{chainName:t},max:1})}function pd(n,e){let t=typeof e.chainName=="string"?e.chainName.trim():"",r=[],o=new Set;for(let s of n){if(e.max!==void 0&&r.length>=e.max)break;let a=s.name?.trim();!a||o.has(a.toLowerCase())||(o.add(a.toLowerCase()),r.push({label:sd(e.labelTemplate,a,e.labelFallback,e.labelNamesMarket===!0),prompt:sd(Bf(e.promptTemplate),a,e.promptFallback)+qf(s.contract,t)}))}return r}function Bf(n){let[e,t]=[n[0],n[1]];return e===void 0||e===e.toLowerCase()||t!==void 0&&t!==t.toLowerCase()?n:e.toLowerCase()+n.slice(1)}function ni(n){return typeof n=="string"?n:""}function qf(n,e){let t=n?.trim();if(!t||!/^0x[a-fA-F0-9]{40}$/.test(t))return"";let r=e?.trim();return r?` (market: ${t} - ${r})`:` (market: ${t})`}function sd(n,e,t,r=!0){let s=n&&(!r||n.includes(Ms))?n:t;return $f(s).split(Ms).join(e).replace(/\s+/g," ").trim()}var ad="{chain}";function $f(n){if(!n.includes(ad))return n;let e=ad.replace(/[{}]/g,"\\$&");return n.replace(new RegExp(`\\s*\\S+\\s*${e}`,"g"),"").replace(new RegExp(`${e}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(e,"g"),"")}var oi=[{id:"aave-v3",label:"Aave v3",types:["aave-v3"],aliases:["aave","aavev3","aave3","ave"]},{id:"compound-v3",label:"Compound v3",types:["compound-v3"],aliases:["compound","compoundv3","compound3","comet","comp"]},{id:"spark-any",label:"Spark",types:["spark","spark-ethereum"],aliases:["spark","sparkfi","sparklend","sparkprotocol"]},{id:"morpho-v2",label:"Morpho",types:["morpho-v2"],aliases:["morpho","morphov2","morpho2","morphoblue","metamorpho"]}],tc=oi.map(n=>n.label),ec={euler:"Euler",venus:"Venus",radiant:"Radiant",benqi:"Benqi",qi:"Benqi",fluid:"Fluid",instadapp:"Fluid",silo:"Silo",moonwell:"Moonwell",sonne:"Sonne",granary:"Granary",ironbank:"Iron Bank",cream:"Cream",maker:"Maker",makerdao:"Maker",sky:"Sky",justlend:"JustLend",kamino:"Kamino",solend:"Solend",marginfi:"marginfi",save:"Save",curve:"Curve",yearn:"Yearn",convex:"Convex",pendle:"Pendle",ethena:"Ethena",gearbox:"Gearbox",notional:"Notional",exactly:"Exactly",seamless:"Seamless",zerolend:"ZeroLend",dforce:"dForce",tectonic:"Tectonic",liqee:"Liqee"};function md(n){let e=typeof n=="string"?n.trim():"";if(!e)return{kind:"none"};let t=Yf(e);if(!t)return{kind:"none"};let r=Hf(t);if(r){let s=new Set(r.types);return{kind:"supported",label:r.label,matches:a=>s.has(a.type)}}let o=Wf(t);return o?{kind:"unsupported",label:o,requested:e}:{kind:"unknown",requested:e}}function Hf(n){let e=oi.filter(t=>t.aliases.includes(n));if(e.length===1)return e[0];if(e.length>1)return null;if(n.length>=3){let t=oi.filter(r=>r.aliases.some(o=>o.includes(n)||n.includes(o)));if(t.length===1)return t[0];if(t.length>1)return null}return Vf(n)}function Vf(n){let e=null,t=!1;for(let r of oi)for(let o of r.aliases){let s=hd(o);if(s===0||Math.abs(o.length-n.length)>s)continue;let a=fd(n,o,s);a>s||(!e||a<e.distance?(e={spec:r,distance:a},t=!1):a===e.distance&&r!==e.spec&&(t=!0))}return e&&!t?e.spec:null}function hd(n){return n.length<=4?0:n.length<=9?2:3}function Wf(n){let e=ec[n];if(e)return e;if(n.length>=4){let o=new Set(Object.entries(ec).filter(([s])=>s.length>=4&&(s.includes(n)||n.includes(s))).map(([,s])=>s));if(o.size===1)return[...o][0];if(o.size>1)return null}let t=null,r=!1;for(let[o,s]of Object.entries(ec)){let a=hd(o);if(a===0||Math.abs(o.length-n.length)>a)continue;let i=fd(n,o,a);i>a||(!t||i<t.distance?(t={label:s,distance:i},r=!1):i===t.distance&&s!==t.label&&(r=!0))}return t&&!r?t.label:null}function Yf(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function fd(n,e,t){if(n===e)return 0;if(!n.length)return e.length;if(!e.length)return n.length;let r=new Array(e.length+1),o=Array.from({length:e.length+1},(a,i)=>i),s=new Array(e.length+1);for(let a=1;a<=n.length;a++){s[0]=a;let i=s[0];for(let c=1;c<=e.length;c++){let d=o[c-1]+(n[a-1]===e[c-1]?0:1),u=Math.min(s[c-1]+1,o[c]+1,d);a>1&&c>1&&n[a-1]===e[c-2]&&n[a-2]===e[c-1]&&(u=Math.min(u,r[c-2]+1)),s[c]=u,u<i&&(i=u)}if(i>t)return t+1;let l=r;r=o,o=s,s=l}return o[e.length]}function ye(n,e){return n==null?null:od(n,e)}var De=2,mn=2;function si(n){let e=ye(n.currentApyPercent,De),t=n.rewards.map(s=>({apyPercent:ye(s.apyPercent,De)??0,tokenSymbol:s.tokenSymbol,conditions:s.conditions})),r=n.rewardApyPercent===null?null:t.reduce((s,a)=>s+Math.round(a.apyPercent*100),0)/100;if(r===null||e===null)return{currentApyPercent:e,rewardApyPercent:r,rewards:t,baseApyPercent:ye(n.baseApyPercent,De)};let o=Math.round(e*100)-Math.round(r*100);return{currentApyPercent:e,rewardApyPercent:r,rewards:t,baseApyPercent:o/100}}var Gf=["apy","score","size"],gd=3,yd=40,so=class extends A{name="get-lending-markets";kind="ui";description='BROWSE the LENDING / SUPPLY markets available to deposit into and earn yield on (Aave v3, Compound v3, Spark, Morpho vaults). Returns a deliberately SHORT shortlist row per market: its name, its page on the protocol, and its live supply APY \u2014 nothing else. Ranked by that live APY by default, and filterable to ONE protocol via `protocol`. Each market gets a "More detail" button \u2014 how the user reaches its size, recent average APY, reward split and platform score \u2014 and a "Supply" button that starts a deposit. So this tool answers "what is out there", NOT "is this one worth it". Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. The same applies to CHAINS and ASSETS: the market list is fetched live, so never answer "we have no markets on X" or "we only support USDC" from memory \u2014 call the tool and report what it returns. Do NOT use for: everything about ONE named market (size, score, average APY, rewards, whether it is a good place to put money) \u2192 get-lending-market-detail; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:`Hex chain ID to scope the list to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry markets is resolved at call time, so never filter the request against a list you remember. Set it ONLY when the user names a chain; otherwise OMIT it \u2014 the connected wallet's chain is used, or every chain at once when no wallet is connected. Never guess a chain to work around a wallet connected to one without lending markets.`,required:!1},{name:"protocol",type:"string",description:`Scope the list to ONE lending protocol. Supported: ${tc.join(", ")}. Set it whenever the user names a protocol \u2014 "supply aave", "morpho vaults", "l\xE3i su\u1EA5t b\xEAn Compound" \u2014 and pass what they wrote, VERBATIM. Do NOT correct their spelling, do NOT translate it, and do NOT map it to a name from the supported list yourself: misspellings are resolved for you, and a protocol that is NOT supported is reported back so you can tell the user. Pass it even when you believe the protocol is unsupported \u2014 that is how the user gets told. OMIT it when the user named no protocol; never guess one to narrow a list they asked for in full.`,required:!1},{name:"limit",type:"number",description:`How many markets to return, 1-${yd}. Default ${gd} \u2014 the top markets by the chosen ranking, which answers "where can I earn on my USDC" on its own. Raise it ONLY when the user asks for more than that, for the full list, or to compare broadly; lower it when they want a shorter shortlist.`,required:!1},{name:"sort",type:"string",description:'Ranking: "apy" (default, highest live protocol APY first), "score" (safest / best-rated first \u2014 use when the user asks for safe, reliable or trusted markets), or "size" (largest market first \u2014 use when the user asks for the biggest or most liquid markets).',required:!1},...id,...ri];service;constructor(e){super(),this.service=new dt(e)}async run(e,t){let r=K(e.chain,void 0),o=r?null:I(t?.chain),s=r??o,a=s?await this.service.isSupported(s):!1,i=a?[]:await this.service.listSupportedChains();if(s&&!a)return{_instructions:`There are no lending markets on ${T(s)}`+(o?", the chain the wallet is currently connected to":"")+". Tell the user that in their language and name the chains that DO have them (in `chainsWithLendingMarkets`), offering to list those instead. Do NOT mention tool names.",chain:T(s),connectedChainHasNoMarkets:o!==null,marketCount:0,marketNames:[],chainsWithLendingMarkets:i.map(y=>T(y))};let l=md(e.protocol);if(l.kind==="unsupported"||l.kind==="unknown")return this.unsupportedProtocol(l);let c=s?[s]:i,d=jf(e.sort),u=zf(e.limit),p=await this.service.getMarketOverviews({chains:c}),m=l.kind==="supported"?p.filter(y=>l.matches(y)):p;if(l.kind==="supported"&&m.length===0&&p.length>0)return{_instructions:`There are no ${l.label} lending markets on ${s?T(s):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${l.label} market. Do NOT mention tool names.`,requestedProtocol:l.label,chain:s?T(s):"all",marketCount:0,marketNames:[],protocolsAvailable:[...new Set(p.map(y=>y.protocol))]};let f=[...m].sort(Kf[d]).slice(0,u),h=f.map(y=>dd({name:y.name,contract:y.contract,protocol:y.protocol,protocolUrl:y.protocolUrl,apyPercent:ye(y.currentApyPercent,De),canSupply:this.service.supply.canSupply(y)},e,T(y.chain))),b={component:"LendingMarketList",props:{chain:s?T(s):"all",multiChain:new Set(h.map(y=>y.chain)).size>1,markets:h}};return{...h.length>0?{ui:b}:{},_instructions:this.instructions(f,d,h.length>0,l.kind==="supported"?l.label:null),chain:s?T(s):"all",chainsQueried:c.map(y=>T(y)),...l.kind==="supported"?{protocolFilter:l.label}:{},sortedBy:d,marketCount:h.length,totalMarketsAvailable:m.length,marketNames:h.map(y=>y.name)}}unsupportedProtocol(e){let t=e.kind==="unsupported",r=t?e.label:`"${e.requested}"`;return{_instructions:`The user asked about ${r}, which has no lending markets here. In their language: tell them plainly that ${r} is ${t?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${r} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:t?e.label:e.requested,protocolSupported:!1,supportedProtocols:[...tc],marketCount:0,marketNames:[]}}instructions(e,t,r=!1,o=null){if(e.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let s={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[t];return[o?`These are the ${o} lending markets the user can supply to, ${s}. The list is SCOPED to ${o} because that is what they asked about \u2014 say so, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${s}.`,`Write your reply in TWO parts separated by a line containing exactly ${ld} and nothing`,"else. Include that marker EXACTLY ONCE, on its own line. Do not translate it, style it, or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: at most two short sentences \u2014 the takeaway, then the caveats below.","Do not retell the markets in either part; they are already on screen.",t==="apy"?"In part two you MAY name the market at the top of the list and the live APY shown on its card, as the plain observation that it currently leads on rate. Write it in your own words. Do not add anything else about that market, and do not present it as a recommendation.":"Do NOT say which market pays the most: this list is NOT ordered by APY, so its first entry is not the highest-paying one.",new Set(e.map(a=>a.chain)).size>1?"The markets span several chains; each one shows its own chain.":`All of them are on ${T(e[0].chain)} \u2014 you may name that chain in your sentence.`,"You have NOT been given the market size, the platform score, the average APY, the daily change,","or the interest/reward split \u2014 they are not in this result. Do NOT state, estimate, or imply ANY of them,","for the list as a whole or for any single market.",`Saying the list is ${s} is allowed and expected \u2014 that is what the ordering means.`,"What you must NOT do is make a QUALITY claim about a market: do not call any one of them safe, safest,","stable, reliable, biggest or best-rated. Naming which market tops the ordering is fine \u2014 that is just",'reading the list back. Calling it the best one is not, because "best" rests on the figures this step',"does not have.",'So do NOT recommend one market over the others and do NOT name a "best option" \u2014 the figures that would',"justify a pick are exactly the ones this step omits. Point the user at a card instead: the full figures","are one tap away.","Part two MUST end by noting, in your own words, that APYs move constantly so a rate shown now is not a","promise of future yield, and that this is information rather than financial advice. Phrase it naturally","in the user's language \u2014 never omit it, however short the user asked you to be.","Do NOT mention tool names.",r?cd:""].filter(Boolean).join(" ")}},Kf={apy:(n,e)=>(e.currentApyPercent??-1)-(n.currentApyPercent??-1),score:(n,e)=>(e.platformScore??-1)-(n.platformScore??-1),size:(n,e)=>(e.totalSuppliedUsdc??-1)-(n.totalSuppliedUsdc??-1)};function jf(n){let e=typeof n=="string"?n.trim().toLowerCase():"";return Gf.includes(e)?e:"apy"}function zf(n){let e=typeof n=="number"?n:Number(n);return!Number.isFinite(e)||e<1?gd:Math.min(Math.floor(e),yd)}function bd(n){let{currentApyPercent:e,avgApyPercent:t,totalSuppliedUsdc:r,rewardApyPercent:o,baseApyPercent:s,platformScore:a}=n;return n.rewards.find(l=>l.conditions)?{id:"conditional-reward",lead:"the headline rate is not what a plain deposit earns \u2014 a reward programme with conditions attached makes up part of it, and the user meets those conditions only by doing something extra",order:"split the rate first and say what a plain deposit actually earns, then the conditions in plain words, and only afterwards the market itself and who this genuinely suits"}:o!==null&&s!==null&&o>s*1?{id:"reward-dominant",lead:"most of this rate is incentive rewards rather than interest paid by borrowers, so it depends on a programme that can be cut or expire",order:"where the yield really comes from first, then how durable that makes it, then the market and protocol underneath it"}:e!==null&&t!==null&&t>0&&e>t*1.5?{id:"spiked-rate",lead:"the live rate sits well above its own recent average, so it has caught a spike rather than settled there and should not be read as the rate to expect",order:"the gap between live and average first and what usually causes it, then what a supplier would more realistically earn, then the market and protocol"}:r!==null&&r<1e7?{id:"thin-market",lead:"this market is small, so its size is the first thing to weigh: a few large withdrawals can move things, and position sizing matters more here than the rate does",order:"size and what it implies for getting money back out first, then the protocol and who runs it, and the rate last"}:a!==null&&a<6?{id:"weak-score",lead:"the platform score is on the low side, which is the first thing to square before the rate matters",order:"what the score does and does not tell them first, then the protocol itself, then size and rate"}:a!==null&&a>=8.5&&r!==null&&r>=25e7?{id:"blue-chip",lead:"this is one of the most established places to lend this asset \u2014 depth and track record are the real argument here, and the rate is almost a detail",order:"how proven and deep it is first, then what that means for getting money in and out, then the rate and what moves it"}:r!==null&&r>=25e7?{id:"deep-market",lead:"the market is deep enough that the user's deposit is a drop in it \u2014 they can come and go without moving the rate",order:"depth and liquidity first, then where the yield comes from, then the protocol"}:{id:"ordinary",lead:"nothing here is dramatic, and that is the finding: it is an ordinary, steady place to park this asset, which is exactly what suits a first lending position",order:"the absence of surprises first and why that is a virtue, then what is actually earned and from whom, then the protocol behind it"}}function ai(n){let e=typeof n=="string"?n.trim():"",t=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/i.exec(e);if(t)return t[1];let r=/0x[a-fA-F0-9]{40}/.exec(e);return r&&r[0]!==e?r[0]:e}var ao=class extends A{name="get-lending-market-detail";category="blockchain-data";description='Everything about ONE lending / supply market, for when the user has picked a market and wants to know whether it is worth depositing into: its size, the live supply APY split into interest vs reward incentives (with any conditions attached to those incentives), the recent average APY and how the rate has moved, the asset it lends, its 0\u201310 platform score, and its page on the protocol. This is the tool for a tapped "More detail" button, and for any question aimed at a SINGLE named market: "tell me more about Aave v3 USDC", "is Morpho Gauntlet USDC safe?", "how big is the Spark vault", "chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng Compound v3", "what is the real APY on that one". Pass `market` \u2014 the market name, the protocol, or the market contract address. When the message carries a "(market: 0x\u2026 - <chain>)" hint, pass THAT address as `market` and THAT chain as `chain` \u2014 together they name the exact market. Needs NO wallet: it reads and describes, it does not deposit. Do NOT use for: LISTING or comparing several markets \u2192 get-lending-markets; actually depositing into this market \u2192 open-supply-usdc-form; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to describe \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID the market lives on (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the message names \u2014 INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},...ri];service;constructor(e){super(),this.service=new dt(e)}async run(e,t){let o=K(e.chain,void 0)??I(t?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for this market, so it cannot be looked up. Ask the user which chain the market is on. Do NOT mention tool names."};if(!await this.service.isSupported(o)){let u=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:T(o),chainsWithLendingMarkets:u.map(p=>T(p)),_instructions:`There are no lending markets on ${T(o)}, so there is no market to describe there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let s=ai(e.market);if(!s)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to know about \u2014 do not pick one for them. Do NOT mention tool names."};let a=await this.service.findMarket(o,s);if(a.length===0)return{error:"market_not_found",market:s,chain:T(o),_instructions:`No lending market matching "${s}" exists on ${T(o)}. Tell the user in their language and offer to show the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(a.length>1)return{error:"ambiguous_market",market:s,chain:T(o),candidates:a.map(u=>({marketName:u.name,protocol:u.protocol})),_instructions:`"${s}" matches ${a.length} different markets on ${T(o)}, so there is no single one to describe. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+s+`" and chain for ${T(o)}, plus the localized button templates \u2014 that shows the user each market as a card to tap. Write no message of your own before that call.`};let i=a[0],l=await this.describeOne(o,i);if(!l)return{error:"market_unavailable",marketName:i.name,chain:T(o),_instructions:`${i.name}'s current figures could not be read just now. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT quote any rate, size or score from memory, and do NOT mention tool names.`};let c=this.service.supply.canSupply(i),d=c?Zl({name:i.name,contract:i.contract},e,T(o)):[];return{_instructions:this.instructions(l,d.length>0,c),...d.length>0?{actionButtons:d}:{},marketName:l.name,protocol:l.protocolLabel??l.protocol,protocolUrl:l.protocolUrl,chain:T(l.chain),suppliedAssetSymbol:l.asset.symbol,totalSuppliedUsdc:ye(l.totalSuppliedUsdc,mn),...si(l),avgApyPercent:ye(l.avgApyPercent,De),apyChangePercent:ye(l.apyChangePercent,De),platformScore:l.platformScore,supplySupported:c}}async describeOne(e,t){try{let[r]=await this.service.describeResolvedMarkets(e,[t]);return r??null}catch{return null}}instructions(e,t,r){let o=bd(e);return[`This is the full picture of ONE lending market, ${e.name}, which the user asked about.`,"Lead with `marketName` in bold as PLAIN TEXT \u2014 **marketName** \u2014 not as a link, and name its `chain`.",'Go straight from that line into the bullets: do NOT write an introductory sentence before them ("Here is','a closer look at this market", "Here are the details", "Below is an overview"). Such a line says nothing',"the title has not already said and reads as boilerplate when every market opens with it.","Give a short bullet list, in this order. The FIRST bullet is nothing but a markdown link whose TEXT",'is the single word "Website" (translated into the user\'s language) and whose target is `protocolUrl` \u2014','exactly "- [Website](protocolUrl)". Do NOT put a label, a colon or any other word before or after that','link on the bullet: never "Website: [Website](\u2026)". NEVER print the raw URL as visible text, and NEVER use',"the market name as the link text. When `protocolUrl` is null, OMIT this bullet entirely; never invent a","URL.",'Then "Total supplied" = `totalSuppliedUsdc`, "Current APY" = `currentApyPercent`, "Avg APY" =',"`avgApyPercent`, and \u2014 only when the user asked about safety or the number helps your verdict \u2014",'"Platform score" = `platformScore`.',"Label `avgApyPercent` simply as the RECENT average. You have NOT been told what period it covers, so do",'NOT say "7-day", "past week", "last 30 days" or name any window or number of days for it.',"When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: write the",'"Current APY" bullet as the total followed by the split in parentheses \u2014 e.g. "2.11% (1.60% interest +','0.51% rewards)" \u2014 naming the reward token from `rewards[].tokenSymbol` when there is one. When it IS',"null, write `currentApyPercent` plainly and say NOTHING about rewards.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL \u2014 the user earns it only by meeting","those requirements, which a plain deposit usually does not. You MUST add a short plain-language warning","saying the reward part needs conditions and summarising them, so the total is never presented as what a","simple deposit earns. Never omit this to keep the answer short, and never quote such a total as if it","were guaranteed.",'Note that "Avg APY" covers the interest rate only, since reward history is not published \u2014 do not add',"`rewardApyPercent` to it, and if the average sits below the current rate, say that is why.","Compare the live rate against the average: a `currentApyPercent` well above `avgApyPercent` is a SPIKE,","not the rate to expect \u2014 say so plainly rather than quoting the live figure flat. `apyChangePercent` is","the move in the INTEREST rate over the LAST HOUR in percentage POINTS, rewards excluded; mention it","only when it is large enough to matter.","Format `totalSuppliedUsdc` compactly (100.12M, 23.45M). It is denominated in `suppliedAssetSymbol`:","when that is a dollar stablecoin (USDC, USDT, DAI) write it as dollars ($100.12M); otherwise append the","symbol instead (93.31K WETH). NEVER write a non-stablecoin amount with a $ sign.","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage. A null APY, size or score means","that figure was unavailable \u2014 say so rather than showing 0.",'Then, after the bullets, write a short heading line meaning "Reasons to consider supplying',"`suppliedAssetSymbol` to this lending market\", in the user's language and naming the actual asset \u2014","plain bold text, not a markdown heading. Under it, argue the case for supplying here as a bulleted list","of AT LEAST 6 points, each point its own bullet.",`The most important true thing about THIS market, for someone about to put money in, is that ${o.lead}.`,"Open the list by establishing exactly that, in your own words \u2014 it is bullet one, and every later bullet",`defends, qualifies or completes it. Then ${o.order}.`,"Follow that running order rather than any habit of listing rate, then size, then score.","Study how these two differ \u2014 not their numbers, their SHAPE:",'<example market="deep, unremarkable USDC market">',"- Nothing here is dramatic, and for a first lending position that is the point: a steady rate on a stable","asset, no strings attached.","- At $412M supplied, your deposit is a drop in the pool \u2014 you can pull it out whenever you want without","moving the rate.","- The 4.1% comes from real borrowers paying interest, not from a token giveaway that expires.","- Aave has run this market through several crashes now. That's the strongest argument it has.","- The rate drifts with borrowing demand, so treat 4.1% as roughly where it sits, not a fixed return.","- If you want the highest number on screen, this is not it. If you want somewhere boring to leave USDC,","it is hard to beat.","</example>",'<example market="small vault, conditional reward, spiked rate">',"- Read the 12.4% carefully: only 3.2% is interest. The other 9.2% is a reward programme, and it only pays","if you also borrow against your deposit \u2014 a plain deposit earns the 3.2%.","- Today's rate is also well above its recent average, so it caught a spike rather than settled there.","- The vault holds $6.8M. That is small enough that a few large withdrawals could move things, so size","your position with that in mind.","- A curator picks which loans this vault makes, so you are trusting their judgement on top of the code.","- A score of 5.6 is middling \u2014 not alarming, not proven either.","- Someone who understands the borrow leg and wants the incentive can do well here. Anyone looking for a","place to park stablecoins should look at a plainer market.","</example>","Note what changed: one opens on the absence of drama, the other on a number that misleads. One reassures","about size, the other warns about it. Neither walks APY, then size, then score. Match that variability \u2014","do NOT reuse these sentences.","Each bullet MUST carry a judgement, not a figure. Every number is already listed above, so delete the","number from a bullet and it must still say something. Cite a figure only as evidence.","Where the data cuts against the market, that belongs in the list, not omitted.","At least one bullet MUST judge `protocol` itself, since that is who holds the money: how established and","used it is, who ultimately pays the yield, and what a depositor is really exposed to (contract risk, the","asset, a vault curator). This comes from your own knowledge, so keep it qualitative \u2014 NO invented TVL,","launch date, audit count or incident history, and no numbers beyond those given. If you do not reliably","know the protocol, say so and point to its site.","Voice: an experienced analyst talking to a friend who has never lent on-chain. Plain sentences, no","jargon, no marketing tone; explain any unavoidable DeFi term (supply, incentives, vault) in the same","breath.","Ground every judgement in the given numbers: never invent a fact or a risk figure, and never promise a","return.","Close with a short reminder that this is information, not financial advice, worded to fit what you just",'said and DIFFERENT every time \u2014 e.g. "None of this is advice \u2014 check the numbers yourself before you','commit." / "Worth doing your own reading before you deposit; this is information only." / "That is the','picture as the data has it, not a recommendation." NEVER paste a stock line such as "This information is','for informational purposes only and not financial advice."',r?"":"Depositing into this market is NOT supported in the app yet. Say that plainly at the end, and do not invite the user to supply here.","Do NOT mention tool names.",t?ud:""].filter(Boolean).join(" ")}};var io=class extends A{name="get-wallet-lending-positions";description='Get a wallet\'s own LENDING / SUPPLY (earn, deposit, savings) positions in the curated lending markets: which protocol and market the wallet supplies to (Aave v3, Compound v3, Spark, Morpho vaults), how much it has supplied there, the AVERAGE supply APY over the last week (plus the live rate and the day-over-day change), the estimated yearly yield on that balance, and the market total supplied. Balances are read on-chain, so they match the app. Use for questions like: "Which protocols am I supplying on?", "Show my lending positions", "How much am I earning on my USDC?", "What APY am I getting?", "Where is my USDC deposited?", "My Aave / Compound / Spark / Morpho supply", "what am I earning on Aave", "my savings positions". This is the PREFERRED tool for any "what am I earning / supplying / depositing" question, even when the user names a protocol ("my Aave v3 supply", "my Spark deposit") \u2014 it is the only source of the 7-day average APY, the estimated yearly yield and the platform safety score. Each position reports its OWN asset, which is usually USDC but need not be \u2014 never assume the amounts are dollars without checking `suppliedAssetSymbol`. Chains and markets come from the live catalogue, so do not rule a chain out from memory: call the tool and let it answer. For protocols outside Aave v3 / Compound v3 / Spark / Morpho (Aave v2, MakerDAO\u2026), or when this tool reports nothing but the user insists they have a deposit, fall back to get-wallet-defi-positions. Do NOT use for: markets the wallet has NOT supplied to yet \u2014 where to deposit, best available APY, "promising lending" \u2192 get-lending-markets; the BORROW side of these same protocols, plus LP / staking \u2192 get-wallet-defi-positions (or get-wallet-defi-protocol-positions for one named protocol); plain token balances \u2192 get-wallet-token-balances.';category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:`Hex chain ID to scope to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry lending markets is resolved at call time, so do NOT filter the request against a list you remember. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 positions are then read on the connected wallet's own chain.`,required:!1}];service;constructor(e){super(),this.service=new dt(e)}async run(e,t){let r=le(e.address,t);if(!R(r))return{error:`"${r}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=K(e.chain,t),s=o?await this.service.isSupported(o):!1,a=s?[]:await this.service.listSupportedChains();if(o&&!s)return{_instructions:`There are no lending markets on ${T(o)}, so the wallet cannot have a supply position there. Tell the user that in their language and name the chains that DO have lending markets (listed in \`chainsWithLendingMarkets\`). Do NOT mention tool names.`,walletAddress:r,chain:T(o),positionCount:0,positions:[],chainsWithLendingMarkets:a.map(c=>T(c))};let i=o?[o]:a,l=await this.service.getSupplyPositions({address:r,chains:i});return{_instructions:this.instructions(l),walletAddress:r,chain:o?T(o):"all",chainsQueried:i.map(c=>T(c)),positionCount:l.length,totals:Xf(l),positions:l.map(c=>({marketName:c.name,protocol:c.protocol,protocolUrl:c.protocolUrl,chain:T(c.chain),suppliedUsdc:ye(c.suppliedUsdc,mn),suppliedAssetSymbol:c.asset.symbol,avgApyPercent:ye(c.avgApyPercent,De),...si(c),apyChangePercent:ye(c.apyChangePercent,De),estimatedAnnualYieldUsdc:ye(c.estimatedAnnualYieldUsdc,mn),marketTotalSuppliedUsdc:ye(c.totalSuppliedUsdc,mn),apyHistory:c.apyHistory.map(d=>({...d,apyPercent:ye(d.apyPercent,De)})),platformScore:c.platformScore}))}}instructions(e){return e.length===0?"The wallet supplies to NONE of the curated markets (Aave v3, Compound v3, Spark, Morpho) on the chains in `chainsQueried`. Say exactly that in the user's language \u2014 do not guess at other protocols and do not imply an error. This covers the curated markets only, so if the user believes they have a deposit it may be in a protocol outside that set; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the timestamped samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: say so when",'you quote that market`s APY, giving the split \u2014 e.g. "2.11% total (1.60% interest + 0.51% rewards)" \u2014 and',"naming the reward token from `rewards[].tokenSymbol` when there is one. Say nothing about rewards when it","is null. `avgApyPercent` covers the interest rate only, as reward history is not published.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL: the wallet earns that part only","while it meets those requirements. Say so briefly and summarise them, rather than reporting the total as","income the position is already receiving.","`estimatedAnnualYieldUsdc` deliberately counts only the interest and any UNCONDITIONAL reward, so on a","market with a conditional programme it is the floor, not the ceiling. If the user asks about yearly","earnings there, give that figure and add that meeting the reward conditions would raise it.","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(e.map(r=>r.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals` \u2014 but ONLY when `totals.mixedAssets` is false; when it is true","the positions are in different assets and cannot be added up, so give no portfolio total and let the","per-position amounts stand. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function Xf(n){if(new Set(n.map(a=>a.asset.symbol??a.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let r=n.reduce((a,i)=>a+i.suppliedUsdc,0),o=n.filter(a=>a.avgApyPercent!==null),s=o.reduce((a,i)=>a+i.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:n[0]?.asset.symbol??null,suppliedUsdc:ye(r,mn),estimatedAnnualYieldUsdc:ye(n.reduce((a,i)=>a+(i.estimatedAnnualYieldUsdc??0),0),mn),weightedAvgApyPercent:ye(s>0?o.reduce((a,i)=>a+i.suppliedUsdc*i.avgApyPercent,0)/s:null,De)}}var lo=class extends A{name="open-supply-usdc-form";kind="ui";category="lending-action";description='Open the SUPPLY form so the user can DEPOSIT into a specific lending market and start earning yield. This is the tool for a supply COMMAND: the user names a market and tells you to act on it, in any wording and any language \u2014 "supply USDC to Aave", "deposit 100 USDC into Compound", "n\u1EA1p USDC v\xE0o Morpho", a bare "Supply Aave", or a tapped "Supply \u2026" button. A supply verb plus a market name is already a complete command; terseness is not ambiguity, and the words the user left out are supplied by context rather than looked up. Each market deposits its OWN asset (usually USDC), resolved from the market itself \u2014 so a message that names no asset is still this tool: resolve the market from whatever the user did name. An amount is optional. Pass `market` \u2014 the market name or protocol exactly as it was shown to them (e.g. "Aave v3 USDC", "Spark"), and `amount` ONLY when they named one. Supports Aave v3, Compound v3, Spark and Morpho vaults, on whichever chains currently carry them \u2014 that set is resolved at call time, so never refuse a chain from memory. PRECONDITION: a connected wallet. The boundary is command vs question: use this to ACT on one market; to LIST or compare markets \u2192 get-lending-markets; for what the wallet already supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to supply to \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the message names, INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for; whether it carries markets is checked at call time. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`Amount to pre-fill, in the market's own asset, as a plain decimal ("100", "25.5"). Pass ONLY when the user named an amount. Omit otherwise \u2014 the user types it in the form. Never invent or convert an amount.`,required:!1}];service;moralis;constructor(e){super(),this.service=new dt(e),this.moralis=new O(e?.moralis)}async run(e,t){let r=t?.walletAddress;if(!r)return{error:"wallet_not_connected",_instructions:"Supplying moves real funds, so it needs a connected wallet. Ask the user to connect one, in their language. Do NOT render a form and do NOT mention tool names."};let s=K(e.chain,void 0)??I(t?.chain);if(!s)return{error:"no_chain",_instructions:"No chain could be determined for the supply. Ask the user which chain they want to supply on, naming the supported ones. Do NOT mention tool names."};if(!await this.service.isSupported(s)){let b=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:T(s),chainsWithLendingMarkets:b.map(y=>T(y)),_instructions:`There are no lending markets on ${T(s)}, so nothing can be supplied there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let a=ai(e.market);if(!a)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let i=await this.service.findMarket(s,a);if(i.length===0)return{error:"market_not_found",market:a,chain:T(s),_instructions:`No lending market matching "${a}" exists on ${T(s)}. Tell the user in their language and offer to list the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(i.length>1)return{error:"ambiguous_market",market:a,chain:T(s),candidates:i.map(b=>({marketName:b.name,protocol:b.protocol})),_instructions:`"${a}" matches ${i.length} different markets on ${T(s)}, so the supply cannot target one yet. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+a+`" and chain for ${T(s)}, plus the localized detail-button templates \u2014 that shows the user each market as a card with its live APY. Tapping one opens that market's full figures, and the supply is started from there. Write no message of your own before that call.`};let l=i[0];if(!this.service.supply.canSupply(l))return{error:"unsupported_protocol",marketName:l.name,protocol:l.protocol,_instructions:`Supplying to ${l.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let c=await this.describeOne(s,l),d=Qf(c);if(!d)return{error:"asset_unresolved",marketName:l.name,chain:T(s),_instructions:`The asset ${l.name} lends could not be read just now, so the supply cannot be prepared safely. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT guess the asset, do NOT name USDC, and do NOT mention tool names.`};let[u,p]=await Promise.all([this.assetBalance(r,s,d.address),this.service.readReceiptToken(s,l)]);if(u&&sn(u.amount,"0")<=0)return{error:"no_asset_balance",marketName:l.name,chain:T(s),assetSymbol:d.symbol,assetBalance:"0",_instructions:`The user has no ${d.symbol} available to supply to ${l.name} on ${T(s)}. In the user's language, tell them plainly that they have no ${d.symbol} available on this chain and need to add some before they can supply. Do NOT show any amount form, do NOT invent a balance, and do NOT state a specific balance figure. Keep it to one or two short sentences. Do NOT mention tool names.`};let m=Jf(e.amount),f=m?Dt(m,d.decimals):null;if(f&&u&&sn(f,u.amount)>0)return{error:"insufficient_asset_balance",marketName:l.name,chain:T(s),assetSymbol:d.symbol,requestedAmount:m,assetBalance:u.amount,_instructions:`The user wants to supply ${m} ${d.symbol} to ${l.name}, but they only hold ${u.amount} ${d.symbol} on ${T(s)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${m} ${d.symbol} exceeds their balance of ${u.amount} ${d.symbol} on this chain, then ask them to enter a smaller amount or add more. Do NOT open any amount form and do NOT invent figures. Keep it to one or two short sentences. Do NOT mention tool names.`};let h={action:"supply_usdc",chainId:s,chainName:T(s),walletAddress:r,market:{name:l.name,type:l.type,protocol:l.protocol,protocolUrl:c?.protocolUrl??ei(l),contract:l.contract,token:l.token,apyPercent:c?.currentApyPercent??c?.avgApyPercent??null,receiptToken:p},asset:d,...f?{prefillAmount:f}:{},...u?{spendable:u.amount}:{},...u?.usd?{spendableUsd:u.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:h},marketName:l.name,protocol:l.protocol,chain:T(s),apyPercent:ye(h.market.apyPercent,De),assetSymbol:d.symbol,assetBalance:u?.amount??null,_instructions:this.instructions(l,d.symbol)}}async describeOne(e,t){try{let[r]=await this.service.describeResolvedMarkets(e,[t]);return r??null}catch{return null}}async assetBalance(e,t,r){try{let o=await this.moralis.getWalletTokenBalances({address:e,chain:t,tokenAddresses:[r]});if(!o.success)return null;let s=(o.data?.result??[]).find(i=>(i.token_address||"").toLowerCase()===r.toLowerCase());if(!s?.balance_formatted)return{amount:"0",usd:null};let a=typeof s.usd_value=="number"?String(s.usd_value):null;return{amount:String(s.balance_formatted),usd:a}}catch{return null}}instructions(e,t){return[`The supply action for ${e.name} is ready.`,`In the user's language, invite them to enter the amount of ${t} they want to supply, naming the`,"market and the chain.",`Speak ONLY of the action the USER takes (supplying / depositing ${t}). NEVER say you "opened a form",`,'"opened" anything, or describe any screen, form, window or UI \u2014 phrase it as their next step, not something',"you did.","Do NOT state their balance, the contract address or any figure from the form; it is all on screen already.","Keep it to one or two short sentences. Add a brief note that supplying carries protocol risk and rates","float \u2014 information, not financial advice.","Do NOT mention tool names."].join(" ")}};function Qf(n){let e=n?.asset;return!e?.address||e.address===Yn||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function Jf(n){let e=typeof n=="string"?n.trim():typeof n=="number"?String(n):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}var ii="https://ipfs.pantograph.app/ipfs/",wd=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function Kn(n){let e=n?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${ii}${t[1]}`:wd.test(e)?`${ii}${e}`:null}function kd(n){let e=n?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${ii}${t[1]}`:wd.test(e)?`${ii}${e}`:null}function vd(n){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(n)}function nc(n){if(!n||typeof n!="object")return;let e=n,t=e.image??e.image_url??e.imageUrl;return typeof t=="string"&&t.trim()?t.trim():void 0}function Zf(n){if(typeof atob=="function"){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return new TextDecoder().decode(t)}if(typeof Buffer<"u")return Buffer.from(n,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function eg(n){let e=n.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let t=e[1]??"",r=e[2]??"";try{let o=/;base64/i.test(t)?Zf(r):decodeURIComponent(r);return JSON.parse(o)}catch{try{return JSON.parse(r)}catch{return null}}}function Td(n){let e=n?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=eg(e);return t?Kn(nc(t)):null}var tg=12,ng=6e3;async function rg(n,e,t){let r=new Array(n.length),o=0,s=new Array(Math.max(1,Math.min(e,n.length))).fill(0).map(async()=>{for(;o<n.length;){let a=o++;r[a]=await t(n[a],a)}});return await Promise.all(s),r}async function og(n,e){try{let t=await C.get(n,{timeout:e});if(!t.ok)return null;let r=t.data;if(r&&typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{return null}return null}catch{return null}}async function sg(n,e){let t=n?.trim();if(!t)return null;if(/^data:/i.test(t))return Td(t);let r=kd(t);if(!r)return null;if(vd(r))return r;let o=await og(r,e);if(o){let s=Kn(nc(o));if(s)return s}return null}async function li(n,e,t){if(e.length===0)return[];let r=t?.concurrency??tg,o=t?.timeoutMs??ng,s=await Tu(n,e,t?.rpcUrl);return rg(s,r,a=>sg(a,o))}var Ad=100,ag=100,co="{name}",Pd="{chain}",uo=class extends A{name="get-wallet-nfts";description=`Show the NFTs a wallet holds. Call with NO contract_address for a general request ("my NFTs", "show my NFTs", "what NFTs do I own") \u2014 it lists the wallet's NFT collections and renders a picker button per collection. Call WITH contract_address (and collection_name when known) once the user has named or picked a collection \u2014 it then lists that collection's NFTs with image, name and token id. Do NOT use for: sending an NFT \u2192 open-send-nft-form; details about one specific NFT \u2192 get-nft-metadata; info about a collection the wallet does not hold \u2192 get-nft-contract-info.`;category="nft";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID (e.g. "0x1" Ethereum, "0x89" Polygon, "0x2105" Base). ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, all supported chains are queried.',required:!1},{name:"contract_address",type:"string",description:'NFT COLLECTION contract address (0x\u2026) to list the NFTs of. Set this ONLY when the user named a specific collection or clicked a collection button (their message then contains the address). OMIT it for a general "show my NFTs" request \u2014 that lists the collections to pick from.',required:!1},{name:"collection_name",type:"string",description:'Collection name as the user said it (e.g. "Bored Ape Yacht Club"). Used to find the collection when the user named one WITHOUT an address. Omit when unknown.',required:!1},{name:"pick_button_label",type:"string",description:`Label template for the per-collection picker buttons, IN THE USER'S CURRENT LANGUAGE. Use the exact placeholder "{name}" (do not translate the braces); it is replaced with the collection name. The label should be JUST the name \u2014 pass "{name}" unless a different wording is clearly better.`,required:!1},{name:"pick_prompt_template",type:"string",description:`A short "show this collection" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a collection button is clicked. Use TWO exact placeholders (do not translate the braces): "{name}" (the collection name) and "{chain}" (the network name, e.g. Optimism). Place {chain} where it reads naturally in the user's language, with the connector word in THAT language. English example: "show my {name} NFTs on {chain}". Vietnamese example: "xem NFT {name} c\u1EE7a t\xF4i tr\xEAn {chain}". Always include BOTH {name} and {chain}. Do NOT add the contract address yourself \u2014 it is appended automatically.`,required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let r=le(e.address,t),o=K(e.chain,t),s=o?[o]:qe(),a=pg(e.contract_address),i=Cd(e.collection_name);return a||i?this.listNfts({address:r,chains:s,singleChain:!!o,contract:a,collectionName:i}):this.listCollections({address:r,chains:s,singleChain:!!o,args:e})}async listCollections(e){let{address:t,chains:r,singleChain:o,args:s}=e,a=await Promise.all(r.map(async c=>{let d=await this.service.getWalletNftCollections({address:t,chain:c,limit:Ad});return{chain:c,rows:d.success?Sd(d.data?.result??[]):[],ok:d.success}}));if(o&&!a[0].ok)return{error:"Failed to fetch wallet NFT collections"};let i=a.flatMap(c=>c.rows.map(d=>({name:lg(d),contractAddress:d.token_address,chain:T(c.chain),nftCount:d.count??null})));if(i.length===0)return{_instructions:"The wallet holds no NFT collections"+(o?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:t,collectionCount:0,collections:[]};let l=ug(i,s);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:t,collectionCount:i.length,collections:i,...l.length>0?{actionButtons:l}:{}}}async listNfts(e){let{address:t,chains:r,singleChain:o,contract:s,collectionName:a}=e,i=await Promise.all(r.map(async m=>{let f=await this.service.getWalletNFTs({address:t,chain:m,limit:Ad,...s?{tokenAddresses:[s]}:{}});return{chain:m,rows:f.success?Sd(f.data?.result??[]):[],ok:f.success}}));if(o&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(m=>m.rows.filter(f=>ig(f,{contract:s,collectionName:a})).map(f=>({chain:m.chain,row:f})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${a??s??""}"`+(o?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||a||l[0].row.token_address,d=await this.resolveOnchainImages(l),u=l.map(({chain:m,row:f},h)=>{let g=cg(f);return{name:g.name,tokenId:g.tokenId,contractAddress:g.contractAddress,image:d[h]??g.image,chain:T(m)}});return{ui:{component:"WalletNftList",props:{walletAddress:t,collectionName:c,nfts:u}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:t,collectionName:c,nftCount:l.length}}async resolveOnchainImages(e){let t=new Array(e.length).fill(null),r=new Map;e.forEach((o,s)=>{let a=r.get(o.chain)??[];a.push(s),r.set(o.chain,a)});try{await Promise.all([...r.entries()].map(async([o,s])=>{let a=s.map(l=>({contract:e[l].row.token_address,tokenId:e[l].row.token_id})),i=await li(o,a);s.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function Sd(n){return n.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function ig(n,e){if(e.contract)return n.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let t=e.collectionName.toLowerCase();return(n.name??"").toLowerCase().includes(t)}return!1}function lg(n){let e=n.name?.trim();if(e)return e;let t=n.token_address??"";return t.length>10?`${t.slice(0,6)}\u2026${t.slice(-4)}`:t}function cg(n){return{name:n.normalized_metadata?.name||n.name||`#${n.token_id}`,tokenId:n.token_id,contractAddress:n.token_address,image:Kn(n.normalized_metadata?.image||n.media?.original_media_url)}}function ug(n,e){let t=typeof e.pick_button_label=="string"?e.pick_button_label:"",r=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",o=[];for(let s of n){if(o.length>=ag)break;if(!s.contractAddress)continue;let a=typeof s.chain=="string"?s.chain.trim():"",i=a?`show my ${co} NFTs on ${Pd}`:`show my ${co} NFTs`,l=xd(r,{[co]:s.name,[Pd]:a},i);a&&!l.includes(a)&&(l=`${l} (${a})`),o.push({label:dg(t,s.name,co),prompt:`${l} (${s.contractAddress})`})}return o}function xd(n,e,t){let r=n&&n.includes(co)?n:t;for(let[o,s]of Object.entries(e))r=r.split(o).join(s);return r.replace(/\s+/g," ").trim()}function dg(n,e,t){return xd(n,{[co]:e},t)}function Cd(n){if(typeof n!="string")return;let e=n.trim();return e||void 0}function pg(n){let e=Cd(n);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var mg="You are an NFT research analyst with live Google Search grounding. Base every factual claim (floor price, volume, holders, traits, sales, dates) on up-to-date search results and note the source. NEVER invent floor prices, volumes, token ids, or contract addresses \u2014 if the data is not available, state that plainly rather than guessing.",St=class extends A{kind="data";category="nft";llm;constructor(e){super(),this.llm=new ke(e??{})}static promptParams(e){return[{name:"prompt",type:"string",description:e,required:!0}]}async run(e){let t=typeof e.prompt=="string"?e.prompt.trim():"";if(!t)return{error:"Missing required parameter: prompt"};let r=await this.askGeminiWithSearch(t);return r?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:r}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(e){let t=Date.now();try{return(await this.llm.chat([{role:"system",content:mg,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var po=class extends St{name="get-nft-contract-info";description='Get information about an NFT COLLECTION / contract \u2014 name, symbol, token standard (ERC-721/1155), current floor price, total supply, holder count, recent trading volume, and official website / socials. Use when the user asks about a collection ("tell me about Bored Apes", "floor of Azuki", "is X collection legit"). Answers from live web data via the `prompt`.';parameters=St.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the collection. Cover the collection: its contract address, token standard, current floor price, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks. Example: "Research the Azuki NFT collection on Ethereum using up-to-date web sources. Report its contract address, token standard, current floor price in ETH, total supply, holder count, recent trading volume, official website and social links, and any notable news or risks."`);presentInstructions="Present the collection info clearly: name, contract address, token standard, current floor price, total supply, holder count, recent volume, official links, and any notable news or risks."};var mo=class extends St{name="get-nft-metadata";description='Get details about a SPECIFIC NFT \u2014 its traits, rarity, image, the collection it belongs to, current floor price, and recent sales. Use when the user asks about ONE NFT ("show NFT #1234 of collection X", "traits of this NFT", "floor price of this NFT"). Answers from live web data via the `prompt`.';parameters=St.promptParams(`A rich, self-contained research prompt sent to Gemini with Google Search grounding (real-time web). Gemini does NOT see the user's original message \u2014 embed everything: the collection name AND/OR contract address and the token id, plus an instruction to use up-to-date web sources. Do NOT worry about which chain \u2014 let Gemini find the NFT. Cover the specific NFT: its traits/attributes and rarity, the collection it belongs to, the current collection floor price, and the most recent sale price if available. Example: "Look up NFT #1234 in the Bored Ape Yacht Club collection (contract 0xBC4CA0E\u2026) on Ethereum using up-to-date web sources. Report its traits and rarity rank, the current collection floor price in ETH, the most recent sale price if available, and any notable details about this specific token."`);presentInstructions="Present the NFT details clearly: the collection and token id, its traits/rarity, the current floor price, recent sale(s), and any notable points."};var rc={en:"amazon.com",zh:"amazon.cn",ja:"amazon.co.jp",de:"amazon.de",es:"amazon.es",fr:"amazon.fr",it:"amazon.it",ko:"amazon.com",nl:"amazon.nl",pl:"amazon.pl",pt:"amazon.es",ru:"amazon.com",th:"amazon.com",tr:"amazon.com.tr",vi:"amazon.com"},oc="amazon.com";function hg(n){return n?n.trim().toLowerCase().split(/[-_]/)[0]:""}function sc(n){let e=hg(n);return rc[e]??oc}function ci(n){return`https://${sc(n)}/s?k=NFC%20Tag`}function ui(n){if(!n)return"";let e=n.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var fg=720*60*1e3,Rd=new Map,Ed=3;function gg(n){return[`A user in country "${n}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Ed} LARGEST / most popular e-commerce marketplaces in`,"THAT country where a regular consumer can buy NFC tags. For each store give its brand name and a","search URL that, opened TODAY, lands directly on a page LISTING NFC-tag products for sale.","CRITICAL about the URL:","- Use the store's CURRENT, official, live domain. Do NOT use domains that have been shut down,"," merged, rebranded or moved (e.g. an old service folded into a new one) \u2014 verify via search that"," the domain still serves search results today.","- Use that site's real, current search endpoint and query parameter (e.g. Amazon /s?k=, Shopee"," /search?keyword=, Rakuten /search/mall/<query>/). Prefer the simplest official search URL.","- The URL must return actual product results for the query, not a homepage, category page, login,"," 404 or empty page. Prefer the local storefront/domain for that country. URL-encode the query.","Return ONLY a compact JSON array, no prose, no markdown fences, of the form:",'[{"label":"Shopee","url":"https://shopee.vn/search?keyword=NFC%20Tag"}]',"Use https URLs only. Do not invent stores or URLs you cannot confirm operate in that country."].join(" ")}function yg(n){if(!n)return[];let e=n.indexOf("["),t=n.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let r;try{r=JSON.parse(n.slice(e,t+1))}catch{return[]}if(!Array.isArray(r))return[];let o=[],s=new Set;for(let a of r){if(!a||typeof a!="object")continue;let i=a.label,l=a.url;if(typeof i!="string"||!i.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!s.has(c)&&(s.add(c),o.push({label:i.trim(),url:l.trim()}),o.length>=Ed))break}return o}async function ac(n,e){let t=ui(n);if(!t||!e)return null;let r=Rd.get(t);if(r&&r.expires>Date.now())return r.links;let o=Date.now(),s=[{role:"user",content:gg(t),timestamp:o}];try{let a=await e.chat(s,void 0,{googleSearch:!0,maxRetries:1}),i=yg(a.text);if(i.length)return Rd.set(t,{links:i,expires:Date.now()+fg}),i}catch{}return null}async function ho(n){let e=await ac(n.country,n.llm);return e&&e.length?e:[{label:"Amazon",url:ci(n.language)}]}function bg(n){return n.length<=1?n.length===1?`[${n[0].label}](${n[0].url})`:"":n.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
40
40
  `)}var _d=["WHAT IT IS: NFC (Near-Field Communication) is a short-range wireless standard operating at 13.56 MHz, a",'subset of the older RFID family. An "NFC tag" is a tiny passive chip + antenna (often embedded in a','sticker, card, keyfob, wristband, or ring). "Passive" means it has no battery \u2014 it draws all its power from',"the electromagnetic field of the reader (a smartphone or dedicated reader) when held within ~2\u20134 cm. The","tag does nothing on its own; it simply waits to be tapped, then hands over the small piece of data it holds.","","HOW IT WORKS: When an NFC-enabled phone comes close, the reader emits a 13.56 MHz radio field. Through","inductive (magnetic) coupling that field powers the tag, which then transmits its stored data back to the","reader \u2014 no pairing, no app launch, no internet required for the handshake. The exchange is bidirectional","and near-instant (well under a second). Tags can be READ many times and, unless locked, also re-WRITTEN.","Data is stored in the standardised NDEF format (NFC Data Exchange Format) so any NFC phone can parse it the","same way. NFC works in three modes: reader/writer (phone reads or writes a tag), peer-to-peer (two devices","exchange data), and card-emulation (the phone itself acts like a tag, e.g. for tap-to-pay).","","WHAT'S INSIDE AN NFC TAG: just two parts \u2014 (1) a microchip (the integrated circuit) that holds a small","block of memory plus simple logic, and (2) a thin coiled antenna (usually etched copper or aluminium) that","both harvests power from the reader's field and carries the data signal. There is no battery and no moving","parts, which is why tags are paper-thin, cheap, and last for years (often rated for ~10 years of storage","and 100,000+ rewrites). Common chips differ mainly by memory size: NTAG213 (~144 bytes), NTAG215","(~504 bytes), NTAG216 (~888 bytes); larger/industrial families (e.g. ICODE, MIFARE) add more memory or","security features.","","WHAT IT CAN STORE: capacity is small \u2014 tens to a few hundred bytes of usable memory \u2014 so a tag holds a","compact payload, not files. Typical contents: a website URL, plain text, a contact card (vCard), Wi-Fi","credentials (SSID + password for one-tap join), an app-launch or deep link, a phone number / email,","geo-coordinates, a Bluetooth pairing handoff, or a small identifier/token. It is NOT mass storage \u2014 large","content lives elsewhere and the tag holds a pointer (a link or ID) to it.","","COMMON REAL-WORLD USES: contactless payments (Apple Pay / Google Pay via card emulation); transit and","access cards (metro, office door badges, hotel keys); product tags and anti-counterfeit / authenticity","checks; smart posters and marketing (tap to open a page, menu, or promo); pairing speakers/headphones with",'one tap; digital business cards and "tap to share contact"; smart-home automations (tap a tag by the door',"to run a routine); inventory, asset tracking, and ticketing; and tap-to-act crypto flows (e.g. open a","wallet address or a dapp link).","","HOW TO USE ONE: (1) Get an NFC tag (sticker/card/keyfob). (2) Make sure the phone has NFC enabled","(Settings \u2192 Connections/NFC; most modern Android phones and iPhone XS and later support it). (3) To WRITE,",'install an NFC writer app (e.g. "NFC Tools"), choose the record type (URL, text, Wi-Fi\u2026), enter the data,',"and tap the phone to the tag to program it. (4) To READ, just tap the phone to the tag \u2014 the action fires","automatically. (5) Optionally LOCK the tag to make it read-only so the data cannot be overwritten. Keep the","tag away from metal surfaces, which can detune the antenna and block reads.","","WHY THEY ARE POPULAR: they are extremely cheap (cents each), battery-free and maintenance-free, work with","the phone almost everyone already carries, and need just a tap \u2014 no app pairing, codes, or setup. The very","short range is a feature, not a bug: you must deliberately bring the devices together, which makes NFC","trusted for payments and access where accidental or remote reads would be a security risk.","","CRYPTO / WALLET CONTEXT: because a tag can hold a short identifier or address, NFC is handy for tap-to-act","flows \u2014 e.g. encoding a public wallet address or a deep link. Private keys/seed phrases should never be","written to an open, re-writable tag; treat tags as public, tamper-readable pointers, not secure key vaults.","","PRACTICAL TIPS: re-writable blank tags are inexpensive; pick a chip with enough memory for the payload",'(NTAG215+ for longer URLs or vCards). Use a metal-shielded ("on-metal") tag if you must stick it to a',"metal surface. Range is intentionally tiny (a few cm) for security \u2014 you must deliberately tap."].join(`
41
41
  `),fo=class extends A{kind="data";name="nfc-info";category="nfc";description='Use when the user asks a conceptual / how-to question about NFC tags \u2014 what an NFC tag is, how NFC works, what data a tag can store, tag types/capacity, or how to read/write/use one ("what is an NFC tag", "how does NFC work", "what can I store on an NFC tag", "how do I use an NFC tag"). Returns an expert reference to answer from, plus a country-appropriate Amazon buy link to close with. Pass the current turn\'s BCP-47 `language` so the right storefront is picked. For a pure "where to buy" question with no explanation needed, prefer nfc-buy-link.';parameters=[{name:"language",type:"string",description:`The BCP-47 language tag of the user's current message (e.g. "en", "vi", "ja", "zh", "de"). Used only to pick the local Amazon storefront for the closing buy link. Optional (defaults to amazon.com).`,required:!1}];llm;constructor(e){super(),e&&(this.llm=new ke(e))}async run(e,t){let r=typeof e.language=="string"&&e.language.trim()?e.language.trim():void 0,o=await ho({country:t?.country,language:r,llm:this.llm}),s=bg(o),a=o.length>1;return{reference:_d,marketplaceLinks:o,_instructions:`Answer the user's NFC question as a knowledgeable, friendly expert, writing in the USER'S language (translate naturally \u2014 never leave it in English when they wrote another language). Draw on the reference below for the facts (do NOT invent anything beyond it), but write a polished, well-organized answer \u2014 not a terse one-liner. FORMAT: Use short Markdown section headings (bold or "##") and bullet points so it is easy to scan, similar to a great encyclopedia entry. For a broad question like "what is an NFC tag", give a thorough multi-section answer: open with a 1\u20132 sentence plain-language definition, then cover sections such as "How it works", "What's inside", "What it can store", "Common uses", "How to use one", and "Why they're popular" \u2014 include concrete specifics (the 13.56 MHz frequency, chip names + byte capacities, example payloads, numbered steps). Aim for genuinely useful depth, several short paragraphs/lists, not a wall of dense text. For a NARROW question (e.g. only "what can it store" or "how do I write one"), answer just that part in focused detail and skip the unrelated sections. Do not mention tools, this reference, or that anything is canned. AT THE END, add a short closing line telling them where they can buy NFC tags, then include EACH of these exact CLICKABLE Markdown links `+(a?"as a NUMBERED Markdown list (1., 2., 3.), ONE store per line, in this exact order and numbering":"inline")+` (keep every URL byte-for-byte; localize only the visible text; keep the form [text](url)):
42
42
  ${s}
@@ -140,7 +140,7 @@ ${qd}`,Lg=`query V4Pool($chain: Chain!, $poolId: String!) {
140
140
  __typename
141
141
  }
142
142
  }
143
- ${qd}`,fn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114,"0xe708":59144};function Bs(n){return new Promise(e=>setTimeout(e,n))}async function Id(n,e,t){let r;return Promise.race([n,new Promise(o=>{r=setTimeout(()=>o(t),e)})]).finally(()=>clearTimeout(r))}function hi(n){if(!n)return 1;let e=n.toLowerCase();return fn[e]??1}function ic(n){if(!n)return"ETHEREUM";let e=n.toLowerCase();return Bd[e]??"ETHEREUM"}var Ig=Object.fromEntries(Object.entries(fn).map(([n,e])=>[e,n]));function $d(n){if(typeof n!="number")return;let e=Ig[n];return e?Bd[e]:void 0}function Ug(n){if(typeof n!="string")return;let e=n.replace("PROTOCOL_VERSION_","").toUpperCase();return e==="V2"||e==="V3"||e==="V4"?e:void 0}function Dg(n){switch(n){case"volume1Day":return"POOLS_ORDER_BY_VOLUME_1D";case"volume30Day":return"POOLS_ORDER_BY_VOLUME_30D";case"apr":return"POOLS_ORDER_BY_APR";case"tvl":return"POOLS_ORDER_BY_TVL";default:return}}function Ud(n){let e=n.pool,t=e?.poolId?.trim();if(!e||!t)return;let r=n.stats??{},o=Ug(e.protocolVersion),s=$d(e.chainId),a=di(e.feeTier,e.protocolFee,o);return{id:t,chain:s,protocolVersion:o,feeTier:e.feeTier,isDynamicFee:e.isDynamicFee,totalLiquidity:gn(r.tvl),volume1Day:gn(r.volume1d),volume30Day:gn(r.volume30d),apr:$(r.apr),totalApr:$(r.totalApr),volumeToTvlRatio:typeof r.volume1dTvlRatio=="number"?r.volume1dTvlRatio:void 0,lpFeeShare:a,fee24hUsd:pi(r.volume1d,e.feeTier,a),token0:Md(e.token0),token1:Md(e.token1)}}function gn(n){return typeof n=="number"&&Number.isFinite(n)?{value:n,currency:"USD"}:void 0}function lc(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string"||n.trim()==="")return;let e=Number(n);return Number.isFinite(e)?e:void 0}function Dd(n,e,t,r){if(!n&&!e&&!r)return;let o=lc(t);return{...r,address:e??r?.address,symbol:n?.symbol??r?.symbol,name:n?.name??r?.name,decimals:n?.decimals??r?.decimals,logo:n?.logoUrl??r?.logo,price:gn(o)??r?.price,market:o!==void 0?{price:gn(o)}:r?.market,project:r?.project}}function Od(n,e){let t=n.poolIdentifier,r=n.protocolVersion==="V4",o=n.hookAddress&&n.hookAddress!==Eg?n.hookAddress:e?.hook?.address??void 0;return{id:e?.id,protocolVersion:n.protocolVersion??e?.protocolVersion,address:r?e?.address:t??e?.address,poolId:r?t??e?.poolId:e?.poolId,feeTier:n.feeTier??e?.feeTier,tickSpacing:n.tickSpacing??e?.tickSpacing,isDynamicFee:n.isDynamicFee??e?.isDynamicFee,hook:o?{address:o}:void 0,totalLiquidity:gn(n.tvlUsd)??e?.totalLiquidity,totalLiquidityPercentChange24h:gn(n.tvlUsdChange1d)??e?.totalLiquidityPercentChange24h,volume24h:gn(n.volumeUsd1d)??e?.volume24h,token0Supply:lc(n.token0Supply)??e?.token0Supply,token1Supply:lc(n.token1Supply)??e?.token1Supply,txCount:e?.txCount,historicalVolume:e?.historicalVolume,token0:Dd(n.token0Metadata,n.token0Address,n.token0PriceUsd,e?.token0),token1:Dd(n.token1Metadata,n.token1Address,n.token1PriceUsd,e?.token1),protocolFee:n.protocolFee,apr:$(n.apr),totalApr:$(n.totalApr),currentTick:n.currentTick,sqrtPriceX96:n.sqrtPriceX96,liquidity:n.liquidity}}function Md(n){if(n)return{chain:$d(n.chainId),address:n.address,symbol:n.symbol,name:n.name,decimals:n.decimals,standard:n.type?.replace("TOKEN_TYPE_",""),logo:n.project?.logoUrl,project:n.project?.logoUrl?{logo:{url:n.project.logoUrl}}:void 0}}function Fd(n,e){switch(e){case"volume1Day":return n.volume1Day?.value??0;case"volume1Week":return n.volume1Week?.value??0;case"volume30Day":return n.volume30Day?.value??0;case"txCount":return n.txCount??0;case"apr":return n.apr??n.totalApr??0;default:return n.totalLiquidity?.value??0}}var $e=class{baseUrl;searchBaseUrl;liquidityBaseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Tg).replace(/\/$/,""),this.searchBaseUrl=(e?.searchBaseUrl??Pg).replace(/\/$/,""),this.liquidityBaseUrl=(e?.liquidityBaseUrl??Cg).replace(/\/$/,"")}isSupported(e){if(!e)return!1;let t=D(e)??e.toLowerCase();return Object.prototype.hasOwnProperty.call(fn,t)}listSupportedChains(){return Object.keys(fn).filter(e=>Be(e))}async listPools(e){let t=await this.listPoolsPage(e);return t.success?{success:!0,data:t.data?.pools??[]}:{success:!1,error:t.error}}async listPoolsPage(e){if(e.chainIds.length===0)return{success:!1,error:"At least one chain is required"};let t=`${this.searchBaseUrl}${Sg}`,r=JSON.stringify({chainIds:e.chainIds,sort:{orderBy:e.orderBy,ascending:e.ascending===!0},filter:{protocolVersions:e.protocolVersions.map(s=>`PROTOCOL_VERSION_${s}`),includeSpam:e.includeSpam===!0,applyTopLevelFilters:!0},page:{pageSize:Math.min(Math.max(Math.floor(e.pageSize),1),mi),...e.pageToken?{pageToken:e.pageToken}:{}}}),o="Unknown error";for(let s=1;s<=xt;s++)try{let a=await C.post(t,r,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!a.ok)throw new Error(_(a));let i=a.data;return{success:!0,data:{pools:i.pools??[],nextPageToken:i.page?.nextPageToken||void 0}}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<xt&&await Bs(Fs)}return{success:!1,error:o}}async listAllPools(e){let t=[],r=new Set,o;for(let s=0;s<xg;s++){let a=await this.listPoolsPage({...e,pageToken:o});if(!a.success||!a.data){if(s===0)return{success:!1,error:a.error||"Failed to fetch pools"};break}t.push(...a.data.pools);let i=a.data.nextPageToken;if(!i||a.data.pools.length===0||r.has(i))break;r.add(i),o=i}return{success:!0,data:t}}async getTopPools(e){let t=e?.protocolVersion??"V3",r=e?.limit&&e.limit>0?Math.floor(e.limit):10,o=e?.sortBy??"tvl",s=e?.multichain?Object.values(fn):[hi(e?.chain)],a=Dg(o),i=a?Math.min(r,mi):mi,l=await this.listPools({chainIds:s,protocolVersions:[t],orderBy:a??"POOLS_ORDER_BY_TVL",pageSize:i});return!l.success||!l.data?{success:!1,error:l.error||"Failed to fetch pools"}:{success:!0,data:l.data.map(u=>Ud(u)).filter(u=>u!==void 0).sort((u,p)=>Fd(p,o)-Fd(u,o)).slice(0,r)}}async getPool(e){let t=e.addressOrId?.trim();if(!t)return{success:!1,error:"Pool address or id is required"};let r=`${this.liquidityBaseUrl}${Rg}`,o=JSON.stringify({pool:{chainId:hi(e.chain),addressOrId:t}}),s="Unknown error";for(let a=1;a<=xt;a++)try{let i=await C.post(r,o,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(i.status===404)return{success:!1,error:"Pool not found"};if(!i.ok)throw new Error(_(i));let l=i.data?.pool;return l?{success:!0,data:l}:{success:!1,error:"Pool not found"}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<xt&&await Bs(Fs)}return{success:!1,error:s}}async getV3PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V3Pool",query:_g,variables:{chain:ic(e.chain),address:t},pickField:"v3Pool"}):{success:!1,error:"Pool address is required"}}async getV2PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V2Pair",query:Ng,variables:{chain:ic(e.chain),address:t},pickField:"v2Pair"}):{success:!1,error:"Pair address is required"}}async getV4PoolDetail(e){let t=e.poolId?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V4Pool",query:Lg,variables:{chain:ic(e.chain),poolId:t},pickField:"v4Pool"}):{success:!1,error:"V4 poolId is required"}}async getPoolDetailEnriched(e){let t=await this.getPool(e);if(!t.success||!t.data)return{success:!1,error:t.error||"Failed to fetch pool detail"};let r=t.data;if(e.enrich===!1)return{success:!0,data:Od(r,void 0)};let o=r.protocolVersion,s=r.poolIdentifier??e.addressOrId.trim(),a=o==="V4"?this.getV4PoolDetail({poolId:s,chain:e.chain}):o==="V2"?this.getV2PoolDetail({address:s,chain:e.chain}):this.getV3PoolDetail({address:s,chain:e.chain}),i=await Id(a.then(l=>l.success?l.data:void 0).catch(()=>{}),Ld,void 0);return{success:!0,data:Od(r,i)}}async fetchPoolDetailGraphQL(e){let t=`${this.baseUrl}${Ag}`,r=JSON.stringify({operationName:e.operationName,variables:e.variables,query:e.query}),o="Unknown error";for(let s=1;s<=xt;s++)try{let a=await C.post(t,r,{headers:{accept:"*/*","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web","_dd-custom-header-graph-ql-operation-name":e.operationName,"_dd-custom-header-graph-ql-operation-type":"query"}});if(!a.ok)throw new Error(_(a));let i=a.data;if(i.errors)throw new Error(`GraphQL error: ${JSON.stringify(i.errors)}`);let l=i.data?.[e.pickField]??void 0;return l?{success:!0,data:l}:{success:!1,error:"Pool not found"}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<xt&&await Bs(Fs)}return{success:!1,error:o}}async searchTokens(e){let t=e.query?.trim();return t?R(t)?{success:!1,error:"Address is invalid for token search. If you pasted a 0x address, it may be a Uniswap pool \u2014 try the pool search tool instead."}:this.fetchSearchTokens({query:t,chain:e.chain,page:e.page,size:e.size}):{success:!1,error:"Search query is required"}}async getTokenSafetyByAddress(e,t){let r=Array.from(new Set(e.filter(s=>typeof s=="string"&&R(s.trim())).map(s=>s.trim()))),o=new Map;return r.length===0||await Id(Promise.all(r.map(async s=>{let a=await this.fetchSearchTokens({query:s,chain:t,size:5});if(!a.success)return;let i=s.toLowerCase(),l=(a.data??[]).find(c=>c.address?.toLowerCase()===i);l&&o.set(i,l)})).catch(()=>{}),Ld,void 0),o}async fetchSearchTokens(e){let t=hi(e.chain),r=e.page&&e.page>0?Math.floor(e.page):1,o=e.size&&e.size>0?Math.min(Math.floor(e.size),50):15,s=`${this.searchBaseUrl}${Nd}`,a=JSON.stringify({searchQuery:e.query,chainIds:[t],searchType:"TOKEN",page:r,size:o}),i="Unknown error";for(let l=1;l<=xt;l++)try{let c=await C.post(s,a,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!c.ok)throw new Error(_(c));return{success:!0,data:c.data.tokens??[]}}catch(c){i=c instanceof Error?c.message:"Unknown error",l<xt&&await Bs(Fs)}return{success:!1,error:i}}async searchPools(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};let r=hi(e.chain),o=e.page&&e.page>0?Math.floor(e.page):1,s=e.size&&e.size>0?Math.min(Math.floor(e.size),50):15,a=e.protocolVersion??"V3",i=e.feeTier&&e.feeTier>0?Math.floor(e.feeTier):void 0,l=`${this.searchBaseUrl}${Nd}`,c=JSON.stringify({searchQuery:t,chainIds:[r],searchType:"POOL",page:o,size:s}),[d,u]=await Promise.allSettled([this.fetchSearchPools(l,c),this.listPools({chainIds:[r],protocolVersions:a==="ALL"?["V2","V3","V4"]:[a],orderBy:"POOLS_ORDER_BY_TVL",pageSize:mi})]);if(d.status==="rejected"||!d.value.success)return{success:!1,error:d.status==="rejected"?String(d.reason):d.value.error??"Failed to search pools"};let p=t.toLowerCase().split(/\s+/).filter(Boolean),m=d.value.data??[];a!=="ALL"&&(m=m.filter(y=>y.protocolVersion===a)),i!=null&&(m=m.filter(y=>y.feeTier===i));let f=new Map,h=new Map,g=new Map;for(let y of m)y.id&&f.set(y.id.toLowerCase(),y);if(u.status==="fulfilled"&&u.value.success&&u.value.data)for(let y of u.value.data){let w=Ud(y);if(!w||i!=null&&w.feeTier!==i)continue;let k=(w.token0?.symbol??"").toLowerCase(),v=(w.token1?.symbol??"").toLowerCase(),S=(w.token0?.name??"").toLowerCase(),P=(w.token1?.name??"").toLowerCase();if(!p.some(z=>k.includes(z)||v.includes(z)||S.includes(z)||P.includes(z)))continue;let I=w.id.toLowerCase(),E=w.totalLiquidity?.value,we=w.volume1Day?.value,V=f.get(I);f.set(I,{...V??{id:w.id,protocolVersion:w.protocolVersion,feeTier:w.feeTier,token0:w.token0?{address:w.token0.address,symbol:w.token0.symbol,name:w.token0.name,decimals:w.token0.decimals}:void 0,token1:w.token1?{address:w.token1.address,symbol:w.token1.symbol,name:w.token1.name,decimals:w.token1.decimals}:void 0},...E!=null?{tvlUsd:E}:{},...we!=null?{volume1DayUsd:we}:{},...w.isDynamicFee===!0||hn(w.feeTier)?{isDynamicFee:!0}:{}}),h.set(I,w.chain),g.set(I,w.apr)}let b=Array.from(f.entries()).sort(([,y],[,w])=>this.matchScore(w,p)-this.matchScore(y,p));for(let[y,w]of b){let k=$(g.get(y));k!=null&&(w.apr=k)}return{success:!0,data:b.map(([,y])=>y)}}async fetchSearchPools(e,t){let r="Unknown error";for(let o=1;o<=xt;o++)try{let s=await C.post(e,t,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!s.ok)throw new Error(_(s));return{success:!0,data:s.data.pools??[]}}catch(s){r=s instanceof Error?s.message:"Unknown error",o<xt&&await Bs(Fs)}return{success:!1,error:r}}matchScore(e,t){let r=[e.token0?.symbol??"",e.token1?.symbol??""].map(s=>s.toLowerCase()),o=0;for(let s of t){let a=0;for(let i of r)i===s?a=Math.max(a,3):i.startsWith(s)?a=Math.max(a,2):i.includes(s)&&(a=Math.max(a,1));o+=a}return o}};var Hd=2n**96n;function Se(n,e=8){return!Number.isFinite(n)||n===0?n:Number(n.toPrecision(e))}function Vd(n,e,t){let r=n*n,o=Hd*Hd,s=r*10n**18n/o;return Number(s)/1e18*Math.pow(10,e-t)}function pt(n,e,t){return Math.pow(1.0001,n)*Math.pow(10,e-t)}function jn(n,e,t){if(n<=0)throw new Error("priceToTick: price must be > 0");let r=n/Math.pow(10,e-t),o=Math.log(r)/Math.log(1.0001),s=Math.round(o);return Math.abs(o-s)<.001?s:Math.floor(o)}function ko(n,e,t){let r={minPrice:n,maxPrice:e,inverted:!1};if(!Number.isFinite(n)||!Number.isFinite(e)||!Number.isFinite(t)||n<=0||e<=0||t<=0||n>=e)return r;let o={minPrice:1/e,maxPrice:1/n,inverted:!0},s=c=>t>=c.minPrice&&t<=c.maxPrice,a=s(r),i=s(o);if(a&&!i)return r;if(i&&!a)return o;let l=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/t));return l(o)<l(r)?o:r}function Ct(n,e,t="nearest"){let r=Math.abs(n-Math.round(n))<1e-6?Math.round(n):n,o=(r%e+e)%e;if(o===0)return r;let s=r-o,a=s+e;return t==="down"?s:t==="up"?a:r-s<a-r?s:a}var yn=-887272,wo=887272;function Rt(n){return n<yn?yn:n>wo?wo:n}var Og={"0x1":"https://gateway.thegraph.com/api/subgraphs/id/5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV","0xa4b1":"https://gateway.thegraph.com/api/subgraphs/id/FbCGRftH4a3yZugY7TnbYgPJVEv2LvMT6oF1fxPe9aJM","0x89":"https://gateway.thegraph.com/api/subgraphs/id/3hCPRGf4z88VC5rsBKU5AA9FBBq5nF3jbKJG7VZCbhjm","0x38":"https://gateway.thegraph.com/api/subgraphs/id/GcKPSgHoY42xNYVAkSPDhXSzi6aJDRQSKqBSXezL47gV","0x2105":"https://gateway.thegraph.com/api/subgraphs/id/HMuAwufqZ1YCRmzL2SfHTVkzZovC9VL2UAKhjvRqKiR1","0xa":"https://gateway.thegraph.com/api/subgraphs/id/Cghf4LfVqPiFw6fp6Y5X5Ubc8UpmUhSfJL82zwiBFLaj","0xa86a":"https://gateway.thegraph.com/api/subgraphs/id/GVH9h9KZ9CqheUEL93qMbq7QwgoBu32QXQDPR6bev4Eo"},Mg={"0x1":"ethereum","0xa4b1":"arbitrum","0x89":"polygon","0x38":"bsc","0x2105":"base","0xa":"optimism","0xa86a":"avalanche"},Fg={"0x1":1,"0xa4b1":42161,"0x89":137,"0x38":56,"0x2105":8453,"0xa":10,"0xa86a":43114},Wd={"0x1":"0x1",1:"0x1",eth:"0x1",ethereum:"0x1",mainnet:"0x1","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","0x38":"0x38",56:"0x38",bnb:"0x38",bsc:"0x38","0x2105":"0x2105",8453:"0x2105",base:"0x2105","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a"},Yd={100:.01,500:.05,3e3:.3,1e4:1},Bg={ethereum:"0x1","arbitrum one":"0xa4b1",arbitrum:"0xa4b1",polygon:"0x89",bsc:"0x38",base:"0x2105",optimism:"0xa","avalanche c-chain":"0xa86a",avalanche:"0xa86a"},qg=300*1e3,xe=class{apiKey;subgraphUrls;coinPoolBaseUrl;llamaCache=null;llamaCacheAt=0;constructor(e={}){this.apiKey=e.theGraphApiKey||"4c67ac7a75b21befbd28dc9120c709f1";let t={...Og,...e.subgraphUrls||{}};this.subgraphUrls=Object.fromEntries(Object.entries(t).filter(([r])=>Be(r))),this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}resolveChain(e){if(!e)return"0x1";let t=e.toLowerCase();return Wd[t]||(this.subgraphUrls[t]?t:"0x1")}isSupported(e){if(!e)return!1;let t=e.toLowerCase(),r=Wd[t];return!!(r&&this.subgraphUrls[r])}chainName(e){let t=this.resolveChain(e);return Mg[t]||t}numericChainId(e){return Fg[this.resolveChain(e)]}listSupportedChains(){return Object.keys(this.subgraphUrls)}async querySubgraph(e,t){let r=this.resolveChain(e),o=this.subgraphUrls[r];if(!o)throw new Error(`No subgraph available for chain: ${e}`);let s=await C.post(o,{query:t},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!s.ok)throw new Error(`Subgraph query failed: ${_(s)}`);let a=s.data;if(a.errors&&a.errors.length>0)throw new Error(`Subgraph error: ${a.errors[0].message||"Unknown"}`);return a.data}poolFragment(){return`
143
+ ${qd}`,fn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114,"0xe708":59144};function Bs(n){return new Promise(e=>setTimeout(e,n))}async function Id(n,e,t){let r;return Promise.race([n,new Promise(o=>{r=setTimeout(()=>o(t),e)})]).finally(()=>clearTimeout(r))}function hi(n){if(!n)return 1;let e=n.toLowerCase();return fn[e]??1}function ic(n){if(!n)return"ETHEREUM";let e=n.toLowerCase();return Bd[e]??"ETHEREUM"}var Ig=Object.fromEntries(Object.entries(fn).map(([n,e])=>[e,n]));function $d(n){if(typeof n!="number")return;let e=Ig[n];return e?Bd[e]:void 0}function Ug(n){if(typeof n!="string")return;let e=n.replace("PROTOCOL_VERSION_","").toUpperCase();return e==="V2"||e==="V3"||e==="V4"?e:void 0}function Dg(n){switch(n){case"volume1Day":return"POOLS_ORDER_BY_VOLUME_1D";case"volume30Day":return"POOLS_ORDER_BY_VOLUME_30D";case"apr":return"POOLS_ORDER_BY_APR";case"tvl":return"POOLS_ORDER_BY_TVL";default:return}}function Ud(n){let e=n.pool,t=e?.poolId?.trim();if(!e||!t)return;let r=n.stats??{},o=Ug(e.protocolVersion),s=$d(e.chainId),a=di(e.feeTier,e.protocolFee,o);return{id:t,chain:s,protocolVersion:o,feeTier:e.feeTier,isDynamicFee:e.isDynamicFee,totalLiquidity:gn(r.tvl),volume1Day:gn(r.volume1d),volume30Day:gn(r.volume30d),apr:$(r.apr),totalApr:$(r.totalApr),volumeToTvlRatio:typeof r.volume1dTvlRatio=="number"?r.volume1dTvlRatio:void 0,lpFeeShare:a,fee24hUsd:pi(r.volume1d,e.feeTier,a),token0:Md(e.token0),token1:Md(e.token1)}}function gn(n){return typeof n=="number"&&Number.isFinite(n)?{value:n,currency:"USD"}:void 0}function lc(n){if(typeof n=="number")return Number.isFinite(n)?n:void 0;if(typeof n!="string"||n.trim()==="")return;let e=Number(n);return Number.isFinite(e)?e:void 0}function Dd(n,e,t,r){if(!n&&!e&&!r)return;let o=lc(t);return{...r,address:e??r?.address,symbol:n?.symbol??r?.symbol,name:n?.name??r?.name,decimals:n?.decimals??r?.decimals,logo:n?.logoUrl??r?.logo,price:gn(o)??r?.price,market:o!==void 0?{price:gn(o)}:r?.market,project:r?.project}}function Od(n,e){let t=n.poolIdentifier,r=n.protocolVersion==="V4",o=n.hookAddress&&n.hookAddress!==Eg?n.hookAddress:e?.hook?.address??void 0;return{id:e?.id,protocolVersion:n.protocolVersion??e?.protocolVersion,address:r?e?.address:t??e?.address,poolId:r?t??e?.poolId:e?.poolId,feeTier:n.feeTier??e?.feeTier,tickSpacing:n.tickSpacing??e?.tickSpacing,isDynamicFee:n.isDynamicFee??e?.isDynamicFee,hook:o?{address:o}:void 0,totalLiquidity:gn(n.tvlUsd)??e?.totalLiquidity,totalLiquidityPercentChange24h:gn(n.tvlUsdChange1d)??e?.totalLiquidityPercentChange24h,volume24h:gn(n.volumeUsd1d)??e?.volume24h,token0Supply:lc(n.token0Supply)??e?.token0Supply,token1Supply:lc(n.token1Supply)??e?.token1Supply,txCount:e?.txCount,historicalVolume:e?.historicalVolume,token0:Dd(n.token0Metadata,n.token0Address,n.token0PriceUsd,e?.token0),token1:Dd(n.token1Metadata,n.token1Address,n.token1PriceUsd,e?.token1),protocolFee:n.protocolFee,apr:$(n.apr),totalApr:$(n.totalApr),currentTick:n.currentTick,sqrtPriceX96:n.sqrtPriceX96,liquidity:n.liquidity}}function Md(n){if(n)return{chain:$d(n.chainId),address:n.address,symbol:n.symbol,name:n.name,decimals:n.decimals,standard:n.type?.replace("TOKEN_TYPE_",""),logo:n.project?.logoUrl,project:n.project?.logoUrl?{logo:{url:n.project.logoUrl}}:void 0}}function Fd(n,e){switch(e){case"volume1Day":return n.volume1Day?.value??0;case"volume1Week":return n.volume1Week?.value??0;case"volume30Day":return n.volume30Day?.value??0;case"txCount":return n.txCount??0;case"apr":return n.apr??n.totalApr??0;default:return n.totalLiquidity?.value??0}}var $e=class{baseUrl;searchBaseUrl;liquidityBaseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Tg).replace(/\/$/,""),this.searchBaseUrl=(e?.searchBaseUrl??Pg).replace(/\/$/,""),this.liquidityBaseUrl=(e?.liquidityBaseUrl??Cg).replace(/\/$/,"")}isSupported(e){if(!e)return!1;let t=I(e);return!!t&&Object.prototype.hasOwnProperty.call(fn,t)}listSupportedChains(){return Object.keys(fn).filter(e=>Be(e))}async listPools(e){let t=await this.listPoolsPage(e);return t.success?{success:!0,data:t.data?.pools??[]}:{success:!1,error:t.error}}async listPoolsPage(e){if(e.chainIds.length===0)return{success:!1,error:"At least one chain is required"};let t=`${this.searchBaseUrl}${Sg}`,r=JSON.stringify({chainIds:e.chainIds,sort:{orderBy:e.orderBy,ascending:e.ascending===!0},filter:{protocolVersions:e.protocolVersions.map(s=>`PROTOCOL_VERSION_${s}`),includeSpam:e.includeSpam===!0,applyTopLevelFilters:!0},page:{pageSize:Math.min(Math.max(Math.floor(e.pageSize),1),mi),...e.pageToken?{pageToken:e.pageToken}:{}}}),o="Unknown error";for(let s=1;s<=xt;s++)try{let a=await C.post(t,r,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!a.ok)throw new Error(_(a));let i=a.data;return{success:!0,data:{pools:i.pools??[],nextPageToken:i.page?.nextPageToken||void 0}}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<xt&&await Bs(Fs)}return{success:!1,error:o}}async listAllPools(e){let t=[],r=new Set,o;for(let s=0;s<xg;s++){let a=await this.listPoolsPage({...e,pageToken:o});if(!a.success||!a.data){if(s===0)return{success:!1,error:a.error||"Failed to fetch pools"};break}t.push(...a.data.pools);let i=a.data.nextPageToken;if(!i||a.data.pools.length===0||r.has(i))break;r.add(i),o=i}return{success:!0,data:t}}async getTopPools(e){let t=e?.protocolVersion??"V3",r=e?.limit&&e.limit>0?Math.floor(e.limit):10,o=e?.sortBy??"tvl",s=e?.multichain?Object.values(fn):[hi(e?.chain)],a=Dg(o),i=a?Math.min(r,mi):mi,l=await this.listPools({chainIds:s,protocolVersions:[t],orderBy:a??"POOLS_ORDER_BY_TVL",pageSize:i});return!l.success||!l.data?{success:!1,error:l.error||"Failed to fetch pools"}:{success:!0,data:l.data.map(u=>Ud(u)).filter(u=>u!==void 0).sort((u,p)=>Fd(p,o)-Fd(u,o)).slice(0,r)}}async getPool(e){let t=e.addressOrId?.trim();if(!t)return{success:!1,error:"Pool address or id is required"};let r=`${this.liquidityBaseUrl}${Rg}`,o=JSON.stringify({pool:{chainId:hi(e.chain),addressOrId:t}}),s="Unknown error";for(let a=1;a<=xt;a++)try{let i=await C.post(r,o,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(i.status===404)return{success:!1,error:"Pool not found"};if(!i.ok)throw new Error(_(i));let l=i.data?.pool;return l?{success:!0,data:l}:{success:!1,error:"Pool not found"}}catch(i){s=i instanceof Error?i.message:"Unknown error",a<xt&&await Bs(Fs)}return{success:!1,error:s}}async getV3PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V3Pool",query:_g,variables:{chain:ic(e.chain),address:t},pickField:"v3Pool"}):{success:!1,error:"Pool address is required"}}async getV2PoolDetail(e){let t=e.address?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V2Pair",query:Ng,variables:{chain:ic(e.chain),address:t},pickField:"v2Pair"}):{success:!1,error:"Pair address is required"}}async getV4PoolDetail(e){let t=e.poolId?.trim();return t?this.fetchPoolDetailGraphQL({operationName:"V4Pool",query:Lg,variables:{chain:ic(e.chain),poolId:t},pickField:"v4Pool"}):{success:!1,error:"V4 poolId is required"}}async getPoolDetailEnriched(e){let t=await this.getPool(e);if(!t.success||!t.data)return{success:!1,error:t.error||"Failed to fetch pool detail"};let r=t.data;if(e.enrich===!1)return{success:!0,data:Od(r,void 0)};let o=r.protocolVersion,s=r.poolIdentifier??e.addressOrId.trim(),a=o==="V4"?this.getV4PoolDetail({poolId:s,chain:e.chain}):o==="V2"?this.getV2PoolDetail({address:s,chain:e.chain}):this.getV3PoolDetail({address:s,chain:e.chain}),i=await Id(a.then(l=>l.success?l.data:void 0).catch(()=>{}),Ld,void 0);return{success:!0,data:Od(r,i)}}async fetchPoolDetailGraphQL(e){let t=`${this.baseUrl}${Ag}`,r=JSON.stringify({operationName:e.operationName,variables:e.variables,query:e.query}),o="Unknown error";for(let s=1;s<=xt;s++)try{let a=await C.post(t,r,{headers:{accept:"*/*","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web","_dd-custom-header-graph-ql-operation-name":e.operationName,"_dd-custom-header-graph-ql-operation-type":"query"}});if(!a.ok)throw new Error(_(a));let i=a.data;if(i.errors)throw new Error(`GraphQL error: ${JSON.stringify(i.errors)}`);let l=i.data?.[e.pickField]??void 0;return l?{success:!0,data:l}:{success:!1,error:"Pool not found"}}catch(a){o=a instanceof Error?a.message:"Unknown error",s<xt&&await Bs(Fs)}return{success:!1,error:o}}async searchTokens(e){let t=e.query?.trim();return t?R(t)?{success:!1,error:"Address is invalid for token search. If you pasted a 0x address, it may be a Uniswap pool \u2014 try the pool search tool instead."}:this.fetchSearchTokens({query:t,chain:e.chain,page:e.page,size:e.size}):{success:!1,error:"Search query is required"}}async getTokenSafetyByAddress(e,t){let r=Array.from(new Set(e.filter(s=>typeof s=="string"&&R(s.trim())).map(s=>s.trim()))),o=new Map;return r.length===0||await Id(Promise.all(r.map(async s=>{let a=await this.fetchSearchTokens({query:s,chain:t,size:5});if(!a.success)return;let i=s.toLowerCase(),l=(a.data??[]).find(c=>c.address?.toLowerCase()===i);l&&o.set(i,l)})).catch(()=>{}),Ld,void 0),o}async fetchSearchTokens(e){let t=hi(e.chain),r=e.page&&e.page>0?Math.floor(e.page):1,o=e.size&&e.size>0?Math.min(Math.floor(e.size),50):15,s=`${this.searchBaseUrl}${Nd}`,a=JSON.stringify({searchQuery:e.query,chainIds:[t],searchType:"TOKEN",page:r,size:o}),i="Unknown error";for(let l=1;l<=xt;l++)try{let c=await C.post(s,a,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!c.ok)throw new Error(_(c));return{success:!0,data:c.data.tokens??[]}}catch(c){i=c instanceof Error?c.message:"Unknown error",l<xt&&await Bs(Fs)}return{success:!1,error:i}}async searchPools(e){let t=e.query?.trim();if(!t)return{success:!1,error:"Search query is required"};let r=hi(e.chain),o=e.page&&e.page>0?Math.floor(e.page):1,s=e.size&&e.size>0?Math.min(Math.floor(e.size),50):15,a=e.protocolVersion??"V3",i=e.feeTier&&e.feeTier>0?Math.floor(e.feeTier):void 0,l=`${this.searchBaseUrl}${Nd}`,c=JSON.stringify({searchQuery:t,chainIds:[r],searchType:"POOL",page:o,size:s}),[d,u]=await Promise.allSettled([this.fetchSearchPools(l,c),this.listPools({chainIds:[r],protocolVersions:a==="ALL"?["V2","V3","V4"]:[a],orderBy:"POOLS_ORDER_BY_TVL",pageSize:mi})]);if(d.status==="rejected"||!d.value.success)return{success:!1,error:d.status==="rejected"?String(d.reason):d.value.error??"Failed to search pools"};let p=t.toLowerCase().split(/\s+/).filter(Boolean),m=d.value.data??[];a!=="ALL"&&(m=m.filter(y=>y.protocolVersion===a)),i!=null&&(m=m.filter(y=>y.feeTier===i));let f=new Map,h=new Map,g=new Map;for(let y of m)y.id&&f.set(y.id.toLowerCase(),y);if(u.status==="fulfilled"&&u.value.success&&u.value.data)for(let y of u.value.data){let w=Ud(y);if(!w||i!=null&&w.feeTier!==i)continue;let k=(w.token0?.symbol??"").toLowerCase(),v=(w.token1?.symbol??"").toLowerCase(),S=(w.token0?.name??"").toLowerCase(),P=(w.token1?.name??"").toLowerCase();if(!p.some(z=>k.includes(z)||v.includes(z)||S.includes(z)||P.includes(z)))continue;let U=w.id.toLowerCase(),E=w.totalLiquidity?.value,we=w.volume1Day?.value,V=f.get(U);f.set(U,{...V??{id:w.id,protocolVersion:w.protocolVersion,feeTier:w.feeTier,token0:w.token0?{address:w.token0.address,symbol:w.token0.symbol,name:w.token0.name,decimals:w.token0.decimals}:void 0,token1:w.token1?{address:w.token1.address,symbol:w.token1.symbol,name:w.token1.name,decimals:w.token1.decimals}:void 0},...E!=null?{tvlUsd:E}:{},...we!=null?{volume1DayUsd:we}:{},...w.isDynamicFee===!0||hn(w.feeTier)?{isDynamicFee:!0}:{}}),h.set(U,w.chain),g.set(U,w.apr)}let b=Array.from(f.entries()).sort(([,y],[,w])=>this.matchScore(w,p)-this.matchScore(y,p));for(let[y,w]of b){let k=$(g.get(y));k!=null&&(w.apr=k)}return{success:!0,data:b.map(([,y])=>y)}}async fetchSearchPools(e,t){let r="Unknown error";for(let o=1;o<=xt;o++)try{let s=await C.post(e,t,{headers:{accept:"*/*","connect-protocol-version":"1","content-type":"application/json",origin:"https://app.uniswap.org",referer:"https://app.uniswap.org/","x-request-source":"uniswap-web"}});if(!s.ok)throw new Error(_(s));return{success:!0,data:s.data.pools??[]}}catch(s){r=s instanceof Error?s.message:"Unknown error",o<xt&&await Bs(Fs)}return{success:!1,error:r}}matchScore(e,t){let r=[e.token0?.symbol??"",e.token1?.symbol??""].map(s=>s.toLowerCase()),o=0;for(let s of t){let a=0;for(let i of r)i===s?a=Math.max(a,3):i.startsWith(s)?a=Math.max(a,2):i.includes(s)&&(a=Math.max(a,1));o+=a}return o}};var Hd=2n**96n;function Se(n,e=8){return!Number.isFinite(n)||n===0?n:Number(n.toPrecision(e))}function Vd(n,e,t){let r=n*n,o=Hd*Hd,s=r*10n**18n/o;return Number(s)/1e18*Math.pow(10,e-t)}function pt(n,e,t){return Math.pow(1.0001,n)*Math.pow(10,e-t)}function jn(n,e,t){if(n<=0)throw new Error("priceToTick: price must be > 0");let r=n/Math.pow(10,e-t),o=Math.log(r)/Math.log(1.0001),s=Math.round(o);return Math.abs(o-s)<.001?s:Math.floor(o)}function ko(n,e,t){let r={minPrice:n,maxPrice:e,inverted:!1};if(!Number.isFinite(n)||!Number.isFinite(e)||!Number.isFinite(t)||n<=0||e<=0||t<=0||n>=e)return r;let o={minPrice:1/e,maxPrice:1/n,inverted:!0},s=c=>t>=c.minPrice&&t<=c.maxPrice,a=s(r),i=s(o);if(a&&!i)return r;if(i&&!a)return o;let l=c=>Math.abs(Math.log(Math.sqrt(c.minPrice*c.maxPrice)/t));return l(o)<l(r)?o:r}function Ct(n,e,t="nearest"){let r=Math.abs(n-Math.round(n))<1e-6?Math.round(n):n,o=(r%e+e)%e;if(o===0)return r;let s=r-o,a=s+e;return t==="down"?s:t==="up"?a:r-s<a-r?s:a}var yn=-887272,wo=887272;function Rt(n){return n<yn?yn:n>wo?wo:n}var Og={"0x1":"https://gateway.thegraph.com/api/subgraphs/id/5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV","0xa4b1":"https://gateway.thegraph.com/api/subgraphs/id/FbCGRftH4a3yZugY7TnbYgPJVEv2LvMT6oF1fxPe9aJM","0x89":"https://gateway.thegraph.com/api/subgraphs/id/3hCPRGf4z88VC5rsBKU5AA9FBBq5nF3jbKJG7VZCbhjm","0x38":"https://gateway.thegraph.com/api/subgraphs/id/GcKPSgHoY42xNYVAkSPDhXSzi6aJDRQSKqBSXezL47gV","0x2105":"https://gateway.thegraph.com/api/subgraphs/id/HMuAwufqZ1YCRmzL2SfHTVkzZovC9VL2UAKhjvRqKiR1","0xa":"https://gateway.thegraph.com/api/subgraphs/id/Cghf4LfVqPiFw6fp6Y5X5Ubc8UpmUhSfJL82zwiBFLaj","0xa86a":"https://gateway.thegraph.com/api/subgraphs/id/GVH9h9KZ9CqheUEL93qMbq7QwgoBu32QXQDPR6bev4Eo"},Mg={"0x1":"ethereum","0xa4b1":"arbitrum","0x89":"polygon","0x38":"bsc","0x2105":"base","0xa":"optimism","0xa86a":"avalanche"},Fg={"0x1":1,"0xa4b1":42161,"0x89":137,"0x38":56,"0x2105":8453,"0xa":10,"0xa86a":43114},Wd={"0x1":"0x1",1:"0x1",eth:"0x1",ethereum:"0x1",mainnet:"0x1","0xa4b1":"0xa4b1",42161:"0xa4b1",arb:"0xa4b1",arbitrum:"0xa4b1","0x89":"0x89",137:"0x89",matic:"0x89",polygon:"0x89","0x38":"0x38",56:"0x38",bnb:"0x38",bsc:"0x38","0x2105":"0x2105",8453:"0x2105",base:"0x2105","0xa":"0xa",10:"0xa",op:"0xa",optimism:"0xa","0xa86a":"0xa86a",43114:"0xa86a",avax:"0xa86a",avalanche:"0xa86a"},Yd={100:.01,500:.05,3e3:.3,1e4:1},Bg={ethereum:"0x1","arbitrum one":"0xa4b1",arbitrum:"0xa4b1",polygon:"0x89",bsc:"0x38",base:"0x2105",optimism:"0xa","avalanche c-chain":"0xa86a",avalanche:"0xa86a"},qg=300*1e3,xe=class{apiKey;subgraphUrls;coinPoolBaseUrl;llamaCache=null;llamaCacheAt=0;constructor(e={}){this.apiKey=e.theGraphApiKey||"4c67ac7a75b21befbd28dc9120c709f1";let t={...Og,...e.subgraphUrls||{}};this.subgraphUrls=Object.fromEntries(Object.entries(t).filter(([r])=>Be(r))),this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}resolveChain(e){if(!e)return"0x1";let t=e.toLowerCase();return Wd[t]||(this.subgraphUrls[t]?t:"0x1")}isSupported(e){if(!e)return!1;let t=e.toLowerCase(),r=Wd[t];return!!(r&&this.subgraphUrls[r])}chainName(e){let t=this.resolveChain(e);return Mg[t]||t}numericChainId(e){return Fg[this.resolveChain(e)]}listSupportedChains(){return Object.keys(this.subgraphUrls)}async querySubgraph(e,t){let r=this.resolveChain(e),o=this.subgraphUrls[r];if(!o)throw new Error(`No subgraph available for chain: ${e}`);let s=await C.post(o,{query:t},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!s.ok)throw new Error(`Subgraph query failed: ${_(s)}`);let a=s.data;if(a.errors&&a.errors.length>0)throw new Error(`Subgraph error: ${a.errors[0].message||"Unknown"}`);return a.data}poolFragment(){return`
144
144
  id
145
145
  token0 { id symbol name }
146
146
  token1 { id symbol name }
@@ -199,20 +199,20 @@ ${qd}`,fn={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0
199
199
  ${this.poolFragment()}
200
200
  }
201
201
  }
202
- }`,o=await this.querySubgraph(t,r);if(!o?.position?.pool)return null;let s=o.position,a=this.mapPool(s.pool,t),i=await this.fetchDefiLlamaUniswap(),l=i.length>0?this.enrichWithLlama([a],i)[0]:a,c=l.feeTierBps,d=l.feeTierPercent;return{position:{positionId:s.id,poolAddress:l.poolAddress,pair:l.pair,token0:{symbol:l.token0.symbol,address:l.token0.address},token1:{symbol:l.token1.symbol,address:l.token1.address},feeTierBps:c,feeTierPercent:d,chain:l.chain,liquidity:s.liquidity,depositedToken0:s.depositedToken0,depositedToken1:s.depositedToken1,withdrawnToken0:s.withdrawnToken0,withdrawnToken1:s.withdrawnToken1,collectedFeesToken0:s.collectedFeesToken0,collectedFeesToken1:s.collectedFeesToken1},pool:l}}async getCoinPoolPairs(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let o=(await this.fetchCoinPoolV2Items(t)).map(s=>this.mapCoinPoolV2Item(s)).filter(s=>s!==null);if(e.tokens&&e.tokens.length>=2){let s=e.tokens[0].toUpperCase(),a=e.tokens[1].toUpperCase();o=o.filter(i=>{let[l="",c=""]=i.pair.toUpperCase().split("/");return l.includes(s)&&c.includes(a)||l.includes(a)&&c.includes(s)})}return o}async getCoinPoolByAddress(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let r=e.poolAddress.toLowerCase();return(await this.fetchCoinPoolV2Items(t)).filter(s=>s.poolId?.toLowerCase()===r).map(s=>this.mapCoinPoolV2Item(s)).filter(s=>s!==null).sort((s,a)=>(a.apr??-1/0)-(s.apr??-1/0))}async fetchCoinPoolV2Items(e){if(!this.coinPoolBaseUrl)return[];try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,r=await C.get(t);if(!r.ok)throw new Error(_(r));return r.data?.data?.items||[]}catch{return[]}}mapCoinPoolV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,r=e.token1.decimal??18,o=S=>S==null||!Number.isFinite(S)?0:Math.pow(1.0001,S)*Math.pow(10,t-r),s=o(e.minTick),a=o(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,d=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),u=d?s:a>0?1/a:0,p=d?a:s>0?1/s:0,m=d?c:c>0?1/c:0,f=d?e.token0.symbol:e.token1.symbol,h=d?e.token1.symbol:e.token0.symbol;if(!m||!u&&!p)return null;let g=Math.min(u,p),b=Math.max(u,p);if(m<g||m>b)return null;let y=Number(e.fee),w=Yd[y]??y/1e4,k=$(e.apr)??$(e.aprAvg)??null,v=$(e.aprAvg)??null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:v,token0Price:i,token1Price:l,priceRange:{minPrice:Se(u),maxPrice:Se(p),currentPrice:Se(m),baseToken:f,quoteToken:h}}}};var bn=class{config;constructor(e){this.config=e}withRoute(e){let t=Object.create(this);return t.getQuote=r=>this.getQuote({route:e,...r}),t}};var Et=class{constructor(e,t=Number.POSITIVE_INFINITY){this.loader=e;this.ttlMs=t}loader;ttlMs;value=null;loadedAt=0;inFlight=null;async get(){return this.value!==null&&Date.now()-this.loadedAt<this.ttlMs?this.value:this.inFlight?this.inFlight:(this.inFlight=(async()=>{try{let e=await this.loader();return e!==null&&(this.value=e,this.loadedAt=Date.now()),e}catch{return this.value}finally{this.inFlight=null}})(),this.inFlight)}};var $g="https://api.relay.link";function Gd(n){return n===7565164||n==="7565164"?792703809:n}var vo=class extends bn{apiBaseUrl;apiKey;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??$g,this.apiKey=e.apiKey}getProviderName(){return"relay"}hasIntegratedApproval(){return!0}async getQuote(e){let{srcChainId:t,srcTokenAddress:r,srcTokenAmount:o,dstChainId:s,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c}=e,d=await wn.getAffiliateFee(this.getProviderName(),t,e.route),u={user:i||l,originChainId:Gd(t),destinationChainId:Gd(s),originCurrency:r,destinationCurrency:a,amount:o,recipient:i||l,tradeType:"EXACT_INPUT"};d&&(u.appFees=[{recipient:d.affiliateFeeRecipient,fee:Math.floor(d.affiliateFeePercent*100)}]),typeof c=="number"&&Number.isFinite(c)&&(u.slippageTolerance=Math.floor(c*100).toString());try{let p=await this.request("/quote/v2","POST",u);if(!p||p.error)return{success:!1,error:p?.error??"Unknown error",errorMessage:p?.message??"Failed to fetch quote from Relay"};let m=(p.steps??[]).filter(y=>y.id==="approve"),f=p.steps?.find(y=>y.id==="swap"||y.id==="deposit"),h=f?.items?.[0]?.data,g=Array.isArray(h?.instructions);return{success:!0,provider:"relay",tx:h?g?{data:{instructions:h.instructions??[],addressLookupTableAddresses:h.addressLookupTableAddresses??[]},chainId:h.chainId}:{from:h.from,to:h.to,data:h.data,value:h.value,chainId:h.chainId,gas:h.gas,maxFeePerGas:h.maxFeePerGas,maxPriorityFeePerGas:h.maxPriorityFeePerGas}:null,isCrossChain:t!==s,srcChainId:t,dstChainId:s,raw:{steps:p.steps,fees:p.fees,details:p.details,approveSteps:m,requestId:f?.requestId}}}catch(p){return{success:!1,error:p,errorMessage:p instanceof Error?p.message:"Failed to fetch quote"}}}async checkApproval(e){let t=e.quoteData?.raw,o=(t?.approveSteps??(t?.approveStep?[t.approveStep]:[])).map(s=>s.items?.[0]?.data).filter(s=>!!s?.to&&typeof s.data=="string").map(s=>({to:s.to,from:s.from,data:s.data,value:s.value??"0",chainId:s.chainId,gas:s.gas,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas}));return o.length>0?{isNeeded:!0,integrated:!0,approvals:o,approvalData:o[0],contractAddress:o[0].to,message:o.length>1?`${o.length} approval steps are included in the quote and run first, in order.`:"Approval step is included in quote and will be executed first."}:{isNeeded:!1,integrated:!0,approvals:[],message:"No approval needed or already approved"}}async trackTransaction(e){try{let r=(await this.request("/intents/status/v3","GET",{requestId:e.requestIdOrTxHash})).status??"";return r==="success"||r==="refunded"?{success:!0,status:"COMPLETED"}:r==="failure"||r==="expired"?{success:!0,status:"FAILED"}:{success:!0,status:"PENDING"}}catch(t){return{success:!1,status:"ERROR",error:t instanceof Error?t.message:String(t)}}}async request(e,t,r){let o={"Content-Type":"application/json"};this.apiKey&&(o["x-api-key"]=this.apiKey);let s=`${this.apiBaseUrl}${e}`,a;if(t==="GET"&&r){let l=Object.entries(r).map(([c,d])=>`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`).join("&");s=`${s}?${l}`}else t==="POST"&&r&&(a=r);let i=await C.request(t,s,a,{headers:o});if(!i.ok)throw new Error(_(i));return i.data}};var Hg="https://api.coinpool.app/config/addresses",Vg="https://api.coinpool.app/config/bridgeProviderByChain",Kd="createPoolProxyV3",Wg="nftPositionUniswap",Yg=/^0x[0-9a-fA-F]{40}$/,qs=class{addresses;providerMap;constructor(e=Hg,t=Vg){this.addresses=new Et(async()=>(await C.get(e,{headers:{Accept:"application/json"}})).data?.data??null),this.providerMap=new Et(async()=>(await C.get(t,{headers:{Accept:"application/json"}})).data?.data??null)}async getProviderByChain(e){let r=(await this.providerMap.get())?.[String(e)];return this.isProviderName(r)?r:null}async getGatewayAddress(e){return this.getAddress(Kd,e)}async getPositionManagerAddress(e){return this.getAddress(Wg,e)}async getGatewayChains(){return this.listChainsWithAddress(Kd)}async getAddress(e,t){let r=await this.addresses.get();if(!r)return;let o=this.toDecimalChainKey(t);if(o)return this.firstAddress(r[e]?.[o])}async listChainsWithAddress(e){let t=(await this.addresses.get())?.[e];if(!t||typeof t!="object")return[];let r=[];for(let[o,s]of Object.entries(t)){let a=this.firstAddress(s);a&&Yg.test(a)&&r.push(o)}return r}firstAddress(e){let t=Array.isArray(e)?e[0]:e;return typeof t=="string"?t.trim():void 0}toDecimalChainKey(e){let t=e.trim();if(/^0x[0-9a-fA-F]+$/.test(t)){let r=Number.parseInt(t,16);return Number.isFinite(r)?String(r):null}return/^\d+$/.test(t)?t:null}isProviderName(e){return e==="debridge"||e==="relay"}},kn=new qs;var To=class{async resolve(e){try{return await this.resolveProvider(e)??Bt}catch{return Bt}}toNumericChainId(e){if(e==null)return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}},Ao=class extends To{constructor(t=kn){super();this.config=t}config;route="pool";async resolveProvider({srcChainId:t}){let r=this.toNumericChainId(t);return r===null?null:this.config.getProviderByChain(r)}},Po=class extends To{constructor(t=wn){super();this.setting=t}setting;route="userSwap";async resolveProvider({srcChainId:t,dstChainId:r}){return this.setting.getBridgeProvider(t,r)}};var $s=class{routers=new Map;constructor(e=[new Ao,new Po]){for(let t of e)this.routers.set(t.route,t)}async resolveProvider(e){return await this.routers.get(e.route)?.resolve(e)??Bt}},fi=new $s;var Hs=class{configOverride;routersOverride;cache=new Map;constructor(e,t){this.configOverride=e,this.routersOverride=t}get providers(){return this.configOverride??xo}get routers(){return this.routersOverride??fi}async getService(e){let t=this.getServiceByProvider(await this.resolveProvider(e));return e.route?t.withRoute(e.route):t}getServiceByProvider(e){let t=this.cache.get(e);if(t)return t;let r=this.createService(e);return this.cache.set(e,r),r}resetCache(){this.cache.clear()}async resolveProvider(e){return this.routers.resolveProvider(e)}createService(e){let t=this.providers[e]??{};switch(e){case"debridge":return new Co(t);case"relay":return new vo(t);default:{let r=e;throw new Error(`Unknown swap provider: ${String(r)}`)}}}},So=new Hs;var xo={debridge:{apiBaseUrl:"https://dln.debridge.finance/v1.0",accessToken:"d6c45897b8f6"},relay:{apiBaseUrl:"https://api.relay.link"}},Bt="relay";function gi(n,e){let t={...xo[n]??{},...e};for(let r of Object.keys(t))t[r]===void 0&&delete t[r];xo[n]=t,So.resetCache()}var Gg="https://exchange-api.keyring.app/admin/setting?configs=others",Kg="https://api.relay.link/chains",jg="https://dln.debridge.finance/v1.0/supported-chains-info",zg=14400*1e3,Xg=300*1e3,Qg=new Set([728126428,7565164]),jd={relay:"relay",debridge:"deBridge"},Vs=class{setting;chainSupport;constructor(e=Gg){this.setting=new Et(async()=>(await C.get(e,{headers:{Accept:"application/json"}})).data?.others??null,Xg),this.chainSupport=new Et(async()=>this.fetchChainSupport(),zg)}async getBridgeProvider(e,t){let r=this.toChainKey(e),o=this.toChainKey(t??e),[s,a]=await Promise.all([this.setting.get(),this.chainSupport.get()]),i=this.normalizeProvider(s?.keyringV2?.bridgeProvider)??Bt;if(!r||!o||!a)return i;let l=this.requireChainKeys(s?.keyringV2,"debridge"),c=l.includes(r)||l.includes(o),d=a.debridge.has(r)&&a.debridge.has(o);return c&&d?"debridge":i}async getAffiliateFee(e,t,r="userSwap"){let o=await this.setting.get();if(!o)return null;let s=r==="pool"?this.resolveLegacyFee(o,e,t):this.resolveKeyringV2Fee(o,e,t);return!s.recipient||s.percent<=0?null:{affiliateFeeRecipient:s.recipient,affiliateFeePercent:s.percent}}resolveLegacyFee(e,t,r){return t==="debridge"?{recipient:this.parseRecipientMap(e.affiliateRecipient)?.[String(r)],percent:this.toPercent(e.AFFILIATE_FEE_PERENT)}:{recipient:e.RELAY_AFFILIATE_FEE_RECIPIENT,percent:this.toPercent(e.RELAY_AFFILIATE_FEE_PERCENT)}}resolveKeyringV2Fee(e,t,r){let o=e.keyringV2;if(!o)return{recipient:void 0,percent:0};let s=o[jd[t]],a=String(r);return{percent:this.toPercent(s?.affiliateFeePercentCustom?.[a])||this.toPercent(s?.affiliateFeePercent),recipient:s?.affiliateRecipientCustom?.[a]||o.affiliateRecipientDefault}}parseRecipientMap(e){if(!e)return null;try{let t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}async fetchChainSupport(){let[e,t]=await Promise.allSettled([C.get(Kg,{headers:{Accept:"application/json"}}),C.get(jg,{headers:{Accept:"application/json"}})]),r=new Set;if(e.status==="fulfilled")for(let s of e.value.data?.chains??[]){if(s?.vmType!=="evm")continue;let a=this.toChainKey(s.id);a&&r.add(a)}let o=new Set;if(t.status==="fulfilled")for(let s of t.value.data?.chains??[]){let a=s?.originalChainId??s?.chainId;if(a===void 0||Qg.has(a))continue;let i=this.toChainKey(a);i&&o.add(i)}return{relay:r,debridge:o}}requireChainKeys(e,t){return(e?.[jd[t]]?.requireChain??[]).map(o=>this.toChainKey(o)).filter(o=>o!==null)}normalizeProvider(e){if(typeof e!="string")return null;let t=e.toLowerCase();return t==="relay"?"relay":t==="debridge"?"debridge":null}toChainKey(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?String(e):null;let t=e.trim();if(!t)return null;let r=/^0x/i.test(t)?Number.parseInt(t,16):Number(t);return Number.isFinite(r)?String(r):null}toPercent(e){if(e==null)return 0;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:0}},wn=new Vs;function yi(n,e){return M({abi:q,functionName:"approve",args:[n,e]})}async function Jg(n,e,t,r,o){try{return await Re(n).call({account:t,to:e,data:yi(r,o)}),!0}catch(s){return Zg(s)?!1:null}}function Zg(n){let e=n?.name??"";if(e==="ContractFunctionRevertedError"||e==="CallExecutionError")return!0;let t=n instanceof Error?n.message.toLowerCase():String(n??"").toLowerCase();return t.includes("revert")||t.includes("execution reverted")||t.includes("invalid opcode")||t.includes("out of gas")}async function bi({chain:n,token:e,owner:t,spender:r,amount:o,allowance:s}){let a=l=>({to:e,from:t,data:yi(r,l),value:"0"});return s!=null&&s>=o?[]:s===0n||!n?[a(o)]:await Jg(n,e,t,r,o)===!1?[a(0n),a(o)]:[a(o)]}var ey="https://dln.debridge.finance/v1.0",ty="0x0000000000000000000000000000000000000000",ny=new Set([429,500]),ry=5,oy=1e3,sy=n=>new Promise(e=>setTimeout(e,n)),Co=class extends bn{apiBaseUrl;accessToken;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??ey,this.accessToken=e.accessToken??"d6c45897b8f6"}getProviderName(){return"debridge"}hasIntegratedApproval(){return!1}async getQuote(e){let{srcChainId:t,srcTokenAddress:r,srcTokenAmount:o,dstChainId:s,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c,isCrossChain:d}=e,u=d??t!==s,p=await wn.getAffiliateFee(this.getProviderName(),t,e.route);try{if(u){let h={srcChainId:String(t),srcChainTokenIn:r,srcChainTokenInAmount:o,dstChainId:String(s),dstChainTokenOut:a,dstChainTokenOutRecipient:i,srcChainOrderAuthorityAddress:l,dstChainOrderAuthorityAddress:i,accesstoken:this.accessToken};p&&(h.affiliateFeeRecipient=p.affiliateFeeRecipient,h.affiliateFeePercent=p.affiliateFeePercent);let g=await this.get(`${this.apiBaseUrl}/dln/order/create-tx`,h);return g.error||g.errorMessage?{success:!1,error:g.error??g.errorMessage,errorMessage:g.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:g.tx,estimation:g.estimation,isCrossChain:!0,srcChainId:t,dstChainId:s,raw:g}}let m={chainId:String(t),tokenIn:r,tokenInAmount:o,tokenOut:a,tokenOutRecipient:i,accesstoken:this.accessToken};p&&(m.affiliateFeeRecipient=p.affiliateFeeRecipient,m.affiliateFeePercent=p.affiliateFeePercent),c!==void 0&&(m.slippage=c);let f=await this.get(`${this.apiBaseUrl}/chain/transaction`,m);return f.error||f.errorMessage?{success:!1,error:f.error??f.errorMessage,errorMessage:f.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:f.tx,isCrossChain:!1,srcChainId:t,dstChainId:t,raw:f}}catch(m){return{success:!1,error:m,errorMessage:m instanceof Error?m.message:"Failed to fetch quote"}}}async checkApproval(e){let{chain:t,userAddress:r,tokenAddress:o,amount:s}=e,a=e.quoteData?.tx?.to;if(!a)return{isNeeded:!1,error:"No contract address found in quote"};if(!o||o.toLowerCase()===ty)return{isNeeded:!1,integrated:!1,approvals:[],contractAddress:a,message:"Native coin needs no approval."};let i;try{i=BigInt(s)}catch{i=0n}let l=await this.readAllowance(t,o,r,a);if(l!==null&&l>=i)return{isNeeded:!1,integrated:!1,approvals:[],contractAddress:a,message:"Sufficient allowance already granted."};let c=await bi({chain:t,token:o,owner:r,spender:a,amount:i,allowance:l});return{isNeeded:!0,integrated:!1,approvals:c,approvalData:c[0],contractAddress:a,message:c.length>1?"Approval required: the standing allowance must be reset to 0 before the new one is granted.":l===null?"Could not read allowance; approval required before the swap.":"Approval required: current allowance is below the swap amount."}}async readAllowance(e,t,r,o){if(!e)return null;try{return await Re(e).readContract({address:t,abi:q,functionName:"allowance",args:[r,o]})}catch{return null}}async trackTransaction(e){let{requestIdOrTxHash:t}=e;try{let r=await this.get(`${this.apiBaseUrl}/dln/tx/${t}/order-ids`,{accesstoken:this.accessToken});if(!r.orderIds?.length)return{success:!1,status:"PENDING"};let o=r.orderIds[0];switch(((await this.get(`${this.apiBaseUrl}/dln/order/${o}/status`,{accesstoken:this.accessToken})).status??"").toUpperCase()){case"FULFILLED":case"SENTUNLOCK":case"CLAIMEDUNLOCK":return{success:!0,status:"COMPLETED"};case"ORDERCANCELLED":case"SENTORDERCANCEL":case"CLAIMEDORDERCANCEL":return{success:!0,status:"FAILED"};default:return{success:!0,status:"PENDING"}}}catch(r){return{success:!1,status:"ERROR",error:r instanceof Error?r.message:String(r)}}}async get(e,t){let r=Object.entries(t).map(([a,i])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(i))}`).join("&"),o=r?`${e}?${r}`:e,s=await C.get(o,{headers:{Accept:"application/json"}});for(let a=0;a<ry&&ny.has(s.status);a++)await sy(oy),s=await C.get(o,{headers:{Accept:"application/json"}});return s.data}};function zd(n){let e=n.raw??{},t=e.tokenOut?.amount??e.tokenOut?.minAmount??e.details?.currencyOut?.amount??e.details?.currencyOut?.minimumAmount??e.estimation?.dstChainTokenOut?.recommendedAmount??e.estimation?.dstChainTokenOut?.amount;return t&&/^\d+$/.test(t)?t:void 0}function Xd(n){if(n.errorMessage&&n.errorMessage.trim())return n.errorMessage.trim();let e=r=>{if(typeof r=="string"&&r.trim())return r.trim();if(r&&typeof r=="object"){let o=r;for(let s of[o.message,o.errorMessage,o.error])if(typeof s=="string"&&s.trim())return s.trim()}},t=n.raw??{};return e(n.error)??e(t.errorMessage)??e(t.error)??"The swap could not be quoted right now."}var ay={1:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",10:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",56:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",137:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",143:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",1514:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",4326:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",4663:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",8453:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",42161:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",43114:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",59144:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",25:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",999:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",1776:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66"},iy=[{inputs:[],name:"globalFixedNativeFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}];function Qd(n){if(n==null)return null;if(typeof n=="number")return Number.isFinite(n)?String(n):null;let e=n.trim();if(!e)return null;let t=/^0x/i.test(e)?Number.parseInt(e,16):Number(e);return Number.isFinite(t)?String(t):null}async function wi(n){let{provider:e,srcChainId:t}=n,r=Qd(t),o=Qd(n.dstChainId??t);if(!r||!o||r===o||e!=="debridge")return 0n;let s=ay[r];if(!s)return 0n;try{let a=await Re(r).readContract({address:s,abi:iy,functionName:"globalFixedNativeFee"});return typeof a=="bigint"&&a>0n?a:0n}catch{return 0n}}var ue="0x0000000000000000000000000000000000000000",Jd={"0x1":{hexId:"0x1",name:"Ethereum",defaultRpc:Xe["0x1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa":{hexId:"0xa",name:"Optimism",defaultRpc:Xe["0xa"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0x38":{hexId:"0x38",name:"BNB Smart Chain",defaultRpc:Xe["0x38"],native:{symbol:"BNB",name:"BNB",decimals:18,coingeckoId:"binancecoin"},defaultMintGasLimit:12e5},"0x89":{hexId:"0x89",name:"Polygon",defaultRpc:Xe["0x89"],native:{symbol:"POL",name:"Polygon",decimals:18,coingeckoId:"matic-network"},defaultMintGasLimit:12e5},"0x2105":{hexId:"0x2105",name:"Base",defaultRpc:Xe["0x2105"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa4b1":{hexId:"0xa4b1",name:"Arbitrum One",defaultRpc:Xe["0xa4b1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:22e5},"0xa86a":{hexId:"0xa86a",name:"Avalanche",defaultRpc:Xe["0xa86a"],native:{symbol:"AVAX",name:"Avalanche",decimals:18,coingeckoId:"avalanche-2"},defaultMintGasLimit:12e5},"0xe708":{hexId:"0xe708",name:"Linea",defaultRpc:Xe["0xe708"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5}};function mt(n){return Jd[n.toLowerCase()]}function Ro(n){return mt(n)?.native}var Zd="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";function cc(n){let e=n.stableTicks??3,t=n.widePercent??{down:50,up:100},r=pt(n.currentTick,n.token0Decimals,n.token1Decimals),o=Rt(Ct(n.currentTick-e*n.tickSpacing,n.tickSpacing,"down")),s=Rt(Ct(n.currentTick+e*n.tickSpacing,n.tickSpacing,"up")),a=r*(1-t.down/100),i=r*(1+t.up/100),l=jn(a,n.token0Decimals,n.token1Decimals),c=jn(i,n.token0Decimals,n.token1Decimals),d=Rt(Ct(l,n.tickSpacing,"down")),u=Rt(Ct(c,n.tickSpacing,"up")),p=(m,f,h,g,b)=>{let y=pt(g,n.token0Decimals,n.token1Decimals),w=pt(b,n.token0Decimals,n.token1Decimals);return{id:m,label:f,description:h,tickLower:g,tickUpper:b,minPrice:y,maxPrice:w,minPercentChange:(y-r)/r*100,maxPercentChange:(w-r)/r*100}};return[p("stable","Stable","Good for stablecoins or low volatility pairs",o,s),p("wide","Wide","Good for volatile pairs",d,u)]}var ie=class{swapFactory;constructor(e){this.swapFactory=e?.swapFactory??So}isSupported(e){if(!e)return!1;let t=D(e)??e.toLowerCase();return!!mt(t)}listSupportedChains(){return Object.keys(Jd).filter(e=>Be(e))}getRpcUrl(e){let t=Mn(e);if(t)return t;let r=mt(e);if(!r)throw new Error(`Unsupported chain: ${e}`);return r.defaultRpc}async getGatewayAddress(e){return kn.getGatewayAddress(e)}async isAddLiquiditySupported(e){return this.isSupported(e)&&!!await this.getGatewayAddress(e)}async listAddLiquiditySupportedChains(){let e=await kn.getGatewayChains(),t=[];for(let r of e){let o=D(r);o&&mt(o)&&!t.includes(o)&&t.push(o)}return t.length>0?t:this.listSupportedChains()}async getPositionManagerAddress(e){return kn.getPositionManagerAddress(e)}client(e){return Re(e)}async ethCall(e,t,r){let{data:o}=await this.client(e).call({to:t,data:r});return o??"0x"}async getNativeBalance(e,t){return this.client(e).getBalance({address:t})}async getGasPrice(e){return this.client(e).getGasPrice()}async getTransactionReceipt(e,t){return this.client(e).rpc("eth_getTransactionReceipt",[t])}async extractMintedNftId(e,t){let r=await this.getPositionManagerAddress(e);if(!r)return null;let o=r.toLowerCase();for(let s of t.logs??[]){if((s.address??"").toLowerCase()!==o)continue;let a=s.topics??[];if(!(a.length<4||a[0]?.toLowerCase()!==Zd||"0x"+a[1].slice(-40).toLowerCase()!==ue))try{return BigInt(a[3]).toString()}catch{return null}}return null}async estimateGasReserveWei(e){let t=mt(e);if(!t)throw new Error(`Unsupported chain: ${e}`);let r=await this.getGasPrice(e);return BigInt(t.defaultMintGasLimit)*r*18n/10n}async readPoolOnchain(e,t){let o={address:t,abi:Fl},[s,a,i,l,c,d]=await this.client(e).multicall({contracts:[{...o,functionName:"slot0"},{...o,functionName:"liquidity"},{...o,functionName:"tickSpacing"},{...o,functionName:"fee"},{...o,functionName:"token0"},{...o,functionName:"token1"}],allowFailure:!1}),[u,p]=s,m=c.toLowerCase(),f=d.toLowerCase(),[h,g]=await Promise.all([this.readErc20Decimals(e,m),this.readErc20Decimals(e,f)]),b=Vd(u,h,g);return{poolAddress:t,chainId:e,fee:l,tickSpacing:i,liquidity:a,sqrtPriceX96:u,currentTick:p,token0:m,token1:f,currentPrice:b}}async readErc20Decimals(e,t){return t.toLowerCase()===ue?18:this.client(e).readContract({address:t,abi:q,functionName:"decimals"})}async getNativePriceUsd(e){let t=mt(e);if(!t)return null;try{let r=`https://api.coingecko.com/api/v3/simple/price?ids=${t.native.coingeckoId}&vs_currencies=usd`,o=await C.get(r);if(!o.ok)return null;let a=o.data[t.native.coingeckoId]?.usd;return typeof a=="number"?a:null}catch{return null}}splitNativeAmountForRange(e){let{nativeAmountWei:t,pool:r,tickLower:o,tickUpper:s,token0Decimals:a,token1Decimals:i}=e,l=2**96,c=Number(r.sqrtPriceX96)/l,d=Math.pow(1.0001,o/2),u=Math.pow(1.0001,s/2);if(c<=d)return{ratio0:1,ratio1:0,amountInFor0Wei:t,amountInFor1Wei:0n};if(c>=u)return{ratio0:0,ratio1:1,amountInFor0Wei:0n,amountInFor1Wei:t};let p=1/c-1/u,m=c-d,f=c*c,h=p*f,b=h+m;if(!Number.isFinite(b)||b<=0)throw new Error("splitNativeAmountForRange: invalid total value");let y=h/b,w=1-y,k=1000000000000000n,v=BigInt(Math.floor(y*Number(k))),S=t*v/k,P=t-S;return{ratio0:y,ratio1:w,amountInFor0Wei:S,amountInFor1Wei:P}}async fetchSwapLeg(e){let t=Number.parseInt(e.chainId,16);if(!Number.isFinite(t))throw new Error(`Invalid hex chain id: ${e.chainId}`);let o=await(await this.swapFactory.getService({route:"pool",srcChainId:t})).getQuote({srcChainId:t,srcTokenAddress:e.tokenIn,srcTokenAmount:e.tokenInAmount,dstChainId:t,dstTokenAddress:e.tokenOut,recipientAddress:e.tokenOutRecipient,senderAddress:e.senderAddress??e.tokenOutRecipient,slippage:e.slippage,isCrossChain:!1});if(!o.success||!o.tx)throw new Error(o.errorMessage??"Swap quote failed");let s=o.tx;if(!s.to||typeof s.data!="string")throw new Error("Swap quote returned an unsupported tx shape (non-EVM payload?)");let a=o.raw??{},i=a.tokenOut?.minAmount??a.details?.currencyOut?.minimumAmount??"0";return{to:s.to,data:s.data,value:s.value??"0",minAmountOut:i}}};var ly={"0x1":"ethereum","0xa":"optimism","0x38":"bnb","0x89":"polygon","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avalanche"},cy=/^0x[a-fA-F0-9]{40}$/;function Ws(n,e){if(typeof n!="string"||typeof e!="string")return null;let t=ly[n.toLowerCase()];return!t||!cy.test(e)?null:`https://app.uniswap.org/explore/pools/${t}/${e}`}function ht(n,e){let t=Ws(n,e);return t?{uniswapUrl:t}:{}}var ep=Object.keys(fn),nt="Hex chain ID of the chain the user named. Map the chain name to its EXACT hex id \u2014 pass ONLY one of these values, never a guessed or made-up one: Ethereum=0x1, Optimism=0xa, BSC=0x38, Polygon=0x89, Base=0x2105, Arbitrum=0xa4b1, Avalanche=0xa86a, Linea=0xe708, Gnosis=0x64, HyperEVM=0x3e7, Mantle=0x1388, Monad=0x8f. Set this WHENEVER the user EXPLICITLY names a chain (always send the exact hex from this list). Otherwise OMIT it entirely so the connected wallet chain is used automatically.";function Oe(){return ep.filter(n=>Be(n)).map(n=>T(n)).join(", ")}function rt(){return{kind:"info",async listSupported(){return ep.filter(n=>Be(n))},async isSupported(n){if(!n)return!1;let e=D(n)??n.toLowerCase();return Object.prototype.hasOwnProperty.call(fn,e)}}}function vn(n){return{kind:"add-liquidity",listSupported:()=>n.listAddLiquiditySupportedChains(),isSupported:e=>n.isAddLiquiditySupported(e)}}function uc(n,e,t){let r=o=>typeof o=="string"&&o.trim()!=="";if(r(n))return D(n)??n.trim();if(r(e?.chain))return D(e.chain)??e.chain.trim();if(r(e?.walletAddress))throw new ge(typeof e?.query=="string"?e.query:void 0,t);return Je}async function te(n,e,t){let r=await n.listSupported(),o=uc(e,t,r);return await n.isSupported(o)?{ok:!0,chain:o}:{ok:!1,result:dc(o,r,n.kind)}}function dc(n,e,t="info"){return{_instructions:`${t==="add-liquidity"?"Adding liquidity is NOT available on this network. Tell the user, in their language, that they cannot add liquidity / provide LP on this chain yet (note: viewing pool info may still work on other chains). Then name the chains where adding liquidity IS available":"Liquidity-pool data is NOT available on this network. Tell the user, in their language, that pools are not supported on this chain. Then name the chains where pools ARE available"} using EXACTLY and ONLY the entries in the \`supportedChains\` field below \u2014 copy them verbatim, add nothing. CRITICAL: this list is the complete, authoritative set. Do NOT add, infer, or invent ANY other chain \u2014 NOT EVEN a chain this app supports for wallet/token/DeFi features (for example Gnosis, HyperEVM, Mantle, and Monad are NOT pool chains; never list them unless they literally appear in \`supportedChains\`). Keep it short and friendly. Do NOT mention tools, services, APIs, forms, or any internals.`,unsupportedChain:T(n),supportedChains:e.map(o=>T(o))}}var ki="{pair}";var Ee=[{name:"add_button_label",type:"string",description:`Label template for the per-pool "Add liquidity" buttons that render under EVERY pool you show, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each pool automatically. Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:`A short "add liquidity" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a pool's button is clicked. ALWAYS provide it. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name or a pool address yourself \u2014 the pool address and the chain these pools are on are appended automatically as "(Pool: 0x\u2026 - <chain>)".`,required:!1}],de=' A clickable "Add liquidity" button is shown below your reply for each pool automatically \u2014 do NOT list, number, or repeat those buttons in your text; just deliver your analysis.';function pe(n,e,t){return pc(n,typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",t)}function pc(n,e,t,r){let o=typeof r=="string"?r.trim():"",s=[];for(let a of n){if(s.length>=5)break;let i=a.token0?.symbol?.trim(),l=a.token1?.symbol?.trim();if(!i||!l)continue;let c=dy(i,l,a.feeTierPercent);s.push({label:tp(e,c,`Add liquidity to ${ki}`),prompt:tp(t,c,`add liquidity to ${ki}`)+uy(a.address,o)})}return s}function uy(n,e){let r=[typeof n=="string"&&n.trim()?`Pool: ${n.trim()}`:"",e].filter(Boolean);return r.length>0?` (${r.join(" - ")})`:""}function dy(n,e,t){let r=`${n}/${e}`;return typeof t=="number"&&Number.isFinite(t)?`${r} ${py(t)}%`:r}function py(n){return Number(n.toFixed(4)).toString()}function tp(n,e,t){return(n&&n.includes(ki)?n:t).split(ki).join(e).replace(/\s+/g," ").trim()}var me="You are a seasoned DEX liquidity-pool analyst with deep, credible expertise. Deliver a genuinely insightful, professional read \u2014 the kind a sophisticated LP would pay for \u2014 in natural, flowing prose rather than a rigid template, never sacrificing depth or authority for a conversational tone. ",he='Ground every judgement rigorously in the data, never guesses \u2014 and only use a signal when its data is present: \u2022 capital efficiency = `volumeToTvlRatio` (volume \xF7 TVL) \u2014 higher means each $ of liquidity earns more fees; >1 is very active, <0.1 is sluggish. \u2022 APR quality \u2014 a very high APR sitting on a TINY TVL is usually volatile/unsustainable (treat with caution); a solid APR on deep TVL is the sweet spot. When an APR field is ABSENT there is no yield reading for that pool: say nothing about its APR \u2014 never print "APR 0%", "APR: N/A", a dash, or infer the yield from other fields. Judge such a pool on its remaining metrics alone. \u2022 TVL trend \u2014 when a 24h TVL % change is present, note whether liquidity is growing or shrinking. \u2022 TVL depth \u2014 deeper pools = lower slippage and a steadier position; thin pools carry higher risk. \u2022 fee tier vs pair type \u2014 stable/correlated pairs suit low tiers (0.01\u20130.05%), volatile pairs suit higher tiers (0.3\u20131%). \u2022 token safety \u2014 when a token exposes isSpam=true or a non-VERIFIED safetyLevel, FLAG it prominently as a risk. \u2022 transfer tax \u2014 when a token exposes transferFeeBps, it charges that tax (in basis points: 200 = 2%) on transfers. FLAG it prominently: it eats directly into LP returns, and a high or one-sided tax is a common honeypot trait. \u2022 unrecognized token \u2014 when a token exposes isUnrecognizedToken=true, Uniswap does not know that contract at all. Treat this as a SEVERE warning, stronger than any safetyLevel: a token wearing a well-known ticker (WBTC, USDC\u2026) on a contract Uniswap cannot identify is most likely an impostor. Say so plainly and advise verifying the contract address before providing any liquidity. ',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. ",Y="End with a brief reminder that yields fluctuate and concentrated LPs face impermanent loss (informational, not financial advice). ",j=`LINKS \u2014 write every pool pair as PLAIN TEXT only (e.g. "USDC/WETH"). Do NOT create markdown links, do NOT output any URLs, and do NOT print raw pool or token contract addresses anywhere in your answer. The system automatically turns each pool's pair into the correct clickable link after you reply, so you must NEVER add a link, a "Link to pool" line, a "View on Uniswap" line, or a bare URL yourself \u2014 doing so produces wrong/duplicate links. Just name each pair in text. Format numbers human-readably (e.g. $12.5M, +1.23%, 0.05%). Omit null fields. Answer in the user's language. Do NOT mention tool or API names.`;var my=["tvl","volume1Day","volume30Day","apr"],hy=["V2","V3","V4"],Eo=class extends A{name="uniswap-top-pools";description=`List the top Uniswap liquidity pools on a given EVM chain, ranked by TVL by default. Returns each pool's address, fee tier, protocol version, both tokens (symbol, name, address, decimals), TVL, rolling volume (1d / 30d), and estimated APR. Use this tool for questions like: "top pools on Ethereum", "biggest Uniswap V3 pools on Base", "which pool has the most liquidity for USDC", "show pools with highest 24h volume on Arbitrum". Source: https://app.uniswap.org/explore (ListPools gateway). Supports: `+Oe();category="blockchain-data";parameters=[{name:"chain",type:"string",description:nt,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version to filter by: "V2", "V3", or "V4". Default is "V3" (the dataset with the richest stats). Use "V4" only when the user explicitly asks for V4 pools.',required:!1,default:"V3"},{name:"sortBy",type:"string",description:'Ranking metric: "tvl" (total value locked, default), "volume1Day", "volume30Day", or "apr" (estimated annualized fee yield, net of the protocol fee). Pools are returned in descending order by this metric.',required:!1,default:"tvl"},{name:"limit",type:"number",description:'Maximum number of pools to return after sorting. Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"multichain",type:"boolean",description:"When true, request Uniswap's multichain aggregated view instead of a single chain. Defaults to false. Most queries should leave this off.",required:!1,default:!1},{name:"forAddLiquidity",type:"boolean",description:'Set TRUE only when this ranking is the ENTRY POINT of the ADD-LIQUIDITY flow \u2014 the user wants to add / provide liquidity ("add pool", "i want to add liquidity", "th\xEAm thanh kho\u1EA3n") but named NO specific pool, so you show top pools (use sortBy="apr") for them to pick one. In that mode the tool gates on ADD-LIQUIDITY chain support (only chains with a gateway) and, when the connected chain has no gateway, returns the "adding liquidity is not available on this chain" message with the correct supported list \u2014 so the user is told up front, not after picking a pool. OMIT (false) for ordinary informational rankings ("top pools on Base", "biggest pools").',required:!1,default:!1},...Ee];service;subgraphFallback;pool;constructor(e,t){super(),this.service=new $e(e),this.subgraphFallback=new xe(t),this.pool=new ie}async run(e,t){let r=e.forAddLiquidity===!0,o=r?vn(this.pool):rt(),s=await o.listSupported(),a=uc(e.chain,t,s),i=this.parseProtocolVersion(e.protocolVersion),l=this.parseSortKey(e.sortBy),c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,d=!r&&e.multichain===!0;if(!d&&!await o.isSupported(a))return dc(a,s,o.kind);let u=await this.service.getTopPools({chain:a,protocolVersion:i,sortBy:l,limit:c,multichain:d});if(!u.success)return{error:u.error||"Failed to fetch top pools"};let p=(u.data??[]).map(w=>this.formatPool(w)),m="uniswap";if(p.length===0&&i==="V3"){let w=await this.fetchV3Fallback(a,l,c);w.length>0&&(p=w,m="subgraph")}let f=p.map(w=>this.withExpertSignals(w)),h=await this.pool.isAddLiquiditySupported(a)?pe(f,e,T(a)):[],g=m==="subgraph",b=g?`"Volume past day" (translate naturally into the user's language; NEVER call it "24h volume", "daily volume", or "24h")`:"24h volume";return{_instructions:(g?`BEGIN your answer with "According to the latest data from Subgraph Uniswap V3," (translate the sentence naturally into the user's language but keep the word "Subgraph" as-is). `:"")+me+`You are briefing a peer. Present the pools as a ranked list, then deliver the analysis. For each pool include the key facts: rank, pair (token0/token1 symbols), fee tier (in %), TVL in USD, ${b}, and APR (in %). CRITICAL: every pool MUST have its own written analysis \u2014 2\u20133 sentences of genuine expert read placed directly under that pool's facts. NEVER skip a pool and NEVER reduce a pool to just a facts list. Vary the wording from pool to pool (do not repeat the same sentence structure), go a little deeper on the standouts, and surface the non-obvious insight a less experienced observer would miss. `+he+"After the per-pool reads, close with a short overall section that (1) gives a high-level read across the whole list \u2014 the broad pattern you see (where the real capital efficiency and fee yield sit, how the risk/reward stacks up), (2) names the single best pool to provide liquidity in right now and explains why it stands out, and (3) gives the user a concrete, actionable recommendation tailored to the data. "+be+Y+"Mention the chain and the sort metric in the intro line. "+j+(h.length>0?de:""),chain:a,protocolVersion:i,sortBy:l,source:m,count:f.length,pools:f.map(w=>({...w,...ht(a,w.address)})),...h.length>0?{actionButtons:h}:{}}}withExpertSignals(e){let t=a=>Math.round(a*1e3)/1e3;if(typeof e.volumeToTvlRatio=="number"&&Number.isFinite(e.volumeToTvlRatio))return{...e,volumeToTvlRatio:t(e.volumeToTvlRatio)};let r=e.tvlUsd,o=e.volume1DayUsd,s=typeof r=="number"&&r>0&&typeof o=="number"?t(o/r):void 0;return{...e,volumeToTvlRatio:s}}async fetchV3Fallback(e,t,r){try{return(await this.subgraphFallback.getTrendingPools({chain:e})).map(i=>this.formatSubgraphPool(i,e)).sort((i,l)=>this.fallbackSortValue(l,t)-this.fallbackSortValue(i,t)).slice(0,r)}catch{return[]}}fallbackSortValue(e,t){switch(t){case"apr":return e.apr??0;case"volume1Day":case"volume30Day":return e.volume1DayUsd??0;default:return e.tvlUsd??0}}formatSubgraphPool(e,t){return{apr:$(e.apr),totalApr:void 0,address:e.poolAddress,chain:t,protocolVersion:"V3",feeTierBps:e.feeTierBps,feeTierPercent:typeof e.feeTierBps=="number"?e.feeTierBps/1e4:void 0,tvlUsd:e.tvl,fee24hUsd:e.fees24hUsd,volume1DayUsd:e.volume24hUsd,volume1WeekUsd:void 0,volume30DayUsd:void 0,volumeToTvlRatio:void 0,txCount:void 0,token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:void 0,priceUsd:void 0,isSpam:void 0,safetyLevel:void 0}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:void 0,priceUsd:void 0,isSpam:void 0,safetyLevel:void 0}:void 0}}parseProtocolVersion(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(hy.includes(t))return t}return"V3"}parseSortKey(e){if(typeof e=="string"){let t=e.trim();if(my.includes(t))return t}return"tvl"}formatPool(e){let t=e.isDynamicFee===!0||hn(e.feeTier);return{apr:$(e.apr),totalApr:typeof e.totalApr=="number"&&typeof e.apr=="number"&&e.totalApr>e.apr?e.totalApr:void 0,address:e.id,chain:e.chain,protocolVersion:e.protocolVersion,feeTierBps:t?void 0:e.feeTier,feeTierPercent:!t&&typeof e.feeTier=="number"?e.feeTier/1e4:void 0,...t?{isDynamicFee:!0}:{},tvlUsd:e.totalLiquidity?.value,fee24hUsd:e.fee24hUsd,volume1DayUsd:e.volume1Day?.value,volume1WeekUsd:e.volume1Week?.value,volume30DayUsd:e.volume30Day?.value,volumeToTvlRatio:e.volumeToTvlRatio,txCount:e.txCount,token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.price?.value,isSpam:e.token0.project?.isSpam,safetyLevel:e.token0.project?.safetyLevel}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:e.token1.decimals,priceUsd:e.token1.price?.value,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}};var mc={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114},fy={100:.01,500:.05,3e3:.3,1e4:1},Tn=class{coinPoolBaseUrl;constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}isSupported(e){let t=D(e);return!!(t&&mc[t])}listSupportedChains(){return Object.keys(mc).filter(e=>D(e)===e)}numericChainId(e){let t=D(e);return t?mc[t]:void 0}async getPairs(e){let t=this.numericChainId(e.chain);if(!t)return[];let o=(await this.fetchV2Items(t)).map(s=>this.mapV2Item(s)).filter(s=>s!==null);if(e.tokens&&e.tokens.length>=2){let s=e.tokens[0].toUpperCase(),a=e.tokens[1].toUpperCase(),i=(l,c)=>l.includes(c)||c.includes(l);o=o.filter(l=>{let[c="",d=""]=l.pair.toUpperCase().split("/");return i(c,s)&&i(d,a)||i(c,a)&&i(d,s)})}return o}async getByAddress(e){let t=this.numericChainId(e.chain);if(!t)return[];let r=e.poolAddress.toLowerCase();return(await this.fetchV2Items(t)).filter(s=>s.poolId?.toLowerCase()===r).map(s=>this.mapV2Item(s)).filter(s=>s!==null).sort((s,a)=>(a.apr??-1/0)-(s.apr??-1/0))}async fetchV2Items(e){try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,r=await C.get(t);if(!r.ok)throw new Error(_(r));return r.data?.data?.items||[]}catch{return[]}}mapV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,r=e.token1.decimal??18,o=S=>S==null||!Number.isFinite(S)?0:Math.pow(1.0001,S)*Math.pow(10,t-r),s=o(e.minTick),a=o(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,d=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),u=d?s:a>0?1/a:0,p=d?a:s>0?1/s:0,m=d?c:c>0?1/c:0,f=d?e.token0.symbol:e.token1.symbol,h=d?e.token1.symbol:e.token0.symbol;if(!m||!u&&!p)return null;let g=Math.min(u,p),b=Math.max(u,p);if(m<g||m>b)return null;let y=Number(e.fee),w=fy[y]??y/1e4,k=$(e.apr)??$(e.aprAvg)??null,v=$(e.aprAvg)??null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:v,token0Price:i,token1Price:l,priceRange:{minPrice:Se(u),maxPrice:Se(p),currentPrice:Se(m),baseToken:f,quoteToken:h}}}};function gy(n){if(!(!n||n.length===0))return n.map(e=>({timestamp:e.timestamp,volumeUsd:e.value}))}function yy(n,e){if(!(typeof n!="number"||typeof e!="number"||e<=0))return Math.round(n/e*1e3)/1e3}function zn(n,e){let t=e!==void 0&&Array.from(e.values()).some(i=>i.safetyLevel!=null),r=n.totalLiquidity?.value,o=n.volume24h?.value,s=n.feeTier,a=di(s,n.protocolFee,n.protocolVersion);return{address:n.address??n.poolId,protocolVersion:n.protocolVersion,poolId:n.poolId,tickSpacing:n.tickSpacing,isDynamicFee:n.isDynamicFee,hookAddress:n.hook?.address,feeTierBps:s,feeTierPercent:typeof s=="number"?s/1e4:void 0,tvlUsd:r,tvlChange24hPercent:n.totalLiquidityPercentChange24h?.value,volume24hUsd:o,fees24hUsd:pi(o,s,a),lpFeeShare:a,aprPercent:$(n.apr),totalAprPercent:$(n.totalApr),volumeToTvlRatio:yy(o,r),txCount:n.txCount,historicalVolumeWeek:gy(n.historicalVolume),token0:np(n.token0,n.token0Supply,e,t),token1:np(n.token1,n.token1Supply,e,t)}}function np(n,e,t,r){if(!n)return;let o=n.address?t?.get(n.address.toLowerCase()):void 0,s=r&&n.address!=null&&!o?.safetyLevel,a=o?.isSpam==null?void 0:o.isSpam.toUpperCase()==="TRUE",i=Number(o?.feeData?.buyFeeBps??0),l=Number(o?.feeData?.sellFeeBps??0),c=Number.isFinite(i)&&Number.isFinite(l)?Math.max(i,l):0;return{address:n.address,symbol:n.symbol,name:n.name,decimals:n.decimals,priceUsd:n.market?.price?.value??n.price?.value,reserve:e,isSpam:a??n.project?.isSpam??void 0,safetyLevel:o?.safetyLevel??n.project?.safetyLevel??void 0,transferFeeBps:c>0?c:void 0,isUnrecognizedToken:s||void 0}}var rp=/^0x[a-fA-F0-9]{40}$/,by=6,_o=class extends A{name="uniswap-pool-detail";description="Get detailed stats for a Uniswap V3 pool by token pair (and optional fee tier). Always runs a search first and filters by the provided symbols + fee tier. When the filter resolves to exactly one pool, returns its full detail. When the pair is fully named but NO fee tier is given, returns detail plus a comparative analysis of ALL the pair's fee-tier variants (no need to ask the user to pick). When only one token is given (so the matches are different pairs), returns a `candidates` list \u2014 show it and ask which pair they want, then re-call this tool with the missing info. Detail response includes: pool address, fee tier (bps and %), both tokens (symbol, name, address, decimals, USD price), token0/token1 reserves, total TVL with 24h % change, 24h volume, weekly historical volume series, total tx count, and the pool's fee APR (net of the protocol fee). NEVER pass a pool address \u2014 the tool resolves the address itself by searching. Token contract addresses are NOT pool addresses. Source: https://app.uniswap.org. Supports: "+Oe();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:`Symbol of one of the pool's tokens (e.g. "USDC"). Pair order does not matter \u2014 USDC/WETH and WETH/USDC resolve to the same pool. When both token0Symbol and token1Symbol are provided the search is filtered to that exact pair.`,required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Optional \u2014 when omitted the tool returns all pools containing token0Symbol so the user can pick.',required:!1},{name:"feeTier",type:"number",description:'Fee tier in basis points (bps): 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. ONLY set this when the user EXPLICITLY mentions a fee tier (in the current message OR earlier in the conversation, e.g. "USDC/WETH 0.05%" \u2192 feeTier=500). NEVER guess or infer one. When the user has not mentioned a fee tier, OMIT it \u2014 the tool then returns detail plus a comparative analysis of ALL fee-tier variants of the pair (no need to ask the user to pick one).',required:!1},{name:"chain",type:"string",description:nt,required:!1},...Ee];service;coinPool;pool;constructor(e,t){super(),this.service=new $e(e),this.coinPool=new Tn(t),this.pool=new ie}async run(e,t){let r=await te(rt(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",a=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0;if(!s)return{error:"token0Symbol is required. Provide at least one token symbol; add token1Symbol and feeTier to narrow the result."};let l=a?`${s} ${a}`:s,c=await this.service.searchPools({query:l,chain:o,page:1,size:100,protocolVersion:"V3"});if(!c.success)return{error:c.error||"Pool search failed"};let d=c.data??[],p=d.filter(g=>this.matchesFilter(g,s,a,i,"ordered")),m=!1;if(p.length===0&&a){let g=d.filter(b=>this.matchesFilter(b,s,a,i,"reversed"));g.length>0&&(p=g,m=!0)}if(p.length===0)return{error:`No V3 pool matched ${this.describeQuery(s,a,i)} on ${T(o)}. Verify the symbols and fee tier with the user.`};if(p.length===1){let g=p[0];if(!g.id||!rp.test(g.id))return{error:"Resolved pool has no valid address"};let[b,y,w]=await Promise.all([this.service.getPoolDetailEnriched({addressOrId:g.id,chain:o}),this.fetchPriceRanges(o,g.id,g.token0?.symbol,g.token1?.symbol),this.service.getTokenSafetyByAddress([g.token0?.address,g.token1?.address],o)]);if(!b.success||!b.data)return{error:b.error||"Failed to fetch pool detail"};let k={...zn(b.data,w),...ht(o,g.id)},v=await this.pool.isAddLiquiditySupported(o)?pe([k],e,T(o)):[];return{priceRanges:y,_instructions:me+"Give an expert read on ONE pool. First, a SNAPSHOT block: lead with the pair (token0/token1 symbols), fee tier (%), and chain, then show TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), token0 reserve + USD price, token1 reserve + USD price, and total tx count. Optionally include the weekly historical volume as a sparkline-style bullet list. Then an EXPERT ANALYSIS section \u2014 is this pool worth providing liquidity in, and why. "+he+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` \u2014 omitting the APR for any entry whose `apr` is null/absent (never "APR 0%", "N/A" or a dash). CRITICAL: that `apr` is the yield for THAT specific range only \u2014 NEVER present it as the overall pool APR. Sort by apr desc; note the top entry is the most concentrated/highest-yield range but narrower = higher risk of going out of range. When `priceRanges` is empty or absent, simply omit this section. '+Y+j+(v.length>0?de:""),pairOrderMatched:m?"reversed":"ordered",pool:k,...v.length>0?{actionButtons:v}:{}}}if(a){let g=this.rankCandidates(p).slice(0,by),[b,y]=await Promise.all([Promise.all(g.map(async k=>{if(!k.id||!rp.test(k.id))return;let v=await this.service.getPoolDetailEnriched({addressOrId:k.id,chain:o});if(!(!v.success||!v.data))return{detail:v.data,id:k.id}})),this.service.getTokenSafetyByAddress(g.flatMap(k=>[k.token0?.address,k.token1?.address]),o)]),w=b.filter(k=>k!=null).map(k=>({...zn(k.detail,y),...ht(o,k.id)}));if(w.length>0){let k=await this.pool.isAddLiquiditySupported(o)?pe(w,e,T(o)):[];return{_instructions:me+"The user named a pair WITHOUT a fee tier, so here is EVERY fee-tier variant of that pair \u2014 do NOT ask them to pick a tier. Present them as a ranked list (rank them by capital efficiency / fee yield, not just TVL). For each variant show the fee tier (%), TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), and tx count. Analyze every variant \u2014 give each its own genuine read, never skip one, and never repeat the same sentence structure. "+he+"Focus on which fee tier is the right home for THIS pair: lower tiers (0.01\u20130.05%) win on stable/correlated pairs and high turnover, higher tiers (0.3\u20131%) suit volatile pairs \u2014 and the tier that actually captures most of the real volume with deep TVL is usually the one to LP in. Close with an overall section naming the single best fee tier to provide liquidity in right now and why. "+be+Y+j+(k.length>0?de:""),chain:o,pairOrderMatched:m?"reversed":"ordered",multiFeeTier:!0,count:w.length,pools:w,...k.length>0?{actionButtons:k}:{}}}}let f=this.rankCandidates(p).slice(0,10).map(g=>{let b=this.formatCandidate(g);return{...b,...ht(o,b.address)}}),h=await this.pool.isAddLiquiditySupported(o)?pe(f,e,T(o)):[];return{_instructions:"The filter matched multiple pools. Render them as a numbered list (pair, fee tier %, 24h volume) and ask the user which one they want to see. Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. When they answer, re-call this tool with their selection \u2014 pass token0Symbol + token1Symbol + feeTier (use the exact feeTier in bps from the chosen candidate). Format numbers human-readably (e.g. $12.5M, 0.05%). Do NOT mention tool/API names."+(h.length>0?de:""),chain:o,pairOrderMatched:m?"reversed":"ordered",reason:this.candidateReason(s,a,i),missing:this.missingFields(a,i),candidates:f,...h.length>0?{actionButtons:h}:{}}}matchesFilter(e,t,r,o,s){if(o!=null&&e.feeTier!==o)return!1;let a=(e.token0?.symbol??"").toLowerCase(),i=(e.token1?.symbol??"").toLowerCase(),l=t.toLowerCase();if(r){let c=r.toLowerCase();return s==="reversed"?this.symbolIncludes(a,c)&&this.symbolIncludes(i,l):this.symbolIncludes(a,l)&&this.symbolIncludes(i,c)}return this.symbolIncludes(a,l)||this.symbolIncludes(i,l)}symbolIncludes(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}describeQuery(e,t,r){let o=t?`${e}/${t}`:e;return r!=null?`${o} at fee tier ${r} bps`:o}candidateReason(e,t,r){return t?r==null?`Multiple fee tiers exist for ${e}/${t}. Ask the user which fee tier they want.`:`Multiple ${e}/${t} pools share fee tier ${r} bps. Ask the user which one they meant.`:`Multiple pools contain ${e}. Ask the user for the other token (and fee tier).`}missingFields(e,t){let r=[];return e||r.push("token1Symbol"),t==null&&r.push("feeTier"),r}rankCandidates(e){return[...e].sort((t,r)=>(r.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}formatCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}async fetchPriceRanges(e,t,r,o){try{if(!this.coinPool.isSupported(e))return[];let s=await this.coinPool.getByAddress({chain:e,poolAddress:t});return s.length===0&&r&&o&&(s=await this.coinPool.getPairs({chain:e,tokens:[r,o]})),s.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}};var wy=["V2","V3","V4","ALL"],No=class extends A{name="uniswap-search-pools";description='Search Uniswap liquidity pools on a given chain by free-text query \u2014 a SINGLE token symbol or token name. Returns matching pools with: pool address, fee tier (bps + %), protocol version, both tokens (symbol, name, address, decimals, logo), and short-window USD volume buckets (6h / 12h / 24h). Use this tool when the user names ONE token and wants pools related to it: "find WBTC pools on Optimism", "pools containing PEPE on Ethereum", "show USDC pools". Do NOT use for: (a) two-symbol pair lookups like "USDC/WETH 0.05%" \u2014 use get-pool-detail; (b) raw 0x addresses (token or pool) \u2014 use lookup-pool-by-address; (c) chain-wide rankings with no token mentioned \u2014 use get-top-pools. Source: https://app.uniswap.org search. Supports: '+Oe();category="blockchain-data";parameters=[{name:"query",type:"string",description:'Single token symbol or name to search pools by (e.g. "WBTC", "USDC", "pepe"). Do NOT pass a 0x address (use lookup-pool-by-address) or a two-symbol pair (use get-pool-detail).',required:!0},{name:"chain",type:"string",description:nt,required:!1},{name:"protocolVersion",type:"string",description:'Filter results by Uniswap protocol version: "V2", "V3", "V4", or "ALL" to include every version. Default is "V3" \u2014 only switch when the user explicitly asks for V2, V4, or all versions.',required:!1,default:"V3"},{name:"page",type:"number",description:"1-based page index. Defaults to 1.",required:!1,default:1},{name:"size",type:"number",description:'Page size (max 50). Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"feeTier",type:"number",description:'Optional fee tier filter in basis points (bps): 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. When provided, only pools with this exact fee tier are returned. Pass it whenever the user mentions a fee tier in the current message OR earlier in the conversation (e.g. "USDC/WETH 0.05% pool on Base" \u2192 feeTier=500). Omit otherwise.',required:!1},...Ee];service;pool;constructor(e){super(),this.service=new $e(e),this.pool=new ie}async run(e,t){let r=typeof e.query=="string"?e.query.trim():"";if(!r)return{error:"Search query is required"};let o=await te(rt(),e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=typeof e.page=="number"&&Number.isFinite(e.page)&&e.page>0?Math.floor(e.page):1,i=typeof e.size=="number"&&Number.isFinite(e.size)&&e.size>0?Math.min(Math.floor(e.size),50):5,l=this.parseProtocolFilter(e.protocolVersion),c=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.floor(e.feeTier):void 0,d=await this.service.searchPools({query:r,chain:s,page:a,size:i,protocolVersion:l,feeTier:c});if(!d.success)return{error:d.error||"Failed to search pools"};let u=(d.data??[]).map(m=>this.formatPool(m)),p=await this.pool.isAddLiquiditySupported(s)?pe(u,e,T(s)):[];return{_instructions:me+"Present the pools that match the search AND give an expert read on each. Render each pool as its own block: a bold header with the pair (token0/token1 symbols) + fee tier (%), then beneath it the metrics that have data \u2014 TVL (USD), 24h volume (USD), APR (%), tx count, protocol version. Skip any field that is null/undefined \u2014 never show zeros or dashes for missing data. Then add an expert read on each pool \u2014 is it worth providing liquidity in, and why. "+he+be+"When several pools share the searched token, finish with a clear TOP PICK among them. "+Y+"Mention the search query and chain in the intro. "+j+(p.length>0?de:""),query:r,chain:s,protocolVersion:l,feeTierBps:c,feeTierPercent:c!=null?c/1e4:void 0,page:a,size:i,count:u.length,pools:u.map(m=>({...m,...ht(s,m.address)})),...p.length>0?{actionButtons:p}:{}}}parseProtocolFilter(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(wy.includes(t))return t}return"V3"}formatPool(e){let t=e.isDynamicFee===!0||hn(e.feeTier),r={address:e.id,chainId:e.chainId,protocolVersion:e.protocolVersion,feeTierBps:t?void 0:e.feeTier,feeTierPercent:!t&&typeof e.feeTier=="number"?e.feeTier/1e4:void 0,...t?{isDynamicFee:!0}:{}},o=$(e.apr);o!=null&&(r.apr=o),e.tvlUsd!=null&&(r.tvlUsd=e.tvlUsd);let s=e.volume1DayUsd??e.volumeUsd24hr;s!=null&&(r.volume24hUsd=s),e.volumeUsd6hr!=null&&(r.volume6hUsd=e.volumeUsd6hr),e.volumeUsd12hr!=null&&(r.volume12hUsd=e.volumeUsd12hr),e.txCount!=null&&(r.txCount=e.txCount),e.tvlUsd!=null&&e.tvlUsd>0&&s!=null&&(r.volumeToTvlRatio=Math.round(s/e.tvlUsd*1e3)/1e3);let a=e.token0,i=e.token1;return a&&(r.token0={address:a.address,symbol:a.symbol,name:a.name,decimals:a.decimals}),i&&(r.token1={address:i.address,symbol:i.symbol,name:i.name,decimals:i.decimals}),r}};var Lo=class extends A{name="uniswap-pool-by-address";description=`Resolve an unknown 0x address as either a Uniswap pool or a token, then return the appropriate data: pool detail when the address is a pool, or the list of pools containing that token when the address is a token. Use this tool when the user pastes a single address and asks about "the pool" without saying which kind. For pool detail (when the address is a pool): pair, fee tier, TVL with 24h % change, 24h volume, 24h fees, estimated APR, token reserves with USD prices, and each token's safety flags. For token resolution (when the address is a token): the resolved token (symbol, name, decimals) plus a ranked list of pools that include it (pair, fee tier, 24h volume, pool address). Source: https://app.uniswap.org. Supports: `+Oe();category="blockchain-data";parameters=[{name:"address",type:"string",description:"A 0x-prefixed EVM address. May be a Uniswap pool contract OR a token contract \u2014 the tool figures out which.",required:!0},{name:"chain",type:"string",description:nt,required:!1},...Ee];service;pool;constructor(e){super(),this.service=new $e(e),this.pool=new ie}async run(e,t){let r=await te(rt(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.address=="string"?e.address.trim():"",[a,i]=await Promise.all([this.service.searchPools({query:s,chain:o,page:1,size:5,protocolVersion:"ALL"}),this.service.searchTokens({query:s,chain:o,page:1,size:5})]),l=a.success?this.findPoolByAddress(a.data??[],s):void 0;if(l)return this.handlePoolHit(l,o,e);let c=i.success?this.findTokenByAddress(i.data??[],s):void 0;return c?this.handleTokenHit(c,o,e):!a.success&&!i.success?{error:a.error||i.error||"Failed to resolve address"}:{error:`Address ${s} did not match any pool or token Uniswap knows on ${T(o)}. Verify the chain (the address may exist on a different network) or ask the user for context.`}}async handlePoolHit(e,t,r){if(!e.id)return{error:"Resolved pool has no identifier"};let o=await this.service.getPoolDetailEnriched({addressOrId:e.id,chain:t,enrich:!1});if(!o.success||!o.data)return{error:o.error||"Failed to fetch pool detail"};let s=await this.service.getTokenSafetyByAddress([o.data.token0?.address,o.data.token1?.address],t),a=o.data.protocolVersion??e.protocolVersion??"V3",i={...zn(o.data,s),...ht(t,e.id)},l=await this.pool.isAddLiquiditySupported(t)?pe([i],r,T(t)):[];return{_instructions:`The address is a Uniswap ${a} pool. `+me+"Give an expert read on ONE pool. First, a SNAPSHOT block: lead with the pair (token0/token1 symbols), fee tier (%), protocol version, and chain, then show TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), token0 reserve + USD price, and token1 reserve + USD price. For V4 pools also mention tickSpacing, isDynamicFee, and the hook address if present. Then an EXPERT ANALYSIS section \u2014 is this pool worth providing liquidity in, and why. "+he+be+Y+j+(l.length>0?de:""),resolvedAs:"pool",chain:t,protocolVersion:a,pool:i,...l.length>0?{actionButtons:l}:{}}}async handleTokenHit(e,t,r){let o=e.symbol?.trim();if(!o)return{error:"Resolved token has no symbol \u2014 cannot search related pools."};let s=await this.service.searchPools({query:o,chain:t,page:1,size:100,protocolVersion:"V3"});if(!s.success)return{error:s.error||"Failed to fetch pools for resolved token"};let a=(e.address??"").toLowerCase(),l=[...(s.data??[]).filter(u=>{let p=(u.token0?.address??"").toLowerCase(),m=(u.token1?.address??"").toLowerCase();return p===a||m===a})].sort((u,p)=>(p.volumeUsd24hr??0)-(u.volumeUsd24hr??0)).slice(0,10),c=l.map(u=>({...this.formatPoolCandidate(u),...ht(t,u.id)})),d=await this.pool.isAddLiquiditySupported(t)?pe(c,r,T(t)):[];return{_instructions:"The address is a token, not a pool. Tell the user which token it is (symbol + name), then render the matching pools as a numbered list: pair (token0/token1 symbols), fee tier (%), protocol version, 24h volume (USD). Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. Ask which pool they want detail on; when they answer, re-call this tool with that pool address to fetch the detail. Format numbers human-readably. Omit null fields. Do NOT mention tool/API names."+(d.length>0?de:""),resolvedAs:"token",chain:t,protocolVersion:"V3",token:this.formatToken(e),poolCount:l.length,pools:c,...d.length>0?{actionButtons:d}:{}}}findPoolByAddress(e,t){let r=t.toLowerCase();return e.find(o=>(o.id??"").toLowerCase()===r)}findTokenByAddress(e,t){let r=t.toLowerCase();return e.find(o=>(o.address??"").toLowerCase()===r)}formatToken(e){return{address:e.address,symbol:e.symbol,name:e.name,decimals:e.decimals,chainId:e.chainId,isSpam:e.isSpam,safetyLevel:e.safetyLevel}}formatPoolCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}};var vi=class{uniswap;constructor(e){this.uniswap=new $e(e)}async resolveCandidates(e){let t=await this.uniswap.searchPools({query:`${e.token0Symbol} ${e.token1Symbol}`,chain:e.chain,page:1,size:100,protocolVersion:e.protocolVersion,feeTier:e.feeTier});return t.success?t.data??[]:null}};var op=/^0x[a-fA-F0-9]{40}$/,sp=/^0x[a-fA-F0-9]{64}$/,Xn=class extends A{name="pool-open-add-liquidity-form";kind="ui";category="pool-action";description='Open the Add-Liquidity form for a specific Uniswap V3 pool. Use this when the user wants to provide liquidity / add LP / farm / stake / deposit into a pool \u2014 natural-language verbs in any language all map here. Resolves the pool by its exact address when the message carries one (the add-liquidity buttons under a pool listing append "(Pool: 0x\u2026 - <chain>)" \u2014 pass that address through as `poolAddress`), otherwise by token symbols and optional fee tier. Reads on-chain state, checks the connected wallet\'s NATIVE balance, then returns a UI payload that the FE renders as the form (with two preset ranges: Stable \xB13 ticks and Wide -50%/+100%). CONSTRAINT: the gateway only accepts the chain\'s NATIVE coin as input (ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche). The native amount is auto-split via deBridge into both pool tokens \u2014 the user never selects a different input. If the user asks to add liquidity using a NON-NATIVE token amount (e.g. "add pool with 5 USDT", "th\xEAm 100 USDC"), pass that symbol via `requestedNonNativeToken` so the tool can return error="unsupported_input_token" \u2014 never silently convert their non-native amount into native or USD. PRECONDITION: a connected wallet (userContext.walletAddress). If absent, the tool returns error="wallet_not_connected" and the agent must ask the user to connect. VERSION CONSTRAINT: only Uniswap V3 pools can be added to. When the pool the user picked is V2 or V4, the tool returns error="unsupported_protocol_version" with the version \u2014 tell the user that version is not supported yet (the pool DOES exist; never say it was not found).';parameters=[{name:"token0Symbol",type:"string",description:`Symbol of one of the pool's tokens (e.g. "USDC"). Pair order does not matter.`,required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Required to uniquely identify the pool.',required:!0},{name:"poolAddress",type:"string",description:`The pool's exact on-chain address (0x\u2026), when the user's message names one \u2014 the add-liquidity buttons under a pool listing carry it as "(Pool: 0x\u2026 - <chain>)". Pass it through VERBATIM whenever it is present: it pins the flow to that exact pool instead of re-searching by symbols, which can land on a different pool of the same pair. Omit when the user named no address.`,required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. Omit when unknown \u2014 the tool will resolve the best match automatically.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prefillNativeAmount",type:"number",description:"Optional NATIVE-COIN amount (human-readable) to pre-fill the form's input field. ONLY pass this when the user named an amount in the chain's native coin itself \u2014 ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche. Example: \"add 0.1 ETH to USDC/WETH on Base\". Pass the plain decimal number (e.g. 0.1 for 0.1 ETH). DO NOT convert a non-native amount (USDC, USDT, DAI, WBTC, \u2026) into native here \u2014 pass `requestedNonNativeToken` instead so the tool can reject. Mutually exclusive with prefillUsdAmount \u2014 pass one or neither.",required:!1},{name:"prefillUsdAmount",type:"number",description:'Optional USD amount to pre-fill the form\'s input field. Use this ONLY when the user explicitly speaks in USD/dollars \u2014 e.g. "add $10 to this pool", "10 dollars", "10 \u0111\xF4". The tool converts the USD value to native amount automatically using the current native-token price. DO NOT use this as a workaround for non-native token amounts (e.g. "5 USDT" is NOT $5 \u2014 USDT may de-peg, and even if 1:1 the user asked for a token, not USD). For non-native token amounts pass `requestedNonNativeToken` instead. Mutually exclusive with prefillNativeAmount \u2014 pass one or neither.',required:!1},{name:"requestedNonNativeToken",type:"string",description:`Set this ONLY when the user named an AMOUNT in a non-native token \u2014 e.g. "add pool with 5 USDT", "add 100 USDC to USDC/WETH", "th\xEAm 5 USDT v\xE0o pool". The trigger is "<number> <non-native-symbol>" in the user's message, NOT the mere appearance of the symbol. Pass the symbol the user attached the amount to (e.g. "USDT", "USDC", "DAI"). CRITICAL: If the user also names a NATIVE amount in the same message (e.g. "add USDC/WETH with 0.1 ETH", "th\xEAm pool USDC/WETH 0.3% v\u1EDBi 0.000005 ETH"), the native amount is the input \u2014 leave this EMPTY and use prefillNativeAmount. The pool pair symbols (the two tokens after "pool" / "to") are NEVER the input token by themselves \u2014 they only identify which pool. The tool will return error="unsupported_input_token" so the agent can tell the user that only the chain's native coin is accepted as input. DO NOT silently convert the user's non-native amount into a native amount or USD amount \u2014 the user explicitly named a different asset and must be informed, not auto-corrected. Leave empty when the user did name a native amount, a USD amount, or no amount at all.`,required:!1},{name:"rangeStrategy",type:"string",description:'Optional preset that pre-fills the min/max price inputs (FE keeps them editable). One of: "stable" \u2014 \xB13 tickSpacing around the current price (narrow, higher yield, higher out-of-range risk; pick for stablecoin / low-volatility pairs and when the user says "safe", "tight", "high yield", "t\u1EADp trung"); "wide" \u2014 currentPrice \xD7 [0.5, 2.0] (broad, lower yield, less rebalancing; pick when the user says "wide", "set and forget", "r\u1ED9ng"); "full" \u2014 full V3 tick range (V2-style, lowest yield, never goes out of range; pick when the user says "full range", "v2-style", "kh\xF4ng lo out of range"). Omit when the user did not signal a preference AND did not provide explicit minPrice/maxPrice. Mutually exclusive with minPrice/maxPrice \u2014 if both are passed, explicit prices win.',required:!1},{name:"minPrice",type:"number",description:'Optional explicit lower bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 minPrice=1800. Must be paired with maxPrice. When set, overrides rangeStrategy.',required:!1},{name:"maxPrice",type:"number",description:'Optional explicit upper bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 maxPrice=2200. Must be paired with minPrice. When set, overrides rangeStrategy.',required:!1},{name:"add_button_label",type:"string",description:`Label template for the per-fee-tier "Add liquidity" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. ALWAYS pass this when you call the tool with a pair but NO feeTier (the tool may return several fee-tier variants for the pair, and each gets a one-tap button). Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:'A short "add liquidity" command template IN THE USER\'S CURRENT LANGUAGE, submitted as the next user turn when a fee-tier button is clicked \u2014 it carries the chosen fee tier so the tool resolves that exact pool. ALWAYS pass this alongside `add_button_label` when calling with a pair but no feeTier. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name yourself \u2014 the chain this pair is on is appended to the prompt automatically.',required:!1}];resolver;pool;coinPool;minProvideUsd;constructor(e){super(),this.resolver=e?.resolver??new vi(e),this.pool=new ie(e?.pool),this.coinPool=new Tn(e?.coinPool),this.minProvideUsd=e?.minProvideUsd??.01}async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:r,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&typeof s=="object"&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let r=await te(vn(this.pool),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",a=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,l=typeof e.poolAddress=="string"?e.poolAddress.trim():"",c=op.test(l)||sp.test(l)?l.toLowerCase():"",d=sp.test(l),u=typeof e.prefillNativeAmount=="number"&&Number.isFinite(e.prefillNativeAmount)&&e.prefillNativeAmount>0?e.prefillNativeAmount:null,p=typeof e.prefillUsdAmount=="number"&&Number.isFinite(e.prefillUsdAmount)&&e.prefillUsdAmount>0?e.prefillUsdAmount:null,m=typeof e.requestedNonNativeToken=="string"&&e.requestedNonNativeToken.trim()?e.requestedNonNativeToken.trim():null,f=m&&u!=null&&(m.toLowerCase()===s.toLowerCase()||m.toLowerCase()===a.toLowerCase())?null:m,h=this.parseRangeStrategy(e.rangeStrategy),g=typeof e.minPrice=="number"&&Number.isFinite(e.minPrice)&&e.minPrice>0?e.minPrice:null,b=typeof e.maxPrice=="number"&&Number.isFinite(e.maxPrice)&&e.maxPrice>0?e.maxPrice:null;if(!s||!a)return{error:"missing_pool_identifier",_instructions:"token0Symbol and token1Symbol are required. Ask the user for the missing token symbol."};let y=mt(o);if(!y)return{error:"unsupported_chain",chain:o,_instructions:`Chain ${o} is not supported by the add-liquidity flow.`};let w=Ro(o);if(f&&w&&f.toLowerCase()!==w.symbol.toLowerCase())return{error:"unsupported_input_token",requestedToken:f,nativeSymbol:w.symbol,chainName:y.name,_instructions:`The user asked to add liquidity using ${f}, but this app only supports the chain's native coin (${w.symbol} on ${y.name}) as the input. Tell the user this in their language and ask them to either restate the amount in ${w.symbol} or in USD. DO NOT silently convert their ${f} amount, do NOT pre-fill the form, and do NOT call this tool again until the user provides a native or USD amount.`};let k=await this.pool.getGatewayAddress(o);if(!k)return{error:"no_gateway_configured",chain:o,_instructions:`No gateway contract is configured for chain ${o} (${y.name}). Tell the user this chain is not yet supported for add-liquidity in this app.`};let v=t?.walletAddress;if(!v)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before adding liquidity. Do NOT render the form."};if(d)return this.unsupportedVersionResult({protocolVersion:"V4",token0:{symbol:s},token1:{symbol:a}},s,a,y.name);let S=await this.resolver.resolveCandidates({chain:o,token0Symbol:s,token1Symbol:a,protocolVersion:"V3",feeTier:c?void 0:i});if(S===null)return{error:"pool_search_failed"};let P=c?S.find(G=>typeof G.id=="string"&&G.id.toLowerCase()===c):void 0;if(c&&!P){let G=await this.findUnsupportedVersionPool(o,s,a,i,c);if(G)return this.unsupportedVersionResult(G,s,a,y.name)}let x=P??S.find(G=>this.matchesPairExact(G,s,a,i)),I=x?[]:S.filter(G=>this.matchesPair(G,s,a,i));if(!x&&I.length===0){let G=await this.findUnsupportedVersionPool(o,s,a,i,c);return G?this.unsupportedVersionResult(G,s,a,y.name):{error:"pool_not_found",_instructions:`No V3 pool found for ${s}/${a}${i!=null?` at ${i}bps`:""} on ${y.name}. Verify the inputs with the user.`}}if(!x&&I.length>1){let G=I.map(ve=>{let nr=ve.volume1DayUsd??ve.volumeUsd24hr,ia=ve.tvlUsd,Rc=typeof nr=="number"&&typeof ia=="number"&&ia>0?nr/ia:void 0;return{address:ve.id,token0Symbol:ve.token0?.symbol,token1Symbol:ve.token1?.symbol,feeTier:ve.feeTier,feeTierPercent:ve.feeTier!=null?ve.feeTier/1e4:void 0,volume24hUsd:nr,tvlUsd:ia,...Rc!=null?{volumeToTvlRatio:Rc}:void 0,...ve.apr?{apr:ve.apr}:void 0}}).sort((ve,nr)=>(nr.volumeToTvlRatio??nr.apr??-1/0)-(ve.volumeToTvlRatio??ve.apr??-1/0)).slice(0,5),$i=pc(G.map(ve=>({token0:{symbol:ve.token0Symbol},token1:{symbol:ve.token1Symbol},feeTierPercent:ve.feeTierPercent,address:ve.address})),typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",T(o));return{relatedPools:G,count:G.length,...$i.length>0?{actionButtons:$i}:{},_instructions:me+"The user wants to ADD LIQUIDITY to this pair but named NO fee tier \u2014 `relatedPools` holds the related pools (the pair's fee-tier variants and closely-matching pools). Do NOT just ask them to pick blindly: give a genuine comparative read. Present them as a ranked list (rank by capital efficiency / fee yield, not just TVL); for each show the fee tier (%), TVL (USD), 24h volume (USD), and estimated APR (%) when present. Analyze each with its own real read \u2014 never skip one or repeat the same sentence structure. "+he+"Focus on which fee tier is the best home for THIS pair to LP in: lower tiers (0.01\u20130.05%) suit stable/correlated pairs and high turnover, higher tiers (0.3\u20131%) suit volatile pairs \u2014 the tier that captures most of the real volume on deep TVL is usually the one to provide liquidity in. Close by naming the single best fee tier to add liquidity in right now and why, then invite the user to confirm a tier to continue. When they choose, re-run the add-liquidity step with token0Symbol + token1Symbol + the chosen feeTier (in bps). "+be+Y+j+($i.length>0?' A clickable "Add liquidity" button is shown below your reply for each fee-tier candidate automatically \u2014 do NOT list, number, or repeat those buttons.':"")}}let E=x??I[0];if(!E.id||!op.test(E.id))return{error:"invalid_pool_address"};let we=this.fetchPriceRanges(o,E.id,E.token0?.symbol,E.token1?.symbol),V=await this.pool.readPoolOnchain(o,E.id),[z,fe,Ne]=await Promise.all([this.pool.getNativeBalance(o,v),this.pool.estimateGasReserveWei(o),this.pool.getNativePriceUsd(o)]),W=z>fe?z-fe:0n,J=Ro(o),Ht=Number(W)/10**J.decimals,tr=Number(z)/10**J.decimals,Le=Ne!=null?Ht*Ne:null,[Ye,Vt]=await Promise.all([this.pool.readErc20Decimals(o,V.token0),this.pool.readErc20Decimals(o,V.token1)]),Ge={min:pt(yn,Ye,Vt),max:pt(wo,Ye,Vt)},ze=null;z===0n?ze="no_balance":Le!=null&&Le<this.minProvideUsd&&(ze="insufficient_balance");let Pn=E.token0,Sn=E.token1,aa=[25,50,75,100].map(G=>({percent:G,amountWei:(W*BigInt(G)/100n).toString(),amount:Ht*(G/100)})),Lt=null,at=null;if(u!=null){at=u;let G=BigInt(Math.floor(at*10**J.decimals));G>0n&&(Lt=G.toString())}else if(p!=null&&Ne!=null&&Ne>0){at=p/Ne;let G=BigInt(Math.floor(at*10**J.decimals));G>0n&&(Lt=G.toString())}let xc={address:ue,isNative:!0,symbol:J.symbol,name:J.name,decimals:J.decimals,priceUsd:Ne,balanceWei:z.toString(),balance:tr,gasReserveWei:fe.toString(),spendableWei:W.toString(),spendable:Ht,spendableUsd:Le,quickRates:aa,minProvideUsd:this.minProvideUsd,warning:ze,warningMessage:ze==="no_balance"?`You have no ${J.symbol} on ${y.name}. Top up to add liquidity.`:ze==="insufficient_balance"?`Spendable ${J.symbol} is below the $${this.minProvideUsd} minimum.`:null,prefillAmount:at,prefillAmountWei:Lt},Cc=this.computePrefillRange({explicitMinPrice:g,explicitMaxPrice:b,rangeStrategy:h,currentPrice:V.currentPrice,currentTick:V.currentTick,tickSpacing:V.tickSpacing,token0Decimals:Ye,token1Decimals:Vt,priceBounds:Ge}),Up={component:"AddLiquidityForm",props:{chain:{hexId:o,name:y.name},pool:{address:V.poolAddress,fee:V.fee,feePercent:V.fee/1e4,tickSpacing:V.tickSpacing,currentTick:V.currentTick,currentPrice:Se(V.currentPrice),sqrtPriceX96:V.sqrtPriceX96.toString(),token0:{address:V.token0,symbol:Pn?.symbol,name:Pn?.name,logo:Pn?.logo},token1:{address:V.token1,symbol:Sn?.symbol,name:Sn?.name,logo:Sn?.logo}},inputToken:xc,priceBounds:Ge,prefillRange:Cc,gatewayAddress:k}},Dp=this.orientRangesToForm(await we,V.currentPrice,Pn?.symbol,Sn?.symbol);return{ui:Up,suggestedRanges:Dp,summary:this.buildSummary({chainName:y.name,pair:`${Pn?.symbol??s}/${Sn?.symbol??a}`,feePercent:V.fee/1e4,warning:ze,minProvideUsd:this.minProvideUsd,nativeSymbol:J.symbol}),_instructions:'The add-liquidity action is ready. In the user\'s language, invite them to enter the amount and price range to add liquidity, naming the pool + chain (e.g. "Enter the amount and price range to add liquidity to <pool> on <chain>"). Speak ONLY of the user\'s action (adding liquidity). NEVER say you "opened a form", "opened" anything, or describe any screen/form/window/UI being shown \u2014 phrase it as the next step the user takes, not as something you did. If warning="no_balance" tell them they need to top up. If warning="insufficient_balance" tell them the balance is below the minimum. REFERENCE RANGES: when `suggestedRanges` is a non-empty array, briefly offer 1\u20133 of them (highest `apr` first) as price ranges the user can REFERENCE when filling in their range \u2014 for each give the min\u2013max (`minPrice`\u2013`maxPrice`) and its `apr` \u2014 omitting the APR for any entry whose `apr` is absent (never "APR 0%", "N/A" or a dash). These prices are ALREADY in the SAME unit the form shows (`quoteSymbol` per `baseSymbol`), so quote them as-is \u2014 do NOT invert them. CRITICAL: that `apr` is the yield for THAT specific range ONLY \u2014 NEVER present it as the overall pool APR; narrower = higher out-of-range risk. These are only in-range suggestions to reference \u2014 the user still chooses their own range. When `suggestedRanges` is empty or absent, omit this entirely. '+Y+"Do NOT mention balance amounts, deBridge, native coin mechanics, UI, forms, data sources, or internal tool names. Wait for the user to fill in amount + price range before proceeding."}}async fetchPriceRanges(e,t,r,o){try{if(!this.coinPool.isSupported(e))return[];let s=await this.coinPool.getByAddress({chain:e,poolAddress:t});return s.length===0&&r&&o&&(s=await this.coinPool.getPairs({chain:e,tokens:[r,o]})),s.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}orientRangesToForm(e,t,r,o){let s=a=>Number.isFinite(a)&&a>0;return s(t)?e.map(a=>{let{minPrice:i,maxPrice:l,currentPrice:c}=a.priceRange,d=i,u=l,p=c;if(s(c)){let m=Math.abs(Math.log(c/t));Math.abs(Math.log(c*t))<m&&(d=s(l)?1/l:0,u=s(i)?1/i:0,p=1/c)}return{fee:a.fee,apr:$(a.apr),minPrice:Se(d),maxPrice:Se(u),currentPrice:Se(p),baseSymbol:r,quoteSymbol:o}}).filter(a=>s(a.minPrice)&&s(a.maxPrice)):[]}unsupportedVersionResult(e,t,r,o){let s=e.protocolVersion??"V4";return{error:"unsupported_protocol_version",protocolVersion:s,pair:`${e.token0?.symbol??t}/${e.token1?.symbol??r}`,chain:o,_instructions:`This is a Uniswap ${s} pool, and adding liquidity currently works only for V3 pools. Tell the user \u2014 in their language \u2014 that the pool they picked does exist but that adding liquidity to ${s} pools is not supported yet, only V3 pools are. Suggest they pick a V3 pool for this pair instead (one may well exist). Keep it short and friendly. Do NOT say the pool was not found, and do NOT mention tools, services, APIs, forms, or any internals.`}}async findUnsupportedVersionPool(e,t,r,o,s){try{let a=await this.resolver.resolveCandidates({chain:e,token0Symbol:t,token1Symbol:r,protocolVersion:"ALL"});if(a===null)return;let i=a.filter(l=>l.protocolVersion&&l.protocolVersion!=="V3");return i.length===0?void 0:s?i.find(l=>typeof l.id=="string"&&l.id.toLowerCase()===s):i.find(l=>this.matchesPairExact(l,t,r,o))??i.find(l=>this.matchesPair(l,t,r,o))}catch{return}}matchesPairExact(e,t,r,o){if(!o||o!=null&&e.feeTier!==o)return!1;let s=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=r.toLowerCase();return s===i&&a===l||s===l&&a===i}matchesPair(e,t,r,o){if(o!=null&&e.feeTier!==o)return!1;let s=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=r.toLowerCase(),c=this.symMatch(s,i)&&this.symMatch(a,l),d=this.symMatch(s,l)&&this.symMatch(a,i);return c||d}symMatch(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}parseRangeStrategy(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="stable"||t==="wide"||t==="full"?t:null}computePrefillRange(e){let{explicitMinPrice:t,explicitMaxPrice:r,rangeStrategy:o,currentPrice:s,priceBounds:a}=e;if(t!=null&&r!=null&&r>t){let{minPrice:i,maxPrice:l}=ko(t,r,s);return{strategy:"user",minPrice:Math.max(i,a.min),maxPrice:Math.min(l,a.max)}}if(o==="full")return{strategy:"full",minPrice:a.min,maxPrice:a.max};if(o==="stable"||o==="wide"){let l=cc({currentTick:e.currentTick,tickSpacing:e.tickSpacing,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals}).find(c=>c.id===o);if(l)return{strategy:o,minPrice:l.minPrice,maxPrice:l.maxPrice}}return null}buildSummary(e){let t=[`Ready to add liquidity to the ${e.pair} ${e.feePercent}% pool on ${e.chainName}. Enter an amount and a price range to continue.`];return e.warning==="no_balance"?t.push(`You'll need some ${e.nativeSymbol} on ${e.chainName} first \u2014 top up to continue.`):e.warning==="insufficient_balance"&&t.push(`Your spendable ${e.nativeSymbol} is below the $${e.minProvideUsd} minimum \u2014 top up before continuing.`),t.join(" ")}};var ky=/^0x[a-fA-F0-9]{40}$/,Qn=class extends A{name="pool-preview-add-liquidity";kind="action";category="pool-action";description='Preview the add-liquidity transaction. Call this whenever a concrete pool ADDRESS, a native amount, and BOTH min and max price (in token1 per token0) are known \u2014 whether the user filled the AddLiquidityForm OR stated all of them directly in chat (e.g. "add to USDC/WETH with 0.01 ETH, range 0.0005-0.0007, pool=0x\u2026"). Do NOT require the form to have been opened first. The tool converts prices \u2192 ticks (rounded to tickSpacing), fetches deBridge swap quotes for both legs, encodes the gateway.mint call, and returns an unsigned tx the FE will sign. REQUIRES the exact poolAddress (from open-add-liquidity-form props.pool.address or given by the user) \u2014 if only token symbols / a fee tier are known, resolve the pool via open-add-liquidity-form first.';parameters=[{name:"poolAddress",type:"string",description:"V3 pool contract address (returned by open-add-liquidity-form in props.pool.address).",required:!0},{name:"chain",type:"string",description:`Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea .Must match the pool's chain. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.`,required:!1},{name:"minPrice",type:"number",description:`Lower bound of the position price range, in token1-per-token0 units (decimal-adjusted \u2014 the SAME unit as pool.currentPrice from open-add-liquidity-form). Example: if currentPrice is 1800 (USDC per WETH), minPrice 900 means "the position is in-range while WETH \u2265 900 USDC". Must be >= 0 and < maxPrice. Pass 0 for a "full-range lower" position (the range extends down to price 0, i.e. Uniswap's MIN_TICK). CRITICAL: copy the number the user gave VERBATIM \u2014 every digit and every leading zero. Do NOT add or drop a zero, round, or rescale it. Tiny decimals like 0.000533 are easy to mis-transcribe (0.000533 must stay 0.000533, NEVER 0.0000533). If unsure, prefer the user's exact characters over your own reformatting.`,required:!0},{name:"maxPrice",type:"number",description:`Upper bound of the position price range, in the same units as minPrice. Must be > minPrice. Pass a very large number (or props.priceBounds.max) for a "full range upper" position. CRITICAL: copy the user's number VERBATIM \u2014 every digit and leading zero; never add/drop a zero, round, or rescale.`,required:!0},{name:"nativeAmount",type:"number",description:"Native amount the user wants to spend, as a human-readable decimal number (e.g. 0.1 for 0.1 ETH). The tool converts to wei internally.",required:!0},{name:"slippageBps",type:"number",description:"Slippage tolerance in basis points (100 = 1%). Optional \u2014 defaults to 100.",required:!1}];pool;defaultSlippageBps;mintMinPercent;pantograph;constructor(e){super(),this.pool=new ie(e?.pool),this.defaultSlippageBps=e?.defaultSlippageBps??"auto",this.mintMinPercent=e?.mintMinPercent??80,this.pantograph=new Ae}async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:r,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),a}catch(s){return{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let r=typeof e.poolAddress=="string"?e.poolAddress.trim():"",o=await te(vn(this.pool),e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=Number(e.minPrice),i=Number(e.maxPrice),l=typeof e.nativeAmount=="number"&&Number.isFinite(e.nativeAmount)?e.nativeAmount:NaN,c=typeof e.slippageBps=="number"&&Number.isFinite(e.slippageBps)&&String(e.slippageBps)!=="auto"?Math.floor(e.slippageBps)/100:String(this.defaultSlippageBps);if(!r||!s||!Number.isFinite(l)||!Number.isFinite(a)||!Number.isFinite(i))return{error:"missing_inputs",_instructions:"poolAddress, chain, minPrice, maxPrice, nativeAmount are all required."};if(!ky.test(r))return{error:"invalid_pool_address",_instructions:"poolAddress is not a valid EVM address. Re-open the add-liquidity form to get the correct pool address."};if(a<0||i<=0||a>=i)return{error:"invalid_price_range",_instructions:"minPrice must be >= 0 (0 = full-range lower), maxPrice must be > 0, and minPrice must be strictly less than maxPrice."};if(l<=0)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let d=mt(s);if(!d)return{error:"unsupported_chain",chain:s};let u=await this.pool.getGatewayAddress(s);if(!u)return{error:"no_gateway_configured",chain:s};let p=t?.walletAddress;if(!p)return{error:"wallet_not_connected"};let m=Ro(s),f=BigInt(Math.floor(l*10**m.decimals));if(f<=0n)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let h=await this.pool.readPoolOnchain(s,r),[g,b]=await Promise.all([this.pool.readErc20Decimals(s,h.token0),this.pool.readErc20Decimals(s,h.token1)]),{minPrice:y,maxPrice:w}=ko(a,i,h.currentPrice),k=y===0?yn:jn(y,g,b),v=jn(w,g,b),S=y===0?Rt(Ct(yn,h.tickSpacing,"up")):Rt(Ct(k,h.tickSpacing,"down")),P=Rt(Ct(v,h.tickSpacing,"up"));if(S>=P||S<yn||P>wo)return{error:"invalid_range_after_alignment",_instructions:"After aligning to tickSpacing the range collapsed. Ask the user for a wider price range.",rawTickLower:k,rawTickUpper:v,tickLower:S,tickUpper:P};let x={tickLower:S,tickUpper:P,minPrice:Se(pt(S,g,b)),maxPrice:Se(pt(P,g,b))},I=h.currentTick;if(I<S||I>=P){let Z=I<S?"below":"above";return{error:"out_of_range",_instructions:`The chosen price range does NOT include the pool's current price, so this would be an OUT-OF-RANGE position (it would sit entirely in one token and earn no fees until the price moves back into the range). The current price is ${Z==="below"?"BELOW":"ABOVE"} the chosen range. Tell the user (in their language) that their range is out of range, show the current price and their chosen min/max, and ask them to pick a range that brackets the current price. Do NOT proceed with the transaction. Do NOT mention tool names.`,currentPrice:Se(h.currentPrice),requestedRange:{minPrice:x.minPrice,maxPrice:x.maxPrice},side:Z}}let[E,we,V]=await Promise.all([this.pool.getNativeBalance(s,p),this.pool.estimateGasReserveWei(s),this.pool.getNativePriceUsd(s)]),z=f+we;if(E<z)return{error:"insufficient_balance",_instructions:"User does not have enough native coin (amount + gas reserve). Tell them the shortfall in their language.",balanceWei:E.toString(),requiredWei:z.toString(),gasReserveWei:we.toString()};let fe=this.pool.splitNativeAmountForRange({nativeAmountWei:f,pool:h,tickLower:S,tickUpper:P,token0Decimals:g,token1Decimals:b}),Ne=h.token0.toLowerCase()===ue,W=h.token1.toLowerCase()===ue,J=[];if(Ne||fe.amountInFor0Wei===0n)J.push({tokenIn:ue,tokenOut:h.token0,amountIn:fe.amountInFor0Wei,tx:{to:ue,data:"0x",value:"0"},minAmountOut:Ne?fe.amountInFor0Wei:0n});else{let Z=await this.pool.fetchSwapLeg({senderAddress:p,chainId:s,tokenIn:ue,tokenInAmount:fe.amountInFor0Wei.toString(),tokenOut:h.token0,tokenOutRecipient:u,slippage:typeof c=="number"?c:"auto"});J.push({tokenIn:ue,tokenOut:h.token0,amountIn:fe.amountInFor0Wei,tx:{to:Z.to,data:Z.data,value:Z.value},minAmountOut:BigInt(Z.minAmountOut||"0")})}if(W||fe.amountInFor1Wei===0n)J.push({tokenIn:ue,tokenOut:h.token1,amountIn:fe.amountInFor1Wei,tx:{to:ue,data:"0x",value:"0"},minAmountOut:W?fe.amountInFor1Wei:0n});else{let Z=await this.pool.fetchSwapLeg({senderAddress:p,chainId:s,tokenIn:ue,tokenInAmount:fe.amountInFor1Wei.toString(),tokenOut:h.token1,tokenOutRecipient:u,slippage:typeof c=="number"?c:"auto"});J.push({tokenIn:ue,tokenOut:h.token1,amountIn:fe.amountInFor1Wei,tx:{to:Z.to,data:Z.data,value:Z.value},minAmountOut:BigInt(Z.minAmountOut||"0")})}let Ht=Z=>Z*BigInt(this.mintMinPercent)/100n,tr=Ht(J[0].minAmountOut),Le=Ht(J[1].minAmountOut),Ye=J.map(Z=>({tokenIn:Z.tokenIn,tokenInAmount:BigInt(Z.amountIn),tokenOut:Z.tokenOut,tokenOutAmount:BigInt(Z.minAmountOut)})),Vt=J.map(Z=>({to:Z.tx.to,data:Z.tx.data,value:BigInt(Z.tx.value||"0")})),Ge=M({abi:Ml,functionName:"mint",args:[Ye,Vt,{fee:Number(h.fee),amount0Min:BigInt(tr),amount1Min:BigInt(Le),tickLower:S,tickUpper:P}]}),ze=l,Pn={chainId:s,to:u,data:Ge,value:f.toString(),from:p},Sn={nativeIn:ze,nativeSymbol:m.symbol,nativeInUsd:V!=null?ze*V:null,ratio:{token0Percent:fe.ratio0,token1Percent:fe.ratio1},expectedToken0:Number(J[0].minAmountOut)/10**g,expectedToken1:Number(J[1].minAmountOut)/10**b,amount0Min:tr.toString(),amount1Min:Le.toString(),slippageBps:c},aa=await this.pantograph.getTokensMetadata([h.token0,h.token1],s),Lt=aa[h.token0],at=aa[h.token1];return{ui:{component:"ConfirmAddLiquidityTx",props:{chain:{hexId:s,name:d.name},unsignedTx:Pn,summary:Sn,pool:{...h,feePercent:h.fee/1e4,currentPrice:Se(h.currentPrice),token0:{address:h.token0,symbol:Lt?.auditGoplus?.token_symbol||Lt.symbol,name:Lt.name,decimals:Lt.decimals,logo:Lt.icon_image},token1:{address:h.token1,symbol:at?.auditGoplus?.token_symbol||at.symbol,name:at.name,decimals:at.decimals,logo:at.icon_image}},range:x,gatewayAddress:u}},summary:`Ready to add ${ze} ${m.symbol} to pool ${h.token0}/${h.token1} ${h.fee/1e4}% on ${d.name}, range [${x.minPrice}, ${x.maxPrice}].`,_instructions:"A confirmation panel has been opened on the FE; the user will sign and broadcast the unsigned tx with their wallet. Briefly tell them (in their language) what is about to happen \u2014 the native amount, the auto-split ratio between the two pool tokens, and the chosen price range. Do NOT mention internal tool/component names."}}};var vy=365,Ty=1e3,Ay=/^0x[a-fA-F0-9]{40}$/;function Py(n,e){return{depositUsd:n,aprPercent:e*100,dailyUsd:n*e/vy,weeklyUsd:n*e/52,monthlyUsd:n*e/12,yearlyUsd:n*e}}var Io=class extends A{name="uniswap-estimate-pool-yield";description=`Estimate daily / weekly / monthly / yearly fee yield for a USD deposit into a Uniswap V3 pool. Answers questions like: "If I put $1000 into the USDC/WETH 0.05% pool, how much per day?", "b\u1ECF 500$ v\xE0o pool ETH/USDC 0.3% m\u1ED7i ng\xE0y l\u1EDDi bao nhi\xEAu?", "APR of WBTC/ETH 0.3% on Arbitrum". BEHAVIOR (designed to minimize back-and-forth with the user):
202
+ }`,o=await this.querySubgraph(t,r);if(!o?.position?.pool)return null;let s=o.position,a=this.mapPool(s.pool,t),i=await this.fetchDefiLlamaUniswap(),l=i.length>0?this.enrichWithLlama([a],i)[0]:a,c=l.feeTierBps,d=l.feeTierPercent;return{position:{positionId:s.id,poolAddress:l.poolAddress,pair:l.pair,token0:{symbol:l.token0.symbol,address:l.token0.address},token1:{symbol:l.token1.symbol,address:l.token1.address},feeTierBps:c,feeTierPercent:d,chain:l.chain,liquidity:s.liquidity,depositedToken0:s.depositedToken0,depositedToken1:s.depositedToken1,withdrawnToken0:s.withdrawnToken0,withdrawnToken1:s.withdrawnToken1,collectedFeesToken0:s.collectedFeesToken0,collectedFeesToken1:s.collectedFeesToken1},pool:l}}async getCoinPoolPairs(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let o=(await this.fetchCoinPoolV2Items(t)).map(s=>this.mapCoinPoolV2Item(s)).filter(s=>s!==null);if(e.tokens&&e.tokens.length>=2){let s=e.tokens[0].toUpperCase(),a=e.tokens[1].toUpperCase();o=o.filter(i=>{let[l="",c=""]=i.pair.toUpperCase().split("/");return l.includes(s)&&c.includes(a)||l.includes(a)&&c.includes(s)})}return o}async getCoinPoolByAddress(e){if(!this.coinPoolBaseUrl)return[];let t=this.numericChainId(e.chain);if(!t)return[];let r=e.poolAddress.toLowerCase();return(await this.fetchCoinPoolV2Items(t)).filter(s=>s.poolId?.toLowerCase()===r).map(s=>this.mapCoinPoolV2Item(s)).filter(s=>s!==null).sort((s,a)=>(a.apr??-1/0)-(s.apr??-1/0))}async fetchCoinPoolV2Items(e){if(!this.coinPoolBaseUrl)return[];try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,r=await C.get(t);if(!r.ok)throw new Error(_(r));return r.data?.data?.items||[]}catch{return[]}}mapCoinPoolV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,r=e.token1.decimal??18,o=S=>S==null||!Number.isFinite(S)?0:Math.pow(1.0001,S)*Math.pow(10,t-r),s=o(e.minTick),a=o(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,d=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),u=d?s:a>0?1/a:0,p=d?a:s>0?1/s:0,m=d?c:c>0?1/c:0,f=d?e.token0.symbol:e.token1.symbol,h=d?e.token1.symbol:e.token0.symbol;if(!m||!u&&!p)return null;let g=Math.min(u,p),b=Math.max(u,p);if(m<g||m>b)return null;let y=Number(e.fee),w=Yd[y]??y/1e4,k=$(e.apr)??$(e.aprAvg)??null,v=$(e.aprAvg)??null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:v,token0Price:i,token1Price:l,priceRange:{minPrice:Se(u),maxPrice:Se(p),currentPrice:Se(m),baseToken:f,quoteToken:h}}}};var bn=class{config;constructor(e){this.config=e}withRoute(e){let t=Object.create(this);return t.getQuote=r=>this.getQuote({route:e,...r}),t}};var Et=class{constructor(e,t=Number.POSITIVE_INFINITY){this.loader=e;this.ttlMs=t}loader;ttlMs;value=null;loadedAt=0;inFlight=null;async get(){return this.value!==null&&Date.now()-this.loadedAt<this.ttlMs?this.value:this.inFlight?this.inFlight:(this.inFlight=(async()=>{try{let e=await this.loader();return e!==null&&(this.value=e,this.loadedAt=Date.now()),e}catch{return this.value}finally{this.inFlight=null}})(),this.inFlight)}};var $g="https://api.relay.link";function Gd(n){return n===7565164||n==="7565164"?792703809:n}var vo=class extends bn{apiBaseUrl;apiKey;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??$g,this.apiKey=e.apiKey}getProviderName(){return"relay"}hasIntegratedApproval(){return!0}async getQuote(e){let{srcChainId:t,srcTokenAddress:r,srcTokenAmount:o,dstChainId:s,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c}=e,d=await wn.getAffiliateFee(this.getProviderName(),t,e.route),u={user:i||l,originChainId:Gd(t),destinationChainId:Gd(s),originCurrency:r,destinationCurrency:a,amount:o,recipient:i||l,tradeType:"EXACT_INPUT"};d&&(u.appFees=[{recipient:d.affiliateFeeRecipient,fee:Math.floor(d.affiliateFeePercent*100)}]),typeof c=="number"&&Number.isFinite(c)&&(u.slippageTolerance=Math.floor(c*100).toString());try{let p=await this.request("/quote/v2","POST",u);if(!p||p.error)return{success:!1,error:p?.error??"Unknown error",errorMessage:p?.message??"Failed to fetch quote from Relay"};let m=(p.steps??[]).filter(y=>y.id==="approve"),f=p.steps?.find(y=>y.id==="swap"||y.id==="deposit"),h=f?.items?.[0]?.data,g=Array.isArray(h?.instructions);return{success:!0,provider:"relay",tx:h?g?{data:{instructions:h.instructions??[],addressLookupTableAddresses:h.addressLookupTableAddresses??[]},chainId:h.chainId}:{from:h.from,to:h.to,data:h.data,value:h.value,chainId:h.chainId,gas:h.gas,maxFeePerGas:h.maxFeePerGas,maxPriorityFeePerGas:h.maxPriorityFeePerGas}:null,isCrossChain:t!==s,srcChainId:t,dstChainId:s,raw:{steps:p.steps,fees:p.fees,details:p.details,approveSteps:m,requestId:f?.requestId}}}catch(p){return{success:!1,error:p,errorMessage:p instanceof Error?p.message:"Failed to fetch quote"}}}async checkApproval(e){let t=e.quoteData?.raw,o=(t?.approveSteps??(t?.approveStep?[t.approveStep]:[])).map(s=>s.items?.[0]?.data).filter(s=>!!s?.to&&typeof s.data=="string").map(s=>({to:s.to,from:s.from,data:s.data,value:s.value??"0",chainId:s.chainId,gas:s.gas,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas}));return o.length>0?{isNeeded:!0,integrated:!0,approvals:o,approvalData:o[0],contractAddress:o[0].to,message:o.length>1?`${o.length} approval steps are included in the quote and run first, in order.`:"Approval step is included in quote and will be executed first."}:{isNeeded:!1,integrated:!0,approvals:[],message:"No approval needed or already approved"}}async trackTransaction(e){try{let r=(await this.request("/intents/status/v3","GET",{requestId:e.requestIdOrTxHash})).status??"";return r==="success"||r==="refunded"?{success:!0,status:"COMPLETED"}:r==="failure"||r==="expired"?{success:!0,status:"FAILED"}:{success:!0,status:"PENDING"}}catch(t){return{success:!1,status:"ERROR",error:t instanceof Error?t.message:String(t)}}}async request(e,t,r){let o={"Content-Type":"application/json"};this.apiKey&&(o["x-api-key"]=this.apiKey);let s=`${this.apiBaseUrl}${e}`,a;if(t==="GET"&&r){let l=Object.entries(r).map(([c,d])=>`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`).join("&");s=`${s}?${l}`}else t==="POST"&&r&&(a=r);let i=await C.request(t,s,a,{headers:o});if(!i.ok)throw new Error(_(i));return i.data}};var Hg="https://api.coinpool.app/config/addresses",Vg="https://api.coinpool.app/config/bridgeProviderByChain",Kd="createPoolProxyV3",Wg="nftPositionUniswap",Yg=/^0x[0-9a-fA-F]{40}$/,qs=class{addresses;providerMap;constructor(e=Hg,t=Vg){this.addresses=new Et(async()=>(await C.get(e,{headers:{Accept:"application/json"}})).data?.data??null),this.providerMap=new Et(async()=>(await C.get(t,{headers:{Accept:"application/json"}})).data?.data??null)}async getProviderByChain(e){let r=(await this.providerMap.get())?.[String(e)];return this.isProviderName(r)?r:null}async getGatewayAddress(e){return this.getAddress(Kd,e)}async getPositionManagerAddress(e){return this.getAddress(Wg,e)}async getGatewayChains(){return this.listChainsWithAddress(Kd)}async getAddress(e,t){let r=await this.addresses.get();if(!r)return;let o=this.toDecimalChainKey(t);if(o)return this.firstAddress(r[e]?.[o])}async listChainsWithAddress(e){let t=(await this.addresses.get())?.[e];if(!t||typeof t!="object")return[];let r=[];for(let[o,s]of Object.entries(t)){let a=this.firstAddress(s);a&&Yg.test(a)&&r.push(o)}return r}firstAddress(e){let t=Array.isArray(e)?e[0]:e;return typeof t=="string"?t.trim():void 0}toDecimalChainKey(e){let t=e.trim();if(/^0x[0-9a-fA-F]+$/.test(t)){let r=Number.parseInt(t,16);return Number.isFinite(r)?String(r):null}return/^\d+$/.test(t)?t:null}isProviderName(e){return e==="debridge"||e==="relay"}},kn=new qs;var To=class{async resolve(e){try{return await this.resolveProvider(e)??Bt}catch{return Bt}}toNumericChainId(e){if(e==null)return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}},Ao=class extends To{constructor(t=kn){super();this.config=t}config;route="pool";async resolveProvider({srcChainId:t}){let r=this.toNumericChainId(t);return r===null?null:this.config.getProviderByChain(r)}},Po=class extends To{constructor(t=wn){super();this.setting=t}setting;route="userSwap";async resolveProvider({srcChainId:t,dstChainId:r}){return this.setting.getBridgeProvider(t,r)}};var $s=class{routers=new Map;constructor(e=[new Ao,new Po]){for(let t of e)this.routers.set(t.route,t)}async resolveProvider(e){return await this.routers.get(e.route)?.resolve(e)??Bt}},fi=new $s;var Hs=class{configOverride;routersOverride;cache=new Map;constructor(e,t){this.configOverride=e,this.routersOverride=t}get providers(){return this.configOverride??xo}get routers(){return this.routersOverride??fi}async getService(e){let t=this.getServiceByProvider(await this.resolveProvider(e));return e.route?t.withRoute(e.route):t}getServiceByProvider(e){let t=this.cache.get(e);if(t)return t;let r=this.createService(e);return this.cache.set(e,r),r}resetCache(){this.cache.clear()}async resolveProvider(e){return this.routers.resolveProvider(e)}createService(e){let t=this.providers[e]??{};switch(e){case"debridge":return new Co(t);case"relay":return new vo(t);default:{let r=e;throw new Error(`Unknown swap provider: ${String(r)}`)}}}},So=new Hs;var xo={debridge:{apiBaseUrl:"https://dln.debridge.finance/v1.0",accessToken:"d6c45897b8f6"},relay:{apiBaseUrl:"https://api.relay.link"}},Bt="relay";function gi(n,e){let t={...xo[n]??{},...e};for(let r of Object.keys(t))t[r]===void 0&&delete t[r];xo[n]=t,So.resetCache()}var Gg="https://exchange-api.keyring.app/admin/setting?configs=others",Kg="https://api.relay.link/chains",jg="https://dln.debridge.finance/v1.0/supported-chains-info",zg=14400*1e3,Xg=300*1e3,Qg=new Set([728126428,7565164]),jd={relay:"relay",debridge:"deBridge"},Vs=class{setting;chainSupport;constructor(e=Gg){this.setting=new Et(async()=>(await C.get(e,{headers:{Accept:"application/json"}})).data?.others??null,Xg),this.chainSupport=new Et(async()=>this.fetchChainSupport(),zg)}async getBridgeProvider(e,t){let r=this.toChainKey(e),o=this.toChainKey(t??e),[s,a]=await Promise.all([this.setting.get(),this.chainSupport.get()]),i=this.normalizeProvider(s?.keyringV2?.bridgeProvider)??Bt;if(!r||!o||!a)return i;let l=this.requireChainKeys(s?.keyringV2,"debridge"),c=l.includes(r)||l.includes(o),d=a.debridge.has(r)&&a.debridge.has(o);return c&&d?"debridge":i}async getAffiliateFee(e,t,r="userSwap"){let o=await this.setting.get();if(!o)return null;let s=r==="pool"?this.resolveLegacyFee(o,e,t):this.resolveKeyringV2Fee(o,e,t);return!s.recipient||s.percent<=0?null:{affiliateFeeRecipient:s.recipient,affiliateFeePercent:s.percent}}resolveLegacyFee(e,t,r){return t==="debridge"?{recipient:this.parseRecipientMap(e.affiliateRecipient)?.[String(r)],percent:this.toPercent(e.AFFILIATE_FEE_PERENT)}:{recipient:e.RELAY_AFFILIATE_FEE_RECIPIENT,percent:this.toPercent(e.RELAY_AFFILIATE_FEE_PERCENT)}}resolveKeyringV2Fee(e,t,r){let o=e.keyringV2;if(!o)return{recipient:void 0,percent:0};let s=o[jd[t]],a=String(r);return{percent:this.toPercent(s?.affiliateFeePercentCustom?.[a])||this.toPercent(s?.affiliateFeePercent),recipient:s?.affiliateRecipientCustom?.[a]||o.affiliateRecipientDefault}}parseRecipientMap(e){if(!e)return null;try{let t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}async fetchChainSupport(){let[e,t]=await Promise.allSettled([C.get(Kg,{headers:{Accept:"application/json"}}),C.get(jg,{headers:{Accept:"application/json"}})]),r=new Set;if(e.status==="fulfilled")for(let s of e.value.data?.chains??[]){if(s?.vmType!=="evm")continue;let a=this.toChainKey(s.id);a&&r.add(a)}let o=new Set;if(t.status==="fulfilled")for(let s of t.value.data?.chains??[]){let a=s?.originalChainId??s?.chainId;if(a===void 0||Qg.has(a))continue;let i=this.toChainKey(a);i&&o.add(i)}return{relay:r,debridge:o}}requireChainKeys(e,t){return(e?.[jd[t]]?.requireChain??[]).map(o=>this.toChainKey(o)).filter(o=>o!==null)}normalizeProvider(e){if(typeof e!="string")return null;let t=e.toLowerCase();return t==="relay"?"relay":t==="debridge"?"debridge":null}toChainKey(e){if(e==null)return null;if(typeof e=="number")return Number.isFinite(e)?String(e):null;let t=e.trim();if(!t)return null;let r=/^0x/i.test(t)?Number.parseInt(t,16):Number(t);return Number.isFinite(r)?String(r):null}toPercent(e){if(e==null)return 0;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:0}},wn=new Vs;function yi(n,e){return M({abi:q,functionName:"approve",args:[n,e]})}async function Jg(n,e,t,r,o){try{return await Re(n).call({account:t,to:e,data:yi(r,o)}),!0}catch(s){return Zg(s)?!1:null}}function Zg(n){let e=n?.name??"";if(e==="ContractFunctionRevertedError"||e==="CallExecutionError")return!0;let t=n instanceof Error?n.message.toLowerCase():String(n??"").toLowerCase();return t.includes("revert")||t.includes("execution reverted")||t.includes("invalid opcode")||t.includes("out of gas")}async function bi({chain:n,token:e,owner:t,spender:r,amount:o,allowance:s}){let a=l=>({to:e,from:t,data:yi(r,l),value:"0"});return s!=null&&s>=o?[]:s===0n||!n?[a(o)]:await Jg(n,e,t,r,o)===!1?[a(0n),a(o)]:[a(o)]}var ey="https://dln.debridge.finance/v1.0",ty="0x0000000000000000000000000000000000000000",ny=new Set([429,500]),ry=5,oy=1e3,sy=n=>new Promise(e=>setTimeout(e,n)),Co=class extends bn{apiBaseUrl;accessToken;constructor(e={}){super(e),this.apiBaseUrl=e.apiBaseUrl??ey,this.accessToken=e.accessToken??"d6c45897b8f6"}getProviderName(){return"debridge"}hasIntegratedApproval(){return!1}async getQuote(e){let{srcChainId:t,srcTokenAddress:r,srcTokenAmount:o,dstChainId:s,dstTokenAddress:a,recipientAddress:i,senderAddress:l,slippage:c,isCrossChain:d}=e,u=d??t!==s,p=await wn.getAffiliateFee(this.getProviderName(),t,e.route);try{if(u){let h={srcChainId:String(t),srcChainTokenIn:r,srcChainTokenInAmount:o,dstChainId:String(s),dstChainTokenOut:a,dstChainTokenOutRecipient:i,srcChainOrderAuthorityAddress:l,dstChainOrderAuthorityAddress:i,accesstoken:this.accessToken};p&&(h.affiliateFeeRecipient=p.affiliateFeeRecipient,h.affiliateFeePercent=p.affiliateFeePercent);let g=await this.get(`${this.apiBaseUrl}/dln/order/create-tx`,h);return g.error||g.errorMessage?{success:!1,error:g.error??g.errorMessage,errorMessage:g.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:g.tx,estimation:g.estimation,isCrossChain:!0,srcChainId:t,dstChainId:s,raw:g}}let m={chainId:String(t),tokenIn:r,tokenInAmount:o,tokenOut:a,tokenOutRecipient:i,accesstoken:this.accessToken};p&&(m.affiliateFeeRecipient=p.affiliateFeeRecipient,m.affiliateFeePercent=p.affiliateFeePercent),c!==void 0&&(m.slippage=c);let f=await this.get(`${this.apiBaseUrl}/chain/transaction`,m);return f.error||f.errorMessage?{success:!1,error:f.error??f.errorMessage,errorMessage:f.errorMessage??"deBridge quote failed"}:{success:!0,provider:"debridge",tx:f.tx,isCrossChain:!1,srcChainId:t,dstChainId:t,raw:f}}catch(m){return{success:!1,error:m,errorMessage:m instanceof Error?m.message:"Failed to fetch quote"}}}async checkApproval(e){let{chain:t,userAddress:r,tokenAddress:o,amount:s}=e,a=e.quoteData?.tx?.to;if(!a)return{isNeeded:!1,error:"No contract address found in quote"};if(!o||o.toLowerCase()===ty)return{isNeeded:!1,integrated:!1,approvals:[],contractAddress:a,message:"Native coin needs no approval."};let i;try{i=BigInt(s)}catch{i=0n}let l=await this.readAllowance(t,o,r,a);if(l!==null&&l>=i)return{isNeeded:!1,integrated:!1,approvals:[],contractAddress:a,message:"Sufficient allowance already granted."};let c=await bi({chain:t,token:o,owner:r,spender:a,amount:i,allowance:l});return{isNeeded:!0,integrated:!1,approvals:c,approvalData:c[0],contractAddress:a,message:c.length>1?"Approval required: the standing allowance must be reset to 0 before the new one is granted.":l===null?"Could not read allowance; approval required before the swap.":"Approval required: current allowance is below the swap amount."}}async readAllowance(e,t,r,o){if(!e)return null;try{return await Re(e).readContract({address:t,abi:q,functionName:"allowance",args:[r,o]})}catch{return null}}async trackTransaction(e){let{requestIdOrTxHash:t}=e;try{let r=await this.get(`${this.apiBaseUrl}/dln/tx/${t}/order-ids`,{accesstoken:this.accessToken});if(!r.orderIds?.length)return{success:!1,status:"PENDING"};let o=r.orderIds[0];switch(((await this.get(`${this.apiBaseUrl}/dln/order/${o}/status`,{accesstoken:this.accessToken})).status??"").toUpperCase()){case"FULFILLED":case"SENTUNLOCK":case"CLAIMEDUNLOCK":return{success:!0,status:"COMPLETED"};case"ORDERCANCELLED":case"SENTORDERCANCEL":case"CLAIMEDORDERCANCEL":return{success:!0,status:"FAILED"};default:return{success:!0,status:"PENDING"}}}catch(r){return{success:!1,status:"ERROR",error:r instanceof Error?r.message:String(r)}}}async get(e,t){let r=Object.entries(t).map(([a,i])=>`${encodeURIComponent(a)}=${encodeURIComponent(String(i))}`).join("&"),o=r?`${e}?${r}`:e,s=await C.get(o,{headers:{Accept:"application/json"}});for(let a=0;a<ry&&ny.has(s.status);a++)await sy(oy),s=await C.get(o,{headers:{Accept:"application/json"}});return s.data}};function zd(n){let e=n.raw??{},t=e.tokenOut?.amount??e.tokenOut?.minAmount??e.details?.currencyOut?.amount??e.details?.currencyOut?.minimumAmount??e.estimation?.dstChainTokenOut?.recommendedAmount??e.estimation?.dstChainTokenOut?.amount;return t&&/^\d+$/.test(t)?t:void 0}function Xd(n){if(n.errorMessage&&n.errorMessage.trim())return n.errorMessage.trim();let e=r=>{if(typeof r=="string"&&r.trim())return r.trim();if(r&&typeof r=="object"){let o=r;for(let s of[o.message,o.errorMessage,o.error])if(typeof s=="string"&&s.trim())return s.trim()}},t=n.raw??{};return e(n.error)??e(t.errorMessage)??e(t.error)??"The swap could not be quoted right now."}var ay={1:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",10:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",56:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",137:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",143:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",1514:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",4326:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",4663:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",8453:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",42161:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",43114:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",59144:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",25:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",999:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66",1776:"0xeF4fB24aD0916217251F553c0596F8Edc630EB66"},iy=[{inputs:[],name:"globalFixedNativeFee",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"}];function Qd(n){if(n==null)return null;if(typeof n=="number")return Number.isFinite(n)?String(n):null;let e=n.trim();if(!e)return null;let t=/^0x/i.test(e)?Number.parseInt(e,16):Number(e);return Number.isFinite(t)?String(t):null}async function wi(n){let{provider:e,srcChainId:t}=n,r=Qd(t),o=Qd(n.dstChainId??t);if(!r||!o||r===o||e!=="debridge")return 0n;let s=ay[r];if(!s)return 0n;try{let a=await Re(r).readContract({address:s,abi:iy,functionName:"globalFixedNativeFee"});return typeof a=="bigint"&&a>0n?a:0n}catch{return 0n}}var ue="0x0000000000000000000000000000000000000000",Jd={"0x1":{hexId:"0x1",name:"Ethereum",defaultRpc:Xe["0x1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa":{hexId:"0xa",name:"Optimism",defaultRpc:Xe["0xa"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0x38":{hexId:"0x38",name:"BNB Smart Chain",defaultRpc:Xe["0x38"],native:{symbol:"BNB",name:"BNB",decimals:18,coingeckoId:"binancecoin"},defaultMintGasLimit:12e5},"0x89":{hexId:"0x89",name:"Polygon",defaultRpc:Xe["0x89"],native:{symbol:"POL",name:"Polygon",decimals:18,coingeckoId:"matic-network"},defaultMintGasLimit:12e5},"0x2105":{hexId:"0x2105",name:"Base",defaultRpc:Xe["0x2105"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5},"0xa4b1":{hexId:"0xa4b1",name:"Arbitrum One",defaultRpc:Xe["0xa4b1"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:22e5},"0xa86a":{hexId:"0xa86a",name:"Avalanche",defaultRpc:Xe["0xa86a"],native:{symbol:"AVAX",name:"Avalanche",decimals:18,coingeckoId:"avalanche-2"},defaultMintGasLimit:12e5},"0xe708":{hexId:"0xe708",name:"Linea",defaultRpc:Xe["0xe708"],native:{symbol:"ETH",name:"Ether",decimals:18,coingeckoId:"ethereum"},defaultMintGasLimit:12e5}};function mt(n){return Jd[n.toLowerCase()]}function Ro(n){return mt(n)?.native}var Zd="0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";function cc(n){let e=n.stableTicks??3,t=n.widePercent??{down:50,up:100},r=pt(n.currentTick,n.token0Decimals,n.token1Decimals),o=Rt(Ct(n.currentTick-e*n.tickSpacing,n.tickSpacing,"down")),s=Rt(Ct(n.currentTick+e*n.tickSpacing,n.tickSpacing,"up")),a=r*(1-t.down/100),i=r*(1+t.up/100),l=jn(a,n.token0Decimals,n.token1Decimals),c=jn(i,n.token0Decimals,n.token1Decimals),d=Rt(Ct(l,n.tickSpacing,"down")),u=Rt(Ct(c,n.tickSpacing,"up")),p=(m,f,h,g,b)=>{let y=pt(g,n.token0Decimals,n.token1Decimals),w=pt(b,n.token0Decimals,n.token1Decimals);return{id:m,label:f,description:h,tickLower:g,tickUpper:b,minPrice:y,maxPrice:w,minPercentChange:(y-r)/r*100,maxPercentChange:(w-r)/r*100}};return[p("stable","Stable","Good for stablecoins or low volatility pairs",o,s),p("wide","Wide","Good for volatile pairs",d,u)]}var ie=class{swapFactory;constructor(e){this.swapFactory=e?.swapFactory??So}isSupported(e){if(!e)return!1;let t=I(e);return!!t&&!!mt(t)}listSupportedChains(){return Object.keys(Jd).filter(e=>Be(e))}getRpcUrl(e){let t=Mn(e);if(t)return t;let r=mt(e);if(!r)throw new Error(`Unsupported chain: ${e}`);return r.defaultRpc}async getGatewayAddress(e){return kn.getGatewayAddress(e)}async isAddLiquiditySupported(e){return this.isSupported(e)&&!!await this.getGatewayAddress(e)}async listAddLiquiditySupportedChains(){let e=await kn.getGatewayChains(),t=[];for(let r of e){let o=I(r);o&&mt(o)&&!t.includes(o)&&t.push(o)}return t.length>0?t:this.listSupportedChains()}async getPositionManagerAddress(e){return kn.getPositionManagerAddress(e)}client(e){return Re(e)}async ethCall(e,t,r){let{data:o}=await this.client(e).call({to:t,data:r});return o??"0x"}async getNativeBalance(e,t){return this.client(e).getBalance({address:t})}async getGasPrice(e){return this.client(e).getGasPrice()}async getTransactionReceipt(e,t){return this.client(e).rpc("eth_getTransactionReceipt",[t])}async extractMintedNftId(e,t){let r=await this.getPositionManagerAddress(e);if(!r)return null;let o=r.toLowerCase();for(let s of t.logs??[]){if((s.address??"").toLowerCase()!==o)continue;let a=s.topics??[];if(!(a.length<4||a[0]?.toLowerCase()!==Zd||"0x"+a[1].slice(-40).toLowerCase()!==ue))try{return BigInt(a[3]).toString()}catch{return null}}return null}async estimateGasReserveWei(e){let t=mt(e);if(!t)throw new Error(`Unsupported chain: ${e}`);let r=await this.getGasPrice(e);return BigInt(t.defaultMintGasLimit)*r*18n/10n}async readPoolOnchain(e,t){let o={address:t,abi:Fl},[s,a,i,l,c,d]=await this.client(e).multicall({contracts:[{...o,functionName:"slot0"},{...o,functionName:"liquidity"},{...o,functionName:"tickSpacing"},{...o,functionName:"fee"},{...o,functionName:"token0"},{...o,functionName:"token1"}],allowFailure:!1}),[u,p]=s,m=c.toLowerCase(),f=d.toLowerCase(),[h,g]=await Promise.all([this.readErc20Decimals(e,m),this.readErc20Decimals(e,f)]),b=Vd(u,h,g);return{poolAddress:t,chainId:e,fee:l,tickSpacing:i,liquidity:a,sqrtPriceX96:u,currentTick:p,token0:m,token1:f,currentPrice:b}}async readErc20Decimals(e,t){return t.toLowerCase()===ue?18:this.client(e).readContract({address:t,abi:q,functionName:"decimals"})}async getNativePriceUsd(e){let t=mt(e);if(!t)return null;try{let r=`https://api.coingecko.com/api/v3/simple/price?ids=${t.native.coingeckoId}&vs_currencies=usd`,o=await C.get(r);if(!o.ok)return null;let a=o.data[t.native.coingeckoId]?.usd;return typeof a=="number"?a:null}catch{return null}}splitNativeAmountForRange(e){let{nativeAmountWei:t,pool:r,tickLower:o,tickUpper:s,token0Decimals:a,token1Decimals:i}=e,l=2**96,c=Number(r.sqrtPriceX96)/l,d=Math.pow(1.0001,o/2),u=Math.pow(1.0001,s/2);if(c<=d)return{ratio0:1,ratio1:0,amountInFor0Wei:t,amountInFor1Wei:0n};if(c>=u)return{ratio0:0,ratio1:1,amountInFor0Wei:0n,amountInFor1Wei:t};let p=1/c-1/u,m=c-d,f=c*c,h=p*f,b=h+m;if(!Number.isFinite(b)||b<=0)throw new Error("splitNativeAmountForRange: invalid total value");let y=h/b,w=1-y,k=1000000000000000n,v=BigInt(Math.floor(y*Number(k))),S=t*v/k,P=t-S;return{ratio0:y,ratio1:w,amountInFor0Wei:S,amountInFor1Wei:P}}async fetchSwapLeg(e){let t=Number.parseInt(e.chainId,16);if(!Number.isFinite(t))throw new Error(`Invalid hex chain id: ${e.chainId}`);let o=await(await this.swapFactory.getService({route:"pool",srcChainId:t})).getQuote({srcChainId:t,srcTokenAddress:e.tokenIn,srcTokenAmount:e.tokenInAmount,dstChainId:t,dstTokenAddress:e.tokenOut,recipientAddress:e.tokenOutRecipient,senderAddress:e.senderAddress??e.tokenOutRecipient,slippage:e.slippage,isCrossChain:!1});if(!o.success||!o.tx)throw new Error(o.errorMessage??"Swap quote failed");let s=o.tx;if(!s.to||typeof s.data!="string")throw new Error("Swap quote returned an unsupported tx shape (non-EVM payload?)");let a=o.raw??{},i=a.tokenOut?.minAmount??a.details?.currencyOut?.minimumAmount??"0";return{to:s.to,data:s.data,value:s.value??"0",minAmountOut:i}}};var ly={"0x1":"ethereum","0xa":"optimism","0x38":"bnb","0x89":"polygon","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avalanche"},cy=/^0x[a-fA-F0-9]{40}$/;function Ws(n,e){if(typeof n!="string"||typeof e!="string")return null;let t=ly[n.toLowerCase()];return!t||!cy.test(e)?null:`https://app.uniswap.org/explore/pools/${t}/${e}`}function ht(n,e){let t=Ws(n,e);return t?{uniswapUrl:t}:{}}var ep=Object.keys(fn),nt="Hex chain ID of the chain the user named. Map the chain name to its EXACT hex id \u2014 pass ONLY one of these values, never a guessed or made-up one: Ethereum=0x1, Optimism=0xa, BSC=0x38, Polygon=0x89, Base=0x2105, Arbitrum=0xa4b1, Avalanche=0xa86a, Linea=0xe708, Gnosis=0x64, HyperEVM=0x3e7, Mantle=0x1388, Monad=0x8f. Set this WHENEVER the user EXPLICITLY names a chain (always send the exact hex from this list). Otherwise OMIT it entirely so the connected wallet chain is used automatically.";function Oe(){return ep.filter(n=>Be(n)).map(n=>T(n)).join(", ")}function rt(){return{kind:"info",async listSupported(){return ep.filter(n=>Be(n))},async isSupported(n){if(!n)return!1;let e=I(n);return!!e&&Object.prototype.hasOwnProperty.call(fn,e)}}}function vn(n){return{kind:"add-liquidity",listSupported:()=>n.listAddLiquiditySupportedChains(),isSupported:e=>n.isAddLiquiditySupported(e)}}function uc(n,e,t){let r=o=>typeof o=="string"&&o.trim()!=="";if(r(n))return I(n)??n.trim();if(r(e?.chain))return I(e.chain)??e.chain.trim();if(r(e?.walletAddress))throw new ge(typeof e?.query=="string"?e.query:void 0,t);return Je}async function te(n,e,t){let r=await n.listSupported(),o=uc(e,t,r);return await n.isSupported(o)?{ok:!0,chain:o}:{ok:!1,result:dc(o,r,n.kind)}}function dc(n,e,t="info"){return{_instructions:`${t==="add-liquidity"?"Adding liquidity is NOT available on this network. Tell the user, in their language, that they cannot add liquidity / provide LP on this chain yet (note: viewing pool info may still work on other chains). Then name the chains where adding liquidity IS available":"Liquidity-pool data is NOT available on this network. Tell the user, in their language, that pools are not supported on this chain. Then name the chains where pools ARE available"} using EXACTLY and ONLY the entries in the \`supportedChains\` field below \u2014 copy them verbatim, add nothing. CRITICAL: this list is the complete, authoritative set. Do NOT add, infer, or invent ANY other chain \u2014 NOT EVEN a chain this app supports for wallet/token/DeFi features (for example Gnosis, HyperEVM, Mantle, and Monad are NOT pool chains; never list them unless they literally appear in \`supportedChains\`). Keep it short and friendly. Do NOT mention tools, services, APIs, forms, or any internals.`,unsupportedChain:T(n),supportedChains:e.map(o=>T(o))}}var ki="{pair}";var Ee=[{name:"add_button_label",type:"string",description:`Label template for the per-pool "Add liquidity" buttons that render under EVERY pool you show, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each pool automatically. Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:`A short "add liquidity" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a pool's button is clicked. ALWAYS provide it. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name or a pool address yourself \u2014 the pool address and the chain these pools are on are appended automatically as "(Pool: 0x\u2026 - <chain>)".`,required:!1}],de=' A clickable "Add liquidity" button is shown below your reply for each pool automatically \u2014 do NOT list, number, or repeat those buttons in your text; just deliver your analysis.';function pe(n,e,t){return pc(n,typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",t)}function pc(n,e,t,r){let o=typeof r=="string"?r.trim():"",s=[];for(let a of n){if(s.length>=5)break;let i=a.token0?.symbol?.trim(),l=a.token1?.symbol?.trim();if(!i||!l)continue;let c=dy(i,l,a.feeTierPercent);s.push({label:tp(e,c,`Add liquidity to ${ki}`),prompt:tp(t,c,`add liquidity to ${ki}`)+uy(a.address,o)})}return s}function uy(n,e){let r=[typeof n=="string"&&n.trim()?`Pool: ${n.trim()}`:"",e].filter(Boolean);return r.length>0?` (${r.join(" - ")})`:""}function dy(n,e,t){let r=`${n}/${e}`;return typeof t=="number"&&Number.isFinite(t)?`${r} ${py(t)}%`:r}function py(n){return Number(n.toFixed(4)).toString()}function tp(n,e,t){return(n&&n.includes(ki)?n:t).split(ki).join(e).replace(/\s+/g," ").trim()}var me="You are a seasoned DEX liquidity-pool analyst with deep, credible expertise. Deliver a genuinely insightful, professional read \u2014 the kind a sophisticated LP would pay for \u2014 in natural, flowing prose rather than a rigid template, never sacrificing depth or authority for a conversational tone. ",he='Ground every judgement rigorously in the data, never guesses \u2014 and only use a signal when its data is present: \u2022 capital efficiency = `volumeToTvlRatio` (volume \xF7 TVL) \u2014 higher means each $ of liquidity earns more fees; >1 is very active, <0.1 is sluggish. \u2022 APR quality \u2014 a very high APR sitting on a TINY TVL is usually volatile/unsustainable (treat with caution); a solid APR on deep TVL is the sweet spot. When an APR field is ABSENT there is no yield reading for that pool: say nothing about its APR \u2014 never print "APR 0%", "APR: N/A", a dash, or infer the yield from other fields. Judge such a pool on its remaining metrics alone. \u2022 TVL trend \u2014 when a 24h TVL % change is present, note whether liquidity is growing or shrinking. \u2022 TVL depth \u2014 deeper pools = lower slippage and a steadier position; thin pools carry higher risk. \u2022 fee tier vs pair type \u2014 stable/correlated pairs suit low tiers (0.01\u20130.05%), volatile pairs suit higher tiers (0.3\u20131%). \u2022 token safety \u2014 when a token exposes isSpam=true or a non-VERIFIED safetyLevel, FLAG it prominently as a risk. \u2022 transfer tax \u2014 when a token exposes transferFeeBps, it charges that tax (in basis points: 200 = 2%) on transfers. FLAG it prominently: it eats directly into LP returns, and a high or one-sided tax is a common honeypot trait. \u2022 unrecognized token \u2014 when a token exposes isUnrecognizedToken=true, Uniswap does not know that contract at all. Treat this as a SEVERE warning, stronger than any safetyLevel: a token wearing a well-known ticker (WBTC, USDC\u2026) on a contract Uniswap cannot identify is most likely an impostor. Say so plainly and advise verifying the contract address before providing any liquidity. ',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. ",Y="End with a brief reminder that yields fluctuate and concentrated LPs face impermanent loss (informational, not financial advice). ",j=`LINKS \u2014 write every pool pair as PLAIN TEXT only (e.g. "USDC/WETH"). Do NOT create markdown links, do NOT output any URLs, and do NOT print raw pool or token contract addresses anywhere in your answer. The system automatically turns each pool's pair into the correct clickable link after you reply, so you must NEVER add a link, a "Link to pool" line, a "View on Uniswap" line, or a bare URL yourself \u2014 doing so produces wrong/duplicate links. Just name each pair in text. Format numbers human-readably (e.g. $12.5M, +1.23%, 0.05%). Omit null fields. Answer in the user's language. Do NOT mention tool or API names.`;var my=["tvl","volume1Day","volume30Day","apr"],hy=["V2","V3","V4"],Eo=class extends A{name="uniswap-top-pools";description=`List the top Uniswap liquidity pools on a given EVM chain, ranked by TVL by default. Returns each pool's address, fee tier, protocol version, both tokens (symbol, name, address, decimals), TVL, rolling volume (1d / 30d), and estimated APR. Use this tool for questions like: "top pools on Ethereum", "biggest Uniswap V3 pools on Base", "which pool has the most liquidity for USDC", "show pools with highest 24h volume on Arbitrum". Source: https://app.uniswap.org/explore (ListPools gateway). Supports: `+Oe();category="blockchain-data";parameters=[{name:"chain",type:"string",description:nt,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version to filter by: "V2", "V3", or "V4". Default is "V3" (the dataset with the richest stats). Use "V4" only when the user explicitly asks for V4 pools.',required:!1,default:"V3"},{name:"sortBy",type:"string",description:'Ranking metric: "tvl" (total value locked, default), "volume1Day", "volume30Day", or "apr" (estimated annualized fee yield, net of the protocol fee). Pools are returned in descending order by this metric.',required:!1,default:"tvl"},{name:"limit",type:"number",description:'Maximum number of pools to return after sorting. Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"multichain",type:"boolean",description:"When true, request Uniswap's multichain aggregated view instead of a single chain. Defaults to false. Most queries should leave this off.",required:!1,default:!1},{name:"forAddLiquidity",type:"boolean",description:'Set TRUE only when this ranking is the ENTRY POINT of the ADD-LIQUIDITY flow \u2014 the user wants to add / provide liquidity ("add pool", "i want to add liquidity", "th\xEAm thanh kho\u1EA3n") but named NO specific pool, so you show top pools (use sortBy="apr") for them to pick one. In that mode the tool gates on ADD-LIQUIDITY chain support (only chains with a gateway) and, when the connected chain has no gateway, returns the "adding liquidity is not available on this chain" message with the correct supported list \u2014 so the user is told up front, not after picking a pool. OMIT (false) for ordinary informational rankings ("top pools on Base", "biggest pools").',required:!1,default:!1},...Ee];service;subgraphFallback;pool;constructor(e,t){super(),this.service=new $e(e),this.subgraphFallback=new xe(t),this.pool=new ie}async run(e,t){let r=e.forAddLiquidity===!0,o=r?vn(this.pool):rt(),s=await o.listSupported(),a=uc(e.chain,t,s),i=this.parseProtocolVersion(e.protocolVersion),l=this.parseSortKey(e.sortBy),c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,d=!r&&e.multichain===!0;if(!d&&!await o.isSupported(a))return dc(a,s,o.kind);let u=await this.service.getTopPools({chain:a,protocolVersion:i,sortBy:l,limit:c,multichain:d});if(!u.success)return{error:u.error||"Failed to fetch top pools"};let p=(u.data??[]).map(w=>this.formatPool(w)),m="uniswap";if(p.length===0&&i==="V3"){let w=await this.fetchV3Fallback(a,l,c);w.length>0&&(p=w,m="subgraph")}let f=p.map(w=>this.withExpertSignals(w)),h=await this.pool.isAddLiquiditySupported(a)?pe(f,e,T(a)):[],g=m==="subgraph",b=g?`"Volume past day" (translate naturally into the user's language; NEVER call it "24h volume", "daily volume", or "24h")`:"24h volume";return{_instructions:(g?`BEGIN your answer with "According to the latest data from Subgraph Uniswap V3," (translate the sentence naturally into the user's language but keep the word "Subgraph" as-is). `:"")+me+`You are briefing a peer. Present the pools as a ranked list, then deliver the analysis. For each pool include the key facts: rank, pair (token0/token1 symbols), fee tier (in %), TVL in USD, ${b}, and APR (in %). CRITICAL: every pool MUST have its own written analysis \u2014 2\u20133 sentences of genuine expert read placed directly under that pool's facts. NEVER skip a pool and NEVER reduce a pool to just a facts list. Vary the wording from pool to pool (do not repeat the same sentence structure), go a little deeper on the standouts, and surface the non-obvious insight a less experienced observer would miss. `+he+"After the per-pool reads, close with a short overall section that (1) gives a high-level read across the whole list \u2014 the broad pattern you see (where the real capital efficiency and fee yield sit, how the risk/reward stacks up), (2) names the single best pool to provide liquidity in right now and explains why it stands out, and (3) gives the user a concrete, actionable recommendation tailored to the data. "+be+Y+"Mention the chain and the sort metric in the intro line. "+j+(h.length>0?de:""),chain:a,protocolVersion:i,sortBy:l,source:m,count:f.length,pools:f.map(w=>({...w,...ht(a,w.address)})),...h.length>0?{actionButtons:h}:{}}}withExpertSignals(e){let t=a=>Math.round(a*1e3)/1e3;if(typeof e.volumeToTvlRatio=="number"&&Number.isFinite(e.volumeToTvlRatio))return{...e,volumeToTvlRatio:t(e.volumeToTvlRatio)};let r=e.tvlUsd,o=e.volume1DayUsd,s=typeof r=="number"&&r>0&&typeof o=="number"?t(o/r):void 0;return{...e,volumeToTvlRatio:s}}async fetchV3Fallback(e,t,r){try{return(await this.subgraphFallback.getTrendingPools({chain:e})).map(i=>this.formatSubgraphPool(i,e)).sort((i,l)=>this.fallbackSortValue(l,t)-this.fallbackSortValue(i,t)).slice(0,r)}catch{return[]}}fallbackSortValue(e,t){switch(t){case"apr":return e.apr??0;case"volume1Day":case"volume30Day":return e.volume1DayUsd??0;default:return e.tvlUsd??0}}formatSubgraphPool(e,t){return{apr:$(e.apr),totalApr:void 0,address:e.poolAddress,chain:t,protocolVersion:"V3",feeTierBps:e.feeTierBps,feeTierPercent:typeof e.feeTierBps=="number"?e.feeTierBps/1e4:void 0,tvlUsd:e.tvl,fee24hUsd:e.fees24hUsd,volume1DayUsd:e.volume24hUsd,volume1WeekUsd:void 0,volume30DayUsd:void 0,volumeToTvlRatio:void 0,txCount:void 0,token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:void 0,priceUsd:void 0,isSpam:void 0,safetyLevel:void 0}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:void 0,priceUsd:void 0,isSpam:void 0,safetyLevel:void 0}:void 0}}parseProtocolVersion(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(hy.includes(t))return t}return"V3"}parseSortKey(e){if(typeof e=="string"){let t=e.trim();if(my.includes(t))return t}return"tvl"}formatPool(e){let t=e.isDynamicFee===!0||hn(e.feeTier);return{apr:$(e.apr),totalApr:typeof e.totalApr=="number"&&typeof e.apr=="number"&&e.totalApr>e.apr?e.totalApr:void 0,address:e.id,chain:e.chain,protocolVersion:e.protocolVersion,feeTierBps:t?void 0:e.feeTier,feeTierPercent:!t&&typeof e.feeTier=="number"?e.feeTier/1e4:void 0,...t?{isDynamicFee:!0}:{},tvlUsd:e.totalLiquidity?.value,fee24hUsd:e.fee24hUsd,volume1DayUsd:e.volume1Day?.value,volume1WeekUsd:e.volume1Week?.value,volume30DayUsd:e.volume30Day?.value,volumeToTvlRatio:e.volumeToTvlRatio,txCount:e.txCount,token0:e.token0?{address:e.token0.address,symbol:e.token0.symbol,name:e.token0.name,decimals:e.token0.decimals,priceUsd:e.token0.price?.value,isSpam:e.token0.project?.isSpam,safetyLevel:e.token0.project?.safetyLevel}:void 0,token1:e.token1?{address:e.token1.address,symbol:e.token1.symbol,name:e.token1.name,decimals:e.token1.decimals,priceUsd:e.token1.price?.value,isSpam:e.token1.project?.isSpam,safetyLevel:e.token1.project?.safetyLevel}:void 0}}};var mc={"0x1":1,"0xa":10,"0x38":56,"0x89":137,"0x2105":8453,"0xa4b1":42161,"0xa86a":43114},fy={100:.01,500:.05,3e3:.3,1e4:1},Tn=class{coinPoolBaseUrl;constructor(e={}){this.coinPoolBaseUrl=e.coinPoolBaseUrl||"https://api.coinpool.app"}isSupported(e){let t=I(e);return!!(t&&mc[t])}listSupportedChains(){return Object.keys(mc).filter(e=>I(e)===e)}numericChainId(e){let t=I(e);return t?mc[t]:void 0}async getPairs(e){let t=this.numericChainId(e.chain);if(!t)return[];let o=(await this.fetchV2Items(t)).map(s=>this.mapV2Item(s)).filter(s=>s!==null);if(e.tokens&&e.tokens.length>=2){let s=e.tokens[0].toUpperCase(),a=e.tokens[1].toUpperCase(),i=(l,c)=>l.includes(c)||c.includes(l);o=o.filter(l=>{let[c="",d=""]=l.pair.toUpperCase().split("/");return i(c,s)&&i(d,a)||i(c,a)&&i(d,s)})}return o}async getByAddress(e){let t=this.numericChainId(e.chain);if(!t)return[];let r=e.poolAddress.toLowerCase();return(await this.fetchV2Items(t)).filter(s=>s.poolId?.toLowerCase()===r).map(s=>this.mapV2Item(s)).filter(s=>s!==null).sort((s,a)=>(a.apr??-1/0)-(s.apr??-1/0))}async fetchV2Items(e){try{let t=`${this.coinPoolBaseUrl}/pair/v2?chainId=${e}&limit=1000&page=1&sortApr=true`,r=await C.get(t);if(!r.ok)throw new Error(_(r));return r.data?.data?.items||[]}catch{return[]}}mapV2Item(e){if(!e?.poolId||!e.token0||!e.token1)return null;let t=e.token0.decimal??18,r=e.token1.decimal??18,o=S=>S==null||!Number.isFinite(S)?0:Math.pow(1.0001,S)*Math.pow(10,t-r),s=o(e.minTick),a=o(e.maxTick),i=e.token0.price,l=e.token1.price,c=typeof i=="number"&&typeof l=="number"&&l>0?i/l:0,d=e.selectorAddress?.toLowerCase()===e.token0.address.toLowerCase(),u=d?s:a>0?1/a:0,p=d?a:s>0?1/s:0,m=d?c:c>0?1/c:0,f=d?e.token0.symbol:e.token1.symbol,h=d?e.token1.symbol:e.token0.symbol;if(!m||!u&&!p)return null;let g=Math.min(u,p),b=Math.max(u,p);if(m<g||m>b)return null;let y=Number(e.fee),w=fy[y]??y/1e4,k=$(e.apr)??$(e.aprAvg)??null,v=$(e.aprAvg)??null;return{poolId:e.poolId,pair:`${e.token0.symbol}/${e.token1.symbol}`,fee:`${w}%`,apr:k,aprAvg:v,token0Price:i,token1Price:l,priceRange:{minPrice:Se(u),maxPrice:Se(p),currentPrice:Se(m),baseToken:f,quoteToken:h}}}};function gy(n){if(!(!n||n.length===0))return n.map(e=>({timestamp:e.timestamp,volumeUsd:e.value}))}function yy(n,e){if(!(typeof n!="number"||typeof e!="number"||e<=0))return Math.round(n/e*1e3)/1e3}function zn(n,e){let t=e!==void 0&&Array.from(e.values()).some(i=>i.safetyLevel!=null),r=n.totalLiquidity?.value,o=n.volume24h?.value,s=n.feeTier,a=di(s,n.protocolFee,n.protocolVersion);return{address:n.address??n.poolId,protocolVersion:n.protocolVersion,poolId:n.poolId,tickSpacing:n.tickSpacing,isDynamicFee:n.isDynamicFee,hookAddress:n.hook?.address,feeTierBps:s,feeTierPercent:typeof s=="number"?s/1e4:void 0,tvlUsd:r,tvlChange24hPercent:n.totalLiquidityPercentChange24h?.value,volume24hUsd:o,fees24hUsd:pi(o,s,a),lpFeeShare:a,aprPercent:$(n.apr),totalAprPercent:$(n.totalApr),volumeToTvlRatio:yy(o,r),txCount:n.txCount,historicalVolumeWeek:gy(n.historicalVolume),token0:np(n.token0,n.token0Supply,e,t),token1:np(n.token1,n.token1Supply,e,t)}}function np(n,e,t,r){if(!n)return;let o=n.address?t?.get(n.address.toLowerCase()):void 0,s=r&&n.address!=null&&!o?.safetyLevel,a=o?.isSpam==null?void 0:o.isSpam.toUpperCase()==="TRUE",i=Number(o?.feeData?.buyFeeBps??0),l=Number(o?.feeData?.sellFeeBps??0),c=Number.isFinite(i)&&Number.isFinite(l)?Math.max(i,l):0;return{address:n.address,symbol:n.symbol,name:n.name,decimals:n.decimals,priceUsd:n.market?.price?.value??n.price?.value,reserve:e,isSpam:a??n.project?.isSpam??void 0,safetyLevel:o?.safetyLevel??n.project?.safetyLevel??void 0,transferFeeBps:c>0?c:void 0,isUnrecognizedToken:s||void 0}}var rp=/^0x[a-fA-F0-9]{40}$/,by=6,_o=class extends A{name="uniswap-pool-detail";description="Get detailed stats for a Uniswap V3 pool by token pair (and optional fee tier). Always runs a search first and filters by the provided symbols + fee tier. When the filter resolves to exactly one pool, returns its full detail. When the pair is fully named but NO fee tier is given, returns detail plus a comparative analysis of ALL the pair's fee-tier variants (no need to ask the user to pick). When only one token is given (so the matches are different pairs), returns a `candidates` list \u2014 show it and ask which pair they want, then re-call this tool with the missing info. Detail response includes: pool address, fee tier (bps and %), both tokens (symbol, name, address, decimals, USD price), token0/token1 reserves, total TVL with 24h % change, 24h volume, weekly historical volume series, total tx count, and the pool's fee APR (net of the protocol fee). NEVER pass a pool address \u2014 the tool resolves the address itself by searching. Token contract addresses are NOT pool addresses. Source: https://app.uniswap.org. Supports: "+Oe();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:`Symbol of one of the pool's tokens (e.g. "USDC"). Pair order does not matter \u2014 USDC/WETH and WETH/USDC resolve to the same pool. When both token0Symbol and token1Symbol are provided the search is filtered to that exact pair.`,required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Optional \u2014 when omitted the tool returns all pools containing token0Symbol so the user can pick.',required:!1},{name:"feeTier",type:"number",description:'Fee tier in basis points (bps): 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. ONLY set this when the user EXPLICITLY mentions a fee tier (in the current message OR earlier in the conversation, e.g. "USDC/WETH 0.05%" \u2192 feeTier=500). NEVER guess or infer one. When the user has not mentioned a fee tier, OMIT it \u2014 the tool then returns detail plus a comparative analysis of ALL fee-tier variants of the pair (no need to ask the user to pick one).',required:!1},{name:"chain",type:"string",description:nt,required:!1},...Ee];service;coinPool;pool;constructor(e,t){super(),this.service=new $e(e),this.coinPool=new Tn(t),this.pool=new ie}async run(e,t){let r=await te(rt(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",a=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0;if(!s)return{error:"token0Symbol is required. Provide at least one token symbol; add token1Symbol and feeTier to narrow the result."};let l=a?`${s} ${a}`:s,c=await this.service.searchPools({query:l,chain:o,page:1,size:100,protocolVersion:"V3"});if(!c.success)return{error:c.error||"Pool search failed"};let d=c.data??[],p=d.filter(g=>this.matchesFilter(g,s,a,i,"ordered")),m=!1;if(p.length===0&&a){let g=d.filter(b=>this.matchesFilter(b,s,a,i,"reversed"));g.length>0&&(p=g,m=!0)}if(p.length===0)return{error:`No V3 pool matched ${this.describeQuery(s,a,i)} on ${T(o)}. Verify the symbols and fee tier with the user.`};if(p.length===1){let g=p[0];if(!g.id||!rp.test(g.id))return{error:"Resolved pool has no valid address"};let[b,y,w]=await Promise.all([this.service.getPoolDetailEnriched({addressOrId:g.id,chain:o}),this.fetchPriceRanges(o,g.id,g.token0?.symbol,g.token1?.symbol),this.service.getTokenSafetyByAddress([g.token0?.address,g.token1?.address],o)]);if(!b.success||!b.data)return{error:b.error||"Failed to fetch pool detail"};let k={...zn(b.data,w),...ht(o,g.id)},v=await this.pool.isAddLiquiditySupported(o)?pe([k],e,T(o)):[];return{priceRanges:y,_instructions:me+"Give an expert read on ONE pool. First, a SNAPSHOT block: lead with the pair (token0/token1 symbols), fee tier (%), and chain, then show TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), token0 reserve + USD price, token1 reserve + USD price, and total tx count. Optionally include the weekly historical volume as a sparkline-style bullet list. Then an EXPERT ANALYSIS section \u2014 is this pool worth providing liquidity in, and why. "+he+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` \u2014 omitting the APR for any entry whose `apr` is null/absent (never "APR 0%", "N/A" or a dash). CRITICAL: that `apr` is the yield for THAT specific range only \u2014 NEVER present it as the overall pool APR. Sort by apr desc; note the top entry is the most concentrated/highest-yield range but narrower = higher risk of going out of range. When `priceRanges` is empty or absent, simply omit this section. '+Y+j+(v.length>0?de:""),pairOrderMatched:m?"reversed":"ordered",pool:k,...v.length>0?{actionButtons:v}:{}}}if(a){let g=this.rankCandidates(p).slice(0,by),[b,y]=await Promise.all([Promise.all(g.map(async k=>{if(!k.id||!rp.test(k.id))return;let v=await this.service.getPoolDetailEnriched({addressOrId:k.id,chain:o});if(!(!v.success||!v.data))return{detail:v.data,id:k.id}})),this.service.getTokenSafetyByAddress(g.flatMap(k=>[k.token0?.address,k.token1?.address]),o)]),w=b.filter(k=>k!=null).map(k=>({...zn(k.detail,y),...ht(o,k.id)}));if(w.length>0){let k=await this.pool.isAddLiquiditySupported(o)?pe(w,e,T(o)):[];return{_instructions:me+"The user named a pair WITHOUT a fee tier, so here is EVERY fee-tier variant of that pair \u2014 do NOT ask them to pick a tier. Present them as a ranked list (rank them by capital efficiency / fee yield, not just TVL). For each variant show the fee tier (%), TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), and tx count. Analyze every variant \u2014 give each its own genuine read, never skip one, and never repeat the same sentence structure. "+he+"Focus on which fee tier is the right home for THIS pair: lower tiers (0.01\u20130.05%) win on stable/correlated pairs and high turnover, higher tiers (0.3\u20131%) suit volatile pairs \u2014 and the tier that actually captures most of the real volume with deep TVL is usually the one to LP in. Close with an overall section naming the single best fee tier to provide liquidity in right now and why. "+be+Y+j+(k.length>0?de:""),chain:o,pairOrderMatched:m?"reversed":"ordered",multiFeeTier:!0,count:w.length,pools:w,...k.length>0?{actionButtons:k}:{}}}}let f=this.rankCandidates(p).slice(0,10).map(g=>{let b=this.formatCandidate(g);return{...b,...ht(o,b.address)}}),h=await this.pool.isAddLiquiditySupported(o)?pe(f,e,T(o)):[];return{_instructions:"The filter matched multiple pools. Render them as a numbered list (pair, fee tier %, 24h volume) and ask the user which one they want to see. Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. When they answer, re-call this tool with their selection \u2014 pass token0Symbol + token1Symbol + feeTier (use the exact feeTier in bps from the chosen candidate). Format numbers human-readably (e.g. $12.5M, 0.05%). Do NOT mention tool/API names."+(h.length>0?de:""),chain:o,pairOrderMatched:m?"reversed":"ordered",reason:this.candidateReason(s,a,i),missing:this.missingFields(a,i),candidates:f,...h.length>0?{actionButtons:h}:{}}}matchesFilter(e,t,r,o,s){if(o!=null&&e.feeTier!==o)return!1;let a=(e.token0?.symbol??"").toLowerCase(),i=(e.token1?.symbol??"").toLowerCase(),l=t.toLowerCase();if(r){let c=r.toLowerCase();return s==="reversed"?this.symbolIncludes(a,c)&&this.symbolIncludes(i,l):this.symbolIncludes(a,l)&&this.symbolIncludes(i,c)}return this.symbolIncludes(a,l)||this.symbolIncludes(i,l)}symbolIncludes(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}describeQuery(e,t,r){let o=t?`${e}/${t}`:e;return r!=null?`${o} at fee tier ${r} bps`:o}candidateReason(e,t,r){return t?r==null?`Multiple fee tiers exist for ${e}/${t}. Ask the user which fee tier they want.`:`Multiple ${e}/${t} pools share fee tier ${r} bps. Ask the user which one they meant.`:`Multiple pools contain ${e}. Ask the user for the other token (and fee tier).`}missingFields(e,t){let r=[];return e||r.push("token1Symbol"),t==null&&r.push("feeTier"),r}rankCandidates(e){return[...e].sort((t,r)=>(r.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}formatCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}async fetchPriceRanges(e,t,r,o){try{if(!this.coinPool.isSupported(e))return[];let s=await this.coinPool.getByAddress({chain:e,poolAddress:t});return s.length===0&&r&&o&&(s=await this.coinPool.getPairs({chain:e,tokens:[r,o]})),s.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}};var wy=["V2","V3","V4","ALL"],No=class extends A{name="uniswap-search-pools";description='Search Uniswap liquidity pools on a given chain by free-text query \u2014 a SINGLE token symbol or token name. Returns matching pools with: pool address, fee tier (bps + %), protocol version, both tokens (symbol, name, address, decimals, logo), and short-window USD volume buckets (6h / 12h / 24h). Use this tool when the user names ONE token and wants pools related to it: "find WBTC pools on Optimism", "pools containing PEPE on Ethereum", "show USDC pools". Do NOT use for: (a) two-symbol pair lookups like "USDC/WETH 0.05%" \u2014 use get-pool-detail; (b) raw 0x addresses (token or pool) \u2014 use lookup-pool-by-address; (c) chain-wide rankings with no token mentioned \u2014 use get-top-pools. Source: https://app.uniswap.org search. Supports: '+Oe();category="blockchain-data";parameters=[{name:"query",type:"string",description:'Single token symbol or name to search pools by (e.g. "WBTC", "USDC", "pepe"). Do NOT pass a 0x address (use lookup-pool-by-address) or a two-symbol pair (use get-pool-detail).',required:!0},{name:"chain",type:"string",description:nt,required:!1},{name:"protocolVersion",type:"string",description:'Filter results by Uniswap protocol version: "V2", "V3", "V4", or "ALL" to include every version. Default is "V3" \u2014 only switch when the user explicitly asks for V2, V4, or all versions.',required:!1,default:"V3"},{name:"page",type:"number",description:"1-based page index. Defaults to 1.",required:!1,default:1},{name:"size",type:"number",description:'Page size (max 50). Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"feeTier",type:"number",description:'Optional fee tier filter in basis points (bps): 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. When provided, only pools with this exact fee tier are returned. Pass it whenever the user mentions a fee tier in the current message OR earlier in the conversation (e.g. "USDC/WETH 0.05% pool on Base" \u2192 feeTier=500). Omit otherwise.',required:!1},...Ee];service;pool;constructor(e){super(),this.service=new $e(e),this.pool=new ie}async run(e,t){let r=typeof e.query=="string"?e.query.trim():"";if(!r)return{error:"Search query is required"};let o=await te(rt(),e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=typeof e.page=="number"&&Number.isFinite(e.page)&&e.page>0?Math.floor(e.page):1,i=typeof e.size=="number"&&Number.isFinite(e.size)&&e.size>0?Math.min(Math.floor(e.size),50):5,l=this.parseProtocolFilter(e.protocolVersion),c=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.floor(e.feeTier):void 0,d=await this.service.searchPools({query:r,chain:s,page:a,size:i,protocolVersion:l,feeTier:c});if(!d.success)return{error:d.error||"Failed to search pools"};let u=(d.data??[]).map(m=>this.formatPool(m)),p=await this.pool.isAddLiquiditySupported(s)?pe(u,e,T(s)):[];return{_instructions:me+"Present the pools that match the search AND give an expert read on each. Render each pool as its own block: a bold header with the pair (token0/token1 symbols) + fee tier (%), then beneath it the metrics that have data \u2014 TVL (USD), 24h volume (USD), APR (%), tx count, protocol version. Skip any field that is null/undefined \u2014 never show zeros or dashes for missing data. Then add an expert read on each pool \u2014 is it worth providing liquidity in, and why. "+he+be+"When several pools share the searched token, finish with a clear TOP PICK among them. "+Y+"Mention the search query and chain in the intro. "+j+(p.length>0?de:""),query:r,chain:s,protocolVersion:l,feeTierBps:c,feeTierPercent:c!=null?c/1e4:void 0,page:a,size:i,count:u.length,pools:u.map(m=>({...m,...ht(s,m.address)})),...p.length>0?{actionButtons:p}:{}}}parseProtocolFilter(e){if(typeof e=="string"){let t=e.trim().toUpperCase();if(wy.includes(t))return t}return"V3"}formatPool(e){let t=e.isDynamicFee===!0||hn(e.feeTier),r={address:e.id,chainId:e.chainId,protocolVersion:e.protocolVersion,feeTierBps:t?void 0:e.feeTier,feeTierPercent:!t&&typeof e.feeTier=="number"?e.feeTier/1e4:void 0,...t?{isDynamicFee:!0}:{}},o=$(e.apr);o!=null&&(r.apr=o),e.tvlUsd!=null&&(r.tvlUsd=e.tvlUsd);let s=e.volume1DayUsd??e.volumeUsd24hr;s!=null&&(r.volume24hUsd=s),e.volumeUsd6hr!=null&&(r.volume6hUsd=e.volumeUsd6hr),e.volumeUsd12hr!=null&&(r.volume12hUsd=e.volumeUsd12hr),e.txCount!=null&&(r.txCount=e.txCount),e.tvlUsd!=null&&e.tvlUsd>0&&s!=null&&(r.volumeToTvlRatio=Math.round(s/e.tvlUsd*1e3)/1e3);let a=e.token0,i=e.token1;return a&&(r.token0={address:a.address,symbol:a.symbol,name:a.name,decimals:a.decimals}),i&&(r.token1={address:i.address,symbol:i.symbol,name:i.name,decimals:i.decimals}),r}};var Lo=class extends A{name="uniswap-pool-by-address";description=`Resolve an unknown 0x address as either a Uniswap pool or a token, then return the appropriate data: pool detail when the address is a pool, or the list of pools containing that token when the address is a token. Use this tool when the user pastes a single address and asks about "the pool" without saying which kind. For pool detail (when the address is a pool): pair, fee tier, TVL with 24h % change, 24h volume, 24h fees, estimated APR, token reserves with USD prices, and each token's safety flags. For token resolution (when the address is a token): the resolved token (symbol, name, decimals) plus a ranked list of pools that include it (pair, fee tier, 24h volume, pool address). Source: https://app.uniswap.org. Supports: `+Oe();category="blockchain-data";parameters=[{name:"address",type:"string",description:"A 0x-prefixed EVM address. May be a Uniswap pool contract OR a token contract \u2014 the tool figures out which.",required:!0},{name:"chain",type:"string",description:nt,required:!1},...Ee];service;pool;constructor(e){super(),this.service=new $e(e),this.pool=new ie}async run(e,t){let r=await te(rt(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.address=="string"?e.address.trim():"",[a,i]=await Promise.all([this.service.searchPools({query:s,chain:o,page:1,size:5,protocolVersion:"ALL"}),this.service.searchTokens({query:s,chain:o,page:1,size:5})]),l=a.success?this.findPoolByAddress(a.data??[],s):void 0;if(l)return this.handlePoolHit(l,o,e);let c=i.success?this.findTokenByAddress(i.data??[],s):void 0;return c?this.handleTokenHit(c,o,e):!a.success&&!i.success?{error:a.error||i.error||"Failed to resolve address"}:{error:`Address ${s} did not match any pool or token Uniswap knows on ${T(o)}. Verify the chain (the address may exist on a different network) or ask the user for context.`}}async handlePoolHit(e,t,r){if(!e.id)return{error:"Resolved pool has no identifier"};let o=await this.service.getPoolDetailEnriched({addressOrId:e.id,chain:t,enrich:!1});if(!o.success||!o.data)return{error:o.error||"Failed to fetch pool detail"};let s=await this.service.getTokenSafetyByAddress([o.data.token0?.address,o.data.token1?.address],t),a=o.data.protocolVersion??e.protocolVersion??"V3",i={...zn(o.data,s),...ht(t,e.id)},l=await this.pool.isAddLiquiditySupported(t)?pe([i],r,T(t)):[];return{_instructions:`The address is a Uniswap ${a} pool. `+me+"Give an expert read on ONE pool. First, a SNAPSHOT block: lead with the pair (token0/token1 symbols), fee tier (%), protocol version, and chain, then show TVL (USD) with 24h % change, 24h volume (USD), 24h fees (USD), estimated APR (%), token0 reserve + USD price, and token1 reserve + USD price. For V4 pools also mention tickSpacing, isDynamicFee, and the hook address if present. Then an EXPERT ANALYSIS section \u2014 is this pool worth providing liquidity in, and why. "+he+be+Y+j+(l.length>0?de:""),resolvedAs:"pool",chain:t,protocolVersion:a,pool:i,...l.length>0?{actionButtons:l}:{}}}async handleTokenHit(e,t,r){let o=e.symbol?.trim();if(!o)return{error:"Resolved token has no symbol \u2014 cannot search related pools."};let s=await this.service.searchPools({query:o,chain:t,page:1,size:100,protocolVersion:"V3"});if(!s.success)return{error:s.error||"Failed to fetch pools for resolved token"};let a=(e.address??"").toLowerCase(),l=[...(s.data??[]).filter(u=>{let p=(u.token0?.address??"").toLowerCase(),m=(u.token1?.address??"").toLowerCase();return p===a||m===a})].sort((u,p)=>(p.volumeUsd24hr??0)-(u.volumeUsd24hr??0)).slice(0,10),c=l.map(u=>({...this.formatPoolCandidate(u),...ht(t,u.id)})),d=await this.pool.isAddLiquiditySupported(t)?pe(c,r,T(t)):[];return{_instructions:"The address is a token, not a pool. Tell the user which token it is (symbol + name), then render the matching pools as a numbered list: pair (token0/token1 symbols), fee tier (%), protocol version, 24h volume (USD). Write each pair as PLAIN TEXT \u2014 do NOT add markdown links, URLs, or raw pool addresses; the system makes each pair clickable automatically. Ask which pool they want detail on; when they answer, re-call this tool with that pool address to fetch the detail. Format numbers human-readably. Omit null fields. Do NOT mention tool/API names."+(d.length>0?de:""),resolvedAs:"token",chain:t,protocolVersion:"V3",token:this.formatToken(e),poolCount:l.length,pools:c,...d.length>0?{actionButtons:d}:{}}}findPoolByAddress(e,t){let r=t.toLowerCase();return e.find(o=>(o.id??"").toLowerCase()===r)}findTokenByAddress(e,t){let r=t.toLowerCase();return e.find(o=>(o.address??"").toLowerCase()===r)}formatToken(e){return{address:e.address,symbol:e.symbol,name:e.name,decimals:e.decimals,chainId:e.chainId,isSpam:e.isSpam,safetyLevel:e.safetyLevel}}formatPoolCandidate(e){return{address:e.id,protocolVersion:e.protocolVersion,feeTierBps:e.feeTier,feeTierPercent:typeof e.feeTier=="number"?e.feeTier/1e4:void 0,volume24hUsd:e.volumeUsd24hr,pair:e.token0?.symbol&&e.token1?.symbol?`${e.token0.symbol}/${e.token1.symbol}`:void 0,token0:e.token0?{symbol:e.token0.symbol,name:e.token0.name,address:e.token0.address}:void 0,token1:e.token1?{symbol:e.token1.symbol,name:e.token1.name,address:e.token1.address}:void 0}}};var vi=class{uniswap;constructor(e){this.uniswap=new $e(e)}async resolveCandidates(e){let t=await this.uniswap.searchPools({query:`${e.token0Symbol} ${e.token1Symbol}`,chain:e.chain,page:1,size:100,protocolVersion:e.protocolVersion,feeTier:e.feeTier});return t.success?t.data??[]:null}};var op=/^0x[a-fA-F0-9]{40}$/,sp=/^0x[a-fA-F0-9]{64}$/,Xn=class extends A{name="pool-open-add-liquidity-form";kind="ui";category="pool-action";description='Open the Add-Liquidity form for a specific Uniswap V3 pool. Use this when the user wants to provide liquidity / add LP / farm / stake / deposit into a pool \u2014 natural-language verbs in any language all map here. Resolves the pool by its exact address when the message carries one (the add-liquidity buttons under a pool listing append "(Pool: 0x\u2026 - <chain>)" \u2014 pass that address through as `poolAddress`), otherwise by token symbols and optional fee tier. Reads on-chain state, checks the connected wallet\'s NATIVE balance, then returns a UI payload that the FE renders as the form (with two preset ranges: Stable \xB13 ticks and Wide -50%/+100%). CONSTRAINT: the gateway only accepts the chain\'s NATIVE coin as input (ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche). The native amount is auto-split via deBridge into both pool tokens \u2014 the user never selects a different input. If the user asks to add liquidity using a NON-NATIVE token amount (e.g. "add pool with 5 USDT", "th\xEAm 100 USDC"), pass that symbol via `requestedNonNativeToken` so the tool can return error="unsupported_input_token" \u2014 never silently convert their non-native amount into native or USD. PRECONDITION: a connected wallet (userContext.walletAddress). If absent, the tool returns error="wallet_not_connected" and the agent must ask the user to connect. VERSION CONSTRAINT: only Uniswap V3 pools can be added to. When the pool the user picked is V2 or V4, the tool returns error="unsupported_protocol_version" with the version \u2014 tell the user that version is not supported yet (the pool DOES exist; never say it was not found).';parameters=[{name:"token0Symbol",type:"string",description:`Symbol of one of the pool's tokens (e.g. "USDC"). Pair order does not matter.`,required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Required to uniquely identify the pool.',required:!0},{name:"poolAddress",type:"string",description:`The pool's exact on-chain address (0x\u2026), when the user's message names one \u2014 the add-liquidity buttons under a pool listing carry it as "(Pool: 0x\u2026 - <chain>)". Pass it through VERBATIM whenever it is present: it pins the flow to that exact pool instead of re-searching by symbols, which can land on a different pool of the same pair. Omit when the user named no address.`,required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. Omit when unknown \u2014 the tool will resolve the best match automatically.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"prefillNativeAmount",type:"number",description:"Optional NATIVE-COIN amount (human-readable) to pre-fill the form's input field. ONLY pass this when the user named an amount in the chain's native coin itself \u2014 ETH on Ethereum/Base/Arbitrum/Optimism/Linea, BNB on BSC, MATIC on Polygon, AVAX on Avalanche. Example: \"add 0.1 ETH to USDC/WETH on Base\". Pass the plain decimal number (e.g. 0.1 for 0.1 ETH). DO NOT convert a non-native amount (USDC, USDT, DAI, WBTC, \u2026) into native here \u2014 pass `requestedNonNativeToken` instead so the tool can reject. Mutually exclusive with prefillUsdAmount \u2014 pass one or neither.",required:!1},{name:"prefillUsdAmount",type:"number",description:'Optional USD amount to pre-fill the form\'s input field. Use this ONLY when the user explicitly speaks in USD/dollars \u2014 e.g. "add $10 to this pool", "10 dollars", "10 \u0111\xF4". The tool converts the USD value to native amount automatically using the current native-token price. DO NOT use this as a workaround for non-native token amounts (e.g. "5 USDT" is NOT $5 \u2014 USDT may de-peg, and even if 1:1 the user asked for a token, not USD). For non-native token amounts pass `requestedNonNativeToken` instead. Mutually exclusive with prefillNativeAmount \u2014 pass one or neither.',required:!1},{name:"requestedNonNativeToken",type:"string",description:`Set this ONLY when the user named an AMOUNT in a non-native token \u2014 e.g. "add pool with 5 USDT", "add 100 USDC to USDC/WETH", "th\xEAm 5 USDT v\xE0o pool". The trigger is "<number> <non-native-symbol>" in the user's message, NOT the mere appearance of the symbol. Pass the symbol the user attached the amount to (e.g. "USDT", "USDC", "DAI"). CRITICAL: If the user also names a NATIVE amount in the same message (e.g. "add USDC/WETH with 0.1 ETH", "th\xEAm pool USDC/WETH 0.3% v\u1EDBi 0.000005 ETH"), the native amount is the input \u2014 leave this EMPTY and use prefillNativeAmount. The pool pair symbols (the two tokens after "pool" / "to") are NEVER the input token by themselves \u2014 they only identify which pool. The tool will return error="unsupported_input_token" so the agent can tell the user that only the chain's native coin is accepted as input. DO NOT silently convert the user's non-native amount into a native amount or USD amount \u2014 the user explicitly named a different asset and must be informed, not auto-corrected. Leave empty when the user did name a native amount, a USD amount, or no amount at all.`,required:!1},{name:"rangeStrategy",type:"string",description:'Optional preset that pre-fills the min/max price inputs (FE keeps them editable). One of: "stable" \u2014 \xB13 tickSpacing around the current price (narrow, higher yield, higher out-of-range risk; pick for stablecoin / low-volatility pairs and when the user says "safe", "tight", "high yield", "t\u1EADp trung"); "wide" \u2014 currentPrice \xD7 [0.5, 2.0] (broad, lower yield, less rebalancing; pick when the user says "wide", "set and forget", "r\u1ED9ng"); "full" \u2014 full V3 tick range (V2-style, lowest yield, never goes out of range; pick when the user says "full range", "v2-style", "kh\xF4ng lo out of range"). Omit when the user did not signal a preference AND did not provide explicit minPrice/maxPrice. Mutually exclusive with minPrice/maxPrice \u2014 if both are passed, explicit prices win.',required:!1},{name:"minPrice",type:"number",description:'Optional explicit lower bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 minPrice=1800. Must be paired with maxPrice. When set, overrides rangeStrategy.',required:!1},{name:"maxPrice",type:"number",description:'Optional explicit upper bound for the price range, in token1-per-token0 units (same unit as pool.currentPrice \u2014 decimal-adjusted). Pass when the user named a concrete number, e.g. "range 1800 to 2200" \u2192 maxPrice=2200. Must be paired with minPrice. When set, overrides rangeStrategy.',required:!1},{name:"add_button_label",type:"string",description:`Label template for the per-fee-tier "Add liquidity" suggestion buttons, IN THE USER'S CURRENT LANGUAGE. ALWAYS pass this when you call the tool with a pair but NO feeTier (the tool may return several fee-tier variants for the pair, and each gets a one-tap button). Use the exact placeholder "{pair}" (do not translate the braces); it is replaced per pool with the pair + fee tier (e.g. "USDC/WETH 0.05%"). English example: "Add liquidity to {pair}". Vietnamese example: "Th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}.`,required:!1},{name:"add_prompt_template",type:"string",description:'A short "add liquidity" command template IN THE USER\'S CURRENT LANGUAGE, submitted as the next user turn when a fee-tier button is clicked \u2014 it carries the chosen fee tier so the tool resolves that exact pool. ALWAYS pass this alongside `add_button_label` when calling with a pair but no feeTier. Use the exact placeholder "{pair}" (replaced with the pair + fee tier, e.g. "USDC/WETH 0.05%"). English example: "add liquidity to {pair}". Vietnamese example: "th\xEAm thanh kho\u1EA3n {pair}". Always include {pair}. Do NOT add a chain name yourself \u2014 the chain this pair is on is appended to the prompt automatically.',required:!1}];resolver;pool;coinPool;minProvideUsd;constructor(e){super(),this.resolver=e?.resolver??new vi(e),this.pool=new ie(e?.pool),this.coinPool=new Tn(e?.coinPool),this.minProvideUsd=e?.minProvideUsd??.01}async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:r,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&typeof s=="object"&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let r=await te(vn(this.pool),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",a=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,l=typeof e.poolAddress=="string"?e.poolAddress.trim():"",c=op.test(l)||sp.test(l)?l.toLowerCase():"",d=sp.test(l),u=typeof e.prefillNativeAmount=="number"&&Number.isFinite(e.prefillNativeAmount)&&e.prefillNativeAmount>0?e.prefillNativeAmount:null,p=typeof e.prefillUsdAmount=="number"&&Number.isFinite(e.prefillUsdAmount)&&e.prefillUsdAmount>0?e.prefillUsdAmount:null,m=typeof e.requestedNonNativeToken=="string"&&e.requestedNonNativeToken.trim()?e.requestedNonNativeToken.trim():null,f=m&&u!=null&&(m.toLowerCase()===s.toLowerCase()||m.toLowerCase()===a.toLowerCase())?null:m,h=this.parseRangeStrategy(e.rangeStrategy),g=typeof e.minPrice=="number"&&Number.isFinite(e.minPrice)&&e.minPrice>0?e.minPrice:null,b=typeof e.maxPrice=="number"&&Number.isFinite(e.maxPrice)&&e.maxPrice>0?e.maxPrice:null;if(!s||!a)return{error:"missing_pool_identifier",_instructions:"token0Symbol and token1Symbol are required. Ask the user for the missing token symbol."};let y=mt(o);if(!y)return{error:"unsupported_chain",chain:o,_instructions:`Chain ${o} is not supported by the add-liquidity flow.`};let w=Ro(o);if(f&&w&&f.toLowerCase()!==w.symbol.toLowerCase())return{error:"unsupported_input_token",requestedToken:f,nativeSymbol:w.symbol,chainName:y.name,_instructions:`The user asked to add liquidity using ${f}, but this app only supports the chain's native coin (${w.symbol} on ${y.name}) as the input. Tell the user this in their language and ask them to either restate the amount in ${w.symbol} or in USD. DO NOT silently convert their ${f} amount, do NOT pre-fill the form, and do NOT call this tool again until the user provides a native or USD amount.`};let k=await this.pool.getGatewayAddress(o);if(!k)return{error:"no_gateway_configured",chain:o,_instructions:`No gateway contract is configured for chain ${o} (${y.name}). Tell the user this chain is not yet supported for add-liquidity in this app.`};let v=t?.walletAddress;if(!v)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before adding liquidity. Do NOT render the form."};if(d)return this.unsupportedVersionResult({protocolVersion:"V4",token0:{symbol:s},token1:{symbol:a}},s,a,y.name);let S=await this.resolver.resolveCandidates({chain:o,token0Symbol:s,token1Symbol:a,protocolVersion:"V3",feeTier:c?void 0:i});if(S===null)return{error:"pool_search_failed"};let P=c?S.find(G=>typeof G.id=="string"&&G.id.toLowerCase()===c):void 0;if(c&&!P){let G=await this.findUnsupportedVersionPool(o,s,a,i,c);if(G)return this.unsupportedVersionResult(G,s,a,y.name)}let x=P??S.find(G=>this.matchesPairExact(G,s,a,i)),U=x?[]:S.filter(G=>this.matchesPair(G,s,a,i));if(!x&&U.length===0){let G=await this.findUnsupportedVersionPool(o,s,a,i,c);return G?this.unsupportedVersionResult(G,s,a,y.name):{error:"pool_not_found",_instructions:`No V3 pool found for ${s}/${a}${i!=null?` at ${i}bps`:""} on ${y.name}. Verify the inputs with the user.`}}if(!x&&U.length>1){let G=U.map(ve=>{let nr=ve.volume1DayUsd??ve.volumeUsd24hr,ia=ve.tvlUsd,Rc=typeof nr=="number"&&typeof ia=="number"&&ia>0?nr/ia:void 0;return{address:ve.id,token0Symbol:ve.token0?.symbol,token1Symbol:ve.token1?.symbol,feeTier:ve.feeTier,feeTierPercent:ve.feeTier!=null?ve.feeTier/1e4:void 0,volume24hUsd:nr,tvlUsd:ia,...Rc!=null?{volumeToTvlRatio:Rc}:void 0,...ve.apr?{apr:ve.apr}:void 0}}).sort((ve,nr)=>(nr.volumeToTvlRatio??nr.apr??-1/0)-(ve.volumeToTvlRatio??ve.apr??-1/0)).slice(0,5),$i=pc(G.map(ve=>({token0:{symbol:ve.token0Symbol},token1:{symbol:ve.token1Symbol},feeTierPercent:ve.feeTierPercent,address:ve.address})),typeof e.add_button_label=="string"?e.add_button_label:"",typeof e.add_prompt_template=="string"?e.add_prompt_template:"",T(o));return{relatedPools:G,count:G.length,...$i.length>0?{actionButtons:$i}:{},_instructions:me+"The user wants to ADD LIQUIDITY to this pair but named NO fee tier \u2014 `relatedPools` holds the related pools (the pair's fee-tier variants and closely-matching pools). Do NOT just ask them to pick blindly: give a genuine comparative read. Present them as a ranked list (rank by capital efficiency / fee yield, not just TVL); for each show the fee tier (%), TVL (USD), 24h volume (USD), and estimated APR (%) when present. Analyze each with its own real read \u2014 never skip one or repeat the same sentence structure. "+he+"Focus on which fee tier is the best home for THIS pair to LP in: lower tiers (0.01\u20130.05%) suit stable/correlated pairs and high turnover, higher tiers (0.3\u20131%) suit volatile pairs \u2014 the tier that captures most of the real volume on deep TVL is usually the one to provide liquidity in. Close by naming the single best fee tier to add liquidity in right now and why, then invite the user to confirm a tier to continue. When they choose, re-run the add-liquidity step with token0Symbol + token1Symbol + the chosen feeTier (in bps). "+be+Y+j+($i.length>0?' A clickable "Add liquidity" button is shown below your reply for each fee-tier candidate automatically \u2014 do NOT list, number, or repeat those buttons.':"")}}let E=x??U[0];if(!E.id||!op.test(E.id))return{error:"invalid_pool_address"};let we=this.fetchPriceRanges(o,E.id,E.token0?.symbol,E.token1?.symbol),V=await this.pool.readPoolOnchain(o,E.id),[z,fe,Ne]=await Promise.all([this.pool.getNativeBalance(o,v),this.pool.estimateGasReserveWei(o),this.pool.getNativePriceUsd(o)]),W=z>fe?z-fe:0n,J=Ro(o),Ht=Number(W)/10**J.decimals,tr=Number(z)/10**J.decimals,Le=Ne!=null?Ht*Ne:null,[Ye,Vt]=await Promise.all([this.pool.readErc20Decimals(o,V.token0),this.pool.readErc20Decimals(o,V.token1)]),Ge={min:pt(yn,Ye,Vt),max:pt(wo,Ye,Vt)},ze=null;z===0n?ze="no_balance":Le!=null&&Le<this.minProvideUsd&&(ze="insufficient_balance");let Pn=E.token0,Sn=E.token1,aa=[25,50,75,100].map(G=>({percent:G,amountWei:(W*BigInt(G)/100n).toString(),amount:Ht*(G/100)})),Lt=null,at=null;if(u!=null){at=u;let G=BigInt(Math.floor(at*10**J.decimals));G>0n&&(Lt=G.toString())}else if(p!=null&&Ne!=null&&Ne>0){at=p/Ne;let G=BigInt(Math.floor(at*10**J.decimals));G>0n&&(Lt=G.toString())}let xc={address:ue,isNative:!0,symbol:J.symbol,name:J.name,decimals:J.decimals,priceUsd:Ne,balanceWei:z.toString(),balance:tr,gasReserveWei:fe.toString(),spendableWei:W.toString(),spendable:Ht,spendableUsd:Le,quickRates:aa,minProvideUsd:this.minProvideUsd,warning:ze,warningMessage:ze==="no_balance"?`You have no ${J.symbol} on ${y.name}. Top up to add liquidity.`:ze==="insufficient_balance"?`Spendable ${J.symbol} is below the $${this.minProvideUsd} minimum.`:null,prefillAmount:at,prefillAmountWei:Lt},Cc=this.computePrefillRange({explicitMinPrice:g,explicitMaxPrice:b,rangeStrategy:h,currentPrice:V.currentPrice,currentTick:V.currentTick,tickSpacing:V.tickSpacing,token0Decimals:Ye,token1Decimals:Vt,priceBounds:Ge}),Up={component:"AddLiquidityForm",props:{chain:{hexId:o,name:y.name},pool:{address:V.poolAddress,fee:V.fee,feePercent:V.fee/1e4,tickSpacing:V.tickSpacing,currentTick:V.currentTick,currentPrice:Se(V.currentPrice),sqrtPriceX96:V.sqrtPriceX96.toString(),token0:{address:V.token0,symbol:Pn?.symbol,name:Pn?.name,logo:Pn?.logo},token1:{address:V.token1,symbol:Sn?.symbol,name:Sn?.name,logo:Sn?.logo}},inputToken:xc,priceBounds:Ge,prefillRange:Cc,gatewayAddress:k}},Dp=this.orientRangesToForm(await we,V.currentPrice,Pn?.symbol,Sn?.symbol);return{ui:Up,suggestedRanges:Dp,summary:this.buildSummary({chainName:y.name,pair:`${Pn?.symbol??s}/${Sn?.symbol??a}`,feePercent:V.fee/1e4,warning:ze,minProvideUsd:this.minProvideUsd,nativeSymbol:J.symbol}),_instructions:'The add-liquidity action is ready. In the user\'s language, invite them to enter the amount and price range to add liquidity, naming the pool + chain (e.g. "Enter the amount and price range to add liquidity to <pool> on <chain>"). Speak ONLY of the user\'s action (adding liquidity). NEVER say you "opened a form", "opened" anything, or describe any screen/form/window/UI being shown \u2014 phrase it as the next step the user takes, not as something you did. If warning="no_balance" tell them they need to top up. If warning="insufficient_balance" tell them the balance is below the minimum. REFERENCE RANGES: when `suggestedRanges` is a non-empty array, briefly offer 1\u20133 of them (highest `apr` first) as price ranges the user can REFERENCE when filling in their range \u2014 for each give the min\u2013max (`minPrice`\u2013`maxPrice`) and its `apr` \u2014 omitting the APR for any entry whose `apr` is absent (never "APR 0%", "N/A" or a dash). These prices are ALREADY in the SAME unit the form shows (`quoteSymbol` per `baseSymbol`), so quote them as-is \u2014 do NOT invert them. CRITICAL: that `apr` is the yield for THAT specific range ONLY \u2014 NEVER present it as the overall pool APR; narrower = higher out-of-range risk. These are only in-range suggestions to reference \u2014 the user still chooses their own range. When `suggestedRanges` is empty or absent, omit this entirely. '+Y+"Do NOT mention balance amounts, deBridge, native coin mechanics, UI, forms, data sources, or internal tool names. Wait for the user to fill in amount + price range before proceeding."}}async fetchPriceRanges(e,t,r,o){try{if(!this.coinPool.isSupported(e))return[];let s=await this.coinPool.getByAddress({chain:e,poolAddress:t});return s.length===0&&r&&o&&(s=await this.coinPool.getPairs({chain:e,tokens:[r,o]})),s.sort((a,i)=>(i.apr??-1/0)-(a.apr??-1/0)).slice(0,10)}catch{return[]}}orientRangesToForm(e,t,r,o){let s=a=>Number.isFinite(a)&&a>0;return s(t)?e.map(a=>{let{minPrice:i,maxPrice:l,currentPrice:c}=a.priceRange,d=i,u=l,p=c;if(s(c)){let m=Math.abs(Math.log(c/t));Math.abs(Math.log(c*t))<m&&(d=s(l)?1/l:0,u=s(i)?1/i:0,p=1/c)}return{fee:a.fee,apr:$(a.apr),minPrice:Se(d),maxPrice:Se(u),currentPrice:Se(p),baseSymbol:r,quoteSymbol:o}}).filter(a=>s(a.minPrice)&&s(a.maxPrice)):[]}unsupportedVersionResult(e,t,r,o){let s=e.protocolVersion??"V4";return{error:"unsupported_protocol_version",protocolVersion:s,pair:`${e.token0?.symbol??t}/${e.token1?.symbol??r}`,chain:o,_instructions:`This is a Uniswap ${s} pool, and adding liquidity currently works only for V3 pools. Tell the user \u2014 in their language \u2014 that the pool they picked does exist but that adding liquidity to ${s} pools is not supported yet, only V3 pools are. Suggest they pick a V3 pool for this pair instead (one may well exist). Keep it short and friendly. Do NOT say the pool was not found, and do NOT mention tools, services, APIs, forms, or any internals.`}}async findUnsupportedVersionPool(e,t,r,o,s){try{let a=await this.resolver.resolveCandidates({chain:e,token0Symbol:t,token1Symbol:r,protocolVersion:"ALL"});if(a===null)return;let i=a.filter(l=>l.protocolVersion&&l.protocolVersion!=="V3");return i.length===0?void 0:s?i.find(l=>typeof l.id=="string"&&l.id.toLowerCase()===s):i.find(l=>this.matchesPairExact(l,t,r,o))??i.find(l=>this.matchesPair(l,t,r,o))}catch{return}}matchesPairExact(e,t,r,o){if(!o||o!=null&&e.feeTier!==o)return!1;let s=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=r.toLowerCase();return s===i&&a===l||s===l&&a===i}matchesPair(e,t,r,o){if(o!=null&&e.feeTier!==o)return!1;let s=(e.token0?.symbol??"").toLowerCase(),a=(e.token1?.symbol??"").toLowerCase(),i=t.toLowerCase(),l=r.toLowerCase(),c=this.symMatch(s,i)&&this.symMatch(a,l),d=this.symMatch(s,l)&&this.symMatch(a,i);return c||d}symMatch(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}parseRangeStrategy(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="stable"||t==="wide"||t==="full"?t:null}computePrefillRange(e){let{explicitMinPrice:t,explicitMaxPrice:r,rangeStrategy:o,currentPrice:s,priceBounds:a}=e;if(t!=null&&r!=null&&r>t){let{minPrice:i,maxPrice:l}=ko(t,r,s);return{strategy:"user",minPrice:Math.max(i,a.min),maxPrice:Math.min(l,a.max)}}if(o==="full")return{strategy:"full",minPrice:a.min,maxPrice:a.max};if(o==="stable"||o==="wide"){let l=cc({currentTick:e.currentTick,tickSpacing:e.tickSpacing,token0Decimals:e.token0Decimals,token1Decimals:e.token1Decimals}).find(c=>c.id===o);if(l)return{strategy:o,minPrice:l.minPrice,maxPrice:l.maxPrice}}return null}buildSummary(e){let t=[`Ready to add liquidity to the ${e.pair} ${e.feePercent}% pool on ${e.chainName}. Enter an amount and a price range to continue.`];return e.warning==="no_balance"?t.push(`You'll need some ${e.nativeSymbol} on ${e.chainName} first \u2014 top up to continue.`):e.warning==="insufficient_balance"&&t.push(`Your spendable ${e.nativeSymbol} is below the $${e.minProvideUsd} minimum \u2014 top up before continuing.`),t.join(" ")}};var ky=/^0x[a-fA-F0-9]{40}$/,Qn=class extends A{name="pool-preview-add-liquidity";kind="action";category="pool-action";description='Preview the add-liquidity transaction. Call this whenever a concrete pool ADDRESS, a native amount, and BOTH min and max price (in token1 per token0) are known \u2014 whether the user filled the AddLiquidityForm OR stated all of them directly in chat (e.g. "add to USDC/WETH with 0.01 ETH, range 0.0005-0.0007, pool=0x\u2026"). Do NOT require the form to have been opened first. The tool converts prices \u2192 ticks (rounded to tickSpacing), fetches deBridge swap quotes for both legs, encodes the gateway.mint call, and returns an unsigned tx the FE will sign. REQUIRES the exact poolAddress (from open-add-liquidity-form props.pool.address or given by the user) \u2014 if only token symbols / a fee tier are known, resolve the pool via open-add-liquidity-form first.';parameters=[{name:"poolAddress",type:"string",description:"V3 pool contract address (returned by open-add-liquidity-form in props.pool.address).",required:!0},{name:"chain",type:"string",description:`Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea .Must match the pool's chain. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.`,required:!1},{name:"minPrice",type:"number",description:`Lower bound of the position price range, in token1-per-token0 units (decimal-adjusted \u2014 the SAME unit as pool.currentPrice from open-add-liquidity-form). Example: if currentPrice is 1800 (USDC per WETH), minPrice 900 means "the position is in-range while WETH \u2265 900 USDC". Must be >= 0 and < maxPrice. Pass 0 for a "full-range lower" position (the range extends down to price 0, i.e. Uniswap's MIN_TICK). CRITICAL: copy the number the user gave VERBATIM \u2014 every digit and every leading zero. Do NOT add or drop a zero, round, or rescale it. Tiny decimals like 0.000533 are easy to mis-transcribe (0.000533 must stay 0.000533, NEVER 0.0000533). If unsure, prefer the user's exact characters over your own reformatting.`,required:!0},{name:"maxPrice",type:"number",description:`Upper bound of the position price range, in the same units as minPrice. Must be > minPrice. Pass a very large number (or props.priceBounds.max) for a "full range upper" position. CRITICAL: copy the user's number VERBATIM \u2014 every digit and leading zero; never add/drop a zero, round, or rescale.`,required:!0},{name:"nativeAmount",type:"number",description:"Native amount the user wants to spend, as a human-readable decimal number (e.g. 0.1 for 0.1 ETH). The tool converts to wei internally.",required:!0},{name:"slippageBps",type:"number",description:"Slippage tolerance in basis points (100 = 1%). Optional \u2014 defaults to 100.",required:!1}];pool;defaultSlippageBps;mintMinPercent;pantograph;constructor(e){super(),this.pool=new ie(e?.pool),this.defaultSlippageBps=e?.defaultSlippageBps??"auto",this.mintMinPercent=e?.mintMinPercent??80,this.pantograph=new Ae}async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:r,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),a}catch(s){return{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let r=typeof e.poolAddress=="string"?e.poolAddress.trim():"",o=await te(vn(this.pool),e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=Number(e.minPrice),i=Number(e.maxPrice),l=typeof e.nativeAmount=="number"&&Number.isFinite(e.nativeAmount)?e.nativeAmount:NaN,c=typeof e.slippageBps=="number"&&Number.isFinite(e.slippageBps)&&String(e.slippageBps)!=="auto"?Math.floor(e.slippageBps)/100:String(this.defaultSlippageBps);if(!r||!s||!Number.isFinite(l)||!Number.isFinite(a)||!Number.isFinite(i))return{error:"missing_inputs",_instructions:"poolAddress, chain, minPrice, maxPrice, nativeAmount are all required."};if(!ky.test(r))return{error:"invalid_pool_address",_instructions:"poolAddress is not a valid EVM address. Re-open the add-liquidity form to get the correct pool address."};if(a<0||i<=0||a>=i)return{error:"invalid_price_range",_instructions:"minPrice must be >= 0 (0 = full-range lower), maxPrice must be > 0, and minPrice must be strictly less than maxPrice."};if(l<=0)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let d=mt(s);if(!d)return{error:"unsupported_chain",chain:s};let u=await this.pool.getGatewayAddress(s);if(!u)return{error:"no_gateway_configured",chain:s};let p=t?.walletAddress;if(!p)return{error:"wallet_not_connected"};let m=Ro(s),f=BigInt(Math.floor(l*10**m.decimals));if(f<=0n)return{error:"invalid_native_amount",_instructions:"nativeAmount must be > 0."};let h=await this.pool.readPoolOnchain(s,r),[g,b]=await Promise.all([this.pool.readErc20Decimals(s,h.token0),this.pool.readErc20Decimals(s,h.token1)]),{minPrice:y,maxPrice:w}=ko(a,i,h.currentPrice),k=y===0?yn:jn(y,g,b),v=jn(w,g,b),S=y===0?Rt(Ct(yn,h.tickSpacing,"up")):Rt(Ct(k,h.tickSpacing,"down")),P=Rt(Ct(v,h.tickSpacing,"up"));if(S>=P||S<yn||P>wo)return{error:"invalid_range_after_alignment",_instructions:"After aligning to tickSpacing the range collapsed. Ask the user for a wider price range.",rawTickLower:k,rawTickUpper:v,tickLower:S,tickUpper:P};let x={tickLower:S,tickUpper:P,minPrice:Se(pt(S,g,b)),maxPrice:Se(pt(P,g,b))},U=h.currentTick;if(U<S||U>=P){let Z=U<S?"below":"above";return{error:"out_of_range",_instructions:`The chosen price range does NOT include the pool's current price, so this would be an OUT-OF-RANGE position (it would sit entirely in one token and earn no fees until the price moves back into the range). The current price is ${Z==="below"?"BELOW":"ABOVE"} the chosen range. Tell the user (in their language) that their range is out of range, show the current price and their chosen min/max, and ask them to pick a range that brackets the current price. Do NOT proceed with the transaction. Do NOT mention tool names.`,currentPrice:Se(h.currentPrice),requestedRange:{minPrice:x.minPrice,maxPrice:x.maxPrice},side:Z}}let[E,we,V]=await Promise.all([this.pool.getNativeBalance(s,p),this.pool.estimateGasReserveWei(s),this.pool.getNativePriceUsd(s)]),z=f+we;if(E<z)return{error:"insufficient_balance",_instructions:"User does not have enough native coin (amount + gas reserve). Tell them the shortfall in their language.",balanceWei:E.toString(),requiredWei:z.toString(),gasReserveWei:we.toString()};let fe=this.pool.splitNativeAmountForRange({nativeAmountWei:f,pool:h,tickLower:S,tickUpper:P,token0Decimals:g,token1Decimals:b}),Ne=h.token0.toLowerCase()===ue,W=h.token1.toLowerCase()===ue,J=[];if(Ne||fe.amountInFor0Wei===0n)J.push({tokenIn:ue,tokenOut:h.token0,amountIn:fe.amountInFor0Wei,tx:{to:ue,data:"0x",value:"0"},minAmountOut:Ne?fe.amountInFor0Wei:0n});else{let Z=await this.pool.fetchSwapLeg({senderAddress:p,chainId:s,tokenIn:ue,tokenInAmount:fe.amountInFor0Wei.toString(),tokenOut:h.token0,tokenOutRecipient:u,slippage:typeof c=="number"?c:"auto"});J.push({tokenIn:ue,tokenOut:h.token0,amountIn:fe.amountInFor0Wei,tx:{to:Z.to,data:Z.data,value:Z.value},minAmountOut:BigInt(Z.minAmountOut||"0")})}if(W||fe.amountInFor1Wei===0n)J.push({tokenIn:ue,tokenOut:h.token1,amountIn:fe.amountInFor1Wei,tx:{to:ue,data:"0x",value:"0"},minAmountOut:W?fe.amountInFor1Wei:0n});else{let Z=await this.pool.fetchSwapLeg({senderAddress:p,chainId:s,tokenIn:ue,tokenInAmount:fe.amountInFor1Wei.toString(),tokenOut:h.token1,tokenOutRecipient:u,slippage:typeof c=="number"?c:"auto"});J.push({tokenIn:ue,tokenOut:h.token1,amountIn:fe.amountInFor1Wei,tx:{to:Z.to,data:Z.data,value:Z.value},minAmountOut:BigInt(Z.minAmountOut||"0")})}let Ht=Z=>Z*BigInt(this.mintMinPercent)/100n,tr=Ht(J[0].minAmountOut),Le=Ht(J[1].minAmountOut),Ye=J.map(Z=>({tokenIn:Z.tokenIn,tokenInAmount:BigInt(Z.amountIn),tokenOut:Z.tokenOut,tokenOutAmount:BigInt(Z.minAmountOut)})),Vt=J.map(Z=>({to:Z.tx.to,data:Z.tx.data,value:BigInt(Z.tx.value||"0")})),Ge=M({abi:Ml,functionName:"mint",args:[Ye,Vt,{fee:Number(h.fee),amount0Min:BigInt(tr),amount1Min:BigInt(Le),tickLower:S,tickUpper:P}]}),ze=l,Pn={chainId:s,to:u,data:Ge,value:f.toString(),from:p},Sn={nativeIn:ze,nativeSymbol:m.symbol,nativeInUsd:V!=null?ze*V:null,ratio:{token0Percent:fe.ratio0,token1Percent:fe.ratio1},expectedToken0:Number(J[0].minAmountOut)/10**g,expectedToken1:Number(J[1].minAmountOut)/10**b,amount0Min:tr.toString(),amount1Min:Le.toString(),slippageBps:c},aa=await this.pantograph.getTokensMetadata([h.token0,h.token1],s),Lt=aa[h.token0],at=aa[h.token1];return{ui:{component:"ConfirmAddLiquidityTx",props:{chain:{hexId:s,name:d.name},unsignedTx:Pn,summary:Sn,pool:{...h,feePercent:h.fee/1e4,currentPrice:Se(h.currentPrice),token0:{address:h.token0,symbol:Lt?.auditGoplus?.token_symbol||Lt.symbol,name:Lt.name,decimals:Lt.decimals,logo:Lt.icon_image},token1:{address:h.token1,symbol:at?.auditGoplus?.token_symbol||at.symbol,name:at.name,decimals:at.decimals,logo:at.icon_image}},range:x,gatewayAddress:u}},summary:`Ready to add ${ze} ${m.symbol} to pool ${h.token0}/${h.token1} ${h.fee/1e4}% on ${d.name}, range [${x.minPrice}, ${x.maxPrice}].`,_instructions:"A confirmation panel has been opened on the FE; the user will sign and broadcast the unsigned tx with their wallet. Briefly tell them (in their language) what is about to happen \u2014 the native amount, the auto-split ratio between the two pool tokens, and the chosen price range. Do NOT mention internal tool/component names."}}};var vy=365,Ty=1e3,Ay=/^0x[a-fA-F0-9]{40}$/;function Py(n,e){return{depositUsd:n,aprPercent:e*100,dailyUsd:n*e/vy,weeklyUsd:n*e/52,monthlyUsd:n*e/12,yearlyUsd:n*e}}var Io=class extends A{name="uniswap-estimate-pool-yield";description=`Estimate daily / weekly / monthly / yearly fee yield for a USD deposit into a Uniswap V3 pool. Answers questions like: "If I put $1000 into the USDC/WETH 0.05% pool, how much per day?", "b\u1ECF 500$ v\xE0o pool ETH/USDC 0.3% m\u1ED7i ng\xE0y l\u1EDDi bao nhi\xEAu?", "APR of WBTC/ETH 0.3% on Arbitrum". BEHAVIOR (designed to minimize back-and-forth with the user):
203
203
  \u2022 If only ONE token symbol is given \u2192 auto-pick the highest-volume V3 pool containing that token and compute yield. Do NOT ask the user for the other token.
204
204
  \u2022 If BOTH tokens are given but fee tier is missing AND multiple fee tiers exist \u2192 return candidates (one per fee tier) so the agent can ask the user to pick.
205
205
  \u2022 If depositUsd is missing \u2192 default to $1000 and clearly mark the result as a per-$1000 example. Do NOT ask the user for the deposit amount.
206
206
  \u2022 If chain is missing \u2192 default to userContext.chain or "0x1" (Ethereum).
207
- Source: Uniswap Explore (live 24h data). Supports: `+Oe();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:'Symbol of one of the pool tokens (e.g. "USDC"). Pair order does not matter.',required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Optional \u2014 if omitted, the tool auto-picks the highest-volume pool containing token0Symbol.',required:!1},{name:"feeTier",type:"number",description:'Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. ONLY set this when the user EXPLICITLY mentions a fee tier (in the current message OR earlier in the conversation, e.g. "ETH/USDC 0.3%" \u2192 feeTier=3000). NEVER guess or infer one. When the user has not mentioned a fee tier and the pair has multiple fee tiers, OMIT it \u2014 the tool then returns candidates.',required:!1},{name:"depositUsd",type:"number",description:"USD amount to deposit. Optional \u2014 defaults to 1000 and the response is marked as a per-$1000 example.",required:!1},{name:"chain",type:"string",description:nt,required:!1}];service;constructor(e){super(),this.service=new $e(e)}async run(e,t){let r=await te(rt(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",a=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,l=typeof e.depositUsd=="number"&&Number.isFinite(e.depositUsd)&&e.depositUsd>0,c=l?e.depositUsd:Ty;if(!s)return{error:"token0Symbol is required. Ask the user which pool / token they want to estimate yield for."};let d=a?`${s} ${a}`:s,u=await this.service.searchPools({query:d,chain:o,page:1,size:50,protocolVersion:"V3"});if(!u.success)return{error:u.error||"Pool search failed"};let p=u.data??[],m=this.filterPools(p,s,a,i);if(m.length===0)return{error:`No V3 pool found for ${this.describeQuery(s,a,i)} on ${T(o)}. Verify the token symbols with the user.`};let f=this.rankByVolume(m);if(a&&i==null&&new Set(f.map(P=>P.feeTier).filter(P=>typeof P=="number")).size>1){let P=this.dedupeByFeeTier(f).slice(0,5);return{_instructions:"The pair has multiple fee tiers. Present them as a short numbered list (fee tier %, 24h volume). Ask which fee tier the user wants, then re-call with the same token symbols + chosen feeTier. If the user already mentioned a deposit amount, pass it along as depositUsd. Do NOT mention tool names. Format numbers human-readably (e.g. $12.5M, 0.05%).",reason:`${s}/${a} exists across multiple fee tiers \u2014 user choice required.`,missing:["feeTier"],candidates:P.map(x=>({pair:x.token0?.symbol&&x.token1?.symbol?`${x.token0.symbol}/${x.token1.symbol}`:void 0,feeTierBps:x.feeTier,feeTierPercent:typeof x.feeTier=="number"?x.feeTier/1e4:void 0,volume24hUsd:x.volumeUsd24hr,address:x.id}))}}let h=f[0];if(!h.id||!Ay.test(h.id))return{error:"Resolved pool has no valid address."};let g=await this.service.getPoolDetailEnriched({addressOrId:h.id,chain:o,enrich:!1});if(!g.success||!g.data)return{error:g.error||"Failed to fetch pool detail."};let b=zn(g.data),y=typeof b.aprPercent=="number"?b.aprPercent/100:void 0,w={address:b.address,pair:b.token0?.symbol&&b.token1?.symbol?`${b.token0.symbol}/${b.token1.symbol}`:void 0,feeTierBps:b.feeTierBps,feeTierPercent:b.feeTierPercent,tvlUsd:b.tvlUsd,volume24hUsd:b.volume24hUsd,fees24hUsd:b.fees24hUsd,lpFeeShare:b.lpFeeShare,volumeToTvlRatio:b.volumeToTvlRatio,aprPercent:b.aprPercent,chain:o,token0:b.token0?{symbol:b.token0.symbol}:void 0,token1:b.token1?{symbol:b.token1.symbol}:void 0},k=a?void 0:`User only provided ${s}; auto-picked the highest-volume V3 pool containing it.`;if(y==null)return{_instructions:"Pool APR could not be computed (TVL or volume data unavailable). Inform the user briefly and show TVL/volume if present. Do NOT mention tool names.",pool:w,autoPickedReason:k,aprUnavailableReason:b.tvlUsd?b.isDynamicFee?"This pool's fee is set per swap by a hook, so it has no fixed rate to project a yield from":"Volume data unavailable":"TVL is zero or unavailable"};let v=Py(c,y);return{_instructions:me+"Present the yield estimate naturally in the user's language. "+(l?"Lead with: pool (pair + fee %), chain, APR %. Then show projected earnings for the user's deposit \u2014 daily, weekly, monthly, yearly. ":'IMPORTANT: depositUsd was NOT specified by the user \u2014 the result is a per-$1000 EXAMPLE. Lead with: pool (pair + fee %), chain, APR %. Then say "for every $1000 deposited you would earn approximately:" and list daily / weekly / monthly / yearly. End with a short note that the user can multiply these numbers by (their deposit / 1000) for a custom amount. ')+(k?'Mention briefly that you picked the highest-volume pool for this token (do NOT say "auto-picked"). ':"")+"After the numbers, add a SHORT expert read of whether this pool is actually worth the deposit. "+he+be+Y+"Format USD numbers with 2 decimal places (e.g. $3.45/day). Do NOT mention tool names.",pool:w,estimate:v,depositMode:l?"user-specified":"default-1000-example",autoPickedReason:k,disclaimer:"Fee yield is based on the pool's 24h volume snapshot and assumes full-range liquidity. Actual returns vary with price movement, volume changes, and impermanent loss."}}filterPools(e,t,r,o){let s=t.toLowerCase(),a=r?r.toLowerCase():"";return e.filter(i=>{if(o!=null&&i.feeTier!==o)return!1;let l=(i.token0?.symbol??"").toLowerCase(),c=(i.token1?.symbol??"").toLowerCase();return a?this.sym(l,s)&&this.sym(c,a)||this.sym(l,a)&&this.sym(c,s):this.sym(l,s)||this.sym(c,s)})}sym(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}rankByVolume(e){return[...e].sort((t,r)=>(r.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}dedupeByFeeTier(e){let t=new Set,r=[];for(let o of e)typeof o.feeTier=="number"&&(t.has(o.feeTier)||(t.add(o.feeTier),r.push(o)));return r}describeQuery(e,t,r){let o=t?`${e}/${t}`:e;return r!=null?`${o} at ${r} bps`:o}};var Jn=class extends A{name="pool-price-ranges";description='List CoinPool concentrated-liquidity price-range candidates for a token pair on a given EVM chain. Each entry shows: pair, fee tier, min/max price range, current price, and the APR earned WITHIN that range (strictly per-range \u2014 NOT the overall pool APR). Use ONLY for questions about price ranges or which range to pick: "what price range should I use for ETH/USDC?", "best range for USDC/WETH on Arbitrum", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC". Do NOT use for general "show me ETH/USDC pools" \u2014 use get-pool-detail or search-pools for that. Source: CoinPool. Supports: '+Oe()+".";category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:'Two token symbols (e.g. ["ETH","USDC"]).',required:!0},{name:"chain",type:"string",description:nt,required:!1},{name:"limit",type:"number",description:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}];service;scope;constructor(e){if(super(),this.service=new Tn(e),this.scope=e?.scope??rt(),e?.supportsLabel){let t=Oe();if(!this.description.includes(t))throw new Error("PoolPriceRangesTool: description no longer contains the default supported-chain label; update the description or the label so `supportsLabel` can override it.");this.description=this.description.replace(t,e.supportsLabel)}if(e?.chainParamDescription){let t=this.parameters.find(r=>r.name==="chain");t&&(t.description=e.chainParamDescription)}}async run(e,t){let r=(Array.isArray(e.tokens)?e.tokens:[]).filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim().toUpperCase());if(r.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let o=await te(this.scope,e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,i=await this.service.getPairs({chain:s,tokens:r});if(i.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and offer the pool's overall stats instead (via get-pool-detail).",tokens:r,chain:s,pairs:[],count:0};let l=[...i].sort((c,d)=>(d.apr??-1/0)-(c.apr??-1/0)).slice(0,a);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". When an entry has no `apr` (null/absent) there is no yield reading for it: omit the APR part entirely for that entry \u2014 never write "APR 0%", "N/A" or a dash. Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk. '+Y+"Do NOT mention tool or API names.",tokens:r,chain:s,count:l.length,pairs:l}}};var ap="https://coinpool.app/my-liquidity",Zn=class extends A{name="pool-manage-liquidity-redirect";description='Use when the user wants to MANAGE an EXISTING liquidity position rather than open a new one \u2014 specifically: collecting / claiming earned fees or rewards ("collect earnings", "claim my fees", "thu ph\xED", "r\xFAt l\xE3i"), or closing / removing / withdrawing a position ("close the pair", "close my position", "remove liquidity", "withdraw liquidity", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n", "\u0111\xF3ng c\u1EB7p"). This tool does NOT perform the action \u2014 it returns a link to the CoinPool management page where the user does it themselves. Do NOT use this for ADDING liquidity (use the add-liquidity form) or for pool data/analysis questions.';category="pool-action";parameters=[{name:"action",type:"string",description:'What the user wants to do \u2014 one of: "collect" (collect/claim earned fees) or "close" (close/remove the position). Optional \u2014 used only to tailor the wording. Omit if unclear.',required:!1}];async run(e){let t=e.action==="collect"||e.action==="close"?e.action:void 0;return{_instructions:`Managing an existing position is not available in-app yet. Tell the user (in their language) that to ${t==="collect"?"collect their earned fees":t==="close"?"close / remove their position":"manage their existing position (collect earnings or close the pair)"}, they need to visit the CoinPool management page and do it there. Give them the link as plain text: ${ap} \u2014 write the URL exactly, do NOT shorten it or wrap it in markdown. Keep it short and friendly. Do NOT mention tool names.`,url:ap,action:t}}};var Sy=["tvl","volume","apr","fee","liquidity"],Uo=class extends A{name="subgraph-search-pools";description='Search Uniswap V3 liquidity pools via The Graph subgraphs by token symbol(s) on one or more chains. Use for: "find ETH/USDC pools on Base", "show OP pools", "stablecoin pools on Arbitrum", "best USDC pool". Returns pools with pair, TVL, volume past day, fee tier (%), APR (DefiLlama-enriched), and liquidity rank. When exactly two tokens are given, also returns CoinPool concentrated-liquidity price-range candidates (per-range APR) for that pair. Supports TVL/APR/fee filters and sort by tvl, volume, apr, fee, or liquidity. Supported chains: Ethereum (0x1), Arbitrum (0xa4b1), Polygon (0x89), BSC (0x38), Base (0x2105), Optimism (0xa), Avalanche (0xa86a).';category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:"Token symbols to match. 0 tokens = top pools by chosen sort. 1 token = pools containing it. 2 tokens = pools with that exact pair (both orderings tried). Wrapped variants (WETH\u2194ETH, WBTC\u2194BTC) auto-handled.",required:!1,default:[]},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]},{name:"sortBy",type:"string",description:'Sort key: "tvl" (default), "volume", "apr", "fee" (low-to-high), or "liquidity".',required:!1,default:"tvl"},{name:"minTVL",type:"number",description:"Minimum TVL in USD.",required:!1},{name:"maxTVL",type:"number",description:"Maximum TVL in USD.",required:!1},{name:"minAPR",type:"number",description:"Minimum APR percentage (e.g. 5 for 5%).",required:!1},{name:"maxAPR",type:"number",description:"Maximum APR percentage.",required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100, 500, 3000, or 10000.",required:!1},{name:"limit",type:"number",description:"Max pools to return after sort/filter. Default 5, max 20.",required:!1,default:5}];service;constructor(e){super(),this.service=new xe(e)}async run(e,t){let r=(Array.isArray(e.tokens)?e.tokens:[]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.trim().toUpperCase()),o=(Array.isArray(e.chains)?e.chains:[]).filter(f=>typeof f=="string"&&f.trim().length>0),s=o.filter(f=>!this.service.isSupported(f)),a=o.filter(f=>this.service.isSupported(f)).map(f=>this.service.resolveChain(f));if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],l=typeof e.sortBy=="string"&&Sy.includes(e.sortBy)?e.sortBy:"tvl",c={minTVL:typeof e.minTVL=="number"?e.minTVL:void 0,maxTVL:typeof e.maxTVL=="number"?e.maxTVL:void 0,minAPR:typeof e.minAPR=="number"?e.minAPR:void 0,maxAPR:typeof e.maxAPR=="number"?e.maxAPR:void 0,feeTier:typeof e.feeTier=="number"?e.feeTier:void 0},d=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5;if(o.length>0&&a.length===0)return{_instructions:"The user requested chains we do not support via The Graph subgraph. Politely list the unsupported chains and the supported chains. Do not show any pool data.",unsupportedChains:s.map(T),supportedChains:this.service.listSupportedChains().map(T),pools:[],count:0};let p=(await Promise.allSettled(i.map(f=>this.service.searchPools({tokens:r,chain:f,sortBy:l,filters:c})))).flatMap(f=>f.status==="fulfilled"?f.value:[]);l==="apr"?p.sort((f,h)=>(h.apr??0)-(f.apr??0)):l==="tvl"?p.sort((f,h)=>h.tvl-f.tvl):l==="volume"?p.sort((f,h)=>h.volume24hUsd-f.volume24hUsd):l==="fee"&&p.sort((f,h)=>f.feeTierBps-h.feeTierBps),p=p.slice(0,d);let m=[];return r.length===2&&(m=(await Promise.allSettled(i.map(h=>this.service.getCoinPoolPairs({chain:h,tokens:r})))).flatMap((h,g)=>h.status==="fulfilled"?h.value.map(b=>({...b,chain:T(i[g])})):[]),m.sort((h,g)=>(g.apr??-1/0)-(h.apr??-1/0)),m=m.slice(0,d)),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). Then list the pools with: pair (e.g. USDC/WETH), fee tier (%), TVL (USD), volume past day (USD), APR (%). Format USD human-readably ($12.5M, $450K). Mention chain and sort metric briefly. If a pool has no APR (null), skip the APR field rather than showing zero. For EACH pool, render the provided uniswapUrl as a clickable markdown link \u2014 e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)". Never omit this link. Do not invent URLs. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: the APR in coinPoolPairs is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the list, add a brief, natural read on the pools \u2014 conversational, like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4CA} Evaluation"); vary your wording each time and only mention what actually stands out in THIS data. Reason ONLY from the numbers shown \u2014 never invent figures. Touch on, as it fits: which pool looks strongest and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; a high volume-to-TVL ratio signals an active, fee-generating pool); whether the fee tier fits the pair (0.05% for stable/correlated, 0.30% for typical volatile, 1% for exotic/low-liquidity); any pool to be cautious about (thin TVL/volume, or an eye-catching APR that is likely volatile/unsustainable rather than a sure thing); and the key risks in a line (APR is variable, high APR usually means higher risk, impermanent loss for LPs on volatile pairs). Keep it short and human \u2014 a sentence or two or a couple of light bullets. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, no stock disclaimer). If unsupportedChains is non-empty, mention them once at the end.',tokens:r,chains:i.map(T),unsupportedChains:s.map(T),sortBy:l,filters:c,count:p.length,pools:p.map(f=>this.formatPool(f)),coinPoolPairs:m}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:je(e)}}};function je(n){return`https://app.uniswap.org/explore/pools/${Ys[n.chain]||n.chain}/${n.poolAddress}`}var Ys={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};var Do=class extends A{name="subgraph-trending-pools";description='List Uniswap V3 pools with the highest volume past day on one or more chains via The Graph subgraphs. Use for: "what are trending pools?", "most active pools", "hot pools right now", "pools with biggest volume today". Returns pair, TVL, volume past day, fee tier (%), APR (DefiLlama-enriched) for each. Supported chains: Ethereum (0x1), Arbitrum (0xa4b1), Polygon (0x89), BSC (0x38), Base (0x2105), Optimism (0xa), Avalanche (0xa86a).';category="blockchain-data";parameters=[{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]},{name:"limit",type:"number",description:"Max pools to return. Default 5, max 20.",required:!1,default:5}];service;constructor(e){super(),this.service=new xe(e)}async run(e,t){let r=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),o=r.filter(d=>!this.service.isSupported(d)),s=r.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(r.length>0&&s.length===0)return{_instructions:"User requested unsupported chains. Politely list them and the supported chains; do not show pool data.",unsupportedChains:o,supportedChains:this.service.listSupportedChains(),pools:[],count:0};if(s.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0);let a=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5,c=(await Promise.allSettled(a.map(d=>this.service.getTrendingPools({chain:d})))).flatMap(d=>d.status==="fulfilled"?d.value:[]);return c.sort((d,u)=>u.volume24hUsd-d.volume24hUsd),c=c.slice(0,i),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). List pools ranked by volume past day. For each: pair, fee %, volume past day, TVL, APR (skip if null). For EACH pool render the provided uniswapUrl as a clickable markdown link (e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)"). Never omit it. Do not invent URLs.',chains:a,unsupportedChains:o,count:c.length,pools:c.map(d=>({pair:d.pair,poolAddress:d.poolAddress,chain:d.chain,feeTierBps:d.feeTierBps,feeTierPercent:d.feeTierPercent,tvlUsd:d.tvl,volumePastDayUsd:d.volume24hUsd,fees24hUsd:d.fees24hUsd,apr:d.apr,token0:d.token0,token1:d.token1,uniswapUrl:je(d)}))}}};var Oo=class extends A{name="subgraph-pool-by-address";description='Fetch full pool detail AND an evaluation for a specific Uniswap V3 pool by its on-chain address via The Graph subgraphs. Returns Uniswap fundamentals (pair, fee tier, TVL, volume past day + fees, APR, token addresses) enriched with CoinPool concentrated-liquidity price-range candidates (per-range APR + min/max/current price), then a genuine assessment of the pool. Use whenever the user pastes a 0x pool address \u2014 both for plain detail ("tell me about pool 0xabc\u2026", "details of this pool 0x\u2026") and for an opinion ("\u0111\xE1nh gi\xE1 pool 0x\u2026", "rate/evaluate this pool 0x\u2026", "is pool 0x\u2026 good?", "pool n\xE0y c\xF3 t\u1ED1t kh\xF4ng").';category="blockchain-data";parameters=[{name:"poolAddress",type:"string",description:"0x-prefixed Uniswap V3 pool contract address (40 hex chars).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1}];service;constructor(e){super(),this.service=new xe(e)}async run(e,t){let r=typeof e.poolAddress=="string"?e.poolAddress.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(r))return{error:"This only supports Uniswap V3 pools. Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address)."};let o=typeof e.chain=="string"&&e.chain.trim();if(!o&&!t?.chain&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0);let s=o?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(s))return{_instructions:"The requested chain is not supported by the Subgraph pool service. List the supported chains briefly.",unsupportedChains:[s],supportedChains:this.service.listSupportedChains()};let a=this.service.resolveChain(s),[i,l]=await Promise.all([this.service.getPoolByAddress({poolAddress:r,chain:a}),this.service.getCoinPoolByAddress({chain:a,poolAddress:r}).catch(()=>[])]);return i?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3,'+(l.length>0?" enriched with CoinPool range data,":"")+'" (translate naturally; keep "Subgraph" and "CoinPool" as-is). First show the pool snapshot: pair, fee tier (%), TVL, volume past day, 24h fees, APR (skip if null), and the pool address. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: a range APR is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Then give a genuine evaluation of THIS pool \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading; vary the wording each time and only cover what is actually relevant to this pool and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: liquidity depth & activity (higher TVL + volume past day = deeper liquidity, more fees, less slippage; thin TVL/volume is a red flag); fee-tier fit (0.05% suits stable/correlated pairs, 0.30% typical volatile pairs, 1% exotic/low-liquidity ones \u2014 flag a mismatch); whether the APR looks attractive vs. how sustainable it is (fee-driven and steady vs. thin-TVL spikes that can vanish); if coinPoolPairs is present, which price range makes sense \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Close with a short, natural overall take (e.g. solid / decent-with-caveats / risky) and a brief nudge that it is informational, not financial advice \u2014 phrase it differently each time, do not paste a stock disclaimer. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs. Do NOT mention tool names, UI, or forms.',chain:a,coinPoolPairs:l,pool:{pair:i.pair,poolAddress:i.poolAddress,chain:i.chain,feeTierBps:i.feeTierBps,feeTierPercent:i.feeTierPercent,tvlUsd:i.tvl,volumePastDayUsd:i.volume24hUsd,fees24hUsd:i.fees24hUsd,apr:i.apr,token0:i.token0,token1:i.token1,uniswapUrl:je(i)}}:{error:`No pool found at ${r} on ${T(a)}.`}}};var Mo=class extends A{name="subgraph-pool-by-position-id";description='Return the pool underlying a Uniswap V3 NFT position id. Use when the user wants the pool stats for a numeric id WITHOUT the deposit/withdraw/fee history (e.g. "which pool is position 962961 in?", "show the pool of id 12345"). For full position history use subgraph-position-detail instead.';category="blockchain-data";parameters=[{name:"positionId",type:"string",description:"Numeric Uniswap V3 NFT position id as a string.",required:!0},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]}];service;constructor(e){super(),this.service=new xe(e)}async run(e,t){let r=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(r))return{error:"positionId must be a numeric string."};let o=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),s=o.filter(d=>!this.service.isSupported(d)),a=o.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(o.length>0&&a.length===0)return{_instructions:"Requested chains are not supported. List the supported chains.",unsupportedChains:s,supportedChains:this.service.listSupportedChains()};if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(d=>this.service.getPoolByPositionId({positionId:r,chain:d})))).map(d=>d.status==="fulfilled"?d.value:null).find(d=>d!=null);return c?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). Show the pool of that position: pair, fee %, TVL, volume past day, APR (skip the APR entirely when it is null \u2014 never write "APR 0%", "N/A" or a dash). Mention the position id. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs.',positionId:r,pool:{pair:c.pair,poolAddress:c.poolAddress,chain:c.chain,feeTierBps:c.feeTierBps,feeTierPercent:c.feeTierPercent,tvlUsd:c.tvl,volumePastDayUsd:c.volume24hUsd,fees24hUsd:c.fees24hUsd,apr:c.apr,token0:c.token0,token1:c.token1,uniswapUrl:je(c)}}:{_instructions:"No pool found for this position id on the chosen chains. Ask the user to verify the id or chain.",positionId:r,chains:i,found:!1}}};var Fo=class extends A{name="subgraph-position-detail";description=`Look up a Uniswap V3 liquidity position by its numeric NFT id (e.g. 962961) on one or more chains via The Graph subgraphs. Returns the position (deposited/withdrawn token amounts, collected fees, liquidity) AND its underlying pool (pair, fee tier, TVL, volume past day, APR). Use when the user names a numeric id with phrases like: "position 12345", "pool id 962961", "tell me about position 962961". Does NOT support the user's wallet-wide LP list \u2014 only a specific id.`;category="blockchain-data";parameters=[{name:"positionId",type:"string",description:'Numeric Uniswap V3 NFT position id as a string (e.g. "962961").',required:!0},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]}];service;constructor(e){super(),this.service=new xe(e)}async run(e,t){let r=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(r))return{error:"positionId must be a numeric string (Uniswap V3 NFT id)."};let o=(Array.isArray(e.chains)?e.chains:[]).filter(u=>typeof u=="string"&&u.trim().length>0),s=o.filter(u=>!this.service.isSupported(u)),a=o.filter(u=>this.service.isSupported(u)).map(u=>this.service.resolveChain(u));if(o.length>0&&a.length===0)return{_instructions:"User asked about a position on chains we do not support. List unsupported + supported chains.",unsupportedChains:s,supportedChains:this.service.listSupportedChains()};if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0);let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(u=>this.service.getPositionDetail({positionId:r,chain:u})))).map(u=>u.status==="fulfilled"?u.value:null).find(u=>u!=null);if(!c)return{_instructions:"No position with this id was found on the chosen chains. Suggest the user double-check the id or specify another chain.",positionId:r,chains:i,found:!1};let d=Ys[c.position.chain]||c.position.chain;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). Show the pair, chain, fee tier (%), deposited/withdrawn/collected fees for each token, plus pool stats (TVL, volume past day, APR \u2014 skip the APR entirely when it is null, never write "APR 0%", "N/A" or a dash). End the response with TWO clickable markdown links from the data: position.uniswapPositionUrl as "[View position on Uniswap](uniswapPositionUrl)" and pool.uniswapUrl as "[View pool on Uniswap](uniswapUrl)". Never omit them. Do not invent URLs.',positionId:r,position:{...c.position,uniswapPositionUrl:`https://app.uniswap.org/positions/v3/${d}/${c.position.positionId}`},pool:{...c.pool,uniswapUrl:je(c.pool)}}}};var Bo=class extends A{name="subgraph-coinpool-pairs";description='List CoinPool concentrated-liquidity price-range candidates for a token pair on a chain. Each entry shows: pair, fee tier, min/max price range, current price, and APR within that range (NOT the overall pool APR \u2014 strictly per-range). Use ONLY for queries about price ranges or which range to pick: "what price range should I use for ETH/USDC?", "best range for USDC/WETH on Arbitrum", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC". Do NOT use for general "show me ETH/USDC pools" \u2014 use subgraph-search-pools for that.';category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:'Two token symbols (e.g. ["ETH","USDC"]).',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1},{name:"limit",type:"number",description:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new xe(e)}async run(e,t){let r=(Array.isArray(e.tokens)?e.tokens:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim().toUpperCase());if(r.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let o=typeof e.chain=="string"&&e.chain.trim();if(!o&&!t?.chain&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0);let s=o?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(s))return{_instructions:"Requested chain not supported. Mention supported chains.",unsupportedChains:[s],supportedChains:this.service.listSupportedChains()};let a=this.service.resolveChain(s),i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,l=await this.service.getCoinPoolPairs({chain:a,tokens:r});if(l.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and suggest using general pool data instead (via subgraph-search-pools).",tokens:r,chain:a,pairs:[],count:0};let c=[...l].sort((d,u)=>(u.apr??-1/0)-(d.apr??-1/0)).slice(0,i);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". When an entry has no `apr` (null/absent), omit the APR part for that entry \u2014 never write "APR 0%", "N/A" or a dash. Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk.',tokens:r,chain:a,count:c.length,pairs:c}}};var qo=class extends A{name="subgraph-add-pool";description='Open the ADD-LIQUIDITY / ADD-POOL flow for Uniswap V3 via The Graph subgraphs. Use for ANY "provide / add liquidity", "add LP", "add pool", "create pool", "create pair", "farm/deposit into a pool" intent (natural-language verbs in any language map here: "th\xEAm thanh kho\u1EA3n", "th\xEAm pool", "t\u1EA1o pool"). It RESOLVES the pool the user means \u2014 by 0x pool address, or by one/two token symbols (with optional fee tier) \u2014 like the detail/search tools, then points the user to the add-liquidity website. When two token symbols are given, it also surfaces CoinPool concentrated-liquidity price-range candidates (per-range APR) to help pick a range. Pass `poolAddress` when the user gives a 0x pool address; otherwise pass `tokens` (1 or 2 symbols) and optional `feeTier`. Leave both blank when the user named no pool/token \u2014 the tool returns the chain\'s top pools to choose from. It does NOT build a transaction; it surfaces the add-liquidity link.';category="blockchain-data";parameters=[{name:"poolAddress",type:"string",description:"0x-prefixed Uniswap V3 pool contract address (40 hex chars). Pass when the user gives a concrete pool address; otherwise leave blank and pass `tokens`.",required:!1},{name:"tokens",type:"array",items:{type:"string"},description:"Token symbols of the pair to add liquidity to. 1 token = pools containing it; 2 tokens = that exact pair (both orderings tried). Leave EMPTY when the user named no token \u2014 the tool returns top pools to choose from.",required:!1,default:[]},{name:"feeTier",type:"number",description:"Optional fee tier in basis points (100, 500, 3000, or 10000) to disambiguate the pool.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1},{name:"howTo",type:"boolean",description:'Set TRUE when the user asks HOW to add liquidity / how to create a pool or pair / how it works ("how to add pool", "how to add pair", "how do I add liquidity", "c\xE1ch th\xEAm thanh kho\u1EA3n", "l\xE0m sao \u0111\u1EC3 add pool/pair") rather than naming a specific pool to add to ("pool" and "pair" are equivalent here). Returns the general steps + the add-liquidity website link, without needing a pool, token, or connected chain. Leave false/omit for a concrete add-liquidity request.',required:!1}];service;linkAddLiquidity;constructor(e){super(),this.service=new xe(e),this.linkAddLiquidity=e?.linkAddLiquidity?.trim()||void 0}async run(e,t){if(e.howTo===!0){let u=this.linkAddLiquidity??null,p=typeof e.chain=="string"&&e.chain.trim()||t?.chain||"0x1",m="",f=[];if(this.service.isSupported(p)){m=this.service.resolveChain(p);try{f=(await this.service.searchPools({tokens:[],chain:m,sortBy:"tvl"})).slice(0,5)}catch{f=[]}}return{_instructions:`The user is asking HOW to add liquidity / create a pool \u2014 a how-to question, not a request about a specific pool. Reply in the user's language, in THIS exact order:
207
+ Source: Uniswap Explore (live 24h data). Supports: `+Oe();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:'Symbol of one of the pool tokens (e.g. "USDC"). Pair order does not matter.',required:!0},{name:"token1Symbol",type:"string",description:'Symbol of the other pool token (e.g. "WETH"). Optional \u2014 if omitted, the tool auto-picks the highest-volume pool containing token0Symbol.',required:!1},{name:"feeTier",type:"number",description:'Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.30%, 10000 = 1.00%. ONLY set this when the user EXPLICITLY mentions a fee tier (in the current message OR earlier in the conversation, e.g. "ETH/USDC 0.3%" \u2192 feeTier=3000). NEVER guess or infer one. When the user has not mentioned a fee tier and the pair has multiple fee tiers, OMIT it \u2014 the tool then returns candidates.',required:!1},{name:"depositUsd",type:"number",description:"USD amount to deposit. Optional \u2014 defaults to 1000 and the response is marked as a per-$1000 example.",required:!1},{name:"chain",type:"string",description:nt,required:!1}];service;constructor(e){super(),this.service=new $e(e)}async run(e,t){let r=await te(rt(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"",a=typeof e.token1Symbol=="string"?e.token1Symbol.trim():"",i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,l=typeof e.depositUsd=="number"&&Number.isFinite(e.depositUsd)&&e.depositUsd>0,c=l?e.depositUsd:Ty;if(!s)return{error:"token0Symbol is required. Ask the user which pool / token they want to estimate yield for."};let d=a?`${s} ${a}`:s,u=await this.service.searchPools({query:d,chain:o,page:1,size:50,protocolVersion:"V3"});if(!u.success)return{error:u.error||"Pool search failed"};let p=u.data??[],m=this.filterPools(p,s,a,i);if(m.length===0)return{error:`No V3 pool found for ${this.describeQuery(s,a,i)} on ${T(o)}. Verify the token symbols with the user.`};let f=this.rankByVolume(m);if(a&&i==null&&new Set(f.map(P=>P.feeTier).filter(P=>typeof P=="number")).size>1){let P=this.dedupeByFeeTier(f).slice(0,5);return{_instructions:"The pair has multiple fee tiers. Present them as a short numbered list (fee tier %, 24h volume). Ask which fee tier the user wants, then re-call with the same token symbols + chosen feeTier. If the user already mentioned a deposit amount, pass it along as depositUsd. Do NOT mention tool names. Format numbers human-readably (e.g. $12.5M, 0.05%).",reason:`${s}/${a} exists across multiple fee tiers \u2014 user choice required.`,missing:["feeTier"],candidates:P.map(x=>({pair:x.token0?.symbol&&x.token1?.symbol?`${x.token0.symbol}/${x.token1.symbol}`:void 0,feeTierBps:x.feeTier,feeTierPercent:typeof x.feeTier=="number"?x.feeTier/1e4:void 0,volume24hUsd:x.volumeUsd24hr,address:x.id}))}}let h=f[0];if(!h.id||!Ay.test(h.id))return{error:"Resolved pool has no valid address."};let g=await this.service.getPoolDetailEnriched({addressOrId:h.id,chain:o,enrich:!1});if(!g.success||!g.data)return{error:g.error||"Failed to fetch pool detail."};let b=zn(g.data),y=typeof b.aprPercent=="number"?b.aprPercent/100:void 0,w={address:b.address,pair:b.token0?.symbol&&b.token1?.symbol?`${b.token0.symbol}/${b.token1.symbol}`:void 0,feeTierBps:b.feeTierBps,feeTierPercent:b.feeTierPercent,tvlUsd:b.tvlUsd,volume24hUsd:b.volume24hUsd,fees24hUsd:b.fees24hUsd,lpFeeShare:b.lpFeeShare,volumeToTvlRatio:b.volumeToTvlRatio,aprPercent:b.aprPercent,chain:o,token0:b.token0?{symbol:b.token0.symbol}:void 0,token1:b.token1?{symbol:b.token1.symbol}:void 0},k=a?void 0:`User only provided ${s}; auto-picked the highest-volume V3 pool containing it.`;if(y==null)return{_instructions:"Pool APR could not be computed (TVL or volume data unavailable). Inform the user briefly and show TVL/volume if present. Do NOT mention tool names.",pool:w,autoPickedReason:k,aprUnavailableReason:b.tvlUsd?b.isDynamicFee?"This pool's fee is set per swap by a hook, so it has no fixed rate to project a yield from":"Volume data unavailable":"TVL is zero or unavailable"};let v=Py(c,y);return{_instructions:me+"Present the yield estimate naturally in the user's language. "+(l?"Lead with: pool (pair + fee %), chain, APR %. Then show projected earnings for the user's deposit \u2014 daily, weekly, monthly, yearly. ":'IMPORTANT: depositUsd was NOT specified by the user \u2014 the result is a per-$1000 EXAMPLE. Lead with: pool (pair + fee %), chain, APR %. Then say "for every $1000 deposited you would earn approximately:" and list daily / weekly / monthly / yearly. End with a short note that the user can multiply these numbers by (their deposit / 1000) for a custom amount. ')+(k?'Mention briefly that you picked the highest-volume pool for this token (do NOT say "auto-picked"). ':"")+"After the numbers, add a SHORT expert read of whether this pool is actually worth the deposit. "+he+be+Y+"Format USD numbers with 2 decimal places (e.g. $3.45/day). Do NOT mention tool names.",pool:w,estimate:v,depositMode:l?"user-specified":"default-1000-example",autoPickedReason:k,disclaimer:"Fee yield is based on the pool's 24h volume snapshot and assumes full-range liquidity. Actual returns vary with price movement, volume changes, and impermanent loss."}}filterPools(e,t,r,o){let s=t.toLowerCase(),a=r?r.toLowerCase():"";return e.filter(i=>{if(o!=null&&i.feeTier!==o)return!1;let l=(i.token0?.symbol??"").toLowerCase(),c=(i.token1?.symbol??"").toLowerCase();return a?this.sym(l,s)&&this.sym(c,a)||this.sym(l,a)&&this.sym(c,s):this.sym(l,s)||this.sym(c,s)})}sym(e,t){return!e||!t?!1:e.includes(t)||t.includes(e)}rankByVolume(e){return[...e].sort((t,r)=>(r.volumeUsd24hr??0)-(t.volumeUsd24hr??0))}dedupeByFeeTier(e){let t=new Set,r=[];for(let o of e)typeof o.feeTier=="number"&&(t.has(o.feeTier)||(t.add(o.feeTier),r.push(o)));return r}describeQuery(e,t,r){let o=t?`${e}/${t}`:e;return r!=null?`${o} at ${r} bps`:o}};var Jn=class extends A{name="pool-price-ranges";description='List CoinPool concentrated-liquidity price-range candidates for a token pair on a given EVM chain. Each entry shows: pair, fee tier, min/max price range, current price, and the APR earned WITHIN that range (strictly per-range \u2014 NOT the overall pool APR). Use ONLY for questions about price ranges or which range to pick: "what price range should I use for ETH/USDC?", "best range for USDC/WETH on Arbitrum", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC". Do NOT use for general "show me ETH/USDC pools" \u2014 use get-pool-detail or search-pools for that. Source: CoinPool. Supports: '+Oe()+".";category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:'Two token symbols (e.g. ["ETH","USDC"]).',required:!0},{name:"chain",type:"string",description:nt,required:!1},{name:"limit",type:"number",description:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}];service;scope;constructor(e){if(super(),this.service=new Tn(e),this.scope=e?.scope??rt(),e?.supportsLabel){let t=Oe();if(!this.description.includes(t))throw new Error("PoolPriceRangesTool: description no longer contains the default supported-chain label; update the description or the label so `supportsLabel` can override it.");this.description=this.description.replace(t,e.supportsLabel)}if(e?.chainParamDescription){let t=this.parameters.find(r=>r.name==="chain");t&&(t.description=e.chainParamDescription)}}async run(e,t){let r=(Array.isArray(e.tokens)?e.tokens:[]).filter(c=>typeof c=="string"&&c.trim().length>0).map(c=>c.trim().toUpperCase());if(r.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let o=await te(this.scope,e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,i=await this.service.getPairs({chain:s,tokens:r});if(i.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and offer the pool's overall stats instead (via get-pool-detail).",tokens:r,chain:s,pairs:[],count:0};let l=[...i].sort((c,d)=>(d.apr??-1/0)-(c.apr??-1/0)).slice(0,a);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". When an entry has no `apr` (null/absent) there is no yield reading for it: omit the APR part entirely for that entry \u2014 never write "APR 0%", "N/A" or a dash. Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk. '+Y+"Do NOT mention tool or API names.",tokens:r,chain:s,count:l.length,pairs:l}}};var ap="https://coinpool.app/my-liquidity",Zn=class extends A{name="pool-manage-liquidity-redirect";description='Use when the user wants to MANAGE an EXISTING liquidity position rather than open a new one \u2014 specifically: collecting / claiming earned fees or rewards ("collect earnings", "claim my fees", "thu ph\xED", "r\xFAt l\xE3i"), or closing / removing / withdrawing a position ("close the pair", "close my position", "remove liquidity", "withdraw liquidity", "\u0111\xF3ng v\u1ECB th\u1EBF", "r\xFAt thanh kho\u1EA3n", "\u0111\xF3ng c\u1EB7p"). This tool does NOT perform the action \u2014 it returns a link to the CoinPool management page where the user does it themselves. Do NOT use this for ADDING liquidity (use the add-liquidity form) or for pool data/analysis questions.';category="pool-action";parameters=[{name:"action",type:"string",description:'What the user wants to do \u2014 one of: "collect" (collect/claim earned fees) or "close" (close/remove the position). Optional \u2014 used only to tailor the wording. Omit if unclear.',required:!1}];async run(e){let t=e.action==="collect"||e.action==="close"?e.action:void 0;return{_instructions:`Managing an existing position is not available in-app yet. Tell the user (in their language) that to ${t==="collect"?"collect their earned fees":t==="close"?"close / remove their position":"manage their existing position (collect earnings or close the pair)"}, they need to visit the CoinPool management page and do it there. Give them the link as plain text: ${ap} \u2014 write the URL exactly, do NOT shorten it or wrap it in markdown. Keep it short and friendly. Do NOT mention tool names.`,url:ap,action:t}}};var Sy=["tvl","volume","apr","fee","liquidity"],Uo=class extends A{name="subgraph-search-pools";description='Search Uniswap V3 liquidity pools via The Graph subgraphs by token symbol(s) on one or more chains. Use for: "find ETH/USDC pools on Base", "show OP pools", "stablecoin pools on Arbitrum", "best USDC pool". Returns pools with pair, TVL, volume past day, fee tier (%), APR (DefiLlama-enriched), and liquidity rank. When exactly two tokens are given, also returns CoinPool concentrated-liquidity price-range candidates (per-range APR) for that pair. Supports TVL/APR/fee filters and sort by tvl, volume, apr, fee, or liquidity. Supported chains: Ethereum (0x1), Arbitrum (0xa4b1), Polygon (0x89), BSC (0x38), Base (0x2105), Optimism (0xa), Avalanche (0xa86a).';category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:"Token symbols to match. 0 tokens = top pools by chosen sort. 1 token = pools containing it. 2 tokens = pools with that exact pair (both orderings tried). Wrapped variants (WETH\u2194ETH, WBTC\u2194BTC) auto-handled.",required:!1,default:[]},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]},{name:"sortBy",type:"string",description:'Sort key: "tvl" (default), "volume", "apr", "fee" (low-to-high), or "liquidity".',required:!1,default:"tvl"},{name:"minTVL",type:"number",description:"Minimum TVL in USD.",required:!1},{name:"maxTVL",type:"number",description:"Maximum TVL in USD.",required:!1},{name:"minAPR",type:"number",description:"Minimum APR percentage (e.g. 5 for 5%).",required:!1},{name:"maxAPR",type:"number",description:"Maximum APR percentage.",required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100, 500, 3000, or 10000.",required:!1},{name:"limit",type:"number",description:"Max pools to return after sort/filter. Default 5, max 20.",required:!1,default:5}];service;constructor(e){super(),this.service=new xe(e)}async run(e,t){let r=(Array.isArray(e.tokens)?e.tokens:[]).filter(f=>typeof f=="string"&&f.trim().length>0).map(f=>f.trim().toUpperCase()),o=(Array.isArray(e.chains)?e.chains:[]).filter(f=>typeof f=="string"&&f.trim().length>0),s=o.filter(f=>!this.service.isSupported(f)),a=o.filter(f=>this.service.isSupported(f)).map(f=>this.service.resolveChain(f));if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],l=typeof e.sortBy=="string"&&Sy.includes(e.sortBy)?e.sortBy:"tvl",c={minTVL:typeof e.minTVL=="number"?e.minTVL:void 0,maxTVL:typeof e.maxTVL=="number"?e.maxTVL:void 0,minAPR:typeof e.minAPR=="number"?e.minAPR:void 0,maxAPR:typeof e.maxAPR=="number"?e.maxAPR:void 0,feeTier:typeof e.feeTier=="number"?e.feeTier:void 0},d=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5;if(o.length>0&&a.length===0)return{_instructions:"The user requested chains we do not support via The Graph subgraph. Politely list the unsupported chains and the supported chains. Do not show any pool data.",unsupportedChains:s.map(T),supportedChains:this.service.listSupportedChains().map(T),pools:[],count:0};let p=(await Promise.allSettled(i.map(f=>this.service.searchPools({tokens:r,chain:f,sortBy:l,filters:c})))).flatMap(f=>f.status==="fulfilled"?f.value:[]);l==="apr"?p.sort((f,h)=>(h.apr??0)-(f.apr??0)):l==="tvl"?p.sort((f,h)=>h.tvl-f.tvl):l==="volume"?p.sort((f,h)=>h.volume24hUsd-f.volume24hUsd):l==="fee"&&p.sort((f,h)=>f.feeTierBps-h.feeTierBps),p=p.slice(0,d);let m=[];return r.length===2&&(m=(await Promise.allSettled(i.map(h=>this.service.getCoinPoolPairs({chain:h,tokens:r})))).flatMap((h,g)=>h.status==="fulfilled"?h.value.map(b=>({...b,chain:T(i[g])})):[]),m.sort((h,g)=>(g.apr??-1/0)-(h.apr??-1/0)),m=m.slice(0,d)),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). Then list the pools with: pair (e.g. USDC/WETH), fee tier (%), TVL (USD), volume past day (USD), APR (%). Format USD human-readably ($12.5M, $450K). Mention chain and sort metric briefly. If a pool has no APR (null), skip the APR field rather than showing zero. For EACH pool, render the provided uniswapUrl as a clickable markdown link \u2014 e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)". Never omit this link. Do not invent URLs. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: the APR in coinPoolPairs is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the list, add a brief, natural read on the pools \u2014 conversational, like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4CA} Evaluation"); vary your wording each time and only mention what actually stands out in THIS data. Reason ONLY from the numbers shown \u2014 never invent figures. Touch on, as it fits: which pool looks strongest and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; a high volume-to-TVL ratio signals an active, fee-generating pool); whether the fee tier fits the pair (0.05% for stable/correlated, 0.30% for typical volatile, 1% for exotic/low-liquidity); any pool to be cautious about (thin TVL/volume, or an eye-catching APR that is likely volatile/unsustainable rather than a sure thing); and the key risks in a line (APR is variable, high APR usually means higher risk, impermanent loss for LPs on volatile pairs). Keep it short and human \u2014 a sentence or two or a couple of light bullets. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, no stock disclaimer). If unsupportedChains is non-empty, mention them once at the end.',tokens:r,chains:i.map(T),unsupportedChains:s.map(T),sortBy:l,filters:c,count:p.length,pools:p.map(f=>this.formatPool(f)),coinPoolPairs:m}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:je(e)}}};function je(n){return`https://app.uniswap.org/explore/pools/${Ys[n.chain]||n.chain}/${n.poolAddress}`}var Ys={ethereum:"ethereum",arbitrum:"arbitrum",polygon:"polygon",bsc:"bnb",base:"base",optimism:"optimism",avalanche:"avalanche"};var Do=class extends A{name="subgraph-trending-pools";description='List Uniswap V3 pools with the highest volume past day on one or more chains via The Graph subgraphs. Use for: "what are trending pools?", "most active pools", "hot pools right now", "pools with biggest volume today". Returns pair, TVL, volume past day, fee tier (%), APR (DefiLlama-enriched) for each. Supported chains: Ethereum (0x1), Arbitrum (0xa4b1), Polygon (0x89), BSC (0x38), Base (0x2105), Optimism (0xa), Avalanche (0xa86a).';category="blockchain-data";parameters=[{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]},{name:"limit",type:"number",description:"Max pools to return. Default 5, max 20.",required:!1,default:5}];service;constructor(e){super(),this.service=new xe(e)}async run(e,t){let r=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),o=r.filter(d=>!this.service.isSupported(d)),s=r.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(r.length>0&&s.length===0)return{_instructions:"User requested unsupported chains. Politely list them and the supported chains; do not show pool data.",unsupportedChains:o,supportedChains:this.service.listSupportedChains(),pools:[],count:0};if(s.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());let a=s.length>0?s:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),20):5,c=(await Promise.allSettled(a.map(d=>this.service.getTrendingPools({chain:d})))).flatMap(d=>d.status==="fulfilled"?d.value:[]);return c.sort((d,u)=>u.volume24hUsd-d.volume24hUsd),c=c.slice(0,i),{_instructions:'Prefix the answer with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). List pools ranked by volume past day. For each: pair, fee %, volume past day, TVL, APR (skip if null). For EACH pool render the provided uniswapUrl as a clickable markdown link (e.g. wrap the pair as "[USDC/WETH](uniswapUrl)" or append "[View on Uniswap](uniswapUrl)"). Never omit it. Do not invent URLs.',chains:a,unsupportedChains:o,count:c.length,pools:c.map(d=>({pair:d.pair,poolAddress:d.poolAddress,chain:d.chain,feeTierBps:d.feeTierBps,feeTierPercent:d.feeTierPercent,tvlUsd:d.tvl,volumePastDayUsd:d.volume24hUsd,fees24hUsd:d.fees24hUsd,apr:d.apr,token0:d.token0,token1:d.token1,uniswapUrl:je(d)}))}}};var Oo=class extends A{name="subgraph-pool-by-address";description='Fetch full pool detail AND an evaluation for a specific Uniswap V3 pool by its on-chain address via The Graph subgraphs. Returns Uniswap fundamentals (pair, fee tier, TVL, volume past day + fees, APR, token addresses) enriched with CoinPool concentrated-liquidity price-range candidates (per-range APR + min/max/current price), then a genuine assessment of the pool. Use whenever the user pastes a 0x pool address \u2014 both for plain detail ("tell me about pool 0xabc\u2026", "details of this pool 0x\u2026") and for an opinion ("\u0111\xE1nh gi\xE1 pool 0x\u2026", "rate/evaluate this pool 0x\u2026", "is pool 0x\u2026 good?", "pool n\xE0y c\xF3 t\u1ED1t kh\xF4ng").';category="blockchain-data";parameters=[{name:"poolAddress",type:"string",description:"0x-prefixed Uniswap V3 pool contract address (40 hex chars).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1}];service;constructor(e){super(),this.service=new xe(e)}async run(e,t){let r=typeof e.poolAddress=="string"?e.poolAddress.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(r))return{error:"This only supports Uniswap V3 pools. Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address)."};let o=typeof e.chain=="string"&&e.chain.trim();if(!o&&!t?.chain&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());let s=o?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(s))return{_instructions:"The requested chain is not supported by the Subgraph pool service. List the supported chains briefly.",unsupportedChains:[s],supportedChains:this.service.listSupportedChains()};let a=this.service.resolveChain(s),[i,l]=await Promise.all([this.service.getPoolByAddress({poolAddress:r,chain:a}),this.service.getCoinPoolByAddress({chain:a,poolAddress:r}).catch(()=>[])]);return i?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3,'+(l.length>0?" enriched with CoinPool range data,":"")+'" (translate naturally; keep "Subgraph" and "CoinPool" as-is). First show the pool snapshot: pair, fee tier (%), TVL, volume past day, 24h fees, APR (skip if null), and the pool address. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)". CRITICAL: a range APR is for that SPECIFIC price range only \u2014 never present it as the overall pool APR. Then give a genuine evaluation of THIS pool \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading; vary the wording each time and only cover what is actually relevant to this pool and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: liquidity depth & activity (higher TVL + volume past day = deeper liquidity, more fees, less slippage; thin TVL/volume is a red flag); fee-tier fit (0.05% suits stable/correlated pairs, 0.30% typical volatile pairs, 1% exotic/low-liquidity ones \u2014 flag a mismatch); whether the APR looks attractive vs. how sustainable it is (fee-driven and steady vs. thin-TVL spikes that can vanish); if coinPoolPairs is present, which price range makes sense \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Close with a short, natural overall take (e.g. solid / decent-with-caveats / risky) and a brief nudge that it is informational, not financial advice \u2014 phrase it differently each time, do not paste a stock disclaimer. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs. Do NOT mention tool names, UI, or forms.',chain:a,coinPoolPairs:l,pool:{pair:i.pair,poolAddress:i.poolAddress,chain:i.chain,feeTierBps:i.feeTierBps,feeTierPercent:i.feeTierPercent,tvlUsd:i.tvl,volumePastDayUsd:i.volume24hUsd,fees24hUsd:i.fees24hUsd,apr:i.apr,token0:i.token0,token1:i.token1,uniswapUrl:je(i)}}:{error:`No pool found at ${r} on ${T(a)}.`}}};var Mo=class extends A{name="subgraph-pool-by-position-id";description='Return the pool underlying a Uniswap V3 NFT position id. Use when the user wants the pool stats for a numeric id WITHOUT the deposit/withdraw/fee history (e.g. "which pool is position 962961 in?", "show the pool of id 12345"). For full position history use subgraph-position-detail instead.';category="blockchain-data";parameters=[{name:"positionId",type:"string",description:"Numeric Uniswap V3 NFT position id as a string.",required:!0},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]}];service;constructor(e){super(),this.service=new xe(e)}async run(e,t){let r=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(r))return{error:"positionId must be a numeric string."};let o=(Array.isArray(e.chains)?e.chains:[]).filter(d=>typeof d=="string"&&d.trim().length>0),s=o.filter(d=>!this.service.isSupported(d)),a=o.filter(d=>this.service.isSupported(d)).map(d=>this.service.resolveChain(d));if(o.length>0&&a.length===0)return{_instructions:"Requested chains are not supported. List the supported chains.",unsupportedChains:s,supportedChains:this.service.listSupportedChains()};if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(d=>this.service.getPoolByPositionId({positionId:r,chain:d})))).map(d=>d.status==="fulfilled"?d.value:null).find(d=>d!=null);return c?{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). Show the pool of that position: pair, fee %, TVL, volume past day, APR (skip the APR entirely when it is null \u2014 never write "APR 0%", "N/A" or a dash). Mention the position id. End the response with the provided uniswapUrl as a clickable markdown link, e.g. "[View on Uniswap](uniswapUrl)". Never omit it. Do not invent URLs.',positionId:r,pool:{pair:c.pair,poolAddress:c.poolAddress,chain:c.chain,feeTierBps:c.feeTierBps,feeTierPercent:c.feeTierPercent,tvlUsd:c.tvl,volumePastDayUsd:c.volume24hUsd,fees24hUsd:c.fees24hUsd,apr:c.apr,token0:c.token0,token1:c.token1,uniswapUrl:je(c)}}:{_instructions:"No pool found for this position id on the chosen chains. Ask the user to verify the id or chain.",positionId:r,chains:i,found:!1}}};var Fo=class extends A{name="subgraph-position-detail";description=`Look up a Uniswap V3 liquidity position by its numeric NFT id (e.g. 962961) on one or more chains via The Graph subgraphs. Returns the position (deposited/withdrawn token amounts, collected fees, liquidity) AND its underlying pool (pair, fee tier, TVL, volume past day, APR). Use when the user names a numeric id with phrases like: "position 12345", "pool id 962961", "tell me about position 962961". Does NOT support the user's wallet-wide LP list \u2014 only a specific id.`;category="blockchain-data";parameters=[{name:"positionId",type:"string",description:'Numeric Uniswap V3 NFT position id as a string (e.g. "962961").',required:!0},{name:"chains",type:"array",items:{type:"string"},description:'Hex chain IDs: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Pass [] when the user did not name a chain \u2014 the tool defaults to the connected chain.',required:!1,default:[]}];service;constructor(e){super(),this.service=new xe(e)}async run(e,t){let r=typeof e.positionId=="string"?e.positionId.trim():"";if(!/^\d+$/.test(r))return{error:"positionId must be a numeric string (Uniswap V3 NFT id)."};let o=(Array.isArray(e.chains)?e.chains:[]).filter(u=>typeof u=="string"&&u.trim().length>0),s=o.filter(u=>!this.service.isSupported(u)),a=o.filter(u=>this.service.isSupported(u)).map(u=>this.service.resolveChain(u));if(o.length>0&&a.length===0)return{_instructions:"User asked about a position on chains we do not support. List unsupported + supported chains.",unsupportedChains:s,supportedChains:this.service.listSupportedChains()};if(a.length===0&&!this.service.isSupported(t?.chain)&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());let i=a.length>0?a:this.service.isSupported(t?.chain)?[this.service.resolveChain(t?.chain)]:["0x1"],c=(await Promise.allSettled(i.map(u=>this.service.getPositionDetail({positionId:r,chain:u})))).map(u=>u.status==="fulfilled"?u.value:null).find(u=>u!=null);if(!c)return{_instructions:"No position with this id was found on the chosen chains. Suggest the user double-check the id or specify another chain.",positionId:r,chains:i,found:!1};let d=Ys[c.position.chain]||c.position.chain;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally; keep "Subgraph" as-is). Show the pair, chain, fee tier (%), deposited/withdrawn/collected fees for each token, plus pool stats (TVL, volume past day, APR \u2014 skip the APR entirely when it is null, never write "APR 0%", "N/A" or a dash). End the response with TWO clickable markdown links from the data: position.uniswapPositionUrl as "[View position on Uniswap](uniswapPositionUrl)" and pool.uniswapUrl as "[View pool on Uniswap](uniswapUrl)". Never omit them. Do not invent URLs.',positionId:r,position:{...c.position,uniswapPositionUrl:`https://app.uniswap.org/positions/v3/${d}/${c.position.positionId}`},pool:{...c.pool,uniswapUrl:je(c.pool)}}}};var Bo=class extends A{name="subgraph-coinpool-pairs";description='List CoinPool concentrated-liquidity price-range candidates for a token pair on a chain. Each entry shows: pair, fee tier, min/max price range, current price, and APR within that range (NOT the overall pool APR \u2014 strictly per-range). Use ONLY for queries about price ranges or which range to pick: "what price range should I use for ETH/USDC?", "best range for USDC/WETH on Arbitrum", "g\u1EE3i \xFD kho\u1EA3ng gi\xE1 ETH/USDC". Do NOT use for general "show me ETH/USDC pools" \u2014 use subgraph-search-pools for that.';category="blockchain-data";parameters=[{name:"tokens",type:"array",items:{type:"string"},description:'Two token symbols (e.g. ["ETH","USDC"]).',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1},{name:"limit",type:"number",description:"Max entries to return (sorted by APR desc). Default 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new xe(e)}async run(e,t){let r=(Array.isArray(e.tokens)?e.tokens:[]).filter(d=>typeof d=="string"&&d.trim().length>0).map(d=>d.trim().toUpperCase());if(r.length<2)return{error:'tokens must contain two token symbols (e.g. ["ETH","USDC"]).'};let o=typeof e.chain=="string"&&e.chain.trim();if(!o&&!t?.chain&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());let s=o?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(s))return{_instructions:"Requested chain not supported. Mention supported chains.",unsupportedChains:[s],supportedChains:this.service.listSupportedChains()};let a=this.service.resolveChain(s),i=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),30):10,l=await this.service.getCoinPoolPairs({chain:a,tokens:r});if(l.length===0)return{_instructions:"No CoinPool range data is available for this pair on this chain. Tell the user this nicely and suggest using general pool data instead (via subgraph-search-pools).",tokens:r,chain:a,pairs:[],count:0};let c=[...l].sort((d,u)=>(u.apr??-1/0)-(d.apr??-1/0)).slice(0,i);return{_instructions:'CRITICAL: APR in each entry is the APR for that SPECIFIC price range only \u2014 NEVER present it as the overall pool APR. For each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price, and the APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200 ETH/USDC)". When an entry has no `apr` (null/absent), omit the APR part for that entry \u2014 never write "APR 0%", "N/A" or a dash. Sort by APR descending; explain that the top entry is the best concentrated range but narrower = higher out-of-range risk.',tokens:r,chain:a,count:c.length,pairs:c}}};var qo=class extends A{name="subgraph-add-pool";description='Open the ADD-LIQUIDITY / ADD-POOL flow for Uniswap V3 via The Graph subgraphs. Use for ANY "provide / add liquidity", "add LP", "add pool", "create pool", "create pair", "farm/deposit into a pool" intent (natural-language verbs in any language map here: "th\xEAm thanh kho\u1EA3n", "th\xEAm pool", "t\u1EA1o pool"). It RESOLVES the pool the user means \u2014 by 0x pool address, or by one/two token symbols (with optional fee tier) \u2014 like the detail/search tools, then points the user to the add-liquidity website. When two token symbols are given, it also surfaces CoinPool concentrated-liquidity price-range candidates (per-range APR) to help pick a range. Pass `poolAddress` when the user gives a 0x pool address; otherwise pass `tokens` (1 or 2 symbols) and optional `feeTier`. Leave both blank when the user named no pool/token \u2014 the tool returns the chain\'s top pools to choose from. It does NOT build a transaction; it surfaces the add-liquidity link.';category="blockchain-data";parameters=[{name:"poolAddress",type:"string",description:"0x-prefixed Uniswap V3 pool contract address (40 hex chars). Pass when the user gives a concrete pool address; otherwise leave blank and pass `tokens`.",required:!1},{name:"tokens",type:"array",items:{type:"string"},description:"Token symbols of the pair to add liquidity to. 1 token = pools containing it; 2 tokens = that exact pair (both orderings tried). Leave EMPTY when the user named no token \u2014 the tool returns top pools to choose from.",required:!1,default:[]},{name:"feeTier",type:"number",description:"Optional fee tier in basis points (100, 500, 3000, or 10000) to disambiguate the pool.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche. Defaults to the connected chain when omitted.',required:!1},{name:"howTo",type:"boolean",description:'Set TRUE when the user asks HOW to add liquidity / how to create a pool or pair / how it works ("how to add pool", "how to add pair", "how do I add liquidity", "c\xE1ch th\xEAm thanh kho\u1EA3n", "l\xE0m sao \u0111\u1EC3 add pool/pair") rather than naming a specific pool to add to ("pool" and "pair" are equivalent here). Returns the general steps + the add-liquidity website link, without needing a pool, token, or connected chain. Leave false/omit for a concrete add-liquidity request.',required:!1}];service;linkAddLiquidity;constructor(e){super(),this.service=new xe(e),this.linkAddLiquidity=e?.linkAddLiquidity?.trim()||void 0}async run(e,t){if(e.howTo===!0){let u=this.linkAddLiquidity??null,p=typeof e.chain=="string"&&e.chain.trim()||t?.chain||"0x1",m="",f=[];if(this.service.isSupported(p)){m=this.service.resolveChain(p);try{f=(await this.service.searchPools({tokens:[],chain:m,sortBy:"tvl"})).slice(0,5)}catch{f=[]}}return{_instructions:`The user is asking HOW to add liquidity / create a pool \u2014 a how-to question, not a request about a specific pool. Reply in the user's language, in THIS exact order:
208
208
  1) A clear, easy-to-follow step-by-step guide (numbered steps) on how adding liquidity works. Generate the steps yourself from how Uniswap V3 add-liquidity actually works \u2014 keep each step short; do not pad with filler.
209
209
  `+(f.length>0?'2) A few popular pools (from the provided list) as examples to add liquidity to \u2014 show fee tier %, TVL, APR (skip APR if null). For EACH pool, make it a clickable Uniswap link using its `uniswapUrl`: wrap the pair as a markdown link, e.g. "[USDC/WETH](uniswapUrl)", or append "[View on Uniswap](uniswapUrl)". Use the uniswapUrl verbatim; never invent one. Make clear these are just examples for reference, not recommendations.\n':"")+(f.length>0?"3) ":"2) ")+this.linkInstruction(u)+`
210
- Do NOT mention tool names, UI, or forms.`,howTo:!0,chain:m||void 0,addLiquidityLink:u,count:f.length,pools:f.map(h=>this.formatPool(h))}}let r=typeof e.poolAddress=="string"?e.poolAddress.trim():"",o=(Array.isArray(e.tokens)?e.tokens:[]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toUpperCase()),s=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,a=typeof e.chain=="string"&&e.chain.trim();if(!a&&!t?.chain&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0);let i=a?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(i))return{_instructions:"The requested chain is not supported by the Subgraph pool service. Tell the user, in their language, that add-liquidity is not available on that network and list the supported chains briefly. Do NOT mention tool names.",unsupportedChains:[T(i)],supportedChains:this.service.listSupportedChains().map(T)};let l=this.service.resolveChain(i);if(r){if(!/^0x[a-fA-F0-9]{40}$/.test(r))return{error:"Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address) to add liquidity to it."};let u=await this.service.getPoolByAddress({poolAddress:r,chain:l});return u?this.poolsResult([u],l,!0):{error:`No pool found at ${r} on ${T(l)}.`}}if(o.length>0){let u=await this.service.searchPools({tokens:o,chain:l,sortBy:"tvl",filters:{feeTier:s}});if(u.length===0)return{error:`No Uniswap V3 pool found for ${o.join("/")}${s!=null?` at ${s}bps`:""} on ${T(l)}. Ask the user to check the token symbols, or try a different pair.`};let p=o.length===2?await this.fetchCoinPoolPairs(l,o):[];return this.poolsResult(u.slice(0,8),l,!0,p)}let c=await this.service.searchPools({tokens:[],chain:l,sortBy:"tvl"}),d=this.linkAddLiquidity??null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity but has not named a pool yet. Briefly list these top pools (pair, fee tier %, TVL, APR \u2014 skip APR if null) as suggestions, render each `uniswapUrl` as a clickable markdown link, then ask the user which token pair (or pool) they want to add liquidity to. '+this.linkInstruction(d)+"Do NOT mention tool names, UI, or forms.",chain:l,needsSelection:!0,addLiquidityLink:d,count:c.length,pools:c.slice(0,6).map(u=>this.formatPool(u))}}async fetchCoinPoolPairs(e,t){try{return[...await this.service.getCoinPoolPairs({chain:e,tokens:t})].sort((o,s)=>(s.apr??-1/0)-(o.apr??-1/0)).slice(0,10)}catch{return[]}}linkInstruction(e){return e?`ALWAYS finish by inviting the user to add liquidity on the website, as ONE short sentence that shows the FULL link in plain view \u2014 display the entire URL verbatim (${e}) as the visible link text, do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${e}](${e}). For example: "You can add liquidity here: [${e}](${e})". Use the URL verbatim; never invent one, and never use a pool's uniswapUrl here. `:"No add-liquidity website is configured, so do not show or invent any link. "}poolsResult(e,t,r,o=[]){let s=r?this.linkAddLiquidity??null:null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity. Show the resolved pool(s): pair (e.g. USDC/WETH), fee tier (%), TVL, volume past day, APR (skip if null), and the pool address. For EACH pool, render the provided `uniswapUrl` as a clickable markdown link. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)", to help the user choose a range when adding liquidity. CRITICAL: that APR is for the SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the data, give a genuine, conversational recommendation \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4A1} Recommendation"); vary your wording naturally each time and only cover what is actually relevant to THIS pair and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: which pool/fee tier looks best and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; fee-tier fit: 0.05% for stable/correlated pairs, 0.30% for typical volatile pairs, 1% for exotic/low-liquidity ones); which price range makes sense (from coinPoolPairs if present) \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; anything worth avoiding (thin TVL/volume, ranges far from current price, chasing the top APR blindly); and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Keep it short and human \u2014 a sentence or two or a couple of light bullets, tailored to whether the pair is stable or volatile. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, do not paste a stock disclaimer). '+(s?`Then, at the VERY END, write ONE short, friendly sentence in the user's language inviting them to add liquidity, showing the FULL add-liquidity link in plain view: display the entire URL verbatim as the visible link text \u2014 do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${s}](${s}). For example: "If you'd like to add liquidity to one of these pools, you can do it here: [${s}](${s})." Use the addLiquidityLink verbatim; never invent a URL, and never use a pool's uniswapUrl here.`:"Do NOT invent or show any add-liquidity link (none is configured). Just present the pool(s).")+" Do NOT mention tool names, UI, forms, or that a transaction is built elsewhere.",chain:t,addLiquidityLink:s,count:e.length,pools:e.map(i=>this.formatPool(i)),coinPoolPairs:o}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:je(e)}}};var up={"0x1":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0xa":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0x89":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0xa4b1":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0x38":"0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7","0x2105":"0x33128a8fC17869897dcE68Ed026d694621f6FDfD","0xa86a":"0x740b1c1de25031C31FF4fC9A62f554A55cdC1baD"},xy="e34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54",ip=/^0x[a-fA-F0-9]{40}$/;function Ti(n){let e=n.startsWith("0x")?n.slice(2):n,t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++)t[r]=parseInt(e.slice(r*2,r*2+2),16);return t}function lp(n){let e=new Uint8Array(32);return e.set(Ti(n.toLowerCase()),12),e}function Cy(n){let e=new Uint8Array(32),t=BigInt(n);for(let r=31;r>=0&&t>0n;r--)e[r]=Number(t&0xffn),t>>=8n;return e}function cp(n){let e=n.reduce((o,s)=>o+s.length,0),t=new Uint8Array(e),r=0;for(let o of n)t.set(o,r),r+=o.length;return t}function hc(n){return Object.prototype.hasOwnProperty.call(up,n.toLowerCase())}function fc(n,e,t,r){let o=up[n.toLowerCase()];if(!o||!ip.test(e)||!ip.test(t)||!Number.isInteger(r)||r<=0)return null;let s=e.toLowerCase(),a=t.toLowerCase();if(s===a)return null;let[i,l]=BigInt(s)<BigInt(a)?[s,a]:[a,s],c=ba(cp([lp(i),lp(l),Cy(r)]));return`0x${ba(cp([new Uint8Array([255]),Ti(o),Ti(c),Ti(xy)])).slice(2).slice(24)}`}var pp={"0x1":"Ethereum","0xa":"OP Mainnet","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche"},Ry={ethereum:"0x1","op mainnet":"0xa",optimism:"0xa",bsc:"0x38",binance:"0x38",polygon:"0x89",base:"0x2105",arbitrum:"0xa4b1","arbitrum one":"0xa4b1",avalanche:"0xa86a","avalanche c-chain":"0xa86a"},dp={"uniswap-v2":"V2","uniswap-v3":"V3","uniswap-v4":"V4"},Ey=new Set([100,200,300,400,500,1e3,2500,3e3,1e4,2e4]),_y="https://yields.llama.fi",Ny=300*1e3,$o=Object.keys(pp),gc=new Map,Me=class{baseUrl;cacheTtlMs;constructor(e){this.baseUrl=(e?.baseUrl||_y).replace(/\/$/,""),this.cacheTtlMs=e?.cacheTtlMs??Ny}get store(){let e=gc.get(this.baseUrl);return e||(e={pools:null,fetchedAt:0,inflight:null},gc.set(this.baseUrl,e)),e}isSupported(e){return e?Object.prototype.hasOwnProperty.call(pp,e.toLowerCase()):!1}listSupportedChains(){return[...$o]}async snapshot(){let e=this.store,t=Date.now();return e.pools&&t-e.fetchedAt<this.cacheTtlMs?e.pools:(e.inflight||(e.inflight=(async()=>{try{let r=await C.get(`${this.baseUrl}/pools`);if(!r.ok)throw new Error(`DefiLlama: ${_(r)}`);let o=r.data,a=(Array.isArray(o?.data)?o.data:[]).filter(i=>i&&typeof i.project=="string"&&dp[i.project]!==void 0).map(i=>this.normalize(i)).filter(i=>i!==null);return e.pools=a,e.fetchedAt=Date.now(),a}catch(r){if(e.pools)return e.pools;throw r}finally{e.inflight=null}})()),e.inflight)}clearCache(){gc.delete(this.baseUrl)}parseFeeTierBps(e){if(typeof e!="string")return;let t=e.match(/([\d.]+)\s*%/);if(!t)return;let r=parseFloat(t[1]);if(!Number.isFinite(r)||r<=0)return;let o=Math.round(r*1e4);return Ey.has(o)?o:void 0}normalize(e){let t=Ry[String(e.chain).toLowerCase()];if(!t)return null;let r=dp[e.project];if(!r)return null;let o=this.parseFeeTierBps(e.poolMeta),s=String(e.symbol||"").split(/[-/]/).map(p=>p.trim()).filter(Boolean),a=Array.isArray(e.underlyingTokens)?e.underlyingTokens.filter(p=>typeof p=="string"):[],i=r==="V3"&&o&&a.length===2&&hc(t)?fc(t,a[0],a[1],o)??void 0:void 0,l=typeof e.tvlUsd=="number"&&e.tvlUsd>0?e.tvlUsd:0,c=typeof e.volumeUsd1d=="number"&&e.volumeUsd1d>=0?e.volumeUsd1d:void 0,d=$(e.apyBase??e.apy),u=$(e.apy)??d;return{id:e.pool,pair:s.length>=2?`${s[0]}/${s[1]}`:String(e.symbol||""),chain:t,protocolVersion:r,address:i,feeTierBps:o,feeTierPercent:o!==void 0?o/1e4:void 0,tvlUsd:l,apr:d!==void 0?parseFloat(d.toFixed(2)):void 0,totalApr:u!==void 0?parseFloat(u.toFixed(2)):void 0,volume1DayUsd:c,volume7DayUsd:typeof e.volumeUsd7d=="number"&&e.volumeUsd7d>=0?e.volumeUsd7d:void 0,volumeToTvlRatio:c!==void 0&&l>0?parseFloat((c/l).toFixed(4)):void 0,fee24hUsd:c!==void 0&&o!==void 0?parseFloat((c*o/1e6).toFixed(2)):void 0,token0:s[0]||a[0]?{symbol:s[0],address:a[0]}:void 0,token1:s[1]||a[1]?{symbol:s[1],address:a[1]}:void 0,isStablecoin:e.stablecoin===!0?!0:void 0,ilRisk:typeof e.ilRisk=="string"?e.ilRisk:void 0,aprChange1D:typeof e.apyPct1D=="number"?e.apyPct1D:void 0,aprChange7D:typeof e.apyPct7D=="number"?e.apyPct7D:void 0,aprChange30D:typeof e.apyPct30D=="number"?e.apyPct30D:void 0,aprMean30d:typeof e.apyMean30d=="number"?parseFloat(e.apyMean30d.toFixed(2)):void 0}}sortValue(e,t){switch(t){case"apr":return e.apr??-1;case"volume1Day":return e.volume1DayUsd??-1;case"volume7Day":return e.volume7DayUsd??-1;default:return e.tvlUsd}}sorted(e,t){return[...e].sort((r,o)=>this.sortValue(o,t)-this.sortValue(r,t))}async getTopPools(e){try{let t=await this.snapshot(),r=e.protocolVersion??"V3",o=Math.min(Math.max(e.limit??10,1),50),s=t.filter(a=>a.chain===e.chain);return r!=="ALL"&&(s=s.filter(a=>a.protocolVersion===r)),e.forAddLiquidity&&(s=s.filter(a=>a.address!==void 0)),{success:!0,data:this.sorted(s,e.sortBy??"tvl").slice(0,o)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async searchPools(e){try{let t=await this.snapshot(),r=e.protocolVersion??"V3",o=Math.min(Math.max(e.limit??10,1),50),s=String(e.query||"").split(/[\s,/-]+/).map(i=>i.trim().toLowerCase()).filter(Boolean),a=t.filter(i=>i.chain===e.chain);return r!=="ALL"&&(a=a.filter(i=>i.protocolVersion===r)),e.forAddLiquidity&&(a=a.filter(i=>i.address!==void 0)),s.length>0&&(a=a.filter(i=>{let l=[i.token0?.symbol?.toLowerCase(),i.token1?.symbol?.toLowerCase(),i.token0?.address?.toLowerCase(),i.token1?.address?.toLowerCase()].filter(c=>typeof c=="string");return s.every(c=>l.some(d=>c.startsWith("0x")?d===c:this.symbolMatches(d,c)))})),{success:!0,data:this.sorted(a,e.sortBy??"tvl").slice(0,o)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}symbolMatches(e,t){return e===t||e===`w${t}`||t===`w${e}`}async getPoolsByPair(e){let t=[e.token0Symbol,e.token1Symbol].filter(Boolean).join(" "),r=await this.searchPools({chain:e.chain,query:t,limit:50,sortBy:"tvl",protocolVersion:e.protocolVersion??"V3"});return!r.success||!r.data?r:{success:!0,data:e.feeTierBps!==void 0?r.data.filter(s=>s.feeTierBps===e.feeTierBps):r.data}}async findByPoolAddress(e){try{let t=await this.snapshot(),r=e.address.toLowerCase();return{success:!0,data:t.find(s=>s.chain===e.chain&&s.address===r)??null}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async findPoolsByTokenAddress(e){try{let t=await this.snapshot(),r=e.address.toLowerCase(),o=t.filter(s=>s.chain===e.chain&&(s.token0?.address?.toLowerCase()===r||s.token1?.address?.toLowerCase()===r));return{success:!0,data:this.sorted(o,"tvl").slice(0,Math.min(e.limit??10,50))}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}};function He(){return{kind:"info",async listSupported(){return $o.filter(n=>Be(n))},async isSupported(n){if(!n)return!1;let e=D(n)??n.toLowerCase();return $o.includes(e)}}}function Ve(){return $o.filter(n=>Be(n)).map(n=>T(n)).join(", ")}var We="Hex chain ID of the chain the user named. Map the chain name to its EXACT hex id \u2014 pass ONLY one of these values, never a guessed or made-up one: Ethereum=0x1, Optimism=0xa, BSC=0x38, Polygon=0x89, Base=0x2105, Arbitrum=0xa4b1, Avalanche=0xa86a. Set this WHENEVER the user EXPLICITLY names a chain (always send the exact hex from this list). Otherwise OMIT it entirely so the connected wallet chain is used automatically.";var Ly=["V2","V3","V4"];function Ho(n){if(typeof n!="string")return"V3";let e=n.trim().toUpperCase();return e==="ALL"?"ALL":Ly.includes(e)?e:"V3"}function Iy(n){return Object.fromEntries(Object.entries(n).filter(([,e])=>e!=null))}function _e(n){let e=Ws(n.chain,n.address);return Iy({pair:n.pair,address:n.address,chain:n.chain,protocolVersion:n.protocolVersion,feeTierBps:n.feeTierBps,feeTierPercent:n.feeTierPercent,tvlUsd:n.tvlUsd,volume1DayUsd:n.volume1DayUsd,volume7DayUsd:n.volume7DayUsd,fee24hUsd:n.fee24hUsd,apr:n.apr,totalApr:n.totalApr!==void 0&&n.totalApr!==n.apr?n.totalApr:void 0,volumeToTvlRatio:n.volumeToTvlRatio,aprChange1D:n.aprChange1D,aprChange7D:n.aprChange7D,aprMean30d:n.aprMean30d,isStablecoin:n.isStablecoin,ilRisk:n.ilRisk,token0:n.token0,token1:n.token1,uniswapUrl:e??void 0,addLiquidityUnavailable:n.address===void 0?!0:void 0})}var ft='\u2022 APR trend \u2014 `aprChange1D` / `aprChange7D` are the change in APR over the last day / week in PERCENTAGE POINTS, and `aprMean30d` is the 30-day average APR. A spot `apr` far above `aprMean30d` is a spike that is unlikely to hold; one near or below it is steadier. Use these to judge whether a yield is durable rather than a snapshot. \u2022 `ilRisk` = "no" marks a pool upstream considers free of impermanent-loss exposure (typically a correlated or stablecoin pair); "yes" is the normal volatile-pair case. `isStablecoin` marks a stablecoin pair. \u2022 `totalApr` (when present and higher than `apr`) includes incentive/reward emissions on top of swap fees \u2014 call that out, since emissions can end at any time while fee yield does not. \u2022 `addLiquidityUnavailable: true` means this pool cannot be added to in-app \u2014 never offer to add liquidity to it. ';var Uy=["tvl","volume1Day","volume7Day","apr"],Vo=class extends A{name="defillama-top-pools";description=`List the top Uniswap liquidity pools on a given EVM chain, ranked by TVL by default. Returns each pool's address, fee tier, protocol version, both tokens, TVL, rolling volume (1d / 7d), fee revenue, and APR (with 1d/7d/30d APR trend). Use this tool for questions like: "top pools on Ethereum", "biggest Uniswap pools on Base", "which pools have the most liquidity", "show pools with the highest APR on Arbitrum". Source: DefiLlama Yields. Supports: `+Ve();category="blockchain-data";parameters=[{name:"chain",type:"string",description:We,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version to filter by: "V2", "V3", "V4", or "ALL". Default is "V3" (the dataset with the richest stats and the only one that supports adding liquidity in-app). Use "V4" only when the user explicitly asks for V4 pools.',required:!1,default:"V3"},{name:"sortBy",type:"string",description:'Ranking metric: "tvl" (total value locked, default), "volume1Day", "volume7Day", or "apr" (annualized fee yield). Pools are returned in descending order by this metric. There is no 30-day volume or transaction-count ranking \u2014 for "most active" use "volume1Day".',required:!1,default:"tvl"},{name:"limit",type:"number",description:'Maximum number of pools to return after sorting. Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"forAddLiquidity",type:"boolean",description:"Set true when the user wants to ADD LIQUIDITY and is picking a pool (rather than just browsing). Validates ADD-LIQUIDITY chain support up front and returns ONLY pools that can actually be added to, so the user never picks a pool that dead-ends at the next step.",required:!1,default:!1},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new ie}async run(e,t){let r=e.forAddLiquidity===!0,o=await te(r?vn(this.pool):He(),e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=Ho(e.protocolVersion),i=typeof e.sortBy=="string"?e.sortBy:"tvl",l=Uy.includes(i)?i:"tvl",c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,d=await this.service.getTopPools({chain:s,limit:c,sortBy:l,protocolVersion:a,forAddLiquidity:r});if(!d.success)return{_instructions:"Pool data could not be retrieved right now. Tell the user briefly, in their language, that pool data is temporarily unavailable and to try again shortly. Do NOT mention tools, APIs, or any internals.",error:d.error};let u=(d.data??[]).map(_e);if(u.length===0)return{_instructions:"No pools matched on this chain. Tell the user plainly, in their language, that no pools were found here and suggest another chain. Do NOT invent pools. Do NOT mention tools or APIs.",chain:T(s),count:0,pools:[]};let p=await this.pool.isAddLiquiditySupported(s)?pe(u.filter(m=>m.address!==void 0),e,T(s)):[];return{_instructions:me+"You are briefing a peer. Present the pools as a ranked list, then deliver the analysis. For each pool include the key facts: rank, pair (token0/token1 symbols), fee tier (in %), TVL in USD, 24h volume, and APR (in %). CRITICAL: every pool MUST have its own written analysis \u2014 2\u20133 sentences of genuine expert read placed directly under that pool's facts. NEVER skip a pool and NEVER reduce a pool to just a facts list. Vary the wording from pool to pool (do not repeat the same sentence structure), go a little deeper on the standouts, and surface the non-obvious insight a less experienced observer would miss. "+he+ft+"After the per-pool reads, close with a short overall section that (1) gives a high-level read across the whole list \u2014 the broad pattern you see (where the real capital efficiency and fee yield sit, how the risk/reward stacks up), (2) names the single best pool to provide liquidity in right now and explains why it stands out, and (3) gives the user a concrete, actionable recommendation tailored to the data. "+be+Y+"Mention the chain and the sort metric in the intro line. "+j+(p.length>0?de:""),chain:s,protocolVersion:a,sortBy:l,count:u.length,pools:u,...p.length>0?{actionButtons:p}:{}}}};var Dy=["tvl","volume1Day","volume7Day","apr"],Wo=class extends A{name="defillama-search-pools";description='Search Uniswap liquidity pools by token symbol, token name, or token address on a given EVM chain. Use for: "show pools for USDC", "find WBTC pools on Base", "pools containing PEPE", "USDC/ETH pools on Arbitrum", "top USDC pools". Use this WHENEVER the user names a specific token \u2014 even with words like "top" or "biggest". Returns matching pools with pair, fee tier, TVL, 24h/7d volume, and APR. Source: DefiLlama Yields. Supports: '+Ve();category="blockchain-data";parameters=[{name:"query",type:"string",description:'The token symbol(s), token name, or token address to search for. For a PAIR, pass both symbols separated by a space ("USDC WETH") \u2014 every term must appear in the pool, so this returns that pair specifically. For a single token pass just its symbol ("USDC").',required:!0},{name:"chain",type:"string",description:We,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version to filter by: "V2", "V3", "V4", or "ALL". Default "V3". Use "ALL" only when the user explicitly wants every version.',required:!1,default:"V3"},{name:"sortBy",type:"string",description:'Ranking metric for the matches: "tvl" (default), "volume1Day", "volume7Day", or "apr". Use "volume1Day" when the user asked for the "top"/"biggest"/"most active" pools of a token.',required:!1,default:"tvl"},{name:"limit",type:"number",description:"Maximum number of pools to return. Defaults to 5, max 50.",required:!1,default:5},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new ie}async run(e,t){let r=await te(He(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.query=="string"?e.query.trim():"";if(!s)return{_instructions:"No search term was provided. Ask the user which token they want pools for, in their language. Do NOT mention tools or APIs."};let a=Ho(e.protocolVersion),i=typeof e.sortBy=="string"?e.sortBy:"tvl",l=Dy.includes(i)?i:"tvl",c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,d=await this.service.searchPools({chain:o,query:s,limit:c,sortBy:l,protocolVersion:a});if(!d.success)return{_instructions:"Pool data could not be retrieved right now. Tell the user briefly, in their language, that pool data is temporarily unavailable and to try again shortly. Do NOT mention tools, APIs, or any internals.",error:d.error};let u=(d.data??[]).map(_e);if(u.length===0)return{_instructions:"No pools matched this token on this chain. Tell the user plainly, in their language, that no pools were found for it here, and suggest checking another chain or a different token. NEVER invent pools. Do NOT mention tools or APIs.",chain:T(o),query:s,count:0,pools:[]};let p=await this.pool.isAddLiquiditySupported(o)?pe(u.filter(m=>m.address!==void 0),e,T(o)):[];return{_instructions:me+`Present the pools matching "${s}" as a ranked list, then deliver the analysis. For each pool include: pair, fee tier (in %), TVL in USD, 24h volume, and APR (in %). CRITICAL: every pool MUST have its own 2\u20133 sentence expert read directly under its facts \u2014 never a bare list. Vary the wording between pools and surface the non-obvious insight. `+he+ft+"IMPORTANT \u2014 same pair, different pools: two pools can show the SAME pair and fee tier yet be different contracts (one of the tokens is an impostor wearing a well-known ticker). When you see that, flag the one with far lower TVL as the likely impostor and tell the user to verify the token contract before providing liquidity. Close with a short overall read: which of these pools is the most attractive for an LP right now and why. "+be+Y+j+(p.length>0?de:""),chain:o,query:s,sortBy:l,count:u.length,pools:u,...p.length>0?{actionButtons:p}:{}}}};var Yo=class extends A{name="defillama-pool-detail";description='Get full statistics for ONE specific Uniswap pool identified by its TOKEN PAIR (and optional fee tier). Use for: "details for USDC/WETH 0.05% on Base", "TVL and APR of the WBTC/USDC pool", "how is the ETH/USDC pool doing". Returns TVL, 24h/7d volume, fee revenue, APR (with trend), fee tier, and both tokens. Pass token symbols \u2014 NEVER a pool address (use lookup-pool-by-address for an address). When several fee tiers match, returns a candidates list to choose from instead of a single pool. Source: DefiLlama Yields. Supports: '+Ve();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:'Symbol of the first token in the pair, e.g. "USDC". Required.',required:!0},{name:"token1Symbol",type:"string",description:`Symbol of the second token, e.g. "WETH". Omit when the user named only one token \u2014 the tool then returns that token's pools as candidates.`,required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points as Uniswap stores it: 100 = 0.01%, 500 = 0.05%, 3000 = 0.3%, 10000 = 1%. Omit when the user did not name one \u2014 the tool then returns the matching tiers as candidates.",required:!1},{name:"chain",type:"string",description:We,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version: "V2", "V3", "V4", or "ALL". Default "V3".',required:!1,default:"V3"},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new ie}async run(e,t){let r=await te(He(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"";if(!s)return{_instructions:"No token was named. Ask the user which pool they mean, in their language. Do NOT mention tools or APIs."};let a=typeof e.token1Symbol=="string"&&e.token1Symbol.trim()?e.token1Symbol.trim():void 0,i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.round(e.feeTier):void 0,l=Ho(e.protocolVersion),c=await this.service.getPoolsByPair({chain:o,token0Symbol:s,token1Symbol:a,feeTierBps:i,protocolVersion:l});if(!c.success)return{_instructions:"Pool data could not be retrieved right now. Tell the user briefly, in their language, that pool data is temporarily unavailable and to try again shortly. Do NOT mention tools, APIs, or any internals.",error:c.error};let d=c.data??[],u=[s,a].filter(Boolean).join("/");if(d.length===0)return{_instructions:"No pool matched that pair on this chain. Tell the user plainly, in their language, that this pool was not found here, and suggest another chain or checking the token symbols. NEVER invent pool stats. Do NOT mention tools or APIs.",chain:T(o),pair:u,pool:null};let p=await this.pool.isAddLiquiditySupported(o);if(d.length>1){let h=d.map(_e),g=p?pe(h.filter(b=>b.address!==void 0),e,T(o)):[];return{_instructions:`Several ${u} pools exist on this chain \u2014 they differ by fee tier. Present them as a short numbered list (pair, fee %, TVL, 24h volume, APR) with a one-line expert note on each saying which kind of LP it suits, then ask the user which one they want. Do NOT present any single one as "the" pool and do NOT merge their stats. `+j+(g.length>0?de:""),chain:o,pair:u,count:h.length,candidates:h,...g.length>0?{actionButtons:g}:{}}}let m=_e(d[0]),f=p&&m.address!==void 0?pe([m],e,T(o)):[];return{_instructions:me+"Give a thorough read on this ONE pool. Lead with the facts \u2014 pair, fee tier (in %), chain, TVL, 24h volume, 24h fee revenue, and APR (in %) \u2014 then deliver several sentences of genuine expert analysis in flowing prose. "+he+ft+"Close by telling the user concretely whether this pool is worth providing liquidity in right now, and for which kind of LP it is best suited. "+be+Y+j+(f.length>0?de:""),chain:o,pair:u,pool:m,...f.length>0?{actionButtons:f}:{}}}};var Oy=/^0x[a-fA-F0-9]{40}$/,Go=class extends A{name="defillama-pool-by-address";description='Resolve an unknown 0x address as either a Uniswap pool or a token, then return the appropriate data: pool detail when the address is a pool, or the list of pools containing that token when the address is a token. Use when the user pastes a single 0x address without saying which it is ("what is 0x88e6\u2026", "tell me about this address"). For pool resolution: pair, fee tier, TVL, volume, fee revenue and APR. For token resolution: the token plus a ranked list of pools containing it. Source: DefiLlama Yields, with an on-chain read as fallback. Supports: '+Ve();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:We,required:!1},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new ie}async run(e,t){let r=await te(He(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.address=="string"?e.address.trim():"";if(!Oy.test(s))return{_instructions:"The value provided is not a valid EVM address. Ask the user, in their language, to re-send the full 0x address. Do NOT mention tools or APIs."};let a=s.toLowerCase(),i=await this.pool.isAddLiquiditySupported(o),l=await this.service.findByPoolAddress({chain:o,address:a});if(l.success&&l.data){let u=_e(l.data),p=i&&u.address!==void 0?pe([u],e,T(o)):[];return{_instructions:me+"This address is a liquidity POOL. Lead with the facts \u2014 pair, fee tier (in %), chain, TVL, 24h volume, 24h fee revenue and APR (in %) \u2014 then give several sentences of genuine expert analysis. "+he+ft+"Close by saying concretely whether this pool is worth providing liquidity in right now. "+be+Y+j+(p.length>0?de:""),chain:o,resolvedAs:"pool",pool:u,...p.length>0?{actionButtons:p}:{}}}let c=await this.service.findPoolsByTokenAddress({chain:o,address:a,limit:10});if(c.success&&c.data&&c.data.length>0){let u=c.data.map(_e),p=c.data[0],m=p.token0?.address?.toLowerCase()===a?p.token0?.symbol:p.token1?.symbol,f=i?pe(u.filter(h=>h.address!==void 0),e,T(o)):[];return{_instructions:"The address is a TOKEN, not a pool. Tell the user which token it is, then present the pools containing it as a ranked numbered list (pair, fee %, TVL, 24h volume, APR) with a brief expert note on each. Invite them to pick one for a deeper look. "+he+ft+j+(f.length>0?de:""),chain:o,resolvedAs:"token",token:{address:a,symbol:m},count:u.length,pools:u,...f.length>0?{actionButtons:f}:{}}}let d=await this.readPoolOnchain(o,a);if(d){let u=i?pe([d],e,T(o)):[];return{_instructions:me+"This address IS a real Uniswap V3 pool on-chain, but it is not covered by the market-data feed, so ONLY the on-chain facts below are available: the token pair, the fee tier, and the current price. State those plainly, then say clearly that TVL, volume and APR are not available for this pool. CRITICAL: do NOT invent, estimate, or infer TVL, volume, APR or any yield figure \u2014 you have none. A pool missing from the market-data feed is usually very new or very thinly traded; say so, and advise the user to check its liquidity depth carefully before providing liquidity. "+Y+j+(u.length>0?de:""),chain:o,resolvedAs:"pool",dataSource:"onchain-only",pool:d,...u.length>0?{actionButtons:u}:{}}}return{_instructions:`This address matched neither a pool nor a token on ${T(o)}. Tell the user plainly, in their language, that nothing was found for it on this network, and suggest they check the address or try another chain. NEVER invent pool or token data. Do NOT mention tools or APIs.`,chain:T(o),address:a,resolvedAs:null}}async readPoolOnchain(e,t){try{let r=await this.pool.readPoolOnchain(e,t),[o,s]=await on(e,[r.token0,r.token1]).catch(()=>[{symbol:null,decimals:null},{symbol:null,decimals:null}]),a=o?.symbol??void 0,i=s?.symbol??void 0,l=Ws(e,t);return{pair:a&&i?`${a}/${i}`:void 0,address:t,chain:e,protocolVersion:"V3",feeTierBps:r.fee,feeTierPercent:r.fee/1e4,currentPrice:r.currentPrice,token0:{symbol:a,address:r.token0},token1:{symbol:i,address:r.token1},...l?{uniswapUrl:l}:{}}}catch{return null}}};var My=1e3,Fy=365;function By(n,e){let t=e/100;return{depositUsd:n,aprPercent:e,dailyUsd:n*t/Fy,weeklyUsd:n*t/52,monthlyUsd:n*t/12,yearlyUsd:n*t}}var Ko=class extends A{name="defillama-estimate-pool-yield";description=`Estimate daily / weekly / monthly / yearly fee yield for a USD deposit into a Uniswap pool. Use for: "if I put $1000 into USDC/WETH how much do I earn per day?", "b\u1ECF 500$ v\xE0o pool n\xE0y l\u1EDDi bao nhi\xEAu?", "APR of the WBTC/ETH pool", "daily income for this pool". Call it IMMEDIATELY with whatever the user gave \u2014 it fills the gaps itself: \u2022 Only ONE token named \u2192 pass just token0Symbol; the tool auto-picks that token's highest-volume pool. \u2022 BOTH tokens but no fee tier AND several tiers exist \u2192 returns candidates (one per fee tier) to choose from. \u2022 No deposit amount \u2192 defaults to $1000 and marks the result as a per-$1000 example. Source: DefiLlama Yields. Supports: `+Ve();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:'Symbol of the first token, e.g. "USDC". Required.',required:!0},{name:"token1Symbol",type:"string",description:`Symbol of the second token, e.g. "WETH". Omit when the user named only one token \u2014 the tool then auto-picks that token's highest-volume pool rather than asking.`,required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.3%, 10000 = 1%. OMIT when the user has not mentioned one \u2014 the tool returns candidates if the pair has several tiers.",required:!1},{name:"depositUsd",type:"number",description:"The USD amount the user wants to deposit. OMIT when they did not say \u2014 the tool defaults to $1000 and labels the result a per-$1000 example. Do NOT ask the user for this up front.",required:!1},{name:"chain",type:"string",description:We,required:!1}];service;constructor(e){super(),this.service=new Me(e)}async run(e,t){let r=await te(He(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"";if(!s)return{_instructions:"No token was named. Ask the user which pool they want the yield estimate for, in their language. Do NOT mention tools or APIs."};let a=typeof e.token1Symbol=="string"&&e.token1Symbol.trim()?e.token1Symbol.trim():void 0,i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.round(e.feeTier):void 0,l=typeof e.depositUsd=="number"&&Number.isFinite(e.depositUsd)&&e.depositUsd>0,c=l?e.depositUsd:My,d=await this.service.getPoolsByPair({chain:o,token0Symbol:s,token1Symbol:a,feeTierBps:i});if(!d.success)return{_instructions:"Pool data could not be retrieved right now. Tell the user briefly, in their language, that pool data is temporarily unavailable and to try again shortly. Do NOT mention tools, APIs, or any internals.",error:d.error};let u=[s,a].filter(Boolean).join("/"),p=d.data??[];if(p.length===0)return{_instructions:"No pool matched that pair on this chain, so no yield can be estimated. Tell the user plainly, in their language, and suggest another chain or different tokens. NEVER invent an APR or an earnings figure. Do NOT mention tools or APIs.",chain:T(o),pair:u};let m=new Set(p.map(y=>y.feeTierBps).filter(y=>y!==void 0));if(a&&i===void 0&&m.size>1){let y=this.dedupeByFeeTier(p).slice(0,5);return{_instructions:`The ${u} pair has several fee tiers. Present them as a short numbered list (fee %, TVL, 24h volume, APR) and ask the user which one they mean. When they answer, call this tool again with the chosen feeTier \u2014 and pass along the original deposit amount if the user gave one. Do NOT estimate earnings yet, and do NOT merge the tiers into one figure. `+j,chain:o,pair:u,candidates:y.map(_e)}}let f=[...p].sort((y,w)=>(w.volume1DayUsd??0)-(y.volume1DayUsd??0)),h=f[0],g=a?f.length>1?`Auto-selected the highest-volume ${u} pool at this fee tier.`:void 0:`Auto-selected the highest-volume ${s} pool.`;if(h.apr===void 0)return{_instructions:"This pool has no APR reading, so earnings CANNOT be projected. Say so plainly in the user's language and show the TVL and 24h volume instead. CRITICAL: never invent, estimate, or infer an APR or an earnings figure. "+j,chain:o,pair:u,pool:_e(h),...g?{autoPickedReason:g}:{}};let b=By(c,h.apr);return{_instructions:(l?"Lead with: pool (pair + fee %), chain, APR %. Then show the projected earnings for the user's deposit \u2014 daily, weekly, monthly and yearly, in USD with 2 decimals. ":'IMPORTANT: the user did NOT specify a deposit amount \u2014 this result is a per-$1000 EXAMPLE. Lead with: pool (pair + fee %), chain, APR %. Then say "for every $1000 deposited you would earn approximately:" and list the daily / weekly / monthly / yearly figures in USD with 2 decimals. Afterwards you MAY invite the user to share their actual budget for a personalized number. ')+(g?'Mention naturally that this is the most active pool for that token (e.g. "the highest-volume USDC/WETH pool") \u2014 never say you "auto-picked" it. ':"")+"Note briefly that this projection assumes the current APR holds and that real returns vary with trading volume. "+Y+j,chain:o,pair:u,pool:_e(h),depositMode:l?"user-specified":"default-1000-example",estimate:b,...g?{autoPickedReason:g}:{}}}dedupeByFeeTier(e){let t=new Map;for(let r of e){if(r.feeTierBps===void 0)continue;let o=t.get(r.feeTierBps);(!o||r.tvlUsd>o.tvlUsd)&&t.set(r.feeTierBps,r)}return[...t.values()].sort((r,o)=>o.tvlUsd-r.tvlUsd)}};var jo=class{service;constructor(e){this.service=new Me(e)}async resolveCandidates(e){let t=e.protocolVersion==="ALL"?"ALL":"V3",r=await this.service.getPoolsByPair({chain:e.chain,token0Symbol:e.token0Symbol,token1Symbol:e.token1Symbol,feeTierBps:e.feeTier,protocolVersion:t});return r.success?(r.data??[]).filter(o=>o.protocolVersion==="V3"?o.address!==void 0:t==="ALL").map(o=>({id:o.address,protocolVersion:o.protocolVersion,feeTier:o.feeTierBps,token0:o.token0,token1:o.token1,tvlUsd:o.tvlUsd,volume1DayUsd:o.volume1DayUsd,apr:o.apr})):null}};function _t(n){if(typeof n=="number")return Number.isFinite(n)&&n>0?{kind:"token",value:n,raw:String(n)}:null;if(typeof n!="string")return null;let e=n.trim();if(!e)return null;if(/^(?:max(?:imum)?|all|everything|tất\s*cả|toàn\s*bộ)$/i.test(e))return{kind:"percent",percent:100,raw:e};let t=e.match(/^%?\s*([0-9]*\.?[0-9]+)\s*%$|^%\s*([0-9]*\.?[0-9]+)$/);if(t){let s=parseFloat(t[1]??t[2]);return Number.isFinite(s)&&s>0?{kind:"percent",percent:s,raw:e}:null}let r=e.match(/^\$\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*\$$|^(?:usd)\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*usd$/i);if(r){let s=parseFloat(r[1]??r[2]??r[3]??r[4]);return Number.isFinite(s)&&s>0?{kind:"usd",usd:s,raw:e}:null}let o=e.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(o){let s=parseFloat(o[1]);return Number.isFinite(s)&&s>0?{kind:"token",value:s,raw:e}:null}return null}function mp(n,e){switch(n.kind){case"token":return{ok:!0,amount:n.value};case"percent":return e.balance===void 0||!Number.isFinite(e.balance)||e.balance<=0?{ok:!1,reason:"no_balance"}:{ok:!0,amount:e.balance*n.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:n.usd/e.usdPrice}}}function er(n){let e=n?.trim();if(!e)return"";let t=T(e);return!t||t==="the requested chain"||t===e?"":` (${t})`}function Q(n){let e=er(n).trim();return e?` on ${e.slice(1,-1)}`:" on this chain"}var hp={send:30000n,swap:1000000n};async function qy(n){try{let e=await Re(n).getGasPrice();return e>0n?e:0n}catch{return 0n}}function fp(n,e){let t=hp[n],r=$y(e);return r!==null&&r>t?r:t}function $y(n){let e=n?.tx?.gas??n?.estimatedTransactionFee?.details?.gasLimit;if(e==null)return null;try{let t=typeof e=="bigint"?e:BigInt(e);return t>0n?t:null}catch{return null}}async function yc(n,e,t={}){let[r,o]=await Promise.all([qy(n),t.provider?wi({provider:t.provider,srcChainId:n,dstChainId:t.dstChainId??n}):Promise.resolve(0n)]);return(r>0n?fp(e,t.quoteGas)*r:0n)+o}async function Gs(n,e,t={}){return yc(n,e,t)}function Ks(n,e,t){if(e<=0n)return n;let r=Un(t)?.decimals;if(r===void 0)return n;let o=Number(e)/10**r;return!Number.isFinite(o)||o<=0?n:Math.max(0,n-o)}function bc(n,e){let t=Un(e)?.decimals;if(t===void 0)return null;let r=Number(n)/10**t;return Number.isFinite(r)?r:null}function gp(n){let{nativeBalance:e,feeWei:t,chainId:r}=n;if(t<=0n)return null;let o=bc(t,r);if(o===null||o<=0||!Number.isFinite(e)||e>o)return null;let s=Math.ceil(Math.max(0,o-e)*1e8)/1e8;return s>0?s:1e-8}async function js(n){let{chainId:e,gasKind:t,readNativeBalance:r,feeContext:o}=n;if(!e)return null;try{let[s,a]=await Promise.all([yc(e,t,o??{}),r()]),i=gp({nativeBalance:a?.balance??0,feeWei:s,chainId:e});return i===null?null:{shortfall:i,nativeSymbol:a?.symbol??Un(e)?.symbol??"the native coin",fee:bc(s,e)??0}}catch{return null}}var ot=class extends A{kind="ui";category="wallet-action";buildUI(e){let t={action:this.actionType,chainId:e.chainId,chainName:T(e.chainId),walletAddress:e.walletAddress,parameters:e.parameters};return{component:this.component,props:t}}userInputFields=[];moralis;constructor(e){super(),e!==void 0&&(this.moralis=new O(e))}async resolveContractAddress(e,t,r){if(!this.moralis||!e)return;let o=e.trim().toLowerCase(),s=R(e.trim()),a=l=>s?(l.token_address??"").toLowerCase()===o:(l.symbol??"").toLowerCase()===o;if(r){let l=await this.moralis.getWalletTokenBalances({address:r,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}parseDecimals(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isInteger(t)&&t>=0)return t}}async resolveTokenRef(e){let{contractArg:t,symbolArg:r,decimalsArg:o,chain:s,walletAddress:a}=e,i=this.parseDecimals(o),l=typeof r=="string"&&r.trim()?r.trim():void 0,c=this.normaliseAddress(t),d=typeof t=="string"&&t.trim()?t.trim():void 0,u=c??l??d;if(!u)return{token:void 0};let p=await this.resolveContractAddress(u,s,a);return p?{token:{address:p.address,symbol:p.symbolIsOnchain?p.symbol:l??p.symbol,name:p.name,decimals:i??p.decimals}}:c?{token:{address:c,symbol:l,decimals:i}}:{error:"token_not_found",key:u}}requireWallet(e){let t=e?.walletAddress;return t?{ok:!0,address:t}:{ok:!1,payload:{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before submitting the action. Do NOT render the form."}}}requireChain(e,t){return K(e.chain,t)}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return R(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let r=parseFloat(t);return Number.isFinite(r)&&r>0?t:null}async resolveAmountInput(e){let{rawAmount:t,tokenAddress:r,chain:o,walletAddress:s,gasKind:a}=e,i=_t(t);if(!i)return null;let l=e.symbol??"the token",c=r.toLowerCase()==="native",d=!!a&&c&&!!o;if(i.kind==="token")return{amount:this.toPlainDecimal(i.value)};let u=await this.readTokenBalanceAndPrice(r,o,s),p=u?.balance;d&&u?.balance!==void 0&&(p=await this.computeNativeSpendable(o,a,u.balance));let m=mp(i,{balance:p,usdPrice:u?.usdPrice});return m.ok?{amount:this.toPlainDecimal(m.amount)}:m.reason==="no_balance"?{error:"amount_balance_unavailable",chain:o,_instructions:`Could not read the user's ${l} balance${Q(o)} to work out ${i.raw} right now. Tell them, in their language, that the balance couldn't be fetched at the moment and ask them to enter an exact ${l} amount instead. Do NOT invent a balance or amount. Do NOT mention tool names, UI, or forms.`}:{error:"amount_price_unavailable",chain:o,_instructions:`Could not get a USD price for ${l}${Q(o)} to work out ${i.raw} right now. Tell them, in their language, that the price couldn't be fetched at the moment and ask them to enter an exact ${l} amount instead. Do NOT invent a price or amount. Do NOT mention tool names, UI, or forms.`}}async computeNativeSpendable(e,t,r){let o=await Gs(e,t);return Ks(r,o,e)}async resolveNativeSpendableFormatted(e,t,r){if(!(!e||!t))try{let o=await this.readTokenBalanceAndPrice("native",e,t);if(o?.balance===void 0)return;let s=await this.computeNativeSpendable(e,r,o.balance);return this.toPlainDecimal(s)}catch{return}}async readTokenBalanceAndPrice(e,t,r){if(!this.moralis||!r)return;let o=await this.moralis.getWalletTokenBalances({address:r,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=o.success?o.data?.result??[]:[],a=e.toLowerCase()==="native",i=e.toLowerCase(),l=s.find(d=>a?d.native_token===!0:(d.token_address??"").toLowerCase()===i);if(!l)return;let c=l.balance_formatted!=null?Number(l.balance_formatted):void 0;return{balance:Number.isFinite(c)?c:void 0,usdPrice:typeof l.usd_price=="number"&&l.usd_price>0?l.usd_price:void 0,balanceFormatted:l.balance_formatted,symbol:l.symbol}}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let r=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.split("."),c=i+l,d;if(a>=0){let u=i.length+a;d=u>=c.length?c.padEnd(u,"0"):`${c.slice(0,u)}.${c.slice(u)}`}else d=`0.${"0".repeat(-a-i.length)}${c}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),r?`-${d}`:d}formatSpendableUsd(e,t){if(e===void 0||t===void 0)return;let r=Number(e);if(!Number.isFinite(r)||!Number.isFinite(t)||t<=0)return;let o=r*t;if(!(!Number.isFinite(o)||o<=0))return this.toPlainDecimal(o)}async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:r,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let r=this.requireWallet(t);if(!r.ok)return r.payload;let o=this.requireChain(e,t);if(!o){let h=typeof t?.query=="string"?t.query:void 0;return Fr(this.actionType.replace(/_/g," "),h)}let s=await this.buildParameters(e,t);if(s&&typeof s=="object"&&"error"in s&&typeof s.error=="string"||s&&typeof s=="object"&&"actionButtons"in s&&Array.isArray(s.actionButtons)||s&&typeof s=="object"&&"ui"in s&&s.ui&&typeof s.ui=="object"&&typeof s.ui.component=="string")return s;let a=s,i=this.buildUI({parameters:a,chainId:o,walletAddress:r.address}),l=h=>{let g=a[h];return g!=null&&g!==""},c=this.userInputFields.filter(h=>!(Array.isArray(h.key)?h.key:[h.key]).some(l)).map(h=>h.label),d=this.userInputFields.map(h=>{let b=(Array.isArray(h.key)?h.key:[h.key]).find(l);return b?`${h.label}: ${a[b]}`:null}).filter(h=>h!=null),u=this.actionType.replace(/_/g," "),p='NEVER invent, guess, or insert a placeholder (e.g. "[recipient address]") for any detail the user has not actually provided \u2014 only state values listed as already provided. Do NOT mention tool names, UI, or forms.',m="The user completes this themselves and it is submitted right away \u2014 do NOT ask them to reply to confirm, do NOT say you will send it for them, and do NOT announce the result. This turn ends after your message.",f=c.length>0?`The ${u} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${c.join(", ")}. `+(d.length>0?`Already provided: ${d.join("; ")}. `:"")+`${m} ${p}`:`The ${u} has all required details. In the user's language, briefly tell the user to review the details and submit to complete the ${u}. `+(d.length>0?`Details provided: ${d.join("; ")}. `:"")+`${m} ${p}`;return{ui:i,action:this.actionType,chainId:o,parameters:a,_instructions:f}}};var zo=class extends ot{name="open-send-native-form";actionType="send_native";component="SendNativeForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}async run(e,t){if(e.chain==null||e.chain===""){let r=Uu(e.native_symbol);if(r)return super.run({...e,chain:r},t)}return super.run(e,t)}description=`Open the SEND NATIVE form for the chain's native coin (ETH/BNB/MATIC/AVAX/\u2026). Use for ANY native-send intent: "send eth", "send 0.1 ETH", "transfer 1 BNB to vitalik.eth", "g\u1EEDi ETH". Call EVEN IF the user did not name an amount or recipient \u2014 the form prompts for them. Do NOT use for ERC-20 tokens \u2014 use open-send-token-form instead.`;parameters=[{name:"chain",type:"string",description:Ze,required:!1},{name:"native_symbol",type:"string",description:'The native coin the user named to send, VERBATIM (e.g. "ETH", "BNB", "MATIC", "AVAX"). ALWAYS set this when the user names the coin ("send bnb" \u2192 native_symbol="BNB"); leave blank only when they say just "send" with no coin. A coin that belongs to one specific chain (BNB\u2192BSC, MATIC/POL\u2192Polygon, AVAX\u2192Avalanche, XDAI\u2192Gnosis, HYPE\u2192HyperEVM, MNT\u2192Mantle, MON\u2192Monad) selects that chain, so the tool can detect when the wallet is connected elsewhere.',required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Amount of native coin to send. Accepted forms: a plain amount ("0.1"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become the literal "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself (and for the native coin always leaves enough to cover the network fee). Omit when unknown.',required:!1}];async buildParameters(e,t){let r={},o=this.requireChain(e,t)??void 0,s=t?.walletAddress??void 0,a=await this.readTokenBalanceAndPrice("native",o,s);if(!a||a.balance==null||a.balance<=0){let u=typeof e.native_symbol=="string"&&e.native_symbol.trim()?e.native_symbol.trim():void 0,p=a?.symbol||u||Fa(o)||"their native coin";return{error:"no_native_balance",chain:o,_instructions:`The user wants to send ${p} but their wallet holds 0 ${p}${Q(o)}. Tell them, in their language, that they do not have any ${p} to send${Q(o)} \u2014 name that network explicitly so they know which one is empty \u2014 and suggest they top up first. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}let i=a.symbol||(typeof e.native_symbol=="string"&&e.native_symbol.trim()?e.native_symbol.trim():void 0);if(i&&(r.native_symbol=i),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?r.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(r.to_address=e.to_address.trim())}let l=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:"native",symbol:"the native coin",chain:o,walletAddress:s,gasKind:"send"});if(l&&"error"in l)return l;l&&(r.amount=l.amount);let c=await this.resolveNativeSpendableFormatted(o,s,"send");c!==void 0&&(r.spendable=c);let d=this.formatSpendableUsd(c,a.usdPrice);return d!==void 0&&(r.spendableUsd=d),r}};var Xo=class extends ot{name="open-send-token-form";actionType="send_token";component="SendTokenForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}description=`Open the SEND TOKEN (ERC-20) form. Use for ANY ERC-20 send/transfer intent: "send token", "send USDC", "transfer 50 DAI to 0x\u2026", "g\u1EEDi 10 USDT". Call this tool EVEN IF the user did not name a token, amount, or recipient \u2014 the tool handles missing token via a picker, the form prompts for the rest. Do NOT use for the chain's native coin (ETH/BNB/MATIC/AVAX) \u2014 use open-send-native-form instead.`;parameters=[{name:"chain",type:"string",description:Ze,required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol \u2014 the tool will look up the address.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). ALWAYS set this whenever the user names a token to send ("send usdc" \u2192 token_symbol="USDC"); only leave it blank when the user names NO token at all ("send token"), so the tool can show a wallet picker. Used to auto-resolve the contract address and to display the symbol in the form. (Pass either this or contract_address.)',required:!1},{name:"decimals",type:"number",description:"Token decimals (e.g. 6 for USDC, 18 for most ERC-20s). Optional.",required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown.",required:!1},{name:"amount",type:"string",description:'Amount of the token to send. Accepted forms: a plain amount ("100"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself. Omit when unknown.',required:!1},{name:"send_prompt_template",type:"string",description:`A short imperative "send" command IN THE USER'S LANGUAGE, used as the label/command when the user has not yet picked which token to send (token-picker buttons). Write it in the SAME language the user is using right now. Use these exact placeholders (do not translate the braces): "{symbol}" for the token, "{amount}" for the amount, "{to}" for the recipient address, "{chain}" for the chain name. Put the localized verb, the "to" preposition, and the "on <chain>" preposition directly in the text. English example: "send {amount} {symbol} to {to} on {chain}". Vietnamese example: "g\u1EEDi {amount} {symbol} \u0111\u1EBFn {to} tr\xEAn {chain}". Japanese example: "{chain} \u3067 {to} \u306B {amount} {symbol} \u3092\u9001\u308B". Always include {symbol}. Include {amount}/{to}/{chain} too \u2014 the tool removes any whose value is unknown.`,required:!0}];async buildParameters(e,t){let r=this.normaliseAddress(e.contract_address)!=null,o=typeof e.token_symbol=="string"&&e.token_symbol.trim().length>0;if(!r&&!o&&this.moralis){let u=this.requireChain(e,t)??void 0,p=t?.walletAddress;if(p){let m=await this.moralis.getWalletTokenBalances({address:p,chain:u,excludeSpam:!1,excludeUnverifiedContracts:!1}),h=(m.success?m.data?.result??[]:[]).filter(v=>v.symbol&&(v.native_token||v.token_address)).sort((v,S)=>(S.usd_value??0)-(v.usd_value??0)).slice(0,8);if(h.length===0)return{error:"no_token_holdings",chain:u,_instructions:`The wallet does not hold any sendable tokens${Q(u)}. Tell the user they have nothing to send${Q(u)}, naming that network explicitly, and suggest they top up first. Do NOT open the form.`};let g=e.to_address!=null?this.normaliseAddress(e.to_address):null,b=this.normaliseAmount(e.amount),y=typeof e.send_prompt_template=="string"?e.send_prompt_template:"",w=u?T(u):null;return{actionButtons:h.map(v=>{let S=v.symbol,P=v.balance_formatted?this.cleanAmountString(v.balance_formatted):"",x=v.name?v.name:"",I=v.usd_value?`($${v.usd_value.toFixed(2)})`:"";return{label:`${x}:${P} ${S} ${I}`.trim(),prompt:this.buildSendPrompt(y,S,b,g,w)}}),_instructions:"Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n g\u1EEDi token.' / 'You want to send a token.'), then ask them to choose which token from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n g\u1EEDi.' / 'Please choose the token you want to send.'). Do NOT list the tokens in text \u2014 the options already show them. Do NOT mention tool names, UI, or forms."}}}let s=this.requireChain(e,t)??void 0,a=t?.walletAddress??void 0,i=await this.findOwnedTokenForSend(e,s,a);if(i&&"error"in i)return i;let l=i?.token,c={};l?.address&&(c.contract_address=l.address),l?.symbol&&(c.token_symbol=l.symbol),l?.decimals!==void 0&&(c.decimals=String(l.decimals)),i?.spendable!==void 0&&(c.spendable=i.spendable);let d=this.formatSpendableUsd(i?.spendable,i?.usdPrice);if(d!==void 0&&(c.spendableUsd=d),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?c.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(c.to_address=e.to_address.trim())}if(l?.address){let u=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:l.address,symbol:l.symbol,chain:s,walletAddress:a});if(u&&"error"in u)return u;u&&(c.amount=u.amount)}else{let u=this.normaliseAmount(e.amount);u&&(c.amount=u)}return c}async findOwnedTokenForSend(e,t,r){let o=this.normaliseAddress(e.contract_address),s=typeof e.token_symbol=="string"&&e.token_symbol.trim()?e.token_symbol.trim():void 0,a=o??s;if(!this.moralis||!r||!a){let m=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:t,walletAddress:r});return"error"in m?{error:"token_not_found",symbol:m.key,_instructions:`Could not resolve token "${m.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`}:{token:m.token}}let i=a.toLowerCase(),l=o!=null,c=await this.moralis.getWalletTokenBalances({address:r,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),u=(c.success?c.data?.result??[]:[]).find(m=>l?(m.token_address??"").toLowerCase()===i:(m.symbol??"").toLowerCase()===i);if(u&&u.balance&&!/^0*$/.test(u.balance.trim())){let m=this.parseDecimals(e.decimals);return{token:{address:u.token_address,symbol:u.symbol??s,name:u.name,decimals:m??(typeof u.decimals=="number"?u.decimals:void 0)},spendable:u.balance_formatted?this.cleanAmountString(u.balance_formatted):void 0,usdPrice:typeof u.usd_price=="number"&&u.usd_price>0?u.usd_price:void 0}}let p=u?.symbol??s??a;return{error:"no_balance",symbol:p,chain:t,_instructions:`The user does not hold any ${p} in their wallet${Q(t)}, so there is nothing to send. Tell them (in their language) that they don't have any ${p} to send${Q(t)} \u2014 name that network explicitly so they know which one is empty \u2014 and suggest they top up or pick another token. Do NOT open a form. Do NOT mention tool names, UI, or forms.`}}buildSendPrompt(e,t,r,o,s){let i=(e&&e.includes("{symbol}")?e:"send {amount} {symbol} to {to} on {chain}").replace(/\{symbol\}/g,t).replace(/\{amount\}/g,r??"");return i=this.fillOrDropPhrase(i,"{to}",o),i=this.fillOrDropPhrase(i,"{chain}",s),i.replace(/\s+/g," ").trim()}fillOrDropPhrase(e,t,r){if(r)return e.split(t).join(r);let o=t.replace(/[{}]/g,"\\$&");return e.replace(new RegExp(`\\s*\\S+\\s*${o}`,"g"),"").replace(new RegExp(`${o}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(o,"g"),"")}};var Qo=class extends ot{name="open-approve-token-form";actionType="approve_token";component="ApproveTokenForm";userInputFields=[{key:"spender_address",label:"the spender address to approve"}];constructor(e){super(e)}description='Open the APPROVE TOKEN form so the user can grant a spender allowance on an ERC-20 token. Use when the user says "approve USDC for Uniswap", "c\u1EA5p quy\u1EC1n 100 USDT cho 0x\u2026", "revoke approval". Pass `contract_address` when you have it; otherwise pass `token_symbol` (e.g. "USDC") and the tool auto-resolves the contract. Always pass `spender_address` (the contract being approved). Pass `amount` for a specific allowance; omit for unlimited (max uint256). For approving 0 to revoke, pass amount="0".';parameters=[{name:"chain",type:"string",description:Ze,required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). Required when contract_address is not given. Used to auto-resolve the contract.',required:!1},{name:"decimals",type:"number",description:"Token decimals.",required:!1},{name:"spender_address",type:"string",description:"EVM address of the spender contract being approved (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Human-readable allowance amount. Omit for UNLIMITED (max uint256). Pass "0" to revoke.',required:!1}];async buildParameters(e,t){let r=this.requireChain(e,t)??void 0,o=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:r,walletAddress:t?.walletAddress??void 0});if("error"in o)return{error:"token_not_found",symbol:o.key,_instructions:`Could not resolve token "${o.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`};let s=o.token,a=this.normaliseAddress(e.spender_address),i={};if(s?.address&&(i.contract_address=s.address),a&&(i.spender_address=a),s?.symbol&&(i.token_symbol=s.symbol),s?.decimals!==void 0&&(i.decimals=String(s.decimals)),typeof e.amount=="string"&&e.amount.trim()){let l=e.amount.trim(),c=parseFloat(l);Number.isFinite(c)&&c>=0&&(i.amount=l)}else typeof e.amount=="number"&&Number.isFinite(e.amount)&&e.amount>=0&&(i.amount=String(e.amount));return i}};function Ai(n){let{action:e,fromSym:t,toSym:r,amount:o,spendable:s}=n,a=e==="swap"?`swap ${t} to ${r}`:`buy ${r} with ${t}`,i=e==="swap"?"swapping":"buying",l=e==="swap"?`swap ${o} ${t} to ${r}`:`buy ${r} with ${o} ${t}`,c=s?` They have ${s} ${t} available to spend.`:"";return(o?`The user wants to ${l}.${c} Reply briefly in the user's language confirming the amount and asking them to review and complete it. `:`The user wants to ${a}.${c} Reply briefly in the user's language: state what they want to do${s?" and their available balance":""}, then ask how much they want to ${e}. `)+`Do NOT list amounts or percentages, and do NOT state an estimated receive amount or a rate \u2014 you do not have one. Speak only of the user's action (${i}) \u2014 NEVER say you 'opened' a panel/form/window or describe any UI being shown. NEVER invent numbers not provided here. Do NOT mention tool names, UI, buttons, or forms.`}var qt=n=>n.logo||n.icon_image||n.logoURI||n.thumbnail||void 0,wc=n=>typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0;async function zs(n){let{moralis:e,tokenAddress:t,chain:r}=n;if(!e)return null;let o=t==="native"?ue:t;try{let s=await e.getTokenMetadata({address:o,chain:r});return wc(s.success?s.data?.usd_price:void 0)??null}catch{return null}}var Hy=n=>Number.isFinite(n)?vs(parseFloat(n.toPrecision(8))):"0",Vy=n=>{if(!/e/i.test(n))return n;let e=Number(n);return Number.isFinite(e)?vs(e):n};async function Xs(n){let{moralis:e,walletAddress:t,tokenAddress:r,chain:o,kind:s="swap",feeContext:a,dbg:i}=n;if(!e)return null;let l=await e.getWalletTokenBalances({address:t,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1}),c=l.success?l.data?.result??[]:[];i?.("readSpendableBalance",{tokenAddress:r,chain:o,ok:l.success,count:c.length});let d=r.toLowerCase(),u=c.find(m=>d==="native"?m.native_token===!0:m.token_address?.toLowerCase()===d);if(!u?.balance_formatted)return i?.("readSpendableBalance: token NOT held \u2192 null",{tokenAddress:r}),null;let p=Number(u.balance_formatted);if(!Number.isFinite(p)||p<=0)return i?.("readSpendableBalance: zero/invalid balance \u2192 null",{tokenAddress:r,balance:u.balance_formatted}),null;if(d==="native"&&o){let m=await Gs(o,s,a??{}),f=Ks(p,m,o);if(i?.("readSpendableBalance: native spendable",{balanceNum:p,spendable:f}),f<=0)return i?.("readSpendableBalance: native spendable \u2264 0 \u2192 null",{balanceNum:p}),null;let h=Hy(f),g=typeof u.decimals=="number"?u.decimals:18;return yp({balanceFormatted:h,balanceNum:f,symbol:u.symbol,decimals:g,logo:qt(u),usdPrice:wc(u.usd_price)})}return i?.("readSpendableBalance: held",{tokenAddress:r,balance:u.balance_formatted,symbol:u.symbol}),yp({balanceFormatted:u.balance_formatted,balanceNum:p,symbol:u.symbol,decimals:typeof u.decimals=="number"?u.decimals:void 0,logo:qt(u),usdPrice:wc(u.usd_price)})}function yp(n){let e=Vy(n.balanceFormatted),t=n.decimals===void 0?null:Bn(e,n.decimals);return{...n,balanceFormatted:e,rawAmount:t?.toString()}}async function Pi(n,e){let t=n?Ce(n)?.nativeCurrency:void 0,r=e.map(a=>a&&(a.address==="native"?{...a,symbol:t?.symbol??a.symbol,decimals:t?.decimals??a.decimals,symbolIsOnchain:t?.symbol?!0:a.symbolIsOnchain??!1}:{...a})),o=[];if(r.forEach((a,i)=>{if(!a||a.address==="native"||!R(a.address))return;let l=a.symbolIsOnchain===!0&&!!a.symbol?.trim(),c=typeof a.decimals=="number"&&Number.isFinite(a.decimals);l&&c||o.push({index:i,address:a.address})}),!n||o.length===0)return r;let s=await on(n,o.map(a=>a.address)).catch(()=>[]);return o.forEach((a,i)=>{let l=s[i];if(!l)return;let c=r[a.index];typeof l.symbol=="string"&&l.symbol.trim()&&(c.symbol=l.symbol.trim(),c.symbolIsOnchain=!0),typeof l.decimals=="number"&&Number.isFinite(l.decimals)&&(c.decimals=l.decimals)}),r}function Si(n,e){let t=n?.trim().toLowerCase(),r=e?.trim().toLowerCase();return!t||!r?!1:t===r}var Jo=class extends A{name="open-buy-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new O(e),this.pantograph=new Ae({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[BuyTokenTool] ${e}`):console.log(`[BuyTokenTool] ${e}`,JSON.stringify(t)))}description='Open the BUY TOKEN flow for ANY buy/purchase intent. Handles both cases: (a) the user NAMED a token \u2014 "buy PEPE", "mua DOGE", "buy 100 USDC with ETH": pass `token_symbol` (the destination); if you also know the pay token, fill `pay_with_symbol` (or `pay_with_address`), else leave pay_with_* blank and the tool returns a wallet picker. (b) the user did NOT name a token \u2014 "buy a trending token", "mua token trending", "buy something pumping", "buy hot tokens", "mua token t\u0103ng m\u1EA1nh": leave `token_symbol` blank and the tool returns buttons of the chain\'s current trending tokens so the user picks one. Amount: `buy_amount` = destination to RECEIVE; `pay_with_amount` = payment to SPEND. Never both. CHAINS: when the user names a DIFFERENT network per side \u2014 "buy USDC on Base with ETH on Arbitrum" \u2014 you MUST put each one in `token_chain` and `pay_with_chain` (NOT in `chain`, and never drop one of them): that is a cross-chain request and the tool answers it with the correct unsupported message. Use the single `chain` parameter only when ONE network covers the whole request.';parameters=[{name:"chain",type:"string",description:Ze,required:!1},{name:"token_chain",type:"string",description:Mr("token being BOUGHT"),required:!1},{name:"pay_with_chain",type:"string",description:Mr("token being SPENT to pay"),required:!1},{name:"token_symbol",type:"string",description:'Symbol of the token the user wants to BUY (e.g. "PEPE"). Leave EMPTY when the user did not name a token (e.g. "buy a trending token") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"contract_address",type:"string",description:`Destination token address (0x\u2026), or "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from token_symbol.`,required:!1},{name:"buy_amount",type:"string",description:`Quantity of the DESTINATION token (the one being bought) the user wants to RECEIVE. Set this when the amount sits next to the token being bought: "buy 5 PEPE", "mua 5 PEPE", "buy 0.02 PCM with USDC" \u2192 buy_amount = the number next to PEPE/PCM. May also be a USD value when the user sizes the buy in dollars ("buy $5 of PEPE" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$" to a token quantity). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with pay_with_amount \u2014 set at most ONE of the two.`,required:!1},{name:"pay_with_symbol",type:"string",description:'Symbol of the payment token (e.g. "USDC", "ETH"). Set ONLY when the user actually named a token to pay with. Leave EMPTY when they did not \u2014 do NOT default to the native coin / ETH; the tool then returns a picker of the tokens the wallet holds.',required:!1},{name:"pay_with_address",type:"string",description:`Address of the payment token (0x\u2026), OR "native" for the chain's native coin. Set ONLY when the user named the payment token. Leave EMPTY when they did not \u2014 do NOT invent an address or default to native.`,required:!1},{name:"pay_with_amount",type:"string",description:'Quantity of the PAYMENT token (the one being spent) the user wants to SPEND. Set this when the amount sits next to the payment token: "buy PEPE with 10 USDC", "mua PEPE b\u1EB1ng 10 USDC", "spend 0.5 ETH on DOGE" \u2192 pay_with_amount = the number next to USDC/ETH. May also be a PERCENT of the pay-token balance ("buy USDC with 50% USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("buy USDC with 5$ USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set pay_with_symbol to the payment token ("ETH" in "buy USDC with max ETH"). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with buy_amount \u2014 set at most ONE of the two.',required:!1},{name:"limit",type:"number",description:"Only used when no token is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the trending-token picker (when the user named no token). Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}. Do NOT write the chain name yourself \u2014 the chain these tokens are on is appended automatically as a "(<chain>)" suffix, e.g. "buy PEPE (Base)".`,required:!0},{name:"buy_with_prompt_template",type:"string",description:`A short "buy X with Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the pay-token picker and the percentage-spend buttons. Use these exact placeholders (do not translate the braces): "{token}" = token being bought, "{pay}" = payment token, "{buy_amount}" = quantity of the BOUGHT token (place it next to {token}), "{pay_amount}" = quantity of the PAYMENT token (place it next to {pay}). Put the localized verb and the "with" preposition directly in the text. English example: "buy {buy_amount} {token} with {pay_amount} {pay}". Vietnamese example: "mua {buy_amount} {token} b\u1EB1ng {pay_amount} {pay}". Japanese example: "{pay_amount} {pay} \u3067 {buy_amount} {token} \u8CFC\u5165". Always include {token} and {pay}. Include both {buy_amount} and {pay_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount). Do NOT write the chain name yourself \u2014 the chain is appended automatically as a "(<chain>)" suffix, e.g. "buy PEPE with ETH (Base)".`,required:!0}];async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:r,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before buying. Do NOT proceed."};let o=Ba(e.pay_with_chain,e.token_chain);if(o)return qa("buy",o);if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return Fr("buy",a)}return this.buildResult(e,t)}async buildResult(e,t){this.correctAmountSide(e,t),this.dropUnmentionedPayToken(e,t),this.dropInventedAmounts(e,t);let r=typeof e.token_symbol=="string"?e.token_symbol.trim():"",o=typeof e.contract_address=="string"?e.contract_address.trim():"",s=this.requireChain(e,t)??void 0,a=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:s,walletAddress:a,hasMoralis:!!this.moralis}),!r&&!o)return this.dbg("\u2192 Branch 0: trending picker (no token named)"),await this.buildTrendingPicker(e,t);let[i,l]=await Promise.all([this.resolveSide(e.contract_address,r,s,a,"dest"),this.resolveSide(e.pay_with_address,e.pay_with_symbol,s,a,"pay")]),[c,d]=await Pi(s,[i.address?{...i,address:i.address}:void 0,l.address?{...l,address:l.address}:void 0]),u=i.address,p=c?.symbol??r,m=c?.decimals,f=i.logo,h=l.address,g=d?.symbol,b=d?.decimals,y=await this.resolveBuyAmountSpec(e.buy_amount,u,s,p),w=h?await this.resolvePayAmountSpec(e.pay_with_amount,h,s,a,g,b??(h==="native"?18:void 0)):this.normaliseAmount(e.pay_with_amount),k=_t(e.pay_with_amount),v=!!k&&k.kind!=="token",S=null;if(this.dbg("resolved sides",{dest:{destContract:u,destSymbol:p,destDecimals:m},pay:{payAddr:h,paySymbol:g,payDecimals:b},buyAmount:y,payAmount:w}),!u)return this.dbg("\u2192 dest token not resolved"),{error:"dest_token_not_found",_instructions:`Could not find the token "${p||o}" to buy on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(Si(h,u))return this.dbg("\u2192 same token both sides",{payAddr:h,destContract:u,paySymbol:g,destSymbol:p}),{error:"same_token",_instructions:`The user asked to buy ${p} and pay with ${g??p} \u2014 the SAME token on both sides, which buys nothing and cannot be done. Tell them, in their language, that the token they pay with has to be different from the token they are buying, and ask which token they want to pay with instead. Do NOT proceed. Do NOT render the form. Do NOT mention tool names, UI, or forms.`};if(!h&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: pay picker (pay token missing)"),await this.buildPayWithPicker({args:e,userContext:t,destSymbol:p,destContract:u,buyAmount:y,payAmount:w});if(!h)return{error:"pay_token_missing",_instructions:`Ask the user, in their language, which token they want to spend to buy ${p}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(y&&!w){this.dbg("Branch 1.3: deriving pay amount from buy amount",{buyAmount:y,destSymbol:p,paySymbol:g});let P=await this.derivePayAmountFromBuy({chain:s,buyAmount:y,destContract:u,destSymbol:p,payAddr:h,paySymbol:g});if(!P)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs pay amount"),{error:"needs_pay_amount",_instructions:`Could not work out how much ${g??"of the payment token"} equals ${y} ${p} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${g??"of the payment token"} they want to spend instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};w=P,S=y,v=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:w,derivedFromBuy:S})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking pay balance",{payAddr:h,paySymbol:g,payAmount:w});let P=await this.checkPayBalance({args:e,userContext:t,chain:s,destSymbol:p,destContract:u,payAddr:h,paySymbol:g,payAmount:w,buyAmount:y,derivedFromBuy:S,amountSizedToBalance:v});if(P)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:P.error,hasButtons:Array.isArray(P.actionButtons)}),P;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!y&&t?.walletAddress){this.dbg("Branch 1.5: building amount form",{payAmount:w});let P=await this.buildAmountForm({userContext:t,chain:s,destContract:u,destSymbol:p,destDecimals:m,destLogo:f,payAddr:h,paySymbol:g,payDecimals:b,payAmount:w??void 0});if(P)return this.dbg("\u2192 Branch 1.5: amount form returned"),P;this.dbg("Branch 1.5: amount form null \u2014 needs a resolvable pay token")}return this.dbg("\u2192 needs pay amount"),{error:"needs_pay_amount",_instructions:`Ask the user, in their language, how much ${g??"of the payment token"} they want to spend to buy ${p}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return R(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let r=t.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(!r)return null;let o=parseFloat(r[1]);return Number.isFinite(o)&&o>0?r[1]:null}correctAmountSide(e,t){let r=typeof t?.query=="string"?t.query:"",o=typeof e.token_symbol=="string"?e.token_symbol.trim():"",s=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"";if(!r||!o||!s)return;let a=typeof e.buy_amount=="string"?e.buy_amount.trim():"",i=typeof e.pay_with_amount=="string"?e.pay_with_amount.trim():"",l=a.length>0,c=i.length>0;if(l===c)return;let d=l?a:i,u=d.match(/[0-9]*\.?[0-9]+/)?.[0];if(!u)return;let p=this.nearestSymbolSide(r,u,o,s);p&&(p==="pay"&&l?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:d,buySym:o,paySym:s}),e.pay_with_amount=d,e.buy_amount=""):p==="buy"&&c&&(this.dbg("correctAmountSide: pay_with_amount \u2192 buy_amount",{amount:d,buySym:o,paySym:s}),e.buy_amount=d,e.pay_with_amount=""))}dropUnmentionedPayToken(e,t){let r=typeof t?.query=="string"?t.query:"";if(!r)return;let o=typeof e.token_symbol=="string"?e.token_symbol.trim():"";if(!o)return;let s=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"",a=typeof e.pay_with_address=="string"?e.pay_with_address.trim():"";if(!s&&!a)return;let i=r.toLowerCase(),l=s.toLowerCase(),c=a.toLowerCase(),d=l==="native"||c==="native",u=[];if(s&&l!=="native"&&u.push(l),c&&c!=="native"&&u.push(c),d){u.push("native");let m=this.requireChain(e,t)??void 0,f=m?Un(m)?.symbol:void 0;f&&u.push(f.toLowerCase())}u.some(m=>R(m)?i.includes(m):this.indexOfToken(i,m)>=0)||(this.dbg("dropUnmentionedPayToken: clearing invented pay token",{paySym:s,payAddr:a,buySym:o}),e.pay_with_symbol="",e.pay_with_address="")}dropInventedAmounts(e,t){let r=typeof t?.query=="string"?t.query:"";if(!r)return;let o=(r.match(/[0-9]*\.?[0-9]+/g)??[]).map(parseFloat).filter(Number.isFinite),s=a=>{let i=typeof e[a]=="string"?e[a].trim():"";if(!i)return;let l=i.match(/[0-9]*\.?[0-9]+/)?.[0];if(l===void 0)return;let c=parseFloat(l);Number.isFinite(c)&&(o.some(d=>d===c)||(this.dbg(`dropInventedAmounts: clearing invented ${a}`,{val:i}),e[a]=""))};s("buy_amount"),s("pay_with_amount")}nearestSymbolSide(e,t,r,o){let s=e.toLowerCase(),a=s.indexOf(t.toLowerCase()),i=this.indexOfToken(s,r.toLowerCase()),l=this.indexOfToken(s,o.toLowerCase());if(a<0||i<0||l<0)return null;let c=(p,m)=>Math.max(0,p-(a+t.length),a-(p+m)),d=c(i,r.length),u=c(l,o.length);return u===d?null:u<d?"pay":"buy"}indexOfToken(e,t){if(!t)return-1;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=e.match(new RegExp(`(?:^|[^a-z0-9])(${r})(?:[^a-z0-9]|$)`));return o&&o.index!==void 0?o.index+o[0].indexOf(o[1]):-1}requireChain(e,t){return K(e.chain,t)}async resolveContractAddress(e,t,r){if(!this.moralis||!e)return;let o=e.trim().toLowerCase(),s=R(e.trim()),a=l=>s?(l.token_address??"").toLowerCase()===o:(l.symbol??"").toLowerCase()===o;if(r){let l=await this.moralis.getWalletTokenBalances({address:r,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:qt(c)}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:qt(c),symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}async resolveSide(e,t,r,o,s="side"){let a=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(a.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,d=m=>m.toLowerCase()===ue?"native":m,u=l??c??(a||void 0);if(!u)return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(u,r,o);return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,key:u,lookup:p}),p?{address:d(p.address),symbol:p.symbolIsOnchain?p.symbol:c??p.symbol,decimals:p.decimals,logo:p.logo,symbolIsOnchain:p.symbolIsOnchain??!1}:l?{address:d(l),symbol:c}:{address:null,symbol:c}}async derivePayAmountFromBuy(e){let{chain:t,buyAmount:r,destContract:o,payAddr:s}=e,[a,i]=await Promise.all([this.getUsdPrice(o,t),this.getUsdPrice(s,t)]);if(this.dbg("derivePayAmountFromBuy: prices",{destPrice:a,payPrice:i}),!a||!i)return null;let l=Number(r);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,d=l*a/i;return!Number.isFinite(d)||d<=0?null:this.trimAmount(d*c)}async getUsdPrice(e,t){return zs({moralis:this.moralis,tokenAddress:e,chain:t})}async resolvePayAmountSpec(e,t,r,o,s,a){let i=_t(e);if(!i)return null;let l=d=>a===void 0?d:Dt(d,a);if(i.kind==="token")return l(qn(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!o)return null;let d=await this.readPayBalance(o,t,r);if(this.dbg("resolvePayAmountSpec: percent",{percent:i.percent,paySymbol:s,bal:d?.balanceNum}),!d||!Number.isFinite(d.balanceNum)||d.balanceNum<=0)return null;let u=d.decimals??a??18;return i.percent>=100?this.cleanAmountString(d.balanceFormatted):$n(d.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,u)}let c=await this.getUsdPrice(t,r);return this.dbg("resolvePayAmountSpec: usd",{usd:i.usd,paySymbol:s,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveBuyAmountSpec(e,t,r,o){let s=_t(e);if(!s)return null;if(s.kind==="token")return qn(e)??this.toPlainDecimal(s.value);if(s.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,r);return this.dbg("resolveBuyAmountSpec: usd",{usd:s.usd,destSymbol:o,price:a}),a?this.trimAmount(s.usd/a):null}async buildPayWithPicker(e){let{args:t,userContext:r,destSymbol:o,destContract:s}=e,a=this.requireChain(t,r)??void 0,i=this.moralis,l=r.walletAddress,c=await i.getWalletTokenBalances({address:l,chain:a,excludeSpam:!1,excludeUnverifiedContracts:!1}),d=c.success?c.data?.result??[]:[],u=s?.toLowerCase(),p=o.trim().toLowerCase(),m=d.filter(y=>!y.symbol||p&&y.symbol.toLowerCase()===p?!1:y.native_token?u!=="native":!(!y.token_address||u&&y.token_address.toLowerCase()===u)).sort((y,w)=>(w.usd_value??0)-(y.usd_value??0)).slice(0,8);if(m.length===0)return{error:"no_pay_token_holdings",chain:a,_instructions:`The wallet has no tokens that can pay for this purchase${Q(a)}. Tell the user to top up first, naming that network explicitly so they know which one is empty. Do NOT mention tool names, UI, or forms.`};let f=e.buyAmount??this.normaliseAmount(t.buy_amount),h=e.payAmount??this.normaliseAmount(t.pay_with_amount),g=typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"";return{actionButtons:m.map(y=>{let w=y.symbol,k=y.name?.trim()||w,v=y.balance_formatted?`${this.cleanAmountString(y.balance_formatted)} `:"",S=typeof y.usd_value=="number"&&y.usd_value>0?` ($${y.usd_value.toFixed(2)})`:"",P=`${k}: ${v}${w}${S}`,x=f?this.buildBuyWithPrompt(g,o,w,f,null,a):this.buildBuyWithPrompt(g,o,w,null,h,a);return{label:P,prompt:x}}),_instructions:`Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n mua ${o}.' / 'You want to buy ${o}.'), then ask them to choose which token they want to spend to buy ${o} from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua.' / 'Please choose the token to spend.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms.`}}async checkPayBalance(e){let{args:t,userContext:r,chain:o,destSymbol:s,destContract:a,payAddr:i,payAmount:l,buyAmount:c,derivedFromBuy:d}=e,u=r.walletAddress,p=await this.readPayBalance(u,i,o),m=e.paySymbol??p?.symbol??"the selected token";if(!p){this.dbg("checkPayBalance: NOT held \u2192 pay picker fallback",{paySymbol:m});let y=await this.buildPayWithPicker({args:t,userContext:r,destSymbol:s,destContract:a,buyAmount:c,payAmount:l});return"actionButtons"in y?{error:"no_pay_balance",actionButtons:y.actionButtons,_instructions:`The user wanted to spend ${m} to buy ${s}, but their wallet holds no ${m}${Q(o)}. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${m}${Q(o)}, naming that network explicitly (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${m} tr\xEAn ${Q(o).replace(" on ","")}.'), then ask them to choose one of the tokens they already hold to pay with (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua ${s} t\u1EEB danh s\xE1ch b\xEAn d\u01B0\u1EDBi.' / 'Please choose a token to pay with from the options below.'). Do NOT list the tokens in text, do NOT invent a balance, and do NOT mention tool names, UI, or forms.`}:y}if(i.toLowerCase()!=="native"){let y=await js({chainId:o,gasKind:"swap",readNativeBalance:()=>this.readNativeHeldBalance(u,o)});if(y)return this.dbg("checkPayBalance: cannot cover gas",y),{error:"insufficient_native_for_gas",_instructions:`The wallet holds ${m} but cannot cover the network fee for this purchase: it needs about ${y.shortfall} more ${y.nativeSymbol}. Tell the user in their language that they need roughly ${y.shortfall} more ${y.nativeSymbol} to pay the network fee before they can buy ${s} (e.g., 'B\u1EA1n c\u1EA7n th\xEAm kho\u1EA3ng ${y.shortfall} ${y.nativeSymbol} \u0111\u1EC3 tr\u1EA3 ph\xED m\u1EA1ng.'), and suggest they top up ${y.nativeSymbol} first. Do NOT open a form, do NOT invent a different number, and do NOT mention tool names, UI, or forms.`}}if(!l||e.amountSizedToBalance)return null;let f=p.decimals!==void 0?Dt(l,p.decimals):l;if(sn(f,p.balanceFormatted)<=0)return null;let h=this.cleanAmountString(p.balanceFormatted),g=this.percentSpendButtons({balanceFormatted:p.balanceFormatted,balanceNum:p.balanceNum,decimals:p.decimals,paySymbol:m,destSymbol:s,buyWithTemplate:typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"",...o===void 0?{}:{chain:o}}),b=d?`Buying ${d} ${s} needs about ${l} ${m}, but they only have ${h} ${m}${Q(o)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them that buying ${d} ${s} would cost about ${l} ${m}, which is more than their balance of ${h} ${m}, then ask them to choose a smaller amount or spend less \u2014 `:`The user wants to spend ${l} ${m} to buy ${s}, but they only have ${h} ${m}${Q(o)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${l} ${m} exceeds their balance of ${h} ${m}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_pay_balance",actionButtons:g,_instructions:b+'invite them to choose one of the options below (sized to their balance) or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT invent numbers, and do NOT mention tool names, UI, buttons, or forms.'}}async readPayBalance(e,t,r){return Xs({moralis:this.moralis,walletAddress:e,tokenAddress:t,chain:r,kind:"swap",dbg:(o,s)=>this.dbg(o,s)})}async readNativeHeldBalance(e,t){if(!this.moralis)return{balance:0};try{let r=await this.moralis.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=(r.success?r.data?.result??[]:[]).find(i=>i.native_token===!0),a=s?.balance_formatted!=null?Number(s.balance_formatted):0;return{balance:Number.isFinite(a)?a:0,...s?.symbol===void 0?{}:{symbol:s.symbol}}}catch{return{balance:0}}}percentSpendButtons(e){let{balanceFormatted:t,decimals:r,paySymbol:o,destSymbol:s,buyWithTemplate:a,chain:i}=e,l=r??18;return[25,50,75,100].map(d=>{let u=$n(this.cleanAmountString(t),BigInt(d),100n,l);return{label:`${d}%`,prompt:this.buildBuyWithPrompt(a,s,o,null,u,i)}})}async buildAmountForm(e){let{userContext:t,chain:r,destContract:o,destSymbol:s,destDecimals:a,destLogo:i,payAddr:l,payAmount:c}=e,d=t.walletAddress;if(!r)return null;let u=Ce(r);if(!u)return null;let p=await this.readPayBalance(d,l,r),m=e.paySymbol??p?.symbol;if(!m)return null;let f=l==="native",h=p?.decimals??e.payDecimals??(f?u.nativeCurrency.decimals??18:void 0);if(h===void 0)return null;let g=p?.balanceFormatted,b=p?.rawAmount??(g?Bn(g,h)?.toString():void 0),y=await this.getUsdPrice(o,r).catch(()=>null);return{ui:{component:"SwapTokenForm",props:{chain:{hexId:r,name:u.name},fromToken:{address:f?"native":l,symbol:m,decimals:h,amount:g,rawAmount:b??void 0,logo:p?.logo,usdPrice:p?.usdPrice},toToken:{address:o,symbol:s,decimals:a,logo:i,usdPrice:y??void 0},walletAddress:d,intent:"buy",initialAmount:c}},_instructions:Ai({action:"buy",fromSym:m,toSym:s,amount:c,spendable:g})}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let r=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.split("."),c=i+l,d;if(a>=0){let u=i.length+a;d=u>=c.length?c.padEnd(u,"0"):`${c.slice(0,u)}.${c.slice(u)}`}else d=`0.${"0".repeat(-a-i.length)}${c}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),r?`-${d}`:d}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildBuyPrompt(e,t,r){return(e&&e.includes("{token}")?e:"buy {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()+er(r)}buildBuyWithPrompt(e,t,r,o,s,a){return(e&&e.includes("{token}")&&e.includes("{pay}")?e:"buy {buy_amount} {token} with {pay_amount} {pay}").replace(/\{token\}/g,t).replace(/\{pay\}/g,r).replace(/\{buy_amount\}/g,o??"").replace(/\{pay_amount\}/g,s??"").replace(/\s+/g," ").trim()+er(a)}async buildTrendingPicker(e,t){if(!this.pantograph)return{error:"trending_unavailable",_instructions:"Trending tokens are unavailable in this build (service not configured). Tell the user briefly and ask them to name a token to buy."};let r=this.requireChain(e,t)??void 0,o=typeof e.limit=="number"&&Number.isFinite(e.limit)?Math.floor(e.limit):6,s=Math.max(1,Math.min(10,o)),a=await this.pantograph.getTrendingTokens({chain:r,limit:s}),i=a.success?a.data??[]:[];if(i.length===0)return{error:"no_trending_tokens",_instructions:"No trending tokens are available for this chain right now. Tell the user briefly and suggest they name a token directly."};let l=i.filter(m=>m.symbol),c=typeof e.buy_prompt_template=="string"?e.buy_prompt_template:"",d=l.map(m=>{let f=m.symbol;return{label:f,prompt:this.buildBuyPrompt(c,f,r)}}),p=l.map((m,f)=>{let h=m.name?.trim()||m.symbol,g=m.symbol,b=typeof m.usdPrice=="number"&&m.usdPrice>0?`$${this.formatPrice(m.usdPrice)}`:"N/A",y=m.pricePercentChange?.["24h"],w=typeof y=="number"&&Number.isFinite(y)?` (${y>0?"+":y<0?"-":""}${this.formatPercent(Math.abs(y))}%)`:"";return`${f+1}. ${h} (${g}) \u2014 ${b}${w}`}).join(`
210
+ Do NOT mention tool names, UI, or forms.`,howTo:!0,chain:m||void 0,addLiquidityLink:u,count:f.length,pools:f.map(h=>this.formatPool(h))}}let r=typeof e.poolAddress=="string"?e.poolAddress.trim():"",o=(Array.isArray(e.tokens)?e.tokens:[]).filter(u=>typeof u=="string"&&u.trim().length>0).map(u=>u.trim().toUpperCase()),s=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)?Math.floor(e.feeTier):void 0,a=typeof e.chain=="string"&&e.chain.trim();if(!a&&!t?.chain&&t?.walletAddress)throw new ge(typeof t?.query=="string"?t.query:void 0,this.service.listSupportedChains());let i=a?e.chain.trim():t?.chain||"0x1";if(!this.service.isSupported(i))return{_instructions:"The requested chain is not supported by the Subgraph pool service. Tell the user, in their language, that add-liquidity is not available on that network and list the supported chains briefly. Do NOT mention tool names.",unsupportedChains:[T(i)],supportedChains:this.service.listSupportedChains().map(T)};let l=this.service.resolveChain(i);if(r){if(!/^0x[a-fA-F0-9]{40}$/.test(r))return{error:"Provide a valid Uniswap V3 pool address (a 0x-prefixed 40-character hex address) to add liquidity to it."};let u=await this.service.getPoolByAddress({poolAddress:r,chain:l});return u?this.poolsResult([u],l,!0):{error:`No pool found at ${r} on ${T(l)}.`}}if(o.length>0){let u=await this.service.searchPools({tokens:o,chain:l,sortBy:"tvl",filters:{feeTier:s}});if(u.length===0)return{error:`No Uniswap V3 pool found for ${o.join("/")}${s!=null?` at ${s}bps`:""} on ${T(l)}. Ask the user to check the token symbols, or try a different pair.`};let p=o.length===2?await this.fetchCoinPoolPairs(l,o):[];return this.poolsResult(u.slice(0,8),l,!0,p)}let c=await this.service.searchPools({tokens:[],chain:l,sortBy:"tvl"}),d=this.linkAddLiquidity??null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity but has not named a pool yet. Briefly list these top pools (pair, fee tier %, TVL, APR \u2014 skip APR if null) as suggestions, render each `uniswapUrl` as a clickable markdown link, then ask the user which token pair (or pool) they want to add liquidity to. '+this.linkInstruction(d)+"Do NOT mention tool names, UI, or forms.",chain:l,needsSelection:!0,addLiquidityLink:d,count:c.length,pools:c.slice(0,6).map(u=>this.formatPool(u))}}async fetchCoinPoolPairs(e,t){try{return[...await this.service.getCoinPoolPairs({chain:e,tokens:t})].sort((o,s)=>(s.apr??-1/0)-(o.apr??-1/0)).slice(0,10)}catch{return[]}}linkInstruction(e){return e?`ALWAYS finish by inviting the user to add liquidity on the website, as ONE short sentence that shows the FULL link in plain view \u2014 display the entire URL verbatim (${e}) as the visible link text, do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${e}](${e}). For example: "You can add liquidity here: [${e}](${e})". Use the URL verbatim; never invent one, and never use a pool's uniswapUrl here. `:"No add-liquidity website is configured, so do not show or invent any link. "}poolsResult(e,t,r,o=[]){let s=r?this.linkAddLiquidity??null:null;return{_instructions:'Prefix with: "According to the latest data from Subgraph Uniswap V3," (translate naturally into the user language; keep the word "Subgraph" as-is). The user wants to add liquidity. Show the resolved pool(s): pair (e.g. USDC/WETH), fee tier (%), TVL, volume past day, APR (skip if null), and the pool address. For EACH pool, render the provided `uniswapUrl` as a clickable markdown link. If coinPoolPairs is non-empty, add a short "Suggested price ranges (CoinPool)" section: for each entry show its fee tier (the `fee` field, e.g. "0.3%"), the min\u2013max price and its APR, e.g. "Fee 0.3% \xB7 APR X% (range: 1800 \u2013 2200)", to help the user choose a range when adding liquidity. CRITICAL: that APR is for the SPECIFIC price range only \u2014 never present it as the overall pool APR. Narrower ranges = higher APR but higher out-of-range risk. After the data, give a genuine, conversational recommendation \u2014 like a knowledgeable friend, NOT a rigid template. Do NOT force a fixed heading ("\u{1F4A1} Recommendation"); vary your wording naturally each time and only cover what is actually relevant to THIS pair and data. Reason ONLY from the numbers shown \u2014 never invent figures. Weave in, as it fits: which pool/fee tier looks best and why (higher TVL & volume past day = deeper liquidity, more fees, less slippage; fee-tier fit: 0.05% for stable/correlated pairs, 0.30% for typical volatile pairs, 1% for exotic/low-liquidity ones); which price range makes sense (from coinPoolPairs if present) \u2014 wider around the current price is safer and lower-maintenance, narrower earns more but can fall out of range and stop earning; anything worth avoiding (thin TVL/volume, ranges far from current price, chasing the top APR blindly); and the real risks (impermanent loss on volatile pairs/narrow ranges, out-of-range = 0 fees, gas/rebalancing, APR is variable). Keep it short and human \u2014 a sentence or two or a couple of light bullets, tailored to whether the pair is stable or volatile. Close with a brief, natural nudge that it is informational, not financial advice (phrase it differently each time, do not paste a stock disclaimer). '+(s?`Then, at the VERY END, write ONE short, friendly sentence in the user's language inviting them to add liquidity, showing the FULL add-liquidity link in plain view: display the entire URL verbatim as the visible link text \u2014 do NOT hide it behind a word like "Add liquidity" or "here". Render it as a clickable Markdown link whose visible text IS the URL itself, i.e. [${s}](${s}). For example: "If you'd like to add liquidity to one of these pools, you can do it here: [${s}](${s})." Use the addLiquidityLink verbatim; never invent a URL, and never use a pool's uniswapUrl here.`:"Do NOT invent or show any add-liquidity link (none is configured). Just present the pool(s).")+" Do NOT mention tool names, UI, forms, or that a transaction is built elsewhere.",chain:t,addLiquidityLink:s,count:e.length,pools:e.map(i=>this.formatPool(i)),coinPoolPairs:o}}formatPool(e){return{pair:e.pair,poolAddress:e.poolAddress,chain:e.chain,feeTierBps:e.feeTierBps,feeTierPercent:e.feeTierPercent,tvlUsd:e.tvl,volumePastDayUsd:e.volume24hUsd,fees24hUsd:e.fees24hUsd,apr:e.apr,token0:e.token0,token1:e.token1,uniswapUrl:je(e)}}};var up={"0x1":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0xa":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0x89":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0xa4b1":"0x1F98431c8aD98523631AE4a59f267346ea31F984","0x38":"0xdB1d10011AD0Ff90774D0C6Bb92e5C5c8b4461F7","0x2105":"0x33128a8fC17869897dcE68Ed026d694621f6FDfD","0xa86a":"0x740b1c1de25031C31FF4fC9A62f554A55cdC1baD"},xy="e34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54",ip=/^0x[a-fA-F0-9]{40}$/;function Ti(n){let e=n.startsWith("0x")?n.slice(2):n,t=new Uint8Array(e.length/2);for(let r=0;r<t.length;r++)t[r]=parseInt(e.slice(r*2,r*2+2),16);return t}function lp(n){let e=new Uint8Array(32);return e.set(Ti(n.toLowerCase()),12),e}function Cy(n){let e=new Uint8Array(32),t=BigInt(n);for(let r=31;r>=0&&t>0n;r--)e[r]=Number(t&0xffn),t>>=8n;return e}function cp(n){let e=n.reduce((o,s)=>o+s.length,0),t=new Uint8Array(e),r=0;for(let o of n)t.set(o,r),r+=o.length;return t}function hc(n){return Object.prototype.hasOwnProperty.call(up,n.toLowerCase())}function fc(n,e,t,r){let o=up[n.toLowerCase()];if(!o||!ip.test(e)||!ip.test(t)||!Number.isInteger(r)||r<=0)return null;let s=e.toLowerCase(),a=t.toLowerCase();if(s===a)return null;let[i,l]=BigInt(s)<BigInt(a)?[s,a]:[a,s],c=ba(cp([lp(i),lp(l),Cy(r)]));return`0x${ba(cp([new Uint8Array([255]),Ti(o),Ti(c),Ti(xy)])).slice(2).slice(24)}`}var pp={"0x1":"Ethereum","0xa":"OP Mainnet","0x38":"BSC","0x89":"Polygon","0x2105":"Base","0xa4b1":"Arbitrum","0xa86a":"Avalanche"},Ry={ethereum:"0x1","op mainnet":"0xa",optimism:"0xa",bsc:"0x38",binance:"0x38",polygon:"0x89",base:"0x2105",arbitrum:"0xa4b1","arbitrum one":"0xa4b1",avalanche:"0xa86a","avalanche c-chain":"0xa86a"},dp={"uniswap-v2":"V2","uniswap-v3":"V3","uniswap-v4":"V4"},Ey=new Set([100,200,300,400,500,1e3,2500,3e3,1e4,2e4]),_y="https://yields.llama.fi",Ny=300*1e3,$o=Object.keys(pp),gc=new Map,Me=class{baseUrl;cacheTtlMs;constructor(e){this.baseUrl=(e?.baseUrl||_y).replace(/\/$/,""),this.cacheTtlMs=e?.cacheTtlMs??Ny}get store(){let e=gc.get(this.baseUrl);return e||(e={pools:null,fetchedAt:0,inflight:null},gc.set(this.baseUrl,e)),e}isSupported(e){if(!e)return!1;let t=I(e);return!!t&&Object.prototype.hasOwnProperty.call(pp,t)}listSupportedChains(){return $o.filter(e=>I(e)===e)}async snapshot(){let e=this.store,t=Date.now();return e.pools&&t-e.fetchedAt<this.cacheTtlMs?e.pools:(e.inflight||(e.inflight=(async()=>{try{let r=await C.get(`${this.baseUrl}/pools`);if(!r.ok)throw new Error(`DefiLlama: ${_(r)}`);let o=r.data,a=(Array.isArray(o?.data)?o.data:[]).filter(i=>i&&typeof i.project=="string"&&dp[i.project]!==void 0).map(i=>this.normalize(i)).filter(i=>i!==null);return e.pools=a,e.fetchedAt=Date.now(),a}catch(r){if(e.pools)return e.pools;throw r}finally{e.inflight=null}})()),e.inflight)}clearCache(){gc.delete(this.baseUrl)}parseFeeTierBps(e){if(typeof e!="string")return;let t=e.match(/([\d.]+)\s*%/);if(!t)return;let r=parseFloat(t[1]);if(!Number.isFinite(r)||r<=0)return;let o=Math.round(r*1e4);return Ey.has(o)?o:void 0}normalize(e){let t=Ry[String(e.chain).toLowerCase()];if(!t)return null;let r=dp[e.project];if(!r)return null;let o=this.parseFeeTierBps(e.poolMeta),s=String(e.symbol||"").split(/[-/]/).map(p=>p.trim()).filter(Boolean),a=Array.isArray(e.underlyingTokens)?e.underlyingTokens.filter(p=>typeof p=="string"):[],i=r==="V3"&&o&&a.length===2&&hc(t)?fc(t,a[0],a[1],o)??void 0:void 0,l=typeof e.tvlUsd=="number"&&e.tvlUsd>0?e.tvlUsd:0,c=typeof e.volumeUsd1d=="number"&&e.volumeUsd1d>=0?e.volumeUsd1d:void 0,d=$(e.apyBase??e.apy),u=$(e.apy)??d;return{id:e.pool,pair:s.length>=2?`${s[0]}/${s[1]}`:String(e.symbol||""),chain:t,protocolVersion:r,address:i,feeTierBps:o,feeTierPercent:o!==void 0?o/1e4:void 0,tvlUsd:l,apr:d!==void 0?parseFloat(d.toFixed(2)):void 0,totalApr:u!==void 0?parseFloat(u.toFixed(2)):void 0,volume1DayUsd:c,volume7DayUsd:typeof e.volumeUsd7d=="number"&&e.volumeUsd7d>=0?e.volumeUsd7d:void 0,volumeToTvlRatio:c!==void 0&&l>0?parseFloat((c/l).toFixed(4)):void 0,fee24hUsd:c!==void 0&&o!==void 0?parseFloat((c*o/1e6).toFixed(2)):void 0,token0:s[0]||a[0]?{symbol:s[0],address:a[0]}:void 0,token1:s[1]||a[1]?{symbol:s[1],address:a[1]}:void 0,isStablecoin:e.stablecoin===!0?!0:void 0,ilRisk:typeof e.ilRisk=="string"?e.ilRisk:void 0,aprChange1D:typeof e.apyPct1D=="number"?e.apyPct1D:void 0,aprChange7D:typeof e.apyPct7D=="number"?e.apyPct7D:void 0,aprChange30D:typeof e.apyPct30D=="number"?e.apyPct30D:void 0,aprMean30d:typeof e.apyMean30d=="number"?parseFloat(e.apyMean30d.toFixed(2)):void 0}}sortValue(e,t){switch(t){case"apr":return e.apr??-1;case"volume1Day":return e.volume1DayUsd??-1;case"volume7Day":return e.volume7DayUsd??-1;default:return e.tvlUsd}}sorted(e,t){return[...e].sort((r,o)=>this.sortValue(o,t)-this.sortValue(r,t))}async getTopPools(e){try{let t=await this.snapshot(),r=e.protocolVersion??"V3",o=Math.min(Math.max(e.limit??10,1),50),s=t.filter(a=>a.chain===e.chain);return r!=="ALL"&&(s=s.filter(a=>a.protocolVersion===r)),e.forAddLiquidity&&(s=s.filter(a=>a.address!==void 0)),{success:!0,data:this.sorted(s,e.sortBy??"tvl").slice(0,o)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async searchPools(e){try{let t=await this.snapshot(),r=e.protocolVersion??"V3",o=Math.min(Math.max(e.limit??10,1),50),s=String(e.query||"").split(/[\s,/-]+/).map(i=>i.trim().toLowerCase()).filter(Boolean),a=t.filter(i=>i.chain===e.chain);return r!=="ALL"&&(a=a.filter(i=>i.protocolVersion===r)),e.forAddLiquidity&&(a=a.filter(i=>i.address!==void 0)),s.length>0&&(a=a.filter(i=>{let l=[i.token0?.symbol?.toLowerCase(),i.token1?.symbol?.toLowerCase(),i.token0?.address?.toLowerCase(),i.token1?.address?.toLowerCase()].filter(c=>typeof c=="string");return s.every(c=>l.some(d=>c.startsWith("0x")?d===c:this.symbolMatches(d,c)))})),{success:!0,data:this.sorted(a,e.sortBy??"tvl").slice(0,o)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}symbolMatches(e,t){return e===t||e===`w${t}`||t===`w${e}`}async getPoolsByPair(e){let t=[e.token0Symbol,e.token1Symbol].filter(Boolean).join(" "),r=await this.searchPools({chain:e.chain,query:t,limit:50,sortBy:"tvl",protocolVersion:e.protocolVersion??"V3"});return!r.success||!r.data?r:{success:!0,data:e.feeTierBps!==void 0?r.data.filter(s=>s.feeTierBps===e.feeTierBps):r.data}}async findByPoolAddress(e){try{let t=await this.snapshot(),r=e.address.toLowerCase();return{success:!0,data:t.find(s=>s.chain===e.chain&&s.address===r)??null}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async findPoolsByTokenAddress(e){try{let t=await this.snapshot(),r=e.address.toLowerCase(),o=t.filter(s=>s.chain===e.chain&&(s.token0?.address?.toLowerCase()===r||s.token1?.address?.toLowerCase()===r));return{success:!0,data:this.sorted(o,"tvl").slice(0,Math.min(e.limit??10,50))}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}};function He(){return{kind:"info",async listSupported(){return $o.filter(n=>Be(n))},async isSupported(n){if(!n)return!1;let e=I(n);return!!e&&$o.includes(e)}}}function Ve(){return $o.filter(n=>Be(n)).map(n=>T(n)).join(", ")}var We="Hex chain ID of the chain the user named. Map the chain name to its EXACT hex id \u2014 pass ONLY one of these values, never a guessed or made-up one: Ethereum=0x1, Optimism=0xa, BSC=0x38, Polygon=0x89, Base=0x2105, Arbitrum=0xa4b1, Avalanche=0xa86a. Set this WHENEVER the user EXPLICITLY names a chain (always send the exact hex from this list). Otherwise OMIT it entirely so the connected wallet chain is used automatically.";var Ly=["V2","V3","V4"];function Ho(n){if(typeof n!="string")return"V3";let e=n.trim().toUpperCase();return e==="ALL"?"ALL":Ly.includes(e)?e:"V3"}function Iy(n){return Object.fromEntries(Object.entries(n).filter(([,e])=>e!=null))}function _e(n){let e=Ws(n.chain,n.address);return Iy({pair:n.pair,address:n.address,chain:n.chain,protocolVersion:n.protocolVersion,feeTierBps:n.feeTierBps,feeTierPercent:n.feeTierPercent,tvlUsd:n.tvlUsd,volume1DayUsd:n.volume1DayUsd,volume7DayUsd:n.volume7DayUsd,fee24hUsd:n.fee24hUsd,apr:n.apr,totalApr:n.totalApr!==void 0&&n.totalApr!==n.apr?n.totalApr:void 0,volumeToTvlRatio:n.volumeToTvlRatio,aprChange1D:n.aprChange1D,aprChange7D:n.aprChange7D,aprMean30d:n.aprMean30d,isStablecoin:n.isStablecoin,ilRisk:n.ilRisk,token0:n.token0,token1:n.token1,uniswapUrl:e??void 0,addLiquidityUnavailable:n.address===void 0?!0:void 0})}var ft='\u2022 APR trend \u2014 `aprChange1D` / `aprChange7D` are the change in APR over the last day / week in PERCENTAGE POINTS, and `aprMean30d` is the 30-day average APR. A spot `apr` far above `aprMean30d` is a spike that is unlikely to hold; one near or below it is steadier. Use these to judge whether a yield is durable rather than a snapshot. \u2022 `ilRisk` = "no" marks a pool upstream considers free of impermanent-loss exposure (typically a correlated or stablecoin pair); "yes" is the normal volatile-pair case. `isStablecoin` marks a stablecoin pair. \u2022 `totalApr` (when present and higher than `apr`) includes incentive/reward emissions on top of swap fees \u2014 call that out, since emissions can end at any time while fee yield does not. \u2022 `addLiquidityUnavailable: true` means this pool cannot be added to in-app \u2014 never offer to add liquidity to it. ';var Uy=["tvl","volume1Day","volume7Day","apr"],Vo=class extends A{name="defillama-top-pools";description=`List the top Uniswap liquidity pools on a given EVM chain, ranked by TVL by default. Returns each pool's address, fee tier, protocol version, both tokens, TVL, rolling volume (1d / 7d), fee revenue, and APR (with 1d/7d/30d APR trend). Use this tool for questions like: "top pools on Ethereum", "biggest Uniswap pools on Base", "which pools have the most liquidity", "show pools with the highest APR on Arbitrum". Source: DefiLlama Yields. Supports: `+Ve();category="blockchain-data";parameters=[{name:"chain",type:"string",description:We,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version to filter by: "V2", "V3", "V4", or "ALL". Default is "V3" (the dataset with the richest stats and the only one that supports adding liquidity in-app). Use "V4" only when the user explicitly asks for V4 pools.',required:!1,default:"V3"},{name:"sortBy",type:"string",description:'Ranking metric: "tvl" (total value locked, default), "volume1Day", "volume7Day", or "apr" (annualized fee yield). Pools are returned in descending order by this metric. There is no 30-day volume or transaction-count ranking \u2014 for "most active" use "volume1Day".',required:!1,default:"tvl"},{name:"limit",type:"number",description:'Maximum number of pools to return after sorting. Defaults to 5. ONLY raise this when the user explicitly asks for a specific or larger count ("show 10 pools", "top 20").',required:!1,default:5},{name:"forAddLiquidity",type:"boolean",description:"Set true when the user wants to ADD LIQUIDITY and is picking a pool (rather than just browsing). Validates ADD-LIQUIDITY chain support up front and returns ONLY pools that can actually be added to, so the user never picks a pool that dead-ends at the next step.",required:!1,default:!1},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new ie}async run(e,t){let r=e.forAddLiquidity===!0,o=await te(r?vn(this.pool):He(),e.chain,t);if(!o.ok)return o.result;let s=o.chain,a=Ho(e.protocolVersion),i=typeof e.sortBy=="string"?e.sortBy:"tvl",l=Uy.includes(i)?i:"tvl",c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,d=await this.service.getTopPools({chain:s,limit:c,sortBy:l,protocolVersion:a,forAddLiquidity:r});if(!d.success)return{_instructions:"Pool data could not be retrieved right now. Tell the user briefly, in their language, that pool data is temporarily unavailable and to try again shortly. Do NOT mention tools, APIs, or any internals.",error:d.error};let u=(d.data??[]).map(_e);if(u.length===0)return{_instructions:"No pools matched on this chain. Tell the user plainly, in their language, that no pools were found here and suggest another chain. Do NOT invent pools. Do NOT mention tools or APIs.",chain:T(s),count:0,pools:[]};let p=await this.pool.isAddLiquiditySupported(s)?pe(u.filter(m=>m.address!==void 0),e,T(s)):[];return{_instructions:me+"You are briefing a peer. Present the pools as a ranked list, then deliver the analysis. For each pool include the key facts: rank, pair (token0/token1 symbols), fee tier (in %), TVL in USD, 24h volume, and APR (in %). CRITICAL: every pool MUST have its own written analysis \u2014 2\u20133 sentences of genuine expert read placed directly under that pool's facts. NEVER skip a pool and NEVER reduce a pool to just a facts list. Vary the wording from pool to pool (do not repeat the same sentence structure), go a little deeper on the standouts, and surface the non-obvious insight a less experienced observer would miss. "+he+ft+"After the per-pool reads, close with a short overall section that (1) gives a high-level read across the whole list \u2014 the broad pattern you see (where the real capital efficiency and fee yield sit, how the risk/reward stacks up), (2) names the single best pool to provide liquidity in right now and explains why it stands out, and (3) gives the user a concrete, actionable recommendation tailored to the data. "+be+Y+"Mention the chain and the sort metric in the intro line. "+j+(p.length>0?de:""),chain:s,protocolVersion:a,sortBy:l,count:u.length,pools:u,...p.length>0?{actionButtons:p}:{}}}};var Dy=["tvl","volume1Day","volume7Day","apr"],Wo=class extends A{name="defillama-search-pools";description='Search Uniswap liquidity pools by token symbol, token name, or token address on a given EVM chain. Use for: "show pools for USDC", "find WBTC pools on Base", "pools containing PEPE", "USDC/ETH pools on Arbitrum", "top USDC pools". Use this WHENEVER the user names a specific token \u2014 even with words like "top" or "biggest". Returns matching pools with pair, fee tier, TVL, 24h/7d volume, and APR. Source: DefiLlama Yields. Supports: '+Ve();category="blockchain-data";parameters=[{name:"query",type:"string",description:'The token symbol(s), token name, or token address to search for. For a PAIR, pass both symbols separated by a space ("USDC WETH") \u2014 every term must appear in the pool, so this returns that pair specifically. For a single token pass just its symbol ("USDC").',required:!0},{name:"chain",type:"string",description:We,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version to filter by: "V2", "V3", "V4", or "ALL". Default "V3". Use "ALL" only when the user explicitly wants every version.',required:!1,default:"V3"},{name:"sortBy",type:"string",description:'Ranking metric for the matches: "tvl" (default), "volume1Day", "volume7Day", or "apr". Use "volume1Day" when the user asked for the "top"/"biggest"/"most active" pools of a token.',required:!1,default:"tvl"},{name:"limit",type:"number",description:"Maximum number of pools to return. Defaults to 5, max 50.",required:!1,default:5},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new ie}async run(e,t){let r=await te(He(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.query=="string"?e.query.trim():"";if(!s)return{_instructions:"No search term was provided. Ask the user which token they want pools for, in their language. Do NOT mention tools or APIs."};let a=Ho(e.protocolVersion),i=typeof e.sortBy=="string"?e.sortBy:"tvl",l=Dy.includes(i)?i:"tvl",c=typeof e.limit=="number"&&Number.isFinite(e.limit)&&e.limit>0?Math.min(Math.floor(e.limit),50):5,d=await this.service.searchPools({chain:o,query:s,limit:c,sortBy:l,protocolVersion:a});if(!d.success)return{_instructions:"Pool data could not be retrieved right now. Tell the user briefly, in their language, that pool data is temporarily unavailable and to try again shortly. Do NOT mention tools, APIs, or any internals.",error:d.error};let u=(d.data??[]).map(_e);if(u.length===0)return{_instructions:"No pools matched this token on this chain. Tell the user plainly, in their language, that no pools were found for it here, and suggest checking another chain or a different token. NEVER invent pools. Do NOT mention tools or APIs.",chain:T(o),query:s,count:0,pools:[]};let p=await this.pool.isAddLiquiditySupported(o)?pe(u.filter(m=>m.address!==void 0),e,T(o)):[];return{_instructions:me+`Present the pools matching "${s}" as a ranked list, then deliver the analysis. For each pool include: pair, fee tier (in %), TVL in USD, 24h volume, and APR (in %). CRITICAL: every pool MUST have its own 2\u20133 sentence expert read directly under its facts \u2014 never a bare list. Vary the wording between pools and surface the non-obvious insight. `+he+ft+"IMPORTANT \u2014 same pair, different pools: two pools can show the SAME pair and fee tier yet be different contracts (one of the tokens is an impostor wearing a well-known ticker). When you see that, flag the one with far lower TVL as the likely impostor and tell the user to verify the token contract before providing liquidity. Close with a short overall read: which of these pools is the most attractive for an LP right now and why. "+be+Y+j+(p.length>0?de:""),chain:o,query:s,sortBy:l,count:u.length,pools:u,...p.length>0?{actionButtons:p}:{}}}};var Yo=class extends A{name="defillama-pool-detail";description='Get full statistics for ONE specific Uniswap pool identified by its TOKEN PAIR (and optional fee tier). Use for: "details for USDC/WETH 0.05% on Base", "TVL and APR of the WBTC/USDC pool", "how is the ETH/USDC pool doing". Returns TVL, 24h/7d volume, fee revenue, APR (with trend), fee tier, and both tokens. Pass token symbols \u2014 NEVER a pool address (use lookup-pool-by-address for an address). When several fee tiers match, returns a candidates list to choose from instead of a single pool. Source: DefiLlama Yields. Supports: '+Ve();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:'Symbol of the first token in the pair, e.g. "USDC". Required.',required:!0},{name:"token1Symbol",type:"string",description:`Symbol of the second token, e.g. "WETH". Omit when the user named only one token \u2014 the tool then returns that token's pools as candidates.`,required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points as Uniswap stores it: 100 = 0.01%, 500 = 0.05%, 3000 = 0.3%, 10000 = 1%. Omit when the user did not name one \u2014 the tool then returns the matching tiers as candidates.",required:!1},{name:"chain",type:"string",description:We,required:!1},{name:"protocolVersion",type:"string",description:'Uniswap protocol version: "V2", "V3", "V4", or "ALL". Default "V3".',required:!1,default:"V3"},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new ie}async run(e,t){let r=await te(He(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"";if(!s)return{_instructions:"No token was named. Ask the user which pool they mean, in their language. Do NOT mention tools or APIs."};let a=typeof e.token1Symbol=="string"&&e.token1Symbol.trim()?e.token1Symbol.trim():void 0,i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.round(e.feeTier):void 0,l=Ho(e.protocolVersion),c=await this.service.getPoolsByPair({chain:o,token0Symbol:s,token1Symbol:a,feeTierBps:i,protocolVersion:l});if(!c.success)return{_instructions:"Pool data could not be retrieved right now. Tell the user briefly, in their language, that pool data is temporarily unavailable and to try again shortly. Do NOT mention tools, APIs, or any internals.",error:c.error};let d=c.data??[],u=[s,a].filter(Boolean).join("/");if(d.length===0)return{_instructions:"No pool matched that pair on this chain. Tell the user plainly, in their language, that this pool was not found here, and suggest another chain or checking the token symbols. NEVER invent pool stats. Do NOT mention tools or APIs.",chain:T(o),pair:u,pool:null};let p=await this.pool.isAddLiquiditySupported(o);if(d.length>1){let h=d.map(_e),g=p?pe(h.filter(b=>b.address!==void 0),e,T(o)):[];return{_instructions:`Several ${u} pools exist on this chain \u2014 they differ by fee tier. Present them as a short numbered list (pair, fee %, TVL, 24h volume, APR) with a one-line expert note on each saying which kind of LP it suits, then ask the user which one they want. Do NOT present any single one as "the" pool and do NOT merge their stats. `+j+(g.length>0?de:""),chain:o,pair:u,count:h.length,candidates:h,...g.length>0?{actionButtons:g}:{}}}let m=_e(d[0]),f=p&&m.address!==void 0?pe([m],e,T(o)):[];return{_instructions:me+"Give a thorough read on this ONE pool. Lead with the facts \u2014 pair, fee tier (in %), chain, TVL, 24h volume, 24h fee revenue, and APR (in %) \u2014 then deliver several sentences of genuine expert analysis in flowing prose. "+he+ft+"Close by telling the user concretely whether this pool is worth providing liquidity in right now, and for which kind of LP it is best suited. "+be+Y+j+(f.length>0?de:""),chain:o,pair:u,pool:m,...f.length>0?{actionButtons:f}:{}}}};var Oy=/^0x[a-fA-F0-9]{40}$/,Go=class extends A{name="defillama-pool-by-address";description='Resolve an unknown 0x address as either a Uniswap pool or a token, then return the appropriate data: pool detail when the address is a pool, or the list of pools containing that token when the address is a token. Use when the user pastes a single 0x address without saying which it is ("what is 0x88e6\u2026", "tell me about this address"). For pool resolution: pair, fee tier, TVL, volume, fee revenue and APR. For token resolution: the token plus a ranked list of pools containing it. Source: DefiLlama Yields, with an on-chain read as fallback. Supports: '+Ve();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:We,required:!1},...Ee];service;pool;constructor(e){super(),this.service=new Me(e),this.pool=new ie}async run(e,t){let r=await te(He(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.address=="string"?e.address.trim():"";if(!Oy.test(s))return{_instructions:"The value provided is not a valid EVM address. Ask the user, in their language, to re-send the full 0x address. Do NOT mention tools or APIs."};let a=s.toLowerCase(),i=await this.pool.isAddLiquiditySupported(o),l=await this.service.findByPoolAddress({chain:o,address:a});if(l.success&&l.data){let u=_e(l.data),p=i&&u.address!==void 0?pe([u],e,T(o)):[];return{_instructions:me+"This address is a liquidity POOL. Lead with the facts \u2014 pair, fee tier (in %), chain, TVL, 24h volume, 24h fee revenue and APR (in %) \u2014 then give several sentences of genuine expert analysis. "+he+ft+"Close by saying concretely whether this pool is worth providing liquidity in right now. "+be+Y+j+(p.length>0?de:""),chain:o,resolvedAs:"pool",pool:u,...p.length>0?{actionButtons:p}:{}}}let c=await this.service.findPoolsByTokenAddress({chain:o,address:a,limit:10});if(c.success&&c.data&&c.data.length>0){let u=c.data.map(_e),p=c.data[0],m=p.token0?.address?.toLowerCase()===a?p.token0?.symbol:p.token1?.symbol,f=i?pe(u.filter(h=>h.address!==void 0),e,T(o)):[];return{_instructions:"The address is a TOKEN, not a pool. Tell the user which token it is, then present the pools containing it as a ranked numbered list (pair, fee %, TVL, 24h volume, APR) with a brief expert note on each. Invite them to pick one for a deeper look. "+he+ft+j+(f.length>0?de:""),chain:o,resolvedAs:"token",token:{address:a,symbol:m},count:u.length,pools:u,...f.length>0?{actionButtons:f}:{}}}let d=await this.readPoolOnchain(o,a);if(d){let u=i?pe([d],e,T(o)):[];return{_instructions:me+"This address IS a real Uniswap V3 pool on-chain, but it is not covered by the market-data feed, so ONLY the on-chain facts below are available: the token pair, the fee tier, and the current price. State those plainly, then say clearly that TVL, volume and APR are not available for this pool. CRITICAL: do NOT invent, estimate, or infer TVL, volume, APR or any yield figure \u2014 you have none. A pool missing from the market-data feed is usually very new or very thinly traded; say so, and advise the user to check its liquidity depth carefully before providing liquidity. "+Y+j+(u.length>0?de:""),chain:o,resolvedAs:"pool",dataSource:"onchain-only",pool:d,...u.length>0?{actionButtons:u}:{}}}return{_instructions:`This address matched neither a pool nor a token on ${T(o)}. Tell the user plainly, in their language, that nothing was found for it on this network, and suggest they check the address or try another chain. NEVER invent pool or token data. Do NOT mention tools or APIs.`,chain:T(o),address:a,resolvedAs:null}}async readPoolOnchain(e,t){try{let r=await this.pool.readPoolOnchain(e,t),[o,s]=await on(e,[r.token0,r.token1]).catch(()=>[{symbol:null,decimals:null},{symbol:null,decimals:null}]),a=o?.symbol??void 0,i=s?.symbol??void 0,l=Ws(e,t);return{pair:a&&i?`${a}/${i}`:void 0,address:t,chain:e,protocolVersion:"V3",feeTierBps:r.fee,feeTierPercent:r.fee/1e4,currentPrice:r.currentPrice,token0:{symbol:a,address:r.token0},token1:{symbol:i,address:r.token1},...l?{uniswapUrl:l}:{}}}catch{return null}}};var My=1e3,Fy=365;function By(n,e){let t=e/100;return{depositUsd:n,aprPercent:e,dailyUsd:n*t/Fy,weeklyUsd:n*t/52,monthlyUsd:n*t/12,yearlyUsd:n*t}}var Ko=class extends A{name="defillama-estimate-pool-yield";description=`Estimate daily / weekly / monthly / yearly fee yield for a USD deposit into a Uniswap pool. Use for: "if I put $1000 into USDC/WETH how much do I earn per day?", "b\u1ECF 500$ v\xE0o pool n\xE0y l\u1EDDi bao nhi\xEAu?", "APR of the WBTC/ETH pool", "daily income for this pool". Call it IMMEDIATELY with whatever the user gave \u2014 it fills the gaps itself: \u2022 Only ONE token named \u2192 pass just token0Symbol; the tool auto-picks that token's highest-volume pool. \u2022 BOTH tokens but no fee tier AND several tiers exist \u2192 returns candidates (one per fee tier) to choose from. \u2022 No deposit amount \u2192 defaults to $1000 and marks the result as a per-$1000 example. Source: DefiLlama Yields. Supports: `+Ve();category="blockchain-data";parameters=[{name:"token0Symbol",type:"string",description:'Symbol of the first token, e.g. "USDC". Required.',required:!0},{name:"token1Symbol",type:"string",description:`Symbol of the second token, e.g. "WETH". Omit when the user named only one token \u2014 the tool then auto-picks that token's highest-volume pool rather than asking.`,required:!1},{name:"feeTier",type:"number",description:"Fee tier in basis points: 100 = 0.01%, 500 = 0.05%, 3000 = 0.3%, 10000 = 1%. OMIT when the user has not mentioned one \u2014 the tool returns candidates if the pair has several tiers.",required:!1},{name:"depositUsd",type:"number",description:"The USD amount the user wants to deposit. OMIT when they did not say \u2014 the tool defaults to $1000 and labels the result a per-$1000 example. Do NOT ask the user for this up front.",required:!1},{name:"chain",type:"string",description:We,required:!1}];service;constructor(e){super(),this.service=new Me(e)}async run(e,t){let r=await te(He(),e.chain,t);if(!r.ok)return r.result;let o=r.chain,s=typeof e.token0Symbol=="string"?e.token0Symbol.trim():"";if(!s)return{_instructions:"No token was named. Ask the user which pool they want the yield estimate for, in their language. Do NOT mention tools or APIs."};let a=typeof e.token1Symbol=="string"&&e.token1Symbol.trim()?e.token1Symbol.trim():void 0,i=typeof e.feeTier=="number"&&Number.isFinite(e.feeTier)&&e.feeTier>0?Math.round(e.feeTier):void 0,l=typeof e.depositUsd=="number"&&Number.isFinite(e.depositUsd)&&e.depositUsd>0,c=l?e.depositUsd:My,d=await this.service.getPoolsByPair({chain:o,token0Symbol:s,token1Symbol:a,feeTierBps:i});if(!d.success)return{_instructions:"Pool data could not be retrieved right now. Tell the user briefly, in their language, that pool data is temporarily unavailable and to try again shortly. Do NOT mention tools, APIs, or any internals.",error:d.error};let u=[s,a].filter(Boolean).join("/"),p=d.data??[];if(p.length===0)return{_instructions:"No pool matched that pair on this chain, so no yield can be estimated. Tell the user plainly, in their language, and suggest another chain or different tokens. NEVER invent an APR or an earnings figure. Do NOT mention tools or APIs.",chain:T(o),pair:u};let m=new Set(p.map(y=>y.feeTierBps).filter(y=>y!==void 0));if(a&&i===void 0&&m.size>1){let y=this.dedupeByFeeTier(p).slice(0,5);return{_instructions:`The ${u} pair has several fee tiers. Present them as a short numbered list (fee %, TVL, 24h volume, APR) and ask the user which one they mean. When they answer, call this tool again with the chosen feeTier \u2014 and pass along the original deposit amount if the user gave one. Do NOT estimate earnings yet, and do NOT merge the tiers into one figure. `+j,chain:o,pair:u,candidates:y.map(_e)}}let f=[...p].sort((y,w)=>(w.volume1DayUsd??0)-(y.volume1DayUsd??0)),h=f[0],g=a?f.length>1?`Auto-selected the highest-volume ${u} pool at this fee tier.`:void 0:`Auto-selected the highest-volume ${s} pool.`;if(h.apr===void 0)return{_instructions:"This pool has no APR reading, so earnings CANNOT be projected. Say so plainly in the user's language and show the TVL and 24h volume instead. CRITICAL: never invent, estimate, or infer an APR or an earnings figure. "+j,chain:o,pair:u,pool:_e(h),...g?{autoPickedReason:g}:{}};let b=By(c,h.apr);return{_instructions:(l?"Lead with: pool (pair + fee %), chain, APR %. Then show the projected earnings for the user's deposit \u2014 daily, weekly, monthly and yearly, in USD with 2 decimals. ":'IMPORTANT: the user did NOT specify a deposit amount \u2014 this result is a per-$1000 EXAMPLE. Lead with: pool (pair + fee %), chain, APR %. Then say "for every $1000 deposited you would earn approximately:" and list the daily / weekly / monthly / yearly figures in USD with 2 decimals. Afterwards you MAY invite the user to share their actual budget for a personalized number. ')+(g?'Mention naturally that this is the most active pool for that token (e.g. "the highest-volume USDC/WETH pool") \u2014 never say you "auto-picked" it. ':"")+"Note briefly that this projection assumes the current APR holds and that real returns vary with trading volume. "+Y+j,chain:o,pair:u,pool:_e(h),depositMode:l?"user-specified":"default-1000-example",estimate:b,...g?{autoPickedReason:g}:{}}}dedupeByFeeTier(e){let t=new Map;for(let r of e){if(r.feeTierBps===void 0)continue;let o=t.get(r.feeTierBps);(!o||r.tvlUsd>o.tvlUsd)&&t.set(r.feeTierBps,r)}return[...t.values()].sort((r,o)=>o.tvlUsd-r.tvlUsd)}};var jo=class{service;constructor(e){this.service=new Me(e)}async resolveCandidates(e){let t=e.protocolVersion==="ALL"?"ALL":"V3",r=await this.service.getPoolsByPair({chain:e.chain,token0Symbol:e.token0Symbol,token1Symbol:e.token1Symbol,feeTierBps:e.feeTier,protocolVersion:t});return r.success?(r.data??[]).filter(o=>o.protocolVersion==="V3"?o.address!==void 0:t==="ALL").map(o=>({id:o.address,protocolVersion:o.protocolVersion,feeTier:o.feeTierBps,token0:o.token0,token1:o.token1,tvlUsd:o.tvlUsd,volume1DayUsd:o.volume1DayUsd,apr:o.apr})):null}};function _t(n){if(typeof n=="number")return Number.isFinite(n)&&n>0?{kind:"token",value:n,raw:String(n)}:null;if(typeof n!="string")return null;let e=n.trim();if(!e)return null;if(/^(?:max(?:imum)?|all|everything|tất\s*cả|toàn\s*bộ)$/i.test(e))return{kind:"percent",percent:100,raw:e};let t=e.match(/^%?\s*([0-9]*\.?[0-9]+)\s*%$|^%\s*([0-9]*\.?[0-9]+)$/);if(t){let s=parseFloat(t[1]??t[2]);return Number.isFinite(s)&&s>0?{kind:"percent",percent:s,raw:e}:null}let r=e.match(/^\$\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*\$$|^(?:usd)\s*([0-9]*\.?[0-9]+)$|^([0-9]*\.?[0-9]+)\s*usd$/i);if(r){let s=parseFloat(r[1]??r[2]??r[3]??r[4]);return Number.isFinite(s)&&s>0?{kind:"usd",usd:s,raw:e}:null}let o=e.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(o){let s=parseFloat(o[1]);return Number.isFinite(s)&&s>0?{kind:"token",value:s,raw:e}:null}return null}function mp(n,e){switch(n.kind){case"token":return{ok:!0,amount:n.value};case"percent":return e.balance===void 0||!Number.isFinite(e.balance)||e.balance<=0?{ok:!1,reason:"no_balance"}:{ok:!0,amount:e.balance*n.percent/100};case"usd":return e.usdPrice===void 0||!Number.isFinite(e.usdPrice)||e.usdPrice<=0?{ok:!1,reason:"no_price"}:{ok:!0,amount:n.usd/e.usdPrice}}}function er(n){let e=n?.trim();if(!e)return"";let t=T(e);return!t||t==="the requested chain"||t===e?"":` (${t})`}function Q(n){let e=er(n).trim();return e?` on ${e.slice(1,-1)}`:" on this chain"}var hp={send:30000n,swap:1000000n};async function qy(n){try{let e=await Re(n).getGasPrice();return e>0n?e:0n}catch{return 0n}}function fp(n,e){let t=hp[n],r=$y(e);return r!==null&&r>t?r:t}function $y(n){let e=n?.tx?.gas??n?.estimatedTransactionFee?.details?.gasLimit;if(e==null)return null;try{let t=typeof e=="bigint"?e:BigInt(e);return t>0n?t:null}catch{return null}}async function yc(n,e,t={}){let[r,o]=await Promise.all([qy(n),t.provider?wi({provider:t.provider,srcChainId:n,dstChainId:t.dstChainId??n}):Promise.resolve(0n)]);return(r>0n?fp(e,t.quoteGas)*r:0n)+o}async function Gs(n,e,t={}){return yc(n,e,t)}function Ks(n,e,t){if(e<=0n)return n;let r=Un(t)?.decimals;if(r===void 0)return n;let o=Number(e)/10**r;return!Number.isFinite(o)||o<=0?n:Math.max(0,n-o)}function bc(n,e){let t=Un(e)?.decimals;if(t===void 0)return null;let r=Number(n)/10**t;return Number.isFinite(r)?r:null}function gp(n){let{nativeBalance:e,feeWei:t,chainId:r}=n;if(t<=0n)return null;let o=bc(t,r);if(o===null||o<=0||!Number.isFinite(e)||e>o)return null;let s=Math.ceil(Math.max(0,o-e)*1e8)/1e8;return s>0?s:1e-8}async function js(n){let{chainId:e,gasKind:t,readNativeBalance:r,feeContext:o}=n;if(!e)return null;try{let[s,a]=await Promise.all([yc(e,t,o??{}),r()]),i=gp({nativeBalance:a?.balance??0,feeWei:s,chainId:e});return i===null?null:{shortfall:i,nativeSymbol:a?.symbol??Un(e)?.symbol??"the native coin",fee:bc(s,e)??0}}catch{return null}}var ot=class extends A{kind="ui";category="wallet-action";buildUI(e){let t={action:this.actionType,chainId:e.chainId,chainName:T(e.chainId),walletAddress:e.walletAddress,parameters:e.parameters};return{component:this.component,props:t}}userInputFields=[];moralis;constructor(e){super(),e!==void 0&&(this.moralis=new O(e))}async resolveContractAddress(e,t,r){if(!this.moralis||!e)return;let o=e.trim().toLowerCase(),s=R(e.trim()),a=l=>s?(l.token_address??"").toLowerCase()===o:(l.symbol??"").toLowerCase()===o;if(r){let l=await this.moralis.getWalletTokenBalances({address:r,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}parseDecimals(e){if(typeof e=="number"&&Number.isInteger(e)&&e>=0)return e;if(typeof e=="string"&&e.trim()){let t=parseInt(e,10);if(Number.isInteger(t)&&t>=0)return t}}async resolveTokenRef(e){let{contractArg:t,symbolArg:r,decimalsArg:o,chain:s,walletAddress:a}=e,i=this.parseDecimals(o),l=typeof r=="string"&&r.trim()?r.trim():void 0,c=this.normaliseAddress(t),d=typeof t=="string"&&t.trim()?t.trim():void 0,u=c??l??d;if(!u)return{token:void 0};let p=await this.resolveContractAddress(u,s,a);return p?{token:{address:p.address,symbol:p.symbolIsOnchain?p.symbol:l??p.symbol,name:p.name,decimals:i??p.decimals}}:c?{token:{address:c,symbol:l,decimals:i}}:{error:"token_not_found",key:u}}requireWallet(e){let t=e?.walletAddress;return t?{ok:!0,address:t}:{ok:!1,payload:{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before submitting the action. Do NOT render the form."}}}requireChain(e,t){return K(e.chain,t)}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return R(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let r=parseFloat(t);return Number.isFinite(r)&&r>0?t:null}async resolveAmountInput(e){let{rawAmount:t,tokenAddress:r,chain:o,walletAddress:s,gasKind:a}=e,i=_t(t);if(!i)return null;let l=e.symbol??"the token",c=r.toLowerCase()==="native",d=!!a&&c&&!!o;if(i.kind==="token")return{amount:this.toPlainDecimal(i.value)};let u=await this.readTokenBalanceAndPrice(r,o,s),p=u?.balance;d&&u?.balance!==void 0&&(p=await this.computeNativeSpendable(o,a,u.balance));let m=mp(i,{balance:p,usdPrice:u?.usdPrice});return m.ok?{amount:this.toPlainDecimal(m.amount)}:m.reason==="no_balance"?{error:"amount_balance_unavailable",chain:o,_instructions:`Could not read the user's ${l} balance${Q(o)} to work out ${i.raw} right now. Tell them, in their language, that the balance couldn't be fetched at the moment and ask them to enter an exact ${l} amount instead. Do NOT invent a balance or amount. Do NOT mention tool names, UI, or forms.`}:{error:"amount_price_unavailable",chain:o,_instructions:`Could not get a USD price for ${l}${Q(o)} to work out ${i.raw} right now. Tell them, in their language, that the price couldn't be fetched at the moment and ask them to enter an exact ${l} amount instead. Do NOT invent a price or amount. Do NOT mention tool names, UI, or forms.`}}async computeNativeSpendable(e,t,r){let o=await Gs(e,t);return Ks(r,o,e)}async resolveNativeSpendableFormatted(e,t,r){if(!(!e||!t))try{let o=await this.readTokenBalanceAndPrice("native",e,t);if(o?.balance===void 0)return;let s=await this.computeNativeSpendable(e,r,o.balance);return this.toPlainDecimal(s)}catch{return}}async readTokenBalanceAndPrice(e,t,r){if(!this.moralis||!r)return;let o=await this.moralis.getWalletTokenBalances({address:r,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=o.success?o.data?.result??[]:[],a=e.toLowerCase()==="native",i=e.toLowerCase(),l=s.find(d=>a?d.native_token===!0:(d.token_address??"").toLowerCase()===i);if(!l)return;let c=l.balance_formatted!=null?Number(l.balance_formatted):void 0;return{balance:Number.isFinite(c)?c:void 0,usdPrice:typeof l.usd_price=="number"&&l.usd_price>0?l.usd_price:void 0,balanceFormatted:l.balance_formatted,symbol:l.symbol}}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let r=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.split("."),c=i+l,d;if(a>=0){let u=i.length+a;d=u>=c.length?c.padEnd(u,"0"):`${c.slice(0,u)}.${c.slice(u)}`}else d=`0.${"0".repeat(-a-i.length)}${c}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),r?`-${d}`:d}formatSpendableUsd(e,t){if(e===void 0||t===void 0)return;let r=Number(e);if(!Number.isFinite(r)||!Number.isFinite(t)||t<=0)return;let o=r*t;if(!(!Number.isFinite(o)||o<=0))return this.toPlainDecimal(o)}async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:r,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){let r=this.requireWallet(t);if(!r.ok)return r.payload;let o=this.requireChain(e,t);if(!o){let h=typeof t?.query=="string"?t.query:void 0;return Fr(this.actionType.replace(/_/g," "),h)}let s=await this.buildParameters(e,t);if(s&&typeof s=="object"&&"error"in s&&typeof s.error=="string"||s&&typeof s=="object"&&"actionButtons"in s&&Array.isArray(s.actionButtons)||s&&typeof s=="object"&&"ui"in s&&s.ui&&typeof s.ui=="object"&&typeof s.ui.component=="string")return s;let a=s,i=this.buildUI({parameters:a,chainId:o,walletAddress:r.address}),l=h=>{let g=a[h];return g!=null&&g!==""},c=this.userInputFields.filter(h=>!(Array.isArray(h.key)?h.key:[h.key]).some(l)).map(h=>h.label),d=this.userInputFields.map(h=>{let b=(Array.isArray(h.key)?h.key:[h.key]).find(l);return b?`${h.label}: ${a[b]}`:null}).filter(h=>h!=null),u=this.actionType.replace(/_/g," "),p='NEVER invent, guess, or insert a placeholder (e.g. "[recipient address]") for any detail the user has not actually provided \u2014 only state values listed as already provided. Do NOT mention tool names, UI, or forms.',m="The user completes this themselves and it is submitted right away \u2014 do NOT ask them to reply to confirm, do NOT say you will send it for them, and do NOT announce the result. This turn ends after your message.",f=c.length>0?`The ${u} is in progress but still needs input from the user. Ask the user, in their language, to provide: ${c.join(", ")}. `+(d.length>0?`Already provided: ${d.join("; ")}. `:"")+`${m} ${p}`:`The ${u} has all required details. In the user's language, briefly tell the user to review the details and submit to complete the ${u}. `+(d.length>0?`Details provided: ${d.join("; ")}. `:"")+`${m} ${p}`;return{ui:i,action:this.actionType,chainId:o,parameters:a,_instructions:f}}};var zo=class extends ot{name="open-send-native-form";actionType="send_native";component="SendNativeForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}async run(e,t){if(e.chain==null||e.chain===""){let r=Uu(e.native_symbol);if(r)return super.run({...e,chain:r},t)}return super.run(e,t)}description=`Open the SEND NATIVE form for the chain's native coin (ETH/BNB/MATIC/AVAX/\u2026). Use for ANY native-send intent: "send eth", "send 0.1 ETH", "transfer 1 BNB to vitalik.eth", "g\u1EEDi ETH". Call EVEN IF the user did not name an amount or recipient \u2014 the form prompts for them. Do NOT use for ERC-20 tokens \u2014 use open-send-token-form instead.`;parameters=[{name:"chain",type:"string",description:Ze,required:!1},{name:"native_symbol",type:"string",description:'The native coin the user named to send, VERBATIM (e.g. "ETH", "BNB", "MATIC", "AVAX"). ALWAYS set this when the user names the coin ("send bnb" \u2192 native_symbol="BNB"); leave blank only when they say just "send" with no coin. A coin that belongs to one specific chain (BNB\u2192BSC, MATIC/POL\u2192Polygon, AVAX\u2192Avalanche, XDAI\u2192Gnosis, HYPE\u2192HyperEVM, MNT\u2192Mantle, MON\u2192Monad) selects that chain, so the tool can detect when the wallet is connected elsewhere.',required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Amount of native coin to send. Accepted forms: a plain amount ("0.1"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become the literal "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself (and for the native coin always leaves enough to cover the network fee). Omit when unknown.',required:!1}];async buildParameters(e,t){let r={},o=this.requireChain(e,t)??void 0,s=t?.walletAddress??void 0,a=await this.readTokenBalanceAndPrice("native",o,s);if(!a||a.balance==null||a.balance<=0){let u=typeof e.native_symbol=="string"&&e.native_symbol.trim()?e.native_symbol.trim():void 0,p=a?.symbol||u||Fa(o)||"their native coin";return{error:"no_native_balance",chain:o,_instructions:`The user wants to send ${p} but their wallet holds 0 ${p}${Q(o)}. Tell them, in their language, that they do not have any ${p} to send${Q(o)} \u2014 name that network explicitly so they know which one is empty \u2014 and suggest they top up first. Do NOT open the form. Do NOT mention tool names, UI, or forms.`}}let i=a.symbol||(typeof e.native_symbol=="string"&&e.native_symbol.trim()?e.native_symbol.trim():void 0);if(i&&(r.native_symbol=i),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?r.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(r.to_address=e.to_address.trim())}let l=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:"native",symbol:"the native coin",chain:o,walletAddress:s,gasKind:"send"});if(l&&"error"in l)return l;l&&(r.amount=l.amount);let c=await this.resolveNativeSpendableFormatted(o,s,"send");c!==void 0&&(r.spendable=c);let d=this.formatSpendableUsd(c,a.usdPrice);return d!==void 0&&(r.spendableUsd=d),r}};var Xo=class extends ot{name="open-send-token-form";actionType="send_token";component="SendTokenForm";userInputFields=[{key:"to_address",label:"the recipient address"},{key:"amount",label:"the amount to send"}];constructor(e){super(e)}description=`Open the SEND TOKEN (ERC-20) form. Use for ANY ERC-20 send/transfer intent: "send token", "send USDC", "transfer 50 DAI to 0x\u2026", "g\u1EEDi 10 USDT". Call this tool EVEN IF the user did not name a token, amount, or recipient \u2014 the tool handles missing token via a picker, the form prompts for the rest. Do NOT use for the chain's native coin (ETH/BNB/MATIC/AVAX) \u2014 use open-send-native-form instead.`;parameters=[{name:"chain",type:"string",description:Ze,required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol \u2014 the tool will look up the address.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). ALWAYS set this whenever the user names a token to send ("send usdc" \u2192 token_symbol="USDC"); only leave it blank when the user names NO token at all ("send token"), so the tool can show a wallet picker. Used to auto-resolve the contract address and to display the symbol in the form. (Pass either this or contract_address.)',required:!1},{name:"decimals",type:"number",description:"Token decimals (e.g. 6 for USDC, 18 for most ERC-20s). Optional.",required:!1},{name:"to_address",type:"string",description:"Recipient EVM address (0x\u2026). Omit when unknown.",required:!1},{name:"amount",type:"string",description:'Amount of the token to send. Accepted forms: a plain amount ("100"); a PERCENT of their balance ("50%"); the literal word "max" for the WHOLE balance; or a USD value ("5$", "$5", "5 usd"). NORMALIZE natural-language phrasing in ANY language to one of these before passing it: any "send everything / the whole balance / maximum" phrasing \u2014 regardless of language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") \u2014 MUST become "max"; any "half" phrasing ("half", "m\u1ED9t n\u1EEDa", "\u4E00\u534A", "\u534A\u5206") MUST become "50%". Pass plain/percent/USD numbers VERBATIM. The tool converts percent/usd/max into a concrete amount itself. Omit when unknown.',required:!1},{name:"send_prompt_template",type:"string",description:`A short imperative "send" command IN THE USER'S LANGUAGE, used as the label/command when the user has not yet picked which token to send (token-picker buttons). Write it in the SAME language the user is using right now. Use these exact placeholders (do not translate the braces): "{symbol}" for the token, "{amount}" for the amount, "{to}" for the recipient address, "{chain}" for the chain name. Put the localized verb, the "to" preposition, and the "on <chain>" preposition directly in the text. English example: "send {amount} {symbol} to {to} on {chain}". Vietnamese example: "g\u1EEDi {amount} {symbol} \u0111\u1EBFn {to} tr\xEAn {chain}". Japanese example: "{chain} \u3067 {to} \u306B {amount} {symbol} \u3092\u9001\u308B". Always include {symbol}. Include {amount}/{to}/{chain} too \u2014 the tool removes any whose value is unknown.`,required:!0}];async buildParameters(e,t){let r=this.normaliseAddress(e.contract_address)!=null,o=typeof e.token_symbol=="string"&&e.token_symbol.trim().length>0;if(!r&&!o&&this.moralis){let u=this.requireChain(e,t)??void 0,p=t?.walletAddress;if(p){let m=await this.moralis.getWalletTokenBalances({address:p,chain:u,excludeSpam:!1,excludeUnverifiedContracts:!1}),h=(m.success?m.data?.result??[]:[]).filter(v=>v.symbol&&(v.native_token||v.token_address)).sort((v,S)=>(S.usd_value??0)-(v.usd_value??0)).slice(0,8);if(h.length===0)return{error:"no_token_holdings",chain:u,_instructions:`The wallet does not hold any sendable tokens${Q(u)}. Tell the user they have nothing to send${Q(u)}, naming that network explicitly, and suggest they top up first. Do NOT open the form.`};let g=e.to_address!=null?this.normaliseAddress(e.to_address):null,b=this.normaliseAmount(e.amount),y=typeof e.send_prompt_template=="string"?e.send_prompt_template:"",w=u?T(u):null;return{actionButtons:h.map(v=>{let S=v.symbol,P=v.balance_formatted?this.cleanAmountString(v.balance_formatted):"",x=v.name?v.name:"",U=v.usd_value?`($${v.usd_value.toFixed(2)})`:"";return{label:`${x}:${P} ${S} ${U}`.trim(),prompt:this.buildSendPrompt(y,S,b,g,w)}}),_instructions:"Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n g\u1EEDi token.' / 'You want to send a token.'), then ask them to choose which token from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n g\u1EEDi.' / 'Please choose the token you want to send.'). Do NOT list the tokens in text \u2014 the options already show them. Do NOT mention tool names, UI, or forms."}}}let s=this.requireChain(e,t)??void 0,a=t?.walletAddress??void 0,i=await this.findOwnedTokenForSend(e,s,a);if(i&&"error"in i)return i;let l=i?.token,c={};l?.address&&(c.contract_address=l.address),l?.symbol&&(c.token_symbol=l.symbol),l?.decimals!==void 0&&(c.decimals=String(l.decimals)),i?.spendable!==void 0&&(c.spendable=i.spendable);let d=this.formatSpendableUsd(i?.spendable,i?.usdPrice);if(d!==void 0&&(c.spendableUsd=d),e.to_address!=null){let u=this.normaliseAddress(e.to_address);u?c.to_address=u:typeof e.to_address=="string"&&e.to_address.trim()&&(c.to_address=e.to_address.trim())}if(l?.address){let u=await this.resolveAmountInput({rawAmount:e.amount,tokenAddress:l.address,symbol:l.symbol,chain:s,walletAddress:a});if(u&&"error"in u)return u;u&&(c.amount=u.amount)}else{let u=this.normaliseAmount(e.amount);u&&(c.amount=u)}return c}async findOwnedTokenForSend(e,t,r){let o=this.normaliseAddress(e.contract_address),s=typeof e.token_symbol=="string"&&e.token_symbol.trim()?e.token_symbol.trim():void 0,a=o??s;if(!this.moralis||!r||!a){let m=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:t,walletAddress:r});return"error"in m?{error:"token_not_found",symbol:m.key,_instructions:`Could not resolve token "${m.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`}:{token:m.token}}let i=a.toLowerCase(),l=o!=null,c=await this.moralis.getWalletTokenBalances({address:r,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),u=(c.success?c.data?.result??[]:[]).find(m=>l?(m.token_address??"").toLowerCase()===i:(m.symbol??"").toLowerCase()===i);if(u&&u.balance&&!/^0*$/.test(u.balance.trim())){let m=this.parseDecimals(e.decimals);return{token:{address:u.token_address,symbol:u.symbol??s,name:u.name,decimals:m??(typeof u.decimals=="number"?u.decimals:void 0)},spendable:u.balance_formatted?this.cleanAmountString(u.balance_formatted):void 0,usdPrice:typeof u.usd_price=="number"&&u.usd_price>0?u.usd_price:void 0}}let p=u?.symbol??s??a;return{error:"no_balance",symbol:p,chain:t,_instructions:`The user does not hold any ${p} in their wallet${Q(t)}, so there is nothing to send. Tell them (in their language) that they don't have any ${p} to send${Q(t)} \u2014 name that network explicitly so they know which one is empty \u2014 and suggest they top up or pick another token. Do NOT open a form. Do NOT mention tool names, UI, or forms.`}}buildSendPrompt(e,t,r,o,s){let i=(e&&e.includes("{symbol}")?e:"send {amount} {symbol} to {to} on {chain}").replace(/\{symbol\}/g,t).replace(/\{amount\}/g,r??"");return i=this.fillOrDropPhrase(i,"{to}",o),i=this.fillOrDropPhrase(i,"{chain}",s),i.replace(/\s+/g," ").trim()}fillOrDropPhrase(e,t,r){if(r)return e.split(t).join(r);let o=t.replace(/[{}]/g,"\\$&");return e.replace(new RegExp(`\\s*\\S+\\s*${o}`,"g"),"").replace(new RegExp(`${o}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(o,"g"),"")}};var Qo=class extends ot{name="open-approve-token-form";actionType="approve_token";component="ApproveTokenForm";userInputFields=[{key:"spender_address",label:"the spender address to approve"}];constructor(e){super(e)}description='Open the APPROVE TOKEN form so the user can grant a spender allowance on an ERC-20 token. Use when the user says "approve USDC for Uniswap", "c\u1EA5p quy\u1EC1n 100 USDT cho 0x\u2026", "revoke approval". Pass `contract_address` when you have it; otherwise pass `token_symbol` (e.g. "USDC") and the tool auto-resolves the contract. Always pass `spender_address` (the contract being approved). Pass `amount` for a specific allowance; omit for unlimited (max uint256). For approving 0 to revoke, pass amount="0".';parameters=[{name:"chain",type:"string",description:Ze,required:!1},{name:"contract_address",type:"string",description:"ERC-20 token contract address (0x\u2026). Pass when known. Otherwise leave empty and provide token_symbol.",required:!1},{name:"token_symbol",type:"string",description:'Token symbol (e.g. "USDC"). Required when contract_address is not given. Used to auto-resolve the contract.',required:!1},{name:"decimals",type:"number",description:"Token decimals.",required:!1},{name:"spender_address",type:"string",description:"EVM address of the spender contract being approved (0x\u2026). Omit when unknown \u2014 the form will prompt the user.",required:!1},{name:"amount",type:"string",description:'Human-readable allowance amount. Omit for UNLIMITED (max uint256). Pass "0" to revoke.',required:!1}];async buildParameters(e,t){let r=this.requireChain(e,t)??void 0,o=await this.resolveTokenRef({contractArg:e.contract_address,symbolArg:e.token_symbol,decimalsArg:e.decimals,chain:r,walletAddress:t?.walletAddress??void 0});if("error"in o)return{error:"token_not_found",symbol:o.key,_instructions:`Could not resolve token "${o.key}" to a contract address on this chain. Ask the user to provide the token contract directly.`};let s=o.token,a=this.normaliseAddress(e.spender_address),i={};if(s?.address&&(i.contract_address=s.address),a&&(i.spender_address=a),s?.symbol&&(i.token_symbol=s.symbol),s?.decimals!==void 0&&(i.decimals=String(s.decimals)),typeof e.amount=="string"&&e.amount.trim()){let l=e.amount.trim(),c=parseFloat(l);Number.isFinite(c)&&c>=0&&(i.amount=l)}else typeof e.amount=="number"&&Number.isFinite(e.amount)&&e.amount>=0&&(i.amount=String(e.amount));return i}};function Ai(n){let{action:e,fromSym:t,toSym:r,amount:o,spendable:s}=n,a=e==="swap"?`swap ${t} to ${r}`:`buy ${r} with ${t}`,i=e==="swap"?"swapping":"buying",l=e==="swap"?`swap ${o} ${t} to ${r}`:`buy ${r} with ${o} ${t}`,c=s?` They have ${s} ${t} available to spend.`:"";return(o?`The user wants to ${l}.${c} Reply briefly in the user's language confirming the amount and asking them to review and complete it. `:`The user wants to ${a}.${c} Reply briefly in the user's language: state what they want to do${s?" and their available balance":""}, then ask how much they want to ${e}. `)+`Do NOT list amounts or percentages, and do NOT state an estimated receive amount or a rate \u2014 you do not have one. Speak only of the user's action (${i}) \u2014 NEVER say you 'opened' a panel/form/window or describe any UI being shown. NEVER invent numbers not provided here. Do NOT mention tool names, UI, buttons, or forms.`}var qt=n=>n.logo||n.icon_image||n.logoURI||n.thumbnail||void 0,wc=n=>typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0;async function zs(n){let{moralis:e,tokenAddress:t,chain:r}=n;if(!e)return null;let o=t==="native"?ue:t;try{let s=await e.getTokenMetadata({address:o,chain:r});return wc(s.success?s.data?.usd_price:void 0)??null}catch{return null}}var Hy=n=>Number.isFinite(n)?vs(parseFloat(n.toPrecision(8))):"0",Vy=n=>{if(!/e/i.test(n))return n;let e=Number(n);return Number.isFinite(e)?vs(e):n};async function Xs(n){let{moralis:e,walletAddress:t,tokenAddress:r,chain:o,kind:s="swap",feeContext:a,dbg:i}=n;if(!e)return null;let l=await e.getWalletTokenBalances({address:t,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1}),c=l.success?l.data?.result??[]:[];i?.("readSpendableBalance",{tokenAddress:r,chain:o,ok:l.success,count:c.length});let d=r.toLowerCase(),u=c.find(m=>d==="native"?m.native_token===!0:m.token_address?.toLowerCase()===d);if(!u?.balance_formatted)return i?.("readSpendableBalance: token NOT held \u2192 null",{tokenAddress:r}),null;let p=Number(u.balance_formatted);if(!Number.isFinite(p)||p<=0)return i?.("readSpendableBalance: zero/invalid balance \u2192 null",{tokenAddress:r,balance:u.balance_formatted}),null;if(d==="native"&&o){let m=await Gs(o,s,a??{}),f=Ks(p,m,o);if(i?.("readSpendableBalance: native spendable",{balanceNum:p,spendable:f}),f<=0)return i?.("readSpendableBalance: native spendable \u2264 0 \u2192 null",{balanceNum:p}),null;let h=Hy(f),g=typeof u.decimals=="number"?u.decimals:18;return yp({balanceFormatted:h,balanceNum:f,symbol:u.symbol,decimals:g,logo:qt(u),usdPrice:wc(u.usd_price)})}return i?.("readSpendableBalance: held",{tokenAddress:r,balance:u.balance_formatted,symbol:u.symbol}),yp({balanceFormatted:u.balance_formatted,balanceNum:p,symbol:u.symbol,decimals:typeof u.decimals=="number"?u.decimals:void 0,logo:qt(u),usdPrice:wc(u.usd_price)})}function yp(n){let e=Vy(n.balanceFormatted),t=n.decimals===void 0?null:Bn(e,n.decimals);return{...n,balanceFormatted:e,rawAmount:t?.toString()}}async function Pi(n,e){let t=n?Ce(n)?.nativeCurrency:void 0,r=e.map(a=>a&&(a.address==="native"?{...a,symbol:t?.symbol??a.symbol,decimals:t?.decimals??a.decimals,symbolIsOnchain:t?.symbol?!0:a.symbolIsOnchain??!1}:{...a})),o=[];if(r.forEach((a,i)=>{if(!a||a.address==="native"||!R(a.address))return;let l=a.symbolIsOnchain===!0&&!!a.symbol?.trim(),c=typeof a.decimals=="number"&&Number.isFinite(a.decimals);l&&c||o.push({index:i,address:a.address})}),!n||o.length===0)return r;let s=await on(n,o.map(a=>a.address)).catch(()=>[]);return o.forEach((a,i)=>{let l=s[i];if(!l)return;let c=r[a.index];typeof l.symbol=="string"&&l.symbol.trim()&&(c.symbol=l.symbol.trim(),c.symbolIsOnchain=!0),typeof l.decimals=="number"&&Number.isFinite(l.decimals)&&(c.decimals=l.decimals)}),r}function Si(n,e){let t=n?.trim().toLowerCase(),r=e?.trim().toLowerCase();return!t||!r?!1:t===r}var Jo=class extends A{name="open-buy-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new O(e),this.pantograph=new Ae({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[BuyTokenTool] ${e}`):console.log(`[BuyTokenTool] ${e}`,JSON.stringify(t)))}description='Open the BUY TOKEN flow for ANY buy/purchase intent. Handles both cases: (a) the user NAMED a token \u2014 "buy PEPE", "mua DOGE", "buy 100 USDC with ETH": pass `token_symbol` (the destination); if you also know the pay token, fill `pay_with_symbol` (or `pay_with_address`), else leave pay_with_* blank and the tool returns a wallet picker. (b) the user did NOT name a token \u2014 "buy a trending token", "mua token trending", "buy something pumping", "buy hot tokens", "mua token t\u0103ng m\u1EA1nh": leave `token_symbol` blank and the tool returns buttons of the chain\'s current trending tokens so the user picks one. Amount: `buy_amount` = destination to RECEIVE; `pay_with_amount` = payment to SPEND. Never both. CHAINS: when the user names a DIFFERENT network per side \u2014 "buy USDC on Base with ETH on Arbitrum" \u2014 you MUST put each one in `token_chain` and `pay_with_chain` (NOT in `chain`, and never drop one of them): that is a cross-chain request and the tool answers it with the correct unsupported message. Use the single `chain` parameter only when ONE network covers the whole request.';parameters=[{name:"chain",type:"string",description:Ze,required:!1},{name:"token_chain",type:"string",description:Mr("token being BOUGHT"),required:!1},{name:"pay_with_chain",type:"string",description:Mr("token being SPENT to pay"),required:!1},{name:"token_symbol",type:"string",description:'Symbol of the token the user wants to BUY (e.g. "PEPE"). Leave EMPTY when the user did not name a token (e.g. "buy a trending token") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"contract_address",type:"string",description:`Destination token address (0x\u2026), or "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from token_symbol.`,required:!1},{name:"buy_amount",type:"string",description:`Quantity of the DESTINATION token (the one being bought) the user wants to RECEIVE. Set this when the amount sits next to the token being bought: "buy 5 PEPE", "mua 5 PEPE", "buy 0.02 PCM with USDC" \u2192 buy_amount = the number next to PEPE/PCM. May also be a USD value when the user sizes the buy in dollars ("buy $5 of PEPE" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$" to a token quantity). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with pay_with_amount \u2014 set at most ONE of the two.`,required:!1},{name:"pay_with_symbol",type:"string",description:'Symbol of the payment token (e.g. "USDC", "ETH"). Set ONLY when the user actually named a token to pay with. Leave EMPTY when they did not \u2014 do NOT default to the native coin / ETH; the tool then returns a picker of the tokens the wallet holds.',required:!1},{name:"pay_with_address",type:"string",description:`Address of the payment token (0x\u2026), OR "native" for the chain's native coin. Set ONLY when the user named the payment token. Leave EMPTY when they did not \u2014 do NOT invent an address or default to native.`,required:!1},{name:"pay_with_amount",type:"string",description:'Quantity of the PAYMENT token (the one being spent) the user wants to SPEND. Set this when the amount sits next to the payment token: "buy PEPE with 10 USDC", "mua PEPE b\u1EB1ng 10 USDC", "spend 0.5 ETH on DOGE" \u2192 pay_with_amount = the number next to USDC/ETH. May also be a PERCENT of the pay-token balance ("buy USDC with 50% USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("buy USDC with 5$ USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set pay_with_symbol to the payment token ("ETH" in "buy USDC with max ETH"). Leave EMPTY when the user gave NO amount \u2014 do NOT invent a number; the tool then asks for the amount. Mutually exclusive with buy_amount \u2014 set at most ONE of the two.',required:!1},{name:"limit",type:"number",description:"Only used when no token is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"buy_prompt_template",type:"string",description:`A short "buy" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the trending-token picker (when the user named no token). Use the exact placeholder "{token}" (do not translate the braces) for the token symbol; put the localized verb directly in the text. English example: "buy {token}". Vietnamese example: "mua {token}". Japanese example: "{token} \u8CFC\u5165". Always include {token}. Do NOT write the chain name yourself \u2014 the chain these tokens are on is appended automatically as a "(<chain>)" suffix, e.g. "buy PEPE (Base)".`,required:!0},{name:"buy_with_prompt_template",type:"string",description:`A short "buy X with Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the pay-token picker and the percentage-spend buttons. Use these exact placeholders (do not translate the braces): "{token}" = token being bought, "{pay}" = payment token, "{buy_amount}" = quantity of the BOUGHT token (place it next to {token}), "{pay_amount}" = quantity of the PAYMENT token (place it next to {pay}). Put the localized verb and the "with" preposition directly in the text. English example: "buy {buy_amount} {token} with {pay_amount} {pay}". Vietnamese example: "mua {buy_amount} {token} b\u1EB1ng {pay_amount} {pay}". Japanese example: "{pay_amount} {pay} \u3067 {buy_amount} {token} \u8CFC\u5165". Always include {token} and {pay}. Include both {buy_amount} and {pay_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount). Do NOT write the chain name yourself \u2014 the chain is appended automatically as a "(<chain>)" suffix, e.g. "buy PEPE with ETH (Base)".`,required:!0}];async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:r,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before buying. Do NOT proceed."};let o=Ba(e.pay_with_chain,e.token_chain);if(o)return qa("buy",o);if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return Fr("buy",a)}return this.buildResult(e,t)}async buildResult(e,t){this.correctAmountSide(e,t),this.dropUnmentionedPayToken(e,t),this.dropInventedAmounts(e,t);let r=typeof e.token_symbol=="string"?e.token_symbol.trim():"",o=typeof e.contract_address=="string"?e.contract_address.trim():"",s=this.requireChain(e,t)??void 0,a=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:s,walletAddress:a,hasMoralis:!!this.moralis}),!r&&!o)return this.dbg("\u2192 Branch 0: trending picker (no token named)"),await this.buildTrendingPicker(e,t);let[i,l]=await Promise.all([this.resolveSide(e.contract_address,r,s,a,"dest"),this.resolveSide(e.pay_with_address,e.pay_with_symbol,s,a,"pay")]),[c,d]=await Pi(s,[i.address?{...i,address:i.address}:void 0,l.address?{...l,address:l.address}:void 0]),u=i.address,p=c?.symbol??r,m=c?.decimals,f=i.logo,h=l.address,g=d?.symbol,b=d?.decimals,y=await this.resolveBuyAmountSpec(e.buy_amount,u,s,p),w=h?await this.resolvePayAmountSpec(e.pay_with_amount,h,s,a,g,b??(h==="native"?18:void 0)):this.normaliseAmount(e.pay_with_amount),k=_t(e.pay_with_amount),v=!!k&&k.kind!=="token",S=null;if(this.dbg("resolved sides",{dest:{destContract:u,destSymbol:p,destDecimals:m},pay:{payAddr:h,paySymbol:g,payDecimals:b},buyAmount:y,payAmount:w}),!u)return this.dbg("\u2192 dest token not resolved"),{error:"dest_token_not_found",_instructions:`Could not find the token "${p||o}" to buy on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(Si(h,u))return this.dbg("\u2192 same token both sides",{payAddr:h,destContract:u,paySymbol:g,destSymbol:p}),{error:"same_token",_instructions:`The user asked to buy ${p} and pay with ${g??p} \u2014 the SAME token on both sides, which buys nothing and cannot be done. Tell them, in their language, that the token they pay with has to be different from the token they are buying, and ask which token they want to pay with instead. Do NOT proceed. Do NOT render the form. Do NOT mention tool names, UI, or forms.`};if(!h&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: pay picker (pay token missing)"),await this.buildPayWithPicker({args:e,userContext:t,destSymbol:p,destContract:u,buyAmount:y,payAmount:w});if(!h)return{error:"pay_token_missing",_instructions:`Ask the user, in their language, which token they want to spend to buy ${p}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(y&&!w){this.dbg("Branch 1.3: deriving pay amount from buy amount",{buyAmount:y,destSymbol:p,paySymbol:g});let P=await this.derivePayAmountFromBuy({chain:s,buyAmount:y,destContract:u,destSymbol:p,payAddr:h,paySymbol:g});if(!P)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs pay amount"),{error:"needs_pay_amount",_instructions:`Could not work out how much ${g??"of the payment token"} equals ${y} ${p} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${g??"of the payment token"} they want to spend instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};w=P,S=y,v=!1,this.dbg("\u2192 Branch 1.3: derived pay amount",{payAmount:w,derivedFromBuy:S})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking pay balance",{payAddr:h,paySymbol:g,payAmount:w});let P=await this.checkPayBalance({args:e,userContext:t,chain:s,destSymbol:p,destContract:u,payAddr:h,paySymbol:g,payAmount:w,buyAmount:y,derivedFromBuy:S,amountSizedToBalance:v});if(P)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:P.error,hasButtons:Array.isArray(P.actionButtons)}),P;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!y&&t?.walletAddress){this.dbg("Branch 1.5: building amount form",{payAmount:w});let P=await this.buildAmountForm({userContext:t,chain:s,destContract:u,destSymbol:p,destDecimals:m,destLogo:f,payAddr:h,paySymbol:g,payDecimals:b,payAmount:w??void 0});if(P)return this.dbg("\u2192 Branch 1.5: amount form returned"),P;this.dbg("Branch 1.5: amount form null \u2014 needs a resolvable pay token")}return this.dbg("\u2192 needs pay amount"),{error:"needs_pay_amount",_instructions:`Ask the user, in their language, how much ${g??"of the payment token"} they want to spend to buy ${p}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return R(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let r=t.match(/^([0-9]*\.?[0-9]+)(?:\s+[a-zA-Z][a-zA-Z0-9]*)?$/);if(!r)return null;let o=parseFloat(r[1]);return Number.isFinite(o)&&o>0?r[1]:null}correctAmountSide(e,t){let r=typeof t?.query=="string"?t.query:"",o=typeof e.token_symbol=="string"?e.token_symbol.trim():"",s=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"";if(!r||!o||!s)return;let a=typeof e.buy_amount=="string"?e.buy_amount.trim():"",i=typeof e.pay_with_amount=="string"?e.pay_with_amount.trim():"",l=a.length>0,c=i.length>0;if(l===c)return;let d=l?a:i,u=d.match(/[0-9]*\.?[0-9]+/)?.[0];if(!u)return;let p=this.nearestSymbolSide(r,u,o,s);p&&(p==="pay"&&l?(this.dbg("correctAmountSide: buy_amount \u2192 pay_with_amount",{amount:d,buySym:o,paySym:s}),e.pay_with_amount=d,e.buy_amount=""):p==="buy"&&c&&(this.dbg("correctAmountSide: pay_with_amount \u2192 buy_amount",{amount:d,buySym:o,paySym:s}),e.buy_amount=d,e.pay_with_amount=""))}dropUnmentionedPayToken(e,t){let r=typeof t?.query=="string"?t.query:"";if(!r)return;let o=typeof e.token_symbol=="string"?e.token_symbol.trim():"";if(!o)return;let s=typeof e.pay_with_symbol=="string"?e.pay_with_symbol.trim():"",a=typeof e.pay_with_address=="string"?e.pay_with_address.trim():"";if(!s&&!a)return;let i=r.toLowerCase(),l=s.toLowerCase(),c=a.toLowerCase(),d=l==="native"||c==="native",u=[];if(s&&l!=="native"&&u.push(l),c&&c!=="native"&&u.push(c),d){u.push("native");let m=this.requireChain(e,t)??void 0,f=m?Un(m)?.symbol:void 0;f&&u.push(f.toLowerCase())}u.some(m=>R(m)?i.includes(m):this.indexOfToken(i,m)>=0)||(this.dbg("dropUnmentionedPayToken: clearing invented pay token",{paySym:s,payAddr:a,buySym:o}),e.pay_with_symbol="",e.pay_with_address="")}dropInventedAmounts(e,t){let r=typeof t?.query=="string"?t.query:"";if(!r)return;let o=(r.match(/[0-9]*\.?[0-9]+/g)??[]).map(parseFloat).filter(Number.isFinite),s=a=>{let i=typeof e[a]=="string"?e[a].trim():"";if(!i)return;let l=i.match(/[0-9]*\.?[0-9]+/)?.[0];if(l===void 0)return;let c=parseFloat(l);Number.isFinite(c)&&(o.some(d=>d===c)||(this.dbg(`dropInventedAmounts: clearing invented ${a}`,{val:i}),e[a]=""))};s("buy_amount"),s("pay_with_amount")}nearestSymbolSide(e,t,r,o){let s=e.toLowerCase(),a=s.indexOf(t.toLowerCase()),i=this.indexOfToken(s,r.toLowerCase()),l=this.indexOfToken(s,o.toLowerCase());if(a<0||i<0||l<0)return null;let c=(p,m)=>Math.max(0,p-(a+t.length),a-(p+m)),d=c(i,r.length),u=c(l,o.length);return u===d?null:u<d?"pay":"buy"}indexOfToken(e,t){if(!t)return-1;let r=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=e.match(new RegExp(`(?:^|[^a-z0-9])(${r})(?:[^a-z0-9]|$)`));return o&&o.index!==void 0?o.index+o[0].indexOf(o[1]):-1}requireChain(e,t){return K(e.chain,t)}async resolveContractAddress(e,t,r){if(!this.moralis||!e)return;let o=e.trim().toLowerCase(),s=R(e.trim()),a=l=>s?(l.token_address??"").toLowerCase()===o:(l.symbol??"").toLowerCase()===o;if(r){let l=await this.moralis.getWalletTokenBalances({address:r,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:qt(c)}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:qt(c),symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}async resolveSide(e,t,r,o,s="side"){let a=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(a.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,d=m=>m.toLowerCase()===ue?"native":m,u=l??c??(a||void 0);if(!u)return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(u,r,o);return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,key:u,lookup:p}),p?{address:d(p.address),symbol:p.symbolIsOnchain?p.symbol:c??p.symbol,decimals:p.decimals,logo:p.logo,symbolIsOnchain:p.symbolIsOnchain??!1}:l?{address:d(l),symbol:c}:{address:null,symbol:c}}async derivePayAmountFromBuy(e){let{chain:t,buyAmount:r,destContract:o,payAddr:s}=e,[a,i]=await Promise.all([this.getUsdPrice(o,t),this.getUsdPrice(s,t)]);if(this.dbg("derivePayAmountFromBuy: prices",{destPrice:a,payPrice:i}),!a||!i)return null;let l=Number(r);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,d=l*a/i;return!Number.isFinite(d)||d<=0?null:this.trimAmount(d*c)}async getUsdPrice(e,t){return zs({moralis:this.moralis,tokenAddress:e,chain:t})}async resolvePayAmountSpec(e,t,r,o,s,a){let i=_t(e);if(!i)return null;let l=d=>a===void 0?d:Dt(d,a);if(i.kind==="token")return l(qn(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!o)return null;let d=await this.readPayBalance(o,t,r);if(this.dbg("resolvePayAmountSpec: percent",{percent:i.percent,paySymbol:s,bal:d?.balanceNum}),!d||!Number.isFinite(d.balanceNum)||d.balanceNum<=0)return null;let u=d.decimals??a??18;return i.percent>=100?this.cleanAmountString(d.balanceFormatted):$n(d.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,u)}let c=await this.getUsdPrice(t,r);return this.dbg("resolvePayAmountSpec: usd",{usd:i.usd,paySymbol:s,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveBuyAmountSpec(e,t,r,o){let s=_t(e);if(!s)return null;if(s.kind==="token")return qn(e)??this.toPlainDecimal(s.value);if(s.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,r);return this.dbg("resolveBuyAmountSpec: usd",{usd:s.usd,destSymbol:o,price:a}),a?this.trimAmount(s.usd/a):null}async buildPayWithPicker(e){let{args:t,userContext:r,destSymbol:o,destContract:s}=e,a=this.requireChain(t,r)??void 0,i=this.moralis,l=r.walletAddress,c=await i.getWalletTokenBalances({address:l,chain:a,excludeSpam:!1,excludeUnverifiedContracts:!1}),d=c.success?c.data?.result??[]:[],u=s?.toLowerCase(),p=o.trim().toLowerCase(),m=d.filter(y=>!y.symbol||p&&y.symbol.toLowerCase()===p?!1:y.native_token?u!=="native":!(!y.token_address||u&&y.token_address.toLowerCase()===u)).sort((y,w)=>(w.usd_value??0)-(y.usd_value??0)).slice(0,8);if(m.length===0)return{error:"no_pay_token_holdings",chain:a,_instructions:`The wallet has no tokens that can pay for this purchase${Q(a)}. Tell the user to top up first, naming that network explicitly so they know which one is empty. Do NOT mention tool names, UI, or forms.`};let f=e.buyAmount??this.normaliseAmount(t.buy_amount),h=e.payAmount??this.normaliseAmount(t.pay_with_amount),g=typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"";return{actionButtons:m.map(y=>{let w=y.symbol,k=y.name?.trim()||w,v=y.balance_formatted?`${this.cleanAmountString(y.balance_formatted)} `:"",S=typeof y.usd_value=="number"&&y.usd_value>0?` ($${y.usd_value.toFixed(2)})`:"",P=`${k}: ${v}${w}${S}`,x=f?this.buildBuyWithPrompt(g,o,w,f,null,a):this.buildBuyWithPrompt(g,o,w,null,h,a);return{label:P,prompt:x}}),_instructions:`Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n mua ${o}.' / 'You want to buy ${o}.'), then ask them to choose which token they want to spend to buy ${o} from the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua.' / 'Please choose the token to spend.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms.`}}async checkPayBalance(e){let{args:t,userContext:r,chain:o,destSymbol:s,destContract:a,payAddr:i,payAmount:l,buyAmount:c,derivedFromBuy:d}=e,u=r.walletAddress,p=await this.readPayBalance(u,i,o),m=e.paySymbol??p?.symbol??"the selected token";if(!p){this.dbg("checkPayBalance: NOT held \u2192 pay picker fallback",{paySymbol:m});let y=await this.buildPayWithPicker({args:t,userContext:r,destSymbol:s,destContract:a,buyAmount:c,payAmount:l});return"actionButtons"in y?{error:"no_pay_balance",actionButtons:y.actionButtons,_instructions:`The user wanted to spend ${m} to buy ${s}, but their wallet holds no ${m}${Q(o)}. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them they don't have any ${m}${Q(o)}, naming that network explicitly (e.g., 'B\u1EA1n kh\xF4ng c\xF3 ${m} tr\xEAn ${Q(o).replace(" on ","")}.'), then ask them to choose one of the tokens they already hold to pay with (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n d\xF9ng \u0111\u1EC3 mua ${s} t\u1EEB danh s\xE1ch b\xEAn d\u01B0\u1EDBi.' / 'Please choose a token to pay with from the options below.'). Do NOT list the tokens in text, do NOT invent a balance, and do NOT mention tool names, UI, or forms.`}:y}if(i.toLowerCase()!=="native"){let y=await js({chainId:o,gasKind:"swap",readNativeBalance:()=>this.readNativeHeldBalance(u,o)});if(y)return this.dbg("checkPayBalance: cannot cover gas",y),{error:"insufficient_native_for_gas",_instructions:`The wallet holds ${m} but cannot cover the network fee for this purchase: it needs about ${y.shortfall} more ${y.nativeSymbol}. Tell the user in their language that they need roughly ${y.shortfall} more ${y.nativeSymbol} to pay the network fee before they can buy ${s} (e.g., 'B\u1EA1n c\u1EA7n th\xEAm kho\u1EA3ng ${y.shortfall} ${y.nativeSymbol} \u0111\u1EC3 tr\u1EA3 ph\xED m\u1EA1ng.'), and suggest they top up ${y.nativeSymbol} first. Do NOT open a form, do NOT invent a different number, and do NOT mention tool names, UI, or forms.`}}if(!l||e.amountSizedToBalance)return null;let f=p.decimals!==void 0?Dt(l,p.decimals):l;if(sn(f,p.balanceFormatted)<=0)return null;let h=this.cleanAmountString(p.balanceFormatted),g=this.percentSpendButtons({balanceFormatted:p.balanceFormatted,balanceNum:p.balanceNum,decimals:p.decimals,paySymbol:m,destSymbol:s,buyWithTemplate:typeof t.buy_with_prompt_template=="string"?t.buy_with_prompt_template:"",...o===void 0?{}:{chain:o}}),b=d?`Buying ${d} ${s} needs about ${l} ${m}, but they only have ${h} ${m}${Q(o)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them that buying ${d} ${s} would cost about ${l} ${m}, which is more than their balance of ${h} ${m}, then ask them to choose a smaller amount or spend less \u2014 `:`The user wants to spend ${l} ${m} to buy ${s}, but they only have ${h} ${m}${Q(o)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${l} ${m} exceeds their balance of ${h} ${m}, then ask them to choose a smaller amount \u2014 `;return{error:"insufficient_pay_balance",actionButtons:g,_instructions:b+'invite them to choose one of the options below (sized to their balance) or type the amount they want. CRITICAL: clickable percentage buttons are rendered separately below your message \u2014 your text must NOT contain any "%", percentage values, or a list of amounts (no "25%", "50%", "75%", "100%"). Do NOT invent numbers, and do NOT mention tool names, UI, buttons, or forms.'}}async readPayBalance(e,t,r){return Xs({moralis:this.moralis,walletAddress:e,tokenAddress:t,chain:r,kind:"swap",dbg:(o,s)=>this.dbg(o,s)})}async readNativeHeldBalance(e,t){if(!this.moralis)return{balance:0};try{let r=await this.moralis.getWalletTokenBalances({address:e,chain:t,excludeSpam:!1,excludeUnverifiedContracts:!1}),s=(r.success?r.data?.result??[]:[]).find(i=>i.native_token===!0),a=s?.balance_formatted!=null?Number(s.balance_formatted):0;return{balance:Number.isFinite(a)?a:0,...s?.symbol===void 0?{}:{symbol:s.symbol}}}catch{return{balance:0}}}percentSpendButtons(e){let{balanceFormatted:t,decimals:r,paySymbol:o,destSymbol:s,buyWithTemplate:a,chain:i}=e,l=r??18;return[25,50,75,100].map(d=>{let u=$n(this.cleanAmountString(t),BigInt(d),100n,l);return{label:`${d}%`,prompt:this.buildBuyWithPrompt(a,s,o,null,u,i)}})}async buildAmountForm(e){let{userContext:t,chain:r,destContract:o,destSymbol:s,destDecimals:a,destLogo:i,payAddr:l,payAmount:c}=e,d=t.walletAddress;if(!r)return null;let u=Ce(r);if(!u)return null;let p=await this.readPayBalance(d,l,r),m=e.paySymbol??p?.symbol;if(!m)return null;let f=l==="native",h=p?.decimals??e.payDecimals??(f?u.nativeCurrency.decimals??18:void 0);if(h===void 0)return null;let g=p?.balanceFormatted,b=p?.rawAmount??(g?Bn(g,h)?.toString():void 0),y=await this.getUsdPrice(o,r).catch(()=>null);return{ui:{component:"SwapTokenForm",props:{chain:{hexId:r,name:u.name},fromToken:{address:f?"native":l,symbol:m,decimals:h,amount:g,rawAmount:b??void 0,logo:p?.logo,usdPrice:p?.usdPrice},toToken:{address:o,symbol:s,decimals:a,logo:i,usdPrice:y??void 0},walletAddress:d,intent:"buy",initialAmount:c}},_instructions:Ai({action:"buy",fromSym:m,toSym:s,amount:c,spendable:g})}}trimAmount(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(8))):"0"}toPlainDecimal(e){let t=String(e);if(!/e/i.test(t))return t;let r=e<0,[o,s]=Math.abs(e).toString().split("e"),a=Number(s),[i,l=""]=o.split("."),c=i+l,d;if(a>=0){let u=i.length+a;d=u>=c.length?c.padEnd(u,"0"):`${c.slice(0,u)}.${c.slice(u)}`}else d=`0.${"0".repeat(-a-i.length)}${c}`;return d.includes(".")&&(d=d.replace(/\.?0+$/,"")),r?`-${d}`:d}cleanAmountString(e){if(!/e/i.test(e))return e;let t=Number(e);return Number.isFinite(t)?this.toPlainDecimal(t):e}buildBuyPrompt(e,t,r){return(e&&e.includes("{token}")?e:"buy {token}").replace(/\{token\}/g,t).replace(/\s+/g," ").trim()+er(r)}buildBuyWithPrompt(e,t,r,o,s,a){return(e&&e.includes("{token}")&&e.includes("{pay}")?e:"buy {buy_amount} {token} with {pay_amount} {pay}").replace(/\{token\}/g,t).replace(/\{pay\}/g,r).replace(/\{buy_amount\}/g,o??"").replace(/\{pay_amount\}/g,s??"").replace(/\s+/g," ").trim()+er(a)}async buildTrendingPicker(e,t){if(!this.pantograph)return{error:"trending_unavailable",_instructions:"Trending tokens are unavailable in this build (service not configured). Tell the user briefly and ask them to name a token to buy."};let r=this.requireChain(e,t)??void 0,o=typeof e.limit=="number"&&Number.isFinite(e.limit)?Math.floor(e.limit):6,s=Math.max(1,Math.min(10,o)),a=await this.pantograph.getTrendingTokens({chain:r,limit:s}),i=a.success?a.data??[]:[];if(i.length===0)return{error:"no_trending_tokens",_instructions:"No trending tokens are available for this chain right now. Tell the user briefly and suggest they name a token directly."};let l=i.filter(m=>m.symbol),c=typeof e.buy_prompt_template=="string"?e.buy_prompt_template:"",d=l.map(m=>{let f=m.symbol;return{label:f,prompt:this.buildBuyPrompt(c,f,r)}}),p=l.map((m,f)=>{let h=m.name?.trim()||m.symbol,g=m.symbol,b=typeof m.usdPrice=="number"&&m.usdPrice>0?`$${this.formatPrice(m.usdPrice)}`:"N/A",y=m.pricePercentChange?.["24h"],w=typeof y=="number"&&Number.isFinite(y)?` (${y>0?"+":y<0?"-":""}${this.formatPercent(Math.abs(y))}%)`:"";return`${f+1}. ${h} (${g}) \u2014 ${b}${w}`}).join(`
211
211
  `)+`
212
212
 
213
213
  Is there any token you want to buy?`;return{actionButtons:d,_instructions:`The trending tokens are on ${r?T(r):"the connected chain"}. Reply in the user's language using the pattern 'state intent \u2192 ask to choose'. Start with a one-line header that states the user's intent (e.g., 'B\u1EA1n mu\u1ED1n mua token \u2014 \u0111\xE2y l\xE0 c\xE1c token \u0111ang trending tr\xEAn <chain name>:' / '\u{1F4C8} You want to buy a token \u2014 here are the tokens currently trending upwards on <chain name>:'), then output EXACTLY the following list, preserving the line breaks, ordering, prices, and percentages verbatim (translate only the wording, never the numbers). The list already ends with a 'choose' prompt. Do NOT add or remove tokens, and do NOT mention tool names, UI, or forms:
214
214
 
215
- ${p}`}}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),r=t.match(/^0\.0*([1-9]\d{0,3})/);return r?t.slice(0,(r[0].length||0)+0):t}};var Zo=class extends A{name="open-swap-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new O(e),this.pantograph=new Ae({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[SwapTokenTool] ${e}`):console.log(`[SwapTokenTool] ${e}`,JSON.stringify(t)))}description='Open the SWAP TOKEN flow for ANY swap/exchange/convert intent where the user swaps a token they ALREADY HOLD into another token \u2014 "swap USDC to USDT", "swap USDC", "\u0111\u1ED5i USDC sang ETH", "convert DAI to USDC", "exchange 10 USDC for PEPE". The FROM token is the user\'s own holding (the source). Handles both cases: (a) the user named the destination \u2014 "swap USDC to USDT": pass `from_symbol` (the source, e.g. "USDC") and `to_symbol` (the destination, e.g. "USDT"). (b) the user named only the source \u2014 "swap USDC": pass `from_symbol` and leave `to_symbol` blank; the tool returns buttons of the chain\'s current trending tokens so the user picks what to receive. If the user named NO token at all \u2014 "swap" / "\u0111\u1ED5i token": leave both blank and the tool returns the wallet\'s holdings so the user picks what to swap FROM. Amount: `from_amount` = source to SPEND; `to_amount` = destination to RECEIVE. Never both. CHAINS: when the user names a DIFFERENT network for each side \u2014 "swap ETH on Optimism to ETH on Base", "\u0111\u1ED5i ETH tr\xEAn OP sang ETH tr\xEAn Base" \u2014 you MUST put each one in `from_chain` and `to_chain` (NOT in `chain`, and never drop one of them): that is a cross-chain request and the tool answers it with the correct unsupported message. Use the single `chain` parameter only when ONE network covers the whole request.';parameters=[{name:"chain",type:"string",description:Ze,required:!1},{name:"from_chain",type:"string",description:Mr("SOURCE token being swapped FROM"),required:!1},{name:"to_chain",type:"string",description:Mr("DESTINATION token being received"),required:!1},{name:"from_symbol",type:"string",description:`Symbol of the SOURCE token the user wants to swap FROM \u2014 a token they already hold (e.g. "USDC"). Leave EMPTY only when the user named no token at all (e.g. "swap") \u2014 the tool then returns the wallet's holdings to pick the source from.`,required:!1},{name:"from_address",type:"string",description:`Source token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from from_symbol.`,required:!1},{name:"from_amount",type:"string",description:'Quantity of the SOURCE token (the one being swapped FROM / spent) the user wants to SPEND. Set this when the amount sits next to the source token: "swap 10 USDC to USDT", "\u0111\u1ED5i 10 USDC sang ETH" \u2192 from_amount = the number next to USDC. May also be a PERCENT of the source balance ("swap 50% USDC to USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("swap $5 USDC to USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set from_symbol to the source token ("ETH" in "swap max ETH to USDC"). Mutually exclusive with to_amount \u2014 set at most ONE of the two.',required:!1},{name:"to_symbol",type:"string",description:'Symbol of the DESTINATION token the user wants to RECEIVE (e.g. "USDT"). Leave EMPTY when the user did not name a destination (e.g. "swap USDC") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"to_address",type:"string",description:`Destination token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from to_symbol.`,required:!1},{name:"to_amount",type:"string",description:`Quantity of the DESTINATION token (the one being received) the user wants to RECEIVE. Set this when the amount sits next to the destination token: "swap USDC to 5 USDT" \u2192 to_amount = the number next to USDT. May also be a USD value ("swap USDC to $5 USDT" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$"). Mutually exclusive with from_amount \u2014 set at most ONE.`,required:!1},{name:"limit",type:"number",description:"Only used when no destination is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"swap_from_prompt_template",type:"string",description:`A short "swap {token}" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the source picker when the user named NEITHER side (a bare "swap"). Use the exact placeholder "{token}" (do not translate the braces) for the source symbol; put the localized verb directly in the text. English example: "swap {token}". Vietnamese example: "\u0111\u1ED5i {token}". Japanese example: "{token} \u3092\u30B9\u30EF\u30C3\u30D7". Always include {token}. Do NOT write the chain name yourself \u2014 the chain these holdings are on is appended automatically as a "(<chain>)" suffix, e.g. "swap ETH (Base)".`,required:!0},{name:"swap_to_prompt_template",type:"string",description:`A short "swap X to Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the destination (trending) picker, the percentage-spend buttons, and the source picker whenever the user already named a destination ("swap to USDC"). Use these exact placeholders (do not translate the braces): "{from}" = source token, "{to}" = destination token, "{from_amount}" = quantity of the SOURCE token (place it next to {from}), "{to_amount}" = quantity of the DESTINATION token (place it next to {to}). Put the localized verb and the "to" preposition directly in the text. English example: "swap {from_amount} {from} to {to_amount} {to}". Vietnamese example: "\u0111\u1ED5i {from_amount} {from} sang {to_amount} {to}". Japanese example: "{from_amount} {from} \u3092 {to_amount} {to} \u306B\u30B9\u30EF\u30C3\u30D7". Always include {from} and {to}. Include both {from_amount} and {to_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount). Do NOT write the chain name yourself \u2014 the chain is appended automatically as a "(<chain>)" suffix, e.g. "swap ETH to USDC (Base)".`,required:!0}];async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:r,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before swapping. Do NOT proceed."};let o=Ba(e.from_chain,e.to_chain);if(o)return qa("swap",o);if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return Fr("swap",a)}return this.buildResult(e,t)}async buildResult(e,t){let r=typeof e.from_symbol=="string"?e.from_symbol.trim():"",o=typeof e.from_address=="string"?e.from_address.trim():"",s=typeof e.to_symbol=="string"?e.to_symbol.trim():"",a=this.requireChain(e,t)??void 0,i=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:a,walletAddress:i,hasMoralis:!!this.moralis}),!r&&!o){this.dbg("\u2192 Branch 0: source picker (no source token named)");let x=typeof e.to_address=="string"?e.to_address.trim():"",I=s||x;return await this.buildSourcePicker(e,t,I?{symbol:I,amount:this.normaliseAmount(e.to_amount)}:void 0)}let[l,c]=await Promise.all([this.resolveSide(e.from_address,r,a,i,"from"),this.resolveSide(e.to_address,s,a,i,"to")]),[d,u]=await Pi(a,[l.address?{...l,address:l.address}:void 0,c.address?{...c,address:c.address}:void 0]),p=l.address,m=d?.symbol??r,f=d?.decimals,h=c.address,g=u?.symbol??s,b=u?.decimals,y=c.logo;if(Si(p,h))return this.dbg("\u2192 same token both sides",{fromContract:p,toContract:h,fromSym:m,toSym:g}),{error:"same_token",_instructions:`The user asked to swap ${m} into ${g} \u2014 the SAME token on both sides, which is not a swap and cannot be done. Tell them, in their language, that the two tokens have to be different, and ask which token they want to receive instead. Do NOT proceed. Do NOT render the form. Do NOT mention tool names, UI, or forms.`};let w=await this.resolveToAmountSpec(e.to_amount,h,a,g),k=p?await this.resolveFromAmountSpec(e.from_amount,p,a,i,m,f??(p==="native"?18:void 0)):this.normaliseAmount(e.from_amount),v=_t(e.from_amount),S=!!v&&v.kind!=="token",P=null;if(this.dbg("resolved sides",{from:{fromContract:p,fromSym:m,fromDecimals:f},to:{toContract:h,toSym:g,toDecimals:b},fromAmount:k,toAmount:w}),!p)return this.dbg("\u2192 source token not resolved"),{error:"from_token_not_found",_instructions:`Could not find the token "${m||o}" to swap from on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(!h&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: destination picker (dest token missing)"),await this.buildToTrendingPicker({args:e,userContext:t,fromSym:m,fromContract:p,fromAmount:k,toAmount:w});if(!h)return{error:"to_token_missing",_instructions:`Ask the user, in their language, which token they want to receive when swapping ${m}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(w&&!k){this.dbg("Branch 1.3: deriving from amount from to amount",{toAmount:w,fromSym:m,toSym:g});let x=await this.deriveFromAmountFromTo({chain:a,toAmount:w,toContract:h,toSym:g,fromContract:p,fromSym:m});if(!x)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs from amount"),{error:"needs_from_amount",_instructions:`Could not work out how much ${m??"of the source token"} equals ${w} ${g} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${m??"of the source token"} they want to swap instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};k=x,P=w,S=!1,this.dbg("\u2192 Branch 1.3: derived from amount",{fromAmount:k,derivedFromTo:P})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking source balance",{fromContract:p,fromSym:m,fromAmount:k});let x=await this.checkFromBalance({args:e,userContext:t,chain:a,fromContract:p,fromSym:m,toSym:g,fromAmount:k,toAmount:w,derivedFromTo:P,amountSizedToBalance:S});if(x)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:x.error,hasButtons:Array.isArray(x.actionButtons)}),x;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!w&&t?.walletAddress){this.dbg("Branch 1.5: building amount form",{fromAmount:k});let x=await this.buildAmountForm({userContext:t,chain:a,fromContract:p,fromSym:m,fromDecimals:f,toContract:h,toSym:g,toDecimals:b,toLogo:y,fromAmount:k??void 0});if(x)return this.dbg("\u2192 Branch 1.5: amount form returned"),x;this.dbg("Branch 1.5: amount form null \u2014 needs a resolvable source token")}return this.dbg("\u2192 needs from amount"),{error:"needs_from_amount",_instructions:`Ask the user, in their language, how much ${m??"of the source token"} they want to swap to ${g}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return R(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let r=parseFloat(t);return Number.isFinite(r)&&r>0?t:null}requireChain(e,t){return K(e.chain,t)}async resolveContractAddress(e,t,r){if(!this.moralis||!e)return;let o=e.trim().toLowerCase(),s=R(e.trim()),a=l=>s?(l.token_address??"").toLowerCase()===o:(l.symbol??"").toLowerCase()===o;if(r){let l=await this.moralis.getWalletTokenBalances({address:r,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:qt(c)}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:qt(c),symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}async resolveSide(e,t,r,o,s="side"){let a=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(a.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,d=m=>m.toLowerCase()===ue?"native":m,u=l??c??(a||void 0);if(!u)return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(u,r,o);return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,key:u,lookup:p}),p?{address:d(p.address),symbol:p.symbolIsOnchain?p.symbol:c??p.symbol,decimals:p.decimals,logo:p.logo,symbolIsOnchain:p.symbolIsOnchain??!1}:l?{address:d(l),symbol:c}:{address:null,symbol:c}}async deriveFromAmountFromTo(e){let{chain:t,toAmount:r,toContract:o,fromContract:s}=e,[a,i]=await Promise.all([this.getUsdPrice(o,t),this.getUsdPrice(s,t)]);if(this.dbg("deriveFromAmountFromTo: prices",{toPrice:a,fromPrice:i}),!a||!i)return null;let l=Number(r);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,d=l*a/i;return!Number.isFinite(d)||d<=0?null:this.trimAmount(d*c)}async getUsdPrice(e,t){return zs({moralis:this.moralis,tokenAddress:e,chain:t})}async resolveFromAmountSpec(e,t,r,o,s,a){let i=_t(e);if(!i)return null;let l=d=>a===void 0?d:Dt(d,a);if(i.kind==="token")return l(qn(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!o)return null;let d=await this.readFromBalance(o,t,r);if(this.dbg("resolveFromAmountSpec: percent",{percent:i.percent,fromSym:s,bal:d?.balanceNum}),!d||!Number.isFinite(d.balanceNum)||d.balanceNum<=0)return null;let u=d.decimals??a??18;return i.percent>=100?this.cleanAmountString(d.balanceFormatted):$n(d.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,u)}let c=await this.getUsdPrice(t,r);return this.dbg("resolveFromAmountSpec: usd",{usd:i.usd,fromSym:s,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveToAmountSpec(e,t,r,o){let s=_t(e);if(!s)return null;if(s.kind==="token")return qn(e)??this.toPlainDecimal(s.value);if(s.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,r);return this.dbg("resolveToAmountSpec: usd",{usd:s.usd,toSym:o,price:a}),a?this.trimAmount(s.usd/a):null}async buildSourcePicker(e,t,r){if(!this.moralis||!t?.walletAddress)return{error:"source_unavailable",_instructions:"Cannot list the wallet holdings in this build. Tell the user briefly and ask them to name the token they want to swap from."};let o=this.requireChain(e,t)??void 0,s=t.walletAddress,a=await this.moralis.getWalletTokenBalances({address:s,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1}),l=(a.success?a.data?.result??[]:[]).filter(m=>m.symbol?m.native_token?!0:!!m.token_address:!1).sort((m,f)=>(f.usd_value??0)-(m.usd_value??0)).slice(0,8);if(l.length===0)return{error:"no_swap_holdings",chain:o,_instructions:`The wallet holds no tokens to swap${Q(o)}. Tell the user to top up first, naming that network explicitly so they know which one is empty. Do NOT mention tool names, UI, or forms.`};let c=typeof e.swap_from_prompt_template=="string"?e.swap_from_prompt_template:"",d=typeof e.swap_to_prompt_template=="string"?e.swap_to_prompt_template:"",u=l.map(m=>{let f=m.symbol,h=m.name?.trim()||f,g=m.balance_formatted?`${this.cleanAmountString(m.balance_formatted)} `:"",b=typeof m.usd_value=="number"&&m.usd_value>0?` ($${m.usd_value.toFixed(2)})`:"",y=`${h}: ${g}${f}${b}`,w=r?this.buildSwapToPrompt(d,f,r.symbol,null,r.amount??null,o):this.buildSwapFromPrompt(c,f,o);return{label:y,prompt:w}}),p=r?`state what the user wants to do, naming the destination they already gave (e.g., 'B\u1EA1n mu\u1ED1n swap sang ${r.symbol}.' / 'You want to swap to ${r.symbol}.')`:"state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n swap token.' / 'You want to swap a token.')";return{actionButtons:u,_instructions:`Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first ${p}, then ask them to choose which token to swap from in the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap.' / 'Please choose the token to swap from.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms.`}}async buildToTrendingPicker(e){let{args:t,userContext:r,fromSym:o,fromContract:s}=e,a=this.requireChain(t,r)??void 0,i=this.pantograph,l=typeof t.limit=="number"&&Number.isFinite(t.limit)?Math.floor(t.limit):6,c=Math.max(1,Math.min(10,l)),d=await i.getTrendingTokens({chain:a,limit:c+2}),u=d.success?d.data??[]:[],p=s?.toLowerCase(),m=o.toLowerCase(),f=u.filter(v=>!(!v.symbol||p&&p!=="native"&&v.tokenAddress&&v.tokenAddress.toLowerCase()===p||v.symbol.toLowerCase()===m)).slice(0,c);if(f.length===0)return{error:"no_trending_tokens",_instructions:`No trending tokens are available to swap ${o} into on this chain right now. Tell the user briefly and suggest they name the token they want to receive directly. Do NOT mention tool names, UI, or forms.`};let h=e.fromAmount??this.normaliseAmount(t.from_amount),g=e.toAmount??this.normaliseAmount(t.to_amount),b=typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:"",y=f.map(v=>{let S=v.symbol,P=h?this.buildSwapToPrompt(b,o,S,h,null,a):this.buildSwapToPrompt(b,o,S,null,g,a);return{label:S,prompt:P}}),k=f.map((v,S)=>{let P=v.name?.trim()||v.symbol,x=v.symbol,I=typeof v.usdPrice=="number"&&v.usdPrice>0?`$${this.formatPrice(v.usdPrice)}`:"N/A",E=v.pricePercentChange?.["24h"],we=typeof E=="number"&&Number.isFinite(E)?` (${E>0?"+":E<0?"-":""}${this.formatPercent(Math.abs(E))}%)`:"";return`${S+1}. ${P} (${x}) \u2014 ${I}${we}`}).join(`
215
+ ${p}`}}formatPercent(e){return Number.isFinite(e)?this.toPlainDecimal(parseFloat(e.toPrecision(6))):"0"}formatPrice(e){if(e>=1)return e.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2});if(e>=.01)return e.toFixed(4);let t=e.toFixed(12),r=t.match(/^0\.0*([1-9]\d{0,3})/);return r?t.slice(0,(r[0].length||0)+0):t}};var Zo=class extends A{name="open-swap-token-form";kind="action";category="wallet-action";moralis;pantograph;debug;constructor(e,t){super(),e!==void 0&&(this.moralis=new O(e),this.pantograph=new Ae({baseUrl:e.pantographUrl})),this.debug=t?.debug??!1}dbg(e,t){this.debug&&(t===void 0?console.log(`[SwapTokenTool] ${e}`):console.log(`[SwapTokenTool] ${e}`,JSON.stringify(t)))}description='Open the SWAP TOKEN flow for ANY swap/exchange/convert intent where the user swaps a token they ALREADY HOLD into another token \u2014 "swap USDC to USDT", "swap USDC", "\u0111\u1ED5i USDC sang ETH", "convert DAI to USDC", "exchange 10 USDC for PEPE". The FROM token is the user\'s own holding (the source). Handles both cases: (a) the user named the destination \u2014 "swap USDC to USDT": pass `from_symbol` (the source, e.g. "USDC") and `to_symbol` (the destination, e.g. "USDT"). (b) the user named only the source \u2014 "swap USDC": pass `from_symbol` and leave `to_symbol` blank; the tool returns buttons of the chain\'s current trending tokens so the user picks what to receive. If the user named NO token at all \u2014 "swap" / "\u0111\u1ED5i token": leave both blank and the tool returns the wallet\'s holdings so the user picks what to swap FROM. Amount: `from_amount` = source to SPEND; `to_amount` = destination to RECEIVE. Never both. CHAINS: when the user names a DIFFERENT network for each side \u2014 "swap ETH on Optimism to ETH on Base", "\u0111\u1ED5i ETH tr\xEAn OP sang ETH tr\xEAn Base" \u2014 you MUST put each one in `from_chain` and `to_chain` (NOT in `chain`, and never drop one of them): that is a cross-chain request and the tool answers it with the correct unsupported message. Use the single `chain` parameter only when ONE network covers the whole request.';parameters=[{name:"chain",type:"string",description:Ze,required:!1},{name:"from_chain",type:"string",description:Mr("SOURCE token being swapped FROM"),required:!1},{name:"to_chain",type:"string",description:Mr("DESTINATION token being received"),required:!1},{name:"from_symbol",type:"string",description:`Symbol of the SOURCE token the user wants to swap FROM \u2014 a token they already hold (e.g. "USDC"). Leave EMPTY only when the user named no token at all (e.g. "swap") \u2014 the tool then returns the wallet's holdings to pick the source from.`,required:!1},{name:"from_address",type:"string",description:`Source token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from from_symbol.`,required:!1},{name:"from_amount",type:"string",description:'Quantity of the SOURCE token (the one being swapped FROM / spent) the user wants to SPEND. Set this when the amount sits next to the source token: "swap 10 USDC to USDT", "\u0111\u1ED5i 10 USDC sang ETH" \u2192 from_amount = the number next to USDC. May also be a PERCENT of the source balance ("swap 50% USDC to USDT" \u2192 "50%"), the literal word "max" meaning the WHOLE balance, or a USD value ("swap $5 USDC to USDT" \u2192 "5$"). NORMALIZE any "whole balance / everything / maximum" phrasing in ANY language (e.g. "all", "max", "t\u1EA5t c\u1EA3", "to\xE0n b\u1ED9", "\u5168\u90E8", "\u3059\u3079\u3066", "\uC804\uBD80", "todo", "tout") to the literal "max"; pass plain/percent/USD numbers VERBATIM (the tool converts "%"/"$"/"max"). "max" is an AMOUNT, never a token \u2014 still set from_symbol to the source token ("ETH" in "swap max ETH to USDC"). Mutually exclusive with to_amount \u2014 set at most ONE of the two.',required:!1},{name:"to_symbol",type:"string",description:'Symbol of the DESTINATION token the user wants to RECEIVE (e.g. "USDT"). Leave EMPTY when the user did not name a destination (e.g. "swap USDC") \u2014 the tool then returns trending tokens to pick from.',required:!1},{name:"to_address",type:"string",description:`Destination token address (0x\u2026), OR "native" for the chain's native coin. Leave empty when unknown \u2014 the tool resolves it from to_symbol.`,required:!1},{name:"to_amount",type:"string",description:`Quantity of the DESTINATION token (the one being received) the user wants to RECEIVE. Set this when the amount sits next to the destination token: "swap USDC to 5 USDT" \u2192 to_amount = the number next to USDT. May also be a USD value ("swap USDC to $5 USDT" \u2192 "5$"); pass the user's expression VERBATIM (the tool converts "$"). Mutually exclusive with from_amount \u2014 set at most ONE.`,required:!1},{name:"limit",type:"number",description:"Only used when no destination is named: max number of trending tokens to show as buttons. Default 6. Clamped to [1, 10].",required:!1},{name:"swap_from_prompt_template",type:"string",description:`A short "swap {token}" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the source picker when the user named NEITHER side (a bare "swap"). Use the exact placeholder "{token}" (do not translate the braces) for the source symbol; put the localized verb directly in the text. English example: "swap {token}". Vietnamese example: "\u0111\u1ED5i {token}". Japanese example: "{token} \u3092\u30B9\u30EF\u30C3\u30D7". Always include {token}. Do NOT write the chain name yourself \u2014 the chain these holdings are on is appended automatically as a "(<chain>)" suffix, e.g. "swap ETH (Base)".`,required:!0},{name:"swap_to_prompt_template",type:"string",description:`A short "swap X to Y" command IN THE USER'S CURRENT LANGUAGE, used as the click-command for the destination (trending) picker, the percentage-spend buttons, and the source picker whenever the user already named a destination ("swap to USDC"). Use these exact placeholders (do not translate the braces): "{from}" = source token, "{to}" = destination token, "{from_amount}" = quantity of the SOURCE token (place it next to {from}), "{to_amount}" = quantity of the DESTINATION token (place it next to {to}). Put the localized verb and the "to" preposition directly in the text. English example: "swap {from_amount} {from} to {to_amount} {to}". Vietnamese example: "\u0111\u1ED5i {from_amount} {from} sang {to_amount} {to}". Japanese example: "{from_amount} {from} \u3092 {to_amount} {to} \u306B\u30B9\u30EF\u30C3\u30D7". Always include {from} and {to}. Include both {from_amount} and {to_amount} too \u2014 the tool removes whichever amount is unknown (only one side ever carries an amount). Do NOT write the chain name yourself \u2014 the chain is appended automatically as a "(<chain>)" suffix, e.g. "swap ETH to USDC (Base)".`,required:!0}];async execute(e,t){let r=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a={toolName:this.name,callId:r,success:!0,data:s,duration:Date.now()-o};return s&&typeof s=="object"&&s.ui&&(a.ui=s.ui),s&&Array.isArray(s.actionButtons)&&s.actionButtons.length>0&&(a.actionButtons=s.actionButtons),a}catch(s){return{toolName:this.name,callId:r,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}async run(e,t){if(!t?.walletAddress)return{error:"wallet_not_connected",_instructions:"The user is not connected. Ask them to connect their wallet before swapping. Do NOT proceed."};let o=Ba(e.from_chain,e.to_chain);if(o)return qa("swap",o);if(!this.requireChain(e,t)){let a=typeof t?.query=="string"?t.query:void 0;return Fr("swap",a)}return this.buildResult(e,t)}async buildResult(e,t){let r=typeof e.from_symbol=="string"?e.from_symbol.trim():"",o=typeof e.from_address=="string"?e.from_address.trim():"",s=typeof e.to_symbol=="string"?e.to_symbol.trim():"",a=this.requireChain(e,t)??void 0,i=t?.walletAddress??void 0;if(this.dbg("buildResult:args",{args:e,chain:a,walletAddress:i,hasMoralis:!!this.moralis}),!r&&!o){this.dbg("\u2192 Branch 0: source picker (no source token named)");let x=typeof e.to_address=="string"?e.to_address.trim():"",U=s||x;return await this.buildSourcePicker(e,t,U?{symbol:U,amount:this.normaliseAmount(e.to_amount)}:void 0)}let[l,c]=await Promise.all([this.resolveSide(e.from_address,r,a,i,"from"),this.resolveSide(e.to_address,s,a,i,"to")]),[d,u]=await Pi(a,[l.address?{...l,address:l.address}:void 0,c.address?{...c,address:c.address}:void 0]),p=l.address,m=d?.symbol??r,f=d?.decimals,h=c.address,g=u?.symbol??s,b=u?.decimals,y=c.logo;if(Si(p,h))return this.dbg("\u2192 same token both sides",{fromContract:p,toContract:h,fromSym:m,toSym:g}),{error:"same_token",_instructions:`The user asked to swap ${m} into ${g} \u2014 the SAME token on both sides, which is not a swap and cannot be done. Tell them, in their language, that the two tokens have to be different, and ask which token they want to receive instead. Do NOT proceed. Do NOT render the form. Do NOT mention tool names, UI, or forms.`};let w=await this.resolveToAmountSpec(e.to_amount,h,a,g),k=p?await this.resolveFromAmountSpec(e.from_amount,p,a,i,m,f??(p==="native"?18:void 0)):this.normaliseAmount(e.from_amount),v=_t(e.from_amount),S=!!v&&v.kind!=="token",P=null;if(this.dbg("resolved sides",{from:{fromContract:p,fromSym:m,fromDecimals:f},to:{toContract:h,toSym:g,toDecimals:b},fromAmount:k,toAmount:w}),!p)return this.dbg("\u2192 source token not resolved"),{error:"from_token_not_found",_instructions:`Could not find the token "${m||o}" to swap from on this chain. Tell the user, in their language, that the token could not be found and ask them to check the name or provide its contract address. Do NOT invent an address. Do NOT mention tool names, UI, or forms.`};if(!h&&this.moralis&&t?.walletAddress)return this.dbg("\u2192 Branch 1: destination picker (dest token missing)"),await this.buildToTrendingPicker({args:e,userContext:t,fromSym:m,fromContract:p,fromAmount:k,toAmount:w});if(!h)return{error:"to_token_missing",_instructions:`Ask the user, in their language, which token they want to receive when swapping ${m}. Do NOT invent a token. Do NOT mention tool names, UI, or forms.`};if(w&&!k){this.dbg("Branch 1.3: deriving from amount from to amount",{toAmount:w,fromSym:m,toSym:g});let x=await this.deriveFromAmountFromTo({chain:a,toAmount:w,toContract:h,toSym:g,fromContract:p,fromSym:m});if(!x)return this.dbg("\u2192 Branch 1.3: price unavailable \u2014 needs from amount"),{error:"needs_from_amount",_instructions:`Could not work out how much ${m??"of the source token"} equals ${w} ${g} right now. Tell the user, in their language, that the price couldn't be fetched at the moment, and ask how much ${m??"of the source token"} they want to swap instead. Do NOT invent an amount or a price. Do NOT mention tool names, UI, or forms.`};k=x,P=w,S=!1,this.dbg("\u2192 Branch 1.3: derived from amount",{fromAmount:k,derivedFromTo:P})}if(this.moralis&&t?.walletAddress){this.dbg("Branch 1.4: checking source balance",{fromContract:p,fromSym:m,fromAmount:k});let x=await this.checkFromBalance({args:e,userContext:t,chain:a,fromContract:p,fromSym:m,toSym:g,fromAmount:k,toAmount:w,derivedFromTo:P,amountSizedToBalance:S});if(x)return this.dbg("\u2192 Branch 1.4: balance shortfall \u2014 returning",{error:x.error,hasButtons:Array.isArray(x.actionButtons)}),x;this.dbg("Branch 1.4: balance OK \u2014 continuing")}if(!w&&t?.walletAddress){this.dbg("Branch 1.5: building amount form",{fromAmount:k});let x=await this.buildAmountForm({userContext:t,chain:a,fromContract:p,fromSym:m,fromDecimals:f,toContract:h,toSym:g,toDecimals:b,toLogo:y,fromAmount:k??void 0});if(x)return this.dbg("\u2192 Branch 1.5: amount form returned"),x;this.dbg("Branch 1.5: amount form null \u2014 needs a resolvable source token")}return this.dbg("\u2192 needs from amount"),{error:"needs_from_amount",_instructions:`Ask the user, in their language, how much ${m??"of the source token"} they want to swap to ${g}. Do NOT invent an amount. Do NOT mention tool names, UI, or forms.`}}normaliseAddress(e){if(typeof e!="string")return null;let t=e.trim();return R(t)?t:null}normaliseAmount(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return String(e);if(typeof e!="string")return null;let t=e.trim();if(!t)return null;let r=parseFloat(t);return Number.isFinite(r)&&r>0?t:null}requireChain(e,t){return K(e.chain,t)}async resolveContractAddress(e,t,r){if(!this.moralis||!e)return;let o=e.trim().toLowerCase(),s=R(e.trim()),a=l=>s?(l.token_address??"").toLowerCase()===o:(l.symbol??"").toLowerCase()===o;if(r){let l=await this.moralis.getWalletTokenBalances({address:r,chain:t});if(l.success&&l.data?.result?.length){let c=l.data.result.find(a);if(c)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:qt(c)}}}let i=await this.moralis.searchTokensByKey({key:e,chain:t});if(i.success&&i.data?.length){let c=i.data.find(a)??i.data[0];if(c?.token_address)return{address:c.token_address,symbol:c.symbol,name:c.name,decimals:typeof c.decimals=="number"?c.decimals:void 0,logo:qt(c),symbolIsOnchain:typeof c.symbolOnchain=="string"&&c.symbolOnchain.trim().length>0}}}async resolveSide(e,t,r,o,s="side"){let a=typeof e=="string"?e.trim():"",i=typeof t=="string"?t.trim():"";if(a.toLowerCase()==="native"||i.toLowerCase()==="native")return{address:"native",symbol:i||void 0};let l=this.normaliseAddress(e),c=i||void 0,d=m=>m.toLowerCase()===ue?"native":m,u=l??c??(a||void 0);if(!u)return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,resolved:"none"}),{address:null,symbol:c};let p=await this.resolveContractAddress(u,r,o);return this.dbg(`resolveSide:${s}`,{refStr:a,symbolStr:i,chain:r,key:u,lookup:p}),p?{address:d(p.address),symbol:p.symbolIsOnchain?p.symbol:c??p.symbol,decimals:p.decimals,logo:p.logo,symbolIsOnchain:p.symbolIsOnchain??!1}:l?{address:d(l),symbol:c}:{address:null,symbol:c}}async deriveFromAmountFromTo(e){let{chain:t,toAmount:r,toContract:o,fromContract:s}=e,[a,i]=await Promise.all([this.getUsdPrice(o,t),this.getUsdPrice(s,t)]);if(this.dbg("deriveFromAmountFromTo: prices",{toPrice:a,fromPrice:i}),!a||!i)return null;let l=Number(r);if(!Number.isFinite(l)||l<=0)return null;let c=1.02,d=l*a/i;return!Number.isFinite(d)||d<=0?null:this.trimAmount(d*c)}async getUsdPrice(e,t){return zs({moralis:this.moralis,tokenAddress:e,chain:t})}async resolveFromAmountSpec(e,t,r,o,s,a){let i=_t(e);if(!i)return null;let l=d=>a===void 0?d:Dt(d,a);if(i.kind==="token")return l(qn(e)??this.toPlainDecimal(i.value));if(i.kind==="percent"){if(!o)return null;let d=await this.readFromBalance(o,t,r);if(this.dbg("resolveFromAmountSpec: percent",{percent:i.percent,fromSym:s,bal:d?.balanceNum}),!d||!Number.isFinite(d.balanceNum)||d.balanceNum<=0)return null;let u=d.decimals??a??18;return i.percent>=100?this.cleanAmountString(d.balanceFormatted):$n(d.balanceFormatted,BigInt(Math.round(i.percent*1e6)),100000000n,u)}let c=await this.getUsdPrice(t,r);return this.dbg("resolveFromAmountSpec: usd",{usd:i.usd,fromSym:s,price:c}),c?l(this.trimAmount(i.usd/c)):null}async resolveToAmountSpec(e,t,r,o){let s=_t(e);if(!s)return null;if(s.kind==="token")return qn(e)??this.toPlainDecimal(s.value);if(s.kind==="percent"||!t)return null;let a=await this.getUsdPrice(t,r);return this.dbg("resolveToAmountSpec: usd",{usd:s.usd,toSym:o,price:a}),a?this.trimAmount(s.usd/a):null}async buildSourcePicker(e,t,r){if(!this.moralis||!t?.walletAddress)return{error:"source_unavailable",_instructions:"Cannot list the wallet holdings in this build. Tell the user briefly and ask them to name the token they want to swap from."};let o=this.requireChain(e,t)??void 0,s=t.walletAddress,a=await this.moralis.getWalletTokenBalances({address:s,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1}),l=(a.success?a.data?.result??[]:[]).filter(m=>m.symbol?m.native_token?!0:!!m.token_address:!1).sort((m,f)=>(f.usd_value??0)-(m.usd_value??0)).slice(0,8);if(l.length===0)return{error:"no_swap_holdings",chain:o,_instructions:`The wallet holds no tokens to swap${Q(o)}. Tell the user to top up first, naming that network explicitly so they know which one is empty. Do NOT mention tool names, UI, or forms.`};let c=typeof e.swap_from_prompt_template=="string"?e.swap_from_prompt_template:"",d=typeof e.swap_to_prompt_template=="string"?e.swap_to_prompt_template:"",u=l.map(m=>{let f=m.symbol,h=m.name?.trim()||f,g=m.balance_formatted?`${this.cleanAmountString(m.balance_formatted)} `:"",b=typeof m.usd_value=="number"&&m.usd_value>0?` ($${m.usd_value.toFixed(2)})`:"",y=`${h}: ${g}${f}${b}`,w=r?this.buildSwapToPrompt(d,f,r.symbol,null,r.amount??null,o):this.buildSwapFromPrompt(c,f,o);return{label:y,prompt:w}}),p=r?`state what the user wants to do, naming the destination they already gave (e.g., 'B\u1EA1n mu\u1ED1n swap sang ${r.symbol}.' / 'You want to swap to ${r.symbol}.')`:"state what the user wants to do (e.g., 'B\u1EA1n mu\u1ED1n swap token.' / 'You want to swap a token.')";return{actionButtons:u,_instructions:`Reply briefly in the user's language with two short sentences using the pattern 'state intent \u2192 ask to choose': first ${p}, then ask them to choose which token to swap from in the options below (e.g., 'H\xE3y ch\u1ECDn token b\u1EA1n mu\u1ED1n swap.' / 'Please choose the token to swap from.'). Do NOT list the tokens in text. Do NOT mention tool names, UI, or forms.`}}async buildToTrendingPicker(e){let{args:t,userContext:r,fromSym:o,fromContract:s}=e,a=this.requireChain(t,r)??void 0,i=this.pantograph,l=typeof t.limit=="number"&&Number.isFinite(t.limit)?Math.floor(t.limit):6,c=Math.max(1,Math.min(10,l)),d=await i.getTrendingTokens({chain:a,limit:c+2}),u=d.success?d.data??[]:[],p=s?.toLowerCase(),m=o.toLowerCase(),f=u.filter(v=>!(!v.symbol||p&&p!=="native"&&v.tokenAddress&&v.tokenAddress.toLowerCase()===p||v.symbol.toLowerCase()===m)).slice(0,c);if(f.length===0)return{error:"no_trending_tokens",_instructions:`No trending tokens are available to swap ${o} into on this chain right now. Tell the user briefly and suggest they name the token they want to receive directly. Do NOT mention tool names, UI, or forms.`};let h=e.fromAmount??this.normaliseAmount(t.from_amount),g=e.toAmount??this.normaliseAmount(t.to_amount),b=typeof t.swap_to_prompt_template=="string"?t.swap_to_prompt_template:"",y=f.map(v=>{let S=v.symbol,P=h?this.buildSwapToPrompt(b,o,S,h,null,a):this.buildSwapToPrompt(b,o,S,null,g,a);return{label:S,prompt:P}}),k=f.map((v,S)=>{let P=v.name?.trim()||v.symbol,x=v.symbol,U=typeof v.usdPrice=="number"&&v.usdPrice>0?`$${this.formatPrice(v.usdPrice)}`:"N/A",E=v.pricePercentChange?.["24h"],we=typeof E=="number"&&Number.isFinite(E)?` (${E>0?"+":E<0?"-":""}${this.formatPercent(Math.abs(E))}%)`:"";return`${S+1}. ${P} (${x}) \u2014 ${U}${we}`}).join(`
216
216
  `)+`
217
217
 
218
218
  Which token do you want to receive?`;return{actionButtons:y,_instructions:`The user wants to swap ${o} into another token. The trending tokens are on ${a?T(a):"the connected chain"}. Reply in the user's language using the pattern 'state intent \u2192 ask to choose'. Start with a one-line header that states the user's intent (e.g., 'B\u1EA1n mu\u1ED1n swap ${o} sang token kh\xE1c \u2014 \u0111\xE2y l\xE0 c\xE1c token \u0111ang trending tr\xEAn <chain name>:' / '\u{1F4C8} You want to swap ${o} \u2014 here are the tokens currently trending on <chain name>:'), then output EXACTLY the following list, preserving the line breaks, ordering, prices, and percentages verbatim (translate only the wording, never the numbers). The list already ends with a 'choose' prompt. Do NOT add or remove tokens, and do NOT mention tool names, UI, or forms:
@@ -306,11 +306,11 @@ LANGUAGE-AGNOSTIC TOOL SELECTION: The user query may arrive in ANY language (Eng
306
306
  OUTPUT FORMAT: Reply in plain text. NEVER draw tables or any column/pipe layout. When presenting multiple items, use a simple bullet or numbered list; otherwise just write short sentences.`,Qy=`
307
307
 
308
308
  DATA INTEGRITY: NEVER invent, guess, round, or estimate on-chain or market values \u2014 prices, balances, amounts, holder counts, APRs, floor prices, contract or wallet addresses, transaction hashes, or token ids. Every such value MUST come verbatim from an actual tool result in this conversation. If the tools did not return it, say so plainly instead of filling it in.`,ne=class{name;description;domain;capability;toolNames;systemPrompt;cortexFallbackTool;mustCallTool;llm;registry;maxToolCalls;historyMessages;debug;constructor(e){if(this.name=e.name,this.description=e.description,this.domain=e.domain,this.capability=e.capability,this.toolNames=new Set(e.toolNames),this.systemPrompt=e.systemPrompt+zy+Xy+Qy,this.cortexFallbackTool=e.cortexFallbackTool,this.mustCallTool=e.mustCallTool??!1,this.cortexFallbackTool&&!this.toolNames.has(this.cortexFallbackTool))throw new Error(`Subagent "${e.name}": cortexFallbackTool "${this.cortexFallbackTool}" must be in toolNames.`);this.llm=e.llm,this.registry=e.registry,this.maxToolCalls=e.options?.maxToolCalls??5,this.historyMessages=e.options?.historyMessages??10,this.debug=e.options?.debug??!1}getCard(){return{name:this.name,description:this.description,domain:this.domain}}ownsTool(e){return this.toolNames.has(e)}getTools(){return this.registry.getDefinitions().filter(e=>this.toolNames.has(e.name))}async run(e,t,r){let o=this.getTools();if(this.debug&&(console.log(`
309
- [${this.name}] query: "${e.query}"`),console.log(` [${this.name}] tools available: ${o.map(x=>x.name).join(", ")}`)),o.length===0)return{subagentName:this.name,steps:[],finalAnswer:`Subagent "${this.name}" has no registered tools available.`,toolResults:[],toolMessages:[]};let s=[],a=[],i=[],l=new Set,c=0,d=!1,u=[];if(r?.walletAddress&&u.push(`Connected wallet: ${r.walletAddress}`),r?.chain){let x=T(r.chain),I=Fa(r.chain),E=I?`; native coin: ${I}`:"";u.push(`Current chain: ${x} (${r.chain})${E}`)}let p=typeof e.mentionedChain=="string"?e.mentionedChain.trim():"",m=D(p),f=D(r?.chain);p&&!(m!==null&&f!==null&&m===f)&&u.push(`Network named by the user THIS turn: ${p} \u2014 this is the network the request targets, NOT the connected one. Pass it to the tool's chain parameter (as its hex id). Do NOT substitute the current chain and do NOT omit it.`);let h=u.length>0?`User context:
309
+ [${this.name}] query: "${e.query}"`),console.log(` [${this.name}] tools available: ${o.map(x=>x.name).join(", ")}`)),o.length===0)return{subagentName:this.name,steps:[],finalAnswer:`Subagent "${this.name}" has no registered tools available.`,toolResults:[],toolMessages:[]};let s=[],a=[],i=[],l=new Set,c=0,d=!1,u=[];if(r?.walletAddress&&u.push(`Connected wallet: ${r.walletAddress}`),r?.chain){let x=T(r.chain),U=Fa(r.chain),E=U?`; native coin: ${U}`:"";u.push(`Current chain: ${x} (${r.chain})${E}`)}let p=typeof e.mentionedChain=="string"?e.mentionedChain.trim():"",m=I(p),f=I(r?.chain);p&&!(m!==null&&f!==null&&m===f)&&u.push(`Network named by the user THIS turn: ${p} \u2014 this is the network the request targets, NOT the connected one. Pass it to the tool's chain parameter (as its hex id). Do NOT substitute the current chain and do NOT omit it.`);let h=u.length>0?`User context:
310
310
  ${u.join(`
311
311
  `)}`:"",g=e.language?`The user's current language is "${e.language}" (BCP-47). Write every user-facing string you produce \u2014 replies AND any localized tool arguments \u2014 in this language.`:"",b=[h,g,`Routed query: ${e.query}`,e.reasoning?`Router reasoning: ${e.reasoning}`:"","Use only the tools you own. If you already have enough information, respond directly in the user's language."].filter(Boolean).join(`
312
312
 
313
- `),y=bp(t,this.toolNames),w=$t(y,this.historyMessages),k=[{role:"system",content:this.systemPrompt,timestamp:0},...w,{role:"user",content:b,timestamp:Date.now()}],v=6e3,S=this.maxToolCalls+1;for(let x=0;x<S;x++){let I=c<this.maxToolCalls,E=I?o:void 0,we=I&&this.mustCallTool&&c===0,V=E?jy:Tp,z=await this.llm.chat(k,E,{maxOutputTokens:V,...we?{forceToolUse:!0}:{}});if(z.toolCalls.length===0){if(c===0&&this.cortexFallbackTool&&I){this.debug&&console.log(` [${this.name}] no tool called \u2014 re-prompting to act via a tool (AI fallback: ${this.cortexFallbackTool})`),k.push({role:"user",content:`You answered without calling any tool. This is not allowed for on-chain queries \u2014 you must act via a tool, not plain text. FIRST, if any of your structured tools matches the user's intent, call that ONE tool now \u2014 resolve any missing field with a sensible default (per the defaults in your instructions; when the user named NO network, chain = the connected chain, else Ethereum \u2014 but when they DID name one, pass THAT network, never the connected one) instead of asking the user. ONLY if no structured tool fits \u2014 a broad, conceptual, or open-ended question \u2014 call "${this.cortexFallbackTool}" with a clear, self-contained English prompt that captures the user's intent. Do NOT answer in text \u2014 call a tool.`,timestamp:Date.now()});continue}if(c===0&&this.mustCallTool&&I&&!d){d=!0,this.debug&&console.log(` [${this.name}] no tool called \u2014 forcing the LLM to pick a tool`),k.push({role:"user",content:"You answered in text without calling any tool. That is not allowed here: this request needs you to open a form. Call exactly ONE of your tools that matches the user's intent now. Pass only the fields the user actually gave; leave everything else blank \u2014 the tool/form collects the rest (including a token/amount picker when needed). Do NOT ask the user for missing fields. Do NOT answer in text \u2014 call the tool.",timestamp:Date.now()});continue}return this.debug&&console.log(` [${this.name}] done \u2014 ${c} tool call(s), answer: "${z.text.slice(0,80)}\u2026"`),{subagentName:this.name,steps:s,finalAnswer:z.text,toolResults:a,toolMessages:i}}let fe={role:"assistant",content:z.text||"",toolCalls:z.toolCalls,timestamp:Date.now()};k.push(fe);let Ne=[];for(let W of z.toolCalls){if(!this.toolNames.has(W.toolName)){let Ge=`Tool "${W.toolName}" is not owned by ${this.name}`;this.debug&&console.log(` [${this.name}] WARN: ${Ge}`),s.push({phase:"observe",content:Ge,timestamp:Date.now()}),k.push({role:"tool",content:Ge,toolName:W.toolName,toolCallId:W.callId,timestamp:Date.now()});continue}let J=`${W.toolName}::${JSON.stringify(W.args)}`;if(l.has(J)){let Ge=`Skipped duplicate call: ${W.toolName}`;this.debug&&console.log(` [${this.name}] SKIP duplicate: ${W.toolName}`),s.push({phase:"observe",content:Ge,timestamp:Date.now()}),k.push({role:"tool",content:Ge,toolName:W.toolName,toolCallId:W.callId,timestamp:Date.now()});continue}l.add(J),c++,this.debug&&console.log(` [${this.name}] call #${c}: ${W.toolName} ${JSON.stringify(W.args)}`),s.push({phase:"think",content:z.text||`Calling ${W.toolName}`,timestamp:Date.now()}),s.push({phase:"act",content:`Calling tool: ${W.toolName}`,toolCall:{toolName:W.toolName,args:W.args},timestamp:Date.now()});let Ht=Date.now(),tr={...r,query:e.query},Le=await this.registry.execute(W.toolName,W.args,tr);a.push(Le);let Ye=Le.success?JSON.stringify(Le.data):`Error: ${Le.error}`;if(this.debug){let Ge=Le.success?"OK":"ERR",ze=Le.success?`${Ye.slice(0,120)}${Ye.length>120?"\u2026":""}`:Le.error;console.log(` [${this.name}] ${Ge} (${Date.now()-Ht}ms): ${ze}`)}s.push({phase:"observe",content:Ye,toolResult:Le,timestamp:Date.now()});let Vt={role:"tool",content:Ye,toolName:W.toolName,toolCallId:W.callId,timestamp:Date.now()};k.push(Vt),Ne.push({...Vt,content:Ye.length>v?Ye.slice(0,v)+"\u2026[truncated]":Ye})}Ne.length>0&&(i.push(fe),i.push(...Ne))}this.debug&&console.log(` [${this.name}] budget exhausted after ${c} calls, forcing final answer`),k.push({role:"user",content:"Tool budget reached. Give your best answer now based on the data gathered.",timestamp:Date.now()});let P=await this.llm.chat(k,void 0,{maxOutputTokens:Tp});return{subagentName:this.name,steps:s,finalAnswer:P.text,toolResults:a,toolMessages:i}}};var Jy=`You are the Wallet domain expert. You answer questions about a specific wallet's on-chain state.
313
+ `),y=bp(t,this.toolNames),w=$t(y,this.historyMessages),k=[{role:"system",content:this.systemPrompt,timestamp:0},...w,{role:"user",content:b,timestamp:Date.now()}],v=6e3,S=this.maxToolCalls+1;for(let x=0;x<S;x++){let U=c<this.maxToolCalls,E=U?o:void 0,we=U&&this.mustCallTool&&c===0,V=E?jy:Tp,z=await this.llm.chat(k,E,{maxOutputTokens:V,...we?{forceToolUse:!0}:{}});if(z.toolCalls.length===0){if(c===0&&this.cortexFallbackTool&&U){this.debug&&console.log(` [${this.name}] no tool called \u2014 re-prompting to act via a tool (AI fallback: ${this.cortexFallbackTool})`),k.push({role:"user",content:`You answered without calling any tool. This is not allowed for on-chain queries \u2014 you must act via a tool, not plain text. FIRST, if any of your structured tools matches the user's intent, call that ONE tool now \u2014 resolve any missing field with a sensible default (per the defaults in your instructions; when the user named NO network, chain = the connected chain, else Ethereum \u2014 but when they DID name one, pass THAT network, never the connected one) instead of asking the user. ONLY if no structured tool fits \u2014 a broad, conceptual, or open-ended question \u2014 call "${this.cortexFallbackTool}" with a clear, self-contained English prompt that captures the user's intent. Do NOT answer in text \u2014 call a tool.`,timestamp:Date.now()});continue}if(c===0&&this.mustCallTool&&U&&!d){d=!0,this.debug&&console.log(` [${this.name}] no tool called \u2014 forcing the LLM to pick a tool`),k.push({role:"user",content:"You answered in text without calling any tool. That is not allowed here: this request needs you to open a form. Call exactly ONE of your tools that matches the user's intent now. Pass only the fields the user actually gave; leave everything else blank \u2014 the tool/form collects the rest (including a token/amount picker when needed). Do NOT ask the user for missing fields. Do NOT answer in text \u2014 call the tool.",timestamp:Date.now()});continue}return this.debug&&console.log(` [${this.name}] done \u2014 ${c} tool call(s), answer: "${z.text.slice(0,80)}\u2026"`),{subagentName:this.name,steps:s,finalAnswer:z.text,toolResults:a,toolMessages:i}}let fe={role:"assistant",content:z.text||"",toolCalls:z.toolCalls,timestamp:Date.now()};k.push(fe);let Ne=[];for(let W of z.toolCalls){if(!this.toolNames.has(W.toolName)){let Ge=`Tool "${W.toolName}" is not owned by ${this.name}`;this.debug&&console.log(` [${this.name}] WARN: ${Ge}`),s.push({phase:"observe",content:Ge,timestamp:Date.now()}),k.push({role:"tool",content:Ge,toolName:W.toolName,toolCallId:W.callId,timestamp:Date.now()});continue}let J=`${W.toolName}::${JSON.stringify(W.args)}`;if(l.has(J)){let Ge=`Skipped duplicate call: ${W.toolName}`;this.debug&&console.log(` [${this.name}] SKIP duplicate: ${W.toolName}`),s.push({phase:"observe",content:Ge,timestamp:Date.now()}),k.push({role:"tool",content:Ge,toolName:W.toolName,toolCallId:W.callId,timestamp:Date.now()});continue}l.add(J),c++,this.debug&&console.log(` [${this.name}] call #${c}: ${W.toolName} ${JSON.stringify(W.args)}`),s.push({phase:"think",content:z.text||`Calling ${W.toolName}`,timestamp:Date.now()}),s.push({phase:"act",content:`Calling tool: ${W.toolName}`,toolCall:{toolName:W.toolName,args:W.args},timestamp:Date.now()});let Ht=Date.now(),tr={...r,query:e.query},Le=await this.registry.execute(W.toolName,W.args,tr);a.push(Le);let Ye=Le.success?JSON.stringify(Le.data):`Error: ${Le.error}`;if(this.debug){let Ge=Le.success?"OK":"ERR",ze=Le.success?`${Ye.slice(0,120)}${Ye.length>120?"\u2026":""}`:Le.error;console.log(` [${this.name}] ${Ge} (${Date.now()-Ht}ms): ${ze}`)}s.push({phase:"observe",content:Ye,toolResult:Le,timestamp:Date.now()});let Vt={role:"tool",content:Ye,toolName:W.toolName,toolCallId:W.callId,timestamp:Date.now()};k.push(Vt),Ne.push({...Vt,content:Ye.length>v?Ye.slice(0,v)+"\u2026[truncated]":Ye})}Ne.length>0&&(i.push(fe),i.push(...Ne))}this.debug&&console.log(` [${this.name}] budget exhausted after ${c} calls, forcing final answer`),k.push({role:"user",content:"Tool budget reached. Give your best answer now based on the data gathered.",timestamp:Date.now()});let P=await this.llm.chat(k,void 0,{maxOutputTokens:Tp});return{subagentName:this.name,steps:s,finalAnswer:P.text,toolResults:a,toolMessages:i}}};var Jy=`You are the Wallet domain expert. You answer questions about a specific wallet's on-chain state.
314
314
 
315
315
  SPECIALISED TOOLS (prefer these when intent matches):
316
316
  - get-wallet-token-balances: token + native coin balances