-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathconfig.rs
More file actions
2172 lines (1932 loc) · 69.4 KB
/
Copy pathconfig.rs
File metadata and controls
2172 lines (1932 loc) · 69.4 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 crate::test::{
BacktraceMode, CoverageFormat, MutationDiffMode, MutationLevel, ReportFormat, TestConfig,
};
use anyhow::{Result, anyhow};
use path_absolutize::Absolutize;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::{Arc, OnceLock};
pub use ton_networks::{CustomNetworkUrls, Network};
static MANIFEST_PATH: OnceLock<PathBuf> = OnceLock::new();
static PROJECT_ROOT: OnceLock<PathBuf> = OnceLock::new();
static MANIFEST_PATH_SOURCE: OnceLock<ResolutionSource> = OnceLock::new();
static PROJECT_ROOT_SOURCE: OnceLock<ResolutionSource> = OnceLock::new();
pub const DEFAULT_PROJECT_MAPPINGS: &[(&str, &str)] = &[
("acton", ".acton"),
("contracts", "contracts"),
("tests", "tests"),
("wrappers", "wrappers"),
("gen", "gen"),
];
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum ResolutionSource {
ProjectRootFlag,
ManifestPathFlag,
AutoDetected,
FallbackCwd,
}
impl ResolutionSource {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::ProjectRootFlag => "--project-root",
Self::ManifestPathFlag => "--manifest-path",
Self::AutoDetected => "auto-detected",
Self::FallbackCwd => "fallback-cwd",
}
}
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ResolvedPathsDiagnostics {
pub project_root: PathBuf,
pub manifest_path: PathBuf,
pub project_root_source: ResolutionSource,
pub manifest_path_source: ResolutionSource,
}
#[derive(clap::ValueEnum, Debug, Copy, Clone)]
pub enum Explorer {
Tonscan,
Toncx,
Dton,
Tonviewer,
}
/// Output format for `acton check` diagnostics
#[derive(
clap::ValueEnum, Debug, Clone, Serialize, Deserialize, JsonSchema, Hash, Eq, PartialEq, Default,
)]
#[serde(rename_all = "kebab-case")]
pub enum CheckOutputFormat {
/// Human-readable plain output
#[default]
Plain,
/// Structured JSON output
Json,
/// SARIF output for code scanning tools
Sarif,
/// GitHub workflow command output
Github,
/// GitLab code quality output
Gitlab,
}
/// How a compiled dependency is linked into a contract
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Hash, Eq, PartialEq, Default)]
pub enum DependencyKind {
/// Embed dependency code directly into the output
#[serde(rename = "embed_code")]
#[default]
EmbedCode,
/// Reference the dependency as an on-chain library
#[serde(rename = "library_ref")]
LibraryRef,
}
/// Dependency declaration for a contract
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Hash, Eq, PartialEq)]
#[serde(untagged)]
pub enum ContractDependency {
/// Name of the contract to depend on in the simple form
Simple(String),
/// Detailed dependency configuration
Detailed {
/// Name of the contract to depend on
name: String,
#[serde(default)]
/// Dependency type
kind: DependencyKind,
/// Custom name for the generated code function
function: Option<String>,
/// Project-relative custom output path for the generated code file
path: Option<String>,
},
}
/// `TonCenter` API endpoints for a custom network
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(deny_unknown_fields)]
pub struct CustomNetworkApiConfig {
/// The URL for the `TonCenter` API v2. For localnet this defaults to
/// `http://localhost:<localnet.port>/api/v2` with `5411` as the fallback port
pub v2: Option<String>,
/// The URL for the `TonCenter` API v3. For localnet this defaults to
/// `http://localhost:<localnet.port>/api/v3` with `5411` as the fallback port
pub v3: Option<String>,
}
/// Custom network configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(deny_unknown_fields)]
pub struct CustomNetworkConfig {
/// Base URL used to build transaction links for this network. Acton appends
/// `/tx/<hash>` automatically and derives links from `api.v2` when omitted
pub explorer: Option<String>,
/// `TonCenter` API endpoints for this network
pub api: Option<CustomNetworkApiConfig>,
}
/// JSON schema for Acton.toml configuration file
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[schemars(title = "Acton Configuration Schema")]
pub struct ActonConfig {
/// Package metadata for the Acton project
pub package: PackageConfig,
/// Required versions for project-level tooling
pub toolchain: Option<ToolchainConfig>,
/// Definition of contracts in the project
pub contracts: Option<ContractsConfig>,
/// Default settings for the test runner
pub test: Option<TestSettings>,
/// Linter configuration for the project
pub lint: Option<LintConfig>,
/// Settings for the Tolk code formatter
pub fmt: Option<FmtSettings>,
/// Default settings for the build command
pub build: Option<BuildSettings>,
/// Default settings for wrapper generation
pub wrappers: Option<WrappersConfig>,
/// Default settings for `acton localnet` commands
pub localnet: Option<LocalnetSettings>,
/// Custom scripts that can be run with `acton run`
pub scripts: Option<BTreeMap<String, String>>,
#[serde(skip)] // we build wallets manually
pub wallets: Option<WalletsConfig>,
#[serde(skip)] // we build libraries manually
pub libraries: Option<LibrariesConfig>,
/// Import path mappings for Tolk compiler imports, for example mapping
/// `"core" = "./foo/core"` so imports can use `@core/...`
#[serde(rename = "import-mappings")]
#[schemars(rename = "import-mappings")]
pub mappings: Option<BTreeMap<String, String>>,
/// Custom network configurations
pub networks: Option<BTreeMap<String, CustomNetworkConfig>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LibrariesConfig {
#[serde(flatten)]
pub libraries: BTreeMap<String, LibraryConfig>,
}
impl JsonSchema for LibrariesConfig {
fn schema_name() -> String {
"LibrariesConfig".to_string()
}
fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
<BTreeMap<String, LibraryConfig>>::json_schema(generator)
}
}
/// A deployed library entry from `libraries.toml`
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct LibraryConfig {
/// Logical library name
pub name: String,
/// Library hash
pub hash: String,
/// Library code encoded as BOC
pub code: String,
/// Account address that stores the library
pub account: String,
/// Remaining deployment duration in seconds
pub duration: u64,
/// Network where the library is deployed
pub network: Network,
/// Initial deployment timestamp
pub timestamp: String,
/// Last top-up timestamp
pub last_topup_timestamp: String,
/// Number of bits in the serialized library cell tree
pub bits: u64,
/// Number of cells in the serialized library cell tree
pub cells: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
pub struct LibrariesFile {
pub libraries: Option<LibrariesConfig>,
}
/// Package metadata for the Acton project
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct PackageConfig {
/// The name of the project
pub name: String,
/// A short description of the project
pub description: String,
/// The current version of the project
pub version: String,
/// The URL of the project's repository
pub repository: Option<String>,
/// The project's license identifier
pub license: Option<String>,
}
/// Required versions for project-level tooling
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "kebab-case")]
pub struct ToolchainConfig {
/// Acton CLI version required by this project
pub acton: Option<String>,
}
/// Coverage settings for the test runner
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "kebab-case")]
pub struct TestCoverageSettings {
/// Enable code coverage reporting
pub enabled: Option<bool>,
/// Format for coverage reports
#[schemars(with = "Option<CoverageFormat>")]
#[schemars(default = "default_test_coverage_format")]
pub format: Option<String>,
/// Path to save the coverage report
pub output_file: Option<String>,
/// Minimum total line coverage percentage required for a non-UI coverage run
pub minimum_percent: Option<f64>,
/// Include files from the `@wrappers` mapping in coverage reports
pub include_wrappers: Option<bool>,
/// Include `.test.tolk` files in coverage reports
pub include_tests: Option<bool>,
}
/// Fuzz settings for parameterized tests marked with dotted `@test.fuzz`
/// annotations: `@test.fuzz`, `@test.fuzz(<runs>)`, or `@test.fuzz({ ... })`
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "kebab-case")]
pub struct TestFuzzSettings {
/// Number of accepted fuzz cases to execute for each fuzz test
pub runs: Option<usize>,
/// Maximum number of rejected inputs from `assume(...)` before the test fails
pub max_test_rejects: Option<usize>,
/// Seed used for reproducible fuzz input generation
pub seed: Option<u64>,
}
/// Default settings for the test runner
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "kebab-case")]
pub struct TestSettings {
/// Regex pattern to filter test names
pub filter: Option<String>,
/// List of test reporters to use
#[schemars(with = "Option<Vec<ReportFormat>>")]
pub reporter: Option<Vec<String>>,
/// Enable debug mode for tests
pub debug: Option<bool>,
/// Port for the debug server
#[schemars(default = "default_test_debug_port", range(max = 65535))]
pub debug_port: Option<u16>,
/// Enable stack traces for failed tests
#[schemars(with = "Option<BacktraceMode>")]
pub backtrace: Option<String>,
/// Coverage settings for test runs
pub coverage: Option<TestCoverageSettings>,
/// Default fuzz settings for parameterized tests
pub fuzz: Option<TestFuzzSettings>,
/// Glob patterns to exclude from testing
pub exclude: Option<Vec<String>>,
/// Glob patterns to include in testing
pub include: Option<Vec<String>>,
/// Directory for `JUnit` XML reports
pub junit_path: Option<String>,
/// Merge all test suites into a single `JUnit` file
pub junit_merge: Option<bool>,
/// Network to fork for testing
#[schemars(with = "Option<Network>")]
pub fork_net: Option<String>,
/// Specific block number to fork from
pub fork_block_number: Option<u64>,
/// Configuration for mutation testing
pub mutation: Option<MutationConfig>,
/// Stop test execution after the first failure
pub fail_fast: Option<bool>,
/// Exit with a non-zero code when profiling differs from baseline
pub fail_on_diff: Option<bool>,
/// Enable the test UI server
pub ui: Option<bool>,
/// Port for the test UI server
#[schemars(range(max = 65535))]
pub ui_port: Option<u16>,
#[schemars(with = "BTreeMap<String, serde_json::Value>")]
#[serde(flatten)]
pub metadata: BTreeMap<String, toml::Value>,
}
const fn default_test_debug_port() -> Option<u16> {
Some(12345)
}
fn default_test_coverage_format() -> Option<String> {
Some("lcov".to_string())
}
/// Lint severity level
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum LintLevel {
/// Disable the rule
Allow,
/// Emit warnings for the rule
Warn,
/// Treat the rule as an error
Deny,
}
/// Lint rule configuration, either a global level or contract-specific overrides
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(untagged)]
pub enum LintEntry {
/// Global lint level for a rule
Level(LintLevel),
/// Contract-specific lint overrides
Config(BTreeMap<String, LintLevel>),
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LintRules {
#[serde(flatten)]
pub entries: BTreeMap<String, LintEntry>,
}
impl JsonSchema for LintRules {
fn schema_name() -> String {
"LintRules".to_string()
}
fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
<BTreeMap<String, LintEntry>>::json_schema(generator)
}
}
const fn default_max_warnings() -> usize {
usize::MAX
}
#[allow(clippy::trivially_copy_pass_by_ref)]
const fn is_default_max_warnings(v: &usize) -> bool {
*v == default_max_warnings()
}
/// Linter configuration for the project
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub struct LintConfig {
/// Glob patterns for files to exclude from lint diagnostics
pub exclude: Option<Vec<String>>,
#[serde(
default = "default_max_warnings",
skip_serializing_if = "is_default_max_warnings"
)]
/// Maximum allowed warning count before `acton check` exits with a non-zero code
pub max_warnings: usize,
/// Output format for `acton check` diagnostics
pub output_format: Option<CheckOutputFormat>,
/// Lint rules and contract-specific overrides
pub rules: Option<LintRules>,
#[schemars(with = "BTreeMap<String, serde_json::Value>")]
#[serde(flatten)]
pub metadata: BTreeMap<String, toml::Value>,
}
impl Default for LintConfig {
fn default() -> Self {
Self {
exclude: None,
max_warnings: default_max_warnings(),
output_format: None,
rules: None,
metadata: BTreeMap::new(),
}
}
}
/// Settings for the Tolk code formatter
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "kebab-case")]
pub struct FmtSettings {
/// Maximum line width for formatting
#[schemars(default = "default_fmt_width")]
pub width: Option<usize>,
/// Glob patterns to ignore from formatting
pub ignore: Option<Vec<String>>,
/// Insert an empty line between import groups (`@stdlib`, `@acton`, `@<other>`, `../`, `./`)
#[schemars(default = "default_fmt_separate_import_groups")]
pub separate_import_groups: Option<bool>,
}
const fn default_fmt_width() -> Option<usize> {
Some(100)
}
const fn default_fmt_separate_import_groups() -> Option<bool> {
Some(false)
}
/// Default settings for the build command
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "kebab-case")]
pub struct BuildSettings {
/// Project-relative directory where JSON build artifacts are saved
pub out_dir: Option<String>,
/// Project-relative directory where generated dependency files are saved
pub gen_dir: Option<String>,
/// Project-relative directory where per-contract ABI JSON files are saved
pub output_abi: Option<String>,
/// Project-relative directory where per-contract compiled Fift files are saved
pub output_fift: Option<String>,
}
/// Default settings for wrapper generation
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
pub struct WrappersConfig {
/// Default settings for Tolk wrapper generation
pub tolk: Option<TolkWrapperSettings>,
/// Default settings for TypeScript wrapper generation
pub typescript: Option<TypescriptWrapperSettings>,
}
/// Default settings for Tolk wrapper generation
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "kebab-case")]
pub struct TolkWrapperSettings {
/// Project-relative directory where `acton wrapper` writes generated Tolk wrappers by default
pub output_dir: Option<String>,
/// Generate a Tolk test stub by default for `acton wrapper`
pub generate_test: Option<bool>,
/// Project-relative directory where generated Tolk test stubs are written by default
pub test_output_dir: Option<String>,
}
/// Default settings for TypeScript wrapper generation
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "kebab-case")]
pub struct TypescriptWrapperSettings {
/// Project-relative directory where `acton wrapper --ts` writes generated TypeScript wrappers by default
pub output_dir: Option<String>,
}
/// Default settings for `acton localnet` commands
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "kebab-case")]
pub struct LocalnetSettings {
/// Localnet port used by `acton localnet` commands
#[schemars(default = "default_localnet_port", range(max = 65535))]
pub port: Option<u16>,
/// Network to fork from used by `acton localnet start`
#[schemars(with = "Option<Network>")]
pub fork_net: Option<String>,
/// Block sequence number used by `acton localnet start` when forking from historical state
pub fork_block_number: Option<u64>,
/// Wallet names from `[wallets]` that are automatically funded and deployed on
/// `acton localnet start`
pub accounts: Option<Vec<String>>,
/// Maximum number of API requests per second served by `Localnet` `/api` endpoints
pub rate_limit: Option<u32>,
}
const fn default_localnet_port() -> Option<u16> {
Some(3000)
}
/// Configuration for mutation testing
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "kebab-case")]
pub struct MutationConfig {
/// List of mutation rules to disable
pub disable_rules: Option<Vec<String>>,
/// Path to a JSON file with custom query-based mutation rules
pub rules_file: Option<String>,
/// List of mutation levels to run
pub mutation_levels: Option<Vec<MutationLevel>>,
/// Minimum mutation score percentage required for the run to succeed
pub minimum_percent: Option<f64>,
/// Diff scope used to limit mutation testing to changed lines
pub diff: Option<MutationDiffMode>,
/// Base ref used by diff-based mutation testing modes
pub diff_ref: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ContractsConfig {
#[serde(flatten)]
pub contracts: BTreeMap<String, ContractConfig>,
}
impl JsonSchema for ContractsConfig {
fn schema_name() -> String {
"ContractsConfig".to_string()
}
fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
<BTreeMap<String, ContractConfig>>::json_schema(generator)
}
}
/// Wallet seed sources
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct WalletKeys {
/// Environment variable that contains the wallet mnemonic
#[serde(rename = "mnemonic-env")]
pub mnemonic_env: Option<String>,
/// File path that stores the wallet mnemonic
#[serde(rename = "mnemonic-file")]
pub mnemonic_file: Option<String>,
/// Wallet mnemonic stored directly in the config
pub mnemonic: Option<String>,
/// Keyring entry that stores the wallet mnemonic
#[serde(rename = "mnemonic-keyring")]
pub mnemonic_keyring: Option<String>,
}
/// Expected wallet addresses for different networks
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct WalletExpectedAddresses {
/// Expected mainnet address
#[serde(rename = "address-mainnet")]
pub address_mainnet: Option<String>,
/// Expected testnet address
#[serde(rename = "address-testnet")]
pub address_testnet: Option<String>,
}
/// Wallet configuration entry
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct WalletConfig {
/// Wallet contract type
pub kind: String,
/// Workchain for the wallet address
pub workchain: Option<i32>,
/// Mnemonic and key storage configuration
pub keys: WalletKeys,
#[serde(default)]
/// Expected wallet addresses for supported networks
pub expected: Option<WalletExpectedAddresses>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct WalletsConfig {
#[serde(flatten)]
pub wallets: BTreeMap<String, WalletConfig>,
}
impl JsonSchema for WalletsConfig {
fn schema_name() -> String {
"WalletsConfig".to_string()
}
fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
<BTreeMap<String, WalletConfig>>::json_schema(generator)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
pub struct WalletsFile {
pub wallets: Option<WalletsConfig>,
}
/// Definition of a contract in the project
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Default)]
pub struct ContractConfig {
/// Human-readable display name of the contract
#[serde(rename = "display-name", skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Path to the contract source (`.tolk`) or precompiled (`.boc`) file
pub src: String,
/// Dependencies of this contract
pub depends: Option<Vec<ContractDependency>>,
/// Project-relative path where the compiled `.boc` should be saved
pub output: Option<String>,
}
impl Default for ActonConfig {
fn default() -> Self {
Self {
package: PackageConfig {
name: "my-acton-project".to_string(),
description: "A TON blockchain project".to_string(),
version: "0.1.0".to_string(),
repository: None,
license: Some("MIT".to_string()),
},
toolchain: None,
test: None,
lint: None,
contracts: None,
fmt: Some(FmtSettings {
width: Some(100),
ignore: Some(vec![]),
separate_import_groups: None,
}),
build: None,
wrappers: None,
localnet: None,
wallets: None,
libraries: None,
scripts: None,
mappings: None,
networks: None,
}
}
}
impl std::fmt::Display for ContractDependency {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ContractDependency::Simple(name) | ContractDependency::Detailed { name, .. } => {
write!(f, "{name}")
}
}
}
}
impl ContractDependency {
#[must_use]
pub fn name(&self) -> &str {
match self {
ContractDependency::Simple(name) | ContractDependency::Detailed { name, .. } => name,
}
}
#[must_use]
pub fn kind(&self) -> DependencyKind {
match self {
ContractDependency::Simple(_) => DependencyKind::EmbedCode,
ContractDependency::Detailed { kind, .. } => kind.clone(),
}
}
#[must_use]
pub fn compiled_code_function(&self) -> Option<&str> {
match self {
ContractDependency::Simple(_) => None,
ContractDependency::Detailed { function, .. } => function.as_deref(),
}
}
#[must_use]
pub fn compiled_code_out_path(&self) -> Option<&str> {
match self {
ContractDependency::Simple(_) => None,
ContractDependency::Detailed { path, .. } => path.as_deref(),
}
}
}
impl ContractConfig {
#[must_use]
pub fn display_name<'a>(&'a self, contract_id: &'a str) -> &'a str {
self.name
.as_deref()
.filter(|name| !name.is_empty())
.unwrap_or(contract_id)
}
#[must_use]
pub fn dependency_names(&self) -> Vec<&str> {
self.depends
.as_ref()
.map(|deps| deps.iter().map(ContractDependency::name).collect())
.unwrap_or_default()
}
#[must_use]
pub fn get_dependency(&self, name: &str) -> Option<&ContractDependency> {
self.depends.as_ref()?.iter().find(|dep| dep.name() == name)
}
/// Returns the contract source path resolved relative to the project root.
/// If `src` is already absolute, it is returned as-is.
#[must_use]
pub fn absolute_source_path(&self, project_root: &Path) -> PathBuf {
match Path::new(&self.src).absolutize_from(project_root) {
Ok(path) => path.into_owned(),
Err(_) => Path::new(self.src.as_str()).to_path_buf(),
}
}
}
impl ActonConfig {
pub fn load_manifest() -> Result<Self> {
let config_path = manifest_path();
if !config_path.exists() {
return Err(anyhow!(
"Acton.toml not found. Run 'acton init' to initialize Acton in the project."
));
}
let content = fs::read_to_string(config_path)?;
Ok(toml::from_str(&content)?)
}
pub fn load_wallets() -> Result<WalletsConfig> {
// Merge wallets from different sources
// Order of importance (later overrides earlier):
// 1. Global ~/.config/acton/wallets/global.wallets.toml
// 2. Local wallets.toml
let mut merged_wallets = BTreeMap::new();
// 1. Load global wallets
if let Some(global_path) = global_wallets_path()
&& global_path.exists()
{
let global_content = fs::read_to_string(&global_path)?;
let global_wallets: WalletsFile = toml::from_str(&global_content)?;
if let Some(wallets) = global_wallets.wallets {
for (name, wallet) in wallets.wallets {
merged_wallets.insert(name, wallet);
}
}
}
// 2. Load local wallets.toml
let local_wallets_path = project_root().join("wallets.toml");
if local_wallets_path.exists() {
let local_content = fs::read_to_string(local_wallets_path)?;
let local_wallets: WalletsFile = toml::from_str(&local_content)?;
if let Some(wallets) = local_wallets.wallets {
for (name, wallet) in wallets.wallets {
merged_wallets.insert(name, wallet);
}
}
}
Ok(WalletsConfig {
wallets: merged_wallets,
})
}
pub fn load() -> Result<Self> {
let mut config = Self::load_manifest()?;
config.wallets = Some(Self::load_wallets()?);
// Merge libraries from different sources
let mut merged_libraries = BTreeMap::new();
// 1. Load global libraries
if let Some(global_path) = global_libraries_path()
&& global_path.exists()
{
let global_content = fs::read_to_string(&global_path)?;
let global_libraries: LibrariesFile = toml::from_str(&global_content)?;
if let Some(libraries) = global_libraries.libraries {
for (name, library) in libraries.libraries {
merged_libraries.insert(name, library);
}
}
}
// 2. Load local libraries.toml
let local_libraries_path = project_root().join("libraries.toml");
if local_libraries_path.exists() {
let local_content = fs::read_to_string(local_libraries_path)?;
let local_libraries: LibrariesFile = toml::from_str(&local_content)?;
if let Some(libraries) = local_libraries.libraries {
for (name, library) in libraries.libraries {
merged_libraries.insert(name, library);
}
}
}
config.libraries = Some(LibrariesConfig {
libraries: merged_libraries,
});
Ok(config)
}
pub fn save(&self) -> Result<()> {
let content = toml::to_string_pretty(self)?;
fs::write("Acton.toml", content)?;
Ok(())
}
#[must_use]
pub fn contracts(&self) -> Option<&BTreeMap<String, ContractConfig>> {
self.contracts.as_ref().map(|c| &c.contracts)
}
#[must_use]
pub fn get_contract(&self, name: &str) -> Option<&ContractConfig> {
self.contracts.as_ref()?.contracts.get(name)
}
#[must_use]
pub fn wallets(&self) -> Option<&BTreeMap<String, WalletConfig>> {
self.wallets.as_ref().map(|w| &w.wallets)
}
#[must_use]
pub fn get_wallet(&self, name: &str) -> Option<&WalletConfig> {
self.wallets.as_ref()?.wallets.get(name)
}
#[must_use]
pub fn libraries(&self) -> Option<&BTreeMap<String, LibraryConfig>> {
self.libraries.as_ref().map(|l| &l.libraries)
}
#[must_use]
pub fn get_library(&self, name: &str) -> Option<&LibraryConfig> {
self.libraries.as_ref()?.libraries.get(name)
}
#[must_use]
pub fn tolk_wrapper_output_dir(&self) -> Option<&str> {
self.wrappers.as_ref()?.tolk.as_ref()?.output_dir.as_deref()
}
#[must_use]
pub fn tolk_wrapper_generate_test(&self) -> bool {
self.wrappers
.as_ref()
.and_then(|wrappers| wrappers.tolk.as_ref())
.and_then(|tolk| tolk.generate_test)
.unwrap_or(false)
}
#[must_use]
pub fn tolk_wrapper_test_output_dir(&self) -> Option<&str> {
self.wrappers
.as_ref()?
.tolk
.as_ref()?
.test_output_dir
.as_deref()
}
#[must_use]
pub fn typescript_wrapper_output_dir(&self) -> Option<&str> {
self.wrappers
.as_ref()?
.typescript
.as_ref()?
.output_dir
.as_deref()
}
#[must_use]
pub fn custom_networks(&self) -> HashMap<String, CustomNetworkUrls> {
let mut result = HashMap::new();
let localnet_port = self
.localnet
.as_ref()
.and_then(|cfg| cfg.port)
.unwrap_or(5411);
let default_localnet_v2 = format!("http://localhost:{localnet_port}/api/v2");
let default_localnet_v3 = format!("http://localhost:{localnet_port}/api/v3");
let localnet_config = self
.networks
.as_ref()
.and_then(|networks| networks.get("localnet"));
let localnet_v2 = localnet_config
.and_then(|config| config.api.as_ref())
.and_then(|api| api.v2.as_deref())
.unwrap_or(default_localnet_v2.as_str());
let localnet_v3 = localnet_config
.and_then(|config| config.api.as_ref())
.and_then(|api| api.v3.as_deref())
.unwrap_or(default_localnet_v3.as_str());
result.insert(
"localnet".to_string(),
CustomNetworkUrls {
v2_url: Arc::from(localnet_v2.trim_end_matches('/')),
v3_url: Some(Arc::from(localnet_v3.trim_end_matches('/'))),
explorer_url: localnet_config
.and_then(|config| config.explorer.as_ref())
.map(|s| Arc::from(s.trim_end_matches('/'))),
},
);
if let Some(networks) = &self.networks {
for (name, config) in networks {
if name == "localnet" {
continue;
}
let Some(v2_url) = config
.api
.as_ref()
.and_then(|api| api.v2.as_ref())
.map(String::as_str)
else {
continue;
};
result.insert(
name.clone(),
CustomNetworkUrls {
v2_url: Arc::from(v2_url.trim_end_matches('/')),
v3_url: config
.api
.as_ref()
.and_then(|api| api.v3.as_ref())
.map(|s| Arc::from(s.trim_end_matches('/'))),
explorer_url: config
.explorer
.as_ref()
.map(|s| Arc::from(s.trim_end_matches('/'))),
},
);
}
}
result
}
#[must_use]
pub fn mappings(&self) -> Option<BTreeMap<String, String>> {
normalize_mappings(&self.mappings, project_root())
}
pub fn ensure_default_mappings(&mut self) -> bool {
let mappings = self.mappings.get_or_insert_with(default_project_mappings);
let mut changed = false;
for (prefix, target) in DEFAULT_PROJECT_MAPPINGS {
if !mappings.contains_key(*prefix) {
mappings.insert((*prefix).to_string(), (*target).to_string());
changed = true;
}
}
changed
}
}
#[must_use]
pub fn default_project_mappings() -> BTreeMap<String, String> {
DEFAULT_PROJECT_MAPPINGS
.iter()
.map(|(prefix, target)| ((*prefix).to_string(), (*target).to_string()))
.collect()
}
#[must_use]
pub fn manifest_path() -> &'static Path {
MANIFEST_PATH
.get_or_init(|| {
let (root, manifest) = default_project_root_and_manifest_path();
let _ = PROJECT_ROOT.set(root);
let _ = PROJECT_ROOT_SOURCE.set(ResolutionSource::FallbackCwd);
let _ = MANIFEST_PATH_SOURCE.set(ResolutionSource::FallbackCwd);
manifest
})
.as_path()
}
#[must_use]
pub fn project_root() -> &'static Path {
PROJECT_ROOT
.get_or_init(|| {
let (root, manifest) = default_project_root_and_manifest_path();
let _ = MANIFEST_PATH.set(manifest);
let _ = MANIFEST_PATH_SOURCE.set(ResolutionSource::FallbackCwd);
let _ = PROJECT_ROOT_SOURCE.set(ResolutionSource::FallbackCwd);
root
})