How can I initialize a user's balance in a Sub

2019-08-16 16:59发布

问题:

When I start my Substrate blockchain, I want to initialize users with some free balance.

How can I achieve this?

What if my chain is already running and I do not want to restart it?

回答1:

Genesis Configuration

The best way to set up your Substrate users with some initial free balance is to update your chain_spec.rs file such that users are given units at the genesis block of your blockchain.

This genesis configuration happens through the Balances module:

fn testnet_genesis(initial_authorities: Vec<AuthorityId>, endowed_accounts: Vec<AccountId>, root_key: AccountId) -> GenesisConfig {
    GenesisConfig {
        balances: Some(BalancesConfig {
            transaction_base_fee: 1,
            transaction_byte_fee: 0,
            existential_deposit: 500,
            transfer_fee: 0,
            creation_fee: 0,
            balances: endowed_accounts.iter().cloned().map(|k|(k, 1 << 60)).collect(),
            vesting: vec![],
        }),
        ...
    }
}

Note the balances configuration here where each of the endowed_accounts are iterated, and their balance is set to 1 << 60 (which reads 1 left shift 60, which is 1152921504606846976 in decimal).

For the --dev chain, the endowed_accounts is just Alice, but you can add whatever accounts you want like this:

vec![
    account_key("Alice"),
    account_key("Bob"),
    // From public key
    sr25519::Public::from_ss58check("5GukQt4gJW2XqzFwmm3RHa7x6sYuVcGhuhz72CN7oiBsgffx").unwrap(),

]

Where the account_key function uses the inputted string to generate an sr25519 seed.

fn account_key(s: &str) -> AccountId {
    sr25519::Pair::from_string(&format!("//{}", s), None)
        .expect("static values are valid; qed")
        .public()
}

Sudo Module

If you already have started a blockchain and you have the Sudo module enabled, then use can also make a call to the set_balance privileged function in the Balances module.

This function will allow you to set the free and reserved balance of any account to any value.