Skip to content

Instantly share code, notes, and snippets.

@roninjin10
Created October 13, 2025 10:46
Show Gist options
  • Select an option

  • Save roninjin10/5886f192ed86100cf9168c5c8240c02c to your computer and use it in GitHub Desktop.

Select an option

Save roninjin10/5886f192ed86100cf9168c5c8240c02c to your computer and use it in GitHub Desktop.
foundry-compilers napi rs exmaple api
Here's what a TypeScript interface would look like if you wrapped the
foundry-compilers Rust API with NAPI-RS:
// =======================================================================
=====
// Core Types
// =======================================================================
=====
export type Severity = 'error' | 'warning' | 'info';
export type PathStyle = 'unix' | 'windows' | 'hh_contract_identifier';
export interface Version {
major: number;
minor: number;
patch: number;
prerelease?: string;
build?: string;
}
// =======================================================================
=====
// Project Configuration
// =======================================================================
=====
export interface ProjectPathsConfig {
/** Root directory of the project */
root: string;
/** Directory containing contract sources */
sources: string;
/** Directory for compiler artifacts */
artifacts: string;
/** Directory for build info files */
build_info: string;
/** Cache file path */
cache: string;
/** Libraries directories */
libraries?: string[];
/** Remappings for imports */
remappings?: string[];
}
export interface SolcSettings {
optimizer?: {
enabled: boolean;
runs: number;
details?: Record<string, unknown>;
};
outputSelection?: Record<string, Record<string, string[]>>;
evmVersion?: string;
metadata?: {
bytecodeHash?: 'none' | 'ipfs' | 'bzzr1';
useLiteralContent?: boolean;
};
libraries?: Record<string, Record<string, string>>;
viaIR?: boolean;
debug?: {
revertStrings?: string;
debugInfo?: string[];
};
}
export interface CompilerRestrictions {
/** Minimum compiler version */
minVersion?: string;
/** Maximum compiler version */
maxVersion?: string;
/** Specific settings required */
settings?: Partial<SolcSettings>;
}
// =======================================================================
=====
// Artifacts
// =======================================================================
=====
export interface ContractBytecode {
object: string;
sourceMap?: string;
linkReferences?: Record<string, Record<string, Array<{ start: number;
length: number }>>>;
deployedObject?: string;
deployedSourceMap?: string;
deployedLinkReferences?: Record<string, Record<string, Array<{ start:
number; length: number }>>>;
}
export interface ContractAbi {
type: 'function' | 'constructor' | 'receive' | 'fallback' | 'event' |
'error';
name?: string;
inputs?: Array<{ name: string; type: string; internalType?: string }>;
outputs?: Array<{ name: string; type: string; internalType?: string }>;
stateMutability?: 'pure' | 'view' | 'nonpayable' | 'payable';
anonymous?: boolean;
}
export interface CompilerArtifact {
/** Contract ABI */
abi?: ContractAbi[];
/** Bytecode for deployment */
bytecode?: ContractBytecode;
/** Deployed bytecode */
deployedBytecode?: ContractBytecode;
/** Method identifiers */
methodIdentifiers?: Record<string, string>;
/** Gas estimates */
gasEstimates?: Record<string, unknown>;
/** Storage layout */
storageLayout?: {
storage: Array<{
astId: number;
contract: string;
label: string;
offset: number;
slot: string;
type: string;
}>;
types: Record<string, unknown>;
};
/** Developer documentation */
devdoc?: Record<string, unknown>;
/** User documentation */
userdoc?: Record<string, unknown>;
/** AST */
ast?: Record<string, unknown>;
/** Metadata */
metadata?: string;
/** IR (Intermediate Representation) */
ir?: string;
/** Optimized IR */
irOptimized?: string;
}
export interface ArtifactFile {
/** Artifact data */
artifact: CompilerArtifact;
/** Path to artifact file */
file: string;
/** Compiler version used */
version: Version;
}
export interface Artifacts {
/** Map of contract path -> contract name -> artifact */
contracts: Map<string, Map<string, CompilerArtifact>>;
}
// =======================================================================
=====
// Compilation Output
// =======================================================================
=====
export interface CompilerError {
/** Error severity */
severity: Severity;
/** Error code */
errorCode?: string;
/** Error message */
message: string;
/** Source location */
sourceLocation?: {
file: string;
start: number;
end: number;
};
/** Formatted message */
formattedMessage?: string;
}
export interface SourceFile {
/** File content */
content: string;
/** AST */
ast?: Record<string, unknown>;
/** Source file ID */
id: number;
}
export interface CompilerOutput {
/** Compiled contracts */
contracts: Map<string, Map<string, CompilerArtifact>>;
/** Source files */
sources: Map<string, SourceFile>;
/** Errors and warnings */
errors?: CompilerError[];
/** Compiler version */
version: Version;
}
export interface ProjectCompileOutput {
/** Artifacts from compilation */
artifacts: Artifacts;
/** Compiler output */
output: CompilerOutput;
/** Whether any contracts were compiled */
compiled: boolean;
/** Cached artifacts (not recompiled) */
cached: Map<string, CompilerArtifact>;
/** Ignored errors */
ignoredErrors: CompilerError[];
}
// =======================================================================
=====
// Project Builder
// =======================================================================
=====
export interface ProjectBuilderOptions {
/** Project paths configuration */
paths?: ProjectPathsConfig;
/** Default compiler settings */
settings?: SolcSettings;
/** Additional settings profiles */
additionalSettings?: Record<string, SolcSettings>;
/** Enable caching */
cached?: boolean;
/** Output build info */
buildInfo?: boolean;
/** Disable artifact writing */
noArtifacts?: boolean;
/** Ignored error codes */
ignoredErrorCodes?: number[];
/** Ignored file paths */
ignoredFilePaths?: string[];
/** Minimum severity to treat as error */
compilerSeverityFilter?: Severity;
/** Offline mode (no network access) */
offline?: boolean;
/** Use slash paths on Windows */
slashPaths?: boolean;
/** Path style for output */
pathStyle?: PathStyle;
}
// =======================================================================
=====
// Main Project Class
// =======================================================================
=====
export class Project {
//
-------------------------------------------------------------------------
// Static Constructors
//
-------------------------------------------------------------------------
/**
* Create a new project builder
*/
static builder(): ProjectBuilder;
/**
* Create a project with default Hardhat paths
* @param root - Project root directory
*/
static hardhat(root: string): Project;
/**
* Create a project with default Foundry paths
* @param root - Project root directory
*/
static foundry(root: string): Project;
//
-------------------------------------------------------------------------
// Properties
//
-------------------------------------------------------------------------
/** Get project root directory */
readonly root: string;
/** Get sources directory path */
readonly sourcesPath: string;
/** Get artifacts directory path */
readonly artifactsPath: string;
/** Get cache file path */
readonly cachePath: string;
/** Get build info directory path */
readonly buildInfoPath: string;
/** Get project paths configuration */
readonly paths: ProjectPathsConfig;
/** Get compiler settings */
readonly settings: SolcSettings;
/** Whether caching is enabled */
readonly cached: boolean;
/** Whether build info is enabled */
readonly buildInfo: boolean;
//
-------------------------------------------------------------------------
// Compilation Methods
//
-------------------------------------------------------------------------
/**
* Compile all contracts in the project
* @returns Compilation output with artifacts
*/
compile(): Promise<ProjectCompileOutput>;
/**
* Compile a single contract file
* @param file - Path to contract file
* @returns Compilation output
*/
compileFile(file: string): Promise<ProjectCompileOutput>;
/**
* Compile specific contract files
* @param files - Array of file paths
* @returns Compilation output
*/
compileFiles(files: string[]): Promise<ProjectCompileOutput>;
//
-------------------------------------------------------------------------
// Utility Methods
//
-------------------------------------------------------------------------
/**
* Get all source files in the project
* @returns Map of file path to source content
*/
sources(): Promise<Map<string, string>>;
/**
* Read the compiler cache file
* @returns Cache data
*/
readCacheFile(): Promise<Record<string, unknown>>;
/**
* Find the path of a contract by name
* @param name - Contract name
* @returns Contract file path
* @throws If multiple or no contracts found
*/
findContractPath(name: string): Promise<string>;
/**
* Clean up artifacts and cache files
*/
cleanup(): Promise<void>;
/**
* Set maximum parallel compiler processes
* @param jobs - Number of parallel jobs
*/
setSolcJobs(jobs: number): void;
/**
* Update output selection for all settings profiles
* @param updater - Function to modify output selection
*/
updateOutputSelection(
updater: (selection: Record<string, Record<string, string[]>>) => void
): void;
/**
* Generate standard JSON input for compilation
* @param target - Target contract path
* @returns Standard JSON compiler input
*/
standardJsonInput(target: string): Promise<Record<string, unknown>>;
}
// =======================================================================
=====
// Project Builder
// =======================================================================
=====
export class ProjectBuilder {
constructor();
/**
* Set project paths
*/
paths(paths: ProjectPathsConfig): this;
/**
* Set compiler settings
*/
settings(settings: SolcSettings): this;
/**
* Add additional settings profile
*/
additionalSettings(name: string, settings: SolcSettings): this;
/**
* Enable/disable caching
*/
cached(enabled: boolean): this;
/**
* Enable/disable build info
*/
buildInfo(enabled: boolean): this;
/**
* Enable/disable artifact writing
*/
noArtifacts(enabled: boolean): this;
/**
* Set ignored error codes
*/
ignoredErrorCodes(codes: number[]): this;
/**
* Set ignored file paths
*/
ignoredFilePaths(paths: string[]): this;
/**
* Set compiler severity filter
*/
compilerSeverityFilter(severity: Severity): this;
/**
* Enable/disable offline mode
*/
offline(enabled: boolean): this;
/**
* Enable/disable slash paths on Windows
*/
slashPaths(enabled: boolean): this;
/**
* Set path style
*/
pathStyle(style: PathStyle): this;
/**
* Build the project with the configured options
*/
build(): Project;
}
// =======================================================================
=====
// Utility Functions
// =======================================================================
=====
/**
* Get default Hardhat paths for a root directory
*/
export function hardhatPaths(root: string): ProjectPathsConfig;
/**
* Get default Foundry paths for a root directory
*/
export function foundryPaths(root: string): ProjectPathsConfig;
/**
* Parse Solidity version string
*/
export function parseVersion(version: string): Version;
/**
* Format version to string
*/
export function formatVersion(version: Version): string;
Usage Example
import { Project, ProjectBuilder } from '@guillotine/foundry-compilers';
// Using builder pattern
const project = Project.builder()
.paths({
root: './contracts',
sources: './contracts/src',
artifacts: './out',
cache: './cache',
build_info: './out/build-info',
})
.settings({
optimizer: {
enabled: true,
runs: 200,
},
evmVersion: 'paris',
})
.cached(true)
.buildInfo(true)
.ignoredErrorCodes([5667]) // Unused function parameter
.build();
// Compile all contracts
const output = await project.compile();
console.log('Compiled:', output.compiled);
console.log('Artifacts:', output.artifacts.contracts.size);
// Compile specific file
const fileOutput = await project.compileFile('src/MyContract.sol');
// Find contract
const path = await project.findContractPath('MyContract');
// Cleanup
await project.cleanup();
// Using presets
const hardhatProject = Project.hardhat('./');
const foundryProject = Project.foundry('./');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment