Skip to main content
Glama
kukapay

blocknative-mcp

estimate_gas_cost

Estimate transaction gas costs by analyzing gas limit, confidence level, and blockchain network to predict accurate fee requirements.

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
NameRequiredDescriptionDefault
gas_limitYes
confidenceNo
chain_idNo
ctxNo

Implementation Reference

  • The handler function for the 'estimate_gas_cost' tool, decorated with @mcp.tool() for registration. It validates inputs, fetches gas prices using the helper, selects the closest confidence prediction, calculates the total gas cost in Gwei and ETH, and returns a formatted 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)"
        )
  • Supporting helper function that fetches gas price data from the Blocknative API, extracts predictions and base fee, and handles errors. Used by the estimate_gas_cost handler.
    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)}"}
  • Function signature with type annotations and docstring defining the input parameters and return type, serving as the tool schema.
    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.
        """
  • The @mcp.tool() decorator registers the estimate_gas_cost function as an MCP tool.
    @mcp.tool()

Tool Definition Quality

Score is being calculated. Check back soon.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/kukapay/blocknative-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server