web3-tools-mcp 1.2.3 → 1.3.1

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/src/client.ts CHANGED
@@ -1,5 +1,19 @@
1
1
  import { http, createPublicClient } from 'viem'
2
- import { arbitrum, base, celo, localhost, mainnet, optimism, polygon } from 'viem/chains'
2
+ import {
3
+ arbitrum,
4
+ avalanche,
5
+ base,
6
+ bsc,
7
+ gnosis,
8
+ linea,
9
+ localhost,
10
+ mainnet,
11
+ optimism,
12
+ polygon,
13
+ sonic,
14
+ unichain,
15
+ zksync
16
+ } from 'viem/chains'
3
17
  import type { ChainName, Config } from './types.js'
4
18
 
5
19
  // Enhanced RPC configuration with API keys
@@ -31,7 +45,7 @@ function getRpcUrl(chainName: string, config: Config): string {
31
45
  ? `https://polygon-mainnet.g.alchemy.com/v2/${config.alchemyApiKey}`
32
46
  : config.infuraApiKey
33
47
  ? `https://polygon-mainnet.infura.io/v3/${config.infuraApiKey}`
34
- : 'https://polygon-rpc.com/',
48
+ : 'https://polygon-rpc.com',
35
49
 
36
50
  optimism: config.alchemyApiKey
37
51
  ? `https://opt-mainnet.g.alchemy.com/v2/${config.alchemyApiKey}`
@@ -39,7 +53,44 @@ function getRpcUrl(chainName: string, config: Config): string {
39
53
  ? `https://optimism-mainnet.infura.io/v3/${config.infuraApiKey}`
40
54
  : 'https://mainnet.optimism.io',
41
55
 
42
- celo: 'https://celo.drpc.org',
56
+ avalanche: config.alchemyApiKey
57
+ ? `https://avax-mainnet.g.alchemy.com/v2/${config.alchemyApiKey}`
58
+ : config.infuraApiKey
59
+ ? `https://avalanche-mainnet.infura.io/v3/${config.infuraApiKey}`
60
+ : 'https://api.avax.network/ext/bc/C/rpc',
61
+
62
+ bnb: config.alchemyApiKey
63
+ ? `https://bnb-mainnet.g.alchemy.com/v2/${config.alchemyApiKey}`
64
+ : config.infuraApiKey
65
+ ? `https://bsc-mainnet.infura.io/v3/${config.infuraApiKey}`
66
+ : 'https://bsc-dataseed.bnbchain.org',
67
+
68
+ gnosis: config.alchemyApiKey
69
+ ? `https://gnosis-mainnet.g.alchemy.com/v2/${config.alchemyApiKey}`
70
+ : 'https://rpc.gnosischain.com',
71
+
72
+ sonic: config.alchemyApiKey
73
+ ? `https://sonic-mainnet.g.alchemy.com/v2/${config.alchemyApiKey}`
74
+ : 'https://rpc.soniclabs.com',
75
+
76
+ zksync: config.alchemyApiKey
77
+ ? `https://zksync-mainnet.g.alchemy.com/v2/${config.alchemyApiKey}`
78
+ : config.infuraApiKey
79
+ ? `https://zksync-mainnet.infura.io/v3/${config.infuraApiKey}`
80
+ : 'https://mainnet.era.zksync.io',
81
+
82
+ linea: config.alchemyApiKey
83
+ ? `https://linea-mainnet.g.alchemy.com/v2/${config.alchemyApiKey}`
84
+ : config.infuraApiKey
85
+ ? `https://linea-mainnet.infura.io/v3/${config.infuraApiKey}`
86
+ : 'https://rpc.linea.build',
87
+
88
+ unichain: config.alchemyApiKey
89
+ ? `https://unichain-mainnet.g.alchemy.com/v2/${config.alchemyApiKey}`
90
+ : config.infuraApiKey
91
+ ? `https://unichain-mainnet.infura.io/v3/${config.infuraApiKey}`
92
+ : 'https://sepolia.unichain.org',
93
+
43
94
  localhost: 'http://localhost:8545'
44
95
  }
45
96
 
@@ -78,10 +129,46 @@ export const CHAINS = (config: Config) => ({
78
129
  return getRpcUrl('optimism', config)
79
130
  }
80
131
  },
81
- celo: {
82
- chain: celo,
132
+ avalanche: {
133
+ chain: avalanche,
134
+ get rpc() {
135
+ return getRpcUrl('avalanche', config)
136
+ }
137
+ },
138
+ bnb: {
139
+ chain: bsc,
140
+ get rpc() {
141
+ return getRpcUrl('bnb', config)
142
+ }
143
+ },
144
+ gnosis: {
145
+ chain: gnosis,
146
+ get rpc() {
147
+ return getRpcUrl('gnosis', config)
148
+ }
149
+ },
150
+ sonic: {
151
+ chain: sonic,
152
+ get rpc() {
153
+ return getRpcUrl('sonic', config)
154
+ }
155
+ },
156
+ zksync: {
157
+ chain: zksync,
158
+ get rpc() {
159
+ return getRpcUrl('zksync', config)
160
+ }
161
+ },
162
+ linea: {
163
+ chain: linea,
164
+ get rpc() {
165
+ return getRpcUrl('linea', config)
166
+ }
167
+ },
168
+ unichain: {
169
+ chain: unichain,
83
170
  get rpc() {
84
- return getRpcUrl('celo', config)
171
+ return getRpcUrl('unichain', config)
85
172
  }
86
173
  },
87
174
  localhost: {
@@ -94,15 +181,36 @@ export const CHAINS = (config: Config) => ({
94
181
 
95
182
  // Hypersync URLs for supported chains (localhost is not supported)
96
183
  export const HYPERSYNC_URLS: Partial<Record<ChainName, string>> = {
97
- base: 'https://base.hypersync.xyz',
98
- arbitrum: 'https://arbitrum.hypersync.xyz',
99
- mainnet: 'https://eth.hypersync.xyz',
100
- polygon: 'https://polygon.hypersync.xyz',
101
- optimism: 'https://optimism.hypersync.xyz'
102
- // celo and localhost are not supported by hypersync
184
+ mainnet: 'https://eth.hypersync.xyz', // Chain ID 1
185
+ arbitrum: 'https://arbitrum.hypersync.xyz', // Chain ID 42161
186
+ avalanche: 'https://avalanche.hypersync.xyz', // Chain ID 43114
187
+ base: 'https://base.hypersync.xyz', // Chain ID 8453
188
+ bnb: 'https://bsc.hypersync.xyz', // Chain ID 56
189
+ gnosis: 'https://gnosis.hypersync.xyz', // Chain ID 100
190
+ sonic: 'https://sonic.hypersync.xyz', // Chain ID 146
191
+ optimism: 'https://optimism.hypersync.xyz', // Chain ID 10
192
+ polygon: 'https://polygon.hypersync.xyz', // Chain ID 137
193
+ zksync: 'https://zksync.hypersync.xyz', // Chain ID 324
194
+ linea: 'https://linea.hypersync.xyz', // Chain ID 59144
195
+ unichain: 'https://unichain.hypersync.xyz' // Chain ID 130
196
+ // localhost is not supported by hypersync
103
197
  }
104
198
 
105
- export const SUPPORTED_CHAINS = ['mainnet', 'base', 'arbitrum', 'polygon', 'optimism', 'celo', 'localhost'] as const
199
+ export const SUPPORTED_CHAINS = [
200
+ 'mainnet',
201
+ 'arbitrum',
202
+ 'avalanche',
203
+ 'base',
204
+ 'bnb',
205
+ 'gnosis',
206
+ 'sonic',
207
+ 'optimism',
208
+ 'polygon',
209
+ 'zksync',
210
+ 'linea',
211
+ 'unichain',
212
+ 'localhost'
213
+ ] as const
106
214
 
107
215
  // Client manager
108
216
  export class ClientManager {
@@ -137,7 +245,13 @@ export class ClientManager {
137
245
  arbitrum: 'arbiscan.io',
138
246
  polygon: 'polygonscan.com',
139
247
  optimism: 'optimistic.etherscan.io',
140
- celo: 'celoscan.io',
248
+ avalanche: 'snowtrace.io',
249
+ bnb: 'bscscan.com',
250
+ gnosis: 'gnosisscan.io',
251
+ sonic: 'sonicscan.org',
252
+ zksync: 'era.zksync.network',
253
+ linea: 'lineascan.build',
254
+ unichain: 'uniscan.xyz',
141
255
  localhost: 'etherscan.io'
142
256
  }
143
257
  return domains[chainName] || 'etherscan.io'
package/src/index.ts CHANGED
@@ -35,7 +35,7 @@ ENVIRONMENT VARIABLES:
35
35
  HYPERSYNC_API_KEY Alternative to --hypersync-api-key
36
36
 
37
37
  SUPPORTED CHAINS:
38
- mainnet, base, arbitrum, polygon, optimism, celo, localhost
38
+ mainnet, arbitrum, avalanche, base, bnb, gnosis, sonic, optimism, polygon, zksync, linea, unichain, localhost
39
39
 
40
40
  EXAMPLES:
41
41
  # Use with npx (recommended)
@@ -0,0 +1,267 @@
1
+ import { type AbiFunction, type Address, isAddress, parseAbiItem, encodeFunctionData, decodeFunctionResult } from "viem";
2
+ import { z } from "zod";
3
+ import type { ChainName } from "../types.js";
4
+ import { getClientManager, SUPPORTED_CHAINS } from "../client.js";
5
+ import { convertArgumentsToTypes, createTool, formatResponse } from "../utils.js";
6
+
7
+ export default {
8
+ simulate_contract: createTool(
9
+ "Simulate Contract Call",
10
+ "Simulate a contract call (including state-changing functions) without broadcasting. Returns simulation result and estimated gas.",
11
+ z.object({
12
+ chain: z
13
+ .enum(SUPPORTED_CHAINS)
14
+ .describe("Blockchain network to simulate on"),
15
+ contractAddress: z
16
+ .string()
17
+ .describe("Contract address to call"),
18
+ functionAbi: z
19
+ .string()
20
+ .describe(
21
+ 'Function ABI signature (e.g., "function transfer(address to, uint256 amount)"). Can be any function type.'
22
+ ),
23
+ args: z
24
+ .array(z.union([z.string(), z.number(), z.boolean(), z.null()]))
25
+ .optional()
26
+ .describe("Function arguments in order matching the ABI signature"),
27
+ from: z
28
+ .string()
29
+ .optional()
30
+ .describe("Sender address (defaults to zero address)"),
31
+ value: z
32
+ .string()
33
+ .optional()
34
+ .describe("ETH value to send with the transaction (in wei as string)"),
35
+ blockNumber: z
36
+ .string()
37
+ .optional()
38
+ .describe("Block number for simulation (defaults to latest)"),
39
+ }),
40
+ async (args) => {
41
+ if (!isAddress(args.contractAddress)) {
42
+ throw new Error(`Invalid contract address: ${args.contractAddress}`);
43
+ }
44
+
45
+ if (args.from && !isAddress(args.from)) {
46
+ throw new Error(`Invalid from address: ${args.from}`);
47
+ }
48
+
49
+ const clientManager = getClientManager();
50
+ const client = clientManager.getClient(args.chain as ChainName);
51
+
52
+ try {
53
+ const abiItem = parseAbiItem(args.functionAbi) as AbiFunction;
54
+ const convertedArgs = convertArgumentsToTypes(args.args || [], abiItem.inputs);
55
+
56
+ const blockTag = args.blockNumber ? BigInt(args.blockNumber) : undefined;
57
+
58
+ // Simulate the call
59
+ const result = await client.call({
60
+ to: args.contractAddress as Address,
61
+ data: encodeFunctionData({
62
+ abi: [abiItem],
63
+ functionName: abiItem.name,
64
+ args: convertedArgs,
65
+ }),
66
+ account: args.from ? (args.from as Address) : undefined,
67
+ value: args.value ? BigInt(args.value) : undefined,
68
+ blockNumber: blockTag,
69
+ });
70
+
71
+ // Also estimate gas
72
+ const gasEstimate = await client.estimateGas({
73
+ to: args.contractAddress as Address,
74
+ data: encodeFunctionData({
75
+ abi: [abiItem],
76
+ functionName: abiItem.name,
77
+ args: convertedArgs,
78
+ }),
79
+ account: args.from ? (args.from as Address) : undefined,
80
+ value: args.value ? BigInt(args.value) : undefined,
81
+ blockNumber: blockTag,
82
+ });
83
+
84
+ // Decode the result if the function has outputs
85
+ let decodedResult: unknown = result.data;
86
+ if (abiItem.outputs && abiItem.outputs.length > 0 && result.data) {
87
+ decodedResult = decodeFunctionResult({
88
+ abi: [abiItem],
89
+ functionName: abiItem.name,
90
+ data: result.data,
91
+ });
92
+ }
93
+
94
+ return formatResponse({
95
+ success: true,
96
+ chain: args.chain,
97
+ contractAddress: args.contractAddress,
98
+ functionName: abiItem.name,
99
+ result: decodedResult,
100
+ rawData: result.data,
101
+ gasEstimate: gasEstimate.toString(),
102
+ blockNumber: args.blockNumber || "latest",
103
+ });
104
+ } catch (error) {
105
+ // Check if it's a revert error
106
+ const errorMessage = error instanceof Error ? error.message : String(error);
107
+
108
+ return formatResponse({
109
+ success: false,
110
+ chain: args.chain,
111
+ contractAddress: args.contractAddress,
112
+ error: errorMessage,
113
+ reverted: errorMessage.includes("revert") || errorMessage.includes("execution reverted"),
114
+ });
115
+ }
116
+ }
117
+ ),
118
+
119
+ estimate_gas: createTool(
120
+ "Estimate Gas",
121
+ "Estimate gas required for a transaction. Supports contract calls, transfers, and deployments.",
122
+ z.object({
123
+ chain: z
124
+ .enum(SUPPORTED_CHAINS)
125
+ .describe("Blockchain network"),
126
+ to: z
127
+ .string()
128
+ .optional()
129
+ .describe("Recipient address (omit for contract deployment)"),
130
+ from: z
131
+ .string()
132
+ .optional()
133
+ .describe("Sender address (optional)"),
134
+ value: z
135
+ .string()
136
+ .optional()
137
+ .describe("ETH value to send (in wei as string)"),
138
+ data: z
139
+ .string()
140
+ .optional()
141
+ .describe("Transaction data (hex string for contract calls or deployment bytecode)"),
142
+ functionAbi: z
143
+ .string()
144
+ .optional()
145
+ .describe("Optional: Function ABI signature to encode call data automatically"),
146
+ args: z
147
+ .array(z.union([z.string(), z.number(), z.boolean(), z.null()]))
148
+ .optional()
149
+ .describe("Optional: Function arguments (only used with functionAbi)"),
150
+ }),
151
+ async (args) => {
152
+ if (args.to && !isAddress(args.to)) {
153
+ throw new Error(`Invalid to address: ${args.to}`);
154
+ }
155
+
156
+ if (args.from && !isAddress(args.from)) {
157
+ throw new Error(`Invalid from address: ${args.from}`);
158
+ }
159
+
160
+ const clientManager = getClientManager();
161
+ const client = clientManager.getClient(args.chain as ChainName);
162
+
163
+ try {
164
+ let callData = args.data;
165
+
166
+ // If functionAbi is provided, encode the call data
167
+ if (args.functionAbi) {
168
+ const abiItem = parseAbiItem(args.functionAbi) as AbiFunction;
169
+ const convertedArgs = convertArgumentsToTypes(args.args || [], abiItem.inputs);
170
+ callData = encodeFunctionData({
171
+ abi: [abiItem],
172
+ functionName: abiItem.name,
173
+ args: convertedArgs,
174
+ });
175
+ }
176
+
177
+ const gasEstimate = await client.estimateGas({
178
+ to: args.to ? (args.to as Address) : undefined,
179
+ account: args.from ? (args.from as Address) : undefined,
180
+ value: args.value ? BigInt(args.value) : undefined,
181
+ data: callData as `0x${string}` | undefined,
182
+ });
183
+
184
+ return formatResponse({
185
+ success: true,
186
+ chain: args.chain,
187
+ gasEstimate: gasEstimate.toString(),
188
+ to: args.to,
189
+ from: args.from,
190
+ value: args.value,
191
+ });
192
+ } catch (error) {
193
+ throw new Error(`Gas estimation failed: ${error}`);
194
+ }
195
+ }
196
+ ),
197
+
198
+ get_gas_price: createTool(
199
+ "Get Gas Price",
200
+ "Get current gas prices for a chain. Returns both legacy gasPrice and EIP-1559 fees (maxFeePerGas, maxPriorityFeePerGas).",
201
+ z.object({
202
+ chain: z
203
+ .enum(SUPPORTED_CHAINS)
204
+ .describe("Blockchain network"),
205
+ formatted: z
206
+ .boolean()
207
+ .optional()
208
+ .default(true)
209
+ .describe("Return prices in Gwei (default: true). If false, returns wei."),
210
+ }),
211
+ async (args) => {
212
+ const clientManager = getClientManager();
213
+ const client = clientManager.getClient(args.chain as ChainName);
214
+
215
+ try {
216
+ // Get both legacy and EIP-1559 gas prices
217
+ const [gasPrice, feeData] = await Promise.all([
218
+ client.getGasPrice(),
219
+ client.estimateFeesPerGas().catch(() => null), // Some chains don't support EIP-1559
220
+ ]);
221
+
222
+ const formatPrice = (wei: bigint): string => {
223
+ if (args.formatted) {
224
+ // Convert to Gwei (1 Gwei = 1e9 wei)
225
+ const gwei = Number(wei) / 1e9;
226
+ return `${gwei.toFixed(2)} Gwei`;
227
+ }
228
+ return wei.toString();
229
+ };
230
+
231
+ const response: any = {
232
+ chain: args.chain,
233
+ timestamp: new Date().toISOString(),
234
+ legacy: {
235
+ gasPrice: args.formatted ? formatPrice(gasPrice) : gasPrice.toString(),
236
+ gasPriceWei: gasPrice.toString(),
237
+ },
238
+ };
239
+
240
+ // Add EIP-1559 data if available
241
+ if (feeData) {
242
+ response.eip1559 = {
243
+ maxFeePerGas: args.formatted
244
+ ? formatPrice(feeData.maxFeePerGas)
245
+ : feeData.maxFeePerGas.toString(),
246
+ maxPriorityFeePerGas: args.formatted
247
+ ? formatPrice(feeData.maxPriorityFeePerGas)
248
+ : feeData.maxPriorityFeePerGas.toString(),
249
+ maxFeePerGasWei: feeData.maxFeePerGas.toString(),
250
+ maxPriorityFeePerGasWei: feeData.maxPriorityFeePerGas.toString(),
251
+ };
252
+
253
+ // Calculate estimated total cost for a standard 21000 gas transaction
254
+ const standardGasLimit = 21000n;
255
+ const estimatedCost = feeData.maxFeePerGas * standardGasLimit;
256
+ response.eip1559.estimatedCostFor21kGas = args.formatted
257
+ ? `${(Number(estimatedCost) / 1e18).toFixed(6)} ETH`
258
+ : estimatedCost.toString();
259
+ }
260
+
261
+ return formatResponse(response);
262
+ } catch (error) {
263
+ throw new Error(`Failed to get gas price: ${error}`);
264
+ }
265
+ }
266
+ ),
267
+ };
@@ -6,6 +6,7 @@ import balanceTools from './balance.js'
6
6
  import contractTools from './contract.js'
7
7
  import contractInfoTools from './contract-info.js'
8
8
  import ensTools from './ens.js'
9
+ import gasTools from './gas.js'
9
10
  import logTools from './logs.js'
10
11
  import signatureTools from './signatures.js'
11
12
 
@@ -16,7 +17,8 @@ const allToolDefinitions = {
16
17
  ...balanceTools,
17
18
  ...logTools,
18
19
  ...advancedTools,
19
- ...ensTools
20
+ ...ensTools,
21
+ ...gasTools
20
22
  } as const
21
23
 
22
24
  // Register all tools with the MCP server
package/src/types.ts CHANGED
@@ -17,7 +17,20 @@ export interface Config {
17
17
  }
18
18
 
19
19
  // Chain names
20
- export type ChainName = 'mainnet' | 'base' | 'arbitrum' | 'polygon' | 'optimism' | 'celo' | 'localhost'
20
+ export type ChainName =
21
+ | 'mainnet'
22
+ | 'arbitrum'
23
+ | 'avalanche'
24
+ | 'base'
25
+ | 'bnb'
26
+ | 'gnosis'
27
+ | 'sonic'
28
+ | 'optimism'
29
+ | 'polygon'
30
+ | 'zksync'
31
+ | 'linea'
32
+ | 'unichain'
33
+ | 'localhost'
21
34
 
22
35
  // Tool handler result type
23
36
  export interface ToolResult {