or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

compilation.mdexceptions.mdindex.mdversion-management.md

compilation.mddocs/

0

# Solidity Compilation

1

2

Comprehensive compilation functions for converting Solidity source code into bytecode, ABI, and other compilation artifacts. Supports all major compilation workflows including string-based compilation, file-based compilation, and the standard JSON interface.

3

4

## Capabilities

5

6

### Source Code Compilation

7

8

Compile Solidity source code directly from a string. Ideal for dynamic compilation scenarios or when working with programmatically generated contracts.

9

10

```python { .api }

11

def compile_source(

12

source: str,

13

output_values: Optional[List] = None,

14

import_remappings: Optional[Union[Dict, List, str]] = None,

15

base_path: Optional[Union[Path, str]] = None,

16

allow_paths: Optional[Union[List, Path, str]] = None,

17

output_dir: Optional[Union[Path, str]] = None,

18

overwrite: bool = False,

19

evm_version: Optional[str] = None,

20

revert_strings: Optional[Union[List, str]] = None,

21

metadata_hash: Optional[str] = None,

22

metadata_literal: bool = False,

23

optimize: bool = False,

24

optimize_runs: Optional[int] = None,

25

optimize_yul: Optional[bool] = None,

26

no_optimize_yul: Optional[bool] = None,

27

yul_optimizations: Optional[int] = None,

28

solc_binary: Optional[Union[str, Path]] = None,

29

solc_version: Optional[Union[str, Version]] = None,

30

allow_empty: bool = False,

31

**kwargs: Any,

32

) -> Dict:

33

"""

34

Compile Solidity contract from source string.

35

36

Parameters:

37

- source: Solidity source code as string

38

- output_values: List of compiler outputs to return (e.g., ['abi', 'bin'])

39

- import_remappings: Path remappings for imports as dict, list, or string

40

- base_path: Root path for source tree instead of filesystem root

41

- allow_paths: Paths allowed for imports

42

- output_dir: Directory for output files

43

- overwrite: Whether to overwrite existing output files

44

- evm_version: Target EVM version (e.g., 'london', 'berlin')

45

- revert_strings: Revert string handling ('default', 'strip', 'debug')

46

- metadata_hash: Metadata hash method ('ipfs', 'bzzr1', 'none')

47

- metadata_literal: Store sources as literal data in metadata

48

- optimize: Enable bytecode optimizer

49

- optimize_runs: Optimization runs (lower = cheaper deployment, higher = cheaper execution)

50

- optimize_yul: Enable Yul optimizer

51

- no_optimize_yul: Disable Yul optimizer

52

- yul_optimizations: Custom Yul optimization sequence

53

- solc_binary: Path to specific solc binary

54

- solc_version: Specific solc version to use

55

- allow_empty: Don't raise exception if no contracts compiled

56

57

Returns:

58

Dict mapping contract names to compilation artifacts

59

60

Raises:

61

ContractsNotFound: No contracts found in source

62

SolcError: Compilation failed

63

"""

64

```

65

66

Usage example:

67

68

```python

69

import solcx

70

71

# Simple compilation

72

source = '''

73

pragma solidity ^0.8.0;

74

contract Example {

75

uint256 public value = 42;

76

}

77

'''

78

79

compiled = solcx.compile_source(source)

80

contract = compiled['<stdin>:Example']

81

print("ABI:", contract['abi'])

82

print("Bytecode:", contract['bin'])

83

84

# With optimization

85

compiled_optimized = solcx.compile_source(

86

source,

87

optimize=True,

88

optimize_runs=200

89

)

90

91

# Custom output values

92

compiled_custom = solcx.compile_source(

93

source,

94

output_values=['abi', 'bin', 'bin-runtime', 'opcodes']

95

)

96

```

97

98

### File-Based Compilation

99

100

Compile one or more Solidity source files. Supports complex project structures with imports and dependencies.

101

102

```python { .api }

103

def compile_files(

104

source_files: Union[List, Path, str],

105

output_values: Optional[List] = None,

106

import_remappings: Optional[Union[Dict, List, str]] = None,

107

base_path: Optional[Union[Path, str]] = None,

108

allow_paths: Optional[Union[List, Path, str]] = None,

109

output_dir: Optional[Union[Path, str]] = None,

110

overwrite: bool = False,

111

evm_version: Optional[str] = None,

112

revert_strings: Optional[Union[List, str]] = None,

113

metadata_hash: Optional[str] = None,

114

metadata_literal: bool = False,

115

optimize: bool = False,

116

optimize_runs: Optional[int] = None,

117

optimize_yul: Optional[bool] = None,

118

no_optimize_yul: Optional[bool] = None,

119

yul_optimizations: Optional[int] = None,

120

solc_binary: Optional[Union[str, Path]] = None,

121

solc_version: Optional[Union[str, Version]] = None,

122

allow_empty: bool = False,

123

**kwargs: Any,

124

) -> Dict:

125

"""

126

Compile one or more Solidity source files.

127

128

Parameters:

129

- source_files: Path or list of paths to Solidity files

130

- Other parameters same as compile_source()

131

132

Returns:

133

Dict mapping contract names to compilation artifacts

134

135

Raises:

136

ContractsNotFound: No contracts found in files

137

SolcError: Compilation failed

138

FileNotFoundError: Source file not found

139

"""

140

```

141

142

Usage example:

143

144

```python

145

import solcx

146

147

# Compile single file

148

compiled = solcx.compile_files('contracts/Token.sol')

149

150

# Compile multiple files

151

compiled = solcx.compile_files([

152

'contracts/Token.sol',

153

'contracts/TokenSale.sol'

154

])

155

156

# With import remappings

157

compiled = solcx.compile_files(

158

'contracts/Token.sol',

159

import_remappings={

160

'@openzeppelin': 'node_modules/@openzeppelin'

161

}

162

)

163

164

# Output to directory

165

solcx.compile_files(

166

'contracts/Token.sol',

167

output_dir='build/contracts',

168

overwrite=True

169

)

170

```

171

172

### Standard JSON Interface

173

174

Compile using Solidity's standard JSON input/output interface. Provides the most flexibility and control over the compilation process.

175

176

```python { .api }

177

def compile_standard(

178

input_data: Dict,

179

base_path: Optional[Union[str, Path]] = None,

180

allow_paths: Optional[Union[List, Path, str]] = None,

181

output_dir: Optional[str] = None,

182

overwrite: bool = False,

183

solc_binary: Optional[Union[str, Path]] = None,

184

solc_version: Optional[Union[str, Version]] = None,

185

allow_empty: bool = False,

186

) -> Dict:

187

"""

188

Compile using standard JSON input/output interface.

189

190

Parameters:

191

- input_data: Standard JSON input specification

192

- base_path: Root path for source tree

193

- allow_paths: Paths allowed for imports

194

- output_dir: Directory for output files

195

- overwrite: Whether to overwrite existing files

196

- solc_binary: Path to specific solc binary

197

- solc_version: Specific solc version to use

198

- allow_empty: Don't raise exception if no contracts compiled

199

200

Returns:

201

Standard JSON output specification

202

203

Raises:

204

ContractsNotFound: No sources in input JSON

205

SolcError: Compilation failed with errors

206

"""

207

```

208

209

Usage example:

210

211

```python

212

import solcx

213

import json

214

215

# Standard JSON input

216

input_json = {

217

"language": "Solidity",

218

"sources": {

219

"Token.sol": {

220

"content": "pragma solidity ^0.8.0; contract Token { uint256 public totalSupply = 1000000; }"

221

}

222

},

223

"settings": {

224

"optimizer": {

225

"enabled": True,

226

"runs": 200

227

},

228

"outputSelection": {

229

"*": {

230

"*": ["abi", "evm.bytecode", "evm.deployedBytecode"]

231

}

232

}

233

}

234

}

235

236

# Compile with standard JSON

237

output = solcx.compile_standard(input_json)

238

contracts = output['contracts']['Token.sol']['Token']

239

print("ABI:", contracts['abi'])

240

print("Bytecode:", contracts['evm']['bytecode']['object'])

241

```

242

243

### Bytecode Linking

244

245

Link library addresses into unlinked bytecode that contains library placeholders.

246

247

```python { .api }

248

def link_code(

249

unlinked_bytecode: str,

250

libraries: Dict,

251

solc_binary: Optional[Union[str, Path]] = None,

252

solc_version: Optional[Version] = None,

253

) -> str:

254

"""

255

Add library addresses into unlinked bytecode.

256

257

Parameters:

258

- unlinked_bytecode: Bytecode containing library placeholders

259

- libraries: Library addresses as {"library_name": "address"}

260

- solc_binary: Path to specific solc binary

261

- solc_version: Specific solc version to use

262

263

Returns:

264

Linked bytecode string

265

266

Raises:

267

SolcError: Linking failed

268

"""

269

```

270

271

Usage example:

272

273

```python

274

import solcx

275

276

# Unlinked bytecode with library placeholders

277

unlinked_bytecode = "608060405234801561001057600080fd5b50__$library_placeholder$__..."

278

279

# Library addresses

280

libraries = {

281

"MyLibrary": "0x1234567890123456789012345678901234567890",

282

"MathLib": "0x0987654321098765432109876543210987654321"

283

}

284

285

# Link the bytecode

286

linked_bytecode = solcx.link_code(unlinked_bytecode, libraries)

287

print("Linked bytecode:", linked_bytecode)

288

```

289

290

### Version Information

291

292

Get version information about the currently active or specified Solidity compiler.

293

294

```python { .api }

295

def get_solc_version(with_commit_hash: bool = False) -> Version:

296

"""

297

Get version of the active solc binary.

298

299

Parameters:

300

- with_commit_hash: Include commit hash in version

301

302

Returns:

303

Version object of active solc

304

305

Raises:

306

SolcNotInstalled: No solc version is active

307

SolcError: Cannot determine version

308

"""

309

```

310

311

Usage example:

312

313

```python

314

import solcx

315

316

# Set a specific version

317

solcx.set_solc_version('0.8.19')

318

319

# Get version info

320

version = solcx.get_solc_version()

321

print(f"Active solc version: {version}")

322

323

# Get version with commit hash

324

version_with_commit = solcx.get_solc_version(with_commit_hash=True)

325

print(f"Full version: {version_with_commit}")

326

```

327

328

## Error Handling

329

330

Compilation functions raise specific exceptions for different error conditions:

331

332

```python

333

import solcx

334

from solcx import ContractsNotFound, SolcError

335

336

try:

337

# This might fail

338

compiled = solcx.compile_source("invalid solidity code")

339

except ContractsNotFound:

340

print("No contracts found in source")

341

except SolcError as e:

342

print(f"Compilation failed: {e}")

343

print(f"Command: {' '.join(e.command)}")

344

print(f"Return code: {e.return_code}")

345

print(f"Stderr: {e.stderr_data}")

346

```