solang 0.3.4

Solang Solidity Compiler
Documentation
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
// SPDX-License-Identifier: Apache-2.0

use crate::cli::IdlCommand;
use anchor_syn::idl::types::{Idl, IdlAccountItem, IdlInstruction, IdlType, IdlTypeDefinitionTy};
use itertools::Itertools;
use serde_json::Value as JsonValue;
use solang::abi::anchor::function_discriminator;
use solang_parser::lexer::is_keyword;
use std::{ffi::OsStr, fs::File, io::Write, path::PathBuf, process::exit};

/// This subcommand generates a Solidity interface file from Anchor IDL file.
/// The IDL file is json and lists all the instructions, events, structs, enums,
/// etc. We have to avoid the numerous Solidity keywords, and retain any documentation.
pub fn idl(idl_args: &IdlCommand) {
    for file in &idl_args.input {
        idl_file(file, &idl_args.output);
    }
}

fn idl_file(file: &OsStr, output: &Option<PathBuf>) {
    let f = match File::open(file) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("{}: error: {}", file.to_string_lossy(), e);
            exit(1);
        }
    };

    let idl: Idl = match serde_json::from_reader(f) {
        Ok(idl) => idl,
        Err(e) => {
            eprintln!("{}: error: {}", file.to_string_lossy(), e);
            exit(1);
        }
    };

    let filename = format!("{}.sol", idl.name);

    let path = if let Some(base) = output {
        base.join(filename)
    } else {
        PathBuf::from(filename)
    };

    println!(
        "{}: info: creating '{}'",
        file.to_string_lossy(),
        path.display()
    );

    let f = match File::create(&path) {
        Ok(f) => f,
        Err(e) => {
            eprintln!("{}: error: {}", path.display(), e);
            exit(1);
        }
    };

    if let Err(e) = write_solidity(&idl, f) {
        eprintln!("{}: error: {}", path.display(), e);
        exit(1);
    }
}

fn write_solidity(idl: &Idl, mut f: File) -> Result<(), std::io::Error> {
    let mut ty_names = idl
        .types
        .iter()
        .map(|ty| (ty.name.to_string(), ty.name.to_string()))
        .collect::<Vec<(String, String)>>();

    if let Some(events) = &idl.events {
        events
            .iter()
            .for_each(|event| ty_names.push((event.name.to_string(), event.name.to_string())));
    }

    rename_keywords(&mut ty_names);

    for ty_def in &idl.types {
        if let IdlTypeDefinitionTy::Enum { variants } = &ty_def.ty {
            if variants.iter().any(|variant| variant.fields.is_some()) {
                eprintln!(
                    "enum {} has variants with fields, not supported in Solidity\n",
                    ty_def.name
                );
                continue;
            }
            let mut name_map = variants
                .iter()
                .map(|variant| (variant.name.to_string(), variant.name.to_string()))
                .collect::<Vec<(String, String)>>();

            rename_keywords(&mut name_map);

            docs(&mut f, 0, &ty_def.docs)?;

            let name = &ty_names.iter().find(|e| *e.0 == ty_def.name).unwrap().1;

            writeln!(f, "enum {name} {{")?;
            let mut iter = variants.iter().enumerate();
            let mut next = iter.next();
            while let Some((no, _)) = next {
                next = iter.next();

                writeln!(
                    f,
                    "\t{}{}",
                    name_map[no].1,
                    if next.is_some() { "," } else { "" }
                )?;
            }
            writeln!(f, "}}")?;
        }
    }

    for ty_def in &idl.types {
        if let IdlTypeDefinitionTy::Struct { fields } = &ty_def.ty {
            let badtys: Vec<String> = fields
                .iter()
                .filter_map(|field| idltype_to_solidity(&field.ty, &ty_names).err())
                .collect();

            if badtys.is_empty() {
                let mut name_map = fields
                    .iter()
                    .map(|field| (field.name.to_string(), field.name.to_string()))
                    .collect::<Vec<(String, String)>>();

                rename_keywords(&mut name_map);

                docs(&mut f, 0, &ty_def.docs)?;

                let name = &ty_names.iter().find(|e| *e.0 == ty_def.name).unwrap().1;

                writeln!(f, "struct {name} {{")?;

                for (no, field) in fields.iter().enumerate() {
                    docs(&mut f, 1, &field.docs)?;

                    writeln!(
                        f,
                        "\t{}\t{};",
                        idltype_to_solidity(&field.ty, &ty_names).unwrap(),
                        name_map[no].1
                    )?;
                }

                writeln!(f, "}}")?;
            } else {
                eprintln!(
                    "struct {} has fields of type {} which is not supported on Solidity",
                    ty_def.name,
                    badtys.join(", ")
                );
            }
        }
    }

    if let Some(events) = &idl.events {
        for event in events {
            let badtys: Vec<String> = event
                .fields
                .iter()
                .filter_map(|field| idltype_to_solidity(&field.ty, &ty_names).err())
                .collect();

            if badtys.is_empty() {
                let mut name_map = event
                    .fields
                    .iter()
                    .map(|field| (field.name.to_string(), field.name.to_string()))
                    .collect::<Vec<(String, String)>>();

                rename_keywords(&mut name_map);

                let name = &ty_names.iter().find(|e| *e.0 == event.name).unwrap().1;

                writeln!(f, "event {name} (")?;
                let mut iter = event.fields.iter().enumerate();
                let mut next = iter.next();
                while let Some((no, e)) = next {
                    next = iter.next();

                    writeln!(
                        f,
                        "\t{}\t{}{}{}",
                        idltype_to_solidity(&e.ty, &ty_names).unwrap(),
                        if e.index { " indexed " } else { " " },
                        name_map[no].1,
                        if next.is_some() { "," } else { "" }
                    )?;
                }
                writeln!(f, ");")?;
            } else {
                eprintln!(
                    "event {} has fields of type {} which is not supported on Solidity",
                    event.name,
                    badtys.join(", ")
                );
            }
        }
    }

    docs(&mut f, 0, &idl.docs)?;

    if let Some(program_id) = program_id(idl) {
        writeln!(f, "@program_id(\"{}\")", program_id)?;
    }
    writeln!(f, "interface {} {{", idl.name)?;

    let mut instruction_names = idl
        .instructions
        .iter()
        .map(|instr| (instr.name.to_string(), instr.name.to_string()))
        .collect::<Vec<(String, String)>>();

    rename_keywords(&mut instruction_names);

    for instr in &idl.instructions {
        instruction(&mut f, instr, &instruction_names, &ty_names)?;
    }

    writeln!(f, "}}")?;

    Ok(())
}

fn instruction(
    f: &mut File,
    instr: &IdlInstruction,
    instruction_names: &[(String, String)],
    ty_names: &[(String, String)],
) -> std::io::Result<()> {
    let mut badtys: Vec<String> = instr
        .args
        .iter()
        .filter_map(|field| idltype_to_solidity(&field.ty, ty_names).err())
        .collect();

    if let Some(ty) = &instr.returns {
        if let Err(s) = idltype_to_solidity(ty, ty_names) {
            badtys.push(s);
        }
    }

    if badtys.is_empty() {
        docs(f, 1, &instr.docs)?;

        let name = &instruction_names
            .iter()
            .find(|e| *e.0 == instr.name)
            .unwrap()
            .1;

        // The anchor discriminator is what Solidity calls a selector
        let selector = function_discriminator(&instr.name);

        write!(
            f,
            "\t@selector([{}])\n\tfunction {}(",
            selector.iter().map(|v| format!("{v:#04x}")).join(","),
            if instr.name == "new" {
                "initialize"
            } else {
                name
            }
        )?;

        let mut iter = instr.args.iter();
        let mut next = iter.next();

        while let Some(e) = next {
            next = iter.next();

            write!(
                f,
                "{} {}{}",
                idltype_to_solidity(&e.ty, ty_names).unwrap(),
                e.name,
                if next.is_some() { "," } else { "" }
            )?;
        }

        let is_view = instr.returns.is_some() && !mutable_account_exists(&instr.accounts);
        write!(f, ") {}external", if is_view { "view " } else { "" })?;

        if let Some(ty) = &instr.returns {
            writeln!(
                f,
                " returns ({});",
                idltype_to_solidity(ty, ty_names).unwrap()
            )?;
        } else {
            writeln!(f, ";")?;
        }
    } else {
        eprintln!(
            "instructions {} has arguments of type {} which is not supported on Solidity",
            instr.name,
            badtys.join(", ")
        );
    }

    Ok(())
}

fn mutable_account_exists(accounts: &[IdlAccountItem]) -> bool {
    accounts.iter().any(|item| match item {
        IdlAccountItem::IdlAccount(acc) => acc.is_mut,
        IdlAccountItem::IdlAccounts(accs) => mutable_account_exists(&accs.accounts),
    })
}

fn docs(f: &mut File, indent: usize, docs: &Option<Vec<String>>) -> std::io::Result<()> {
    if let Some(docs) = docs {
        for doc in docs {
            for _ in 0..indent {
                write!(f, "\t")?;
            }
            writeln!(f, "/// {doc}")?;
        }
    }

    Ok(())
}

fn idltype_to_solidity(ty: &IdlType, ty_names: &[(String, String)]) -> Result<String, String> {
    match ty {
        IdlType::Bool => Ok("bool".to_string()),
        IdlType::U8 => Ok("uint8".to_string()),
        IdlType::I8 => Ok("int8".to_string()),
        IdlType::U16 => Ok("uint16".to_string()),
        IdlType::I16 => Ok("int16".to_string()),
        IdlType::U32 => Ok("uint32".to_string()),
        IdlType::I32 => Ok("int32".to_string()),
        IdlType::U64 => Ok("uint64".to_string()),
        IdlType::I64 => Ok("int64".to_string()),
        IdlType::U128 => Ok("uint128".to_string()),
        IdlType::I128 => Ok("int128".to_string()),
        IdlType::U256 => Ok("uint256".to_string()),
        IdlType::I256 => Ok("int256".to_string()),
        IdlType::F32 => Err("f32".to_string()),
        IdlType::F64 => Err("f64".to_string()),
        IdlType::Bytes => Ok("bytes".to_string()),
        IdlType::String => Ok("string".to_string()),
        IdlType::PublicKey => Ok("address".to_string()),
        IdlType::Option(ty) => Err(format!(
            "Option({})",
            match idltype_to_solidity(ty, ty_names) {
                Ok(ty) => ty,
                Err(ty) => ty,
            }
        )),
        IdlType::Defined(ty) => {
            if let Some(e) = ty_names.iter().find(|rename| rename.0 == *ty) {
                Ok(e.1.clone())
            } else {
                Ok(ty.into())
            }
        }
        IdlType::Vec(ty) => match idltype_to_solidity(ty, ty_names) {
            Ok(ty) => Ok(format!("{ty}[]")),
            Err(ty) => Err(format!("{ty}[]")),
        },
        IdlType::Array(ty, size) => match idltype_to_solidity(ty, ty_names) {
            Ok(ty) => Ok(format!("{ty}[{size}]")),
            Err(ty) => Err(format!("{ty}[{size}]")),
        },
        IdlType::Generic(..)
        | IdlType::GenericLenArray(..)
        | IdlType::DefinedWithTypeArgs { .. } => Err("generics are not supported".into()),
    }
}

fn program_id(idl: &Idl) -> Option<&String> {
    if let Some(JsonValue::Object(metadata)) = &idl.metadata {
        if let Some(JsonValue::String(address)) = metadata.get("address") {
            return Some(address);
        }
    }

    None
}

/// There are many keywords in Solidity which are not keywords in Rust, so they may
/// occur as field name, function name, etc. Rename those fields by prepending
/// underscores until unique
fn rename_keywords(name_map: &mut [(String, String)]) {
    for i in 0..name_map.len() {
        let name = &name_map[i].0;

        if is_keyword(name) {
            let mut name = name.clone();
            loop {
                name = format!("_{name}");
                if name_map.iter().all(|(_, n)| *n != name) {
                    break;
                }
            }
            name_map[i].1 = name;
        }
    }
}