astar_primitives/
genesis.rs

1// This file is part of Astar.
2
3// Copyright (C) Stake Technologies Pte.Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later
5
6// Astar is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// Astar is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with Astar. If not, see <http://www.gnu.org/licenses/>.
18
19use scale_info::prelude::format;
20use sp_core::{Pair, Public};
21use sp_runtime::traits::{IdentifyAccount, Verify};
22
23use super::{AccountId, Signature};
24
25type AccountPublic = <Signature as Verify>::Signer;
26
27/// Helper function to generate a crypto pair from seed
28pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
29    TPublic::Pair::from_string(&format!("//{}", seed), None)
30        .expect("static values are valid; qed")
31        .public()
32}
33
34/// Helper function to generate an account ID from seed
35pub fn get_account_id_from_seed<TPublic: Public>(seed: &str) -> AccountId
36where
37    AccountPublic: From<<TPublic::Pair as Pair>::Public>,
38{
39    AccountPublic::from(get_from_seed::<TPublic>(seed)).into_account()
40}
41
42/// Helper struct for genesis configuration.
43#[derive(Clone, PartialEq, Eq)]
44pub struct GenesisAccount<TPublic: Public> {
45    /// Account ID
46    pub account_id: AccountId,
47    /// Public key
48    pub pub_key: <TPublic::Pair as Pair>::Public,
49}
50
51impl<TPublic: Public> GenesisAccount<TPublic>
52where
53    AccountPublic: From<<TPublic::Pair as Pair>::Public>,
54{
55    /// Create a new genesis account from a seed.
56    pub fn from_seed(seed: &str) -> Self {
57        let pub_key = get_from_seed::<TPublic>(seed);
58        let account_id = AccountPublic::from(pub_key.clone()).into_account();
59
60        Self {
61            account_id,
62            pub_key,
63        }
64    }
65
66    /// Return the `account Id` (address) of the genesis account.
67    pub fn account_id(&self) -> AccountId {
68        self.account_id.clone()
69    }
70
71    /// Return the `public key` of the genesis account.
72    pub fn pub_key(&self) -> <TPublic::Pair as Pair>::Public {
73        self.pub_key.clone()
74    }
75}