keyring-agent-core 0.3.1 → 0.3.2
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 +2 -2
- package/dist/index.native.js +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var bd=Object.create;var xs=Object.defineProperty;var wd=Object.getOwnPropertyDescriptor;var kd=Object.getOwnPropertyNames;var vd=Object.getPrototypeOf,Td=Object.prototype.hasOwnProperty;var Ad=(r,e)=>{for(var t in e)xs(r,t,{get:e[t],enumerable:!0})},Il=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kd(e))!Td.call(r,o)&&o!==t&&xs(r,o,{get:()=>e[o],enumerable:!(n=wd(e,o))||n.enumerable});return r};var Pd=(r,e,t)=>(t=r!=null?bd(vd(r)):{},Il(e||!r||!r.__esModule?xs(t,"default",{value:r,enumerable:!0}):t,r)),Sd=r=>Il(xs({},"__esModule",{value:!0}),r);var If={};Ad(If,{AI_AGENT_TOOL_NAMES:()=>Ha,AbortError:()=>Ht,AgentCore:()=>za,ApproveTokenTool:()=>Ao,BaseNftAiTool:()=>dt,BaseSwapService:()=>Jt,BaseTool:()=>S,BaseWalletActionTool:()=>He,BuyTokenTool:()=>Po,ChatHistory:()=>Co,DEFAULT_CHAIN:()=>Me,DEFAULT_PROVIDER:()=>ps,DEFAULT_RPC_BY_CHAIN:()=>De,DebridgeAdapter:()=>Jr,EstimatePoolYieldTool:()=>lo,GeminiProvider:()=>ie,GeminiSearchAiTool:()=>Kr,HEX_TO_PANTOGRAPH:()=>Hc,KnowledgeBase:()=>Eo,LendingMarketDetailTool:()=>Mr,LendingMarketsTool:()=>Or,LendingReadService:()=>Lr,LendingService:()=>ze,LendingSupplyService:()=>Dr,MULTICALL3_ADDRESS:()=>X,ManageLiquidityRedirectTool:()=>uo,MoralisService:()=>O,NFC_AGENT_TOOL_NAMES:()=>$a,NFC_AMAZON_DEFAULT_DOMAIN:()=>ml,NFC_AMAZON_DOMAINS:()=>pl,NFTContractInfoTool:()=>Hr,NFTMetadataTool:()=>Vr,NFT_AGENT_TOOL_NAMES:()=>qa,NfcBuyTool:()=>Gr,NfcInfoTool:()=>Yr,NoFormTool:()=>gs,OpenAddLiquidityFormTool:()=>ao,OpenSupplyFormTool:()=>Br,POOL_AGENT_TOOL_NAMES:()=>Va,PantographService:()=>le,PoolByAddressTool:()=>so,PoolDetailTool:()=>ro,PoolFallbackAiTool:()=>jr,PoolPriceRangesTool:()=>co,PoolSearchTool:()=>oo,PoolService:()=>Pe,PreviewAddLiquidityTool:()=>io,PublicClient:()=>wn,RelayAdapter:()=>Zr,Router:()=>_o,SUPPLIABLE_TYPES:()=>sl,SUPPORTED_CHAINS:()=>cr,SUPPORTED_CHAINS_LABEL:()=>dr,SWAP_PROVIDER_CONFIG:()=>Na,SendNativeTool:()=>vo,SendNftTool:()=>xo,SendTokenTool:()=>To,Subagent:()=>oe,SubgraphAddPoolTool:()=>bo,SubgraphCoinPoolPairsTool:()=>yo,SubgraphPoolByAddressTool:()=>ho,SubgraphPoolByPositionIdTool:()=>go,SubgraphPoolSearchTool:()=>po,SubgraphPositionDetailTool:()=>fo,SubgraphTrendingPoolsTool:()=>mo,Summarizer:()=>Ro,SwapServiceFactory:()=>Rn,SwapTokenTool:()=>So,Synthesizer:()=>No,TOKEN_AGENT_TOOL_NAMES:()=>Ba,TRANSFER_TOPIC:()=>Qu,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Vc,TokenAnalyticsTool:()=>wr,TokenHoldersTool:()=>br,TokenInfoTool:()=>yr,TokenScoreTool:()=>kr,ToolRegistry:()=>lr,TopGainersTool:()=>Tr,TopPoolsTool:()=>no,TransactionByHashTool:()=>Ir,TrendingTokensTool:()=>vr,UNISWAP_CHAIN_SLUG:()=>hs,UNRESOLVED_ASSET:()=>Pn,UpstashKnowledgeBase:()=>tn,WALLET_ACTION_AGENT_TOOL_NAMES:()=>Wa,WALLET_AGENT_TOOL_NAMES:()=>Fa,WalletApprovalsTool:()=>Er,WalletDefiPositionsTool:()=>_r,WalletDefiProtocolPositionsTool:()=>Nr,WalletHistoryTool:()=>Pr,WalletLendingPositionsTool:()=>Fr,WalletNFTsTool:()=>$r,WalletNftTransfersTool:()=>xr,WalletPnlSummaryTool:()=>Cr,WalletPnlTool:()=>Rr,WalletTokenBalancesTool:()=>Ar,WalletTokenTransfersTool:()=>Sr,WebsiteTrustKeyringAgent:()=>Xa,ZERO_ADDRESS:()=>G,amazonDomainForLanguage:()=>hl,apiClient:()=>x,applyYieldConversions:()=>ca,buildChallenge:()=>$i,buildRangePresets:()=>wl,buildUniswapPoolUrl:()=>Le,call:()=>at,chains:()=>mn,checksumAddress:()=>Ln,clampTick:()=>ht,clearPublicClientCache:()=>Ys,completeX402:()=>Hi,configureSupportedChains:()=>Js,convertSusdsShares:()=>An,createAiAgent:()=>vs,createDefaultSubagents:()=>Ya,createNfcAgent:()=>ks,createNftAgent:()=>ws,createPoolAgent:()=>Ts,createPublicClient:()=>qt,createTokenAgent:()=>bs,createTransport:()=>Ft,createWalletActionAgent:()=>As,createWalletAgent:()=>ys,createX402SignatureProvider:()=>Wi,decodeAbiParameters:()=>ke,decodeErrorResult:()=>Bn,decodeFunctionData:()=>gi,decodeFunctionResult:()=>rt,displayFromChallenge:()=>Uc,effectivePriceUSD:()=>ls,encodeAbiParameters:()=>On,encodeErrorResult:()=>ui,encodeFunctionData:()=>F,encodeSignedHeader:()=>Vi,erc1155Abi:()=>Bs,erc20Abi:()=>H,erc20Abi_bytes32:()=>jn,erc721Abi:()=>zn,estimateGas:()=>Gn,ethCallAt:()=>tu,ethCallByChain:()=>Lm,fallback:()=>Bt,fetchTopMarketplaces:()=>gl,getAbiItem:()=>Ut,getAddress:()=>oi,getAffiliateFee:()=>Qr,getBalance:()=>Hn,getBlock:()=>Kn,getBlockNumber:()=>qn,getChain:()=>vt,getChainContractAddress:()=>Vo,getChainId:()=>$n,getChainMeta:()=>ge,getCode:()=>Lt,getDefaultRpcUrl:()=>_i,getGasPrice:()=>Yn,getGatewayAddress:()=>Ua,getGatewayChains:()=>La,getNativeTokenInfo:()=>eo,getPositionManagerAddress:()=>Da,getProviderByChain:()=>_a,getPublicClient:()=>xe,getRevertReason:()=>Bo,getRpcOverrides:()=>Ko,getStorageAt:()=>Vn,getTokenPriceUSD:()=>sa,getTransactionCount:()=>Wn,http:()=>Ke,ingestKnowledgeBase:()=>yd,isAbortError:()=>vn,isAddress:()=>_,isAddressEqual:()=>si,isPaymentRequired:()=>Dp,isShareBasedProtocol:()=>la,isShareBasedYieldToken:()=>Kc,isSupplyChain:()=>ha,listCandidateChains:()=>ol,listSupplyChains:()=>ma,multicall:()=>sr,multicall3Abi:()=>Ge,multicallRaw:()=>Ot,nfcAmazonSearchUrl:()=>Pa,normaliseCountry:()=>Sa,normalizePriceRangeToPool:()=>Xr,parseAbi:()=>wi,parseAbiItem:()=>Ms,parseAbiParameters:()=>$o,planYieldTokenConversions:()=>tl,priceToTick:()=>Cn,protocolLabelFor:()=>Be,psm3For:()=>ia,readContract:()=>it,readPaymentError:()=>Nc,readPaymentRequired:()=>zs,readReceipt:()=>Ic,registerMaybeNoForm:()=>Ma,requestWithX402:()=>Lp,resolveNfcShopLinks:()=>Wr,resolveRpcUrl:()=>bn,resolveRpcUrls:()=>yn,resolveTokenPriceUSD:()=>zc,roundTickToSpacing:()=>mt,rpcCall:()=>eu,setRpcOverrides:()=>fn,swapServiceFactory:()=>gt,tickToPrice:()=>Qe,toEventSelector:()=>ii,toFunctionSelector:()=>kt,toPantographChain:()=>Zp,valueYieldTokens:()=>ua});module.exports=Sd(If);var Ll=Pd(require("axios"));var Ul="0.3.
|
|
1
|
+
"use strict";var bd=Object.create;var xs=Object.defineProperty;var wd=Object.getOwnPropertyDescriptor;var kd=Object.getOwnPropertyNames;var vd=Object.getPrototypeOf,Td=Object.prototype.hasOwnProperty;var Ad=(r,e)=>{for(var t in e)xs(r,t,{get:e[t],enumerable:!0})},Il=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of kd(e))!Td.call(r,o)&&o!==t&&xs(r,o,{get:()=>e[o],enumerable:!(n=wd(e,o))||n.enumerable});return r};var Pd=(r,e,t)=>(t=r!=null?bd(vd(r)):{},Il(e||!r||!r.__esModule?xs(t,"default",{value:r,enumerable:!0}):t,r)),Sd=r=>Il(xs({},"__esModule",{value:!0}),r);var If={};Ad(If,{AI_AGENT_TOOL_NAMES:()=>Ha,AbortError:()=>Ht,AgentCore:()=>za,ApproveTokenTool:()=>Ao,BaseNftAiTool:()=>dt,BaseSwapService:()=>Jt,BaseTool:()=>S,BaseWalletActionTool:()=>He,BuyTokenTool:()=>Po,ChatHistory:()=>Co,DEFAULT_CHAIN:()=>Me,DEFAULT_PROVIDER:()=>ps,DEFAULT_RPC_BY_CHAIN:()=>De,DebridgeAdapter:()=>Jr,EstimatePoolYieldTool:()=>lo,GeminiProvider:()=>ie,GeminiSearchAiTool:()=>Kr,HEX_TO_PANTOGRAPH:()=>Hc,KnowledgeBase:()=>Eo,LendingMarketDetailTool:()=>Mr,LendingMarketsTool:()=>Or,LendingReadService:()=>Lr,LendingService:()=>ze,LendingSupplyService:()=>Dr,MULTICALL3_ADDRESS:()=>X,ManageLiquidityRedirectTool:()=>uo,MoralisService:()=>O,NFC_AGENT_TOOL_NAMES:()=>$a,NFC_AMAZON_DEFAULT_DOMAIN:()=>ml,NFC_AMAZON_DOMAINS:()=>pl,NFTContractInfoTool:()=>Hr,NFTMetadataTool:()=>Vr,NFT_AGENT_TOOL_NAMES:()=>qa,NfcBuyTool:()=>Gr,NfcInfoTool:()=>Yr,NoFormTool:()=>gs,OpenAddLiquidityFormTool:()=>ao,OpenSupplyFormTool:()=>Br,POOL_AGENT_TOOL_NAMES:()=>Va,PantographService:()=>le,PoolByAddressTool:()=>so,PoolDetailTool:()=>ro,PoolFallbackAiTool:()=>jr,PoolPriceRangesTool:()=>co,PoolSearchTool:()=>oo,PoolService:()=>Pe,PreviewAddLiquidityTool:()=>io,PublicClient:()=>wn,RelayAdapter:()=>Zr,Router:()=>_o,SUPPLIABLE_TYPES:()=>sl,SUPPORTED_CHAINS:()=>cr,SUPPORTED_CHAINS_LABEL:()=>dr,SWAP_PROVIDER_CONFIG:()=>Na,SendNativeTool:()=>vo,SendNftTool:()=>xo,SendTokenTool:()=>To,Subagent:()=>oe,SubgraphAddPoolTool:()=>bo,SubgraphCoinPoolPairsTool:()=>yo,SubgraphPoolByAddressTool:()=>ho,SubgraphPoolByPositionIdTool:()=>go,SubgraphPoolSearchTool:()=>po,SubgraphPositionDetailTool:()=>fo,SubgraphTrendingPoolsTool:()=>mo,Summarizer:()=>Ro,SwapServiceFactory:()=>Rn,SwapTokenTool:()=>So,Synthesizer:()=>No,TOKEN_AGENT_TOOL_NAMES:()=>Ba,TRANSFER_TOPIC:()=>Qu,TRENDING_DEFAULT_BY_HEX_CHAIN:()=>Vc,TokenAnalyticsTool:()=>wr,TokenHoldersTool:()=>br,TokenInfoTool:()=>yr,TokenScoreTool:()=>kr,ToolRegistry:()=>lr,TopGainersTool:()=>Tr,TopPoolsTool:()=>no,TransactionByHashTool:()=>Ir,TrendingTokensTool:()=>vr,UNISWAP_CHAIN_SLUG:()=>hs,UNRESOLVED_ASSET:()=>Pn,UpstashKnowledgeBase:()=>tn,WALLET_ACTION_AGENT_TOOL_NAMES:()=>Wa,WALLET_AGENT_TOOL_NAMES:()=>Fa,WalletApprovalsTool:()=>Er,WalletDefiPositionsTool:()=>_r,WalletDefiProtocolPositionsTool:()=>Nr,WalletHistoryTool:()=>Pr,WalletLendingPositionsTool:()=>Fr,WalletNFTsTool:()=>$r,WalletNftTransfersTool:()=>xr,WalletPnlSummaryTool:()=>Cr,WalletPnlTool:()=>Rr,WalletTokenBalancesTool:()=>Ar,WalletTokenTransfersTool:()=>Sr,WebsiteTrustKeyringAgent:()=>Xa,ZERO_ADDRESS:()=>G,amazonDomainForLanguage:()=>hl,apiClient:()=>x,applyYieldConversions:()=>ca,buildChallenge:()=>$i,buildRangePresets:()=>wl,buildUniswapPoolUrl:()=>Le,call:()=>at,chains:()=>mn,checksumAddress:()=>Ln,clampTick:()=>ht,clearPublicClientCache:()=>Ys,completeX402:()=>Hi,configureSupportedChains:()=>Js,convertSusdsShares:()=>An,createAiAgent:()=>vs,createDefaultSubagents:()=>Ya,createNfcAgent:()=>ks,createNftAgent:()=>ws,createPoolAgent:()=>Ts,createPublicClient:()=>qt,createTokenAgent:()=>bs,createTransport:()=>Ft,createWalletActionAgent:()=>As,createWalletAgent:()=>ys,createX402SignatureProvider:()=>Wi,decodeAbiParameters:()=>ke,decodeErrorResult:()=>Bn,decodeFunctionData:()=>gi,decodeFunctionResult:()=>rt,displayFromChallenge:()=>Uc,effectivePriceUSD:()=>ls,encodeAbiParameters:()=>On,encodeErrorResult:()=>ui,encodeFunctionData:()=>F,encodeSignedHeader:()=>Vi,erc1155Abi:()=>Bs,erc20Abi:()=>H,erc20Abi_bytes32:()=>jn,erc721Abi:()=>zn,estimateGas:()=>Gn,ethCallAt:()=>tu,ethCallByChain:()=>Lm,fallback:()=>Bt,fetchTopMarketplaces:()=>gl,getAbiItem:()=>Ut,getAddress:()=>oi,getAffiliateFee:()=>Qr,getBalance:()=>Hn,getBlock:()=>Kn,getBlockNumber:()=>qn,getChain:()=>vt,getChainContractAddress:()=>Vo,getChainId:()=>$n,getChainMeta:()=>ge,getCode:()=>Lt,getDefaultRpcUrl:()=>_i,getGasPrice:()=>Yn,getGatewayAddress:()=>Ua,getGatewayChains:()=>La,getNativeTokenInfo:()=>eo,getPositionManagerAddress:()=>Da,getProviderByChain:()=>_a,getPublicClient:()=>xe,getRevertReason:()=>Bo,getRpcOverrides:()=>Ko,getStorageAt:()=>Vn,getTokenPriceUSD:()=>sa,getTransactionCount:()=>Wn,http:()=>Ke,ingestKnowledgeBase:()=>yd,isAbortError:()=>vn,isAddress:()=>_,isAddressEqual:()=>si,isPaymentRequired:()=>Dp,isShareBasedProtocol:()=>la,isShareBasedYieldToken:()=>Kc,isSupplyChain:()=>ha,listCandidateChains:()=>ol,listSupplyChains:()=>ma,multicall:()=>sr,multicall3Abi:()=>Ge,multicallRaw:()=>Ot,nfcAmazonSearchUrl:()=>Pa,normaliseCountry:()=>Sa,normalizePriceRangeToPool:()=>Xr,parseAbi:()=>wi,parseAbiItem:()=>Ms,parseAbiParameters:()=>$o,planYieldTokenConversions:()=>tl,priceToTick:()=>Cn,protocolLabelFor:()=>Be,psm3For:()=>ia,readContract:()=>it,readPaymentError:()=>Nc,readPaymentRequired:()=>zs,readReceipt:()=>Ic,registerMaybeNoForm:()=>Ma,requestWithX402:()=>Lp,resolveNfcShopLinks:()=>Wr,resolveRpcUrl:()=>bn,resolveRpcUrls:()=>yn,resolveTokenPriceUSD:()=>zc,roundTickToSpacing:()=>mt,rpcCall:()=>eu,setRpcOverrides:()=>fn,swapServiceFactory:()=>gt,tickToPrice:()=>Qe,toEventSelector:()=>ii,toFunctionSelector:()=>kt,toPantographChain:()=>Zp,valueYieldTokens:()=>ua});module.exports=Sd(If);var Ll=Pd(require("axios"));var Ul="0.3.2";var Cd=`keyring-agent-core/${Ul} (Keyring Chatbot Agent; +https://keyring.app)`,Ja=null;function Dl(r){Ja=r}var Rd=["payment-signature","x-payment"];function Ed(r){return r?Object.keys(r).some(e=>Rd.includes(e.toLowerCase())):!1}var Ol;function Do(r){Ol=r}var _d=3e4,Nd=typeof process<"u"&&process.versions?.node!=null,Za=class{instance;constructor(e={}){this.instance=Ll.default.create({baseURL:e.baseURL,timeout:e.timeout??_d,validateStatus:()=>!0,headers:{Accept:"application/json",...Nd?{"User-Agent":e.userAgent??Cd}:{},...e.headers}})}async request(e,t,n,o={}){let s=o.signal??Ol,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&&Ja&&!Ed(o.headers)){let c=await Ja(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 Za;function I(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 Id(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??Id(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 Ml(this,e)}};function Ml(r,e){if(e?.(r))return r;let t=r&&typeof r=="object"?r.cause:void 0;return t!=null?Ml(t,e):e?null:r}var Ct=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."]})}},Cs=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}`]})}},Rs=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}`]})}},We=class extends B{name="InvalidAbiValueError";constructor({type:e,value:t,reason:n}){super(`Invalid value for ABI type "${e}".`,{metaMessages:[`Value: ${Fl(t)}`,`Reason: ${n}`]})}},Es=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}`]})}},Nn=class extends B{name="InvalidAddressError";constructor(e){super(`Address "${Fl(e)}" is invalid.`,{metaMessages:["An address must be 0x-prefixed and exactly 20 bytes (40 hex characters)."]})}};function Fl(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 _s=class extends B{name="AbiEncodingBytesSizeMismatchError";constructor({expectedSize:e,value:t}){super(`Size of bytes "${t}" does not match expected size of bytes${e}.`)}},Rt=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."]})}},Ns=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}},In=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."]})}},Is=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."]})}},Et=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 Ud=/^0x[0-9a-fA-F]*$/;function ln(r,{strict:e=!0}={}){return typeof r!="string"?!1:e?Ud.test(r):r.startsWith("0x")}function nt(r){return r.startsWith("0x")||r.startsWith("0X")?r.slice(2):r}function Oo(r){return typeof r=="string"?Math.ceil(nt(r).length/2):r.length}function cn(r,e,t){let n=nt(r),o=(e??0)*2,s=t===void 0?n.length:t*2;return`0x${n.slice(o,s)}`}function Us(r){return`0x${r.map(nt).join("")}`}function un(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 _t(r){let e=nt(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 wt(r){let e="";for(let t of r)e+=t.toString(16).padStart(2,"0");return`0x${e}`}function ei(r){return new TextEncoder().encode(r)}function ti(r){return new TextDecoder().decode(r)}function Se(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 ni(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 ri(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 dn(r){let e=1n<<256n,t=(r%e+e)%e;return _t(t.toString(16).padStart(64,"0"))}function Un(r,{signed:e=!1}={}){let t=BigInt(wt(r));if(!e)return t;let n=BigInt(r.length*8);return t>=1n<<n-1n?t-(1n<<n):t}function Ye(r,{signed:e=!1}={}){return nt(r)?Un(_t(r),{signed:e}):0n}function Ls(r,e={}){return Number(Ye(r,e))}var Bl=require("js-sha3");var Ld=/^0x[0-9a-fA-F]{40}$/;function _(r){return typeof r=="string"&&Ld.test(r)}function Ln(r){let e=nt(r).toLowerCase(),t=(0,Bl.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 oi(r){if(!_(r))throw new Error(`Address "${r}" is invalid.`);return Ln(r)}function si(r,e){return _(r)&&_(e)&&r.toLowerCase()===e.toLowerCase()}var ai=require("js-sha3");function ql(r){return`0x${(0,ai.keccak_256)(new TextEncoder().encode(r))}`}function Nt(r){let e=r.match(/^(.*)\[(\d+)?\]$/);return e?[e[2]?Number(e[2]):null,e[1]]:void 0}function It(r){return r.replace(/^uint(\[|$)/,"uint256$1").replace(/^int(\[|$)/,"int256$1").replace(/^byte(\[|$)/,"bytes1$1")}function Mo(r){let e=It(r.type);return e==="tuple"||e.startsWith("tuple[")?`(${(r.components??[]).map(Mo).join(",")})${e.slice(5)}`:e}function Dn(r){return`${r.name??""}(${(r.inputs??[]).map(Mo).join(",")})`}function kt(r){let e=typeof r=="string"?r:Dn(r);return`0x${(0,ai.keccak_256)(new TextEncoder().encode(e)).slice(0,8)}`}function ii(r){let e=typeof r=="string"?r:Dn(r);return ql(e)}function $l(r,e){let t=It(e.type),n=Nt(t);if(n){let[o,s]=n;return!Array.isArray(r)||o!==null&&r.length!==o?!1:r.every(a=>$l(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 Ut({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=>kt(i)===e.toLowerCase());if(e.includes("("))return s.find(i=>Dn(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)=>$l(t[u],c))})??a[0]}function pn(r){let e=Ut(r);if(!e)throw new Is({name:r.name,type:r.type??"function"});return e}function Hl(r){let e=new Uint8Array(Math.ceil(r.length/32)*32);return e.set(r),{dynamic:!0,encoded:un([dn(BigInt(r.length)),e])}}function Vl(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 Ct(r);return n}function Wl(r,e){if(typeof r=="bigint")return r;if(typeof r=="number"){if(!Number.isInteger(r))throw new We({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 We({type:e,value:r,reason:"string is not a valid integer"})}throw new We({type:e,value:r,reason:"expected a bigint, number or numeric string"})}function Yl(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 Es({type:n,value:r,min:s,max:o})}function Gl(r,e){if(r instanceof Uint8Array)return r;if(typeof r=="string"){if(!ln(r))throw new We({type:e,value:r,reason:"expected 0x-prefixed hex"});return _t(r)}throw new We({type:e,value:r,reason:"expected a hex string or Uint8Array"})}function li(r,e){let t=Nt(r.type);if(t){let[o,s]=t;if(!Array.isArray(e))throw new We({type:r.type,value:e,reason:"expected an array"});return Dd({...r,type:s},e,o,r.type)}if(r.type==="tuple")return Od(r,e);let n=It(r.type);if(n==="address"){if(!_(e))throw new Nn(e);return{dynamic:!1,encoded:ni(_t(nt(e).toLowerCase()))}}if(n==="bool"){if(typeof e!="boolean")throw new We({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=Wl(e,n);return Yl(o,{bits:Vl(n,"uint"),signed:!1,type:n}),{dynamic:!1,encoded:dn(o)}}if(/^int\d*$/.test(n)){let o=Wl(e,n);return Yl(o,{bits:Vl(n,"int"),signed:!0,type:n}),o<0n&&(o+=1n<<256n),{dynamic:!1,encoded:dn(o)}}if(/^bytes\d+$/.test(n)){let o=Number(n.slice(5));if(o<1||o>32)throw new Ct(r.type);let s=Gl(e,n);if(s.length!==o)throw new _s({expectedSize:o,value:String(e)});return{dynamic:!1,encoded:ri(s)}}if(n==="bytes")return Hl(Gl(e,n));if(n==="string"){if(typeof e!="string"&&!(e instanceof Uint8Array))throw new We({type:n,value:e,reason:"expected a string"});return Hl(typeof e=="string"?ei(e):e)}throw new Ct(r.type)}function ci(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(dn(BigInt(e+o))),n.push(a),o+=a.length):t.push(a);return un([...t,...n])}function Dd(r,e,t,n){let o=t===null;if(!o&&e.length!==t)throw new Rs({expectedLength:t,givenLength:e.length,type:n});let s=!1,a=[];for(let i of e){let l=li(r,i);l.dynamic&&(s=!0),a.push(l)}if(o||s){let i=ci(a);if(!o)return{dynamic:!0,encoded:i};let l=dn(BigInt(a.length));return{dynamic:!0,encoded:a.length>0?un([l,i]):l}}return{dynamic:!1,encoded:un(a.map(i=>i.encoded))}}function Od(r,e){let t=r.components??[],n=!1,o=[];for(let s=0;s<t.length;s++){let a=t[s],i=li(a,Array.isArray(e)?e[s]:e[a.name??""]);i.dynamic&&(n=!0),o.push(i)}return{dynamic:n,encoded:n?ci(o):un(o.map(s=>s.encoded))}}function On(r,e){if(r.length!==e.length)throw new Cs({expectedLength:r.length,givenLength:e.length});return r.length===0?"0x":wt(ci(r.map((t,n)=>li(t,e[n]))))}function F({abi:r,functionName:e,args:t=[]}){let n=pn({abi:r,name:e,args:t,type:"function"}),o=kt(n),s=n.inputs??[];return s.length===0?o:Us([o,On(s,t)])}function ui({abi:r,errorName:e,args:t=[]}){let n=pn({abi:r,name:e,args:t,type:"error"}),o=n.inputs??[],s=kt(n);return o.length===0?s:Us([s,On(o,t)])}function Md(r){let e=r.replace(/^u?int/,"");return e?Number(e):256}function Fo(r,e){if(e<0||e+32>r.length)throw new In({position:e,length:r.length});return r.subarray(e,e+32)}function mi(r,e){let t=Un(Fo(r,e));if(t>BigInt(r.length))throw new In({position:Number(t),length:r.length});return Number(t)}function di(r){let e=Nt(r.type);if(e){let[n,o]=e;return n===null||di({...r,type:o})}if(r.type==="tuple")return(r.components??[]).some(di);let t=It(r.type);return t==="bytes"||t==="string"}function pi(r){let e=Nt(r.type);if(e){let[t,n]=e;return t===null?32:t*pi({...r,type:n})}return r.type==="tuple"?(r.components??[]).reduce((t,n)=>t+pi(n),0):32}function hi(r,e,t){let n=[],o=e;for(let s of t)di(s)?(n.push(Kl(r,e+mi(r,o),s)),o+=32):(n.push(Kl(r,o,s)),o+=pi(s));return n}function Fd(r,e,t,n){let o=n===null?mi(r,e):n,s=n===null?e+32:e;return hi(r,s,new Array(o).fill(t))}function Bd(r,e,t){let n=t.components??[],o=hi(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 Kl(r,e,t){let n=Nt(t.type);if(n){let[s,a]=n;return Fd(r,e,{...t,type:a},s)}if(t.type==="tuple")return Bd(r,e,t);let o=It(t.type);if(o==="address")return Ln(wt(Fo(r,e).subarray(12)));if(o==="bool")return Un(Fo(r,e))!==0n;if(/^u?int\d*$/.test(o)){let s=o.startsWith("int"),a=Un(Fo(r,e),{signed:s});return Md(o)>48?a:Number(a)}if(/^bytes\d+$/.test(o)){let s=Number(o.slice(5));return wt(Fo(r,e).subarray(0,s))}if(o==="bytes"||o==="string"){let s=mi(r,e),a=e+32;if(a+s>r.length)throw new In({position:a+s,length:r.length});let i=r.subarray(a,a+s);return o==="bytes"?wt(i):ti(i)}throw new Ct(t.type)}function ke(r,e){let t=typeof e=="string"?_t(e):e;if(t.length===0){if(r.length>0)throw new Rt;return[]}if(t.length<32)throw new Ns({data:typeof e=="string"?e:wt(e),params:r,size:t.length});return hi(t,0,r)}function j(r){if(!r)return null;try{let[e]=ke([{type:"uint256"}],r);return e}catch{return null}}function Y(r){if(!r)return null;try{let[e]=ke([{type:"address"}],r),t=e;return/^0x0{40}$/i.test(t)?null:t}catch{return null}}function Mn(r){if(!r)return null;try{let[e]=ke([{type:"string"}],r),t=jl(e);if(t)return t}catch{}try{let[e]=ke([{type:"bytes32"}],r);return Os(e)}catch{return null}}function Fn(r){return Ds(j(r))}function Ds(r){let e=typeof r=="bigint"?Number(r):typeof r=="number"?r:NaN;return Number.isFinite(e)&&e>=0&&e<=36?e:null}function Os(r){return typeof r!="string"||!r.startsWith("0x")?null:jl(Buffer.from(r.slice(2),"hex").toString("utf8"))||null}function jl(r){return r.replace(/[^\x20-\x7e]/g,"").trim()}function rt({abi:r,functionName:e,args:t,data:n}){let s=pn({abi:r,name:e,args:t,type:"function"}).outputs??[],a=ke(s,n);if(a.length!==0)return a.length===1?a[0]:a}function gi({abi:r,data:e}){let t=cn(e,0,4),n=pn({abi:r,name:t,type:"function"}),o=n.inputs??[];return{functionName:n.name,args:o.length===0||Oo(e)<=4?[]:ke(o,cn(e,4))}}var zl={type:"error",name:"Error",inputs:[{name:"message",type:"string"}]},Xl={type:"error",name:"Panic",inputs:[{name:"reason",type:"uint256"}]},Ql={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 Bn({abi:r=[],data:e}){let t=cn(e,0,4);if(Oo(e)<4)throw new Error(`Cannot decode error result: "${e}" is too short.`);let n=[...r,zl,Xl],o=Ut({abi:n,name:t,type:"error"})??n.find(a=>(a.type??"")==="error"&&kt(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?ke(s,cn(e,4)):void 0}}function Bo({abi:r,data:e}){if(!(!e||e==="0x"))try{let{errorName:t,args:n}=Bn({abi:r,data:e});if(t==="Error")return String(n?.[0]??"");if(t==="Panic"){let o=Number(n?.[0]??0);return Ql[o]??`Panic code ${o}.`}return!n||n.length===0?t:`${t}(${n.map(o=>String(o)).join(", ")})`}catch{return}}var qd=new Set(["pure","view","nonpayable","payable"]),$d=new Set(["external","public","internal","private","calldata","memory","storage"]);function yi(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 Et(r,"Unbalanced parentheses.")}function Zl(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 Hd(r){let e=r.match(/^((?:\[\d*\])*)([\s\S]*)$/);return{suffix:e?.[1]??"",rest:(e?.[2]??"").trim()}}function Jl(r,e){let t=!1,n;for(let o of r)o==="indexed"?t=!0:$d.has(o)||(n=o);return{...e,...n?{name:n}:{},...t?{indexed:!0}:{}}}function bi(r){let e=r.trim();if(e.startsWith("(")){let o=yi(e,0),s=Zl(e.slice(1,o)).map(bi),{suffix:a,rest:i}=Hd(e.slice(o+1).trim());return Jl(i.split(/\s+/).filter(Boolean),{type:`tuple${a}`,components:s})}let[t,...n]=e.split(/\s+/).filter(Boolean);if(!t)throw new Et(r,"Missing parameter type.");return Jl(n,{type:t})}function $o(r){return Zl(r).map(bi)}function qo(r,e,t){let n=r.indexOf("(",e);if(n===-1)throw new Et(t,"Missing parameter list.");let o=yi(r,n);return{name:r.slice(e,n).trim(),params:$o(r.slice(n+1,o)),rest:r.slice(o+1).trim()}}function fi(r,e){return r.split(/[\s()]+/).find(n=>qd.has(n))??e}function Ms(r){let e=r.trim();if(e.startsWith("function ")){let{name:t,params:n,rest:o}=qo(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 Et(r,"`returns` without a parameter list.");i=$o(o.slice(l+1,yi(o,l)))}return{type:"function",name:t,inputs:n,outputs:i,stateMutability:fi(a,"nonpayable")}}if(e.startsWith("event ")){let{name:t,params:n}=qo(e,6,r);return{type:"event",name:t,inputs:n}}if(e.startsWith("error ")){let{name:t,params:n}=qo(e,6,r);return{type:"error",name:t,inputs:n}}if(e.startsWith("constructor")){let{params:t,rest:n}=qo(e,11,r);return{type:"constructor",inputs:t,stateMutability:fi(n,"nonpayable")}}if(e.startsWith("fallback")){let{rest:t}=qo(e,8,r);return{type:"fallback",stateMutability:fi(t,"nonpayable")}}if(e.startsWith("receive"))return{type:"receive",stateMutability:"payable"};throw new Et(r,"Expected function, event, error, constructor, fallback or receive.")}function wi(r){return r.map(Ms)}function ot({blockNumber:r,blockTag:e="latest"}={}){return r!==void 0?Se(r):e}function Ho(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=Se(o)),s!==void 0&&(u.gas=Se(s)),a!==void 0&&(u.gasPrice=Se(a)),i!==void 0&&(u.maxFeePerGas=Se(i)),l!==void 0&&(u.maxPriorityFeePerGas=Se(l)),c!==void 0&&(u.nonce=Se(c)),u}function ki(r){let e={};for(let[t,n]of Object.entries(r)){let o={};n.balance!==void 0&&(o.balance=Se(n.balance)),n.nonce!==void 0&&(o.nonce=Se(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 qn(r){return Ye(await r.request({method:"eth_blockNumber"}))}async function $n(r){return Ls(await r.request({method:"eth_chainId"}))}async function Hn(r,{address:e,...t}){return Ye(await r.request({method:"eth_getBalance",params:[e,ot(t)]}))}async function Lt(r,{address:e,...t}){let n=await r.request({method:"eth_getCode",params:[e,ot(t)]});return!n||n==="0x"?void 0:n}async function Vn(r,{address:e,slot:t,...n}){return await r.request({method:"eth_getStorageAt",params:[e,t,ot(n)]})??void 0}async function Wn(r,{address:e,...t}){return Ls(await r.request({method:"eth_getTransactionCount",params:[e,ot(t)]}))}async function Yn(r){return Ye(await r.request({method:"eth_gasPrice"}))}async function Fs(r){return Ye(await r.request({method:"eth_maxPriorityFeePerGas"}))}async function Gn(r,{blockNumber:e,blockTag:t,...n}){return Ye(await r.request({method:"eth_estimateGas",params:[Ho(n),ot({blockNumber:e,blockTag:t})]}))}async function Kn(r,{includeTransactions:e=!1,...t}={}){let n=await r.request({method:"eth_getBlockByNumber",params:[ot(t),e]});return n?{...n,blockNumber:n.number?Ye(n.number):void 0,blockTimestamp:n.timestamp?Ye(n.timestamp):void 0,baseFee:n.baseFeePerGas?Ye(n.baseFeePerGas):void 0}:null}var X="0xcA11bde05977b3631167028862bE2a173976CA11",ec={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:X,blockCreated:14353601}}},tc={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:X,blockCreated:4286263}}},nc={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:X}}},rc={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:X,blockCreated:25770160}}},oc={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:X,blockCreated:5022}}},sc={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:X,blockCreated:7654707}}},ac={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:X}}},ic={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:X}}},lc={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:X}}},cc={id:999,hexId:"0x3e7",name:"HyperEVM",nativeCurrency:{name:"HYPE",symbol:"HYPE",decimals:18},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}},contracts:{multicall3:{address:X}}},uc={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:X}}},dc={id:143,hexId:"0x8f",name:"Monad",nativeCurrency:{name:"Monad",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://rpc.monad.xyz"]}},contracts:{multicall3:{address:X}}},mn=[ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,uc,dc];var pc=new Map,vi=new Map;function Vd(r,e){return`${r??"unknown"}|${e.toLowerCase()}`}async function mc(r,e=X){let t=Vd(r.chain?.id??r.chain?.hexId,e),n=pc.get(t);if(n!==void 0)return n;let o=vi.get(t);if(o)return o;let s=(async()=>{try{let i=await Lt(r,{address:e})!==void 0;return pc.set(t,i),i}catch{return!0}finally{vi.delete(t)}})();return vi.set(t,s),s}async function hn(r,e,t=!1){return t||typeof r.batch?.multicall=="object"&&r.batch.multicall.assumeMulticall3?!0:mc(r,e)}var Ge=[{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 H=[{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}]}],jn=[{type:"function",name:"name",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]},{type:"function",name:"symbol",stateMutability:"view",inputs:[],outputs:[{name:"",type:"bytes32"}]}];var zn=[{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 Bs=[{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 st=[{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 Xn=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`."]})}},gn=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."]})}},Dt=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 Ti(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 Vo({blockNumber:r,chain:e,contract:t}){let n=e.contracts?.[t];if(!n)throw new Dt({chain:e.name,contract:t});if(r!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(r))throw new Dt({blockNumber:r,chain:e.name,contract:t});return n.address}var Qn=class extends B{name="RawContractError";data;constructor({data:e,shortMessage:t="The contract call reverted."}){super(t),this.data=e}},Ai=class extends B{name="ContractFunctionRevertedError";errorName;errorArgs;reason;data;constructor({abi:e,data:t,functionName:n}){let o=t?Bo({abi:e,data:t}):void 0,s,a;if(t&&t!=="0x")try{let i=Bn({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}},Pi=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."]})}},Si=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?Ut({abi:t,name:s,args:o}):void 0,l=i?Dn(i):s,c=o&&o.length>0?` args: (${o.map(d=>Wd(d)).join(", ")})`:void 0,u=i?.inputs?.length?`(${i.inputs.map(Mo).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}},Wo=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 Wd(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 hc(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?hc(e.cause):void 0}function Jn(r,{abi:e,address:t,args:n,functionName:o,sender:s}){let a=hc(r),i=r instanceof Rt?new Pi({functionName:o}):a!==void 0?new Ai({abi:e,data:a,functionName:o}):r;return new Si(i,{abi:e,address:t,args:n,functionName:o,sender:s})}var xi=new Map;function Yo({fn:r,id:e,shouldSplitBatch:t,wait:n=0}){let o=()=>xi.get(e)??void 0,s=i=>xi.set(e,i),a=async i=>{o()===i&&xi.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 Yd(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 Gd(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 gn;let l=Vo({blockNumber:o,chain:r.chain,contract:"multicall3"});if(!await hn(r,l,!1))throw new Dt({chain:r.chain.name,contract:"multicall3"});let c=o!==void 0?Se(o):s,{schedule:u}=Yo({id:`${r.uid}.call.${c}`,wait:n,shouldSplitBatch:m=>m.reduce((f,h)=>f+(h.data.length-2)/2,0)>t,fn:async m=>{let f=F({abi:Ge,functionName:"aggregate3",args:[m.map(g=>({allowFailure:!0,callData:g.data,target:g.to}))]}),h=await r.request({method:"eth_call",params:[{to:l,data:f},c]});return rt({abi:Ge,functionName:"aggregate3",data:h})}}),{returnData:d,success:p}=await u({data:a,to:i});if(!p)throw new Qn({data:d});return d}async function at(r,e){let{blockNumber:t,blockTag:n,stateOverride:o,skipBatch:s,...a}=e;if(r.batch?.multicall&&!s&&Yd(e))try{let l=await Gd(r,{blockNumber:t,blockTag:n,data:a.data,to:a.to});return{data:l==="0x"?void 0:l}}catch(l){if(!(l instanceof gn||l instanceof Dt))throw new Wo(l,{to:a.to,data:a.data})}let i=[Ho(a),ot({blockNumber:t,blockTag:n})];o&&i.push(ki(o));try{let l=await r.request({method:"eth_call",params:i});return{data:!l||l==="0x"?void 0:l}}catch(l){throw new Wo(l,{to:a.to,data:a.data})}}var Ci=8;function gc(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:Ci}function Go(r,e,t){if(e)return e;if(!r.chain)throw new gn;let n=r.chain.contracts?.multicall3;return n?t!==void 0&&n.blockCreated!==void 0&&n.blockCreated>Number(t)?X:n.address:X}async function Zn(r,e,t={}){let{concurrency:n,account:o,blockNumber:s,blockTag:a,stateOverride:i}=t;return(await Ti(e,gc(r,n),async c=>{let{data:u}=await at(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 it(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 at(r,{...a,to:n,data:i});return rt({abi:t,functionName:o,args:s,data:l??"0x"})}catch(i){throw Jn(i,{abi:t,address:n,args:s,functionName:o,sender:a.account})}}var Kd=1024,jd=50;async function Ot(r,e){let{calls:t,account:n,blockNumber:o,blockTag:s,batchSize:a=Kd,maxCalls:i=jd,multicallAddress:l,stateOverride:c,fallbackConcurrency:u}=e,d=t.map(()=>({success:!1,returnData:"0x"}));if(t.length===0)return d;let p=Go(r,l,o),m=[];if(t.forEach((b,y)=>{_(b.target)&&ln(b.callData)&&m.push({index:y,call:b})}),m.length===0)return d;if(!await hn(r,p,l!==void 0))return(await Zn(r,m.map(y=>y.call),{account:n,blockNumber:o,blockTag:s,stateOverride:c,concurrency:u})).forEach((y,k)=>{d[m[k].index]={success:y.success,returnData:y.returnData}}),d;let f=[],h;return m.forEach(({call:b,index:y})=>{let k=(b.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},f.push(h)),h.calls.push(b),h.indexes.push(y),h.size+=k}),(await Promise.allSettled(f.map(b=>it(r,{abi:Ge,address:p,functionName:"aggregate3",args:[b.calls.map(y=>({target:y.target,allowFailure:!0,callData:y.callData}))],account:n,blockNumber:o,blockTag:s,stateOverride:c})))).forEach((b,y)=>{b.status==="fulfilled"&&f[y].indexes.forEach((k,w)=>{let v=b.value[w];v&&(d[k]={success:!!v.success,returnData:v.returnData??"0x"})})}),d}var fc="https://wallet-api.pantograph.app/keyring/chains_v6",zd=6,Xd=/[$]?\{[^}]*\}|YOUR[-_]|<[A-Za-z_]+>/,yc={},er=null;function Qd(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://")||Xd.test(s))&&(n.includes(s)||n.push(s),n.length>=zd))break}return n}function bc(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=lt(t)??(typeof o.chainId=="number"?lt(o.chainId):void 0);if(!s)continue;let a=Qd(o);a.length>0&&(e[s]=a)}return e}function wc(r){yc=r}function Ri(r){let e=lt(r);return e?yc[e]??[]:[]}function Ei(){er||qs()}function qs(r={}){let{url:e=fc,force:t=!1,debug:n=!1}=r;return er&&!t||(er=(async()=>{try{let o=await x.get(e);if(!o.ok)throw new Error(`HTTP ${o.status} ${o.statusText}`);let s=bc(o.data),a=Object.keys(s).length;if(a===0)throw new Error("catalogue contained no usable RPC endpoints");return wc(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 er=null,!1}})()),er}var Jd=new Map(mn.map(r=>[r.hexId.toLowerCase(),r])),Zd=new Map(mn.map(r=>[r.id,r]));function lt(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 vt(r){if(typeof r=="number")return Zd.get(r);let e=lt(r);return e?Jd.get(e):void 0}var De=Object.fromEntries(mn.map(r=>[r.hexId,r.rpcUrls.default.http[0]]));function _i(r){return vt(r)?.rpcUrls.default.http[0]}var Ni={};function fn(r){let e={};if(r)for(let[t,n]of Object.entries(r)){if(typeof n!="string"||!n.trim())continue;let o=lt(t)??t.toLowerCase();e[o]=n.trim()}Ni=e}function Ko(){return{...Ni}}function yn(r){Ei();let e=lt(r),t=e?Ni[e]:void 0,n=Ri(r),o=vt(r)?.rpcUrls.default.http??[];return[...new Set([...t?[t]:[],...n,...o])]}function bn(r){return yn(r)[0]}function Ii(r){let e=vt(r);if(!e)return;let t=yn(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 Mt=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}},tr=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)}`]:[]]})}},nr=class extends B{name="NetworkError";constructor({cause:e,url:t}){super("Could not reach the RPC endpoint.",{cause:e,metaMessages:[`URL: ${t}`]})}},$s=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.']})}},jo=class extends B{name="FallbackTransportError";constructor({cause:e,count:t}){super(`All ${t} fallback transports failed.`,{cause:e})}};var rr=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 Oe(r,e,t){return class extends rr{static code=e;name=r;constructor(n){super({...n,shortMessage:t})}}}var ep=Oe("ParseRpcError",-32700,"The node could not parse the JSON request."),tp=Oe("InvalidRequestRpcError",-32600,"The JSON request is not valid."),np=Oe("MethodNotFoundRpcError",-32601,"The RPC method does not exist on this endpoint."),rp=Oe("InvalidParamsRpcError",-32602,"The RPC method was called with invalid parameters."),op=Oe("InternalRpcError",-32603,"The node reported an internal error."),sp=Oe("InvalidInputRpcError",-32e3,"The RPC input is not valid."),ap=Oe("ResourceNotFoundRpcError",-32001,"The requested resource was not found."),ip=Oe("ResourceUnavailableRpcError",-32002,"The requested resource is not available."),lp=Oe("TransactionRejectedRpcError",-32003,"The transaction was rejected by the node."),cp=Oe("MethodNotSupportedRpcError",-32004,"The RPC method is not supported by this endpoint."),Ui=Oe("LimitExceededRpcError",-32005,"The request exceeded the endpoint's rate limit."),up=Oe("UserRejectedRequestError",4001,"The user rejected the request."),dp=new Map([[-32700,ep],[-32600,tp],[-32601,np],[-32602,rp],[-32603,op],[-32e3,sp],[-32001,ap],[-32002,ip],[-32003,lp],[-32004,cp],[-32005,Ui],[4001,up]]);function kc(r){let e=dp.get(r.error.code);return e?new e(r):new rr(r)}function vc(r){return new Promise(e=>setTimeout(e,r))}async function Li(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 vc(a)}}function Di(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 pp=new Set([408,413,429,500,502,503,504]),mp=new Set([401,402,403]);function Hs(r){return r instanceof tr||r instanceof nr?!0:r instanceof Mt?r.status?pp.has(r.status)||r.status>=500:!0:r instanceof Ui?!0:r instanceof rr?r.code===-32603:!1}function Vs(r){return r instanceof Mt&&r.status&&mp.has(r.status)?!0:Hs(r)}function Ws(r,{retryCount:e=3,retryDelay:t=150}={}){return function(o,s={}){return Li(()=>r(o),{retryCount:s.retryCount??e,shouldRetry:({error:a})=>Hs(a),delay:({count:a,error:i})=>{let l=i instanceof Mt?Di(i.headers):void 0;return l!==void 0?l:(s.retryDelay??t)*2**(a-1)}})}}function Ft({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:Ws(n,{retryCount:o,retryDelay:s}),value:i}}function Bt(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 jo({count:0});return Ft({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}),!Vs(m))throw m}throw new jo({cause:d,count:l.length})},retryCount:o,retryDelay:s,timeout:i.timeout},{transports:l})}}var Tc=0;function Ac(){return Tc+=1,Tc}function hp(r){let e=r?.code;if(e==="ECONNABORTED"||e==="ETIMEDOUT")return!0;let t=r?.message??"";return/timeout/i.test(t)}var or=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 hp(n)?new tr({body:e,url:this.url,timeout:this.timeout}):new nr({cause:n,url:this.url})}if(!t.ok)throw new Mt({body:e,details:I(t),headers:t.headers,status:t.status,url:this.url});return t.data}async request(e){let t={jsonrpc:"2.0",id:Ac(),...e};return await this.post(t)??{id:t.id}}async requestBatch(e){let t=e.map(s=>({jsonrpc:"2.0",id:Ac(),...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 Pc(r,e,t){if(r.error)throw kc({body:e,error:r.error,url:t});return r.result}function Ke(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:f=0}=typeof t=="object"?t:{},h=l??p??1e4,g=r??c?.rpcUrls.default.http[0];if(!g)throw new $s;let b=new or(g,{timeout:h,fetchOptions:n});return Ft({key:o,name:s,type:"http",retryCount:a??u,retryDelay:i??d,timeout:h,async request({method:y,params:k}){let w={method:y,params:k};if(t){let{schedule:v}=Yo({id:`${g}:${m}:${f}`,wait:f,shouldSplitBatch:T=>T.length>m,fn:T=>b.requestBatch(T)});return Pc(await v(w),w,g)}return Pc(await b.request(w),w,g)}},{url:g})}}var gp=1024;async function sr(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||gp),d=new Array(t.length);if(t.length===0)return n?d:[];let p=Go(r,i,s),m=[],f;t.forEach((b,y)=>{let{abi:k,address:w,functionName:v,args:T}=b,P;try{if(!_(w))throw new Nn(w);P=F({abi:k,functionName:v,args:T})}catch(N){let R=Jn(N,{abi:k,address:w,args:T,functionName:v,sender:o});if(!n)throw R;d[y]={status:"failure",error:R};return}let C=(P.length-2)/2;(!f||u>0&&f.size+C>u&&f.calls.length>0)&&(f={calls:[],indexes:[],size:0},m.push(f)),f.calls.push({target:w,allowFailure:!0,callData:P}),f.indexes.push(y),f.size+=C}),(await hn(r,p,i!==void 0)?await Promise.allSettled(m.map(b=>it(r,{abi:Ge,address:p,functionName:"aggregate3",args:[b.calls],account:o,blockNumber:s,blockTag:a,stateOverride:l}))):await(async()=>{let b=m.flatMap(k=>k.calls.map((w,v)=>({target:w.target,callData:w.callData,index:k.indexes[v]}))),y=await Zn(r,b,{account:o,blockNumber:s,blockTag:a,stateOverride:l,concurrency:c});return m.length=0,y.map((k,w)=>(m.push({calls:[],indexes:[b[w].index],size:0}),k.success?{status:"fulfilled",value:[{success:!0,returnData:k.returnData}]}:{status:"rejected",reason:k.error}))})()).forEach((b,y)=>{let k=m[y];if(b.status==="rejected"){for(let w of k.indexes){let v=t[w],T=Jn(b.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=b.value[v];try{if(!P)throw new Error("Multicall returned fewer results than calls.");if(!P.success)throw new Qn({data:P.returnData});if(!P.returnData||P.returnData==="0x")throw new Rt;let C=rt({abi:T.abi,functionName:T.functionName,args:T.args,data:P.returnData});d[w]={status:"success",result:C}}catch(C){let N=Jn(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 b=0;b<t.length;b++){if(d[b])continue;let y=new Error("Multicall returned no result for this call.");if(!n)throw y;d[b]={status:"failure",error:y}}return n?d:d.map(b=>b.result)}var fp=0,wn=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=bp(e.chain),this.key=n,this.name=o,this.batch=t,this.uid=`${n}-${++fp}-${Math.random().toString(36).slice(2,8)}`;let c=(e.transport??yp(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 at(this,e)}readContract(e){return it(this,e)}multicall(e){return sr(this,e)}multicallRaw(e){return Ot(this,e)}getBlockNumber(){return qn(this)}getChainId(){return $n(this)}getBalance(e){return Hn(this,e)}getCode(e){return Lt(this,e)}getStorageAt(e){return Vn(this,e)}getTransactionCount(e){return Wn(this,e)}getGasPrice(){return Yn(this)}estimateMaxPriorityFeePerGas(){return Fs(this)}estimateGas(e){return Gn(this,e)}getBlock(e){return Kn(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 yp(r,e){if(r)return Ke(r);let t=e?.rpcUrls.default.http??[];return t.length>1?Bt(t.map(n=>Ke(n,{retryCount:1}))):Ke(t[0])}function bp(r){if(r===void 0)return;if(typeof r=="object")return r;let e=Ii(r);if(!e)throw new Xn(r);return e}function qt(r={}){return new wn(r)}var Oi=new Map;function wp(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:X}}}}function xe(r,e={}){let{batch:t=!0,pinRpcUrl:n=!1,fallbackConcurrency:o,assumeMulticall3:s}=e,a=lt(r),i=e.rpcUrl?.trim(),l=a?yn(a):[],c=i?n?[i]:[...new Set([i,...l])]:l;if(c.length===0)throw new Xn(r);let u=`${a??r}|${c.join(",")}|${t?1:0}|${o??""}|${s?1:0}`,d=Oi.get(u);if(d)return d;let p=qt({chain:a&&!vt(a)?wp(a,c):a,transport:c.length===1?Ke(c[0]):Bt(c.map(m=>Ke(m,{retryCount:1}))),batch:t?{multicall:{fallbackConcurrency:o,assumeMulticall3:s}}:void 0});return Oi.set(u,p),p}function Ys(){Oi.clear()}function Fi(r,e){try{return xe(r,{rpcUrl:e?.trim()||void 0})}catch{return null}}async function de(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)=>{!_(a.target)||!ln(a.callData)||s.push({index:i,target:a.target,callData:a.callData})}),s.length===0)return n;try{(await Ot(o,{calls:s})).forEach((i,l)=>{i.success&&(n[s[l].index]=i.returnData)})}catch{}return n}function Gs(r){return r?.status==="success"?r.result:void 0}async function Mi(r,e){try{return await r.multicall({contracts:e})}catch{return[]}}async function Ks(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)=>{_(l)&&s.push({index:c,address:l})}),s.length===0)return n;let a=await Mi(o,s.flatMap(l=>[{address:l.address,abi:H,functionName:"symbol"},{address:l.address,abi:H,functionName:"decimals"}]));s.forEach((l,c)=>{let u=Gs(a[c*2]);typeof u=="string"&&u.trim()&&(n[l.index].symbol=u.trim()),n[l.index].decimals=Ds(Gs(a[c*2+1]))});let i=s.filter(l=>n[l.index].symbol===null);if(i.length>0){let l=await Mi(o,i.map(c=>({address:c.address,abi:jn,functionName:"symbol"})));i.forEach((c,u)=>{n[c.index].symbol=Os(Gs(l[u]))})}return n}async function Sc(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(_(i.contract))try{s.push({index:l,address:i.contract,tokenId:BigInt(i.tokenId)})}catch{}}),s.length===0||(await Mi(o,s.map(i=>({address:i.address,abi:zn,functionName:"tokenURI",args:[i.tokenId]})))).forEach((i,l)=>{let c=Gs(i);if(typeof c!="string")return;let u=c.replace(/\0+$/,"").trim();u&&(n[s[l].index]=u)}),n}function kp(r){return js(String(r))??"0"}function js(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 Bi(r){let e=js(r);if(e===null||e.startsWith("-"))return null;let[t,n=""]=e.split(".");return{mant:BigInt(t+n),frac:n.length}}function qi(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 ar(r){if(typeof r=="number")return Number.isFinite(r)&&r>0?kp(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=js(e[0]);return t&&t!=="0"&&!t.startsWith("-")?t:null}function $t(r,e){let t=js(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 ir(r,e,t,n){let o=Bi(r);if(!o||t<=0n||n<0)return r;let s=o.mant*e*10n**BigInt(n)/(t*10n**BigInt(o.frac));return qi(s,n)}function kn(r,e){let t=Bi(r),n=Bi(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 vp={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"}]},Tp="payment-required",Ap="PAYMENT-SIGNATURE",Pp="X-PAYMENT",Sp="payment-response",xp="x-payment-response",Cp=600,Rp=300,Ep={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 xc(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 Rc(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 _p(){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 Ec(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=Ep[e.toLowerCase()];if(t===void 0)throw new Error(`Unsupported x402 network: ${r}`);return t}function _c(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 zs(r){let e=r.headers[Tp];if(e){let o=Cc(Np(e));return o&&Array.isArray(o.accepts)?{version:2,payload:o}:null}let t=r.data,n=t&&typeof t=="object"?t:Cc(t);return n&&Array.isArray(n.accepts)?{version:1,payload:n}:null}function Cc(r){if(typeof r!="string")return null;try{let e=JSON.parse(r);return e&&typeof e=="object"?e:null}catch{return null}}function Np(r){try{return Rc(r)}catch{return null}}function Ip(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 Up(r){let e=null;for(let t of r){let n=Ip(t);if(n){if(n.scheme!=="exact"){e=`unsupported scheme "${n.scheme}"`;continue}try{return Ec(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 $i(r,e,t,n){let o=zs(r);if(!o)throw new Error("402 response carries no x402 payment requirements");let{version:s,payload:a}=o,i=Up(a.accepts??[]);if(!t)throw new Error("No connected wallet address to build the payment from");let l=Ec(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??Rp)),nonce:_p()},d={domain:{name:i.extra?.name,version:i.extra?.version,chainId:l,verifyingContract:i.asset},types:vp,primaryType:"TransferWithAuthorization",message:{...u}};return{request:{url:_c(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 Lp(r,e,t,n){let o=_c(e),s=await r.request(e.method??"GET",o,e.body,{headers:e.headers});if(s.status===402)return{status:"payment_required",challenge:$i(s,e,t,n)};if(!s.ok)throw new Error(I(s));return{status:"ok",data:s.data}}async function Hi(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(Op(i)??I(i))}function Dp(r){return zs(r)!==null}function Nc(r){let e=Ic(r);return e?.errorReason?e.errorReason:zs(r)?.payload.error??null}function Op(r){let e=Nc(r);return e?`x402 payment rejected: ${e}`:null}var Mp={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{[Pp]:xc(JSON.stringify(a))}}let s={x402Version:2,...r.resource!=null?{resource:r.resource}:{},accepted:Fp(t),payload:o,...r.extensions!=null?{extensions:r.extensions}:{}};return{[Ap]:xc(JSON.stringify(s))}}function Fp(r){let{resource:e,description:t,mimeType:n,outputSchema:o,...s}=r;return s}function Ic(r){let e=r.headers[Sp]??r.headers[xp];if(!e)return null;try{return JSON.parse(Rc(e))}catch{return null}}function Bp(r,e){return r==null?e:Mp[r]??`Chain ${r}`}async function Uc(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 Ks("0x"+o.toString(16),[e.asset]);s=l?.symbol??null,a=l?.decimals??null}let i=String(e.amount);if(a!==null)try{i=qi(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:Bp(o,e.network),payTo:e.payTo,...n?{description:n}:{},resourceUrl:r.request.url}}function Wi(r){return async(e,t)=>{let n=r.getPayer(),o=r.getSigner();if(!n||!o)return null;let s;try{s=$i(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 Uc(s)})}catch{a=null}return a?Vi(s,a):null}}var Ht=class extends Error{constructor(e="Aborted"){super(e),this.name="AbortError"}};function vn(r){if(!r||typeof r!="object")return!1;let e=r;return e.name==="AbortError"||e.name==="CanceledError"||e.code==="ERR_CANCELED"}function zo(r){if(r?.aborted)throw new Ht}function Yi(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 Lc={string:"STRING",number:"NUMBER",boolean:"BOOLEAN",object:"OBJECT",array:"ARRAY"},qp="https://nft.keyring.app/api/gemini-stable",$p="https://generativelanguage.googleapis.com",Hp=new Set([408,429,500,502,503,504]),Dc=3e4,Xs=r=>new Promise(e=>setTimeout(e,r));function Qs(r,e,t){if(t!=null&&t>0)return Math.min(t,Dc);let n=Math.min(e*2**(r-1),Dc);return n/2+Math.random()*(n/2)}function Vp(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 ie=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?$p:qp)).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;zo(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 g=h.parts.map(b=>b.functionCall?`fc:${b.functionCall.name}`:b.functionResponse?`fr:${b.functionResponse.name}`:`text:${(b.text??"").slice(0,40)}`).join(", ");console.log(` ${h.role}: [${g}]`)}}let 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`,f="Unknown error";for(let h=1;h<=a;h++){zo(l);let g;try{g=await x.post(m,p,{headers:{"Content-Type":"application/json",...this.apiKey?{"x-goog-api-key":this.apiKey}:{}},signal:l})}catch(P){if(vn(P))throw P;if(f=P instanceof Error?P.message:String(P),h>=a)break;await Xs(Qs(h,i));continue}if(!g.ok){let P=typeof g.data=="string"?g.data:JSON.stringify(g.data)||g.statusText;if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} error ${g.status}: ${P}`,!Hp.has(g.status))throw new Error(f);if(h>=a)break;let C=Vp(g.headers["retry-after"]??null);await Xs(Qs(h,i,C));continue}if(g.data==null||typeof g.data!="object"){if(f=`${this.isDirect?"Gemini API":"Gemini proxy"} returned invalid JSON`,h>=a)break;await Xs(Qs(h,i));continue}let b=g.data,y=b.candidates?.[0];if(!y)return{text:"",toolCalls:[]};let k="",w=[],v=y.content?.parts;if(!Array.isArray(v)||v.length===0){let P=y.finishReason;if(!(P==="SAFETY"||P==="RECITATION")&&h<a){f=`Gemini returned an empty turn (finishReason=${P??"none"})`,await Xs(Qs(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=b.usageMetadata?{promptTokens:b.usageMetadata.promptTokenCount??0,completionTokens:b.usageMetadata.candidatesTokenCount??0,totalTokens:b.usageMetadata.totalTokenCount??0}:void 0;return{text:k,toolCalls:w,usage:T}}throw new Error(f)}toContents(e){let t=[],n=[];for(let i of e){if(i.role==="system"){t.push(i.content);continue}if(i.role==="tool"){n.push({role:"function",parts:[{functionResponse:{name:i.toolName??"unknown",response:{result:i.content},...i.toolCallId?{id:i.toolCallId}:{}}}]});continue}if(i.role==="assistant"&&i.toolCalls?.length){n.push({role:"model",parts:i.toolCalls.map(l=>({functionCall:{name:l.toolName,args:l.args,...l.callId?{id:l.callId}:{}}}))});continue}n.push({role:i.role==="assistant"?"model":"user",parts:[{text:i.content}]})}let 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:Lc[s.type]??"STRING",description:s.description};s.type==="array"&&(a.items={type:Lc[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 lr=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 cr=["0x1","0xa","0x38","0x89","0x2105","0xa4b1","0xa86a","0xe708","0x64","0x3e7","0x1388","0x8f"],Wp=new Set(cr),Vt=[...cr],Gi=new Set(Vt),Me="0x1",dr="Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad";function Yp(r){return r.map(e=>ur[e]??e).join(", ")}function Js(r){let e=new Set;if(r)for(let n of r){let o=Zs(n);o&&e.add(o)}let t=cr.filter(n=>!e.has(n));Vt=t.length>0?[...t]:[...cr],Gi=new Set(Vt),Me=Vt.includes("0x1")?"0x1":Vt[0],dr=Yp(Vt)}var Gp={"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=Zs(r);return e&&Gi.has(e)?e:null}function Zs(r){if(typeof r!="string")return null;let e=r.trim().toLowerCase().replace(/\s+/g," ");if(!e)return null;let t=Gp[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&&Wp.has(n)?n:null}function je(r){return q(r)!==null}function Ce(){return[...Vt]}var Yt=class extends Error{constructor(t){super(`Chain "${t}" is not supported. Supported chains: ${dr}.`);this.requested=t;this.name="UnsupportedChainError"}requested;code="unsupported_chain"},Wt=r=>typeof r=="string"&&r.trim()!=="";function te(r,e){if(Wt(r)){let t=q(r);if(t)return t;throw new Yt(r.trim())}if(Wt(e?.chain)){let t=q(e.chain);if(t)return t;throw new Yt(e.chain.trim())}return null}function ea(r,e){return q(r)??q(e?.chain)??void 0}var ur={"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=Zs(r);return e&&ur[e]?ur[e]:typeof r=="string"&&r.trim()?r.trim():"the requested chain"}var Kp={"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 Oc(r,e){let t=Zs(r),n=t?Kp[t]:void 0;return!n||typeof e!="string"||!/^0x[0-9a-fA-F]{64}$/.test(e.trim())?null:`${n}/tx/${e.trim()}`}var jp={bnb:"0x38",matic:"0x89",pol:"0x89",avax:"0xa86a",xdai:"0x64",hype:"0x3e7",mnt:"0x1388",mon:"0x8f"};function Mc(r){if(typeof r!="string")return null;let e=r.trim().toLowerCase();return e?jp[e]??null:null}var zp={"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 Fc(r){let e=q(r);return e?zp[e]??null:null}function pr(r,e){if(!Wt(r))return null;let t=q(r),n=q(e?.chain);return!t||!n||t===n?null:{requested:t,connected:n,requestedLabel:ur[t]??t,connectedLabel:ur[n]??n}}function Bc(r,e){let t=typeof r=="string"?r.trim():"",n=e&&e.length?e.filter(s=>Gi.has(s)):[];return(n.length?n:Vt).map(s=>{let a=ur[s]??s;return{label:a,prompt:t?`${t} (${a})`:a}})}function mr(r,e){return{actionButtons:Bc(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 se=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=Bc(e,t)}},Xo=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 ne(r,e){if(Wt(r))return r.trim();if(Wt(e?.walletAddress))return e.walletAddress.trim();throw new Xo}function pe(r,e,t){if(Wt(r)){let n=q(r);if(n)return n;throw new Yt(r.trim())}if(Wt(e?.chain)){let n=q(e.chain);if(n)return n;throw new Yt(e.chain.trim())}if(Wt(e?.walletAddress))throw new se(typeof e?.query=="string"?e.query:void 0,t);return Me}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=Xp(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 se?{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 Xo?{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 Xp(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 Qp="https://wallet-api.pantograph.app",Jp="0x0000000000000000000000000000000000000000",Hc={"0x1":"ether","0xa":"optimism","0x38":"bsc","0x89":"matic","0x2105":"base","0xa4b1":"arbitrum","0xa86a":"avax","0xe708":"linea"},Vc={"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 Zp(r){return Hc[r.toLowerCase()]||r}function qc(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 Ki(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 ta(r){if(Array.isArray(r))return r;let e=r;return Array.isArray(e?.items)?e.items:Array.isArray(e?.data)?e.data:[]}function ve(r){if(r==null)return null;let e=typeof r=="number"?r:parseFloat(String(r));return Number.isFinite(e)?e:null}function $c(r,e){let t=r.decimals,n=typeof t=="number"?t:typeof t=="string"?parseInt(t,10):null,o=ve(r.price_change_percentage_24h)??ve(r.priceChange24h)??ve(r.usd_price_24hr_percent_change)??ve(r.price_change_24h)??ve(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:ve(r.price)??ve(r.usd_price),marketCap:ve(r.market_cap)??ve(r.marketCap),totalVolume:{"24h":ve(r.total_volume)??ve(r.volume24h)},pricePercentChange:{"24h":o}}}var le=class{baseUrl;constructor(e){this.baseUrl=(e?.baseUrl??Qp).replace(/\/+$/,"")}tokensUrl(e,t){let n=parseInt(e,16);return`${this.baseUrl}/keyrings/tokens/all/${n}?addresses=${encodeURIComponent(t)}`}async enrichTokenPrices(e,t){let n=new Map;if(e.length===0)return n;try{let o=e.map(c=>c.token_address).join(","),s=this.tokensUrl(t,o),a=await x.get(s);if(!a.ok)return n;let i=ta(a.data),l=new Map;for(let c of i)if(c.address){let u=c.address.toLowerCase();l.set(u,{price:c.price!=null?parseFloat(String(c.price)):NaN,icon_image:c.icon_image}),("yieldProtocol"in c||"yieldAsset"in c)&&n.set(u,{yieldProtocol:c.yieldProtocol,yieldAsset:c.yieldAsset})}for(let c=0;c<e.length;c++){let u=l.get(e[c].token_address.toLowerCase());u&&(u.icon_image&&(e[c].logo=u.icon_image,e[c].thumbnail=u.icon_image),isNaN(u.price)||(e[c].usd_price=u.price,e[c].usd_value=parseFloat(e[c].balance_formatted||"0")*u.price))}}catch{}return n}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?ta(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=ta(o.data),a=e.toLowerCase()===Jp,i=s.find(l=>l.address?.toLowerCase()===e.toLowerCase()||a&&l.address===""||l.token_address?.toLowerCase()===e.toLowerCase()||a&&l.token_address==="");return i?Ki(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=ta(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]=Ki(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||Me,16);if(isNaN(s))return{success:!1,error:`Invalid hex chain: ${n}`};try{let a=qc({chainId:s,key:t}),i=`${this.baseUrl}/token-list/all?${a}`,l=await x.get(i);if(!l.ok)throw new Error(I(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(Ki)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}async getTrendingTokens(e){let t=e?.chain||Me,n=5,o=e?.limit&&e.limit>0?Math.floor(e.limit):void 0;try{let s=Vc[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=>$c(h,t)):[],d=new Set,p=[];for(let h of u){let g=h.tokenAddress?.toLowerCase();!g||d.has(g)||(d.add(g),p.push(h))}let m=[];for(let h of c){let g=h.tokenAddress?.toLowerCase();!g||d.has(g)||(d.add(g),m.push(h))}let f=o!=null?[...p,...m].slice(0,o):[...p,...m.slice(0,n)];return await this.enrichTrendingMarketData(f,t),{success:!0,data:f}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Unknown error"}}}async enrichTrendingMarketData(e,t){let 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=ve(a.market_cap)??ve(a.marketCap)),s.totalVolume?.["24h"]==null&&(s.totalVolume={"24h":ve(a.total_volume)??ve(a.volume24h)}))}}async fetchTopGainers(e,t,n="24h"){let o=parseInt(e,16),s=qc({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(I(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=>$c(l,e))}async getTopGainers(e){let t=e?.chain||Me,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"}}}};function K(r,e,t,n=[]){return{target:r,callData:F({abi:e,functionName:t,args:n})}}var Tn=1e27,na=10n**27n,Qo=31536e3,em=10;function ct(r){return Number.isFinite(r)&&r>=0&&r<=em?r:null}function ji(r){return Math.expm1(r)}function Fe(r,e){return Number(r)/10**e}function Jo(r){return new Date(r).toISOString().slice(0,10)}async function hr(r,e,t){let n=`${t.lendingRatesBaseUrl}/lending-rates/${e.chainId}/${r.token}?range=h&day=${7}`,o=await x.get(n);if(!o.ok)throw new Error(I(o));return{samples:(Array.isArray(o.data)?o.data:o.data?.data||[]).filter(a=>a?.rate!==null&&a?.rate!==void 0).map(a=>({timeMs:Date.parse(a?.date??""),fraction:Number(a?.rate)})),current:null,rewards:[]}}var ut=class{underlyingCall(e){return K(e.contract,st,"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=j(e);return n===null?null:Fe(n,t.decimals)}decodeLiveRate(e){return null}convertToAssetsCall(e,t){return this.balanceIsUnderlying?null:K(e.contract,st,"convertToAssets",[t])}},Gt=class extends ut{type="spark";balanceIsUnderlying=!1;sizeCall(e){return K(e.contract,st,"totalAssets")}fetchApy(e,t,n){return hr(e,t,n)}};var zi=[{type:"constructor",inputs:[{name:"owner_",type:"address",internalType:"address"},{name:"supportedRouter_",type:"address",internalType:"address"},{name:"nonfungiblePositionManager_",type:"address",internalType:"address"}],stateMutability:"nonpayable"},{type:"function",name:"NATIVE_TOKEN",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"getSupportedRouters",inputs:[],outputs:[{name:"",type:"address[]",internalType:"address[]"}],stateMutability:"view"},{type:"function",name:"increaseLiquidity",inputs:[{name:"tokenId_",type:"uint256",internalType:"uint256"},{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"increaseLiquidityData_",type:"tuple",internalType:"struct CoinPoolGateway.IncreaseLiquidityData",components:[{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"mint",inputs:[{name:"swapInfo_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapInfo[2]",components:[{name:"tokenIn",type:"address",internalType:"address"},{name:"tokenInAmount",type:"uint256",internalType:"uint256"},{name:"tokenOut",type:"address",internalType:"address"},{name:"tokenOutAmount",type:"uint256",internalType:"uint256"}]},{name:"swapOp_",type:"tuple[2]",internalType:"struct CoinPoolGateway.SwapOp[2]",components:[{name:"to",type:"address",internalType:"address"},{name:"value",type:"uint256",internalType:"uint256"},{name:"data",type:"bytes",internalType:"bytes"}]},{name:"mintData_",type:"tuple",internalType:"struct CoinPoolGateway.MintData",components:[{name:"fee",type:"uint24",internalType:"uint24"},{name:"tickLower",type:"int24",internalType:"int24"},{name:"tickUpper",type:"int24",internalType:"int24"},{name:"amount0Min",type:"uint256",internalType:"uint256"},{name:"amount1Min",type:"uint256",internalType:"uint256"}]}],outputs:[],stateMutability:"payable"},{type:"function",name:"nonfungiblePositionManager",inputs:[],outputs:[{name:"",type:"address",internalType:"contract INonfungiblePositionManager"}],stateMutability:"view"},{type:"function",name:"owner",inputs:[],outputs:[{name:"",type:"address",internalType:"address"}],stateMutability:"view"},{type:"function",name:"pause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"paused",inputs:[],outputs:[{name:"",type:"bool",internalType:"bool"}],stateMutability:"view"},{type:"function",name:"renounceOwnership",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"rescue",inputs:[{name:"token_",type:"address",internalType:"address"},{name:"amount_",type:"uint256",internalType:"uint256"},{name:"recipient_",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"transferOwnership",inputs:[{name:"newOwner",type:"address",internalType:"address"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"unpause",inputs:[],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"updateSupportedRouters",inputs:[{name:"routers_",type:"address[]",internalType:"address[]"},{name:"isSupported_",type:"bool[]",internalType:"bool[]"}],outputs:[],stateMutability:"nonpayable"},{type:"event",name:"LiquidityIncreased",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1LiquidityIncreased",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1IncreaseLiquidityRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"Minted",inputs:[{name:"tokenId",type:"uint256",indexed:!1,internalType:"uint256"},{name:"token0",type:"address",indexed:!1,internalType:"address"},{name:"token1",type:"address",indexed:!1,internalType:"address"},{name:"amount0Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1Minted",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1SwapRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount0MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"},{name:"amount1MintRefunded",type:"uint256",indexed:!1,internalType:"uint256"}],anonymous:!1},{type:"event",name:"OwnershipTransferred",inputs:[{name:"previousOwner",type:"address",indexed:!0,internalType:"address"},{name:"newOwner",type:"address",indexed:!0,internalType:"address"}],anonymous:!1},{type:"event",name:"Paused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"event",name:"SupportedRoutersUpdated",inputs:[{name:"routers",type:"address[]",indexed:!1,internalType:"address[]"},{name:"isSupported",type:"bool[]",indexed:!1,internalType:"bool[]"}],anonymous:!1},{type:"event",name:"Unpaused",inputs:[{name:"account",type:"address",indexed:!1,internalType:"address"}],anonymous:!1},{type:"error",name:"AddressEmptyCode",inputs:[{name:"target",type:"address",internalType:"address"}]},{type:"error",name:"EnforcedPause",inputs:[]},{type:"error",name:"ExpectedPause",inputs:[]},{type:"error",name:"FailedCall",inputs:[]},{type:"error",name:"InsufficientAmountOut",inputs:[]},{type:"error",name:"InsufficientBalance",inputs:[{name:"balance",type:"uint256",internalType:"uint256"},{name:"needed",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidAmountIn",inputs:[]},{type:"error",name:"InvalidLength",inputs:[]},{type:"error",name:"InvalidRefundUnusedToken",inputs:[]},{type:"error",name:"InvalidSwapAction",inputs:[]},{type:"error",name:"InvalidTokenInInfo",inputs:[]},{type:"error",name:"InvalidTokenOutInfo",inputs:[]},{type:"error",name:"InvalidTotalAmountIn",inputs:[]},{type:"error",name:"NotSupportedRouter",inputs:[]},{type:"error",name:"OwnableInvalidOwner",inputs:[{name:"owner",type:"address",internalType:"address"}]},{type:"error",name:"OwnableUnauthorizedAccount",inputs:[{name:"account",type:"address",internalType:"address"}]},{type:"error",name:"ReentrancyGuardReentrantCall",inputs:[]},{type:"error",name:"SafeERC20FailedDecreaseAllowance",inputs:[{name:"spender",type:"address",internalType:"address"},{name:"currentAllowance",type:"uint256",internalType:"uint256"},{name:"requestedDecrease",type:"uint256",internalType:"uint256"}]},{type:"error",name:"SafeERC20FailedOperation",inputs:[{name:"token",type:"address",internalType:"address"}]}];var Zo=[{type:"function",name:"slot0",stateMutability:"view",inputs:[],outputs:[{name:"sqrtPriceX96",type:"uint160"},{name:"tick",type:"int24"},{name:"observationIndex",type:"uint16"},{name:"observationCardinality",type:"uint16"},{name:"observationCardinalityNext",type:"uint16"},{name:"feeProtocol",type:"uint8"},{name:"unlocked",type:"bool"}]},{type:"function",name:"liquidity",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint128"}]},{type:"function",name:"tickSpacing",stateMutability:"view",inputs:[],outputs:[{name:"",type:"int24"}]},{type:"function",name:"fee",stateMutability:"view",inputs:[],outputs:[{name:"",type:"uint24"}]},{type:"function",name:"token0",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"token1",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var oa=[{type:"function",name:"getReserveData",stateMutability:"view",inputs:[{name:"asset",type:"address"}],outputs:[{name:"reserveData",type:"tuple",components:[{name:"configuration",type:"uint256"},{name:"liquidityIndex",type:"uint128"},{name:"currentLiquidityRate",type:"uint128"}]}]}],gr=[{type:"function",name:"UNDERLYING_ASSET_ADDRESS",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]},{type:"function",name:"POOL",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}],Xi=[{type:"function",name:"ADDRESSES_PROVIDER",stateMutability:"view",inputs:[],outputs:[{name:"",type:"address"}]}];var Tt=[{inputs:[],name:"getUtilization",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseToken",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{name:"utilization",type:"uint256"}],name:"getSupplyRate",outputs:[{name:"",type:"uint64"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseTrackingSupplySpeed",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"baseIndexScale",outputs:[{name:"",type:"uint64"}],stateMutability:"pure",type:"function"}],Qi=[{inputs:[{name:"comet",type:"address"}],name:"rewardConfig",outputs:[{name:"token",type:"address"},{name:"rescaleFactor",type:"uint64"},{name:"shouldUpscale",type:"bool"}],stateMutability:"view",type:"function"}];var fr=[{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"vsr",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],Kt=[{inputs:[],name:"getAPR",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getConversionRate",outputs:[{name:"",type:"uint256"}],stateMutability:"view",type:"function"}],Ji=[{inputs:[],name:"susds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"usds",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"rateProvider",outputs:[{name:"",type:"address"}],stateMutability:"view",type:"function"}];var rm=`query SupplyAPYHistory($request: SupplyAPYHistoryRequest!, $reserve: ReserveRequest!) {
|
|
@@ -31,7 +31,7 @@ Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-ce
|
|
|
31
31
|
- Market Cap: <marketCap>
|
|
32
32
|
- Price Change: <pricePercentChange.24h> (prefix "+" for positive, "-" for negative)
|
|
33
33
|
- 24h Volume: <totalVolume.24h>
|
|
34
|
-
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:n?A(n):"all",timeFrame:s??null,count:c.length,tokens:c}}};var Ar=class extends S{name="get-wallet-token-balances";description='Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new O(e)}truncateUsd(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[n,o=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${n}.${(o+"00").slice(0,2)}`}async run(e,t){let n=ne(e.address,t),o=te(e.chain,t);if(o){let i=await this.service.getWalletTokenBalances({address:n,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1});return i.success?this.renderBalances(n,o,i.data?.result||[]):{error:i.error||"Failed to fetch token balances"}}let s=Ce(),a=await Promise.all(s.map(async i=>{let l=await this.service.getWalletTokenBalances({address:n,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(n,a)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",n=e.balance_formatted??"0",o=e.symbol||"",s=typeof e.usd_value=="number"?`$${this.truncateUsd(e.usd_value)}`:"$-";return`- ${t}: ${n} ${o} (${s})`.replace(/\s+/g," ").trim()}renderBalances(e,t,n){let o=n.reduce((s,a)=>s+(a.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:e,chain:t,totalUsdValue:`$${this.truncateUsd(o)}`,tokens:n.map(s=>this.toTokenLine(s))}}renderBalancesByChain(e,t){let n=t.map(s=>{let a=s.tokens.reduce((l,c)=>l+(c.usd_value||0),0),i=s.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:A(s.chain),total:a,tokens:i}}).filter(s=>s.tokens.length>0).sort((s,a)=>a.total-s.total),o=n.reduce((s,a)=>s+a.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:e,chain:"all",totalUsdValue:`$${this.truncateUsd(o)}`,chains:n.map(s=>({chain:s.chain,totalUsdValue:`$${this.truncateUsd(s.total)}`,tokens:s.tokens.map(a=>this.toTokenLine(a))}))}}};var Pr=class extends S{name="get-wallet-history";description=`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=pe(e.chain,t),s=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,a=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,i=typeof e.fromBlock=="number"?e.fromBlock:typeof e.fromBlock=="string"&&e.fromBlock?Number(e.fromBlock):void 0,l=typeof e.toBlock=="number"?e.toBlock:typeof e.toBlock=="string"&&e.toBlock?Number(e.toBlock):void 0,c=Number.isFinite(i)?i:void 0,u=Number.isFinite(l)?l:void 0,d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",f=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,h=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,g=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,b=Number.isFinite(g)&&g>0?g:10,y=await this.service.getWalletHistory({address:n,chain:o,limit:b,fromDate:s,toDate:a,fromBlock:c,toBlock:u,cursor:d,order:m,includeInternalTransactions:f,nftMetadata:h});if(!y.success)return{error:y.error||"Failed to fetch wallet history"};let w=(y.data?.result||[]).map(v=>{let T=Oc(o,v.hash);return T?{...v,explorerUrl:T}:v});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:n,chain:o||"default",pagination:{cursor:y.data?.cursor??null,hasMore:!!y.data?.cursor},transactionCount:w.length,transactions:w}}};function Am(r){if(r.value_decimal)return r.value_decimal;let e=parseInt(r.token_decimals??"18",10);if(isNaN(e)||e===0)return r.value;try{let t=BigInt(r.value),n=BigInt(10)**BigInt(e),o=t/n,a=(t%n).toString().padStart(e,"0").replace(/0+$/,"");return a?`${o}.${a}`:`${o}`}catch{return r.value}}var Sr=class extends S{name="get-wallet-token-transfers";description=`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=pe(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",h=f==="send"?"send":f==="receive"?"receive":"all",g=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,b=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(R=>typeof R=="string"&&!!R).map(R=>R.trim()):void 0,y,k;if(g){let R=await this.resolveContractAddressBySymbol(g,n,o);R&&(b=[R.address],y=R.symbol,k=R.name)}let w=await this.service.getWalletTokenTransfers({address:n,chain:o,contractAddresses:b,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:m});if(!w.success)return{error:w.error||"Failed to fetch token transfers"};let v=n.toLowerCase(),P=(w.data?.result||[]).map(R=>{let V=R.from_address.toLowerCase()===v,E=V?"send":"receive",ce=V?R.to_address:R.from_address,$=V?R.to_address_label??void 0:R.from_address_label??void 0,fe=V?R.to_address_entity??void 0:R.from_address_entity??void 0;return{...R,direction:E,amount_formatted:Am(R),counterparty:ce,counterparty_label:$,counterparty_entity:fe}}),C=h==="all"?P:P.filter(R=>R.direction===h);if(g&&!b){let R=g.toLowerCase();C=C.filter(V=>(V.token_symbol??"").toLowerCase()===R)}let N=this.buildCounterparties(C);return{walletAddress:n,chain:o||"default",resolvedToken:y?{symbol:y,name:k,contractAddress:b?.[0]}:null,filters:{tokenSymbol:g||null,contractAddresses:b||null,direction:h,limit:a,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:u??null},pagination:{cursor:w.data?.cursor??null,pageSize:w.data?.page_size??a,page:w.data?.page??null,hasMore:!!w.data?.cursor},transferCount:C.length,transfers:C,counterparties:N}}async resolveContractAddressBySymbol(e,t,n){let o=e.toLowerCase(),s=await this.service.getWalletTokenBalances({address:t,chain:n});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}let a=await this.service.searchTokensByKey({key:e,chain:n});if(a.success&&a.data?.length){let l=a.data.find(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}buildCounterparties(e){let t=new Map,n=new Map;for(let s of e){let a=s.direction==="send"?t:n,i=s.counterparty.toLowerCase(),l=parseFloat(s.amount_formatted)||0,c=a.get(i);c?(c.total+=l,c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):a.set(i,{label:s.counterparty_label,entity:s.counterparty_entity,total:l,count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,total_amount:i.total.toFixed(6).replace(/\.?0+$/,""),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:o(t),received:o(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var xr=class extends S{name="get-wallet-nft-transfers";description=`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=pe(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.includePrices=="boolean"?e.includePrices:void 0,h=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",g=h==="send"?"send":h==="receive"?"receive":"all",b=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(C=>typeof C=="string"&&!!C).map(C=>C.trim()):void 0,y=await this.service.getWalletNftTransfers({address:n,chain:o,contractAddresses:b,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:m,includePrices:f});if(!y.success)return{error:y.error||"Failed to fetch NFT transfers"};let k=n.toLowerCase(),v=(y.data?.result||[]).map(C=>{let N=C.from_address.toLowerCase()===k,R=N?"send":"receive",V=N?C.to_address:C.from_address,E=N?C.to_address_label??void 0:C.from_address_label??void 0,ce=N?C.to_address_entity??void 0:C.from_address_entity??void 0;return{...C,direction:R,counterparty:V,counterparty_label:E,counterparty_entity:ce}}),T=g==="all"?v:v.filter(C=>C.direction===g),P=this.buildCounterparties(T);return{walletAddress:n,chain:o||"default",filters:{contractAddresses:b||null,direction:g,limit:a,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:u??null,includePrices:f??null},pagination:{cursor:y.data?.cursor??null,pageSize:y.data?.page_size??a,page:y.data?.page??null,hasMore:!!y.data?.cursor},transferCount:T.length,transfers:T,counterparties:P}}buildCounterparties(e){let t=new Map,n=new Map;for(let s of e){let a=s.direction==="send"?t:n,i=s.counterparty.toLowerCase(),l=s.token_name??s.token_address,c=a.get(i);c?(c.tokenIds.add(s.token_id),c.collections.add(l),c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):a.set(i,{label:s.counterparty_label,entity:s.counterparty_entity,tokenIds:new Set([s.token_id]),collections:new Set([l]),count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,token_ids:Array.from(i.tokenIds),collections:Array.from(i.collections),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:o(t),received:o(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Pm=["all","7","30","60","90"],Cr=class extends S{name="get-wallet-pnl-summary";description=`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=te(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=Pm.includes(s)?s:void 0;if(o){let h=await this.service.getWalletPnlSummary({address:n,chain:o,days:a});return h.success?{walletAddress:n,chain:o,days:a??"all",summary:this.mapSummary(h.data)}:{error:h.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(Ce().map(async h=>{let g=await this.service.getWalletPnlSummary({address:n,chain:h,days:a});return{chain:h,data:g.success?g.data:void 0}}))).flatMap(h=>h.data&&h.data.total_count_of_trades>0?[{chain:h.chain,data:h.data}]:[]),c=l.map(h=>({chain:A(h.chain),summary:this.mapSummary(h.data)})),u=l.reduce((h,g)=>h+Number(g.data.total_realized_profit_usd||0),0),d=l.reduce((h,g)=>h+Number(g.data.total_bought_volume_usd||0),0),p=l.reduce((h,g)=>h+Number(g.data.total_sold_volume_usd||0),0),m=l.reduce((h,g)=>h+Number(g.data.total_trade_volume||0),0),f={totalCountOfTrades:l.reduce((h,g)=>h+g.data.total_count_of_trades,0),totalTradeVolume:m,totalRealizedProfitUsd:u,totalRealizedProfitPercentage:d>0?u/d*100:0,totalBuys:l.reduce((h,g)=>h+g.data.total_buys,0),totalSells:l.reduce((h,g)=>h+g.data.total_sells,0),totalBoughtVolumeUsd:d,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:a??"all",summary:f,chains:c}}mapSummary(e){return{totalCountOfTrades:e.total_count_of_trades,totalTradeVolume:e.total_trade_volume,totalRealizedProfitUsd:e.total_realized_profit_usd,totalRealizedProfitPercentage:e.total_realized_profit_percentage,totalBuys:e.total_buys,totalSells:e.total_sells,totalBoughtVolumeUsd:e.total_bought_volume_usd,totalSoldVolumeUsd:e.total_sold_volume_usd}}};var Sm=["all","7","30","60","90"],da=25,Rr=class extends S{name="get-wallet-pnl";description=`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${da}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${da}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${da}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=te(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=Sm.includes(s)?s:void 0,i=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[],l=Array.isArray(e.tokenAddresses)?e.tokenAddresses.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[];if(o){let d=await this.fetchChainPnl(n,o,a,i,l);return d.ok?{walletAddress:n,chain:o,days:a??"all",filters:{tokenAddresses:d.tokenAddresses??null,resolvedSymbols:d.resolvedFromSymbols.length>0?d.resolvedFromSymbols:null,unresolvedSymbols:d.unresolvedSymbols.length>0?d.unresolvedSymbols:null},tokenCount:d.tokens.length,tokens:d.tokens}:{error:d.error||"Failed to fetch wallet PnL"}}let u=(await Promise.all(Ce().map(async d=>({chain:d,res:await this.fetchChainPnl(n,d,a,i,l)})))).filter(d=>d.res.ok&&d.res.tokens.length>0).map(d=>({chain:A(d.chain),tokenCount:d.res.tokens.length,tokens:d.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:a??"all",filters:{requestedSymbols:i.length>0?i:null,requestedAddresses:l.length>0?l:null},tokenCount:u.reduce((d,p)=>d+p.tokenCount,0),chains:u}}async fetchChainPnl(e,t,n,o,s){let a=[],i=[];o.length>0&&(await Promise.all(o.map(p=>this.resolveContractAddress(p,t,e)))).forEach((p,m)=>{p?a.push({symbol:o[m],address:p.address}):i.push(o[m])});let l=xm([...a.map(d=>d.address),...s]).slice(0,da),c=l.length>0?l:void 0,u=await this.service.getWalletPnl({address:e,chain:t,days:n,tokenAddresses:c});return{ok:u.success,error:u.error,tokens:u.data?.result??[],tokenAddresses:c,resolvedFromSymbols:a,unresolvedSymbols:i}}async resolveContractAddress(e,t,n){let o=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};function xm(r){let e=new Set,t=[];for(let n of r){let o=n.toLowerCase();e.has(o)||(e.add(o),t.push(n))}return t}var Cm=BigInt(2)**BigInt(255),Er=class extends S{name="get-wallet-approvals";description=`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=pe(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):100,i=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,l=await this.service.getWalletApprovals({address:n,chain:o,limit:a,cursor:i});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,d=(c.result||[]).map(h=>Rm(h)),p=0,m=0,f=[];for(let h of d){h.isUnlimited&&(m+=1);let g=parseFloat(h.token.usdAtRisk??"");Number.isFinite(g)&&(p+=g);let b=h.token.possibleSpam||h.token.verifiedContract===!1,y=!h.spender.label&&!h.spender.entity;(b||h.isUnlimited&&y)&&f.push(h)}return{walletAddress:n,chain:o||"default",filters:{limit:a,cursor:i??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??a,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:d.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:f.length},approvals:d,riskyApprovals:f}}};function Rm(r){let e=Em(r.value);return{blockNumber:r.block_number,blockTimestamp:r.block_timestamp??null,transactionHash:r.transaction_hash??null,value:r.value,valueFormatted:r.value_formatted??null,isUnlimited:e,token:{address:r.token.address,addressLabel:r.token.address_label??null,name:r.token.name??null,symbol:r.token.symbol??null,logo:r.token.logo??null,possibleSpam:!!r.token.possible_spam,verifiedContract:r.token.verified_contract??null,currentBalance:r.token.current_balance??null,currentBalanceFormatted:r.token.current_balance_formatted??null,usdPrice:r.token.usd_price??null,usdAtRisk:r.token.usd_at_risk??null},spender:{address:r.spender.address,label:r.spender.address_label??null,entity:r.spender.entity??null,entityLogo:r.spender.entity_logo??null}}}function Em(r){if(!r)return!1;try{return BigInt(r)>=Cm}catch{return!1}}var _r=class extends S{name="get-wallet-defi-positions";description=`The BROAD, cross-protocol inventory of every DeFi position a wallet holds \u2014 liquidity provision, staking, borrowing AND supply/lending alike \u2014 with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Any APY here is the LIVE SPOT rate. Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "What is my health factor?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited funds \u2014 "what am I earning", "my supply APY", "my savings/deposits", "my Aave supply" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Use this tool for supply positions only as part of a full portfolio sweep, or for assets it does not cover (it handles USDC only). Never report both tools' APY for the same position. Also not for: positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=te(e.chain,t);if(o){let i=await this.service.getWalletDefiPositions({address:n,chain:o});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=i.data||[];return{walletAddress:n,chain:o,positionCount:l.length,positions:l.map(Jc)}}let a=(await Promise.all(Ce().map(async i=>{let l=await this.service.getWalletDefiPositions({address:n,chain:i});return{chain:i,rows:l.success?l.data||[]:[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:A(i.chain),positionCount:i.rows.length,positions:i.rows.map(Jc)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:n,chain:"all",positionCount:a.reduce((i,l)=>i+l.positionCount,0),chains:a}}};function Jc(r){return{protocolName:r.protocol_name,protocolId:r.protocol_id,protocolUrl:r.protocol_url,protocolLogo:r.protocol_logo,accountHealthFactor:r.account_data?.health_factor??null,position:_m(r.position)}}function _m(r){return{label:r.label,address:r.address,balanceUsd:r.balance_usd,totalUnclaimedUsdValue:r.total_unclaimed_usd_value,tokens:(r.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:r.position_details??null}}var Nr=class extends S{name="get-wallet-defi-protocol-positions";description=`Get every position a wallet holds inside ONE specific DeFi protocol \u2014 liquidity provision, staking, borrowing and supply alike \u2014 with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Any APY here is the LIVE SPOT rate. Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "show my Lido staking", "my Curve pools", "Pendle positions", "how much did I borrow on Aave", "what do I have on Aave v3". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited USDC \u2014 "my Aave v3 supply", "what am I earning on Spark", "my Compound deposit" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Come back here for that protocol's borrow / LP / staking side, or for supplied assets other than USDC. Never report both tools' APY for the same position. Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-positions to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=e.protocol?.trim();if(!n)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let o=ne(e.address,t),s=te(e.chain,t);if(s){let l=await this.service.getWalletDefiProtocolPositions({address:o,protocol:n,chain:s});return l.success?l.data?{walletAddress:o,chain:s,...this.protocolFields(l.data)}:{error:"No data returned for this protocol"}:{error:l.error||"Failed to fetch wallet DeFi protocol positions"}}let i=(await Promise.all(Ce().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:n,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:A(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${n} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:o,chain:"all",protocol:n,totalUsdValue:i.reduce((l,c)=>l+c.totalUsdValue,0),chains:i}}protocolFields(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,accountHealthFactor:e.account_data?.health_factor??null,positionCount:(e.positions||[]).length,positions:(e.positions||[]).map(Nm)}}};function Nm(r){return{label:r.label,address:r.address,balanceUsd:r.balance_usd,totalUnclaimedUsdValue:r.total_unclaimed_usd_value,tokens:(r.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:r.position_details??null}}function Im(r){try{return(Number(BigInt(r))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return r}}var Ir=class extends S{name="get-transaction-by-hash";description='Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.';category="blockchain-data";parameters=[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=e.transactionHash;if(!n)return{error:"Transaction hash is required."};let o=pe(e.chain,t),s=await this.service.getTransactionByHash({transactionHash:n,chain:o});if(!s.success||!s.data)return{error:s.error||"Failed to fetch transaction"};let a=s.data,i=(a.logs??[]).filter(c=>!!c.decoded_event).map(c=>({contract:c.address,signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params})),l=a.logs.map(c=>({address:c.address,decodedEvent:c.decoded_event?{signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params}:null}));return{hash:a.hash,status:a.receipt_status==="1"?"success":a.receipt_status==="0"?"failed":"unknown",timestamp:a.block_timestamp,blockNumber:a.block_number,from:{address:a.from_address,label:a.from_address_label||null,entity:a.from_address_entity||null},to:a.to_address?{address:a.to_address,label:a.to_address_label||null,entity:a.to_address_entity||null}:null,valueEth:Im(a.value||"0"),fee:a.transaction_fee,gasUsed:a.receipt_gas_used,gasPriceGwei:a.gas_price?(Number(a.gas_price)/1e9).toFixed(4):null,decodedCall:a.decoded_call?{signature:a.decoded_call.signature,label:a.decoded_call.label,params:a.decoded_call.params}:null,decodedEvents:i,contractCreated:a.receipt_contract_address||null,logs:l}}};var Zc=new Map;function Um(r){let e=Zc.get(r);if(e)return e;let t=qt({rpcUrl:r});return Zc.set(r,t),t}async function eu(r,e,t=[]){let n=await Um(r).rpc(e,t);if(n===void 0)throw new Error(`RPC ${e}: empty result`);return n}function tu(r,e,t){return eu(r,"eth_call",[{to:e,data:t},"latest"])}async function Lm(r,e,t){let n=bn(r);if(!n)return null;try{return await tu(n,e,t)}catch{return null}}function M(r,e){globalThis.__LENDING_DEBUG__!==!1&&(e===void 0?console.log(`[LEND] ${r}`):console.log(`[LEND] ${r}`,JSON.stringify(e,Dm)))}function Dm(r,e){return typeof e=="bigint"?`${e}n`:e}var Om=6e4,rl=new Map;async function cs(r,e){let t=At(e),n=t?parseInt(t,16):NaN;if(!t||!Number.isFinite(n))return[];let o=`${r}|${t}`,s=rl.get(o);if(s&&Date.now()-s.at<Om)return s.markets;let a=Mm(r,t,n),i=a.then(l=>l.markets);return rl.set(o,{at:Date.now(),markets:i}),a.then(l=>{l.answered||rl.delete(o)}),i}async function pa(r,e){return(await cs(r,e)).length>0}async function Mm(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:I(o)}),{markets:[],answered:a}}let s=(o.data?.data?.items||[]).flatMap(a=>{let i=Fm(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 nu(r,e){let t=e.trim().toLowerCase();if(!t)return[];if(_(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 Fm(r,e){if(r?.isDeleted===!0)return null;let t=typeof r?.contract=="string"?r.contract.toLowerCase():"";if(!_(t))return null;let n=typeof r?.token=="string"&&_(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:Be(s),protocolUrl:r?.protocolId?.domain?.trim()||null,type:s,contract:t,token:n,platformScore:Number.isFinite(o)?o:null}}function ol(){return Ce()}async function ma(r){let e=ol(),t=await Promise.all(e.map(n=>pa(r,n)));return e.filter((n,o)=>t[o])}async function ha(r,e){let t=q(e);return t?pa(r,t):!1}async function ru(r,e){let t=e.map(s=>q(s)).filter(s=>!!s),n=[...new Set(t)],o=await Promise.all(n.map(s=>pa(r,s)));return n.filter((s,a)=>o[a])}function Ur(r){return as(r)}var ou=5;async function su(r,e,t){let n=e.map(b=>_(b)?b.toLowerCase():null);if(n.every(b=>b===null))return M("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let o=ia(r),s;try{M("discovery: probing 5 accessors per token",{chain:r,tokens:n,psm:o}),s=await de(r,[...n.flatMap(b=>b?Bm(b):[]),...o?Wc(o):[]])}catch(b){return M("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:r,message:b?.message}),e.map(()=>null)}let a=o?s.slice(s.length-Yc):[],i=Y(a[0])?.toLowerCase()??null,l=Y(a[1]),c=Y(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(b=>{if(!b)return null;let y=s.slice(d,d+ou);return d+=ou,M("discovery: probe answers",{token:b,"POOL()":Y(y[0]),"UNDERLYING_ASSET_ADDRESS()":Y(y[1]),"baseToken()":Y(y[2]),"asset()":Y(y[3]),"vsr()":j(y[4])?.toString()??null}),{token:b,slice:y}}),m=new Set;for(let b of p){if(!b)continue;let y=Y(b.slice[0]);y&&Y(b.slice[1])&&m.add(y.toLowerCase())}let f=await qm(r,[...m]);m.size>0&&M("discovery: Aave pool authentication",{claimed:[...m],genuine:[...f]});let h=p.flatMap(b=>b?Y(b.slice[0])&&Y(b.slice[1])||Y(b.slice[2])?[]:Y(b.slice[3])?[b.token]:[]:[]),g=await $m(r,[...new Set(h)],t);return h.length>0&&M("discovery: Morpho vault lookup",{asked:[...new Set(h)],recognised:[...g.keys()]}),p.map(b=>{if(!b)return null;let{token:y,slice:k}=b,w={chain:r,protocolUrl:null,token:y,platformScore:null};if(u&&y===u.susds)return M("discovery: classified",{token:y,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:u.oracle}),{...w,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:Be("spark-l2-susds"),protocolUrl:Ur("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let v=Y(k[0]);if(v&&Y(k[1])){let T=f.has(v.toLowerCase());return M("discovery: classified",{token:y,as:T?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:v}),T?{...w,name:"Aave v3",protocol:"AAVE",protocolLabel:Be("aave-v3"),protocolUrl:Ur("aave-v3"),type:"aave-v3",contract:v}:null}if(Y(k[2]))return M("discovery: classified",{token:y,as:"compound-v3"}),{...w,name:"Compound v3",protocol:"COMPOUND",protocolLabel:Be("compound-v3"),protocolUrl:Ur("compound-v3"),type:"compound-v3",contract:y};if(Y(k[3])){if(g.has(y)){M("discovery: classified",{token:y,as:"morpho-v2"});let C=g.get(y)||"Morpho V2";return{...w,name:C,protocol:"MORPHO",protocolLabel:Be("morpho-v2"),protocolUrl:Ur("morpho-v2"),type:"morpho-v2",contract:y}}let P=j(k[4])!==null;return M("discovery: classified",{token:y,as:P?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),P?{...w,name:"Spark",protocol:"SPARK",protocolLabel:Be("spark-ethereum"),protocolUrl:Ur("spark-ethereum"),type:"spark-ethereum",contract:y}:{...w,name:"Spark",protocol:"SPARK",protocolLabel:Be("spark"),protocolUrl:Ur("spark"),type:"spark",contract:y}}return M("discovery: classified",{token:y,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function Bm(r){return[{target:r,callData:F({abi:gr,functionName:"POOL"})},{target:r,callData:F({abi:gr,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:r,callData:F({abi:Tt,functionName:"baseToken"})},{target:r,callData:F({abi:st,functionName:"asset"})},{target:r,callData:F({abi:fr,functionName:"vsr"})}]}async function qm(r,e){if(e.length===0)return new Set;try{let t=await de(r,e.map(n=>({target:n,callData:F({abi:Xi,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((n,o)=>Y(t[o])!==null))}catch{return new Set}}async function $m(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 Hm=.01;function Vm(r){return r.reduce((e,t)=>t.conditions===null?e+t.apyPercent:e,0)}function Wm(r,e){if(typeof e!="string"||!e.trim())return;let t=e.trim(),n=Ko();n[r]!==t&&fn({...n,[r]:t})}var Lr=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=At(e);s&&Wm(s,n);let a=s?is(s):null,i=[...new Set(t.filter(_).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 su(s,i,this.endpoints.morphoApiUrl),u=[...new Map(i.flatMap((p,m)=>{let f=l[m];return M("describeReceiptTokens: discovery result",{token:p,found:!!f,protocol:f?.protocol,type:f?.type,contract:f?.contract}),f?[[p,f]]:[]})).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,baseApyPercent:p.baseApyPercent,rewardApyPercent:p.rewardApyPercent,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}),!_(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.address))return[];let t=await ru(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=At(e),o=n?is(n):null;return n&&o?this.describer.describe(n,o,t):[]}async positionsForChain(e,t){let n=is(e),o=await cs(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<Hm?[]:[{...l,suppliedUsdc:u,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:u*(l.avgApyPercent+Vm(l.rewards))/100}]})}};var sl=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Dr=class{constructor(e){this.coinPoolBaseUrl=e}coinPoolBaseUrl;async listChains(){return ma(this.coinPoolBaseUrl)}async isSupported(e){return ha(this.coinPoolBaseUrl,e)}async getMarkets(e){let t=q(e);return t?cs(this.coinPoolBaseUrl,t):[]}async findMarket(e,t){let n=await this.getMarkets(e);return nu(n,t)}canSupply(e){return sl.includes(e.type)}async readReceiptToken(e,t){let n=jt(t).balanceIsUnderlying;try{let o=await de(e,[{target:t.token,callData:F({abi:H,functionName:"symbol"})},{target:t.token,callData:F({abi:H,functionName:"decimals"})}]);return{symbol:Mn(o[0]),decimals:Fn(o[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}};var Ym={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},Gm={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"},Km={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},jm={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function ga(r){let e=rh(r.chain);return(e===null?null:zm(r,e))??as(r.type)??nh(r,e)}function zm(r,e){switch(r.type){case"morpho-v2":{let t=Ym[e];if(!t||!r.contract)return null;let n=`https://app.morpho.org/${t}/vault/${al(r.contract)}`,o=Jm(r.name);return o?`${n}/${o}`:n}case"aave-v3":{let t=Gm[e],n=Xm(r);return!t||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${al(n)}&marketName=${t}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let t=Km[e],n=eh(r);return!t||!n?null:`https://app.spark.fi/savings/${t}/${n}`}case"compound-v3":{let t=jm[e],n=Zm(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 Qm=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Jm(r){let e=r?.trim().toLowerCase()||"";return!e||Qm.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Zm(r){let e=r.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function eh(r){let e=r.shareSymbol?.trim().toLowerCase()||"";if(/^[a-z0-9]{2,12}$/.test(e))return e;let t=`${r.name||""} ${r.token||""}`.toLowerCase();for(let o of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(t.includes(o))return o;if(r.type==="spark-ethereum")return th[r.contract?.trim().toLowerCase()||""]??null;let n=r.asset?.symbol?.trim().toLowerCase()||"";return!/^[a-z0-9]{2,11}$/.test(n)||n.startsWith("s")?null:`s${n}`}var th={"0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f":"speth","0x80128dbb9f07b93dde62a6daeadb69ed14a7d354":"sppyusd","0xe2e7a17dff93280dec073c995595155283e3c372":"spusdt","0x28b3a8fb53b741a8fd78c0fb9a6b2393d896a43d":"spusdc","0x45d91340b3b7b96985a72b5c678f7d9e8d664b62":"spusdt","0xc358c90d32375721cb3924320fdc2f8b694347ca":"spusdt","0xde770c84fe66e063336b31737cfe9790f18c4087":"spusdg"};function nh(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",al(r.contract)),o.toString()}catch{return n}}function al(r){let e=r.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function rh(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 oh=new Set(["spark","spark-ethereum","spark-l2-susds"]),sh=8;function ah(r,e,t){if(r.market.type!=="spark-l2-susds")return j(e);let n=j(e);return n===null||r.tokenDecimals===null?null:An(r.rawBalance,n,r.tokenDecimals,t)}var fa=class{constructor(e){this.endpoints=e}endpoints;apyLimiter=new il(sh);pantograph=new le;async describe(e,t,n){if(n.length===0)return[];M("describe: START",{chain:e,count:n.length,types:n.map(l=>l.type)});let{assets:o,shareSymbols:s}=await this.resolveAssets(e,n);M("describe: assets resolved",o);let[a,i]=await Promise.all([this.readMarketState(e,n,o),Promise.all(n.map((l,c)=>this.apyLimiter.run(()=>this.fetchApy(l,t,o[c]))))]);return M("describe: on-chain state",a),M("describe: APY fetched",i.map((l,c)=>({type:n[c].type,rawSamples:l.samples.length,sourceCurrent:l.current}))),n.map((l,c)=>{let{totalSuppliedUsdc:u,liveApyFraction:d}=a[c],p=lh(i[c].samples,d??i[c].current,i[c].rewards,i[c].avgOverride??null);return M("describe: summarised",{market:l.name,type:l.type,liveFrom:d!==null?"on-chain":i[c].current!==null?"api":"none",rawSamples:i[c].samples.length,historyPoints:p.history.length,currentApyPercent:p.currentApyPercent,avgApyPercent:p.avgApyPercent,apyChangePercent:p.apyChangePercent,totalSuppliedUsdc:u,asset:o[c]?.symbol}),{...l,protocolUrl:ga({...l,asset:o[c],shareSymbol:s[c]}),asset:o[c],totalSuppliedUsdc:u,avgApyPercent:p.avgApyPercent,currentApyPercent:p.currentApyPercent,baseApyPercent:p.baseApyPercent,rewardApyPercent:p.rewardApyPercent,rewards:p.rewards,apyChangePercent:p.apyChangePercent,apyHistory:p.history}})}async readBalances(e,t,n){let o=F({abi:H,functionName:"balanceOf",args:[t]}),s=F({abi:H,functionName:"decimals"}),a=n.flatMap(l=>[{target:l.token,callData:o},{target:l.token,callData:s}]),i=await de(e,a);return n.flatMap((l,c)=>{let u=j(i[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:Fn(i[c*2+1])}]})}async convertToUnderlying(e,t,n){let o=[],s=t.map(i=>{let l=jt(i.market).convertToAssetsCall(i.market,i.rawBalance);return l?(o.push(l),o.length-1):-1}),a=await de(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 Fe(i.rawBalance,c);let u=ah(i,a[s[l]],c);return u===null?Fe(i.rawBalance,i.tokenDecimals??c):Fe(u,c)})}async resolveAssets(e,t){let n={address:Pn,decimals:NaN,symbol:null,logo:null},o=[],s=t.map(p=>{let m=jt(p).underlyingCall(p);return m?(o.push(m),o.length-1):-1}),a;try{let p=o.length>0?await de(e,o):[];a=s.map(m=>m<0?null:Y(p[m]))}catch{a=t.map(()=>null)}a=a.map((p,m)=>p??t[m]?.assetAddress??null);let i=[...new Set(a.filter(p=>!!p).map(p=>p.toLowerCase()))],[l,c,u]=await Promise.all([this.readAssetMetadata(e,i),this.fetchAssetLogos(e,i),this.readShareSymbols(e,t)]);return{assets:a.map(p=>{if(!p)return n;let m=p.toLowerCase(),f=l.get(m),h=c.get(m)??null;return f?.decimals!==null&&f?.decimals!==void 0?{address:p,decimals:f.decimals,symbol:f.symbol??null,logo:h}:{address:p,decimals:NaN,symbol:null,logo:h}}),shareSymbols:u}}async readShareSymbols(e,t){let n=F({abi:H,functionName:"symbol"}),o=[],s=t.map(a=>!oh.has(a.type)||!a.contract?-1:(o.push({target:a.contract,callData:n}),o.length-1));if(o.length===0)return t.map(()=>null);try{let a=await de(e,o);return s.map(i=>i<0?null:Mn(a[i]))}catch{return t.map(()=>null)}}async readAssetMetadata(e,t){let n=new Map;if(t.length===0)return n;let o=F({abi:H,functionName:"decimals"}),s=F({abi:H,functionName:"symbol"});try{let a=await de(e,t.flatMap(i=>[{target:i,callData:o},{target:i,callData:s}]));t.forEach((i,l)=>{n.set(i,{decimals:Fn(a[l*2]),symbol:Mn(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=jt(u),m=n[d],f={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&&(f.rate=o.length,o.push(h)),f}),a=await de(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 de(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 jt(e).fetchApy(e,t,this.endpoints,n);return M("fetchApy: got",{market:e.name,samples:o.samples.length,current:o.current,avgOverride:o.avgOverride??null}),o}catch(o){return M("fetchApy: FAILED \u2014 market listed without APY",{market:e.name,type:e.type,message:o?.message}),{samples:[],current:null,rewards:[]}}}},il=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 ih(r,e){let t=Jo(Date.now()),n=new Map,o=null;for(let i of r)!Number.isFinite(i.timeMs)||!Number.isFinite(i.fraction)||i.fraction<0||Jo(i.timeMs)>t||((!o||i.timeMs>o.timeMs)&&(o=i),n.set(i.timeMs,i.fraction));let s=[...n.entries()].sort((i,l)=>i[0]-l[0]).map(([i,l])=>({date:new Date(i).toISOString(),apyPercent:l*100})),a=e??(o&&Jo(o.timeMs)===t?o.fraction:null);return{history:s,live:a}}function lh(r,e,t=[],n=null){let{history:o,live:s}=ih(r,e),a=s===null?null:s*100,i=t.map(m=>({apyPercent:m.fraction*100,tokenSymbol:m.tokenSymbol,conditions:m.conditions})),l=i.length===0?null:i.reduce((m,f)=>m+f.apyPercent,0),c=a===null?null:a+(l??0),u={baseApyPercent:a,rewardApyPercent:l,rewards:i},d=n!==null&&Number.isFinite(n)?n*100:null;if(o.length===0)return{history:o,avgApyPercent:d,currentApyPercent:c,apyChangePercent:null,...u};let p=o.reduce((m,f)=>m+f.apyPercent,0);return{history:o,avgApyPercent:d??p/o.length,currentApyPercent:c,apyChangePercent:uh(o,a),...u}}var au=3600*1e3,ch=au/2;function uh(r,e){if(e===null)return null;let t=Date.now()-au,n=null,o=Number.POSITIVE_INFINITY;for(let s=r.length-1;s>=0;s--){let a=Math.abs(Date.parse(r[s].date)-t);if(a>o)break;o=a,n=r[s]}return!n||o>ch?null:e-n.apyPercent}function iu(r,e){if(!Number.isFinite(r))return r;let t=10**e,n=Number((r*t).toPrecision(15));return(r<0?-Math.floor(-n):Math.floor(n))/t+0}var ze=class{read;supply;constructor(e={}){let t=e.coinPoolBaseUrl||"https://api.coinpool.app",n={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 fa(n);this.read=new Lr(t,n,o),this.supply=new Dr(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 us="{market}",uu=[{name:"detail_button_label",type:"string",description:`Label for the per-market "More detail" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Just the words "More detail" translated: English "More detail", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the market in it and do NOT use the "{market}" placeholder \u2014 each button is rendered on that market's own card with its name directly above, so repeating the name only makes every card wordier. Keep it to one or two words so it fits on one line.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this market in detail" request template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "show me details of {market}". Vietnamese example: "xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng {market}". Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],ba=[{name:"supply_button_label",type:"string",description:`Label template for the "Supply" button \u2014 shown on EVERY market you list, and on the single market you describe \u2014 IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it; the button is rendered automatically. Unlike the "More detail" label, this one DOES name the market: it is the button that moves money. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". IN JAPANESE the label MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 render "supply" as the katakana \u30B5\u30D7\u30E9\u30A4, NEVER as \u4F9B\u7D66, \u9810\u3051\u5165\u308C, \u5165\u91D1 or any other kanji wording. Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "supply to {market}". Vietnamese example: "n\u1EA1p v\xE0o {market}". IN JAPANESE it MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 use the katakana \u30B5\u30D7\u30E9\u30A4, NEVER \u4F9B\u7D66 or another kanji wording. Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],du="[[LIST]]",pu=' The market list is ALREADY RENDERED as cards below your reply \u2014 each card is numbered and shows the market name (linked to its page), its chain and its live APY, with its own "More detail" and "Supply" buttons. Do NOT write the list out in your text: no numbered list, no bullet list, no per-market lines, no links, and no mention of the buttons or of tapping one. Anything you write is shown ABOVE the cards, so repeating them just prints the same list twice. Naming the ONE market that tops the ordering, with its rate, is not repeating the list and is allowed where your other instructions say so \u2014 what is banned is walking through the markets one by one. Do NOT tell the user to supply, or push them toward it: the button is there if they want it, and this step has not shown them enough to judge a market.',mu=' A clickable "Supply" button for this market is shown below your reply automatically \u2014 do NOT repeat it in your text, do NOT tell the user to tap it, and do NOT describe it as a button, form or screen; just deliver the analysis.';function hu(r,e,t){let[n]=dh([r],e,t),[o]=r.canSupply?ll(r,e,t):[];return{name:r.name?.trim()||r.protocol,protocol:r.protocol,protocolUrl:r.protocolUrl,chain:t,apyPercent:r.apyPercent,detailPrompt:n?.prompt??"",detailLabel:n?.label??"",supplyPrompt:o?.prompt??"",supplyLabel:o?.label??""}}function dh(r,e,t){return gu(r,{labelTemplate:ya(e.detail_button_label),promptTemplate:ya(e.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${us}`,...t===void 0?{}:{chainName:t}})}function ll(r,e,t){return gu([r],{labelTemplate:ya(e.supply_button_label),promptTemplate:ya(e.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${us}`,promptFallback:`supply to ${us}`,...t===void 0?{}:{chainName:t},max:1})}function gu(r,e){let t=typeof e.chainName=="string"?e.chainName.trim():"",n=[],o=new Set;for(let s of r){if(e.max!==void 0&&n.length>=e.max)break;let a=s.name?.trim();!a||o.has(a.toLowerCase())||(o.add(a.toLowerCase()),n.push({label:lu(e.labelTemplate,a,e.labelFallback,e.labelNamesMarket===!0),prompt:lu(ph(e.promptTemplate),a,e.promptFallback)+mh(s.contract,t)}))}return n}function ph(r){let[e,t]=[r[0],r[1]];return e===void 0||e===e.toLowerCase()||t!==void 0&&t!==t.toLowerCase()?r:e.toLowerCase()+r.slice(1)}function ya(r){return typeof r=="string"?r:""}function mh(r,e){let t=r?.trim();if(!t||!/^0x[a-fA-F0-9]{40}$/.test(t))return"";let n=e?.trim();return n?` (market: ${t} - ${n})`:` (market: ${t})`}function lu(r,e,t,n=!0){let s=r&&(!n||r.includes(us))?r:t;return hh(s).split(us).join(e).replace(/\s+/g," ").trim()}var cu="{chain}";function hh(r){if(!r.includes(cu))return r;let e=cu.replace(/[{}]/g,"\\$&");return r.replace(new RegExp(`\\s*\\S+\\s*${e}`,"g"),"").replace(new RegExp(`${e}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(e,"g"),"")}var wa=[{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"]}],ul=wa.map(r=>r.label),cl={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 fu(r){let e=typeof r=="string"?r.trim():"";if(!e)return{kind:"none"};let t=bh(e);if(!t)return{kind:"none"};let n=gh(t);if(n){let s=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>s.has(a.type)}}let o=yh(t);return o?{kind:"unsupported",label:o,requested:e}:{kind:"unknown",requested:e}}function gh(r){let e=wa.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=wa.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 fh(r)}function fh(r){let e=null,t=!1;for(let n of wa)for(let o of n.aliases){let s=yu(o);if(s===0||Math.abs(o.length-r.length)>s)continue;let a=bu(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 yu(r){return r.length<=4?0:r.length<=9?2:3}function yh(r){let e=cl[r];if(e)return e;if(r.length>=4){let o=new Set(Object.entries(cl).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(cl)){let a=yu(o);if(a===0||Math.abs(o.length-r.length)>a)continue;let i=bu(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 bh(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function bu(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]}function ae(r,e){return r==null?null:iu(r,e)}var Te=2,zt=2;function ka(r){let e=ae(r.currentApyPercent,Te),t=r.rewards.map(s=>({apyPercent:ae(s.apyPercent,Te)??0,tokenSymbol:s.tokenSymbol,conditions:s.conditions})),n=r.rewardApyPercent===null?null:t.reduce((s,a)=>s+Math.round(a.apyPercent*100),0)/100;if(n===null||e===null)return{currentApyPercent:e,rewardApyPercent:n,rewards:t,baseApyPercent:ae(r.baseApyPercent,Te)};let o=Math.round(e*100)-Math.round(n*100);return{currentApyPercent:e,rewardApyPercent:n,rewards:t,baseApyPercent:o/100}}var wh=["apy","score","size"],wu=3,ku=40,Or=class extends S{name="get-lending-markets";kind="ui";description='BROWSE the LENDING / SUPPLY markets available to deposit into and earn yield on (Aave v3, Compound v3, Spark, Morpho vaults). Returns a deliberately SHORT shortlist row per market: its name, its page on the protocol, and its live supply APY \u2014 nothing else. Ranked by that live APY by default, and filterable to ONE protocol via `protocol`. Each market gets a "More detail" button \u2014 how the user reaches its size, recent average APY, reward split and platform score \u2014 and a "Supply" button that starts a deposit. So this tool answers "what is out there", NOT "is this one worth it". Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. The same applies to CHAINS and ASSETS: the market list is fetched live, so never answer "we have no markets on X" or "we only support USDC" from memory \u2014 call the tool and report what it returns. Do NOT use for: everything about ONE named market (size, score, average APY, rewards, whether it is a good place to put money) \u2192 get-lending-market-detail; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:`Hex chain ID to scope the list to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry markets is resolved at call time, so never filter the request against a list you remember. Set it ONLY when the user names a chain; otherwise OMIT it \u2014 the connected wallet's chain is used, or every chain at once when no wallet is connected. Never guess a chain to work around a wallet connected to one without lending markets.`,required:!1},{name:"protocol",type:"string",description:`Scope the list to ONE lending protocol. Supported: ${ul.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-${ku}. Default ${wu} \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},...uu,...ba];service;constructor(e){super(),this.service=new ze(e)}async run(e,t){let n=te(e.chain,void 0),o=n?null:q(t?.chain),s=n??o,a=s?await this.service.isSupported(s):!1,i=a?[]:await this.service.listSupportedChains();if(s&&!a)return{_instructions:`There are no lending markets on ${A(s)}`+(o?", the chain the wallet is currently connected to":"")+". Tell the user that in their language and name the chains that DO have them (in `chainsWithLendingMarkets`), offering to list those instead. Do NOT mention tool names.",chain:A(s),connectedChainHasNoMarkets:o!==null,marketCount:0,marketNames:[],chainsWithLendingMarkets:i.map(y=>A(y))};let l=fu(e.protocol);if(l.kind==="unsupported"||l.kind==="unknown")return this.unsupportedProtocol(l);let c=s?[s]:i,u=vh(e.sort),d=Th(e.limit),p=await this.service.getMarketOverviews({chains:c}),m=l.kind==="supported"?p.filter(y=>l.matches(y)):p;if(l.kind==="supported"&&m.length===0&&p.length>0)return{_instructions:`There are no ${l.label} lending markets on ${s?A(s):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${l.label} market. Do NOT mention tool names.`,requestedProtocol:l.label,chain:s?A(s):"all",marketCount:0,marketNames:[],protocolsAvailable:[...new Set(p.map(y=>y.protocol))]};let f=[...m].sort(kh[u]).slice(0,d),h=f.map(y=>hu({name:y.name,contract:y.contract,protocol:y.protocol,protocolUrl:y.protocolUrl,apyPercent:ae(y.currentApyPercent,Te),canSupply:this.service.supply.canSupply(y)},e,A(y.chain))),b={component:"LendingMarketList",props:{chain:s?A(s):"all",multiChain:new Set(h.map(y=>y.chain)).size>1,markets:h}};return{...h.length>0?{ui:b}:{},_instructions:this.instructions(f,u,h.length>0,l.kind==="supported"?l.label:null),chain:s?A(s):"all",chainsQueried:c.map(y=>A(y)),...l.kind==="supported"?{protocolFilter:l.label}:{},sortedBy:u,marketCount:h.length,totalMarketsAvailable:m.length,marketNames:h.map(y=>y.name)}}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:[...ul],marketCount:0,marketNames:[]}}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 say so, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${s}.`,`Write your reply in TWO parts separated by a line containing exactly ${du} and nothing`,"else. Include that marker EXACTLY ONCE, on its own line. Do not translate it, style it, or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: at most two short sentences \u2014 the takeaway, then the caveats below.","Do not retell the markets in either part; they are already on screen.",t==="apy"?"In part two you MAY name the market at the top of the list and the live APY shown on its card, as the plain observation that it currently leads on rate. Write it in your own words. Do not add anything else about that market, and do not present it as a recommendation.":"Do NOT say which market pays the most: this list is NOT ordered by APY, so its first entry is not the highest-paying one.",new Set(e.map(a=>a.chain)).size>1?"The markets span several chains; each one shows its own chain.":`All of them are on ${A(e[0].chain)} \u2014 you may name that chain in your sentence.`,"You have NOT been given the market size, the platform score, the average APY, the daily change,","or the interest/reward split \u2014 they are not in this result. Do NOT state, estimate, or imply ANY of them,","for the list as a whole or for any single market.",`Saying the list is ${s} is allowed and expected \u2014 that is what the ordering means.`,"What you must NOT do is make a QUALITY claim about a market: do not call any one of them safe, safest,","stable, reliable, biggest or best-rated. Naming which market tops the ordering is fine \u2014 that is just",'reading the list back. Calling it the best one is not, because "best" rests on the figures this step',"does not have.",'So do NOT recommend one market over the others and do NOT name a "best option" \u2014 the figures that would',"justify a pick are exactly the ones this step omits. Point the user at a card instead: the full figures","are one tap away.","Part two MUST end by noting, in your own words, that APYs move constantly so a rate shown now is not a","promise of future yield, and that this is information rather than financial advice. Phrase it naturally","in the user's language \u2014 never omit it, however short the user asked you to be.","Do NOT mention tool names.",n?pu:""].filter(Boolean).join(" ")}},kh={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 vh(r){let e=typeof r=="string"?r.trim().toLowerCase():"";return wh.includes(e)?e:"apy"}function Th(r){let e=typeof r=="number"?r:Number(r);return!Number.isFinite(e)||e<1?wu:Math.min(Math.floor(e),ku)}function vu(r){let{currentApyPercent:e,avgApyPercent:t,totalSuppliedUsdc:n,rewardApyPercent:o,baseApyPercent:s,platformScore:a}=r;return r.rewards.find(l=>l.conditions)?{id:"conditional-reward",lead:"the headline rate is not what a plain deposit earns \u2014 a reward programme with conditions attached makes up part of it, and the user meets those conditions only by doing something extra",order:"split the rate first and say what a plain deposit actually earns, then the conditions in plain words, and only afterwards the market itself and who this genuinely suits"}:o!==null&&s!==null&&o>s*1?{id:"reward-dominant",lead:"most of this rate is incentive rewards rather than interest paid by borrowers, so it depends on a programme that can be cut or expire",order:"where the yield really comes from first, then how durable that makes it, then the market and protocol underneath it"}:e!==null&&t!==null&&t>0&&e>t*1.5?{id:"spiked-rate",lead:"the live rate sits well above its own recent average, so it has caught a spike rather than settled there and should not be read as the rate to expect",order:"the gap between live and average first and what usually causes it, then what a supplier would more realistically earn, then the market and protocol"}:n!==null&&n<1e7?{id:"thin-market",lead:"this market is small, so its size is the first thing to weigh: a few large withdrawals can move things, and position sizing matters more here than the rate does",order:"size and what it implies for getting money back out first, then the protocol and who runs it, and the rate last"}:a!==null&&a<6?{id:"weak-score",lead:"the platform score is on the low side, which is the first thing to square before the rate matters",order:"what the score does and does not tell them first, then the protocol itself, then size and rate"}:a!==null&&a>=8.5&&n!==null&&n>=25e7?{id:"blue-chip",lead:"this is one of the most established places to lend this asset \u2014 depth and track record are the real argument here, and the rate is almost a detail",order:"how proven and deep it is first, then what that means for getting money in and out, then the rate and what moves it"}:n!==null&&n>=25e7?{id:"deep-market",lead:"the market is deep enough that the user's deposit is a drop in it \u2014 they can come and go without moving the rate",order:"depth and liquidity first, then where the yield comes from, then the protocol"}:{id:"ordinary",lead:"nothing here is dramatic, and that is the finding: it is an ordinary, steady place to park this asset, which is exactly what suits a first lending position",order:"the absence of surprises first and why that is a virtue, then what is actually earned and from whom, then the protocol behind it"}}function va(r){let e=typeof r=="string"?r.trim():"",t=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/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}var Mr=class extends S{name="get-lending-market-detail";category="blockchain-data";description='Everything about ONE lending / supply market, for when the user has picked a market and wants to know whether it is worth depositing into: its size, the live supply APY split into interest vs reward incentives (with any conditions attached to those incentives), the recent average APY and how the rate has moved, the asset it lends, its 0\u201310 platform score, and its page on the protocol. This is the tool for a tapped "More detail" button, and for any question aimed at a SINGLE named market: "tell me more about Aave v3 USDC", "is Morpho Gauntlet USDC safe?", "how big is the Spark vault", "chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng Compound v3", "what is the real APY on that one". Pass `market` \u2014 the market name, the protocol, or the market contract address. When the message carries a "(market: 0x\u2026 - <chain>)" hint, pass THAT address as `market` and THAT chain as `chain` \u2014 together they name the exact market. Needs NO wallet: it reads and describes, it does not deposit. Do NOT use for: LISTING or comparing several markets \u2192 get-lending-markets; actually depositing into this market \u2192 open-supply-usdc-form; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to describe \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID the market lives on (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the message names \u2014 INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},...ba];service;constructor(e){super(),this.service=new ze(e)}async run(e,t){let o=te(e.chain,void 0)??q(t?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for this market, so it cannot be looked up. Ask the user which chain the market is on. Do NOT mention tool names."};if(!await this.service.isSupported(o)){let d=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:A(o),chainsWithLendingMarkets:d.map(p=>A(p)),_instructions:`There are no lending markets on ${A(o)}, so there is no market to describe there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let s=va(e.market);if(!s)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to know about \u2014 do not pick one for them. Do NOT mention tool names."};let a=await this.service.findMarket(o,s);if(a.length===0)return{error:"market_not_found",market:s,chain:A(o),_instructions:`No lending market matching "${s}" exists on ${A(o)}. Tell the user in their language and offer to show the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(a.length>1)return{error:"ambiguous_market",market:s,chain:A(o),candidates:a.map(d=>({marketName:d.name,protocol:d.protocol})),_instructions:`"${s}" matches ${a.length} different markets on ${A(o)}, so there is no single one to describe. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+s+`" and chain for ${A(o)}, plus the localized button templates \u2014 that shows the user each market as a card to tap. Write no message of your own before that call.`};let i=a[0],l=await this.describeOne(o,i);if(!l)return{error:"market_unavailable",marketName:i.name,chain:A(o),_instructions:`${i.name}'s current figures could not be read just now. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT quote any rate, size or score from memory, and do NOT mention tool names.`};let c=this.service.supply.canSupply(i),u=c?ll({name:i.name,contract:i.contract},e,A(o)):[];return{_instructions:this.instructions(l,u.length>0,c),...u.length>0?{actionButtons:u}:{},marketName:l.name,protocol:l.protocolLabel??l.protocol,protocolUrl:l.protocolUrl,chain:A(l.chain),suppliedAssetSymbol:l.asset.symbol,totalSuppliedUsdc:ae(l.totalSuppliedUsdc,zt),...ka(l),avgApyPercent:ae(l.avgApyPercent,Te),apyChangePercent:ae(l.apyChangePercent,Te),platformScore:l.platformScore,supplySupported:c}}async describeOne(e,t){try{let[n]=await this.service.describeResolvedMarkets(e,[t]);return n??null}catch{return null}}instructions(e,t,n){let o=vu(e);return[`This is the full picture of ONE lending market, ${e.name}, which the user asked about.`,"Lead with `marketName` in bold as PLAIN TEXT \u2014 **marketName** \u2014 not as a link, and name its `chain`.",'Go straight from that line into the bullets: do NOT write an introductory sentence before them ("Here is','a closer look at this market", "Here are the details", "Below is an overview"). Such a line says nothing',"the title has not already said and reads as boilerplate when every market opens with it.","Give a short bullet list, in this order. The FIRST bullet is nothing but a markdown link whose TEXT",'is the single word "Website" (translated into the user\'s language) and whose target is `protocolUrl` \u2014','exactly "- [Website](protocolUrl)". Do NOT put a label, a colon or any other word before or after that','link on the bullet: never "Website: [Website](\u2026)". NEVER print the raw URL as visible text, and NEVER use',"the market name as the link text. When `protocolUrl` is null, OMIT this bullet entirely; never invent a","URL.",'Then "Total supplied" = `totalSuppliedUsdc`, "Current APY" = `currentApyPercent`, "Avg APY" =',"`avgApyPercent`, and \u2014 only when the user asked about safety or the number helps your verdict \u2014",'"Platform score" = `platformScore`.',"Label `avgApyPercent` simply as the RECENT average. You have NOT been told what period it covers, so do",'NOT say "7-day", "past week", "last 30 days" or name any window or number of days for it.',"When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: write the",'"Current APY" bullet as the total followed by the split in parentheses \u2014 e.g. "2.11% (1.60% interest +','0.51% rewards)" \u2014 naming the reward token from `rewards[].tokenSymbol` when there is one. When it IS',"null, write `currentApyPercent` plainly and say NOTHING about rewards.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL \u2014 the user earns it only by meeting","those requirements, which a plain deposit usually does not. You MUST add a short plain-language warning","saying the reward part needs conditions and summarising them, so the total is never presented as what a","simple deposit earns. Never omit this to keep the answer short, and never quote such a total as if it","were guaranteed.",'Note that "Avg APY" covers the interest rate only, since reward history is not published \u2014 do not add',"`rewardApyPercent` to it, and if the average sits below the current rate, say that is why.","Compare the live rate against the average: a `currentApyPercent` well above `avgApyPercent` is a SPIKE,","not the rate to expect \u2014 say so plainly rather than quoting the live figure flat. `apyChangePercent` is","the move in the INTEREST rate over the LAST HOUR in percentage POINTS, rewards excluded; mention it","only when it is large enough to matter.","Format `totalSuppliedUsdc` compactly (100.12M, 23.45M). It is denominated in `suppliedAssetSymbol`:","when that is a dollar stablecoin (USDC, USDT, DAI) write it as dollars ($100.12M); otherwise append the","symbol instead (93.31K WETH). NEVER write a non-stablecoin amount with a $ sign.","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage. A null APY, size or score means","that figure was unavailable \u2014 say so rather than showing 0.",'Then, after the bullets, write a short heading line meaning "Reasons to consider supplying',"`suppliedAssetSymbol` to this lending market\", in the user's language and naming the actual asset \u2014","plain bold text, not a markdown heading. Under it, argue the case for supplying here as a bulleted list","of AT LEAST 6 points, each point its own bullet.",`The most important true thing about THIS market, for someone about to put money in, is that ${o.lead}.`,"Open the list by establishing exactly that, in your own words \u2014 it is bullet one, and every later bullet",`defends, qualifies or completes it. Then ${o.order}.`,"Follow that running order rather than any habit of listing rate, then size, then score.","Study how these two differ \u2014 not their numbers, their SHAPE:",'<example market="deep, unremarkable USDC market">',"- Nothing here is dramatic, and for a first lending position that is the point: a steady rate on a stable","asset, no strings attached.","- At $412M supplied, your deposit is a drop in the pool \u2014 you can pull it out whenever you want without","moving the rate.","- The 4.1% comes from real borrowers paying interest, not from a token giveaway that expires.","- Aave has run this market through several crashes now. That's the strongest argument it has.","- The rate drifts with borrowing demand, so treat 4.1% as roughly where it sits, not a fixed return.","- If you want the highest number on screen, this is not it. If you want somewhere boring to leave USDC,","it is hard to beat.","</example>",'<example market="small vault, conditional reward, spiked rate">',"- Read the 12.4% carefully: only 3.2% is interest. The other 9.2% is a reward programme, and it only pays","if you also borrow against your deposit \u2014 a plain deposit earns the 3.2%.","- Today's rate is also well above its recent average, so it caught a spike rather than settled there.","- The vault holds $6.8M. That is small enough that a few large withdrawals could move things, so size","your position with that in mind.","- A curator picks which loans this vault makes, so you are trusting their judgement on top of the code.","- A score of 5.6 is middling \u2014 not alarming, not proven either.","- Someone who understands the borrow leg and wants the incentive can do well here. Anyone looking for a","place to park stablecoins should look at a plainer market.","</example>","Note what changed: one opens on the absence of drama, the other on a number that misleads. One reassures","about size, the other warns about it. Neither walks APY, then size, then score. Match that variability \u2014","do NOT reuse these sentences.","Each bullet MUST carry a judgement, not a figure. Every number is already listed above, so delete the","number from a bullet and it must still say something. Cite a figure only as evidence.","Where the data cuts against the market, that belongs in the list, not omitted.","At least one bullet MUST judge `protocol` itself, since that is who holds the money: how established and","used it is, who ultimately pays the yield, and what a depositor is really exposed to (contract risk, the","asset, a vault curator). This comes from your own knowledge, so keep it qualitative \u2014 NO invented TVL,","launch date, audit count or incident history, and no numbers beyond those given. If you do not reliably","know the protocol, say so and point to its site.","Voice: an experienced analyst talking to a friend who has never lent on-chain. Plain sentences, no","jargon, no marketing tone; explain any unavoidable DeFi term (supply, incentives, vault) in the same","breath.","Ground every judgement in the given numbers: never invent a fact or a risk figure, and never promise a","return.","Close with a short reminder that this is information, not financial advice, worded to fit what you just",'said and DIFFERENT every time \u2014 e.g. "None of this is advice \u2014 check the numbers yourself before you','commit." / "Worth doing your own reading before you deposit; this is information only." / "That is the','picture as the data has it, not a recommendation." NEVER paste a stock line such as "This information is','for informational purposes only and not financial advice."',n?"":"Depositing into this market is NOT supported in the app yet. Say that plainly at the end, and do not invite the user to supply here.","Do NOT mention tool names.",t?mu:""].filter(Boolean).join(" ")}};var Fr=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 ze(e)}async run(e,t){let n=ne(e.address,t);if(!_(n))return{error:`"${n}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=te(e.chain,t),s=o?await this.service.isSupported(o):!1,a=s?[]:await this.service.listSupportedChains();if(o&&!s)return{_instructions:`There are no lending markets on ${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:a.map(c=>A(c))};let i=o?[o]:a,l=await this.service.getSupplyPositions({address:n,chains:i});return{_instructions:this.instructions(l),walletAddress:n,chain:o?A(o):"all",chainsQueried:i.map(c=>A(c)),positionCount:l.length,totals:Ah(l),positions:l.map(c=>({marketName:c.name,protocol:c.protocol,protocolUrl:c.protocolUrl,chain:A(c.chain),suppliedUsdc:ae(c.suppliedUsdc,zt),suppliedAssetSymbol:c.asset.symbol,avgApyPercent:ae(c.avgApyPercent,Te),...ka(c),apyChangePercent:ae(c.apyChangePercent,Te),estimatedAnnualYieldUsdc:ae(c.estimatedAnnualYieldUsdc,zt),marketTotalSuppliedUsdc:ae(c.totalSuppliedUsdc,zt),apyHistory:c.apyHistory.map(u=>({...u,apyPercent:ae(u.apyPercent,Te)})),platformScore:c.platformScore}))}}instructions(e){return e.length===0?"The wallet supplies to NONE of the curated markets (Aave v3, Compound v3, Spark, Morpho) on the chains in `chainsQueried`. Say exactly that in the user's language \u2014 do not guess at other protocols and do not imply an error. This covers the curated markets only, so if the user believes they have a deposit it may be in a protocol outside that set; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the timestamped samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: say so when",'you quote that market`s APY, giving the split \u2014 e.g. "2.11% total (1.60% interest + 0.51% rewards)" \u2014 and',"naming the reward token from `rewards[].tokenSymbol` when there is one. Say nothing about rewards when it","is null. `avgApyPercent` covers the interest rate only, as reward history is not published.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL: the wallet earns that part only","while it meets those requirements. Say so briefly and summarise them, rather than reporting the total as","income the position is already receiving.","`estimatedAnnualYieldUsdc` deliberately counts only the interest and any UNCONDITIONAL reward, so on a","market with a conditional programme it is the floor, not the ceiling. If the user asks about yearly","earnings there, give that figure and add that meeting the reward conditions would raise it.","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(e.map(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 Ah(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:ae(n,zt),estimatedAnnualYieldUsdc:ae(r.reduce((a,i)=>a+(i.estimatedAnnualYieldUsdc??0),0),zt),weightedAvgApyPercent:ae(s>0?o.reduce((a,i)=>a+i.suppliedUsdc*i.avgApyPercent,0)/s:null,Te)}}var Br=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 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the message names, INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for; whether it carries markets is checked at call time. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`Amount to pre-fill, in the market's own asset, as a plain decimal ("100", "25.5"). Pass ONLY when the user named an amount. Omit otherwise \u2014 the user types it in the form. Never invent or convert an amount.`,required:!1}];service;moralis;constructor(e){super(),this.service=new ze(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=te(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."};if(!await this.service.isSupported(s)){let b=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:A(s),chainsWithLendingMarkets:b.map(y=>A(y)),_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 a=va(e.market);if(!a)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let i=await this.service.findMarket(s,a);if(i.length===0)return{error:"market_not_found",market:a,chain:A(s),_instructions:`No lending market matching "${a}" 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(i.length>1)return{error:"ambiguous_market",market:a,chain:A(s),candidates:i.map(b=>({marketName:b.name,protocol:b.protocol})),_instructions:`"${a}" matches ${i.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="`+a+`" and chain for ${A(s)}, plus the localized detail-button templates \u2014 that shows the user each market as a card with its live APY. Tapping one opens that market's full figures, and the supply is started from there. Write no message of your own before that call.`};let l=i[0];if(!this.service.supply.canSupply(l))return{error:"unsupported_protocol",marketName:l.name,protocol:l.protocol,_instructions:`Supplying to ${l.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let c=await this.describeOne(s,l),u=Ph(c);if(!u)return{error:"asset_unresolved",marketName:l.name,chain:A(s),_instructions:`The asset ${l.name} lends could not be read just now, so the supply cannot be prepared safely. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT guess the asset, do NOT name USDC, and do NOT mention tool names.`};let[d,p]=await Promise.all([this.assetBalance(n,s,u.address),this.service.readReceiptToken(s,l)]);if(d&&kn(d.amount,"0")<=0)return{error:"no_asset_balance",marketName:l.name,chain:A(s),assetSymbol:u.symbol,assetBalance:"0",_instructions:`The user has no ${u.symbol} available to supply to ${l.name} on ${A(s)}. In the user's language, tell them plainly that they have no ${u.symbol} available on this chain and need to add some before they can supply. Do NOT show any amount form, do NOT invent a balance, and do NOT state a specific balance figure. Keep it to one or two short sentences. Do NOT mention tool names.`};let m=Sh(e.amount),f=m?$t(m,u.decimals):null;if(f&&d&&kn(f,d.amount)>0)return{error:"insufficient_asset_balance",marketName:l.name,chain:A(s),assetSymbol:u.symbol,requestedAmount:m,assetBalance:d.amount,_instructions:`The user wants to supply ${m} ${u.symbol} to ${l.name}, but they only hold ${d.amount} ${u.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 ${m} ${u.symbol} exceeds their balance of ${d.amount} ${u.symbol} on this chain, then ask them to enter a smaller amount or add more. Do NOT open any amount form and do NOT invent figures. Keep it to one or two short sentences. Do NOT mention tool names.`};let h={action:"supply_usdc",chainId:s,chainName:A(s),walletAddress:n,market:{name:l.name,type:l.type,protocol:l.protocol,protocolUrl:c?.protocolUrl??ga(l),contract:l.contract,token:l.token,apyPercent:c?.currentApyPercent??c?.avgApyPercent??null,receiptToken:p},asset:u,...f?{prefillAmount:f}:{},...d?{spendable:d.amount}:{},...d?.usd?{spendableUsd:d.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:h},marketName:l.name,protocol:l.protocol,chain:A(s),apyPercent:ae(h.market.apyPercent,Te),assetSymbol:u.symbol,assetBalance:d?.amount??null,_instructions:this.instructions(l,u.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 Ph(r){let e=r?.asset;return!e?.address||e.address===Pn||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function Sh(r){let e=typeof r=="string"?r.trim():typeof r=="number"?String(r):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}var Ta="https://ipfs.pantograph.app/ipfs/",Tu=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function Sn(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?`${Ta}${t[1]}`:Tu.test(e)?`${Ta}${e}`:null}function Au(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?`${Ta}${t[1]}`:Tu.test(e)?`${Ta}${e}`:null}function Pu(r){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(r)}function dl(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 xh(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 Ch(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)?xh(n):decodeURIComponent(n);return JSON.parse(o)}catch{try{return JSON.parse(n)}catch{return null}}}function Su(r){let e=r?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=Ch(e);return t?Sn(dl(t)):null}var Rh=12,Eh=6e3;async function _h(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 Nh(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 Su(t);let n=Au(t);if(!n)return null;if(Pu(n))return n;let o=await Nh(n,e);if(o){let s=Sn(dl(o));if(s)return s}return null}async function Aa(r,e,t){if(e.length===0)return[];let n=t?.concurrency??Rh,o=t?.timeoutMs??Eh,s=await Sc(r,e,t?.rpcUrl);return _h(s,n,a=>Ih(a,o))}var xu=100,Uh=100,qr="{name}",Cu="{chain}",$r=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=ne(e.address,t),o=te(e.chain,t),s=o?[o]:Ce(),a=Bh(e.contract_address),i=_u(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:xu});return{chain:c,rows:u.success?Ru(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:Dh(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=Mh(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 f=await this.service.getWalletNFTs({address:t,chain:m,limit:xu,...s?{tokenAddresses:[s]}:{}});return{chain:m,rows:f.success?Ru(f.data?.result??[]):[],ok:f.success}}));if(o&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(m=>m.rows.filter(f=>Lh(f,{contract:s,collectionName:a})).map(f=>({chain:m.chain,row:f})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${a??s??""}"`+(o?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||a||l[0].row.token_address,u=await this.resolveOnchainImages(l),d=l.map(({chain:m,row:f},h)=>{let g=Oh(f);return{name:g.name,tokenId:g.tokenId,contractAddress:g.contractAddress,image:u[h]??g.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 Aa(o,a);s.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function Ru(r){return r.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function Lh(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 Dh(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 Oh(r){return{name:r.normalized_metadata?.name||r.name||`#${r.token_id}`,tokenId:r.token_id,contractAddress:r.token_address,image:Sn(r.normalized_metadata?.image||r.media?.original_media_url)}}function Mh(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>=Uh)break;if(!s.contractAddress)continue;let a=typeof s.chain=="string"?s.chain.trim():"",i=a?`show my ${qr} NFTs on ${Cu}`:`show my ${qr} NFTs`,l=Eu(n,{[qr]:s.name,[Cu]:a},i);a&&!l.includes(a)&&(l=`${l} (${a})`),o.push({label:Fh(t,s.name,qr),prompt:`${l} (${s.contractAddress})`})}return o}function Eu(r,e,t){let n=r&&r.includes(qr)?r:t;for(let[o,s]of Object.entries(e))n=n.split(o).join(s);return n.replace(/\s+/g," ").trim()}function Fh(r,e,t){return Eu(r,{[qr]:e},t)}function _u(r){if(typeof r!="string")return;let e=r.trim();return e||void 0}function Bh(r){let e=_u(r);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var qh="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.",dt=class extends S{kind="data";category="nft";llm;constructor(e){super(),this.llm=new ie(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:qh,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Hr=class extends dt{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=dt.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 Vr=class extends dt{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=dt.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 pl={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"},ml="amazon.com";function $h(r){return r?r.trim().toLowerCase().split(/[-_]/)[0]:""}function hl(r){let e=$h(r);return pl[e]??ml}function Pa(r){return`https://${hl(r)}/s?k=NFC%20Tag`}function Sa(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 Hh=720*60*1e3,Nu=new Map,Iu=3;function Vh(r){return[`A user in country "${r}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Iu} 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>=Iu))break}return o}async function gl(r,e){let t=Sa(r);if(!t||!e)return null;let n=Nu.get(t);if(n&&n.expires>Date.now())return n.links;let o=Date.now(),s=[{role:"user",content:Vh(t),timestamp:o}];try{let a=await e.chat(s,void 0,{googleSearch:!0,maxRetries:1}),i=Wh(a.text);if(i.length)return Nu.set(t,{links:i,expires:Date.now()+Hh}),i}catch{}return null}async function Wr(r){let e=await gl(r.country,r.llm);return e&&e.length?e:[{label:"Amazon",url:Pa(r.language)}]}function Yh(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(`
|
|
34
|
+
Format numbers human-readably: price as $0.65 / $0.016 (more decimals for sub-cent), market cap & volume compact ($12.8M, $6,474), price change signed with one or two decimals (+5.67%, -1.6%). Reply in the user's language and use the human-readable chain name. Do NOT mention tool names, UI, or forms.`,chain:n?A(n):"all",timeFrame:s??null,count:c.length,tokens:c}}};var Ar=class extends S{name="get-wallet-token-balances";description='Get all ERC-20 token balances for a wallet address, including USD prices and 24h changes. Use this when the user asks about: "my tokens", "my balances", "what do I hold", "portfolio", "how much ETH/USDC/\u2026 do I have", or any wallet balance question. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. ';category="blockchain-data";parameters=[{name:"address",type:"string",description:"Wallet address to query (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, balances are fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new O(e)}truncateUsd(e){if(!Number.isFinite(e))return"0.00";let t=e<0,[n,o=""]=Math.abs(e).toFixed(8).split(".");return`${t?"-":""}${n}.${(o+"00").slice(0,2)}`}async run(e,t){let n=ne(e.address,t),o=te(e.chain,t);if(o){let i=await this.service.getWalletTokenBalances({address:n,chain:o,excludeSpam:!1,excludeUnverifiedContracts:!1});return i.success?this.renderBalances(n,o,i.data?.result||[]):{error:i.error||"Failed to fetch token balances"}}let s=Ce(),a=await Promise.all(s.map(async i=>{let l=await this.service.getWalletTokenBalances({address:n,chain:i,excludeSpam:!1,excludeUnverifiedContracts:!1});return{chain:i,tokens:l.success?l.data?.result||[]:[]}}));return this.renderBalancesByChain(n,a)}toTokenLine(e){let t=e.name||e.symbol||"Unknown",n=e.balance_formatted??"0",o=e.symbol||"",s=typeof e.usd_value=="number"?`$${this.truncateUsd(e.usd_value)}`:"$-";return`- ${t}: ${n} ${o} (${s})`.replace(/\s+/g," ").trim()}renderBalances(e,t,n){let o=n.reduce((s,a)=>s+(a.usd_value||0),0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). Then output the token lines EXACTLY as provided in `tokens` \u2014 one Markdown bullet each, in order, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings, no bold, no tool names.",walletAddress:e,chain:t,totalUsdValue:`$${this.truncateUsd(o)}`,tokens:n.map(s=>this.toTokenLine(s))}}renderBalancesByChain(e,t){let n=t.map(s=>{let a=s.tokens.reduce((l,c)=>l+(c.usd_value||0),0),i=s.tokens.slice().sort((l,c)=>(c.usd_value||0)-(l.usd_value||0));return{chain:A(s.chain),total:a,tokens:i}}).filter(s=>s.tokens.length>0).sort((s,a)=>a.total-s.total),o=n.reduce((s,a)=>s+a.total,0);return{_instructions:"Open with one short, natural sentence in the user's language stating the wallet's total value (totalUsdValue), e.g. \"Your wallet is worth about $0.04.\" (plain text \u2014 do NOT bold it). These balances cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet actually holds tokens on, the chain with the most value first). Render ONE section per entry in `chains`, in order: write the chain name (the entry's `chain`) on its own short line, then that entry's token bullets EXACTLY as provided in its `tokens` \u2014 one Markdown bullet each, nothing added or removed. Keep every amount and USD value verbatim: never shorten, round, reformat, or bold them. Keep it conversational and clean \u2014 no table, no extra headings beyond the chain name lines, no bold, no tool names. If `chains` is empty, say the wallet holds no tokens on any supported chain.",walletAddress:e,chain:"all",totalUsdValue:`$${this.truncateUsd(o)}`,chains:n.map(s=>({chain:s.chain,totalUsdValue:`$${this.truncateUsd(s.total)}`,tokens:s.tokens.map(a=>this.toTokenLine(a))}))}}};var Pr=class extends S{name="get-wallet-history";description=`Get a wallet's decoded on-chain transaction history. Always fetches the latest 100 transactions. Each transaction includes: category, summary, from_address, to_address, and nested arrays: native_transfers (each has direction="send"|"receive", from_address, to_address, value_formatted, token_symbol), erc20_transfers (each has direction, token_symbol, value_formatted), nft_transfers. To find ETH sends/receives, inspect native_transfers[].direction \u2014 ETH moves appear across many categories (e.g. "token swap", "send", "receive"), not just category="send". Use this tool for: native coin transfers, swaps, airdrops, deposits, withdrawals, contract interactions, mixed history. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. Do NOT use for: specific ERC-20 tokens \u2192 get-wallet-token-transfers; NFT transfers \u2192 get-wallet-nft-transfers; balances \u2192 get-wallet-token-balances.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includeInternalTransactions",type:"boolean",description:"Include decoded internal transactions on each item.",required:!1},{name:"nftMetadata",type:"boolean",description:"Include NFT normalized metadata in nft_transfers.",required:!1},{name:"limit",type:"number",description:"Number of transactions to return per page. Defaults to 10.",required:!1,default:10}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=pe(e.chain,t),s=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,a=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,i=typeof e.fromBlock=="number"?e.fromBlock:typeof e.fromBlock=="string"&&e.fromBlock?Number(e.fromBlock):void 0,l=typeof e.toBlock=="number"?e.toBlock:typeof e.toBlock=="string"&&e.toBlock?Number(e.toBlock):void 0,c=Number.isFinite(i)?i:void 0,u=Number.isFinite(l)?l:void 0,d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():void 0)==="ASC"?"ASC":"DESC",f=typeof e.includeInternalTransactions=="boolean"?e.includeInternalTransactions:void 0,h=typeof e.nftMetadata=="boolean"?e.nftMetadata:void 0,g=typeof e.limit=="number"?e.limit:typeof e.limit=="string"?Number(e.limit):void 0,b=Number.isFinite(g)&&g>0?g:10,y=await this.service.getWalletHistory({address:n,chain:o,limit:b,fromDate:s,toDate:a,fromBlock:c,toBlock:u,cursor:d,order:m,includeInternalTransactions:f,nftMetadata:h});if(!y.success)return{error:y.error||"Failed to fetch wallet history"};let w=(y.data?.result||[]).map(v=>{let T=Oc(o,v.hash);return T?{...v,explorerUrl:T}:v});return{_instructions:"For EACH transaction include its block-explorer link from `explorerUrl` so the user can open it on the chain block scanner. Render it as a Markdown link on the transaction hash, or as a short localized view-on-explorer link in the user language. Use the `explorerUrl` value VERBATIM \u2014 never invent or alter a URL; if a transaction has no `explorerUrl`, omit the link for it. Do NOT mention tool names.",walletAddress:n,chain:o||"default",pagination:{cursor:y.data?.cursor??null,hasMore:!!y.data?.cursor},transactionCount:w.length,transactions:w}}};function Am(r){if(r.value_decimal)return r.value_decimal;let e=parseInt(r.token_decimals??"18",10);if(isNaN(e)||e===0)return r.value;try{let t=BigInt(r.value),n=BigInt(10)**BigInt(e),o=t/n,a=(t%n).toString().padStart(e,"0").replace(/0+$/,"");return a?`${o}.${a}`:`${o}`}catch{return r.value}}var Sr=class extends S{name="get-wallet-token-transfers";description=`Get all ERC-20 token transfers for a wallet from the dedicated Moralis transfers endpoint. Each transfer includes direction (send/receive), human-readable amount, and the exact counterparty address with its label/entity. The response includes a "counterparties" section that aggregates unique sender/recipient addresses with totals. Use tokenSymbol (e.g. "USDC") to filter by token name \u2014 the tool automatically resolves the contract address by checking the wallet's token balances first, then falling back to token search. Use contractAddresses when you already have the exact contract address. Use this tool for questions like: "When did I last send USDC and to whom?" (tokenSymbol=USDC, direction=send, limit=1), "Who have I sent token 0x\u2026 to?" (contractAddresses=[0x\u2026], direction=send), "Who sent me USDT?" (tokenSymbol=USDT, direction=receive), "Show all USDC transfers" (tokenSymbol=USDC), "What tokens did I receive this month?" (fromDate=..., direction=receive). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page. IMPORTANT \u2014 this tool covers ERC-20 tokens ONLY. Do NOT use it for native coins (ETH, BNB, MATIC, AVAX, etc.) \u2014 native coin transfers are not ERC-20 and will not appear here. For native coin transfer history use get-wallet-history instead.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"tokenSymbol",type:"string",description:'Filter by token symbol (e.g. "USDC", "USDT", "WETH"). The tool resolves the contract address automatically: first checks wallet balances, then searches by symbol on the chain. Use this when the user mentions a token by name/symbol. Takes precedence over contractAddresses when both are given.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more ERC-20 token contract addresses (0x\u2026). Use when the exact contract address is already known. Ignored if tokenSymbol is provided.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet is sender), "receive" (wallet is recipient), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:'Page size (1-100, default 25). Use limit=1 ONLY when the user asks for the single most recent transfer (e.g. "L\u1EA7n cu\u1ED1i c\xF9ng t\xF4i g\u1EEDi USDC l\xE0 khi n\xE0o?"). For "show recent history" or "list my transfers" questions use the default (25). Use 100 for bulk counterparty analysis.',required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=pe(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",h=f==="send"?"send":f==="receive"?"receive":"all",g=typeof e.tokenSymbol=="string"&&e.tokenSymbol?e.tokenSymbol.trim():void 0,b=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(R=>typeof R=="string"&&!!R).map(R=>R.trim()):void 0,y,k;if(g){let R=await this.resolveContractAddressBySymbol(g,n,o);R&&(b=[R.address],y=R.symbol,k=R.name)}let w=await this.service.getWalletTokenTransfers({address:n,chain:o,contractAddresses:b,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:m});if(!w.success)return{error:w.error||"Failed to fetch token transfers"};let v=n.toLowerCase(),P=(w.data?.result||[]).map(R=>{let V=R.from_address.toLowerCase()===v,E=V?"send":"receive",ce=V?R.to_address:R.from_address,$=V?R.to_address_label??void 0:R.from_address_label??void 0,fe=V?R.to_address_entity??void 0:R.from_address_entity??void 0;return{...R,direction:E,amount_formatted:Am(R),counterparty:ce,counterparty_label:$,counterparty_entity:fe}}),C=h==="all"?P:P.filter(R=>R.direction===h);if(g&&!b){let R=g.toLowerCase();C=C.filter(V=>(V.token_symbol??"").toLowerCase()===R)}let N=this.buildCounterparties(C);return{walletAddress:n,chain:o||"default",resolvedToken:y?{symbol:y,name:k,contractAddress:b?.[0]}:null,filters:{tokenSymbol:g||null,contractAddresses:b||null,direction:h,limit:a,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:u??null},pagination:{cursor:w.data?.cursor??null,pageSize:w.data?.page_size??a,page:w.data?.page??null,hasMore:!!w.data?.cursor},transferCount:C.length,transfers:C,counterparties:N}}async resolveContractAddressBySymbol(e,t,n){let o=e.toLowerCase(),s=await this.service.getWalletTokenBalances({address:t,chain:n});if(s.success&&s.data?.result?.length){let i=s.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}let a=await this.service.searchTokensByKey({key:e,chain:n});if(a.success&&a.data?.length){let l=a.data.find(c=>(c.symbol??"").toLowerCase()===o)??a.data[0];if(l?.token_address)return{address:l.token_address,symbol:l.symbol,name:l.name}}}buildCounterparties(e){let t=new Map,n=new Map;for(let s of e){let a=s.direction==="send"?t:n,i=s.counterparty.toLowerCase(),l=parseFloat(s.amount_formatted)||0,c=a.get(i);c?(c.total+=l,c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):a.set(i,{label:s.counterparty_label,entity:s.counterparty_entity,total:l,count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,total_amount:i.total.toFixed(6).replace(/\.?0+$/,""),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:o(t),received:o(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var xr=class extends S{name="get-wallet-nft-transfers";description=`Get all NFT transfers for a wallet from the dedicated Moralis NFT transfers endpoint. Each transfer includes direction (send/receive), the exact counterparty address, token ID, collection, contract type (ERC721/ERC1155), and optional last sale price. The response includes a 'counterparties' section aggregating unique senders/recipients with token IDs and collections. Use this tool for questions like: "Which NFTs did I sell and to whom?" (direction=send), "Who sent me NFTs from collection 0x\u2026?" (contractAddresses=[0x\u2026], direction=receive), "Show all transfers for my NFT collection 0x\u2026" (contractAddresses=[0x\u2026]), "What NFTs did I mint?" (direction=receive), "Show NFT sales with prices" (direction=send, includePrices=true). Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. Returns paginated results \u2014 pass cursor to get the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"contractAddresses",type:"array",description:"Filter by one or more NFT contract addresses (0x\u2026). Use this to scope queries to a specific collection. Omit to return all NFT transfers.",required:!1,items:{type:"string"}},{name:"direction",type:"string",description:'Client-side direction filter: "send" (wallet sent the NFT), "receive" (wallet received it), "all" (default).',required:!1,default:"all"},{name:"limit",type:"number",description:"Page size (1-100, default 25).",required:!1,default:25},{name:"fromDate",type:"string",description:'Inclusive start date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"toDate",type:"string",description:'Inclusive end date (ISO-8601 or "YYYY-MM-DD").',required:!1},{name:"fromBlock",type:"number",description:"Minimum block number.",required:!1},{name:"toBlock",type:"number",description:"Maximum block number.",required:!1},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1},{name:"order",type:"string",description:'"DESC" newest first (default) or "ASC" oldest first.',required:!1,default:"DESC"},{name:"includePrices",type:"boolean",description:"If true, include last_sale price data (buyer, seller, price, USD value, payment token) on each transfer. Useful for questions about NFT sale prices.",required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=pe(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):25,i=typeof e.fromDate=="string"&&e.fromDate?e.fromDate:void 0,l=typeof e.toDate=="string"&&e.toDate?e.toDate:void 0,c=this.parseBlock(e.fromBlock),u=this.parseBlock(e.toBlock),d=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,m=(typeof e.order=="string"?e.order.toUpperCase():"")==="ASC"?"ASC":"DESC",f=typeof e.includePrices=="boolean"?e.includePrices:void 0,h=typeof e.direction=="string"?e.direction.trim().toLowerCase():"all",g=h==="send"?"send":h==="receive"?"receive":"all",b=Array.isArray(e.contractAddresses)?e.contractAddresses.filter(C=>typeof C=="string"&&!!C).map(C=>C.trim()):void 0,y=await this.service.getWalletNftTransfers({address:n,chain:o,contractAddresses:b,limit:a,fromDate:i,toDate:l,fromBlock:c,toBlock:u,cursor:d,order:m,includePrices:f});if(!y.success)return{error:y.error||"Failed to fetch NFT transfers"};let k=n.toLowerCase(),v=(y.data?.result||[]).map(C=>{let N=C.from_address.toLowerCase()===k,R=N?"send":"receive",V=N?C.to_address:C.from_address,E=N?C.to_address_label??void 0:C.from_address_label??void 0,ce=N?C.to_address_entity??void 0:C.from_address_entity??void 0;return{...C,direction:R,counterparty:V,counterparty_label:E,counterparty_entity:ce}}),T=g==="all"?v:v.filter(C=>C.direction===g),P=this.buildCounterparties(T);return{walletAddress:n,chain:o||"default",filters:{contractAddresses:b||null,direction:g,limit:a,order:m,fromDate:i||null,toDate:l||null,fromBlock:c??null,toBlock:u??null,includePrices:f??null},pagination:{cursor:y.data?.cursor??null,pageSize:y.data?.page_size??a,page:y.data?.page??null,hasMore:!!y.data?.cursor},transferCount:T.length,transfers:T,counterparties:P}}buildCounterparties(e){let t=new Map,n=new Map;for(let s of e){let a=s.direction==="send"?t:n,i=s.counterparty.toLowerCase(),l=s.token_name??s.token_address,c=a.get(i);c?(c.tokenIds.add(s.token_id),c.collections.add(l),c.count+=1,!c.label&&s.counterparty_label&&(c.label=s.counterparty_label),!c.entity&&s.counterparty_entity&&(c.entity=s.counterparty_entity),s.block_timestamp<c.first&&(c.first=s.block_timestamp),s.block_timestamp>c.last&&(c.last=s.block_timestamp)):a.set(i,{label:s.counterparty_label,entity:s.counterparty_entity,tokenIds:new Set([s.token_id]),collections:new Set([l]),count:1,first:s.block_timestamp,last:s.block_timestamp})}let o=s=>Array.from(s.entries()).sort((a,i)=>i[1].count-a[1].count).map(([a,i])=>({address:a,label:i.label,entity:i.entity,token_ids:Array.from(i.tokenIds),collections:Array.from(i.collections),tx_count:i.count,first_seen:i.first,last_seen:i.last}));return{sent:o(t),received:o(n)}}parseBlock(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(typeof e=="string"&&e){let t=Number(e);return Number.isFinite(t)?t:void 0}}};var Pm=["all","7","30","60","90"],Cr=class extends S{name="get-wallet-pnl-summary";description=`Get a wallet's aggregate realized profit-and-loss summary across all tokens it has traded. Returns: total_count_of_trades, total_trade_volume (USD), total_realized_profit_usd, total_realized_profit_percentage, total_buys, total_sells, total_sold_volume_usd, total_bought_volume_usd. Use this tool for questions like: "How much profit have I made trading?", "What is my realized PnL?", "How many trades have I done this month?" (days=30), "Am I up or down overall?". IMPORTANT \u2014 this endpoint only supports mainnet: Ethereum ("0x1"), Base ("0x2105"), Polygon ("0x89"). Use days="all" (default), "7", "30", "60", or "90" to scope the time window. Do NOT use for: per-token breakdown \u2192 get-wallet-pnl; current portfolio value \u2192 get-wallet-token-balance; transfer history \u2192 get-wallet-history.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea . ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the summary. Values: "all" (default, lifetime), "7", "30", "60", "90". Pass "30" when the user asks about the last month, "7" for the last week, etc.',required:!1,default:"all"}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=te(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=Pm.includes(s)?s:void 0;if(o){let h=await this.service.getWalletPnlSummary({address:n,chain:o,days:a});return h.success?{walletAddress:n,chain:o,days:a??"all",summary:this.mapSummary(h.data)}:{error:h.error||"Failed to fetch wallet PnL summary"}}let l=(await Promise.all(Ce().map(async h=>{let g=await this.service.getWalletPnlSummary({address:n,chain:h,days:a});return{chain:h,data:g.success?g.data:void 0}}))).flatMap(h=>h.data&&h.data.total_count_of_trades>0?[{chain:h.chain,data:h.data}]:[]),c=l.map(h=>({chain:A(h.chain),summary:this.mapSummary(h.data)})),u=l.reduce((h,g)=>h+Number(g.data.total_realized_profit_usd||0),0),d=l.reduce((h,g)=>h+Number(g.data.total_bought_volume_usd||0),0),p=l.reduce((h,g)=>h+Number(g.data.total_sold_volume_usd||0),0),m=l.reduce((h,g)=>h+Number(g.data.total_trade_volume||0),0),f={totalCountOfTrades:l.reduce((h,g)=>h+g.data.total_count_of_trades,0),totalTradeVolume:m,totalRealizedProfitUsd:u,totalRealizedProfitPercentage:d>0?u/d*100:0,totalBuys:l.reduce((h,g)=>h+g.data.total_buys,0),totalSells:l.reduce((h,g)=>h+g.data.total_sells,0),totalBoughtVolumeUsd:d,totalSoldVolumeUsd:p};return{_instructions:"This PnL summary covers ALL supported chains (the user named no chain). `summary` is the combined total across them; `chains` is the per-chain breakdown (only chains the wallet actually has trading data on). State the overall realized PnL first, then optionally the per-chain split. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:a??"all",summary:f,chains:c}}mapSummary(e){return{totalCountOfTrades:e.total_count_of_trades,totalTradeVolume:e.total_trade_volume,totalRealizedProfitUsd:e.total_realized_profit_usd,totalRealizedProfitPercentage:e.total_realized_profit_percentage,totalBuys:e.total_buys,totalSells:e.total_sells,totalBoughtVolumeUsd:e.total_bought_volume_usd,totalSoldVolumeUsd:e.total_sold_volume_usd}}};var Sm=["all","7","30","60","90"],da=25,Rr=class extends S{name="get-wallet-pnl";description=`Get a wallet's realized profit-and-loss broken down per ERC-20 token. Each entry includes: token_address, name, symbol, decimals, logo, avg_buy_price_usd, avg_sell_price_usd, total_usd_invested, total_tokens_bought, total_tokens_sold, total_sold_usd, avg_cost_of_quantity_sold, count_of_trades, realized_profit_usd, realized_profit_percentage, total_buys, total_sells, possible_spam. Use this tool for questions like: "Which tokens made me the most money?", "What are my best/worst trades?", "How much profit did I make on USDC?" (tokenSymbols=["USDC"]), "PnL for PEPE and DEGEN this month" (tokenSymbols=["PEPE","DEGEN"], days=30), "PnL breakdown for each token I traded this month" (days=30). IMPORTANT \u2014 this endpoint ONLY supports mainnet: Ethereum ("0x1"), Polygon ("0x89"), Base ("0x2105"). Use days="all" (default), "7", "30", "60", or "90" for the time window. Pass tokenSymbols (by ticker, auto-resolved) and/or tokenAddresses (raw 0x\u2026) to restrict to specific tokens \u2014 combined total capped at ${da}. Do NOT use for: aggregate summary \u2192 get-wallet-pnl-summary; current balances \u2192 get-wallet-token-balances; transfer history \u2192 get-wallet-token-transfers.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, PnL is fetched across all supported chains.',required:!1},{name:"days",type:"string",description:'Time window for the breakdown. Values: "all" (default, lifetime), "7", "30", "60", "90".',required:!1,default:"all"},{name:"tokenSymbols",type:"array",description:`Optional list of token symbols (e.g. ["USDC", "PEPE"]). Auto-resolved to contract addresses via the connected wallet's balances first, then Pantograph search. Symbols that can't be resolved are skipped. Merged with tokenAddresses; combined total capped at ${da}.`,required:!1,items:{type:"string"}},{name:"tokenAddresses",type:"array",description:`Optional list of raw ERC-20 contract addresses (0x\u2026). Use when the exact addresses are already known. Merged with tokenSymbols; combined total capped at ${da}.`,required:!1,items:{type:"string"}}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=te(e.chain,t),s=typeof e.days=="string"?e.days.trim().toLowerCase():"",a=Sm.includes(s)?s:void 0,i=Array.isArray(e.tokenSymbols)?e.tokenSymbols.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[],l=Array.isArray(e.tokenAddresses)?e.tokenAddresses.filter(d=>typeof d=="string"&&!!d.trim()).map(d=>d.trim()):[];if(o){let d=await this.fetchChainPnl(n,o,a,i,l);return d.ok?{walletAddress:n,chain:o,days:a??"all",filters:{tokenAddresses:d.tokenAddresses??null,resolvedSymbols:d.resolvedFromSymbols.length>0?d.resolvedFromSymbols:null,unresolvedSymbols:d.unresolvedSymbols.length>0?d.unresolvedSymbols:null},tokenCount:d.tokens.length,tokens:d.tokens}:{error:d.error||"Failed to fetch wallet PnL"}}let u=(await Promise.all(Ce().map(async d=>({chain:d,res:await this.fetchChainPnl(n,d,a,i,l)})))).filter(d=>d.res.ok&&d.res.tokens.length>0).map(d=>({chain:A(d.chain),tokenCount:d.res.tokens.length,tokens:d.res.tokens}));return{_instructions:"This per-token PnL covers ALL supported chains (the user named no chain) and is GROUPED BY CHAIN in `chains` (only chains the wallet actually has trading data on). Present one section per chain. If `chains` is empty, say the wallet has no trading history on the supported chains. Do NOT mention tool names.",walletAddress:n,chain:"all",days:a??"all",filters:{requestedSymbols:i.length>0?i:null,requestedAddresses:l.length>0?l:null},tokenCount:u.reduce((d,p)=>d+p.tokenCount,0),chains:u}}async fetchChainPnl(e,t,n,o,s){let a=[],i=[];o.length>0&&(await Promise.all(o.map(p=>this.resolveContractAddress(p,t,e)))).forEach((p,m)=>{p?a.push({symbol:o[m],address:p.address}):i.push(o[m])});let l=xm([...a.map(d=>d.address),...s]).slice(0,da),c=l.length>0?l:void 0,u=await this.service.getWalletPnl({address:e,chain:t,days:n,tokenAddresses:c});return{ok:u.success,error:u.error,tokens:u.data?.result??[],tokenAddresses:c,resolvedFromSymbols:a,unresolvedSymbols:i}}async resolveContractAddress(e,t,n){let o=e.toLowerCase();if(n){let a=await this.service.getWalletTokenBalances({address:n,chain:t});if(a.success&&a.data?.result?.length){let i=a.data.result.find(l=>(l.symbol??"").toLowerCase()===o);if(i)return{address:i.token_address,symbol:i.symbol,name:i.name}}}let s=await this.service.searchTokensByKey({key:e,chain:t});if(s.success&&s.data?.length){let i=s.data.find(l=>(l.symbol??"").toLowerCase()===o)??s.data[0];if(i?.token_address)return{address:i.token_address,symbol:i.symbol,name:i.name}}}};function xm(r){let e=new Set,t=[];for(let n of r){let o=n.toLowerCase();e.has(o)||(e.add(o),t.push(n))}return t}var Cm=BigInt(2)**BigInt(255),Er=class extends S{name="get-wallet-approvals";description=`List every active ERC-20 token approval granted by a wallet \u2014 i.e. which contracts can still spend the wallet's tokens. For each approval, returns: the token (address, name, symbol, logo, current balance, USD price, USD at risk, possible_spam, verified_contract), the spender (address, label, entity \u2014 e.g. "Uniswap V3 Router", "Permit2"), the approved amount (value / value_formatted / isUnlimited flag), and when the approval was granted (block number, timestamp, transaction hash). Also returns aggregates: total approvals, unlimited-approval count, total USD at risk, and approvals flagged as risky (spam tokens, unverified contracts, or unlimited allowance to unlabeled spenders). Use for questions like: "What approvals do I have?", "Show my token approvals", "Am I exposed to any risky approvals?", "Which contracts can drain my wallet?", "Do I have any unlimited approvals?", "Revoke approvals / token allowances". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). Paginated \u2014 pass cursor to fetch the next page.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1},{name:"limit",type:"number",description:"Page size (1-100, default 100).",required:!1,default:100},{name:"cursor",type:"string",description:"Pagination cursor from a previous response.",required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=pe(e.chain,t),s=typeof e.limit=="number"?e.limit:Number(e.limit),a=Number.isFinite(s)&&s>0?Math.min(100,Math.floor(s)):100,i=typeof e.cursor=="string"&&e.cursor?e.cursor:void 0,l=await this.service.getWalletApprovals({address:n,chain:o,limit:a,cursor:i});if(!l.success)return{error:l.error||"Failed to fetch wallet approvals"};let c=l.data,d=(c.result||[]).map(h=>Rm(h)),p=0,m=0,f=[];for(let h of d){h.isUnlimited&&(m+=1);let g=parseFloat(h.token.usdAtRisk??"");Number.isFinite(g)&&(p+=g);let b=h.token.possibleSpam||h.token.verifiedContract===!1,y=!h.spender.label&&!h.spender.entity;(b||h.isUnlimited&&y)&&f.push(h)}return{walletAddress:n,chain:o||"default",filters:{limit:a,cursor:i??null},pagination:{cursor:c.cursor??null,pageSize:c.page_size??a,page:c.page??null,hasMore:!!c.cursor},summary:{totalApprovals:d.length,unlimitedApprovals:m,totalUsdAtRisk:p,riskyApprovalCount:f.length},approvals:d,riskyApprovals:f}}};function Rm(r){let e=Em(r.value);return{blockNumber:r.block_number,blockTimestamp:r.block_timestamp??null,transactionHash:r.transaction_hash??null,value:r.value,valueFormatted:r.value_formatted??null,isUnlimited:e,token:{address:r.token.address,addressLabel:r.token.address_label??null,name:r.token.name??null,symbol:r.token.symbol??null,logo:r.token.logo??null,possibleSpam:!!r.token.possible_spam,verifiedContract:r.token.verified_contract??null,currentBalance:r.token.current_balance??null,currentBalanceFormatted:r.token.current_balance_formatted??null,usdPrice:r.token.usd_price??null,usdAtRisk:r.token.usd_at_risk??null},spender:{address:r.spender.address,label:r.spender.address_label??null,entity:r.spender.entity??null,entityLogo:r.spender.entity_logo??null}}}function Em(r){if(!r)return!1;try{return BigInt(r)>=Cm}catch{return!1}}var _r=class extends S{name="get-wallet-defi-positions";description=`The BROAD, cross-protocol inventory of every DeFi position a wallet holds \u2014 liquidity provision, staking, borrowing AND supply/lending alike \u2014 with full detail: protocol identity, position label (e.g. "Liquidity Provision", "Supply", "Borrow", "Staking"), tokens involved (with balances and USD values), balance_usd, total_unclaimed_usd_value, and position_details (fee tier, liquidity, APY, price range, health factor, etc.). Any APY here is the LIVE SPOT rate. Use for questions like: "Show my DeFi positions", "What LP positions do I have?", "What am I staking?", "Do I have any borrows?", "What is my health factor?", "List all my DeFi holdings with details". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad. PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited funds \u2014 "what am I earning", "my supply APY", "my savings/deposits", "my Aave supply" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Use this tool for supply positions only as part of a full portfolio sweep, or for assets it does not cover (it handles USDC only). Never report both tools' APY for the same position. Also not for: positions filtered to a single protocol \u2192 get-wallet-defi-protocol-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=ne(e.address,t),o=te(e.chain,t);if(o){let i=await this.service.getWalletDefiPositions({address:n,chain:o});if(!i.success)return{error:i.error||"Failed to fetch wallet DeFi positions"};let l=i.data||[];return{walletAddress:n,chain:o,positionCount:l.length,positions:l.map(Jc)}}let a=(await Promise.all(Ce().map(async i=>{let l=await this.service.getWalletDefiPositions({address:n,chain:i});return{chain:i,rows:l.success?l.data||[]:[]}}))).filter(i=>i.rows.length>0).map(i=>({chain:A(i.chain),positionCount:i.rows.length,positions:i.rows.map(Jc)}));return{_instructions:"These DeFi positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in `chains` (only chains the wallet holds positions on). Present one section per chain, in order: the chain name then its positions. If `chains` is empty, say the wallet has no DeFi positions on any supported chain. Do NOT mention tool names.",walletAddress:n,chain:"all",positionCount:a.reduce((i,l)=>i+l.positionCount,0),chains:a}}};function Jc(r){return{protocolName:r.protocol_name,protocolId:r.protocol_id,protocolUrl:r.protocol_url,protocolLogo:r.protocol_logo,accountHealthFactor:r.account_data?.health_factor??null,position:_m(r.position)}}function _m(r){return{label:r.label,address:r.address,balanceUsd:r.balance_usd,totalUnclaimedUsdValue:r.total_unclaimed_usd_value,tokens:(r.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:r.position_details??null}}var Nr=class extends S{name="get-wallet-defi-protocol-positions";description=`Get every position a wallet holds inside ONE specific DeFi protocol \u2014 liquidity provision, staking, borrowing and supply alike \u2014 with full detail. Returns the protocol identity, totals (total_usd_value, total_unclaimed_usd_value), and an array of positions (label, tokens, balance_usd, unclaimed, fee tier, APY, health factor, etc.). Any APY here is the LIVE SPOT rate. Use when the user names a specific protocol, e.g. "my Uniswap v3 positions", "show my Lido staking", "my Curve pools", "Pendle positions", "how much did I borrow on Aave", "what do I have on Aave v3". The "protocol" argument is the Moralis protocol id (kebab-case), e.g. uniswap-v2, uniswap-v3, pancakeswap-v2, pancakeswap-v3, quickswap-v2, quickswap-v3, sushiswap-v2, aave-v2, aave-v3, aave-lido, fraxswap-v1, fraxswap-v2, lido, makerdao, eigenlayer, pendle, etherfi, rocketpool, sparkfi, takara-lend, neverland, kintsu. Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad (EVM mainnets only). PREFER get-wallet-lending-positions instead whenever the question is about EARNING on supplied/deposited USDC \u2014 "my Aave v3 supply", "what am I earning on Spark", "my Compound deposit" \u2014 because that tool adds the 7-day average APY, estimated yearly yield and a safety score that this one lacks. Come back here for that protocol's borrow / LP / staking side, or for supplied assets other than USDC. Never report both tools' APY for the same position. Do NOT use for: cross-protocol view \u2192 get-wallet-defi-positions.`;category="blockchain-data";parameters=[{name:"address",type:"string",description:"EVM wallet address (0x\u2026). If omitted, uses the connected wallet from user context.",required:!1},{name:"protocol",type:"string",description:'Moralis protocol identifier in kebab-case. Examples: "uniswap-v2", "uniswap-v3", "pancakeswap-v2", "pancakeswap-v3", "quickswap-v2", "quickswap-v3", "sushiswap-v2", "aave-v2", "aave-v3", "aave-lido", "fraxswap-v1", "fraxswap-v2", "lido", "makerdao", "eigenlayer", "pendle", "etherfi", "rocketpool", "sparkfi", "takara-lend", "neverland", "kintsu"Use get-wallet-defi-positions to discover which protocols a wallet uses.',required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it \u2014 the connected wallet chain is used, or, when the wallet has no chain set, data is fetched across ALL supported chains.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=e.protocol?.trim();if(!n)return{error:'Protocol identifier is required (e.g. "uniswap-v3", "aave-v3").'};let o=ne(e.address,t),s=te(e.chain,t);if(s){let l=await this.service.getWalletDefiProtocolPositions({address:o,protocol:n,chain:s});return l.success?l.data?{walletAddress:o,chain:s,...this.protocolFields(l.data)}:{error:"No data returned for this protocol"}:{error:l.error||"Failed to fetch wallet DeFi protocol positions"}}let i=(await Promise.all(Ce().map(async l=>{let c=await this.service.getWalletDefiProtocolPositions({address:o,protocol:n,chain:l});return{chain:l,data:c.success?c.data:void 0}}))).flatMap(l=>l.data&&(l.data.positions||[]).length>0?[{chain:A(l.chain),data:l.data}]:[]).map(l=>({chain:l.chain,...this.protocolFields(l.data)})).sort((l,c)=>c.totalUsdValue-l.totalUsdValue);return{_instructions:`These ${n} positions cover ALL supported chains (the user named no chain) and are GROUPED BY CHAIN in \`chains\` (only chains where the wallet holds positions in this protocol, highest value first). Present one section per chain. If \`chains\` is empty, say the wallet has no positions in this protocol on any supported chain. Do NOT mention tool names.`,walletAddress:o,chain:"all",protocol:n,totalUsdValue:i.reduce((l,c)=>l+c.totalUsdValue,0),chains:i}}protocolFields(e){return{protocolName:e.protocol_name,protocolId:e.protocol_id,protocolUrl:e.protocol_url,protocolLogo:e.protocol_logo,totalUsdValue:e.total_usd_value,totalUnclaimedUsdValue:e.total_unclaimed_usd_value,accountHealthFactor:e.account_data?.health_factor??null,positionCount:(e.positions||[]).length,positions:(e.positions||[]).map(Nm)}}};function Nm(r){return{label:r.label,address:r.address,balanceUsd:r.balance_usd,totalUnclaimedUsdValue:r.total_unclaimed_usd_value,tokens:(r.tokens||[]).map(e=>({tokenType:e.token_type,name:e.name,symbol:e.symbol,contractAddress:e.contract_address,decimals:e.decimals,logo:e.logo,thumbnail:e.thumbnail,balance:e.balance,balanceFormatted:e.balance_formatted,usdPrice:e.usd_price,usdValue:e.usd_value})),details:r.position_details??null}}function Im(r){try{return(Number(BigInt(r))/1e18).toFixed(10).replace(/\.?0+$/,"")||"0"}catch{return r}}var Ir=class extends S{name="get-transaction-by-hash";description='Get full decoded details of a single EVM transaction by its hash. Returns: status (success/failed), timestamp, from/to addresses with labels and entity names, native value transferred (ETH), transaction fee, gas used, decoded function call with params, and decoded event logs (ERC-20 transfers, swaps, approvals, etc.). Use this when the user asks: "what did this transaction do?", "explain tx 0x\u2026", "was this transaction successful?", "who sent/received in this tx?", "what function was called?". Supports: Ethereum, Optimism, BSC, Polygon, Base, Arbitrum, Avalanche, Linea, Gnosis, HyperEVM, Mantle, Monad.';category="blockchain-data";parameters=[{name:"transactionHash",type:"string",description:"The transaction hash to look up (0x\u2026).",required:!0},{name:"chain",type:"string",description:'Hex chain ID: "0x1" Ethereum, "0xa" Optimism, "0x38" BSC, "0x89" Polygon, "0x2105" Base, "0xa4b1" Arbitrum, "0xa86a" Avalanche, "0xe708" Linea, "0x64" Gnosis, "0x3e7" HyperEVM, "0x1388" Mantle, "0x8f" Monad. ONLY set this when the user EXPLICITLY names a chain; otherwise OMIT it so the connected wallet chain is used.',required:!1}];service;constructor(e){super(),this.service=new O(e)}async run(e,t){let n=e.transactionHash;if(!n)return{error:"Transaction hash is required."};let o=pe(e.chain,t),s=await this.service.getTransactionByHash({transactionHash:n,chain:o});if(!s.success||!s.data)return{error:s.error||"Failed to fetch transaction"};let a=s.data,i=(a.logs??[]).filter(c=>!!c.decoded_event).map(c=>({contract:c.address,signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params})),l=a.logs.map(c=>({address:c.address,decodedEvent:c.decoded_event?{signature:c.decoded_event.signature,label:c.decoded_event.label,params:c.decoded_event.params}:null}));return{hash:a.hash,status:a.receipt_status==="1"?"success":a.receipt_status==="0"?"failed":"unknown",timestamp:a.block_timestamp,blockNumber:a.block_number,from:{address:a.from_address,label:a.from_address_label||null,entity:a.from_address_entity||null},to:a.to_address?{address:a.to_address,label:a.to_address_label||null,entity:a.to_address_entity||null}:null,valueEth:Im(a.value||"0"),fee:a.transaction_fee,gasUsed:a.receipt_gas_used,gasPriceGwei:a.gas_price?(Number(a.gas_price)/1e9).toFixed(4):null,decodedCall:a.decoded_call?{signature:a.decoded_call.signature,label:a.decoded_call.label,params:a.decoded_call.params}:null,decodedEvents:i,contractCreated:a.receipt_contract_address||null,logs:l}}};var Zc=new Map;function Um(r){let e=Zc.get(r);if(e)return e;let t=qt({rpcUrl:r});return Zc.set(r,t),t}async function eu(r,e,t=[]){let n=await Um(r).rpc(e,t);if(n===void 0)throw new Error(`RPC ${e}: empty result`);return n}function tu(r,e,t){return eu(r,"eth_call",[{to:e,data:t},"latest"])}async function Lm(r,e,t){let n=bn(r);if(!n)return null;try{return await tu(n,e,t)}catch{return null}}function M(r,e){globalThis.__LENDING_DEBUG__!==!1&&(e===void 0?console.log(`[LEND] ${r}`):console.log(`[LEND] ${r}`,JSON.stringify(e,Dm)))}function Dm(r,e){return typeof e=="bigint"?`${e}n`:e}var Om=6e4,rl=new Map;async function cs(r,e){let t=At(e),n=t?parseInt(t,16):NaN;if(!t||!Number.isFinite(n))return[];let o=`${r}|${t}`,s=rl.get(o);if(s&&Date.now()-s.at<Om)return s.markets;let a=Mm(r,t,n),i=a.then(l=>l.markets);return rl.set(o,{at:Date.now(),markets:i}),a.then(l=>{l.answered||rl.delete(o)}),i}async function pa(r,e){return(await cs(r,e)).length>0}async function Mm(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:I(o)}),{markets:[],answered:a}}let s=(o.data?.data?.items||[]).flatMap(a=>{let i=Fm(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 nu(r,e){let t=e.trim().toLowerCase();if(!t)return[];if(_(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 Fm(r,e){if(r?.isDeleted===!0)return null;let t=typeof r?.contract=="string"?r.contract.toLowerCase():"";if(!_(t))return null;let n=typeof r?.token=="string"&&_(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:Be(s),protocolUrl:r?.protocolId?.domain?.trim()||null,type:s,contract:t,token:n,platformScore:Number.isFinite(o)?o:null}}function ol(){return Ce()}async function ma(r){let e=ol(),t=await Promise.all(e.map(n=>pa(r,n)));return e.filter((n,o)=>t[o])}async function ha(r,e){let t=q(e);return t?pa(r,t):!1}async function ru(r,e){let t=e.map(s=>q(s)).filter(s=>!!s),n=[...new Set(t)],o=await Promise.all(n.map(s=>pa(r,s)));return n.filter((s,a)=>o[a])}function Ur(r){return as(r)}var ou=5;async function su(r,e,t){let n=e.map(b=>_(b)?b.toLowerCase():null);if(n.every(b=>b===null))return M("discovery: ABORT \u2014 no valid token address",{tokens:e}),e.map(()=>null);let o=ia(r),s;try{M("discovery: probing 5 accessors per token",{chain:r,tokens:n,psm:o}),s=await de(r,[...n.flatMap(b=>b?Bm(b):[]),...o?Wc(o):[]])}catch(b){return M("discovery: multicall FAILED \u2014 all tokens unresolved",{chain:r,message:b?.message}),e.map(()=>null)}let a=o?s.slice(s.length-Yc):[],i=Y(a[0])?.toLowerCase()??null,l=Y(a[1]),c=Y(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(b=>{if(!b)return null;let y=s.slice(d,d+ou);return d+=ou,M("discovery: probe answers",{token:b,"POOL()":Y(y[0]),"UNDERLYING_ASSET_ADDRESS()":Y(y[1]),"baseToken()":Y(y[2]),"asset()":Y(y[3]),"vsr()":j(y[4])?.toString()??null}),{token:b,slice:y}}),m=new Set;for(let b of p){if(!b)continue;let y=Y(b.slice[0]);y&&Y(b.slice[1])&&m.add(y.toLowerCase())}let f=await qm(r,[...m]);m.size>0&&M("discovery: Aave pool authentication",{claimed:[...m],genuine:[...f]});let h=p.flatMap(b=>b?Y(b.slice[0])&&Y(b.slice[1])||Y(b.slice[2])?[]:Y(b.slice[3])?[b.token]:[]:[]),g=await $m(r,[...new Set(h)],t);return h.length>0&&M("discovery: Morpho vault lookup",{asked:[...new Set(h)],recognised:[...g.keys()]}),p.map(b=>{if(!b)return null;let{token:y,slice:k}=b,w={chain:r,protocolUrl:null,token:y,platformScore:null};if(u&&y===u.susds)return M("discovery: classified",{token:y,as:"spark-l2-susds (bridged share token \u2014 no ERC-4626)",oracle:u.oracle}),{...w,name:"Spark Savings USDS",protocol:"SPARK",protocolLabel:Be("spark-l2-susds"),protocolUrl:Ur("spark-l2-susds"),type:"spark-l2-susds",contract:u.oracle,assetAddress:u.usds};let v=Y(k[0]);if(v&&Y(k[1])){let T=f.has(v.toLowerCase());return M("discovery: classified",{token:y,as:T?"aave-v3":"REJECTED \u2014 pool failed ADDRESSES_PROVIDER()",pool:v}),T?{...w,name:"Aave v3",protocol:"AAVE",protocolLabel:Be("aave-v3"),protocolUrl:Ur("aave-v3"),type:"aave-v3",contract:v}:null}if(Y(k[2]))return M("discovery: classified",{token:y,as:"compound-v3"}),{...w,name:"Compound v3",protocol:"COMPOUND",protocolLabel:Be("compound-v3"),protocolUrl:Ur("compound-v3"),type:"compound-v3",contract:y};if(Y(k[3])){if(g.has(y)){M("discovery: classified",{token:y,as:"morpho-v2"});let C=g.get(y)||"Morpho V2";return{...w,name:C,protocol:"MORPHO",protocolLabel:Be("morpho-v2"),protocolUrl:Ur("morpho-v2"),type:"morpho-v2",contract:y}}let P=j(k[4])!==null;return M("discovery: classified",{token:y,as:P?"spark-ethereum (Vaults V2 \u2014 vsr())":"spark (generic ERC-4626)"}),P?{...w,name:"Spark",protocol:"SPARK",protocolLabel:Be("spark-ethereum"),protocolUrl:Ur("spark-ethereum"),type:"spark-ethereum",contract:y}:{...w,name:"Spark",protocol:"SPARK",protocolLabel:Be("spark"),protocolUrl:Ur("spark"),type:"spark",contract:y}}return M("discovery: classified",{token:y,as:"NOT a lending receipt \u2014 plain ERC-20"}),null})}function Bm(r){return[{target:r,callData:F({abi:gr,functionName:"POOL"})},{target:r,callData:F({abi:gr,functionName:"UNDERLYING_ASSET_ADDRESS"})},{target:r,callData:F({abi:Tt,functionName:"baseToken"})},{target:r,callData:F({abi:st,functionName:"asset"})},{target:r,callData:F({abi:fr,functionName:"vsr"})}]}async function qm(r,e){if(e.length===0)return new Set;try{let t=await de(r,e.map(n=>({target:n,callData:F({abi:Xi,functionName:"ADDRESSES_PROVIDER"})})));return new Set(e.filter((n,o)=>Y(t[o])!==null))}catch{return new Set}}async function $m(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 Hm=.01;function Vm(r){return r.reduce((e,t)=>t.conditions===null?e+t.apyPercent:e,0)}function Wm(r,e){if(typeof e!="string"||!e.trim())return;let t=e.trim(),n=Ko();n[r]!==t&&fn({...n,[r]:t})}var Lr=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=At(e);s&&Wm(s,n);let a=s?is(s):null,i=[...new Set(t.filter(_).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 su(s,i,this.endpoints.morphoApiUrl),u=[...new Map(i.flatMap((p,m)=>{let f=l[m];return M("describeReceiptTokens: discovery result",{token:p,found:!!f,protocol:f?.protocol,type:f?.type,contract:f?.contract}),f?[[p,f]]:[]})).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,baseApyPercent:p.baseApyPercent,rewardApyPercent:p.rewardApyPercent,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}),!_(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.address))return[];let t=await ru(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=At(e),o=n?is(n):null;return n&&o?this.describer.describe(n,o,t):[]}async positionsForChain(e,t){let n=is(e),o=await cs(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<Hm?[]:[{...l,suppliedUsdc:u,estimatedAnnualYieldUsdc:l.avgApyPercent===null?null:u*(l.avgApyPercent+Vm(l.rewards))/100}]})}};var sl=["aave-v3","compound-v3","spark","spark-ethereum","morpho-v2"];var Dr=class{constructor(e){this.coinPoolBaseUrl=e}coinPoolBaseUrl;async listChains(){return ma(this.coinPoolBaseUrl)}async isSupported(e){return ha(this.coinPoolBaseUrl,e)}async getMarkets(e){let t=q(e);return t?cs(this.coinPoolBaseUrl,t):[]}async findMarket(e,t){let n=await this.getMarkets(e);return nu(n,t)}canSupply(e){return sl.includes(e.type)}async readReceiptToken(e,t){let n=jt(t).balanceIsUnderlying;try{let o=await de(e,[{target:t.token,callData:F({abi:H,functionName:"symbol"})},{target:t.token,callData:F({abi:H,functionName:"decimals"})}]);return{symbol:Mn(o[0]),decimals:Fn(o[1]),isUnderlying:n}}catch{return{symbol:null,decimals:null,isUnderlying:n}}}};var Ym={1:"ethereum",10:"opmainnet",56:"bsc",130:"unichain",8453:"base",42161:"arbitrum"},Gm={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"},Km={1:"mainnet",10:"optimism",100:"gnosis",130:"unichain",196:"xlayer",480:"worldchain",4663:"robinhood",8453:"base",42161:"arbitrum",43114:"avalanche"},jm={1:"mainnet",10:"op",130:"unichain",137:"polygon",8453:"basemainnet",42161:"arb",59144:"linea",534352:"scroll"};function ga(r){let e=rh(r.chain);return(e===null?null:zm(r,e))??as(r.type)??nh(r,e)}function zm(r,e){switch(r.type){case"morpho-v2":{let t=Ym[e];if(!t||!r.contract)return null;let n=`https://app.morpho.org/${t}/vault/${al(r.contract)}`,o=Jm(r.name);return o?`${n}/${o}`:n}case"aave-v3":{let t=Gm[e],n=Xm(r);return!t||!n?null:`https://app.aave.com/reserve-overview/?underlyingAsset=${al(n)}&marketName=${t}`}case"spark":case"spark-ethereum":case"spark-l2-susds":{let t=Km[e],n=eh(r);return!t||!n?null:`https://app.spark.fi/savings/${t}/${n}`}case"compound-v3":{let t=jm[e],n=Zm(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 Qm=new Set(["morpho","morpho v2","morpho v1","morpho vault","morpho blue"]);function Jm(r){let e=r?.trim().toLowerCase()||"";return!e||Qm.has(e)?null:e.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||null}function Zm(r){let e=r.asset?.symbol?.trim().toLowerCase()||"";return/^[a-z0-9]+(\.[a-z0-9]+)*$/.test(e)&&e.length<=12?e:null}function eh(r){let e=r.shareSymbol?.trim().toLowerCase()||"";if(/^[a-z0-9]{2,12}$/.test(e))return e;let t=`${r.name||""} ${r.token||""}`.toLowerCase();for(let o of["spusdc","spusdt","spusdg","sppyusd","speth","susds","susdc","sdai"])if(t.includes(o))return o;if(r.type==="spark-ethereum")return th[r.contract?.trim().toLowerCase()||""]??null;let n=r.asset?.symbol?.trim().toLowerCase()||"";return!/^[a-z0-9]{2,11}$/.test(n)||n.startsWith("s")?null:`s${n}`}var th={"0xfe6eb3b609a7c8352a241f7f3a21cea4e9209b8f":"speth","0x80128dbb9f07b93dde62a6daeadb69ed14a7d354":"sppyusd","0xe2e7a17dff93280dec073c995595155283e3c372":"spusdt","0x28b3a8fb53b741a8fd78c0fb9a6b2393d896a43d":"spusdc","0x45d91340b3b7b96985a72b5c678f7d9e8d664b62":"spusdt","0xc358c90d32375721cb3924320fdc2f8b694347ca":"spusdt","0xde770c84fe66e063336b31737cfe9790f18c4087":"spusdg"};function nh(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",al(r.contract)),o.toString()}catch{return n}}function al(r){let e=r.trim().toLowerCase();return e.startsWith("0x")?e:`0x${e}`}function rh(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 oh=new Set(["spark","spark-ethereum"]),sh=8;function ah(r,e,t){if(r.market.type!=="spark-l2-susds")return j(e);let n=j(e);return n===null||r.tokenDecimals===null?null:An(r.rawBalance,n,r.tokenDecimals,t)}var fa=class{constructor(e){this.endpoints=e}endpoints;apyLimiter=new il(sh);pantograph=new le;async describe(e,t,n){if(n.length===0)return[];M("describe: START",{chain:e,count:n.length,types:n.map(l=>l.type)});let{assets:o,shareSymbols:s}=await this.resolveAssets(e,n);M("describe: assets resolved",o);let[a,i]=await Promise.all([this.readMarketState(e,n,o),Promise.all(n.map((l,c)=>this.apyLimiter.run(()=>this.fetchApy(l,t,o[c]))))]);return M("describe: on-chain state",a),M("describe: APY fetched",i.map((l,c)=>({type:n[c].type,rawSamples:l.samples.length,sourceCurrent:l.current}))),n.map((l,c)=>{let{totalSuppliedUsdc:u,liveApyFraction:d}=a[c],p=lh(i[c].samples,d??i[c].current,i[c].rewards,i[c].avgOverride??null);return M("describe: summarised",{market:l.name,type:l.type,liveFrom:d!==null?"on-chain":i[c].current!==null?"api":"none",rawSamples:i[c].samples.length,historyPoints:p.history.length,currentApyPercent:p.currentApyPercent,avgApyPercent:p.avgApyPercent,apyChangePercent:p.apyChangePercent,totalSuppliedUsdc:u,asset:o[c]?.symbol}),{...l,protocolUrl:ga({...l,asset:o[c],shareSymbol:s[c]}),asset:o[c],totalSuppliedUsdc:u,avgApyPercent:p.avgApyPercent,currentApyPercent:p.currentApyPercent,baseApyPercent:p.baseApyPercent,rewardApyPercent:p.rewardApyPercent,rewards:p.rewards,apyChangePercent:p.apyChangePercent,apyHistory:p.history}})}async readBalances(e,t,n){let o=F({abi:H,functionName:"balanceOf",args:[t]}),s=F({abi:H,functionName:"decimals"}),a=n.flatMap(l=>[{target:l.token,callData:o},{target:l.token,callData:s}]),i=await de(e,a);return n.flatMap((l,c)=>{let u=j(i[c*2]);return u===null||u<=0n?[]:[{market:l,rawBalance:u,tokenDecimals:Fn(i[c*2+1])}]})}async convertToUnderlying(e,t,n){let o=[],s=t.map(i=>{let l=jt(i.market).convertToAssetsCall(i.market,i.rawBalance);return l?(o.push(l),o.length-1):-1}),a=await de(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 Fe(i.rawBalance,c);let u=ah(i,a[s[l]],c);return u===null?Fe(i.rawBalance,i.tokenDecimals??c):Fe(u,c)})}async resolveAssets(e,t){let n={address:Pn,decimals:NaN,symbol:null,logo:null},o=[],s=t.map(p=>{let m=jt(p).underlyingCall(p);return m?(o.push(m),o.length-1):-1}),a;try{let p=o.length>0?await de(e,o):[];a=s.map(m=>m<0?null:Y(p[m]))}catch{a=t.map(()=>null)}a=a.map((p,m)=>p??t[m]?.assetAddress??null);let i=[...new Set(a.filter(p=>!!p).map(p=>p.toLowerCase()))],[l,c,u]=await Promise.all([this.readAssetMetadata(e,i),this.fetchAssetLogos(e,i),this.readShareSymbols(e,t)]);return{assets:a.map(p=>{if(!p)return n;let m=p.toLowerCase(),f=l.get(m),h=c.get(m)??null;return f?.decimals!==null&&f?.decimals!==void 0?{address:p,decimals:f.decimals,symbol:f.symbol??null,logo:h}:{address:p,decimals:NaN,symbol:null,logo:h}}),shareSymbols:u}}async readShareSymbols(e,t){let n=F({abi:H,functionName:"symbol"}),o=[],s=t.map(a=>!oh.has(a.type)||!a.contract?-1:(o.push({target:a.contract,callData:n}),o.length-1));if(o.length===0)return t.map(()=>null);try{let a=await de(e,o);return s.map(i=>i<0?null:Mn(a[i]))}catch{return t.map(()=>null)}}async readAssetMetadata(e,t){let n=new Map;if(t.length===0)return n;let o=F({abi:H,functionName:"decimals"}),s=F({abi:H,functionName:"symbol"});try{let a=await de(e,t.flatMap(i=>[{target:i,callData:o},{target:i,callData:s}]));t.forEach((i,l)=>{n.set(i,{decimals:Fn(a[l*2]),symbol:Mn(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=jt(u),m=n[d],f={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&&(f.rate=o.length,o.push(h)),f}),a=await de(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 de(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 jt(e).fetchApy(e,t,this.endpoints,n);return M("fetchApy: got",{market:e.name,samples:o.samples.length,current:o.current,avgOverride:o.avgOverride??null}),o}catch(o){return M("fetchApy: FAILED \u2014 market listed without APY",{market:e.name,type:e.type,message:o?.message}),{samples:[],current:null,rewards:[]}}}},il=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 ih(r,e){let t=Jo(Date.now()),n=new Map,o=null;for(let i of r)!Number.isFinite(i.timeMs)||!Number.isFinite(i.fraction)||i.fraction<0||Jo(i.timeMs)>t||((!o||i.timeMs>o.timeMs)&&(o=i),n.set(i.timeMs,i.fraction));let s=[...n.entries()].sort((i,l)=>i[0]-l[0]).map(([i,l])=>({date:new Date(i).toISOString(),apyPercent:l*100})),a=e??(o&&Jo(o.timeMs)===t?o.fraction:null);return{history:s,live:a}}function lh(r,e,t=[],n=null){let{history:o,live:s}=ih(r,e),a=s===null?null:s*100,i=t.map(m=>({apyPercent:m.fraction*100,tokenSymbol:m.tokenSymbol,conditions:m.conditions})),l=i.length===0?null:i.reduce((m,f)=>m+f.apyPercent,0),c=a===null?null:a+(l??0),u={baseApyPercent:a,rewardApyPercent:l,rewards:i},d=n!==null&&Number.isFinite(n)?n*100:null;if(o.length===0)return{history:o,avgApyPercent:d,currentApyPercent:c,apyChangePercent:null,...u};let p=o.reduce((m,f)=>m+f.apyPercent,0);return{history:o,avgApyPercent:d??p/o.length,currentApyPercent:c,apyChangePercent:uh(o,a),...u}}var au=3600*1e3,ch=au/2;function uh(r,e){if(e===null)return null;let t=Date.now()-au,n=null,o=Number.POSITIVE_INFINITY;for(let s=r.length-1;s>=0;s--){let a=Math.abs(Date.parse(r[s].date)-t);if(a>o)break;o=a,n=r[s]}return!n||o>ch?null:e-n.apyPercent}function iu(r,e){if(!Number.isFinite(r))return r;let t=10**e,n=Number((r*t).toPrecision(15));return(r<0?-Math.floor(-n):Math.floor(n))/t+0}var ze=class{read;supply;constructor(e={}){let t=e.coinPoolBaseUrl||"https://api.coinpool.app",n={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 fa(n);this.read=new Lr(t,n,o),this.supply=new Dr(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 us="{market}",uu=[{name:"detail_button_label",type:"string",description:`Label for the per-market "More detail" buttons that render under EVERY market you list, IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it \u2014 a button is shown for each market automatically. Just the words "More detail" translated: English "More detail", Vietnamese "Chi ti\u1EBFt", Japanese "\u8A73\u7D30". Do NOT name the market in it and do NOT use the "{market}" placeholder \u2014 each button is rendered on that market's own card with its name directly above, so repeating the name only makes every card wordier. Keep it to one or two words so it fits on one line.`,required:!1},{name:"detail_prompt_template",type:"string",description:`A short "show me this market in detail" request template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when a market's button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "show me details of {market}". Vietnamese example: "xem chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng {market}". Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],ba=[{name:"supply_button_label",type:"string",description:`Label template for the "Supply" button \u2014 shown on EVERY market you list, and on the single market you describe \u2014 IN THE USER'S CURRENT LANGUAGE. ALWAYS provide it; the button is rendered automatically. Unlike the "More detail" label, this one DOES name the market: it is the button that moves money. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name (e.g. "Aave v3 USDC"). English example: "Supply {market}". Vietnamese example: "N\u1EA1p v\xE0o {market}". IN JAPANESE the label MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 render "supply" as the katakana \u30B5\u30D7\u30E9\u30A4, NEVER as \u4F9B\u7D66, \u9810\u3051\u5165\u308C, \u5165\u91D1 or any other kanji wording. Always include {market}.`,required:!1},{name:"supply_prompt_template",type:"string",description:`A short "supply" command template IN THE USER'S CURRENT LANGUAGE, submitted as the next user turn when the button is clicked. ALWAYS provide it. Use the exact placeholder "{market}" (do not translate the braces); it is replaced with the market name. English example: "supply to {market}". Vietnamese example: "n\u1EA1p v\xE0o {market}". IN JAPANESE it MUST be exactly "{market}\u3092\u30B5\u30D7\u30E9\u30A4" \u2014 use the katakana \u30B5\u30D7\u30E9\u30A4, NEVER \u4F9B\u7D66 or another kanji wording. Always include {market}. Do NOT write the chain name or a contract address yourself \u2014 the chain and the exact market identifier are appended automatically as a "(market: 0x\u2026 - <chain>)" hint.`,required:!1}],du="[[LIST]]",pu=' The market list is ALREADY RENDERED as cards below your reply \u2014 each card is numbered and shows the market name (linked to its page), its chain and its live APY, with its own "More detail" and "Supply" buttons. Do NOT write the list out in your text: no numbered list, no bullet list, no per-market lines, no links, and no mention of the buttons or of tapping one. Anything you write is shown ABOVE the cards, so repeating them just prints the same list twice. Naming the ONE market that tops the ordering, with its rate, is not repeating the list and is allowed where your other instructions say so \u2014 what is banned is walking through the markets one by one. Do NOT tell the user to supply, or push them toward it: the button is there if they want it, and this step has not shown them enough to judge a market.',mu=' A clickable "Supply" button for this market is shown below your reply automatically \u2014 do NOT repeat it in your text, do NOT tell the user to tap it, and do NOT describe it as a button, form or screen; just deliver the analysis.';function hu(r,e,t){let[n]=dh([r],e,t),[o]=r.canSupply?ll(r,e,t):[];return{name:r.name?.trim()||r.protocol,protocol:r.protocol,protocolUrl:r.protocolUrl,chain:t,apyPercent:r.apyPercent,detailPrompt:n?.prompt??"",detailLabel:n?.label??"",supplyPrompt:o?.prompt??"",supplyLabel:o?.label??""}}function dh(r,e,t){return gu(r,{labelTemplate:ya(e.detail_button_label),promptTemplate:ya(e.detail_prompt_template),labelFallback:"More detail",promptFallback:`Show me details of ${us}`,...t===void 0?{}:{chainName:t}})}function ll(r,e,t){return gu([r],{labelTemplate:ya(e.supply_button_label),promptTemplate:ya(e.supply_prompt_template),labelNamesMarket:!0,labelFallback:`Supply ${us}`,promptFallback:`supply to ${us}`,...t===void 0?{}:{chainName:t},max:1})}function gu(r,e){let t=typeof e.chainName=="string"?e.chainName.trim():"",n=[],o=new Set;for(let s of r){if(e.max!==void 0&&n.length>=e.max)break;let a=s.name?.trim();!a||o.has(a.toLowerCase())||(o.add(a.toLowerCase()),n.push({label:lu(e.labelTemplate,a,e.labelFallback,e.labelNamesMarket===!0),prompt:lu(ph(e.promptTemplate),a,e.promptFallback)+mh(s.contract,t)}))}return n}function ph(r){let[e,t]=[r[0],r[1]];return e===void 0||e===e.toLowerCase()||t!==void 0&&t!==t.toLowerCase()?r:e.toLowerCase()+r.slice(1)}function ya(r){return typeof r=="string"?r:""}function mh(r,e){let t=r?.trim();if(!t||!/^0x[a-fA-F0-9]{40}$/.test(t))return"";let n=e?.trim();return n?` (market: ${t} - ${n})`:` (market: ${t})`}function lu(r,e,t,n=!0){let s=r&&(!n||r.includes(us))?r:t;return hh(s).split(us).join(e).replace(/\s+/g," ").trim()}var cu="{chain}";function hh(r){if(!r.includes(cu))return r;let e=cu.replace(/[{}]/g,"\\$&");return r.replace(new RegExp(`\\s*\\S+\\s*${e}`,"g"),"").replace(new RegExp(`${e}\\s*\\S+\\s*`,"g"),"").replace(new RegExp(e,"g"),"")}var wa=[{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"]}],ul=wa.map(r=>r.label),cl={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 fu(r){let e=typeof r=="string"?r.trim():"";if(!e)return{kind:"none"};let t=bh(e);if(!t)return{kind:"none"};let n=gh(t);if(n){let s=new Set(n.types);return{kind:"supported",label:n.label,matches:a=>s.has(a.type)}}let o=yh(t);return o?{kind:"unsupported",label:o,requested:e}:{kind:"unknown",requested:e}}function gh(r){let e=wa.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=wa.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 fh(r)}function fh(r){let e=null,t=!1;for(let n of wa)for(let o of n.aliases){let s=yu(o);if(s===0||Math.abs(o.length-r.length)>s)continue;let a=bu(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 yu(r){return r.length<=4?0:r.length<=9?2:3}function yh(r){let e=cl[r];if(e)return e;if(r.length>=4){let o=new Set(Object.entries(cl).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(cl)){let a=yu(o);if(a===0||Math.abs(o.length-r.length)>a)continue;let i=bu(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 bh(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"").replace(/v\d+$/,"")}function bu(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]}function ae(r,e){return r==null?null:iu(r,e)}var Te=2,zt=2;function ka(r){let e=ae(r.currentApyPercent,Te),t=r.rewards.map(s=>({apyPercent:ae(s.apyPercent,Te)??0,tokenSymbol:s.tokenSymbol,conditions:s.conditions})),n=r.rewardApyPercent===null?null:t.reduce((s,a)=>s+Math.round(a.apyPercent*100),0)/100;if(n===null||e===null)return{currentApyPercent:e,rewardApyPercent:n,rewards:t,baseApyPercent:ae(r.baseApyPercent,Te)};let o=Math.round(e*100)-Math.round(n*100);return{currentApyPercent:e,rewardApyPercent:n,rewards:t,baseApyPercent:o/100}}var wh=["apy","score","size"],wu=3,ku=40,Or=class extends S{name="get-lending-markets";kind="ui";description='BROWSE the LENDING / SUPPLY markets available to deposit into and earn yield on (Aave v3, Compound v3, Spark, Morpho vaults). Returns a deliberately SHORT shortlist row per market: its name, its page on the protocol, and its live supply APY \u2014 nothing else. Ranked by that live APY by default, and filterable to ONE protocol via `protocol`. Each market gets a "More detail" button \u2014 how the user reaches its size, recent average APY, reward split and platform score \u2014 and a "Supply" button that starts a deposit. So this tool answers "what is out there", NOT "is this one worth it". Use for questions like: "promising lending DeFi", "where can I earn on my USDC?", "best lending APY", "which protocols can I supply USDC to?", "lending options on Base", "safest place to lend stablecoins", "best yield right now", "show me the Aave markets". ALSO use when the user asks about a lending protocol you believe is NOT supported \u2014 pass their wording as `protocol` and this tool reports whether it exists here, so you never answer that from memory. The same applies to CHAINS and ASSETS: the market list is fetched live, so never answer "we have no markets on X" or "we only support USDC" from memory \u2014 call the tool and report what it returns. Do NOT use for: everything about ONE named market (size, score, average APY, rewards, whether it is a good place to put money) \u2192 get-lending-market-detail; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions; liquidity-pool / LP yield \u2192 the pool tools.';category="blockchain-data";parameters=[{name:"chain",type:"string",description:`Hex chain ID to scope the list to (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the user names \u2014 which chains carry markets is resolved at call time, so never filter the request against a list you remember. Set it ONLY when the user names a chain; otherwise OMIT it \u2014 the connected wallet's chain is used, or every chain at once when no wallet is connected. Never guess a chain to work around a wallet connected to one without lending markets.`,required:!1},{name:"protocol",type:"string",description:`Scope the list to ONE lending protocol. Supported: ${ul.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-${ku}. Default ${wu} \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},...uu,...ba];service;constructor(e){super(),this.service=new ze(e)}async run(e,t){let n=te(e.chain,void 0),o=n?null:q(t?.chain),s=n??o,a=s?await this.service.isSupported(s):!1,i=a?[]:await this.service.listSupportedChains();if(s&&!a)return{_instructions:`There are no lending markets on ${A(s)}`+(o?", the chain the wallet is currently connected to":"")+". Tell the user that in their language and name the chains that DO have them (in `chainsWithLendingMarkets`), offering to list those instead. Do NOT mention tool names.",chain:A(s),connectedChainHasNoMarkets:o!==null,marketCount:0,marketNames:[],chainsWithLendingMarkets:i.map(y=>A(y))};let l=fu(e.protocol);if(l.kind==="unsupported"||l.kind==="unknown")return this.unsupportedProtocol(l);let c=s?[s]:i,u=vh(e.sort),d=Th(e.limit),p=await this.service.getMarketOverviews({chains:c}),m=l.kind==="supported"?p.filter(y=>l.matches(y)):p;if(l.kind==="supported"&&m.length===0&&p.length>0)return{_instructions:`There are no ${l.label} lending markets on ${s?A(s):"any supported chain"} right now. Say so in the user's language, then offer what IS there: name the protocols in \`protocolsAvailable\` and offer to list those markets instead. Do NOT invent a ${l.label} market. Do NOT mention tool names.`,requestedProtocol:l.label,chain:s?A(s):"all",marketCount:0,marketNames:[],protocolsAvailable:[...new Set(p.map(y=>y.protocol))]};let f=[...m].sort(kh[u]).slice(0,d),h=f.map(y=>hu({name:y.name,contract:y.contract,protocol:y.protocol,protocolUrl:y.protocolUrl,apyPercent:ae(y.currentApyPercent,Te),canSupply:this.service.supply.canSupply(y)},e,A(y.chain))),b={component:"LendingMarketList",props:{chain:s?A(s):"all",multiChain:new Set(h.map(y=>y.chain)).size>1,markets:h}};return{...h.length>0?{ui:b}:{},_instructions:this.instructions(f,u,h.length>0,l.kind==="supported"?l.label:null),chain:s?A(s):"all",chainsQueried:c.map(y=>A(y)),...l.kind==="supported"?{protocolFilter:l.label}:{},sortedBy:u,marketCount:h.length,totalMarketsAvailable:m.length,marketNames:h.map(y=>y.name)}}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:[...ul],marketCount:0,marketNames:[]}}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 say so, and do not imply it is every lending market available.`:`These are lending markets the user can supply to, ${s}.`,`Write your reply in TWO parts separated by a line containing exactly ${du} and nothing`,"else. Include that marker EXACTLY ONCE, on its own line. Do not translate it, style it, or explain it.","PART ONE, before the marker: ONE short sentence saying what the list is and how it is ordered.","PART TWO, after the marker: at most two short sentences \u2014 the takeaway, then the caveats below.","Do not retell the markets in either part; they are already on screen.",t==="apy"?"In part two you MAY name the market at the top of the list and the live APY shown on its card, as the plain observation that it currently leads on rate. Write it in your own words. Do not add anything else about that market, and do not present it as a recommendation.":"Do NOT say which market pays the most: this list is NOT ordered by APY, so its first entry is not the highest-paying one.",new Set(e.map(a=>a.chain)).size>1?"The markets span several chains; each one shows its own chain.":`All of them are on ${A(e[0].chain)} \u2014 you may name that chain in your sentence.`,"You have NOT been given the market size, the platform score, the average APY, the daily change,","or the interest/reward split \u2014 they are not in this result. Do NOT state, estimate, or imply ANY of them,","for the list as a whole or for any single market.",`Saying the list is ${s} is allowed and expected \u2014 that is what the ordering means.`,"What you must NOT do is make a QUALITY claim about a market: do not call any one of them safe, safest,","stable, reliable, biggest or best-rated. Naming which market tops the ordering is fine \u2014 that is just",'reading the list back. Calling it the best one is not, because "best" rests on the figures this step',"does not have.",'So do NOT recommend one market over the others and do NOT name a "best option" \u2014 the figures that would',"justify a pick are exactly the ones this step omits. Point the user at a card instead: the full figures","are one tap away.","Part two MUST end by noting, in your own words, that APYs move constantly so a rate shown now is not a","promise of future yield, and that this is information rather than financial advice. Phrase it naturally","in the user's language \u2014 never omit it, however short the user asked you to be.","Do NOT mention tool names.",n?pu:""].filter(Boolean).join(" ")}},kh={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 vh(r){let e=typeof r=="string"?r.trim().toLowerCase():"";return wh.includes(e)?e:"apy"}function Th(r){let e=typeof r=="number"?r:Number(r);return!Number.isFinite(e)||e<1?wu:Math.min(Math.floor(e),ku)}function vu(r){let{currentApyPercent:e,avgApyPercent:t,totalSuppliedUsdc:n,rewardApyPercent:o,baseApyPercent:s,platformScore:a}=r;return r.rewards.find(l=>l.conditions)?{id:"conditional-reward",lead:"the headline rate is not what a plain deposit earns \u2014 a reward programme with conditions attached makes up part of it, and the user meets those conditions only by doing something extra",order:"split the rate first and say what a plain deposit actually earns, then the conditions in plain words, and only afterwards the market itself and who this genuinely suits"}:o!==null&&s!==null&&o>s*1?{id:"reward-dominant",lead:"most of this rate is incentive rewards rather than interest paid by borrowers, so it depends on a programme that can be cut or expire",order:"where the yield really comes from first, then how durable that makes it, then the market and protocol underneath it"}:e!==null&&t!==null&&t>0&&e>t*1.5?{id:"spiked-rate",lead:"the live rate sits well above its own recent average, so it has caught a spike rather than settled there and should not be read as the rate to expect",order:"the gap between live and average first and what usually causes it, then what a supplier would more realistically earn, then the market and protocol"}:n!==null&&n<1e7?{id:"thin-market",lead:"this market is small, so its size is the first thing to weigh: a few large withdrawals can move things, and position sizing matters more here than the rate does",order:"size and what it implies for getting money back out first, then the protocol and who runs it, and the rate last"}:a!==null&&a<6?{id:"weak-score",lead:"the platform score is on the low side, which is the first thing to square before the rate matters",order:"what the score does and does not tell them first, then the protocol itself, then size and rate"}:a!==null&&a>=8.5&&n!==null&&n>=25e7?{id:"blue-chip",lead:"this is one of the most established places to lend this asset \u2014 depth and track record are the real argument here, and the rate is almost a detail",order:"how proven and deep it is first, then what that means for getting money in and out, then the rate and what moves it"}:n!==null&&n>=25e7?{id:"deep-market",lead:"the market is deep enough that the user's deposit is a drop in it \u2014 they can come and go without moving the rate",order:"depth and liquidity first, then where the yield comes from, then the protocol"}:{id:"ordinary",lead:"nothing here is dramatic, and that is the finding: it is an ordinary, steady place to park this asset, which is exactly what suits a first lending position",order:"the absence of surprises first and why that is a virtue, then what is actually earned and from whom, then the protocol behind it"}}function va(r){let e=typeof r=="string"?r.trim():"",t=/[[(]\s*market\s*:\s*(0x[a-fA-F0-9]{40})[^\])]*[\])]/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}var Mr=class extends S{name="get-lending-market-detail";category="blockchain-data";description='Everything about ONE lending / supply market, for when the user has picked a market and wants to know whether it is worth depositing into: its size, the live supply APY split into interest vs reward incentives (with any conditions attached to those incentives), the recent average APY and how the rate has moved, the asset it lends, its 0\u201310 platform score, and its page on the protocol. This is the tool for a tapped "More detail" button, and for any question aimed at a SINGLE named market: "tell me more about Aave v3 USDC", "is Morpho Gauntlet USDC safe?", "how big is the Spark vault", "chi ti\u1EBFt th\u1ECB tr\u01B0\u1EDDng Compound v3", "what is the real APY on that one". Pass `market` \u2014 the market name, the protocol, or the market contract address. When the message carries a "(market: 0x\u2026 - <chain>)" hint, pass THAT address as `market` and THAT chain as `chain` \u2014 together they name the exact market. Needs NO wallet: it reads and describes, it does not deposit. Do NOT use for: LISTING or comparing several markets \u2192 get-lending-markets; actually depositing into this market \u2192 open-supply-usdc-form; what the wallet ALREADY supplies \u2192 get-wallet-lending-positions.';parameters=[{name:"market",type:"string",description:'Which market to describe \u2014 the market name or protocol as shown to the user ("Aave v3 USDC", "Compound v3", "Morpho Steakhouse USDC"), or the market contract address. Required: never guess a market the user did not name. When the user\'s message carries a "(market: 0x\u2026 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID the market lives on (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base). Pass whatever chain the message names \u2014 INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},...ba];service;constructor(e){super(),this.service=new ze(e)}async run(e,t){let o=te(e.chain,void 0)??q(t?.chain);if(!o)return{error:"no_chain",_instructions:"No chain could be determined for this market, so it cannot be looked up. Ask the user which chain the market is on. Do NOT mention tool names."};if(!await this.service.isSupported(o)){let d=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:A(o),chainsWithLendingMarkets:d.map(p=>A(p)),_instructions:`There are no lending markets on ${A(o)}, so there is no market to describe there. Tell the user in their language and name the chains in \`chainsWithLendingMarkets\` instead. Do NOT mention tool names.`}}let s=va(e.market);if(!s)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to know about \u2014 do not pick one for them. Do NOT mention tool names."};let a=await this.service.findMarket(o,s);if(a.length===0)return{error:"market_not_found",market:s,chain:A(o),_instructions:`No lending market matching "${s}" exists on ${A(o)}. Tell the user in their language and offer to show the markets that ARE available there. Do NOT invent a market and do NOT mention tool names.`};if(a.length>1)return{error:"ambiguous_market",market:s,chain:A(o),candidates:a.map(d=>({marketName:d.name,protocol:d.protocol})),_instructions:`"${s}" matches ${a.length} different markets on ${A(o)}, so there is no single one to describe. Do NOT answer this turn and do NOT ask the user to pick from a list of names. Instead call get-lending-markets NOW, passing protocol="`+s+`" and chain for ${A(o)}, plus the localized button templates \u2014 that shows the user each market as a card to tap. Write no message of your own before that call.`};let i=a[0],l=await this.describeOne(o,i);if(!l)return{error:"market_unavailable",marketName:i.name,chain:A(o),_instructions:`${i.name}'s current figures could not be read just now. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT quote any rate, size or score from memory, and do NOT mention tool names.`};let c=this.service.supply.canSupply(i),u=c?ll({name:i.name,contract:i.contract},e,A(o)):[];return{_instructions:this.instructions(l,u.length>0,c),...u.length>0?{actionButtons:u}:{},marketName:l.name,protocol:l.protocolLabel??l.protocol,protocolUrl:l.protocolUrl,chain:A(l.chain),suppliedAssetSymbol:l.asset.symbol,totalSuppliedUsdc:ae(l.totalSuppliedUsdc,zt),...ka(l),avgApyPercent:ae(l.avgApyPercent,Te),apyChangePercent:ae(l.apyChangePercent,Te),platformScore:l.platformScore,supplySupported:c}}async describeOne(e,t){try{let[n]=await this.service.describeResolvedMarkets(e,[t]);return n??null}catch{return null}}instructions(e,t,n){let o=vu(e);return[`This is the full picture of ONE lending market, ${e.name}, which the user asked about.`,"Lead with `marketName` in bold as PLAIN TEXT \u2014 **marketName** \u2014 not as a link, and name its `chain`.",'Go straight from that line into the bullets: do NOT write an introductory sentence before them ("Here is','a closer look at this market", "Here are the details", "Below is an overview"). Such a line says nothing',"the title has not already said and reads as boilerplate when every market opens with it.","Give a short bullet list, in this order. The FIRST bullet is nothing but a markdown link whose TEXT",'is the single word "Website" (translated into the user\'s language) and whose target is `protocolUrl` \u2014','exactly "- [Website](protocolUrl)". Do NOT put a label, a colon or any other word before or after that','link on the bullet: never "Website: [Website](\u2026)". NEVER print the raw URL as visible text, and NEVER use',"the market name as the link text. When `protocolUrl` is null, OMIT this bullet entirely; never invent a","URL.",'Then "Total supplied" = `totalSuppliedUsdc`, "Current APY" = `currentApyPercent`, "Avg APY" =',"`avgApyPercent`, and \u2014 only when the user asked about safety or the number helps your verdict \u2014",'"Platform score" = `platformScore`.',"Label `avgApyPercent` simply as the RECENT average. You have NOT been told what period it covers, so do",'NOT say "7-day", "past week", "last 30 days" or name any window or number of days for it.',"When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: write the",'"Current APY" bullet as the total followed by the split in parentheses \u2014 e.g. "2.11% (1.60% interest +','0.51% rewards)" \u2014 naming the reward token from `rewards[].tokenSymbol` when there is one. When it IS',"null, write `currentApyPercent` plainly and say NOTHING about rewards.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL \u2014 the user earns it only by meeting","those requirements, which a plain deposit usually does not. You MUST add a short plain-language warning","saying the reward part needs conditions and summarising them, so the total is never presented as what a","simple deposit earns. Never omit this to keep the answer short, and never quote such a total as if it","were guaranteed.",'Note that "Avg APY" covers the interest rate only, since reward history is not published \u2014 do not add',"`rewardApyPercent` to it, and if the average sits below the current rate, say that is why.","Compare the live rate against the average: a `currentApyPercent` well above `avgApyPercent` is a SPIKE,","not the rate to expect \u2014 say so plainly rather than quoting the live figure flat. `apyChangePercent` is","the move in the INTEREST rate over the LAST HOUR in percentage POINTS, rewards excluded; mention it","only when it is large enough to matter.","Format `totalSuppliedUsdc` compactly (100.12M, 23.45M). It is denominated in `suppliedAssetSymbol`:","when that is a dollar stablecoin (USDC, USDT, DAI) write it as dollars ($100.12M); otherwise append the","symbol instead (93.31K WETH). NEVER write a non-stablecoin amount with a $ sign.","`platformScore` is a 0\u201310 rating (higher is better), NEVER a percentage. A null APY, size or score means","that figure was unavailable \u2014 say so rather than showing 0.",'Then, after the bullets, write a short heading line meaning "Reasons to consider supplying',"`suppliedAssetSymbol` to this lending market\", in the user's language and naming the actual asset \u2014","plain bold text, not a markdown heading. Under it, argue the case for supplying here as a bulleted list","of AT LEAST 6 points, each point its own bullet.",`The most important true thing about THIS market, for someone about to put money in, is that ${o.lead}.`,"Open the list by establishing exactly that, in your own words \u2014 it is bullet one, and every later bullet",`defends, qualifies or completes it. Then ${o.order}.`,"Follow that running order rather than any habit of listing rate, then size, then score.","Study how these two differ \u2014 not their numbers, their SHAPE:",'<example market="deep, unremarkable USDC market">',"- Nothing here is dramatic, and for a first lending position that is the point: a steady rate on a stable","asset, no strings attached.","- At $412M supplied, your deposit is a drop in the pool \u2014 you can pull it out whenever you want without","moving the rate.","- The 4.1% comes from real borrowers paying interest, not from a token giveaway that expires.","- Aave has run this market through several crashes now. That's the strongest argument it has.","- The rate drifts with borrowing demand, so treat 4.1% as roughly where it sits, not a fixed return.","- If you want the highest number on screen, this is not it. If you want somewhere boring to leave USDC,","it is hard to beat.","</example>",'<example market="small vault, conditional reward, spiked rate">',"- Read the 12.4% carefully: only 3.2% is interest. The other 9.2% is a reward programme, and it only pays","if you also borrow against your deposit \u2014 a plain deposit earns the 3.2%.","- Today's rate is also well above its recent average, so it caught a spike rather than settled there.","- The vault holds $6.8M. That is small enough that a few large withdrawals could move things, so size","your position with that in mind.","- A curator picks which loans this vault makes, so you are trusting their judgement on top of the code.","- A score of 5.6 is middling \u2014 not alarming, not proven either.","- Someone who understands the borrow leg and wants the incentive can do well here. Anyone looking for a","place to park stablecoins should look at a plainer market.","</example>","Note what changed: one opens on the absence of drama, the other on a number that misleads. One reassures","about size, the other warns about it. Neither walks APY, then size, then score. Match that variability \u2014","do NOT reuse these sentences.","Each bullet MUST carry a judgement, not a figure. Every number is already listed above, so delete the","number from a bullet and it must still say something. Cite a figure only as evidence.","Where the data cuts against the market, that belongs in the list, not omitted.","At least one bullet MUST judge `protocol` itself, since that is who holds the money: how established and","used it is, who ultimately pays the yield, and what a depositor is really exposed to (contract risk, the","asset, a vault curator). This comes from your own knowledge, so keep it qualitative \u2014 NO invented TVL,","launch date, audit count or incident history, and no numbers beyond those given. If you do not reliably","know the protocol, say so and point to its site.","Voice: an experienced analyst talking to a friend who has never lent on-chain. Plain sentences, no","jargon, no marketing tone; explain any unavoidable DeFi term (supply, incentives, vault) in the same","breath.","Ground every judgement in the given numbers: never invent a fact or a risk figure, and never promise a","return.","Close with a short reminder that this is information, not financial advice, worded to fit what you just",'said and DIFFERENT every time \u2014 e.g. "None of this is advice \u2014 check the numbers yourself before you','commit." / "Worth doing your own reading before you deposit; this is information only." / "That is the','picture as the data has it, not a recommendation." NEVER paste a stock line such as "This information is','for informational purposes only and not financial advice."',n?"":"Depositing into this market is NOT supported in the app yet. Say that plainly at the end, and do not invite the user to supply here.","Do NOT mention tool names.",t?mu:""].filter(Boolean).join(" ")}};var Fr=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 ze(e)}async run(e,t){let n=ne(e.address,t);if(!_(n))return{error:`"${n}" is not a valid EVM wallet address (expected 0x followed by 40 hex characters).`};let o=te(e.chain,t),s=o?await this.service.isSupported(o):!1,a=s?[]:await this.service.listSupportedChains();if(o&&!s)return{_instructions:`There are no lending markets on ${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:a.map(c=>A(c))};let i=o?[o]:a,l=await this.service.getSupplyPositions({address:n,chains:i});return{_instructions:this.instructions(l),walletAddress:n,chain:o?A(o):"all",chainsQueried:i.map(c=>A(c)),positionCount:l.length,totals:Ah(l),positions:l.map(c=>({marketName:c.name,protocol:c.protocol,protocolUrl:c.protocolUrl,chain:A(c.chain),suppliedUsdc:ae(c.suppliedUsdc,zt),suppliedAssetSymbol:c.asset.symbol,avgApyPercent:ae(c.avgApyPercent,Te),...ka(c),apyChangePercent:ae(c.apyChangePercent,Te),estimatedAnnualYieldUsdc:ae(c.estimatedAnnualYieldUsdc,zt),marketTotalSuppliedUsdc:ae(c.totalSuppliedUsdc,zt),apyHistory:c.apyHistory.map(u=>({...u,apyPercent:ae(u.apyPercent,Te)})),platformScore:c.platformScore}))}}instructions(e){return e.length===0?"The wallet supplies to NONE of the curated markets (Aave v3, Compound v3, Spark, Morpho) on the chains in `chainsQueried`. Say exactly that in the user's language \u2014 do not guess at other protocols and do not imply an error. This covers the curated markets only, so if the user believes they have a deposit it may be in a protocol outside that set; in that case look up their broader DeFi positions before concluding they have none. Do NOT mention tool names.":["These are the lending markets the wallet CURRENTLY supplies USDC to, ordered by supplied amount (largest","first). Present them as a numbered list; for each market give its `marketName` in bold as a markdown link","to that market's `protocolUrl` \u2014 **[marketName](protocolUrl)** \u2014 so the name opens the market's page on the","protocol. When `protocolUrl` is null, write the name in bold as plain text; NEVER invent a URL for it. Then","`suppliedUsdc` as the supplied amount and `avgApyPercent` as the APY \u2014 label it as the average APY of the","last ~7 days (`apyHistory` holds the timestamped samples it averages, and `currentApyPercent` is the live rate;","mention the live rate only if the user asks about it or it differs sharply from the average).","When `rewardApyPercent` is not null the market pays extra rewards on top of its interest rate: say so when",'you quote that market`s APY, giving the split \u2014 e.g. "2.11% total (1.60% interest + 0.51% rewards)" \u2014 and',"naming the reward token from `rewards[].tokenSymbol` when there is one. Say nothing about rewards when it","is null. `avgApyPercent` covers the interest rate only, as reward history is not published.","A reward entry with a non-null `rewards[].conditions` is CONDITIONAL: the wallet earns that part only","while it meets those requirements. Say so briefly and summarise them, rather than reporting the total as","income the position is already receiving.","`estimatedAnnualYieldUsdc` deliberately counts only the interest and any UNCONDITIONAL reward, so on a","market with a conditional programme it is the floor, not the ceiling. If the user asks about yearly","earnings there, give that figure and add that meeting the reward conditions would raise it.","Each amount is denominated in that position`s `suppliedAssetSymbol`: format it as US dollars when that is a","dollar stablecoin (USDC, USDT, DAI) \u2014 compactly, $1.23M / $45.6K / $12.34 \u2014 and otherwise append the symbol","instead (0.85 WETH). NEVER put a $ sign on a non-stablecoin amount.","A null APY means the rate history was unavailable for that market \u2014 say the APY is unavailable rather than","showing 0. Use `estimatedAnnualYieldUsdc` when the user asks how much they earn per year,","`marketTotalSuppliedUsdc` for how large the market is, and `platformScore` \u2014 a 0\u201310 rating (higher is","better), NEVER a percentage \u2014 if the user asks how safe a market is.",new Set(e.map(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 Ah(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:ae(n,zt),estimatedAnnualYieldUsdc:ae(r.reduce((a,i)=>a+(i.estimatedAnnualYieldUsdc??0),0),zt),weightedAvgApyPercent:ae(s>0?o.reduce((a,i)=>a+i.suppliedUsdc*i.avgApyPercent,0)/s:null,Te)}}var Br=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 - <chain>)" hint, pass ONLY THE ADDRESS from it verbatim as this argument \u2014 not the chain, not the brackets \u2014 and ignore the market name in the sentence; the address identifies the exact market they picked, while a name may match several vaults of the same protocol. The chain in that hint goes in `chain`.',required:!0},{name:"chain",type:"string",description:`Hex chain ID (e.g. "0x1" Ethereum, "0xa" Optimism, "0x2105" Base) \u2014 pass whatever chain the message names, INCLUDING the one inside a "(market: 0x\u2026 - <chain>)" hint, which states the chain its market was listed for; whether it carries markets is checked at call time. Set it ONLY when a chain is named; otherwise OMIT it so the connected wallet's chain is used.`,required:!1},{name:"amount",type:"string",description:`Amount to pre-fill, in the market's own asset, as a plain decimal ("100", "25.5"). Pass ONLY when the user named an amount. Omit otherwise \u2014 the user types it in the form. Never invent or convert an amount.`,required:!1}];service;moralis;constructor(e){super(),this.service=new ze(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=te(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."};if(!await this.service.isSupported(s)){let b=await this.service.listSupportedChains();return{error:"unsupported_chain",chain:A(s),chainsWithLendingMarkets:b.map(y=>A(y)),_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 a=va(e.market);if(!a)return{error:"missing_market",_instructions:"No market was named. Ask the user WHICH lending market they want to supply to \u2014 do not pick one for them. Do NOT mention tool names."};let i=await this.service.findMarket(s,a);if(i.length===0)return{error:"market_not_found",market:a,chain:A(s),_instructions:`No lending market matching "${a}" 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(i.length>1)return{error:"ambiguous_market",market:a,chain:A(s),candidates:i.map(b=>({marketName:b.name,protocol:b.protocol})),_instructions:`"${a}" matches ${i.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="`+a+`" and chain for ${A(s)}, plus the localized detail-button templates \u2014 that shows the user each market as a card with its live APY. Tapping one opens that market's full figures, and the supply is started from there. Write no message of your own before that call.`};let l=i[0];if(!this.service.supply.canSupply(l))return{error:"unsupported_protocol",marketName:l.name,protocol:l.protocol,_instructions:`Supplying to ${l.name} is not supported in the app yet. Tell the user that plainly in their language and offer the other markets instead. Do NOT mention tool names.`};let c=await this.describeOne(s,l),u=Ph(c);if(!u)return{error:"asset_unresolved",marketName:l.name,chain:A(s),_instructions:`The asset ${l.name} lends could not be read just now, so the supply cannot be prepared safely. In the user's language, say the market's details are temporarily unavailable and suggest trying again in a moment. Do NOT guess the asset, do NOT name USDC, and do NOT mention tool names.`};let[d,p]=await Promise.all([this.assetBalance(n,s,u.address),this.service.readReceiptToken(s,l)]);if(d&&kn(d.amount,"0")<=0)return{error:"no_asset_balance",marketName:l.name,chain:A(s),assetSymbol:u.symbol,assetBalance:"0",_instructions:`The user has no ${u.symbol} available to supply to ${l.name} on ${A(s)}. In the user's language, tell them plainly that they have no ${u.symbol} available on this chain and need to add some before they can supply. Do NOT show any amount form, do NOT invent a balance, and do NOT state a specific balance figure. Keep it to one or two short sentences. Do NOT mention tool names.`};let m=Sh(e.amount),f=m?$t(m,u.decimals):null;if(f&&d&&kn(f,d.amount)>0)return{error:"insufficient_asset_balance",marketName:l.name,chain:A(s),assetSymbol:u.symbol,requestedAmount:m,assetBalance:d.amount,_instructions:`The user wants to supply ${m} ${u.symbol} to ${l.name}, but they only hold ${d.amount} ${u.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 ${m} ${u.symbol} exceeds their balance of ${d.amount} ${u.symbol} on this chain, then ask them to enter a smaller amount or add more. Do NOT open any amount form and do NOT invent figures. Keep it to one or two short sentences. Do NOT mention tool names.`};let h={action:"supply_usdc",chainId:s,chainName:A(s),walletAddress:n,market:{name:l.name,type:l.type,protocol:l.protocol,protocolUrl:c?.protocolUrl??ga(l),contract:l.contract,token:l.token,apyPercent:c?.currentApyPercent??c?.avgApyPercent??null,receiptToken:p},asset:u,...f?{prefillAmount:f}:{},...d?{spendable:d.amount}:{},...d?.usd?{spendableUsd:d.usd}:{}};return{ui:{component:"SupplyUsdcForm",props:h},marketName:l.name,protocol:l.protocol,chain:A(s),apyPercent:ae(h.market.apyPercent,Te),assetSymbol:u.symbol,assetBalance:d?.amount??null,_instructions:this.instructions(l,u.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 Ph(r){let e=r?.asset;return!e?.address||e.address===Pn||!Number.isFinite(e.decimals)?null:{address:e.address,symbol:e.symbol||"the market asset",decimals:e.decimals}}function Sh(r){let e=typeof r=="string"?r.trim():typeof r=="number"?String(r):"";return/^\d*\.?\d+$/.test(e)&&Number(e)>0?e:null}var Ta="https://ipfs.pantograph.app/ipfs/",Tu=/^(Qm[1-9A-HJ-NP-Za-km-z]{44}|baf[a-z0-9]{20,})(\/.*)?$/;function Sn(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?`${Ta}${t[1]}`:Tu.test(e)?`${Ta}${e}`:null}function Au(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?`${Ta}${t[1]}`:Tu.test(e)?`${Ta}${e}`:null}function Pu(r){return/\.(png|jpe?g|gif|webp|svg|avif|bmp)(\?.*)?(#.*)?$/i.test(r)}function dl(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 xh(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 Ch(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)?xh(n):decodeURIComponent(n);return JSON.parse(o)}catch{try{return JSON.parse(n)}catch{return null}}}function Su(r){let e=r?.trim();if(!e||!/^data:/i.test(e))return null;if(/^data:image\//i.test(e))return e;let t=Ch(e);return t?Sn(dl(t)):null}var Rh=12,Eh=6e3;async function _h(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 Nh(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 Su(t);let n=Au(t);if(!n)return null;if(Pu(n))return n;let o=await Nh(n,e);if(o){let s=Sn(dl(o));if(s)return s}return null}async function Aa(r,e,t){if(e.length===0)return[];let n=t?.concurrency??Rh,o=t?.timeoutMs??Eh,s=await Sc(r,e,t?.rpcUrl);return _h(s,n,a=>Ih(a,o))}var xu=100,Uh=100,qr="{name}",Cu="{chain}",$r=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=ne(e.address,t),o=te(e.chain,t),s=o?[o]:Ce(),a=Bh(e.contract_address),i=_u(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:xu});return{chain:c,rows:u.success?Ru(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:Dh(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=Mh(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 f=await this.service.getWalletNFTs({address:t,chain:m,limit:xu,...s?{tokenAddresses:[s]}:{}});return{chain:m,rows:f.success?Ru(f.data?.result??[]):[],ok:f.success}}));if(o&&!i[0].ok)return{error:"Failed to fetch wallet NFTs"};let l=i.flatMap(m=>m.rows.filter(f=>Lh(f,{contract:s,collectionName:a})).map(f=>({chain:m.chain,row:f})));if(l.length===0)return{error:"collection_not_held",_instructions:`The wallet holds no ERC-721 NFTs matching "${a??s??""}"`+(o?" on this chain":"")+". Tell the user that in their language and invite them to ask for their NFTs again to see the collections they do hold. Do NOT mention tool names."};let c=l[0].row.name?.trim()||a||l[0].row.token_address,u=await this.resolveOnchainImages(l),d=l.map(({chain:m,row:f},h)=>{let g=Oh(f);return{name:g.name,tokenId:g.tokenId,contractAddress:g.contractAddress,image:u[h]??g.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 Aa(o,a);s.forEach((l,c)=>{t[l]=i[c]??null})}))}catch{}return t}};function Ru(r){return r.filter(e=>(e.contract_type||"").toUpperCase()==="ERC721")}function Lh(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 Dh(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 Oh(r){return{name:r.normalized_metadata?.name||r.name||`#${r.token_id}`,tokenId:r.token_id,contractAddress:r.token_address,image:Sn(r.normalized_metadata?.image||r.media?.original_media_url)}}function Mh(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>=Uh)break;if(!s.contractAddress)continue;let a=typeof s.chain=="string"?s.chain.trim():"",i=a?`show my ${qr} NFTs on ${Cu}`:`show my ${qr} NFTs`,l=Eu(n,{[qr]:s.name,[Cu]:a},i);a&&!l.includes(a)&&(l=`${l} (${a})`),o.push({label:Fh(t,s.name,qr),prompt:`${l} (${s.contractAddress})`})}return o}function Eu(r,e,t){let n=r&&r.includes(qr)?r:t;for(let[o,s]of Object.entries(e))n=n.split(o).join(s);return n.replace(/\s+/g," ").trim()}function Fh(r,e,t){return Eu(r,{[qr]:e},t)}function _u(r){if(typeof r!="string")return;let e=r.trim();return e||void 0}function Bh(r){let e=_u(r);return e&&/^0x[a-fA-F0-9]{40}$/.test(e)?e:void 0}var qh="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.",dt=class extends S{kind="data";category="nft";llm;constructor(e){super(),this.llm=new ie(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:qh,timestamp:t},{role:"user",content:e,timestamp:t}],void 0,{googleSearch:!0,maxRetries:1})).text?.trim()||null}catch{return null}}};var Hr=class extends dt{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=dt.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 Vr=class extends dt{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=dt.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 pl={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"},ml="amazon.com";function $h(r){return r?r.trim().toLowerCase().split(/[-_]/)[0]:""}function hl(r){let e=$h(r);return pl[e]??ml}function Pa(r){return`https://${hl(r)}/s?k=NFC%20Tag`}function Sa(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 Hh=720*60*1e3,Nu=new Map,Iu=3;function Vh(r){return[`A user in country "${r}" (ISO 3166-1 alpha-2) wants to buy NFC tags online.`,`Using Google Search, list the ${Iu} 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>=Iu))break}return o}async function gl(r,e){let t=Sa(r);if(!t||!e)return null;let n=Nu.get(t);if(n&&n.expires>Date.now())return n.links;let o=Date.now(),s=[{role:"user",content:Vh(t),timestamp:o}];try{let a=await e.chat(s,void 0,{googleSearch:!0,maxRetries:1}),i=Wh(a.text);if(i.length)return Nu.set(t,{links:i,expires:Date.now()+Hh}),i}catch{}return null}async function Wr(r){let e=await gl(r.country,r.llm);return e&&e.length?e:[{label:"Amazon",url:Pa(r.language)}]}function Yh(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(`
|
|
35
35
|
`)}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(`
|
|
36
36
|
`),Yr=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 ie(e))}async run(e,t){let n=typeof e.language=="string"&&e.language.trim()?e.language.trim():void 0,o=await Wr({country:t?.country,language:n,llm:this.llm}),s=Yh(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)):
|
|
37
37
|
${s}
|