sdkt-wasm 2.7.0

WASM binary metadata parser for Soroban DevKit — exports, imports, custom sections, and hashing.
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
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
//! Offline contract comparison (ABI / WASM diff).
//!
//! Compares two compiled Soroban WASM binaries by extracting their
//! `ContractSpec` (functions, events, custom types) via the existing
//! [`crate::parse_contract_spec`] parser, then classifying the deltas.
//!
//! Everything is offline: no RPC, no network. The diff operates purely on the
//! declared ABI, so it is a safe pre-upgrade check (detect breaking changes
//! before `sdkt deploy` of a new WASM).

use serde::{Deserialize, Serialize};

use crate::{
    parse_contract_spec, parse_metadata, ContractEvent, ContractFunction, ContractSpec,
    ContractType, WasmError,
};

/// The full comparison result between two contract WASM binaries.
///
/// `Eq` is not derived because `size_delta_pct` is an `Option<f64>`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct SpecDiff {
    /// Metadata of the "old" (baseline) WASM.
    pub old: WasmSummary,
    /// Metadata of the "new" (candidate) WASM.
    pub new: WasmSummary,
    /// Functions present in `new` but absent from `old`.
    pub added_functions: Vec<ContractFunction>,
    /// Functions present in `old` but absent from `new`.
    pub removed_functions: Vec<ContractFunction>,
    /// Functions present in both whose signature (inputs + outputs) changed.
    pub changed_functions: Vec<FunctionSignatureChange>,
    /// Events present in `new` but absent from `old`.
    pub added_events: Vec<String>,
    /// Events present in `old` but absent from `new`.
    pub removed_events: Vec<String>,
    /// Events present in both whose signature (prefix topics, params, data
    /// format) changed.
    pub changed_events: Vec<EventSignatureChange>,
    /// Custom types present in `new` but absent from `old`.
    pub added_types: Vec<String>,
    /// Custom types present in `old` but absent from `new`.
    pub removed_types: Vec<String>,
    /// Custom types present in both whose definition (kind or members) changed.
    pub changed_types: Vec<TypeDefinitionChange>,
    /// Signed size change: `new.size_bytes - old.size_bytes` (negative when the
    /// candidate shrank). Always present; independent of any policy flag.
    pub size_delta_bytes: i64,
    /// Percentage growth relative to the old artifact, rounded to one decimal
    /// place (e.g. `2157.6`). `null` when the old artifact is zero bytes and
    /// the new one is not — a relative change against an empty baseline is
    /// mathematically undefined, and is never coerced to 0 or infinity.
    /// Both artifacts empty ⇒ `Some(0.0)`.
    #[serde(default)]
    pub size_delta_pct: Option<f64>,
}

/// Lightweight WASM identity summary for diff context.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct WasmSummary {
    /// SHA-256 hex of the raw WASM bytes.
    pub hash: String,
    /// Size in bytes.
    pub size_bytes: usize,
}

/// A function whose signature changed between old and new.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FunctionSignatureChange {
    pub name: String,
    pub old: ContractFunction,
    pub new: ContractFunction,
}

/// An event whose signature changed while keeping its name.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct EventSignatureChange {
    pub name: String,
    pub old: ContractEvent,
    pub new: ContractEvent,
}

/// A custom type whose definition changed while keeping its name.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TypeDefinitionChange {
    pub name: String,
    pub old: ContractType,
    pub new: ContractType,
}

impl SpecDiff {
    /// True when the two WASM binaries declare an identical ABI surface
    /// (same functions, signatures, events, and custom types).
    pub fn is_identical(&self) -> bool {
        self.added_functions.is_empty()
            && self.removed_functions.is_empty()
            && self.changed_functions.is_empty()
            && self.added_events.is_empty()
            && self.removed_events.is_empty()
            && self.changed_events.is_empty()
            && self.added_types.is_empty()
            && self.removed_types.is_empty()
            && self.changed_types.is_empty()
    }

    /// Total number of breaking/non-breaking deltas (a single count used for
    /// quick pass/fail triage in CI).
    pub fn total_changes(&self) -> usize {
        self.added_functions.len()
            + self.removed_functions.len()
            + self.changed_functions.len()
            + self.added_events.len()
            + self.removed_events.len()
            + self.changed_events.len()
            + self.added_types.len()
            + self.removed_types.len()
            + self.changed_types.len()
    }
}

/// Convenience: build a [`WasmSummary`] from raw WASM bytes.
fn summarize(raw: &[u8]) -> Result<WasmSummary, WasmError> {
    let meta = parse_metadata(raw)?;
    Ok(WasmSummary {
        hash: meta.hash,
        size_bytes: meta.size_bytes,
    })
}

/// Diff two raw WASM binaries (offline).
///
/// Each side is parsed independently; if either fails to yield a
/// `ContractSpec`, the error is returned. Missing entries are treated as
/// empty lists, so a contract with no events still diffs cleanly against one
/// that declares events.
pub fn diff_wasm(old_raw: &[u8], new_raw: &[u8]) -> Result<SpecDiff, WasmError> {
    let old_spec = parse_contract_spec(old_raw)?;
    let new_spec = parse_contract_spec(new_raw)?;
    diff_specs(
        &old_spec,
        &new_spec,
        summarize(old_raw)?,
        summarize(new_raw)?,
    )
}

/// Diff two already-parsed [`ContractSpec`] values.
///
/// `old_summary` / `new_summary` carry WASM identity (hash/size) for context in
/// reports; pass `WasmSummary::default()` when not available.
pub fn diff_specs(
    old: &ContractSpec,
    new: &ContractSpec,
    old_summary: WasmSummary,
    new_summary: WasmSummary,
) -> Result<SpecDiff, WasmError> {
    let mut diff = SpecDiff {
        old: old_summary,
        new: new_summary,
        ..Default::default()
    };
    diff.size_delta_bytes = size_delta_bytes(diff.old.size_bytes, diff.new.size_bytes);
    diff.size_delta_pct = size_delta_pct(diff.old.size_bytes, diff.new.size_bytes);

    // Index old by name for O(n) lookups.
    let old_fns: std::collections::BTreeMap<&str, &ContractFunction> =
        old.functions.iter().map(|f| (f.name.as_str(), f)).collect();
    let new_fns: std::collections::BTreeMap<&str, &ContractFunction> =
        new.functions.iter().map(|f| (f.name.as_str(), f)).collect();

    for (name, nf) in &new_fns {
        match old_fns.get(name) {
            None => diff.added_functions.push((**nf).clone()),
            Some(of) => {
                if of.parameters != nf.parameters || of.outputs != nf.outputs {
                    diff.changed_functions.push(FunctionSignatureChange {
                        name: (*name).to_string(),
                        old: (*of).clone(),
                        new: (**nf).clone(),
                    });
                }
            }
        }
    }
    for (_name, of) in &old_fns {
        if !new_fns.contains_key(_name) {
            diff.removed_functions.push((**of).clone());
        }
    }

    // Events and custom types: name-set comparison for add/remove, then a
    // definition comparison for the ones present on both sides. Comparing
    // names alone would report an event/type that changed its shape in place
    // as unchanged.
    let old_events = by_name(&old.events, |e| e.name.as_str());
    let new_events = by_name(&new.events, |e| e.name.as_str());
    diff_set(
        &old.events
            .iter()
            .map(|e| e.name.clone())
            .collect::<Vec<_>>(),
        &new.events
            .iter()
            .map(|e| e.name.clone())
            .collect::<Vec<_>>(),
        &mut diff.added_events,
        &mut diff.removed_events,
    );
    for (name, ne) in &new_events {
        if let Some(oe) = old_events.get(name) {
            if !event_signature_eq(oe, ne) {
                diff.changed_events.push(EventSignatureChange {
                    name: (*name).to_string(),
                    old: (*oe).clone(),
                    new: (**ne).clone(),
                });
            }
        }
    }

    let old_types = by_name(&old.custom_types, |t| t.name.as_str());
    let new_types = by_name(&new.custom_types, |t| t.name.as_str());
    diff_set(
        &old.custom_types
            .iter()
            .map(|t| t.name.clone())
            .collect::<Vec<_>>(),
        &new.custom_types
            .iter()
            .map(|t| t.name.clone())
            .collect::<Vec<_>>(),
        &mut diff.added_types,
        &mut diff.removed_types,
    );
    for (name, nt) in &new_types {
        if let Some(ot) = old_types.get(name) {
            if !type_definition_eq(ot, nt) {
                diff.changed_types.push(TypeDefinitionChange {
                    name: (*name).to_string(),
                    old: (*ot).clone(),
                    new: (**nt).clone(),
                });
            }
        }
    }

    Ok(diff)
}

/// Index a list of named ABI entries by name for O(n) lookups.
fn by_name<T, F>(items: &[T], name_of: F) -> std::collections::BTreeMap<&str, &T>
where
    F: Fn(&T) -> &str,
{
    items.iter().map(|i| (name_of(i), i)).collect()
}

/// Compare two [`ContractType`] references by identity, ignoring docs.
///
/// For compound types (`option<T>`, `vec<T>`, `map<K,V>`, `result<O,E>`,
/// `tuple<...>`, `bytesn<N>`) the recursive inner structure is encoded into
/// `name` (e.g. `"vec<u32>"` vs `"vec<i128>"`), so a name + kind comparison
/// is sufficient to distinguish e.g. `Vec<u32>` from `Vec<i128>`. The members
/// field is compared as well for defence-in-depth.
fn type_ref_eq(a: &ContractType, b: &ContractType) -> bool {
    if a.name != b.name || a.kind != b.kind {
        return false;
    }
    // For compound types the `members` field carries the inner ContractTypes
    // that were recursively mapped.  Comparing them here ensures that nested
    // compound structures (e.g. Option<Vec<u32>>) are compared deeply even
    // if, hypothetically, the name encoding were ever changed.
    if a.kind == "compound" {
        return a.members.len() == b.members.len()
            && a.members
                .iter()
                .zip(b.members.iter())
                .all(|(x, y)| x.name == y.name && member_types_eq(&x.types, &y.types));
    }
    true
}

/// Compare two member type lists by identity (name + kind), ignoring docs.
fn member_types_eq(a: &[ContractType], b: &[ContractType]) -> bool {
    a.len() == b.len() && a.iter().zip(b.iter()).all(|(x, y)| type_ref_eq(x, y))
}

/// Compare two event signatures, ignoring doc comments (docs are not ABI).
///
/// A consumer decodes the topic/data payload layout, so any change to the
/// prefix topics, the parameter list (name, type, or topic-vs-data location),
/// or the data format is a signature change.
fn event_signature_eq(a: &ContractEvent, b: &ContractEvent) -> bool {
    a.prefix_topics == b.prefix_topics
        && a.data_format == b.data_format
        && a.params.len() == b.params.len()
        && a.params.iter().zip(b.params.iter()).all(|(x, y)| {
            x.name == y.name && x.location == y.location && type_ref_eq(&x.type_, &y.type_)
        })
}

/// Compare two custom type definitions, ignoring doc comments (docs are not
/// ABI). A change of kind (struct -> enum), of any member's name or types, or
/// of an enum case's discriminant is a definition change.
fn type_definition_eq(a: &ContractType, b: &ContractType) -> bool {
    a.kind == b.kind
        && a.members.len() == b.members.len()
        && a.members.iter().zip(b.members.iter()).all(|(x, y)| {
            x.name == y.name && x.value == y.value && member_types_eq(&x.types, &y.types)
        })
}

/// Classify named items present in `new` but not `old` (`added`) and `old` but
/// not `new` (`removed`). Names are the identity key.
fn diff_set(old: &[String], new: &[String], added: &mut Vec<String>, removed: &mut Vec<String>) {
    let old_set: std::collections::BTreeSet<&str> = old.iter().map(String::as_str).collect();
    let new_set: std::collections::BTreeSet<&str> = new.iter().map(String::as_str).collect();

    for n in &new_set {
        if !old_set.contains(n) {
            added.push((*n).to_string());
        }
    }
    for n in &old_set {
        if !new_set.contains(n) {
            removed.push((*n).to_string());
        }
    }
}

/// Kind of ABI delta observed during an upgrade-safety check.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChangeKind {
    RemovedFunction,
    ChangedSignature,
    RemovedEvent,
    RemovedType,
    AddedFunction,
    AddedEvent,
    AddedType,
    ChangedEvent,
    ChangedTypeDefinition,
}

/// A single classified delta, used for both breaking and non-breaking lists.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerdictChange {
    pub kind: ChangeKind,
    /// Item name (function/event/type). Functions are stored bare; the
    /// human label adds `()` for call-style rendering.
    pub name: String,
    /// Optional human-readable detail (e.g. old/new signature for a change).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub detail: String,
}

impl VerdictChange {
    /// Human-readable `Kind: name()` label for pretty output.
    pub fn label(&self) -> String {
        let kind = match self.kind {
            ChangeKind::RemovedFunction => "Removed function",
            ChangeKind::ChangedSignature => "Changed signature",
            ChangeKind::RemovedEvent => "Removed event",
            ChangeKind::RemovedType => "Removed type",
            ChangeKind::AddedFunction => "Added function",
            ChangeKind::AddedEvent => "Added event",
            ChangeKind::AddedType => "Added type",
            ChangeKind::ChangedEvent => "Changed event",
            ChangeKind::ChangedTypeDefinition => "Changed type definition",
        };
        match self.kind {
            ChangeKind::RemovedFunction
            | ChangeKind::AddedFunction
            | ChangeKind::ChangedSignature => {
                format!("{}: {}()", kind, self.name)
            }
            _ => format!("{}: {}", kind, self.name),
        }
    }
}

/// An actionable upgrade-safety verdict derived from a [`SpecDiff`].
///
/// `compatible` is `false` when any *breaking* change is present (removed
/// function, changed signature, removed event, changed event signature,
/// removed type, changed type definition). Additions are non-breaking and
/// recorded separately.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct UpgradeVerdict {
    pub compatible: bool,
    pub breaking_changes: Vec<VerdictChange>,
    pub non_breaking_changes: Vec<VerdictChange>,
}

impl UpgradeVerdict {
    /// Classify a [`SpecDiff`] into an upgrade-safety verdict.
    ///
    /// This deliberately reuses the existing diff output; no comparison logic
    /// is duplicated.
    pub fn from_diff(diff: &SpecDiff) -> Self {
        let mut breaking = Vec::new();
        let mut non_breaking = Vec::new();

        for f in &diff.removed_functions {
            breaking.push(VerdictChange {
                kind: ChangeKind::RemovedFunction,
                name: f.name.clone(),
                detail: String::new(),
            });
        }
        for c in &diff.changed_functions {
            breaking.push(VerdictChange {
                kind: ChangeKind::ChangedSignature,
                name: c.name.clone(),
                detail: format!("old: {}\n      new: {}", sig_of(&c.old), sig_of(&c.new)),
            });
        }
        for e in &diff.removed_events {
            breaking.push(VerdictChange {
                kind: ChangeKind::RemovedEvent,
                name: e.clone(),
                detail: String::new(),
            });
        }
        for c in &diff.changed_events {
            breaking.push(VerdictChange {
                kind: ChangeKind::ChangedEvent,
                name: c.name.clone(),
                detail: format!(
                    "old: {}\n      new: {}",
                    event_sig(&c.old),
                    event_sig(&c.new)
                ),
            });
        }
        for t in &diff.removed_types {
            breaking.push(VerdictChange {
                kind: ChangeKind::RemovedType,
                name: t.clone(),
                detail: String::new(),
            });
        }
        for c in &diff.changed_types {
            breaking.push(VerdictChange {
                kind: ChangeKind::ChangedTypeDefinition,
                name: c.name.clone(),
                detail: format!("old: {}\n      new: {}", type_sig(&c.old), type_sig(&c.new)),
            });
        }
        for f in &diff.added_functions {
            non_breaking.push(VerdictChange {
                kind: ChangeKind::AddedFunction,
                name: f.name.clone(),
                detail: String::new(),
            });
        }
        for e in &diff.added_events {
            non_breaking.push(VerdictChange {
                kind: ChangeKind::AddedEvent,
                name: e.clone(),
                detail: String::new(),
            });
        }
        for t in &diff.added_types {
            non_breaking.push(VerdictChange {
                kind: ChangeKind::AddedType,
                name: t.clone(),
                detail: String::new(),
            });
        }

        let compatible = breaking.is_empty();
        Self {
            compatible,
            breaking_changes: breaking,
            non_breaking_changes: non_breaking,
        }
    }
}

/// Signed size delta in bytes between two artifacts.
pub fn size_delta_bytes(old_bytes: usize, new_bytes: usize) -> i64 {
    new_bytes as i64 - old_bytes as i64
}

/// Percentage growth of `new_bytes` relative to `old_bytes`, rounded to one
/// decimal place.
///
/// Zero-byte baseline semantics (documented, no division by zero):
/// - old == 0, new == 0 → `Some(0.0)` (nothing grew);
/// - old == 0, new  > 0 → `None` — undefined relative change (rendered as
///   `null` in JSON); absolute policy (`--max-size-bytes`) still applies.
pub fn size_delta_pct(old_bytes: usize, new_bytes: usize) -> Option<f64> {
    if old_bytes == 0 {
        return if new_bytes == 0 { Some(0.0) } else { None };
    }
    let pct = (new_bytes as f64 - old_bytes as f64) * 100.0 / old_bytes as f64;
    Some((pct * 10.0).round() / 10.0)
}

/// Build a `name(params) -> outputs` signature string for a function.
fn sig_of(f: &ContractFunction) -> String {
    let params = f
        .parameters
        .iter()
        .map(|p| p.type_.name.clone())
        .collect::<Vec<_>>()
        .join(", ");
    let outputs = f
        .outputs
        .iter()
        .map(|o| o.name.clone())
        .collect::<Vec<_>>()
        .join(", ");
    format!("{}({}) -> ({})", f.name, params, outputs)
}

/// Build a `name(param: type, ...)` signature string for an event, annotating
/// each parameter with whether it is carried in a topic or in the data
/// payload — the two are decoded differently by consumers.
pub fn event_sig(e: &ContractEvent) -> String {
    let mut parts: Vec<String> = e
        .prefix_topics
        .iter()
        .map(|t| format!("{}: symbol [prefix]", t))
        .collect();
    parts.extend(
        e.params
            .iter()
            .map(|p| format!("{}: {} [{}]", p.name, p.type_.name, p.location)),
    );
    format!("{}({}) -> {}", e.name, parts.join(", "), e.data_format)
}

/// Build a `kind name { member, ... }` definition string for a custom type.
///
/// An enum or error-enum case renders as `Name=0`, showing the discriminant
/// that decodes the case; a struct field or union case renders as
/// `name: type` (or `name: void` for a void union case).
pub fn type_sig(t: &ContractType) -> String {
    let members = t
        .members
        .iter()
        .map(|m| {
            let Some(value) = m.value else {
                let types = m.types.iter().map(|ty| ty.name.clone()).collect::<Vec<_>>();
                let shape = match types.len() {
                    0 => "void".to_string(),
                    1 => types.into_iter().next().unwrap_or_default(),
                    _ => format!("({})", types.join(", ")),
                };
                return format!("{}: {}", m.name, shape);
            };
            let types = m.types.iter().map(|ty| ty.name.clone()).collect::<Vec<_>>();
            if types.is_empty() {
                format!("{}={}", m.name, value)
            } else {
                format!("{}={}: ({})", m.name, value, types.join(", "))
            }
        })
        .collect::<Vec<_>>();
    if members.is_empty() {
        format!("{} {}", t.kind, t.name)
    } else {
        format!("{} {} {{ {} }}", t.kind, t.name, members.join(", "))
    }
}

/// Compute an upgrade-safety verdict from two already-parsed [`ContractSpec`]s.
///
/// Reuses [`diff_specs`] (no duplicated comparison logic).
pub fn upgrade_safety(old: &ContractSpec, new: &ContractSpec) -> UpgradeVerdict {
    let diff =
        diff_specs(old, new, WasmSummary::default(), WasmSummary::default()).unwrap_or_default();
    UpgradeVerdict::from_diff(&diff)
}

/// Compute an upgrade-safety verdict directly from two raw WASM binaries.
pub fn upgrade_safety_wasm(old_raw: &[u8], new_raw: &[u8]) -> Result<UpgradeVerdict, WasmError> {
    let diff = diff_wasm(old_raw, new_raw)?;
    Ok(UpgradeVerdict::from_diff(&diff))
}

#[cfg(test)]
mod tests {
    use super::*;

    // ---- size delta / growth policy math (WASM size policy) ----

    #[test]
    fn size_delta_bytes_is_signed_and_sums_correctly() {
        assert_eq!(size_delta_bytes(467, 10543), 10076); // growth
        assert_eq!(size_delta_bytes(10543, 467), -10076); // shrink
        assert_eq!(size_delta_bytes(530, 530), 0); // equal
        assert_eq!(size_delta_bytes(0, 0), 0);
        assert_eq!(size_delta_bytes(0, 4096), 4096);
    }

    #[test]
    fn size_delta_pct_rounds_to_one_decimal() {
        assert_eq!(size_delta_pct(467, 10543), Some(2157.6));
        assert_eq!(size_delta_pct(198, 530), Some(167.7)); // 167.676… -> 167.7
        assert_eq!(size_delta_pct(467, 467), Some(0.0)); // equal
        assert_eq!(size_delta_pct(1000, 900), Some(-10.0)); // negative growth
        assert_eq!(size_delta_pct(10, 10), Some(0.0));
        // 1.44 -> 1.4 (half-away-from-zero), 1.45 -> 1.5
        assert_eq!(size_delta_pct(1000, 1014), Some(1.4));
        assert_eq!(size_delta_pct(1000, 1015), Some(1.5));
    }

    #[test]
    fn size_delta_pct_zero_baseline_is_none_unless_both_zero() {
        // Division by zero must never happen: undefined relative change -> None.
        assert_eq!(size_delta_pct(0, 1), None);
        assert_eq!(size_delta_pct(0, 4096), None);
        assert_eq!(size_delta_pct(0, 0), Some(0.0)); // nothing grew
    }

    #[test]
    fn diff_specs_reports_size_fields() {
        let old = ContractSpec {
            env_meta: None,
            functions: vec![],
            custom_types: vec![],
            events: vec![],
        };
        let new = old.clone();
        let diff = diff_specs(
            &old,
            &new,
            WasmSummary {
                hash: "o".into(),
                size_bytes: 467,
            },
            WasmSummary {
                hash: "n".into(),
                size_bytes: 530,
            },
        )
        .unwrap();
        assert_eq!(diff.size_delta_bytes, 63);
        assert_eq!(diff.size_delta_pct, Some(13.5));
        // JSON key presence/shape is asserted from the real CLI output in
        // `sdkt-cli` integration tests (this crate has no serde_json dep).
    }

    #[test]
    fn diff_specs_zero_baseline_serializes_null_pct() {
        let spec = ContractSpec {
            env_meta: None,
            functions: vec![],
            custom_types: vec![],
            events: vec![],
        };
        let diff = diff_specs(
            &spec,
            &spec,
            WasmSummary::default(),
            WasmSummary {
                hash: "n".into(),
                size_bytes: 100,
            },
        )
        .unwrap();
        assert_eq!(diff.size_delta_bytes, 100);
        assert_eq!(diff.size_delta_pct, None);
    }
    use crate::spec::tests::func_entry;
    use crate::spec::tests::spec_section;
    use stellar_xdr::ScSpecTypeDef;

    // Re-create small WASM blobs with the helper from spec.rs tests.

    #[test]
    fn identical_specs_diff_empty() {
        let wasm = spec_section(&[func_entry(
            "greet",
            vec![("name".into(), ScSpecTypeDef::String)],
        )]);
        let d = diff_wasm(&wasm, &wasm).unwrap();
        assert!(d.is_identical());
        assert_eq!(d.total_changes(), 0);
    }

    #[test]
    fn detects_added_function() {
        let old = spec_section(&[func_entry("a", vec![])]);
        let new = spec_section(&[
            func_entry("a", vec![]),
            func_entry("b", vec![("x".into(), ScSpecTypeDef::U32)]),
        ]);
        let d = diff_wasm(&old, &new).unwrap();
        assert_eq!(d.added_functions.len(), 1);
        assert_eq!(d.added_functions[0].name, "b");
        assert!(d.removed_functions.is_empty());
        assert!(d.changed_functions.is_empty());
    }

    #[test]
    fn detects_removed_function() {
        let old = spec_section(&[func_entry("a", vec![]), func_entry("b", vec![])]);
        let new = spec_section(&[func_entry("a", vec![])]);
        let d = diff_wasm(&old, &new).unwrap();
        assert_eq!(d.removed_functions.len(), 1);
        assert_eq!(d.removed_functions[0].name, "b");
    }

    #[test]
    fn detects_changed_signature() {
        let old = spec_section(&[func_entry("f", vec![("x".into(), ScSpecTypeDef::U32)])]);
        let new = spec_section(&[func_entry("f", vec![("x".into(), ScSpecTypeDef::U64)])]);
        let d = diff_wasm(&old, &new).unwrap();
        assert_eq!(d.changed_functions.len(), 1);
        assert_eq!(d.changed_functions[0].name, "f");
        assert_eq!(d.changed_functions[0].old.parameters[0].type_.name, "u32");
        assert_eq!(d.changed_functions[0].new.parameters[0].type_.name, "u64");
    }

    #[test]
    fn detects_added_removed_events() {
        use crate::spec::tests::event_entry;
        let old = spec_section(&[event_entry("Transfer")]);
        let new = spec_section(&[event_entry("Mint")]);
        let d = diff_wasm(&old, &new).unwrap();
        assert_eq!(d.added_events, vec!["Mint".to_string()]);
        assert_eq!(d.removed_events, vec!["Transfer".to_string()]);
    }

    #[test]
    fn detects_added_removed_types() {
        use crate::spec::tests::udt_struct_entry;
        let old = spec_section(&[udt_struct_entry("Point")]);
        let new = spec_section(&[udt_struct_entry("Circle")]);
        let d = diff_wasm(&old, &new).unwrap();
        assert_eq!(d.added_types, vec!["Circle".to_string()]);
        assert_eq!(d.removed_types, vec!["Point".to_string()]);
    }

    #[test]
    fn detects_changed_event_params() {
        use crate::spec::tests::event_entry_with_params;
        // Same event name, different params: `amount` widens and `memo` is added.
        let old = spec_section(&[event_entry_with_params(
            "Transfer",
            vec![
                ("from".into(), ScSpecTypeDef::Address),
                ("amount".into(), ScSpecTypeDef::I128),
            ],
        )]);
        let new = spec_section(&[event_entry_with_params(
            "Transfer",
            vec![
                ("from".into(), ScSpecTypeDef::Address),
                ("amount".into(), ScSpecTypeDef::U64),
                ("memo".into(), ScSpecTypeDef::String),
            ],
        )]);
        let d = diff_wasm(&old, &new).unwrap();
        assert_eq!(d.changed_events.len(), 1);
        assert_eq!(d.changed_events[0].name, "Transfer");
        assert_eq!(d.changed_events[0].old.params.len(), 2);
        assert_eq!(d.changed_events[0].old.params[1].type_.name, "i128");
        assert_eq!(d.changed_events[0].new.params.len(), 3);
        assert_eq!(d.changed_events[0].new.params[1].type_.name, "u64");
        // A changed event is not an add or a remove.
        assert!(d.added_events.is_empty());
        assert!(d.removed_events.is_empty());
    }

    #[test]
    fn identical_events_produce_no_change() {
        use crate::spec::tests::event_entry_with_params;
        let wasm = spec_section(&[event_entry_with_params(
            "Transfer",
            vec![("from".into(), ScSpecTypeDef::Address)],
        )]);
        let d = diff_wasm(&wasm, &wasm).unwrap();
        assert!(d.changed_events.is_empty());
        assert!(d.is_identical());
        assert_eq!(d.total_changes(), 0);
    }

    #[test]
    fn detects_changed_type_members() {
        use crate::spec::tests::udt_struct_entry_with_fields;
        // Same type name, different members: `x` widens and `z` is added.
        let old = spec_section(&[udt_struct_entry_with_fields(
            "Point",
            vec![("x".into(), ScSpecTypeDef::I32)],
        )]);
        let new = spec_section(&[udt_struct_entry_with_fields(
            "Point",
            vec![
                ("x".into(), ScSpecTypeDef::I64),
                ("z".into(), ScSpecTypeDef::I32),
            ],
        )]);
        let d = diff_wasm(&old, &new).unwrap();
        assert_eq!(d.changed_types.len(), 1);
        assert_eq!(d.changed_types[0].name, "Point");
        assert_eq!(d.changed_types[0].old.members.len(), 1);
        assert_eq!(d.changed_types[0].old.members[0].types[0].name, "i32");
        assert_eq!(d.changed_types[0].new.members.len(), 2);
        assert_eq!(d.changed_types[0].new.members[0].types[0].name, "i64");
        // A changed type is not an add or a remove.
        assert!(d.added_types.is_empty());
        assert!(d.removed_types.is_empty());
    }

    #[test]
    fn detects_type_kind_change() {
        use stellar_xdr::{
            ScSpecEntry, ScSpecUdtEnumCaseV0, ScSpecUdtEnumV0, ScSpecUdtStructFieldV0,
            ScSpecUdtStructV0,
        };
        let struct_entry = ScSpecEntry::UdtStructV0(ScSpecUdtStructV0 {
            doc: "".try_into().unwrap(),
            lib: "soroban_sdk".try_into().unwrap(),
            name: "Status".try_into().unwrap(),
            fields: vec![ScSpecUdtStructFieldV0 {
                doc: "".try_into().unwrap(),
                name: "active".try_into().unwrap(),
                type_: ScSpecTypeDef::Bool,
            }]
            .try_into()
            .unwrap(),
        });
        let enum_entry = ScSpecEntry::UdtEnumV0(ScSpecUdtEnumV0 {
            doc: "".try_into().unwrap(),
            lib: "soroban_sdk".try_into().unwrap(),
            name: "Status".try_into().unwrap(),
            cases: vec![ScSpecUdtEnumCaseV0 {
                doc: "".try_into().unwrap(),
                name: "Active".try_into().unwrap(),
                value: 0,
            }]
            .try_into()
            .unwrap(),
        });
        let d = diff_wasm(&spec_section(&[struct_entry]), &spec_section(&[enum_entry])).unwrap();
        assert_eq!(d.changed_types.len(), 1);
        assert_eq!(d.changed_types[0].name, "Status");
        assert_eq!(d.changed_types[0].old.kind, "struct");
        assert_eq!(d.changed_types[0].new.kind, "enum");
    }

    #[test]
    fn identical_types_produce_no_change() {
        use crate::spec::tests::udt_struct_entry_with_fields;
        let wasm = spec_section(&[udt_struct_entry_with_fields(
            "Point",
            vec![("x".into(), ScSpecTypeDef::I32)],
        )]);
        let d = diff_wasm(&wasm, &wasm).unwrap();
        assert!(d.changed_types.is_empty());
        assert!(d.is_identical());
        assert_eq!(d.total_changes(), 0);
    }

    #[test]
    fn parse_error_propagates() {
        // "old" is valid but has no contract spec; "new" is a valid spec.
        let old = vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00];
        let new = spec_section(&[func_entry("a", vec![])]);
        let err = diff_wasm(&old, &new);
        assert!(matches!(err, Err(WasmError::NoContractSpec)));
    }

    // ---- Upgrade-safety verdict tests (reuse diff_specs, no new comparison) ----

    #[test]
    fn verdict_flags_removed_function_breaking() {
        let old = spec_section(&[func_entry("a", vec![]), func_entry("b", vec![])]);
        let new = spec_section(&[func_entry("a", vec![])]);
        let v = upgrade_safety_wasm(&old, &new).unwrap();
        assert!(!v.compatible);
        assert_eq!(v.breaking_changes.len(), 1);
        assert_eq!(v.breaking_changes[0].kind, ChangeKind::RemovedFunction);
        assert_eq!(v.breaking_changes[0].name, "b");
    }

    #[test]
    fn verdict_flags_changed_signature_breaking() {
        let old = spec_section(&[func_entry("f", vec![("x".into(), ScSpecTypeDef::U32)])]);
        let new = spec_section(&[func_entry("f", vec![("x".into(), ScSpecTypeDef::U64)])]);
        let v = upgrade_safety_wasm(&old, &new).unwrap();
        assert!(!v.compatible);
        assert_eq!(v.breaking_changes.len(), 1);
        assert_eq!(v.breaking_changes[0].kind, ChangeKind::ChangedSignature);
        assert_eq!(v.breaking_changes[0].name, "f");
    }

    #[test]
    fn verdict_flags_changed_event_breaking() {
        use crate::spec::tests::event_entry_with_params;
        let old = spec_section(&[event_entry_with_params(
            "Transfer",
            vec![("amount".into(), ScSpecTypeDef::I128)],
        )]);
        let new = spec_section(&[event_entry_with_params(
            "Transfer",
            vec![("amount".into(), ScSpecTypeDef::U64)],
        )]);
        let v = upgrade_safety_wasm(&old, &new).unwrap();
        assert!(!v.compatible);
        assert_eq!(v.breaking_changes.len(), 1);
        assert_eq!(v.breaking_changes[0].kind, ChangeKind::ChangedEvent);
        assert_eq!(v.breaking_changes[0].name, "Transfer");
        // The detail shows both shapes so the change is actionable.
        let d = &v.breaking_changes[0].detail;
        assert!(d.contains("i128"), "detail should show the old type: {}", d);
        assert!(d.contains("u64"), "detail should show the new type: {}", d);
    }

    #[test]
    fn detects_changed_enum_discriminant() {
        use stellar_xdr::{ScSpecEntry, ScSpecUdtEnumCaseV0, ScSpecUdtEnumV0};
        // Same case names, different discriminants: stored data that decoded
        // as `Active` would now resolve to a different case.
        let enum_with = |value: u32| {
            ScSpecEntry::UdtEnumV0(ScSpecUdtEnumV0 {
                doc: "".try_into().unwrap(),
                lib: "soroban_sdk".try_into().unwrap(),
                name: "Status".try_into().unwrap(),
                cases: vec![
                    ScSpecUdtEnumCaseV0 {
                        doc: "".try_into().unwrap(),
                        name: "Active".try_into().unwrap(),
                        value: 0,
                    },
                    ScSpecUdtEnumCaseV0 {
                        doc: "".try_into().unwrap(),
                        name: "Paused".try_into().unwrap(),
                        value,
                    },
                ]
                .try_into()
                .unwrap(),
            })
        };
        let d = diff_wasm(
            &spec_section(&[enum_with(1)]),
            &spec_section(&[enum_with(2)]),
        )
        .unwrap();
        assert_eq!(d.changed_types.len(), 1);
        assert_eq!(d.changed_types[0].name, "Status");
        assert_eq!(
            d.changed_types[0].old.members[1].value,
            Some(1),
            "old discriminant must be retained"
        );
        assert_eq!(d.changed_types[0].new.members[1].value, Some(2));
        // Breaking, with both discriminants visible in the detail.
        let v = upgrade_safety(
            &parse_contract_spec(&spec_section(&[enum_with(1)])).unwrap(),
            &parse_contract_spec(&spec_section(&[enum_with(2)])).unwrap(),
        );
        assert!(!v.compatible);
        assert_eq!(
            v.breaking_changes[0].kind,
            ChangeKind::ChangedTypeDefinition
        );
        assert!(
            v.breaking_changes[0].detail.contains("Paused=1"),
            "{}",
            v.breaking_changes[0].detail
        );
        assert!(
            v.breaking_changes[0].detail.contains("Paused=2"),
            "{}",
            v.breaking_changes[0].detail
        );
    }

    #[test]
    fn identical_enum_discriminants_produce_no_change() {
        use stellar_xdr::{ScSpecEntry, ScSpecUdtEnumCaseV0, ScSpecUdtEnumV0};
        let entry = ScSpecEntry::UdtEnumV0(ScSpecUdtEnumV0 {
            doc: "".try_into().unwrap(),
            lib: "soroban_sdk".try_into().unwrap(),
            name: "Status".try_into().unwrap(),
            cases: vec![ScSpecUdtEnumCaseV0 {
                doc: "".try_into().unwrap(),
                name: "Active".try_into().unwrap(),
                value: 7,
            }]
            .try_into()
            .unwrap(),
        });
        let wasm = spec_section(&[entry]);
        let d = diff_wasm(&wasm, &wasm).unwrap();
        assert!(d.changed_types.is_empty());
        assert!(d.is_identical());
    }

    #[test]
    fn verdict_flags_changed_type_definition_breaking() {
        use crate::spec::tests::udt_struct_entry_with_fields;
        let old = spec_section(&[udt_struct_entry_with_fields(
            "Point",
            vec![("x".into(), ScSpecTypeDef::I32)],
        )]);
        let new = spec_section(&[udt_struct_entry_with_fields(
            "Point",
            vec![("x".into(), ScSpecTypeDef::I64)],
        )]);
        let v = upgrade_safety_wasm(&old, &new).unwrap();
        assert!(!v.compatible);
        assert_eq!(v.breaking_changes.len(), 1);
        assert_eq!(
            v.breaking_changes[0].kind,
            ChangeKind::ChangedTypeDefinition
        );
        assert_eq!(v.breaking_changes[0].name, "Point");
        let d = &v.breaking_changes[0].detail;
        assert!(d.contains("i32"), "detail should show the old type: {}", d);
        assert!(d.contains("i64"), "detail should show the new type: {}", d);
    }

    #[test]
    fn verdict_flags_removed_event_breaking() {
        use crate::spec::tests::event_entry;
        let old = spec_section(&[event_entry("Transfer")]);
        let new = spec_section(&[]);
        let v = upgrade_safety_wasm(&old, &new).unwrap();
        assert!(!v.compatible);
        assert_eq!(v.breaking_changes.len(), 1);
        assert_eq!(v.breaking_changes[0].kind, ChangeKind::RemovedEvent);
        assert_eq!(v.breaking_changes[0].name, "Transfer");
    }

    #[test]
    fn verdict_flags_removed_type_breaking() {
        use crate::spec::tests::udt_struct_entry;
        let old = spec_section(&[udt_struct_entry("Point")]);
        let new = spec_section(&[]);
        let v = upgrade_safety_wasm(&old, &new).unwrap();
        assert!(!v.compatible);
        assert_eq!(v.breaking_changes.len(), 1);
        assert_eq!(v.breaking_changes[0].kind, ChangeKind::RemovedType);
        assert_eq!(v.breaking_changes[0].name, "Point");
    }

    #[test]
    fn verdict_only_additions_is_compatible() {
        use crate::spec::tests::event_entry;
        let old = spec_section(&[func_entry("a", vec![])]);
        let new = spec_section(&[
            func_entry("a", vec![]),
            func_entry("b", vec![("x".into(), ScSpecTypeDef::U32)]),
        ]);
        let old2 = spec_section(&[func_entry("a", vec![])]);
        let new2 = spec_section(&[func_entry("a", vec![]), event_entry("Mint")]);
        let v = upgrade_safety_wasm(&old, &new).unwrap();
        assert!(v.compatible);
        let v2 = upgrade_safety_wasm(&old2, &new2).unwrap();
        assert!(v2.compatible);
        assert!(v2.breaking_changes.is_empty());
        assert!(!v2.non_breaking_changes.is_empty());
        assert!(v2
            .non_breaking_changes
            .iter()
            .any(|c| c.kind == ChangeKind::AddedEvent && c.name == "Mint"));
    }

    #[test]
    fn verdict_identical_is_compatible() {
        let wasm = spec_section(&[func_entry(
            "greet",
            vec![("name".into(), ScSpecTypeDef::String)],
        )]);
        let v = upgrade_safety_wasm(&wasm, &wasm).unwrap();
        assert!(v.compatible);
        assert!(v.breaking_changes.is_empty());
        assert!(v.non_breaking_changes.is_empty());
    }
}