borderless 0.3.0

SDK for borderless packages
Documentation
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
use crate::agents::env::{agent_id, executor};
use crate::common::Id;
use crate::contracts::env::{contract_id, is_contract, participant, sinks};
use crate::events::private::Sealed;
use anyhow::anyhow;
use borderless_id_types::{BorderlessId, ContractId};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fmt::Formatter;
use std::{fmt::Debug, fmt::Display, str::FromStr};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
/// Enum to represent the type of method-call
pub enum MethodOrId {
    /// Method is called by its name
    ByName { method: String },
    /// Method is called by its id
    ById { method_id: u32 },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Data-model for an action-call in contracts and agents.
pub struct CallAction {
    #[serde(flatten)]
    pub method: MethodOrId,
    pub params: Value,
}

impl FromStr for CallAction {
    type Err = serde_json::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        serde_json::from_str(s)
    }
}

impl CallAction {
    /// Create a new `CallAction`
    pub fn new(method: MethodOrId, params: Value) -> Self {
        Self { method, params }
    }

    /// Create a new `CallAction` by method-name
    pub fn by_method(method_name: impl AsRef<str>, params: Value) -> Self {
        Self {
            method: MethodOrId::ByName {
                method: method_name.as_ref().to_string(),
            },
            params,
        }
    }

    /// Create a new `CallAction` by method-id
    pub fn by_method_id(method_id: u32, params: Value) -> Self {
        Self {
            method: MethodOrId::ById { method_id },
            params,
        }
    }

    /// Returns the method-name of this action (if any)
    pub fn method_name(&self) -> Option<&str> {
        match &self.method {
            MethodOrId::ByName { method } => Some(method.as_str()),
            MethodOrId::ById { .. } => None,
        }
    }

    /// Returns the method-id of this action (if any)
    pub fn method_id(&self) -> Option<u32> {
        match self.method {
            MethodOrId::ByName { .. } => None,
            MethodOrId::ById { method_id } => Some(method_id),
        }
    }

    /// Prints either the method-name or method-id for this action
    pub fn print_method(&self) -> String {
        match &self.method {
            MethodOrId::ByName { method } => format!("method-name={method}"),
            MethodOrId::ById { method_id } => format!("method-id={method_id}"),
        }
    }

    /// Deserializes the JSON-Bytes into a `CallAction`
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        serde_json::from_slice(bytes)
    }

    /// Pretty-prints the entire `CallAction` as JSON
    pub fn pretty_print(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self)
    }

    /// Serialized the `CallAction` into JSON-Bytes
    pub fn to_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
        serde_json::to_vec(&self)
    }
}

pub struct CBInit;
pub struct CBWithAction;

/// Builder to create a new `ContractCall`
pub struct CallBuilder<STATE> {
    pub(crate) id: ContractId,
    pub(crate) name: String,
    pub(crate) writer: Option<BorderlessId>,
    pub(crate) action: Option<CallAction>,
    _marker: std::marker::PhantomData<STATE>,
}

impl CallBuilder<CBInit> {
    pub fn new(id: ContractId, method_name: &str) -> CallBuilder<CBInit> {
        CallBuilder {
            id,
            name: method_name.to_string(),
            writer: None,
            action: None,
            _marker: std::marker::PhantomData,
        }
    }

    pub(crate) fn new_with_writer(
        id: ContractId,
        method_name: &str,
        writer: &str,
    ) -> CallBuilder<CBInit> {
        let writer = if is_contract() {
            participant(writer).expect("sink contains unknown writer")
        } else {
            // When dealing with a sw-agent, the executor must be the writer
            executor()
        };

        CallBuilder {
            id,
            name: method_name.to_string(),
            writer: Some(writer),
            action: None,
            _marker: std::marker::PhantomData,
        }
    }

    /// Specify the arguments of the action directly as a json-value
    pub fn with_value(self, value: Value) -> CallBuilder<CBWithAction> {
        let action = CallAction::by_method(&self.name, value);
        CallBuilder {
            id: self.id,
            name: self.name,
            writer: self.writer,
            action: Some(action),
            _marker: std::marker::PhantomData,
        }
    }

    /// Specify the arguments of the action
    ///
    /// In contrast to `with_value`, this function expects a serializable object to build the json value.
    pub fn with_args<T: serde::Serialize>(
        self,
        args: T,
    ) -> Result<CallBuilder<CBWithAction>, crate::Error> {
        let value = serde_json::to_value(args).map_err(|e| {
            crate::Error::msg(format!("failed to convert args for method-call: {e}"))
        })?;
        let action = CallAction::by_method(&self.name, value);
        Ok(CallBuilder {
            id: self.id,
            name: self.name,
            writer: self.writer,
            action: Some(action),
            _marker: std::marker::PhantomData,
        })
    }
}

impl CallBuilder<CBWithAction> {
    /// Specify the writer of the transaction by their alias
    ///
    /// Returns an error, if no participant exists with that alias.
    pub fn with_writer(
        self,
        writer_alias: impl AsRef<str>,
    ) -> Result<CallBuilder<CBWithAction>, crate::Error> {
        // Check if a participant with the provided alias exists
        let writer_id = participant(writer_alias.as_ref())?;
        Ok(CallBuilder {
            id: self.id,
            name: self.name,
            writer: Some(writer_id),
            action: self.action,
            _marker: std::marker::PhantomData,
        })
    }

    /// Builds the `ContractCall`
    pub fn build(self) -> Result<ContractCall, crate::Error> {
        debug_assert!(self.action.is_some(), "invariant: action must be set");

        // NOTE: If we have specified a writer, we don't want to check the existing sinks,
        // as the user seems to know what he/she is doing (calling an action based on contract-id + writer-id):
        if let Some(writer) = self.writer {
            return Ok(ContractCall {
                contract_id: self.id,
                action: self.action.unwrap(),
                writer,
            });
        }
        // --- Proceed as normal, without a writer

        // Fetch the sinks related to the contract
        let mut sinks: Vec<Sink> = sinks()
            .into_iter()
            .filter(|s| s.contract_id == self.id)
            .collect();

        // Ensure there is a single match when looking for a sink
        let writer = match sinks.len() {
            0 => return Err(anyhow!("Found no sink related to contract-id {}", self.id)),
            1 => {
                let sink = sinks.pop().unwrap();
                participant(sink.writer)?
            }
            _ => {
                return Err(anyhow!(
                    "Found multiple sinks for contract-id {} - please specify the writer directly",
                    self.id
                ));
            }
        };

        Ok(ContractCall {
            contract_id: self.id,
            action: self.action.unwrap(),
            writer,
        })
    }
}

/// An outgoing event for another contract
///
/// `ContractCall`s will be converted into transactions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContractCall {
    pub contract_id: ContractId,
    pub action: CallAction,
    pub writer: BorderlessId,
}

/// An outgoing message that clients or agents can subscribe to
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
    pub publisher: Id,
    pub topic: String,
    pub value: Value,
}

/// Convenience function to generate messages
///
/// Returns a [`MsgBuilder`], which can be used to generate messages:
/// ```no_run
/// # use borderless::prelude::*;
/// // Build a new message for topic "/base/nested"
/// let msg = message("/base/nested")
///    .with_value(value!({ "switch": false }));
/// ```
///
/// Note: All topics are prefixed with `/{contract-id}` (or `/{agent-id}`),
/// so your topic `my-topic` would become e.g. `/cc963345-4cd9-8f30-b215-2cdffee3d189/my-topic`.
/// This way we distinguish identical topic names for different contracts or agents.
/// Trailing slashes are ignored, so `/my-topic` and `my-topic` would result in an identical topic string.
///
/// Also be aware, that topic subscriptions and matchings are case-insensitive.
///
/// All of these topics would be identical:
/// - `/my-topic`
/// - `my-topic`
/// - `/My-Topic`
/// - `MY-TOPIC`
pub fn message(topic: impl AsRef<str>) -> MsgBuilder {
    // Fetch publisher from the environment
    let publisher = if is_contract() {
        Id::contract(contract_id())
    } else {
        Id::agent(agent_id())
    };

    MsgBuilder {
        publisher,
        topic: topic.as_ref().to_ascii_lowercase(),
    }
}

pub struct MsgBuilder {
    publisher: Id,
    topic: String,
}

impl MsgBuilder {
    pub fn with_value(self, value: Value) -> Message {
        Message {
            publisher: self.publisher,
            topic: self.topic,
            value,
        }
    }

    pub fn with_content<T: serde::Serialize>(self, content: &T) -> Result<Message, crate::Error> {
        let value = serde_json::to_value(content).map_err(|e| {
            crate::Error::msg(format!(
                "failed to serialize argument for message on topic '{}': {e}",
                self.topic,
            ))
        })?;
        Ok(Message {
            publisher: self.publisher,
            topic: self.topic,
            value,
        })
    }
}

/// Output Events generated by a contract or sw-agent
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Events {
    pub contracts: Vec<ContractCall>,
    pub local: Vec<Message>,
}

impl Events {
    /// Returns `true` if there are no events at all
    pub fn is_empty(&self) -> bool {
        self.contracts.is_empty() && self.local.is_empty()
    }

    /// Decodes the `Events` with [`serde_json`]
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        serde_json::from_slice(bytes)
    }

    /// Encodes the `Events` with [`serde_json`]
    pub fn to_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
        serde_json::to_vec(self)
    }
}

impl From<ContractCall> for Events {
    fn from(value: ContractCall) -> Self {
        Events {
            contracts: vec![value],
            local: Vec::new(),
        }
    }
}

impl From<Message> for Events {
    fn from(value: Message) -> Self {
        Events {
            contracts: Vec::new(),
            local: vec![value],
        }
    }
}

impl From<Vec<ContractCall>> for Events {
    fn from(value: Vec<ContractCall>) -> Self {
        Events {
            contracts: value,
            local: Vec::new(),
        }
    }
}

impl From<Vec<Message>> for Events {
    fn from(value: Vec<Message>) -> Self {
        Events {
            contracts: Vec::new(),
            local: value,
        }
    }
}

/// Trait that indicates that a return type can be used as an output of an action function.
///
/// Note: This trait converts `()`, `ActionOutput`, `Result<(), E>` and `Result<ActionOutput, E>` into [`Events`].
/// The implementation of `ActionOutput` also checks, if the writer actually has access to a sink.
pub trait ActionOutput: Sealed {
    fn convert_out_events(self) -> crate::Result<Events>;
}

mod private {
    pub trait Sealed {}
}

impl Sealed for () {}
impl ActionOutput for () {
    fn convert_out_events(self) -> crate::Result<Events> {
        Ok(Events::default())
    }
}

impl<E> Sealed for Result<(), E> where E: Display + Send + Sync + 'static {}
impl<E> ActionOutput for Result<(), E>
where
    E: Display + Debug + Send + Sync + 'static,
{
    fn convert_out_events(self) -> crate::Result<Events> {
        self.map_err(|e| crate::Error::msg(e))?.convert_out_events()
    }
}

impl Sealed for Events {}
impl ActionOutput for Events {
    fn convert_out_events(self) -> anyhow::Result<Events> {
        Ok(self)
    }
}

impl<E> Sealed for Result<Events, E> where E: Display + Debug + Send + Sync + 'static {}
impl<E> ActionOutput for Result<Events, E>
where
    E: Display + Debug + Send + Sync + 'static,
{
    fn convert_out_events(self) -> anyhow::Result<Events> {
        let inner = self.map_err(|e| crate::Error::msg(e))?;
        inner.convert_out_events()
    }
}

impl Sealed for ContractCall {}
impl ActionOutput for ContractCall {
    fn convert_out_events(self) -> crate::Result<Events> {
        Ok(Events::from(self))
    }
}

impl<E> Sealed for Result<ContractCall, E> where E: Display + Debug + Send + Sync + 'static {}
impl<E> ActionOutput for Result<ContractCall, E>
where
    E: Display + Debug + Send + Sync + 'static,
{
    fn convert_out_events(self) -> crate::Result<Events> {
        let inner = self.map_err(|e| crate::Error::msg(e))?;
        inner.convert_out_events()
    }
}

impl Sealed for Vec<ContractCall> {}
impl ActionOutput for Vec<ContractCall> {
    fn convert_out_events(self) -> anyhow::Result<Events> {
        Ok(Events::from(self))
    }
}

impl<E> Sealed for Result<Vec<ContractCall>, E> where E: Display + Debug + Send + Sync + 'static {}
impl<E> ActionOutput for Result<Vec<ContractCall>, E>
where
    E: Display + Debug + Send + Sync + 'static,
{
    fn convert_out_events(self) -> anyhow::Result<Events> {
        let inner = self.map_err(|e| crate::Error::msg(e))?;
        inner.convert_out_events()
    }
}

impl Sealed for Message {}
impl ActionOutput for Message {
    fn convert_out_events(self) -> anyhow::Result<Events> {
        Ok(Events::from(self))
    }
}

impl<E> Sealed for Result<Message, E> where E: Display + Debug + Send + Sync + 'static {}
impl<E> ActionOutput for Result<Message, E>
where
    E: Display + Debug + Send + Sync + 'static,
{
    fn convert_out_events(self) -> anyhow::Result<Events> {
        let inner = self.map_err(|e| crate::Error::msg(e))?;
        inner.convert_out_events()
    }
}

impl Sealed for Vec<Message> {}
impl ActionOutput for Vec<Message> {
    fn convert_out_events(self) -> anyhow::Result<Events> {
        Ok(Events::from(self))
    }
}

impl<E> Sealed for Result<Vec<Message>, E> where E: Display + Debug + Send + Sync + 'static {}
impl<E> ActionOutput for Result<Vec<Message>, E>
where
    E: Display + Debug + Send + Sync + 'static,
{
    fn convert_out_events(self) -> anyhow::Result<Events> {
        let inner = self.map_err(|e| crate::Error::msg(e))?;
        inner.convert_out_events()
    }
}

/// An event Sink for a smart-contract
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Sink {
    /// Contract-ID of the sink
    pub contract_id: ContractId,
    /// Alias for the sink
    ///
    /// Sinks can be accessed by their alias, allowing an easier lookup.
    pub alias: String,
    /// Participant-Alias of the writer
    ///
    /// All transactions for this `Sink` will be written by this writer.
    pub writer: String,
}

impl Sink {
    /// Creates a new Sink for a SmartContract
    pub fn new(contract_id: ContractId, alias: String, writer: String) -> Sink {
        Sink {
            contract_id,
            alias,
            writer,
        }
    }

    /// Checks the alias of the sink against some string
    ///
    /// Note: The casing is ignored here, as it should be in all alias lookups.
    pub fn has_alias(&self, alias: impl AsRef<str>) -> bool {
        alias.as_ref().eq_ignore_ascii_case(&self.alias)
    }
}

/// A topic for Sw-Agents
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Topic {
    /// The publisher's ID, who creates new messages
    pub publisher: Id,
    /// The topic an agent can subscribe to
    pub topic: String,
    /// The method triggered in the subscriber's side
    pub method: String,
}

impl Topic {
    pub fn new(publisher: Id, topic: impl AsRef<str>, method: impl AsRef<str>) -> Self {
        Topic {
            publisher,
            topic: topic.as_ref().to_string(),
            method: method.as_ref().to_string(),
        }
    }

    pub fn to_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
        serde_json::to_vec(&self)
    }

    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        serde_json::from_slice(bytes)
    }

    /// Checks the method's validity
    ///
    /// The method name cannot contain the delimiter used in our subscriptions DB (newline character)
    pub fn validate(&self) -> bool {
        if self.method.is_empty() {
            return false;
        }
        if self.method.contains('\n') {
            return false;
        }
        true
    }
}

impl Display for Topic {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "topic: /{}/{}, method: {}",
            self.publisher, self.topic, self.method
        )
    }
}

impl From<TopicDto> for Topic {
    fn from(value: TopicDto) -> Self {
        // The method field is only relevant when starting a new subscription
        Topic::new(
            value.publisher,
            value.topic,
            value.method.unwrap_or_default(),
        )
    }
}

/// Data Transfer Object (DTO) for a topic
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TopicDto {
    /// The publisher's ID, who creates new messages
    pub publisher: Id,
    /// The topic an agent can subscribe to
    pub topic: String,
    /// The method triggered in the subscriber's side
    pub method: Option<String>,
}

impl TopicDto {
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        serde_json::from_slice(bytes)
    }
}