Skip to main content

forc_crypto/
address.rs

1use anyhow::anyhow;
2use fuel_crypto::fuel_types::Address;
3use serde_json::json;
4use std::str::{from_utf8, FromStr};
5
6forc_util::cli_examples! {
7    crate::Command {
8        [ Convert an address to another format => "forc crypto address fuel12e0xwx34nfp7jrzvn9mp5qkac3yvp7h8fx37ghl7klf82vv2wkys6wd523" ]
9    }
10}
11
12#[derive(Debug, clap::Args)]
13#[clap(
14    version,
15    about = "Converts an address to another format",
16    after_help = help(),
17)]
18pub struct Args {
19    /// The address to convert. It can be either a valid address in hex format
20    pub address: String,
21}
22
23/// Takes a valid address in any supported format and returns them in all
24/// supported format. This is meant to be a tool that can be used to convert any
25/// address format to all other formats
26pub fn dump_address<T: AsRef<[u8]>>(data: T) -> anyhow::Result<serde_json::Value> {
27    let bytes_32: Result<[u8; 32], _> = data.as_ref().try_into();
28    let addr = match bytes_32 {
29        Ok(bytes) => Address::from(bytes),
30        Err(_) => handle_string_conversion(data)?,
31    };
32
33    Ok(json!({
34        "Address": addr.to_string(),
35    }))
36}
37
38fn handle_string_conversion<T: AsRef<[u8]>>(data: T) -> anyhow::Result<Address> {
39    let addr = from_utf8(data.as_ref())?;
40    Address::from_str(addr).map_err(|_| anyhow!("{} cannot be parsed to a valid address", addr))
41}