soroban-spec-rust 27.0.4

Soroban contract spec utilities for generating Rust.
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
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
mod syn_ext;
pub mod r#trait;
pub mod types;

use std::borrow::Cow;
use std::{fs, io};

use proc_macro2::TokenStream;
use quote::quote;
use sha2::{Digest, Sha256};
use stellar_xdr::{ScSpecEntry, ScSpecTypeDef, ScSpecTypeUdt, ScSpecUdtUnionCaseV0};
use syn::Error;

use soroban_spec::read::{from_wasm, FromWasmError};

use types::{
    generate_enum_with_options, generate_error_enum_with_options, generate_event_with_options,
    generate_struct_with_options, generate_union_with_options,
};
pub use types::{GenerateError, GenerateOptions};

// IMPORTANT: The "docs" fields of spec entries are not output in Rust token
// streams as rustdocs, because rustdocs can contain Rust code, and that code
// will be executed. Generated code may be generated from untrusted Wasm
// containing untrusted spec docs.

#[derive(thiserror::Error, Debug)]
pub enum GenerateFromFileError {
    #[error("reading file: {0}")]
    Io(io::Error),
    #[error("sha256 does not match, expected: {expected}")]
    VerifySha256 { expected: String },
    #[error("parsing contract spec: {0}")]
    Parse(stellar_xdr::Error),
    #[error("getting contract spec: {0}")]
    GetSpec(FromWasmError),
    #[error("generating code: {0}")]
    Generate(GenerateError),
}

pub fn generate_from_file(
    file: &str,
    verify_sha256: Option<&str>,
) -> Result<TokenStream, GenerateFromFileError> {
    // Read file.
    let wasm = fs::read(file).map_err(GenerateFromFileError::Io)?;

    // Generate code.
    let code = generate_from_wasm(&wasm, file, verify_sha256)?;
    Ok(code)
}

pub fn generate_from_wasm(
    wasm: &[u8],
    file: &str,
    verify_sha256: Option<&str>,
) -> Result<TokenStream, GenerateFromFileError> {
    generate_from_wasm_with_options(wasm, file, verify_sha256, &GenerateOptions::default())
}

pub fn generate_from_wasm_with_options(
    wasm: &[u8],
    file: &str,
    verify_sha256: Option<&str>,
    opts: &GenerateOptions,
) -> Result<TokenStream, GenerateFromFileError> {
    let sha256 = Sha256::digest(wasm);
    let sha256 = format!("{:x}", sha256);
    if let Some(verify_sha256) = verify_sha256 {
        if verify_sha256 != sha256 {
            return Err(GenerateFromFileError::VerifySha256 { expected: sha256 });
        }
    }

    let spec = from_wasm(wasm).map_err(GenerateFromFileError::GetSpec)?;
    let code = generate_with_options(&spec, file, &sha256, opts)
        .map_err(GenerateFromFileError::Generate)?;
    Ok(code)
}

pub fn generate(
    specs: &[ScSpecEntry],
    file: &str,
    sha256: &str,
) -> Result<TokenStream, GenerateError> {
    generate_with_options(specs, file, sha256, &GenerateOptions::default())
}

pub fn generate_with_options(
    specs: &[ScSpecEntry],
    file: &str,
    sha256: &str,
    opts: &GenerateOptions,
) -> Result<TokenStream, GenerateError> {
    let generated = generate_without_file_with_options(specs, opts)?;
    Ok(quote! {
        pub const WASM: &[u8] = soroban_sdk::contractfile!(file = #file, sha256 = #sha256);
        #generated
    })
}

pub fn generate_without_file(specs: &[ScSpecEntry]) -> Result<TokenStream, GenerateError> {
    generate_without_file_with_options(specs, &GenerateOptions::default())
}

pub fn generate_without_file_with_options(
    specs: &[ScSpecEntry],
    opts: &GenerateOptions,
) -> Result<TokenStream, GenerateError> {
    let specs = apply_error_udt_override(specs);
    let specs: &[ScSpecEntry] = &specs;

    let mut spec_fns = Vec::new();
    let mut spec_structs = Vec::new();
    let mut spec_unions = Vec::new();
    let mut spec_enums = Vec::new();
    let mut spec_error_enums = Vec::new();
    let mut spec_events = Vec::new();
    for s in specs {
        match s {
            ScSpecEntry::FunctionV0(f) => spec_fns.push(f),
            ScSpecEntry::UdtStructV0(s) => spec_structs.push(s),
            ScSpecEntry::UdtUnionV0(u) => spec_unions.push(u),
            ScSpecEntry::UdtEnumV0(e) => spec_enums.push(e),
            ScSpecEntry::UdtErrorEnumV0(e) => spec_error_enums.push(e),
            ScSpecEntry::EventV0(e) => spec_events.push(e),
        }
    }

    let trait_name = "Contract";

    let trait_ = r#trait::generate_trait(trait_name, &spec_fns)?;
    let structs = spec_structs
        .iter()
        .map(|s| generate_struct_with_options(s, opts))
        .collect::<Result<Vec<_>, _>>()?;
    let unions = spec_unions
        .iter()
        .map(|s| generate_union_with_options(s, opts))
        .collect::<Result<Vec<_>, _>>()?;
    let enums = spec_enums
        .iter()
        .map(|s| generate_enum_with_options(s, opts))
        .collect::<Result<Vec<_>, _>>()?;
    let error_enums = spec_error_enums
        .iter()
        .map(|s| generate_error_enum_with_options(s, opts))
        .collect::<Result<Vec<_>, _>>()?;
    let events = spec_events
        .iter()
        .map(|s| generate_event_with_options(s, opts))
        .collect::<Result<Vec<_>, _>>()?;

    Ok(quote! {
        #[soroban_sdk::contractargs(name = "Args")]
        #[soroban_sdk::contractclient(name = "Client")]
        #trait_

        #(#structs)*
        #(#unions)*
        #(#enums)*
        #(#error_enums)*
        #(#events)*
    })
}

/// The `#[contractimpl]` macro emits any type named `Error` in a contract's
/// function signatures as the built-in `ScSpecTypeDef::Error` in the spec,
/// regardless of whether the contract defined its own error enum named `Error`
/// or used `soroban_sdk::Error` directly. To let clients of contracts that
/// define their own `Error` enum see the user-defined type instead of
/// `soroban_sdk::Error`, this pass rewrites every `ScSpecTypeDef::Error`
/// reference in the spec to `Udt { name: "Error" }` whenever the spec also
/// contains a `UdtErrorEnumV0` named `Error`.
///
/// This keeps the on-the-wire spec format unchanged (so already-deployed
/// contracts benefit without redeployment) and shifts the resolution to the
/// client generator.
///
/// Returns a borrowed slice when no rewrite is needed, otherwise a
/// freshly-owned `Vec` with the rewrite applied.
fn apply_error_udt_override(specs: &[ScSpecEntry]) -> Cow<'_, [ScSpecEntry]> {
    let has_error_udt = specs.iter().any(|e| {
        matches!(
            e,
            ScSpecEntry::UdtErrorEnumV0(err) if err.name.to_utf8_string_lossy() == "Error"
        )
    });
    if has_error_udt {
        let mut v = specs.to_vec();
        rewrite_error_to_udt(&mut v);
        Cow::Owned(v)
    } else {
        Cow::Borrowed(specs)
    }
}

/// Rewrites every `ScSpecTypeDef::Error` reference in the given entries to
/// `ScSpecTypeDef::Udt { name: "Error" }`. Called only when the spec contains
/// a user-defined error enum named `Error`, so the UDT reference resolves to
/// that enum during code generation.
fn rewrite_error_to_udt(entries: &mut [ScSpecEntry]) {
    fn rewrite_ty(t: &mut ScSpecTypeDef) {
        match t {
            ScSpecTypeDef::Error => {
                *t = ScSpecTypeDef::Udt(ScSpecTypeUdt {
                    name: "Error".try_into().unwrap(),
                });
            }
            ScSpecTypeDef::Option(o) => rewrite_ty(&mut o.value_type),
            ScSpecTypeDef::Result(r) => {
                rewrite_ty(&mut r.ok_type);
                rewrite_ty(&mut r.error_type);
            }
            ScSpecTypeDef::Vec(v) => rewrite_ty(&mut v.element_type),
            ScSpecTypeDef::Map(m) => {
                rewrite_ty(&mut m.key_type);
                rewrite_ty(&mut m.value_type);
            }
            ScSpecTypeDef::Tuple(tu) => {
                for vt in tu.value_types.iter_mut() {
                    rewrite_ty(vt);
                }
            }
            _ => {}
        }
    }
    for entry in entries.iter_mut() {
        match entry {
            ScSpecEntry::FunctionV0(f) => {
                for input in f.inputs.iter_mut() {
                    rewrite_ty(&mut input.type_);
                }
                for output in f.outputs.iter_mut() {
                    rewrite_ty(output);
                }
            }
            ScSpecEntry::UdtStructV0(s) => {
                for field in s.fields.iter_mut() {
                    rewrite_ty(&mut field.type_);
                }
            }
            ScSpecEntry::UdtUnionV0(u) => {
                for case in u.cases.iter_mut() {
                    if let ScSpecUdtUnionCaseV0::TupleV0(t) = case {
                        for ty in t.type_.iter_mut() {
                            rewrite_ty(ty);
                        }
                    }
                }
            }
            ScSpecEntry::UdtEnumV0(_) | ScSpecEntry::UdtErrorEnumV0(_) => {}
            ScSpecEntry::EventV0(e) => {
                for p in e.params.iter_mut() {
                    rewrite_ty(&mut p.type_);
                }
            }
        }
    }
}

/// Implemented by types that can be converted into pretty formatted Strings of
/// Rust code.
pub trait ToFormattedString {
    /// Converts the value to a String that is pretty formatted. If there is any
    /// error parsing the token stream the raw String version of the code is
    /// returned instead.
    fn to_formatted_string(&self) -> Result<String, Error>;
}

impl ToFormattedString for TokenStream {
    fn to_formatted_string(&self) -> Result<String, Error> {
        let file = syn::parse2(self.clone())?;
        Ok(prettyplease::unparse(&file))
    }
}

#[cfg(test)]
mod test {
    use pretty_assertions::assert_eq;

    use super::{generate, ToFormattedString};
    use soroban_spec::read::from_wasm;

    const EXAMPLE_WASM: &[u8] = include_bytes!("../../target/wasm32v1-none/release/test_udt.wasm");

    #[test]
    fn example() {
        let entries = from_wasm(EXAMPLE_WASM).unwrap();
        let rust = generate(&entries, "<file>", "<sha256>")
            .unwrap()
            .to_formatted_string()
            .unwrap();
        assert_eq!(
            rust,
            r#"pub const WASM: &[u8] = soroban_sdk::contractfile!(file = "<file>", sha256 = "<sha256>");
#[soroban_sdk::contractargs(name = "Args")]
#[soroban_sdk::contractclient(name = "Client")]
pub trait Contract {
    fn add(env: soroban_sdk::Env, a: UdtEnum, b: UdtEnum) -> i64;
    fn recursive(env: soroban_sdk::Env, a: UdtRecursive) -> Option<UdtRecursive>;
    fn recursive_enum(
        env: soroban_sdk::Env,
        a: RecursiveEnum,
        key: u32,
    ) -> Result<Option<RecursiveEnum>, soroban_sdk::Error>;
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct UdtTuple(pub i64, pub soroban_sdk::Vec<i64>);
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct UdtStruct {
    pub a: i64,
    pub b: i64,
    pub c: soroban_sdk::Vec<i64>,
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct UdtRecursive {
    pub a: soroban_sdk::Symbol,
    pub b: soroban_sdk::Vec<UdtRecursive>,
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct RecursiveToEnum {
    pub a: soroban_sdk::Symbol,
    pub b: soroban_sdk::Map<u32, RecursiveEnum>,
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct ContractContext {
    pub args: soroban_sdk::Vec<soroban_sdk::Val>,
    pub contract: soroban_sdk::Address,
    pub fn_name: soroban_sdk::Symbol,
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct SubContractInvocation {
    pub context: ContractContext,
    pub sub_invocations: soroban_sdk::Vec<InvokerContractAuthEntry>,
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct CreateContractHostFnContext {
    pub executable: ContractExecutable,
    pub salt: soroban_sdk::BytesN<32>,
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct CreateContractWithConstructorHostFnContext {
    pub constructor_args: soroban_sdk::Vec<soroban_sdk::Val>,
    pub executable: ContractExecutable,
    pub salt: soroban_sdk::BytesN<32>,
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum UdtEnum {
    UdtA,
    UdtB(UdtStruct),
    UdtC(UdtEnum2),
    UdtD(UdtTuple),
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum RecursiveEnum {
    NotRecursive,
    Recursive(RecursiveToEnum),
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum Context {
    Contract(ContractContext),
    CreateContractHostFn(CreateContractHostFnContext),
    CreateContractWithCtorHostFn(CreateContractWithConstructorHostFnContext),
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum ContractExecutable {
    Wasm(soroban_sdk::BytesN<32>),
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum InvokerContractAuthEntry {
    Contract(SubContractInvocation),
    CreateContractHostFn(CreateContractHostFnContext),
    CreateContractWithCtorHostFn(CreateContractWithConstructorHostFnContext),
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum Executable {
    Wasm(soroban_sdk::BytesN<32>),
    StellarAsset,
    Account,
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum UdtEnum2 {
    A = 10,
    B = 15,
}
"#,
        );
    }

    const ADD_U64_WASM: &[u8] =
        include_bytes!("../../target/wasm32v1-none/release/test_add_u64.wasm");

    /// Test that Result types with user-defined error types are generated correctly.
    /// This specifically tests that:
    /// - An error enum named `Error` generates `Result<u64, Error>` (not `Result<u64, soroban_sdk::Error>`)
    /// - An error enum named `MyError` generates `Result<u64, MyError>`
    #[test]
    fn test_add_u64_result_types() {
        let entries = from_wasm(ADD_U64_WASM).unwrap();
        let rust = generate(&entries, "<file>", "<sha256>")
            .unwrap()
            .to_formatted_string()
            .unwrap();
        assert_eq!(
            rust,
            r#"pub const WASM: &[u8] = soroban_sdk::contractfile!(file = "<file>", sha256 = "<sha256>");
#[soroban_sdk::contractargs(name = "Args")]
#[soroban_sdk::contractclient(name = "Client")]
pub trait Contract {
    fn add(env: soroban_sdk::Env, a: u64, b: u64) -> u64;
    fn safe_add(env: soroban_sdk::Env, a: u64, b: u64) -> Result<u64, Error>;
    fn safe_add_two(env: soroban_sdk::Env, a: u64, b: u64) -> Result<u64, MyError>;
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct ContractContext {
    pub args: soroban_sdk::Vec<soroban_sdk::Val>,
    pub contract: soroban_sdk::Address,
    pub fn_name: soroban_sdk::Symbol,
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct SubContractInvocation {
    pub context: ContractContext,
    pub sub_invocations: soroban_sdk::Vec<InvokerContractAuthEntry>,
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct CreateContractHostFnContext {
    pub executable: ContractExecutable,
    pub salt: soroban_sdk::BytesN<32>,
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct CreateContractWithConstructorHostFnContext {
    pub constructor_args: soroban_sdk::Vec<soroban_sdk::Val>,
    pub executable: ContractExecutable,
    pub salt: soroban_sdk::BytesN<32>,
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum Context {
    Contract(ContractContext),
    CreateContractHostFn(CreateContractHostFnContext),
    CreateContractWithCtorHostFn(CreateContractWithConstructorHostFnContext),
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum ContractExecutable {
    Wasm(soroban_sdk::BytesN<32>),
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum InvokerContractAuthEntry {
    Contract(SubContractInvocation),
    CreateContractHostFn(CreateContractHostFnContext),
    CreateContractWithCtorHostFn(CreateContractWithConstructorHostFnContext),
}
#[soroban_sdk::contracttype(export = false)]
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum Executable {
    Wasm(soroban_sdk::BytesN<32>),
    StellarAsset,
    Account,
}
#[soroban_sdk::contracterror(export = false)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum Error {
    Overflow = 1,
}
#[soroban_sdk::contracterror(export = false)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum MyError {
    Overflow = 1,
}
"#,
        );
    }

    /// Test that shows the raw spec entries from the wasm.
    /// Verifies that the on-the-wire spec format is unchanged: a contract
    /// error enum named `Error` is still emitted as the built-in
    /// `ScSpecTypeDef::Error` in function signatures (the user-defined-vs-SDK
    /// disambiguation happens at client generation time, not here). A
    /// differently-named error enum (`MyError`) is emitted as a UDT reference.
    #[test]
    fn test_add_u64_spec_entries() {
        use super::ScSpecEntry;
        use stellar_xdr::ScSpecTypeDef;

        let entries = from_wasm(ADD_U64_WASM).unwrap();

        // Find the safe_add function spec
        let safe_add_fn = entries
            .iter()
            .find_map(|e| match e {
                ScSpecEntry::FunctionV0(f) if f.name.to_utf8_string().unwrap() == "safe_add" => {
                    Some(f)
                }
                _ => None,
            })
            .expect("safe_add function not found");

        let output = safe_add_fn.outputs.to_option().expect("should have output");
        let ScSpecTypeDef::Result(r) = output else {
            panic!("output should be a Result type");
        };
        assert!(
            matches!(r.ok_type.as_ref(), ScSpecTypeDef::U64),
            "ok_type should be U64"
        );
        assert!(
            matches!(r.error_type.as_ref(), ScSpecTypeDef::Error),
            "error_type should be the built-in Error in the wasm spec, got {:?}",
            r.error_type
        );

        // Find the safe_add_two function spec
        let safe_add_two_fn = entries
            .iter()
            .find_map(|e| match e {
                ScSpecEntry::FunctionV0(f)
                    if f.name.to_utf8_string().unwrap() == "safe_add_two" =>
                {
                    Some(f)
                }
                _ => None,
            })
            .expect("safe_add_two function not found");

        let output = safe_add_two_fn
            .outputs
            .to_option()
            .expect("should have output");
        let ScSpecTypeDef::Result(r) = output else {
            panic!("output should be a Result type");
        };
        assert!(
            matches!(r.ok_type.as_ref(), ScSpecTypeDef::U64),
            "ok_type should be U64"
        );
        let ScSpecTypeDef::Udt(u) = r.error_type.as_ref() else {
            panic!(
                "error_type should be a UDT for MyError, got {:?}",
                r.error_type
            );
        };
        assert_eq!(
            u.name.to_utf8_string().unwrap(),
            "MyError",
            "error_type should be MyError UDT"
        );
    }

    /// When the spec references `ScSpecTypeDef::Error` and contains no error
    /// enum named `Error`, the generator must leave it as `soroban_sdk::Error`.
    /// This covers contracts that use `soroban_sdk::Error` directly as their
    /// Result error type, including every contract compiled before the
    /// error-enum override was introduced.
    #[test]
    fn test_missing_error_udt_falls_back_to_sdk_error() {
        use super::ScSpecEntry;
        use stellar_xdr::{ScSpecFunctionV0, ScSpecTypeDef, ScSpecTypeResult};

        let func = ScSpecFunctionV0 {
            doc: "".try_into().unwrap(),
            name: "safe_add".try_into().unwrap(),
            inputs: [].try_into().unwrap(),
            outputs: [ScSpecTypeDef::Result(Box::new(ScSpecTypeResult {
                ok_type: Box::new(ScSpecTypeDef::U64),
                error_type: Box::new(ScSpecTypeDef::Error),
            }))]
            .try_into()
            .unwrap(),
        };
        let entries = [ScSpecEntry::FunctionV0(func)];
        let rust = generate(&entries, "<file>", "<sha256>")
            .unwrap()
            .to_formatted_string()
            .unwrap();
        assert_eq!(
            rust,
            r#"pub const WASM: &[u8] = soroban_sdk::contractfile!(file = "<file>", sha256 = "<sha256>");
#[soroban_sdk::contractargs(name = "Args")]
#[soroban_sdk::contractclient(name = "Client")]
pub trait Contract {
    fn safe_add(env: soroban_sdk::Env) -> Result<u64, soroban_sdk::Error>;
}
"#,
        );
    }

    /// When the spec contains a user-defined `Error` error enum, every
    /// `ScSpecTypeDef::Error` reference in the spec must be rewritten to
    /// reference that UDT instead of `soroban_sdk::Error`.
    #[test]
    fn test_error_udt_overrides_sdk_error() {
        use super::ScSpecEntry;
        use stellar_xdr::{
            ScSpecFunctionV0, ScSpecTypeDef, ScSpecTypeResult, ScSpecUdtErrorEnumCaseV0,
            ScSpecUdtErrorEnumV0,
        };

        let func = ScSpecFunctionV0 {
            doc: "".try_into().unwrap(),
            name: "safe_add".try_into().unwrap(),
            inputs: [].try_into().unwrap(),
            outputs: [ScSpecTypeDef::Result(Box::new(ScSpecTypeResult {
                ok_type: Box::new(ScSpecTypeDef::U64),
                error_type: Box::new(ScSpecTypeDef::Error),
            }))]
            .try_into()
            .unwrap(),
        };
        let error_enum = ScSpecUdtErrorEnumV0 {
            doc: "".try_into().unwrap(),
            lib: "".try_into().unwrap(),
            name: "Error".try_into().unwrap(),
            cases: [ScSpecUdtErrorEnumCaseV0 {
                doc: "".try_into().unwrap(),
                name: "Overflow".try_into().unwrap(),
                value: 1,
            }]
            .try_into()
            .unwrap(),
        };
        let entries = [
            ScSpecEntry::FunctionV0(func),
            ScSpecEntry::UdtErrorEnumV0(error_enum),
        ];
        let rust = generate(&entries, "<file>", "<sha256>")
            .unwrap()
            .to_formatted_string()
            .unwrap();
        assert_eq!(
            rust,
            r#"pub const WASM: &[u8] = soroban_sdk::contractfile!(file = "<file>", sha256 = "<sha256>");
#[soroban_sdk::contractargs(name = "Args")]
#[soroban_sdk::contractclient(name = "Client")]
pub trait Contract {
    fn safe_add(env: soroban_sdk::Env) -> Result<u64, Error>;
}
#[soroban_sdk::contracterror(export = false)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum Error {
    Overflow = 1,
}
"#,
        );
    }

    /// When the `Error` override applies, nested `ScSpecTypeDef::Error`
    /// references must be rewritten too.
    #[test]
    fn test_error_udt_override_rewrites_nested_vec() {
        use super::ScSpecEntry;
        use stellar_xdr::{
            ScSpecFunctionV0, ScSpecTypeDef, ScSpecTypeVec, ScSpecUdtErrorEnumCaseV0,
            ScSpecUdtErrorEnumV0,
        };

        let func = ScSpecFunctionV0 {
            doc: "".try_into().unwrap(),
            name: "errors".try_into().unwrap(),
            inputs: [].try_into().unwrap(),
            outputs: [ScSpecTypeDef::Vec(Box::new(ScSpecTypeVec {
                element_type: Box::new(ScSpecTypeDef::Error),
            }))]
            .try_into()
            .unwrap(),
        };
        let error_enum = ScSpecUdtErrorEnumV0 {
            doc: "".try_into().unwrap(),
            lib: "".try_into().unwrap(),
            name: "Error".try_into().unwrap(),
            cases: [ScSpecUdtErrorEnumCaseV0 {
                doc: "".try_into().unwrap(),
                name: "Overflow".try_into().unwrap(),
                value: 1,
            }]
            .try_into()
            .unwrap(),
        };
        let entries = [
            ScSpecEntry::FunctionV0(func),
            ScSpecEntry::UdtErrorEnumV0(error_enum),
        ];
        let rust = generate(&entries, "<file>", "<sha256>")
            .unwrap()
            .to_formatted_string()
            .unwrap();
        assert_eq!(
            rust,
            r#"pub const WASM: &[u8] = soroban_sdk::contractfile!(file = "<file>", sha256 = "<sha256>");
#[soroban_sdk::contractargs(name = "Args")]
#[soroban_sdk::contractclient(name = "Client")]
pub trait Contract {
    fn errors(env: soroban_sdk::Env) -> soroban_sdk::Vec<Error>;
}
#[soroban_sdk::contracterror(export = false)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum Error {
    Overflow = 1,
}
"#,
        );
    }
}