keyring-agent-core 0.2.56 → 0.2.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var ed=Object.create;var ps=Object.defineProperty;var td=Object.getOwnPropertyDescriptor;var nd=Object.getOwnPropertyNames;var rd=Object.getPrototypeOf,od=Object.prototype.hasOwnProperty;var sd=(r,e)=>{for(var t in e)ps(r,t,{get:e[t],enumerable:!0})},fl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of nd(e))!od.call(r,o)&&o!==t&&ps(r,o,{get:()=>e[o],enumerable:!(n=td(e,o))||n.enumerable});return r};var ad=(r,e,t)=>(t=r!=null?ed(rd(r)):{},fl(e||!r||!r.__esModule?ps(t,"default",{value:r,enumerable:!0}):t,r)),id=r=>fl(ps({},"__esModule",{value:!0}),r);var uf={};sd(uf,{AI_AGENT_TOOL_NAMES:()=>ba,AbortError:()=>Ot,AgentCore:()=>Sa,ApproveTokenTool:()=>go,BaseNftAiTool:()=>st,BaseSwapService:()=>Wt,BaseTool:()=>S,BaseWalletActionTool:()=>Fe,BuyTokenTool:()=>fo,ChatHistory:()=>wo,DEFAULT_CHAIN:()=>De,DEFAULT_PROVIDER:()=>Jo,DEFAULT_RPC_BY_CHAIN:()=>Ie,DebridgeAdapter:()=>Wr,EstimatePoolYieldTool:()=>eo,GeminiProvider:()=>re,GeminiSearchAiTool:()=>Br,HEX_TO_PANTOGRAPH:()=>Cc,KnowledgeBase:()=>vo,LendingMarketsTool:()=>_r,LendingReadService:()=>Cr,LendingService:()=>yt,LendingSupplyService:()=>Rr,MULTICALL3_ADDRESS:()=>K,ManageLiquidityRedirectTool:()=>no,MoralisService:()=>O,NFC_AGENT_TOOL_NAMES:()=>ya,NFC_AMAZON_DEFAULT_DOMAIN:()=>zi,NFC_AMAZON_DOMAINS:()=>Ki,NFTContractInfoTool:()=>Lr,NFTMetadataTool:()=>Dr,NFT_AGENT_TOOL_NAMES:()=>fa,NfcBuyTool:()=>Fr,NfcInfoTool:()=>Mr,NoFormTool:()=>ts,OpenAddLiquidityFormTool:()=>Jr,OpenSupplyFormTool:()=>Nr,POOL_AGENT_TOOL_NAMES:()=>wa,PantographService:()=>se,PoolByAddressTool:()=>Qr,PoolDetailTool:()=>zr,PoolFallbackAiTool:()=>qr,PoolPriceRangesTool:()=>to,PoolSearchTool:()=>Xr,PoolService:()=>ve,PreviewAddLiquidityTool:()=>Zr,PublicClient:()=>dn,RelayAdapter:()=>Yr,Router:()=>To,SUPPLIABLE_TYPES:()=>Vi,SUPPORTED_CHAINS:()=>tr,SUPPORTED_CHAINS_LABEL:()=>rr,SWAP_PROVIDER_CONFIG:()=>ia,SendNativeTool:()=>mo,SendNftTool:()=>bo,SendTokenTool:()=>ho,Subagent:()=>te,SubgraphAddPoolTool:()=>co,SubgraphCoinPoolPairsTool:()=>lo,SubgraphPoolByAddressTool:()=>so,SubgraphPoolByPositionIdTool:()=>ao,SubgraphPoolSearchTool:()=>ro,SubgraphPositionDetailTool:()=>io,SubgraphTrendingPoolsTool:()=>oo,Summarizer:()=>ko,SwapServiceFactory:()=>vn,SwapTokenTool:()=>yo,Synthesizer:()=>Ao,TOKEN_AGENT_TOOL_NAMES:()=>ga,TRANSFER_TOPIC:()=>Ru,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Rc,TokenAnalyticsTool:()=>lr,TokenHoldersTool:()=>ir,TokenInfoTool:()=>ar,TokenScoreTool:()=>cr,ToolRegistry:()=>er,TopGainersTool:()=>dr,TopPoolsTool:()=>Kr,TransactionByHashTool:()=>vr,TrendingTokensTool:()=>ur,UNISWAP_CHAIN_SLUG:()=>es,UNRESOLVED_ASSET:()=>hn,UpstashKnowledgeBase:()=>jt,WALLET_ACTION_AGENT_TOOL_NAMES:()=>ka,WALLET_AGENT_TOOL_NAMES:()=>ha,WalletApprovalsTool:()=>br,WalletDefiPositionsTool:()=>wr,WalletDefiProtocolPositionsTool:()=>kr,WalletHistoryTool:()=>mr,WalletLendingPositionsTool:()=>Er,WalletNFTsTool:()=>Ir,WalletNftTransfersTool:()=>gr,WalletPnlSummaryTool:()=>fr,WalletPnlTool:()=>yr,WalletTokenBalancesTool:()=>pr,WalletTokenTransfersTool:()=>hr,WebsiteTrustKeyringAgent:()=>xa,ZERO_ADDRESS:()=>Y,amazonDomainForLanguage:()=>Xi,apiClient:()=>x,applyYieldConversions:()=>Ra,buildChallenge:()=>wi,buildRangePresets:()=>tl,buildUniswapPoolUrl:()=>Ue,call:()=>nt,chains:()=>on,checksumAddress:()=>Cn,clampTick:()=>lt,clearPublicClientCache:()=>Ns,completeX402:()=>ki,configureSupportedChains:()=>Ms,convertSusdsShares:()=>Sr,createAiAgent:()=>is,createDefaultSubagents:()=>va,createNfcAgent:()=>as,createNftAgent:()=>ss,createPoolAgent:()=>ls,createPublicClient:()=>Lt,createTokenAgent:()=>os,createTransport:()=>Ut,createWalletActionAgent:()=>cs,createWalletAgent:()=>rs,createX402SignatureProvider:()=>Ti,decodeAbiParameters:()=>be,decodeErrorResult:()=>Nn,decodeFunctionData:()=>ja,decodeFunctionResult:()=>Ze,displayFromChallenge:()=>bc,encodeAbiParameters:()=>_n,encodeErrorResult:()=>Ha,encodeFunctionData:()=>F,encodeSignedHeader:()=>vi,erc1155Abi:()=>Ss,erc20Abi:()=>W,erc20Abi_bytes32:()=>qn,erc721Abi:()=>$n,estimateGas:()=>Fn,ethCallAt:()=>Lc,ethCallByChain:()=>tm,fallback:()=>It,fetchTopMarketplaces:()=>Qi,getAbiItem:()=>Ct,getAddress:()=>Oa,getAffiliateFee:()=>Vr,getBalance:()=>Ln,getBlock:()=>Bn,getBlockNumber:()=>Un,getChain:()=>gt,getChainContractAddress:()=>Oo,getChainId:()=>In,getChainMeta:()=>pe,getCode:()=>Rt,getDefaultRpcUrl:()=>li,getGasPrice:()=>Mn,getGatewayAddress:()=>ca,getGatewayChains:()=>ua,getNativeTokenInfo:()=>Gr,getPositionManagerAddress:()=>da,getProviderByChain:()=>aa,getPublicClient:()=>Ae,getRevertReason:()=>Uo,getRpcOverrides:()=>qo,getStorageAt:()=>Dn,getTokenPriceUSD:()=>af,getTransactionCount:()=>On,http:()=>Ve,ingestKnowledgeBase:()=>Zu,isAbortError:()=>mn,isAddress:()=>E,isAddressEqual:()=>Ma,isPaymentRequired:()=>yp,isShareBasedProtocol:()=>Ca,isShareBasedYieldToken:()=>zu,isSupplyChain:()=>js,listCandidateChains:()=>Bi,listSupplyChains:()=>Gs,multicall:()=>Qn,multicall3Abi:()=>He,multicallRaw:()=>Et,nfcAmazonSearchUrl:()=>ea,normaliseCountry:()=>ta,normalizePriceRangeToPool:()=>Hr,parseAbi:()=>Qa,parseAbiItem:()=>As,parseAbiParameters:()=>Lo,planYieldTokenConversions:()=>pl,priceToTick:()=>kn,protocolLabelFor:()=>Ye,psm3For:()=>Ks,readContract:()=>rt,readPaymentError:()=>fc,readPaymentRequired:()=>Ls,readReceipt:()=>yc,registerMaybeNoForm:()=>ma,requestWithX402:()=>fp,resolveNfcShopLinks:()=>Or,resolveRpcUrl:()=>un,resolveRpcUrls:()=>cn,resolveTokenPriceUSD:()=>Ju,roundTickToSpacing:()=>it,rpcCall:()=>Ic,setRpcOverrides:()=>ln,swapServiceFactory:()=>ct,tickToPrice:()=>je,toEventSelector:()=>Ba,toFunctionSelector:()=>ht,toPantographChain:()=>Dp,valueYieldTokens:()=>Qu});module.exports=id(uf);var bl=ad(require("axios"));var yl="0.2.56";var cd=`keyring-agent-core/${yl} (Keyring Chatbot Agent; +https://keyring.app)`,Ea=null;function wl(r){Ea=r}var ud=["payment-signature","x-payment"];function dd(r){return r?Object.keys(r).some(e=>ud.includes(e.toLowerCase())):!1}var kl;function Co(r){kl=r}var pd=3e4,md=typeof process<"u"&&process.versions?.node!=null,Na=class{instance;constructor(e={}){this.instance=bl.default.create({baseURL:e.baseURL,timeout:e.timeout??pd,validateStatus:()=>!0,headers:{Accept:"application/json",...md?{"User-Agent":e.userAgent??cd}:{},...e.headers}})}async request(e,t,n,o={}){let s=o.signal??kl,a=await this.instance.request({...o,signal:s,method:e,url:t,data:n}),i={};for(let[c,u]of Object.entries(a.headers??{}))u!=null&&(i[c.toLowerCase()]=String(u));let l={ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:i};if(l.status===402&&Ea&&!dd(o.headers)){let c=await Ea(l,{url:t,method:String(e),body:n,headers:o.headers});if(c)return this.request(e,t,n,{...o,headers:{...o.headers,...c}})}return l}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},x=new Na;function U(r){let{data:e,status:t,statusText:n}=r,o=n?`HTTP ${t} ${n}`:`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 hd(r){return r instanceof B?r.details||r.shortMessage:r instanceof Error?r.message:typeof r=="string"?r:""}var B=class extends Error{name="BaseError";shortMessage;details;metaMessages;constructor(e,t={}){let n=t.details??hd(t.cause),o=t.metaMessages??[],s=[e||"An error occurred.",...o.length>0?["",...o]:[],...n?["",`Details: ${n}`]:[]].join(`
1
+ "use strict";var ed=Object.create;var ps=Object.defineProperty;var td=Object.getOwnPropertyDescriptor;var nd=Object.getOwnPropertyNames;var rd=Object.getPrototypeOf,od=Object.prototype.hasOwnProperty;var sd=(r,e)=>{for(var t in e)ps(r,t,{get:e[t],enumerable:!0})},fl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of nd(e))!od.call(r,o)&&o!==t&&ps(r,o,{get:()=>e[o],enumerable:!(n=td(e,o))||n.enumerable});return r};var ad=(r,e,t)=>(t=r!=null?ed(rd(r)):{},fl(e||!r||!r.__esModule?ps(t,"default",{value:r,enumerable:!0}):t,r)),id=r=>fl(ps({},"__esModule",{value:!0}),r);var uf={};sd(uf,{AI_AGENT_TOOL_NAMES:()=>ba,AbortError:()=>Ot,AgentCore:()=>Sa,ApproveTokenTool:()=>go,BaseNftAiTool:()=>st,BaseSwapService:()=>Wt,BaseTool:()=>S,BaseWalletActionTool:()=>Fe,BuyTokenTool:()=>fo,ChatHistory:()=>wo,DEFAULT_CHAIN:()=>De,DEFAULT_PROVIDER:()=>Jo,DEFAULT_RPC_BY_CHAIN:()=>Ie,DebridgeAdapter:()=>Wr,EstimatePoolYieldTool:()=>eo,GeminiProvider:()=>re,GeminiSearchAiTool:()=>Br,HEX_TO_PANTOGRAPH:()=>Cc,KnowledgeBase:()=>vo,LendingMarketsTool:()=>_r,LendingReadService:()=>Cr,LendingService:()=>yt,LendingSupplyService:()=>Rr,MULTICALL3_ADDRESS:()=>K,ManageLiquidityRedirectTool:()=>no,MoralisService:()=>O,NFC_AGENT_TOOL_NAMES:()=>ya,NFC_AMAZON_DEFAULT_DOMAIN:()=>zi,NFC_AMAZON_DOMAINS:()=>Ki,NFTContractInfoTool:()=>Lr,NFTMetadataTool:()=>Dr,NFT_AGENT_TOOL_NAMES:()=>fa,NfcBuyTool:()=>Fr,NfcInfoTool:()=>Mr,NoFormTool:()=>ts,OpenAddLiquidityFormTool:()=>Jr,OpenSupplyFormTool:()=>Nr,POOL_AGENT_TOOL_NAMES:()=>wa,PantographService:()=>se,PoolByAddressTool:()=>Qr,PoolDetailTool:()=>zr,PoolFallbackAiTool:()=>qr,PoolPriceRangesTool:()=>to,PoolSearchTool:()=>Xr,PoolService:()=>ve,PreviewAddLiquidityTool:()=>Zr,PublicClient:()=>dn,RelayAdapter:()=>Yr,Router:()=>To,SUPPLIABLE_TYPES:()=>Vi,SUPPORTED_CHAINS:()=>tr,SUPPORTED_CHAINS_LABEL:()=>rr,SWAP_PROVIDER_CONFIG:()=>ia,SendNativeTool:()=>mo,SendNftTool:()=>bo,SendTokenTool:()=>ho,Subagent:()=>te,SubgraphAddPoolTool:()=>co,SubgraphCoinPoolPairsTool:()=>lo,SubgraphPoolByAddressTool:()=>so,SubgraphPoolByPositionIdTool:()=>ao,SubgraphPoolSearchTool:()=>ro,SubgraphPositionDetailTool:()=>io,SubgraphTrendingPoolsTool:()=>oo,Summarizer:()=>ko,SwapServiceFactory:()=>vn,SwapTokenTool:()=>yo,Synthesizer:()=>Ao,TOKEN_AGENT_TOOL_NAMES:()=>ga,TRANSFER_TOPIC:()=>Ru,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Rc,TokenAnalyticsTool:()=>lr,TokenHoldersTool:()=>ir,TokenInfoTool:()=>ar,TokenScoreTool:()=>cr,ToolRegistry:()=>er,TopGainersTool:()=>dr,TopPoolsTool:()=>Kr,TransactionByHashTool:()=>vr,TrendingTokensTool:()=>ur,UNISWAP_CHAIN_SLUG:()=>es,UNRESOLVED_ASSET:()=>hn,UpstashKnowledgeBase:()=>jt,WALLET_ACTION_AGENT_TOOL_NAMES:()=>ka,WALLET_AGENT_TOOL_NAMES:()=>ha,WalletApprovalsTool:()=>br,WalletDefiPositionsTool:()=>wr,WalletDefiProtocolPositionsTool:()=>kr,WalletHistoryTool:()=>mr,WalletLendingPositionsTool:()=>Er,WalletNFTsTool:()=>Ir,WalletNftTransfersTool:()=>gr,WalletPnlSummaryTool:()=>fr,WalletPnlTool:()=>yr,WalletTokenBalancesTool:()=>pr,WalletTokenTransfersTool:()=>hr,WebsiteTrustKeyringAgent:()=>xa,ZERO_ADDRESS:()=>Y,amazonDomainForLanguage:()=>Xi,apiClient:()=>x,applyYieldConversions:()=>Ra,buildChallenge:()=>wi,buildRangePresets:()=>tl,buildUniswapPoolUrl:()=>Ue,call:()=>nt,chains:()=>on,checksumAddress:()=>Cn,clampTick:()=>lt,clearPublicClientCache:()=>Ns,completeX402:()=>ki,configureSupportedChains:()=>Ms,convertSusdsShares:()=>Sr,createAiAgent:()=>is,createDefaultSubagents:()=>va,createNfcAgent:()=>as,createNftAgent:()=>ss,createPoolAgent:()=>ls,createPublicClient:()=>Lt,createTokenAgent:()=>os,createTransport:()=>Ut,createWalletActionAgent:()=>cs,createWalletAgent:()=>rs,createX402SignatureProvider:()=>Ti,decodeAbiParameters:()=>be,decodeErrorResult:()=>Nn,decodeFunctionData:()=>ja,decodeFunctionResult:()=>Ze,displayFromChallenge:()=>bc,encodeAbiParameters:()=>_n,encodeErrorResult:()=>Ha,encodeFunctionData:()=>F,encodeSignedHeader:()=>vi,erc1155Abi:()=>Ss,erc20Abi:()=>W,erc20Abi_bytes32:()=>qn,erc721Abi:()=>$n,estimateGas:()=>Fn,ethCallAt:()=>Lc,ethCallByChain:()=>tm,fallback:()=>It,fetchTopMarketplaces:()=>Qi,getAbiItem:()=>Ct,getAddress:()=>Oa,getAffiliateFee:()=>Vr,getBalance:()=>Ln,getBlock:()=>Bn,getBlockNumber:()=>Un,getChain:()=>gt,getChainContractAddress:()=>Oo,getChainId:()=>In,getChainMeta:()=>pe,getCode:()=>Rt,getDefaultRpcUrl:()=>li,getGasPrice:()=>Mn,getGatewayAddress:()=>ca,getGatewayChains:()=>ua,getNativeTokenInfo:()=>Gr,getPositionManagerAddress:()=>da,getProviderByChain:()=>aa,getPublicClient:()=>Ae,getRevertReason:()=>Uo,getRpcOverrides:()=>qo,getStorageAt:()=>Dn,getTokenPriceUSD:()=>af,getTransactionCount:()=>On,http:()=>Ve,ingestKnowledgeBase:()=>Zu,isAbortError:()=>mn,isAddress:()=>E,isAddressEqual:()=>Ma,isPaymentRequired:()=>yp,isShareBasedProtocol:()=>Ca,isShareBasedYieldToken:()=>zu,isSupplyChain:()=>js,listCandidateChains:()=>Bi,listSupplyChains:()=>Gs,multicall:()=>Qn,multicall3Abi:()=>He,multicallRaw:()=>Et,nfcAmazonSearchUrl:()=>ea,normaliseCountry:()=>ta,normalizePriceRangeToPool:()=>Hr,parseAbi:()=>Qa,parseAbiItem:()=>As,parseAbiParameters:()=>Lo,planYieldTokenConversions:()=>pl,priceToTick:()=>kn,protocolLabelFor:()=>Ye,psm3For:()=>Ks,readContract:()=>rt,readPaymentError:()=>fc,readPaymentRequired:()=>Ls,readReceipt:()=>yc,registerMaybeNoForm:()=>ma,requestWithX402:()=>fp,resolveNfcShopLinks:()=>Or,resolveRpcUrl:()=>un,resolveRpcUrls:()=>cn,resolveTokenPriceUSD:()=>Ju,roundTickToSpacing:()=>it,rpcCall:()=>Ic,setRpcOverrides:()=>ln,swapServiceFactory:()=>ct,tickToPrice:()=>je,toEventSelector:()=>Ba,toFunctionSelector:()=>ht,toPantographChain:()=>Dp,valueYieldTokens:()=>Qu});module.exports=id(uf);var bl=ad(require("axios"));var yl="0.2.57";var cd=`keyring-agent-core/${yl} (Keyring Chatbot Agent; +https://keyring.app)`,Ea=null;function wl(r){Ea=r}var ud=["payment-signature","x-payment"];function dd(r){return r?Object.keys(r).some(e=>ud.includes(e.toLowerCase())):!1}var kl;function Co(r){kl=r}var pd=3e4,md=typeof process<"u"&&process.versions?.node!=null,Na=class{instance;constructor(e={}){this.instance=bl.default.create({baseURL:e.baseURL,timeout:e.timeout??pd,validateStatus:()=>!0,headers:{Accept:"application/json",...md?{"User-Agent":e.userAgent??cd}:{},...e.headers}})}async request(e,t,n,o={}){let s=o.signal??kl,a=await this.instance.request({...o,signal:s,method:e,url:t,data:n}),i={};for(let[c,u]of Object.entries(a.headers??{}))u!=null&&(i[c.toLowerCase()]=String(u));let l={ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,data:a.data,headers:i};if(l.status===402&&Ea&&!dd(o.headers)){let c=await Ea(l,{url:t,method:String(e),body:n,headers:o.headers});if(c)return this.request(e,t,n,{...o,headers:{...o.headers,...c}})}return l}get(e,t){return this.request("GET",e,void 0,t)}post(e,t,n){return this.request("POST",e,t,n)}put(e,t,n){return this.request("PUT",e,t,n)}patch(e,t,n){return this.request("PATCH",e,t,n)}delete(e,t){return this.request("DELETE",e,void 0,t)}},x=new Na;function U(r){let{data:e,status:t,statusText:n}=r,o=n?`HTTP ${t} ${n}`:`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 hd(r){return r instanceof B?r.details||r.shortMessage:r instanceof Error?r.message:typeof r=="string"?r:""}var B=class extends Error{name="BaseError";shortMessage;details;metaMessages;constructor(e,t={}){let n=t.details??hd(t.cause),o=t.metaMessages??[],s=[e||"An error occurred.",...o.length>0?["",...o]:[],...n?["",`Details: ${n}`]:[]].join(`
2
2
  `);super(s,t.cause!==void 0?{cause:t.cause}:void 0),this.shortMessage=e,this.details=n,this.metaMessages=o,t.name&&(this.name=t.name)}walk(e){return vl(this,e)}};function vl(r,e){if(e?.(r))return r;let t=r&&typeof r=="object"?r.cause:void 0;return t!=null?vl(t,e):e?null:r}var vt=class extends B{name="AbiParameterTypeError";constructor(e){super(`Type "${e}" is not a valid ABI type.`,{metaMessages:["Supported: address, bool, string, bytes, bytesN, (u)intN, tuple, and arrays of those."]})}},ms=class extends B{name="AbiEncodingLengthMismatchError";constructor({expectedLength:e,givenLength:t}){super("ABI encoding parameters/values length mismatch.",{metaMessages:[`Expected length (parameters): ${e}`,`Given length (values): ${t}`]})}},hs=class extends B{name="AbiEncodingArrayLengthMismatchError";constructor({expectedLength:e,givenLength:t,type:n}){super(`ABI encoding array length mismatch for type ${n}.`,{metaMessages:[`Expected length: ${e}`,`Given length: ${t}`]})}},qe=class extends B{name="InvalidAbiValueError";constructor({type:e,value:t,reason:n}){super(`Invalid value for ABI type "${e}".`,{metaMessages:[`Value: ${Tl(t)}`,`Reason: ${n}`]})}},gs=class extends B{name="IntegerOutOfRangeError";constructor({type:e,value:t,min:n,max:o}){super(`Number "${t}" is not in safe ${e} range.`,{metaMessages:[`Range: ${n} \u2026 ${o}`]})}},Pn=class extends B{name="InvalidAddressError";constructor(e){super(`Address "${Tl(e)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]})}};function Tl(r){if(typeof r=="bigint")return r.toString();if(typeof r=="string")return r;try{return JSON.stringify(r)??String(r)}catch{return String(r)}}var fs=class extends B{name="AbiEncodingBytesSizeMismatchError";constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" does not match expected size of bytes${e}.`)}},Tt=class extends B{name="AbiDecodingZeroDataError";constructor(){super('Cannot decode zero data ("0x") with ABI parameters.',{metaMessages:["The contract returned no data. Usually this means:","- the address is not a contract on this chain,","- the function does not exist on it, or","- the call was made before the contract was deployed."]})}},ys=class extends B{name="AbiDecodingDataSizeTooSmallError";data;params;size;constructor({data:e,params:t,size:n}){super(`Data size of ${n} bytes is too small for given parameters.`,{metaMessages:[`Params: (${t.map(o=>o.type).join(", ")})`,`Data: ${e} (${n} bytes)`]}),this.data=e,this.params=t,this.size=n}},Sn=class extends B{name="AbiDecodingOutOfBoundsError";constructor({position:e,length:t}){super(`Position ${e} is out of bounds (${t} bytes).`,{metaMessages:["The return data is truncated or not ABI-encoded."]})}},bs=class extends B{name="AbiItemNotFoundError";constructor({name:e,type:t="function"}){super(`${t[0].toUpperCase()}${t.slice(1)} "${e}" not found on ABI.`,{metaMessages:["Make sure you are using the correct ABI and that the item exists on it."]})}},At=class extends B{name="InvalidAbiSignatureError";constructor(e,t){super(`Invalid ABI signature: "${e}".`,{metaMessages:t?[t]:['Expected e.g. "function balanceOf(address owner) view returns (uint256)".']})}};var gd=/^0x[0-9a-fA-F]*$/;function Zt(r,{strict:e=!0}={}){return typeof r!="string"?!1:e?gd.test(r):r.startsWith("0x")}function Je(r){return r.startsWith("0x")||r.startsWith("0X")?r.slice(2):r}function Ro(r){return typeof r=="string"?Math.ceil(Je(r).length/2):r.length}function en(r,e,t){let n=Je(r),o=(e??0)*2,s=t===void 0?n.length:t*2;return`0x${n.slice(o,s)}`}function ws(r){return`0x${r.map(Je).join("")}`}function tn(r){let e=new Uint8Array(r.reduce((n,o)=>n+o.length,0)),t=0;for(let n of r)e.set(n,t),t+=n.length;return e}function Pt(r){let e=Je(r),t=e.length%2?`0${e}`:e,n=new Uint8Array(t.length/2);for(let o=0;o<n.length;o++)n[o]=parseInt(t.slice(o*2,o*2+2),16);return n}function mt(r){let e="";for(let t of r)e+=t.toString(16).padStart(2,"0");return`0x${e}`}function Ua(r){return new TextEncoder().encode(r)}function Ia(r){return new TextDecoder().decode(r)}function Te(r,e={}){let{size:t,signed:n}=e,o=BigInt(r);if(o<0n){if(!t)throw new Error("numberToHex: negative values require a `size`");o+=1n<<BigInt(t*8)}else if(n&&t){let a=(1n<<BigInt(t*8-1))-1n;if(o>a)throw new Error(`numberToHex: ${r} overflows int${t*8}`)}let s=o.toString(16);if(!t)return`0x${s}`;if(s.length>t*2)throw new Error(`numberToHex: ${r} overflows ${t} bytes`);return`0x${s.padStart(t*2,"0")}`}function La(r,e=32){if(r.length>e)throw new Error(`padLeft: ${r.length} bytes exceeds ${e}`);let t=new Uint8Array(e);return t.set(r,e-r.length),t}function Da(r,e=32){if(r.length>e)throw new Error(`padRight: ${r.length} bytes exceeds ${e}`);let t=new Uint8Array(e);return t.set(r),t}function nn(r){let e=1n<<256n,t=(r%e+e)%e;return Pt(t.toString(16).padStart(64,"0"))}function xn(r,{signed:e=!1}={}){let t=BigInt(mt(r));if(!e)return t;let n=BigInt(r.length*8);return t>=1n<<n-1n?t-(1n<<n):t}function $e(r,{signed:e=!1}={}){return Je(r)?xn(Pt(r),{signed:e}):0n}function ks(r,e={}){return Number($e(r,e))}var Al=require("js-sha3");var fd=/^0x[0-9a-fA-F]{40}$/;function E(r){return typeof r=="string"&&fd.test(r)}function Cn(r){let e=Je(r).toLowerCase(),t=(0,Al.keccak_256)(e),n="";for(let o=0;o<e.length;o++)n+=parseInt(t[o],16)>=8?e[o].toUpperCase():e[o];return`0x${n}`}function Oa(r){if(!E(r))throw new Error(`Address "${r}" is invalid.`);return Cn(r)}function Ma(r,e){return E(r)&&E(e)&&r.toLowerCase()===e.toLowerCase()}var Fa=require("js-sha3");function Pl(r){return`0x${(0,Fa.keccak_256)(new TextEncoder().encode(r))}`}function St(r){let e=r.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function xt(r){return r.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1").replace(/^byte(\[|$)/,"bytes1$1")}function _o(r){let e=xt(r.type);return e==="tuple"||e.startsWith("tuple[")?`(${(r.components??[]).map(_o).join(",")})${e.slice(5)}`:e}function Rn(r){return`${r.name??""}(${(r.inputs??[]).map(_o).join(",")})`}function ht(r){let e=typeof r=="string"?r:Rn(r);return`0x${(0,Fa.keccak_256)(new TextEncoder().encode(e)).slice(0,8)}`}function Ba(r){let e=typeof r=="string"?r:Rn(r);return Pl(e)}function Sl(r,e){let t=xt(e.type),n=St(t);if(n){let[o,s]=n;return!Array.isArray(r)||o!==null&&r.length!==o?!1:r.every(a=>Sl(a,{...e,type:s}))}if(t==="tuple"){let o=e.components??[];return Array.isArray(r)?r.length===o.length:typeof r=="object"&&r!==null}return t==="address"?typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/.test(r):t==="bool"?typeof r=="boolean":t==="string"?typeof r=="string":t.startsWith("bytes")?typeof r=="string"||r instanceof Uint8Array:t.startsWith("uint")||t.startsWith("int")?typeof r=="number"||typeof r=="bigint"||typeof r=="string":!0}function Ct({abi:r,name:e,args:t,type:n}){let o=n??"function",s=r.filter(i=>(i.type??"function")===o);if(e.startsWith("0x")&&e.length===10)return s.find(i=>ht(i)===e.toLowerCase());if(e.includes("("))return s.find(i=>Rn(i)===e);let a=s.filter(i=>i.name===e);return a.length<=1||!t?a[0]:a.find(i=>{let l=i.inputs??[];return l.length===t.length&&l.every((c,u)=>Sl(t[u],c))})??a[0]}function rn(r){let e=Ct(r);if(!e)throw new bs({name:r.name,type:r.type??"function"});return e}function xl(r){let e=new Uint8Array(Math.ceil(r.length/32)*32);return e.set(r),{dynamic:!0,encoded:tn([nn(BigInt(r.length)),e])}}function Cl(r,e){let t=r.slice(e.length),n=t===""?256:Number(t);if(!Number.isInteger(n)||n<8||n>256||n%8!==0)throw new vt(r);return n}function Rl(r,e){if(typeof r=="bigint")return r;if(typeof r=="number"){if(!Number.isInteger(r))throw new qe({type:e,value:r,reason:"expected an integer, got a fractional number"});return BigInt(r)}if(typeof r=="string"&&r.trim()!=="")try{return BigInt(r.trim())}catch{throw new qe({type:e,value:r,reason:"string is not a valid integer"})}throw new qe({type:e,value:r,reason:"expected a bigint, number or numeric string"})}function _l(r,{bits:e,signed:t,type:n}){let o=t?(1n<<BigInt(e-1))-1n:(1n<<BigInt(e))-1n,s=t?-(1n<<BigInt(e-1)):0n;if(r<s||r>o)throw new gs({type:n,value:r,min:s,max:o})}function El(r,e){if(r instanceof Uint8Array)return r;if(typeof r=="string"){if(!Zt(r))throw new qe({type:e,value:r,reason:"expected 0x-prefixed hex"});return Pt(r)}throw new qe({type:e,value:r,reason:"expected a hex string or Uint8Array"})}function qa(r,e){let t=St(r.type);if(t){let[o,s]=t;if(!Array.isArray(e))throw new qe({type:r.type,value:e,reason:"expected an array"});return yd({...r,type:s},e,o,r.type)}if(r.type==="tuple")return bd(r,e);let n=xt(r.type);if(n==="address"){if(!E(e))throw new Pn(e);return{dynamic:!1,encoded:La(Pt(Je(e).toLowerCase()))}}if(n==="bool"){if(typeof e!="boolean")throw new qe({type:n,value:e,reason:"expected a boolean"});let o=new Uint8Array(32);return o[31]=e?1:0,{dynamic:!1,encoded:o}}if(/^uint\d*$/.test(n)){let o=Rl(e,n);return _l(o,{bits:Cl(n,"uint"),signed:!1,type:n}),{dynamic:!1,encoded:nn(o)}}if(/^int\d*$/.test(n)){let o=Rl(e,n);return _l(o,{bits:Cl(n,"int"),signed:!0,type:n}),o<0n&&(o+=1n<<256n),{dynamic:!1,encoded:nn(o)}}if(/^bytes\d+$/.test(n)){let o=Number(n.slice(5));if(o<1||o>32)throw new vt(r.type);let s=El(e,n);if(s.length!==o)throw new fs({expectedSize:o,value:String(e)});return{dynamic:!1,encoded:Da(s)}}if(n==="bytes")return xl(El(e,n));if(n==="string"){if(typeof e!="string"&&!(e instanceof Uint8Array))throw new qe({type:n,value:e,reason:"expected a string"});return xl(typeof e=="string"?Ua(e):e)}throw new vt(r.type)}function $a(r){let e=0;for(let{dynamic:s,encoded:a}of r)e+=s?32:a.length;let t=[],n=[],o=0;for(let{dynamic:s,encoded:a}of r)s?(t.push(nn(BigInt(e+o))),n.push(a),o+=a.length):t.push(a);return tn([...t,...n])}function yd(r,e,t,n){let o=t===null;if(!o&&e.length!==t)throw new hs({expectedLength:t,givenLength:e.length,type:n});let s=!1,a=[];for(let i of e){let l=qa(r,i);l.dynamic&&(s=!0),a.push(l)}if(o||s){let i=$a(a);if(!o)return{dynamic:!0,encoded:i};let l=nn(BigInt(a.length));return{dynamic:!0,encoded:a.length>0?tn([l,i]):l}}return{dynamic:!1,encoded:tn(a.map(i=>i.encoded))}}function bd(r,e){let t=r.components??[],n=!1,o=[];for(let s=0;s<t.length;s++){let a=t[s],i=qa(a,Array.isArray(e)?e[s]:e[a.name??""]);i.dynamic&&(n=!0),o.push(i)}return{dynamic:n,encoded:n?$a(o):tn(o.map(s=>s.encoded))}}function _n(r,e){if(r.length!==e.length)throw new ms({expectedLength:r.length,givenLength:e.length});return r.length===0?"0x":mt($a(r.map((t,n)=>qa(t,e[n]))))}function F({abi:r,functionName:e,args:t=[]}){let n=rn({abi:r,name:e,args:t,type:"function"}),o=ht(n),s=n.inputs??[];return s.length===0?o:ws([o,_n(s,t)])}function Ha({abi:r,errorName:e,args:t=[]}){let n=rn({abi:r,name:e,args:t,type:"error"}),o=n.inputs??[],s=ht(n);return o.length===0?s:ws([s,_n(o,t)])}function wd(r){let e=r.replace(/^u?int/,"");return e?Number(e):256}function Eo(r,e){if(e<0||e+32>r.length)throw new Sn({position:e,length:r.length});return r.subarray(e,e+32)}function Ya(r,e){let t=xn(Eo(r,e));if(t>BigInt(r.length))throw new Sn({position:Number(t),length:r.length});return Number(t)}function Va(r){let e=St(r.type);if(e){let[n,o]=e;return n===null||Va({...r,type:o})}if(r.type==="tuple")return(r.components??[]).some(Va);let t=xt(r.type);return t==="bytes"||t==="string"}function Wa(r){let e=St(r.type);if(e){let[t,n]=e;return t===null?32:t*Wa({...r,type:n})}return r.type==="tuple"?(r.components??[]).reduce((t,n)=>t+Wa(n),0):32}function Ga(r,e,t){let n=[],o=e;for(let s of t)Va(s)?(n.push(Nl(r,e+Ya(r,o),s)),o+=32):(n.push(Nl(r,o,s)),o+=Wa(s));return n}function kd(r,e,t,n){let o=n===null?Ya(r,e):n,s=n===null?e+32:e;return Ga(r,s,new Array(o).fill(t))}function vd(r,e,t){let n=t.components??[],o=Ga(r,e,n);if(n.length===0||n.some(i=>!i.name))return o;let a={};return n.forEach((i,l)=>{a[i.name]=o[l]}),a}function Nl(r,e,t){let n=St(t.type);if(n){let[s,a]=n;return kd(r,e,{...t,type:a},s)}if(t.type==="tuple")return vd(r,e,t);let o=xt(t.type);if(o==="address")return Cn(mt(Eo(r,e).subarray(12)));if(o==="bool")return xn(Eo(r,e))!==0n;if(/^u?int\d*$/.test(o)){let s=o.startsWith("int"),a=xn(Eo(r,e),{signed:s});return wd(o)>48?a:Number(a)}if(/^bytes\d+$/.test(o)){let s=Number(o.slice(5));return mt(Eo(r,e).subarray(0,s))}if(o==="bytes"||o==="string"){let s=Ya(r,e),a=e+32;if(a+s>r.length)throw new Sn({position:a+s,length:r.length});let i=r.subarray(a,a+s);return o==="bytes"?mt(i):Ia(i)}throw new vt(t.type)}function be(r,e){let t=typeof e=="string"?Pt(e):e;if(t.length===0){if(r.length>0)throw new Tt;return[]}if(t.length<32)throw new ys({data:typeof e=="string"?e:mt(e),params:r,size:t.length});return Ga(t,0,r)}function le(r){if(!r)return null;try{let[e]=be([{type:"uint256"}],r);return e}catch{return null}}function G(r){if(!r)return null;try{let[e]=be([{type:"address"}],r),t=e;return/^0x0{40}$/i.test(t)?null:t}catch{return null}}function No(r){if(!r)return null;try{let[e]=be([{type:"string"}],r),t=Ul(e);if(t)return t}catch{}try{let[e]=be([{type:"bytes32"}],r);return Ts(e)}catch{return null}}function En(r){return vs(le(r))}function vs(r){let e=typeof r=="bigint"?Number(r):typeof r=="number"?r:NaN;return Number.isFinite(e)&&e>=0&&e<=36?e:null}function Ts(r){return typeof r!="string"||!r.startsWith("0x")?null:Ul(Buffer.from(r.slice(2),"hex").toString("utf8"))||null}function Ul(r){return r.replace(/[^\x20-\x7e]/g,"").trim()}function Ze({abi:r,functionName:e,args:t,data:n}){let s=rn({abi:r,name:e,args:t,type:"function"}).outputs??[],a=be(s,n);if(a.length!==0)return a.length===1?a[0]:a}function ja({abi:r,data:e}){let t=en(e,0,4),n=rn({abi:r,name:t,type:"function"}),o=n.inputs??[];return{functionName:n.name,args:o.length===0||Ro(e)<=4?[]:be(o,en(e,4))}}var Il={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},Ll={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},Dl={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 Nn({abi:r=[],data:e}){let t=en(e,0,4);if(Ro(e)<4)throw new Error(`Cannot decode error result: "${e}" is too short.`);let n=[...r,Il,Ll],o=Ct({abi:n,name:t,type:"error"})??n.find(a=>(a.type??"")==="error"&&ht(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?be(s,en(e,4)):void 0}}function Uo({abi:r,data:e}){if(!(!e||e==="0x"))try{let{errorName:t,args:n}=Nn({abi:r,data:e});if(t==="Error")return String(n?.[0]??"");if(t==="Panic"){let o=Number(n?.[0]??0);return Dl[o]??`Panic code ${o}.`}return!n||n.length===0?t:`${t}(${n.map(o=>String(o)).join(", ")})`}catch{return}}var Td=new Set(["pure","view","nonpayable","payable"]),Ad=new Set(["external","public","internal","private","calldata","memory","storage"]);function za(r,e){let t=0;for(let n=e;n<r.length;n++)if(r[n]==="(")t++;else if(r[n]===")"&&(t--,t===0))return n;throw new At(r,"Unbalanced parentheses.")}function Ml(r){let e=[],t=0,n="";for(let o of r){if(o==="("&&t++,o===")"&&t--,o===","&&t===0){e.push(n),n="";continue}n+=o}return n.trim()&&e.push(n),e.map(o=>o.trim()).filter(Boolean)}function Pd(r){let e=r.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:e?.[1]??"",rest:(e?.[2]??"").trim()}}function Ol(r,e){let t=!1,n;for(let o of r)o==="indexed"?t=!0:Ad.has(o)||(n=o);return{...e,...n?{name:n}:{},...t?{indexed:!0}:{}}}function Xa(r){let e=r.trim();if(e.startsWith("(")){let o=za(e,0),s=Ml(e.slice(1,o)).map(Xa),{suffix:a,rest:i}=Pd(e.slice(o+1).trim());return Ol(i.split(/\s+/).filter(Boolean),{type:`tuple${a}`,components:s})}let[t,...n]=e.split(/\s+/).filter(Boolean);if(!t)throw new At(r,"Missing parameter type.");return Ol(n,{type:t})}function Lo(r){return Ml(r).map(Xa)}function Io(r,e,t){let n=r.indexOf("(",e);if(n===-1)throw new At(t,"Missing parameter list.");let o=za(r,n);return{name:r.slice(e,n).trim(),params:Lo(r.slice(n+1,o)),rest:r.slice(o+1).trim()}}function Ka(r,e){return r.split(/[\s()]+/).find(n=>Td.has(n))??e}function As(r){let e=r.trim();if(e.startsWith("function ")){let{name:t,params:n,rest:o}=Io(e,9,r),s=o.indexOf("returns"),a=s===-1?o:o.slice(0,s),i=[];if(s!==-1){let l=o.indexOf("(",s);if(l===-1)throw new At(r,"`returns` without a parameter list.");i=Lo(o.slice(l+1,za(o,l)))}return{type:"function",name:t,inputs:n,outputs:i,stateMutability:Ka(a,"nonpayable")}}if(e.startsWith("event ")){let{name:t,params:n}=Io(e,6,r);return{type:"event",name:t,inputs:n}}if(e.startsWith("error ")){let{name:t,params:n}=Io(e,6,r);return{type:"error",name:t,inputs:n}}if(e.startsWith("constructor")){let{params:t,rest:n}=Io(e,11,r);return{type:"constructor",inputs:t,stateMutability:Ka(n,"nonpayable")}}if(e.startsWith("fallback")){let{rest:t}=Io(e,8,r);return{type:"fallback",stateMutability:Ka(t,"nonpayable")}}if(e.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new At(r,"Expected function, event, error, constructor, fallback or receive.")}function Qa(r){return r.map(As)}function et({blockNumber:r,blockTag:e="latest"}={}){return r!==void 0?Te(r):e}function Do(r){let{account:e,to:t,data:n,value:o,gas:s,gasPrice:a,maxFeePerGas:i,maxPriorityFeePerGas:l,nonce:c}=r,u={};return e&&(u.from=e),t&&(u.to=t),n&&(u.data=n),o!==void 0&&(u.value=Te(o)),s!==void 0&&(u.gas=Te(s)),a!==void 0&&(u.gasPrice=Te(a)),i!==void 0&&(u.maxFeePerGas=Te(i)),l!==void 0&&(u.maxPriorityFeePerGas=Te(l)),c!==void 0&&(u.nonce=Te(c)),u}function Ja(r){let e={};for(let[t,n]of Object.entries(r)){let o={};n.balance!==void 0&&(o.balance=Te(n.balance)),n.nonce!==void 0&&(o.nonce=Te(n.nonce)),n.code!==void 0&&(o.code=n.code),n.state&&(o.state=n.state),n.stateDiff&&(o.stateDiff=n.stateDiff),e[t]=o}return e}async function Un(r){return $e(await r.request({method:"eth_blockNumber"}))}async function In(r){return ks(await r.request({method:"eth_chainId"}))}async function Ln(r,{address:e,...t}){return $e(await r.request({method:"eth_getBalance",params:[e,et(t)]}))}async function Rt(r,{address:e,...t}){let n=await r.request({method:"eth_getCode",params:[e,et(t)]});return!n||n==="0x"?void 0:n}async function Dn(r,{address:e,slot:t,...n}){return await r.request({method:"eth_getStorageAt",params:[e,t,et(n)]})??void 0}async function On(r,{address:e,...t}){return ks(await r.request({method:"eth_getTransactionCount",params:[e,et(t)]}))}async function Mn(r){return $e(await r.request({method:"eth_gasPrice"}))}async function Ps(r){return $e(await r.request({method:"eth_maxPriorityFeePerGas"}))}async function Fn(r,{blockNumber:e,blockTag:t,...n}){return $e(await r.request({method:"eth_estimateGas",params:[Do(n),et({blockNumber:e,blockTag:t})]}))}async function Bn(r,{includeTransactions:e=!1,...t}={}){let n=await r.request({method:"eth_getBlockByNumber",params:[et(t),e]});return n?{...n,blockNumber:n.number?$e(n.number):void 0,blockTimestamp:n.timestamp?$e(n.timestamp):void 0,baseFee:n.baseFeePerGas?$e(n.baseFeePerGas):void 0}:null}var K="0xcA11bde05977b3631167028862bE2a173976CA11",Fl={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:K,blockCreated:14353601}}},Bl={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:K,blockCreated:4286263}}},ql={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:K}}},$l={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:K,blockCreated:25770160}}},Hl={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:K,blockCreated:5022}}},Vl={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:K,blockCreated:7654707}}},Wl={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:K}}},Yl={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:K}}},Gl={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:K}}},jl={id:999,hexId:"0x3e7",name:"HyperEVM",nativeCurrency:{name:"HYPE",symbol:"HYPE",decimals:18},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}},contracts:{multicall3:{address:K}}},Kl={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:K}}},zl={id:143,hexId:"0x8f",name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://rpc.monad.xyz"]}},contracts:{multicall3:{address:K}}},on=[Fl,Bl,ql,$l,Hl,Vl,Wl,Yl,Gl,jl,Kl,zl];var Xl=new Map,Za=new Map;function Sd(r,e){return`${r??"unknown"}|${e.toLowerCase()}`}async function Ql(r,e=K){let t=Sd(r.chain?.id??r.chain?.hexId,e),n=Xl.get(t);if(n!==void 0)return n;let o=Za.get(t);if(o)return o;let s=(async()=>{try{let i=await Rt(r,{address:e})!==void 0;return Xl.set(t,i),i}catch{return!0}finally{Za.delete(t)}})();return Za.set(t,s),s}async function sn(r,e,t=!1){return t||typeof r.batch?.multicall=="object"&&r.batch.multicall.assumeMulticall3?!0:Ql(r,e)}var He=[{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 W=[{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}]}],qn=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]}];var $n=[{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 Ss=[{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 tt=[{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 Hn=class extends B{name="ChainNotFoundError";constructor(e){super(`Chain "${e}" is not supported.`,{metaMessages:["Add it to `chain/chains/definitions.ts`, or pass an explicit `transport`/`rpcUrl`."]})}},an=class extends B{name="ClientChainNotConfiguredError";constructor(){super("No chain was configured on the client.",{metaMessages:["Pass `chain` to createPublicClient(), or pass the address the action needs explicitly."]})}},_t=class extends B{name="ChainDoesNotSupportContractError";constructor({chain:e,contract:t,blockNumber:n}){super(n!==void 0?`Chain "${e}" does not support contract "${t}" at block ${n}.`:`Chain "${e}" does not support contract "${t}".`,{metaMessages:["Pass the contract address explicitly to use it on this chain."]})}};async function ei(r,e,t){let n=new Array(r.length);if(r.length===0)return n;let o=0,s=Math.max(1,Math.min(e>0?e:r.length,r.length));async function a(){for(;;){let i=o++;if(i>=r.length)return;try{n[i]={status:"fulfilled",value:await t(r[i],i)}}catch(l){n[i]={status:"rejected",reason:l}}}}return await Promise.all(Array.from({length:s},a)),n}function Oo({blockNumber:r,chain:e,contract:t}){let n=e.contracts?.[t];if(!n)throw new _t({chain:e.name,contract:t});if(r!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(r))throw new _t({blockNumber:r,chain:e.name,contract:t});return n.address}var Vn=class extends B{name="RawContractError";data;constructor({data:e,shortMessage:t="The contract call reverted."}){super(t),this.data=e}},ti=class extends B{name="ContractFunctionRevertedError";errorName;errorArgs;reason;data;constructor({abi:e,data:t,functionName:n}){let o=t?Uo({abi:e,data:t}):void 0,s,a;if(t&&t!=="0x")try{let i=Nn({abi:e,data:t});s=i.errorName,a=i.args}catch{}super(o?`The contract function "${n??"call"}" reverted with the following reason:
3
3
  ${o}`:`The contract function "${n??"call"}" reverted.`,{metaMessages:t&&t!=="0x"?[`Revert data: ${t}`]:[]}),this.reason=o,this.errorName=s,this.errorArgs=a,this.data=t}},ni=class extends B{name="ContractFunctionZeroDataError";constructor({functionName:e}){super(`The contract function "${e??"call"}" returned no data ("0x").`,{metaMessages:["This usually means:","- the address is not a contract on this chain,","- the ABI does not match the deployed contract, or","- the block predates the contract deployment."]})}},ri=class extends B{name="ContractFunctionExecutionError";abi;address;args;functionName;constructor(e,{abi:t,address:n,args:o,functionName:s,sender:a}){let i=t&&s?Ct({abi:t,name:s,args:o}):void 0,l=i?Rn(i):s,c=o&&o.length>0?` args: (${o.map(d=>xd(d)).join(", ")})`:void 0,u=i?.inputs?.length?`(${i.inputs.map(_o).join(", ")})`:"()";super(e instanceof B?e.shortMessage:`An error occurred calling "${s??"contract"}".`,{cause:e,metaMessages:[...n?[`Contract: ${n}`]:[],...l?[`Function: ${l}${i?"":u}`]:[],...c?[c]:[],...a?[`Sender: ${a}`]:[]]}),this.abi=t,this.address=n,this.args=o,this.functionName=s}},Mo=class extends B{name="CallExecutionError";constructor(e,{to:t,data:n}){super(e instanceof B?e.shortMessage:"The call failed.",{cause:e,metaMessages:[...t?[`To: ${t}`]:[],...n?[`Data: ${n}`]:[]]})}};function xd(r){if(typeof r=="bigint")return r.toString();if(typeof r=="string")return r;try{return JSON.stringify(r,(e,t)=>typeof t=="bigint"?t.toString():t)}catch{return String(r)}}function Jl(r){if(!r||typeof r!="object")return;let e=r,t=e.data;if(typeof t=="string"&&t.startsWith("0x"))return t;if(t&&typeof t=="object"){let n=t.data;if(typeof n=="string"&&n.startsWith("0x"))return n}return e.cause?Jl(e.cause):void 0}function Wn(r,{abi:e,address:t,args:n,functionName:o,sender:s}){let a=Jl(r),i=r instanceof Tt?new ni({functionName:o}):a!==void 0?new ti({abi:e,data:a,functionName:o}):r;return new ri(i,{abi:e,address:t,args:n,functionName:o,sender:s})}var oi=new Map;function Fo({fn:r,id:e,shouldSplitBatch:t,wait:n=0}){let o=()=>oi.get(e)??void 0,s=i=>oi.set(e,i),a=async i=>{o()===i&&oi.delete(e);try{let l=await r(i.map(c=>c.item));i.forEach((c,u)=>c.resolve(l[u]))}catch(l){i.forEach(c=>c.reject(l))}};return{schedule(i){return new Promise((l,c)=>{let u={item:i,resolve:l,reject:c},d=o();if(d)if(t?.([...d.map(m=>m.item),i]))a(d);else{d.push(u);return}let p=[u];s(p),setTimeout(()=>{a(p)},n)})}}}function Cd(r){return!!(r.data&&r.to&&!r.account&&!r.value&&!r.gas&&!r.gasPrice&&!r.maxFeePerGas&&!r.maxPriorityFeePerGas&&r.nonce===void 0&&!r.stateOverride)}async function Rd(r,e){let{batchSize:t=1024,wait:n=0}=typeof r.batch?.multicall=="object"?r.batch.multicall:{},{blockNumber:o,blockTag:s="latest",data:a,to:i}=e;if(!r.chain)throw new an;let l=Oo({blockNumber:o,chain:r.chain,contract:"multicall3"});if(!await sn(r,l,!1))throw new _t({chain:r.chain.name,contract:"multicall3"});let c=o!==void 0?Te(o):s,{schedule:u}=Fo({id:`${r.uid}.call.${c}`,wait:n,shouldSplitBatch:m=>m.reduce((g,h)=>g+(h.data.length-2)/2,0)>t,fn:async m=>{let g=F({abi:He,functionName:"aggregate3",args:[m.map(f=>({allowFailure:!0,callData:f.data,target:f.to}))]}),h=await r.request({method:"eth_call",params:[{to:l,data:g},c]});return Ze({abi:He,functionName:"aggregate3",data:h})}}),{returnData:d,success:p}=await u({data:a,to:i});if(!p)throw new Vn({data:d});return d}async function nt(r,e){let{blockNumber:t,blockTag:n,stateOverride:o,skipBatch:s,...a}=e;if(r.batch?.multicall&&!s&&Cd(e))try{let l=await Rd(r,{blockNumber:t,blockTag:n,data:a.data,to:a.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof an||l instanceof _t))throw new Mo(l,{to:a.to,data:a.data})}let i=[Do(a),et({blockNumber:t,blockTag:n})];o&&i.push(Ja(o));try{let l=await r.request({method:"eth_call",params:i});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new Mo(l,{to:a.to,data:a.data})}}var si=8;function Zl(r,e){if(e!==void 0&&e>0)return e;let t=typeof r.batch?.multicall=="object"?r.batch.multicall.fallbackConcurrency:void 0;return t!==void 0&&t>0?t:si}function Bo(r,e,t){if(e)return e;if(!r.chain)throw new an;let n=r.chain.contracts?.multicall3;return n?t!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(t)?K:n.address:K}async function Yn(r,e,t={}){let{concurrency:n,account:o,blockNumber:s,blockTag:a,stateOverride:i}=t;return(await ei(e,Zl(r,n),async c=>{let{data:u}=await nt(r,{to:c.target,data:c.callData,account:o,blockNumber:s,blockTag:a,stateOverride:i,skipBatch:!0});return u??"0x"})).map(c=>c.status==="fulfilled"?{success:!0,returnData:c.value}:{success:!1,returnData:"0x",error:c.reason})}async function rt(r,e){let{abi:t,address:n,functionName:o,args:s,...a}=e;try{let i=F({abi:t,functionName:o,args:s}),{data:l}=await nt(r,{...a,to:n,data:i});return Ze({abi:t,functionName:o,args:s,data:l??"0x"})}catch(i){throw Wn(i,{abi:t,address:n,args:s,functionName:o,sender:a.account})}}var _d=1024,Ed=50;async function Et(r,e){let{calls:t,account:n,blockNumber:o,blockTag:s,batchSize:a=_d,maxCalls:i=Ed,multicallAddress:l,stateOverride:c,fallbackConcurrency:u}=e,d=t.map(()=>({success:!1,returnData:"0x"}));if(t.length===0)return d;let p=Bo(r,l,o),m=[];if(t.forEach((y,b)=>{E(y.target)&&Zt(y.callData)&&m.push({index:b,call:y})}),m.length===0)return d;if(!await sn(r,p,l!==void 0))return(await Yn(r,m.map(b=>b.call),{account:n,blockNumber:o,blockTag:s,stateOverride:c,concurrency:u})).forEach((b,k)=>{d[m[k].index]={success:b.success,returnData:b.returnData}}),d;let g=[],h;return m.forEach(({call:y,index:b})=>{let k=(y.callData.length-2)/2,w=a>0&&h!==void 0&&h.size+k>a,v=i>0&&h!==void 0&&h.calls.length>=i;(!h||(w||v)&&h.calls.length>0)&&(h={calls:[],indexes:[],size:0},g.push(h)),h.calls.push(y),h.indexes.push(b),h.size+=k}),(await Promise.allSettled(g.map(y=>rt(r,{abi:He,address:p,functionName:"aggregate3",args:[y.calls.map(b=>({target:b.target,allowFailure:!0,callData:b.callData}))],account:n,blockNumber:o,blockTag:s,stateOverride:c})))).forEach((y,b)=>{y.status==="fulfilled"&&g[b].indexes.forEach((k,w)=>{let v=y.value[w];v&&(d[k]={success:!!v.success,returnData:v.returnData??"0x"})})}),d}var ec="https://wallet-api.pantograph.app/keyring/chains_v6",Nd=6,Ud=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,tc={},Gn=null;function Id(r){let e=Array.isArray(r.rpcs)?r.rpcs:[],t=typeof r.linkProvider=="string"?[r.linkProvider]:[],n=[];for(let o of[...t,...e]){if(typeof o!="string")continue;let s=o.trim();if(!(!s.startsWith("https://")||Ud.test(s))&&(n.includes(s)||n.push(s),n.length>=Nd))break}return n}function nc(r){if(!r||typeof r!="object"||Array.isArray(r))return{};let e={};for(let[t,n]of Object.entries(r)){if(!n||typeof n!="object")continue;let o=n,s=ot(t)??(typeof o.chainId=="number"?ot(o.chainId):void 0);if(!s)continue;let a=Id(o);a.length>0&&(e[s]=a)}return e}function rc(r){tc=r}function ai(r){let e=ot(r);return e?tc[e]??[]:[]}function ii(){Gn||xs()}function xs(r={}){let{url:e=ec,force:t=!1,debug:n=!1}=r;return Gn&&!t||(Gn=(async()=>{try{let o=await x.get(e);if(!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);let s=nc(o.data),a=Object.keys(s).length;if(a===0)throw new Error("catalogue contained no usable RPC endpoints");return rc(s),n&&console.log(`[chains] loaded RPC endpoints for ${a} chains from ${e}`),!0}catch(o){if(n){let s=o instanceof Error?o.message:String(o);console.warn(`[chains] remote RPC catalogue unavailable (${s}); using built-in endpoints`)}return Gn=null,!1}})()),Gn}var Ld=new Map(on.map(r=>[r.hexId.toLowerCase(),r])),Dd=new Map(on.map(r=>[r.id,r]));function ot(r){if(typeof r=="number")return Number.isFinite(r)&&r>=0?`0x${r.toString(16)}`:void 0;let e=r.trim().toLowerCase();if(e)return e.startsWith("0x")?/^0x[0-9a-f]+$/.test(e)?e:void 0:/^\d+$/.test(e)?`0x${Number(e).toString(16)}`:void 0}function gt(r){if(typeof r=="number")return Dd.get(r);let e=ot(r);return e?Ld.get(e):void 0}var Ie=Object.fromEntries(on.map(r=>[r.hexId,r.rpcUrls.default.http[0]]));function li(r){return gt(r)?.rpcUrls.default.http[0]}var ci={};function ln(r){let e={};if(r)for(let[t,n]of Object.entries(r)){if(typeof n!="string"||!n.trim())continue;let o=ot(t)??t.toLowerCase();e[o]=n.trim()}ci=e}function qo(){return{...ci}}function cn(r){ii();let e=ot(r),t=e?ci[e]:void 0,n=ai(r),o=gt(r)?.rpcUrls.default.http??[];return[...new Set([...t?[t]:[],...n,...o])]}function un(r){return cn(r)[0]}function ui(r){let e=gt(r);if(!e)return;let t=cn(r),n=e.rpcUrls.default.http;return t.length===0||t.length===n.length&&t.every((o,s)=>o===n[s])?e:{...e,rpcUrls:{default:{http:t}}}}var Nt=class extends B{name="HttpRequestError";status;url;body;headers;constructor({body:e,details:t,headers:n,status:o,url:s}){super("HTTP request failed.",{details:t,metaMessages:[`URL: ${s}`,...o?[`Status: ${o}`]:[],...e?[`Request body: ${JSON.stringify(e)}`]:[]]}),this.status=o,this.url=s,this.body=e,this.headers=n}},jn=class extends B{name="TimeoutError";constructor({body:e,url:t,timeout:n}){super("The request took too long to respond.",{details:`The request timed out after ${n}ms.`,metaMessages:[`URL: ${t}`,...e?[`Request body: ${JSON.stringify(e)}`]:[]]})}},Kn=class extends B{name="NetworkError";constructor({cause:e,url:t}){super("Could not reach the RPC endpoint.",{cause:e,metaMessages:[`URL: ${t}`]})}},Cs=class extends B{name="UrlRequiredError";constructor(){super("No RPC URL was provided.",{metaMessages:['Pass one to the transport \u2014 http("https://\u2026") \u2014 or give the client a chain that has a default RPC URL.']})}},$o=class extends B{name="FallbackTransportError";constructor({cause:e,count:t}){super(`All ${t} fallback transports failed.`,{cause:e})}};var zn=class extends B{name="RpcRequestError";code;data;constructor({body:e,error:t,url:n,shortMessage:o}){super(o??"RPC request failed.",{details:t.message,metaMessages:[...n?[`URL: ${n}`]:[],...e?[`Request body: ${JSON.stringify(e)}`]:[],`Error code: ${t.code}`]}),this.code=t.code,this.data=t.data}};function Le(r,e,t){return class extends zn{static code=e;name=r;constructor(n){super({...n,shortMessage:t})}}}var Od=Le("ParseRpcError",-32700,"The node could not parse the JSON request."),Md=Le("InvalidRequestRpcError",-32600,"The JSON request is not valid."),Fd=Le("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),Bd=Le("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),qd=Le("InternalRpcError",-32603,"The node reported an internal error."),$d=Le("InvalidInputRpcError",-32e3,"The RPC input is not valid."),Hd=Le("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),Vd=Le("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),Wd=Le("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),Yd=Le("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),di=Le("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),Gd=Le("UserRejectedRequestError",4001,"The user rejected the request."),jd=new Map([[-32700,Od],[-32600,Md],[-32601,Fd],[-32602,Bd],[-32603,qd],[-32e3,$d],[-32001,Hd],[-32002,Vd],[-32003,Wd],[-32004,Yd],[-32005,di],[4001,Gd]]);function oc(r){let e=jd.get(r.error.code);return e?new e(r):new zn(r)}function sc(r){return new Promise(e=>setTimeout(e,r))}async function pi(r,{retryCount:e=2,delay:t=150,shouldRetry:n=()=>!0}={}){let o=0;for(;;)try{return await r()}catch(s){if(o++,o>e||!n({count:o,error:s}))throw s;let a=typeof t=="function"?t({count:o,error:s}):t*2**(o-1);a>0&&await sc(a)}}function mi(r){let e=r?.["retry-after"];if(!e)return;let t=Number(e);if(Number.isFinite(t))return t*1e3;let n=Date.parse(e);return Number.isNaN(n)?void 0:Math.max(0,n-Date.now())}var Kd=new Set([408,413,429,500,502,503,504]),zd=new Set([401,402,403]);function Rs(r){return r instanceof jn||r instanceof Kn?!0:r instanceof Nt?r.status?Kd.has(r.status)||r.status>=500:!0:r instanceof di?!0:r instanceof zn?r.code===-32603:!1}function _s(r){return r instanceof Nt&&r.status&&zd.has(r.status)?!0:Rs(r)}function Es(r,{retryCount:e=3,retryDelay:t=150}={}){return function(o,s={}){return pi(()=>r(o),{retryCount:s.retryCount??e,shouldRetry:({error:a})=>Rs(a),delay:({count:a,error:i})=>{let l=i instanceof Nt?mi(i.headers):void 0;return l!==void 0?l:(s.retryDelay??t)*2**(a-1)}})}}function Ut({key:r,name:e,type:t,request:n,retryCount:o=3,retryDelay:s=150,timeout:a=1e4},i){return{config:{key:r,name:e,type:t,request:n,retryCount:o,retryDelay:s,timeout:a},request:Es(n,{retryCount:o,retryDelay:s}),value:i}}function It(r,e={}){let{key:t="fallback",name:n="Fallback",retryCount:o=0,retryDelay:s,onTransportError:a}=e;return(i={})=>{let l=r.map(u=>u(i));if(l.length===0)throw new $o({count:0});return Ut({key:t,name:n,type:"fallback",request:async u=>{let d;for(let p=0;p<l.length;p++)try{return await l[p].request(u)}catch(m){if(d=m,a?.({error:m,index:p,method:u.method}),!_s(m))throw m}throw new $o({cause:d,count:l.length})},retryCount:o,retryDelay:s,timeout:i.timeout},{transports:l})}}var ac=0;function ic(){return ac+=1,ac}function Xd(r){let e=r?.code;if(e==="ECONNABORTED"||e==="ETIMEDOUT")return!0;let t=r?.message??"";return/timeout/i.test(t)}var Xn=class{url;timeout;fetchOptions;constructor(e,{timeout:t=1e4,fetchOptions:n={}}={}){this.url=e,this.timeout=t,this.fetchOptions=n}async post(e){let t;try{t=await x.post(this.url,e,{...this.fetchOptions,timeout:this.timeout,headers:{"Content-Type":"application/json",...this.fetchOptions.headers}})}catch(n){throw Xd(n)?new jn({body:e,url:this.url,timeout:this.timeout}):new Kn({cause:n,url:this.url})}if(!t.ok)throw new Nt({body:e,details:U(t),headers:t.headers,status:t.status,url:this.url});return t.data}async request(e){let t={jsonrpc:"2.0",id:ic(),...e};return await this.post(t)??{id:t.id}}async requestBatch(e){let t=e.map(s=>({jsonrpc:"2.0",id:ic(),...s})),n=await this.post(t);if(!Array.isArray(n))return t.map(s=>({id:s.id,error:n?.error??{code:-32603,message:"Malformed batch response."}}));let o=new Map(n.map(s=>[s.id,s]));return t.map((s,a)=>o.get(s.id)??n[a]??{id:s.id,error:{code:-32603,message:"Missing response for batched request."}})}};function lc(r,e,t){if(r.error)throw oc({body:e,error:r.error,url:t});return r.result}function Ve(r,e={}){let{batch:t,fetchOptions:n,key:o="http",name:s="HTTP JSON-RPC",retryCount:a,retryDelay:i,timeout:l}=e;return({chain:c,retryCount:u,retryDelay:d,timeout:p}={})=>{let{batchSize:m=1e3,wait:g=0}=typeof t=="object"?t:{},h=l??p??1e4,f=r??c?.rpcUrls.default.http[0];if(!f)throw new Cs;let y=new Xn(f,{timeout:h,fetchOptions:n});return Ut({key:o,name:s,type:"http",retryCount:a??u,retryDelay:i??d,timeout:h,async request({method:b,params:k}){let w={method:b,params:k};if(t){let{schedule:v}=Fo({id:`${f}:${m}:${g}`,wait:g,shouldSplitBatch:T=>T.length>m,fn:T=>y.requestBatch(T)});return lc(await v(w),w,f)}return lc(await y.request(w),w,f)}},{url:f})}}var Qd=1024;async function Qn(r,e){let{contracts:t,allowFailure:n=!0,account:o,blockNumber:s,blockTag:a,multicallAddress:i,stateOverride:l,fallbackConcurrency:c}=e,u=e.batchSize??(typeof r.batch?.multicall=="object"&&r.batch.multicall.batchSize||Qd),d=new Array(t.length);if(t.length===0)return n?d:[];let p=Bo(r,i,s),m=[],g;t.forEach((y,b)=>{let{abi:k,address:w,functionName:v,args:T}=y,P;try{if(!E(w))throw new Pn(w);P=F({abi:k,functionName:v,args:T})}catch(N){let R=Wn(N,{abi:k,address:w,args:T,functionName:v,sender:o});if(!n)throw R;d[b]={status:"failure",error:R};return}let C=(P.length-2)/2;(!g||u>0&&g.size+C>u&&g.calls.length>0)&&(g={calls:[],indexes:[],size:0},m.push(g)),g.calls.push({target:w,allowFailure:!0,callData:P}),g.indexes.push(b),g.size+=C}),(await sn(r,p,i!==void 0)?await Promise.allSettled(m.map(y=>rt(r,{abi:He,address:p,functionName:"aggregate3",args:[y.calls],account:o,blockNumber:s,blockTag:a,stateOverride:l}))):await(async()=>{let y=m.flatMap(k=>k.calls.map((w,v)=>({target:w.target,callData:w.callData,index:k.indexes[v]}))),b=await Yn(r,y,{account:o,blockNumber:s,blockTag:a,stateOverride:l,concurrency:c});return m.length=0,b.map((k,w)=>(m.push({calls:[],indexes:[y[w].index],size:0}),k.success?{status:"fulfilled",value:[{success:!0,returnData:k.returnData}]}:{status:"rejected",reason:k.error}))})()).forEach((y,b)=>{let k=m[b];if(y.status==="rejected"){for(let w of k.indexes){let v=t[w],T=Wn(y.reason,{abi:v.abi,address:v.address,args:v.args,functionName:v.functionName,sender:o});if(!n)throw T;d[w]={status:"failure",error:T}}return}k.indexes.forEach((w,v)=>{let T=t[w],P=y.value[v];try{if(!P)throw new Error("Multicall returned fewer results than calls.");if(!P.success)throw new Vn({data:P.returnData});if(!P.returnData||P.returnData==="0x")throw new Tt;let C=Ze({abi:T.abi,functionName:T.functionName,args:T.args,data:P.returnData});d[w]={status:"success",result:C}}catch(C){let N=Wn(C,{abi:T.abi,address:T.address,args:T.args,functionName:T.functionName,sender:o});if(!n)throw N;d[w]={status:"failure",error:N}}})});for(let y=0;y<t.length;y++){if(d[y])continue;let b=new Error("Multicall returned no result for this call.");if(!n)throw b;d[y]={status:"failure",error:b}}return n?d:d.map(y=>y.result)}var Jd=0,dn=class{key;name;uid;chain;transport;batch;request;constructor(e={}){let{batch:t,key:n="public",name:o="Public Client",retryCount:s,retryDelay:a,timeout:i}=e;this.chain=ep(e.chain),this.key=n,this.name=o,this.batch=t,this.uid=`${n}-${++Jd}-${Math.random().toString(36).slice(2,8)}`;let c=(e.transport??Zd(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 nt(this,e)}readContract(e){return rt(this,e)}multicall(e){return Qn(this,e)}multicallRaw(e){return Et(this,e)}getBlockNumber(){return Un(this)}getChainId(){return In(this)}getBalance(e){return Ln(this,e)}getCode(e){return Rt(this,e)}getStorageAt(e){return Dn(this,e)}getTransactionCount(e){return On(this,e)}getGasPrice(){return Mn(this)}estimateMaxPriorityFeePerGas(){return Ps(this)}estimateGas(e){return Fn(this,e)}getBlock(e){return Bn(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 Zd(r,e){if(r)return Ve(r);let t=e?.rpcUrls.default.http??[];return t.length>1?It(t.map(n=>Ve(n,{retryCount:1}))):Ve(t[0])}function ep(r){if(r===void 0)return;if(typeof r=="object")return r;let e=ui(r);if(!e)throw new Hn(r);return e}function Lt(r={}){return new dn(r)}var hi=new Map;function tp(r,e){return{id:parseInt(r,16),hexId:r,name:`Chain ${parseInt(r,16)}`,nativeCurrency:{name:"Native",symbol:"ETH",decimals:18},rpcUrls:{default:{http:e}},contracts:{multicall3:{address:K}}}}function Ae(r,e={}){let{batch:t=!0,pinRpcUrl:n=!1,fallbackConcurrency:o,assumeMulticall3:s}=e,a=ot(r),i=e.rpcUrl?.trim(),l=a?cn(a):[],c=i?n?[i]:[...new Set([i,...l])]:l;if(c.length===0)throw new Hn(r);let u=`${a??r}|${c.join(",")}|${t?1:0}|${o??""}|${s?1:0}`,d=hi.get(u);if(d)return d;let p=Lt({chain:a&&!gt(a)?tp(a,c):a,transport:c.length===1?Ve(c[0]):It(c.map(m=>Ve(m,{retryCount:1}))),batch:t?{multicall:{fallbackConcurrency:o,assumeMulticall3:s}}:void 0});return hi.set(u,p),p}function Ns(){hi.clear()}function fi(r,e){try{return Ae(r,{rpcUrl:e?.trim()||void 0})}catch{return null}}async function Pe(r,e,t){let n=new Array(e.length).fill(null),o=e.length>0?fi(r,t):null;if(!o)return n;let s=[];if(e.forEach((a,i)=>{!E(a.target)||!Zt(a.callData)||s.push({index:i,target:a.target,callData:a.callData})}),s.length===0)return n;try{(await Et(o,{calls:s})).forEach((i,l)=>{i.success&&(n[s[l].index]=i.returnData)})}catch{}return n}function Us(r){return r?.status==="success"?r.result:void 0}async function gi(r,e){try{return await r.multicall({contracts:e})}catch{return[]}}async function cc(r,e,t){let n=e.map(()=>({symbol:null,decimals:null})),o=e.length>0?fi(r,t):null;if(!o)return n;let s=[];if(e.forEach((l,c)=>{E(l)&&s.push({index:c,address:l})}),s.length===0)return n;let a=await gi(o,s.flatMap(l=>[{address:l.address,abi:W,functionName:"symbol"},{address:l.address,abi:W,functionName:"decimals"}]));s.forEach((l,c)=>{let u=Us(a[c*2]);typeof u=="string"&&u.trim()&&(n[l.index].symbol=u.trim()),n[l.index].decimals=vs(Us(a[c*2+1]))});let i=s.filter(l=>n[l.index].symbol===null);if(i.length>0){let l=await gi(o,i.map(c=>({address:c.address,abi:qn,functionName:"symbol"})));i.forEach((c,u)=>{n[c.index].symbol=Ts(Us(l[u]))})}return n}async function uc(r,e,t){let n=new Array(e.length).fill(null),o=e.length>0?fi(r,t):null;if(!o)return n;let s=[];return e.forEach((i,l)=>{if(E(i.contract))try{s.push({index:l,address:i.contract,tokenId:BigInt(i.tokenId)})}catch{}}),s.length===0||(await gi(o,s.map(i=>({address:i.address,abi:$n,functionName:"tokenURI",args:[i.tokenId]})))).forEach((i,l)=>{let c=Us(i);if(typeof c!="string")return;let u=c.replace(/\0+$/,"").trim();u&&(n[s[l].index]=u)}),n}function np(r){return Is(String(r))??"0"}function Is(r){let e=r.trim().match(/^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/);if(!e)return null;let t=e[1]==="-"?"-":"",n=e[2]??"",o=e[3]??"";if(n===""&&o==="")return null;let s=e[4]?parseInt(e[4],10):0,a=n+o,i=n.length+s,l;return i<=0?l=`0.${"0".repeat(-i)}${a}`:i>=a.length?l=a+"0".repeat(i-a.length):l=`${a.slice(0,i)}.${a.slice(i)}`,l=l.replace(/^0+(?=\d)/,""),l.includes(".")&&(l=l.replace(/0+$/,"").replace(/\.$/,"")),(l===""||l==="-")&&(l="0"),l==="0"?"0":t+l}function yi(r){let e=Is(r);if(e===null||e.startsWith("-"))return null;let[t,n=""]=e.split(".");return{mant:BigInt(t+n),frac:n.length}}function bi(r,e){let t=r<0n,n=(t?-r:r).toString(),o;if(e===0)o=n;else{let s=n.padStart(e+1,"0"),a=s.length-e;o=`${s.slice(0,a)}.${s.slice(a)}`.replace(/0+$/,"").replace(/\.$/,"")}return t?`-${o}`:o}function Jn(r){if(typeof r=="number")return Number.isFinite(r)&&r>0?np(r):null;if(typeof r!="string")return null;let e=r.match(/[0-9]*\.?[0-9]+(?:[eE][+-]?[0-9]+)?/);if(!e)return null;let t=Is(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function Dt(r,e){let t=Is(r);if(t===null||e<0)return r;let n=t.startsWith("-"),[o,s=""]=(n?t.slice(1):t).split(".");if(s.length<=e)return t;let a=e===0?o:`${o}.${s.slice(0,e)}`,i=a.includes(".")?a.replace(/0+$/,"").replace(/\.$/,""):a;return n?`-${i}`:i}function Zn(r,e,t,n){let o=yi(r);if(!o||t<=0n||n<0)return r;let s=o.mant*e*10n**BigInt(n)/(t*10n**BigInt(o.frac));return bi(s,n)}function pn(r,e){let t=yi(r),n=yi(e);if(!t||!n){let i=Number(r),l=Number(e);return i<l?-1:i>l?1:0}let o=Math.max(t.frac,n.frac),s=t.mant*10n**BigInt(o-t.frac),a=n.mant*10n**BigInt(o-n.frac);return s<a?-1:s>a?1:0}var rp={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"}]},op="payment-required",sp="PAYMENT-SIGNATURE",ap="X-PAYMENT",ip="payment-response",lp="x-payment-response",cp=600,up=300,dp={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 dc(r){if(typeof globalThis<"u"&&typeof globalThis.btoa=="function"){let e=new TextEncoder().encode(r),t=Array.from(e,n=>String.fromCharCode(n)).join("");return globalThis.btoa(t)}return Buffer.from(r,"utf8").toString("base64")}function mc(r){if(typeof globalThis<"u"&&typeof globalThis.atob=="function"){let e=globalThis.atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(t)}return Buffer.from(r,"base64").toString("utf8")}function pp(){let r=new Uint8Array(32),e=globalThis.crypto;if(e?.getRandomValues)e.getRandomValues(r);else for(let t=0;t<32;t++)r[t]=Math.floor(Math.random()*256);return"0x"+Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}function hc(r){let e=String(r);if(e.includes(":")){let[n,o]=e.split(":"),s=parseInt(o,10);if(n!=="eip155"||Number.isNaN(s))throw new Error(`Unsupported x402 network: ${r} (only EVM "eip155:*" is supported)`);return s}let t=dp[e.toLowerCase()];if(t===void 0)throw new Error(`Unsupported x402 network: ${r}`);return t}function gc(r){if(!r.query||Object.keys(r.query).length===0)return r.url;let e=Object.entries(r.query).map(([t,n])=>`${encodeURIComponent(t)}=${encodeURIComponent(n)}`).join("&");return r.url.includes("?")?`${r.url}&${e}`:`${r.url}?${e}`}function Ls(r){let e=r.headers[op];if(e){let o=pc(mp(e));return o&&Array.isArray(o.accepts)?{version:2,payload:o}:null}let t=r.data,n=t&&typeof t=="object"?t:pc(t);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function pc(r){if(typeof r!="string")return null;try{let e=JSON.parse(r);return e&&typeof e=="object"?e:null}catch{return null}}function mp(r){try{return mc(r)}catch{return null}}function hp(r){let e=r.amount??r.maxAmountRequired;return typeof r.scheme!="string"||typeof r.network!="string"||e==null||typeof r.asset!="string"||typeof r.payTo!="string"?null:{scheme:r.scheme,network:r.network,amount:String(e),asset:r.asset,payTo:r.payTo,...typeof r.maxTimeoutSeconds=="number"?{maxTimeoutSeconds:r.maxTimeoutSeconds}:{},...r.extra&&typeof r.extra=="object"?{extra:r.extra}:{},...typeof r.resource=="string"?{resource:r.resource}:{},...typeof r.description=="string"?{description:r.description}:{},...typeof r.mimeType=="string"?{mimeType:r.mimeType}:{},...r.outputSchema!=null?{outputSchema:r.outputSchema}:{}}}function gp(r){let e=null;for(let t of r){let n=hp(t);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return hc(n.network),n}catch(o){e=o instanceof Error?o.message:String(o)}}}throw new Error(e?`No payable x402 requirement offered (${e}); only the EVM "exact" scheme is supported`:"402 response offered no payment requirements")}function wi(r,e,t,n){let o=Ls(r);if(!o)throw new Error("402 response carries no x402 payment requirements");let{version:s,payload:a}=o,i=gp(a.accepts??[]);if(!t)throw new Error("No connected wallet address to build the payment from");let l=hc(i.network),c=Math.floor(Date.now()/1e3),u={from:t,to:i.payTo,value:String(i.amount),validAfter:String(Math.max(0,c-cp)),validBefore:String(c+(i.maxTimeoutSeconds??up)),nonce:pp()},d={domain:{name:i.extra?.name,version:i.extra?.version,chainId:l,verifyingContract:i.asset},types:rp,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:gc(e),method:e.method??"GET",body:e.body,headers:e.headers},x402Version:s,requirements:i,authorization:u,typedData:d,chainId:l,...a.resource!=null?{resource:a.resource}:{},...a.extensions!=null?{extensions:a.extensions}:{},...n?{userQuery:n}:{}}}async function fp(r,e,t,n){let o=gc(e),s=await r.request(e.method??"GET",o,e.body,{headers:e.headers});if(s.status===402)return{status:"payment_required",challenge:wi(s,e,t,n)};if(!s.ok)throw new Error(U(s));return{status:"ok",data:s.data}}async function ki(r,e,t){let{url:n,method:o,body:s,headers:a}=e.request,i=await r.request(o,n,s,{headers:{...a??{},...vi(e,t)}});if(i.ok)return i.data;throw new Error(bp(i)??U(i))}function yp(r){return Ls(r)!==null}function fc(r){let e=yc(r);return e?.errorReason?e.errorReason:Ls(r)?.payload.error??null}function bp(r){let e=fc(r);return e?`x402 payment rejected: ${e}`:null}var wp={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 vi(r,e){let{requirements:t,authorization:n}=r,o={signature:e,authorization:n};if(r.x402Version===1){let a={x402Version:1,scheme:t.scheme,network:t.network,payload:o};return{[ap]:dc(JSON.stringify(a))}}let s={x402Version:2,...r.resource!=null?{resource:r.resource}:{},accepted:kp(t),payload:o,...r.extensions!=null?{extensions:r.extensions}:{}};return{[sp]:dc(JSON.stringify(s))}}function kp(r){let{resource:e,description:t,mimeType:n,outputSchema:o,...s}=r;return s}function yc(r){let e=r.headers[ip]??r.headers[lp];if(!e)return null;try{return JSON.parse(mc(e))}catch{return null}}function vp(r,e){return r==null?e:wp[r]??`Chain ${r}`}async function bc(r){let e=r.requirements,n=r.resource?.description||e.description,o=r.chainId??null,s=null,a=null;if(o!=null){let[l]=await cc("0x"+o.toString(16),[e.asset]);s=l?.symbol??null,a=l?.decimals??null}let i=String(e.amount);if(a!==null)try{i=bi(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:vp(o,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:r.request.url}}function Ti(r){return async(e,t)=>{let n=r.getPayer(),o=r.getSigner();if(!n||!o)return null;let s;try{s=wi(e,{url:t.url,method:t.method,body:t.body,headers:t.headers},n)}catch{return null}let a;try{a=await o({typedData:s.typedData,display:await bc(s)})}catch{a=null}return a?vi(s,a):null}}var Ot=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function mn(r){if(!r||typeof r!="object")return!1;let e=r;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function Ho(r){if(r?.aborted)throw new Ot}function Ai(r,e){if(!e)return{signal:r.signal,cleanup:()=>{}};if(e.aborted)return r.abort(),{signal:r.signal,cleanup:()=>{}};let t=()=>r.abort();return e.addEventListener("abort",t),{signal:r.signal,cleanup:()=>e.removeEventListener("abort",t)}}var wc={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},Tp="https://nft.keyring.app/api/gemini-stable",Ap="https://generativelanguage.googleapis.com",Pp=new Set([408,429,500,502,503,504]),kc=3e4,Ds=r=>new Promise(e=>setTimeout(e,r));function Os(r,e,t){if(t!=null&&t>0)return Math.min(t,kc);let n=Math.min(e*2**(r-1),kc);return n/2+Math.random()*(n/2)}function Sp(r){if(!r)return null;let e=Number(r);if(Number.isFinite(e))return Math.max(0,e*1e3);let t=Date.parse(r);return Number.isNaN(t)?null:Math.max(0,t-Date.now())}var re=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?Ap:Tp)).replace(/\/+$/,"")}get isDirect(){return this.apiKey.length>0}setRequestSignal(e){this.requestSignal=e}async chat(e,t,n){let{systemInstruction:o,contents:s}=this.toContents(e),{maxRetries:a=5,retryDelayMs:i=1e3}=n??{},l=n?.signal??this.requestSignal;Ho(l);let c=s.length>0?s:[{role:"user",parts:[{text:"(continue)"}]}];if(n?._debug){console.log("[GeminiProvider] turn sequence:");for(let h of c){let f=h.parts.map(y=>y.functionCall?`fc:${y.functionCall.name}`:y.functionResponse?`fr:${y.functionResponse.name}`:`text:${(y.text??"").slice(0,40)}`).join(", ");console.log(` ${h.role}: [${f}]`)}}let u=n?.thinkingBudget??(n?.maxOutputTokens!=null?0:void 0),d={maxOutputTokens:n?.maxOutputTokens??this.maxTokens,temperature:this.temperature};u!=null&&(d.thinkingConfig={thinkingBudget:u});let p={contents:c,generationConfig:d};o&&(p.systemInstruction=o),t?.length?(p.tools=[{functionDeclarations:this.toFunctionDeclarations(t)}],n?.forceToolUse&&(p.toolConfig={functionCallingConfig:{mode:"ANY"}})):n?.googleSearch&&(p.tools=[{googleSearch:{}}]);let m=`${this.baseUrl}/v1beta/models/${this.model}:generateContent`,g="Unknown error";for(let h=1;h<=a;h++){Ho(l);let f;try{f=await x.post(m,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(P){if(mn(P))throw P;if(g=P instanceof Error?P.message:String(P),h>=a)break;await Ds(Os(h,i));continue}if(!f.ok){let P=typeof f.data=="string"?f.data:JSON.stringify(f.data)||f.statusText;if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${f.status}: ${P}`,!Pp.has(f.status))throw new Error(g);if(h>=a)break;let C=Sp(f.headers["retry-after"]??null);await Ds(Os(h,i,C));continue}if(f.data==null||typeof f.data!="object"){if(g=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,h>=a)break;await Ds(Os(h,i));continue}let y=f.data,b=y.candidates?.[0];if(!b)return{text:"",toolCalls:[]};let k="",w=[],v=b.content?.parts;if(!Array.isArray(v)||v.length===0){let P=b.finishReason;if(!(P==="SAFETY"||P==="RECITATION")&&h<a){g=`Gemini returned an empty turn (finishReason=${P??"none"})`,await Ds(Os(h,i));continue}return{text:"",toolCalls:[]}}for(let P of v)P.text&&(k+=P.text),P.functionCall&&w.push({toolName:P.functionCall.name,args:P.functionCall.args??{},callId:P.functionCall.id??`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`});let T=y.usageMetadata?{promptTokens:y.usageMetadata.promptTokenCount??0,completionTokens:y.usageMetadata.candidatesTokenCount??0,totalTokens:y.usageMetadata.totalTokenCount??0}:void 0;return{text:k,toolCalls:w,usage:T}}throw new Error(g)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let o=[];for(let i of n){let l=o[o.length-1],c=i.parts.some(d=>d.functionCall),u=l?.parts.some(d=>d.functionCall);l&&l.role===i.role&&!c&&!u?l.parts.push(...i.parts):o.push({...i,parts:[...i.parts]})}let s=[];for(let i=0;i<o.length;i++){let l=o[i],c=s[s.length-1];l.role==="function"&&!c?.parts.some(d=>d.functionCall)||l.role==="model"&&l.parts.some(d=>d.functionCall)&&!(o[i+1]?.role==="function")||s.push(l)}for(;s.length>0&&s[0].role!=="user";)s.shift();return{systemInstruction:t.length?{role:"user",parts:[{text:t.join(`
4
4
  `)}]}:null,contents:s}}toFunctionDeclarations(e){return e.map(t=>{let n={},o=[];for(let s of t.parameters){let a={type:wc[s.type]??"STRING",description:s.description};s.type==="array"&&(a.items={type:wc[s.items?.type??"string"]??"STRING"}),n[s.name]=a,s.required&&o.push(s.name)}return{name:t.name,description:t.description,parameters:{type:"OBJECT",properties:n,required:o}}})}};var er=class{tools=new Map;register(e){if(this.tools.has(e.name))throw new Error(`Tool "${e.name}" is already registered`);this.tools.set(e.name,e)}unregister(e){return this.tools.delete(e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getDefinitions(){return Array.from(this.tools.values()).map(e=>({name:e.name,description:e.description,parameters:e.parameters,category:e.category,kind:e.kind}))}getDefinitionsByCategory(e){return this.getDefinitions().filter(t=>t.category===e)}async execute(e,t,n){let o=this.tools.get(e);if(!o)return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:`Tool "${e}" not found in registry`,duration:0};let s=Date.now();try{return{...await o.execute(t,n),duration:Date.now()-s}}catch(a){return{toolName:e,callId:`err_${Date.now()}`,success:!1,error:a instanceof Error?a.message:String(a),duration:Date.now()-s}}}get size(){return this.tools.size}listNames(){return Array.from(this.tools.keys())}};var tr=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],xp=new Set(tr),Mt=[...tr],Pi=new Set(Mt),De="0x1",rr="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function Cp(r){return r.map(e=>nr[e]??e).join(", ")}function Ms(r){let e=new Set;if(r)for(let n of r){let o=Fs(n);o&&e.add(o)}let t=tr.filter(n=>!e.has(n));Mt=t.length>0?[...t]:[...tr],Pi=new Set(Mt),De=Mt.includes("0x1")?"0x1":Mt[0],rr=Cp(Mt)}var Rp={"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 q(r){let e=Fs(r);return e&&Pi.has(e)?e:null}function Fs(r){if(typeof r!="string")return null;let e=r.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=Rp[e];if(t)return t;let n=null;return/^0x[0-9a-f]+$/.test(e)?n=e:/^[0-9]+$/.test(e)&&(n="0x"+Number(e).toString(16)),n&&xp.has(n)?n:null}function We(r){return q(r)!==null}function Se(){return[...Mt]}var Bt=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${rr}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Ft=r=>typeof r=="string"&&r.trim()!=="";function oe(r,e){if(Ft(r)){let t=q(r);if(t)return t;throw new Bt(r.trim())}if(Ft(e?.chain)){let t=q(e.chain);if(t)return t;throw new Bt(e.chain.trim())}return null}function Bs(r,e){return q(r)??q(e?.chain)??void 0}var nr={"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 A(r){let e=Fs(r);return e&&nr[e]?nr[e]:typeof r=="string"&&r.trim()?r.trim():"the requested chain"}var _p={"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 vc(r,e){let t=Fs(r),n=t?_p[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var Ep={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function Tc(r){if(typeof r!="string")return null;let e=r.trim().toLowerCase();return e?Ep[e]??null:null}var Np={"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 Ac(r){let e=q(r);return e?Np[e]??null:null}function or(r,e){if(!Ft(r))return null;let t=q(r),n=q(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:nr[t]??t,connectedLabel:nr[n]??n}}function Pc(r,e){let t=typeof r=="string"?r.trim():"",n=e&&e.length?e.filter(s=>Pi.has(s)):[];return(n.length?n:Mt).map(s=>{let a=nr[s]??s;return{label:a,prompt:t?`${t} (${a})`:a}})}function sr(r,e){return{actionButtons:Pc(e),_instructions:`The user wants to ${r} but has a connected wallet with no network set. Ask them, in their language, which network to use \u2014 the chain-picker buttons below let them choose. Keep it short and do NOT list the chain names yourself (the buttons already show them). Do NOT render the form. Do NOT mention tool names, UI, or forms.`}}var ne=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=Pc(e,t)}},Vo=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 Z(r,e){if(Ft(r))return r.trim();if(Ft(e?.walletAddress))return e.walletAddress.trim();throw new Vo}function ce(r,e,t){if(Ft(r)){let n=q(r);if(n)return n;throw new Bt(r.trim())}if(Ft(e?.chain)){let n=q(e.chain);if(n)return n;throw new Bt(e.chain.trim())}if(Ft(e?.walletAddress))throw new ne(typeof e?.query=="string"?e.query:void 0,t);return De}var S=class{category;async execute(e,t){let n=`call_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,o=Date.now();try{let s=await this.run(e,t),a=Up(s);return{toolName:this.name,callId:n,success:!0,data:a.data,duration:Date.now()-o,...a.actionButtons?{actionButtons:a.actionButtons}:{},...a.ui?{ui:a.ui}:{}}}catch(s){return s instanceof ne?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has a connected wallet but no chain is set. Ask them which chain to use \u2014 the chain-picker buttons rendered below your reply let them choose. Keep the message short in the user's language and do NOT list the chain names yourself (the buttons already show them)."},duration:Date.now()-o,actionButtons:s.buttons}:s instanceof Vo?{toolName:this.name,callId:n,success:!0,data:{_instructions:"The user has not connected a wallet. In the user's language, tell them this action needs a wallet \u2014 they can either connect their wallet or include a wallet address (0x\u2026) directly in their question. Keep it short and friendly."},duration:Date.now()-o}:{toolName:this.name,callId:n,success:!1,error:s instanceof Error?s.message:String(s),duration:Date.now()-o}}}};function Up(r){if(!r||typeof r!="object")return{data:r};let e=r,t=e.actionButtons,n=Array.isArray(t)&&t.length>0?t:void 0,o=e.ui,s=o&&typeof o=="object"&&typeof o.component=="string"?o:void 0;if(!n&&!s)return{data:r};let{actionButtons:a,ui:i,...l}=e;return{data:l,...n?{actionButtons:n}:{},...s?{ui:s}:{}}}var Ip="https://wallet-api.pantograph.app",Lp="0x0000000000000000000000000000000000000000",Cc={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},Rc={"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 Dp(r){return Cc[r.toLowerCase()]||r}function Sc(r){let e=[];for(let[t,n]of Object.entries(r))if(n!=null)if(Array.isArray(n))for(let o of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function Si(r){let e=r,t=e.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):NaN,o=e.price,s=o!=null?parseFloat(String(o)):NaN;return{...e,token_address:e.token_address??e.address??"",decimals:Number.isFinite(n)?n:0,...Number.isFinite(s)?{usd_price:s}:{}}}function qs(r){if(Array.isArray(r))return r;let e=r;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function we(r){if(r==null)return null;let e=typeof r=="number"?r:parseFloat(String(r));return Number.isFinite(e)?e:null}function xc(r,e){let t=r.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,o=we(r.price_change_percentage_24h)??we(r.priceChange24h)??we(r.usd_price_24hr_percent_change)??we(r.price_change_24h)??we(r.priceChange);return{chainId:e,tokenAddress:r.address??r.token_address??"",name:r.name??null,symbol:r.symbol??null,decimals:n!=null&&Number.isFinite(n)?n:null,logo:r.logoURI??r.icon_image??r.logo??null,usdPrice:we(r.price)??we(r.usd_price),marketCap:we(r.market_cap)??we(r.marketCap),totalVolume:{"24h":we(r.total_volume)??we(r.volume24h)},pricePercentChange:{"24h":o}}}var se=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Ip).replace(/\/+$/,"")}tokensUrl(e,t){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(t)}`}async enrichTokenPrices(e,t){if(e.length!==0)try{let n=e.map(l=>l.token_address).join(","),o=this.tokensUrl(t,n),s=await x.get(o);if(!s.ok)return;let a=qs(s.data),i=new Map;for(let l of a)l.address&&i.set(l.address.toLowerCase(),{price:l.price!=null?parseFloat(String(l.price)):NaN,icon_image:l.icon_image});for(let l=0;l<e.length;l++){let c=i.get(e[l].token_address.toLowerCase());c&&(c.icon_image&&(e[l].logo=c.icon_image,e[l].thumbnail=c.icon_image),isNaN(c.price)||(e[l].usd_price=c.price,e[l].usd_value=parseFloat(e[l].balance_formatted||"0")*c.price))}}catch{}}async getYieldPricingTokens(e,t){let n=(t??[]).map(s=>String(s??"").trim()).filter(Boolean);if(n.length===0)return[];let o=typeof e=="number"?e:String(e).startsWith("0x")?parseInt(String(e),16):parseInt(String(e),10);if(!Number.isFinite(o))return[];try{let s=`${this.baseUrl}/keyrings/tokens/all/${o}?addresses=${encodeURIComponent(n.join(","))}`,a=await x.get(s);return a.ok?qs(a.data):[]}catch{return[]}}async getTokenMetadata(e,t){try{let n=this.tokensUrl(t,e),o=await x.get(n);if(!o.ok)return null;let s=qs(o.data),a=e.toLowerCase()===Lp,i=s.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return i?Si(i):null}catch{return null}}async getTokensMetadata(e,t){let n={};if(e.length===0)return n;try{let o=this.tokensUrl(t,e.join(",")),s=await x.get(o);if(!s.ok)return n;let a=qs(s.data),i=new Set(e.map(l=>l.toLowerCase()));for(let l of a){let c=l.address?.toLowerCase()||l.token_address?.toLowerCase()||(l.address===""?"":null);c&&i.has(c)&&(n[c]=Si(l))}}catch{}return n}async searchTokensByKey(e){let{key:t,chain:n}=e;if(!t)return{success:!1,error:"Search key is required"};let s=parseInt(n||De,16);if(isNaN(s))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=Sc({chainId:s,key:t}),i=`${this.baseUrl}/token-list/all?${a}`,l=await x.get(i);if(!l.ok)throw new Error(U(l));let c=l.data,u=c?.result??c?.data??c,d=[];return Array.isArray(u)?d=u:u&&typeof u=="object"&&(d=Object.values(u).flat()),{success:!0,data:d.map(Si)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||De,n=5,o=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let s=Rc[t.toLowerCase()]??[],a=o!=null?o+s.length:n+s.length,[i,l]=await Promise.allSettled([this.fetchTopGainers(t,a),s.length>0?this.getTokensMetadata(s,t):Promise.resolve({})]),c=i.status==="fulfilled"?i.value:[],u=l.status==="fulfilled"?s.map(h=>l.value[h.toLowerCase()]).filter(h=>h!=null).map(h=>xc(h,t)):[],d=new Set,p=[];for(let h of u){let f=h.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),p.push(h))}let m=[];for(let h of c){let f=h.tokenAddress?.toLowerCase();!f||d.has(f)||(d.add(f),m.push(h))}let g=o!=null?[...p,...m].slice(0,o):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(g,t),{success:!0,data:g}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let n=e.filter(s=>s.tokenAddress&&(s.marketCap==null||s.totalVolume?.["24h"]==null));if(n.length===0)return;let o=await this.getTokensMetadata(n.map(s=>s.tokenAddress),t);for(let s of n){let a=o[s.tokenAddress.toLowerCase()];a&&(s.marketCap==null&&(s.marketCap=we(a.market_cap)??we(a.marketCap)),s.totalVolume?.["24h"]==null&&(s.totalVolume={"24h":we(a.total_volume)??we(a.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let o=parseInt(e,16),s=Sc({chainId:o,duration:n,limit:t}),a=`${this.baseUrl}/token-list/all/top-gainers${s?`?${s}`:""}`,i=[];for(let l=0;l<5;l++){let c=await x.get(a);if(!c.ok)throw new Error(U(c));let u=c.data;if(i=Array.isArray(u)?u:Array.isArray(u.data)?u.data:[],i.length>0)break;l<4&&await new Promise(d=>setTimeout(d,2e3))}return i.map(l=>xc(l,e))}async getTopGainers(e){let t=e?.chain||De,n=e?.limit&&e.limit>0?Math.floor(e.limit):void 0,o=e?.duration||"24h";try{let s=await this.fetchTopGainers(t,n,o);return await this.enrichTrendingMarketData(s,t),{success:!0,data:s}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}};var Op="https://nft.keyring.app",Mp="https://nft.keyring.app",Fp=.01,I=5,z=1e3,Bp=25,qp="0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",$p="0x0000000000000000000000000000000000000000",L=class extends Error{constructor(t,n){super(n);this.status=t;this.name="MoralisHttpError"}status};function ee(r){return r||De}function X(r){let e=[];for(let[t,n]of Object.entries(r))if(n!=null)if(Array.isArray(n))for(let o of n)e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(o))}`);else e.push(`${encodeURIComponent(t)}=${encodeURIComponent(String(n))}`);return e.join("&")}function Q(r){return new Promise(e=>setTimeout(e,r))}function Hp(r){let e={active_protocols:0,total_positions:0,total_usd_value:0,total_unclaimed_usd_value:0,protocols:[]};if(!r||typeof r!="object")return e;let t=r;if("active_protocols"in t||"total_usd_value"in t){let o=t;return{...e,...o,protocols:o.protocols||[]}}let n=t.result;return!n||typeof n!="object"?e:{active_protocols:n.activeProtocols??0,total_positions:n.totalPositions??0,total_usd_value:n.totalUsd??0,total_unclaimed_usd_value:n.totalUnclaimedUsd??0,protocols:(n.protocols||[]).map(o=>({protocol_id:o.protocolId,protocol_name:o.protocolName,protocol_url:o.protocolUrl??"",protocol_logo:o.protocolLogo??"",positions:o.positionCount??0,total_usd_value:o.totalUsd??0,total_unclaimed_usd_value:o.totalUnclaimedUsd??0,account_health_factor:o.accountHealthFactor??null}))}}function Vp(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"){let e=r;return Array.isArray(e.result)?e.result.map(t=>({protocol_id:t.protocolId,protocol_name:t.protocolName,protocol_url:t.protocolUrl??"",protocol_logo:t.protocolLogo??"",position:{label:t.position.label,address:t.position.address,balance_usd:t.position.balanceUsd??0,total_unclaimed_usd_value:t.position.unclaimedUsd??0,position_details:t.position.details,tokens:t.position.tokens.map(n=>({token_type:n.tokenType,address:n.address,contract_address:n.address,name:n.name??"",symbol:n.symbol??"",decimals:n.decimals??18,logo:n.logo,balance:n.balance??"0",balance_formatted:n.balanceFormatted??"0",usd_price:n.usdPrice,usd_value:n.usdValue}))}})):Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}function xi(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"){let e=r;return Array.isArray(e.result)?e.result:Object.keys(e).filter(t=>/^\d+$/.test(t)).sort((t,n)=>Number(t)-Number(n)).map(t=>e[t]).filter(t=>!!t&&typeof t=="object")}return[]}var O=class{baseUrl;v1BaseUrl;pantograph;constructor(e){this.baseUrl=(e?.baseUrl??Op).replace(/\/+$/,""),this.v1BaseUrl=(e?.v1BaseUrl??Mp).replace(/\/+$/,""),this.pantograph=new se({baseUrl:e?.pantographUrl})}async getWalletTokenBalances(e){let{address:t,chain:n,tokenAddresses:o,excludeSpam:s=!1,excludeUnverifiedContracts:a=!1}=e;if(!t)return{success:!1,error:"Address is required"};let i=ee(n),l="Unknown error";for(let c=1;c<=I;c++)try{let u={chain:i,exclude_spam:s,exclude_unverified_contracts:a,limit:100};o&&(u.token_addresses=o);let d=[],p=null;do{p&&(u.cursor=p);let g=X(u),h=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/tokens?${g}`,f=await x.get(h);if(!f.ok)throw new L(f.status,U(f));let y=f.data,b=y?.data??y;b?.result?.length>0&&d.push(...b.result),p=b?.cursor??null}while(p);let m={result:d};return m?.result?.length>0&&(m.result=m.result.filter(g=>parseFloat(g.balance||"0")>0),m.result=m.result.map(g=>({...g,token_address:g.token_address.toLowerCase()===qp?$p:g.token_address})),await this.enrichTokenPrices(m.result,i),m.result=m.result.filter(g=>g.usd_value==null||g.usd_value>=Fp)),{success:!0,data:m}}catch(u){if(l=u instanceof Error?u.message:"Unknown error",u instanceof L&&u.status===400)break;c<I&&await Q(z)}return{success:!1,error:l}}async getTokenMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token address is required"};let o=ee(n),s="Unknown error",a=await this.pantograph.getTokenMetadata(t,o);if(a)return{success:!0,data:a};for(let i=1;i<=I;i++)try{let[l,c]=await Promise.allSettled([x.get(`${this.baseUrl}/api/moralis/proxy/erc20/metadata?${X({chain:o,addresses:[t]})}`),x.get(`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/price?${X({chain:o,include:"percent_change"})}`)]),u=null;if(l.status==="fulfilled"&&l.value.ok){let p=l.value.data;u=(Array.isArray(p)?p:Array.isArray(p?.data)?p.data:[])[0]??null}if(!u){s="Token metadata not found",i<I&&await Q(z);continue}let d=null;if(c.status==="fulfilled"&&c.value.ok){let p=c.value.data;d=p?.data??p}return{success:!0,data:{...u,...d?.usd_price?{usd_price:d.usd_price}:{},...d?.usd_price_change_percentage_24h?{usd_price_change_percentage_24h:d.usd_price_change_percentage_24h}:{}}}}catch(l){if(s=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<I&&await Q(z)}return{success:!1,error:s}}async getWalletNFTs(e){let{address:t,chain:n,limit:o=100,excludeSpam:s=!1,cursor:a,tokenAddresses:i,includePrices:l,format:c="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};let u=ee(n),d=[],p=a,m,g;for(let h=0;h<Bp;h++){let f=await this.fetchWalletNftsPage({address:t,moralisChain:u,limit:o,excludeSpam:s,cursor:p,tokenAddresses:i,includePrices:l,format:c});if(!f.success){if(d.length===0)return f;break}let y=f.data;if(!y)break;let{result:b,cursor:k,page:w,page_size:v}=y;if(Array.isArray(b)&&d.push(...b),m=w,g=v,p=typeof k=="string"&&k.trim()?k:void 0,!p)break}return{success:!0,data:{result:d,cursor:p,page:m,page_size:g}}}async fetchWalletNftsPage(e){let{address:t,moralisChain:n,limit:o,excludeSpam:s,cursor:a,tokenAddresses:i,includePrices:l,format:c}=e,u="Unknown error";for(let d=1;d<=I;d++)try{let p={chain:n,format:c,limit:o,exclude_spam:s,media_items:!0,normalizeMetadata:!0};a&&(p.cursor=a),l&&(p.include_prices=!0),i&&i.length>0&&(p.token_addresses=i);let m=X(p),g=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft?${m}`,h=await x.get(g);if(!h.ok)throw new L(h.status,U(h));let f=h.data;return{success:!0,data:f?.data??f}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof L&&p.status===400)break;d<I&&await Q(z)}return{success:!1,error:u}}async getWalletNftCollections(e){let{address:t,chain:n,limit:o=100,excludeSpam:s=!0,cursor:a}=e;if(!t)return{success:!1,error:"Address is required"};let i=ee(n),l="Unknown error";for(let c=1;c<=I;c++)try{let u={chain:i,limit:o,exclude_spam:s};a&&(u.cursor=a);let d=X(u),p=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/collections?${d}`,m=await x.get(p);if(!m.ok)throw new L(m.status,U(m));let g=m.data;return{success:!0,data:g?.data??g}}catch(u){if(l=u instanceof Error?u.message:"Unknown error",u instanceof L&&u.status===400)break;c<I&&await Q(z)}return{success:!1,error:l}}async getNftMetadata(e){let{address:t,tokenId:n,chain:o,format:s="decimal",normalizeMetadata:a=!0,mediaItems:i=!0,include:l}=e;if(!t)return{success:!1,error:"NFT contract address is required"};if(n==null||n==="")return{success:!1,error:"Token ID is required"};if(!E(t))return{success:!1,error:"NFT metadata lookup by token ID is only supported on EVM chains"};let c=ee(o),u="Unknown error";for(let d=1;d<=I;d++)try{let p={chain:c,format:s,normalizeMetadata:a,media_items:i};l&&(p.include=l);let m=X(p),g=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/${encodeURIComponent(n)}?${m}`,h=await x.get(g);if(!h.ok)throw new L(h.status,U(h));let f=h.data;return{success:!0,data:f?.data??f}}catch(p){if(u=p instanceof Error?p.message:"Unknown error",p instanceof L&&p.status===400)break;d<I&&await Q(z)}return{success:!1,error:u}}async getNftContractMetadata(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};let o=ee(n),s="Unknown error";for(let a=1;a<=I;a++)try{let i=X({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/nft/${encodeURIComponent(t)}/metadata?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,U(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<I&&await Q(z)}return{success:!1,error:s}}async getWalletHistory(e){let{address:t,chain:n,limit:o=25,fromDate:s,toDate:a,fromBlock:i,toBlock:l,cursor:c,order:u="DESC",includeInternalTransactions:d,nftMetadata:p}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"Wallet history is only supported for EVM addresses"};let m=ee(n),g=Math.max(1,Math.min(100,Math.floor(o))),h="Unknown error";for(let f=1;f<=I;f++)try{let y={chain:m,limit:g,order:u};s&&(y.from_date=s),a&&(y.to_date=a),i!=null&&(y.from_block=i),l!=null&&(y.to_block=l),c&&(y.cursor=c),d!=null&&(y.include_internal_transactions=d),p!=null&&(y.nft_metadata=p);let b=X(y),k=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/history?${b}`,w=await x.get(k);if(!w.ok)throw new L(w.status,U(w));let v=w.data;return{success:!0,data:v?.data??v}}catch(y){if(h=y instanceof Error?y.message:"Unknown error",y instanceof L&&y.status===400)break;f<I&&await Q(z)}return{success:!1,error:h}}async getWalletTokenTransfers(e){let{address:t,chain:n,contractAddresses:o,limit:s=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:u,order:d="DESC"}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"ERC-20 transfers are only supported for EVM addresses"};let p=ee(n),m=Math.max(1,Math.min(100,Math.floor(s))),g="Unknown error";for(let h=1;h<=I;h++)try{let f={chain:p,limit:m,order:d};a&&(f.from_date=a),i&&(f.to_date=i),l!=null&&(f.from_block=l),c!=null&&(f.to_block=c),u&&(f.cursor=u),o?.length&&(f.contract_addresses=o);let y=X(f),b=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/erc20/transfers?${y}`,k=await x.get(b);if(!k.ok)throw new L(k.status,U(k));let w=k.data;return{success:!0,data:w?.data??w}}catch(f){if(g=f instanceof Error?f.message:"Unknown error",f instanceof L&&f.status===400)break;h<I&&await Q(z)}return{success:!1,error:g}}async getWalletNftTransfers(e){let{address:t,chain:n,contractAddresses:o,limit:s=25,fromDate:a,toDate:i,fromBlock:l,toBlock:c,cursor:u,order:d="DESC",includePrices:p,format:m="decimal"}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"NFT transfers are only supported for EVM addresses"};let g=ee(n),h=Math.max(1,Math.min(100,Math.floor(s))),f="Unknown error";for(let y=1;y<=I;y++)try{let b={chain:g,limit:h,order:d,format:m};a&&(b.from_date=a),i&&(b.to_date=i),l!=null&&(b.from_block=l),c!=null&&(b.to_block=c),u&&(b.cursor=u),o?.length&&(b.contract_addresses=o),p!=null&&(b.include_prices=p);let k=X(b),w=`${this.baseUrl}/api/moralis/proxy/${encodeURIComponent(t)}/nft/transfers?${k}`,v=await x.get(w);if(!v.ok)throw new L(v.status,U(v));let T=v.data;return{success:!0,data:T?.data??T}}catch(b){if(f=b instanceof Error?b.message:"Unknown error",b instanceof L&&b.status===400)break;y<I&&await Q(z)}return{success:!1,error:f}}async getTokenHolders(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Contract address is required"};if(!E(t))return{success:!1,error:"Token holders is only supported for EVM contract addresses"};let o=ee(n),s="Unknown error";for(let a=1;a<=I;a++)try{let i=X({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/erc20/${encodeURIComponent(t)}/holders?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,U(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<I&&await Q(z)}return{success:!1,error:s}}async getWalletPnlSummary(e){let{address:t,chain:n,days:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"Wallet PnL summary is only supported for EVM addresses"};let s=ee(n),a="Unknown error";for(let i=1;i<=I;i++)try{let l={chain:s};o&&(l.days=o);let c=X(l),u=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability/summary?${c}`,d=await x.get(u);if(!d.ok)throw new L(d.status,U(d));let p=d.data;return{success:!0,data:p?.data??p}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<I&&await Q(z)}return{success:!1,error:a}}async getWalletPnl(e){let{address:t,chain:n,days:o,tokenAddresses:s}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"Wallet PnL is only supported for EVM addresses"};let a=ee(n),i="Unknown error";for(let l=1;l<=I;l++)try{let c={chain:a};o&&(c.days=o),s&&s.length>0&&(c.token_addresses=s.slice(0,25));let u=X(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/profitability?${u}`,p=await x.get(d);if(!p.ok)throw new L(p.status,U(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<I&&await Q(z)}return{success:!1,error:i}}async getTransactionByHash(e){let{transactionHash:t,chain:n}=e;if(!t)return{success:!1,error:"Transaction hash is required"};let o=ee(n),s="Unknown error";for(let a=1;a<=I;a++)try{let i=X({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/transaction/${encodeURIComponent(t)}/verbose?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,U(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<I&&await Q(z)}return{success:!1,error:s}}async getWalletApprovals(e){let{address:t,chain:n,limit:o,cursor:s}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"Wallet approvals are only supported for EVM addresses"};let a=ee(n),i="Unknown error";for(let l=1;l<=I;l++)try{let c={chain:a};o!=null&&(c.limit=o),s&&(c.cursor=s);let u=X(c),d=`${this.baseUrl}/api/moralis/proxy/wallets/${encodeURIComponent(t)}/approvals?${u}`,p=await x.get(d);if(!p.ok)throw new L(p.status,U(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<I&&await Q(z)}return{success:!1,error:i}}async getWalletDefiSummary(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"Wallet DeFi summary is only supported for EVM addresses"};let o=ee(n),s="Unknown error";for(let a=1;a<=I;a++)try{let i=X({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/summary?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,U(c));let u=c.data,d=u?.data??u;return{success:!0,data:Hp(d)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<I&&await Q(z)}return{success:!1,error:s}}async getWalletDefiPositions(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Address is required"};if(!E(t))return{success:!1,error:"Wallet DeFi positions are only supported for EVM addresses"};let o=ee(n),s="Unknown error";for(let a=1;a<=I;a++)try{let i=X({chains:o}),l=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/positions?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,U(c));let u=c.data,d=u?.data??u;return{success:!0,data:Vp(d)}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<I&&await Q(z)}return{success:!1,error:s}}async getWalletDefiProtocolPositions(e){let{address:t,protocol:n,chain:o}=e;if(!t)return{success:!1,error:"Address is required"};if(!n)return{success:!1,error:"Protocol identifier is required"};if(!E(t))return{success:!1,error:"Wallet DeFi protocol positions are only supported for EVM addresses"};let s=ee(o),a="Unknown error";for(let i=1;i<=I;i++)try{let l=X({chains:s}),c=`${this.v1BaseUrl}/api/moralis-v1/proxy/wallets/${encodeURIComponent(t)}/defi/${encodeURIComponent(n)}/positions?${l}`,u=await x.get(c);if(!u.ok)throw new L(u.status,U(u));let m=u.data.result;return{success:!0,data:{protocol_id:m.protocolId,protocol_name:m.protocolName,protocol_url:m.protocolUrl??"",protocol_logo:m.protocolLogo??"",total_usd_value:m.totalUsd??0,total_unclaimed_usd_value:m.totalUnclaimedUsd??null,positions:m.positions.map(h=>({label:h.label,address:h.address,balance_usd:h.balanceUsd??0,total_unclaimed_usd_value:h.unclaimedUsd??0,position_details:h.details,tokens:h.tokens.map(f=>({token_type:f.tokenType,address:f.address,contract_address:f.address,name:f.name??"",symbol:f.symbol??"",decimals:f.decimals??18,logo:f.logo,balance:f.balance??"0",balance_formatted:f.balanceFormatted??"0",usd_price:f.usdPrice,usd_value:f.usdValue}))}))}}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<I&&await Q(z)}return{success:!1,error:a}}async searchTokensByKey(e){return this.pantograph.searchTokensByKey(e)}async getTokenAnalytics(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!E(t))return{success:!1,error:"Token analytics is only supported for EVM contract addresses"};let o=ee(n),s="Unknown error";for(let a=1;a<=I;a++)try{let i=X({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/analytics?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,U(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<I&&await Q(z)}return{success:!1,error:s}}async getTokenScore(e){let{address:t,chain:n}=e;if(!t)return{success:!1,error:"Token contract address is required"};if(!E(t))return{success:!1,error:"Token score is only supported for EVM contract addresses"};let o=ee(n),s="Unknown error";for(let a=1;a<=I;a++)try{let i=X({chain:o}),l=`${this.baseUrl}/api/moralis/proxy/tokens/${encodeURIComponent(t)}/score?${i}`,c=await x.get(l);if(!c.ok)throw new L(c.status,U(c));let u=c.data;return{success:!0,data:u?.data??u}}catch(i){if(s=i instanceof Error?i.message:"Unknown error",i instanceof L&&i.status===400)break;a<I&&await Q(z)}return{success:!1,error:s}}async getTrendingTokens(e){let t=e?.chain,n=e?.limit,o="Unknown error";for(let s=1;s<=I;s++)try{let a={};t&&(a.chain=ee(t)),n!=null&&(a.limit=n);let i=X(a),l=`${this.baseUrl}/api/moralis/proxy/tokens/trending${i?`?${i}`:""}`,c=await x.get(l);if(!c.ok)throw new L(c.status,U(c));let u=c.data,d=u?.data??u;return{success:!0,data:xi(d)}}catch(a){if(o=a instanceof Error?a.message:"Unknown error",a instanceof L&&a.status===400)break;s<I&&await Q(z)}return{success:!1,error:o}}async getTopGainers(e){let{chain:t,timeFrame:n,minMarketCap:o,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=I;i++)try{let l={};t&&(l.chain=ee(t)),n&&(l.time_frame=n),o!=null&&(l.min_market_cap=o),s!=null&&(l.security_score=s);let c=X(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-gainers${c?`?${c}`:""}`,d=await x.get(u);if(!d.ok)throw new L(d.status,U(d));let p=d.data,m=p?.data??p;return{success:!0,data:xi(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<I&&await Q(z)}return{success:!1,error:a}}async getTopLosers(e){let{chain:t,timeFrame:n,minMarketCap:o,securityScore:s}=e??{},a="Unknown error";for(let i=1;i<=I;i++)try{let l={};t&&(l.chain=ee(t)),n&&(l.time_frame=n),o!=null&&(l.min_market_cap=o),s!=null&&(l.security_score=s);let c=X(l),u=`${this.baseUrl}/api/moralis/proxy/discovery/tokens/top-losers${c?`?${c}`:""}`,d=await x.get(u);if(!d.ok)throw new L(d.status,U(d));let p=d.data,m=p?.data??p;return{success:!0,data:xi(m)}}catch(l){if(a=l instanceof Error?l.message:"Unknown error",l instanceof L&&l.status===400)break;i<I&&await Q(z)}return{success:!1,error:a}}async enrichTokenPrices(e,t){return this.pantograph.enrichTokenPrices(e,t)}};var ar=class extends S{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 re(e?.llm??{})}async run(e,t){let n=e.keyword||"",o=e.prompt||"",s=t?.walletAddress||void 0;if(!n)return{error:"Missing required parameter: keyword"};let a;try{a=ce(e.chain,t)}catch(i){if(i instanceof Bt)return await this.researchTokenChainAgnostic(n,o,s);throw i}return await this.searchToken(n,a,o,s)}async researchTokenChainAgnostic(e,t,n){let o=[n?`User's connected wallet address: ${n}`:null,"The user's connected chain is not one this app supports on-chain, so answer using web research only \u2014 do not assume a specific chain; identify the token across whichever chain(s) it actually exists on."].filter(Boolean).join(`
@@ -22,7 +22,7 @@ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-ce
22
22
  netApyExcludingRewards
23
23
  historicalState { avgNetApy(options: $options) { x y } }
24
24
  }
25
- }`,Pr=class{underlyingCall(e){return he(e.contract,tt,"asset")}liveRateCall(e,t){return null}followUpRateCall(e,t){return null}decodeSize(e,t){if(!Number.isInteger(t.decimals)||t.decimals<0)return null;let n=le(e);return n===null?null:qt(n,t.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,t){return this.balanceIsUnderlying?null:he(e.contract,tt,"convertToAssets",[t])}},Go=class extends Pr{type="spark";balanceIsUnderlying=!1;sizeCall(e){return he(e.contract,tt,"totalAssets")}fetchApy(e,t,n){return Mi(e,t,n)}},Ei=class extends Go{type="spark";liveRateCall(e){return he(e.contract,Ar,"rateProvider")}followUpRateCall(e,t){let n=G(t);return n===null?null:he(n,fn,"getAPR")}decodeLiveRate(e){let t=le(e);return t===null?null:jo(Math.expm1(Number(t)/Vs))}},Ni=class extends Go{type="spark-ethereum";liveRateCall(e){return he(e.contract,Ar,"vsr")}decodeLiveRate(e){let t=le(e);if(t===null)return null;let n=Number(t)/Vs;return n>0?jo(Math.expm1(Math.log(n)*Dc)):null}},Ui=class extends Pr{type="spark-l2-susds";balanceIsUnderlying=!1;underlyingCall(){return null}sizeCall(e){return he(e.token,W,"totalSupply")}liveRateCall(e){return he(e.contract,fn,"getAPR")}decodeLiveRate(e){let t=le(e);return t===null?null:jo(Math.expm1(Number(t)/Vs))}convertToAssetsCall(e){return he(e.contract,fn,"getConversionRate")}fetchApy(e,t,n){return Mi(e,t,n)}};function Sr(r,e,t,n){if(e<=0n||!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0)return null;let o=r*e/sm,s=n-t;return s===0?o:s>0?o*10n**BigInt(s):o/10n**BigInt(-s)}var Ii=class extends Pr{type="aave-v3";balanceIsUnderlying=!0;underlyingCall(e){return he(e.token,Tr,"UNDERLYING_ASSET_ADDRESS")}sizeCall(e){return he(e.token,W,"totalSupply")}liveRateCall(e,t){return he(e.contract,Hs,"getReserveData",[t.address])}decodeLiveRate(e){if(!e)return null;let t;try{let[n]=be(Hs[0].outputs,e);t=n.currentLiquidityRate}catch{return null}return jo(Number(t)/Vs)}async fetchApy(e,t,n,o){let s=await x.post(n.aaveApiUrl,{operationName:"SupplyAPYHistory",query:im,variables:{request:{chainId:t.chainId,market:e.contract,underlyingToken:o.address,window:"LAST_WEEK"}}});if(!s.ok)throw new Error(U(s));return{samples:(s.data?.data?.value||[]).map(a=>({timeMs:Date.parse(a?.date??""),fraction:Number(a?.avgRate?.value)})),current:null}}},Li=class extends Pr{type="compound-v3";balanceIsUnderlying=!0;underlyingCall(e){return he(e.contract,gn,"baseToken")}sizeCall(e){return he(e.token,W,"totalSupply")}liveRateCall(e){return he(e.contract,gn,"getUtilization")}followUpRateCall(e,t){let n=le(t);return n===null?null:he(e.contract,gn,"getSupplyRate",[n])}decodeLiveRate(e){let t=le(e);return t===null?null:jo(Number(t)/1e18*Dc)}fetchApy(e,t,n){return Mi(e,t,n)}},Di=class extends Go{type="morpho-v2";async fetchApy(e,t,n){let o=pm(Date.now()),s=await x.post(n.morphoApiUrl,{operationName:"VaultV2ByAddress",query:lm,variables:{address:e.contract,chainId:t.chainId,options:{startTimestamp:Math.floor(o/1e3)-(Oi-1)*86400,endTimestamp:Math.floor(o/1e3)-86400}}});if(!s.ok)throw new Error(U(s));let a=s.data?.data?.vaultV2ByAddress,i=Number(a?.netApyExcludingRewards);return{samples:(a?.historicalState?.avgNetApy||[]).map(l=>({timeMs:Number(l?.x)*1e3,fraction:Number(l?.y)})),current:Number.isFinite(i)?i:null}}};async function Mi(r,e,t){let n=`${t.coinPoolBaseUrl}/supply/rates/history?chainId=${e.chainId}&token=${r.token}`,o=await x.get(n);if(!o.ok)throw new Error(U(o));return{samples:(o.data?.data||[]).map(s=>({timeMs:Date.parse(s?.date??""),fraction:Number(s?.rate)})),current:null}}var Oc={"aave-v3":new Ii,"compound-v3":new Li,spark:new Ei,"spark-ethereum":new Ni,"spark-l2-susds":new Ui,"morpho-v2":new Di},cm=Oc.spark;function yn(r){return Oc[r.type]??cm}var um={"aave-v3":"Aave V3","compound-v3":"Compound V3",spark:"Spark","spark-ethereum":"Spark","spark-l2-susds":"Spark","morpho-v2":"Morpho V2"};function Ye(r){return um[r]??null}var dm={"aave-v3":"https://app.aave.com","compound-v3":"https://app.compound.finance",spark:"https://app.spark.fi","spark-ethereum":"https://app.spark.fi","spark-l2-susds":"https://app.spark.fi","morpho-v2":"https://app.morpho.org"};function Ws(r){return dm[r]??null}function qt(r,e){return Number(r)/10**e}function Ko(r){return new Date(r).toISOString().slice(0,10)}function pm(r){return Date.parse(`${Ko(r)}T00:00:00.000Z`)}var mm=6e4,Fi=new Map;async function zo(r,e){let t=ft(e),n=t?parseInt(t,16):NaN;if(!t||!Number.isFinite(n))return[];let o=`${r}|${t}`,s=Fi.get(o);if(s&&Date.now()-s.at<mm)return s.markets;let a=hm(r,t,n),i=a.then(l=>l.markets);return Fi.set(o,{at:Date.now(),markets:i}),a.then(l=>{l.answered||Fi.delete(o)}),i}async function Ys(r,e){return(await zo(r,e)).length>0}async function hm(r,e,t){try{let n=`${r}/supply/v2?chainId=${t}&limit=100&page=1`;M("catalog: GET",n);let o=await x.get(n);if(!o.ok){let a=o.status>=400&&o.status<500;return M(a?"catalog: chain not served":"catalog: FAILED",{chain:e,status:o.status,message:U(o)}),{markets:[],answered:a}}let s=(o.data?.data?.items||[]).flatMap(a=>{let i=gm(a,e);return i?[i]:[]});return M("catalog: got markets",{chain:e,rawItems:o.data?.data?.items?.length??0,usable:s.length,tokens:s.map(a=>a.token)}),{markets:s,answered:!0}}catch(n){return M("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:e,message:n?.message}),{markets:[],answered:!1}}}function Mc(r,e){let t=e.trim().toLowerCase();if(!t)return[];if(E(t))return r.filter(o=>o.contract===t||o.token===t);let n=r.filter(o=>o.name.trim().toLowerCase()===t);return n.length>0?n:r.filter(o=>{let s=o.name.trim().toLowerCase(),a=o.protocol.trim().toLowerCase();return s.includes(t)||t.includes(s)||a.includes(t)||t.includes(a)})}function gm(r,e){if(r?.isDeleted===!0)return null;let t=typeof r?.contract=="string"?r.contract.toLowerCase():"";if(!E(t))return null;let n=typeof r?.token=="string"&&E(r.token)?r.token.toLowerCase():t,o=Number(r?.rating?.balanceScore),s=r?.type?.trim()||"unknown";return{chain:e,name:r?.name?.trim()||"USDC lending market",protocol:r?.protocolId?.name?.trim()||"Unknown",protocolLabel:Ye(s),protocolUrl:r?.protocolId?.domain?.trim()||null,type:s,contract:t,token:n,platformScore:Number.isFinite(o)?o:null}}function Bi(){return Se()}async function Gs(r){let e=Bi(),t=await Promise.all(e.map(n=>Ys(r,n)));return e.filter((n,o)=>t[o])}async function js(r,e){let t=q(e);return t?Ys(r,t):!1}async function Fc(r,e){let t=e.map(s=>q(s)).filter(s=>!!s),n=[...new Set(t)],o=await Promise.all(n.map(s=>Ys(r,s)));return n.filter((s,a)=>o[a])}var fm={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function Ks(r){let e=ft(r);return e?fm[e]??null:null}function Bc(r){return["susds","usds","rateProvider"].map(e=>({target:r,callData:F({abi:_i,functionName:e})}))}var qc=3,ym={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function qi(r){let e=ft(r),t=e?ym[e]:void 0;return t?{target:t,callData:F({abi:fn,functionName:"getConversionRate"})}:null}function xr(r){return Ws(r)}var $c=5;async function Hc(r,e,t){let n=e.map(y=>E(y)?y.toLowerCase():null);if(n.every(y=>y===null))return M("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let o=Ks(r),s;try{M("discovery: probing 5 accessors per token",{chain:r,tokens:n,psm:o}),s=await Pe(r,[...n.flatMap(y=>y?bm(y):[]),...o?Bc(o):[]])}catch(y){return M("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:r,message:y?.message}),e.map(()=>null)}let a=o?s.slice(s.length-qc):[],i=G(a[0])?.toLowerCase()??null,l=G(a[1]),c=G(a[2]),u=i&&l&&c?{susds:i,usds:l,oracle:c}:null;o&&M("discovery: PSM3 lookup",{psm:o,susds:i,usds:l,oracle:c});let d=0,p=n.map(y=>{if(!y)return null;let b=s.slice(d,d+$c);return d+=$c,M("discovery: probe answers",{token:y,"POOL()":G(b[0]),"UNDERLYING_ASSET_ADDRESS()":G(b[1]),"baseToken()":G(b[2]),"asset()":G(b[3]),"vsr()":le(b[4])?.toString()??null}),{token:y,slice:b}}),m=new Set;for(let y of p){if(!y)continue;let b=G(y.slice[0]);b&&G(y.slice[1])&&m.add(b.toLowerCase())}let g=await wm(r,[...m]);m.size>0&&M("discovery: Aave pool authentication",{claimed:[...m],genuine:[...g]});let h=p.flatMap(y=>y?G(y.slice[0])&&G(y.slice[1])||G(y.slice[2])?[]:G(y.slice[3])?[y.token]:[]:[]),f=await km(r,[...new Set(h)],t);return h.length>0&&M("discovery: Morpho vault lookup",{asked:[...new Set(h)],recognised:[...f.keys()]}),p.map(y=>{if(!y)return null;let{token:b,slice:k}=y,w={chain:r,protocolUrl:null,token:b,platformScore:null};if(u&&b===u.susds)return M("discovery: classified",{token:b,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:u.oracle}),{...w,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:Ye("spark-l2-susds"),protocolUrl:xr("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let v=G(k[0]);if(v&&G(k[1])){let T=g.has(v.toLowerCase());return M("discovery: classified",{token:b,as:T?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:v}),T?{...w,name:"Aave v3",protocol:"AAVE",protocolLabel:Ye("aave-v3"),protocolUrl:xr("aave-v3"),type:"aave-v3",contract:v}:null}if(G(k[2]))return M("discovery: classified",{token:b,as:"compound-v3"}),{...w,name:"Compound v3",protocol:"COMPOUND",protocolLabel:Ye("compound-v3"),protocolUrl:xr("compound-v3"),type:"compound-v3",contract:b};if(G(k[3])){if(f.has(b)){M("discovery: classified",{token:b,as:"morpho-v2"});let C=f.get(b)||"Morpho V2";return{...w,name:C,protocol:"MORPHO",protocolLabel:Ye("morpho-v2"),protocolUrl:xr("morpho-v2"),type:"morpho-v2",contract:b}}let P=le(k[4])!==null;return M("discovery: classified",{token:b,as:P?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),P?{...w,name:"Spark",protocol:"SPARK",protocolLabel:Ye("spark-ethereum"),protocolUrl:xr("spark-ethereum"),type:"spark-ethereum",contract:b}:{...w,name:"Spark",protocol:"SPARK",protocolLabel:Ye("spark"),protocolUrl:xr("spark"),type:"spark",contract:b}}return M("discovery: classified",{token:b,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function bm(r){return[{target:r,callData:F({abi:Tr,functionName:"POOL"})},{target:r,callData:F({abi:Tr,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:r,callData:F({abi:gn,functionName:"baseToken"})},{target:r,callData:F({abi:tt,functionName:"asset"})},{target:r,callData:F({abi:Ar,functionName:"vsr"})}]}async function wm(r,e){if(e.length===0)return new Set;try{let t=await Pe(r,e.map(n=>({target:n,callData:F({abi:Ri,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((n,o)=>G(t[o])!==null))}catch{return new Set}}async function km(r,e,t){let n=parseInt(r,16);if(e.length===0||!Number.isFinite(n))return new Map;let o=await Promise.all(e.map(async s=>{try{let a=await x.post(t,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:s,c:n}}),i=a.ok?a.data?.data?.vaultV2ByAddress:null;return i?[s,i.name?.trim()||""]:null}catch{return null}}));return new Map(o.filter(s=>s!==null))}var vm={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},Tm={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"},Am={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},Pm={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function zs(r){let e=Um(r.chain);return(e===null?null:Sm(r,e))??Ws(r.type)??Nm(r,e)}function Sm(r,e){switch(r.type){case"morpho-v2":{let t=vm[e];if(!t||!r.contract)return null;let n=`https://app.morpho.org/${t}/vault/${$i(r.contract)}`,o=Rm(r.name);return o?`${n}/${o}`:n}case"aave-v3":{let t=Tm[e],n=xm(r);return!t||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${$i(n)}&marketName=${t}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let t=Am[e],n=Em(r);return!t||!n?null:`https://app.spark.fi/savings/${t}/${n}`}case"compound-v3":{let t=Pm[e],n=_m(r);return!t||!n?null:`https://app.compound.finance/?market=${n}-${t}`}default:return null}}function xm(r){let e=r.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var Cm=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Rm(r){let e=r?.trim().toLowerCase()||"";return!e||Cm.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function _m(r){let e=r.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function Em(r){let e=`${r.name||""} ${r.token||""}`.toLowerCase();for(let n of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(e.includes(n))return n;let t=r.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]{2,11}$/.test(t)?r.type==="spark-ethereum"?`sp${t}`:`s${t}`:null}function Nm(r,e){let t=r.protocolUrl?.trim();if(!t)return null;let n=/^https?:\/\//i.test(t)?t:`https://${t.replace(/^\/+/,"")}`;try{let o=new URL(n);return e!==null&&o.searchParams.set("chainId",String(e)),r.contract&&o.searchParams.set("contract",$i(r.contract)),o.toString()}catch{return n}}function $i(r){let e=r.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function Um(r){let e=r?.trim();if(!e)return null;let t=/^0x/i.test(e)?Number.parseInt(e,16):Number(e);return Number.isFinite(t)&&t>0?t:null}var Im=8;function Lm(r,e,t){if(r.market.type!=="spark-l2-susds")return le(e);let n=le(e);return n===null||r.tokenDecimals===null?null:Sr(r.rawBalance,n,r.tokenDecimals,t)}var Xs=class{constructor(e){this.endpoints=e}endpoints;apyLimiter=new Hi(Im);pantograph=new se;async describe(e,t,n){if(n.length===0)return[];M("describe: START",{chain:e,count:n.length,types:n.map(i=>i.type)});let o=await this.resolveAssets(e,n);M("describe: assets resolved",o);let[s,a]=await Promise.all([this.readMarketState(e,n,o),Promise.all(n.map((i,l)=>this.apyLimiter.run(()=>this.fetchApy(i,t,o[l]))))]);return M("describe: on-chain state",s),M("describe: APY fetched",a.map((i,l)=>({type:n[l].type,rawSamples:i.samples.length,sourceCurrent:i.current}))),n.map((i,l)=>{let{totalSuppliedUsdc:c,liveApyFraction:u}=s[l],d=Dm(a[l].samples,u??a[l].current);return M("describe: summarised",{market:i.name,type:i.type,liveFrom:u!==null?"on-chain":a[l].current!==null?"api":"none",rawSamples:a[l].samples.length,historyPoints:d.history.length,currentApyPercent:d.currentApyPercent,avgApyPercent:d.avgApyPercent,apyChangePercent:d.apyChangePercent,totalSuppliedUsdc:c,asset:o[l]?.symbol}),{...i,protocolUrl:zs({...i,asset:o[l]}),asset:o[l],totalSuppliedUsdc:c===null?null:$t(c,2),avgApyPercent:d.avgApyPercent,currentApyPercent:d.currentApyPercent,apyChangePercent:d.apyChangePercent,apyHistory:d.history}})}async readBalances(e,t,n){let o=F({abi:W,functionName:"balanceOf",args:[t]}),s=F({abi:W,functionName:"decimals"}),a=n.flatMap(l=>[{target:l.token,callData:o},{target:l.token,callData:s}]),i=await Pe(e,a);return n.flatMap((l,c)=>{let u=le(i[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:En(i[c*2+1])}]})}async convertToUnderlying(e,t,n){let o=[],s=t.map(i=>{let l=yn(i.market).convertToAssetsCall(i.market,i.rawBalance);return l?(o.push(l),o.length-1):-1}),a=await Pe(e,o);return t.map((i,l)=>{let c=n[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(s[l]<0)return qt(i.rawBalance,c);let u=Lm(i,a[s[l]],c);return u===null?qt(i.rawBalance,i.tokenDecimals??c):qt(u,c)})}async resolveAssets(e,t){let n={address:hn,decimals:NaN,symbol:null,logo:null},o=[],s=t.map(u=>{let d=yn(u).underlyingCall(u);return d?(o.push(d),o.length-1):-1}),a;try{let u=o.length>0?await Pe(e,o):[];a=s.map(d=>d<0?null:G(u[d]))}catch{a=t.map(()=>null)}a=a.map((u,d)=>u??t[d]?.assetAddress??null);let i=[...new Set(a.filter(u=>!!u).map(u=>u.toLowerCase()))],[l,c]=await Promise.all([this.readAssetMetadata(e,i),this.fetchAssetLogos(e,i)]);return a.map(u=>{if(!u)return n;let d=u.toLowerCase(),p=l.get(d),m=c.get(d)??null;return p?.decimals!==null&&p?.decimals!==void 0?{address:u,decimals:p.decimals,symbol:p.symbol??null,logo:m}:{address:u,decimals:NaN,symbol:null,logo:m}})}async readAssetMetadata(e,t){let n=new Map;if(t.length===0)return n;let o=F({abi:W,functionName:"decimals"}),s=F({abi:W,functionName:"symbol"});try{let a=await Pe(e,t.flatMap(i=>[{target:i,callData:o},{target:i,callData:s}]));t.forEach((i,l)=>{n.set(i,{decimals:En(a[l*2]),symbol:No(a[l*2+1])})})}catch{}return n}async fetchAssetLogos(e,t){let n=new Map;if(t.length===0)return n;try{let o=await this.pantograph.getTokensMetadata(t,e);for(let[s,a]of Object.entries(o)){let i=a.icon_image||a.logo||a.logoURI;i&&n.set(s.toLowerCase(),i)}}catch{}return M("resolveAssets: logos",{chain:e,requested:t.length,found:n.size}),n}async readMarketState(e,t,n){let o=[],s=t.map((u,d)=>{let p=yn(u),m=n[d],g={market:u,protocol:p,asset:m,size:o.length,rate:-1};o.push(p.sizeCall(u,m));let h=p.liveRateCall(u,m);return h&&(g.rate=o.length,o.push(h)),g}),a=await Pe(e,o),i=[],l=s.map(u=>{if(u.rate<0)return-1;let d=u.protocol.followUpRateCall(u.market,a[u.rate]);return d?(i.push(d),i.length-1):-1}),c=i.length>0?await Pe(e,i):[];return s.map((u,d)=>{let p=u.rate<0?null:a[u.rate],m=l[d]>=0?c[l[d]]:p;return{totalSuppliedUsdc:u.protocol.decodeSize(a[u.size],u.asset),liveApyFraction:m===null?null:u.protocol.decodeLiveRate(m)}})}async fetchApy(e,t,n){try{M("fetchApy: requesting",{market:e.name,type:e.type,asset:n?.symbol});let o=await yn(e).fetchApy(e,t,this.endpoints,n);return M("fetchApy: got",{market:e.name,samples:o.samples.length,current:o.current}),o}catch(o){return M("fetchApy: FAILED \u2014 market listed without APY",{market:e.name,type:e.type,message:o?.message}),{samples:[],current:null}}}},Hi=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 Dm(r,e){let t=Ko(Date.now()),n=new Map,o=null;for(let u of r){if(!Number.isFinite(u.timeMs)||!Number.isFinite(u.fraction)||u.fraction<0||((!o||u.timeMs>o.timeMs)&&(o=u),!Om(u.timeMs)))continue;let d=Ko(u.timeMs);d>=t||n.set(d,u.fraction)}let s=[...n.entries()].sort((u,d)=>u[0]<d[0]?-1:1).slice(-Oi).map(([u,d])=>({date:u,apyPercent:$t(d*100,2)})),a=e??(o&&Ko(o.timeMs)===t?o.fraction:null),i=a===null?null:$t(a*100,2);if(i!==null&&s.push({date:t,apyPercent:i}),s.length===0)return{history:s,avgApyPercent:null,currentApyPercent:null,apyChangePercent:null};let l=s.reduce((u,d)=>u+d.apyPercent,0),c=s[s.length-1].apyPercent;return{history:s,avgApyPercent:$t(l/s.length,2),currentApyPercent:i,apyChangePercent:s.length>=2?$t(c-s[s.length-2].apyPercent,2):null}}function $t(r,e){let t=10**e;return Math.round(r*t)/t}function Om(r){let e=new Date(r);return e.getUTCHours()===0&&e.getUTCMinutes()===0&&e.getUTCSeconds()===0}var Mm=.01;function Fm(r,e){if(typeof e!="string"||!e.trim())return;let t=e.trim(),n=qo();n[r]!==t&&ln({...n,[r]:t})}var Cr=class{constructor(e,t,n){this.coinPoolBaseUrl=e;this.endpoints=t;this.describer=n}coinPoolBaseUrl;endpoints;describer;async describeReceiptTokens(e,t,n){let o=Date.now();M("describeReceiptTokens: START",{chain:e,tokens:t,hasRpcUrl:!!n});let s=ft(e);s&&Fm(s,n);let a=s?Wo(s):null,i=[...new Set(t.filter(E).map(p=>p.toLowerCase()))];if(M("describeReceiptTokens: chain resolved",{hex:s,hasChainInfo:!!a,wanted:i}),!s||!a||i.length===0)return M("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:s,hasChainInfo:!!a,wantedCount:i.length}),new Map;M("describeReceiptTokens: on-chain discovery for",i);let l=await Hc(s,i,this.endpoints.morphoApiUrl),u=[...new Map(i.flatMap((p,m)=>{let g=l[m];return M("describeReceiptTokens: discovery result",{token:p,found:!!g,protocol:g?.protocol,type:g?.type,contract:g?.contract}),g?[[p,g]]:[]})).entries()];if(u.length===0)return M("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-o}),new Map;M("describeReceiptTokens: describing markets",{count:u.length,markets:u.map(([p,m])=>({token:p,type:m.type,contract:m.contract}))});let d=await this.describer.describe(s,a,u.map(([,p])=>p));return M("describeReceiptTokens: DONE",{ms:Date.now()-o,overviews:d.map(p=>({name:p.name,protocol:p.protocol,asset:p.asset?.symbol,assetDecimals:p.asset?.decimals,currentApyPercent:p.currentApyPercent,avgApyPercent:p.avgApyPercent,apyChangePercent:p.apyChangePercent,totalSuppliedUsdc:p.totalSuppliedUsdc,apyHistoryPoints:p.apyHistory?.length??0}))}),new Map(d.map((p,m)=>[u[m][0],p]))}async findMarketByReceiptToken(e,t,n){if(M("findMarketByReceiptToken: called",{chain:e,receiptToken:t,hasRpcUrl:!!n}),!E(t))return M("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:t}),null;let s=(await this.describeReceiptTokens(e,[t],n)).get(t.toLowerCase())??null;return M("findMarketByReceiptToken: returning",{found:!!s}),s}async getSupplyPositions(e){if(!E(e.address))return[];let t=await Fc(this.coinPoolBaseUrl,e.chains);return(await Promise.all(t.map(o=>this.positionsForChain(o,e.address)))).flat().sort((o,s)=>s.suppliedUsdc-o.suppliedUsdc||(s.avgApyPercent??0)-(o.avgApyPercent??0))}async describeResolvedMarkets(e,t){let n=ft(e),o=n?Wo(n):null;return n&&o?this.describer.describe(n,o,t):[]}async positionsForChain(e,t){let n=Wo(e),o=await zo(this.coinPoolBaseUrl,e);if(!n||o.length===0)return[];let s=await this.describer.readBalances(e,t,o);if(s.length===0)return[];let a=await this.describer.describe(e,n,s.map(l=>l.market)),i=await this.describer.convertToUnderlying(e,s,a.map(l=>l.asset));return a.flatMap((l,c)=>{let u=i[c];return u<Mm?[]:[{...l,suppliedUsdc:$t(u,6),estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:$t(u*l.avgApyPercent/100,2)}]})}};var Vi=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Rr=class{constructor(e){this.coinPoolBaseUrl=e}coinPoolBaseUrl;async listChains(){return Gs(this.coinPoolBaseUrl)}async isSupported(e){return js(this.coinPoolBaseUrl,e)}async getMarkets(e){let t=q(e);return t?zo(this.coinPoolBaseUrl,t):[]}async findMarket(e,t){let n=await this.getMarkets(e);return Mc(n,t)}canSupply(e){return Vi.includes(e.type)}async readReceiptToken(e,t){let n=yn(t).balanceIsUnderlying;try{let o=await Pe(e,[{target:t.token,callData:F({abi:W,functionName:"symbol"})},{target:t.token,callData:F({abi:W,functionName:"decimals"})}]);return{symbol:No(o[0]),decimals:En(o[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}};var yt=class{read;supply;constructor(e={}){let t=e.coinPoolBaseUrl||"https://api.coinpool.app",n={coinPoolBaseUrl:t,aaveApiUrl:e.aaveApiUrl||"https://api.v3.aave.com/graphql",morphoApiUrl:e.morphoApiUrl||"https://api.morpho.org/graphql"},o=new Xs(n);this.read=new Cr(t,n,o),this.supply=new Rr(t)}async listSupportedChains(){return this.supply.listChains()}async isSupported(e){return this.supply.isSupported(e)}async getMarkets(e){return this.supply.getMarkets(e)}async findMarket(e,t){return this.supply.findMarket(e,t)}canSupply(e){return this.supply.canSupply(e)}async readReceiptToken(e,t){return this.supply.readReceiptToken(e,t)}async describeReceiptTokens(e,t,n){return this.read.describeReceiptTokens(e,t,n)}async findMarketByReceiptToken(e,t,n){return this.read.findMarketByReceiptToken(e,t,n)}async describeResolvedMarkets(e,t){return this.read.describeResolvedMarkets(e,t)}async getMarketOverviews(e){return(await Promise.all(e.chains.map(async n=>this.read.describeResolvedMarkets(n,await this.getMarkets(n))))).flat().sort((n,o)=>(o.avgApyPercent??-1)-(n.avgApyPercent??-1))}async getSupplyPositions(e){return this.read.getSupplyPositions(e)}};var Xo="{market}",Wc="{chain}";var Yc=[{name:"supply_button_label",type:"string",description:`Label template for the per-market "Supply" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Use the exact placeholder "{market}" (do not translate the braces); it is replaced per market with its name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply USDC" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use BOTH exact placeholders (do not translate the braces): "{market}" is replaced with the market name, "{chain}" with the chain name it lives on. Write the connecting words around {chain} in the user's language \u2014 that is why it is a placeholder and not appended for you. English example: "supply USDC to {market} on {chain}". Vietnamese example: "n\u1EA1p USDC v\xE0o {market} tr\xEAn {chain}". Always include BOTH {market} and {chain}. Do NOT write a chain name or a contract address literally \u2014 the exact market identifier is appended automatically.`,required:!1}],Gc=' A clickable "Supply" button is shown below your reply for each market automatically \u2014 do NOT list, number, or repeat those buttons in your text, and do NOT tell the user to tap one; just deliver the list and your suggestion.';function jc(r,e,t){return Bm(r,typeof e.supply_button_label=="string"?e.supply_button_label:"",typeof e.supply_prompt_template=="string"?e.supply_prompt_template:"",t)}function Bm(r,e,t,n){let o=typeof n=="string"?n.trim():"",s=[],a=new Set;for(let i of r){if(s.length>=10)break;let l=i.name?.trim();!l||a.has(l.toLowerCase())||(a.add(l.toLowerCase()),s.push({label:Vc(e,l,"",`Supply ${Xo}`),prompt:Vc(t,l,o,qm(o))+$m(i.contract)}))}return s}function qm(r){return r?`supply USDC to ${Xo} on ${Wc}`:`supply USDC to ${Xo}`}function $m(r){let e=r?.trim();return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?` (market: ${e})`:""}function Vc(r,e,t,n){return(r&&r.includes(Xo)?r:n).split(Xo).join(e).split(Wc).join(t).replace(/\s+/g," ").trim()}var Qs=[{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"]}],Yi=Qs.map(r=>r.label),Wi={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 Kc(r){let e=typeof r=="string"?r.trim():"";if(!e)return{kind:"none"};let t=Ym(e);if(!t)return{kind:"none"};let n=Hm(t);if(n){let s=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>s.has(a.type)}}let o=Wm(t);return o?{kind:"unsupported",label:o,requested:e}:{kind:"unknown",requested:e}}function Hm(r){let e=Qs.filter(t=>t.aliases.includes(r));if(e.length===1)return e[0];if(e.length>1)return null;if(r.length>=3){let t=Qs.filter(n=>n.aliases.some(o=>o.includes(r)||r.includes(o)));if(t.length===1)return t[0];if(t.length>1)return null}return Vm(r)}function Vm(r){let e=null,t=!1;for(let n of Qs)for(let o of n.aliases){let s=zc(o);if(s===0||Math.abs(o.length-r.length)>s)continue;let a=Xc(r,o,s);a>s||(!e||a<e.distance?(e={spec:n,distance:a},t=!1):a===e.distance&&n!==e.spec&&(t=!0))}return e&&!t?e.spec:null}function zc(r){return r.length<=4?0:r.length<=9?2:3}function Wm(r){let e=Wi[r];if(e)return e;if(r.length>=4){let o=new Set(Object.entries(Wi).filter(([s])=>s.length>=4&&(s.includes(r)||r.includes(s))).map(([,s])=>s));if(o.size===1)return[...o][0];if(o.size>1)return null}let t=null,n=!1;for(let[o,s]of Object.entries(Wi)){let a=zc(o);if(a===0||Math.abs(o.length-r.length)>a)continue;let i=Xc(r,o,a);i>a||(!t||i<t.distance?(t={label:s,distance:i},n=!1):i===t.distance&&s!==t.label&&(n=!0))}return t&&!n?t.label:null}function Ym(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function Xc(r,e,t){if(r===e)return 0;if(!r.length)return e.length;if(!e.length)return r.length;let n=new Array(e.length+1),o=Array.from({length:e.length+1},(a,i)=>i),s=new Array(e.length+1);for(let a=1;a<=r.length;a++){s[0]=a;let i=s[0];for(let c=1;c<=e.length;c++){let u=o[c-1]+(r[a-1]===e[c-1]?0:1),d=Math.min(s[c-1]+1,o[c]+1,u);a>1&&c>1&&r[a-1]===e[c-2]&&r[a-2]===e[c-1]&&(d=Math.min(d,n[c-2]+1)),s[c]=d,d<i&&(i=d)}if(i>t)return t+1;let l=n;n=o,o=s,s=l}return o[e.length]}var jm=["apy","score","size"],Qc=5,Jc=40,_r=class extends S{name="get-lending-markets";description='List the LENDING / SUPPLY markets available to deposit into and earn yield on: protocol (Aave v3, Compound v3, Spark, Morpho vaults), market name, chain, total supplied to that market, the live supply APY plus the average over the last week and its daily change, and a 0\u201310 platform score. Ranked by the live protocol APY by default, and filterable to ONE protocol via `protocol`. Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. 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. Each market states its own asset in `suppliedAssetSymbol`, which is usually USDC but need not be. Do NOT use for: what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:`Hex chain ID 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: ${Yi.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-${Jc}. Default ${Qc} \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},...Yc];service;constructor(e){super(),this.service=new yt(e)}async run(e,t){let n=await this.service.listSupportedChains(),o=oe(e.chain,void 0),s=o?null:q(t?.chain),a=o??s;if(a&&!n.includes(a))return{_instructions:`There are no lending markets on ${A(a)}`+(s?", 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:A(a),connectedChainHasNoMarkets:s!==null,marketCount:0,markets:[],chainsWithLendingMarkets:n.map(h=>A(h))};let i=Kc(e.protocol);if(i.kind==="unsupported"||i.kind==="unknown")return this.unsupportedProtocol(i);let l=a?[a]:n,c=zm(e.sort),u=Xm(e.limit),d=await this.service.getMarketOverviews({chains:l}),p=i.kind==="supported"?d.filter(h=>i.matches(h)):d;if(i.kind==="supported"&&p.length===0&&d.length>0)return{_instructions:`There are no ${i.label} lending markets on ${a?A(a):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${i.label} market. Do NOT mention tool names.`,requestedProtocol:i.label,chain:a?A(a):"all",marketCount:0,markets:[],protocolsAvailable:[...new Set(d.map(h=>h.protocol))]};let m=[...p].sort(Km[c]).slice(0,u),g=m.slice(0,10).flatMap(h=>jc([{name:h.name,contract:h.contract}],e,A(h.chain)));return{_instructions:this.instructions(m,c,g.length>0,i.kind==="supported"?i.label:null),...g.length>0?{actionButtons:g}:{},chain:a?A(a):"all",chainsQueried:l.map(h=>A(h)),...i.kind==="supported"?{protocolFilter:i.label}:{},sortedBy:c,marketCount:m.length,totalMarketsAvailable:p.length,markets:m.map(h=>({marketName:h.name,protocol:h.protocol,protocolUrl:h.protocolUrl,chain:A(h.chain),avgApyPercent:h.avgApyPercent,avgApyDays:h.apyHistory.length,currentApyPercent:h.currentApyPercent,apyChangePercent:h.apyChangePercent,totalSuppliedUsdc:h.totalSuppliedUsdc,suppliedAssetSymbol:h.asset.symbol,platformScore:h.platformScore}))}}unsupportedProtocol(e){let t=e.kind==="unsupported",n=t?e.label:`"${e.requested}"`;return{_instructions:`The user asked about ${n}, which has no lending markets here. In their language: tell them plainly that ${n} is ${t?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${n} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:t?e.label:e.requested,protocolSupported:!1,supportedProtocols:[...Yi],marketCount:0,markets:[]}}instructions(e,t,n=!1,o=null){if(e.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let s={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[t];return[o?`These are the ${o} lending markets the user can supply to, ${s}. The list is SCOPED to ${o} because that is what they asked about \u2014 present it as such, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${s}.`,"Present them as a NUMBERED list. Each entry starts with `marketName` as a markdown link to that","market's `protocolUrl` in bold \u2014 **[marketName](protocolUrl)** \u2014 so the name opens that market's page on","the protocol.","When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it.",'Under each name put exactly three bullet points, in this order: "Total supplied" = `totalSuppliedUsdc`,','"Protocol APY" = `currentApyPercent` (the live rate), and "Avg APY" = `avgApyPercent` labelled as the',"average over the last `avgApyDays` days. Do NOT add other bullets.","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 \u2014 mention it only when the user","asks which market is safest. A null APY means that rate was unavailable \u2014 say so rather than showing 0.",new Set(e.map(a=>a.chain)).size>1?"The markets span several chains \u2014 put each one's `chain` on the title line, after the linked name, so the user knows where it lives.":"All markets are on one chain \u2014 state the chain name once before the list, not per market.","Close with one short sentence naming the best option for the ranking used and why.","This is information, NOT financial advice \u2014 say so briefly.","Do NOT mention tool names.",n?Gc:""].filter(Boolean).join(" ")}},Km={apy:(r,e)=>(e.currentApyPercent??-1)-(r.currentApyPercent??-1),score:(r,e)=>(e.platformScore??-1)-(r.platformScore??-1),size:(r,e)=>(e.totalSuppliedUsdc??-1)-(r.totalSuppliedUsdc??-1)};function zm(r){let e=typeof r=="string"?r.trim().toLowerCase():"";return jm.includes(e)?e:"apy"}function Xm(r){let e=typeof r=="number"?r:Number(r);return!Number.isFinite(e)||e<1?Qc:Math.min(Math.floor(e),Jc)}var Er=class extends S{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 yt(e)}async run(e,t){let n=Z(e.address,t);if(!E(n))return{error:`"${n}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=oe(e.chain,t),s=await this.service.listSupportedChains();if(o&&!s.includes(o))return{_instructions:`There are no lending markets on ${A(o)}, so the wallet cannot have a supply position there. Tell the user that in their language and name the chains that DO have lending markets (listed in \`chainsWithLendingMarkets\`). Do NOT mention tool names.`,walletAddress:n,chain:A(o),positionCount:0,positions:[],chainsWithLendingMarkets:s.map(l=>A(l))};let a=o?[o]:s,i=await this.service.getSupplyPositions({address:n,chains:a});return{_instructions:this.instructions(i),walletAddress:n,chain:o?A(o):"all",chainsQueried:a.map(l=>A(l)),positionCount:i.length,totals:Qm(i),positions:i.map(l=>({marketName:l.name,protocol:l.protocol,protocolUrl:l.protocolUrl,chain:A(l.chain),suppliedUsdc:l.suppliedUsdc,suppliedAssetSymbol:l.asset.symbol,avgApyPercent:l.avgApyPercent,currentApyPercent:l.currentApyPercent,apyChangePercent:l.apyChangePercent,estimatedAnnualYieldUsdc:l.estimatedAnnualYieldUsdc,marketTotalSuppliedUsdc:l.totalSuppliedUsdc,apyHistory:l.apyHistory,platformScore:l.platformScore}))}}instructions(e){return e.length===0?"The wallet supplies 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 daily samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(e.map(n=>n.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals` \u2014 but ONLY when `totals.mixedAssets` is false; when it is true","the positions are in different assets and cannot be added up, so give no portfolio total and let the","per-position amounts stand. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function Qm(r){if(new Set(r.map(a=>a.asset.symbol??a.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let n=r.reduce((a,i)=>a+i.suppliedUsdc,0),o=r.filter(a=>a.avgApyPercent!==null),s=o.reduce((a,i)=>a+i.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:r[0]?.asset.symbol??null,suppliedUsdc:Gi(n,6),estimatedAnnualYieldUsdc:Gi(r.reduce((a,i)=>a+(i.estimatedAnnualYieldUsdc??0),0),2),weightedAvgApyPercent:s>0?Gi(o.reduce((a,i)=>a+i.suppliedUsdc*i.avgApyPercent,0)/s,2):null}}function Gi(r,e){let t=10**e;return Math.round(r*t)/t}var Nr=class extends S{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)" hint, pass THAT address verbatim as this argument and ignore the market name in the sentence \u2014 the address identifies the exact market they picked, while a name may match several vaults of the same protocol.`,required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the user names; whether it carries markets is checked at call time. Set it ONLY when the user names a chain; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`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 yt(e),this.moralis=new O(e?.moralis)}async run(e,t){let n=t?.walletAddress;if(!n)return{error:"wallet_not_connected",_instructions:"Supplying moves real funds, so it needs a connected wallet. Ask the user to connect one, in their language. Do NOT render a form and do NOT mention tool names."};let s=oe(e.chain,void 0)??q(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."};let a=await this.service.listSupportedChains();if(!a.includes(s))return{error:"unsupported_chain",chain:A(s),chainsWithLendingMarkets:a.map(b=>A(b)),_instructions:`There are no lending markets on ${A(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 i=Zm(e.market);if(!i)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let l=await this.service.findMarket(s,i);if(l.length===0)return{error:"market_not_found",market:i,chain:A(s),_instructions:`No lending market matching "${i}" exists on ${A(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(l.length>1)return{error:"ambiguous_market",market:i,chain:A(s),candidates:l.map(b=>({marketName:b.name,protocol:b.protocol})),_instructions:`"${i}" matches ${l.length} different markets on ${A(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="`+i+`" and chain for ${A(s)}, plus the localized supply-button templates \u2014 that shows the user each market with its APY, size and score, each with its own Supply button to tap. Write no message of your own before that call.`};let c=l[0];if(!this.service.supply.canSupply(c))return{error:"unsupported_protocol",marketName:c.name,protocol:c.protocol,_instructions:`Supplying to ${c.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let u=await this.describeOne(s,c),d=Jm(u);if(!d)return{error:"asset_unresolved",marketName:c.name,chain:A(s),_instructions:`The asset ${c.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[p,m]=await Promise.all([this.assetBalance(n,s,d.address),this.service.readReceiptToken(s,c)]);if(p&&pn(p.amount,"0")<=0)return{error:"no_asset_balance",marketName:c.name,chain:A(s),assetSymbol:d.symbol,assetBalance:"0",_instructions:`The user has no ${d.symbol} available to supply to ${c.name} on ${A(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 g=eh(e.amount),h=g?Dt(g,d.decimals):null;if(h&&p&&pn(h,p.amount)>0)return{error:"insufficient_asset_balance",marketName:c.name,chain:A(s),assetSymbol:d.symbol,requestedAmount:g,assetBalance:p.amount,_instructions:`The user wants to supply ${g} ${d.symbol} to ${c.name}, but they only hold ${p.amount} ${d.symbol} on ${A(s)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${g} ${d.symbol} exceeds their balance of ${p.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 f={action:"supply_usdc",chainId:s,chainName:A(s),walletAddress:n,market:{name:c.name,type:c.type,protocol:c.protocol,protocolUrl:u?.protocolUrl??zs(c),contract:c.contract,token:c.token,apyPercent:u?.currentApyPercent??u?.avgApyPercent??null,receiptToken:m},asset:d,...h?{prefillAmount:h}:{},...p?{spendable:p.amount}:{},...p?.usd?{spendableUsd:p.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:f},marketName:c.name,protocol:c.protocol,chain:A(s),apyPercent:f.market.apyPercent,assetSymbol:d.symbol,assetBalance:p?.amount??null,_instructions:this.instructions(c,d.symbol)}}async describeOne(e,t){try{let[n]=await this.service.describeResolvedMarkets(e,[t]);return n??null}catch{return null}}async assetBalance(e,t,n){try{let o=await this.moralis.getWalletTokenBalances({address:e,chain:t,tokenAddresses:[n]});if(!o.success)return null;let s=(o.data?.result??[]).find(i=>(i.token_address||"").toLowerCase()===n.toLowerCase());if(!s?.balance_formatted)return{amount:"0",usd:null};let a=typeof s.usd_value=="number"?String(s.usd_value):null;return{amount:String(s.balance_formatted),usd:a}}catch{return null}}instructions(e,t){return[`The supply action for ${e.name} is ready.`,`In the user's language, invite them to enter the amount of ${t} they want to supply, naming the`,"market and the chain.",`Speak ONLY of the action the USER takes (supplying / depositing ${t}). NEVER say you "opened a form",`,'"opened" anything, or describe any screen, form, window or UI \u2014 phrase it as their next step, not something',"you did.","Do NOT state their balance, the contract address or any figure from the form; it is all on screen already.","Keep it to one or two short sentences. Add a brief note that supplying carries protocol risk and rates","float \u2014 information, not financial advice.","Do NOT mention tool names."].join(" ")}};function Jm(r){let e=r?.asset;return!e?.address||e.address===hn||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function Zm(r){let e=typeof r=="string"?r.trim():"",t=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})\s*[\])]/i.exec(e);if(t)return t[1];let n=/0x[a-fA-F0-9]{40}/.exec(e);return n&&n[0]!==e?n[0]:e}function eh(r){let e=typeof r=="string"?r.trim():typeof r=="number"?String(r):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}var Js="https://ipfs.pantograph.app/ipfs/",Zc=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function bn(r){let e=r?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${Js}${t[1]}`:Zc.test(e)?`${Js}${e}`:null}function eu(r){let e=r?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${Js}${t[1]}`:Zc.test(e)?`${Js}${e}`:null}function tu(r){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(r)}function ji(r){if(!r||typeof r!="object")return;let e=r,t=e.image??e.image_url??e.imageUrl;return typeof t=="string"&&t.trim()?t.trim():void 0}function th(r){if(typeof atob=="function"){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder().decode(t)}if(typeof Buffer<"u")return Buffer.from(r,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function nh(r){let e=r.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let t=e[1]??"",n=e[2]??"";try{let o=/;base64/i.test(t)?th(n):decodeURIComponent(n);return JSON.parse(o)}catch{try{return JSON.parse(n)}catch{return null}}}function nu(r){let e=r?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=nh(e);return t?bn(ji(t)):null}var rh=12,oh=6e3;async function sh(r,e,t){let n=new Array(r.length),o=0,s=new Array(Math.max(1,Math.min(e,r.length))).fill(0).map(async()=>{for(;o<r.length;){let a=o++;n[a]=await t(r[a],a)}});return await Promise.all(s),n}async function ah(r,e){try{let t=await x.get(r,{timeout:e});if(!t.ok)return null;let n=t.data;if(n&&typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return null}return null}catch{return null}}async function ih(r,e){let t=r?.trim();if(!t)return null;if(/^data:/i.test(t))return nu(t);let n=eu(t);if(!n)return null;if(tu(n))return n;let o=await ah(n,e);if(o){let s=bn(ji(o));if(s)return s}return null}async function Zs(r,e,t){if(e.length===0)return[];let n=t?.concurrency??rh,o=t?.timeoutMs??oh,s=await uc(r,e,t?.rpcUrl);return sh(s,n,a=>ih(a,o))}var ru=100,lh=100,Ur="{name}",ou="{chain}",Ir=class extends S{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 n=Z(e.address,t),o=oe(e.chain,t),s=o?[o]:Se(),a=hh(e.contract_address),i=iu(e.collection_name);return a||i?this.listNfts({address:n,chains:s,singleChain:!!o,contract:a,collectionName:i}):this.listCollections({address:n,chains:s,singleChain:!!o,args:e})}async listCollections(e){let{address:t,chains:n,singleChain:o,args:s}=e,a=await Promise.all(n.map(async c=>{let u=await this.service.getWalletNftCollections({address:t,chain:c,limit:ru});return{chain:c,rows:u.success?su(u.data?.result??[]):[],ok:u.success}}));if(o&&!a[0].ok)return{error:"Failed to fetch wallet NFT collections"};let i=a.flatMap(c=>c.rows.map(u=>({name:uh(u),contractAddress:u.token_address,chain:A(c.chain),nftCount:u.count??null})));if(i.length===0)return{_instructions:"The wallet holds no NFT collections"+(o?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:t,collectionCount:0,collections:[]};let l=ph(i,s);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:t,collectionCount:i.length,collections:i,...l.length>0?{actionButtons:l}:{}}}async listNfts(e){let{address:t,chains:n,singleChain:o,contract:s,collectionName:a}=e,i=await Promise.all(n.map(async m=>{let g=await this.service.getWalletNFTs({address:t,chain:m,limit:ru,...s?{tokenAddresses:[s]}:{}});return{chain:m,rows:g.success?su(g.data?.result??[]):[],ok:g.success}}));if(o&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(m=>m.rows.filter(g=>ch(g,{contract:s,collectionName:a})).map(g=>({chain:m.chain,row:g})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${a??s??""}"`+(o?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||a||l[0].row.token_address,u=await this.resolveOnchainImages(l),d=l.map(({chain:m,row:g},h)=>{let f=dh(g);return{name:f.name,tokenId:f.tokenId,contractAddress:f.contractAddress,image:u[h]??f.image,chain:A(m)}});return{ui:{component:"WalletNftList",props:{walletAddress:t,collectionName:c,nfts:d}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:t,collectionName:c,nftCount:l.length}}async resolveOnchainImages(e){let t=new Array(e.length).fill(null),n=new Map;e.forEach((o,s)=>{let a=n.get(o.chain)??[];a.push(s),n.set(o.chain,a)});try{await Promise.all([...n.entries()].map(async([o,s])=>{let a=s.map(l=>({contract:e[l].row.token_address,tokenId:e[l].row.token_id})),i=await Zs(o,a);s.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function su(r){return r.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function ch(r,e){if(e.contract)return r.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let t=e.collectionName.toLowerCase();return(r.name??"").toLowerCase().includes(t)}return!1}function uh(r){let e=r.name?.trim();if(e)return e;let t=r.token_address??"";return t.length>10?`${t.slice(0,6)}\u2026${t.slice(-4)}`:t}function dh(r){return{name:r.normalized_metadata?.name||r.name||`#${r.token_id}`,tokenId:r.token_id,contractAddress:r.token_address,image:bn(r.normalized_metadata?.image||r.media?.original_media_url)}}function ph(r,e){let t=typeof e.pick_button_label=="string"?e.pick_button_label:"",n=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",o=[];for(let s of r){if(o.length>=lh)break;if(!s.contractAddress)continue;let a=typeof s.chain=="string"?s.chain.trim():"",i=a?`show my ${Ur} NFTs on ${ou}`:`show my ${Ur} NFTs`,l=au(n,{[Ur]:s.name,[ou]:a},i);a&&!l.includes(a)&&(l=`${l} (${a})`),o.push({label:mh(t,s.name,Ur),prompt:`${l} (${s.contractAddress})`})}return o}function au(r,e,t){let n=r&&r.includes(Ur)?r:t;for(let[o,s]of Object.entries(e))n=n.split(o).join(s);return n.replace(/\s+/g," ").trim()}function mh(r,e,t){return au(r,{[Ur]:e},t)}function iu(r){if(typeof r!="string")return;let e=r.trim();return e||void 0}function hh(r){let e=iu(r);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var gh="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 S{kind="data";category="nft";llm;constructor(e){super(),this.llm=new re(e??{})}static promptParams(e){return[{name:"prompt",type:"string",description:e,required:!0}]}async run(e){let t=typeof e.prompt=="string"?e.prompt.trim():"";if(!t)return{error:"Missing required parameter: prompt"};let n=await this.askGeminiWithSearch(t);return n?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:n}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(e){let t=Date.now();try{return(await this.llm.chat([{role:"system",content:gh,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Lr=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 Dr=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 Ki={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"},zi="amazon.com";function fh(r){return r?r.trim().toLowerCase().split(/[-_]/)[0]:""}function Xi(r){let e=fh(r);return Ki[e]??zi}function ea(r){return`https://${Xi(r)}/s?k=NFC%20Tag`}function ta(r){if(!r)return"";let e=r.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var yh=720*60*1e3,lu=new Map,cu=3;function bh(r){return[`A user in country "${r}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${cu} 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 wh(r){if(!r)return[];let e=r.indexOf("["),t=r.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let n;try{n=JSON.parse(r.slice(e,t+1))}catch{return[]}if(!Array.isArray(n))return[];let o=[],s=new Set;for(let a of n){if(!a||typeof a!="object")continue;let i=a.label,l=a.url;if(typeof i!="string"||!i.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!s.has(c)&&(s.add(c),o.push({label:i.trim(),url:l.trim()}),o.length>=cu))break}return o}async function Qi(r,e){let t=ta(r);if(!t||!e)return null;let n=lu.get(t);if(n&&n.expires>Date.now())return n.links;let o=Date.now(),s=[{role:"user",content:bh(t),timestamp:o}];try{let a=await e.chat(s,void 0,{googleSearch:!0,maxRetries:1}),i=wh(a.text);if(i.length)return lu.set(t,{links:i,expires:Date.now()+yh}),i}catch{}return null}async function Or(r){let e=await Qi(r.country,r.llm);return e&&e.length?e:[{label:"Amazon",url:ea(r.language)}]}function kh(r){return r.length<=1?r.length===1?`[${r[0].label}](${r[0].url})`:"":r.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
25
+ }`,Pr=class{underlyingCall(e){return he(e.contract,tt,"asset")}liveRateCall(e,t){return null}followUpRateCall(e,t){return null}decodeSize(e,t){if(!Number.isInteger(t.decimals)||t.decimals<0)return null;let n=le(e);return n===null?null:qt(n,t.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,t){return this.balanceIsUnderlying?null:he(e.contract,tt,"convertToAssets",[t])}},Go=class extends Pr{type="spark";balanceIsUnderlying=!1;sizeCall(e){return he(e.contract,tt,"totalAssets")}fetchApy(e,t,n){return Mi(e,t,n)}},Ei=class extends Go{type="spark";liveRateCall(e){return he(e.contract,Ar,"rateProvider")}followUpRateCall(e,t){let n=G(t);return n===null?null:he(n,fn,"getAPR")}decodeLiveRate(e){let t=le(e);return t===null?null:jo(Math.expm1(Number(t)/Vs))}},Ni=class extends Go{type="spark-ethereum";liveRateCall(e){return he(e.contract,Ar,"vsr")}decodeLiveRate(e){let t=le(e);if(t===null)return null;let n=Number(t)/Vs;return n>0?jo(Math.expm1(Math.log(n)*Dc)):null}},Ui=class extends Pr{type="spark-l2-susds";balanceIsUnderlying=!1;underlyingCall(){return null}sizeCall(e){return he(e.token,W,"totalSupply")}liveRateCall(e){return he(e.contract,fn,"getAPR")}decodeLiveRate(e){let t=le(e);return t===null?null:jo(Math.expm1(Number(t)/Vs))}convertToAssetsCall(e){return he(e.contract,fn,"getConversionRate")}fetchApy(e,t,n){return Mi(e,t,n)}};function Sr(r,e,t,n){if(e<=0n||!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<0)return null;let o=r*e/sm,s=n-t;return s===0?o:s>0?o*10n**BigInt(s):o/10n**BigInt(-s)}var Ii=class extends Pr{type="aave-v3";balanceIsUnderlying=!0;underlyingCall(e){return he(e.token,Tr,"UNDERLYING_ASSET_ADDRESS")}sizeCall(e){return he(e.token,W,"totalSupply")}liveRateCall(e,t){return he(e.contract,Hs,"getReserveData",[t.address])}decodeLiveRate(e){if(!e)return null;let t;try{let[n]=be(Hs[0].outputs,e);t=n.currentLiquidityRate}catch{return null}return jo(Number(t)/Vs)}async fetchApy(e,t,n,o){let s=await x.post(n.aaveApiUrl,{operationName:"SupplyAPYHistory",query:im,variables:{request:{chainId:t.chainId,market:e.contract,underlyingToken:o.address,window:"LAST_WEEK"}}});if(!s.ok)throw new Error(U(s));return{samples:(s.data?.data?.value||[]).map(a=>({timeMs:Date.parse(a?.date??""),fraction:Number(a?.avgRate?.value)})),current:null}}},Li=class extends Pr{type="compound-v3";balanceIsUnderlying=!0;underlyingCall(e){return he(e.contract,gn,"baseToken")}sizeCall(e){return he(e.token,W,"totalSupply")}liveRateCall(e){return he(e.contract,gn,"getUtilization")}followUpRateCall(e,t){let n=le(t);return n===null?null:he(e.contract,gn,"getSupplyRate",[n])}decodeLiveRate(e){let t=le(e);return t===null?null:jo(Number(t)/1e18*Dc)}fetchApy(e,t,n){return Mi(e,t,n)}},Di=class extends Go{type="morpho-v2";async fetchApy(e,t,n){let o=pm(Date.now()),s=await x.post(n.morphoApiUrl,{operationName:"VaultV2ByAddress",query:lm,variables:{address:e.contract,chainId:t.chainId,options:{startTimestamp:Math.floor(o/1e3)-(Oi-1)*86400,endTimestamp:Math.floor(o/1e3)-86400}}});if(!s.ok)throw new Error(U(s));let a=s.data?.data?.vaultV2ByAddress,i=Number(a?.netApyExcludingRewards);return{samples:(a?.historicalState?.avgNetApy||[]).map(l=>({timeMs:Number(l?.x)*1e3,fraction:Number(l?.y)})),current:Number.isFinite(i)?i:null}}};async function Mi(r,e,t){let n=`${t.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${r.token}`,o=await x.get(n);if(!o.ok)throw new Error(U(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}}var Oc={"aave-v3":new Ii,"compound-v3":new Li,spark:new Ei,"spark-ethereum":new Ni,"spark-l2-susds":new Ui,"morpho-v2":new Di},cm=Oc.spark;function yn(r){return Oc[r.type]??cm}var um={"aave-v3":"Aave V3","compound-v3":"Compound V3",spark:"Spark","spark-ethereum":"Spark","spark-l2-susds":"Spark","morpho-v2":"Morpho V2"};function Ye(r){return um[r]??null}var dm={"aave-v3":"https://app.aave.com","compound-v3":"https://app.compound.finance",spark:"https://app.spark.fi","spark-ethereum":"https://app.spark.fi","spark-l2-susds":"https://app.spark.fi","morpho-v2":"https://app.morpho.org"};function Ws(r){return dm[r]??null}function qt(r,e){return Number(r)/10**e}function Ko(r){return new Date(r).toISOString().slice(0,10)}function pm(r){return Date.parse(`${Ko(r)}T00:00:00.000Z`)}var mm=6e4,Fi=new Map;async function zo(r,e){let t=ft(e),n=t?parseInt(t,16):NaN;if(!t||!Number.isFinite(n))return[];let o=`${r}|${t}`,s=Fi.get(o);if(s&&Date.now()-s.at<mm)return s.markets;let a=hm(r,t,n),i=a.then(l=>l.markets);return Fi.set(o,{at:Date.now(),markets:i}),a.then(l=>{l.answered||Fi.delete(o)}),i}async function Ys(r,e){return(await zo(r,e)).length>0}async function hm(r,e,t){try{let n=`${r}/supply/v2?chainId=${t}&limit=100&page=1`;M("catalog: GET",n);let o=await x.get(n);if(!o.ok){let a=o.status>=400&&o.status<500;return M(a?"catalog: chain not served":"catalog: FAILED",{chain:e,status:o.status,message:U(o)}),{markets:[],answered:a}}let s=(o.data?.data?.items||[]).flatMap(a=>{let i=gm(a,e);return i?[i]:[]});return M("catalog: got markets",{chain:e,rawItems:o.data?.data?.items?.length??0,usable:s.length,tokens:s.map(a=>a.token)}),{markets:s,answered:!0}}catch(n){return M("catalog: FAILED \u2014 falling back to on-chain discovery",{chain:e,message:n?.message}),{markets:[],answered:!1}}}function Mc(r,e){let t=e.trim().toLowerCase();if(!t)return[];if(E(t))return r.filter(o=>o.contract===t||o.token===t);let n=r.filter(o=>o.name.trim().toLowerCase()===t);return n.length>0?n:r.filter(o=>{let s=o.name.trim().toLowerCase(),a=o.protocol.trim().toLowerCase();return s.includes(t)||t.includes(s)||a.includes(t)||t.includes(a)})}function gm(r,e){if(r?.isDeleted===!0)return null;let t=typeof r?.contract=="string"?r.contract.toLowerCase():"";if(!E(t))return null;let n=typeof r?.token=="string"&&E(r.token)?r.token.toLowerCase():t,o=Number(r?.rating?.balanceScore),s=r?.type?.trim()||"unknown";return{chain:e,name:r?.name?.trim()||"USDC lending market",protocol:r?.protocolId?.name?.trim()||"Unknown",protocolLabel:Ye(s),protocolUrl:r?.protocolId?.domain?.trim()||null,type:s,contract:t,token:n,platformScore:Number.isFinite(o)?o:null}}function Bi(){return Se()}async function Gs(r){let e=Bi(),t=await Promise.all(e.map(n=>Ys(r,n)));return e.filter((n,o)=>t[o])}async function js(r,e){let t=q(e);return t?Ys(r,t):!1}async function Fc(r,e){let t=e.map(s=>q(s)).filter(s=>!!s),n=[...new Set(t)],o=await Promise.all(n.map(s=>Ys(r,s)));return n.filter((s,a)=>o[a])}var fm={"0x2105":"0x1601843c5E9bC251A3272907010AFa41Fa18347E","0xa4b1":"0x2B05F8e1cACC6974fD79A673a341Fe1f58d27266","0xa":"0xe0F9978b907853F354d79188A3dEfbD41978af62","0x82":"0x7b42Ed932f26509465F7cE3FAF76FfCe1275312f"};function Ks(r){let e=ft(r);return e?fm[e]??null:null}function Bc(r){return["susds","usds","rateProvider"].map(e=>({target:r,callData:F({abi:_i,functionName:e})}))}var qc=3,ym={"0x2105":"0x65d946e533748A998B1f0E430803e39A6388f7a1","0xa4b1":"0xEE2816c1E1eed14d444552654Ed3027abC033A36","0xa":"0x6E53585449142A5E6D5fC918AE6BEa341dC81C68","0x82":"0x1566BFA55D95686a823751298533D42651183988"};function qi(r){let e=ft(r),t=e?ym[e]:void 0;return t?{target:t,callData:F({abi:fn,functionName:"getConversionRate"})}:null}function xr(r){return Ws(r)}var $c=5;async function Hc(r,e,t){let n=e.map(y=>E(y)?y.toLowerCase():null);if(n.every(y=>y===null))return M("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let o=Ks(r),s;try{M("discovery: probing 5 accessors per token",{chain:r,tokens:n,psm:o}),s=await Pe(r,[...n.flatMap(y=>y?bm(y):[]),...o?Bc(o):[]])}catch(y){return M("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:r,message:y?.message}),e.map(()=>null)}let a=o?s.slice(s.length-qc):[],i=G(a[0])?.toLowerCase()??null,l=G(a[1]),c=G(a[2]),u=i&&l&&c?{susds:i,usds:l,oracle:c}:null;o&&M("discovery: PSM3 lookup",{psm:o,susds:i,usds:l,oracle:c});let d=0,p=n.map(y=>{if(!y)return null;let b=s.slice(d,d+$c);return d+=$c,M("discovery: probe answers",{token:y,"POOL()":G(b[0]),"UNDERLYING_ASSET_ADDRESS()":G(b[1]),"baseToken()":G(b[2]),"asset()":G(b[3]),"vsr()":le(b[4])?.toString()??null}),{token:y,slice:b}}),m=new Set;for(let y of p){if(!y)continue;let b=G(y.slice[0]);b&&G(y.slice[1])&&m.add(b.toLowerCase())}let g=await wm(r,[...m]);m.size>0&&M("discovery: Aave pool authentication",{claimed:[...m],genuine:[...g]});let h=p.flatMap(y=>y?G(y.slice[0])&&G(y.slice[1])||G(y.slice[2])?[]:G(y.slice[3])?[y.token]:[]:[]),f=await km(r,[...new Set(h)],t);return h.length>0&&M("discovery: Morpho vault lookup",{asked:[...new Set(h)],recognised:[...f.keys()]}),p.map(y=>{if(!y)return null;let{token:b,slice:k}=y,w={chain:r,protocolUrl:null,token:b,platformScore:null};if(u&&b===u.susds)return M("discovery: classified",{token:b,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:u.oracle}),{...w,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:Ye("spark-l2-susds"),protocolUrl:xr("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let v=G(k[0]);if(v&&G(k[1])){let T=g.has(v.toLowerCase());return M("discovery: classified",{token:b,as:T?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:v}),T?{...w,name:"Aave v3",protocol:"AAVE",protocolLabel:Ye("aave-v3"),protocolUrl:xr("aave-v3"),type:"aave-v3",contract:v}:null}if(G(k[2]))return M("discovery: classified",{token:b,as:"compound-v3"}),{...w,name:"Compound v3",protocol:"COMPOUND",protocolLabel:Ye("compound-v3"),protocolUrl:xr("compound-v3"),type:"compound-v3",contract:b};if(G(k[3])){if(f.has(b)){M("discovery: classified",{token:b,as:"morpho-v2"});let C=f.get(b)||"Morpho V2";return{...w,name:C,protocol:"MORPHO",protocolLabel:Ye("morpho-v2"),protocolUrl:xr("morpho-v2"),type:"morpho-v2",contract:b}}let P=le(k[4])!==null;return M("discovery: classified",{token:b,as:P?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),P?{...w,name:"Spark",protocol:"SPARK",protocolLabel:Ye("spark-ethereum"),protocolUrl:xr("spark-ethereum"),type:"spark-ethereum",contract:b}:{...w,name:"Spark",protocol:"SPARK",protocolLabel:Ye("spark"),protocolUrl:xr("spark"),type:"spark",contract:b}}return M("discovery: classified",{token:b,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function bm(r){return[{target:r,callData:F({abi:Tr,functionName:"POOL"})},{target:r,callData:F({abi:Tr,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:r,callData:F({abi:gn,functionName:"baseToken"})},{target:r,callData:F({abi:tt,functionName:"asset"})},{target:r,callData:F({abi:Ar,functionName:"vsr"})}]}async function wm(r,e){if(e.length===0)return new Set;try{let t=await Pe(r,e.map(n=>({target:n,callData:F({abi:Ri,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((n,o)=>G(t[o])!==null))}catch{return new Set}}async function km(r,e,t){let n=parseInt(r,16);if(e.length===0||!Number.isFinite(n))return new Map;let o=await Promise.all(e.map(async s=>{try{let a=await x.post(t,{query:"query V($a: String!, $c: Int!) { vaultV2ByAddress(address: $a, chainId: $c) { address name } }",variables:{a:s,c:n}}),i=a.ok?a.data?.data?.vaultV2ByAddress:null;return i?[s,i.name?.trim()||""]:null}catch{return null}}));return new Map(o.filter(s=>s!==null))}var vm={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},Tm={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"},Am={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},Pm={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function zs(r){let e=Um(r.chain);return(e===null?null:Sm(r,e))??Ws(r.type)??Nm(r,e)}function Sm(r,e){switch(r.type){case"morpho-v2":{let t=vm[e];if(!t||!r.contract)return null;let n=`https://app.morpho.org/${t}/vault/${$i(r.contract)}`,o=Rm(r.name);return o?`${n}/${o}`:n}case"aave-v3":{let t=Tm[e],n=xm(r);return!t||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${$i(n)}&marketName=${t}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let t=Am[e],n=Em(r);return!t||!n?null:`https://app.spark.fi/savings/${t}/${n}`}case"compound-v3":{let t=Pm[e],n=_m(r);return!t||!n?null:`https://app.compound.finance/?market=${n}-${t}`}default:return null}}function xm(r){let e=r.asset?.address?.trim().toLowerCase()||"";return/^0x[0-9a-f]{40}$/.test(e)?/^0x0+$/.test(e)?null:e:null}var Cm=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Rm(r){let e=r?.trim().toLowerCase()||"";return!e||Cm.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function _m(r){let e=r.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function Em(r){let e=`${r.name||""} ${r.token||""}`.toLowerCase();for(let n of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(e.includes(n))return n;let t=r.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]{2,11}$/.test(t)?r.type==="spark-ethereum"?`sp${t}`:`s${t}`:null}function Nm(r,e){let t=r.protocolUrl?.trim();if(!t)return null;let n=/^https?:\/\//i.test(t)?t:`https://${t.replace(/^\/+/,"")}`;try{let o=new URL(n);return e!==null&&o.searchParams.set("chainId",String(e)),r.contract&&o.searchParams.set("contract",$i(r.contract)),o.toString()}catch{return n}}function $i(r){let e=r.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function Um(r){let e=r?.trim();if(!e)return null;let t=/^0x/i.test(e)?Number.parseInt(e,16):Number(e);return Number.isFinite(t)&&t>0?t:null}var Im=8;function Lm(r,e,t){if(r.market.type!=="spark-l2-susds")return le(e);let n=le(e);return n===null||r.tokenDecimals===null?null:Sr(r.rawBalance,n,r.tokenDecimals,t)}var Xs=class{constructor(e){this.endpoints=e}endpoints;apyLimiter=new Hi(Im);pantograph=new se;async describe(e,t,n){if(n.length===0)return[];M("describe: START",{chain:e,count:n.length,types:n.map(i=>i.type)});let o=await this.resolveAssets(e,n);M("describe: assets resolved",o);let[s,a]=await Promise.all([this.readMarketState(e,n,o),Promise.all(n.map((i,l)=>this.apyLimiter.run(()=>this.fetchApy(i,t,o[l]))))]);return M("describe: on-chain state",s),M("describe: APY fetched",a.map((i,l)=>({type:n[l].type,rawSamples:i.samples.length,sourceCurrent:i.current}))),n.map((i,l)=>{let{totalSuppliedUsdc:c,liveApyFraction:u}=s[l],d=Dm(a[l].samples,u??a[l].current);return M("describe: summarised",{market:i.name,type:i.type,liveFrom:u!==null?"on-chain":a[l].current!==null?"api":"none",rawSamples:a[l].samples.length,historyPoints:d.history.length,currentApyPercent:d.currentApyPercent,avgApyPercent:d.avgApyPercent,apyChangePercent:d.apyChangePercent,totalSuppliedUsdc:c,asset:o[l]?.symbol}),{...i,protocolUrl:zs({...i,asset:o[l]}),asset:o[l],totalSuppliedUsdc:c===null?null:$t(c,2),avgApyPercent:d.avgApyPercent,currentApyPercent:d.currentApyPercent,apyChangePercent:d.apyChangePercent,apyHistory:d.history}})}async readBalances(e,t,n){let o=F({abi:W,functionName:"balanceOf",args:[t]}),s=F({abi:W,functionName:"decimals"}),a=n.flatMap(l=>[{target:l.token,callData:o},{target:l.token,callData:s}]),i=await Pe(e,a);return n.flatMap((l,c)=>{let u=le(i[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:En(i[c*2+1])}]})}async convertToUnderlying(e,t,n){let o=[],s=t.map(i=>{let l=yn(i.market).convertToAssetsCall(i.market,i.rawBalance);return l?(o.push(l),o.length-1):-1}),a=await Pe(e,o);return t.map((i,l)=>{let c=n[l]?.decimals;if(!Number.isInteger(c)||c<0)return 0;if(s[l]<0)return qt(i.rawBalance,c);let u=Lm(i,a[s[l]],c);return u===null?qt(i.rawBalance,i.tokenDecimals??c):qt(u,c)})}async resolveAssets(e,t){let n={address:hn,decimals:NaN,symbol:null,logo:null},o=[],s=t.map(u=>{let d=yn(u).underlyingCall(u);return d?(o.push(d),o.length-1):-1}),a;try{let u=o.length>0?await Pe(e,o):[];a=s.map(d=>d<0?null:G(u[d]))}catch{a=t.map(()=>null)}a=a.map((u,d)=>u??t[d]?.assetAddress??null);let i=[...new Set(a.filter(u=>!!u).map(u=>u.toLowerCase()))],[l,c]=await Promise.all([this.readAssetMetadata(e,i),this.fetchAssetLogos(e,i)]);return a.map(u=>{if(!u)return n;let d=u.toLowerCase(),p=l.get(d),m=c.get(d)??null;return p?.decimals!==null&&p?.decimals!==void 0?{address:u,decimals:p.decimals,symbol:p.symbol??null,logo:m}:{address:u,decimals:NaN,symbol:null,logo:m}})}async readAssetMetadata(e,t){let n=new Map;if(t.length===0)return n;let o=F({abi:W,functionName:"decimals"}),s=F({abi:W,functionName:"symbol"});try{let a=await Pe(e,t.flatMap(i=>[{target:i,callData:o},{target:i,callData:s}]));t.forEach((i,l)=>{n.set(i,{decimals:En(a[l*2]),symbol:No(a[l*2+1])})})}catch{}return n}async fetchAssetLogos(e,t){let n=new Map;if(t.length===0)return n;try{let o=await this.pantograph.getTokensMetadata(t,e);for(let[s,a]of Object.entries(o)){let i=a.icon_image||a.logo||a.logoURI;i&&n.set(s.toLowerCase(),i)}}catch{}return M("resolveAssets: logos",{chain:e,requested:t.length,found:n.size}),n}async readMarketState(e,t,n){let o=[],s=t.map((u,d)=>{let p=yn(u),m=n[d],g={market:u,protocol:p,asset:m,size:o.length,rate:-1};o.push(p.sizeCall(u,m));let h=p.liveRateCall(u,m);return h&&(g.rate=o.length,o.push(h)),g}),a=await Pe(e,o),i=[],l=s.map(u=>{if(u.rate<0)return-1;let d=u.protocol.followUpRateCall(u.market,a[u.rate]);return d?(i.push(d),i.length-1):-1}),c=i.length>0?await Pe(e,i):[];return s.map((u,d)=>{let p=u.rate<0?null:a[u.rate],m=l[d]>=0?c[l[d]]:p;return{totalSuppliedUsdc:u.protocol.decodeSize(a[u.size],u.asset),liveApyFraction:m===null?null:u.protocol.decodeLiveRate(m)}})}async fetchApy(e,t,n){try{M("fetchApy: requesting",{market:e.name,type:e.type,asset:n?.symbol});let o=await yn(e).fetchApy(e,t,this.endpoints,n);return M("fetchApy: got",{market:e.name,samples:o.samples.length,current:o.current}),o}catch(o){return M("fetchApy: FAILED \u2014 market listed without APY",{market:e.name,type:e.type,message:o?.message}),{samples:[],current:null}}}},Hi=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 Dm(r,e){let t=Ko(Date.now()),n=new Map,o=null;for(let u of r){if(!Number.isFinite(u.timeMs)||!Number.isFinite(u.fraction)||u.fraction<0||((!o||u.timeMs>o.timeMs)&&(o=u),!Om(u.timeMs)))continue;let d=Ko(u.timeMs);d>=t||n.set(d,u.fraction)}let s=[...n.entries()].sort((u,d)=>u[0]<d[0]?-1:1).slice(-Oi).map(([u,d])=>({date:u,apyPercent:$t(d*100,2)})),a=e??(o&&Ko(o.timeMs)===t?o.fraction:null),i=a===null?null:$t(a*100,2);if(i!==null&&s.push({date:t,apyPercent:i}),s.length===0)return{history:s,avgApyPercent:null,currentApyPercent:null,apyChangePercent:null};let l=s.reduce((u,d)=>u+d.apyPercent,0),c=s[s.length-1].apyPercent;return{history:s,avgApyPercent:$t(l/s.length,2),currentApyPercent:i,apyChangePercent:s.length>=2?$t(c-s[s.length-2].apyPercent,2):null}}function $t(r,e){let t=10**e;return Math.round(r*t)/t}function Om(r){let e=new Date(r);return e.getUTCHours()===0&&e.getUTCMinutes()===0&&e.getUTCSeconds()===0}var Mm=.01;function Fm(r,e){if(typeof e!="string"||!e.trim())return;let t=e.trim(),n=qo();n[r]!==t&&ln({...n,[r]:t})}var Cr=class{constructor(e,t,n){this.coinPoolBaseUrl=e;this.endpoints=t;this.describer=n}coinPoolBaseUrl;endpoints;describer;async describeReceiptTokens(e,t,n){let o=Date.now();M("describeReceiptTokens: START",{chain:e,tokens:t,hasRpcUrl:!!n});let s=ft(e);s&&Fm(s,n);let a=s?Wo(s):null,i=[...new Set(t.filter(E).map(p=>p.toLowerCase()))];if(M("describeReceiptTokens: chain resolved",{hex:s,hasChainInfo:!!a,wanted:i}),!s||!a||i.length===0)return M("describeReceiptTokens: ABORT \u2014 unknown chain or no valid token",{hex:s,hasChainInfo:!!a,wantedCount:i.length}),new Map;M("describeReceiptTokens: on-chain discovery for",i);let l=await Hc(s,i,this.endpoints.morphoApiUrl),u=[...new Map(i.flatMap((p,m)=>{let g=l[m];return M("describeReceiptTokens: discovery result",{token:p,found:!!g,protocol:g?.protocol,type:g?.type,contract:g?.contract}),g?[[p,g]]:[]})).entries()];if(u.length===0)return M("describeReceiptTokens: ABORT \u2014 token is no lending receipt",{ms:Date.now()-o}),new Map;M("describeReceiptTokens: describing markets",{count:u.length,markets:u.map(([p,m])=>({token:p,type:m.type,contract:m.contract}))});let d=await this.describer.describe(s,a,u.map(([,p])=>p));return M("describeReceiptTokens: DONE",{ms:Date.now()-o,overviews:d.map(p=>({name:p.name,protocol:p.protocol,asset:p.asset?.symbol,assetDecimals:p.asset?.decimals,currentApyPercent:p.currentApyPercent,avgApyPercent:p.avgApyPercent,apyChangePercent:p.apyChangePercent,totalSuppliedUsdc:p.totalSuppliedUsdc,apyHistoryPoints:p.apyHistory?.length??0}))}),new Map(d.map((p,m)=>[u[m][0],p]))}async findMarketByReceiptToken(e,t,n){if(M("findMarketByReceiptToken: called",{chain:e,receiptToken:t,hasRpcUrl:!!n}),!E(t))return M("findMarketByReceiptToken: ABORT \u2014 not a valid address",{receiptToken:t}),null;let s=(await this.describeReceiptTokens(e,[t],n)).get(t.toLowerCase())??null;return M("findMarketByReceiptToken: returning",{found:!!s}),s}async getSupplyPositions(e){if(!E(e.address))return[];let t=await Fc(this.coinPoolBaseUrl,e.chains);return(await Promise.all(t.map(o=>this.positionsForChain(o,e.address)))).flat().sort((o,s)=>s.suppliedUsdc-o.suppliedUsdc||(s.avgApyPercent??0)-(o.avgApyPercent??0))}async describeResolvedMarkets(e,t){let n=ft(e),o=n?Wo(n):null;return n&&o?this.describer.describe(n,o,t):[]}async positionsForChain(e,t){let n=Wo(e),o=await zo(this.coinPoolBaseUrl,e);if(!n||o.length===0)return[];let s=await this.describer.readBalances(e,t,o);if(s.length===0)return[];let a=await this.describer.describe(e,n,s.map(l=>l.market)),i=await this.describer.convertToUnderlying(e,s,a.map(l=>l.asset));return a.flatMap((l,c)=>{let u=i[c];return u<Mm?[]:[{...l,suppliedUsdc:$t(u,6),estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:$t(u*l.avgApyPercent/100,2)}]})}};var Vi=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Rr=class{constructor(e){this.coinPoolBaseUrl=e}coinPoolBaseUrl;async listChains(){return Gs(this.coinPoolBaseUrl)}async isSupported(e){return js(this.coinPoolBaseUrl,e)}async getMarkets(e){let t=q(e);return t?zo(this.coinPoolBaseUrl,t):[]}async findMarket(e,t){let n=await this.getMarkets(e);return Mc(n,t)}canSupply(e){return Vi.includes(e.type)}async readReceiptToken(e,t){let n=yn(t).balanceIsUnderlying;try{let o=await Pe(e,[{target:t.token,callData:F({abi:W,functionName:"symbol"})},{target:t.token,callData:F({abi:W,functionName:"decimals"})}]);return{symbol:No(o[0]),decimals:En(o[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}};var yt=class{read;supply;constructor(e={}){let t=e.coinPoolBaseUrl||"https://api.coinpool.app",n={coinPoolBaseUrl:t,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 Xs(n);this.read=new Cr(t,n,o),this.supply=new Rr(t)}async listSupportedChains(){return this.supply.listChains()}async isSupported(e){return this.supply.isSupported(e)}async getMarkets(e){return this.supply.getMarkets(e)}async findMarket(e,t){return this.supply.findMarket(e,t)}canSupply(e){return this.supply.canSupply(e)}async readReceiptToken(e,t){return this.supply.readReceiptToken(e,t)}async describeReceiptTokens(e,t,n){return this.read.describeReceiptTokens(e,t,n)}async findMarketByReceiptToken(e,t,n){return this.read.findMarketByReceiptToken(e,t,n)}async describeResolvedMarkets(e,t){return this.read.describeResolvedMarkets(e,t)}async getMarketOverviews(e){return(await Promise.all(e.chains.map(async n=>this.read.describeResolvedMarkets(n,await this.getMarkets(n))))).flat().sort((n,o)=>(o.avgApyPercent??-1)-(n.avgApyPercent??-1))}async getSupplyPositions(e){return this.read.getSupplyPositions(e)}};var Xo="{market}",Wc="{chain}";var Yc=[{name:"supply_button_label",type:"string",description:`Label template for the per-market "Supply" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Use the exact placeholder "{market}" (do not translate the braces); it is replaced per market with its name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply USDC" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use BOTH exact placeholders (do not translate the braces): "{market}" is replaced with the market name, "{chain}" with the chain name it lives on. Write the connecting words around {chain} in the user's language \u2014 that is why it is a placeholder and not appended for you. English example: "supply USDC to {market} on {chain}". Vietnamese example: "n\u1EA1p USDC v\xE0o {market} tr\xEAn {chain}". Always include BOTH {market} and {chain}. Do NOT write a chain name or a contract address literally \u2014 the exact market identifier is appended automatically.`,required:!1}],Gc=' A clickable "Supply" button is shown below your reply for each market automatically \u2014 do NOT list, number, or repeat those buttons in your text, and do NOT tell the user to tap one; just deliver the list and your suggestion.';function jc(r,e,t){return Bm(r,typeof e.supply_button_label=="string"?e.supply_button_label:"",typeof e.supply_prompt_template=="string"?e.supply_prompt_template:"",t)}function Bm(r,e,t,n){let o=typeof n=="string"?n.trim():"",s=[],a=new Set;for(let i of r){if(s.length>=10)break;let l=i.name?.trim();!l||a.has(l.toLowerCase())||(a.add(l.toLowerCase()),s.push({label:Vc(e,l,"",`Supply ${Xo}`),prompt:Vc(t,l,o,qm(o))+$m(i.contract)}))}return s}function qm(r){return r?`supply USDC to ${Xo} on ${Wc}`:`supply USDC to ${Xo}`}function $m(r){let e=r?.trim();return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?` (market: ${e})`:""}function Vc(r,e,t,n){return(r&&r.includes(Xo)?r:n).split(Xo).join(e).split(Wc).join(t).replace(/\s+/g," ").trim()}var Qs=[{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"]}],Yi=Qs.map(r=>r.label),Wi={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 Kc(r){let e=typeof r=="string"?r.trim():"";if(!e)return{kind:"none"};let t=Ym(e);if(!t)return{kind:"none"};let n=Hm(t);if(n){let s=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>s.has(a.type)}}let o=Wm(t);return o?{kind:"unsupported",label:o,requested:e}:{kind:"unknown",requested:e}}function Hm(r){let e=Qs.filter(t=>t.aliases.includes(r));if(e.length===1)return e[0];if(e.length>1)return null;if(r.length>=3){let t=Qs.filter(n=>n.aliases.some(o=>o.includes(r)||r.includes(o)));if(t.length===1)return t[0];if(t.length>1)return null}return Vm(r)}function Vm(r){let e=null,t=!1;for(let n of Qs)for(let o of n.aliases){let s=zc(o);if(s===0||Math.abs(o.length-r.length)>s)continue;let a=Xc(r,o,s);a>s||(!e||a<e.distance?(e={spec:n,distance:a},t=!1):a===e.distance&&n!==e.spec&&(t=!0))}return e&&!t?e.spec:null}function zc(r){return r.length<=4?0:r.length<=9?2:3}function Wm(r){let e=Wi[r];if(e)return e;if(r.length>=4){let o=new Set(Object.entries(Wi).filter(([s])=>s.length>=4&&(s.includes(r)||r.includes(s))).map(([,s])=>s));if(o.size===1)return[...o][0];if(o.size>1)return null}let t=null,n=!1;for(let[o,s]of Object.entries(Wi)){let a=zc(o);if(a===0||Math.abs(o.length-r.length)>a)continue;let i=Xc(r,o,a);i>a||(!t||i<t.distance?(t={label:s,distance:i},n=!1):i===t.distance&&s!==t.label&&(n=!0))}return t&&!n?t.label:null}function Ym(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function Xc(r,e,t){if(r===e)return 0;if(!r.length)return e.length;if(!e.length)return r.length;let n=new Array(e.length+1),o=Array.from({length:e.length+1},(a,i)=>i),s=new Array(e.length+1);for(let a=1;a<=r.length;a++){s[0]=a;let i=s[0];for(let c=1;c<=e.length;c++){let u=o[c-1]+(r[a-1]===e[c-1]?0:1),d=Math.min(s[c-1]+1,o[c]+1,u);a>1&&c>1&&r[a-1]===e[c-2]&&r[a-2]===e[c-1]&&(d=Math.min(d,n[c-2]+1)),s[c]=d,d<i&&(i=d)}if(i>t)return t+1;let l=n;n=o,o=s,s=l}return o[e.length]}var jm=["apy","score","size"],Qc=5,Jc=40,_r=class extends S{name="get-lending-markets";description='List the LENDING / SUPPLY markets available to deposit into and earn yield on: protocol (Aave v3, Compound v3, Spark, Morpho vaults), market name, chain, total supplied to that market, the live supply APY plus the average over the last week and its daily change, and a 0\u201310 platform score. Ranked by the live protocol APY by default, and filterable to ONE protocol via `protocol`. Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. 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. Each market states its own asset in `suppliedAssetSymbol`, which is usually USDC but need not be. Do NOT use for: what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:`Hex chain ID 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: ${Yi.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-${Jc}. Default ${Qc} \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},...Yc];service;constructor(e){super(),this.service=new yt(e)}async run(e,t){let n=await this.service.listSupportedChains(),o=oe(e.chain,void 0),s=o?null:q(t?.chain),a=o??s;if(a&&!n.includes(a))return{_instructions:`There are no lending markets on ${A(a)}`+(s?", 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:A(a),connectedChainHasNoMarkets:s!==null,marketCount:0,markets:[],chainsWithLendingMarkets:n.map(h=>A(h))};let i=Kc(e.protocol);if(i.kind==="unsupported"||i.kind==="unknown")return this.unsupportedProtocol(i);let l=a?[a]:n,c=zm(e.sort),u=Xm(e.limit),d=await this.service.getMarketOverviews({chains:l}),p=i.kind==="supported"?d.filter(h=>i.matches(h)):d;if(i.kind==="supported"&&p.length===0&&d.length>0)return{_instructions:`There are no ${i.label} lending markets on ${a?A(a):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${i.label} market. Do NOT mention tool names.`,requestedProtocol:i.label,chain:a?A(a):"all",marketCount:0,markets:[],protocolsAvailable:[...new Set(d.map(h=>h.protocol))]};let m=[...p].sort(Km[c]).slice(0,u),g=m.slice(0,10).flatMap(h=>jc([{name:h.name,contract:h.contract}],e,A(h.chain)));return{_instructions:this.instructions(m,c,g.length>0,i.kind==="supported"?i.label:null),...g.length>0?{actionButtons:g}:{},chain:a?A(a):"all",chainsQueried:l.map(h=>A(h)),...i.kind==="supported"?{protocolFilter:i.label}:{},sortedBy:c,marketCount:m.length,totalMarketsAvailable:p.length,markets:m.map(h=>({marketName:h.name,protocol:h.protocol,protocolUrl:h.protocolUrl,chain:A(h.chain),avgApyPercent:h.avgApyPercent,avgApyDays:h.apyHistory.length,currentApyPercent:h.currentApyPercent,apyChangePercent:h.apyChangePercent,totalSuppliedUsdc:h.totalSuppliedUsdc,suppliedAssetSymbol:h.asset.symbol,platformScore:h.platformScore}))}}unsupportedProtocol(e){let t=e.kind==="unsupported",n=t?e.label:`"${e.requested}"`;return{_instructions:`The user asked about ${n}, which has no lending markets here. In their language: tell them plainly that ${n} is ${t?"not supported yet":"not something we have lending markets for"}, then introduce what we DO offer \u2014 name the protocols in \`supportedProtocols\` and offer to list those markets instead. Keep it to one or two short sentences, and make the offer the point rather than the refusal. Do NOT invent ${n} markets, rates or a launch date, and do NOT claim it is coming soon. Do NOT mention tool names.`,requestedProtocol:t?e.label:e.requested,protocolSupported:!1,supportedProtocols:[...Yi],marketCount:0,markets:[]}}instructions(e,t,n=!1,o=null){if(e.length===0)return"No lending markets could be loaded for the chains in `chainsQueried` right now. Say so briefly in the user's language and suggest trying again shortly. Do NOT invent markets, protocols or rates. Do NOT mention tool names.";let s={apy:"ordered by the protocol APY, highest first",score:"ordered by platform score, safest first",size:"ordered by market size, largest first"}[t];return[o?`These are the ${o} lending markets the user can supply to, ${s}. The list is SCOPED to ${o} because that is what they asked about \u2014 present it as such, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${s}.`,"Present them as a NUMBERED list. Each entry starts with `marketName` as a markdown link to that","market's `protocolUrl` in bold \u2014 **[marketName](protocolUrl)** \u2014 so the name opens that market's page on","the protocol.","When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it.",'Under each name put exactly three bullet points, in this order: "Total supplied" = `totalSuppliedUsdc`,','"Protocol APY" = `currentApyPercent` (the live rate), and "Avg APY" = `avgApyPercent` labelled as the',"average over the last `avgApyDays` days. Do NOT add other bullets.","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 \u2014 mention it only when the user","asks which market is safest. A null APY means that rate was unavailable \u2014 say so rather than showing 0.",new Set(e.map(a=>a.chain)).size>1?"The markets span several chains \u2014 put each one's `chain` on the title line, after the linked name, so the user knows where it lives.":"All markets are on one chain \u2014 state the chain name once before the list, not per market.","Close with one short sentence naming the best option for the ranking used and why.","This is information, NOT financial advice \u2014 say so briefly.","Do NOT mention tool names.",n?Gc:""].filter(Boolean).join(" ")}},Km={apy:(r,e)=>(e.currentApyPercent??-1)-(r.currentApyPercent??-1),score:(r,e)=>(e.platformScore??-1)-(r.platformScore??-1),size:(r,e)=>(e.totalSuppliedUsdc??-1)-(r.totalSuppliedUsdc??-1)};function zm(r){let e=typeof r=="string"?r.trim().toLowerCase():"";return jm.includes(e)?e:"apy"}function Xm(r){let e=typeof r=="number"?r:Number(r);return!Number.isFinite(e)||e<1?Qc:Math.min(Math.floor(e),Jc)}var Er=class extends S{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 yt(e)}async run(e,t){let n=Z(e.address,t);if(!E(n))return{error:`"${n}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=oe(e.chain,t),s=await this.service.listSupportedChains();if(o&&!s.includes(o))return{_instructions:`There are no lending markets on ${A(o)}, so the wallet cannot have a supply position there. Tell the user that in their language and name the chains that DO have lending markets (listed in \`chainsWithLendingMarkets\`). Do NOT mention tool names.`,walletAddress:n,chain:A(o),positionCount:0,positions:[],chainsWithLendingMarkets:s.map(l=>A(l))};let a=o?[o]:s,i=await this.service.getSupplyPositions({address:n,chains:a});return{_instructions:this.instructions(i),walletAddress:n,chain:o?A(o):"all",chainsQueried:a.map(l=>A(l)),positionCount:i.length,totals:Qm(i),positions:i.map(l=>({marketName:l.name,protocol:l.protocol,protocolUrl:l.protocolUrl,chain:A(l.chain),suppliedUsdc:l.suppliedUsdc,suppliedAssetSymbol:l.asset.symbol,avgApyPercent:l.avgApyPercent,currentApyPercent:l.currentApyPercent,apyChangePercent:l.apyChangePercent,estimatedAnnualYieldUsdc:l.estimatedAnnualYieldUsdc,marketTotalSuppliedUsdc:l.totalSuppliedUsdc,apyHistory:l.apyHistory,platformScore:l.platformScore}))}}instructions(e){return e.length===0?"The wallet supplies 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 daily samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(e.map(n=>n.chain)).size>1?"The positions span several chains \u2014 group them by the `chain` field, one section per chain.":"All positions are on one chain \u2014 state the chain name once, not per position.","Finish with the total supplied from `totals` \u2014 but ONLY when `totals.mixedAssets` is false; when it is true","the positions are in different assets and cannot be added up, so give no portfolio total and let the","per-position amounts stand. This is information, NOT financial advice.","Do NOT mention tool names."].join(" ")}};function Qm(r){if(new Set(r.map(a=>a.asset.symbol??a.asset.address.toLowerCase())).size>1)return{mixedAssets:!0,suppliedUsdc:null,estimatedAnnualYieldUsdc:null,weightedAvgApyPercent:null};let n=r.reduce((a,i)=>a+i.suppliedUsdc,0),o=r.filter(a=>a.avgApyPercent!==null),s=o.reduce((a,i)=>a+i.suppliedUsdc,0);return{mixedAssets:!1,assetSymbol:r[0]?.asset.symbol??null,suppliedUsdc:Gi(n,6),estimatedAnnualYieldUsdc:Gi(r.reduce((a,i)=>a+(i.estimatedAnnualYieldUsdc??0),0),2),weightedAvgApyPercent:s>0?Gi(o.reduce((a,i)=>a+i.suppliedUsdc*i.avgApyPercent,0)/s,2):null}}function Gi(r,e){let t=10**e;return Math.round(r*t)/t}var Nr=class extends S{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)" hint, pass THAT address verbatim as this argument and ignore the market name in the sentence \u2014 the address identifies the exact market they picked, while a name may match several vaults of the same protocol.`,required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the user names; whether it carries markets is checked at call time. Set it ONLY when the user names a chain; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`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 yt(e),this.moralis=new O(e?.moralis)}async run(e,t){let n=t?.walletAddress;if(!n)return{error:"wallet_not_connected",_instructions:"Supplying moves real funds, so it needs a connected wallet. Ask the user to connect one, in their language. Do NOT render a form and do NOT mention tool names."};let s=oe(e.chain,void 0)??q(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."};let a=await this.service.listSupportedChains();if(!a.includes(s))return{error:"unsupported_chain",chain:A(s),chainsWithLendingMarkets:a.map(b=>A(b)),_instructions:`There are no lending markets on ${A(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 i=Zm(e.market);if(!i)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let l=await this.service.findMarket(s,i);if(l.length===0)return{error:"market_not_found",market:i,chain:A(s),_instructions:`No lending market matching "${i}" exists on ${A(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(l.length>1)return{error:"ambiguous_market",market:i,chain:A(s),candidates:l.map(b=>({marketName:b.name,protocol:b.protocol})),_instructions:`"${i}" matches ${l.length} different markets on ${A(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="`+i+`" and chain for ${A(s)}, plus the localized supply-button templates \u2014 that shows the user each market with its APY, size and score, each with its own Supply button to tap. Write no message of your own before that call.`};let c=l[0];if(!this.service.supply.canSupply(c))return{error:"unsupported_protocol",marketName:c.name,protocol:c.protocol,_instructions:`Supplying to ${c.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let u=await this.describeOne(s,c),d=Jm(u);if(!d)return{error:"asset_unresolved",marketName:c.name,chain:A(s),_instructions:`The asset ${c.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[p,m]=await Promise.all([this.assetBalance(n,s,d.address),this.service.readReceiptToken(s,c)]);if(p&&pn(p.amount,"0")<=0)return{error:"no_asset_balance",marketName:c.name,chain:A(s),assetSymbol:d.symbol,assetBalance:"0",_instructions:`The user has no ${d.symbol} available to supply to ${c.name} on ${A(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 g=eh(e.amount),h=g?Dt(g,d.decimals):null;if(h&&p&&pn(h,p.amount)>0)return{error:"insufficient_asset_balance",marketName:c.name,chain:A(s),assetSymbol:d.symbol,requestedAmount:g,assetBalance:p.amount,_instructions:`The user wants to supply ${g} ${d.symbol} to ${c.name}, but they only hold ${p.amount} ${d.symbol} on ${A(s)} \u2014 not enough. Reply in the user's language using the pattern 'state situation \u2192 ask to choose': first tell them ${g} ${d.symbol} exceeds their balance of ${p.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 f={action:"supply_usdc",chainId:s,chainName:A(s),walletAddress:n,market:{name:c.name,type:c.type,protocol:c.protocol,protocolUrl:u?.protocolUrl??zs(c),contract:c.contract,token:c.token,apyPercent:u?.currentApyPercent??u?.avgApyPercent??null,receiptToken:m},asset:d,...h?{prefillAmount:h}:{},...p?{spendable:p.amount}:{},...p?.usd?{spendableUsd:p.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:f},marketName:c.name,protocol:c.protocol,chain:A(s),apyPercent:f.market.apyPercent,assetSymbol:d.symbol,assetBalance:p?.amount??null,_instructions:this.instructions(c,d.symbol)}}async describeOne(e,t){try{let[n]=await this.service.describeResolvedMarkets(e,[t]);return n??null}catch{return null}}async assetBalance(e,t,n){try{let o=await this.moralis.getWalletTokenBalances({address:e,chain:t,tokenAddresses:[n]});if(!o.success)return null;let s=(o.data?.result??[]).find(i=>(i.token_address||"").toLowerCase()===n.toLowerCase());if(!s?.balance_formatted)return{amount:"0",usd:null};let a=typeof s.usd_value=="number"?String(s.usd_value):null;return{amount:String(s.balance_formatted),usd:a}}catch{return null}}instructions(e,t){return[`The supply action for ${e.name} is ready.`,`In the user's language, invite them to enter the amount of ${t} they want to supply, naming the`,"market and the chain.",`Speak ONLY of the action the USER takes (supplying / depositing ${t}). NEVER say you "opened a form",`,'"opened" anything, or describe any screen, form, window or UI \u2014 phrase it as their next step, not something',"you did.","Do NOT state their balance, the contract address or any figure from the form; it is all on screen already.","Keep it to one or two short sentences. Add a brief note that supplying carries protocol risk and rates","float \u2014 information, not financial advice.","Do NOT mention tool names."].join(" ")}};function Jm(r){let e=r?.asset;return!e?.address||e.address===hn||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function Zm(r){let e=typeof r=="string"?r.trim():"",t=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})\s*[\])]/i.exec(e);if(t)return t[1];let n=/0x[a-fA-F0-9]{40}/.exec(e);return n&&n[0]!==e?n[0]:e}function eh(r){let e=typeof r=="string"?r.trim():typeof r=="number"?String(r):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}var Js="https://ipfs.pantograph.app/ipfs/",Zc=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function bn(r){let e=r?.trim();if(!e)return null;if(/^(https?:\/\/|data:image\/)/i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${Js}${t[1]}`:Zc.test(e)?`${Js}${e}`:null}function eu(r){let e=r?.trim();if(!e)return null;if(/^https?:\/\//i.test(e))return e;let t=e.match(/^ipfs:\/\/(?:ipfs\/)?(.+)$/i);return t?`${Js}${t[1]}`:Zc.test(e)?`${Js}${e}`:null}function tu(r){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(r)}function ji(r){if(!r||typeof r!="object")return;let e=r,t=e.image??e.image_url??e.imageUrl;return typeof t=="string"&&t.trim()?t.trim():void 0}function th(r){if(typeof atob=="function"){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new TextDecoder().decode(t)}if(typeof Buffer<"u")return Buffer.from(r,"base64").toString("utf-8");throw new Error("no base64 decoder available")}function nh(r){let e=r.match(/^data:application\/json([^,]*),(.*)$/is);if(!e)return null;let t=e[1]??"",n=e[2]??"";try{let o=/;base64/i.test(t)?th(n):decodeURIComponent(n);return JSON.parse(o)}catch{try{return JSON.parse(n)}catch{return null}}}function nu(r){let e=r?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=nh(e);return t?bn(ji(t)):null}var rh=12,oh=6e3;async function sh(r,e,t){let n=new Array(r.length),o=0,s=new Array(Math.max(1,Math.min(e,r.length))).fill(0).map(async()=>{for(;o<r.length;){let a=o++;n[a]=await t(r[a],a)}});return await Promise.all(s),n}async function ah(r,e){try{let t=await x.get(r,{timeout:e});if(!t.ok)return null;let n=t.data;if(n&&typeof n=="object")return n;if(typeof n=="string")try{return JSON.parse(n)}catch{return null}return null}catch{return null}}async function ih(r,e){let t=r?.trim();if(!t)return null;if(/^data:/i.test(t))return nu(t);let n=eu(t);if(!n)return null;if(tu(n))return n;let o=await ah(n,e);if(o){let s=bn(ji(o));if(s)return s}return null}async function Zs(r,e,t){if(e.length===0)return[];let n=t?.concurrency??rh,o=t?.timeoutMs??oh,s=await uc(r,e,t?.rpcUrl);return sh(s,n,a=>ih(a,o))}var ru=100,lh=100,Ur="{name}",ou="{chain}",Ir=class extends S{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 n=Z(e.address,t),o=oe(e.chain,t),s=o?[o]:Se(),a=hh(e.contract_address),i=iu(e.collection_name);return a||i?this.listNfts({address:n,chains:s,singleChain:!!o,contract:a,collectionName:i}):this.listCollections({address:n,chains:s,singleChain:!!o,args:e})}async listCollections(e){let{address:t,chains:n,singleChain:o,args:s}=e,a=await Promise.all(n.map(async c=>{let u=await this.service.getWalletNftCollections({address:t,chain:c,limit:ru});return{chain:c,rows:u.success?su(u.data?.result??[]):[],ok:u.success}}));if(o&&!a[0].ok)return{error:"Failed to fetch wallet NFT collections"};let i=a.flatMap(c=>c.rows.map(u=>({name:uh(u),contractAddress:u.token_address,chain:A(c.chain),nftCount:u.count??null})));if(i.length===0)return{_instructions:"The wallet holds no NFT collections"+(o?" on this chain":" on any supported chain")+". Tell the user that plainly in their language. Do NOT mention tool names.",walletAddress:t,collectionCount:0,collections:[]};let l=ph(i,s);return{_instructions:"These are the NFT COLLECTIONS the wallet holds. Ask the user, in their language, which collection they want to see. A clickable button is rendered for each collection below your reply automatically \u2014 do NOT list, number, or repeat the collection names in your text, and do NOT show contract addresses. Keep the reply to one short sentence. Do NOT mention tool names.",walletAddress:t,collectionCount:i.length,collections:i,...l.length>0?{actionButtons:l}:{}}}async listNfts(e){let{address:t,chains:n,singleChain:o,contract:s,collectionName:a}=e,i=await Promise.all(n.map(async m=>{let g=await this.service.getWalletNFTs({address:t,chain:m,limit:ru,...s?{tokenAddresses:[s]}:{}});return{chain:m,rows:g.success?su(g.data?.result??[]):[],ok:g.success}}));if(o&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(m=>m.rows.filter(g=>ch(g,{contract:s,collectionName:a})).map(g=>({chain:m.chain,row:g})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${a??s??""}"`+(o?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||a||l[0].row.token_address,u=await this.resolveOnchainImages(l),d=l.map(({chain:m,row:g},h)=>{let f=dh(g);return{name:f.name,tokenId:f.tokenId,contractAddress:f.contractAddress,image:u[h]??f.image,chain:A(m)}});return{ui:{component:"WalletNftList",props:{walletAddress:t,collectionName:c,nfts:d}},_instructions:`The wallet's NFTs in this collection are shown to the user as an image gallery rendered automatically below your reply \u2014 do NOT list, number, describe, or embed the individual NFTs, their images, or their token ids yourself. Reply with ONE short sentence in the user's language, naming the collection and how many NFTs they hold (e.g. "You hold 5 NFTs in <collection>."). Do NOT mention tool names, UI, galleries, or components.`,walletAddress:t,collectionName:c,nftCount:l.length}}async resolveOnchainImages(e){let t=new Array(e.length).fill(null),n=new Map;e.forEach((o,s)=>{let a=n.get(o.chain)??[];a.push(s),n.set(o.chain,a)});try{await Promise.all([...n.entries()].map(async([o,s])=>{let a=s.map(l=>({contract:e[l].row.token_address,tokenId:e[l].row.token_id})),i=await Zs(o,a);s.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function su(r){return r.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function ch(r,e){if(e.contract)return r.token_address.toLowerCase()===e.contract.toLowerCase();if(e.collectionName){let t=e.collectionName.toLowerCase();return(r.name??"").toLowerCase().includes(t)}return!1}function uh(r){let e=r.name?.trim();if(e)return e;let t=r.token_address??"";return t.length>10?`${t.slice(0,6)}\u2026${t.slice(-4)}`:t}function dh(r){return{name:r.normalized_metadata?.name||r.name||`#${r.token_id}`,tokenId:r.token_id,contractAddress:r.token_address,image:bn(r.normalized_metadata?.image||r.media?.original_media_url)}}function ph(r,e){let t=typeof e.pick_button_label=="string"?e.pick_button_label:"",n=typeof e.pick_prompt_template=="string"?e.pick_prompt_template:"",o=[];for(let s of r){if(o.length>=lh)break;if(!s.contractAddress)continue;let a=typeof s.chain=="string"?s.chain.trim():"",i=a?`show my ${Ur} NFTs on ${ou}`:`show my ${Ur} NFTs`,l=au(n,{[Ur]:s.name,[ou]:a},i);a&&!l.includes(a)&&(l=`${l} (${a})`),o.push({label:mh(t,s.name,Ur),prompt:`${l} (${s.contractAddress})`})}return o}function au(r,e,t){let n=r&&r.includes(Ur)?r:t;for(let[o,s]of Object.entries(e))n=n.split(o).join(s);return n.replace(/\s+/g," ").trim()}function mh(r,e,t){return au(r,{[Ur]:e},t)}function iu(r){if(typeof r!="string")return;let e=r.trim();return e||void 0}function hh(r){let e=iu(r);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var gh="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 S{kind="data";category="nft";llm;constructor(e){super(),this.llm=new re(e??{})}static promptParams(e){return[{name:"prompt",type:"string",description:e,required:!0}]}async run(e){let t=typeof e.prompt=="string"?e.prompt.trim():"";if(!t)return{error:"Missing required parameter: prompt"};let n=await this.askGeminiWithSearch(t);return n?{_instructions:this.presentInstructions+` Reply in the user's language. Format numbers human-readably (e.g. 1.23 ETH, $12.5M). Weave the information into a natural answer \u2014 do NOT add an "AI" heading and do NOT mention tools, AI, or that this came from a web search.`,research:n}:{error:"no_data",_instructions:"Tell the user, in their language, that you could not fetch this NFT information right now and to try again shortly. Do not mention tools."}}async askGeminiWithSearch(e){let t=Date.now();try{return(await this.llm.chat([{role:"system",content:gh,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Lr=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 Dr=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 Ki={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"},zi="amazon.com";function fh(r){return r?r.trim().toLowerCase().split(/[-_]/)[0]:""}function Xi(r){let e=fh(r);return Ki[e]??zi}function ea(r){return`https://${Xi(r)}/s?k=NFC%20Tag`}function ta(r){if(!r)return"";let e=r.trim().toUpperCase().split(/[-_]/),t=e.length>1?e[e.length-1]:e[0];return/^[A-Z]{2}$/.test(t)?t:""}var yh=720*60*1e3,lu=new Map,cu=3;function bh(r){return[`A user in country "${r}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${cu} 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 wh(r){if(!r)return[];let e=r.indexOf("["),t=r.lastIndexOf("]");if(e===-1||t===-1||t<=e)return[];let n;try{n=JSON.parse(r.slice(e,t+1))}catch{return[]}if(!Array.isArray(n))return[];let o=[],s=new Set;for(let a of n){if(!a||typeof a!="object")continue;let i=a.label,l=a.url;if(typeof i!="string"||!i.trim()||typeof l!="string"||!/^https:\/\/[^\s]+\.[^\s]+/i.test(l.trim()))continue;let c=l.trim().toLowerCase();if(!s.has(c)&&(s.add(c),o.push({label:i.trim(),url:l.trim()}),o.length>=cu))break}return o}async function Qi(r,e){let t=ta(r);if(!t||!e)return null;let n=lu.get(t);if(n&&n.expires>Date.now())return n.links;let o=Date.now(),s=[{role:"user",content:bh(t),timestamp:o}];try{let a=await e.chat(s,void 0,{googleSearch:!0,maxRetries:1}),i=wh(a.text);if(i.length)return lu.set(t,{links:i,expires:Date.now()+yh}),i}catch{}return null}async function Or(r){let e=await Qi(r.country,r.llm);return e&&e.length?e:[{label:"Amazon",url:ea(r.language)}]}function kh(r){return r.length<=1?r.length===1?`[${r[0].label}](${r[0].url})`:"":r.map((e,t)=>`${t+1}. [${e.label}](${e.url})`).join(`
26
26
  `)}var uu=["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(`
27
27
  `),Mr=class extends S{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 re(e))}async run(e,t){let n=typeof e.language=="string"&&e.language.trim()?e.language.trim():void 0,o=await Or({country:t?.country,language:n,llm:this.llm}),s=kh(o),a=o.length>1;return{reference:uu,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)):
28
28
  ${s}