nym-network-defaults 1.22.0

Nym network defaults
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
// Copyright 2024 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0

use crate::{GAS_PRICE_AMOUNT, mainnet};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::ops::Not;
use url::Url;

pub mod v2;

#[cfg(feature = "env")]
use crate::var_names;
#[cfg(feature = "env")]
use std::env::{VarError, var};
#[cfg(feature = "env")]
use std::ffi::OsStr;

#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, JsonSchema)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ChainDetails {
    pub bech32_account_prefix: String,
    pub mix_denom: DenomDetailsOwned,
    pub stake_denom: DenomDetailsOwned,
}

impl ChainDetails {
    pub fn mainnet() -> Self {
        ChainDetails {
            bech32_account_prefix: mainnet::BECH32_PREFIX.into(),
            mix_denom: mainnet::MIX_DENOM.into(),
            stake_denom: mainnet::STAKE_DENOM.into(),
        }
    }
}

#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, PartialEq, Serialize, JsonSchema)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct NymContracts {
    pub mixnet_contract_address: Option<String>,
    pub vesting_contract_address: Option<String>,
    #[serde(default)]
    pub performance_contract_address: Option<String>,
    #[serde(default)]
    pub network_monitors_contract_address: Option<String>,
    #[serde(default)]
    pub node_families_contract_address: Option<String>,
    #[serde(default)]
    pub directory_contract_address: Option<String>,
    #[serde(default)]
    pub geolocation_contract_address: Option<String>,
    pub ecash_contract_address: Option<String>,
    pub group_contract_address: Option<String>,
    pub multisig_contract_address: Option<String>,
    pub coconut_dkg_contract_address: Option<String>,
}

// I wanted to use the simpler `NetworkDetails` name, but there's a clash
// with `NetworkDetails` defined in all.rs...
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, JsonSchema)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct NymNetworkDetails {
    pub network_name: String,
    pub chain_details: ChainDetails,
    pub endpoints: Vec<ValidatorDetails>,
    pub contracts: NymContracts,
    pub nym_api_urls: Option<Vec<ApiUrl>>,
    pub nym_vpn_api_urls: Option<Vec<ApiUrl>>,
    pub nym_vpn_api_url: Option<String>,
}

#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, JsonSchema)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ApiUrl {
    /// Expects a string formatted Url
    ///
    /// see https://docs.rs/url/latest/url/struct.Url.html
    pub url: String,
    /// Optional alternative equivalent hostnames. Each entry must parse as valid Host
    ///
    /// see https://docs.rs/url/latest/url/enum.Host.html
    pub front_hosts: Option<Vec<String>>,
}

impl From<Url> for ApiUrl {
    fn from(value: Url) -> Self {
        ApiUrl {
            url: value.to_string(),
            front_hosts: None,
        }
    }
}

#[derive(Copy, Clone, Debug, Serialize)]
pub struct ApiUrlConst<'a> {
    pub url: &'a str,
    pub front_hosts: Option<&'a [&'a str]>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DirectoryAttestationSource {
    pub api_url: String,
    pub identity_ed25519_bs58: String,
}

/// A nym-api capable of producing a signed directory-digest-snapshot attestation (see
/// `nym-directory-client`'s `AttestedTrustAnchor`), paired with the ed25519 identity
/// key it is expected to sign with.
#[derive(Copy, Clone, Debug, Serialize)]
pub struct DirectoryAttestationSourceConst<'a> {
    pub api_url: &'a str,
    pub identity_ed25519_bs58: &'a str,
}

impl From<DirectoryAttestationSourceConst<'_>> for DirectoryAttestationSource {
    fn from(value: DirectoryAttestationSourceConst) -> Self {
        DirectoryAttestationSource {
            api_url: value.api_url.into(),
            identity_ed25519_bs58: value.identity_ed25519_bs58.into(),
        }
    }
}

pub fn default_directory_attestation_sources() -> Vec<DirectoryAttestationSource> {
    #[cfg(feature = "env")]
    {
        if crate::env_configured() {
            return json_deserialise_env(var_names::DIRECTORY_ATTESTATION_SOURCES)
                .unwrap_or_default();
        }
    }
    mainnet::DIRECTORY_ATTESTATION_SOURCES
        .iter()
        .map(|i| (*i).into())
        .collect()
}

impl From<ApiUrlConst<'_>> for ApiUrl {
    fn from(value: ApiUrlConst) -> Self {
        ApiUrl {
            url: value.url.to_string(),
            front_hosts: value
                .front_hosts
                .map(|slice| slice.iter().map(|s| s.to_string()).collect()),
        }
    }
}

// by default we assume the same defaults as mainnet, i.e. same prefixes and denoms
impl Default for NymNetworkDetails {
    fn default() -> Self {
        NymNetworkDetails::new_mainnet()
    }
}

impl NymNetworkDetails {
    pub fn new_empty() -> Self {
        NymNetworkDetails {
            network_name: Default::default(),
            chain_details: ChainDetails {
                bech32_account_prefix: Default::default(),
                mix_denom: DenomDetailsOwned {
                    base: Default::default(),
                    display: Default::default(),
                    display_exponent: Default::default(),
                },
                stake_denom: DenomDetailsOwned {
                    base: Default::default(),
                    display: Default::default(),
                    display_exponent: Default::default(),
                },
            },
            endpoints: Default::default(),
            contracts: Default::default(),
            nym_vpn_api_url: Default::default(),
            nym_api_urls: Default::default(),
            nym_vpn_api_urls: Default::default(),
        }
    }

    #[cfg(feature = "env")]
    pub fn new_from_env() -> Self {
        let nym_api_urls = try_parse_api_urls(var_names::NYM_APIS).unwrap_or_else(|e| {
            panic!(
                "{} is set but could not be parsed: {e}",
                var_names::NYM_APIS
            )
        });
        let nym_api_urls = if nym_api_urls.is_empty() {
            vec![parse_legacy_nym_api()]
        } else {
            nym_api_urls
        };
        let nym_api = nym_api_urls
            .first()
            .expect("nym_api_urls is guaranteed non-empty at this point");
        let nym_vpn_api_urls = try_parse_api_urls(var_names::NYM_VPN_APIS).unwrap_or_else(|e| {
            panic!(
                "{} is set but could not be parsed: {e}",
                var_names::NYM_VPN_APIS
            )
        });

        NymNetworkDetails::new_empty()
            .with_network_name(var(var_names::NETWORK_NAME).expect("network name not set"))
            .with_bech32_account_prefix(
                var(var_names::BECH32_PREFIX).expect("bech32 prefix not set"),
            )
            .with_mix_denom(DenomDetailsOwned {
                base: var(var_names::MIX_DENOM).expect("mix denomination base not set"),
                display: var(var_names::MIX_DENOM_DISPLAY)
                    .expect("mix denomination display not set"),
                display_exponent: var(var_names::DENOMS_EXPONENT)
                    .expect("denomination exponent not set")
                    .parse()
                    .expect("denomination exponent is not u32"),
            })
            .with_stake_denom(DenomDetailsOwned {
                base: var(var_names::STAKE_DENOM).expect("stake denomination base not set"),
                display: var(var_names::STAKE_DENOM_DISPLAY)
                    .expect("stake denomination display not set"),
                display_exponent: var(var_names::DENOMS_EXPONENT)
                    .expect("denomination exponent not set")
                    .parse()
                    .expect("denomination exponent is not u32"),
            })
            .with_additional_validator_endpoint(ValidatorDetails::new(
                var(var_names::NYXD).expect("nyxd validator not set"),
                Some(nym_api.url.clone()),
                get_optional_env(var_names::NYXD_WEBSOCKET),
            ))
            .with_mixnet_contract(get_optional_env(var_names::MIXNET_CONTRACT_ADDRESS))
            .with_vesting_contract(get_optional_env(var_names::VESTING_CONTRACT_ADDRESS))
            .with_node_families_contract(get_optional_env(
                var_names::NODE_FAMILIES_CONTRACT_ADDRESS,
            ))
            .with_geolocation_contract(get_optional_env(var_names::GEOLOCATION_CONTRACT_ADDRESS))
            .with_directory_contract(get_optional_env(var_names::DIRECTORY_CONTRACT_ADDRESS))
            .with_ecash_contract(get_optional_env(var_names::ECASH_CONTRACT_ADDRESS))
            .with_group_contract(get_optional_env(var_names::GROUP_CONTRACT_ADDRESS))
            .with_multisig_contract(get_optional_env(var_names::MULTISIG_CONTRACT_ADDRESS))
            .with_coconut_dkg_contract(get_optional_env(var_names::COCONUT_DKG_CONTRACT_ADDRESS))
            .with_performance_contract(get_optional_env(var_names::PERFORMANCE_CONTRACT_ADDRESS))
            .with_network_monitors_contract(get_optional_env(
                var_names::NETWORK_MONITORS_CONTRACT_ADDRESS,
            ))
            .with_nym_vpn_api_urls(nym_vpn_api_urls)
            .with_nym_api_urls(nym_api_urls)
    }

    pub fn new_mainnet() -> Self {
        fn parse_optional_str(raw: &str) -> Option<String> {
            raw.is_empty().not().then(|| raw.into())
        }

        // Consider caching this process (lazy static)
        NymNetworkDetails {
            network_name: mainnet::NETWORK_NAME.into(),
            chain_details: ChainDetails::mainnet(),
            endpoints: mainnet::validators(),
            contracts: NymContracts {
                mixnet_contract_address: parse_optional_str(mainnet::MIXNET_CONTRACT_ADDRESS),
                vesting_contract_address: parse_optional_str(mainnet::VESTING_CONTRACT_ADDRESS),
                performance_contract_address: parse_optional_str(
                    mainnet::PERFORMANCE_CONTRACT_ADDRESS,
                ),
                network_monitors_contract_address: parse_optional_str(
                    mainnet::NETWORK_MONITORS_CONTRACT_ADDRESS,
                ),
                node_families_contract_address: parse_optional_str(
                    mainnet::NODE_FAMILIES_CONTRACT_ADDRESS,
                ),
                directory_contract_address: parse_optional_str(mainnet::DIRECTORY_CONTRACT_ADDRESS),
                geolocation_contract_address: parse_optional_str(
                    mainnet::GEOLOCATION_CONTRACT_ADDRESS,
                ),
                ecash_contract_address: parse_optional_str(mainnet::ECASH_CONTRACT_ADDRESS),
                group_contract_address: parse_optional_str(mainnet::GROUP_CONTRACT_ADDRESS),
                multisig_contract_address: parse_optional_str(mainnet::MULTISIG_CONTRACT_ADDRESS),
                coconut_dkg_contract_address: parse_optional_str(
                    mainnet::COCONUT_DKG_CONTRACT_ADDRESS,
                ),
            },
            nym_vpn_api_url: parse_optional_str(mainnet::NYM_VPN_API),
            nym_api_urls: Some(mainnet::NYM_APIS.iter().copied().map(Into::into).collect()),
            nym_vpn_api_urls: Some(
                mainnet::NYM_VPN_APIS
                    .iter()
                    .copied()
                    .map(Into::into)
                    .collect(),
            ),
        }
    }

    #[rustfmt::skip]
    #[cfg(feature = "env")]
    pub fn export_to_env(self) {
        use crate::var_names;
        use std::env::set_var;

        fn set_optional_var(var_name: &str, value: Option<String>) {
            if let Some(value) = value {
                unsafe { set_var(var_name, value) }
            }
        }
        unsafe {
            let nym_api_urls = self.nym_api_urls_str();
            let nym_vpn_api_urls = self.nym_vpn_api_urls_str();

            set_var(var_names::NETWORK_NAME, self.network_name);
            set_var(var_names::BECH32_PREFIX, self.chain_details.bech32_account_prefix);

            set_var(var_names::MIX_DENOM, self.chain_details.mix_denom.base);
            set_var(var_names::MIX_DENOM_DISPLAY, self.chain_details.mix_denom.display);

            set_var(var_names::STAKE_DENOM, self.chain_details.stake_denom.base);
            set_var(var_names::STAKE_DENOM_DISPLAY, self.chain_details.stake_denom.display);

            set_var(var_names::DENOMS_EXPONENT, self.chain_details.mix_denom.display_exponent.to_string());

            if let Some(e) = self.endpoints.first() {
                set_var(var_names::NYXD, e.nyxd_url.clone());
                set_optional_var(var_names::NYM_API, e.api_url.clone());
                set_optional_var(var_names::NYXD_WEBSOCKET, e.websocket_url.clone());
            }

            set_optional_var(var_names::MIXNET_CONTRACT_ADDRESS, self.contracts.mixnet_contract_address);
            set_optional_var(var_names::VESTING_CONTRACT_ADDRESS, self.contracts.vesting_contract_address);
            set_optional_var(var_names::NETWORK_MONITORS_CONTRACT_ADDRESS, self.contracts.network_monitors_contract_address);
            set_optional_var(var_names::NODE_FAMILIES_CONTRACT_ADDRESS, self.contracts.node_families_contract_address);
            set_optional_var(var_names::DIRECTORY_CONTRACT_ADDRESS, self.contracts.directory_contract_address);
            set_optional_var(var_names::GEOLOCATION_CONTRACT_ADDRESS, self.contracts.geolocation_contract_address);
            set_optional_var(var_names::ECASH_CONTRACT_ADDRESS, self.contracts.ecash_contract_address);
            set_optional_var(var_names::GROUP_CONTRACT_ADDRESS, self.contracts.group_contract_address);
            set_optional_var(var_names::MULTISIG_CONTRACT_ADDRESS, self.contracts.multisig_contract_address);
            set_optional_var(var_names::COCONUT_DKG_CONTRACT_ADDRESS, self.contracts.coconut_dkg_contract_address);

            set_optional_var(var_names::NYM_VPN_APIS, nym_vpn_api_urls);
            set_optional_var(var_names::NYM_APIS, nym_api_urls);

        }
    }

    pub fn default_gas_price_amount(&self) -> f64 {
        GAS_PRICE_AMOUNT
    }

    #[must_use]
    pub fn with_network_name(mut self, network_name: String) -> Self {
        self.network_name = network_name;
        self
    }

    #[must_use]
    pub fn with_chain_details(mut self, chain_details: ChainDetails) -> Self {
        self.chain_details = chain_details;
        self
    }

    #[must_use]
    pub fn with_bech32_account_prefix<S: Into<String>>(mut self, prefix: S) -> Self {
        self.chain_details.bech32_account_prefix = prefix.into();
        self
    }

    #[must_use]
    pub fn with_mix_denom(mut self, mix_denom: DenomDetailsOwned) -> Self {
        self.chain_details.mix_denom = mix_denom;
        self
    }

    #[must_use]
    pub fn with_stake_denom(mut self, stake_denom: DenomDetailsOwned) -> Self {
        self.chain_details.stake_denom = stake_denom;
        self
    }

    #[must_use]
    pub fn with_base_mix_denom<S: Into<String>>(mut self, base_mix_denom: S) -> Self {
        self.chain_details.mix_denom = DenomDetailsOwned::base_only(base_mix_denom.into());
        self
    }

    #[must_use]
    pub fn with_base_stake_denom<S: Into<String>>(mut self, base_stake_denom: S) -> Self {
        self.chain_details.stake_denom = DenomDetailsOwned::base_only(base_stake_denom.into());
        self
    }

    #[must_use]
    pub fn with_additional_validator_endpoint(mut self, endpoint: ValidatorDetails) -> Self {
        self.endpoints.push(endpoint);
        self
    }

    #[must_use]
    pub fn with_validator_endpoint(mut self, endpoint: ValidatorDetails) -> Self {
        self.endpoints = vec![endpoint];
        self
    }

    #[must_use]
    pub fn with_contracts(mut self, contracts: NymContracts) -> Self {
        self.contracts = contracts;
        self
    }

    #[must_use]
    pub fn with_mixnet_contract<S: Into<String>>(mut self, contract: Option<S>) -> Self {
        self.contracts.mixnet_contract_address = contract.map(Into::into);
        self
    }

    #[must_use]
    pub fn with_vesting_contract<S: Into<String>>(mut self, contract: Option<S>) -> Self {
        self.contracts.vesting_contract_address = contract.map(Into::into);
        self
    }

    #[must_use]
    pub fn with_node_families_contract<S: Into<String>>(mut self, contract: Option<S>) -> Self {
        self.contracts.node_families_contract_address = contract.map(Into::into);
        self
    }

    #[must_use]
    pub fn with_directory_contract<S: Into<String>>(mut self, contract: Option<S>) -> Self {
        self.contracts.directory_contract_address = contract.map(Into::into);
        self
    }

    #[must_use]
    pub fn with_geolocation_contract<S: Into<String>>(mut self, contract: Option<S>) -> Self {
        self.contracts.geolocation_contract_address = contract.map(Into::into);
        self
    }

    #[must_use]
    pub fn with_ecash_contract<S: Into<String>>(mut self, contract: Option<S>) -> Self {
        self.contracts.ecash_contract_address = contract.map(Into::into);
        self
    }

    #[must_use]
    pub fn with_group_contract<S: Into<String>>(mut self, contract: Option<S>) -> Self {
        self.contracts.group_contract_address = contract.map(Into::into);
        self
    }

    #[must_use]
    pub fn with_multisig_contract<S: Into<String>>(mut self, contract: Option<S>) -> Self {
        self.contracts.multisig_contract_address = contract.map(Into::into);
        self
    }

    #[must_use]
    pub fn with_coconut_dkg_contract<S: Into<String>>(mut self, contract: Option<S>) -> Self {
        self.contracts.coconut_dkg_contract_address = contract.map(Into::into);
        self
    }

    #[must_use]
    pub fn with_performance_contract<S: Into<String>>(mut self, contract: Option<S>) -> Self {
        self.contracts.performance_contract_address = contract.map(Into::into);
        self
    }

    #[must_use]
    pub fn with_network_monitors_contract<S: Into<String>>(mut self, contract: Option<S>) -> Self {
        self.contracts.network_monitors_contract_address = contract.map(Into::into);
        self
    }

    pub fn set_nym_api_urls<U: Into<ApiUrl>>(&mut self, urls: Vec<U>) {
        let urls: Vec<ApiUrl> = urls.into_iter().map(Into::into).collect();
        self.nym_api_urls = (!urls.is_empty()).then_some(urls);
    }

    #[must_use]
    pub fn with_nym_api_urls<U: Into<ApiUrl>>(mut self, urls: Vec<U>) -> Self {
        self.set_nym_api_urls(urls);
        self
    }

    pub fn set_nym_vpn_api_urls<U: Into<ApiUrl>>(&mut self, urls: Vec<U>) {
        let urls: Vec<ApiUrl> = urls.into_iter().map(Into::into).collect();
        if urls.is_empty() {
            self.nym_vpn_api_urls = None;
            self.nym_vpn_api_url = None
        } else {
            self.nym_vpn_api_url = Some(urls.first().expect("checked non-empty above").url.clone());
            self.nym_vpn_api_urls = Some(urls);
        }
    }

    #[must_use]
    pub fn with_nym_vpn_api_urls<U: Into<ApiUrl>>(mut self, urls: Vec<U>) -> Self {
        self.set_nym_vpn_api_urls(urls);
        self
    }

    /// Returns the configured `nym_api_urls` if any are set, otherwise
    /// falls back to the api urls derived from `endpoints` (the legacy validator list).
    pub fn nym_api_urls(&self) -> Vec<ApiUrl> {
        if let Some(urls) = &self.nym_api_urls
            && !urls.is_empty()
        {
            return urls.clone();
        }

        self.endpoints
            .iter()
            .filter_map(|e| e.api_url())
            .map(ApiUrl::from)
            .collect()
    }

    #[cfg(feature = "env")]
    fn nym_api_urls_str(&self) -> Option<String> {
        serde_json::to_string(&self.nym_api_urls())
            .inspect_err(|e| tracing::warn!("failed to serialize nym_api_urls for env: {e}"))
            .ok()
    }

    pub fn nym_vpn_api_urls(&self) -> Vec<ApiUrl> {
        self.nym_vpn_api_urls.clone().unwrap_or_default()
    }

    #[cfg(feature = "env")]
    fn nym_vpn_api_urls_str(&self) -> Option<String> {
        serde_json::to_string(&self.nym_vpn_api_urls())
            .inspect_err(|e| tracing::warn!("failed to serialize nym_vpn_api_urls for env: {e}"))
            .ok()
    }
}

#[cfg(feature = "env")]
pub(crate) fn json_serialise<T>(data: &T) -> String
where
    T: ?Sized + serde::Serialize,
{
    serde_json::to_string(data)
        .inspect_err(|e| tracing::warn!("failed to serialise data for env: {e}"))
        .unwrap_or_default()
}

#[cfg(feature = "env")]
pub(crate) fn json_deserialise_env<T>(k: impl AsRef<OsStr>) -> Option<T>
where
    T: serde::de::DeserializeOwned,
{
    let raw = var(k).ok()?;
    serde_json::from_str(&raw)
        .inspect_err(|e| tracing::warn!("failed to parse data from env \"{raw:?}\": {e}"))
        .ok()
}

#[cfg(feature = "env")]
fn try_parse_api_urls(k: impl AsRef<OsStr>) -> Result<Vec<ApiUrl>, serde_json::Error> {
    match var(k) {
        Ok(raw) if !raw.is_empty() => serde_json::from_str(&raw),
        _ => Ok(Vec::new()),
    }
}

#[cfg(feature = "env")]
fn get_optional_env<K: AsRef<OsStr>>(env: K) -> Option<String> {
    match var(env) {
        Ok(var) => (!var.is_empty()).then_some(var),
        Err(VarError::NotPresent) => None,
        err => panic!("Unable to set: {err:?}"),
    }
}

// NYM_APIS was introduced to replace the singular NYM_API; fall back to it so
// setups that only ever configured NYM_API (via setup_env's legacy migration
// or otherwise) keep working.
#[cfg(feature = "env")]
fn parse_legacy_nym_api() -> ApiUrl {
    let legacy_api = get_optional_env(var_names::NYM_API).unwrap_or_else(|| {
        panic!(
            "neither {} nor legacy {} is set",
            var_names::NYM_APIS,
            var_names::NYM_API
        )
    });
    Url::parse(&legacy_api)
        .unwrap_or_else(|e| panic!("{} is not a valid url: {e}", var_names::NYM_API))
        .into()
}

#[derive(Debug, Copy, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct DenomDetails {
    pub base: &'static str,
    pub display: &'static str,
    // i.e. display_amount * 10^display_exponent = base_amount
    pub display_exponent: u32,
}

impl DenomDetails {
    pub const fn new(base: &'static str, display: &'static str, display_exponent: u32) -> Self {
        DenomDetails {
            base,
            display,
            display_exponent,
        }
    }
}

#[derive(Debug, Serialize, Deserialize, Hash, Clone, PartialEq, Eq, JsonSchema)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct DenomDetailsOwned {
    pub base: String,
    pub display: String,
    // i.e. display_amount * 10^display_exponent = base_amount
    pub display_exponent: u32,
}

impl From<DenomDetails> for DenomDetailsOwned {
    fn from(details: DenomDetails) -> Self {
        DenomDetailsOwned {
            base: details.base.to_owned(),
            display: details.display.to_owned(),
            display_exponent: details.display_exponent,
        }
    }
}

impl DenomDetailsOwned {
    pub fn base_only(base: String) -> Self {
        DenomDetailsOwned {
            base: base.clone(),
            display: base,
            display_exponent: 0,
        }
    }
}

#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize, JsonSchema)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct ValidatorDetails {
    // it is assumed those values are always valid since they're being provided in our defaults file
    pub nyxd_url: String,
    //
    pub websocket_url: Option<String>,

    // Right now api_url is optional as we are not running the api reliably on all validators
    // however, later on it should be a mandatory field
    pub api_url: Option<String>,
    // TODO: I'd argue this one should also have a field like `gas_price` since its a validator-specific setting
}

impl ValidatorDetails {
    pub fn new<S: Into<String>>(nyxd_url: S, api_url: Option<S>, websocket_url: Option<S>) -> Self {
        ValidatorDetails {
            nyxd_url: nyxd_url.into(),
            websocket_url: websocket_url.map(Into::into),
            api_url: api_url.map(Into::into),
        }
    }

    pub fn new_nyxd_only<S: Into<String>>(nyxd_url: S) -> Self {
        ValidatorDetails {
            nyxd_url: nyxd_url.into(),
            websocket_url: None,
            api_url: None,
        }
    }

    pub fn nyxd_url(&self) -> Url {
        self.nyxd_url
            .parse()
            .expect("the provided nyxd url is invalid!")
    }

    pub fn api_url(&self) -> Option<Url> {
        self.api_url
            .as_ref()
            .map(|url| url.parse().expect("the provided api url is invalid!"))
    }

    pub fn websocket_url(&self) -> Option<Url> {
        self.websocket_url
            .as_ref()
            .map(|url| url.parse().expect("the provided websocket url is invalid!"))
    }
}