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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/// Includes generated protocol buffer code.
macro_rules! include_proto {
    ($package:tt) => {
        include!(concat!(env!("OUT_DIR"), "/", $package, ".rs"));
    };
}

pub mod directory {
    include_proto!("m10.directory");
    use core::fmt;
    use core::str::FromStr;

    #[derive(Debug)]
    pub struct InvalidAliasType();

    impl fmt::Display for InvalidAliasType {
        fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
            f.write_str("invalid alias type")
        }
    }

    impl std::error::Error for InvalidAliasType {}

    impl FromStr for alias::Type {
        type Err = InvalidAliasType;
        fn from_str(s: &str) -> Result<Self, Self::Err> {
            match s {
                "handle" => Ok(alias::Type::Handle),
                "email" => Ok(alias::Type::Email),
                "phone" => Ok(alias::Type::Phone),
                _ => Err(InvalidAliasType()),
            }
        }
    }

    impl AsRef<str> for alias::Type {
        fn as_ref(&self) -> &str {
            match self {
                alias::Type::Handle => "handle",
                alias::Type::Email => "email",
                alias::Type::Phone => "phone",
            }
        }
    }

    impl fmt::Display for alias::Type {
        fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
            f.write_str(self.as_ref())
        }
    }
}

pub mod sdk {
    include_proto!("m10.sdk");

    pub const FILE_DESCRIPTOR_SET_BYTES: &[u8] =
        include_bytes!(concat!(env!("OUT_DIR"), "/m10.sdk.bin"));
    pub static FILE_DESCRIPTOR_SET: once_cell::sync::Lazy<prost_types::FileDescriptorSet> =
        once_cell::sync::Lazy::new(|| {
            prost::Message::decode(FILE_DESCRIPTOR_SET_BYTES).expect("file descriptor parse failed")
        });

    pub mod model {
        include_proto!("m10.sdk.model");
        pub const FILE_DESCRIPTOR_SET_BYTES: &[u8] =
            include_bytes!(concat!(env!("OUT_DIR"), "/m10.model.pb"));
        pub static FILE_DESCRIPTOR_SET: once_cell::sync::Lazy<prost_types::FileDescriptorSet> =
            once_cell::sync::Lazy::new(|| {
                prost::Message::decode(FILE_DESCRIPTOR_SET_BYTES)
                    .expect("file descriptor parse failed")
            });
    }
    pub mod transaction {
        include_proto!("m10.sdk.transaction");
    }
    pub mod metadata {
        include_proto!("m10.sdk.metadata");
    }
    pub use metadata::*;
    pub use model::*;
    use prost::Message;
    pub use transaction::*;

    use core::{fmt, str};
    use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

    use crate::{sdk, Collection, Pack};

    impl str::FromStr for AccountRef {
        type Err = AccountRefParseError;

        fn from_str(s: &str) -> Result<Self, Self::Err> {
            let mut s = s.split('/');
            let ledger_id = s.next().ok_or(AccountRefParseError())?.to_string();
            let account_id = s.next().ok_or(AccountRefParseError())?;
            let account_id = hex::decode(account_id).map_err(|_| AccountRefParseError())?;
            Ok(Self {
                ledger_id,
                account_id,
            })
        }
    }

    impl Serialize for AccountRef {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            serializer.collect_str(self)
        }
    }

    impl<'de> Deserialize<'de> for AccountRef {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            let s = String::deserialize(deserializer)?;
            s.parse().map_err(de::Error::custom)
        }
    }

    impl fmt::Display for AccountRef {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}/{}", self.ledger_id, hex::encode(&self.account_id))
        }
    }

    #[derive(Debug)]
    pub struct AccountRefParseError();

    impl fmt::Display for AccountRefParseError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("failed to parse account ref")
        }
    }

    impl std::error::Error for AccountRefParseError {}

    impl Pack for AccountSet {
        const COLLECTION: Collection = Collection::AccountSets;
        fn set_id(&mut self, id: Vec<u8>) {
            self.id = id;
        }
        fn id(&self) -> &[u8] {
            &self.id
        }
    }

    impl Pack for Account {
        const COLLECTION: Collection = Collection::Accounts;
        fn set_id(&mut self, id: Vec<u8>) {
            self.id = id;
        }
        fn id(&self) -> &[u8] {
            &self.id
        }
    }

    use transaction_data::Data;

    impl From<CreateTransfer> for Data {
        fn from(create_transfer: CreateTransfer) -> Self {
            Self::Transfer(create_transfer)
        }
    }

    impl From<CreateLedgerAccount> for Data {
        fn from(request: CreateLedgerAccount) -> Self {
            Self::CreateLedgerAccount(request)
        }
    }

    impl From<SetFreezeState> for Data {
        fn from(request: SetFreezeState) -> Self {
            Self::SetFreezeState(request)
        }
    }

    impl From<InvokeAction> for Data {
        fn from(request: InvokeAction) -> Self {
            Self::InvokeAction(request)
        }
    }

    impl From<CommitTransfer> for Data {
        fn from(request: CommitTransfer) -> Self {
            Self::CommitTransfer(request)
        }
    }

    impl From<sdk::DocumentOperations> for Data {
        fn from(operations: sdk::DocumentOperations) -> Self {
            Self::DocumentOperations(operations)
        }
    }

    impl From<Vec<sdk::Operation>> for Data {
        fn from(operations: Vec<sdk::Operation>) -> Self {
            Self::from(sdk::DocumentOperations { operations })
        }
    }

    impl From<sdk::Operation> for Data {
        fn from(operation: sdk::Operation) -> Self {
            Self::from(vec![operation])
        }
    }

    impl From<CreateLedgerTransfers> for Contract {
        fn from(transfers: CreateLedgerTransfers) -> Self {
            Self {
                transactions: transfers.encode_to_vec(),
                ..Default::default()
            }
        }
    }

    impl TransactionResponse {
        pub fn tx_error(self) -> Result<Self, TransactionError> {
            match self.error {
                Some(err) => Err(err),
                None => Ok(self),
            }
        }
    }

    impl fmt::Display for TransactionError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{:?}: {}", self.code(), self.message)
        }
    }

    impl std::error::Error for TransactionError {}

    impl From<prost::bytes::Bytes> for Value {
        fn from(bytes: prost::bytes::Bytes) -> Value {
            Value {
                value: Some(value::Value::BytesValue(bytes)),
            }
        }
    }

    impl Operation {
        pub fn insert<D: Pack>(document: D) -> Self {
            Self {
                operation: Some(operation::Operation::InsertDocument(
                    operation::InsertDocument {
                        collection: D::COLLECTION.to_string(),
                        document: document.pack(),
                    },
                )),
            }
        }

        pub fn delete<D: Pack>(id: Vec<u8>) -> Self {
            Self {
                operation: Some(operation::Operation::DeleteDocument(
                    operation::DeleteDocument {
                        collection: D::COLLECTION.to_string(),
                        primary_key: Some(bytes::Bytes::from(id).into()),
                    },
                )),
            }
        }

        pub fn new_index<D: Pack>(path: Vec<String>) -> Self {
            Self {
                operation: Some(operation::Operation::InsertIndex(operation::InsertIndex {
                    collection: D::COLLECTION.to_string(),
                    path: path.join("."),
                })),
            }
        }

        pub fn new_collection(
            name: String,
            descriptor_name: String,
            index_metadata: Vec<IndexMetadata>,
        ) -> Self {
            Self {
                operation: Some(operation::Operation::InsertCollection(CollectionMetadata {
                    name,
                    descriptor_name,
                    file_descriptor_set: Some(crate::sdk::FILE_DESCRIPTOR_SET.clone()),
                    primary_key_path: "id".to_string(),
                    index_metadata,
                })),
            }
        }
    }

    impl Pack for RoleBinding {
        const COLLECTION: Collection = Collection::RoleBindings;
        fn set_id(&mut self, id: Vec<u8>) {
            self.id = bytes::Bytes::from(id);
        }
        fn id(&self) -> &[u8] {
            &self.id
        }
    }

    impl Pack for Role {
        const COLLECTION: Collection = Collection::Roles;
        fn set_id(&mut self, id: Vec<u8>) {
            self.id = bytes::Bytes::from(id);
        }
        fn id(&self) -> &[u8] {
            &self.id
        }
    }
}

pub mod health {
    include_proto!("grpc.health.v1");
}

pub mod metadata;
mod pack;

/// Re-export of prost
pub mod prost {
    pub use prost::*;
    pub use prost_types::*;
}
pub use metadata::*;
pub use pack::{Collection, Pack};

use prost_types::Any;
use serde::{Deserialize, Serialize};
use serde_with::{DeserializeAs, SerializeAs};

pub struct AnySerDeCompat;

#[derive(Serialize)]
struct AnySerializeWrapper<'a> {
    pub type_url: &'a str,
    pub value: &'a [u8],
}

#[derive(Deserialize)]
struct AnyDeserializeWrapper {
    pub type_url: String,
    pub value: Vec<u8>,
}

impl SerializeAs<Any> for AnySerDeCompat {
    fn serialize_as<S>(source: &Any, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        AnySerializeWrapper {
            type_url: &source.type_url,
            value: &source.value,
        }
        .serialize(serializer)
    }
}

impl<'de> DeserializeAs<'de, Any> for AnySerDeCompat {
    fn deserialize_as<D>(deserializer: D) -> Result<Any, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let AnyDeserializeWrapper { type_url, value } =
            AnyDeserializeWrapper::deserialize(deserializer)?;
        Ok(Any { type_url, value })
    }
}