0
# Legacy Combined JSON Compilation
1
2
Legacy compilation methods using the combined JSON output format, supporting older workflows and integrations. These methods are maintained for backward compatibility but new projects should prefer the standard JSON interface.
3
4
## Capabilities
5
6
### Source String Compilation
7
8
Compiles Solidity source code from a string using the legacy combined JSON output format.
9
10
```python { .api }
11
def compile_source(source, allow_empty=False, output_values=ALL_OUTPUT_VALUES, **kwargs):
12
"""
13
Compile Solidity source code from a string.
14
15
Args:
16
source (str): Solidity source code to compile
17
allow_empty (bool): Whether to allow compilation with no contracts found
18
output_values (tuple): Tuple of output values to include in compilation
19
(default: ALL_OUTPUT_VALUES)
20
**kwargs: Additional arguments passed to solc wrapper including:
21
- import_remappings: List of import remapping strings
22
- optimize: Enable optimization
23
- optimize_runs: Number of optimization runs
24
- allow_paths: Allowed import paths
25
26
Returns:
27
dict: Dictionary of compiled contracts with contract names as keys, each containing:
28
- abi: Contract application binary interface (list)
29
- code: Contract creation bytecode (hex string)
30
- code_runtime: Contract runtime bytecode (hex string)
31
- source: Source code (if 'source' in output_values)
32
- meta: Compilation metadata
33
34
Raises:
35
ContractsNotFound: When no contracts found and allow_empty=False
36
SolcError: When compilation fails
37
"""
38
```
39
40
### Source Files Compilation
41
42
Compiles Solidity source files using the legacy combined JSON output format.
43
44
```python { .api }
45
def compile_files(source_files, allow_empty=False, output_values=ALL_OUTPUT_VALUES, **kwargs):
46
"""
47
Compile Solidity source files.
48
49
Args:
50
source_files (list): List of source file paths to compile
51
allow_empty (bool): Whether to allow compilation with no contracts found
52
output_values (tuple): Tuple of output values to include in compilation
53
(default: ALL_OUTPUT_VALUES)
54
**kwargs: Additional arguments passed to solc wrapper
55
56
Returns:
57
dict: Dictionary of compiled contracts with same structure as compile_source
58
59
Raises:
60
ContractsNotFound: When no contracts found and allow_empty=False
61
SolcError: When compilation fails
62
"""
63
```
64
65
## Constants
66
67
### ALL_OUTPUT_VALUES
68
69
```python { .api }
70
ALL_OUTPUT_VALUES = (
71
"abi",
72
"asm",
73
"ast",
74
"bin",
75
"bin-runtime",
76
"clone-bin",
77
"devdoc",
78
"interface",
79
"opcodes",
80
"userdoc"
81
)
82
```
83
84
Default tuple of output values included in legacy compilation. You can specify a subset of these values to reduce compilation time and output size.
85
86
## Usage Examples
87
88
### Basic Source String Compilation
89
90
```python
91
from solc import compile_source
92
93
# Compile simple contract from string
94
source_code = '''
95
pragma solidity ^0.4.24;
96
97
contract SimpleStorage {
98
uint256 public storedData;
99
100
constructor(uint256 initialValue) public {
101
storedData = initialValue;
102
}
103
104
function set(uint256 x) public {
105
storedData = x;
106
}
107
108
function get() public view returns (uint256) {
109
return storedData;
110
}
111
}
112
'''
113
114
compiled = compile_source(source_code)
115
116
# Access contract data
117
contract = compiled['SimpleStorage']
118
abi = contract['abi']
119
bytecode = contract['code']
120
runtime_bytecode = contract['code_runtime']
121
122
print(f"Contract ABI: {abi}")
123
print(f"Bytecode: {bytecode}")
124
```
125
126
### File Compilation
127
128
```python
129
from solc import compile_files
130
131
# Compile contracts from files
132
compiled = compile_files([
133
'/path/to/contracts/Token.sol',
134
'/path/to/contracts/Crowdsale.sol'
135
])
136
137
# Access compiled contracts
138
for contract_name, contract_data in compiled.items():
139
print(f"Contract: {contract_name}")
140
print(f"ABI: {contract_data['abi']}")
141
print(f"Bytecode length: {len(contract_data['code'])}")
142
```
143
144
### Selective Output Values
145
146
```python
147
from solc import compile_source
148
149
# Only compile ABI and bytecode (faster)
150
compiled = compile_source(
151
source_code,
152
output_values=("abi", "bin", "bin-runtime")
153
)
154
155
# Only these keys will be present in the output
156
contract = compiled['MyContract']
157
abi = contract['abi']
158
creation_code = contract['code']
159
runtime_code = contract['code_runtime']
160
# contract['ast'] would not be available
161
```
162
163
### Compilation with Import Remappings
164
165
```python
166
from solc import compile_files
167
168
# Compile with import remappings for cleaner imports
169
compiled = compile_files(
170
['/path/to/my/Contract.sol'],
171
import_remappings=[
172
"openzeppelin-solidity=/path/to/node_modules/openzeppelin-solidity",
173
"my-lib=/path/to/my/libraries"
174
]
175
)
176
```
177
178
### Optimized Compilation
179
180
```python
181
from solc import compile_source
182
183
# Compile with optimization enabled
184
compiled = compile_source(
185
source_code,
186
optimize=True,
187
optimize_runs=200
188
)
189
190
# The resulting bytecode will be optimized
191
optimized_contract = compiled['MyContract']
192
optimized_bytecode = optimized_contract['code']
193
```
194
195
### Multiple Contracts in One Source
196
197
```python
198
from solc import compile_source
199
200
# Source with multiple contracts
201
multi_contract_source = '''
202
pragma solidity ^0.4.24;
203
204
contract Math {
205
function add(uint a, uint b) public pure returns (uint) {
206
return a + b;
207
}
208
}
209
210
contract Calculator {
211
Math private math;
212
213
constructor(address mathAddress) public {
214
math = Math(mathAddress);
215
}
216
217
function calculate(uint x, uint y) public view returns (uint) {
218
return math.add(x, y);
219
}
220
}
221
'''
222
223
compiled = compile_source(multi_contract_source)
224
225
# Both contracts are available
226
math_contract = compiled['Math']
227
calculator_contract = compiled['Calculator']
228
229
print(f"Math ABI: {math_contract['abi']}")
230
print(f"Calculator ABI: {calculator_contract['abi']}")
231
```
232
233
### Error Handling with Legacy Compilation
234
235
```python
236
from solc import compile_source, SolcError, ContractsNotFound
237
238
try:
239
# This will fail due to syntax error
240
broken_source = '''
241
pragma solidity ^0.4.24;
242
contract Broken {
243
uint256 value = ; // Syntax error
244
}
245
'''
246
247
compiled = compile_source(broken_source)
248
249
except SolcError as e:
250
print(f"Compilation error: {e}")
251
print(f"Return code: {e.return_code}")
252
print(f"Stderr: {e.stderr_data}")
253
254
except ContractsNotFound as e:
255
print("No contracts found in source code")
256
```
257
258
### Allow Empty Compilation
259
260
```python
261
from solc import compile_source
262
263
# Source with no contracts (only imports/libraries)
264
empty_source = '''
265
pragma solidity ^0.4.24;
266
267
// Just a comment, no contracts
268
'''
269
270
try:
271
# This would normally raise ContractsNotFound
272
compiled = compile_source(empty_source, allow_empty=True)
273
print("Compilation successful, but no contracts found")
274
print(f"Result: {compiled}") # Will be an empty dict
275
276
except ContractsNotFound:
277
print("This won't be reached because allow_empty=True")
278
```
279
280
## Output Format
281
282
The legacy combined JSON format returns a dictionary where:
283
284
- **Keys**: Contract names (e.g., 'MyContract')
285
- **Values**: Contract compilation data dictionaries
286
287
Each contract data dictionary contains:
288
289
```python
290
{
291
'abi': [
292
{
293
'type': 'function',
294
'name': 'myFunction',
295
'inputs': [...],
296
'outputs': [...],
297
'stateMutability': 'view'
298
},
299
# ... more ABI entries
300
],
301
'code': '0x608060405234801561001057600080fd5b50...', # Creation bytecode
302
'code_runtime': '0x608060405260043610610041576000357c01...', # Runtime bytecode
303
'meta': {
304
'compilerVersion': '0.4.24+commit.e67f0147.Linux.g++',
305
'language': 'Solidity',
306
'languageVersion': '0'
307
},
308
'ast': {...}, # Abstract Syntax Tree (if requested)
309
'asm': '...', # Assembly code (if requested)
310
'devdoc': {...}, # Developer documentation (if requested)
311
'userdoc': {...} # User documentation (if requested)
312
}
313
```
314
315
## Comparison with Standard JSON
316
317
| Feature | Legacy Combined JSON | Standard JSON |
318
|---------|---------------------|---------------|
319
| Input Format | String/Files + options | Structured JSON object |
320
| Output Format | Flat contract dictionary | Nested structure by file |
321
| Error Handling | Exception-based | Errors in output object |
322
| Flexibility | Limited output control | Full compilation control |
323
| Recommended Use | Legacy compatibility | New projects |