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
use ex3_node_error::OtherError;
use ex3_node_types::chain::ChainType;
use ex3_node_types::{wallet_identifier::WalletIdentifier, PublicKey};

use crate::{PayloadDecoder, Result};

impl PayloadDecoder {
    /// Decode the payload to a wallet identifier
    /// The payload should be in the following format:
    /// `{chain},{pub_key}`
    /// where pub_key are hex encoded
    /// Used for the following transactions:
    /// - [TransactionType::WalletRegistration]
    pub fn decode_to_wallet_identifier(payload: &[u8]) -> Result<(ChainType, WalletIdentifier)> {
        let payload_str = String::from_utf8(payload.to_vec()).expect("should success");

        let hexes = payload_str.split('|').collect::<Vec<&str>>();
        let invalid_payload_error = OtherError::new("Invalid payload");
        if hexes.len() != 2 {
            return Err(invalid_payload_error.clone().into());
        }

        let chain =
            u128::from_str_radix(&hexes[0], 16).map_err(|_| invalid_payload_error.clone())?;
        let pub_key = hex::decode(&hexes[1]).map_err(|_| invalid_payload_error)?;

        let pub_key: PublicKey = PublicKey::from(pub_key);

        let wallet_identifier = WalletIdentifier(pub_key);
        Ok((chain.into(), wallet_identifier))
    }
}