multiversx_sc_meta_lib/contract/sc_config/
contract_variant_builder.rs

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
use core::panic;
use multiversx_sc::abi::{ContractAbi, EndpointAbi};
use std::{
    collections::{BTreeSet, HashMap, HashSet},
    fs,
    path::{Path, PathBuf},
};

use crate::ei::parse_check_ei;

use super::{
    contract_variant_settings::{parse_allocator, parse_stack_size},
    proxy_config::ProxyConfig,
    sc_config_model::SC_CONFIG_FILE_NAMES,
    ContractVariant, ContractVariantProfile, ContractVariantSerde, ContractVariantSettings,
    ProxyConfigSerde, ScConfig, ScConfigSerde,
};

/// Temporary structure, to help create instances of `ContractVariant`. Not publicly exposed.
struct ContractVariantBuilder {
    pub contract_id: String,
    pub explicit_name: String,
    pub add_unlabelled: bool,
    pub add_labels: BTreeSet<String>,
    pub add_endpoints: BTreeSet<String>,
    pub collected_endpoints: Vec<EndpointAbi>,
    endpoint_names: HashSet<String>, // help keep endpoints unique
    pub settings: ContractVariantSettings,
}

impl Default for ContractVariantBuilder {
    fn default() -> Self {
        Self {
            contract_id: Default::default(),
            explicit_name: Default::default(),
            add_unlabelled: true,
            add_labels: Default::default(),
            add_endpoints: Default::default(),
            collected_endpoints: Default::default(),
            endpoint_names: Default::default(),
            settings: Default::default(),
        }
    }
}

impl ContractVariantBuilder {
    fn new(id: String) -> Self {
        ContractVariantBuilder {
            contract_id: id.clone(),
            explicit_name: id,
            ..Default::default()
        }
    }

    fn map_from_config(kvp: (&String, &ContractVariantSerde)) -> (String, ContractVariantBuilder) {
        let (contract_id, cms) = kvp;
        let external_view = cms.external_view.unwrap_or_default();
        let mut collected_endpoints = Vec::new();
        if external_view {
            collected_endpoints.push(
                multiversx_sc::external_view_contract::external_view_contract_constructor_abi(),
            )
        }
        let default = ContractVariantBuilder::default();
        (
            contract_id.clone(),
            ContractVariantBuilder {
                contract_id: contract_id.clone(),
                explicit_name: cms.name.clone().unwrap_or(default.explicit_name),
                add_unlabelled: cms.add_unlabelled.unwrap_or(default.add_unlabelled),
                add_labels: cms.add_labels.iter().cloned().collect(),
                add_endpoints: cms.add_endpoints.iter().cloned().collect(),
                collected_endpoints,
                settings: ContractVariantSettings {
                    external_view: cms.external_view.unwrap_or(default.settings.external_view),
                    panic_message: cms.panic_message.unwrap_or(default.settings.panic_message),
                    check_ei: parse_check_ei(&cms.ei),
                    allocator: parse_allocator(&cms.allocator),
                    stack_size: parse_stack_size(&cms.stack_size),
                    features: cms.features.clone(),
                    default_features: cms.default_features,
                    kill_legacy_callback: cms.kill_legacy_callback,
                    profile: ContractVariantProfile::from_serde(&cms.profile),
                },
                ..default
            },
        )
    }

    fn wasm_name(&self) -> &String {
        if !self.explicit_name.is_empty() {
            &self.explicit_name
        } else {
            &self.contract_id
        }
    }

    fn collect_endpoint(&mut self, endpoint_abi: &EndpointAbi) {
        if !self.endpoint_names.contains(&endpoint_abi.name) {
            self.endpoint_names.insert(endpoint_abi.name.clone());
            self.collected_endpoints.push(endpoint_abi.clone());
        }
    }
}

fn process_labels_for_contracts(
    contract_builders: &mut HashMap<String, ContractVariantBuilder>,
    labels_for_contracts: &HashMap<String, Vec<String>>,
) {
    for (label, targets) in labels_for_contracts {
        for target in targets {
            contract_builders
                .entry(target.clone())
                .or_insert_with(|| ContractVariantBuilder::new(target.clone()))
                .add_labels
                .insert(label.clone());
        }
    }
}

fn endpoint_unlabelled(endpoint_abi: &EndpointAbi) -> bool {
    endpoint_abi.labels.is_empty()
}

fn endpoint_matches_labels(endpoint_abi: &EndpointAbi, labels: &BTreeSet<String>) -> bool {
    endpoint_abi
        .labels
        .iter()
        .any(|endpoint_label| labels.contains(endpoint_label))
}

fn collect_unlabelled_endpoints(
    contract_builders: &mut HashMap<String, ContractVariantBuilder>,
    original_abi: &ContractAbi,
) {
    for builder in contract_builders.values_mut() {
        if builder.add_unlabelled {
            for endpoint_abi in original_abi.iter_all_exports() {
                if endpoint_unlabelled(endpoint_abi) {
                    builder.collect_endpoint(endpoint_abi);
                }
            }
        }
    }
}

fn collect_labelled_endpoints(
    contract_builders: &mut HashMap<String, ContractVariantBuilder>,
    original_abi: &ContractAbi,
) {
    for builder in contract_builders.values_mut() {
        for endpoint_abi in original_abi.iter_all_exports() {
            if endpoint_matches_labels(endpoint_abi, &builder.add_labels) {
                builder.collect_endpoint(endpoint_abi);
            }
        }
    }
}

fn collect_add_endpoints(
    contract_builders: &mut HashMap<String, ContractVariantBuilder>,
    original_abi: &ContractAbi,
) {
    for builder in contract_builders.values_mut() {
        for endpoint_abi in original_abi.iter_all_exports() {
            if builder.add_endpoints.contains(&endpoint_abi.name) {
                builder.collect_endpoint(endpoint_abi);
            }
        }
    }
}

fn build_contract_abi(builder: ContractVariantBuilder, original_abi: &ContractAbi) -> ContractAbi {
    let mut constructors = Vec::new();
    let mut upgrade_constructors = Vec::new();
    let mut endpoints = Vec::new();
    let mut promise_callbacks = Vec::new();
    for endpoint_abi in builder.collected_endpoints {
        match endpoint_abi.endpoint_type {
            multiversx_sc::abi::EndpointTypeAbi::Init => constructors.push(endpoint_abi),
            multiversx_sc::abi::EndpointTypeAbi::Upgrade => upgrade_constructors.push(endpoint_abi),
            multiversx_sc::abi::EndpointTypeAbi::Endpoint => endpoints.push(endpoint_abi),
            multiversx_sc::abi::EndpointTypeAbi::PromisesCallback => {
                promise_callbacks.push(endpoint_abi)
            },
        }
    }
    let has_callback = original_abi.has_callback
        && !builder.settings.external_view
        && !builder.settings.kill_legacy_callback;
    ContractAbi {
        build_info: original_abi.build_info.clone(),
        docs: original_abi.docs.clone(),
        name: original_abi.name.clone(),
        constructors,
        upgrade_constructors,
        endpoints,
        promise_callbacks,
        events: original_abi.events.clone(),
        has_callback,
        type_descriptions: original_abi.type_descriptions.clone(),
        esdt_attributes: original_abi.esdt_attributes.clone(),
    }
}

pub(crate) fn default_wasm_crate_name(contract_name: &str) -> String {
    format!("{contract_name}-wasm")
}

fn build_contract(builder: ContractVariantBuilder, original_abi: &ContractAbi) -> ContractVariant {
    let contract_name = builder.wasm_name().clone();
    let wasm_crate_name = default_wasm_crate_name(&contract_name);
    ContractVariant {
        main: false,
        settings: builder.settings.clone(),
        contract_id: builder.contract_id.clone(),
        contract_name,
        wasm_crate_name,
        abi: build_contract_abi(builder, original_abi),
    }
}

fn set_main_contract_flag(
    contracts: &mut [ContractVariant],
    default_contract_config_name_opt: &Option<String>,
) {
    if let Some(default_contract_config_name) = default_contract_config_name_opt {
        for contract in contracts.iter_mut() {
            if &contract.contract_id == default_contract_config_name {
                contract.main = true;
                return;
            }
        }

        panic!(
            "Could not find default contract '{}' among the output contracts. Available contracts are: {:?}",
            default_contract_config_name,
            contracts.iter().map(|contract| &contract.contract_id).collect::<Vec<_>>(),
        )
    } else {
        let first_contract = contracts.get_mut(0).unwrap_or_else(|| {
            panic!("Cannot set default contract because no output contract was specified.")
        });
        first_contract.main = true;
    }
}

fn validate_contract_variants(contracts: &[ContractVariant]) {
    for contract in contracts {
        if contract.main {
            assert!(
                contract.settings.features.is_empty(),
                "features not supported for main contract"
            );
        }
    }
}

fn process_contracts(config: &ScConfigSerde, original_abi: &ContractAbi) -> Vec<ContractVariant> {
    let mut contract_builders: HashMap<String, ContractVariantBuilder> = config
        .contracts
        .iter()
        .map(ContractVariantBuilder::map_from_config)
        .collect();

    collect_and_process_endpoints(
        &mut contract_builders,
        original_abi,
        &config.labels_for_contracts,
    );

    let mut contracts: Vec<ContractVariant> = contract_builders
        .into_values()
        .map(|builder| build_contract(builder, original_abi))
        .collect();

    if contracts.is_empty() {
        contracts.push(ContractVariant::default_from_abi(original_abi));
    }
    set_main_contract_flag(&mut contracts, &config.settings.main);
    validate_contract_variants(&contracts);

    contracts
}

fn process_proxy_contracts(config: &ScConfigSerde, original_abi: &ContractAbi) -> Vec<ProxyConfig> {
    let mut proxy_contracts = Vec::new();

    let main_contract = process_contracts(config, original_abi)
        .into_iter()
        .find(|contract| contract.main)
        .unwrap();

    proxy_contracts.push(ProxyConfig::new_with_default_path(main_contract.abi));

    for proxy_config in &config.proxy {
        let mut contract_builders = HashMap::new();

        match &proxy_config.variant {
            Some(variant) => {
                let setting_contract = config
                    .contracts
                    .iter()
                    .find(|setting| setting.0.eq(variant))
                    .unwrap_or_else(|| panic!("No contact with this name"));
                let (contract_id, mut contract_builder) =
                    ContractVariantBuilder::map_from_config(setting_contract);
                alter_builder_with_proxy_config(proxy_config, &mut contract_builder);

                contract_builders = HashMap::from([(contract_id, contract_builder)]);
            },
            None => {
                let mut contract_builder = ContractVariantBuilder::default();
                alter_builder_with_proxy_config(proxy_config, &mut contract_builder);

                contract_builders.insert(proxy_config.path.clone(), contract_builder);
            },
        }

        collect_and_process_endpoints(
            &mut contract_builders,
            original_abi,
            &config.labels_for_contracts,
        );
        if let Some((_, builder)) = contract_builders.into_iter().next() {
            let contract = build_contract(builder, original_abi);

            proxy_contracts.push(ProxyConfig::new(
                proxy_config.path.to_owned(),
                proxy_config.override_import.to_owned(),
                proxy_config.path_rename.to_owned(),
                contract.abi,
            ));
        }
    }

    proxy_contracts
}

impl ScConfig {
    /// Assembles an `ContractVariantConfig` from a raw config object that was loaded via Serde.
    ///
    /// In most cases the config will be loaded from a .toml file, use `load_from_file` for that.
    pub fn load_from_config(config: &ScConfigSerde, original_abi: &ContractAbi) -> Self {
        let default_contract_config_name = config.settings.main.clone().unwrap_or_default();
        ScConfig {
            default_contract_config_name,
            contracts: process_contracts(config, original_abi),
            proxy_configs: process_proxy_contracts(config, original_abi),
        }
    }
}

fn alter_builder_with_proxy_config(
    proxy_config: &ProxyConfigSerde,
    contract_builder: &mut ContractVariantBuilder,
) {
    let default = ContractVariantBuilder::default();

    contract_builder.add_unlabelled = proxy_config
        .add_unlabelled
        .unwrap_or(default.add_unlabelled);
    contract_builder.add_endpoints = proxy_config.add_endpoints.iter().cloned().collect();
    contract_builder.add_labels = proxy_config.add_labels.iter().cloned().collect();
}

fn collect_and_process_endpoints(
    contract_builders: &mut HashMap<String, ContractVariantBuilder>,
    original_abi: &ContractAbi,
    labels_for_contracts: &HashMap<String, Vec<String>>,
) {
    collect_unlabelled_endpoints(contract_builders, original_abi);
    collect_labelled_endpoints(contract_builders, original_abi);
    collect_add_endpoints(contract_builders, original_abi);
    process_labels_for_contracts(contract_builders, labels_for_contracts);
}

impl ScConfig {
    /// Provides the config for the cases where no `multicontract.toml` file is available.
    ///
    /// The default configuration contains a single main contract, with all endpoints.
    pub fn default_config(original_abi: &ContractAbi) -> Self {
        let default_contract_config_name = original_abi.build_info.contract_crate.name.to_string();
        let wasm_crate_name = default_wasm_crate_name(&default_contract_config_name);
        ScConfig {
            default_contract_config_name: default_contract_config_name.clone(),
            contracts: vec![ContractVariant {
                main: true,
                settings: ContractVariantSettings::default(),
                contract_id: default_contract_config_name.clone(),
                contract_name: default_contract_config_name,
                wasm_crate_name,
                abi: original_abi.clone(),
            }],
            proxy_configs: Vec::new(),
        }
    }

    /// Loads a contract configuration from file. Will return `None` if the file is not found.
    pub fn load_from_file<P: AsRef<Path>>(path: P, original_abi: &ContractAbi) -> Option<Self> {
        match fs::read_to_string(path.as_ref()) {
            Ok(s) => {
                let config_serde: ScConfigSerde = toml::from_str(s.as_str())
                    .unwrap_or_else(|error| panic!("error parsing multicontract.toml: {error}"));
                Some(Self::load_from_config(&config_serde, original_abi))
            },
            Err(_) => None,
        }
    }

    /// The standard way of loading a `multicontract.toml` configuration: read the file if present, use the default config otherwise.
    pub fn load_from_files_or_default<I, P>(paths: I, original_abi: &ContractAbi) -> Self
    where
        P: AsRef<Path>,
        I: Iterator<Item = P>,
    {
        for path in paths {
            if let Some(config) = Self::load_from_file(path.as_ref(), original_abi) {
                return config;
            }
        }

        Self::default_config(original_abi)
    }

    /// The standard way of loading a `multicontract.toml` configuration: read the file if present, use the default config otherwise.
    pub fn load_from_crate_or_default<P>(contract_crate_path: P, original_abi: &ContractAbi) -> Self
    where
        P: AsRef<Path>,
    {
        Self::load_from_files_or_default(
            SC_CONFIG_FILE_NAMES
                .iter()
                .map(|name| PathBuf::from(contract_crate_path.as_ref()).join(name)),
            original_abi,
        )
    }
}