ic_icrc_tx/parser/response/
mod.rs

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use base64::{engine::general_purpose, Engine};
use candid::Decode;
use icrc_ledger_types::icrc1::transfer::{BlockIndex, TransferError};
/// A struct representing the response containing a base64-encoded content map.
pub struct Response {
    pub content_map: String,
}

/// The result type for a transfer, which can either be a `BlockIndex` or a `TransferError`.
pub type TransferResult = Result<BlockIndex, TransferError>;

/// Parses an ICRC1 transfer response.
///
/// This function takes a `Response` input, decodes the base64-encoded content map,
/// and deserializes it into a `TransferResult`.
///
/// # Arguments
///
/// * `response` - The `Response` containing the base64-encoded content map.
///
/// # Returns
///
/// A `TransferResult` which is either a `BlockIndex` or a `TransferError`.
///
/// # Panics
///
/// This function will panic if the base64 decoding or deserialization fails.
pub fn parse_icrc1_transfer_response(response: Response) -> TransferResult {
    // Decode the base64 string to bytes
    let result_bytes = general_purpose::STANDARD
        .decode(response.content_map)
        .unwrap();
    let result = Decode!(&result_bytes, TransferResult).unwrap();

    println!("Result: {:?}", result);

    result
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_icrc1_err_response() {
        let content_map = "RElETAhrAryKAX3F/tIBAWsI0cSYfALCkey5An+UwceJBAPrgqiXBAShw+v9BwXwh+bbCQaT5b7IDH/rnNvVDwdsAsfrxNAJccSYsbUNfWwBm7O+pgp9bAGLvfKbAX1sAb+bt/ANfWwBo7uRjAp4bAGcuracAn0BAAEHAA==";

        let response = Response {
            content_map: content_map.to_string(),
        };

        let result = parse_icrc1_transfer_response(response);

        assert_eq!(result.is_err(), true);
    }

    #[test]
    fn test_parser_icrc1_success_response() {
        let content_map = "RElETAhrAryKAX3F/tIBAWsI0cSYfALCkey5An+UwceJBAPrgqiXBAShw+v9BwXwh+bbCQaT5b7IDH/rnNvVDwdsAsfrxNAJccSYsbUNfWwBm7O+pgp9bAGLvfKbAX1sAb+bt/ANfWwBo7uRjAp4bAGcuracAn0BAACaAg==";
        let response = Response {
            content_map: content_map.to_string(),
        };

        let result = parse_icrc1_transfer_response(response);

        assert_eq!(result.is_ok(), true);
    }
}