or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-nomicfoundation--hardhat-foundry

Hardhat plugin that adds Hardhat support to Foundry projects for seamless Ethereum development workflow integration

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@nomicfoundation/hardhat-foundry@1.2.x

To install, run

npx @tessl/cli install tessl/npm-nomicfoundation--hardhat-foundry@1.2.0

index.mddocs/

Hardhat Foundry

The @nomicfoundation/hardhat-foundry plugin enables seamless integration between Hardhat and Foundry development environments for Ethereum smart contract projects. It automatically configures Hardhat to use Foundry's contracts directory structure and dependency management system, allowing developers to leverage both tools' strengths within a single project.

Package Information

  • Package Name: @nomicfoundation/hardhat-foundry
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @nomicfoundation/hardhat-foundry

Core Imports

import "@nomicfoundation/hardhat-foundry";

For accessing utility functions:

import { 
  getForgeConfig, 
  parseRemappings, 
  getRemappings, 
  installDependency, 
  HardhatFoundryError 
} from "@nomicfoundation/hardhat-foundry/dist/src/foundry";

Basic Usage

The plugin works automatically once imported in your Hardhat configuration:

// hardhat.config.ts
import "@nomicfoundation/hardhat-foundry";

export default {
  solidity: "0.8.19",
  // Other Hardhat config...
};

For projects without Foundry setup, initialize it:

npx hardhat init-foundry

Architecture

The plugin consists of several key components:

  • Configuration Extension: Automatically modifies Hardhat configuration when foundry.toml is present
  • Path Management: Configures source and cache paths based on Foundry configuration
  • Remapping Integration: Adds Foundry remapping support to Hardhat compilation system
  • Task System: Provides init-foundry task for project setup
  • Utility Functions: Core functions for interacting with Foundry toolchain

Capabilities

Plugin Configuration

The plugin automatically extends Hardhat configuration to integrate with Foundry projects when a foundry.toml file is present.

Configuration Extension (Automatic)

When imported, the plugin automatically:

  • Checks for foundry.toml presence and warns if missing
  • Loads Foundry configuration using forge config --json
  • Updates Hardhat's sources path to match Foundry's src configuration
  • Modifies cache path to prevent conflicts with Foundry's cache
  • Validates user-configured paths against Foundry configuration

Project Initialization

Initialize Foundry setup in existing Hardhat projects.

/**
 * Hardhat task that initializes Foundry setup in current project
 * Creates foundry.toml file and installs forge-std dependency
 * Usage: npx hardhat init-foundry
 * @task init-foundry
 */

The init-foundry task:

  • Creates a foundry.toml file with appropriate configuration
  • Sets up proper source, output, and library paths
  • Installs foundry-rs/forge-std dependency automatically
  • Configures cache paths to avoid conflicts

Generated foundry.toml structure:

[profile.default]
src = 'contracts'
out = 'out'
libs = ['node_modules', 'lib']
test = 'test'
cache_path  = 'cache_forge'

Foundry Configuration Access

Retrieve Foundry project configuration data.

/**
 * Gets the current Foundry configuration by running `forge config --json`
 * @returns Foundry configuration object containing src, cache_path, and other config properties
 */
function getForgeConfig(): {
  src: string;
  cache_path: string;
  out: string;
  libs: string[];
  test: string;
  remappings: string[];
  [key: string]: any;
};

Usage Example:

import { getForgeConfig } from "@nomicfoundation/hardhat-foundry/dist/src/foundry";

const config = getForgeConfig();
console.log(config.src); // e.g., "contracts"
console.log(config.cache_path); // e.g., "cache_forge"

Remapping Management

Parse and retrieve Foundry remappings for dependency resolution.

/**
 * Parses Foundry remappings from text format into a mapping object
 * @param remappingsTxt - Raw remappings text from `forge remappings`
 * @returns Object mapping remapping prefixes to their target paths
 */
function parseRemappings(remappingsTxt: string): Record<string, string>;

/**
 * Gets Foundry remappings by running `forge remappings` (cached)
 * @returns Promise resolving to remappings object
 */
function getRemappings(): Promise<Record<string, string>>;

Usage Examples:

import { parseRemappings, getRemappings } from "@nomicfoundation/hardhat-foundry/dist/src/foundry";

// Parse remappings manually
const remappings = parseRemappings("@openzeppelin/=lib/openzeppelin-contracts/\n@forge-std/=lib/forge-std/src/");
console.log(remappings);
// { "@openzeppelin/": "lib/openzeppelin-contracts/", "@forge-std/": "lib/forge-std/src/" }

// Get remappings automatically (cached)
const currentRemappings = await getRemappings();
console.log(currentRemappings);

Remapping Format Rules:

  • Each line contains one remapping in format prefix=target
  • Context remappings (containing :) are not allowed
  • Remappings without targets (no =) are not allowed
  • First occurrence wins if duplicate prefixes exist
  • Empty lines are ignored

Dependency Installation

Install Foundry dependencies using forge install.

/**
 * Installs a Foundry dependency using `forge install`
 * @param dependency - Dependency identifier (e.g., "foundry-rs/forge-std")
 * @returns Promise that resolves when installation completes
 */
function installDependency(dependency: string): Promise<void>;

Usage Example:

import { installDependency } from "@nomicfoundation/hardhat-foundry/dist/src/foundry";

// Install forge standard library
await installDependency("foundry-rs/forge-std");

// Install OpenZeppelin contracts
await installDependency("OpenZeppelin/openzeppelin-contracts");

The function automatically:

  • Checks if --no-commit flag is supported
  • Uses the appropriate forge install command with or without the flag
  • Provides colored console output for the command being run
  • Throws ForgeInstallError if installation fails

Error Handling

Comprehensive error handling for Foundry-related operations.

/**
 * Main error class for hardhat-foundry plugin operations
 */
class HardhatFoundryError extends NomicLabsHardhatPluginError {
  constructor(message: string, parent?: Error);
}

/**
 * Specialized error class for forge install command failures
 */
class ForgeInstallError extends HardhatFoundryError {
  constructor(dependency: string, parent: Error);
}

Common Error Scenarios:

  1. Missing Foundry Installation: When forge command is not available (exit code 127)
  2. Invalid Configuration: When foundry.toml file has syntax errors (exit code 134)
  3. Path Mismatch: When user-configured sources path doesn't match Foundry configuration
  4. Missing Configuration Keys: When required src or cache_path keys are missing
  5. Invalid Remappings: When remappings contain contexts or lack targets
  6. Installation Failures: When forge install fails for dependencies (throws ForgeInstallError)

Usage Example:

import { HardhatFoundryError, getForgeConfig } from "@nomicfoundation/hardhat-foundry/dist/src/foundry";

try {
  const config = getForgeConfig();
} catch (error) {
  if (error instanceof HardhatFoundryError) {
    console.error("Foundry integration error:", error.message);
  }
}

Internal Task Integration

The plugin integrates with Hardhat's internal compilation system through task overrides:

Remapping Integration: The plugin overrides TASK_COMPILE_GET_REMAPPINGS to provide Foundry remappings during compilation.

Version Compatibility: The plugin overrides TASK_COMPILE_TRANSFORM_IMPORT_NAME to ensure compatibility with Hardhat >= 2.17.2.

These integrations are automatic and don't require direct interaction from users.

Types

// Internal type for remapping storage
type Remappings = Record<string, string>;

// Error classes
class HardhatFoundryError extends NomicLabsHardhatPluginError {
  constructor(message: string, parent?: Error);
}

// Specialized error class for forge install command failures
class ForgeInstallError extends HardhatFoundryError {
  constructor(dependency: string, parent: Error);
}

Dependencies

Runtime Dependencies:

  • picocolors: ^1.1.0 - For colored console output

Peer Dependencies:

  • hardhat: ^2.26.0 - Required Hardhat framework

Node.js Built-ins:

  • fs: File system operations
  • path: Path manipulation
  • child_process: Command execution
  • util: Utility functions