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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use parse_display::Display;
use std::{error::Error as StdError, fmt};
use thiserror::Error;

pub(crate) type BoxError = Box<dyn StdError + Send + Sync>;

/// The error used by the [`crate::Adapter`] to wrap any custom error from the client
/// and the kinds of errors that the [`crate::Adapter`] can return.
#[derive(Debug, Error)]
#[error("{inner}")]
pub struct Error {
    inner: Box<Inner>,
}

impl Error {
    pub(crate) fn new<E>(kind: Kind, source: Option<E>) -> Self
    where
        E: Into<BoxError>,
    {
        Self {
            inner: Box::new(Inner {
                kind,
                source: source.map(Into::into),
            }),
        }
    }

    pub fn wallet_unlock<E>(source: E) -> Self
    where
        E: Into<BoxError>,
    {
        Self::new(Kind::WalletUnlock, Some(source))
    }

    pub fn authentication<E>(source: E) -> Self
    where
        E: Into<BoxError>,
    {
        Self::new(Kind::Authentication, Some(source))
    }

    pub fn authorization<E>(source: E) -> Self
    where
        E: Into<BoxError>,
    {
        Self::new(Kind::Authorization, Some(source))
    }

    pub fn adapter<A>(source: A) -> Self
    where
        A: Into<BoxError>,
    {
        Self::new(Kind::Adapter, Some(source))
    }

    pub fn verify<A>(source: A) -> Self
    where
        A: Into<BoxError>,
    {
        Self::new(Kind::Verify, Some(source))
    }
}
#[derive(Debug, Error)]
struct Inner {
    kind: Kind,
    source: Option<BoxError>,
}

impl fmt::Display for Inner {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.source {
            // Writes: "Kind: Error message here"
            Some(source) => write!(f, "{}: {}", self.kind, source),
            // Writes: "Kind"
            None => write!(f, "{}", self.kind),
        }
    }
}

#[derive(Debug, Display)]
pub(crate) enum Kind {
    Adapter,
    WalletUnlock,
    Verify,
    Authentication,
    Authorization,
}