Skip to content
Snippets Groups Projects
account.rs 2.41 KiB
Newer Older
use crate::*;

/// define account subcommands
#[derive(Clone, Default, Debug, clap::Parser)]
pub enum Subcommand {
	/// Fetch account balance
	#[default]
	Balance,
	/// Transfer some currency to an account
	Transfer {
		/// Amount to transfer
		amount: u64,
		/// Destination address
		dest: AccountId,
		/// Prevent from going below account existential deposit
		#[clap(short = 'k', long = "keep-alive")]
		keep_alive: bool,
guenoel's avatar
guenoel committed
		/// Use universal dividends instead of units
		#[clap(short = 'u', long = "ud")]
		is_ud: bool,
	},
	/// Transfer the same amount for each space-separated address.
	/// If an address appears mutiple times, it will get multiple times the same amount
	TransferMultiple {
		/// Amount given to each destination address
		amount: u64,
		/// List of target addresses
		dests: Vec<AccountId>,
	},
	/// Unlink the account from the linked identity
	Unlink,
}

/// handle account commands
pub async fn handle_command(data: Data, command: Subcommand) -> anyhow::Result<()> {
	let mut data = data.build_client().await?;
	match command {
		Subcommand::Balance => {
			data = data.fetch_system_properties().await?;
			get_balance(data).await?
		}
		Subcommand::Transfer {
			amount,
			dest,
			keep_alive,
			is_ud,
guenoel's avatar
guenoel committed
			commands::transfer::transfer(&data, amount, dest, keep_alive, is_ud).await?;
		}
		Subcommand::TransferMultiple { amount, dests } => {
			commands::transfer::transfer_multiple(&data, amount, dests).await?;
		Subcommand::Unlink => {
			unlink_account(&data).await?;
		}
/// get balance
pub async fn get_balance(data: Data) -> Result<(), anyhow::Error> {
	let account_id = data.address();
	let account_info = get_account_info(data.client(), &account_id).await?;
	if let Some(account_info) = account_info {
		println!(
			"{account_id} has {}",
			data.format_balance(account_info.data.free)
		);
	} else {
		println!("account {account_id} does not exist")
	}
	Ok(())
}

/// get account info
pub async fn get_account_info(
Hugo Trentesaux's avatar
Hugo Trentesaux committed
	client: &Client,
	account_id: &AccountId,
) -> Result<Option<AccountInfo>, subxt::Error> {
	client
		.storage()
		.fetch(&runtime::storage().system().account(account_id), None)
		.await

/// unlink account
pub async fn unlink_account(data: &Data) -> Result<(), subxt::Error> {
	submit_call_and_look_event::<
		runtime::account::events::AccountUnlinked,
		StaticTxPayload<runtime::account::calls::UnlinkIdentity>,
	>(data, &runtime::tx().account().unlink_identity())
	.await
}