-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_usage.gleam
More file actions
469 lines (403 loc) · 11.6 KB
/
Copy pathbasic_usage.gleam
File metadata and controls
469 lines (403 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
// Basic usage examples for Gleam Solc library
// This module demonstrates common use cases and patterns
import gleam/dict
import gleam/int
import gleam/io
import gleam/javascript/promise
import gleam/list
import gleam/option.{None, Some}
import gleam/string
import solc
import solc/types
// Example 1: Compile a simple contract
pub fn simple_contract_example() {
let source =
"
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 private value;
event ValueChanged(uint256 newValue);
function setValue(uint256 _value) public {
value = _value;
emit ValueChanged(_value);
}
function getValue() public view returns (uint256) {
return value;
}
}
"
// This would be the actual usage pattern:
// use load_result <- promise.try_await(solc.load_solc("./cache/solc-v0.8.19.js", Some("0.8.19")))
// case load_result {
// Ok(solc_wrapper) -> {
// case solc.compile_simple(solc_wrapper, "SimpleStorage", source) {
// Ok(output) -> handle_compilation_success(output)
// Error(err) -> handle_compilation_error(err)
// }
// }
// Error(err) -> handle_load_error(err)
// }
// For this example, we'll demonstrate the expected structure
io.println("Simple contract compilation example")
io.println("Source length: " <> int.to_string(string.length(source)))
io.println("Expected contract: SimpleStorage")
}
// Example 2: Multiple inheritance with interfaces and abstract contracts
pub fn inheritance_example() {
let interface_source =
"
pragma solidity ^0.8.0;
interface IOwnable {
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
}
"
let abstract_source =
"
pragma solidity ^0.8.0;
import \"./IOwnable.sol\";
abstract contract Ownable is IOwnable {
address private _owner;
constructor() {
_owner = msg.sender;
}
function owner() public view override returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == msg.sender, \"Ownable: caller is not the owner\");
_;
}
function transferOwnership(address newOwner) public virtual override onlyOwner {
require(newOwner != address(0), \"Ownable: new owner is the zero address\");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
"
let implementation_source =
"
pragma solidity ^0.8.0;
import \"./Ownable.sol\";
contract MyContract is Ownable {
string public name;
uint256 public value;
constructor(string memory _name) {
name = _name;
value = 0;
}
function setValue(uint256 _value) external onlyOwner {
value = _value;
}
function emergencyStop() external onlyOwner {
// Emergency functionality
value = 0;
}
}
"
let sources =
dict.from_list([
#("IOwnable.sol", interface_source),
#("Ownable.sol", abstract_source),
#("MyContract.sol", implementation_source),
])
// Example compilation workflow
io.println("Multiple inheritance example")
io.println("Files to compile: " <> int.to_string(dict.size(sources)))
dict.each(sources, fn(filename, source) {
io.println(
"- "
<> filename
<> " ("
<> int.to_string(string.length(source))
<> " chars)",
)
})
}
// Example 3: Custom compilation settings
pub fn custom_settings_example() {
let source =
"
pragma solidity ^0.8.0;
contract OptimizedContract {
mapping(address => uint256) private balances;
uint256 private totalSupply;
function transfer(address to, uint256 amount) external returns (bool) {
require(balances[msg.sender] >= amount, \"Insufficient balance\");
balances[msg.sender] -= amount;
balances[to] += amount;
return true;
}
function balanceOf(address account) external view returns (uint256) {
return balances[account];
}
}
"
// Create custom output selection for detailed output
let output_selection =
types.OutputSelection(
selections: dict.from_list([
#(
"*",
dict.from_list([
#("*", [
"abi",
"evm.bytecode",
"evm.deployedBytecode",
"evm.gasEstimates",
"evm.methodIdentifiers",
"metadata",
"storageLayout",
"devdoc",
"userdoc",
]),
]),
),
]),
)
// Configure optimizer for high-frequency functions
let optimizer =
types.OptimizerSettings(
enabled: True,
runs: 1_000_000,
// Optimize for many function calls
)
let settings =
types.CompilationSettings(
output_selection: output_selection,
optimizer: Some(optimizer),
evm_version: Some("london"),
// Use London hard fork features
libraries: None,
remappings: None,
)
let input =
types.CompilationInput(
language: "Solidity",
sources: dict.from_list([
#("OptimizedContract.sol", types.Source(content: source)),
]),
settings: settings,
)
io.println("Custom compilation settings example")
io.println("Optimizer runs: " <> int.to_string(optimizer.runs))
io.println("EVM version: london")
io.println(
"Output selections: "
<> int.to_string(
list.length([
"abi",
"evm.bytecode",
"evm.deployedBytecode",
"evm.gasEstimates",
"evm.methodIdentifiers",
"metadata",
"storageLayout",
"devdoc",
"userdoc",
]),
),
)
}
// Example 4: Error handling patterns
pub fn error_handling_example() {
let invalid_source =
"
contract InvalidSyntax {
uint256 public value
// Missing semicolon above
function setValue(uint256 _value) public {
value = _value
// Missing semicolon above
}
}
"
// Demonstrate different error types and handling
io.println("Error handling examples:")
// 1. Compilation errors
let compilation_error =
types.CompilationError(
severity: "error",
message: "Expected ';' but got '}'",
formatted_message: Some(
"ParserError: Expected ';' but got '}' at InvalidSyntax.sol:3:21",
),
source_location: Some(types.SourceLocation(
file: "InvalidSyntax.sol",
start: 65,
end: 66,
)),
error_code: Some("2314"),
)
io.println("1. Syntax Error:")
io.println(" " <> compilation_error.message)
case compilation_error.formatted_message {
Some(formatted) -> io.println(" " <> formatted)
None -> Nil
}
// 2. Version errors
let version_error =
types.VersionNotFound("Version 0.8.999 not found in releases")
io.println("2. Version Error: " <> get_error_message(version_error))
// 3. Download errors
let download_error =
types.DownloadError("Failed to download: Network timeout")
io.println("3. Download Error: " <> get_error_message(download_error))
// 4. FFI errors
let ffi_error = types.FFIError("Invalid solc module: Module not found")
io.println("4. FFI Error: " <> get_error_message(ffi_error))
}
// Helper function to extract error messages
fn get_error_message(error: types.SolcError) -> String {
case error {
types.DownloadError(msg) -> msg
types.CompilationFailed(msg) -> msg
types.FFIError(msg) -> msg
types.InvalidInput(msg) -> msg
types.VersionNotFound(msg) -> msg
}
}
// Example 5: Working with compilation output
pub fn output_analysis_example() {
// Mock a successful compilation output
let mock_abi = [
types.ABIFunction(
name: "setValue",
inputs: [
types.ABIParameter(
name: "_value",
type_: "uint256",
internal_type: "uint256",
indexed: None,
),
],
outputs: [],
state_mutability: "nonpayable",
),
types.ABIFunction(
name: "getValue",
inputs: [],
outputs: [
types.ABIParameter(
name: "",
type_: "uint256",
internal_type: "uint256",
indexed: None,
),
],
state_mutability: "view",
),
]
let mock_bytecode =
types.Bytecode(
object: "0x608060405234801561001057600080fd5b5060043610610048760003560e01c806320965255146100...",
link_references: dict.new(),
source_map: Some(
"1:2:0:-:0;;;8:1:-1;5:2;;;30:1;27;20:12;5:2;1:2:0;;;;;;;",
),
)
let mock_gas =
types.GasEstimates(
creation: Some(types.CreationGas(
code_deposit_cost: "200000",
execution_cost: "41908",
total_cost: "241908",
)),
external: dict.from_list([
#("getValue()", "2373"),
#("setValue(uint256)", "24755"),
]),
)
let mock_evm =
types.EVM(
bytecode: mock_bytecode,
deployed_bytecode: Some(mock_bytecode),
gas_estimates: Some(mock_gas),
method_identifiers: dict.from_list([
#("getValue()", "20965255"),
#("setValue(uint256)", "55241077"),
]),
)
let mock_contract =
types.Contract(
abi: mock_abi,
evm: mock_evm,
metadata: "{\"compiler\":{\"version\":\"0.8.19\"}}",
)
// Analyze the compilation output
io.println("Compilation output analysis:")
io.println("ABI functions: " <> int.to_string(list.length(mock_contract.abi)))
io.println(
"Bytecode size: "
<> int.to_string(string.length(mock_contract.evm.bytecode.object)),
)
// Analyze gas estimates
case mock_contract.evm.gas_estimates {
Some(estimates) -> {
case estimates.creation {
Some(creation) -> {
io.println("Deployment cost: " <> creation.total_cost <> " gas")
}
None -> Nil
}
io.println("Function gas costs:")
dict.each(estimates.external, fn(method, cost) {
io.println(" " <> method <> ": " <> cost <> " gas")
})
}
None -> io.println("No gas estimates available")
}
// Analyze method identifiers
io.println("Method identifiers:")
dict.each(mock_contract.evm.method_identifiers, fn(method, id) {
io.println(" " <> method <> ": 0x" <> id)
})
}
// Example 6: Promise-based workflow
pub fn async_workflow_example() {
// This demonstrates the async pattern for real usage
// Step 1: Download and load compiler
// let download_promise = solc.load_solc("./cache/solc-v0.8.19.js", Some("0.8.19"))
// Step 2: Compile when ready
// use solc_wrapper <- promise.try_await(download_promise)
// case solc_wrapper {
// Ok(wrapper) -> {
// let source = "contract Test { uint256 public value; }"
// case solc.compile_simple(wrapper, "Test", source) {
// Ok(output) -> {
// io.println("Compilation successful!")
// promise.resolve(Ok(output))
// }
// Error(err) -> {
// io.println("Compilation failed: " <> get_error_message(err))
// promise.resolve(Error(err))
// }
// }
// }
// Error(err) -> {
// io.println("Failed to load solc: " <> get_error_message(err))
// promise.resolve(Error(err))
// }
// }
io.println("Async workflow pattern demonstrated")
io.println("Steps: download -> load -> compile -> analyze")
}
// Main function to run all examples
pub fn run_examples() {
io.println("=== Gleam Solc Usage Examples ===")
io.println("")
simple_contract_example()
io.println("")
inheritance_example()
io.println("")
custom_settings_example()
io.println("")
error_handling_example()
io.println("")
output_analysis_example()
io.println("")
async_workflow_example()
io.println("")
io.println("=== Examples Complete ===")
}