-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathbuild.rs
More file actions
1086 lines (970 loc) · 35.8 KB
/
Copy pathbuild.rs
File metadata and controls
1086 lines (970 loc) · 35.8 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
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
use assert_fs::TempDir;
use fs_extra::dir::CopyOptions;
use predicates::prelude::{predicate, PredicateBooleanExt};
use shell_escape::escape;
use soroban_cli::xdr::{Limited, Limits, ReadXdr, ScMetaEntry, ScMetaV0, ScSpecEntry};
use soroban_spec_tools::contract::Spec;
use soroban_test::TestEnv;
use std::env;
use std::io::Cursor;
use std::path::{Path, PathBuf};
#[test]
fn build_all() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace/");
let expected = format!(
"cargo rustc {} --crate-type=cdylib --target=wasm32v1-none --release
cargo rustc {} --crate-type=cdylib --target=wasm32v1-none --release
cargo rustc {} --crate-type=cdylib --target=wasm32v1-none --release",
manifest_path_arg(&add_path()),
manifest_path_arg(&call_path()),
manifest_path_arg(&add2_path()),
);
sandbox
.new_assert_cmd("contract")
.current_dir(fixture_path)
.arg("build")
.arg("--print-commands-only")
.assert()
.success()
.stdout(predicate::eq(with_flags(expected.as_str())));
}
#[test]
fn build_with_image_print_commands_only_multi_package() {
// With `--image`, `--print-commands-only` prints the container run command
// instead of the local cargo commands, without touching the engine. The
// workspace has several default-member cdylibs, so they chain through
// `/bin/sh -c`.
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace/");
sandbox
.new_assert_cmd("contract")
.current_dir(fixture_path)
.arg("build")
.arg("--image")
.arg("docker.io/stellar/stellar-cli:latest")
.arg("--print-commands-only")
.assert()
.success()
.stdout(
predicate::str::starts_with("docker run --rm")
.and(predicate::str::contains("-w /source"))
.and(predicate::str::contains("--entrypoint /bin/sh"))
.and(predicate::str::contains(
"docker.io/stellar/stellar-cli:latest",
))
.and(predicate::str::contains(
"stellar contract build --package=add",
))
.and(predicate::str::contains("&&"))
.and(predicate::str::contains("cargo rustc").not()),
);
}
#[test]
fn build_with_image_print_commands_only_single_package() {
// A single package runs the image's default entrypoint directly — no shell
// wrapper.
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace/");
sandbox
.new_assert_cmd("contract")
.current_dir(fixture_path)
.arg("build")
.arg("--image")
.arg("docker.io/stellar/stellar-cli:latest")
.arg("--package=add")
.arg("--print-commands-only")
.assert()
.success()
.stdout(
predicate::str::contains(
"'docker.io/stellar/stellar-cli:latest' contract build --package=add --optimize",
)
.and(predicate::str::contains("--entrypoint").not())
.and(predicate::str::contains("cargo rustc").not()),
);
}
#[test]
fn build_with_image_selects_package_by_manifest_path() {
// With `--image` and a `--manifest-path` pointing at a single member, only
// that package is built — mirroring the local build's package selection —
// instead of chaining every default-member cdylib. So it takes the
// single-package form (image's default entrypoint, no `/bin/sh` chain).
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace/");
sandbox
.new_assert_cmd("contract")
.current_dir(fixture_path)
.arg("build")
.arg("--image")
.arg("docker.io/stellar/stellar-cli:latest")
.arg(format!("--manifest-path={}", add_path()))
.arg("--print-commands-only")
.assert()
.success()
.stdout(
predicate::str::contains("--package=add")
.and(predicate::str::contains("--package=call").not())
.and(predicate::str::contains("--package=add2").not())
.and(predicate::str::contains("&&").not())
.and(predicate::str::contains("--entrypoint").not()),
);
}
#[test]
fn build_package_by_name() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace/");
let expected = format!(
"cargo rustc {} --crate-type=cdylib --target=wasm32v1-none --release",
manifest_path_arg(&add_path()),
);
sandbox
.new_assert_cmd("contract")
.current_dir(fixture_path)
.arg("build")
.arg("--print-commands-only")
.arg("--package=add")
.assert()
.success()
.stdout(predicate::eq(with_flags(expected.as_str())));
}
#[test]
fn build_package_by_current_dir() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace/contracts/add");
sandbox
.new_assert_cmd("contract")
.current_dir(fixture_path)
.arg("build")
.arg("--print-commands-only")
.assert()
.success()
.stdout(predicate::eq(
with_flags("cargo rustc --manifest-path=Cargo.toml --crate-type=cdylib --target=wasm32v1-none --release"),
));
}
#[test]
fn build_with_locked() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace/contracts/add");
sandbox
.new_assert_cmd("contract")
.current_dir(fixture_path)
.arg("build")
.arg("--print-commands-only")
.arg("--locked")
.assert()
.success()
.stdout(predicate::eq(
with_flags("cargo rustc --locked --manifest-path=Cargo.toml --crate-type=cdylib --target=wasm32v1-none --release"),
));
}
#[test]
fn build_no_package_found() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace/");
sandbox
.new_assert_cmd("contract")
.current_dir(fixture_path)
.arg("build")
.arg("--print-commands-only")
.arg("--package=nopkgwiththisname")
.assert()
.failure()
.stderr(predicate::eq(
"\
❌ error: package nopkgwiththisname not found
",
));
}
#[test]
fn build_all_when_in_non_package_directory() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace/contracts/add/src/");
let expected = format!(
"cargo rustc {} --crate-type=cdylib --target=wasm32v1-none --release",
manifest_path_arg(&parent_path()),
);
sandbox
.new_assert_cmd("contract")
.current_dir(fixture_path)
.arg("build")
.arg("--print-commands-only")
.assert()
.success()
.stdout(predicate::eq(with_flags(expected.as_str())));
}
#[test]
fn build_default_members() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace-with-default-members/");
let expected = format!(
"cargo rustc {} --crate-type=cdylib --target=wasm32v1-none --release",
manifest_path_arg(&add_path()),
);
sandbox
.new_assert_cmd("contract")
.current_dir(fixture_path)
.arg("build")
.arg("--print-commands-only")
.assert()
.success()
.stdout(predicate::eq(with_flags(expected.as_str())));
}
#[test]
fn build_with_metadata_rewrite() {
let sandbox = TestEnv::default();
let outdir = sandbox.dir().join("out");
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace");
let temp = TempDir::new().unwrap();
let dir_path = temp.path();
fs_extra::dir::copy(fixture_path, dir_path, &CopyOptions::new()).unwrap();
let dir_path = dir_path.join("workspace").join("contracts").join("add");
sandbox
.new_assert_cmd("contract")
.current_dir(&dir_path)
.arg("build")
.arg("--meta")
.arg("contract meta=added on build")
.arg("--out-dir")
.arg(&outdir)
.assert()
.success();
sandbox
.new_assert_cmd("contract")
.current_dir(&dir_path)
.arg("build")
.arg("--meta")
.arg("meta_replaced=some_new_meta")
.arg("--out-dir")
.arg(&outdir)
.assert()
.success();
let entries = get_entries(&dir_path, &outdir);
// Filter out CLI version for comparison
let filtered_entries: Vec<_> = entries
.into_iter()
.filter(|entry| !matches!(entry, ScMetaEntry::ScMetaV0(ScMetaV0 { key, .. }) if key.to_string() == "cliver"))
.collect();
let expected_entries = vec![
ScMetaEntry::ScMetaV0(ScMetaV0 {
key: "Description".try_into().unwrap(),
val: "A test add contract".try_into().unwrap(),
}),
ScMetaEntry::ScMetaV0(ScMetaV0 {
key: "meta_replaced".try_into().unwrap(),
val: "some_new_meta".try_into().unwrap(),
}),
];
assert_eq!(filtered_entries, expected_entries);
}
#[test]
fn build_with_metadata_diff_dir() {
let sandbox = TestEnv::default();
let outdir1 = sandbox.dir().join("out-1");
let outdir2 = sandbox.dir().join("out-2");
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace");
let temp = TempDir::new().unwrap();
let dir_path = temp.path();
fs_extra::dir::copy(fixture_path, dir_path, &CopyOptions::new()).unwrap();
let dir_path = dir_path.join("workspace").join("contracts").join("add");
sandbox
.new_assert_cmd("contract")
.current_dir(&dir_path)
.arg("build")
.arg("--meta")
.arg("contract meta=added on build")
.arg("--out-dir")
.arg(&outdir1)
.assert()
.success();
sandbox
.new_assert_cmd("contract")
.current_dir(&dir_path)
.arg("build")
.arg("--meta")
.arg("meta_replaced=some_new_meta")
.arg("--out-dir")
.arg(&outdir2)
.assert()
.success();
let entries_dir1 = get_entries(&dir_path, &outdir1);
let entries_dir2 = get_entries(&dir_path, &outdir2);
// Filter out CLI version for comparison
let filtered_entries_dir1: Vec<_> = entries_dir1
.into_iter()
.filter(|entry| !matches!(entry, ScMetaEntry::ScMetaV0(ScMetaV0 { key, .. }) if key.to_string() == "cliver"))
.collect();
let filtered_entries_dir2: Vec<_> = entries_dir2
.into_iter()
.filter(|entry| !matches!(entry, ScMetaEntry::ScMetaV0(ScMetaV0 { key, .. }) if key.to_string() == "cliver"))
.collect();
let expected_entries_dir1 = vec![
ScMetaEntry::ScMetaV0(ScMetaV0 {
key: "Description".try_into().unwrap(),
val: "A test add contract".try_into().unwrap(),
}),
ScMetaEntry::ScMetaV0(ScMetaV0 {
key: "contract meta".try_into().unwrap(),
val: "added on build".try_into().unwrap(),
}),
];
let expected_entries_dir2 = vec![
ScMetaEntry::ScMetaV0(ScMetaV0 {
key: "Description".try_into().unwrap(),
val: "A test add contract".try_into().unwrap(),
}),
ScMetaEntry::ScMetaV0(ScMetaV0 {
key: "meta_replaced".try_into().unwrap(),
val: "some_new_meta".try_into().unwrap(),
}),
];
assert_eq!(filtered_entries_dir1, expected_entries_dir1);
assert_eq!(filtered_entries_dir2, expected_entries_dir2);
}
fn build_spec_shaking_fixture() -> (Vec<ScSpecEntry>, Vec<ScMetaEntry>) {
let sandbox = TestEnv::default();
let outdir = sandbox.dir().join("out");
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace-with-spec-shaking");
let temp = TempDir::new().unwrap();
let dir_path = temp.path();
fs_extra::dir::copy(fixture_path, dir_path, &CopyOptions::new()).unwrap();
let dir_path = dir_path.join("workspace-with-spec-shaking");
sandbox
.new_assert_cmd("contract")
.current_dir(&dir_path)
.arg("build")
.arg("--out-dir")
.arg(&outdir)
.assert()
.success();
let wasm_path = dir_path.join(&outdir).join("shaking.wasm");
let wasm = std::fs::read(wasm_path).unwrap();
let spec = Spec::new(&wasm).unwrap();
(spec.spec, spec.meta)
}
fn spec_entry_name(entry: &ScSpecEntry) -> String {
match entry {
ScSpecEntry::FunctionV0(f) => f.name.to_utf8_string_lossy(),
ScSpecEntry::UdtStructV0(s) => s.name.to_utf8_string_lossy(),
ScSpecEntry::UdtUnionV0(u) => u.name.to_utf8_string_lossy(),
ScSpecEntry::UdtEnumV0(e) => e.name.to_utf8_string_lossy(),
ScSpecEntry::UdtErrorEnumV0(e) => e.name.to_utf8_string_lossy(),
ScSpecEntry::EventV0(e) => e.name.to_utf8_string_lossy(),
}
}
#[test]
fn build_with_spec_shaking_filters_unused_types() {
let (spec, _meta) = build_spec_shaking_fixture();
let names: Vec<String> = spec.iter().map(spec_entry_name).collect();
// All functions should be present
assert!(
names.contains(&"use_struct".to_string()),
"use_struct function should be present"
);
assert!(
names.contains(&"use_enum".to_string()),
"use_enum function should be present"
);
assert!(
names.contains(&"emit_event".to_string()),
"emit_event function should be present"
);
assert!(
names.contains(&"hello".to_string()),
"hello function should be present"
);
// Used types should be present
assert!(
names.contains(&"UsedStruct".to_string()),
"UsedStruct should be present"
);
assert!(
names.contains(&"UsedEnum".to_string()),
"UsedEnum should be present"
);
// Unused types should be removed
assert!(
!names.contains(&"UnusedStruct".to_string()),
"UnusedStruct should be removed"
);
assert!(
!names.contains(&"UnusedEnum".to_string()),
"UnusedEnum should be removed"
);
}
#[test]
fn build_with_spec_shaking_filters_unused_events() {
let (spec, _meta) = build_spec_shaking_fixture();
let names: Vec<String> = spec.iter().map(spec_entry_name).collect();
// Used event should be present
assert!(
names.contains(&"UsedEvent".to_string()),
"UsedEvent should be present"
);
// Unused event should be removed
assert!(
!names.contains(&"UnusedEvent".to_string()),
"UnusedEvent should be removed"
);
}
#[test]
fn build_with_spec_shaking_preserves_all_functions() {
let (spec, _meta) = build_spec_shaking_fixture();
let function_names: Vec<String> = spec
.iter()
.filter(|e| matches!(e, ScSpecEntry::FunctionV0(_)))
.map(spec_entry_name)
.collect();
assert!(function_names.contains(&"use_struct".to_string()));
assert!(function_names.contains(&"use_enum".to_string()));
assert!(function_names.contains(&"emit_event".to_string()));
assert!(function_names.contains(&"hello".to_string()));
assert_eq!(function_names.len(), 4, "expected exactly 4 functions");
}
#[test]
fn filter_and_dedup_spec_removes_duplicates() {
use soroban_cli::commands::contract::build::filter_and_dedup_spec;
use soroban_cli::xdr::{
ReadXdr, ScSpecEntry, ScSpecFunctionInputV0, ScSpecFunctionV0, ScSpecTypeDef,
ScSpecUdtStructFieldV0, ScSpecUdtStructV0, StringM, VecM,
};
let func = ScSpecEntry::FunctionV0(ScSpecFunctionV0 {
doc: StringM::default(),
name: "hello".try_into().unwrap(),
inputs: vec![ScSpecFunctionInputV0 {
doc: StringM::default(),
name: "arg0".try_into().unwrap(),
type_: ScSpecTypeDef::U32,
}]
.try_into()
.unwrap(),
outputs: VecM::default(),
});
let used_struct = ScSpecEntry::UdtStructV0(ScSpecUdtStructV0 {
doc: StringM::default(),
lib: StringM::default(),
name: "MyStruct".try_into().unwrap(),
fields: vec![ScSpecUdtStructFieldV0 {
doc: StringM::default(),
name: "field".try_into().unwrap(),
type_: ScSpecTypeDef::U32,
}]
.try_into()
.unwrap(),
});
// Build markers for the struct so it passes the filter
let mut markers = std::collections::HashSet::new();
markers.insert(soroban_spec::shaking::generate_marker_for_entry(
&used_struct,
));
// Input: function appears twice, struct appears three times
let entries = vec![
func.clone(),
func.clone(),
used_struct.clone(),
used_struct.clone(),
used_struct.clone(),
];
let result_xdr = filter_and_dedup_spec(entries, &markers).unwrap();
// Parse back the entries from the XDR
let result_entries: Vec<ScSpecEntry> =
ScSpecEntry::read_xdr_iter(&mut Limited::new(Cursor::new(result_xdr), Limits::none()))
.collect::<Result<Vec<_>, _>>()
.unwrap();
// Should have exactly 1 function + 1 struct, no duplicates
assert_eq!(
result_entries.len(),
2,
"expected 2 entries (1 function + 1 struct), got {}: {:?}",
result_entries.len(),
result_entries
.iter()
.map(spec_entry_name)
.collect::<Vec<_>>()
);
assert_eq!(spec_entry_name(&result_entries[0]), "hello");
assert_eq!(spec_entry_name(&result_entries[1]), "MyStruct");
}
#[test]
fn build_with_spec_shaking_has_feature_meta() {
let (_spec, meta) = build_spec_shaking_fixture();
let version = soroban_spec::shaking::spec_shaking_version_for_meta(&meta);
assert_eq!(
version, 2,
"contractmeta should indicate spec shaking version 2"
);
}
#[test]
fn build_without_spec_shaking_preserves_all_entries() {
let sandbox = TestEnv::default();
let outdir = sandbox.dir().join("out");
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace");
let temp = TempDir::new().unwrap();
let dir_path = temp.path();
fs_extra::dir::copy(fixture_path, dir_path, &CopyOptions::new()).unwrap();
let dir_path = dir_path.join("workspace").join("contracts").join("add");
sandbox
.new_assert_cmd("contract")
.current_dir(&dir_path)
.arg("build")
.arg("--out-dir")
.arg(&outdir)
.assert()
.success();
let wasm_path = dir_path.join(&outdir).join("add.wasm");
let wasm = std::fs::read(wasm_path).unwrap();
let spec = Spec::new(&wasm).unwrap();
// Without spec shaking, all spec entries should be preserved.
// The "add" contract should have at least its function(s).
let function_names: Vec<String> = spec
.spec
.iter()
.filter(|e| matches!(e, ScSpecEntry::FunctionV0(_)))
.map(spec_entry_name)
.collect();
assert!(
!function_names.is_empty(),
"functions should be preserved without spec shaking"
);
// Verify no rssdk_spec_shaking meta entry exists (no spec shaking support)
let has_feature_meta = spec.meta.iter().any(|entry| {
matches!(
entry,
ScMetaEntry::ScMetaV0(ScMetaV0 { key, .. })
if key.to_string() == "rssdk_spec_shaking"
)
});
assert!(
!has_feature_meta,
"workspace fixture should not have rssdk_spec_shaking meta"
);
}
#[test]
fn replace_custom_section_replaces_and_consolidates() {
use soroban_spec_tools::wasm::replace_custom_section;
use wasm_encoder::{CustomSection, Module};
// Build a minimal WASM with two custom sections with the same name
let mut module = Module::new();
module.section(&CustomSection {
name: "test_section".into(),
data: b"original_content_1".as_slice().into(),
});
module.section(&CustomSection {
name: "test_section".into(),
data: b"original_content_2".as_slice().into(),
});
module.section(&CustomSection {
name: "other_section".into(),
data: b"other_data".as_slice().into(),
});
let wasm = module.finish();
// Replace the custom section
let new_content = b"replaced_content";
let result = replace_custom_section(&wasm, "test_section", new_content).unwrap();
// Parse the result and verify
let parser = wasmparser::Parser::new(0);
let mut test_sections = Vec::new();
let mut other_sections = Vec::new();
for payload in parser.parse_all(&result) {
let payload = payload.unwrap();
if let wasmparser::Payload::CustomSection(section) = payload {
if section.name() == "test_section" {
test_sections.push(section.data().to_vec());
} else if section.name() == "other_section" {
other_sections.push(section.data().to_vec());
}
}
}
// Multiple sections consolidated into one
assert_eq!(
test_sections.len(),
1,
"should have exactly one test_section after replacement"
);
assert_eq!(test_sections[0], new_content, "content should be replaced");
// Other section should be preserved
assert_eq!(other_sections.len(), 1, "other_section should be preserved");
assert_eq!(
other_sections[0], b"other_data",
"other_section content should be unchanged"
);
}
fn get_entries(fixture_path: &Path, outdir: &Path) -> Vec<ScMetaEntry> {
// verify that the metadata added in the contract code via contractmetadata! macro is present
// as well as the meta that is included on build
let wasm_path = fixture_path.join(outdir).join("add.wasm");
let wasm = std::fs::read(wasm_path).unwrap();
let spec = Spec::new(&wasm).unwrap();
let meta = spec.meta_base64.unwrap();
ScMetaEntry::read_xdr_base64_iter(&mut Limited::new(
Cursor::new(meta.as_bytes()),
Limits::none(),
))
.filter(|entry| match entry {
// Ignore the meta entries that the SDK embeds that capture the SDK and
// Rust version, since these will change often and are not really
// relevant to this test.
Ok(ScMetaEntry::ScMetaV0(ScMetaV0 { key, .. })) => {
let key = key.to_string();
!matches!(key.as_str(), "rsver" | "rssdkver")
}
_ => true,
})
.collect::<Result<Vec<_>, _>>()
.unwrap()
}
fn manifest_path_arg(path: &str) -> String {
let arg = format!("--manifest-path={path}");
escape(std::borrow::Cow::Owned(arg)).into_owned()
}
fn add_path() -> String {
PathBuf::new()
.join("contracts")
.join("add")
.join("Cargo.toml")
.to_string_lossy()
.to_string()
}
fn call_path() -> String {
PathBuf::new()
.join("contracts")
.join("call")
.join("Cargo.toml")
.to_string_lossy()
.to_string()
}
fn add2_path() -> String {
PathBuf::new()
.join("contracts")
.join("add")
.join("add2")
.join("Cargo.toml")
.to_string_lossy()
.to_string()
}
fn parent_path() -> String {
PathBuf::new()
.join("..")
.join("Cargo.toml")
.to_string_lossy()
.to_string()
}
fn with_flags(expected: &str) -> String {
// Serialized in sorted key order, so REDUCING_FULL_NAMES precedes SPEC_SHAKING_V2.
const ENV_VARS: &str = concat!(
"SOROBAN_SDK_BUILD_SYSTEM_SUPPORTS_REDUCING_FULL_NAMES=1 ",
"SOROBAN_SDK_BUILD_SYSTEM_SUPPORTS_SPEC_SHAKING_V2=1"
);
let cargo_home = home::cargo_home().unwrap();
let registry_prefix = cargo_home.join("registry").join("src");
let registry_prefix = registry_prefix.display().to_string();
#[cfg(windows)]
let registry_prefix = registry_prefix.replace('\\', "/");
let vec: Vec<_> = if env::var("RUSTFLAGS").is_ok() {
expected
.split('\n')
.map(|x| format!("{ENV_VARS} {x}"))
.collect()
} else {
expected
.split('\n')
.map(|x| {
let rustflags_value = format!("--remap-path-prefix={registry_prefix}=");
let escaped_value = escape(std::borrow::Cow::Borrowed(&rustflags_value));
format!("CARGO_BUILD_RUSTFLAGS={escaped_value} {ENV_VARS} {x}")
})
.collect()
};
format!(
"\
{}
",
vec.join("\n")
)
}
// Test that bins don't contain absolute paths to the local crate registry.
//
// See make_rustflags_to_remap_absolute_paths
#[test]
#[ignore = "TODO https://github.com/stellar/stellar-cli/issues/1867"]
fn remap_absolute_paths() {
#[derive(Eq, PartialEq, Copy, Clone)]
enum Remap {
Yes,
No,
}
fn run(contract_name: &str, manifest_path: &std::path::Path, remap: Remap) -> bool {
let sandbox_remap = TestEnv::default();
let mut cmd = sandbox_remap.new_assert_cmd("contract");
if remap == Remap::No {
// This will prevent stellar-cli from setting CARGO_BUILD_RUSTFLAGS,
// and removing absolute paths.
// See docs for `make_rustflags_to_remap_absolute_paths`.
cmd.env("RUSTFLAGS", "");
}
cmd.current_dir(manifest_path)
.arg("build")
.assert()
.success();
let wasm_path = manifest_path
.join("target/wasm32v1-none/release")
.join(format!("{contract_name}.wasm"));
let cargo_home = home::cargo_home().unwrap();
let registry_prefix = format!("{}/registry/src/", cargo_home.display());
let wasm_buf = std::fs::read(wasm_path).unwrap();
let wasm_str = String::from_utf8_lossy(&wasm_buf);
wasm_str.contains(®istry_prefix)
}
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/eth_abi/");
// The eth_abi example is known to exhibit this problem.
// Compile it both with and without path remapping to verify.
let remap_has_abs_paths = run("soroban_eth_abi", &fixture_path, Remap::Yes);
let noremap_has_abs_paths = run("soroban_eth_abi", &fixture_path, Remap::No);
assert!(!remap_has_abs_paths);
assert!(noremap_has_abs_paths);
}
#[test]
fn build_no_error_for_workspace() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace");
let temp = TempDir::new().unwrap();
let dir_path = temp.path();
fs_extra::dir::copy(fixture_path, dir_path, &CopyOptions::new()).unwrap();
let dir_path = dir_path.join("workspace");
// By default, workspace TOML has overflow-checks = true
sandbox
.new_assert_cmd("contract")
.current_dir(&dir_path)
.arg("build")
.assert()
.success();
}
#[test]
fn build_no_error_for_package() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace/contracts/add/add2");
let temp = TempDir::new().unwrap();
let dir_path = temp.path();
fs_extra::dir::copy(fixture_path, dir_path, &CopyOptions::new()).unwrap();
let dir_path = dir_path.join("add2");
// By default, this TOML does not specify overflow-checks, add it
let cargo_toml_path = dir_path.join("Cargo.toml");
let cargo_toml_path_content = std::fs::read_to_string(&cargo_toml_path).unwrap();
let modified_cargo_toml_content =
format!("{cargo_toml_path_content}\n[profile.release]\noverflow-checks = true\n");
std::fs::write(&cargo_toml_path, modified_cargo_toml_content).unwrap();
sandbox
.new_assert_cmd("contract")
.current_dir(&dir_path)
.arg("build")
.assert()
.success();
}
#[test]
fn build_errors_when_overflow_checks_false() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace");
let temp = TempDir::new().unwrap();
let dir_path = temp.path();
fs_extra::dir::copy(fixture_path, dir_path, &CopyOptions::new()).unwrap();
let dir_path = dir_path.join("workspace");
// Replace overflow-checks = true with false in workspace Cargo.toml
let cargo_toml_path = dir_path.join("Cargo.toml");
let cargo_toml_content = std::fs::read_to_string(&cargo_toml_path).unwrap();
let modified_content =
cargo_toml_content.replace("overflow-checks = true", "overflow-checks = false");
std::fs::write(&cargo_toml_path, modified_content).unwrap();
sandbox
.new_assert_cmd("contract")
.current_dir(&dir_path)
.arg("build")
.assert()
.failure()
.stderr(predicate::str::contains(
"`overflow-checks` is not enabled for profile `release`",
));
}
#[test]
fn build_errors_when_overflow_checks_missing() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace");
let temp = TempDir::new().unwrap();
let dir_path = temp.path();
fs_extra::dir::copy(fixture_path, dir_path, &CopyOptions::new()).unwrap();
let dir_path = dir_path.join("workspace");
// Remove overflow-checks line from workspace Cargo.toml
let cargo_toml_path = dir_path.join("Cargo.toml");
let cargo_toml_content = std::fs::read_to_string(&cargo_toml_path).unwrap();
let modified_content = cargo_toml_content
.replace("overflow-checks = true\r\n", "")
.replace("overflow-checks = true\n", "");
std::fs::write(&cargo_toml_path, modified_content).unwrap();
sandbox
.new_assert_cmd("contract")
.current_dir(&dir_path)
.arg("build")
.assert()
.failure()
.stderr(predicate::str::contains(
"`overflow-checks` is not enabled for profile `release`",
));
}
#[test]
fn build_errors_when_package_overflow_checks_missing() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace/contracts/add/add2");
let temp = TempDir::new().unwrap();
let dir_path = temp.path();
fs_extra::dir::copy(fixture_path, dir_path, &CopyOptions::new()).unwrap();
let dir_path = dir_path.join("add2");
// By default, this TOML does not specify overflow-checks
sandbox
.new_assert_cmd("contract")
.current_dir(&dir_path)
.arg("build")
.assert()
.failure()
.stderr(predicate::str::contains(
"`overflow-checks` is not enabled for profile `release`",
));
}
#[test]
fn build_errors_when_overflow_check_only_applied_to_members() {
let sandbox = TestEnv::default();
let cargo_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let fixture_path = cargo_dir.join("tests/fixtures/workspace");
let temp = TempDir::new().unwrap();
let dir_path = temp.path();
fs_extra::dir::copy(fixture_path, dir_path, &CopyOptions::new()).unwrap();
let dir_path = dir_path.join("workspace");
// Remove overflow-checks line from workspace Cargo.toml
let cargo_toml_path = dir_path.join("Cargo.toml");
let cargo_toml_content = std::fs::read_to_string(&cargo_toml_path).unwrap();
let modified_content = cargo_toml_content
.replace("overflow-checks = true\r\n", "")
.replace("overflow-checks = true\n", "");
std::fs::write(&cargo_toml_path, modified_content).unwrap();
// Add overflow-checks = true to "add" member
let member_cargo_toml_path = dir_path.join("contracts").join("add").join("Cargo.toml");
let member_cargo_toml_content = std::fs::read_to_string(&member_cargo_toml_path).unwrap();
let modified_member_content =
format!("{member_cargo_toml_content}\n[profile.release]\noverflow-checks = true\n");
std::fs::write(&member_cargo_toml_path, modified_member_content).unwrap();
// Add overflow-checks = true to "add2" member
let member_2_cargo_toml_path = dir_path
.join("contracts")
.join("add")
.join("add2")
.join("Cargo.toml");
let member_2_cargo_toml_content = std::fs::read_to_string(&member_2_cargo_toml_path).unwrap();
let modified_member_2_content =
format!("{member_2_cargo_toml_content}\n[profile.release]\noverflow-checks = true\n");
std::fs::write(&member_2_cargo_toml_path, modified_member_2_content).unwrap();
sandbox
.new_assert_cmd("contract")
.current_dir(&dir_path)
.arg("build")
.assert()
.failure()
.stderr(predicate::str::contains(
"`overflow-checks` is not enabled for profile `release`",
));
}
#[test]