estimate_gas_cost
Estimate transaction gas costs using gas limit, confidence level, and blockchain network ID to optimize fee predictions for Ethereum and other chains.
Instructions
Estimate gas cost for a transaction based on gas limit, confidence level, and chain.
Parameters:
- gas_limit (int): The gas limit for the transaction (e.g., 21000 for a simple transfer).
- confidence (int): The confidence level for gas price prediction (0-100).
- chain_id (int): The ID of the blockchain network (e.g., 1 for Ethereum Mainnet). Default: 1.
- ctx (Optional[Context]): The MCP context object. Default: None.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| chain_id | No | ||
| confidence | No | ||
| ctx | No | ||
| gas_limit | Yes |
Implementation Reference
- src/blocknative_mcp/cli.py:99-139 (handler)The handler function for the 'estimate_gas_cost' tool, registered via @mcp.tool(). It validates input parameters, fetches current gas prices using the helper function, selects the gas price prediction matching the specified confidence level, calculates the total gas cost in Gwei and ETH, and returns a formatted result string.@mcp.tool() async def estimate_gas_cost(gas_limit: int, confidence: int = 99, chain_id: int = 1, ctx: Optional[Context] = None) -> str: """ Estimate gas cost for a transaction based on gas limit, confidence level, and chain. Parameters: - gas_limit (int): The gas limit for the transaction (e.g., 21000 for a simple transfer). - confidence (int): The confidence level for gas price prediction (0-100). - chain_id (int): The ID of the blockchain network (e.g., 1 for Ethereum Mainnet). Default: 1. - ctx (Optional[Context]): The MCP context object. Default: None. """ if not (0 <= confidence <= 100): return "Error: Confidence must be between 0 and 100" if gas_limit <= 0: return "Error: Gas limit must be positive" data = await fetch_gas_prices(chain_id) if "error" in data: return data["error"] # Find the closest confidence level predictions = data["estimatedPrices"] closest_prediction = min( predictions, key=lambda p: abs(p.get("confidence", 0) - confidence), default={} ) if not closest_prediction: return "Error: No matching gas price prediction found" max_fee = closest_prediction.get("maxFeePerGas", 0) total_cost_gwei = max_fee * gas_limit total_cost_eth = total_cost_gwei / 1e9 # Convert Gwei to ETH return ( f"Estimated Gas Cost (Confidence {confidence}%, Chain ID {chain_id}):\n" f"- Gas Limit: {gas_limit}\n" f"- Max Fee Per Gas: {max_fee} Gwei\n" f"- Total Cost: {total_cost_gwei} Gwei ({total_cost_eth:.6f} ETH)" )
- src/blocknative_mcp/cli.py:19-48 (helper)Helper function to fetch gas price predictions from the Blocknative API, extracting base fee and estimated prices for use in gas cost estimation.async def fetch_gas_prices(chain_id: int = 1) -> Dict: """Fetch gas price predictions from Blocknative API for a given chain.""" try: headers = {"Authorization": BLOCKNATIVE_API_KEY} if BLOCKNATIVE_API_KEY else {} async with httpx.AsyncClient() as client: response = await client.get( BLOCKNATIVE_GAS_API_URL, headers=headers, params={"chainid": chain_id} ) response.raise_for_status() data = response.json() # Extract relevant fields from the response block_prices = data.get("blockPrices", []) if not block_prices: return {"error": "No block prices found in API response"} # Use the first block's data first_block = block_prices[0] return { "baseFeePerGas": first_block.get("baseFeePerGas", 0), "estimatedPrices": first_block.get("estimatedPrices", []), "unit": data.get("unit", "gwei"), "system": data.get("system", "unknown"), "network": data.get("network", "unknown") } except httpx.HTTPError as e: return {"error": f"Failed to fetch gas prices for chain ID {chain_id}: {str(e)}"}
- src/blocknative_mcp/cli.py:101-109 (schema)Docstring defining the input schema/parameters for the 'estimate_gas_cost' tool, including descriptions and types.""" Estimate gas cost for a transaction based on gas limit, confidence level, and chain. Parameters: - gas_limit (int): The gas limit for the transaction (e.g., 21000 for a simple transfer). - confidence (int): The confidence level for gas price prediction (0-100). - chain_id (int): The ID of the blockchain network (e.g., 1 for Ethereum Mainnet). Default: 1. - ctx (Optional[Context]): The MCP context object. Default: None. """