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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
use prost::Message;
use prost_types::Any;

use crate::sdk::metadata::*;
use crate::sdk::transaction::{CreateTransfer, TransferStep};
use crate::sdk::FinalizedTransfer;

pub fn memo(memo: &str) -> Any {
    Memo {
        plaintext: memo.to_string(),
    }
    .any()
}

pub trait MetadataType {
    const TYPE_URL: &'static str;
}

pub trait Metadata: MetadataType {
    fn any(&self) -> Any;
}

impl<M: MetadataType + Message + Sized + Default> Metadata for M {
    fn any(&self) -> Any {
        Any {
            type_url: Self::TYPE_URL.to_string(),
            value: self.encode_to_vec(),
        }
    }
}

pub trait MetadataExt {
    // Deprecated - please use [`protobuf`] instead
    fn metadata<M: Metadata + Message + Default>(&self) -> Option<M> {
        self.protobuf::<M>()
    }

    fn protobuf<M: Metadata + Message + Default>(&self) -> Option<M> {
        self.with_type::<M>().and_then(|b| M::decode(b).ok())
    }

    fn with_type<M: MetadataType>(&self) -> Option<&[u8]>;

    fn memo(&self) -> String {
        self.protobuf::<Memo>().unwrap_or_default().plaintext
    }
}

impl MetadataExt for Any {
    fn with_type<M: MetadataType>(&self) -> Option<&[u8]> {
        (self.type_url == M::TYPE_URL).then(|| self.value.as_slice())
    }
}

impl<T: MetadataExt> MetadataExt for Vec<T> {
    fn with_type<M: MetadataType>(&self) -> Option<&[u8]> {
        self.iter().find_map(MetadataExt::with_type::<M>)
    }
}

impl MetadataExt for TransferStep {
    fn with_type<M: MetadataType>(&self) -> Option<&[u8]> {
        self.metadata.with_type::<M>()
    }
}

impl MetadataExt for CreateTransfer {
    fn with_type<M: MetadataType>(&self) -> Option<&[u8]> {
        self.transfer_steps.with_type::<M>()
    }
}

impl MetadataExt for FinalizedTransfer {
    fn with_type<M: MetadataType>(&self) -> Option<&[u8]> {
        self.transfer_steps.with_type::<M>()
    }
}

impl MetadataType for Attachment {
    const TYPE_URL: &'static str = "m10.sdk.metadata.Attachment";
}

impl MetadataType for Memo {
    const TYPE_URL: &'static str = "m10.sdk.metadata.Memo";
}

impl MetadataType for Fee {
    const TYPE_URL: &'static str = "m10.sdk.metadata.Fee";
}

impl MetadataType for Withdraw {
    const TYPE_URL: &'static str = "m10.sdk.metadata.Withdraw";
}

impl MetadataType for Deposit {
    const TYPE_URL: &'static str = "m10.sdk.metadata.Deposit";
}

impl MetadataType for Contract {
    const TYPE_URL: &'static str = "m10.sdk.metadata.Contract";
}