borderless 0.1.2

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
use std::{collections::BTreeMap, fmt::Display, str::FromStr};

use borderless_id_types::{AgentId, Uuid};
use borderless_pkg::WasmPkg;
use serde::{Deserialize, Serialize};
use serde_json::Value;

pub use borderless_pkg as pkg;

use crate::{
    contracts::{Role, TxCtx},
    events::Sink,
    BorderlessId, ContractId,
};

/// High level description and information about the contract or agent itself
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Description {
    pub display_name: String,
    pub summary: String,
    #[serde(default)]
    pub legal: Option<String>,
}

/// Metadata of the contract or process.
///
/// Used for administration purposes.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Metadata {
    #[serde(default)]
    /// Time when the contract or process was created (milliseconds since unix epoch)
    pub active_since: u64,

    #[serde(default)]
    /// Transaction context of the contract-introduction transaction
    ///
    /// Is `None`, if the entity is not a contract.
    pub tx_ctx_introduction: Option<TxCtx>,

    /// Time when the contract or process was revoked or archived (milliseconds since unix epoch)
    #[serde(default)]
    pub inactive_since: u64,

    #[serde(default)]
    /// Transaction context of the contract-revocation transaction (only for contracts)
    ///
    /// Is `None`, if the entity is not a contract.
    pub tx_ctx_revocation: Option<TxCtx>,

    /// Parent of the contract or process (in case the contract / agent was updated or replaced by a newer version)
    #[serde(default)]
    pub parent: Option<Uuid>,
}

/// Generalized ID-Tag for contracts and agents
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum Id {
    Contract { contract_id: ContractId },
    Agent { agent_id: AgentId },
}

impl Id {
    pub fn as_cid(&self) -> Option<ContractId> {
        match self {
            Id::Contract { contract_id } => Some(*contract_id),
            Id::Agent { .. } => None,
        }
    }

    pub fn as_aid(&self) -> Option<AgentId> {
        match self {
            Id::Contract { .. } => None,
            Id::Agent { agent_id } => Some(*agent_id),
        }
    }

    pub fn contract(contract_id: ContractId) -> Self {
        Id::Contract { contract_id }
    }

    pub fn agent(agent_id: AgentId) -> Self {
        Id::Agent { agent_id }
    }
}

impl Display for Id {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Id::Contract { contract_id } => write!(f, "{contract_id}"),
            Id::Agent { agent_id } => write!(f, "{agent_id}"),
        }
    }
}

impl AsRef<[u8; 16]> for Id {
    fn as_ref(&self) -> &[u8; 16] {
        match self {
            Id::Contract { contract_id } => contract_id.as_ref(),
            Id::Agent { agent_id } => agent_id.as_ref(),
        }
    }
}

impl PartialEq<ContractId> for Id {
    fn eq(&self, other: &ContractId) -> bool {
        match self {
            Id::Contract { contract_id } => contract_id == other,
            Id::Agent { .. } => false,
        }
    }
}

impl PartialEq<AgentId> for Id {
    fn eq(&self, other: &AgentId) -> bool {
        match self {
            Id::Agent { agent_id } => agent_id == other,
            Id::Contract { .. } => false,
        }
    }
}

impl From<ContractId> for Id {
    fn from(contract_id: ContractId) -> Self {
        Id::Contract { contract_id }
    }
}

impl From<AgentId> for Id {
    fn from(agent_id: AgentId) -> Self {
        Id::Agent { agent_id }
    }
}

// NOTE: We could re-write the participant logic like this
//
// But that's maybe something for later.
//
// pub struct Participant {
//     pub borderless_id: BorderlessId,
//     pub alias: String,
//     pub roles: Vec<String>,
//     pub sinks: Vec<String>,
// }
// { "borderless-id": "4bec7f8e-5074-49a5-9b94-620fb13f12c0", "alias": null, roles": [ "Flipper" ], "sinks": [ "OTHERFLIPPER" ] },

/*
 * Ok, spitballing here:
 *
 * I think the sinks as they are now, are quite OK.
 * The only thing I would change is, that the sinks that the contract itself defines (with the enum),
 * should work differently in the way that they just output their data as plain json,
 * and the sinks (enum below) are used to subscribe to those outputs using the "alias".
 * We should add a "MethodOrId" to each sink; then we are able to build the CallAction struct for the corresponding
 * contract or agent.
 */

/// An introduction of either a contract or agent
///
/// There are no two distinct types, since the similarities between contracts and agents are quite big.
/// The main difference is, that agents have no roles attached to them and are not introduced or revoked by a transaction.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Introduction {
    /// Contract- or Agent-ID
    #[serde(flatten)]
    pub id: Id,

    /// List of participants
    #[serde(default)]
    pub participants: Vec<BorderlessId>,

    /// Initial state as JSON value
    ///
    /// This will be parsed by the implementors of the contract or agent
    pub initial_state: Value,

    /// Mapping between users and roles.
    ///
    /// Only relevant for contracts
    #[serde(default)]
    pub roles: Vec<Role>,

    /// List of available sinks
    #[serde(default)]
    pub sinks: Vec<Sink>,

    /// High-Level description of the contract or agent
    pub desc: Description,

    #[serde(default)]
    /// metadata of the contract or agent
    pub meta: Metadata,

    /// Definition of the wasm package for this contract or agent
    pub package: WasmPkg,
}

impl Introduction {
    /// Encode the introduction to json bytes
    pub fn to_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
        serde_json::to_vec(&self)
    }

    /// Decode the introduction from json bytes
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        serde_json::from_slice(bytes)
    }

    /// Pretty-Print the introduction as json
    pub fn pretty_print(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self)
    }
}

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

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

/// Digital-Tranfer-Object (Dto) of an [`Introduction`]
///
/// When new contracts or agents are created via web-api, things like [`Metadata`] do not make sense yet.
/// This DTO omits the metadata and makes the [`Id`] optional, so a new [`Id`] can be generated for the package.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IntroductionDto {
    /// Optional Contract- or Agent-ID
    ///
    /// If this field is empty, a new ID will be generated for the contract or agent.
    #[serde(flatten)]
    #[serde(default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,

    /// List of participants
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub participants: Vec<BorderlessId>,

    /// Initial state as JSON value
    ///
    /// This will be parsed by the implementors of the contract or agent
    pub initial_state: Value,

    /// Mapping between users and roles.
    ///
    /// Only relevant for contracts
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub roles: Vec<Role>,

    /// List of available sinks
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub sinks: Vec<Sink>,

    /// High-Level description of the contract or agent
    pub desc: Description,

    /// Definition of the wasm package for this contract or agent
    pub package: WasmPkg,
}

// TODO: Implement conversion from DTO to Introduction

/// Contract revocation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Revocation {
    /// Contract- or Agent-ID
    #[serde(flatten)]
    pub id: Id,

    /// Reason for the revocation
    pub reason: String,
}

impl Revocation {
    /// Encode the revocation to json bytes
    pub fn to_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
        serde_json::to_vec(&self)
    }

    /// Decode the revocation from json bytes
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        serde_json::from_slice(bytes)
    }

    /// Pretty-Print the revocation as json
    pub fn pretty_print(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self)
    }
}

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

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

/// Generated symbols of a contract
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Symbols {
    /// Fields and addresses (storage-keys) of the contract-state
    pub state: BTreeMap<String, u64>,
    /// Method-names and method-ids of all actions
    pub actions: BTreeMap<String, u32>,
}

impl Symbols {
    // TODO: I liked the hex-encoding more, but it also made it harder to debug based on the generated symbols in the contract.
    //
    // We should either use hex everywhere or the raw number everywhere. For now I will use the numbers here, but I would maybe change
    // the macro later to utilize the hex-encoding.
    pub fn from_symbols(state_syms: &[(&str, u64)], action_syms: &[(&str, u32)]) -> Self {
        // NOTE: We use a BTreeMap instead of a hash-map to get sorted keys.
        let mut state = BTreeMap::new();
        for (name, addr) in state_syms {
            state.insert(name.to_string(), *addr);
        }
        let mut actions = BTreeMap::new();
        for (name, addr) in action_syms {
            actions.insert(name.to_string(), *addr);
        }
        Self { state, actions }
    }

    /// Use json to encode the `Symbols`
    pub fn to_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
        serde_json::to_vec(self)
    }

    /// Use json to decode the `Symbols`
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, serde_json::Error> {
        serde_json::from_slice(bytes)
    }
}

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

    #[test]
    fn general_id() {
        let cid = r#"{ "contract_id": "cbcd81bb-b90c-8806-8341-fe95b8ede45a" }"#;
        let aid = r#"{ "agent_id": "abcd81bb-b90c-8806-8341-fe95b8ede45a" }"#;
        let parsed: Result<Id, _> = serde_json::from_str(&cid);
        assert!(parsed.is_ok(), "{}", parsed.unwrap_err());
        match parsed.unwrap() {
            Id::Contract { contract_id } => assert_eq!(
                contract_id.to_string(),
                "cbcd81bb-b90c-8806-8341-fe95b8ede45a"
            ),
            Id::Agent { .. } => panic!("result was not an agent-id"),
        }

        let parsed: Result<Id, _> = serde_json::from_str(&aid);
        assert!(parsed.is_ok(), "{}", parsed.unwrap_err());
        match parsed.unwrap() {
            Id::Agent { agent_id } => {
                assert_eq!(agent_id.to_string(), "abcd81bb-b90c-8806-8341-fe95b8ede45a")
            }
            Id::Contract { .. } => panic!("result was not a contract-id"),
        }
    }

    #[test]
    fn parse_introduction() {
        let json = r#"
{
  "contract_id": "cc8ca79c-3bbb-89d2-bb28-29636c170387",
  "participants": [],
  "initial_state": {
    "switch": true,
    "counter": 0,
    "history": []
  },
  "roles": [],
  "sinks": [],
  "desc": {
    "display_name": "flipper",
    "summary": "a flipper contract for testing the abi",
    "legal": null
  },
  "meta": {},
  "package": {
     "name": "flipper-contract",
     "pkg_type": "contract",
     "source": {
        "version": "0.1.0",
        "digest": "",
        "wasm": ""
     }
  }
}
"#;
        let result: Result<Introduction, _> = serde_json::from_str(&json);
        assert!(result.is_ok(), "{}", result.unwrap_err());
        let introduction = result.unwrap();
        assert_eq!(
            introduction.id,
            Id::Contract {
                contract_id: "cc8ca79c-3bbb-89d2-bb28-29636c170387".parse().unwrap()
            }
        );
        let json = json.replace(r#""contract_id": "c"#, r#""agent_id": "a"#);
        let result: Result<Introduction, _> = serde_json::from_str(&json);
        assert!(result.is_ok(), "{}", result.unwrap_err());
        let introduction = result.unwrap();
        assert_eq!(
            introduction.id,
            Id::Agent {
                agent_id: "ac8ca79c-3bbb-89d2-bb28-29636c170387".parse().unwrap()
            }
        );
    }
}