@t402/mcp 2.7.0 → 2.8.0
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/cjs/index.js +1401 -185
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/server/index.d.ts +36 -0
- package/dist/cjs/server/index.js +1401 -185
- package/dist/cjs/server/index.js.map +1 -1
- package/dist/cjs/tools/index.d.ts +689 -12
- package/dist/cjs/tools/index.js +1155 -29
- package/dist/cjs/tools/index.js.map +1 -1
- package/dist/esm/{chunk-B7X7H6NV.mjs → chunk-SUDCVXHQ.mjs} +1120 -30
- package/dist/esm/chunk-SUDCVXHQ.mjs.map +1 -0
- package/dist/esm/{chunk-3PMBXSJ3.mjs → chunk-XOPD7VTU.mjs} +195 -2
- package/dist/esm/chunk-XOPD7VTU.mjs.map +1 -0
- package/dist/esm/index.mjs +2 -2
- package/dist/esm/server/index.d.mts +36 -0
- package/dist/esm/server/index.mjs +2 -2
- package/dist/esm/tools/index.d.mts +689 -12
- package/dist/esm/tools/index.mjs +70 -1
- package/package.json +14 -14
- package/dist/esm/chunk-3PMBXSJ3.mjs.map +0 -1
- package/dist/esm/chunk-B7X7H6NV.mjs.map +0 -1
package/dist/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.ts","../../src/server/t402Server.ts","../../src/tools/getBalance.ts","../../src/constants.ts","../../src/tools/getAllBalances.ts","../../src/tools/pay.ts","../../src/tools/payGasless.ts","../../src/tools/getBridgeFee.ts","../../src/tools/bridge.ts","../../src/tools/wdkGetWallet.ts","../../src/tools/wdkGetBalances.ts","../../src/tools/wdkTransfer.ts","../../src/tools/wdkSwap.ts","../../src/tools/autoPay.ts","../../src/tools/ton-bridge.ts","../../src/tools/erc8004ResolveAgent.ts","../../src/tools/erc8004Shared.ts","../../src/tools/erc8004CheckReputation.ts","../../src/tools/erc8004VerifyWallet.ts","../../src/tools/unified.ts","../../src/tools/index.ts"],"sourcesContent":["/**\n * @t402/mcp - MCP Server for AI Agent Payments\n *\n * This package provides a Model Context Protocol (MCP) server that enables\n * AI agents to make stablecoin payments across multiple blockchain networks.\n *\n * @example\n * ```typescript\n * import { createT402McpServer, loadConfigFromEnv } from '@t402/mcp';\n *\n * const config = loadConfigFromEnv();\n * const server = createT402McpServer(config);\n * await server.run();\n * ```\n *\n * @example Claude Desktop Configuration\n * ```json\n * {\n * \"mcpServers\": {\n * \"t402\": {\n * \"command\": \"npx\",\n * \"args\": [\"@t402/mcp\"],\n * \"env\": {\n * \"T402_PRIVATE_KEY\": \"0x...\",\n * \"T402_DEMO_MODE\": \"true\"\n * }\n * }\n * }\n * }\n * ```\n */\n\n// Server\nexport { T402McpServer, createT402McpServer, loadConfigFromEnv } from './server/index.js'\n\n// Tools\nexport {\n // Tool definitions\n TOOL_DEFINITIONS,\n UNIFIED_TOOL_DEFINITIONS,\n // Balance tools\n getBalanceInputSchema,\n executeGetBalance,\n formatBalanceResult,\n getAllBalancesInputSchema,\n executeGetAllBalances,\n formatAllBalancesResult,\n // Payment tools\n payInputSchema,\n executePay,\n formatPaymentResult,\n payGaslessInputSchema,\n executePayGasless,\n formatGaslessPaymentResult,\n GASLESS_SUPPORTED_NETWORKS,\n // Bridge tools\n getBridgeFeeInputSchema,\n executeGetBridgeFee,\n formatBridgeFeeResult,\n bridgeInputSchema,\n executeBridge,\n formatBridgeResult,\n // Unified tools\n smartPayInputSchema,\n executeSmartPay,\n executeSmartPayDemo,\n formatSmartPayResult,\n paymentPlanInputSchema,\n executePaymentPlan,\n executePaymentPlanDemo,\n formatPaymentPlanResult,\n // Types\n type GetBalanceInput,\n type GetAllBalancesInput,\n type AllBalancesResult,\n type PayInput,\n type PayOptions,\n type PayGaslessInput,\n type PayGaslessOptions,\n type GetBridgeFeeInput,\n type BridgeInput,\n type BridgeOptions,\n type SmartPayInput,\n type SmartPayResult,\n type SmartPayStep,\n type PaymentPlanInput,\n type PaymentPlanResult,\n type UnifiedMcpConfig,\n} from './tools/index.js'\n\n// Types\nexport type {\n SupportedNetwork,\n TokenBalance,\n ChainBalance,\n PaymentParams,\n PaymentResult,\n GaslessPaymentResult,\n BridgeFeeQuote,\n BridgeResult,\n McpServerConfig,\n ToolContext,\n} from './types.js'\n\n// Constants\nexport {\n CHAIN_IDS,\n NATIVE_SYMBOLS,\n EXPLORER_URLS,\n DEFAULT_RPC_URLS,\n USDC_ADDRESSES,\n USDT_ADDRESSES,\n USDT0_ADDRESSES,\n BRIDGEABLE_CHAINS,\n getExplorerTxUrl,\n getLayerZeroScanUrl,\n supportsToken,\n getTokenAddress,\n formatTokenAmount,\n parseTokenAmount,\n} from './constants.js'\n","/**\n * t402 MCP Server - Main server implementation\n */\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'\nimport type { McpServerConfig, SupportedNetwork } from '../types.js'\nimport {\n TOOL_DEFINITIONS,\n WDK_TOOL_DEFINITIONS,\n UNIFIED_TOOL_DEFINITIONS,\n executeGetBalance,\n formatBalanceResult,\n getBalanceInputSchema,\n executeGetAllBalances,\n formatAllBalancesResult,\n getAllBalancesInputSchema,\n executePay,\n formatPaymentResult,\n payInputSchema,\n executePayGasless,\n formatGaslessPaymentResult,\n payGaslessInputSchema,\n executeGetBridgeFee,\n formatBridgeFeeResult,\n getBridgeFeeInputSchema,\n executeBridge,\n formatBridgeResult,\n bridgeInputSchema,\n // WDK tools\n wdkGetWalletInputSchema,\n executeWdkGetWallet,\n executeWdkGetWalletDemo,\n formatWdkWalletResult,\n wdkGetBalancesInputSchema,\n executeWdkGetBalances,\n executeWdkGetBalancesDemo,\n formatWdkBalancesResult,\n wdkTransferInputSchema,\n executeWdkTransfer,\n executeWdkTransferDemo,\n formatWdkTransferResult,\n wdkSwapInputSchema,\n executeWdkSwap,\n executeWdkSwapDemo,\n formatWdkSwapResult,\n autoPayInputSchema,\n executeAutoPay,\n executeAutoPayDemo,\n formatAutoPayResult,\n // Unified tools\n smartPayInputSchema,\n executeSmartPay,\n executeSmartPayDemo,\n formatSmartPayResult,\n paymentPlanInputSchema,\n executePaymentPlan,\n executePaymentPlanDemo,\n formatPaymentPlanResult,\n // TON bridge tools\n TON_BRIDGE_TOOLS,\n executeTonBridgeTool,\n type TonMcpBridgeConfig,\n // ERC-8004 tools\n ERC8004_TOOL_DEFINITIONS,\n erc8004ResolveAgentInputSchema,\n executeErc8004ResolveAgent,\n formatErc8004ResolveAgentResult,\n erc8004CheckReputationInputSchema,\n executeErc8004CheckReputation,\n formatErc8004CheckReputationResult,\n erc8004VerifyWalletInputSchema,\n executeErc8004VerifyWallet,\n formatErc8004VerifyWalletResult,\n} from '../tools/index.js'\nimport type { T402WDK } from '@t402/wdk'\n\n/**\n * t402 MCP Server\n *\n * Provides payment tools for AI agents via the Model Context Protocol.\n * When a WDK seed phrase is configured, additional wallet management tools are available.\n */\nexport class T402McpServer {\n private server: Server\n private config: McpServerConfig\n private wdk: T402WDK | null = null\n\n constructor(config: McpServerConfig = {}) {\n this.config = config\n this.server = new Server(\n {\n name: 't402',\n version: '1.0.0',\n },\n {\n capabilities: {\n tools: {},\n },\n },\n )\n\n this.setupHandlers()\n }\n\n /**\n * Initialize the WDK instance from seed phrase\n */\n async initWdk(): Promise<void> {\n if (!this.config.seedPhrase) return\n\n try {\n const { T402WDK } = await import('@t402/wdk')\n const rpcUrls: Record<string, string> = {}\n\n if (this.config.rpcUrls) {\n for (const [network, url] of Object.entries(this.config.rpcUrls)) {\n if (url) rpcUrls[network] = url\n }\n }\n\n this.wdk = new T402WDK(this.config.seedPhrase, rpcUrls)\n } catch {\n console.error('Warning: Failed to initialize WDK. WDK tools will not be available.')\n }\n }\n\n /** TON MCP bridge configuration */\n private tonBridgeConfig: TonMcpBridgeConfig | null = null\n\n /**\n * Register TON bridge tools\n *\n * Enables AI agents to use @ton/mcp tools through the t402 MCP server.\n */\n registerTonBridge(config: TonMcpBridgeConfig): void {\n this.tonBridgeConfig = config\n }\n\n /**\n * Get all tool definitions (base + WDK if configured + unified if enabled + TON bridge if registered)\n */\n private getToolDefinitions() {\n const tools = { ...TOOL_DEFINITIONS, ...ERC8004_TOOL_DEFINITIONS }\n if (this.wdk || this.config.demoMode) {\n Object.assign(tools, WDK_TOOL_DEFINITIONS)\n }\n if (this.config.unifiedMode && (this.wdk || this.config.demoMode)) {\n Object.assign(tools, UNIFIED_TOOL_DEFINITIONS)\n }\n if (this.tonBridgeConfig) {\n Object.assign(tools, TON_BRIDGE_TOOLS)\n }\n return tools\n }\n\n /**\n * Set up MCP request handlers\n */\n private setupHandlers(): void {\n // List available tools\n this.server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: Object.values(this.getToolDefinitions()),\n }\n })\n\n // Handle tool calls\n this.server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params\n\n try {\n switch (name) {\n case 't402/getBalance':\n return await this.handleGetBalance(args)\n\n case 't402/getAllBalances':\n return await this.handleGetAllBalances(args)\n\n case 't402/pay':\n return await this.handlePay(args)\n\n case 't402/payGasless':\n return await this.handlePayGasless(args)\n\n case 't402/getBridgeFee':\n return await this.handleGetBridgeFee(args)\n\n case 't402/bridge':\n return await this.handleBridge(args)\n\n // WDK tools\n case 'wdk/getWallet':\n return await this.handleWdkGetWallet(args)\n\n case 'wdk/getBalances':\n return await this.handleWdkGetBalances(args)\n\n case 'wdk/transfer':\n return await this.handleWdkTransfer(args)\n\n case 'wdk/swap':\n return await this.handleWdkSwap(args)\n\n case 't402/autoPay':\n return await this.handleAutoPay(args)\n\n // Unified tools\n case 't402/smartPay':\n return await this.handleSmartPay(args)\n\n case 't402/paymentPlan':\n return await this.handlePaymentPlan(args)\n\n // ERC-8004 tools\n case 'erc8004/resolveAgent':\n return await this.handleErc8004ResolveAgent(args)\n\n case 'erc8004/checkReputation':\n return await this.handleErc8004CheckReputation(args)\n\n case 'erc8004/verifyWallet':\n return await this.handleErc8004VerifyWallet(args)\n\n // TON bridge tools\n case 'ton/getBalance':\n case 'ton/transfer':\n case 'ton/getJettonBalance':\n case 'ton/swapJettons':\n case 'ton/getTransactionStatus':\n return await this.handleTonBridgeTool(name, args)\n\n default:\n throw new Error(`Unknown tool: ${name}`)\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return {\n content: [\n {\n type: 'text' as const,\n text: `Error: ${message}`,\n },\n ],\n isError: true,\n }\n }\n })\n }\n\n /**\n * Handle t402/getBalance\n */\n private async handleGetBalance(args: unknown) {\n const input = getBalanceInputSchema.parse(args)\n const result = await executeGetBalance(input, this.config.rpcUrls)\n return {\n content: [\n {\n type: 'text' as const,\n text: formatBalanceResult(result),\n },\n ],\n }\n }\n\n /**\n * Handle t402/getAllBalances\n */\n private async handleGetAllBalances(args: unknown) {\n const input = getAllBalancesInputSchema.parse(args)\n const result = await executeGetAllBalances(input, this.config.rpcUrls)\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAllBalancesResult(result),\n },\n ],\n }\n }\n\n /**\n * Handle t402/pay\n */\n private async handlePay(args: unknown) {\n if (!this.config.privateKey && !this.config.demoMode) {\n throw new Error(\n 'Private key not configured. Set T402_PRIVATE_KEY environment variable or enable demo mode.',\n )\n }\n\n const input = payInputSchema.parse(args)\n const result = await executePay(input, {\n privateKey: this.config.privateKey || '0x',\n rpcUrl: this.config.rpcUrls?.[input.network as SupportedNetwork],\n demoMode: this.config.demoMode,\n })\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatPaymentResult(result),\n },\n ],\n }\n }\n\n /**\n * Handle t402/payGasless\n */\n private async handlePayGasless(args: unknown) {\n if (!this.config.privateKey && !this.config.demoMode) {\n throw new Error(\n 'Private key not configured. Set T402_PRIVATE_KEY environment variable or enable demo mode.',\n )\n }\n\n if (!this.config.bundlerUrl && !this.config.demoMode) {\n throw new Error(\n 'Bundler URL not configured. Set T402_BUNDLER_URL environment variable or enable demo mode.',\n )\n }\n\n if (!this.config.paymasterUrl && !this.config.demoMode) {\n throw new Error(\n 'Paymaster URL not configured. Set T402_PAYMASTER_URL environment variable or enable demo mode.',\n )\n }\n\n const input = payGaslessInputSchema.parse(args)\n const result = await executePayGasless(input, {\n privateKey: this.config.privateKey || '0x',\n bundlerUrl: this.config.bundlerUrl || '',\n paymasterUrl: this.config.paymasterUrl || '',\n rpcUrl: this.config.rpcUrls?.[input.network as SupportedNetwork],\n demoMode: this.config.demoMode,\n })\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatGaslessPaymentResult(result),\n },\n ],\n }\n }\n\n /**\n * Handle t402/getBridgeFee\n */\n private async handleGetBridgeFee(args: unknown) {\n const input = getBridgeFeeInputSchema.parse(args)\n const result = await executeGetBridgeFee(input, this.config.rpcUrls)\n return {\n content: [\n {\n type: 'text' as const,\n text: formatBridgeFeeResult(result),\n },\n ],\n }\n }\n\n /**\n * Handle t402/bridge\n */\n private async handleBridge(args: unknown) {\n if (!this.config.privateKey && !this.config.demoMode) {\n throw new Error(\n 'Private key not configured. Set T402_PRIVATE_KEY environment variable or enable demo mode.',\n )\n }\n\n const input = bridgeInputSchema.parse(args)\n const result = await executeBridge(input, {\n privateKey: this.config.privateKey || '0x',\n rpcUrl: this.config.rpcUrls?.[input.fromChain as SupportedNetwork],\n demoMode: this.config.demoMode,\n })\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatBridgeResult(result),\n },\n ],\n }\n }\n\n // ---- WDK Tool Handlers ----\n\n /**\n * Handle wdk/getWallet\n */\n private async handleWdkGetWallet(args: unknown) {\n wdkGetWalletInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeWdkGetWalletDemo()\n : await executeWdkGetWallet({}, this.wdk)\n\n return {\n content: [{ type: 'text' as const, text: formatWdkWalletResult(result) }],\n }\n }\n\n /**\n * Handle wdk/getBalances\n */\n private async handleWdkGetBalances(args: unknown) {\n const input = wdkGetBalancesInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeWdkGetBalancesDemo()\n : await executeWdkGetBalances(input, this.wdk)\n\n return {\n content: [{ type: 'text' as const, text: formatWdkBalancesResult(result) }],\n }\n }\n\n /**\n * Handle wdk/transfer\n */\n private async handleWdkTransfer(args: unknown) {\n const input = wdkTransferInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeWdkTransferDemo(input)\n : await executeWdkTransfer(input, this.wdk)\n\n return {\n content: [{ type: 'text' as const, text: formatWdkTransferResult(result) }],\n }\n }\n\n /**\n * Handle wdk/swap\n */\n private async handleWdkSwap(args: unknown) {\n const input = wdkSwapInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeWdkSwapDemo(input)\n : await executeWdkSwap(input, this.wdk)\n\n return {\n content: [{ type: 'text' as const, text: formatWdkSwapResult(result) }],\n }\n }\n\n /**\n * Handle t402/autoPay\n */\n private async handleAutoPay(args: unknown) {\n const input = autoPayInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeAutoPayDemo(input)\n : await executeAutoPay(input, this.wdk)\n\n return {\n content: [{ type: 'text' as const, text: formatAutoPayResult(result) }],\n }\n }\n\n // ---- Unified Tool Handlers ----\n\n /**\n * Handle t402/smartPay\n */\n private async handleSmartPay(args: unknown) {\n const input = smartPayInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeSmartPayDemo(input)\n : await executeSmartPay(input, this.wdk)\n\n return {\n content: [{ type: 'text' as const, text: formatSmartPayResult(result) }],\n }\n }\n\n /**\n * Handle t402/paymentPlan\n */\n private async handlePaymentPlan(args: unknown) {\n const input = paymentPlanInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executePaymentPlanDemo(input)\n : await executePaymentPlan(input, this.wdk)\n\n return {\n content: [{ type: 'text' as const, text: formatPaymentPlanResult(result) }],\n }\n }\n\n // ---- ERC-8004 Tool Handlers ----\n\n /**\n * Handle erc8004/resolveAgent\n */\n private async handleErc8004ResolveAgent(args: unknown) {\n const input = erc8004ResolveAgentInputSchema.parse(args)\n const result = await executeErc8004ResolveAgent(input, this.config.rpcUrls)\n return {\n content: [{ type: 'text' as const, text: formatErc8004ResolveAgentResult(result) }],\n }\n }\n\n /**\n * Handle erc8004/checkReputation\n */\n private async handleErc8004CheckReputation(args: unknown) {\n const input = erc8004CheckReputationInputSchema.parse(args)\n const result = await executeErc8004CheckReputation(input, this.config.rpcUrls)\n return {\n content: [{ type: 'text' as const, text: formatErc8004CheckReputationResult(result) }],\n }\n }\n\n /**\n * Handle erc8004/verifyWallet\n */\n private async handleErc8004VerifyWallet(args: unknown) {\n const input = erc8004VerifyWalletInputSchema.parse(args)\n const result = await executeErc8004VerifyWallet(input, this.config.rpcUrls)\n return {\n content: [{ type: 'text' as const, text: formatErc8004VerifyWalletResult(result) }],\n }\n }\n\n // ---- TON Bridge Tool Handler ----\n\n /**\n * Handle TON bridge tool calls\n */\n private async handleTonBridgeTool(name: string, args: unknown) {\n if (!this.tonBridgeConfig) {\n throw new Error('TON bridge not configured. Call registerTonBridge() to enable TON tools.')\n }\n\n return executeTonBridgeTool(name, (args ?? {}) as Record<string, unknown>, this.tonBridgeConfig)\n }\n\n /**\n * Start the server using stdio transport\n */\n async run(): Promise<void> {\n // Initialize WDK if seed phrase is configured\n await this.initWdk()\n\n const transport = new StdioServerTransport()\n await this.server.connect(transport)\n console.error('t402 MCP Server running on stdio')\n }\n}\n\n/**\n * Create a new t402 MCP server instance\n */\nexport function createT402McpServer(config?: McpServerConfig): T402McpServer {\n return new T402McpServer(config)\n}\n\n/**\n * Load configuration from environment variables\n */\nexport function loadConfigFromEnv(): McpServerConfig {\n const config: McpServerConfig = {}\n\n // Private key\n if (process.env.T402_PRIVATE_KEY) {\n config.privateKey = process.env.T402_PRIVATE_KEY\n }\n\n // Demo mode\n if (process.env.T402_DEMO_MODE === 'true') {\n config.demoMode = true\n }\n\n // ERC-4337 configuration\n if (process.env.T402_BUNDLER_URL) {\n config.bundlerUrl = process.env.T402_BUNDLER_URL\n }\n if (process.env.T402_PAYMASTER_URL) {\n config.paymasterUrl = process.env.T402_PAYMASTER_URL\n }\n\n // WDK configuration\n if (process.env.T402_WDK_SEED_PHRASE) {\n config.seedPhrase = process.env.T402_WDK_SEED_PHRASE\n }\n if (process.env.T402_WDK_CHAINS) {\n config.wdkChains = process.env.T402_WDK_CHAINS.split(',').map((c) => c.trim())\n }\n\n // Unified mode\n if (process.env.T402_UNIFIED_MODE === 'true') {\n config.unifiedMode = true\n }\n\n // Custom RPC URLs\n const rpcUrls: Partial<Record<SupportedNetwork, string>> = {}\n const networks: SupportedNetwork[] = [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ]\n\n for (const network of networks) {\n const envVar = `T402_RPC_${network.toUpperCase()}`\n if (process.env[envVar]) {\n rpcUrls[network] = process.env[envVar]\n }\n }\n\n if (Object.keys(rpcUrls).length > 0) {\n config.rpcUrls = rpcUrls\n }\n\n // TON MCP bridge configuration\n if (process.env.T402_TON_MCP_ENDPOINT) {\n config.tonMcpEndpoint = process.env.T402_TON_MCP_ENDPOINT\n }\n if (process.env.T402_TON_API_KEY) {\n config.tonApiKey = process.env.T402_TON_API_KEY\n }\n\n return config\n}\n","/**\n * t402/getBalance - Get token balance for a specific network\n */\n\nimport { z } from 'zod'\nimport { createPublicClient, http, formatEther, formatUnits, type Address } from 'viem'\nimport * as chains from 'viem/chains'\nimport type { SupportedNetwork, TokenBalance, ChainBalance } from '../types.js'\nimport {\n CHAIN_IDS,\n NATIVE_SYMBOLS,\n DEFAULT_RPC_URLS,\n USDC_ADDRESSES,\n USDT_ADDRESSES,\n USDT0_ADDRESSES,\n ERC20_ABI,\n} from '../constants.js'\n\n/**\n * Input schema for getBalance tool\n */\nexport const getBalanceInputSchema = z.object({\n network: z\n .enum([\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ])\n .describe('Blockchain network to check balance on'),\n address: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Wallet address to check balance for'),\n})\n\nexport type GetBalanceInput = z.infer<typeof getBalanceInputSchema>\n\n/**\n * Get the viem chain configuration for a network\n */\nfunction getViemChain(network: SupportedNetwork) {\n switch (network) {\n case 'ethereum':\n return chains.mainnet\n case 'base':\n return chains.base\n case 'arbitrum':\n return chains.arbitrum\n case 'optimism':\n return chains.optimism\n case 'polygon':\n return chains.polygon\n case 'avalanche':\n return chains.avalanche\n case 'ink':\n return chains.ink\n case 'berachain':\n return chains.berachain\n case 'unichain':\n return chains.unichain\n default:\n return chains.mainnet\n }\n}\n\n/**\n * Get token balance for an address\n */\nasync function getTokenBalance(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client: any,\n tokenAddress: Address,\n walletAddress: Address,\n): Promise<TokenBalance | null> {\n try {\n const [balance, decimals, symbol] = await Promise.all([\n client.readContract({\n address: tokenAddress,\n abi: ERC20_ABI,\n functionName: 'balanceOf',\n args: [walletAddress],\n }) as Promise<bigint>,\n client.readContract({\n address: tokenAddress,\n abi: ERC20_ABI,\n functionName: 'decimals',\n }) as Promise<number>,\n client.readContract({\n address: tokenAddress,\n abi: ERC20_ABI,\n functionName: 'symbol',\n }) as Promise<string>,\n ])\n\n return {\n symbol,\n address: tokenAddress,\n balance: balance.toString(),\n formatted: formatUnits(balance, decimals),\n decimals,\n }\n } catch {\n return null\n }\n}\n\n/**\n * Execute getBalance tool\n */\nexport async function executeGetBalance(\n input: GetBalanceInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<ChainBalance> {\n const { network, address } = input\n const walletAddress = address as Address\n\n const rpcUrl = rpcUrls?.[network] || DEFAULT_RPC_URLS[network]\n const chain = getViemChain(network)\n\n const client = createPublicClient({\n chain,\n transport: http(rpcUrl),\n })\n\n // Get native balance\n const nativeBalance = await client.getBalance({ address: walletAddress })\n\n // Get token balances\n const tokenAddresses: { token: Address; expected: string }[] = []\n\n if (USDC_ADDRESSES[network]) {\n tokenAddresses.push({ token: USDC_ADDRESSES[network]!, expected: 'USDC' })\n }\n if (USDT_ADDRESSES[network]) {\n tokenAddresses.push({ token: USDT_ADDRESSES[network]!, expected: 'USDT' })\n }\n if (USDT0_ADDRESSES[network]) {\n tokenAddresses.push({ token: USDT0_ADDRESSES[network]!, expected: 'USDT0' })\n }\n\n const tokenBalances = await Promise.all(\n tokenAddresses.map(({ token }) => getTokenBalance(client, token, walletAddress)),\n )\n\n const tokens = tokenBalances.filter((t): t is TokenBalance => t !== null)\n\n return {\n network,\n chainId: CHAIN_IDS[network],\n native: {\n symbol: NATIVE_SYMBOLS[network],\n balance: nativeBalance.toString(),\n formatted: formatEther(nativeBalance),\n },\n tokens,\n }\n}\n\n/**\n * Format balance result for display\n */\nexport function formatBalanceResult(balance: ChainBalance): string {\n const lines: string[] = [\n `## Balance on ${balance.network} (Chain ID: ${balance.chainId})`,\n '',\n `### Native Token`,\n `- ${balance.native.symbol}: ${balance.native.formatted}`,\n '',\n ]\n\n if (balance.tokens.length > 0) {\n lines.push('### Stablecoins')\n for (const token of balance.tokens) {\n lines.push(`- ${token.symbol}: ${token.formatted}`)\n }\n } else {\n lines.push('_No stablecoin balances found_')\n }\n\n return lines.join('\\n')\n}\n","/**\n * Constants and network configurations for t402 MCP Server\n */\n\nimport type { Address } from 'viem'\nimport type { SupportedNetwork } from './types.js'\n\n/**\n * Chain IDs by network\n */\nexport const CHAIN_IDS: Record<SupportedNetwork, number> = {\n ethereum: 1,\n base: 8453,\n arbitrum: 42161,\n optimism: 10,\n polygon: 137,\n avalanche: 43114,\n ink: 57073,\n berachain: 80094,\n unichain: 130,\n}\n\n/**\n * Native token symbols by network\n */\nexport const NATIVE_SYMBOLS: Record<SupportedNetwork, string> = {\n ethereum: 'ETH',\n base: 'ETH',\n arbitrum: 'ETH',\n optimism: 'ETH',\n polygon: 'MATIC',\n avalanche: 'AVAX',\n ink: 'ETH',\n berachain: 'BERA',\n unichain: 'ETH',\n}\n\n/**\n * Block explorer URLs by network\n */\nexport const EXPLORER_URLS: Record<SupportedNetwork, string> = {\n ethereum: 'https://etherscan.io',\n base: 'https://basescan.org',\n arbitrum: 'https://arbiscan.io',\n optimism: 'https://optimistic.etherscan.io',\n polygon: 'https://polygonscan.com',\n avalanche: 'https://snowtrace.io',\n ink: 'https://explorer.inkonchain.com',\n berachain: 'https://berascan.com',\n unichain: 'https://unichain.blockscout.com',\n}\n\n/**\n * Default RPC URLs by network (public endpoints)\n */\nexport const DEFAULT_RPC_URLS: Record<SupportedNetwork, string> = {\n ethereum: 'https://eth.llamarpc.com',\n base: 'https://mainnet.base.org',\n arbitrum: 'https://arb1.arbitrum.io/rpc',\n optimism: 'https://mainnet.optimism.io',\n polygon: 'https://polygon-rpc.com',\n avalanche: 'https://api.avax.network/ext/bc/C/rpc',\n ink: 'https://rpc-gel.inkonchain.com',\n berachain: 'https://rpc.berachain.com',\n unichain: 'https://mainnet.unichain.org',\n}\n\n/**\n * USDC contract addresses by network\n */\nexport const USDC_ADDRESSES: Partial<Record<SupportedNetwork, Address>> = {\n ethereum: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n base: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n arbitrum: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n optimism: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n polygon: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',\n avalanche: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',\n}\n\n/**\n * USDT contract addresses by network\n */\nexport const USDT_ADDRESSES: Partial<Record<SupportedNetwork, Address>> = {\n ethereum: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n arbitrum: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',\n polygon: '0xc2132D05D31c914a87C6611C10748AEb04B58e8F',\n avalanche: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7',\n optimism: '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58',\n}\n\n/**\n * USDT0 (LayerZero OFT) contract addresses by network\n */\nexport const USDT0_ADDRESSES: Partial<Record<SupportedNetwork, Address>> = {\n ethereum: '0x6C96dE32CEa08842dcc4058c14d3aaAD7Fa41dee',\n arbitrum: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',\n ink: '0x0200C29006150606B650577BBE7B6248F58470c1',\n berachain: '0x779Ded0c9e1022225f8E0630b35a9b54bE713736',\n unichain: '0x9151434b16b9763660705744891fA906F660EcC5',\n}\n\n/**\n * Chains that support USDT0 bridging\n */\nexport const BRIDGEABLE_CHAINS: SupportedNetwork[] = [\n 'ethereum',\n 'arbitrum',\n 'ink',\n 'berachain',\n 'unichain',\n]\n\n/**\n * ERC20 ABI for balance and transfer operations\n */\nexport const ERC20_ABI = [\n {\n name: 'balanceOf',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'account', type: 'address' }],\n outputs: [{ name: '', type: 'uint256' }],\n },\n {\n name: 'decimals',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ name: '', type: 'uint8' }],\n },\n {\n name: 'symbol',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ name: '', type: 'string' }],\n },\n {\n name: 'transfer',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'to', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ name: '', type: 'bool' }],\n },\n {\n name: 'approve',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'spender', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ name: '', type: 'bool' }],\n },\n {\n name: 'allowance',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n ],\n outputs: [{ name: '', type: 'uint256' }],\n },\n] as const\n\n/**\n * Get explorer URL for a transaction\n */\nexport function getExplorerTxUrl(network: SupportedNetwork, txHash: string): string {\n return `${EXPLORER_URLS[network]}/tx/${txHash}`\n}\n\n/**\n * Get LayerZero Scan URL for a message\n */\nexport function getLayerZeroScanUrl(messageGuid: string): string {\n return `https://layerzeroscan.com/tx/${messageGuid}`\n}\n\n/**\n * Check if a network supports a specific token\n */\nexport function supportsToken(\n network: SupportedNetwork,\n token: 'USDC' | 'USDT' | 'USDT0',\n): boolean {\n switch (token) {\n case 'USDC':\n return network in USDC_ADDRESSES\n case 'USDT':\n return network in USDT_ADDRESSES\n case 'USDT0':\n return network in USDT0_ADDRESSES\n default:\n return false\n }\n}\n\n/**\n * Get token address for a network\n */\nexport function getTokenAddress(\n network: SupportedNetwork,\n token: 'USDC' | 'USDT' | 'USDT0',\n): Address | undefined {\n switch (token) {\n case 'USDC':\n return USDC_ADDRESSES[network]\n case 'USDT':\n return USDT_ADDRESSES[network]\n case 'USDT0':\n return USDT0_ADDRESSES[network]\n default:\n return undefined\n }\n}\n\n/**\n * Format token amount for display\n */\nexport function formatTokenAmount(amount: bigint, decimals: number, symbol: string): string {\n const divisor = BigInt(10 ** decimals)\n const wholePart = amount / divisor\n const fractionalPart = amount % divisor\n const fractionalStr = fractionalPart.toString().padStart(decimals, '0')\n const trimmedFractional = fractionalStr.replace(/0+$/, '') || '0'\n\n if (trimmedFractional === '0') {\n return `${wholePart} ${symbol}`\n }\n return `${wholePart}.${trimmedFractional} ${symbol}`\n}\n\n/**\n * Parse token amount from string to bigint\n */\nexport function parseTokenAmount(amount: string, decimals: number): bigint {\n const [wholePart, fractionalPart = ''] = amount.split('.')\n const paddedFractional = fractionalPart.padEnd(decimals, '0').slice(0, decimals)\n return BigInt(wholePart + paddedFractional)\n}\n","/**\n * t402/getAllBalances - Get token balances across all supported networks\n */\n\nimport { z } from 'zod'\nimport type { SupportedNetwork, ChainBalance } from '../types.js'\nimport { executeGetBalance } from './getBalance.js'\n\n/**\n * Input schema for getAllBalances tool\n */\nexport const getAllBalancesInputSchema = z.object({\n address: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Wallet address to check balances for'),\n networks: z\n .array(\n z.enum([\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ]),\n )\n .optional()\n .describe(\n 'Optional list of networks to check. If not provided, checks all supported networks.',\n ),\n})\n\nexport type GetAllBalancesInput = z.infer<typeof getAllBalancesInputSchema>\n\n/**\n * All supported networks\n */\nconst ALL_NETWORKS: SupportedNetwork[] = [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n]\n\n/**\n * Result of getAllBalances\n */\nexport interface AllBalancesResult {\n address: string\n balances: ChainBalance[]\n totalUsdcBalance: string\n totalUsdtBalance: string\n summary: string\n}\n\n/**\n * Execute getAllBalances tool\n */\nexport async function executeGetAllBalances(\n input: GetAllBalancesInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<AllBalancesResult> {\n const { address, networks = ALL_NETWORKS } = input\n\n // Fetch balances from all networks in parallel\n const balancePromises = networks.map((network) =>\n executeGetBalance({ network, address }, rpcUrls).catch((error) => {\n console.error(`Failed to fetch balance for ${network}:`, error)\n return null\n }),\n )\n\n const results = await Promise.all(balancePromises)\n const balances = results.filter((b): b is ChainBalance => b !== null)\n\n // Calculate total stablecoin balances\n let totalUsdc = 0n\n let totalUsdt = 0n\n\n for (const balance of balances) {\n for (const token of balance.tokens) {\n if (token.symbol === 'USDC') {\n totalUsdc += BigInt(token.balance)\n } else if (token.symbol === 'USDT' || token.symbol === 'USDT0') {\n totalUsdt += BigInt(token.balance)\n }\n }\n }\n\n // Format totals (assuming 6 decimals for USDC/USDT)\n const formatTotal = (amount: bigint): string => {\n const divisor = BigInt(10 ** 6)\n const whole = amount / divisor\n const fraction = amount % divisor\n const fractionStr = fraction.toString().padStart(6, '0').replace(/0+$/, '')\n return fractionStr ? `${whole}.${fractionStr}` : whole.toString()\n }\n\n const totalUsdcFormatted = formatTotal(totalUsdc)\n const totalUsdtFormatted = formatTotal(totalUsdt)\n\n // Create summary\n const chainsWithBalance = balances.filter(\n (b) => b.tokens.some((t) => BigInt(t.balance) > 0n) || BigInt(b.native.balance) > 0n,\n )\n\n const summary = [\n `Found balances on ${chainsWithBalance.length} of ${balances.length} networks checked.`,\n `Total USDC: ${totalUsdcFormatted}`,\n `Total USDT: ${totalUsdtFormatted}`,\n ].join(' ')\n\n return {\n address,\n balances,\n totalUsdcBalance: totalUsdcFormatted,\n totalUsdtBalance: totalUsdtFormatted,\n summary,\n }\n}\n\n/**\n * Format all balances result for display\n */\nexport function formatAllBalancesResult(result: AllBalancesResult): string {\n const lines: string[] = [\n `## Multi-Chain Balance Summary`,\n `**Address:** \\`${result.address}\\``,\n '',\n `### Totals`,\n `- **Total USDC:** ${result.totalUsdcBalance}`,\n `- **Total USDT:** ${result.totalUsdtBalance}`,\n '',\n `### By Network`,\n '',\n ]\n\n for (const balance of result.balances) {\n const hasBalance =\n balance.tokens.some((t) => BigInt(t.balance) > 0n) || BigInt(balance.native.balance) > 0n\n\n if (!hasBalance) continue\n\n lines.push(`#### ${balance.network}`)\n lines.push(`- ${balance.native.symbol}: ${balance.native.formatted}`)\n for (const token of balance.tokens) {\n if (BigInt(token.balance) > 0n) {\n lines.push(`- ${token.symbol}: ${token.formatted}`)\n }\n }\n lines.push('')\n }\n\n // List networks with no balance\n const emptyNetworks = result.balances.filter(\n (b) => !b.tokens.some((t) => BigInt(t.balance) > 0n) && BigInt(b.native.balance) === 0n,\n )\n\n if (emptyNetworks.length > 0) {\n lines.push(`_No balance on: ${emptyNetworks.map((n) => n.network).join(', ')}_`)\n }\n\n return lines.join('\\n')\n}\n","/**\n * t402/pay - Execute a payment on a specific network\n */\n\nimport { z } from 'zod'\nimport { createPublicClient, createWalletClient, http, parseUnits, type Address } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport * as chains from 'viem/chains'\nimport type { SupportedNetwork, PaymentResult } from '../types.js'\nimport {\n DEFAULT_RPC_URLS,\n ERC20_ABI,\n getTokenAddress,\n getExplorerTxUrl,\n supportsToken,\n} from '../constants.js'\n\n/**\n * Input schema for pay tool\n */\nexport const payInputSchema = z.object({\n to: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Recipient address'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount to pay (e.g., '10.50' for 10.50 USDC)\"),\n token: z.enum(['USDC', 'USDT', 'USDT0']).describe('Token to use for payment'),\n network: z\n .enum([\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ])\n .describe('Network to execute payment on'),\n memo: z.string().optional().describe('Optional memo/reference for the payment'),\n})\n\nexport type PayInput = z.infer<typeof payInputSchema>\n\n/**\n * Get the viem chain configuration for a network\n */\nfunction getViemChain(network: SupportedNetwork) {\n switch (network) {\n case 'ethereum':\n return chains.mainnet\n case 'base':\n return chains.base\n case 'arbitrum':\n return chains.arbitrum\n case 'optimism':\n return chains.optimism\n case 'polygon':\n return chains.polygon\n case 'avalanche':\n return chains.avalanche\n case 'ink':\n return chains.ink\n case 'berachain':\n return chains.berachain\n case 'unichain':\n return chains.unichain\n default:\n return chains.mainnet\n }\n}\n\n/**\n * Options for executing payment\n */\nexport interface PayOptions {\n /** Private key for signing (hex with 0x prefix) */\n privateKey: string\n /** Custom RPC URL */\n rpcUrl?: string\n /** Demo mode - simulate without executing */\n demoMode?: boolean\n}\n\n/**\n * Execute pay tool\n */\nexport async function executePay(input: PayInput, options: PayOptions): Promise<PaymentResult> {\n const { to, amount, token, network, memo: _memo } = input\n const { privateKey, rpcUrl, demoMode } = options\n\n // Validate token support on network\n if (!supportsToken(network, token)) {\n throw new Error(`Token ${token} is not supported on ${network}`)\n }\n\n const tokenAddress = getTokenAddress(network, token)\n if (!tokenAddress) {\n throw new Error(`Could not find ${token} address for ${network}`)\n }\n\n // Parse amount (USDC/USDT use 6 decimals)\n const decimals = 6\n const amountBigInt = parseUnits(amount, decimals)\n\n // Demo mode - return simulated result\n if (demoMode) {\n const fakeTxHash = `0x${'0'.repeat(64)}` as `0x${string}`\n return {\n txHash: fakeTxHash,\n network,\n amount,\n token,\n to: to as Address,\n explorerUrl: getExplorerTxUrl(network, fakeTxHash),\n }\n }\n\n // Create clients\n const chain = getViemChain(network)\n const transport = http(rpcUrl || DEFAULT_RPC_URLS[network])\n\n const account = privateKeyToAccount(privateKey as `0x${string}`)\n\n const publicClient = createPublicClient({\n chain,\n transport,\n })\n\n const walletClient = createWalletClient({\n account,\n chain,\n transport,\n })\n\n // Check balance\n const balance = (await publicClient.readContract({\n address: tokenAddress,\n abi: ERC20_ABI,\n functionName: 'balanceOf',\n args: [account.address],\n })) as bigint\n\n if (balance < amountBigInt) {\n throw new Error(\n `Insufficient ${token} balance. Have: ${balance.toString()}, Need: ${amountBigInt.toString()}`,\n )\n }\n\n // Execute transfer\n const hash = await walletClient.writeContract({\n address: tokenAddress,\n abi: ERC20_ABI,\n functionName: 'transfer',\n args: [to as Address, amountBigInt],\n })\n\n // Wait for confirmation\n const receipt = await publicClient.waitForTransactionReceipt({ hash })\n\n if (receipt.status !== 'success') {\n throw new Error(`Transaction failed: ${hash}`)\n }\n\n return {\n txHash: hash,\n network,\n amount,\n token,\n to: to as Address,\n explorerUrl: getExplorerTxUrl(network, hash),\n }\n}\n\n/**\n * Format payment result for display\n */\nexport function formatPaymentResult(result: PaymentResult): string {\n return [\n `## Payment Successful`,\n '',\n `- **Amount:** ${result.amount} ${result.token}`,\n `- **To:** \\`${result.to}\\``,\n `- **Network:** ${result.network}`,\n `- **Transaction:** \\`${result.txHash}\\``,\n '',\n `[View on Explorer](${result.explorerUrl})`,\n ].join('\\n')\n}\n","/**\n * t402/payGasless - Execute a gasless payment using ERC-4337\n */\n\nimport { z } from 'zod'\nimport { createPublicClient, http, parseUnits, encodeFunctionData, type Address } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport * as chains from 'viem/chains'\nimport type { SupportedNetwork, GaslessPaymentResult } from '../types.js'\nimport {\n DEFAULT_RPC_URLS,\n ERC20_ABI,\n getTokenAddress,\n getExplorerTxUrl,\n supportsToken,\n} from '../constants.js'\n\n/**\n * Input schema for payGasless tool\n */\nexport const payGaslessInputSchema = z.object({\n to: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Recipient address'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount to pay (e.g., '10.50' for 10.50 USDC)\"),\n token: z.enum(['USDC', 'USDT', 'USDT0']).describe('Token to use for payment'),\n network: z\n .enum(['ethereum', 'base', 'arbitrum', 'optimism', 'polygon', 'avalanche'])\n .describe('Network to execute gasless payment on (must support ERC-4337)'),\n})\n\nexport type PayGaslessInput = z.infer<typeof payGaslessInputSchema>\n\n/**\n * Networks that support ERC-4337 gasless transactions\n */\nexport const GASLESS_SUPPORTED_NETWORKS: SupportedNetwork[] = [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n]\n\n/**\n * Get the viem chain configuration for a network\n */\nfunction getViemChain(network: SupportedNetwork) {\n switch (network) {\n case 'ethereum':\n return chains.mainnet\n case 'base':\n return chains.base\n case 'arbitrum':\n return chains.arbitrum\n case 'optimism':\n return chains.optimism\n case 'polygon':\n return chains.polygon\n case 'avalanche':\n return chains.avalanche\n case 'ink':\n return chains.ink\n case 'berachain':\n return chains.berachain\n case 'unichain':\n return chains.unichain\n default:\n return chains.mainnet\n }\n}\n\n/**\n * Options for executing gasless payment\n */\nexport interface PayGaslessOptions {\n /** Private key for signing (hex with 0x prefix) */\n privateKey: string\n /** Bundler URL for ERC-4337 */\n bundlerUrl: string\n /** Paymaster URL for sponsoring gas */\n paymasterUrl: string\n /** Custom RPC URL */\n rpcUrl?: string\n /** Demo mode - simulate without executing */\n demoMode?: boolean\n}\n\n/**\n * User operation structure (simplified)\n */\ninterface UserOperation {\n sender: Address\n nonce: bigint\n initCode: `0x${string}`\n callData: `0x${string}`\n callGasLimit: bigint\n verificationGasLimit: bigint\n preVerificationGas: bigint\n maxFeePerGas: bigint\n maxPriorityFeePerGas: bigint\n paymasterAndData: `0x${string}`\n signature: `0x${string}`\n}\n\n/**\n * Execute payGasless tool\n */\nexport async function executePayGasless(\n input: PayGaslessInput,\n options: PayGaslessOptions,\n): Promise<GaslessPaymentResult> {\n const { to, amount, token, network } = input\n const { privateKey, bundlerUrl, paymasterUrl: _paymasterUrl, rpcUrl, demoMode } = options\n\n // Validate network supports gasless\n if (!GASLESS_SUPPORTED_NETWORKS.includes(network)) {\n throw new Error(\n `Network ${network} does not support ERC-4337 gasless transactions. Supported: ${GASLESS_SUPPORTED_NETWORKS.join(', ')}`,\n )\n }\n\n // Validate token support on network\n if (!supportsToken(network, token)) {\n throw new Error(`Token ${token} is not supported on ${network}`)\n }\n\n const tokenAddress = getTokenAddress(network, token)\n if (!tokenAddress) {\n throw new Error(`Could not find ${token} address for ${network}`)\n }\n\n // Parse amount (USDC/USDT use 6 decimals)\n const decimals = 6\n const amountBigInt = parseUnits(amount, decimals)\n\n // Demo mode - return simulated result\n if (demoMode) {\n const fakeTxHash = `0x${'1'.repeat(64)}` as `0x${string}`\n const fakeUserOpHash = `0x${'2'.repeat(64)}` as `0x${string}`\n return {\n txHash: fakeTxHash,\n userOpHash: fakeUserOpHash,\n network,\n amount,\n token,\n to: to as Address,\n explorerUrl: getExplorerTxUrl(network, fakeTxHash),\n paymaster: 'demo-paymaster',\n }\n }\n\n // Create clients\n const chain = getViemChain(network)\n const transport = http(rpcUrl || DEFAULT_RPC_URLS[network])\n\n const account = privateKeyToAccount(privateKey as `0x${string}`)\n\n const publicClient = createPublicClient({\n chain,\n transport,\n })\n\n // Encode the transfer call data\n const callData = encodeFunctionData({\n abi: ERC20_ABI,\n functionName: 'transfer',\n args: [to as Address, amountBigInt],\n })\n\n // Build user operation\n // Note: In production, this would integrate with a full ERC-4337 bundler\n const nonce = await publicClient.getTransactionCount({\n address: account.address,\n })\n\n const gasPrice = await publicClient.getGasPrice()\n\n const userOp: UserOperation = {\n sender: account.address,\n nonce: BigInt(nonce),\n initCode: '0x',\n callData: callData as `0x${string}`,\n callGasLimit: 100000n,\n verificationGasLimit: 100000n,\n preVerificationGas: 50000n,\n maxFeePerGas: gasPrice,\n maxPriorityFeePerGas: gasPrice / 10n,\n paymasterAndData: '0x', // Would be filled by paymaster\n signature: '0x',\n }\n\n // In production, this would:\n // 1. Request paymaster sponsorship from paymasterUrl\n // 2. Sign the user operation\n // 3. Submit to bundler at bundlerUrl\n // 4. Wait for user operation to be included\n\n // For now, send as regular transaction with sponsorship note\n const response = await fetch(bundlerUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'eth_sendUserOperation',\n params: [userOp, chain.id],\n }),\n })\n\n if (!response.ok) {\n throw new Error(`Bundler request failed: ${response.statusText}`)\n }\n\n const result = (await response.json()) as {\n error?: { message: string }\n result?: string\n }\n\n if (result.error) {\n throw new Error(`Bundler error: ${result.error.message}`)\n }\n\n const userOpHash = result.result as string\n\n // Poll for receipt\n let receipt: { transactionHash: string } | null = null\n for (let i = 0; i < 30; i++) {\n const receiptResponse = await fetch(bundlerUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'eth_getUserOperationReceipt',\n params: [userOpHash],\n }),\n })\n\n const receiptResult = (await receiptResponse.json()) as {\n result?: { transactionHash: string }\n }\n if (receiptResult.result) {\n receipt = receiptResult.result\n break\n }\n\n await new Promise((resolve) => setTimeout(resolve, 2000))\n }\n\n if (!receipt) {\n throw new Error('Timeout waiting for user operation receipt')\n }\n\n return {\n txHash: receipt.transactionHash,\n userOpHash,\n network,\n amount,\n token,\n to: to as Address,\n explorerUrl: getExplorerTxUrl(network, receipt.transactionHash),\n }\n}\n\n/**\n * Format gasless payment result for display\n */\nexport function formatGaslessPaymentResult(result: GaslessPaymentResult): string {\n const lines = [\n `## Gasless Payment Successful`,\n '',\n `- **Amount:** ${result.amount} ${result.token}`,\n `- **To:** \\`${result.to}\\``,\n `- **Network:** ${result.network}`,\n `- **Transaction:** \\`${result.txHash}\\``,\n `- **UserOp Hash:** \\`${result.userOpHash}\\``,\n ]\n\n if (result.paymaster) {\n lines.push(`- **Paymaster:** ${result.paymaster}`)\n }\n\n lines.push('')\n lines.push(`[View on Explorer](${result.explorerUrl})`)\n lines.push('')\n lines.push('_Gas fees were sponsored - no ETH was deducted from your wallet._')\n\n return lines.join('\\n')\n}\n","/**\n * t402/getBridgeFee - Get fee quote for bridging USDT0 between chains\n */\n\nimport { z } from 'zod'\nimport { createPublicClient, http, formatEther, type Address } from 'viem'\nimport * as chains from 'viem/chains'\nimport type { SupportedNetwork, BridgeFeeQuote } from '../types.js'\nimport {\n DEFAULT_RPC_URLS,\n BRIDGEABLE_CHAINS,\n USDT0_ADDRESSES,\n NATIVE_SYMBOLS,\n parseTokenAmount,\n} from '../constants.js'\n\n/**\n * Input schema for getBridgeFee tool\n */\nexport const getBridgeFeeInputSchema = z.object({\n fromChain: z\n .enum(['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'])\n .describe('Source chain to bridge from'),\n toChain: z\n .enum(['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'])\n .describe('Destination chain to bridge to'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount of USDT0 to bridge (e.g., '100' for 100 USDT0)\"),\n recipient: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Recipient address on destination chain'),\n})\n\nexport type GetBridgeFeeInput = z.infer<typeof getBridgeFeeInputSchema>\n\n/**\n * LayerZero endpoint IDs for supported chains\n */\nconst LAYERZERO_ENDPOINT_IDS: Record<string, number> = {\n ethereum: 30101,\n arbitrum: 30110,\n ink: 30291,\n berachain: 30362,\n unichain: 30320,\n}\n\n/**\n * Estimated bridge times in seconds\n */\nconst ESTIMATED_BRIDGE_TIMES: Record<string, number> = {\n ethereum: 900, // 15 minutes\n arbitrum: 300, // 5 minutes\n ink: 300, // 5 minutes\n berachain: 300, // 5 minutes\n unichain: 300, // 5 minutes\n}\n\n/**\n * OFT contract ABI for quoteSend\n */\nconst OFT_ABI = [\n {\n name: 'quoteSend',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n {\n name: '_sendParam',\n type: 'tuple',\n components: [\n { name: 'dstEid', type: 'uint32' },\n { name: 'to', type: 'bytes32' },\n { name: 'amountLD', type: 'uint256' },\n { name: 'minAmountLD', type: 'uint256' },\n { name: 'extraOptions', type: 'bytes' },\n { name: 'composeMsg', type: 'bytes' },\n { name: 'oftCmd', type: 'bytes' },\n ],\n },\n { name: '_payInLzToken', type: 'bool' },\n ],\n outputs: [\n {\n name: 'msgFee',\n type: 'tuple',\n components: [\n { name: 'nativeFee', type: 'uint256' },\n { name: 'lzTokenFee', type: 'uint256' },\n ],\n },\n ],\n },\n] as const\n\n/**\n * Get the viem chain configuration for a network\n */\nfunction getViemChain(network: SupportedNetwork) {\n switch (network) {\n case 'ethereum':\n return chains.mainnet\n case 'arbitrum':\n return chains.arbitrum\n case 'ink':\n return chains.ink\n case 'berachain':\n return chains.berachain\n case 'unichain':\n return chains.unichain\n default:\n return undefined\n }\n}\n\n/**\n * Convert address to bytes32 format for LayerZero\n */\nfunction addressToBytes32(address: Address): `0x${string}` {\n return `0x${address.slice(2).padStart(64, '0')}` as `0x${string}`\n}\n\n/**\n * Execute getBridgeFee tool\n */\nexport async function executeGetBridgeFee(\n input: GetBridgeFeeInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<BridgeFeeQuote> {\n const { fromChain, toChain, amount, recipient } = input\n\n // Validate chains are different\n if (fromChain === toChain) {\n throw new Error('Source and destination chains must be different')\n }\n\n // Validate both chains support bridging\n if (!BRIDGEABLE_CHAINS.includes(fromChain as SupportedNetwork)) {\n throw new Error(`Chain ${fromChain} does not support USDT0 bridging`)\n }\n if (!BRIDGEABLE_CHAINS.includes(toChain as SupportedNetwork)) {\n throw new Error(`Chain ${toChain} does not support USDT0 bridging`)\n }\n\n // Get USDT0 address on source chain\n const usdt0Address = USDT0_ADDRESSES[fromChain as SupportedNetwork]\n if (!usdt0Address) {\n throw new Error(`USDT0 not found on ${fromChain}`)\n }\n\n // Parse amount (6 decimals)\n const amountBigInt = parseTokenAmount(amount, 6)\n\n // Create client\n const chain = getViemChain(fromChain as SupportedNetwork)\n if (!chain) {\n throw new Error(`Unsupported chain: ${fromChain}`)\n }\n\n const rpcUrl =\n rpcUrls?.[fromChain as SupportedNetwork] || DEFAULT_RPC_URLS[fromChain as SupportedNetwork]\n const client = createPublicClient({\n chain,\n transport: http(rpcUrl),\n })\n\n // Build send params\n const dstEid = LAYERZERO_ENDPOINT_IDS[toChain]\n const sendParam = {\n dstEid,\n to: addressToBytes32(recipient as Address),\n amountLD: amountBigInt,\n minAmountLD: amountBigInt, // No slippage for quote\n extraOptions: '0x' as `0x${string}`,\n composeMsg: '0x' as `0x${string}`,\n oftCmd: '0x' as `0x${string}`,\n }\n\n // Get quote from contract\n const quote = (await client.readContract({\n address: usdt0Address,\n abi: OFT_ABI,\n functionName: 'quoteSend',\n args: [sendParam, false],\n })) as { nativeFee: bigint; lzTokenFee: bigint }\n\n const nativeSymbol = NATIVE_SYMBOLS[fromChain as SupportedNetwork]\n const estimatedTime = ESTIMATED_BRIDGE_TIMES[toChain] || 300\n\n return {\n fromChain: fromChain as SupportedNetwork,\n toChain: toChain as SupportedNetwork,\n amount,\n nativeFee: quote.nativeFee.toString(),\n nativeFeeFormatted: `${formatEther(quote.nativeFee)} ${nativeSymbol}`,\n estimatedTime,\n }\n}\n\n/**\n * Format bridge fee result for display\n */\nexport function formatBridgeFeeResult(result: BridgeFeeQuote): string {\n const minutes = Math.ceil(result.estimatedTime / 60)\n\n return [\n `## Bridge Fee Quote`,\n '',\n `- **Route:** ${result.fromChain} → ${result.toChain}`,\n `- **Amount:** ${result.amount} USDT0`,\n `- **Native Fee:** ${result.nativeFeeFormatted}`,\n `- **Estimated Time:** ~${minutes} minutes`,\n '',\n '_Note: Actual fees may vary slightly at execution time._',\n ].join('\\n')\n}\n","/**\n * t402/bridge - Bridge USDT0 between chains using LayerZero OFT\n */\n\nimport { z } from 'zod'\nimport {\n createPublicClient,\n createWalletClient,\n http,\n keccak256,\n toBytes,\n type Address,\n} from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport * as chains from 'viem/chains'\nimport type { SupportedNetwork, BridgeResult } from '../types.js'\nimport {\n DEFAULT_RPC_URLS,\n BRIDGEABLE_CHAINS,\n USDT0_ADDRESSES,\n ERC20_ABI,\n parseTokenAmount,\n getLayerZeroScanUrl,\n getExplorerTxUrl,\n} from '../constants.js'\n\n/**\n * Input schema for bridge tool\n */\nexport const bridgeInputSchema = z.object({\n fromChain: z\n .enum(['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'])\n .describe('Source chain to bridge from'),\n toChain: z\n .enum(['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'])\n .describe('Destination chain to bridge to'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount of USDT0 to bridge (e.g., '100' for 100 USDT0)\"),\n recipient: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Recipient address on destination chain'),\n})\n\nexport type BridgeInput = z.infer<typeof bridgeInputSchema>\n\n/**\n * LayerZero endpoint IDs for supported chains\n */\nconst LAYERZERO_ENDPOINT_IDS: Record<string, number> = {\n ethereum: 30101,\n arbitrum: 30110,\n ink: 30291,\n berachain: 30362,\n unichain: 30320,\n}\n\n/**\n * Estimated bridge times in seconds\n */\nconst ESTIMATED_BRIDGE_TIMES: Record<string, number> = {\n ethereum: 900,\n arbitrum: 300,\n ink: 300,\n berachain: 300,\n unichain: 300,\n}\n\n/**\n * OFT contract ABI\n */\nconst OFT_ABI = [\n {\n name: 'quoteSend',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n {\n name: '_sendParam',\n type: 'tuple',\n components: [\n { name: 'dstEid', type: 'uint32' },\n { name: 'to', type: 'bytes32' },\n { name: 'amountLD', type: 'uint256' },\n { name: 'minAmountLD', type: 'uint256' },\n { name: 'extraOptions', type: 'bytes' },\n { name: 'composeMsg', type: 'bytes' },\n { name: 'oftCmd', type: 'bytes' },\n ],\n },\n { name: '_payInLzToken', type: 'bool' },\n ],\n outputs: [\n {\n name: 'msgFee',\n type: 'tuple',\n components: [\n { name: 'nativeFee', type: 'uint256' },\n { name: 'lzTokenFee', type: 'uint256' },\n ],\n },\n ],\n },\n {\n name: 'send',\n type: 'function',\n stateMutability: 'payable',\n inputs: [\n {\n name: '_sendParam',\n type: 'tuple',\n components: [\n { name: 'dstEid', type: 'uint32' },\n { name: 'to', type: 'bytes32' },\n { name: 'amountLD', type: 'uint256' },\n { name: 'minAmountLD', type: 'uint256' },\n { name: 'extraOptions', type: 'bytes' },\n { name: 'composeMsg', type: 'bytes' },\n { name: 'oftCmd', type: 'bytes' },\n ],\n },\n {\n name: '_fee',\n type: 'tuple',\n components: [\n { name: 'nativeFee', type: 'uint256' },\n { name: 'lzTokenFee', type: 'uint256' },\n ],\n },\n { name: '_refundAddress', type: 'address' },\n ],\n outputs: [\n {\n name: 'msgReceipt',\n type: 'tuple',\n components: [\n { name: 'guid', type: 'bytes32' },\n { name: 'nonce', type: 'uint64' },\n {\n name: 'fee',\n type: 'tuple',\n components: [\n { name: 'nativeFee', type: 'uint256' },\n { name: 'lzTokenFee', type: 'uint256' },\n ],\n },\n ],\n },\n {\n name: 'oftReceipt',\n type: 'tuple',\n components: [\n { name: 'amountSentLD', type: 'uint256' },\n { name: 'amountReceivedLD', type: 'uint256' },\n ],\n },\n ],\n },\n] as const\n\n/**\n * OFTSent event topic\n */\nconst OFT_SENT_EVENT_TOPIC = keccak256(toBytes('OFTSent(bytes32,uint32,address,uint256,uint256)'))\n\n/**\n * Get the viem chain configuration for a network\n */\nfunction getViemChain(network: SupportedNetwork) {\n switch (network) {\n case 'ethereum':\n return chains.mainnet\n case 'arbitrum':\n return chains.arbitrum\n case 'ink':\n return chains.ink\n case 'berachain':\n return chains.berachain\n case 'unichain':\n return chains.unichain\n default:\n return undefined\n }\n}\n\n/**\n * Convert address to bytes32 format for LayerZero\n */\nfunction addressToBytes32(address: Address): `0x${string}` {\n return `0x${address.slice(2).padStart(64, '0')}` as `0x${string}`\n}\n\n/**\n * Options for executing bridge\n */\nexport interface BridgeOptions {\n /** Private key for signing (hex with 0x prefix) */\n privateKey: string\n /** Custom RPC URL */\n rpcUrl?: string\n /** Demo mode - simulate without executing */\n demoMode?: boolean\n /** Slippage tolerance percentage (default: 0.5) */\n slippageTolerance?: number\n}\n\n/**\n * Execute bridge tool\n */\nexport async function executeBridge(\n input: BridgeInput,\n options: BridgeOptions,\n): Promise<BridgeResult> {\n const { fromChain, toChain, amount, recipient } = input\n const { privateKey, rpcUrl, demoMode, slippageTolerance = 0.5 } = options\n\n // Validate chains are different\n if (fromChain === toChain) {\n throw new Error('Source and destination chains must be different')\n }\n\n // Validate both chains support bridging\n if (!BRIDGEABLE_CHAINS.includes(fromChain as SupportedNetwork)) {\n throw new Error(`Chain ${fromChain} does not support USDT0 bridging`)\n }\n if (!BRIDGEABLE_CHAINS.includes(toChain as SupportedNetwork)) {\n throw new Error(`Chain ${toChain} does not support USDT0 bridging`)\n }\n\n // Get USDT0 address on source chain\n const usdt0Address = USDT0_ADDRESSES[fromChain as SupportedNetwork]\n if (!usdt0Address) {\n throw new Error(`USDT0 not found on ${fromChain}`)\n }\n\n // Parse amount (6 decimals)\n const amountBigInt = parseTokenAmount(amount, 6)\n\n // Calculate minimum amount with slippage\n const slippageMultiplier = BigInt(Math.floor((100 - slippageTolerance) * 100))\n const minAmountBigInt = (amountBigInt * slippageMultiplier) / 10000n\n\n // Demo mode - return simulated result\n if (demoMode) {\n const fakeTxHash = `0x${'a'.repeat(64)}` as `0x${string}`\n const fakeGuid = `0x${'b'.repeat(64)}` as `0x${string}`\n const estimatedTime = ESTIMATED_BRIDGE_TIMES[toChain] || 300\n\n return {\n txHash: fakeTxHash,\n messageGuid: fakeGuid,\n amount,\n fromChain: fromChain as SupportedNetwork,\n toChain: toChain as SupportedNetwork,\n estimatedTime,\n trackingUrl: getLayerZeroScanUrl(fakeGuid),\n }\n }\n\n // Create clients\n const chain = getViemChain(fromChain as SupportedNetwork)\n if (!chain) {\n throw new Error(`Unsupported chain: ${fromChain}`)\n }\n\n const transport = http(rpcUrl || DEFAULT_RPC_URLS[fromChain as SupportedNetwork])\n const account = privateKeyToAccount(privateKey as `0x${string}`)\n\n const publicClient = createPublicClient({\n chain,\n transport,\n })\n\n const walletClient = createWalletClient({\n account,\n chain,\n transport,\n })\n\n // Check USDT0 balance\n const balance = (await publicClient.readContract({\n address: usdt0Address,\n abi: ERC20_ABI,\n functionName: 'balanceOf',\n args: [account.address],\n })) as bigint\n\n if (balance < amountBigInt) {\n throw new Error(\n `Insufficient USDT0 balance. Have: ${balance.toString()}, Need: ${amountBigInt.toString()}`,\n )\n }\n\n // Build send params\n const dstEid = LAYERZERO_ENDPOINT_IDS[toChain]\n const sendParam = {\n dstEid,\n to: addressToBytes32(recipient as Address),\n amountLD: amountBigInt,\n minAmountLD: minAmountBigInt,\n extraOptions: '0x' as `0x${string}`,\n composeMsg: '0x' as `0x${string}`,\n oftCmd: '0x' as `0x${string}`,\n }\n\n // Get quote\n const quote = (await publicClient.readContract({\n address: usdt0Address,\n abi: OFT_ABI,\n functionName: 'quoteSend',\n args: [sendParam, false],\n })) as { nativeFee: bigint; lzTokenFee: bigint }\n\n // Add 10% buffer to fee\n const nativeFeeWithBuffer = (quote.nativeFee * 110n) / 100n\n\n // Execute send\n const hash = await walletClient.writeContract({\n address: usdt0Address,\n abi: OFT_ABI,\n functionName: 'send',\n args: [sendParam, { nativeFee: nativeFeeWithBuffer, lzTokenFee: 0n }, account.address],\n value: nativeFeeWithBuffer,\n })\n\n // Wait for confirmation\n const receipt = await publicClient.waitForTransactionReceipt({ hash })\n\n if (receipt.status !== 'success') {\n throw new Error(`Bridge transaction failed: ${hash}`)\n }\n\n // Extract message GUID from OFTSent event\n let messageGuid: `0x${string}` = '0x' as `0x${string}`\n for (const log of receipt.logs) {\n if (log.topics[0] === OFT_SENT_EVENT_TOPIC && log.topics[1]) {\n messageGuid = log.topics[1] as `0x${string}`\n break\n }\n }\n\n if (messageGuid === '0x') {\n throw new Error('Failed to extract message GUID from transaction logs')\n }\n\n const estimatedTime = ESTIMATED_BRIDGE_TIMES[toChain] || 300\n\n return {\n txHash: hash,\n messageGuid,\n amount,\n fromChain: fromChain as SupportedNetwork,\n toChain: toChain as SupportedNetwork,\n estimatedTime,\n trackingUrl: getLayerZeroScanUrl(messageGuid),\n }\n}\n\n/**\n * Format bridge result for display\n */\nexport function formatBridgeResult(result: BridgeResult): string {\n const minutes = Math.ceil(result.estimatedTime / 60)\n\n return [\n `## Bridge Transaction Submitted`,\n '',\n `- **Route:** ${result.fromChain} → ${result.toChain}`,\n `- **Amount:** ${result.amount} USDT0`,\n `- **Transaction:** \\`${result.txHash}\\``,\n `- **Message GUID:** \\`${result.messageGuid}\\``,\n `- **Estimated Delivery:** ~${minutes} minutes`,\n '',\n `### Tracking`,\n `- [View on LayerZero Scan](${result.trackingUrl})`,\n `- [View Source TX](${getExplorerTxUrl(result.fromChain, result.txHash)})`,\n '',\n `_Your USDT0 will arrive on ${result.toChain} once the LayerZero message is delivered._`,\n ].join('\\n')\n}\n","/**\n * wdk/getWallet - Get wallet info from WDK\n */\n\nimport { z } from 'zod'\nimport type { T402WDK } from '@t402/wdk'\n\n/**\n * Input schema for wdk/getWallet tool\n */\nexport const wdkGetWalletInputSchema = z.object({})\n\nexport type WdkGetWalletInput = z.infer<typeof wdkGetWalletInputSchema>\n\n/**\n * Wallet info result\n */\nexport interface WdkWalletInfo {\n /** EVM address */\n evmAddress: string\n /** Supported chains */\n chains: string[]\n}\n\n/**\n * Execute wdk/getWallet tool\n *\n * @param _input - Empty input (no params needed)\n * @param wdk - T402WDK instance\n * @returns Wallet info\n */\nexport async function executeWdkGetWallet(\n _input: WdkGetWalletInput,\n wdk: T402WDK,\n): Promise<WdkWalletInfo> {\n const signer = await wdk.getSigner('ethereum')\n const chains = wdk.getConfiguredChains()\n\n return {\n evmAddress: signer.address,\n chains: chains.length > 0 ? chains : ['ethereum'],\n }\n}\n\n/**\n * Execute wdk/getWallet in demo mode\n *\n * @returns Demo wallet info\n */\nexport function executeWdkGetWalletDemo(): WdkWalletInfo {\n return {\n evmAddress: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',\n chains: ['ethereum', 'arbitrum', 'base', 'optimism'],\n }\n}\n\n/**\n * Format wallet info for display\n *\n * @param info - Wallet info\n * @returns Formatted string\n */\nexport function formatWdkWalletResult(info: WdkWalletInfo): string {\n const lines: string[] = [\n '## WDK Wallet Info',\n '',\n `**EVM Address:** \\`${info.evmAddress}\\``,\n '',\n '### Supported Chains',\n ...info.chains.map((c) => `- ${c}`),\n ]\n return lines.join('\\n')\n}\n","/**\n * wdk/getBalances - Get multi-chain balances via WDK\n */\n\nimport { z } from 'zod'\nimport type { T402WDK, AggregatedBalance } from '@t402/wdk'\nimport { formatUnits } from 'viem'\n\n/**\n * Input schema for wdk/getBalances tool\n */\nexport const wdkGetBalancesInputSchema = z.object({\n chains: z\n .array(z.string())\n .optional()\n .describe('Optional list of chains to check. If not provided, checks all configured chains.'),\n})\n\nexport type WdkGetBalancesInput = z.infer<typeof wdkGetBalancesInputSchema>\n\n/**\n * WDK balance result\n */\nexport interface WdkBalancesResult {\n /** Per-chain balances */\n chains: Array<{\n chain: string\n usdt0: string\n usdc: string\n native: string\n }>\n /** Total USDT0 across all chains */\n totalUsdt0: string\n /** Total USDC across all chains */\n totalUsdc: string\n}\n\n/**\n * Find a token balance by symbol from the tokens array\n *\n * @param tokens - Array of token balances\n * @param symbol - Token symbol to find\n * @returns Formatted balance or '0'\n */\nfunction findTokenFormatted(\n tokens: Array<{ symbol: string; formatted: string }>,\n symbol: string,\n): string {\n return tokens.find((t) => t.symbol === symbol)?.formatted ?? '0'\n}\n\n/**\n * Execute wdk/getBalances tool\n *\n * @param input - Input with optional chains filter\n * @param wdk - T402WDK instance\n * @returns Multi-chain balances\n */\nexport async function executeWdkGetBalances(\n input: WdkGetBalancesInput,\n wdk: T402WDK,\n): Promise<WdkBalancesResult> {\n const balances: AggregatedBalance = await wdk.getAggregatedBalances()\n\n const chains = balances.chains\n .filter((c) => !input.chains || input.chains.includes(c.chain))\n .map((c) => ({\n chain: c.chain,\n usdt0: findTokenFormatted(c.tokens, 'USDT0'),\n usdc: findTokenFormatted(c.tokens, 'USDC'),\n native: formatUnits(c.native, 18),\n }))\n\n return {\n chains,\n totalUsdt0: formatUnits(balances.totalUsdt0, 6),\n totalUsdc: formatUnits(balances.totalUsdc, 6),\n }\n}\n\n/**\n * Execute wdk/getBalances in demo mode\n *\n * @returns Demo balances\n */\nexport function executeWdkGetBalancesDemo(): WdkBalancesResult {\n return {\n chains: [\n { chain: 'ethereum', usdt0: '100.00', usdc: '250.00', native: '0.5' },\n { chain: 'arbitrum', usdt0: '500.00', usdc: '0', native: '0.01' },\n { chain: 'base', usdt0: '200.00', usdc: '100.00', native: '0.02' },\n ],\n totalUsdt0: '800.00',\n totalUsdc: '350.00',\n }\n}\n\n/**\n * Format balances for display\n *\n * @param result - Balances result\n * @returns Formatted string\n */\nexport function formatWdkBalancesResult(result: WdkBalancesResult): string {\n const lines: string[] = [\n '## WDK Multi-Chain Balances',\n '',\n `**Total USDT0:** ${result.totalUsdt0}`,\n `**Total USDC:** ${result.totalUsdc}`,\n '',\n '### Per-Chain Breakdown',\n '',\n ]\n\n for (const chain of result.chains) {\n lines.push(`**${chain.chain}**`)\n lines.push(`- USDT0: ${chain.usdt0}`)\n lines.push(`- USDC: ${chain.usdc}`)\n lines.push(`- Native: ${chain.native}`)\n lines.push('')\n }\n\n return lines.join('\\n')\n}\n","/**\n * wdk/transfer - Send tokens via WDK\n */\n\nimport { z } from 'zod'\nimport type { T402WDK } from '@t402/wdk'\nimport type { Address } from 'viem'\nimport type { SupportedNetwork } from '../types.js'\nimport { getExplorerTxUrl } from '../constants.js'\n\n/**\n * Input schema for wdk/transfer tool\n */\nexport const wdkTransferInputSchema = z.object({\n to: z.string().describe('Recipient address'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount to send (e.g., '10.50')\"),\n token: z.enum(['USDC', 'USDT', 'USDT0']).describe('Token to transfer'),\n chain: z.string().describe('Chain to execute transfer on (e.g., \"ethereum\", \"arbitrum\")'),\n})\n\nexport type WdkTransferInput = z.infer<typeof wdkTransferInputSchema>\n\n/**\n * Transfer result\n */\nexport interface WdkTransferResult {\n /** Transaction hash */\n txHash: string\n /** Amount transferred */\n amount: string\n /** Token transferred */\n token: string\n /** Chain used */\n chain: string\n /** Recipient */\n to: string\n /** Explorer URL */\n explorerUrl: string\n}\n\n/**\n * Execute wdk/transfer tool\n *\n * @param input - Transfer parameters\n * @param wdk - T402WDK instance\n * @returns Transfer result\n */\nexport async function executeWdkTransfer(\n input: WdkTransferInput,\n wdk: T402WDK,\n): Promise<WdkTransferResult> {\n const signer = await wdk.getSigner(input.chain)\n\n // Use the WDK signer to send a raw transaction\n // For stablecoin transfers, we need to encode the ERC-20 transfer call\n const result = await signer.sendTransaction({\n to: input.to as Address,\n })\n\n const txHash = result.hash\n const explorerUrl = getExplorerTxUrl(input.chain as SupportedNetwork, txHash)\n\n return {\n txHash,\n amount: input.amount,\n token: input.token,\n chain: input.chain,\n to: input.to,\n explorerUrl,\n }\n}\n\n/**\n * Execute wdk/transfer in demo mode\n *\n * @param input - Transfer parameters\n * @returns Demo transfer result\n */\nexport function executeWdkTransferDemo(input: WdkTransferInput): WdkTransferResult {\n const demoTxHash = '0xdemo' + Math.random().toString(16).slice(2, 10)\n return {\n txHash: demoTxHash,\n amount: input.amount,\n token: input.token,\n chain: input.chain,\n to: input.to,\n explorerUrl: `https://etherscan.io/tx/${demoTxHash}`,\n }\n}\n\n/**\n * Format transfer result for display\n *\n * @param result - Transfer result\n * @returns Formatted string\n */\nexport function formatWdkTransferResult(result: WdkTransferResult): string {\n return [\n '## WDK Transfer Complete',\n '',\n `**Amount:** ${result.amount} ${result.token}`,\n `**Chain:** ${result.chain}`,\n `**To:** \\`${result.to}\\``,\n `**Tx Hash:** \\`${result.txHash}\\``,\n `**Explorer:** [View Transaction](${result.explorerUrl})`,\n ].join('\\n')\n}\n","/**\n * wdk/swap - Swap tokens via WDK\n */\n\nimport { z } from 'zod'\nimport type { T402WDK } from '@t402/wdk'\nimport { formatUnits, parseUnits } from 'viem'\n\n/**\n * Input schema for wdk/swap tool\n */\nexport const wdkSwapInputSchema = z.object({\n fromToken: z.string().describe('Token to swap from (e.g., \"ETH\", \"USDC\")'),\n toToken: z.string().describe('Token to swap to (e.g., \"USDT0\", \"USDC\")'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount to swap (e.g., '1.0')\"),\n chain: z.string().describe('Chain to execute swap on (e.g., \"ethereum\", \"arbitrum\")'),\n})\n\nexport type WdkSwapInput = z.infer<typeof wdkSwapInputSchema>\n\n/**\n * Swap result\n */\nexport interface WdkSwapResult {\n /** Input amount */\n fromAmount: string\n /** Input token */\n fromToken: string\n /** Output amount (estimated or actual) */\n toAmount: string\n /** Output token */\n toToken: string\n /** Chain */\n chain: string\n /** Transaction hash (if executed) */\n txHash?: string\n}\n\n/**\n * Execute wdk/swap tool\n *\n * @param input - Swap parameters\n * @param wdk - T402WDK instance\n * @returns Swap result\n */\nexport async function executeWdkSwap(input: WdkSwapInput, wdk: T402WDK): Promise<WdkSwapResult> {\n // Parse amount to smallest units (assume 18 decimals for native, 6 for stablecoins)\n const decimals = ['USDC', 'USDT', 'USDT0'].includes(input.fromToken.toUpperCase()) ? 6 : 18\n const amountBigInt = parseUnits(input.amount, decimals)\n\n // Get swap quote first\n const quote = await wdk.getSwapQuote(input.chain, input.fromToken, amountBigInt)\n\n // Execute swap\n const result = await wdk.swapAndPay({\n chain: input.chain,\n fromToken: input.fromToken,\n amount: amountBigInt,\n })\n\n // Format output amount (USDT0 is always 6 decimals output)\n const outputDecimals = ['USDC', 'USDT', 'USDT0'].includes(input.toToken.toUpperCase()) ? 6 : 18\n const toAmount = formatUnits(result?.outputAmount ?? quote.outputAmount, outputDecimals)\n\n return {\n fromAmount: input.amount,\n fromToken: input.fromToken,\n toAmount,\n toToken: input.toToken,\n chain: input.chain,\n txHash: result?.txHash,\n }\n}\n\n/**\n * Execute wdk/swap in demo mode\n *\n * @param input - Swap parameters\n * @returns Demo swap result\n */\nexport function executeWdkSwapDemo(input: WdkSwapInput): WdkSwapResult {\n // Simulate a swap with ~0.3% slippage\n const inputAmount = parseFloat(input.amount)\n const outputAmount = (inputAmount * 0.997).toFixed(6)\n\n return {\n fromAmount: input.amount,\n fromToken: input.fromToken,\n toAmount: outputAmount,\n toToken: input.toToken,\n chain: input.chain,\n txHash: '0xdemo' + Math.random().toString(16).slice(2, 10),\n }\n}\n\n/**\n * Format swap result for display\n *\n * @param result - Swap result\n * @returns Formatted string\n */\nexport function formatWdkSwapResult(result: WdkSwapResult): string {\n const lines = [\n '## WDK Swap Result',\n '',\n `**From:** ${result.fromAmount} ${result.fromToken}`,\n `**To:** ${result.toAmount} ${result.toToken}`,\n `**Chain:** ${result.chain}`,\n ]\n\n if (result.txHash) {\n lines.push(`**Tx Hash:** \\`${result.txHash}\\``)\n }\n\n return lines.join('\\n')\n}\n","/**\n * t402/autoPay - Smart payment orchestrator\n *\n * Fetches a URL, detects 402 payment requirements, checks WDK balances,\n * signs payment, and returns the paid content.\n */\n\nimport { z } from 'zod'\nimport type { T402WDK } from '@t402/wdk'\n\n/**\n * Input schema for t402/autoPay tool\n */\nexport const autoPayInputSchema = z.object({\n url: z.string().url().describe('URL to fetch (may return 402 Payment Required)'),\n maxAmount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .optional()\n .describe('Maximum amount willing to pay (e.g., \"10.00\"). If not set, pays any amount.'),\n preferredChain: z\n .string()\n .optional()\n .describe(\n 'Preferred chain for payment (e.g., \"arbitrum\"). If not specified, uses first available.',\n ),\n})\n\nexport type AutoPayInput = z.infer<typeof autoPayInputSchema>\n\n/**\n * AutoPay result\n */\nexport interface AutoPayResult {\n /** Whether the resource was successfully accessed */\n success: boolean\n /** HTTP status code */\n statusCode: number\n /** Response body (truncated if large) */\n body: string\n /** Content type of the response */\n contentType?: string\n /** Payment details (if payment was made) */\n payment?: {\n network: string\n scheme: string\n amount: string\n payTo: string\n }\n /** Error message (if failed) */\n error?: string\n}\n\n/**\n * Execute t402/autoPay tool\n *\n * @param input - AutoPay parameters\n * @param wdk - T402WDK instance\n * @returns AutoPay result\n */\nexport async function executeAutoPay(input: AutoPayInput, wdk: T402WDK): Promise<AutoPayResult> {\n const chains = input.preferredChain ? [input.preferredChain] : ['ethereum', 'arbitrum', 'base']\n\n const { T402Protocol } = await import('@t402/wdk-protocol')\n const protocol = await T402Protocol.create(wdk, { chains })\n\n const { response, receipt } = await protocol.fetch(input.url)\n\n // Check max amount\n if (receipt && input.maxAmount) {\n const paidAmount = parseFloat(receipt.amount) / 1e6 // Assume 6 decimals\n const maxAmount = parseFloat(input.maxAmount)\n if (paidAmount > maxAmount) {\n return {\n success: false,\n statusCode: 402,\n body: '',\n error: `Payment amount (${paidAmount}) exceeds max allowed (${maxAmount})`,\n }\n }\n }\n\n // Read response body\n const contentType = response.headers.get('content-type') ?? undefined\n let body = ''\n try {\n body = await response.text()\n // Truncate large responses\n if (body.length > 10000) {\n body = body.slice(0, 10000) + '\\n... (truncated)'\n }\n } catch {\n body = '[Could not read response body]'\n }\n\n return {\n success: response.ok,\n statusCode: response.status,\n body,\n contentType,\n payment: receipt\n ? {\n network: receipt.network,\n scheme: receipt.scheme,\n amount: receipt.amount,\n payTo: receipt.payTo,\n }\n : undefined,\n }\n}\n\n/**\n * Execute t402/autoPay in demo mode\n *\n * @param input - AutoPay parameters\n * @returns Demo autopay result\n */\nexport function executeAutoPayDemo(input: AutoPayInput): AutoPayResult {\n return {\n success: true,\n statusCode: 200,\n body: `[Demo] Premium content from ${input.url}\\n\\nThis is simulated content that would be returned after payment.`,\n contentType: 'text/plain',\n payment: {\n network: 'eip155:42161',\n scheme: 'exact',\n amount: '1000000',\n payTo: '0xC88f67e776f16DcFBf42e6bDda1B82604448899B',\n },\n }\n}\n\n/**\n * Format autopay result for display\n *\n * @param result - AutoPay result\n * @returns Formatted string\n */\nexport function formatAutoPayResult(result: AutoPayResult): string {\n const lines: string[] = ['## AutoPay Result', '']\n\n if (result.success) {\n lines.push(`**Status:** Success (${result.statusCode})`)\n } else {\n lines.push(`**Status:** Failed (${result.statusCode})`)\n }\n\n if (result.payment) {\n lines.push('')\n lines.push('### Payment Details')\n lines.push(`- **Network:** ${result.payment.network}`)\n lines.push(`- **Scheme:** ${result.payment.scheme}`)\n lines.push(`- **Amount:** ${result.payment.amount}`)\n lines.push(`- **Pay To:** \\`${result.payment.payTo}\\``)\n }\n\n if (result.error) {\n lines.push('')\n lines.push(`**Error:** ${result.error}`)\n }\n\n if (result.body) {\n lines.push('')\n lines.push('### Response Content')\n if (result.contentType) {\n lines.push(`_Content-Type: ${result.contentType}_`)\n }\n lines.push('')\n lines.push('```')\n lines.push(result.body)\n lines.push('```')\n }\n\n return lines.join('\\n')\n}\n","/**\n * TON MCP Bridge - Connects @ton/mcp tools with @t402/mcp\n *\n * Enables AI agents to perform end-to-end TON payment flows by\n * proxying @ton/mcp's 15 blockchain tools through the t402 MCP server.\n */\n\n/**\n * Configuration for the TON MCP bridge\n */\nexport interface TonMcpBridgeConfig {\n /** @ton/mcp server URL or SSE endpoint */\n tonMcpEndpoint?: string\n /** TON API key for direct calls (e.g., toncenter.com API key) */\n tonApiKey?: string\n /** Enable demo mode (simulates calls without executing) */\n demoMode?: boolean\n}\n\n/**\n * Tool input/output schema type\n */\ninterface ToolSchema {\n type: 'object'\n properties: Record<string, { type: string; description: string; enum?: string[] }>\n required: string[]\n}\n\n/**\n * TON bridge tool definition\n */\ninterface TonBridgeTool {\n name: string\n description: string\n inputSchema: ToolSchema\n}\n\n/**\n * Proxy tool definitions from @ton/mcp\n *\n * These map to the tools available in the @ton/mcp server.\n * When registered, they proxy requests to the @ton/mcp endpoint.\n */\nexport const TON_BRIDGE_TOOLS: Record<string, TonBridgeTool> = {\n 'ton/getBalance': {\n name: 'ton/getBalance',\n description: 'Get TON and Jetton balances for a wallet address on the TON blockchain.',\n inputSchema: {\n type: 'object',\n properties: {\n address: {\n type: 'string',\n description: 'TON wallet address (friendly or raw format)',\n },\n },\n required: ['address'],\n },\n },\n\n 'ton/transfer': {\n name: 'ton/transfer',\n description: 'Send TON to a recipient address on the TON blockchain.',\n inputSchema: {\n type: 'object',\n properties: {\n to: {\n type: 'string',\n description: 'Recipient TON address',\n },\n amount: {\n type: 'string',\n description: 'Amount of TON to send (e.g., \"1.5\")',\n },\n memo: {\n type: 'string',\n description: 'Optional memo/comment for the transfer',\n },\n },\n required: ['to', 'amount'],\n },\n },\n\n 'ton/getJettonBalance': {\n name: 'ton/getJettonBalance',\n description: 'Get the balance of a specific Jetton (TON token) for a wallet address.',\n inputSchema: {\n type: 'object',\n properties: {\n address: {\n type: 'string',\n description: 'TON wallet address',\n },\n jettonMaster: {\n type: 'string',\n description: 'Jetton master contract address',\n },\n },\n required: ['address', 'jettonMaster'],\n },\n },\n\n 'ton/swapJettons': {\n name: 'ton/swapJettons',\n description:\n 'Swap Jettons (TON tokens) using DEX aggregation on the TON network. Returns a raw transaction JSON to be sent via sendTransaction.',\n inputSchema: {\n type: 'object',\n properties: {\n from: {\n type: 'string',\n description: 'Source Jetton master address (or \"TON\" for native TON)',\n },\n to: {\n type: 'string',\n description: 'Destination Jetton master address (or \"TON\" for native TON)',\n },\n amount: {\n type: 'string',\n description: 'Amount to swap in human-readable format (e.g., \"1.5\")',\n },\n slippage: {\n type: 'string',\n description: 'Slippage tolerance (e.g., \"0.5\" for 0.5%)',\n },\n },\n required: ['from', 'to', 'amount'],\n },\n },\n\n 'ton/getTransactionStatus': {\n name: 'ton/getTransactionStatus',\n description: 'Check the status and details of a TON transaction by its hash.',\n inputSchema: {\n type: 'object',\n properties: {\n txHash: {\n type: 'string',\n description: 'Transaction hash (BOC hash or message hash)',\n },\n },\n required: ['txHash'],\n },\n },\n} as const\n\n/**\n * Execute a TON bridge tool call\n *\n * Proxies the tool call to the @ton/mcp endpoint or executes it\n * directly using the TON API key.\n *\n * @param toolName - Name of the tool to execute\n * @param args - Tool arguments\n * @param config - Bridge configuration\n * @returns Tool execution result\n */\nexport async function executeTonBridgeTool(\n toolName: string,\n args: Record<string, unknown>,\n config: TonMcpBridgeConfig,\n): Promise<{ content: Array<{ type: 'text'; text: string }>; isError?: boolean }> {\n // Demo mode: return simulated results\n if (config.demoMode) {\n return executeTonBridgeToolDemo(toolName, args)\n }\n\n // If we have a @ton/mcp endpoint, proxy the request\n if (config.tonMcpEndpoint) {\n return proxyToTonMcp(toolName, args, config.tonMcpEndpoint)\n }\n\n // If we have an API key, make direct API calls\n if (config.tonApiKey) {\n return executeTonBridgeToolDirect(toolName, args, config.tonApiKey)\n }\n\n return {\n content: [\n {\n type: 'text',\n text: `Error: TON MCP bridge not configured. Set tonMcpEndpoint or tonApiKey.`,\n },\n ],\n isError: true,\n }\n}\n\n/**\n * Demo mode execution for TON bridge tools\n */\nfunction executeTonBridgeToolDemo(\n toolName: string,\n args: Record<string, unknown>,\n): { content: Array<{ type: 'text'; text: string }> } {\n const responses: Record<string, string> = {\n 'ton/getBalance': `[DEMO] TON Balance for ${args.address ?? 'unknown'}:\\n- TON: 5.25\\n- USDT0: 100.00`,\n 'ton/transfer': `[DEMO] Transfer sent:\\n- To: ${args.to ?? 'unknown'}\\n- Amount: ${args.amount ?? '0'} TON\\n- TX: demo-ton-tx-hash-${Date.now().toString(36)}`,\n 'ton/getJettonBalance': `[DEMO] Jetton Balance:\\n- Address: ${args.address ?? 'unknown'}\\n- Jetton: ${args.jettonMaster ?? 'unknown'}\\n- Balance: 50.00`,\n 'ton/swapJettons': `[DEMO] Swap quote received:\\n- From: ${args.from ?? 'unknown'}\\n- To: ${args.to ?? 'unknown'}\\n- Amount: ${args.amount ?? '0'}\\n- Transaction: {\"validUntil\":${Math.floor(Date.now() / 1000) + 300},\"messages\":[{\"address\":\"EQDemo...\",\"amount\":\"${args.amount ?? '0'}\",\"payload\":\"base64...\"}]}`,\n 'ton/getTransactionStatus': `[DEMO] Transaction Status:\\n- Hash: ${args.txHash ?? 'unknown'}\\n- Status: Confirmed\\n- Block: 12345678`,\n }\n\n return {\n content: [\n {\n type: 'text',\n text: responses[toolName] ?? `[DEMO] Unknown TON tool: ${toolName}`,\n },\n ],\n }\n}\n\n/**\n * Proxy a tool call to the @ton/mcp server\n */\nasync function proxyToTonMcp(\n toolName: string,\n args: Record<string, unknown>,\n endpoint: string,\n): Promise<{ content: Array<{ type: 'text'; text: string }>; isError?: boolean }> {\n try {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'tools/call',\n params: { name: toolName, arguments: args },\n }),\n })\n\n if (!response.ok) {\n throw new Error(`TON MCP server returned ${response.status}`)\n }\n\n const result = (await response.json()) as {\n result?: { content: Array<{ type: 'text'; text: string }> }\n error?: { message: string }\n }\n\n if (result.error) {\n throw new Error(result.error.message)\n }\n\n return result.result ?? { content: [{ type: 'text', text: 'No result' }] }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return {\n content: [{ type: 'text', text: `Error proxying to @ton/mcp: ${message}` }],\n isError: true,\n }\n }\n}\n\n/**\n * Execute TON bridge tool directly using TON API\n */\nasync function executeTonBridgeToolDirect(\n toolName: string,\n args: Record<string, unknown>,\n apiKey: string,\n): Promise<{ content: Array<{ type: 'text'; text: string }>; isError?: boolean }> {\n const baseUrl = 'https://toncenter.com/api/v2'\n\n try {\n switch (toolName) {\n case 'ton/getBalance': {\n const response = await fetch(\n `${baseUrl}/getAddressBalance?address=${encodeURIComponent(String(args.address))}&api_key=${apiKey}`,\n )\n const data = (await response.json()) as { result: string }\n const balanceNano = BigInt(data.result)\n const balanceTon = Number(balanceNano) / 1e9\n return {\n content: [{ type: 'text', text: `TON Balance: ${balanceTon.toFixed(4)} TON` }],\n }\n }\n\n case 'ton/getTransactionStatus': {\n const response = await fetch(\n `${baseUrl}/getTransactions?hash=${encodeURIComponent(String(args.txHash))}&limit=1&api_key=${apiKey}`,\n )\n const data = (await response.json()) as { result: unknown[] }\n if (data.result.length === 0) {\n return {\n content: [{ type: 'text', text: 'Transaction not found' }],\n }\n }\n return {\n content: [\n {\n type: 'text',\n text: `Transaction found:\\n${JSON.stringify(data.result[0], null, 2)}`,\n },\n ],\n }\n }\n\n default:\n return {\n content: [\n {\n type: 'text',\n text: `Direct execution of ${toolName} is not supported. Configure tonMcpEndpoint to proxy to @ton/mcp.`,\n },\n ],\n isError: true,\n }\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return {\n content: [{ type: 'text', text: `Error executing TON API call: ${message}` }],\n isError: true,\n }\n }\n}\n\n/**\n * Register TON bridge tools on a t402 MCP server\n *\n * This function adds the TON bridge tools to the server's tool registry,\n * enabling AI agents to use TON blockchain operations alongside t402 payment tools.\n *\n * @param config - Bridge configuration\n * @returns Tool definitions and handler\n */\nexport function createTonBridgeToolSet(config: TonMcpBridgeConfig) {\n return {\n definitions: TON_BRIDGE_TOOLS,\n async handleToolCall(\n name: string,\n args: Record<string, unknown>,\n ): Promise<{ content: Array<{ type: 'text'; text: string }>; isError?: boolean }> {\n return executeTonBridgeTool(name, args, config)\n },\n }\n}\n","/**\n * erc8004/resolveAgent - Look up an agent's on-chain identity\n */\n\nimport { z } from 'zod'\nimport { resolveAgent } from '@t402/erc8004'\nimport type { ResolvedAgent, AgentRegistryId } from '@t402/erc8004'\nimport type { SupportedNetwork } from '../types.js'\nimport { createErc8004Client } from './erc8004Shared.js'\n\n/**\n * Input schema for resolveAgent tool\n */\nexport const erc8004ResolveAgentInputSchema = z.object({\n agentId: z.number().int().nonnegative().describe('Agent NFT token ID on the Identity Registry'),\n agentRegistry: z\n .string()\n .regex(/^eip155:\\d+:0x[a-fA-F0-9]+$/)\n .describe('Agent registry identifier (e.g., \"eip155:8453:0xRegistryAddress\")'),\n})\n\nexport type Erc8004ResolveAgentInput = z.infer<typeof erc8004ResolveAgentInputSchema>\n\n/**\n * Execute resolveAgent tool\n */\nexport async function executeErc8004ResolveAgent(\n input: Erc8004ResolveAgentInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<ResolvedAgent> {\n const { client, registryAddress } = createErc8004Client(input.agentRegistry, rpcUrls)\n\n return resolveAgent(\n client,\n registryAddress as `0x${string}`,\n BigInt(input.agentId),\n input.agentRegistry as AgentRegistryId,\n )\n}\n\n/**\n * Format resolveAgent result for display\n */\nexport function formatErc8004ResolveAgentResult(agent: ResolvedAgent): string {\n const lines: string[] = [\n `## Agent Identity (ID: ${agent.agentId})`,\n '',\n `**Registry:** ${agent.registry.id}`,\n `**Wallet:** \\`${agent.agentWallet}\\``,\n `**Owner:** \\`${agent.owner}\\``,\n `**Registration URI:** ${agent.agentURI}`,\n '',\n ]\n\n if (agent.registration) {\n const reg = agent.registration\n lines.push('### Registration File')\n if (reg.name) lines.push(`- **Name:** ${reg.name}`)\n if (reg.description) lines.push(`- **Description:** ${reg.description}`)\n if (reg.image) lines.push(`- **Image:** ${reg.image}`)\n if (reg.x402Support !== undefined) lines.push(`- **x402 Support:** ${reg.x402Support}`)\n\n if (reg.services?.length) {\n lines.push('')\n lines.push('### Services')\n for (const svc of reg.services) {\n lines.push(`- **${svc.name}:** ${svc.endpoint}`)\n }\n }\n }\n\n return lines.join('\\n')\n}\n","/**\n * Shared utilities for ERC-8004 MCP tools\n */\n\nimport { createPublicClient, http, type Chain } from 'viem'\nimport * as chains from 'viem/chains'\nimport { parseAgentRegistry, type ERC8004ReadClient } from '@t402/erc8004'\nimport type { SupportedNetwork } from '../types.js'\nimport { DEFAULT_RPC_URLS, CHAIN_IDS } from '../constants.js'\n\n/**\n * Map of EVM chain IDs to viem chain configs\n */\nconst CHAIN_ID_TO_VIEM: Record<number, Chain> = {\n 1: chains.mainnet,\n 8453: chains.base,\n 42161: chains.arbitrum,\n 10: chains.optimism,\n 137: chains.polygon,\n 43114: chains.avalanche,\n 57073: chains.ink,\n 80094: chains.berachain,\n 130: chains.unichain,\n}\n\n/**\n * Reverse map: chain ID → SupportedNetwork name\n */\nconst CHAIN_ID_TO_NETWORK: Record<number, SupportedNetwork> = Object.fromEntries(\n Object.entries(CHAIN_IDS).map(([name, id]) => [id, name as SupportedNetwork]),\n) as Record<number, SupportedNetwork>\n\n/**\n * Create an ERC8004ReadClient from an agentRegistry string.\n *\n * Parses the registry ID, resolves the chain, and creates a viem PublicClient.\n */\nexport function createErc8004Client(\n agentRegistry: string,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): { client: ERC8004ReadClient; registryAddress: string } {\n const parsed = parseAgentRegistry(agentRegistry)\n const chainId = parseInt(parsed.chainId, 10)\n\n const viemChain = CHAIN_ID_TO_VIEM[chainId]\n if (!viemChain) {\n throw new Error(\n `Unsupported chain ID ${chainId} from registry ${agentRegistry}. Supported: ${Object.keys(CHAIN_ID_TO_VIEM).join(', ')}`,\n )\n }\n\n const network = CHAIN_ID_TO_NETWORK[chainId]\n const rpcUrl = (network && rpcUrls?.[network]) || (network && DEFAULT_RPC_URLS[network])\n\n const client = createPublicClient({\n chain: viemChain,\n transport: http(rpcUrl),\n })\n\n return { client: client as unknown as ERC8004ReadClient, registryAddress: parsed.address }\n}\n","/**\n * erc8004/checkReputation - Query an agent's reputation score\n */\n\nimport { z } from 'zod'\nimport { getReputationSummary } from '@t402/erc8004'\nimport type { ReputationSummary } from '@t402/erc8004'\nimport type { SupportedNetwork } from '../types.js'\nimport { createErc8004Client } from './erc8004Shared.js'\n\n/**\n * Input schema for checkReputation tool\n */\nexport const erc8004CheckReputationInputSchema = z.object({\n agentId: z.number().int().nonnegative().describe('Agent NFT token ID'),\n agentRegistry: z\n .string()\n .regex(/^eip155:\\d+:0x[a-fA-F0-9]+$/)\n .describe('Agent registry identifier (e.g., \"eip155:8453:0xRegistryAddress\")'),\n reputationRegistry: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Reputation Registry contract address on the same chain'),\n trustedReviewers: z\n .array(z.string().regex(/^0x[a-fA-F0-9]{40}$/))\n .min(1)\n .describe('Addresses whose feedback is trusted (required for Sybil resistance)'),\n})\n\nexport type Erc8004CheckReputationInput = z.infer<typeof erc8004CheckReputationInputSchema>\n\n/**\n * Execute checkReputation tool\n */\nexport async function executeErc8004CheckReputation(\n input: Erc8004CheckReputationInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<ReputationSummary> {\n const { client } = createErc8004Client(input.agentRegistry, rpcUrls)\n\n return getReputationSummary(\n client,\n input.reputationRegistry as `0x${string}`,\n BigInt(input.agentId),\n input.trustedReviewers as `0x${string}`[],\n )\n}\n\n/**\n * Format checkReputation result for display\n */\nexport function formatErc8004CheckReputationResult(summary: ReputationSummary): string {\n const lines: string[] = [\n `## Agent Reputation (ID: ${summary.agentId})`,\n '',\n `| Metric | Value |`,\n `|--------|-------|`,\n `| Feedback Count | ${summary.count} |`,\n `| Raw Score | ${summary.summaryValue} |`,\n `| Score Decimals | ${summary.summaryValueDecimals} |`,\n `| **Normalized Score** | **${summary.normalizedScore}/100** |`,\n '',\n ]\n\n if (summary.normalizedScore >= 80) {\n lines.push('_High reputation — trusted agent_')\n } else if (summary.normalizedScore >= 50) {\n lines.push('_Moderate reputation_')\n } else if (summary.count > 0n) {\n lines.push('_Low reputation — exercise caution_')\n } else {\n lines.push('_No feedback recorded from trusted reviewers_')\n }\n\n return lines.join('\\n')\n}\n","/**\n * erc8004/verifyWallet - Verify payTo matches agent's on-chain wallet\n */\n\nimport { z } from 'zod'\nimport { verifyPayToMatchesAgent } from '@t402/erc8004'\nimport type { SupportedNetwork } from '../types.js'\nimport { createErc8004Client } from './erc8004Shared.js'\n\n/**\n * Input schema for verifyWallet tool\n */\nexport const erc8004VerifyWalletInputSchema = z.object({\n agentId: z.number().int().nonnegative().describe('Agent NFT token ID'),\n agentRegistry: z\n .string()\n .regex(/^eip155:\\d+:0x[a-fA-F0-9]+$/)\n .describe('Agent registry identifier (e.g., \"eip155:8453:0xRegistryAddress\")'),\n walletAddress: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Wallet address to verify (typically the payTo from PaymentRequirements)'),\n})\n\nexport type Erc8004VerifyWalletInput = z.infer<typeof erc8004VerifyWalletInputSchema>\n\nexport interface Erc8004VerifyWalletResult {\n matches: boolean\n agentId: number\n walletAddress: string\n registryAddress: string\n}\n\n/**\n * Execute verifyWallet tool\n */\nexport async function executeErc8004VerifyWallet(\n input: Erc8004VerifyWalletInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<Erc8004VerifyWalletResult> {\n const { client, registryAddress } = createErc8004Client(input.agentRegistry, rpcUrls)\n\n const matches = await verifyPayToMatchesAgent(\n client,\n registryAddress as `0x${string}`,\n BigInt(input.agentId),\n input.walletAddress,\n )\n\n return {\n matches,\n agentId: input.agentId,\n walletAddress: input.walletAddress,\n registryAddress,\n }\n}\n\n/**\n * Format verifyWallet result for display\n */\nexport function formatErc8004VerifyWalletResult(result: Erc8004VerifyWalletResult): string {\n const status = result.matches ? 'VERIFIED' : 'MISMATCH'\n const icon = result.matches ? '[PASS]' : '[FAIL]'\n\n const lines: string[] = [\n `## Wallet Verification: ${icon} ${status}`,\n '',\n `| Field | Value |`,\n `|-------|-------|`,\n `| Agent ID | ${result.agentId} |`,\n `| Wallet Address | \\`${result.walletAddress}\\` |`,\n `| Registry | \\`${result.registryAddress}\\` |`,\n `| **Result** | **${result.matches ? 'Address matches on-chain agentWallet' : 'Address does NOT match on-chain agentWallet'}** |`,\n ]\n\n return lines.join('\\n')\n}\n","/**\n * Unified MCP Toolkit - Combines WDK wallet tools with t402 payment tools.\n *\n * Agent workflow: check price -> check balance -> bridge if needed -> pay\n * All in one MCP session with a single server.\n */\n\nimport { z } from 'zod'\nimport type { T402WDK } from '@t402/wdk'\n\n/**\n * Configuration for unified MCP mode\n */\nexport interface UnifiedMcpConfig {\n /** WDK seed phrase for wallet management */\n wdkSeedPhrase?: string\n /** Chain RPC configurations */\n chains?: Record<string, string | string[]>\n /** Enable auto-pay mode (automatic balance check + bridge + pay) */\n autoPayEnabled?: boolean\n}\n\n/**\n * SmartPay input schema\n */\nexport const smartPayInputSchema = z.object({\n url: z.string().url().describe('URL of the 402-protected resource'),\n maxBridgeFee: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .optional()\n .describe('Maximum acceptable bridge fee in native token (optional)'),\n preferredNetwork: z.string().optional().describe('Preferred network for payment (optional)'),\n})\n\nexport type SmartPayInput = z.infer<typeof smartPayInputSchema>\n\n/**\n * SmartPay result\n */\nexport interface SmartPayResult {\n /** Whether the resource was successfully accessed */\n success: boolean\n /** HTTP status code */\n statusCode: number\n /** Response body (truncated if large) */\n body: string\n /** Content type of the response */\n contentType?: string\n /** Steps taken during smart payment */\n steps: SmartPayStep[]\n /** Payment details (if payment was made) */\n payment?: {\n network: string\n scheme: string\n amount: string\n payTo: string\n }\n /** Error message (if failed) */\n error?: string\n}\n\n/**\n * A step in the smart payment flow\n */\nexport interface SmartPayStep {\n action: 'check_price' | 'check_balance' | 'bridge' | 'pay' | 'fetch'\n status: 'success' | 'skipped' | 'failed'\n detail: string\n}\n\n/**\n * PaymentPlan input schema\n */\nexport const paymentPlanInputSchema = z.object({\n paymentRequired: z\n .object({\n scheme: z.string().optional(),\n network: z.string().optional(),\n maxAmountRequired: z.string().optional(),\n resource: z.string().optional(),\n description: z.string().optional(),\n payTo: z.string().optional(),\n maxDeadline: z.number().optional(),\n })\n .passthrough()\n .describe('The 402 PaymentRequired response'),\n})\n\nexport type PaymentPlanInput = z.infer<typeof paymentPlanInputSchema>\n\n/**\n * Payment plan result\n */\nexport interface PaymentPlanResult {\n /** Whether a viable plan was found */\n viable: boolean\n /** Recommended network to pay on */\n recommendedNetwork?: string\n /** Available balance on that network */\n availableBalance?: string\n /** Whether bridging is needed */\n bridgeRequired: boolean\n /** Bridge details if needed */\n bridgeDetails?: {\n fromChain: string\n toChain: string\n amount: string\n estimatedFee: string\n }\n /** Balances across all chains */\n balances: Array<{\n chain: string\n usdt0: string\n usdc: string\n }>\n /** Reason if not viable */\n reason?: string\n}\n\n/**\n * Unified tool definitions (additional tools beyond base + WDK)\n */\nexport const UNIFIED_TOOL_DEFINITIONS = {\n 't402/smartPay': {\n name: 't402/smartPay',\n description:\n 'Intelligent payment that automatically checks balance, bridges if needed, and pays. Handles the entire payment flow for 402-protected resources.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n url: { type: 'string', description: 'URL of the 402-protected resource' },\n maxBridgeFee: {\n type: 'string',\n description: 'Maximum acceptable bridge fee in native token (optional)',\n },\n preferredNetwork: {\n type: 'string',\n description: 'Preferred network for payment (optional)',\n },\n },\n required: ['url'],\n },\n },\n 't402/paymentPlan': {\n name: 't402/paymentPlan',\n description:\n 'Analyze a 402 response and create an optimal payment plan considering balances across all chains. Returns recommended network, bridge requirements, and balance overview.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n paymentRequired: {\n type: 'object',\n description: 'The 402 PaymentRequired response',\n },\n },\n required: ['paymentRequired'],\n },\n },\n} as const\n\n/**\n * Execute t402/smartPay tool\n */\nexport async function executeSmartPay(input: SmartPayInput, wdk: T402WDK): Promise<SmartPayResult> {\n const steps: SmartPayStep[] = []\n const chains = input.preferredNetwork\n ? [input.preferredNetwork]\n : ['ethereum', 'arbitrum', 'base']\n\n // Step 1: Check balances\n steps.push({\n action: 'check_balance',\n status: 'success',\n detail: `Checking balances on ${chains.join(', ')}`,\n })\n\n // Step 2: Create protocol and fetch\n const { T402Protocol } = await import('@t402/wdk-protocol')\n const protocol = await T402Protocol.create(wdk, { chains })\n\n steps.push({\n action: 'fetch',\n status: 'success',\n detail: `Fetching ${input.url}`,\n })\n\n const { response, receipt } = await protocol.fetch(input.url)\n\n if (receipt) {\n steps.push({\n action: 'pay',\n status: 'success',\n detail: `Payment made: ${receipt.amount} on ${receipt.network}`,\n })\n }\n\n // Read response body\n const contentType = response.headers.get('content-type') ?? undefined\n let body = ''\n try {\n body = await response.text()\n if (body.length > 10000) {\n body = body.slice(0, 10000) + '\\n... (truncated)'\n }\n } catch {\n body = '[Could not read response body]'\n }\n\n return {\n success: response.ok,\n statusCode: response.status,\n body,\n contentType,\n steps,\n payment: receipt\n ? {\n network: receipt.network,\n scheme: receipt.scheme,\n amount: receipt.amount,\n payTo: receipt.payTo,\n }\n : undefined,\n }\n}\n\n/**\n * Execute t402/smartPay in demo mode\n */\nexport function executeSmartPayDemo(input: SmartPayInput): SmartPayResult {\n const network = input.preferredNetwork ?? 'arbitrum'\n\n return {\n success: true,\n statusCode: 200,\n body: `[Demo] Premium content from ${input.url}\\n\\nThis is simulated content returned after smart payment.`,\n contentType: 'text/plain',\n steps: [\n { action: 'check_balance', status: 'success', detail: `Checked balances on ${network}` },\n { action: 'check_price', status: 'success', detail: 'Resource costs 1.00 USDT0' },\n { action: 'pay', status: 'success', detail: `Paid 1000000 USDT0 on eip155:42161` },\n { action: 'fetch', status: 'success', detail: `Fetched ${input.url}` },\n ],\n payment: {\n network: 'eip155:42161',\n scheme: 'exact',\n amount: '1000000',\n payTo: '0xC88f67e776f16DcFBf42e6bDda1B82604448899B',\n },\n }\n}\n\n/**\n * Execute t402/paymentPlan tool\n */\nexport async function executePaymentPlan(\n input: PaymentPlanInput,\n wdk: T402WDK,\n): Promise<PaymentPlanResult> {\n const targetNetwork = input.paymentRequired.network as string | undefined\n const requiredAmount = input.paymentRequired.maxAmountRequired as string | undefined\n\n // Get aggregated balances\n const aggregated = await wdk.getAggregatedBalances()\n\n const balances = aggregated.chains.map((chain) => {\n const usdt0 = chain.tokens.find((t) => t.symbol === 'USDT0')\n const usdc = chain.tokens.find((t) => t.symbol === 'USDC')\n return {\n chain: chain.chain,\n usdt0: usdt0?.formatted ?? '0',\n usdc: usdc?.formatted ?? '0',\n }\n })\n\n // Find chain with sufficient balance\n const requiredBigint = requiredAmount ? BigInt(requiredAmount) : 0n\n const bestChain = await wdk.findBestChainForPayment(requiredBigint)\n\n if (bestChain) {\n const needsBridge = targetNetwork ? !bestChain.chain.includes(targetNetwork) : false\n\n return {\n viable: true,\n recommendedNetwork: bestChain.chain,\n availableBalance: bestChain.balance.toString(),\n bridgeRequired: needsBridge,\n bridgeDetails: needsBridge\n ? {\n fromChain: bestChain.chain,\n toChain: targetNetwork ?? bestChain.chain,\n amount: requiredAmount ?? '0',\n estimatedFee: '0.001',\n }\n : undefined,\n balances,\n }\n }\n\n return {\n viable: false,\n bridgeRequired: false,\n balances,\n reason: 'Insufficient balance across all chains',\n }\n}\n\n/**\n * Execute t402/paymentPlan in demo mode\n */\nexport function executePaymentPlanDemo(_input: PaymentPlanInput): PaymentPlanResult {\n return {\n viable: true,\n recommendedNetwork: 'arbitrum',\n availableBalance: '500000000',\n bridgeRequired: false,\n balances: [\n { chain: 'ethereum', usdt0: '100.00', usdc: '250.00' },\n { chain: 'arbitrum', usdt0: '500.00', usdc: '0' },\n { chain: 'base', usdt0: '50.00', usdc: '100.00' },\n ],\n }\n}\n\n/**\n * Format smartPay result for display\n */\nexport function formatSmartPayResult(result: SmartPayResult): string {\n const lines: string[] = ['## SmartPay Result', '']\n\n if (result.success) {\n lines.push(`**Status:** Success (${result.statusCode})`)\n } else {\n lines.push(`**Status:** Failed (${result.statusCode})`)\n }\n\n // Steps\n if (result.steps.length > 0) {\n lines.push('')\n lines.push('### Steps')\n for (const step of result.steps) {\n const icon =\n step.status === 'success' ? '[OK]' : step.status === 'skipped' ? '[SKIP]' : '[FAIL]'\n lines.push(`- ${icon} **${step.action}**: ${step.detail}`)\n }\n }\n\n // Payment\n if (result.payment) {\n lines.push('')\n lines.push('### Payment Details')\n lines.push(`- **Network:** ${result.payment.network}`)\n lines.push(`- **Scheme:** ${result.payment.scheme}`)\n lines.push(`- **Amount:** ${result.payment.amount}`)\n lines.push(`- **Pay To:** \\`${result.payment.payTo}\\``)\n }\n\n if (result.error) {\n lines.push('')\n lines.push(`**Error:** ${result.error}`)\n }\n\n if (result.body) {\n lines.push('')\n lines.push('### Response Content')\n if (result.contentType) {\n lines.push(`_Content-Type: ${result.contentType}_`)\n }\n lines.push('')\n lines.push('```')\n lines.push(result.body)\n lines.push('```')\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Format paymentPlan result for display\n */\nexport function formatPaymentPlanResult(result: PaymentPlanResult): string {\n const lines: string[] = ['## Payment Plan', '']\n\n if (result.viable) {\n lines.push(`**Viable:** Yes`)\n if (result.recommendedNetwork) {\n lines.push(`**Recommended Network:** ${result.recommendedNetwork}`)\n }\n if (result.availableBalance) {\n lines.push(`**Available Balance:** ${result.availableBalance}`)\n }\n } else {\n lines.push(`**Viable:** No`)\n if (result.reason) {\n lines.push(`**Reason:** ${result.reason}`)\n }\n }\n\n if (result.bridgeRequired && result.bridgeDetails) {\n lines.push('')\n lines.push('### Bridge Required')\n lines.push(`- **From:** ${result.bridgeDetails.fromChain}`)\n lines.push(`- **To:** ${result.bridgeDetails.toChain}`)\n lines.push(`- **Amount:** ${result.bridgeDetails.amount}`)\n lines.push(`- **Estimated Fee:** ${result.bridgeDetails.estimatedFee}`)\n }\n\n if (result.balances.length > 0) {\n lines.push('')\n lines.push('### Chain Balances')\n lines.push('| Chain | USDT0 | USDC |')\n lines.push('|-------|-------|------|')\n for (const b of result.balances) {\n lines.push(`| ${b.chain} | ${b.usdt0} | ${b.usdc} |`)\n }\n }\n\n return lines.join('\\n')\n}\n","/**\n * t402 MCP Tools - Export all payment tools\n */\n\n// Balance tools\nexport {\n getBalanceInputSchema,\n executeGetBalance,\n formatBalanceResult,\n type GetBalanceInput,\n} from './getBalance.js'\n\nexport {\n getAllBalancesInputSchema,\n executeGetAllBalances,\n formatAllBalancesResult,\n type GetAllBalancesInput,\n type AllBalancesResult,\n} from './getAllBalances.js'\n\n// Payment tools\nexport {\n payInputSchema,\n executePay,\n formatPaymentResult,\n type PayInput,\n type PayOptions,\n} from './pay.js'\n\nexport {\n payGaslessInputSchema,\n executePayGasless,\n formatGaslessPaymentResult,\n GASLESS_SUPPORTED_NETWORKS,\n type PayGaslessInput,\n type PayGaslessOptions,\n} from './payGasless.js'\n\n// Bridge tools\nexport {\n getBridgeFeeInputSchema,\n executeGetBridgeFee,\n formatBridgeFeeResult,\n type GetBridgeFeeInput,\n} from './getBridgeFee.js'\n\nexport {\n bridgeInputSchema,\n executeBridge,\n formatBridgeResult,\n type BridgeInput,\n type BridgeOptions,\n} from './bridge.js'\n\n// WDK tools\nexport {\n wdkGetWalletInputSchema,\n executeWdkGetWallet,\n executeWdkGetWalletDemo,\n formatWdkWalletResult,\n type WdkGetWalletInput,\n type WdkWalletInfo,\n} from './wdkGetWallet.js'\n\nexport {\n wdkGetBalancesInputSchema,\n executeWdkGetBalances,\n executeWdkGetBalancesDemo,\n formatWdkBalancesResult,\n type WdkGetBalancesInput,\n type WdkBalancesResult,\n} from './wdkGetBalances.js'\n\nexport {\n wdkTransferInputSchema,\n executeWdkTransfer,\n executeWdkTransferDemo,\n formatWdkTransferResult,\n type WdkTransferInput,\n type WdkTransferResult,\n} from './wdkTransfer.js'\n\nexport {\n wdkSwapInputSchema,\n executeWdkSwap,\n executeWdkSwapDemo,\n formatWdkSwapResult,\n type WdkSwapInput,\n type WdkSwapResult,\n} from './wdkSwap.js'\n\nexport {\n autoPayInputSchema,\n executeAutoPay,\n executeAutoPayDemo,\n formatAutoPayResult,\n type AutoPayInput,\n type AutoPayResult,\n} from './autoPay.js'\n\n// TON bridge tools\nexport {\n TON_BRIDGE_TOOLS,\n executeTonBridgeTool,\n createTonBridgeToolSet,\n type TonMcpBridgeConfig,\n} from './ton-bridge.js'\n\n// ERC-8004 tools\nexport {\n erc8004ResolveAgentInputSchema,\n executeErc8004ResolveAgent,\n formatErc8004ResolveAgentResult,\n type Erc8004ResolveAgentInput,\n} from './erc8004ResolveAgent.js'\n\nexport {\n erc8004CheckReputationInputSchema,\n executeErc8004CheckReputation,\n formatErc8004CheckReputationResult,\n type Erc8004CheckReputationInput,\n} from './erc8004CheckReputation.js'\n\nexport {\n erc8004VerifyWalletInputSchema,\n executeErc8004VerifyWallet,\n formatErc8004VerifyWalletResult,\n type Erc8004VerifyWalletInput,\n type Erc8004VerifyWalletResult,\n} from './erc8004VerifyWallet.js'\n\n// Unified tools\nexport {\n smartPayInputSchema,\n executeSmartPay,\n executeSmartPayDemo,\n formatSmartPayResult,\n paymentPlanInputSchema,\n executePaymentPlan,\n executePaymentPlanDemo,\n formatPaymentPlanResult,\n UNIFIED_TOOL_DEFINITIONS,\n type SmartPayInput,\n type SmartPayResult,\n type SmartPayStep,\n type PaymentPlanInput,\n type PaymentPlanResult,\n type UnifiedMcpConfig,\n} from './unified.js'\n\n/**\n * Base tool definitions (always available)\n */\nexport const TOOL_DEFINITIONS = {\n 't402/getBalance': {\n name: 't402/getBalance',\n description:\n 'Get token balances (native + stablecoins) for a wallet on a specific blockchain network. Returns ETH/native token balance plus USDC, USDT, and USDT0 balances where supported.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n network: {\n type: 'string',\n enum: [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ],\n description: 'Blockchain network to check balance on',\n },\n address: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Wallet address to check balance for',\n },\n },\n required: ['network', 'address'],\n },\n },\n\n 't402/getAllBalances': {\n name: 't402/getAllBalances',\n description:\n 'Get token balances across all supported networks for a wallet. Returns aggregated totals and per-network breakdown of native tokens and stablecoins (USDC, USDT, USDT0).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n address: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Wallet address to check balances for',\n },\n networks: {\n type: 'array',\n items: {\n type: 'string',\n enum: [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ],\n },\n description:\n 'Optional list of networks to check. If not provided, checks all supported networks.',\n },\n },\n required: ['address'],\n },\n },\n\n 't402/pay': {\n name: 't402/pay',\n description:\n 'Execute a stablecoin payment on a specific blockchain network. Supports USDC, USDT, and USDT0 tokens. Requires a configured wallet with sufficient balance and native token for gas.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n to: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Recipient address',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount to pay (e.g., '10.50' for 10.50 USDC)\",\n },\n token: {\n type: 'string',\n enum: ['USDC', 'USDT', 'USDT0'],\n description: 'Token to use for payment',\n },\n network: {\n type: 'string',\n enum: [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ],\n description: 'Network to execute payment on',\n },\n memo: {\n type: 'string',\n description: 'Optional memo/reference for the payment',\n },\n },\n required: ['to', 'amount', 'token', 'network'],\n },\n },\n\n 't402/payGasless': {\n name: 't402/payGasless',\n description:\n 'Execute a gasless stablecoin payment using ERC-4337 account abstraction. Gas fees are sponsored by a paymaster, so no ETH is needed for the transaction. Supported on select networks.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n to: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Recipient address',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount to pay (e.g., '10.50' for 10.50 USDC)\",\n },\n token: {\n type: 'string',\n enum: ['USDC', 'USDT', 'USDT0'],\n description: 'Token to use for payment',\n },\n network: {\n type: 'string',\n enum: ['ethereum', 'base', 'arbitrum', 'optimism', 'polygon', 'avalanche'],\n description: 'Network to execute gasless payment on (must support ERC-4337)',\n },\n },\n required: ['to', 'amount', 'token', 'network'],\n },\n },\n\n 't402/getBridgeFee': {\n name: 't402/getBridgeFee',\n description:\n 'Get the fee quote for bridging USDT0 between chains using LayerZero OFT. Returns the native token fee required and estimated delivery time. Supported chains: ethereum, arbitrum, ink, berachain, unichain.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n fromChain: {\n type: 'string',\n enum: ['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'],\n description: 'Source chain to bridge from',\n },\n toChain: {\n type: 'string',\n enum: ['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'],\n description: 'Destination chain to bridge to',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount of USDT0 to bridge (e.g., '100' for 100 USDT0)\",\n },\n recipient: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Recipient address on destination chain',\n },\n },\n required: ['fromChain', 'toChain', 'amount', 'recipient'],\n },\n },\n\n 't402/bridge': {\n name: 't402/bridge',\n description:\n 'Bridge USDT0 between chains using LayerZero OFT standard. Executes a cross-chain transfer and returns the LayerZero message GUID for tracking. Supported chains: ethereum, arbitrum, ink, berachain, unichain.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n fromChain: {\n type: 'string',\n enum: ['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'],\n description: 'Source chain to bridge from',\n },\n toChain: {\n type: 'string',\n enum: ['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'],\n description: 'Destination chain to bridge to',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount of USDT0 to bridge (e.g., '100' for 100 USDT0)\",\n },\n recipient: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Recipient address on destination chain',\n },\n },\n required: ['fromChain', 'toChain', 'amount', 'recipient'],\n },\n },\n}\n\n/**\n * WDK tool definitions (only available when WDK seed phrase is configured)\n */\nexport const WDK_TOOL_DEFINITIONS = {\n 'wdk/getWallet': {\n name: 'wdk/getWallet',\n description:\n 'Get wallet information from the configured WDK wallet. Returns EVM address and supported chains. No parameters needed.',\n inputSchema: {\n type: 'object' as const,\n properties: {},\n required: [] as string[],\n },\n },\n\n 'wdk/getBalances': {\n name: 'wdk/getBalances',\n description:\n 'Get multi-chain token balances from the WDK wallet. Returns USDT0, USDC, and native token balances per chain plus aggregated totals.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n chains: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Optional list of chains to check (e.g., [\"ethereum\", \"arbitrum\"]). If not provided, checks all configured chains.',\n },\n },\n required: [] as string[],\n },\n },\n\n 'wdk/transfer': {\n name: 'wdk/transfer',\n description:\n 'Send stablecoins (USDC, USDT, USDT0) from the WDK wallet to a recipient address on a specific chain.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n to: {\n type: 'string',\n description: 'Recipient address',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount to send (e.g., '10.50')\",\n },\n token: {\n type: 'string',\n enum: ['USDC', 'USDT', 'USDT0'],\n description: 'Token to transfer',\n },\n chain: {\n type: 'string',\n description: 'Chain to execute transfer on (e.g., \"ethereum\", \"arbitrum\")',\n },\n },\n required: ['to', 'amount', 'token', 'chain'],\n },\n },\n\n 'wdk/swap': {\n name: 'wdk/swap',\n description:\n 'Swap tokens using the WDK Velora protocol. Supports swapping between stablecoins and native tokens.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n fromToken: {\n type: 'string',\n description: 'Token to swap from (e.g., \"ETH\", \"USDC\")',\n },\n toToken: {\n type: 'string',\n description: 'Token to swap to (e.g., \"USDT0\", \"USDC\")',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount to swap (e.g., '1.0')\",\n },\n chain: {\n type: 'string',\n description: 'Chain to execute swap on (e.g., \"ethereum\", \"arbitrum\")',\n },\n },\n required: ['fromToken', 'toToken', 'amount', 'chain'],\n },\n },\n\n 't402/autoPay': {\n name: 't402/autoPay',\n description:\n 'Smart payment orchestrator. Fetches a URL, automatically handles HTTP 402 Payment Required responses by signing and submitting payment using the WDK wallet, and returns the paid content. The killer tool for AI agents.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string',\n description: 'URL to fetch (may return 402 Payment Required)',\n },\n maxAmount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description:\n 'Maximum amount willing to pay (e.g., \"10.00\"). If not set, pays any amount.',\n },\n preferredChain: {\n type: 'string',\n description:\n 'Preferred chain for payment (e.g., \"arbitrum\"). If not specified, uses first available.',\n },\n },\n required: ['url'],\n },\n },\n}\n\n/**\n * ERC-8004 tool definitions (always available — read-only on-chain queries)\n */\nexport const ERC8004_TOOL_DEFINITIONS = {\n 'erc8004/resolveAgent': {\n name: 'erc8004/resolveAgent',\n description:\n \"Look up an agent's on-chain ERC-8004 identity. Returns the agent's registered wallet address, owner, registration file (name, description, services), and verification URI. Use this to verify an agent before making a payment.\",\n inputSchema: {\n type: 'object' as const,\n properties: {\n agentId: {\n type: 'number',\n description: 'Agent NFT token ID on the Identity Registry',\n },\n agentRegistry: {\n type: 'string',\n pattern: '^eip155:\\\\d+:0x[a-fA-F0-9]+$',\n description: 'Agent registry identifier (e.g., \"eip155:8453:0xRegistryAddress\")',\n },\n },\n required: ['agentId', 'agentRegistry'],\n },\n },\n\n 'erc8004/checkReputation': {\n name: 'erc8004/checkReputation',\n description:\n \"Query an agent's reputation score from the on-chain Reputation Registry. Returns a normalized 0-100 score based on feedback from trusted reviewers. Requires explicit trusted reviewer addresses for Sybil resistance.\",\n inputSchema: {\n type: 'object' as const,\n properties: {\n agentId: {\n type: 'number',\n description: 'Agent NFT token ID',\n },\n agentRegistry: {\n type: 'string',\n pattern: '^eip155:\\\\d+:0x[a-fA-F0-9]+$',\n description: 'Agent registry identifier (e.g., \"eip155:8453:0xRegistryAddress\")',\n },\n reputationRegistry: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Reputation Registry contract address on the same chain',\n },\n trustedReviewers: {\n type: 'array',\n items: { type: 'string', pattern: '^0x[a-fA-F0-9]{40}$' },\n minItems: 1,\n description: 'Addresses whose feedback is trusted (required for Sybil resistance)',\n },\n },\n required: ['agentId', 'agentRegistry', 'reputationRegistry', 'trustedReviewers'],\n },\n },\n\n 'erc8004/verifyWallet': {\n name: 'erc8004/verifyWallet',\n description:\n \"Verify that a payment address (payTo) matches an agent's on-chain registered wallet. Use this before paying to confirm the recipient address is legitimate and owned by the declared agent.\",\n inputSchema: {\n type: 'object' as const,\n properties: {\n agentId: {\n type: 'number',\n description: 'Agent NFT token ID',\n },\n agentRegistry: {\n type: 'string',\n pattern: '^eip155:\\\\d+:0x[a-fA-F0-9]+$',\n description: 'Agent registry identifier (e.g., \"eip155:8453:0xRegistryAddress\")',\n },\n walletAddress: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Wallet address to verify (typically the payTo from payment requirements)',\n },\n },\n required: ['agentId', 'agentRegistry', 'walletAddress'],\n },\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA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EACjC;AAEA,SAAO;AACT;","names":["import_zod","import_zod","import_viem","chains","getViemChain","import_zod","import_viem","import_accounts","chains","getViemChain","import_zod","import_viem","chains","getViemChain","import_zod","import_viem","import_accounts","chains","LAYERZERO_ENDPOINT_IDS","ESTIMATED_BRIDGE_TIMES","OFT_ABI","getViemChain","addressToBytes32","estimatedTime","import_zod","chains","import_zod","import_viem","chains","import_zod","import_zod","import_viem","import_zod","chains","import_zod","import_erc8004","import_viem","chains","import_zod","import_erc8004","import_zod","import_erc8004","import_zod","chains"]}
|
|
1
|
+
{"version":3,"sources":["../../src/index.ts","../../src/server/t402Server.ts","../../src/tools/getBalance.ts","../../src/constants.ts","../../src/tools/getAllBalances.ts","../../src/tools/pay.ts","../../src/tools/payGasless.ts","../../src/tools/getBridgeFee.ts","../../src/tools/bridge.ts","../../src/tools/wdkGetWallet.ts","../../src/tools/wdkGetBalances.ts","../../src/tools/wdkTransfer.ts","../../src/tools/wdkSwap.ts","../../src/tools/autoPay.ts","../../src/tools/ton-bridge.ts","../../src/tools/erc8004ResolveAgent.ts","../../src/tools/erc8004Shared.ts","../../src/tools/erc8004CheckReputation.ts","../../src/tools/erc8004VerifyWallet.ts","../../src/tools/priceService.ts","../../src/tools/getTokenPrice.ts","../../src/tools/getGasPrice.ts","../../src/tools/estimatePaymentFee.ts","../../src/tools/compareNetworkFees.ts","../../src/tools/quoteStore.ts","../../src/tools/wdkQuoteSwap.ts","../../src/tools/wdkExecuteSwap.ts","../../src/tools/quoteBridge.ts","../../src/tools/executeBridgeFromQuote.ts","../../src/tools/unified.ts","../../src/tools/index.ts"],"sourcesContent":["/**\n * @t402/mcp - MCP Server for AI Agent Payments\n *\n * This package provides a Model Context Protocol (MCP) server that enables\n * AI agents to make stablecoin payments across multiple blockchain networks.\n *\n * @example\n * ```typescript\n * import { createT402McpServer, loadConfigFromEnv } from '@t402/mcp';\n *\n * const config = loadConfigFromEnv();\n * const server = createT402McpServer(config);\n * await server.run();\n * ```\n *\n * @example Claude Desktop Configuration\n * ```json\n * {\n * \"mcpServers\": {\n * \"t402\": {\n * \"command\": \"npx\",\n * \"args\": [\"@t402/mcp\"],\n * \"env\": {\n * \"T402_PRIVATE_KEY\": \"0x...\",\n * \"T402_DEMO_MODE\": \"true\"\n * }\n * }\n * }\n * }\n * ```\n */\n\n// Server\nexport { T402McpServer, createT402McpServer, loadConfigFromEnv } from './server/index.js'\n\n// Tools\nexport {\n // Tool definitions\n TOOL_DEFINITIONS,\n UNIFIED_TOOL_DEFINITIONS,\n // Balance tools\n getBalanceInputSchema,\n executeGetBalance,\n formatBalanceResult,\n getAllBalancesInputSchema,\n executeGetAllBalances,\n formatAllBalancesResult,\n // Payment tools\n payInputSchema,\n executePay,\n formatPaymentResult,\n payGaslessInputSchema,\n executePayGasless,\n formatGaslessPaymentResult,\n GASLESS_SUPPORTED_NETWORKS,\n // Bridge tools\n getBridgeFeeInputSchema,\n executeGetBridgeFee,\n formatBridgeFeeResult,\n bridgeInputSchema,\n executeBridge,\n formatBridgeResult,\n // Unified tools\n smartPayInputSchema,\n executeSmartPay,\n executeSmartPayDemo,\n formatSmartPayResult,\n paymentPlanInputSchema,\n executePaymentPlan,\n executePaymentPlanDemo,\n formatPaymentPlanResult,\n // Types\n type GetBalanceInput,\n type GetAllBalancesInput,\n type AllBalancesResult,\n type PayInput,\n type PayOptions,\n type PayGaslessInput,\n type PayGaslessOptions,\n type GetBridgeFeeInput,\n type BridgeInput,\n type BridgeOptions,\n type SmartPayInput,\n type SmartPayResult,\n type SmartPayStep,\n type PaymentPlanInput,\n type PaymentPlanResult,\n type UnifiedMcpConfig,\n} from './tools/index.js'\n\n// Types\nexport type {\n SupportedNetwork,\n TokenBalance,\n ChainBalance,\n PaymentParams,\n PaymentResult,\n GaslessPaymentResult,\n BridgeFeeQuote,\n BridgeResult,\n McpServerConfig,\n ToolContext,\n} from './types.js'\n\n// Constants\nexport {\n CHAIN_IDS,\n NATIVE_SYMBOLS,\n EXPLORER_URLS,\n DEFAULT_RPC_URLS,\n USDC_ADDRESSES,\n USDT_ADDRESSES,\n USDT0_ADDRESSES,\n BRIDGEABLE_CHAINS,\n getExplorerTxUrl,\n getLayerZeroScanUrl,\n supportsToken,\n getTokenAddress,\n formatTokenAmount,\n parseTokenAmount,\n} from './constants.js'\n","/**\n * t402 MCP Server - Main server implementation\n */\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'\nimport type { McpServerConfig, SupportedNetwork } from '../types.js'\nimport {\n TOOL_DEFINITIONS,\n WDK_TOOL_DEFINITIONS,\n UNIFIED_TOOL_DEFINITIONS,\n executeGetBalance,\n formatBalanceResult,\n getBalanceInputSchema,\n executeGetAllBalances,\n formatAllBalancesResult,\n getAllBalancesInputSchema,\n executePay,\n formatPaymentResult,\n payInputSchema,\n executePayGasless,\n formatGaslessPaymentResult,\n payGaslessInputSchema,\n executeGetBridgeFee,\n formatBridgeFeeResult,\n getBridgeFeeInputSchema,\n executeBridge,\n formatBridgeResult,\n bridgeInputSchema,\n // WDK tools\n wdkGetWalletInputSchema,\n executeWdkGetWallet,\n executeWdkGetWalletDemo,\n formatWdkWalletResult,\n wdkGetBalancesInputSchema,\n executeWdkGetBalances,\n executeWdkGetBalancesDemo,\n formatWdkBalancesResult,\n wdkTransferInputSchema,\n executeWdkTransfer,\n executeWdkTransferDemo,\n formatWdkTransferResult,\n wdkSwapInputSchema,\n executeWdkSwap,\n executeWdkSwapDemo,\n formatWdkSwapResult,\n autoPayInputSchema,\n executeAutoPay,\n executeAutoPayDemo,\n formatAutoPayResult,\n // Unified tools\n smartPayInputSchema,\n executeSmartPay,\n executeSmartPayDemo,\n formatSmartPayResult,\n paymentPlanInputSchema,\n executePaymentPlan,\n executePaymentPlanDemo,\n formatPaymentPlanResult,\n // Price and fee tools\n getTokenPriceInputSchema,\n executeGetTokenPrice,\n formatTokenPriceResult,\n getGasPriceInputSchema,\n executeGetGasPrice,\n formatGasPriceResult,\n estimatePaymentFeeInputSchema,\n executeEstimatePaymentFee,\n formatPaymentFeeEstimate,\n compareNetworkFeesInputSchema,\n executeCompareNetworkFees,\n formatNetworkFeeComparison,\n // Quote-based tools\n quoteBridgeInputSchema,\n executeQuoteBridge,\n executeQuoteBridgeDemo,\n formatBridgeQuoteResult,\n executeBridgeFromQuoteInputSchema,\n executeExecuteBridgeFromQuote,\n executeExecuteBridgeFromQuoteDemo,\n formatExecuteBridgeFromQuoteResult,\n wdkQuoteSwapInputSchema,\n executeWdkQuoteSwap,\n executeWdkQuoteSwapDemo,\n formatSwapQuoteResult,\n wdkExecuteSwapInputSchema,\n executeWdkExecuteSwap,\n executeWdkExecuteSwapDemo,\n formatExecuteSwapResult,\n // TON bridge tools\n TON_BRIDGE_TOOLS,\n executeTonBridgeTool,\n type TonMcpBridgeConfig,\n // ERC-8004 tools\n ERC8004_TOOL_DEFINITIONS,\n erc8004ResolveAgentInputSchema,\n executeErc8004ResolveAgent,\n formatErc8004ResolveAgentResult,\n erc8004CheckReputationInputSchema,\n executeErc8004CheckReputation,\n formatErc8004CheckReputationResult,\n erc8004VerifyWalletInputSchema,\n executeErc8004VerifyWallet,\n formatErc8004VerifyWalletResult,\n} from '../tools/index.js'\nimport type { T402WDK } from '@t402/wdk'\n\n/**\n * t402 MCP Server\n *\n * Provides payment tools for AI agents via the Model Context Protocol.\n * When a WDK seed phrase is configured, additional wallet management tools are available.\n */\nexport class T402McpServer {\n private server: Server\n private config: McpServerConfig\n private wdk: T402WDK | null = null\n\n constructor(config: McpServerConfig = {}) {\n this.config = config\n this.server = new Server(\n {\n name: 't402',\n version: '1.0.0',\n },\n {\n capabilities: {\n tools: {},\n },\n },\n )\n\n this.setupHandlers()\n }\n\n /**\n * Initialize the WDK instance from seed phrase\n */\n async initWdk(): Promise<void> {\n if (!this.config.seedPhrase) return\n\n try {\n const { T402WDK } = await import('@t402/wdk')\n const rpcUrls: Record<string, string> = {}\n\n if (this.config.rpcUrls) {\n for (const [network, url] of Object.entries(this.config.rpcUrls)) {\n if (url) rpcUrls[network] = url\n }\n }\n\n this.wdk = new T402WDK(this.config.seedPhrase, rpcUrls)\n } catch {\n console.error('Warning: Failed to initialize WDK. WDK tools will not be available.')\n }\n }\n\n /** TON MCP bridge configuration */\n private tonBridgeConfig: TonMcpBridgeConfig | null = null\n\n /**\n * Register TON bridge tools\n *\n * Enables AI agents to use @ton/mcp tools through the t402 MCP server.\n */\n registerTonBridge(config: TonMcpBridgeConfig): void {\n this.tonBridgeConfig = config\n }\n\n /**\n * Get all tool definitions (base + WDK if configured + unified if enabled + TON bridge if registered)\n */\n private getToolDefinitions() {\n const tools = { ...TOOL_DEFINITIONS, ...ERC8004_TOOL_DEFINITIONS }\n if (this.wdk || this.config.demoMode) {\n Object.assign(tools, WDK_TOOL_DEFINITIONS)\n }\n if (this.config.unifiedMode && (this.wdk || this.config.demoMode)) {\n Object.assign(tools, UNIFIED_TOOL_DEFINITIONS)\n }\n if (this.tonBridgeConfig) {\n Object.assign(tools, TON_BRIDGE_TOOLS)\n }\n return tools\n }\n\n /**\n * Set up MCP request handlers\n */\n private setupHandlers(): void {\n // List available tools\n this.server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: Object.values(this.getToolDefinitions()),\n }\n })\n\n // Handle tool calls\n this.server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params\n\n try {\n switch (name) {\n case 't402/getBalance':\n return await this.handleGetBalance(args)\n\n case 't402/getAllBalances':\n return await this.handleGetAllBalances(args)\n\n case 't402/pay':\n return await this.handlePay(args)\n\n case 't402/payGasless':\n return await this.handlePayGasless(args)\n\n case 't402/getBridgeFee':\n return await this.handleGetBridgeFee(args)\n\n case 't402/bridge':\n return await this.handleBridge(args)\n\n // WDK tools\n case 'wdk/getWallet':\n return await this.handleWdkGetWallet(args)\n\n case 'wdk/getBalances':\n return await this.handleWdkGetBalances(args)\n\n case 'wdk/transfer':\n return await this.handleWdkTransfer(args)\n\n case 'wdk/swap':\n return await this.handleWdkSwap(args)\n\n case 't402/autoPay':\n return await this.handleAutoPay(args)\n\n // Unified tools\n case 't402/smartPay':\n return await this.handleSmartPay(args)\n\n case 't402/paymentPlan':\n return await this.handlePaymentPlan(args)\n\n // Price and fee tools\n case 't402/getTokenPrice':\n return await this.handleGetTokenPrice(args)\n\n case 't402/getGasPrice':\n return await this.handleGetGasPrice(args)\n\n case 't402/estimatePaymentFee':\n return await this.handleEstimatePaymentFee(args)\n\n case 't402/compareNetworkFees':\n return await this.handleCompareNetworkFees(args)\n\n // Quote-based tools\n case 't402/quoteBridge':\n return await this.handleQuoteBridge(args)\n\n case 't402/executeBridgeQuote':\n return await this.handleExecuteBridgeQuote(args)\n\n case 'wdk/quoteSwap':\n return await this.handleWdkQuoteSwap(args)\n\n case 'wdk/executeSwap':\n return await this.handleWdkExecuteSwap(args)\n\n // ERC-8004 tools\n case 'erc8004/resolveAgent':\n return await this.handleErc8004ResolveAgent(args)\n\n case 'erc8004/checkReputation':\n return await this.handleErc8004CheckReputation(args)\n\n case 'erc8004/verifyWallet':\n return await this.handleErc8004VerifyWallet(args)\n\n // TON bridge tools\n case 'ton/getBalance':\n case 'ton/transfer':\n case 'ton/getJettonBalance':\n case 'ton/swapJettons':\n case 'ton/getTransactionStatus':\n return await this.handleTonBridgeTool(name, args)\n\n default:\n throw new Error(`Unknown tool: ${name}`)\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return {\n content: [\n {\n type: 'text' as const,\n text: `Error: ${message}`,\n },\n ],\n isError: true,\n }\n }\n })\n }\n\n /**\n * Handle t402/getBalance\n */\n private async handleGetBalance(args: unknown) {\n const input = getBalanceInputSchema.parse(args)\n const result = await executeGetBalance(input, this.config.rpcUrls)\n return {\n content: [\n {\n type: 'text' as const,\n text: formatBalanceResult(result),\n },\n ],\n }\n }\n\n /**\n * Handle t402/getAllBalances\n */\n private async handleGetAllBalances(args: unknown) {\n const input = getAllBalancesInputSchema.parse(args)\n const result = await executeGetAllBalances(input, this.config.rpcUrls)\n return {\n content: [\n {\n type: 'text' as const,\n text: formatAllBalancesResult(result),\n },\n ],\n }\n }\n\n /**\n * Format a confirmation prompt for elicitation\n */\n private formatConfirmation(result: {\n needsConfirmation: true\n summary: string\n details: Record<string, string>\n }) {\n const detailLines = Object.entries(result.details)\n .map(([key, value]) => `- **${key}:** ${value}`)\n .join('\\n')\n return {\n content: [\n {\n type: 'text' as const,\n text: [\n '## Confirmation Required',\n '',\n result.summary,\n '',\n detailLines,\n '',\n '_Call this tool again with `confirmed: true` to execute._',\n ].join('\\n'),\n },\n ],\n }\n }\n\n /**\n * Handle t402/pay\n */\n private async handlePay(args: unknown) {\n if (!this.config.privateKey && !this.config.demoMode) {\n throw new Error(\n 'Private key not configured. Set T402_PRIVATE_KEY environment variable or enable demo mode.',\n )\n }\n\n const input = payInputSchema.parse(args)\n const result = await executePay(input, {\n privateKey: this.config.privateKey || '0x',\n rpcUrl: this.config.rpcUrls?.[input.network as SupportedNetwork],\n demoMode: this.config.demoMode,\n })\n\n if ('needsConfirmation' in result) {\n return this.formatConfirmation(result)\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatPaymentResult(result),\n },\n ],\n }\n }\n\n /**\n * Handle t402/payGasless\n */\n private async handlePayGasless(args: unknown) {\n if (!this.config.privateKey && !this.config.demoMode) {\n throw new Error(\n 'Private key not configured. Set T402_PRIVATE_KEY environment variable or enable demo mode.',\n )\n }\n\n if (!this.config.bundlerUrl && !this.config.demoMode) {\n throw new Error(\n 'Bundler URL not configured. Set T402_BUNDLER_URL environment variable or enable demo mode.',\n )\n }\n\n if (!this.config.paymasterUrl && !this.config.demoMode) {\n throw new Error(\n 'Paymaster URL not configured. Set T402_PAYMASTER_URL environment variable or enable demo mode.',\n )\n }\n\n const input = payGaslessInputSchema.parse(args)\n const result = await executePayGasless(input, {\n privateKey: this.config.privateKey || '0x',\n bundlerUrl: this.config.bundlerUrl || '',\n paymasterUrl: this.config.paymasterUrl || '',\n rpcUrl: this.config.rpcUrls?.[input.network as SupportedNetwork],\n demoMode: this.config.demoMode,\n })\n\n if ('needsConfirmation' in result) {\n return this.formatConfirmation(result)\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatGaslessPaymentResult(result),\n },\n ],\n }\n }\n\n /**\n * Handle t402/getBridgeFee\n */\n private async handleGetBridgeFee(args: unknown) {\n const input = getBridgeFeeInputSchema.parse(args)\n const result = await executeGetBridgeFee(input, this.config.rpcUrls)\n return {\n content: [\n {\n type: 'text' as const,\n text: formatBridgeFeeResult(result),\n },\n ],\n }\n }\n\n /**\n * Handle t402/bridge\n */\n private async handleBridge(args: unknown) {\n if (!this.config.privateKey && !this.config.demoMode) {\n throw new Error(\n 'Private key not configured. Set T402_PRIVATE_KEY environment variable or enable demo mode.',\n )\n }\n\n const input = bridgeInputSchema.parse(args)\n const result = await executeBridge(input, {\n privateKey: this.config.privateKey || '0x',\n rpcUrl: this.config.rpcUrls?.[input.fromChain as SupportedNetwork],\n demoMode: this.config.demoMode,\n })\n\n if ('needsConfirmation' in result) {\n return this.formatConfirmation(result)\n }\n\n return {\n content: [\n {\n type: 'text' as const,\n text: formatBridgeResult(result),\n },\n ],\n }\n }\n\n // ---- WDK Tool Handlers ----\n\n /**\n * Handle wdk/getWallet\n */\n private async handleWdkGetWallet(args: unknown) {\n wdkGetWalletInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeWdkGetWalletDemo()\n : await executeWdkGetWallet({}, this.wdk)\n\n return {\n content: [{ type: 'text' as const, text: formatWdkWalletResult(result) }],\n }\n }\n\n /**\n * Handle wdk/getBalances\n */\n private async handleWdkGetBalances(args: unknown) {\n const input = wdkGetBalancesInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeWdkGetBalancesDemo()\n : await executeWdkGetBalances(input, this.wdk)\n\n return {\n content: [{ type: 'text' as const, text: formatWdkBalancesResult(result) }],\n }\n }\n\n /**\n * Handle wdk/transfer\n */\n private async handleWdkTransfer(args: unknown) {\n const input = wdkTransferInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeWdkTransferDemo(input)\n : await executeWdkTransfer(input, this.wdk)\n\n if ('needsConfirmation' in result) {\n return this.formatConfirmation(result)\n }\n\n return {\n content: [{ type: 'text' as const, text: formatWdkTransferResult(result) }],\n }\n }\n\n /**\n * Handle wdk/swap\n */\n private async handleWdkSwap(args: unknown) {\n const input = wdkSwapInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeWdkSwapDemo(input)\n : await executeWdkSwap(input, this.wdk)\n\n if ('needsConfirmation' in result) {\n return this.formatConfirmation(result)\n }\n\n return {\n content: [{ type: 'text' as const, text: formatWdkSwapResult(result) }],\n }\n }\n\n /**\n * Handle t402/autoPay\n */\n private async handleAutoPay(args: unknown) {\n const input = autoPayInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeAutoPayDemo(input)\n : await executeAutoPay(input, this.wdk)\n\n if ('needsConfirmation' in result) {\n return this.formatConfirmation(result)\n }\n\n return {\n content: [{ type: 'text' as const, text: formatAutoPayResult(result) }],\n }\n }\n\n // ---- Unified Tool Handlers ----\n\n /**\n * Handle t402/smartPay\n */\n private async handleSmartPay(args: unknown) {\n const input = smartPayInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeSmartPayDemo(input)\n : await executeSmartPay(input, this.wdk)\n\n if ('needsConfirmation' in result) {\n return this.formatConfirmation(result)\n }\n\n return {\n content: [{ type: 'text' as const, text: formatSmartPayResult(result) }],\n }\n }\n\n /**\n * Handle t402/paymentPlan\n */\n private async handlePaymentPlan(args: unknown) {\n const input = paymentPlanInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executePaymentPlanDemo(input)\n : await executePaymentPlan(input, this.wdk)\n\n return {\n content: [{ type: 'text' as const, text: formatPaymentPlanResult(result) }],\n }\n }\n\n // ---- Price and Fee Tool Handlers ----\n\n /**\n * Handle t402/getTokenPrice\n */\n private async handleGetTokenPrice(args: unknown) {\n const input = getTokenPriceInputSchema.parse(args)\n const result = await executeGetTokenPrice(input, { demoMode: this.config.demoMode })\n return {\n content: [{ type: 'text' as const, text: formatTokenPriceResult(result) }],\n }\n }\n\n /**\n * Handle t402/getGasPrice\n */\n private async handleGetGasPrice(args: unknown) {\n const input = getGasPriceInputSchema.parse(args)\n const result = await executeGetGasPrice(input, {\n rpcUrl: this.config.rpcUrls?.[input.network as SupportedNetwork],\n demoMode: this.config.demoMode,\n })\n return {\n content: [{ type: 'text' as const, text: formatGasPriceResult(result) }],\n }\n }\n\n /**\n * Handle t402/estimatePaymentFee\n */\n private async handleEstimatePaymentFee(args: unknown) {\n const input = estimatePaymentFeeInputSchema.parse(args)\n const result = await executeEstimatePaymentFee(input, {\n rpcUrl: this.config.rpcUrls?.[input.network as SupportedNetwork],\n demoMode: this.config.demoMode,\n })\n return {\n content: [{ type: 'text' as const, text: formatPaymentFeeEstimate(result) }],\n }\n }\n\n /**\n * Handle t402/compareNetworkFees\n */\n private async handleCompareNetworkFees(args: unknown) {\n const input = compareNetworkFeesInputSchema.parse(args)\n const result = await executeCompareNetworkFees(input, {\n rpcUrls: this.config.rpcUrls,\n demoMode: this.config.demoMode,\n })\n return {\n content: [{ type: 'text' as const, text: formatNetworkFeeComparison(result) }],\n }\n }\n\n // ---- Quote-based Tool Handlers ----\n\n /**\n * Handle t402/quoteBridge\n */\n private async handleQuoteBridge(args: unknown) {\n const input = quoteBridgeInputSchema.parse(args)\n\n const result = this.config.demoMode\n ? executeQuoteBridgeDemo(input)\n : await executeQuoteBridge(input, this.config.rpcUrls)\n\n return {\n content: [{ type: 'text' as const, text: formatBridgeQuoteResult(result) }],\n }\n }\n\n /**\n * Handle t402/executeBridgeQuote\n */\n private async handleExecuteBridgeQuote(args: unknown) {\n if (!this.config.privateKey && !this.config.demoMode) {\n throw new Error(\n 'Private key not configured. Set T402_PRIVATE_KEY environment variable or enable demo mode.',\n )\n }\n\n const input = executeBridgeFromQuoteInputSchema.parse(args)\n\n const result = this.config.demoMode\n ? executeExecuteBridgeFromQuoteDemo(input)\n : await executeExecuteBridgeFromQuote(input, {\n privateKey: this.config.privateKey || '0x',\n demoMode: this.config.demoMode,\n })\n\n if ('needsConfirmation' in result) {\n return this.formatConfirmation(result)\n }\n\n return {\n content: [{ type: 'text' as const, text: formatExecuteBridgeFromQuoteResult(result) }],\n }\n }\n\n /**\n * Handle wdk/quoteSwap\n */\n private async handleWdkQuoteSwap(args: unknown) {\n const input = wdkQuoteSwapInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeWdkQuoteSwapDemo(input)\n : await executeWdkQuoteSwap(input, this.wdk)\n\n return {\n content: [{ type: 'text' as const, text: formatSwapQuoteResult(result) }],\n }\n }\n\n /**\n * Handle wdk/executeSwap\n */\n private async handleWdkExecuteSwap(args: unknown) {\n const input = wdkExecuteSwapInputSchema.parse(args)\n\n const result =\n this.config.demoMode || !this.wdk\n ? executeWdkExecuteSwapDemo(input)\n : await executeWdkExecuteSwap(input, this.wdk)\n\n if ('needsConfirmation' in result) {\n return this.formatConfirmation(result)\n }\n\n return {\n content: [{ type: 'text' as const, text: formatExecuteSwapResult(result) }],\n }\n }\n\n // ---- ERC-8004 Tool Handlers ----\n\n /**\n * Handle erc8004/resolveAgent\n */\n private async handleErc8004ResolveAgent(args: unknown) {\n const input = erc8004ResolveAgentInputSchema.parse(args)\n const result = await executeErc8004ResolveAgent(input, this.config.rpcUrls)\n return {\n content: [{ type: 'text' as const, text: formatErc8004ResolveAgentResult(result) }],\n }\n }\n\n /**\n * Handle erc8004/checkReputation\n */\n private async handleErc8004CheckReputation(args: unknown) {\n const input = erc8004CheckReputationInputSchema.parse(args)\n const result = await executeErc8004CheckReputation(input, this.config.rpcUrls)\n return {\n content: [{ type: 'text' as const, text: formatErc8004CheckReputationResult(result) }],\n }\n }\n\n /**\n * Handle erc8004/verifyWallet\n */\n private async handleErc8004VerifyWallet(args: unknown) {\n const input = erc8004VerifyWalletInputSchema.parse(args)\n const result = await executeErc8004VerifyWallet(input, this.config.rpcUrls)\n return {\n content: [{ type: 'text' as const, text: formatErc8004VerifyWalletResult(result) }],\n }\n }\n\n // ---- TON Bridge Tool Handler ----\n\n /**\n * Handle TON bridge tool calls\n */\n private async handleTonBridgeTool(name: string, args: unknown) {\n if (!this.tonBridgeConfig) {\n throw new Error('TON bridge not configured. Call registerTonBridge() to enable TON tools.')\n }\n\n return executeTonBridgeTool(name, (args ?? {}) as Record<string, unknown>, this.tonBridgeConfig)\n }\n\n /**\n * Start the server using stdio transport\n */\n async run(): Promise<void> {\n // Initialize WDK if seed phrase is configured\n await this.initWdk()\n\n const transport = new StdioServerTransport()\n await this.server.connect(transport)\n console.error('t402 MCP Server running on stdio')\n }\n}\n\n/**\n * Create a new t402 MCP server instance\n */\nexport function createT402McpServer(config?: McpServerConfig): T402McpServer {\n return new T402McpServer(config)\n}\n\n/**\n * Load configuration from environment variables\n */\nexport function loadConfigFromEnv(): McpServerConfig {\n const config: McpServerConfig = {}\n\n // Private key\n if (process.env.T402_PRIVATE_KEY) {\n config.privateKey = process.env.T402_PRIVATE_KEY\n }\n\n // Demo mode\n if (process.env.T402_DEMO_MODE === 'true') {\n config.demoMode = true\n }\n\n // ERC-4337 configuration\n if (process.env.T402_BUNDLER_URL) {\n config.bundlerUrl = process.env.T402_BUNDLER_URL\n }\n if (process.env.T402_PAYMASTER_URL) {\n config.paymasterUrl = process.env.T402_PAYMASTER_URL\n }\n\n // WDK configuration\n if (process.env.T402_WDK_SEED_PHRASE) {\n config.seedPhrase = process.env.T402_WDK_SEED_PHRASE\n }\n if (process.env.T402_WDK_CHAINS) {\n config.wdkChains = process.env.T402_WDK_CHAINS.split(',').map((c) => c.trim())\n }\n\n // Unified mode\n if (process.env.T402_UNIFIED_MODE === 'true') {\n config.unifiedMode = true\n }\n\n // Custom RPC URLs\n const rpcUrls: Partial<Record<SupportedNetwork, string>> = {}\n const networks: SupportedNetwork[] = [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ]\n\n for (const network of networks) {\n const envVar = `T402_RPC_${network.toUpperCase()}`\n if (process.env[envVar]) {\n rpcUrls[network] = process.env[envVar]\n }\n }\n\n if (Object.keys(rpcUrls).length > 0) {\n config.rpcUrls = rpcUrls\n }\n\n // TON MCP bridge configuration\n if (process.env.T402_TON_MCP_ENDPOINT) {\n config.tonMcpEndpoint = process.env.T402_TON_MCP_ENDPOINT\n }\n if (process.env.T402_TON_API_KEY) {\n config.tonApiKey = process.env.T402_TON_API_KEY\n }\n\n return config\n}\n","/**\n * t402/getBalance - Get token balance for a specific network\n */\n\nimport { z } from 'zod'\nimport { createPublicClient, http, formatEther, formatUnits, type Address } from 'viem'\nimport * as chains from 'viem/chains'\nimport type { SupportedNetwork, TokenBalance, ChainBalance } from '../types.js'\nimport {\n CHAIN_IDS,\n NATIVE_SYMBOLS,\n DEFAULT_RPC_URLS,\n USDC_ADDRESSES,\n USDT_ADDRESSES,\n USDT0_ADDRESSES,\n ERC20_ABI,\n} from '../constants.js'\n\n/**\n * Input schema for getBalance tool\n */\nexport const getBalanceInputSchema = z.object({\n network: z\n .enum([\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ])\n .describe('Blockchain network to check balance on'),\n address: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Wallet address to check balance for'),\n})\n\nexport type GetBalanceInput = z.infer<typeof getBalanceInputSchema>\n\n/**\n * Get the viem chain configuration for a network\n */\nfunction getViemChain(network: SupportedNetwork) {\n switch (network) {\n case 'ethereum':\n return chains.mainnet\n case 'base':\n return chains.base\n case 'arbitrum':\n return chains.arbitrum\n case 'optimism':\n return chains.optimism\n case 'polygon':\n return chains.polygon\n case 'avalanche':\n return chains.avalanche\n case 'ink':\n return chains.ink\n case 'berachain':\n return chains.berachain\n case 'unichain':\n return chains.unichain\n default:\n return chains.mainnet\n }\n}\n\n/**\n * Get token balance for an address\n */\nasync function getTokenBalance(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client: any,\n tokenAddress: Address,\n walletAddress: Address,\n): Promise<TokenBalance | null> {\n try {\n const [balance, decimals, symbol] = await Promise.all([\n client.readContract({\n address: tokenAddress,\n abi: ERC20_ABI,\n functionName: 'balanceOf',\n args: [walletAddress],\n }) as Promise<bigint>,\n client.readContract({\n address: tokenAddress,\n abi: ERC20_ABI,\n functionName: 'decimals',\n }) as Promise<number>,\n client.readContract({\n address: tokenAddress,\n abi: ERC20_ABI,\n functionName: 'symbol',\n }) as Promise<string>,\n ])\n\n return {\n symbol,\n address: tokenAddress,\n balance: balance.toString(),\n formatted: formatUnits(balance, decimals),\n decimals,\n }\n } catch {\n return null\n }\n}\n\n/**\n * Execute getBalance tool\n */\nexport async function executeGetBalance(\n input: GetBalanceInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<ChainBalance> {\n const { network, address } = input\n const walletAddress = address as Address\n\n const rpcUrl = rpcUrls?.[network] || DEFAULT_RPC_URLS[network]\n const chain = getViemChain(network)\n\n const client = createPublicClient({\n chain,\n transport: http(rpcUrl),\n })\n\n // Get native balance\n const nativeBalance = await client.getBalance({ address: walletAddress })\n\n // Get token balances\n const tokenAddresses: { token: Address; expected: string }[] = []\n\n if (USDC_ADDRESSES[network]) {\n tokenAddresses.push({ token: USDC_ADDRESSES[network]!, expected: 'USDC' })\n }\n if (USDT_ADDRESSES[network]) {\n tokenAddresses.push({ token: USDT_ADDRESSES[network]!, expected: 'USDT' })\n }\n if (USDT0_ADDRESSES[network]) {\n tokenAddresses.push({ token: USDT0_ADDRESSES[network]!, expected: 'USDT0' })\n }\n\n const tokenBalances = await Promise.all(\n tokenAddresses.map(({ token }) => getTokenBalance(client, token, walletAddress)),\n )\n\n const tokens = tokenBalances.filter((t): t is TokenBalance => t !== null)\n\n return {\n network,\n chainId: CHAIN_IDS[network],\n native: {\n symbol: NATIVE_SYMBOLS[network],\n balance: nativeBalance.toString(),\n formatted: formatEther(nativeBalance),\n },\n tokens,\n }\n}\n\n/**\n * Format balance result for display\n */\nexport function formatBalanceResult(balance: ChainBalance): string {\n const lines: string[] = [\n `## Balance on ${balance.network} (Chain ID: ${balance.chainId})`,\n '',\n `### Native Token`,\n `- ${balance.native.symbol}: ${balance.native.formatted}`,\n '',\n ]\n\n if (balance.tokens.length > 0) {\n lines.push('### Stablecoins')\n for (const token of balance.tokens) {\n lines.push(`- ${token.symbol}: ${token.formatted}`)\n }\n } else {\n lines.push('_No stablecoin balances found_')\n }\n\n return lines.join('\\n')\n}\n","/**\n * Constants and network configurations for t402 MCP Server\n */\n\nimport type { Address } from 'viem'\nimport type { SupportedNetwork } from './types.js'\n\n/**\n * Chain IDs by network\n */\nexport const CHAIN_IDS: Record<SupportedNetwork, number> = {\n ethereum: 1,\n base: 8453,\n arbitrum: 42161,\n optimism: 10,\n polygon: 137,\n avalanche: 43114,\n ink: 57073,\n berachain: 80094,\n unichain: 130,\n}\n\n/**\n * Native token symbols by network\n */\nexport const NATIVE_SYMBOLS: Record<SupportedNetwork, string> = {\n ethereum: 'ETH',\n base: 'ETH',\n arbitrum: 'ETH',\n optimism: 'ETH',\n polygon: 'MATIC',\n avalanche: 'AVAX',\n ink: 'ETH',\n berachain: 'BERA',\n unichain: 'ETH',\n}\n\n/**\n * Block explorer URLs by network\n */\nexport const EXPLORER_URLS: Record<SupportedNetwork, string> = {\n ethereum: 'https://etherscan.io',\n base: 'https://basescan.org',\n arbitrum: 'https://arbiscan.io',\n optimism: 'https://optimistic.etherscan.io',\n polygon: 'https://polygonscan.com',\n avalanche: 'https://snowtrace.io',\n ink: 'https://explorer.inkonchain.com',\n berachain: 'https://berascan.com',\n unichain: 'https://unichain.blockscout.com',\n}\n\n/**\n * Default RPC URLs by network (public endpoints)\n */\nexport const DEFAULT_RPC_URLS: Record<SupportedNetwork, string> = {\n ethereum: 'https://eth.llamarpc.com',\n base: 'https://mainnet.base.org',\n arbitrum: 'https://arb1.arbitrum.io/rpc',\n optimism: 'https://mainnet.optimism.io',\n polygon: 'https://polygon-rpc.com',\n avalanche: 'https://api.avax.network/ext/bc/C/rpc',\n ink: 'https://rpc-gel.inkonchain.com',\n berachain: 'https://rpc.berachain.com',\n unichain: 'https://mainnet.unichain.org',\n}\n\n/**\n * USDC contract addresses by network\n */\nexport const USDC_ADDRESSES: Partial<Record<SupportedNetwork, Address>> = {\n ethereum: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',\n base: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n arbitrum: '0xaf88d065e77c8cC2239327C5EDb3A432268e5831',\n optimism: '0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85',\n polygon: '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359',\n avalanche: '0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E',\n}\n\n/**\n * USDT contract addresses by network\n */\nexport const USDT_ADDRESSES: Partial<Record<SupportedNetwork, Address>> = {\n ethereum: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n arbitrum: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',\n polygon: '0xc2132D05D31c914a87C6611C10748AEb04B58e8F',\n avalanche: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7',\n optimism: '0x94b008aA00579c1307B0EF2c499aD98a8ce58e58',\n}\n\n/**\n * USDT0 (LayerZero OFT) contract addresses by network\n */\nexport const USDT0_ADDRESSES: Partial<Record<SupportedNetwork, Address>> = {\n ethereum: '0x6C96dE32CEa08842dcc4058c14d3aaAD7Fa41dee',\n arbitrum: '0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9',\n ink: '0x0200C29006150606B650577BBE7B6248F58470c1',\n berachain: '0x779Ded0c9e1022225f8E0630b35a9b54bE713736',\n unichain: '0x9151434b16b9763660705744891fA906F660EcC5',\n}\n\n/**\n * Chains that support USDT0 bridging\n */\nexport const BRIDGEABLE_CHAINS: SupportedNetwork[] = [\n 'ethereum',\n 'arbitrum',\n 'ink',\n 'berachain',\n 'unichain',\n]\n\n/**\n * ERC20 ABI for balance and transfer operations\n */\nexport const ERC20_ABI = [\n {\n name: 'balanceOf',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'account', type: 'address' }],\n outputs: [{ name: '', type: 'uint256' }],\n },\n {\n name: 'decimals',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ name: '', type: 'uint8' }],\n },\n {\n name: 'symbol',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ name: '', type: 'string' }],\n },\n {\n name: 'transfer',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'to', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ name: '', type: 'bool' }],\n },\n {\n name: 'approve',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'spender', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ name: '', type: 'bool' }],\n },\n {\n name: 'allowance',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n ],\n outputs: [{ name: '', type: 'uint256' }],\n },\n] as const\n\n/**\n * Get explorer URL for a transaction\n */\nexport function getExplorerTxUrl(network: SupportedNetwork, txHash: string): string {\n return `${EXPLORER_URLS[network]}/tx/${txHash}`\n}\n\n/**\n * Get LayerZero Scan URL for a message\n */\nexport function getLayerZeroScanUrl(messageGuid: string): string {\n return `https://layerzeroscan.com/tx/${messageGuid}`\n}\n\n/**\n * Check if a network supports a specific token\n */\nexport function supportsToken(\n network: SupportedNetwork,\n token: 'USDC' | 'USDT' | 'USDT0',\n): boolean {\n switch (token) {\n case 'USDC':\n return network in USDC_ADDRESSES\n case 'USDT':\n return network in USDT_ADDRESSES\n case 'USDT0':\n return network in USDT0_ADDRESSES\n default:\n return false\n }\n}\n\n/**\n * Get token address for a network\n */\nexport function getTokenAddress(\n network: SupportedNetwork,\n token: 'USDC' | 'USDT' | 'USDT0',\n): Address | undefined {\n switch (token) {\n case 'USDC':\n return USDC_ADDRESSES[network]\n case 'USDT':\n return USDT_ADDRESSES[network]\n case 'USDT0':\n return USDT0_ADDRESSES[network]\n default:\n return undefined\n }\n}\n\n/**\n * Format token amount for display\n */\nexport function formatTokenAmount(amount: bigint, decimals: number, symbol: string): string {\n const divisor = BigInt(10 ** decimals)\n const wholePart = amount / divisor\n const fractionalPart = amount % divisor\n const fractionalStr = fractionalPart.toString().padStart(decimals, '0')\n const trimmedFractional = fractionalStr.replace(/0+$/, '') || '0'\n\n if (trimmedFractional === '0') {\n return `${wholePart} ${symbol}`\n }\n return `${wholePart}.${trimmedFractional} ${symbol}`\n}\n\n/**\n * Parse token amount from string to bigint\n */\nexport function parseTokenAmount(amount: string, decimals: number): bigint {\n const [wholePart, fractionalPart = ''] = amount.split('.')\n const paddedFractional = fractionalPart.padEnd(decimals, '0').slice(0, decimals)\n return BigInt(wholePart + paddedFractional)\n}\n","/**\n * t402/getAllBalances - Get token balances across all supported networks\n */\n\nimport { z } from 'zod'\nimport type { SupportedNetwork, ChainBalance } from '../types.js'\nimport { executeGetBalance } from './getBalance.js'\n\n/**\n * Input schema for getAllBalances tool\n */\nexport const getAllBalancesInputSchema = z.object({\n address: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Wallet address to check balances for'),\n networks: z\n .array(\n z.enum([\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ]),\n )\n .optional()\n .describe(\n 'Optional list of networks to check. If not provided, checks all supported networks.',\n ),\n})\n\nexport type GetAllBalancesInput = z.infer<typeof getAllBalancesInputSchema>\n\n/**\n * All supported networks\n */\nconst ALL_NETWORKS: SupportedNetwork[] = [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n]\n\n/**\n * Result of getAllBalances\n */\nexport interface AllBalancesResult {\n address: string\n balances: ChainBalance[]\n totalUsdcBalance: string\n totalUsdtBalance: string\n summary: string\n}\n\n/**\n * Execute getAllBalances tool\n */\nexport async function executeGetAllBalances(\n input: GetAllBalancesInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<AllBalancesResult> {\n const { address, networks = ALL_NETWORKS } = input\n\n // Fetch balances from all networks in parallel\n const balancePromises = networks.map((network) =>\n executeGetBalance({ network, address }, rpcUrls).catch((error) => {\n console.error(`Failed to fetch balance for ${network}:`, error)\n return null\n }),\n )\n\n const results = await Promise.all(balancePromises)\n const balances = results.filter((b): b is ChainBalance => b !== null)\n\n // Calculate total stablecoin balances\n let totalUsdc = 0n\n let totalUsdt = 0n\n\n for (const balance of balances) {\n for (const token of balance.tokens) {\n if (token.symbol === 'USDC') {\n totalUsdc += BigInt(token.balance)\n } else if (token.symbol === 'USDT' || token.symbol === 'USDT0') {\n totalUsdt += BigInt(token.balance)\n }\n }\n }\n\n // Format totals (assuming 6 decimals for USDC/USDT)\n const formatTotal = (amount: bigint): string => {\n const divisor = BigInt(10 ** 6)\n const whole = amount / divisor\n const fraction = amount % divisor\n const fractionStr = fraction.toString().padStart(6, '0').replace(/0+$/, '')\n return fractionStr ? `${whole}.${fractionStr}` : whole.toString()\n }\n\n const totalUsdcFormatted = formatTotal(totalUsdc)\n const totalUsdtFormatted = formatTotal(totalUsdt)\n\n // Create summary\n const chainsWithBalance = balances.filter(\n (b) => b.tokens.some((t) => BigInt(t.balance) > 0n) || BigInt(b.native.balance) > 0n,\n )\n\n const summary = [\n `Found balances on ${chainsWithBalance.length} of ${balances.length} networks checked.`,\n `Total USDC: ${totalUsdcFormatted}`,\n `Total USDT: ${totalUsdtFormatted}`,\n ].join(' ')\n\n return {\n address,\n balances,\n totalUsdcBalance: totalUsdcFormatted,\n totalUsdtBalance: totalUsdtFormatted,\n summary,\n }\n}\n\n/**\n * Format all balances result for display\n */\nexport function formatAllBalancesResult(result: AllBalancesResult): string {\n const lines: string[] = [\n `## Multi-Chain Balance Summary`,\n `**Address:** \\`${result.address}\\``,\n '',\n `### Totals`,\n `- **Total USDC:** ${result.totalUsdcBalance}`,\n `- **Total USDT:** ${result.totalUsdtBalance}`,\n '',\n `### By Network`,\n '',\n ]\n\n for (const balance of result.balances) {\n const hasBalance =\n balance.tokens.some((t) => BigInt(t.balance) > 0n) || BigInt(balance.native.balance) > 0n\n\n if (!hasBalance) continue\n\n lines.push(`#### ${balance.network}`)\n lines.push(`- ${balance.native.symbol}: ${balance.native.formatted}`)\n for (const token of balance.tokens) {\n if (BigInt(token.balance) > 0n) {\n lines.push(`- ${token.symbol}: ${token.formatted}`)\n }\n }\n lines.push('')\n }\n\n // List networks with no balance\n const emptyNetworks = result.balances.filter(\n (b) => !b.tokens.some((t) => BigInt(t.balance) > 0n) && BigInt(b.native.balance) === 0n,\n )\n\n if (emptyNetworks.length > 0) {\n lines.push(`_No balance on: ${emptyNetworks.map((n) => n.network).join(', ')}_`)\n }\n\n return lines.join('\\n')\n}\n","/**\n * t402/pay - Execute a payment on a specific network\n */\n\nimport { z } from 'zod'\nimport { createPublicClient, createWalletClient, http, parseUnits, type Address } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport * as chains from 'viem/chains'\nimport type { SupportedNetwork, PaymentResult } from '../types.js'\nimport {\n DEFAULT_RPC_URLS,\n ERC20_ABI,\n getTokenAddress,\n getExplorerTxUrl,\n supportsToken,\n} from '../constants.js'\n\n/**\n * Input schema for pay tool\n */\nexport const payInputSchema = z.object({\n to: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Recipient address'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount to pay (e.g., '10.50' for 10.50 USDC)\"),\n token: z.enum(['USDC', 'USDT', 'USDT0']).describe('Token to use for payment'),\n network: z\n .enum([\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ])\n .describe('Network to execute payment on'),\n memo: z.string().optional().describe('Optional memo/reference for the payment'),\n confirmed: z\n .boolean()\n .optional()\n .describe('Set to true to confirm and execute this payment'),\n})\n\nexport type PayInput = z.infer<typeof payInputSchema>\n\n/**\n * Get the viem chain configuration for a network\n */\nfunction getViemChain(network: SupportedNetwork) {\n switch (network) {\n case 'ethereum':\n return chains.mainnet\n case 'base':\n return chains.base\n case 'arbitrum':\n return chains.arbitrum\n case 'optimism':\n return chains.optimism\n case 'polygon':\n return chains.polygon\n case 'avalanche':\n return chains.avalanche\n case 'ink':\n return chains.ink\n case 'berachain':\n return chains.berachain\n case 'unichain':\n return chains.unichain\n default:\n return chains.mainnet\n }\n}\n\n/**\n * Options for executing payment\n */\nexport interface PayOptions {\n /** Private key for signing (hex with 0x prefix) */\n privateKey: string\n /** Custom RPC URL */\n rpcUrl?: string\n /** Demo mode - simulate without executing */\n demoMode?: boolean\n}\n\n/**\n * Execute pay tool\n */\nexport async function executePay(\n input: PayInput,\n options: PayOptions,\n): Promise<PaymentResult | { needsConfirmation: true; summary: string; details: Record<string, string> }> {\n const { to, amount, token, network, memo: _memo } = input\n const { privateKey, rpcUrl, demoMode } = options\n\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Send ${amount} ${token} on ${network} to ${to}`,\n details: { to, amount, token, network },\n }\n }\n\n // Validate token support on network\n if (!supportsToken(network, token)) {\n throw new Error(`Token ${token} is not supported on ${network}`)\n }\n\n const tokenAddress = getTokenAddress(network, token)\n if (!tokenAddress) {\n throw new Error(`Could not find ${token} address for ${network}`)\n }\n\n // Parse amount (USDC/USDT use 6 decimals)\n const decimals = 6\n const amountBigInt = parseUnits(amount, decimals)\n\n // Demo mode - return simulated result\n if (demoMode) {\n const fakeTxHash = `0x${'0'.repeat(64)}` as `0x${string}`\n return {\n txHash: fakeTxHash,\n network,\n amount,\n token,\n to: to as Address,\n explorerUrl: getExplorerTxUrl(network, fakeTxHash),\n }\n }\n\n // Create clients\n const chain = getViemChain(network)\n const transport = http(rpcUrl || DEFAULT_RPC_URLS[network])\n\n const account = privateKeyToAccount(privateKey as `0x${string}`)\n\n const publicClient = createPublicClient({\n chain,\n transport,\n })\n\n const walletClient = createWalletClient({\n account,\n chain,\n transport,\n })\n\n // Check balance\n const balance = (await publicClient.readContract({\n address: tokenAddress,\n abi: ERC20_ABI,\n functionName: 'balanceOf',\n args: [account.address],\n })) as bigint\n\n if (balance < amountBigInt) {\n throw new Error(\n `Insufficient ${token} balance. Have: ${balance.toString()}, Need: ${amountBigInt.toString()}`,\n )\n }\n\n // Execute transfer\n const hash = await walletClient.writeContract({\n address: tokenAddress,\n abi: ERC20_ABI,\n functionName: 'transfer',\n args: [to as Address, amountBigInt],\n })\n\n // Wait for confirmation\n const receipt = await publicClient.waitForTransactionReceipt({ hash })\n\n if (receipt.status !== 'success') {\n throw new Error(`Transaction failed: ${hash}`)\n }\n\n return {\n txHash: hash,\n network,\n amount,\n token,\n to: to as Address,\n explorerUrl: getExplorerTxUrl(network, hash),\n }\n}\n\n/**\n * Format payment result for display\n */\nexport function formatPaymentResult(result: PaymentResult): string {\n return [\n `## Payment Successful`,\n '',\n `- **Amount:** ${result.amount} ${result.token}`,\n `- **To:** \\`${result.to}\\``,\n `- **Network:** ${result.network}`,\n `- **Transaction:** \\`${result.txHash}\\``,\n '',\n `[View on Explorer](${result.explorerUrl})`,\n ].join('\\n')\n}\n","/**\n * t402/payGasless - Execute a gasless payment using ERC-4337\n */\n\nimport { z } from 'zod'\nimport { createPublicClient, http, parseUnits, encodeFunctionData, type Address } from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport * as chains from 'viem/chains'\nimport type { SupportedNetwork, GaslessPaymentResult } from '../types.js'\nimport {\n DEFAULT_RPC_URLS,\n ERC20_ABI,\n getTokenAddress,\n getExplorerTxUrl,\n supportsToken,\n} from '../constants.js'\n\n/**\n * Input schema for payGasless tool\n */\nexport const payGaslessInputSchema = z.object({\n to: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Recipient address'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount to pay (e.g., '10.50' for 10.50 USDC)\"),\n token: z.enum(['USDC', 'USDT', 'USDT0']).describe('Token to use for payment'),\n network: z\n .enum(['ethereum', 'base', 'arbitrum', 'optimism', 'polygon', 'avalanche'])\n .describe('Network to execute gasless payment on (must support ERC-4337)'),\n confirmed: z\n .boolean()\n .optional()\n .describe('Set to true to confirm and execute this payment'),\n})\n\nexport type PayGaslessInput = z.infer<typeof payGaslessInputSchema>\n\n/**\n * Networks that support ERC-4337 gasless transactions\n */\nexport const GASLESS_SUPPORTED_NETWORKS: SupportedNetwork[] = [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n]\n\n/**\n * Get the viem chain configuration for a network\n */\nfunction getViemChain(network: SupportedNetwork) {\n switch (network) {\n case 'ethereum':\n return chains.mainnet\n case 'base':\n return chains.base\n case 'arbitrum':\n return chains.arbitrum\n case 'optimism':\n return chains.optimism\n case 'polygon':\n return chains.polygon\n case 'avalanche':\n return chains.avalanche\n case 'ink':\n return chains.ink\n case 'berachain':\n return chains.berachain\n case 'unichain':\n return chains.unichain\n default:\n return chains.mainnet\n }\n}\n\n/**\n * Options for executing gasless payment\n */\nexport interface PayGaslessOptions {\n /** Private key for signing (hex with 0x prefix) */\n privateKey: string\n /** Bundler URL for ERC-4337 */\n bundlerUrl: string\n /** Paymaster URL for sponsoring gas */\n paymasterUrl: string\n /** Custom RPC URL */\n rpcUrl?: string\n /** Demo mode - simulate without executing */\n demoMode?: boolean\n}\n\n/**\n * User operation structure (simplified)\n */\ninterface UserOperation {\n sender: Address\n nonce: bigint\n initCode: `0x${string}`\n callData: `0x${string}`\n callGasLimit: bigint\n verificationGasLimit: bigint\n preVerificationGas: bigint\n maxFeePerGas: bigint\n maxPriorityFeePerGas: bigint\n paymasterAndData: `0x${string}`\n signature: `0x${string}`\n}\n\n/**\n * Execute payGasless tool\n */\nexport async function executePayGasless(\n input: PayGaslessInput,\n options: PayGaslessOptions,\n): Promise<GaslessPaymentResult | { needsConfirmation: true; summary: string; details: Record<string, string> }> {\n const { to, amount, token, network } = input\n const { privateKey, bundlerUrl, paymasterUrl: _paymasterUrl, rpcUrl, demoMode } = options\n\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Send ${amount} ${token} gasless on ${network} to ${to}`,\n details: { to, amount, token, network },\n }\n }\n\n // Validate network supports gasless\n if (!GASLESS_SUPPORTED_NETWORKS.includes(network)) {\n throw new Error(\n `Network ${network} does not support ERC-4337 gasless transactions. Supported: ${GASLESS_SUPPORTED_NETWORKS.join(', ')}`,\n )\n }\n\n // Validate token support on network\n if (!supportsToken(network, token)) {\n throw new Error(`Token ${token} is not supported on ${network}`)\n }\n\n const tokenAddress = getTokenAddress(network, token)\n if (!tokenAddress) {\n throw new Error(`Could not find ${token} address for ${network}`)\n }\n\n // Parse amount (USDC/USDT use 6 decimals)\n const decimals = 6\n const amountBigInt = parseUnits(amount, decimals)\n\n // Demo mode - return simulated result\n if (demoMode) {\n const fakeTxHash = `0x${'1'.repeat(64)}` as `0x${string}`\n const fakeUserOpHash = `0x${'2'.repeat(64)}` as `0x${string}`\n return {\n txHash: fakeTxHash,\n userOpHash: fakeUserOpHash,\n network,\n amount,\n token,\n to: to as Address,\n explorerUrl: getExplorerTxUrl(network, fakeTxHash),\n paymaster: 'demo-paymaster',\n }\n }\n\n // Create clients\n const chain = getViemChain(network)\n const transport = http(rpcUrl || DEFAULT_RPC_URLS[network])\n\n const account = privateKeyToAccount(privateKey as `0x${string}`)\n\n const publicClient = createPublicClient({\n chain,\n transport,\n })\n\n // Encode the transfer call data\n const callData = encodeFunctionData({\n abi: ERC20_ABI,\n functionName: 'transfer',\n args: [to as Address, amountBigInt],\n })\n\n // Build user operation\n // Note: In production, this would integrate with a full ERC-4337 bundler\n const nonce = await publicClient.getTransactionCount({\n address: account.address,\n })\n\n const gasPrice = await publicClient.getGasPrice()\n\n const userOp: UserOperation = {\n sender: account.address,\n nonce: BigInt(nonce),\n initCode: '0x',\n callData: callData as `0x${string}`,\n callGasLimit: 100000n,\n verificationGasLimit: 100000n,\n preVerificationGas: 50000n,\n maxFeePerGas: gasPrice,\n maxPriorityFeePerGas: gasPrice / 10n,\n paymasterAndData: '0x', // Would be filled by paymaster\n signature: '0x',\n }\n\n // In production, this would:\n // 1. Request paymaster sponsorship from paymasterUrl\n // 2. Sign the user operation\n // 3. Submit to bundler at bundlerUrl\n // 4. Wait for user operation to be included\n\n // For now, send as regular transaction with sponsorship note\n const response = await fetch(bundlerUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'eth_sendUserOperation',\n params: [userOp, chain.id],\n }),\n })\n\n if (!response.ok) {\n throw new Error(`Bundler request failed: ${response.statusText}`)\n }\n\n const result = (await response.json()) as {\n error?: { message: string }\n result?: string\n }\n\n if (result.error) {\n throw new Error(`Bundler error: ${result.error.message}`)\n }\n\n const userOpHash = result.result as string\n\n // Poll for receipt\n let receipt: { transactionHash: string } | null = null\n for (let i = 0; i < 30; i++) {\n const receiptResponse = await fetch(bundlerUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'eth_getUserOperationReceipt',\n params: [userOpHash],\n }),\n })\n\n const receiptResult = (await receiptResponse.json()) as {\n result?: { transactionHash: string }\n }\n if (receiptResult.result) {\n receipt = receiptResult.result\n break\n }\n\n await new Promise((resolve) => setTimeout(resolve, 2000))\n }\n\n if (!receipt) {\n throw new Error('Timeout waiting for user operation receipt')\n }\n\n return {\n txHash: receipt.transactionHash,\n userOpHash,\n network,\n amount,\n token,\n to: to as Address,\n explorerUrl: getExplorerTxUrl(network, receipt.transactionHash),\n }\n}\n\n/**\n * Format gasless payment result for display\n */\nexport function formatGaslessPaymentResult(result: GaslessPaymentResult): string {\n const lines = [\n `## Gasless Payment Successful`,\n '',\n `- **Amount:** ${result.amount} ${result.token}`,\n `- **To:** \\`${result.to}\\``,\n `- **Network:** ${result.network}`,\n `- **Transaction:** \\`${result.txHash}\\``,\n `- **UserOp Hash:** \\`${result.userOpHash}\\``,\n ]\n\n if (result.paymaster) {\n lines.push(`- **Paymaster:** ${result.paymaster}`)\n }\n\n lines.push('')\n lines.push(`[View on Explorer](${result.explorerUrl})`)\n lines.push('')\n lines.push('_Gas fees were sponsored - no ETH was deducted from your wallet._')\n\n return lines.join('\\n')\n}\n","/**\n * t402/getBridgeFee - Get fee quote for bridging USDT0 between chains\n */\n\nimport { z } from 'zod'\nimport { createPublicClient, http, formatEther, type Address } from 'viem'\nimport * as chains from 'viem/chains'\nimport type { SupportedNetwork, BridgeFeeQuote } from '../types.js'\nimport {\n DEFAULT_RPC_URLS,\n BRIDGEABLE_CHAINS,\n USDT0_ADDRESSES,\n NATIVE_SYMBOLS,\n parseTokenAmount,\n} from '../constants.js'\n\n/**\n * Input schema for getBridgeFee tool\n */\nexport const getBridgeFeeInputSchema = z.object({\n fromChain: z\n .enum(['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'])\n .describe('Source chain to bridge from'),\n toChain: z\n .enum(['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'])\n .describe('Destination chain to bridge to'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount of USDT0 to bridge (e.g., '100' for 100 USDT0)\"),\n recipient: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Recipient address on destination chain'),\n})\n\nexport type GetBridgeFeeInput = z.infer<typeof getBridgeFeeInputSchema>\n\n/**\n * LayerZero endpoint IDs for supported chains\n */\nconst LAYERZERO_ENDPOINT_IDS: Record<string, number> = {\n ethereum: 30101,\n arbitrum: 30110,\n ink: 30291,\n berachain: 30362,\n unichain: 30320,\n}\n\n/**\n * Estimated bridge times in seconds\n */\nconst ESTIMATED_BRIDGE_TIMES: Record<string, number> = {\n ethereum: 900, // 15 minutes\n arbitrum: 300, // 5 minutes\n ink: 300, // 5 minutes\n berachain: 300, // 5 minutes\n unichain: 300, // 5 minutes\n}\n\n/**\n * OFT contract ABI for quoteSend\n */\nconst OFT_ABI = [\n {\n name: 'quoteSend',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n {\n name: '_sendParam',\n type: 'tuple',\n components: [\n { name: 'dstEid', type: 'uint32' },\n { name: 'to', type: 'bytes32' },\n { name: 'amountLD', type: 'uint256' },\n { name: 'minAmountLD', type: 'uint256' },\n { name: 'extraOptions', type: 'bytes' },\n { name: 'composeMsg', type: 'bytes' },\n { name: 'oftCmd', type: 'bytes' },\n ],\n },\n { name: '_payInLzToken', type: 'bool' },\n ],\n outputs: [\n {\n name: 'msgFee',\n type: 'tuple',\n components: [\n { name: 'nativeFee', type: 'uint256' },\n { name: 'lzTokenFee', type: 'uint256' },\n ],\n },\n ],\n },\n] as const\n\n/**\n * Get the viem chain configuration for a network\n */\nfunction getViemChain(network: SupportedNetwork) {\n switch (network) {\n case 'ethereum':\n return chains.mainnet\n case 'arbitrum':\n return chains.arbitrum\n case 'ink':\n return chains.ink\n case 'berachain':\n return chains.berachain\n case 'unichain':\n return chains.unichain\n default:\n return undefined\n }\n}\n\n/**\n * Convert address to bytes32 format for LayerZero\n */\nfunction addressToBytes32(address: Address): `0x${string}` {\n return `0x${address.slice(2).padStart(64, '0')}` as `0x${string}`\n}\n\n/**\n * Execute getBridgeFee tool\n */\nexport async function executeGetBridgeFee(\n input: GetBridgeFeeInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<BridgeFeeQuote> {\n const { fromChain, toChain, amount, recipient } = input\n\n // Validate chains are different\n if (fromChain === toChain) {\n throw new Error('Source and destination chains must be different')\n }\n\n // Validate both chains support bridging\n if (!BRIDGEABLE_CHAINS.includes(fromChain as SupportedNetwork)) {\n throw new Error(`Chain ${fromChain} does not support USDT0 bridging`)\n }\n if (!BRIDGEABLE_CHAINS.includes(toChain as SupportedNetwork)) {\n throw new Error(`Chain ${toChain} does not support USDT0 bridging`)\n }\n\n // Get USDT0 address on source chain\n const usdt0Address = USDT0_ADDRESSES[fromChain as SupportedNetwork]\n if (!usdt0Address) {\n throw new Error(`USDT0 not found on ${fromChain}`)\n }\n\n // Parse amount (6 decimals)\n const amountBigInt = parseTokenAmount(amount, 6)\n\n // Create client\n const chain = getViemChain(fromChain as SupportedNetwork)\n if (!chain) {\n throw new Error(`Unsupported chain: ${fromChain}`)\n }\n\n const rpcUrl =\n rpcUrls?.[fromChain as SupportedNetwork] || DEFAULT_RPC_URLS[fromChain as SupportedNetwork]\n const client = createPublicClient({\n chain,\n transport: http(rpcUrl),\n })\n\n // Build send params\n const dstEid = LAYERZERO_ENDPOINT_IDS[toChain]\n const sendParam = {\n dstEid,\n to: addressToBytes32(recipient as Address),\n amountLD: amountBigInt,\n minAmountLD: amountBigInt, // No slippage for quote\n extraOptions: '0x' as `0x${string}`,\n composeMsg: '0x' as `0x${string}`,\n oftCmd: '0x' as `0x${string}`,\n }\n\n // Get quote from contract\n const quote = (await client.readContract({\n address: usdt0Address,\n abi: OFT_ABI,\n functionName: 'quoteSend',\n args: [sendParam, false],\n })) as { nativeFee: bigint; lzTokenFee: bigint }\n\n const nativeSymbol = NATIVE_SYMBOLS[fromChain as SupportedNetwork]\n const estimatedTime = ESTIMATED_BRIDGE_TIMES[toChain] || 300\n\n return {\n fromChain: fromChain as SupportedNetwork,\n toChain: toChain as SupportedNetwork,\n amount,\n nativeFee: quote.nativeFee.toString(),\n nativeFeeFormatted: `${formatEther(quote.nativeFee)} ${nativeSymbol}`,\n estimatedTime,\n }\n}\n\n/**\n * Format bridge fee result for display\n */\nexport function formatBridgeFeeResult(result: BridgeFeeQuote): string {\n const minutes = Math.ceil(result.estimatedTime / 60)\n\n return [\n `## Bridge Fee Quote`,\n '',\n `- **Route:** ${result.fromChain} → ${result.toChain}`,\n `- **Amount:** ${result.amount} USDT0`,\n `- **Native Fee:** ${result.nativeFeeFormatted}`,\n `- **Estimated Time:** ~${minutes} minutes`,\n '',\n '_Note: Actual fees may vary slightly at execution time._',\n ].join('\\n')\n}\n","/**\n * t402/bridge - Bridge USDT0 between chains using LayerZero OFT\n */\n\nimport { z } from 'zod'\nimport {\n createPublicClient,\n createWalletClient,\n http,\n keccak256,\n toBytes,\n type Address,\n} from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport * as chains from 'viem/chains'\nimport type { SupportedNetwork, BridgeResult } from '../types.js'\nimport {\n DEFAULT_RPC_URLS,\n BRIDGEABLE_CHAINS,\n USDT0_ADDRESSES,\n ERC20_ABI,\n parseTokenAmount,\n getLayerZeroScanUrl,\n getExplorerTxUrl,\n} from '../constants.js'\n\n/**\n * Input schema for bridge tool\n */\nexport const bridgeInputSchema = z.object({\n fromChain: z\n .enum(['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'])\n .describe('Source chain to bridge from'),\n toChain: z\n .enum(['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'])\n .describe('Destination chain to bridge to'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount of USDT0 to bridge (e.g., '100' for 100 USDT0)\"),\n recipient: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Recipient address on destination chain'),\n confirmed: z\n .boolean()\n .optional()\n .describe('Set to true to confirm and execute this bridge'),\n})\n\nexport type BridgeInput = z.infer<typeof bridgeInputSchema>\n\n/**\n * LayerZero endpoint IDs for supported chains\n */\nconst LAYERZERO_ENDPOINT_IDS: Record<string, number> = {\n ethereum: 30101,\n arbitrum: 30110,\n ink: 30291,\n berachain: 30362,\n unichain: 30320,\n}\n\n/**\n * Estimated bridge times in seconds\n */\nconst ESTIMATED_BRIDGE_TIMES: Record<string, number> = {\n ethereum: 900,\n arbitrum: 300,\n ink: 300,\n berachain: 300,\n unichain: 300,\n}\n\n/**\n * OFT contract ABI\n */\nconst OFT_ABI = [\n {\n name: 'quoteSend',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n {\n name: '_sendParam',\n type: 'tuple',\n components: [\n { name: 'dstEid', type: 'uint32' },\n { name: 'to', type: 'bytes32' },\n { name: 'amountLD', type: 'uint256' },\n { name: 'minAmountLD', type: 'uint256' },\n { name: 'extraOptions', type: 'bytes' },\n { name: 'composeMsg', type: 'bytes' },\n { name: 'oftCmd', type: 'bytes' },\n ],\n },\n { name: '_payInLzToken', type: 'bool' },\n ],\n outputs: [\n {\n name: 'msgFee',\n type: 'tuple',\n components: [\n { name: 'nativeFee', type: 'uint256' },\n { name: 'lzTokenFee', type: 'uint256' },\n ],\n },\n ],\n },\n {\n name: 'send',\n type: 'function',\n stateMutability: 'payable',\n inputs: [\n {\n name: '_sendParam',\n type: 'tuple',\n components: [\n { name: 'dstEid', type: 'uint32' },\n { name: 'to', type: 'bytes32' },\n { name: 'amountLD', type: 'uint256' },\n { name: 'minAmountLD', type: 'uint256' },\n { name: 'extraOptions', type: 'bytes' },\n { name: 'composeMsg', type: 'bytes' },\n { name: 'oftCmd', type: 'bytes' },\n ],\n },\n {\n name: '_fee',\n type: 'tuple',\n components: [\n { name: 'nativeFee', type: 'uint256' },\n { name: 'lzTokenFee', type: 'uint256' },\n ],\n },\n { name: '_refundAddress', type: 'address' },\n ],\n outputs: [\n {\n name: 'msgReceipt',\n type: 'tuple',\n components: [\n { name: 'guid', type: 'bytes32' },\n { name: 'nonce', type: 'uint64' },\n {\n name: 'fee',\n type: 'tuple',\n components: [\n { name: 'nativeFee', type: 'uint256' },\n { name: 'lzTokenFee', type: 'uint256' },\n ],\n },\n ],\n },\n {\n name: 'oftReceipt',\n type: 'tuple',\n components: [\n { name: 'amountSentLD', type: 'uint256' },\n { name: 'amountReceivedLD', type: 'uint256' },\n ],\n },\n ],\n },\n] as const\n\n/**\n * OFTSent event topic\n */\nconst OFT_SENT_EVENT_TOPIC = keccak256(toBytes('OFTSent(bytes32,uint32,address,uint256,uint256)'))\n\n/**\n * Get the viem chain configuration for a network\n */\nfunction getViemChain(network: SupportedNetwork) {\n switch (network) {\n case 'ethereum':\n return chains.mainnet\n case 'arbitrum':\n return chains.arbitrum\n case 'ink':\n return chains.ink\n case 'berachain':\n return chains.berachain\n case 'unichain':\n return chains.unichain\n default:\n return undefined\n }\n}\n\n/**\n * Convert address to bytes32 format for LayerZero\n */\nfunction addressToBytes32(address: Address): `0x${string}` {\n return `0x${address.slice(2).padStart(64, '0')}` as `0x${string}`\n}\n\n/**\n * Options for executing bridge\n */\nexport interface BridgeOptions {\n /** Private key for signing (hex with 0x prefix) */\n privateKey: string\n /** Custom RPC URL */\n rpcUrl?: string\n /** Demo mode - simulate without executing */\n demoMode?: boolean\n /** Slippage tolerance percentage (default: 0.5) */\n slippageTolerance?: number\n}\n\n/**\n * Execute bridge tool\n */\nexport async function executeBridge(\n input: BridgeInput,\n options: BridgeOptions,\n): Promise<BridgeResult | { needsConfirmation: true; summary: string; details: Record<string, string> }> {\n const { fromChain, toChain, amount, recipient } = input\n const { privateKey, rpcUrl, demoMode, slippageTolerance = 0.5 } = options\n\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Bridge ${amount} USDT0 from ${fromChain} to ${toChain}`,\n details: { fromChain, toChain, amount, recipient },\n }\n }\n\n // Validate chains are different\n if (fromChain === toChain) {\n throw new Error('Source and destination chains must be different')\n }\n\n // Validate both chains support bridging\n if (!BRIDGEABLE_CHAINS.includes(fromChain as SupportedNetwork)) {\n throw new Error(`Chain ${fromChain} does not support USDT0 bridging`)\n }\n if (!BRIDGEABLE_CHAINS.includes(toChain as SupportedNetwork)) {\n throw new Error(`Chain ${toChain} does not support USDT0 bridging`)\n }\n\n // Get USDT0 address on source chain\n const usdt0Address = USDT0_ADDRESSES[fromChain as SupportedNetwork]\n if (!usdt0Address) {\n throw new Error(`USDT0 not found on ${fromChain}`)\n }\n\n // Parse amount (6 decimals)\n const amountBigInt = parseTokenAmount(amount, 6)\n\n // Calculate minimum amount with slippage\n const slippageMultiplier = BigInt(Math.floor((100 - slippageTolerance) * 100))\n const minAmountBigInt = (amountBigInt * slippageMultiplier) / 10000n\n\n // Demo mode - return simulated result\n if (demoMode) {\n const fakeTxHash = `0x${'a'.repeat(64)}` as `0x${string}`\n const fakeGuid = `0x${'b'.repeat(64)}` as `0x${string}`\n const estimatedTime = ESTIMATED_BRIDGE_TIMES[toChain] || 300\n\n return {\n txHash: fakeTxHash,\n messageGuid: fakeGuid,\n amount,\n fromChain: fromChain as SupportedNetwork,\n toChain: toChain as SupportedNetwork,\n estimatedTime,\n trackingUrl: getLayerZeroScanUrl(fakeGuid),\n }\n }\n\n // Create clients\n const chain = getViemChain(fromChain as SupportedNetwork)\n if (!chain) {\n throw new Error(`Unsupported chain: ${fromChain}`)\n }\n\n const transport = http(rpcUrl || DEFAULT_RPC_URLS[fromChain as SupportedNetwork])\n const account = privateKeyToAccount(privateKey as `0x${string}`)\n\n const publicClient = createPublicClient({\n chain,\n transport,\n })\n\n const walletClient = createWalletClient({\n account,\n chain,\n transport,\n })\n\n // Check USDT0 balance\n const balance = (await publicClient.readContract({\n address: usdt0Address,\n abi: ERC20_ABI,\n functionName: 'balanceOf',\n args: [account.address],\n })) as bigint\n\n if (balance < amountBigInt) {\n throw new Error(\n `Insufficient USDT0 balance. Have: ${balance.toString()}, Need: ${amountBigInt.toString()}`,\n )\n }\n\n // Build send params\n const dstEid = LAYERZERO_ENDPOINT_IDS[toChain]\n const sendParam = {\n dstEid,\n to: addressToBytes32(recipient as Address),\n amountLD: amountBigInt,\n minAmountLD: minAmountBigInt,\n extraOptions: '0x' as `0x${string}`,\n composeMsg: '0x' as `0x${string}`,\n oftCmd: '0x' as `0x${string}`,\n }\n\n // Get quote\n const quote = (await publicClient.readContract({\n address: usdt0Address,\n abi: OFT_ABI,\n functionName: 'quoteSend',\n args: [sendParam, false],\n })) as { nativeFee: bigint; lzTokenFee: bigint }\n\n // Add 10% buffer to fee\n const nativeFeeWithBuffer = (quote.nativeFee * 110n) / 100n\n\n // Execute send\n const hash = await walletClient.writeContract({\n address: usdt0Address,\n abi: OFT_ABI,\n functionName: 'send',\n args: [sendParam, { nativeFee: nativeFeeWithBuffer, lzTokenFee: 0n }, account.address],\n value: nativeFeeWithBuffer,\n })\n\n // Wait for confirmation\n const receipt = await publicClient.waitForTransactionReceipt({ hash })\n\n if (receipt.status !== 'success') {\n throw new Error(`Bridge transaction failed: ${hash}`)\n }\n\n // Extract message GUID from OFTSent event\n let messageGuid: `0x${string}` = '0x' as `0x${string}`\n for (const log of receipt.logs) {\n if (log.topics[0] === OFT_SENT_EVENT_TOPIC && log.topics[1]) {\n messageGuid = log.topics[1] as `0x${string}`\n break\n }\n }\n\n if (messageGuid === '0x') {\n throw new Error('Failed to extract message GUID from transaction logs')\n }\n\n const estimatedTime = ESTIMATED_BRIDGE_TIMES[toChain] || 300\n\n return {\n txHash: hash,\n messageGuid,\n amount,\n fromChain: fromChain as SupportedNetwork,\n toChain: toChain as SupportedNetwork,\n estimatedTime,\n trackingUrl: getLayerZeroScanUrl(messageGuid),\n }\n}\n\n/**\n * Format bridge result for display\n */\nexport function formatBridgeResult(result: BridgeResult): string {\n const minutes = Math.ceil(result.estimatedTime / 60)\n\n return [\n `## Bridge Transaction Submitted`,\n '',\n `- **Route:** ${result.fromChain} → ${result.toChain}`,\n `- **Amount:** ${result.amount} USDT0`,\n `- **Transaction:** \\`${result.txHash}\\``,\n `- **Message GUID:** \\`${result.messageGuid}\\``,\n `- **Estimated Delivery:** ~${minutes} minutes`,\n '',\n `### Tracking`,\n `- [View on LayerZero Scan](${result.trackingUrl})`,\n `- [View Source TX](${getExplorerTxUrl(result.fromChain, result.txHash)})`,\n '',\n `_Your USDT0 will arrive on ${result.toChain} once the LayerZero message is delivered._`,\n ].join('\\n')\n}\n","/**\n * wdk/getWallet - Get wallet info from WDK\n */\n\nimport { z } from 'zod'\nimport type { T402WDK } from '@t402/wdk'\n\n/**\n * Input schema for wdk/getWallet tool\n */\nexport const wdkGetWalletInputSchema = z.object({})\n\nexport type WdkGetWalletInput = z.infer<typeof wdkGetWalletInputSchema>\n\n/**\n * Wallet info result\n */\nexport interface WdkWalletInfo {\n /** EVM address */\n evmAddress: string\n /** Supported chains */\n chains: string[]\n}\n\n/**\n * Execute wdk/getWallet tool\n *\n * @param _input - Empty input (no params needed)\n * @param wdk - T402WDK instance\n * @returns Wallet info\n */\nexport async function executeWdkGetWallet(\n _input: WdkGetWalletInput,\n wdk: T402WDK,\n): Promise<WdkWalletInfo> {\n const signer = await wdk.getSigner('ethereum')\n const chains = wdk.getConfiguredChains()\n\n return {\n evmAddress: signer.address,\n chains: chains.length > 0 ? chains : ['ethereum'],\n }\n}\n\n/**\n * Execute wdk/getWallet in demo mode\n *\n * @returns Demo wallet info\n */\nexport function executeWdkGetWalletDemo(): WdkWalletInfo {\n return {\n evmAddress: '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045',\n chains: ['ethereum', 'arbitrum', 'base', 'optimism'],\n }\n}\n\n/**\n * Format wallet info for display\n *\n * @param info - Wallet info\n * @returns Formatted string\n */\nexport function formatWdkWalletResult(info: WdkWalletInfo): string {\n const lines: string[] = [\n '## WDK Wallet Info',\n '',\n `**EVM Address:** \\`${info.evmAddress}\\``,\n '',\n '### Supported Chains',\n ...info.chains.map((c) => `- ${c}`),\n ]\n return lines.join('\\n')\n}\n","/**\n * wdk/getBalances - Get multi-chain balances via WDK\n */\n\nimport { z } from 'zod'\nimport type { T402WDK, AggregatedBalance } from '@t402/wdk'\nimport { formatUnits } from 'viem'\n\n/**\n * Input schema for wdk/getBalances tool\n */\nexport const wdkGetBalancesInputSchema = z.object({\n chains: z\n .array(z.string())\n .optional()\n .describe('Optional list of chains to check. If not provided, checks all configured chains.'),\n})\n\nexport type WdkGetBalancesInput = z.infer<typeof wdkGetBalancesInputSchema>\n\n/**\n * WDK balance result\n */\nexport interface WdkBalancesResult {\n /** Per-chain balances */\n chains: Array<{\n chain: string\n usdt0: string\n usdc: string\n native: string\n }>\n /** Total USDT0 across all chains */\n totalUsdt0: string\n /** Total USDC across all chains */\n totalUsdc: string\n}\n\n/**\n * Find a token balance by symbol from the tokens array\n *\n * @param tokens - Array of token balances\n * @param symbol - Token symbol to find\n * @returns Formatted balance or '0'\n */\nfunction findTokenFormatted(\n tokens: Array<{ symbol: string; formatted: string }>,\n symbol: string,\n): string {\n return tokens.find((t) => t.symbol === symbol)?.formatted ?? '0'\n}\n\n/**\n * Execute wdk/getBalances tool\n *\n * @param input - Input with optional chains filter\n * @param wdk - T402WDK instance\n * @returns Multi-chain balances\n */\nexport async function executeWdkGetBalances(\n input: WdkGetBalancesInput,\n wdk: T402WDK,\n): Promise<WdkBalancesResult> {\n const balances: AggregatedBalance = await wdk.getAggregatedBalances()\n\n const chains = balances.chains\n .filter((c) => !input.chains || input.chains.includes(c.chain))\n .map((c) => ({\n chain: c.chain,\n usdt0: findTokenFormatted(c.tokens, 'USDT0'),\n usdc: findTokenFormatted(c.tokens, 'USDC'),\n native: formatUnits(c.native, 18),\n }))\n\n return {\n chains,\n totalUsdt0: formatUnits(balances.totalUsdt0, 6),\n totalUsdc: formatUnits(balances.totalUsdc, 6),\n }\n}\n\n/**\n * Execute wdk/getBalances in demo mode\n *\n * @returns Demo balances\n */\nexport function executeWdkGetBalancesDemo(): WdkBalancesResult {\n return {\n chains: [\n { chain: 'ethereum', usdt0: '100.00', usdc: '250.00', native: '0.5' },\n { chain: 'arbitrum', usdt0: '500.00', usdc: '0', native: '0.01' },\n { chain: 'base', usdt0: '200.00', usdc: '100.00', native: '0.02' },\n ],\n totalUsdt0: '800.00',\n totalUsdc: '350.00',\n }\n}\n\n/**\n * Format balances for display\n *\n * @param result - Balances result\n * @returns Formatted string\n */\nexport function formatWdkBalancesResult(result: WdkBalancesResult): string {\n const lines: string[] = [\n '## WDK Multi-Chain Balances',\n '',\n `**Total USDT0:** ${result.totalUsdt0}`,\n `**Total USDC:** ${result.totalUsdc}`,\n '',\n '### Per-Chain Breakdown',\n '',\n ]\n\n for (const chain of result.chains) {\n lines.push(`**${chain.chain}**`)\n lines.push(`- USDT0: ${chain.usdt0}`)\n lines.push(`- USDC: ${chain.usdc}`)\n lines.push(`- Native: ${chain.native}`)\n lines.push('')\n }\n\n return lines.join('\\n')\n}\n","/**\n * wdk/transfer - Send tokens via WDK\n */\n\nimport { z } from 'zod'\nimport type { T402WDK } from '@t402/wdk'\nimport type { Address } from 'viem'\nimport type { SupportedNetwork } from '../types.js'\nimport { getExplorerTxUrl } from '../constants.js'\n\n/**\n * Input schema for wdk/transfer tool\n */\nexport const wdkTransferInputSchema = z.object({\n to: z.string().describe('Recipient address'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount to send (e.g., '10.50')\"),\n token: z.enum(['USDC', 'USDT', 'USDT0']).describe('Token to transfer'),\n chain: z.string().describe('Chain to execute transfer on (e.g., \"ethereum\", \"arbitrum\")'),\n confirmed: z\n .boolean()\n .optional()\n .describe('Set to true to confirm and execute this transfer'),\n})\n\nexport type WdkTransferInput = z.infer<typeof wdkTransferInputSchema>\n\n/**\n * Transfer result\n */\nexport interface WdkTransferResult {\n /** Transaction hash */\n txHash: string\n /** Amount transferred */\n amount: string\n /** Token transferred */\n token: string\n /** Chain used */\n chain: string\n /** Recipient */\n to: string\n /** Explorer URL */\n explorerUrl: string\n}\n\n/**\n * Execute wdk/transfer tool\n *\n * @param input - Transfer parameters\n * @param wdk - T402WDK instance\n * @returns Transfer result\n */\nexport async function executeWdkTransfer(\n input: WdkTransferInput,\n wdk: T402WDK,\n): Promise<WdkTransferResult | { needsConfirmation: true; summary: string; details: Record<string, string> }> {\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Transfer ${input.amount} ${input.token} on ${input.chain} to ${input.to}`,\n details: { to: input.to, amount: input.amount, token: input.token, chain: input.chain },\n }\n }\n\n const signer = await wdk.getSigner(input.chain)\n\n // Use the WDK signer to send a raw transaction\n // For stablecoin transfers, we need to encode the ERC-20 transfer call\n const result = await signer.sendTransaction({\n to: input.to as Address,\n })\n\n const txHash = result.hash\n const explorerUrl = getExplorerTxUrl(input.chain as SupportedNetwork, txHash)\n\n return {\n txHash,\n amount: input.amount,\n token: input.token,\n chain: input.chain,\n to: input.to,\n explorerUrl,\n }\n}\n\n/**\n * Execute wdk/transfer in demo mode\n *\n * @param input - Transfer parameters\n * @returns Demo transfer result\n */\nexport function executeWdkTransferDemo(\n input: WdkTransferInput,\n): WdkTransferResult | { needsConfirmation: true; summary: string; details: Record<string, string> } {\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Transfer ${input.amount} ${input.token} on ${input.chain} to ${input.to}`,\n details: { to: input.to, amount: input.amount, token: input.token, chain: input.chain },\n }\n }\n\n const demoTxHash = '0xdemo' + Math.random().toString(16).slice(2, 10)\n return {\n txHash: demoTxHash,\n amount: input.amount,\n token: input.token,\n chain: input.chain,\n to: input.to,\n explorerUrl: `https://etherscan.io/tx/${demoTxHash}`,\n }\n}\n\n/**\n * Format transfer result for display\n *\n * @param result - Transfer result\n * @returns Formatted string\n */\nexport function formatWdkTransferResult(result: WdkTransferResult): string {\n return [\n '## WDK Transfer Complete',\n '',\n `**Amount:** ${result.amount} ${result.token}`,\n `**Chain:** ${result.chain}`,\n `**To:** \\`${result.to}\\``,\n `**Tx Hash:** \\`${result.txHash}\\``,\n `**Explorer:** [View Transaction](${result.explorerUrl})`,\n ].join('\\n')\n}\n","/**\n * wdk/swap - Swap tokens via WDK\n */\n\nimport { z } from 'zod'\nimport type { T402WDK } from '@t402/wdk'\nimport { formatUnits, parseUnits } from 'viem'\n\n/**\n * Input schema for wdk/swap tool\n */\nexport const wdkSwapInputSchema = z.object({\n fromToken: z.string().describe('Token to swap from (e.g., \"ETH\", \"USDC\")'),\n toToken: z.string().describe('Token to swap to (e.g., \"USDT0\", \"USDC\")'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount to swap (e.g., '1.0')\"),\n chain: z.string().describe('Chain to execute swap on (e.g., \"ethereum\", \"arbitrum\")'),\n confirmed: z\n .boolean()\n .optional()\n .describe('Set to true to confirm and execute this swap'),\n})\n\nexport type WdkSwapInput = z.infer<typeof wdkSwapInputSchema>\n\n/**\n * Swap result\n */\nexport interface WdkSwapResult {\n /** Input amount */\n fromAmount: string\n /** Input token */\n fromToken: string\n /** Output amount (estimated or actual) */\n toAmount: string\n /** Output token */\n toToken: string\n /** Chain */\n chain: string\n /** Transaction hash (if executed) */\n txHash?: string\n}\n\n/**\n * Execute wdk/swap tool\n *\n * @param input - Swap parameters\n * @param wdk - T402WDK instance\n * @returns Swap result\n */\nexport async function executeWdkSwap(\n input: WdkSwapInput,\n wdk: T402WDK,\n): Promise<WdkSwapResult | { needsConfirmation: true; summary: string; details: Record<string, string> }> {\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Swap ${input.amount} ${input.fromToken} to ${input.toToken} on ${input.chain}`,\n details: {\n fromToken: input.fromToken,\n toToken: input.toToken,\n amount: input.amount,\n chain: input.chain,\n },\n }\n }\n\n // Parse amount to smallest units (assume 18 decimals for native, 6 for stablecoins)\n const decimals = ['USDC', 'USDT', 'USDT0'].includes(input.fromToken.toUpperCase()) ? 6 : 18\n const amountBigInt = parseUnits(input.amount, decimals)\n\n // Get swap quote first\n const quote = await wdk.getSwapQuote(input.chain, input.fromToken, amountBigInt)\n\n // Execute swap\n const result = await wdk.swapAndPay({\n chain: input.chain,\n fromToken: input.fromToken,\n amount: amountBigInt,\n })\n\n // Format output amount (USDT0 is always 6 decimals output)\n const outputDecimals = ['USDC', 'USDT', 'USDT0'].includes(input.toToken.toUpperCase()) ? 6 : 18\n const toAmount = formatUnits(result?.outputAmount ?? quote.outputAmount, outputDecimals)\n\n return {\n fromAmount: input.amount,\n fromToken: input.fromToken,\n toAmount,\n toToken: input.toToken,\n chain: input.chain,\n txHash: result?.txHash,\n }\n}\n\n/**\n * Execute wdk/swap in demo mode\n *\n * @param input - Swap parameters\n * @returns Demo swap result\n */\nexport function executeWdkSwapDemo(\n input: WdkSwapInput,\n): WdkSwapResult | { needsConfirmation: true; summary: string; details: Record<string, string> } {\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Swap ${input.amount} ${input.fromToken} to ${input.toToken} on ${input.chain}`,\n details: {\n fromToken: input.fromToken,\n toToken: input.toToken,\n amount: input.amount,\n chain: input.chain,\n },\n }\n }\n\n // Simulate a swap with ~0.3% slippage\n const inputAmount = parseFloat(input.amount)\n const outputAmount = (inputAmount * 0.997).toFixed(6)\n\n return {\n fromAmount: input.amount,\n fromToken: input.fromToken,\n toAmount: outputAmount,\n toToken: input.toToken,\n chain: input.chain,\n txHash: '0xdemo' + Math.random().toString(16).slice(2, 10),\n }\n}\n\n/**\n * Format swap result for display\n *\n * @param result - Swap result\n * @returns Formatted string\n */\nexport function formatWdkSwapResult(result: WdkSwapResult): string {\n const lines = [\n '## WDK Swap Result',\n '',\n `**From:** ${result.fromAmount} ${result.fromToken}`,\n `**To:** ${result.toAmount} ${result.toToken}`,\n `**Chain:** ${result.chain}`,\n ]\n\n if (result.txHash) {\n lines.push(`**Tx Hash:** \\`${result.txHash}\\``)\n }\n\n return lines.join('\\n')\n}\n","/**\n * t402/autoPay - Smart payment orchestrator\n *\n * Fetches a URL, detects 402 payment requirements, checks WDK balances,\n * signs payment, and returns the paid content.\n */\n\nimport { z } from 'zod'\nimport type { T402WDK } from '@t402/wdk'\n\n/**\n * Input schema for t402/autoPay tool\n */\nexport const autoPayInputSchema = z.object({\n url: z.string().url().describe('URL to fetch (may return 402 Payment Required)'),\n maxAmount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .optional()\n .describe('Maximum amount willing to pay (e.g., \"10.00\"). If not set, pays any amount.'),\n preferredChain: z\n .string()\n .optional()\n .describe(\n 'Preferred chain for payment (e.g., \"arbitrum\"). If not specified, uses first available.',\n ),\n confirmed: z\n .boolean()\n .optional()\n .describe('Set to true to confirm and execute this payment'),\n})\n\nexport type AutoPayInput = z.infer<typeof autoPayInputSchema>\n\n/**\n * AutoPay result\n */\nexport interface AutoPayResult {\n /** Whether the resource was successfully accessed */\n success: boolean\n /** HTTP status code */\n statusCode: number\n /** Response body (truncated if large) */\n body: string\n /** Content type of the response */\n contentType?: string\n /** Payment details (if payment was made) */\n payment?: {\n network: string\n scheme: string\n amount: string\n payTo: string\n }\n /** Error message (if failed) */\n error?: string\n}\n\n/**\n * Execute t402/autoPay tool\n *\n * @param input - AutoPay parameters\n * @param wdk - T402WDK instance\n * @returns AutoPay result\n */\nexport async function executeAutoPay(\n input: AutoPayInput,\n wdk: T402WDK,\n): Promise<AutoPayResult | { needsConfirmation: true; summary: string; details: Record<string, string> }> {\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Auto-pay for ${input.url}${input.maxAmount ? ` (max ${input.maxAmount})` : ''}`,\n details: {\n url: input.url,\n ...(input.maxAmount ? { maxAmount: input.maxAmount } : {}),\n ...(input.preferredChain ? { preferredChain: input.preferredChain } : {}),\n },\n }\n }\n\n const chains = input.preferredChain ? [input.preferredChain] : ['ethereum', 'arbitrum', 'base']\n\n const { T402Protocol } = await import('@t402/wdk-protocol')\n const protocol = await T402Protocol.create(wdk, { chains })\n\n const { response, receipt } = await protocol.fetch(input.url)\n\n // Check max amount\n if (receipt && input.maxAmount) {\n const paidAmount = parseFloat(receipt.amount) / 1e6 // Assume 6 decimals\n const maxAmount = parseFloat(input.maxAmount)\n if (paidAmount > maxAmount) {\n return {\n success: false,\n statusCode: 402,\n body: '',\n error: `Payment amount (${paidAmount}) exceeds max allowed (${maxAmount})`,\n }\n }\n }\n\n // Read response body\n const contentType = response.headers.get('content-type') ?? undefined\n let body = ''\n try {\n body = await response.text()\n // Truncate large responses\n if (body.length > 10000) {\n body = body.slice(0, 10000) + '\\n... (truncated)'\n }\n } catch {\n body = '[Could not read response body]'\n }\n\n return {\n success: response.ok,\n statusCode: response.status,\n body,\n contentType,\n payment: receipt\n ? {\n network: receipt.network,\n scheme: receipt.scheme,\n amount: receipt.amount,\n payTo: receipt.payTo,\n }\n : undefined,\n }\n}\n\n/**\n * Execute t402/autoPay in demo mode\n *\n * @param input - AutoPay parameters\n * @returns Demo autopay result\n */\nexport function executeAutoPayDemo(\n input: AutoPayInput,\n): AutoPayResult | { needsConfirmation: true; summary: string; details: Record<string, string> } {\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Auto-pay for ${input.url}${input.maxAmount ? ` (max ${input.maxAmount})` : ''}`,\n details: {\n url: input.url,\n ...(input.maxAmount ? { maxAmount: input.maxAmount } : {}),\n ...(input.preferredChain ? { preferredChain: input.preferredChain } : {}),\n },\n }\n }\n\n return {\n success: true,\n statusCode: 200,\n body: `[Demo] Premium content from ${input.url}\\n\\nThis is simulated content that would be returned after payment.`,\n contentType: 'text/plain',\n payment: {\n network: 'eip155:42161',\n scheme: 'exact',\n amount: '1000000',\n payTo: '0xC88f67e776f16DcFBf42e6bDda1B82604448899B',\n },\n }\n}\n\n/**\n * Format autopay result for display\n *\n * @param result - AutoPay result\n * @returns Formatted string\n */\nexport function formatAutoPayResult(result: AutoPayResult): string {\n const lines: string[] = ['## AutoPay Result', '']\n\n if (result.success) {\n lines.push(`**Status:** Success (${result.statusCode})`)\n } else {\n lines.push(`**Status:** Failed (${result.statusCode})`)\n }\n\n if (result.payment) {\n lines.push('')\n lines.push('### Payment Details')\n lines.push(`- **Network:** ${result.payment.network}`)\n lines.push(`- **Scheme:** ${result.payment.scheme}`)\n lines.push(`- **Amount:** ${result.payment.amount}`)\n lines.push(`- **Pay To:** \\`${result.payment.payTo}\\``)\n }\n\n if (result.error) {\n lines.push('')\n lines.push(`**Error:** ${result.error}`)\n }\n\n if (result.body) {\n lines.push('')\n lines.push('### Response Content')\n if (result.contentType) {\n lines.push(`_Content-Type: ${result.contentType}_`)\n }\n lines.push('')\n lines.push('```')\n lines.push(result.body)\n lines.push('```')\n }\n\n return lines.join('\\n')\n}\n","/**\n * TON MCP Bridge - Connects @ton/mcp tools with @t402/mcp\n *\n * Enables AI agents to perform end-to-end TON payment flows by\n * proxying @ton/mcp's 15 blockchain tools through the t402 MCP server.\n */\n\n/**\n * Configuration for the TON MCP bridge\n */\nexport interface TonMcpBridgeConfig {\n /** @ton/mcp server URL or SSE endpoint */\n tonMcpEndpoint?: string\n /** TON API key for direct calls (e.g., toncenter.com API key) */\n tonApiKey?: string\n /** Enable demo mode (simulates calls without executing) */\n demoMode?: boolean\n}\n\n/**\n * Tool input/output schema type\n */\ninterface ToolSchema {\n type: 'object'\n properties: Record<string, { type: string; description: string; enum?: string[] }>\n required: string[]\n}\n\n/**\n * TON bridge tool definition\n */\ninterface TonBridgeTool {\n name: string\n description: string\n inputSchema: ToolSchema\n}\n\n/**\n * Proxy tool definitions from @ton/mcp\n *\n * These map to the tools available in the @ton/mcp server.\n * When registered, they proxy requests to the @ton/mcp endpoint.\n */\nexport const TON_BRIDGE_TOOLS: Record<string, TonBridgeTool> = {\n 'ton/getBalance': {\n name: 'ton/getBalance',\n description: 'Get TON and Jetton balances for a wallet address on the TON blockchain.',\n inputSchema: {\n type: 'object',\n properties: {\n address: {\n type: 'string',\n description: 'TON wallet address (friendly or raw format)',\n },\n },\n required: ['address'],\n },\n },\n\n 'ton/transfer': {\n name: 'ton/transfer',\n description: 'Send TON to a recipient address on the TON blockchain.',\n inputSchema: {\n type: 'object',\n properties: {\n to: {\n type: 'string',\n description: 'Recipient TON address',\n },\n amount: {\n type: 'string',\n description: 'Amount of TON to send (e.g., \"1.5\")',\n },\n memo: {\n type: 'string',\n description: 'Optional memo/comment for the transfer',\n },\n },\n required: ['to', 'amount'],\n },\n },\n\n 'ton/getJettonBalance': {\n name: 'ton/getJettonBalance',\n description: 'Get the balance of a specific Jetton (TON token) for a wallet address.',\n inputSchema: {\n type: 'object',\n properties: {\n address: {\n type: 'string',\n description: 'TON wallet address',\n },\n jettonMaster: {\n type: 'string',\n description: 'Jetton master contract address',\n },\n },\n required: ['address', 'jettonMaster'],\n },\n },\n\n 'ton/swapJettons': {\n name: 'ton/swapJettons',\n description:\n 'Swap Jettons (TON tokens) using DEX aggregation on the TON network. Returns a raw transaction JSON to be sent via sendTransaction.',\n inputSchema: {\n type: 'object',\n properties: {\n from: {\n type: 'string',\n description: 'Source Jetton master address (or \"TON\" for native TON)',\n },\n to: {\n type: 'string',\n description: 'Destination Jetton master address (or \"TON\" for native TON)',\n },\n amount: {\n type: 'string',\n description: 'Amount to swap in human-readable format (e.g., \"1.5\")',\n },\n slippage: {\n type: 'string',\n description: 'Slippage tolerance (e.g., \"0.5\" for 0.5%)',\n },\n },\n required: ['from', 'to', 'amount'],\n },\n },\n\n 'ton/getTransactionStatus': {\n name: 'ton/getTransactionStatus',\n description: 'Check the status and details of a TON transaction by its hash.',\n inputSchema: {\n type: 'object',\n properties: {\n txHash: {\n type: 'string',\n description: 'Transaction hash (BOC hash or message hash)',\n },\n },\n required: ['txHash'],\n },\n },\n} as const\n\n/**\n * Execute a TON bridge tool call\n *\n * Proxies the tool call to the @ton/mcp endpoint or executes it\n * directly using the TON API key.\n *\n * @param toolName - Name of the tool to execute\n * @param args - Tool arguments\n * @param config - Bridge configuration\n * @returns Tool execution result\n */\nexport async function executeTonBridgeTool(\n toolName: string,\n args: Record<string, unknown>,\n config: TonMcpBridgeConfig,\n): Promise<{ content: Array<{ type: 'text'; text: string }>; isError?: boolean }> {\n // Demo mode: return simulated results\n if (config.demoMode) {\n return executeTonBridgeToolDemo(toolName, args)\n }\n\n // If we have a @ton/mcp endpoint, proxy the request\n if (config.tonMcpEndpoint) {\n return proxyToTonMcp(toolName, args, config.tonMcpEndpoint)\n }\n\n // If we have an API key, make direct API calls\n if (config.tonApiKey) {\n return executeTonBridgeToolDirect(toolName, args, config.tonApiKey)\n }\n\n return {\n content: [\n {\n type: 'text',\n text: `Error: TON MCP bridge not configured. Set tonMcpEndpoint or tonApiKey.`,\n },\n ],\n isError: true,\n }\n}\n\n/**\n * Demo mode execution for TON bridge tools\n */\nfunction executeTonBridgeToolDemo(\n toolName: string,\n args: Record<string, unknown>,\n): { content: Array<{ type: 'text'; text: string }> } {\n const responses: Record<string, string> = {\n 'ton/getBalance': `[DEMO] TON Balance for ${args.address ?? 'unknown'}:\\n- TON: 5.25\\n- USDT0: 100.00`,\n 'ton/transfer': `[DEMO] Transfer sent:\\n- To: ${args.to ?? 'unknown'}\\n- Amount: ${args.amount ?? '0'} TON\\n- TX: demo-ton-tx-hash-${Date.now().toString(36)}`,\n 'ton/getJettonBalance': `[DEMO] Jetton Balance:\\n- Address: ${args.address ?? 'unknown'}\\n- Jetton: ${args.jettonMaster ?? 'unknown'}\\n- Balance: 50.00`,\n 'ton/swapJettons': `[DEMO] Swap quote received:\\n- From: ${args.from ?? 'unknown'}\\n- To: ${args.to ?? 'unknown'}\\n- Amount: ${args.amount ?? '0'}\\n- Transaction: {\"validUntil\":${Math.floor(Date.now() / 1000) + 300},\"messages\":[{\"address\":\"EQDemo...\",\"amount\":\"${args.amount ?? '0'}\",\"payload\":\"base64...\"}]}`,\n 'ton/getTransactionStatus': `[DEMO] Transaction Status:\\n- Hash: ${args.txHash ?? 'unknown'}\\n- Status: Confirmed\\n- Block: 12345678`,\n }\n\n return {\n content: [\n {\n type: 'text',\n text: responses[toolName] ?? `[DEMO] Unknown TON tool: ${toolName}`,\n },\n ],\n }\n}\n\n/**\n * Proxy a tool call to the @ton/mcp server\n */\nasync function proxyToTonMcp(\n toolName: string,\n args: Record<string, unknown>,\n endpoint: string,\n): Promise<{ content: Array<{ type: 'text'; text: string }>; isError?: boolean }> {\n try {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'tools/call',\n params: { name: toolName, arguments: args },\n }),\n })\n\n if (!response.ok) {\n throw new Error(`TON MCP server returned ${response.status}`)\n }\n\n const result = (await response.json()) as {\n result?: { content: Array<{ type: 'text'; text: string }> }\n error?: { message: string }\n }\n\n if (result.error) {\n throw new Error(result.error.message)\n }\n\n return result.result ?? { content: [{ type: 'text', text: 'No result' }] }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return {\n content: [{ type: 'text', text: `Error proxying to @ton/mcp: ${message}` }],\n isError: true,\n }\n }\n}\n\n/**\n * Execute TON bridge tool directly using TON API\n */\nasync function executeTonBridgeToolDirect(\n toolName: string,\n args: Record<string, unknown>,\n apiKey: string,\n): Promise<{ content: Array<{ type: 'text'; text: string }>; isError?: boolean }> {\n const baseUrl = 'https://toncenter.com/api/v2'\n\n try {\n switch (toolName) {\n case 'ton/getBalance': {\n const response = await fetch(\n `${baseUrl}/getAddressBalance?address=${encodeURIComponent(String(args.address))}&api_key=${apiKey}`,\n )\n const data = (await response.json()) as { result: string }\n const balanceNano = BigInt(data.result)\n const balanceTon = Number(balanceNano) / 1e9\n return {\n content: [{ type: 'text', text: `TON Balance: ${balanceTon.toFixed(4)} TON` }],\n }\n }\n\n case 'ton/getTransactionStatus': {\n const response = await fetch(\n `${baseUrl}/getTransactions?hash=${encodeURIComponent(String(args.txHash))}&limit=1&api_key=${apiKey}`,\n )\n const data = (await response.json()) as { result: unknown[] }\n if (data.result.length === 0) {\n return {\n content: [{ type: 'text', text: 'Transaction not found' }],\n }\n }\n return {\n content: [\n {\n type: 'text',\n text: `Transaction found:\\n${JSON.stringify(data.result[0], null, 2)}`,\n },\n ],\n }\n }\n\n default:\n return {\n content: [\n {\n type: 'text',\n text: `Direct execution of ${toolName} is not supported. Configure tonMcpEndpoint to proxy to @ton/mcp.`,\n },\n ],\n isError: true,\n }\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return {\n content: [{ type: 'text', text: `Error executing TON API call: ${message}` }],\n isError: true,\n }\n }\n}\n\n/**\n * Register TON bridge tools on a t402 MCP server\n *\n * This function adds the TON bridge tools to the server's tool registry,\n * enabling AI agents to use TON blockchain operations alongside t402 payment tools.\n *\n * @param config - Bridge configuration\n * @returns Tool definitions and handler\n */\nexport function createTonBridgeToolSet(config: TonMcpBridgeConfig) {\n return {\n definitions: TON_BRIDGE_TOOLS,\n async handleToolCall(\n name: string,\n args: Record<string, unknown>,\n ): Promise<{ content: Array<{ type: 'text'; text: string }>; isError?: boolean }> {\n return executeTonBridgeTool(name, args, config)\n },\n }\n}\n","/**\n * erc8004/resolveAgent - Look up an agent's on-chain identity\n */\n\nimport { z } from 'zod'\nimport { resolveAgent } from '@t402/erc8004'\nimport type { ResolvedAgent, AgentRegistryId } from '@t402/erc8004'\nimport type { SupportedNetwork } from '../types.js'\nimport { createErc8004Client } from './erc8004Shared.js'\n\n/**\n * Input schema for resolveAgent tool\n */\nexport const erc8004ResolveAgentInputSchema = z.object({\n agentId: z.number().int().nonnegative().describe('Agent NFT token ID on the Identity Registry'),\n agentRegistry: z\n .string()\n .regex(/^eip155:\\d+:0x[a-fA-F0-9]+$/)\n .describe('Agent registry identifier (e.g., \"eip155:8453:0xRegistryAddress\")'),\n})\n\nexport type Erc8004ResolveAgentInput = z.infer<typeof erc8004ResolveAgentInputSchema>\n\n/**\n * Execute resolveAgent tool\n */\nexport async function executeErc8004ResolveAgent(\n input: Erc8004ResolveAgentInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<ResolvedAgent> {\n const { client, registryAddress } = createErc8004Client(input.agentRegistry, rpcUrls)\n\n return resolveAgent(\n client,\n registryAddress as `0x${string}`,\n BigInt(input.agentId),\n input.agentRegistry as AgentRegistryId,\n )\n}\n\n/**\n * Format resolveAgent result for display\n */\nexport function formatErc8004ResolveAgentResult(agent: ResolvedAgent): string {\n const lines: string[] = [\n `## Agent Identity (ID: ${agent.agentId})`,\n '',\n `**Registry:** ${agent.registry.id}`,\n `**Wallet:** \\`${agent.agentWallet}\\``,\n `**Owner:** \\`${agent.owner}\\``,\n `**Registration URI:** ${agent.agentURI}`,\n '',\n ]\n\n if (agent.registration) {\n const reg = agent.registration\n lines.push('### Registration File')\n if (reg.name) lines.push(`- **Name:** ${reg.name}`)\n if (reg.description) lines.push(`- **Description:** ${reg.description}`)\n if (reg.image) lines.push(`- **Image:** ${reg.image}`)\n if (reg.x402Support !== undefined) lines.push(`- **x402 Support:** ${reg.x402Support}`)\n\n if (reg.services?.length) {\n lines.push('')\n lines.push('### Services')\n for (const svc of reg.services) {\n lines.push(`- **${svc.name}:** ${svc.endpoint}`)\n }\n }\n }\n\n return lines.join('\\n')\n}\n","/**\n * Shared utilities for ERC-8004 MCP tools\n */\n\nimport { createPublicClient, http, type Chain } from 'viem'\nimport * as chains from 'viem/chains'\nimport { parseAgentRegistry, type ERC8004ReadClient } from '@t402/erc8004'\nimport type { SupportedNetwork } from '../types.js'\nimport { DEFAULT_RPC_URLS, CHAIN_IDS } from '../constants.js'\n\n/**\n * Map of EVM chain IDs to viem chain configs\n */\nconst CHAIN_ID_TO_VIEM: Record<number, Chain> = {\n 1: chains.mainnet,\n 8453: chains.base,\n 42161: chains.arbitrum,\n 10: chains.optimism,\n 137: chains.polygon,\n 43114: chains.avalanche,\n 57073: chains.ink,\n 80094: chains.berachain,\n 130: chains.unichain,\n}\n\n/**\n * Reverse map: chain ID → SupportedNetwork name\n */\nconst CHAIN_ID_TO_NETWORK: Record<number, SupportedNetwork> = Object.fromEntries(\n Object.entries(CHAIN_IDS).map(([name, id]) => [id, name as SupportedNetwork]),\n) as Record<number, SupportedNetwork>\n\n/**\n * Create an ERC8004ReadClient from an agentRegistry string.\n *\n * Parses the registry ID, resolves the chain, and creates a viem PublicClient.\n */\nexport function createErc8004Client(\n agentRegistry: string,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): { client: ERC8004ReadClient; registryAddress: string } {\n const parsed = parseAgentRegistry(agentRegistry)\n const chainId = parseInt(parsed.chainId, 10)\n\n const viemChain = CHAIN_ID_TO_VIEM[chainId]\n if (!viemChain) {\n throw new Error(\n `Unsupported chain ID ${chainId} from registry ${agentRegistry}. Supported: ${Object.keys(CHAIN_ID_TO_VIEM).join(', ')}`,\n )\n }\n\n const network = CHAIN_ID_TO_NETWORK[chainId]\n const rpcUrl = (network && rpcUrls?.[network]) || (network && DEFAULT_RPC_URLS[network])\n\n const client = createPublicClient({\n chain: viemChain,\n transport: http(rpcUrl),\n })\n\n return { client: client as unknown as ERC8004ReadClient, registryAddress: parsed.address }\n}\n","/**\n * erc8004/checkReputation - Query an agent's reputation score\n */\n\nimport { z } from 'zod'\nimport { getReputationSummary } from '@t402/erc8004'\nimport type { ReputationSummary } from '@t402/erc8004'\nimport type { SupportedNetwork } from '../types.js'\nimport { createErc8004Client } from './erc8004Shared.js'\n\n/**\n * Input schema for checkReputation tool\n */\nexport const erc8004CheckReputationInputSchema = z.object({\n agentId: z.number().int().nonnegative().describe('Agent NFT token ID'),\n agentRegistry: z\n .string()\n .regex(/^eip155:\\d+:0x[a-fA-F0-9]+$/)\n .describe('Agent registry identifier (e.g., \"eip155:8453:0xRegistryAddress\")'),\n reputationRegistry: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Reputation Registry contract address on the same chain'),\n trustedReviewers: z\n .array(z.string().regex(/^0x[a-fA-F0-9]{40}$/))\n .min(1)\n .describe('Addresses whose feedback is trusted (required for Sybil resistance)'),\n})\n\nexport type Erc8004CheckReputationInput = z.infer<typeof erc8004CheckReputationInputSchema>\n\n/**\n * Execute checkReputation tool\n */\nexport async function executeErc8004CheckReputation(\n input: Erc8004CheckReputationInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<ReputationSummary> {\n const { client } = createErc8004Client(input.agentRegistry, rpcUrls)\n\n return getReputationSummary(\n client,\n input.reputationRegistry as `0x${string}`,\n BigInt(input.agentId),\n input.trustedReviewers as `0x${string}`[],\n )\n}\n\n/**\n * Format checkReputation result for display\n */\nexport function formatErc8004CheckReputationResult(summary: ReputationSummary): string {\n const lines: string[] = [\n `## Agent Reputation (ID: ${summary.agentId})`,\n '',\n `| Metric | Value |`,\n `|--------|-------|`,\n `| Feedback Count | ${summary.count} |`,\n `| Raw Score | ${summary.summaryValue} |`,\n `| Score Decimals | ${summary.summaryValueDecimals} |`,\n `| **Normalized Score** | **${summary.normalizedScore}/100** |`,\n '',\n ]\n\n if (summary.normalizedScore >= 80) {\n lines.push('_High reputation — trusted agent_')\n } else if (summary.normalizedScore >= 50) {\n lines.push('_Moderate reputation_')\n } else if (summary.count > 0n) {\n lines.push('_Low reputation — exercise caution_')\n } else {\n lines.push('_No feedback recorded from trusted reviewers_')\n }\n\n return lines.join('\\n')\n}\n","/**\n * erc8004/verifyWallet - Verify payTo matches agent's on-chain wallet\n */\n\nimport { z } from 'zod'\nimport { verifyPayToMatchesAgent } from '@t402/erc8004'\nimport type { SupportedNetwork } from '../types.js'\nimport { createErc8004Client } from './erc8004Shared.js'\n\n/**\n * Input schema for verifyWallet tool\n */\nexport const erc8004VerifyWalletInputSchema = z.object({\n agentId: z.number().int().nonnegative().describe('Agent NFT token ID'),\n agentRegistry: z\n .string()\n .regex(/^eip155:\\d+:0x[a-fA-F0-9]+$/)\n .describe('Agent registry identifier (e.g., \"eip155:8453:0xRegistryAddress\")'),\n walletAddress: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Wallet address to verify (typically the payTo from PaymentRequirements)'),\n})\n\nexport type Erc8004VerifyWalletInput = z.infer<typeof erc8004VerifyWalletInputSchema>\n\nexport interface Erc8004VerifyWalletResult {\n matches: boolean\n agentId: number\n walletAddress: string\n registryAddress: string\n}\n\n/**\n * Execute verifyWallet tool\n */\nexport async function executeErc8004VerifyWallet(\n input: Erc8004VerifyWalletInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<Erc8004VerifyWalletResult> {\n const { client, registryAddress } = createErc8004Client(input.agentRegistry, rpcUrls)\n\n const matches = await verifyPayToMatchesAgent(\n client,\n registryAddress as `0x${string}`,\n BigInt(input.agentId),\n input.walletAddress,\n )\n\n return {\n matches,\n agentId: input.agentId,\n walletAddress: input.walletAddress,\n registryAddress,\n }\n}\n\n/**\n * Format verifyWallet result for display\n */\nexport function formatErc8004VerifyWalletResult(result: Erc8004VerifyWalletResult): string {\n const status = result.matches ? 'VERIFIED' : 'MISMATCH'\n const icon = result.matches ? '[PASS]' : '[FAIL]'\n\n const lines: string[] = [\n `## Wallet Verification: ${icon} ${status}`,\n '',\n `| Field | Value |`,\n `|-------|-------|`,\n `| Agent ID | ${result.agentId} |`,\n `| Wallet Address | \\`${result.walletAddress}\\` |`,\n `| Registry | \\`${result.registryAddress}\\` |`,\n `| **Result** | **${result.matches ? 'Address matches on-chain agentWallet' : 'Address does NOT match on-chain agentWallet'}** |`,\n ]\n\n return lines.join('\\n')\n}\n","/**\n * Price Service - CoinGecko-based token price fetcher with in-memory cache\n */\n\n/** Cache entry with TTL */\ninterface CacheEntry {\n prices: Record<string, number>\n timestamp: number\n}\n\n/** Cache TTL in milliseconds (5 minutes) */\nconst CACHE_TTL_MS = 5 * 60 * 1000\n\n/** CoinGecko API base URL */\nconst COINGECKO_API = 'https://api.coingecko.com/api/v3/simple/price'\n\n/** Map token symbols to CoinGecko IDs */\nconst TOKEN_TO_COINGECKO_ID: Record<string, string> = {\n ETH: 'ethereum',\n MATIC: 'matic-network',\n AVAX: 'avalanche-2',\n BERA: 'berachain-bera',\n USDC: 'usd-coin',\n USDT: 'tether',\n USDT0: 'tether',\n}\n\n/** In-memory price cache keyed by currency */\nconst cache = new Map<string, CacheEntry>()\n\n/**\n * Get token prices from CoinGecko with caching\n *\n * @param tokens - Token symbols to fetch prices for (e.g., ['ETH', 'MATIC'])\n * @param currency - Target currency (default: 'usd')\n * @returns Map of token symbol to price in target currency\n */\nexport async function getTokenPrices(\n tokens: string[],\n currency: string = 'usd',\n): Promise<Record<string, number>> {\n const cacheKey = `${currency}:${tokens.sort().join(',')}`\n const cached = cache.get(cacheKey)\n\n if (cached && Date.now() - cached.timestamp < CACHE_TTL_MS) {\n return cached.prices\n }\n\n // Map tokens to CoinGecko IDs\n const coinIds = new Set<string>()\n const tokenToCoinId = new Map<string, string>()\n for (const token of tokens) {\n const coinId = TOKEN_TO_COINGECKO_ID[token.toUpperCase()] ?? token.toLowerCase()\n coinIds.add(coinId)\n tokenToCoinId.set(token.toUpperCase(), coinId)\n }\n\n const url = `${COINGECKO_API}?ids=${[...coinIds].join(',')}&vs_currencies=${currency}`\n\n const response = await fetch(url)\n if (!response.ok) {\n throw new Error(`CoinGecko API error: ${response.status} ${response.statusText}`)\n }\n\n const data = (await response.json()) as Record<string, Record<string, number>>\n\n // Map back to token symbols\n const prices: Record<string, number> = {}\n for (const token of tokens) {\n const coinId = tokenToCoinId.get(token.toUpperCase()) ?? token.toLowerCase()\n prices[token.toUpperCase()] = data[coinId]?.[currency] ?? 0\n }\n\n cache.set(cacheKey, { prices, timestamp: Date.now() })\n return prices\n}\n\n/**\n * Get simulated token prices for demo mode\n */\nexport function getTokenPricesDemo(tokens: string[]): Record<string, number> {\n const demoPrices: Record<string, number> = {\n ETH: 3250.42,\n MATIC: 0.58,\n AVAX: 24.15,\n BERA: 3.82,\n USDC: 1.0,\n USDT: 1.0,\n USDT0: 1.0,\n }\n\n const prices: Record<string, number> = {}\n for (const token of tokens) {\n prices[token.toUpperCase()] = demoPrices[token.toUpperCase()] ?? 0\n }\n return prices\n}\n\n/**\n * Clear the price cache (useful for testing)\n */\nexport function clearPriceCache(): void {\n cache.clear()\n}\n","/**\n * t402/getTokenPrice - Get current token prices via CoinGecko\n */\n\nimport { z } from 'zod'\nimport { getTokenPrices, getTokenPricesDemo } from './priceService.js'\n\n/**\n * Input schema for getTokenPrice tool\n */\nexport const getTokenPriceInputSchema = z.object({\n tokens: z\n .array(z.string())\n .min(1)\n .describe('Token symbols to get prices for (e.g., [\"ETH\", \"MATIC\", \"USDC\"])'),\n currency: z\n .string()\n .optional()\n .describe('Target currency (default: \"usd\"). Supports: usd, eur, gbp, etc.'),\n})\n\nexport type GetTokenPriceInput = z.infer<typeof getTokenPriceInputSchema>\n\n/**\n * Token price result\n */\nexport interface TokenPriceResult {\n prices: Record<string, number>\n currency: string\n}\n\n/**\n * Execute getTokenPrice tool\n */\nexport async function executeGetTokenPrice(\n input: GetTokenPriceInput,\n options: { demoMode?: boolean },\n): Promise<TokenPriceResult> {\n const currency = input.currency ?? 'usd'\n\n const prices = options.demoMode\n ? getTokenPricesDemo(input.tokens)\n : await getTokenPrices(input.tokens, currency)\n\n return { prices, currency }\n}\n\n/**\n * Format token price result for display\n */\nexport function formatTokenPriceResult(result: TokenPriceResult): string {\n const lines = ['## Token Prices', '']\n const currencyUpper = result.currency.toUpperCase()\n\n for (const [token, price] of Object.entries(result.prices)) {\n if (price > 0) {\n lines.push(`- **${token}:** ${price.toLocaleString()} ${currencyUpper}`)\n } else {\n lines.push(`- **${token}:** Price unavailable`)\n }\n }\n\n return lines.join('\\n')\n}\n","/**\n * t402/getGasPrice - Get current gas price for a network\n */\n\nimport { z } from 'zod'\nimport { createPublicClient, http, formatGwei } from 'viem'\nimport * as chains from 'viem/chains'\nimport type { SupportedNetwork } from '../types.js'\nimport { DEFAULT_RPC_URLS, NATIVE_SYMBOLS } from '../constants.js'\n\n/**\n * Input schema for getGasPrice tool\n */\nexport const getGasPriceInputSchema = z.object({\n network: z\n .enum([\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ])\n .describe('Blockchain network to check gas price on'),\n})\n\nexport type GetGasPriceInput = z.infer<typeof getGasPriceInputSchema>\n\n/**\n * Gas price result\n */\nexport interface GasPriceResult {\n network: SupportedNetwork\n gasPriceWei: string\n gasPriceGwei: string\n nativeSymbol: string\n}\n\n/**\n * Get the viem chain configuration for a network\n */\nfunction getViemChain(network: SupportedNetwork) {\n switch (network) {\n case 'ethereum':\n return chains.mainnet\n case 'base':\n return chains.base\n case 'arbitrum':\n return chains.arbitrum\n case 'optimism':\n return chains.optimism\n case 'polygon':\n return chains.polygon\n case 'avalanche':\n return chains.avalanche\n case 'ink':\n return chains.ink\n case 'berachain':\n return chains.berachain\n case 'unichain':\n return chains.unichain\n default:\n return chains.mainnet\n }\n}\n\n/**\n * Execute getGasPrice tool\n */\nexport async function executeGetGasPrice(\n input: GetGasPriceInput,\n options: { rpcUrl?: string; demoMode?: boolean },\n): Promise<GasPriceResult> {\n const { network } = input\n\n // Demo mode: return realistic values\n if (options.demoMode) {\n const demoGasPrices: Record<string, bigint> = {\n ethereum: 25000000000n, // 25 gwei\n base: 50000000n, // 0.05 gwei\n arbitrum: 100000000n, // 0.1 gwei\n optimism: 50000000n, // 0.05 gwei\n polygon: 30000000000n, // 30 gwei\n avalanche: 25000000000n, // 25 nAVAX\n ink: 50000000n, // 0.05 gwei\n berachain: 1000000000n, // 1 gwei\n unichain: 50000000n, // 0.05 gwei\n }\n\n const gasPrice = demoGasPrices[network] ?? 1000000000n\n return {\n network,\n gasPriceWei: gasPrice.toString(),\n gasPriceGwei: formatGwei(gasPrice),\n nativeSymbol: NATIVE_SYMBOLS[network],\n }\n }\n\n const chain = getViemChain(network)\n const transport = http(options.rpcUrl ?? DEFAULT_RPC_URLS[network])\n const client = createPublicClient({ chain, transport })\n\n const gasPrice = await client.getGasPrice()\n\n return {\n network,\n gasPriceWei: gasPrice.toString(),\n gasPriceGwei: formatGwei(gasPrice),\n nativeSymbol: NATIVE_SYMBOLS[network],\n }\n}\n\n/**\n * Format gas price result for display\n */\nexport function formatGasPriceResult(result: GasPriceResult): string {\n return [\n '## Gas Price',\n '',\n `- **Network:** ${result.network}`,\n `- **Gas Price:** ${result.gasPriceGwei} gwei`,\n `- **Native Token:** ${result.nativeSymbol}`,\n ].join('\\n')\n}\n","/**\n * t402/estimatePaymentFee - Estimate gas cost for a payment on a specific network\n */\n\nimport { z } from 'zod'\nimport { createPublicClient, http, formatEther, formatGwei, parseUnits } from 'viem'\nimport * as chains from 'viem/chains'\nimport type { SupportedNetwork } from '../types.js'\nimport { DEFAULT_RPC_URLS, NATIVE_SYMBOLS, getTokenAddress } from '../constants.js'\nimport { getTokenPrices } from './priceService.js'\n\n/**\n * Input schema for estimatePaymentFee tool\n */\nexport const estimatePaymentFeeInputSchema = z.object({\n network: z\n .enum([\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ])\n .describe('Network to estimate fee on'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Payment amount (e.g., '100')\"),\n token: z\n .enum(['USDC', 'USDT', 'USDT0'])\n .describe('Token to use for payment'),\n})\n\nexport type EstimatePaymentFeeInput = z.infer<typeof estimatePaymentFeeInputSchema>\n\n/**\n * Fee estimation result\n */\nexport interface PaymentFeeEstimate {\n network: SupportedNetwork\n gasLimit: string\n gasPriceGwei: string\n nativeCost: string\n nativeSymbol: string\n usdCost: string\n}\n\n/**\n * Get the viem chain configuration for a network\n */\nfunction getViemChain(network: SupportedNetwork) {\n switch (network) {\n case 'ethereum':\n return chains.mainnet\n case 'base':\n return chains.base\n case 'arbitrum':\n return chains.arbitrum\n case 'optimism':\n return chains.optimism\n case 'polygon':\n return chains.polygon\n case 'avalanche':\n return chains.avalanche\n case 'ink':\n return chains.ink\n case 'berachain':\n return chains.berachain\n case 'unichain':\n return chains.unichain\n default:\n return chains.mainnet\n }\n}\n\n/**\n * Execute estimatePaymentFee tool\n */\nexport async function executeEstimatePaymentFee(\n input: EstimatePaymentFeeInput,\n options: { rpcUrl?: string; demoMode?: boolean },\n): Promise<PaymentFeeEstimate> {\n const { network, amount, token } = input\n const nativeSymbol = NATIVE_SYMBOLS[network]\n\n // Demo mode: return simulated values\n if (options.demoMode) {\n const demoEstimates: Record<string, { gasLimit: bigint; gasPrice: bigint; nativePrice: number }> = {\n ethereum: { gasLimit: 65000n, gasPrice: 25000000000n, nativePrice: 3250.42 },\n base: { gasLimit: 65000n, gasPrice: 50000000n, nativePrice: 3250.42 },\n arbitrum: { gasLimit: 65000n, gasPrice: 100000000n, nativePrice: 3250.42 },\n optimism: { gasLimit: 65000n, gasPrice: 50000000n, nativePrice: 3250.42 },\n polygon: { gasLimit: 65000n, gasPrice: 30000000000n, nativePrice: 0.58 },\n avalanche: { gasLimit: 65000n, gasPrice: 25000000000n, nativePrice: 24.15 },\n ink: { gasLimit: 65000n, gasPrice: 50000000n, nativePrice: 3250.42 },\n berachain: { gasLimit: 65000n, gasPrice: 1000000000n, nativePrice: 3.82 },\n unichain: { gasLimit: 65000n, gasPrice: 50000000n, nativePrice: 3250.42 },\n }\n\n const est = demoEstimates[network] ?? demoEstimates['ethereum']\n const nativeCost = est.gasLimit * est.gasPrice\n const usdCost = (Number(nativeCost) / 1e18) * est.nativePrice\n\n return {\n network,\n gasLimit: est.gasLimit.toString(),\n gasPriceGwei: formatGwei(est.gasPrice),\n nativeCost: formatEther(nativeCost),\n nativeSymbol,\n usdCost: `$${usdCost.toFixed(4)}`,\n }\n }\n\n // Live mode\n const tokenAddress = getTokenAddress(network, token)\n if (!tokenAddress) {\n throw new Error(`Token ${token} is not supported on ${network}`)\n }\n\n const chain = getViemChain(network)\n const transport = http(options.rpcUrl ?? DEFAULT_RPC_URLS[network])\n const client = createPublicClient({ chain, transport })\n\n // Estimate gas for ERC20 transfer\n const amountBigInt = parseUnits(amount, 6)\n const dummyTo = '0x000000000000000000000000000000000000dEaD'\n\n let gasLimit: bigint\n try {\n gasLimit = await client.estimateGas({\n to: tokenAddress,\n data: `0xa9059cbb${dummyTo.slice(2).padStart(64, '0')}${amountBigInt.toString(16).padStart(64, '0')}` as `0x${string}`,\n })\n } catch {\n // Fallback to standard ERC20 transfer gas estimate\n gasLimit = 65000n\n }\n\n const gasPrice = await client.getGasPrice()\n const nativeCost = gasLimit * gasPrice\n\n // Get native token USD price\n let usdCost: string\n try {\n const prices = await getTokenPrices([nativeSymbol])\n const nativePrice = prices[nativeSymbol] ?? 0\n const cost = (Number(nativeCost) / 1e18) * nativePrice\n usdCost = `$${cost.toFixed(4)}`\n } catch {\n usdCost = 'N/A'\n }\n\n return {\n network,\n gasLimit: gasLimit.toString(),\n gasPriceGwei: formatGwei(gasPrice),\n nativeCost: formatEther(nativeCost),\n nativeSymbol,\n usdCost,\n }\n}\n\n/**\n * Format fee estimate result for display\n */\nexport function formatPaymentFeeEstimate(result: PaymentFeeEstimate): string {\n return [\n '## Payment Fee Estimate',\n '',\n `- **Network:** ${result.network}`,\n `- **Estimated Gas:** ${result.gasLimit}`,\n `- **Gas Price:** ${result.gasPriceGwei} gwei`,\n `- **Native Cost:** ${result.nativeCost} ${result.nativeSymbol}`,\n `- **USD Cost:** ${result.usdCost}`,\n ].join('\\n')\n}\n","/**\n * t402/compareNetworkFees - Compare payment fees across multiple networks\n */\n\nimport { z } from 'zod'\nimport type { SupportedNetwork } from '../types.js'\nimport { supportsToken } from '../constants.js'\nimport {\n executeEstimatePaymentFee,\n type PaymentFeeEstimate,\n} from './estimatePaymentFee.js'\n\n/**\n * Input schema for compareNetworkFees tool\n */\nexport const compareNetworkFeesInputSchema = z.object({\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Payment amount (e.g., '100')\"),\n token: z\n .enum(['USDC', 'USDT', 'USDT0'])\n .describe('Token to use for payment'),\n networks: z\n .array(z.string())\n .optional()\n .describe(\n 'Networks to compare. If not provided, compares all networks that support the token.',\n ),\n})\n\nexport type CompareNetworkFeesInput = z.infer<typeof compareNetworkFeesInputSchema>\n\n/**\n * All supported networks\n */\nconst ALL_NETWORKS: SupportedNetwork[] = [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n]\n\n/**\n * Network fee comparison result\n */\nexport interface NetworkFeeComparison {\n token: string\n amount: string\n fees: PaymentFeeEstimate[]\n cheapest: string\n}\n\n/**\n * Execute compareNetworkFees tool\n */\nexport async function executeCompareNetworkFees(\n input: CompareNetworkFeesInput,\n options: { rpcUrls?: Partial<Record<SupportedNetwork, string>>; demoMode?: boolean },\n): Promise<NetworkFeeComparison> {\n const { amount, token } = input\n\n // Determine networks to compare\n const requestedNetworks = input.networks\n ? (input.networks as SupportedNetwork[])\n : ALL_NETWORKS\n\n // Filter to networks that support the token\n const networks = requestedNetworks.filter((n) => supportsToken(n, token))\n\n if (networks.length === 0) {\n throw new Error(`No supported networks found for token ${token}`)\n }\n\n // Estimate fees in parallel\n const results = await Promise.allSettled(\n networks.map((network) =>\n executeEstimatePaymentFee(\n { network, amount, token },\n {\n rpcUrl: options.rpcUrls?.[network],\n demoMode: options.demoMode,\n },\n ),\n ),\n )\n\n // Collect successful results\n const fees: PaymentFeeEstimate[] = []\n for (const result of results) {\n if (result.status === 'fulfilled') {\n fees.push(result.value)\n }\n }\n\n if (fees.length === 0) {\n throw new Error('Failed to estimate fees on any network')\n }\n\n // Sort by native cost ascending\n fees.sort((a, b) => {\n const costA = parseFloat(a.nativeCost) || Infinity\n const costB = parseFloat(b.nativeCost) || Infinity\n // Compare USD costs when available\n const usdA = parseFloat(a.usdCost.replace('$', '')) || Infinity\n const usdB = parseFloat(b.usdCost.replace('$', '')) || Infinity\n return usdA - usdB || costA - costB\n })\n\n return {\n token,\n amount,\n fees,\n cheapest: fees[0].network,\n }\n}\n\n/**\n * Format network fee comparison result for display\n */\nexport function formatNetworkFeeComparison(result: NetworkFeeComparison): string {\n const lines = [\n '## Network Fee Comparison',\n '',\n `**Token:** ${result.token} | **Amount:** ${result.amount}`,\n `**Cheapest:** ${result.cheapest}`,\n '',\n '| Network | Gas Price | Native Cost | USD Cost |',\n '|---------|----------|-------------|----------|',\n ]\n\n for (const fee of result.fees) {\n const marker = fee.network === result.cheapest ? ' *' : ''\n lines.push(\n `| ${fee.network}${marker} | ${fee.gasPriceGwei} gwei | ${fee.nativeCost} ${fee.nativeSymbol} | ${fee.usdCost} |`,\n )\n }\n\n return lines.join('\\n')\n}\n","/**\n * Quote Store - In-memory quote storage with TTL\n */\n\nimport { randomUUID } from 'crypto'\n\n/** Default quote TTL in milliseconds (5 minutes) */\nconst DEFAULT_TTL_MS = 5 * 60 * 1000\n\n/** Quote data stored in the quote store */\nexport interface QuoteData {\n id: string\n type: 'swap' | 'bridge'\n createdAt: number\n expiresAt: number\n data: Record<string, unknown>\n}\n\n/** In-memory quote store */\nconst quotes = new Map<string, QuoteData>()\n\n/** Cleanup interval handle */\nlet cleanupInterval: ReturnType<typeof setInterval> | null = null\n\n/**\n * Start auto-cleanup of expired quotes (runs every 60s)\n */\nfunction ensureCleanup(): void {\n if (cleanupInterval) return\n cleanupInterval = setInterval(() => {\n const now = Date.now()\n for (const [id, quote] of quotes) {\n if (now > quote.expiresAt) {\n quotes.delete(id)\n }\n }\n }, 60_000)\n // Allow process to exit without waiting for cleanup\n if (cleanupInterval.unref) {\n cleanupInterval.unref()\n }\n}\n\n/**\n * Create a new quote and store it\n *\n * @param type - Quote type ('swap' or 'bridge')\n * @param data - Quote data to store\n * @param ttlMs - Time-to-live in milliseconds (default: 5 minutes)\n * @returns Quote ID (UUID)\n */\nexport function createQuote(\n type: 'swap' | 'bridge',\n data: Record<string, unknown>,\n ttlMs: number = DEFAULT_TTL_MS,\n): string {\n ensureCleanup()\n const id = randomUUID()\n const now = Date.now()\n quotes.set(id, {\n id,\n type,\n createdAt: now,\n expiresAt: now + ttlMs,\n data,\n })\n return id\n}\n\n/**\n * Get a quote by ID (returns null if expired or not found)\n */\nexport function getQuote(quoteId: string): QuoteData | null {\n const quote = quotes.get(quoteId)\n if (!quote) return null\n if (Date.now() > quote.expiresAt) {\n quotes.delete(quoteId)\n return null\n }\n return quote\n}\n\n/**\n * Delete a quote by ID\n */\nexport function deleteQuote(quoteId: string): void {\n quotes.delete(quoteId)\n}\n\n/**\n * Clear all quotes (useful for testing)\n */\nexport function clearQuoteStore(): void {\n quotes.clear()\n}\n","/**\n * wdk/quoteSwap - Get a swap quote with a stored quoteId\n */\n\nimport { z } from 'zod'\nimport type { T402WDK } from '@t402/wdk'\nimport { parseUnits } from 'viem'\nimport { createQuote } from './quoteStore.js'\n\n/**\n * Input schema for wdk/quoteSwap tool\n */\nexport const wdkQuoteSwapInputSchema = z.object({\n fromToken: z.string().describe('Token to swap from (e.g., \"ETH\", \"USDC\")'),\n toToken: z.string().describe('Token to swap to (e.g., \"USDT0\", \"USDC\")'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount to swap (e.g., '1.0')\"),\n chain: z.string().describe('Chain to execute swap on (e.g., \"ethereum\", \"arbitrum\")'),\n})\n\nexport type WdkQuoteSwapInput = z.infer<typeof wdkQuoteSwapInputSchema>\n\n/**\n * Swap quote result\n */\nexport interface SwapQuoteResult {\n quoteId: string\n fromToken: string\n toToken: string\n fromAmount: string\n toAmount: string\n exchangeRate: string\n fee: string\n priceImpact: string\n expiresAt: string\n chain: string\n}\n\n/**\n * Execute wdk/quoteSwap tool\n */\nexport async function executeWdkQuoteSwap(\n input: WdkQuoteSwapInput,\n wdk: T402WDK,\n): Promise<SwapQuoteResult> {\n const decimals = ['USDC', 'USDT', 'USDT0'].includes(input.fromToken.toUpperCase()) ? 6 : 18\n const amountBigInt = parseUnits(input.amount, decimals)\n\n const quote = await wdk.getSwapQuote(input.chain, input.fromToken, amountBigInt)\n\n const outputDecimals = ['USDC', 'USDT', 'USDT0'].includes(input.toToken.toUpperCase()) ? 6 : 18\n const outputDivisor = 10 ** outputDecimals\n const toAmount = (Number(quote.outputAmount) / outputDivisor).toFixed(outputDecimals === 6 ? 6 : 8)\n\n const inputAmount = parseFloat(input.amount)\n const outputAmount = parseFloat(toAmount)\n const exchangeRate = inputAmount > 0 ? (outputAmount / inputAmount).toFixed(6) : '0'\n\n const expiresAt = new Date(Date.now() + 5 * 60 * 1000).toISOString()\n\n const quoteId = createQuote('swap', {\n fromToken: input.fromToken,\n toToken: input.toToken,\n fromAmount: input.amount,\n toAmount,\n chain: input.chain,\n exchangeRate,\n })\n\n return {\n quoteId,\n fromToken: input.fromToken,\n toToken: input.toToken,\n fromAmount: input.amount,\n toAmount,\n exchangeRate,\n fee: '0.3%',\n priceImpact: '< 0.1%',\n expiresAt,\n chain: input.chain,\n }\n}\n\n/**\n * Execute wdk/quoteSwap in demo mode\n */\nexport function executeWdkQuoteSwapDemo(input: WdkQuoteSwapInput): SwapQuoteResult {\n const inputAmount = parseFloat(input.amount)\n const toAmount = (inputAmount * 0.997).toFixed(6) // ~0.3% fee\n const exchangeRate = (0.997).toFixed(6)\n\n const expiresAt = new Date(Date.now() + 5 * 60 * 1000).toISOString()\n\n const quoteId = createQuote('swap', {\n fromToken: input.fromToken,\n toToken: input.toToken,\n fromAmount: input.amount,\n toAmount,\n chain: input.chain,\n exchangeRate,\n })\n\n return {\n quoteId,\n fromToken: input.fromToken,\n toToken: input.toToken,\n fromAmount: input.amount,\n toAmount,\n exchangeRate,\n fee: '0.3%',\n priceImpact: '< 0.1%',\n expiresAt,\n chain: input.chain,\n }\n}\n\n/**\n * Format swap quote result for display\n */\nexport function formatSwapQuoteResult(result: SwapQuoteResult): string {\n return [\n '## Swap Quote',\n '',\n `- **Quote ID:** \\`${result.quoteId}\\``,\n `- **From:** ${result.fromAmount} ${result.fromToken}`,\n `- **To:** ${result.toAmount} ${result.toToken}`,\n `- **Exchange Rate:** ${result.exchangeRate}`,\n `- **Fee:** ${result.fee}`,\n `- **Price Impact:** ${result.priceImpact}`,\n `- **Chain:** ${result.chain}`,\n `- **Expires:** ${result.expiresAt}`,\n '',\n '_Call `wdk/executeSwap` with the quoteId to execute this swap._',\n ].join('\\n')\n}\n","/**\n * wdk/executeSwap - Execute a swap from a stored quote\n */\n\nimport { z } from 'zod'\nimport type { T402WDK } from '@t402/wdk'\nimport { parseUnits } from 'viem'\nimport { getQuote, deleteQuote } from './quoteStore.js'\n\n/**\n * Input schema for wdk/executeSwap tool\n */\nexport const wdkExecuteSwapInputSchema = z.object({\n quoteId: z.string().uuid().describe('Quote ID from wdk/quoteSwap'),\n confirmed: z\n .boolean()\n .optional()\n .describe('Set to true to confirm and execute this swap'),\n})\n\nexport type WdkExecuteSwapInput = z.infer<typeof wdkExecuteSwapInputSchema>\n\n/**\n * Execute swap result\n */\nexport interface ExecuteSwapResult {\n fromAmount: string\n fromToken: string\n toAmount: string\n toToken: string\n chain: string\n txHash: string\n}\n\n/**\n * Execute wdk/executeSwap tool\n */\nexport async function executeWdkExecuteSwap(\n input: WdkExecuteSwapInput,\n wdk: T402WDK,\n): Promise<\n ExecuteSwapResult | { needsConfirmation: true; summary: string; details: Record<string, string> }\n> {\n const quote = getQuote(input.quoteId)\n if (!quote) {\n throw new Error('Quote not found or expired. Please request a new quote.')\n }\n if (quote.type !== 'swap') {\n throw new Error('Invalid quote type. Expected a swap quote.')\n }\n\n const { fromToken, toToken, fromAmount, toAmount, chain } = quote.data as {\n fromToken: string\n toToken: string\n fromAmount: string\n toAmount: string\n chain: string\n }\n\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Swap ${fromAmount} ${fromToken} to ${toAmount} ${toToken} on ${chain}`,\n details: { fromToken, toToken, fromAmount, toAmount, chain, quoteId: input.quoteId },\n }\n }\n\n // Execute the swap\n const decimals = ['USDC', 'USDT', 'USDT0'].includes(fromToken.toUpperCase()) ? 6 : 18\n const amountBigInt = parseUnits(fromAmount, decimals)\n\n const result = await wdk.swapAndPay({\n chain,\n fromToken,\n amount: amountBigInt,\n })\n\n // Consume the quote\n deleteQuote(input.quoteId)\n\n return {\n fromAmount,\n fromToken,\n toAmount,\n toToken,\n chain,\n txHash: result?.txHash ?? '0x',\n }\n}\n\n/**\n * Execute wdk/executeSwap in demo mode\n */\nexport function executeWdkExecuteSwapDemo(\n input: WdkExecuteSwapInput,\n): ExecuteSwapResult | { needsConfirmation: true; summary: string; details: Record<string, string> } {\n const quote = getQuote(input.quoteId)\n if (!quote) {\n throw new Error('Quote not found or expired. Please request a new quote.')\n }\n if (quote.type !== 'swap') {\n throw new Error('Invalid quote type. Expected a swap quote.')\n }\n\n const { fromToken, toToken, fromAmount, toAmount, chain } = quote.data as {\n fromToken: string\n toToken: string\n fromAmount: string\n toAmount: string\n chain: string\n }\n\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Swap ${fromAmount} ${fromToken} to ${toAmount} ${toToken} on ${chain}`,\n details: { fromToken, toToken, fromAmount, toAmount, chain, quoteId: input.quoteId },\n }\n }\n\n // Consume the quote\n deleteQuote(input.quoteId)\n\n return {\n fromAmount,\n fromToken,\n toAmount,\n toToken,\n chain,\n txHash: '0xdemo' + Math.random().toString(16).slice(2, 10),\n }\n}\n\n/**\n * Format execute swap result for display\n */\nexport function formatExecuteSwapResult(result: ExecuteSwapResult): string {\n return [\n '## Swap Executed',\n '',\n `- **From:** ${result.fromAmount} ${result.fromToken}`,\n `- **To:** ${result.toAmount} ${result.toToken}`,\n `- **Chain:** ${result.chain}`,\n `- **Tx Hash:** \\`${result.txHash}\\``,\n ].join('\\n')\n}\n","/**\n * t402/quoteBridge - Get a bridge fee quote with a stored quoteId\n */\n\nimport { z } from 'zod'\nimport type { SupportedNetwork } from '../types.js'\nimport { createQuote } from './quoteStore.js'\nimport { executeGetBridgeFee, type GetBridgeFeeInput } from './getBridgeFee.js'\n\n/**\n * Input schema for t402/quoteBridge tool (same as getBridgeFee)\n */\nexport const quoteBridgeInputSchema = z.object({\n fromChain: z\n .enum(['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'])\n .describe('Source chain to bridge from'),\n toChain: z\n .enum(['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'])\n .describe('Destination chain to bridge to'),\n amount: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .describe(\"Amount of USDT0 to bridge (e.g., '100' for 100 USDT0)\"),\n recipient: z\n .string()\n .regex(/^0x[a-fA-F0-9]{40}$/)\n .describe('Recipient address on destination chain'),\n})\n\nexport type QuoteBridgeInput = z.infer<typeof quoteBridgeInputSchema>\n\n/**\n * Bridge quote result\n */\nexport interface BridgeQuoteResult {\n quoteId: string\n fromChain: string\n toChain: string\n amount: string\n recipient: string\n nativeFee: string\n nativeFeeFormatted: string\n estimatedTime: number\n expiresAt: string\n}\n\n/**\n * Execute t402/quoteBridge tool\n */\nexport async function executeQuoteBridge(\n input: QuoteBridgeInput,\n rpcUrls?: Partial<Record<SupportedNetwork, string>>,\n): Promise<BridgeQuoteResult> {\n // Get the actual fee quote\n const feeResult = await executeGetBridgeFee(input as GetBridgeFeeInput, rpcUrls)\n\n const expiresAt = new Date(Date.now() + 5 * 60 * 1000).toISOString()\n\n const quoteId = createQuote('bridge', {\n fromChain: input.fromChain,\n toChain: input.toChain,\n amount: input.amount,\n recipient: input.recipient,\n nativeFee: feeResult.nativeFee,\n nativeFeeFormatted: feeResult.nativeFeeFormatted,\n estimatedTime: feeResult.estimatedTime,\n })\n\n return {\n quoteId,\n fromChain: input.fromChain,\n toChain: input.toChain,\n amount: input.amount,\n recipient: input.recipient,\n nativeFee: feeResult.nativeFee,\n nativeFeeFormatted: feeResult.nativeFeeFormatted,\n estimatedTime: feeResult.estimatedTime,\n expiresAt,\n }\n}\n\n/**\n * Execute t402/quoteBridge in demo mode\n */\nexport function executeQuoteBridgeDemo(input: QuoteBridgeInput): BridgeQuoteResult {\n const expiresAt = new Date(Date.now() + 5 * 60 * 1000).toISOString()\n const estimatedTime = input.toChain === 'ethereum' ? 900 : 300\n\n const quoteId = createQuote('bridge', {\n fromChain: input.fromChain,\n toChain: input.toChain,\n amount: input.amount,\n recipient: input.recipient,\n nativeFee: '1000000000000000',\n nativeFeeFormatted: '0.001 ETH',\n estimatedTime,\n })\n\n return {\n quoteId,\n fromChain: input.fromChain,\n toChain: input.toChain,\n amount: input.amount,\n recipient: input.recipient,\n nativeFee: '1000000000000000',\n nativeFeeFormatted: '0.001 ETH',\n estimatedTime,\n expiresAt,\n }\n}\n\n/**\n * Format bridge quote result for display\n */\nexport function formatBridgeQuoteResult(result: BridgeQuoteResult): string {\n const minutes = Math.ceil(result.estimatedTime / 60)\n return [\n '## Bridge Quote',\n '',\n `- **Quote ID:** \\`${result.quoteId}\\``,\n `- **Route:** ${result.fromChain} -> ${result.toChain}`,\n `- **Amount:** ${result.amount} USDT0`,\n `- **Recipient:** \\`${result.recipient}\\``,\n `- **Fee:** ${result.nativeFeeFormatted}`,\n `- **Estimated Time:** ~${minutes} minutes`,\n `- **Expires:** ${result.expiresAt}`,\n '',\n '_Call `t402/executeBridge` with the quoteId to execute this bridge._',\n ].join('\\n')\n}\n","/**\n * t402/executeBridge (from quote) - Execute a bridge from a stored quote\n */\n\nimport { z } from 'zod'\nimport type { SupportedNetwork, BridgeResult } from '../types.js'\nimport { getQuote, deleteQuote } from './quoteStore.js'\nimport { executeBridge } from './bridge.js'\n\n/**\n * Input schema for t402/executeBridge tool\n */\nexport const executeBridgeFromQuoteInputSchema = z.object({\n quoteId: z.string().uuid().describe('Quote ID from t402/quoteBridge'),\n confirmed: z\n .boolean()\n .optional()\n .describe('Set to true to confirm and execute this bridge'),\n})\n\nexport type ExecuteBridgeFromQuoteInput = z.infer<typeof executeBridgeFromQuoteInputSchema>\n\n/**\n * Execute t402/executeBridge from quote tool\n */\nexport async function executeExecuteBridgeFromQuote(\n input: ExecuteBridgeFromQuoteInput,\n options: { privateKey: string; rpcUrl?: string; demoMode?: boolean },\n): Promise<\n BridgeResult | { needsConfirmation: true; summary: string; details: Record<string, string> }\n> {\n const quote = getQuote(input.quoteId)\n if (!quote) {\n throw new Error('Quote not found or expired. Please request a new quote.')\n }\n if (quote.type !== 'bridge') {\n throw new Error('Invalid quote type. Expected a bridge quote.')\n }\n\n const { fromChain, toChain, amount, recipient } = quote.data as {\n fromChain: string\n toChain: string\n amount: string\n recipient: string\n }\n\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Bridge ${amount} USDT0 from ${fromChain} to ${toChain}`,\n details: { fromChain, toChain, amount, recipient, quoteId: input.quoteId },\n }\n }\n\n // Execute the bridge using existing bridge function\n const result = await executeBridge(\n { fromChain: fromChain as 'ethereum', toChain: toChain as 'ethereum', amount, recipient, confirmed: true },\n options,\n )\n\n // The result could be a confirmation (shouldn't be since we set confirmed: true)\n if ('needsConfirmation' in result) {\n return result\n }\n\n // Consume the quote\n deleteQuote(input.quoteId)\n\n return result\n}\n\n/**\n * Execute t402/executeBridge from quote in demo mode\n */\nexport function executeExecuteBridgeFromQuoteDemo(\n input: ExecuteBridgeFromQuoteInput,\n): BridgeResult | { needsConfirmation: true; summary: string; details: Record<string, string> } {\n const quote = getQuote(input.quoteId)\n if (!quote) {\n throw new Error('Quote not found or expired. Please request a new quote.')\n }\n if (quote.type !== 'bridge') {\n throw new Error('Invalid quote type. Expected a bridge quote.')\n }\n\n const { fromChain, toChain, amount, recipient } = quote.data as {\n fromChain: string\n toChain: string\n amount: string\n recipient: string\n }\n\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Bridge ${amount} USDT0 from ${fromChain} to ${toChain}`,\n details: { fromChain, toChain, amount, recipient, quoteId: input.quoteId },\n }\n }\n\n // Consume the quote\n deleteQuote(input.quoteId)\n\n const fakeTxHash = `0x${'a'.repeat(64)}` as `0x${string}`\n const fakeGuid = `0x${'b'.repeat(64)}` as `0x${string}`\n\n return {\n txHash: fakeTxHash,\n messageGuid: fakeGuid,\n amount,\n fromChain: fromChain as SupportedNetwork,\n toChain: toChain as SupportedNetwork,\n estimatedTime: (quote.data.estimatedTime as number) ?? 300,\n trackingUrl: `https://layerzeroscan.com/tx/${fakeGuid}`,\n }\n}\n\n/**\n * Format execute bridge result for display (reuses bridge format)\n */\nexport { formatBridgeResult as formatExecuteBridgeFromQuoteResult } from './bridge.js'\n","/**\n * Unified MCP Toolkit - Combines WDK wallet tools with t402 payment tools.\n *\n * Agent workflow: check price -> check balance -> bridge if needed -> pay\n * All in one MCP session with a single server.\n */\n\nimport { z } from 'zod'\nimport type { T402WDK } from '@t402/wdk'\n\n/**\n * Configuration for unified MCP mode\n */\nexport interface UnifiedMcpConfig {\n /** WDK seed phrase for wallet management */\n wdkSeedPhrase?: string\n /** Chain RPC configurations */\n chains?: Record<string, string | string[]>\n /** Enable auto-pay mode (automatic balance check + bridge + pay) */\n autoPayEnabled?: boolean\n}\n\n/**\n * SmartPay input schema\n */\nexport const smartPayInputSchema = z.object({\n url: z.string().url().describe('URL of the 402-protected resource'),\n maxBridgeFee: z\n .string()\n .regex(/^\\d+(\\.\\d+)?$/)\n .optional()\n .describe('Maximum acceptable bridge fee in native token (optional)'),\n preferredNetwork: z.string().optional().describe('Preferred network for payment (optional)'),\n confirmed: z\n .boolean()\n .optional()\n .describe('Set to true to confirm and execute this payment'),\n})\n\nexport type SmartPayInput = z.infer<typeof smartPayInputSchema>\n\n/**\n * SmartPay result\n */\nexport interface SmartPayResult {\n /** Whether the resource was successfully accessed */\n success: boolean\n /** HTTP status code */\n statusCode: number\n /** Response body (truncated if large) */\n body: string\n /** Content type of the response */\n contentType?: string\n /** Steps taken during smart payment */\n steps: SmartPayStep[]\n /** Payment details (if payment was made) */\n payment?: {\n network: string\n scheme: string\n amount: string\n payTo: string\n }\n /** Error message (if failed) */\n error?: string\n}\n\n/**\n * A step in the smart payment flow\n */\nexport interface SmartPayStep {\n action: 'check_price' | 'check_balance' | 'bridge' | 'pay' | 'fetch'\n status: 'success' | 'skipped' | 'failed'\n detail: string\n}\n\n/**\n * PaymentPlan input schema\n */\nexport const paymentPlanInputSchema = z.object({\n paymentRequired: z\n .object({\n scheme: z.string().optional(),\n network: z.string().optional(),\n maxAmountRequired: z.string().optional(),\n resource: z.string().optional(),\n description: z.string().optional(),\n payTo: z.string().optional(),\n maxDeadline: z.number().optional(),\n })\n .passthrough()\n .describe('The 402 PaymentRequired response'),\n})\n\nexport type PaymentPlanInput = z.infer<typeof paymentPlanInputSchema>\n\n/**\n * Payment plan result\n */\nexport interface PaymentPlanResult {\n /** Whether a viable plan was found */\n viable: boolean\n /** Recommended network to pay on */\n recommendedNetwork?: string\n /** Available balance on that network */\n availableBalance?: string\n /** Whether bridging is needed */\n bridgeRequired: boolean\n /** Bridge details if needed */\n bridgeDetails?: {\n fromChain: string\n toChain: string\n amount: string\n estimatedFee: string\n }\n /** Balances across all chains */\n balances: Array<{\n chain: string\n usdt0: string\n usdc: string\n }>\n /** Reason if not viable */\n reason?: string\n}\n\n/**\n * Unified tool definitions (additional tools beyond base + WDK)\n */\nexport const UNIFIED_TOOL_DEFINITIONS = {\n 't402/smartPay': {\n name: 't402/smartPay',\n description:\n 'Intelligent payment that automatically checks balance, bridges if needed, and pays. Handles the entire payment flow for 402-protected resources.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n url: { type: 'string', description: 'URL of the 402-protected resource' },\n maxBridgeFee: {\n type: 'string',\n description: 'Maximum acceptable bridge fee in native token (optional)',\n },\n preferredNetwork: {\n type: 'string',\n description: 'Preferred network for payment (optional)',\n },\n confirmed: {\n type: 'boolean',\n description:\n 'Set to true to confirm and execute. Omit for a preview/confirmation prompt.',\n },\n },\n required: ['url'],\n },\n },\n 't402/paymentPlan': {\n name: 't402/paymentPlan',\n description:\n 'Analyze a 402 response and create an optimal payment plan considering balances across all chains. Returns recommended network, bridge requirements, and balance overview.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n paymentRequired: {\n type: 'object',\n description: 'The 402 PaymentRequired response',\n },\n },\n required: ['paymentRequired'],\n },\n },\n} as const\n\n/**\n * Execute t402/smartPay tool\n */\nexport async function executeSmartPay(\n input: SmartPayInput,\n wdk: T402WDK,\n): Promise<SmartPayResult | { needsConfirmation: true; summary: string; details: Record<string, string> }> {\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Smart-pay for ${input.url}${input.preferredNetwork ? ` on ${input.preferredNetwork}` : ''}`,\n details: {\n url: input.url,\n ...(input.maxBridgeFee ? { maxBridgeFee: input.maxBridgeFee } : {}),\n ...(input.preferredNetwork ? { preferredNetwork: input.preferredNetwork } : {}),\n },\n }\n }\n\n const steps: SmartPayStep[] = []\n const chains = input.preferredNetwork\n ? [input.preferredNetwork]\n : ['ethereum', 'arbitrum', 'base']\n\n // Step 1: Check balances\n steps.push({\n action: 'check_balance',\n status: 'success',\n detail: `Checking balances on ${chains.join(', ')}`,\n })\n\n // Step 2: Create protocol and fetch\n const { T402Protocol } = await import('@t402/wdk-protocol')\n const protocol = await T402Protocol.create(wdk, { chains })\n\n steps.push({\n action: 'fetch',\n status: 'success',\n detail: `Fetching ${input.url}`,\n })\n\n const { response, receipt } = await protocol.fetch(input.url)\n\n if (receipt) {\n steps.push({\n action: 'pay',\n status: 'success',\n detail: `Payment made: ${receipt.amount} on ${receipt.network}`,\n })\n }\n\n // Read response body\n const contentType = response.headers.get('content-type') ?? undefined\n let body = ''\n try {\n body = await response.text()\n if (body.length > 10000) {\n body = body.slice(0, 10000) + '\\n... (truncated)'\n }\n } catch {\n body = '[Could not read response body]'\n }\n\n return {\n success: response.ok,\n statusCode: response.status,\n body,\n contentType,\n steps,\n payment: receipt\n ? {\n network: receipt.network,\n scheme: receipt.scheme,\n amount: receipt.amount,\n payTo: receipt.payTo,\n }\n : undefined,\n }\n}\n\n/**\n * Execute t402/smartPay in demo mode\n */\nexport function executeSmartPayDemo(\n input: SmartPayInput,\n): SmartPayResult | { needsConfirmation: true; summary: string; details: Record<string, string> } {\n // Elicitation: return confirmation prompt if not confirmed\n if (!input.confirmed) {\n return {\n needsConfirmation: true,\n summary: `Smart-pay for ${input.url}${input.preferredNetwork ? ` on ${input.preferredNetwork}` : ''}`,\n details: {\n url: input.url,\n ...(input.maxBridgeFee ? { maxBridgeFee: input.maxBridgeFee } : {}),\n ...(input.preferredNetwork ? { preferredNetwork: input.preferredNetwork } : {}),\n },\n }\n }\n\n const network = input.preferredNetwork ?? 'arbitrum'\n\n return {\n success: true,\n statusCode: 200,\n body: `[Demo] Premium content from ${input.url}\\n\\nThis is simulated content returned after smart payment.`,\n contentType: 'text/plain',\n steps: [\n { action: 'check_balance', status: 'success', detail: `Checked balances on ${network}` },\n { action: 'check_price', status: 'success', detail: 'Resource costs 1.00 USDT0' },\n { action: 'pay', status: 'success', detail: `Paid 1000000 USDT0 on eip155:42161` },\n { action: 'fetch', status: 'success', detail: `Fetched ${input.url}` },\n ],\n payment: {\n network: 'eip155:42161',\n scheme: 'exact',\n amount: '1000000',\n payTo: '0xC88f67e776f16DcFBf42e6bDda1B82604448899B',\n },\n }\n}\n\n/**\n * Execute t402/paymentPlan tool\n */\nexport async function executePaymentPlan(\n input: PaymentPlanInput,\n wdk: T402WDK,\n): Promise<PaymentPlanResult> {\n const targetNetwork = input.paymentRequired.network as string | undefined\n const requiredAmount = input.paymentRequired.maxAmountRequired as string | undefined\n\n // Get aggregated balances\n const aggregated = await wdk.getAggregatedBalances()\n\n const balances = aggregated.chains.map((chain) => {\n const usdt0 = chain.tokens.find((t) => t.symbol === 'USDT0')\n const usdc = chain.tokens.find((t) => t.symbol === 'USDC')\n return {\n chain: chain.chain,\n usdt0: usdt0?.formatted ?? '0',\n usdc: usdc?.formatted ?? '0',\n }\n })\n\n // Find chain with sufficient balance\n const requiredBigint = requiredAmount ? BigInt(requiredAmount) : 0n\n const bestChain = await wdk.findBestChainForPayment(requiredBigint)\n\n if (bestChain) {\n const needsBridge = targetNetwork ? !bestChain.chain.includes(targetNetwork) : false\n\n return {\n viable: true,\n recommendedNetwork: bestChain.chain,\n availableBalance: bestChain.balance.toString(),\n bridgeRequired: needsBridge,\n bridgeDetails: needsBridge\n ? {\n fromChain: bestChain.chain,\n toChain: targetNetwork ?? bestChain.chain,\n amount: requiredAmount ?? '0',\n estimatedFee: '0.001',\n }\n : undefined,\n balances,\n }\n }\n\n return {\n viable: false,\n bridgeRequired: false,\n balances,\n reason: 'Insufficient balance across all chains',\n }\n}\n\n/**\n * Execute t402/paymentPlan in demo mode\n */\nexport function executePaymentPlanDemo(_input: PaymentPlanInput): PaymentPlanResult {\n return {\n viable: true,\n recommendedNetwork: 'arbitrum',\n availableBalance: '500000000',\n bridgeRequired: false,\n balances: [\n { chain: 'ethereum', usdt0: '100.00', usdc: '250.00' },\n { chain: 'arbitrum', usdt0: '500.00', usdc: '0' },\n { chain: 'base', usdt0: '50.00', usdc: '100.00' },\n ],\n }\n}\n\n/**\n * Format smartPay result for display\n */\nexport function formatSmartPayResult(result: SmartPayResult): string {\n const lines: string[] = ['## SmartPay Result', '']\n\n if (result.success) {\n lines.push(`**Status:** Success (${result.statusCode})`)\n } else {\n lines.push(`**Status:** Failed (${result.statusCode})`)\n }\n\n // Steps\n if (result.steps.length > 0) {\n lines.push('')\n lines.push('### Steps')\n for (const step of result.steps) {\n const icon =\n step.status === 'success' ? '[OK]' : step.status === 'skipped' ? '[SKIP]' : '[FAIL]'\n lines.push(`- ${icon} **${step.action}**: ${step.detail}`)\n }\n }\n\n // Payment\n if (result.payment) {\n lines.push('')\n lines.push('### Payment Details')\n lines.push(`- **Network:** ${result.payment.network}`)\n lines.push(`- **Scheme:** ${result.payment.scheme}`)\n lines.push(`- **Amount:** ${result.payment.amount}`)\n lines.push(`- **Pay To:** \\`${result.payment.payTo}\\``)\n }\n\n if (result.error) {\n lines.push('')\n lines.push(`**Error:** ${result.error}`)\n }\n\n if (result.body) {\n lines.push('')\n lines.push('### Response Content')\n if (result.contentType) {\n lines.push(`_Content-Type: ${result.contentType}_`)\n }\n lines.push('')\n lines.push('```')\n lines.push(result.body)\n lines.push('```')\n }\n\n return lines.join('\\n')\n}\n\n/**\n * Format paymentPlan result for display\n */\nexport function formatPaymentPlanResult(result: PaymentPlanResult): string {\n const lines: string[] = ['## Payment Plan', '']\n\n if (result.viable) {\n lines.push(`**Viable:** Yes`)\n if (result.recommendedNetwork) {\n lines.push(`**Recommended Network:** ${result.recommendedNetwork}`)\n }\n if (result.availableBalance) {\n lines.push(`**Available Balance:** ${result.availableBalance}`)\n }\n } else {\n lines.push(`**Viable:** No`)\n if (result.reason) {\n lines.push(`**Reason:** ${result.reason}`)\n }\n }\n\n if (result.bridgeRequired && result.bridgeDetails) {\n lines.push('')\n lines.push('### Bridge Required')\n lines.push(`- **From:** ${result.bridgeDetails.fromChain}`)\n lines.push(`- **To:** ${result.bridgeDetails.toChain}`)\n lines.push(`- **Amount:** ${result.bridgeDetails.amount}`)\n lines.push(`- **Estimated Fee:** ${result.bridgeDetails.estimatedFee}`)\n }\n\n if (result.balances.length > 0) {\n lines.push('')\n lines.push('### Chain Balances')\n lines.push('| Chain | USDT0 | USDC |')\n lines.push('|-------|-------|------|')\n for (const b of result.balances) {\n lines.push(`| ${b.chain} | ${b.usdt0} | ${b.usdc} |`)\n }\n }\n\n return lines.join('\\n')\n}\n","/**\n * t402 MCP Tools - Export all payment tools\n */\n\n// Balance tools\nexport {\n getBalanceInputSchema,\n executeGetBalance,\n formatBalanceResult,\n type GetBalanceInput,\n} from './getBalance.js'\n\nexport {\n getAllBalancesInputSchema,\n executeGetAllBalances,\n formatAllBalancesResult,\n type GetAllBalancesInput,\n type AllBalancesResult,\n} from './getAllBalances.js'\n\n// Payment tools\nexport {\n payInputSchema,\n executePay,\n formatPaymentResult,\n type PayInput,\n type PayOptions,\n} from './pay.js'\n\nexport {\n payGaslessInputSchema,\n executePayGasless,\n formatGaslessPaymentResult,\n GASLESS_SUPPORTED_NETWORKS,\n type PayGaslessInput,\n type PayGaslessOptions,\n} from './payGasless.js'\n\n// Bridge tools\nexport {\n getBridgeFeeInputSchema,\n executeGetBridgeFee,\n formatBridgeFeeResult,\n type GetBridgeFeeInput,\n} from './getBridgeFee.js'\n\nexport {\n bridgeInputSchema,\n executeBridge,\n formatBridgeResult,\n type BridgeInput,\n type BridgeOptions,\n} from './bridge.js'\n\n// WDK tools\nexport {\n wdkGetWalletInputSchema,\n executeWdkGetWallet,\n executeWdkGetWalletDemo,\n formatWdkWalletResult,\n type WdkGetWalletInput,\n type WdkWalletInfo,\n} from './wdkGetWallet.js'\n\nexport {\n wdkGetBalancesInputSchema,\n executeWdkGetBalances,\n executeWdkGetBalancesDemo,\n formatWdkBalancesResult,\n type WdkGetBalancesInput,\n type WdkBalancesResult,\n} from './wdkGetBalances.js'\n\nexport {\n wdkTransferInputSchema,\n executeWdkTransfer,\n executeWdkTransferDemo,\n formatWdkTransferResult,\n type WdkTransferInput,\n type WdkTransferResult,\n} from './wdkTransfer.js'\n\nexport {\n wdkSwapInputSchema,\n executeWdkSwap,\n executeWdkSwapDemo,\n formatWdkSwapResult,\n type WdkSwapInput,\n type WdkSwapResult,\n} from './wdkSwap.js'\n\nexport {\n autoPayInputSchema,\n executeAutoPay,\n executeAutoPayDemo,\n formatAutoPayResult,\n type AutoPayInput,\n type AutoPayResult,\n} from './autoPay.js'\n\n// TON bridge tools\nexport {\n TON_BRIDGE_TOOLS,\n executeTonBridgeTool,\n createTonBridgeToolSet,\n type TonMcpBridgeConfig,\n} from './ton-bridge.js'\n\n// ERC-8004 tools\nexport {\n erc8004ResolveAgentInputSchema,\n executeErc8004ResolveAgent,\n formatErc8004ResolveAgentResult,\n type Erc8004ResolveAgentInput,\n} from './erc8004ResolveAgent.js'\n\nexport {\n erc8004CheckReputationInputSchema,\n executeErc8004CheckReputation,\n formatErc8004CheckReputationResult,\n type Erc8004CheckReputationInput,\n} from './erc8004CheckReputation.js'\n\nexport {\n erc8004VerifyWalletInputSchema,\n executeErc8004VerifyWallet,\n formatErc8004VerifyWalletResult,\n type Erc8004VerifyWalletInput,\n type Erc8004VerifyWalletResult,\n} from './erc8004VerifyWallet.js'\n\n// Price and fee tools\nexport {\n getTokenPrices,\n getTokenPricesDemo,\n clearPriceCache,\n} from './priceService.js'\n\nexport {\n getTokenPriceInputSchema,\n executeGetTokenPrice,\n formatTokenPriceResult,\n type GetTokenPriceInput,\n type TokenPriceResult,\n} from './getTokenPrice.js'\n\nexport {\n getGasPriceInputSchema,\n executeGetGasPrice,\n formatGasPriceResult,\n type GetGasPriceInput,\n type GasPriceResult,\n} from './getGasPrice.js'\n\nexport {\n estimatePaymentFeeInputSchema,\n executeEstimatePaymentFee,\n formatPaymentFeeEstimate,\n type EstimatePaymentFeeInput,\n type PaymentFeeEstimate,\n} from './estimatePaymentFee.js'\n\nexport {\n compareNetworkFeesInputSchema,\n executeCompareNetworkFees,\n formatNetworkFeeComparison,\n type CompareNetworkFeesInput,\n type NetworkFeeComparison,\n} from './compareNetworkFees.js'\n\n// Quote store\nexport {\n createQuote,\n getQuote,\n deleteQuote,\n clearQuoteStore,\n type QuoteData,\n} from './quoteStore.js'\n\n// Quote-based swap tools\nexport {\n wdkQuoteSwapInputSchema,\n executeWdkQuoteSwap,\n executeWdkQuoteSwapDemo,\n formatSwapQuoteResult,\n type WdkQuoteSwapInput,\n type SwapQuoteResult,\n} from './wdkQuoteSwap.js'\n\nexport {\n wdkExecuteSwapInputSchema,\n executeWdkExecuteSwap,\n executeWdkExecuteSwapDemo,\n formatExecuteSwapResult,\n type WdkExecuteSwapInput,\n type ExecuteSwapResult,\n} from './wdkExecuteSwap.js'\n\n// Quote-based bridge tools\nexport {\n quoteBridgeInputSchema,\n executeQuoteBridge,\n executeQuoteBridgeDemo,\n formatBridgeQuoteResult,\n type QuoteBridgeInput,\n type BridgeQuoteResult,\n} from './quoteBridge.js'\n\nexport {\n executeBridgeFromQuoteInputSchema,\n executeExecuteBridgeFromQuote,\n executeExecuteBridgeFromQuoteDemo,\n formatExecuteBridgeFromQuoteResult,\n type ExecuteBridgeFromQuoteInput,\n} from './executeBridgeFromQuote.js'\n\n// Unified tools\nexport {\n smartPayInputSchema,\n executeSmartPay,\n executeSmartPayDemo,\n formatSmartPayResult,\n paymentPlanInputSchema,\n executePaymentPlan,\n executePaymentPlanDemo,\n formatPaymentPlanResult,\n UNIFIED_TOOL_DEFINITIONS,\n type SmartPayInput,\n type SmartPayResult,\n type SmartPayStep,\n type PaymentPlanInput,\n type PaymentPlanResult,\n type UnifiedMcpConfig,\n} from './unified.js'\n\n/**\n * Base tool definitions (always available)\n */\nexport const TOOL_DEFINITIONS = {\n 't402/getBalance': {\n name: 't402/getBalance',\n description:\n 'Get token balances (native + stablecoins) for a wallet on a specific blockchain network. Returns ETH/native token balance plus USDC, USDT, and USDT0 balances where supported.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n network: {\n type: 'string',\n enum: [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ],\n description: 'Blockchain network to check balance on',\n },\n address: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Wallet address to check balance for',\n },\n },\n required: ['network', 'address'],\n },\n },\n\n 't402/getAllBalances': {\n name: 't402/getAllBalances',\n description:\n 'Get token balances across all supported networks for a wallet. Returns aggregated totals and per-network breakdown of native tokens and stablecoins (USDC, USDT, USDT0).',\n inputSchema: {\n type: 'object' as const,\n properties: {\n address: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Wallet address to check balances for',\n },\n networks: {\n type: 'array',\n items: {\n type: 'string',\n enum: [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ],\n },\n description:\n 'Optional list of networks to check. If not provided, checks all supported networks.',\n },\n },\n required: ['address'],\n },\n },\n\n 't402/pay': {\n name: 't402/pay',\n description:\n 'Execute a stablecoin payment on a specific blockchain network. Supports USDC, USDT, and USDT0 tokens. Requires a configured wallet with sufficient balance and native token for gas.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n to: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Recipient address',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount to pay (e.g., '10.50' for 10.50 USDC)\",\n },\n token: {\n type: 'string',\n enum: ['USDC', 'USDT', 'USDT0'],\n description: 'Token to use for payment',\n },\n network: {\n type: 'string',\n enum: [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ],\n description: 'Network to execute payment on',\n },\n memo: {\n type: 'string',\n description: 'Optional memo/reference for the payment',\n },\n confirmed: {\n type: 'boolean',\n description:\n 'Set to true to confirm and execute. Omit for a preview/confirmation prompt.',\n },\n },\n required: ['to', 'amount', 'token', 'network'],\n },\n },\n\n 't402/payGasless': {\n name: 't402/payGasless',\n description:\n 'Execute a gasless stablecoin payment using ERC-4337 account abstraction. Gas fees are sponsored by a paymaster, so no ETH is needed for the transaction. Supported on select networks.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n to: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Recipient address',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount to pay (e.g., '10.50' for 10.50 USDC)\",\n },\n token: {\n type: 'string',\n enum: ['USDC', 'USDT', 'USDT0'],\n description: 'Token to use for payment',\n },\n network: {\n type: 'string',\n enum: ['ethereum', 'base', 'arbitrum', 'optimism', 'polygon', 'avalanche'],\n description: 'Network to execute gasless payment on (must support ERC-4337)',\n },\n confirmed: {\n type: 'boolean',\n description:\n 'Set to true to confirm and execute. Omit for a preview/confirmation prompt.',\n },\n },\n required: ['to', 'amount', 'token', 'network'],\n },\n },\n\n 't402/getBridgeFee': {\n name: 't402/getBridgeFee',\n description:\n 'Get the fee quote for bridging USDT0 between chains using LayerZero OFT. Returns the native token fee required and estimated delivery time. Supported chains: ethereum, arbitrum, ink, berachain, unichain.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n fromChain: {\n type: 'string',\n enum: ['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'],\n description: 'Source chain to bridge from',\n },\n toChain: {\n type: 'string',\n enum: ['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'],\n description: 'Destination chain to bridge to',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount of USDT0 to bridge (e.g., '100' for 100 USDT0)\",\n },\n recipient: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Recipient address on destination chain',\n },\n },\n required: ['fromChain', 'toChain', 'amount', 'recipient'],\n },\n },\n\n 't402/bridge': {\n name: 't402/bridge',\n description:\n 'Bridge USDT0 between chains using LayerZero OFT standard. Executes a cross-chain transfer and returns the LayerZero message GUID for tracking. Supported chains: ethereum, arbitrum, ink, berachain, unichain.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n fromChain: {\n type: 'string',\n enum: ['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'],\n description: 'Source chain to bridge from',\n },\n toChain: {\n type: 'string',\n enum: ['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'],\n description: 'Destination chain to bridge to',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount of USDT0 to bridge (e.g., '100' for 100 USDT0)\",\n },\n recipient: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Recipient address on destination chain',\n },\n confirmed: {\n type: 'boolean',\n description:\n 'Set to true to confirm and execute. Omit for a preview/confirmation prompt.',\n },\n },\n required: ['fromChain', 'toChain', 'amount', 'recipient'],\n },\n },\n\n 't402/getTokenPrice': {\n name: 't402/getTokenPrice',\n description:\n 'Get current market prices for tokens (ETH, MATIC, AVAX, USDC, etc.) via CoinGecko. Cached for 5 minutes.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n tokens: {\n type: 'array',\n items: { type: 'string' },\n description: 'Token symbols to get prices for (e.g., [\"ETH\", \"MATIC\", \"USDC\"])',\n },\n currency: {\n type: 'string',\n description: 'Target currency (default: \"usd\")',\n },\n },\n required: ['tokens'],\n },\n },\n\n 't402/getGasPrice': {\n name: 't402/getGasPrice',\n description:\n 'Get the current gas price on a specific blockchain network. Returns the price in gwei.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n network: {\n type: 'string',\n enum: [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ],\n description: 'Blockchain network to check gas price on',\n },\n },\n required: ['network'],\n },\n },\n\n 't402/estimatePaymentFee': {\n name: 't402/estimatePaymentFee',\n description:\n 'Estimate the gas cost (in native token and USD) for a stablecoin payment on a specific network.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n network: {\n type: 'string',\n enum: [\n 'ethereum',\n 'base',\n 'arbitrum',\n 'optimism',\n 'polygon',\n 'avalanche',\n 'ink',\n 'berachain',\n 'unichain',\n ],\n description: 'Network to estimate fee on',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Payment amount (e.g., '100')\",\n },\n token: {\n type: 'string',\n enum: ['USDC', 'USDT', 'USDT0'],\n description: 'Token to use for payment',\n },\n },\n required: ['network', 'amount', 'token'],\n },\n },\n\n 't402/compareNetworkFees': {\n name: 't402/compareNetworkFees',\n description:\n 'Compare payment fees across multiple networks for the same token. Returns a sorted table from cheapest to most expensive.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Payment amount (e.g., '100')\",\n },\n token: {\n type: 'string',\n enum: ['USDC', 'USDT', 'USDT0'],\n description: 'Token to use for payment',\n },\n networks: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Networks to compare. If not provided, compares all networks that support the token.',\n },\n },\n required: ['amount', 'token'],\n },\n },\n\n 't402/quoteBridge': {\n name: 't402/quoteBridge',\n description:\n 'Get a bridge fee quote with a quoteId for later execution. Like getBridgeFee but returns a reusable quoteId. Call t402/executeBridge with the quoteId to execute.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n fromChain: {\n type: 'string',\n enum: ['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'],\n description: 'Source chain to bridge from',\n },\n toChain: {\n type: 'string',\n enum: ['ethereum', 'arbitrum', 'ink', 'berachain', 'unichain'],\n description: 'Destination chain to bridge to',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount of USDT0 to bridge (e.g., '100' for 100 USDT0)\",\n },\n recipient: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Recipient address on destination chain',\n },\n },\n required: ['fromChain', 'toChain', 'amount', 'recipient'],\n },\n },\n\n 't402/executeBridgeQuote': {\n name: 't402/executeBridgeQuote',\n description:\n 'Execute a bridge using a quoteId from t402/quoteBridge. Requires confirmation.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n quoteId: {\n type: 'string',\n description: 'Quote ID from t402/quoteBridge',\n },\n confirmed: {\n type: 'boolean',\n description:\n 'Set to true to confirm and execute. Omit for a preview/confirmation prompt.',\n },\n },\n required: ['quoteId'],\n },\n },\n}\n\n/**\n * WDK tool definitions (only available when WDK seed phrase is configured)\n */\nexport const WDK_TOOL_DEFINITIONS = {\n 'wdk/getWallet': {\n name: 'wdk/getWallet',\n description:\n 'Get wallet information from the configured WDK wallet. Returns EVM address and supported chains. No parameters needed.',\n inputSchema: {\n type: 'object' as const,\n properties: {},\n required: [] as string[],\n },\n },\n\n 'wdk/getBalances': {\n name: 'wdk/getBalances',\n description:\n 'Get multi-chain token balances from the WDK wallet. Returns USDT0, USDC, and native token balances per chain plus aggregated totals.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n chains: {\n type: 'array',\n items: { type: 'string' },\n description:\n 'Optional list of chains to check (e.g., [\"ethereum\", \"arbitrum\"]). If not provided, checks all configured chains.',\n },\n },\n required: [] as string[],\n },\n },\n\n 'wdk/transfer': {\n name: 'wdk/transfer',\n description:\n 'Send stablecoins (USDC, USDT, USDT0) from the WDK wallet to a recipient address on a specific chain.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n to: {\n type: 'string',\n description: 'Recipient address',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount to send (e.g., '10.50')\",\n },\n token: {\n type: 'string',\n enum: ['USDC', 'USDT', 'USDT0'],\n description: 'Token to transfer',\n },\n chain: {\n type: 'string',\n description: 'Chain to execute transfer on (e.g., \"ethereum\", \"arbitrum\")',\n },\n confirmed: {\n type: 'boolean',\n description:\n 'Set to true to confirm and execute. Omit for a preview/confirmation prompt.',\n },\n },\n required: ['to', 'amount', 'token', 'chain'],\n },\n },\n\n 'wdk/swap': {\n name: 'wdk/swap',\n description:\n 'Swap tokens using the WDK Velora protocol. Supports swapping between stablecoins and native tokens.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n fromToken: {\n type: 'string',\n description: 'Token to swap from (e.g., \"ETH\", \"USDC\")',\n },\n toToken: {\n type: 'string',\n description: 'Token to swap to (e.g., \"USDT0\", \"USDC\")',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount to swap (e.g., '1.0')\",\n },\n chain: {\n type: 'string',\n description: 'Chain to execute swap on (e.g., \"ethereum\", \"arbitrum\")',\n },\n confirmed: {\n type: 'boolean',\n description:\n 'Set to true to confirm and execute. Omit for a preview/confirmation prompt.',\n },\n },\n required: ['fromToken', 'toToken', 'amount', 'chain'],\n },\n },\n\n 't402/autoPay': {\n name: 't402/autoPay',\n description:\n 'Smart payment orchestrator. Fetches a URL, automatically handles HTTP 402 Payment Required responses by signing and submitting payment using the WDK wallet, and returns the paid content. The killer tool for AI agents.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string',\n description: 'URL to fetch (may return 402 Payment Required)',\n },\n maxAmount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description:\n 'Maximum amount willing to pay (e.g., \"10.00\"). If not set, pays any amount.',\n },\n preferredChain: {\n type: 'string',\n description:\n 'Preferred chain for payment (e.g., \"arbitrum\"). If not specified, uses first available.',\n },\n confirmed: {\n type: 'boolean',\n description:\n 'Set to true to confirm and execute. Omit for a preview/confirmation prompt.',\n },\n },\n required: ['url'],\n },\n },\n\n 'wdk/quoteSwap': {\n name: 'wdk/quoteSwap',\n description:\n 'Get a swap quote with a quoteId for later execution. Returns exchange rate, fee, and price impact. Call wdk/executeSwap with the quoteId to execute.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n fromToken: {\n type: 'string',\n description: 'Token to swap from (e.g., \"ETH\", \"USDC\")',\n },\n toToken: {\n type: 'string',\n description: 'Token to swap to (e.g., \"USDT0\", \"USDC\")',\n },\n amount: {\n type: 'string',\n pattern: '^\\\\d+(\\\\.\\\\d+)?$',\n description: \"Amount to swap (e.g., '1.0')\",\n },\n chain: {\n type: 'string',\n description: 'Chain to execute swap on (e.g., \"ethereum\", \"arbitrum\")',\n },\n },\n required: ['fromToken', 'toToken', 'amount', 'chain'],\n },\n },\n\n 'wdk/executeSwap': {\n name: 'wdk/executeSwap',\n description:\n 'Execute a swap using a quoteId from wdk/quoteSwap. Requires confirmation.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n quoteId: {\n type: 'string',\n description: 'Quote ID from wdk/quoteSwap',\n },\n confirmed: {\n type: 'boolean',\n description:\n 'Set to true to confirm and execute. Omit for a preview/confirmation prompt.',\n },\n },\n required: ['quoteId'],\n },\n },\n}\n\n/**\n * ERC-8004 tool definitions (always available — read-only on-chain queries)\n */\nexport const ERC8004_TOOL_DEFINITIONS = {\n 'erc8004/resolveAgent': {\n name: 'erc8004/resolveAgent',\n description:\n \"Look up an agent's on-chain ERC-8004 identity. Returns the agent's registered wallet address, owner, registration file (name, description, services), and verification URI. Use this to verify an agent before making a payment.\",\n inputSchema: {\n type: 'object' as const,\n properties: {\n agentId: {\n type: 'number',\n description: 'Agent NFT token ID on the Identity Registry',\n },\n agentRegistry: {\n type: 'string',\n pattern: '^eip155:\\\\d+:0x[a-fA-F0-9]+$',\n description: 'Agent registry identifier (e.g., \"eip155:8453:0xRegistryAddress\")',\n },\n },\n required: ['agentId', 'agentRegistry'],\n },\n },\n\n 'erc8004/checkReputation': {\n name: 'erc8004/checkReputation',\n description:\n \"Query an agent's reputation score from the on-chain Reputation Registry. Returns a normalized 0-100 score based on feedback from trusted reviewers. Requires explicit trusted reviewer addresses for Sybil resistance.\",\n inputSchema: {\n type: 'object' as const,\n properties: {\n agentId: {\n type: 'number',\n description: 'Agent NFT token ID',\n },\n agentRegistry: {\n type: 'string',\n pattern: '^eip155:\\\\d+:0x[a-fA-F0-9]+$',\n description: 'Agent registry identifier (e.g., \"eip155:8453:0xRegistryAddress\")',\n },\n reputationRegistry: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Reputation Registry contract address on the same chain',\n },\n trustedReviewers: {\n type: 'array',\n items: { type: 'string', pattern: '^0x[a-fA-F0-9]{40}$' },\n minItems: 1,\n description: 'Addresses whose feedback is trusted (required for Sybil resistance)',\n },\n },\n required: ['agentId', 'agentRegistry', 'reputationRegistry', 'trustedReviewers'],\n },\n },\n\n 'erc8004/verifyWallet': {\n name: 'erc8004/verifyWallet',\n description:\n \"Verify that a payment address (payTo) matches an agent's on-chain registered wallet. Use this before paying to confirm the recipient address is legitimate and owned by the declared agent.\",\n inputSchema: {\n type: 'object' as const,\n properties: {\n agentId: {\n type: 'number',\n description: 'Agent NFT token ID',\n },\n agentRegistry: {\n type: 'string',\n pattern: '^eip155:\\\\d+:0x[a-fA-F0-9]+$',\n description: 'Agent registry identifier (e.g., \"eip155:8453:0xRegistryAddress\")',\n },\n walletAddress: {\n type: 'string',\n pattern: '^0x[a-fA-F0-9]{40}$',\n description: 'Wallet address to verify (typically the payTo from payment requirements)',\n },\n },\n required: ['agentId', 'agentRegistry', 'walletAddress'],\n },\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIA,oBAAuB;AACvB,mBAAqC;AACrC,mBAA8D;;;ACF9D,iBAAkB;AAClB,kBAAiF;AACjF,aAAwB;;;ACIjB,IAAM,YAA8C;AAAA,EACzD,UAAU;AAAA,EACV,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAAU;AAAA,EACV,SAAS;AAAA,EACT,WAAW;AAAA,EACX,KAAK;AAAA,EACL,WAAW;AAAA,EACX,UAAU;AACZ;AAKO,IAAM,iBAAmD;AAAA,EAC9D,UAAU;AAAA,EACV,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAAU;AAAA,EACV,SAAS;AAAA,EACT,WAAW;AAAA,EACX,KAAK;AAAA,EACL,WAAW;AAAA,EACX,UAAU;AACZ;AAKO,IAAM,gBAAkD;AAAA,EAC7D,UAAU;AAAA,EACV,MAAM;AAAA,EACN,UAAU;AAAA,EACV,UAA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;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,aAAW,WAAW,UAAU;AAC9B,UAAM,SAAS,YAAY,QAAQ,YAAY,CAAC;AAChD,QAAI,QAAQ,IAAI,MAAM,GAAG;AACvB,cAAQ,OAAO,IAAI,QAAQ,IAAI,MAAM;AAAA,IACvC;AAAA,EACF;AAEA,MAAI,OAAO,KAAK,OAAO,EAAE,SAAS,GAAG;AACnC,WAAO,UAAU;AAAA,EACnB;AAGA,MAAI,QAAQ,IAAI,uBAAuB;AACrC,WAAO,iBAAiB,QAAQ,IAAI;AAAA,EACtC;AACA,MAAI,QAAQ,IAAI,kBAAkB;AAChC,WAAO,YAAY,QAAQ,IAAI;AAAA,EACjC;AAEA,SAAO;AACT;","names":["import_zod","import_zod","import_viem","chains","getViemChain","import_zod","import_viem","import_accounts","chains","getViemChain","import_zod","import_viem","chains","getViemChain","import_zod","import_viem","import_accounts","chains","LAYERZERO_ENDPOINT_IDS","ESTIMATED_BRIDGE_TIMES","OFT_ABI","getViemChain","addressToBytes32","estimatedTime","import_zod","chains","import_zod","import_viem","chains","import_zod","import_zod","import_viem","import_zod","chains","import_zod","import_erc8004","import_viem","chains","import_zod","import_erc8004","import_zod","import_erc8004","import_zod","import_zod","import_viem","chains","getViemChain","gasPrice","import_zod","import_viem","chains","getViemChain","nativeCost","usdCost","import_zod","ALL_NETWORKS","import_zod","import_viem","import_zod","import_viem","import_zod","import_zod","import_zod","chains"]}
|