or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-library.mdhardhat-plugin.mdindex.mdprogrammatic-api.mdutility-functions.md

programmatic-api.mddocs/

0

# Programmatic API

1

2

Direct access to the coverage instrumentation and reporting engine for custom workflows, advanced integrations, and non-Hardhat environments. The API class provides complete control over the coverage collection process.

3

4

## Capabilities

5

6

### API Class

7

8

The main coverage runner and instrumentation engine.

9

10

```javascript { .api }

11

/**

12

* Main API class for programmatic coverage control

13

* Provides instrumentation, data collection, and report generation

14

*/

15

const API = require('solidity-coverage/api');

16

17

class API {

18

/**

19

* Creates a new coverage API instance

20

* @param config - Configuration object for coverage behavior

21

*/

22

constructor(config?: CoverageConfig);

23

24

// Core instrumentation methods

25

instrument(targets: Target[]): InstrumentedTarget[];

26

getInstrumentationData(): InstrumentationData;

27

setInstrumentationData(data: InstrumentationData): void;

28

29

// Report generation

30

report(folder?: string): Promise<void>;

31

32

// Provider integration

33

attachToHardhatVM(provider: HardhatProvider): Promise<void>;

34

35

// Test matrix data collection

36

collectTestMatrixData(testInfo: MochaTestInfo): void;

37

38

// File I/O operations

39

saveCoverage(data: CoverageData): void;

40

saveTestMatrix(): void;

41

saveMochaJsonOutput(data: MochaData): void;

42

saveHumanReadableAbis(data: AbiData): void;

43

44

// Path utilities

45

makeKeysRelative(map: CoverageMap, workingDir: string): CoverageMap;

46

47

// Configuration

48

setLoggingLevel(isSilent: boolean): void;

49

50

// Cleanup

51

finish(): Promise<void>;

52

}

53

```

54

55

**Usage Examples:**

56

57

```javascript

58

const API = require('solidity-coverage/api');

59

60

// Basic API usage

61

const api = new API({

62

skipFiles: ['contracts/mocks/'],

63

istanbulReporter: ['html', 'lcov'],

64

});

65

66

// Instrument contracts

67

const targets = [

68

{

69

source: contractSource,

70

canonicalPath: '/path/to/Contract.sol',

71

relativePath: 'contracts/Contract.sol'

72

}

73

];

74

75

const instrumented = api.instrument(targets);

76

77

// Generate reports after tests

78

await api.report('./coverage');

79

```

80

81

### Contract Instrumentation

82

83

Instruments Solidity source files for coverage collection.

84

85

```javascript { .api }

86

/**

87

* Instruments a set of Solidity source files for coverage tracking

88

* @param targets - Array of contract source objects to instrument

89

* @returns Array of instrumented contract objects

90

*/

91

instrument(targets: Target[]): InstrumentedTarget[];

92

93

interface Target {

94

source: string; // Solidity source code to instrument

95

canonicalPath: string; // Absolute path to source file

96

relativePath?: string; // Relative path for display purposes

97

}

98

99

interface InstrumentedTarget {

100

canonicalPath: string; // Absolute path to original source file

101

relativePath?: string; // Relative path for display purposes

102

source: string; // Instrumented Solidity source code

103

}

104

```

105

106

**Usage Examples:**

107

108

```javascript

109

const fs = require('fs');

110

const path = require('path');

111

112

// Prepare targets for instrumentation

113

const contractPath = path.resolve('./contracts/MyContract.sol');

114

const targets = [

115

{

116

source: fs.readFileSync(contractPath, 'utf8'),

117

canonicalPath: contractPath,

118

relativePath: 'contracts/MyContract.sol'

119

}

120

];

121

122

// Instrument the contracts

123

const instrumented = api.instrument(targets);

124

125

// Use instrumented source in compilation

126

instrumented.forEach(target => {

127

fs.writeFileSync(target.canonicalPath.replace('.sol', '.instrumented.sol'), target.source);

128

});

129

```

130

131

### Instrumentation Data Management

132

133

Manages the hit map data used for coverage collection.

134

135

```javascript { .api }

136

/**

137

* Returns a copy of the hit map created during instrumentation

138

* Useful for delegating coverage collection to multiple processes

139

* @returns Deep copy of instrumentation data

140

*/

141

getInstrumentationData(): InstrumentationData;

142

143

/**

144

* Sets the hit map object for pre-existing instrumentation

145

* Useful for collecting data across multiple test runs

146

* @param data - Instrumentation data from previous run

147

*/

148

setInstrumentationData(data: InstrumentationData): void;

149

150

interface InstrumentationData {

151

[hash: string]: {

152

contractPath: string; // Path to the contract file

153

type: CoverageType; // Type of coverage point

154

id: number; // Unique identifier for coverage point

155

hits: number; // Number of times this point was hit

156

locationIdx?: number; // Index for branch coverage points

157

};

158

}

159

160

type CoverageType = 'line' | 'function' | 'statement' | 'branch' | 'and-true' | 'or-false' | 'requirePre' | 'requirePost';

161

```

162

163

**Usage Examples:**

164

165

```javascript

166

// Save instrumentation data for later use

167

const instrumentationData = api.getInstrumentationData();

168

fs.writeFileSync('instrumentation.json', JSON.stringify(instrumentationData));

169

170

// Load instrumentation data in another process

171

const savedData = JSON.parse(fs.readFileSync('instrumentation.json', 'utf8'));

172

api.setInstrumentationData(savedData);

173

```

174

175

### Report Generation

176

177

Generates Istanbul-compatible coverage reports.

178

179

```javascript { .api }

180

/**

181

* Generates coverage reports using Istanbul

182

* Creates HTML, LCOV, text, and JSON reports based on configuration

183

* @param folder - Optional output folder (defaults to config.istanbulFolder)

184

* @returns Promise that resolves when reports are complete

185

*/

186

report(folder?: string): Promise<void>;

187

```

188

189

**Usage Examples:**

190

191

```javascript

192

// Generate reports with default configuration

193

await api.report();

194

195

// Generate reports to specific directory

196

await api.report('./custom-coverage');

197

198

// Generate reports after configuring reporters

199

api.istanbulReporter = ['html', 'json', 'text'];

200

await api.report();

201

```

202

203

### Provider Integration

204

205

Integrates with Hardhat's EVM provider for data collection.

206

207

```javascript { .api }

208

/**

209

* Attaches coverage data collector to Hardhat's EVM

210

* Hooks into VM execution to track coverage hits

211

* @param provider - Hardhat network provider instance

212

* @returns Promise that resolves when attachment is complete

213

*/

214

attachToHardhatVM(provider: HardhatProvider): Promise<void>;

215

216

interface HardhatProvider {

217

// Hardhat provider interface (simplified)

218

init?(): Promise<void>;

219

_wrapped?: HardhatProvider;

220

_node: {

221

_vm: {

222

evm: {

223

events: EventEmitter;

224

};

225

};

226

};

227

}

228

```

229

230

**Usage Examples:**

231

232

```javascript

233

const { ethers } = require('hardhat');

234

235

// Attach to Hardhat provider

236

await api.attachToHardhatVM(ethers.provider);

237

238

// Run tests - coverage data will be collected automatically

239

// ... run your tests here ...

240

241

// Generate reports

242

await api.report();

243

```

244

245

### Test Matrix Data Collection

246

247

Collects test-to-code mapping data for analysis.

248

249

```javascript { .api }

250

/**

251

* Collects mapping data between test cases and code coverage

252

* Useful for understanding which tests exercise which code paths

253

* @param testInfo - Mocha test information object

254

*/

255

collectTestMatrixData(testInfo: MochaTestInfo): void;

256

257

interface MochaTestInfo {

258

title: string; // Test case title

259

file: string; // Test file path

260

fullTitle?(): string; // Full test hierarchy title

261

}

262

263

/**

264

* Saves collected test matrix data to JSON file

265

* Creates testMatrix.json with test-to-coverage mapping

266

*/

267

saveTestMatrix(): void;

268

```

269

270

**Usage Examples:**

271

272

```javascript

273

// In a custom Mocha reporter

274

class CoverageReporter {

275

constructor(runner) {

276

runner.on('test end', (test) => {

277

api.collectTestMatrixData({

278

title: test.title,

279

file: test.file,

280

});

281

});

282

283

runner.on('end', () => {

284

api.saveTestMatrix();

285

});

286

}

287

}

288

```

289

290

### File I/O Operations

291

292

Saves various coverage-related data files.

293

294

```javascript { .api }

295

/**

296

* Saves coverage data to coverage.json file

297

* @param data - Coverage data object from Istanbul

298

*/

299

saveCoverage(data: CoverageData): void;

300

301

/**

302

* Saves Mocha test output to JSON file

303

* @param data - Mocha test results data

304

*/

305

saveMochaJsonOutput(data: MochaData): void;

306

307

/**

308

* Saves human-readable ABI data to JSON file

309

* @param data - Processed ABI information

310

*/

311

saveHumanReadableAbis(data: AbiData): void;

312

313

interface CoverageData {

314

[contractPath: string]: {

315

path: string;

316

statementMap: object;

317

fnMap: object;

318

branchMap: object;

319

s: object; // Statement hits

320

f: object; // Function hits

321

b: object; // Branch hits

322

l: object; // Line hits

323

};

324

}

325

```

326

327

### Path Utilities

328

329

Utilities for working with file paths in coverage data.

330

331

```javascript { .api }

332

/**

333

* Converts absolute paths to relative paths in coverage maps

334

* Ensures coverage reports work correctly on different systems

335

* @param map - Coverage map with absolute paths as keys

336

* @param workingDir - Working directory to make paths relative to

337

* @returns Coverage map with relative paths as keys

338

*/

339

makeKeysRelative(map: CoverageMap, workingDir: string): CoverageMap;

340

341

interface CoverageMap {

342

[path: string]: CoverageData;

343

}

344

```

345

346

**Usage Examples:**

347

348

```javascript

349

const path = require('path');

350

351

// Make coverage paths relative for portability

352

const absoluteCoverage = {

353

'/Users/dev/project/contracts/MyContract.sol': coverageData

354

};

355

356

const relativeCoverage = api.makeKeysRelative(absoluteCoverage, process.cwd());

357

// Result: { 'contracts/MyContract.sol': coverageData }

358

```

359

360

### Configuration Options

361

362

Configuration object structure for API initialization.

363

364

```javascript { .api }

365

interface CoverageConfig {

366

// File handling

367

cwd?: string; // Working directory (default: process.cwd())

368

skipFiles?: string[]; // Files to exclude from instrumentation

369

370

// Output configuration

371

istanbulFolder?: string; // Output directory for reports

372

istanbulReporter?: string[]; // Report formats: html, lcov, text, json

373

abiOutputPath?: string; // Path for ABI output file (default: "humanReadableAbis.json")

374

matrixOutputPath?: string; // Path for test matrix output (default: "testMatrix.json")

375

mochaJsonOutputPath?: string; // Path for Mocha JSON output (default: "mochaOutput.json")

376

matrixReporterPath?: string; // Path to matrix reporter module (default: "solidity-coverage/plugins/resources/matrix.js")

377

378

// Server configuration

379

client?: object; // Client configuration

380

host?: string; // Server host

381

port?: number; // Server port

382

providerOptions?: object; // Provider configuration

383

autoLaunchServer?: boolean; // Auto-launch server flag

384

385

// Coverage measurement toggles

386

measureStatementCoverage?: boolean; // Enable statement coverage

387

measureFunctionCoverage?: boolean; // Enable function coverage

388

measureModifierCoverage?: boolean; // Enable modifier coverage

389

measureLineCoverage?: boolean; // Enable line coverage

390

measureBranchCoverage?: boolean; // Enable branch coverage

391

modifierWhitelist?: string[]; // Specific modifiers to measure

392

393

// Compilation options

394

viaIR?: boolean; // Enable Solidity viaIR compilation

395

usingSolcV4?: boolean; // Compatibility for Solidity v0.4.x

396

irMinimum?: boolean; // Use minimal IR optimization

397

solcOptimizerDetails?: object; // Custom optimizer configuration

398

399

// Workflow hooks

400

onServerReady?: (config: Config) => void; // Server ready callback

401

onCompileComplete?: (config: Config) => void; // Compilation complete callback

402

onTestsComplete?: (config: Config) => void; // Tests complete callback

403

onIstanbulComplete?: (config: Config) => void; // Reports complete callback

404

onPreCompile?: (config: Config) => void; // Pre-compilation callback

405

406

// Logging

407

silent?: boolean; // Disable console output

408

log?: (message: string) => void; // Custom logging function

409

}

410

```

411

412

**Configuration Examples:**

413

414

```javascript

415

// Minimal configuration

416

const api = new API({

417

skipFiles: ['contracts/test/']

418

});

419

420

// Full configuration with hooks

421

const api = new API({

422

cwd: process.cwd(),

423

skipFiles: ['contracts/mocks/', 'contracts/test/'],

424

istanbulReporter: ['html', 'lcov', 'json'],

425

istanbulFolder: './coverage',

426

measureStatementCoverage: true,

427

measureFunctionCoverage: true,

428

measureModifierCoverage: true,

429

measureLineCoverage: true,

430

measureBranchCoverage: true,

431

viaIR: true,

432

silent: false,

433

onCompileComplete: (config) => {

434

console.log('Compilation finished');

435

},

436

onTestsComplete: (config) => {

437

console.log('Tests completed, generating reports...');

438

},

439

onIstanbulComplete: (config) => {

440

console.log('Coverage reports generated');

441

}

442

});

443

```