a4-cli 0.44.2

CLI tool for generating TypeScript SDKs from Arete stream specifications
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
//! Generated by a4 from protocol package `local-tip-jar` 0.1.0 (arete.protocol-spec/v1 `localTipJar`). Do not edit.
//!
//! Local development fixture: two templated System Program transfers.
//!
//! Create a client with [`LocalTipJarPublishableClient`] (publishable key, `public` steps
//! only) or [`LocalTipJarSecretClient`] (secret key, every client-callable step).

use arete_sdk::protocol;
pub use arete_sdk::protocol::{
    verify_webhook, ProtocolClient, ProtocolClientOptions, ProtocolError, ProtocolInteger,
    ProtocolPrepareOptions, ProtocolPrepareResult, ProtocolPrepared, ProtocolRejection,
    ProtocolRejectionCode,
};

/// The stacks this protocol reads, as `a4 install stack --rust` generates them.
pub mod stacks {}

/// The programs this protocol uses, as `a4 install program --rust` generates them.
pub mod programs {}

/// States of the instance machine.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum LocalTipJarInstanceState {
    #[serde(rename = "closed")]
    Closed,
    #[serde(rename = "open")]
    Open,
}

impl LocalTipJarInstanceState {
    pub const ALL: [Self; 2] = [Self::Closed, Self::Open];

    /// The name on the wire.
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::Closed => "closed",
            Self::Open => "open",
        }
    }

    /// The variant named `wire`, if this release knows it.
    pub fn from_wire(wire: &str) -> Option<Self> {
        match wire {
            "closed" => Some(Self::Closed),
            "open" => Some(Self::Open),
            _ => None,
        }
    }
}

impl LocalTipJarInstanceState {
    /// The state of a read instance, if this release knows it.
    pub fn of(instance: &protocol::ProtocolInstanceSummary) -> Option<Self> {
        Self::from_wire(&instance.state)
    }

    /// No step leaves this state.
    pub fn is_terminal(self) -> bool {
        matches!(self, Self::Closed)
    }
}

/// Parameters an instance is created with.
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct LocalTipJarParams {
    /// Format: `u64`.
    pub amount: ProtocolInteger,
}

/// Arguments of the `close` step.
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct LocalTipJarCloseArgs {
    /// Format: `u64`.
    pub amount: ProtocolInteger,
}

/// Arguments of the `open` step.
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct LocalTipJarOpenArgs {
    /// Format: `u64`.
    pub amount: ProtocolInteger,
    /// Format: `pubkey`.
    pub recipient: String,
}

/// An instance's metadata document: the fields written so far.
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct LocalTipJarInstanceMetadata {}

/// A participant's metadata document: the fields written so far.
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct LocalTipJarParticipantMetadata {}

impl LocalTipJarInstanceMetadata {
    /// Read a metadata document.
    pub fn from_map(
        metadata: &serde_json::Map<String, serde_json::Value>,
    ) -> Result<Self, serde_json::Error> {
        serde_json::from_value(serde_json::Value::Object(metadata.clone()))
    }

    /// The fields set here, as a merge patch for `update_metadata`.
    pub fn to_patch(&self) -> serde_json::Map<String, serde_json::Value> {
        match serde_json::to_value(self) {
            Ok(serde_json::Value::Object(patch)) => patch,
            _ => serde_json::Map::new(),
        }
    }
}

impl LocalTipJarParticipantMetadata {
    /// Read a metadata document.
    pub fn from_map(
        metadata: &serde_json::Map<String, serde_json::Value>,
    ) -> Result<Self, serde_json::Error> {
        serde_json::from_value(serde_json::Value::Object(metadata.clone()))
    }

    /// The fields set here, as a merge patch for `update_metadata`.
    pub fn to_patch(&self) -> serde_json::Map<String, serde_json::Value> {
        match serde_json::to_value(self) {
            Ok(serde_json::Value::Object(patch)) => patch,
            _ => serde_json::Map::new(),
        }
    }
}

/// Guard codes the `close` step can reject with, in evaluation order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LocalTipJarCloseGuardCode {
    NotRecipient,
    NotOpen,
}

impl LocalTipJarCloseGuardCode {
    pub const ALL: [Self; 2] = [Self::NotRecipient, Self::NotOpen];

    /// The name on the wire.
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::NotRecipient => "not_recipient",
            Self::NotOpen => "not_open",
        }
    }

    /// The variant named `wire`, if this release knows it.
    pub fn from_wire(wire: &str) -> Option<Self> {
        match wire {
            "not_recipient" => Some(Self::NotRecipient),
            "not_open" => Some(Self::NotOpen),
            _ => None,
        }
    }
}

impl protocol::ProtocolGuardCode for LocalTipJarCloseGuardCode {
    fn from_wire(wire: &str) -> Option<Self> {
        Self::from_wire(wire)
    }

    fn as_wire(&self) -> &str {
        (*self).as_wire()
    }
}

/// Guard codes the `open` step can reject with, in evaluation order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LocalTipJarOpenGuardCode {
    AmountZero,
}

impl LocalTipJarOpenGuardCode {
    pub const ALL: [Self; 1] = [Self::AmountZero];

    /// The name on the wire.
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::AmountZero => "amount_zero",
        }
    }

    /// The variant named `wire`, if this release knows it.
    pub fn from_wire(wire: &str) -> Option<Self> {
        match wire {
            "amount_zero" => Some(Self::AmountZero),
            _ => None,
        }
    }
}

impl protocol::ProtocolGuardCode for LocalTipJarOpenGuardCode {
    fn from_wire(wire: &str) -> Option<Self> {
        Self::from_wire(wire)
    }

    fn as_wire(&self) -> &str {
        (*self).as_wire()
    }
}

/// Events the protocol emits, on the event stream and to webhooks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LocalTipJarEvent {
    TipJarClosed,
}

impl LocalTipJarEvent {
    pub const ALL: [Self; 1] = [Self::TipJarClosed];

    /// The name on the wire.
    pub fn as_wire(self) -> &'static str {
        match self {
            Self::TipJarClosed => "tipJar.closed",
        }
    }

    /// The variant named `wire`, if this release knows it.
    pub fn from_wire(wire: &str) -> Option<Self> {
        match wire {
            "tipJar.closed" => Some(Self::TipJarClosed),
            _ => None,
        }
    }
}

impl LocalTipJarEvent {
    /// The machine the event belongs to.
    pub fn machine(self) -> protocol::ProtocolMachineKind {
        match self {
            Self::TipJarClosed => protocol::ProtocolMachineKind::Instance,
        }
    }

    /// The event a webhook payload carries, if this release knows it.
    pub fn of(payload: &protocol::ProtocolEventPayloadV1) -> Option<Self> {
        Self::from_wire(&payload.event)
    }
}

/// The `localTipJar` protocol and the deployment this client calls.
pub const LOCAL_TIP_JAR_PROTOCOL: protocol::ProtocolDefinition = protocol::ProtocolDefinition {
    name: "localTipJar",
    version: "0.1.0",
    package: "local-tip-jar",
    package_release_hash: "arete:h1:protocol-release:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    protocol_spec_hash: "arete:h1:protocol-spec:sha256:f1a6580e1d2259ca7da870e33e0a1920ea0704cf2014efccf29116c4abc06032",
    protocol_release_hash: "arete:h1:protocol-release:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    deployment: protocol::ProtocolDeploymentDescriptor {
        deployment_id: "dep-local-1",
        access: protocol::ProtocolDeploymentAccess::Private,
        api_url: "https://api.example.test/api",
        session_endpoint: "https://api.example.test/ws/sessions",
    },
    instance_visibility: protocol::ProtocolInstanceVisibility::Shared,
    steps: &[
        protocol::ProtocolStepDefinition {
            name: "close",
            scope: protocol::ProtocolStepScope::Instance,
            access: protocol::ProtocolStepAccess::Secret,
            guards: &["not_recipient", "not_open"],
            args: &["amount"],
        },
        protocol::ProtocolStepDefinition {
            name: "open",
            scope: protocol::ProtocolStepScope::Create,
            access: protocol::ProtocolStepAccess::Secret,
            guards: &["amount_zero"],
            args: &["amount", "recipient"],
        },
    ],
    events: &[
        protocol::ProtocolEventDefinition { name: "tipJar.closed", machine: protocol::ProtocolMachineKind::Instance },
    ],
    instance_metadata: &[],
    participant_metadata: &[],
    live_stack: None,
};

/// A client for a publishable key (`a4_pk_...`): it can prepare the `public`
/// steps only.
///
/// Reads, submit, metadata and the event stream come from [`ProtocolClient`]
/// through `Deref`.
#[derive(Debug, Clone)]
pub struct LocalTipJarPublishableClient {
    client: ProtocolClient,
}

impl LocalTipJarPublishableClient {
    /// Authenticate with a publishable key.
    pub fn new(publishable_key: impl Into<String>) -> Result<Self, ProtocolError> {
        Self::with_options(ProtocolClientOptions::default().with_publishable_key(publishable_key))
    }

    /// Full options: tokens, token providers, URL overrides, an HTTP client.
    pub fn with_options(mut options: ProtocolClientOptions) -> Result<Self, ProtocolError> {
        options.key_class = Some(protocol::ProtocolKeyClass::Publishable);
        Ok(Self {
            client: ProtocolClient::new(&LOCAL_TIP_JAR_PROTOCOL, options)?,
        })
    }

    /// A client on `session`'s auth whose instance handles follow the
    /// session's stack members; see `Session::protocol_client`.
    pub fn from_session(
        session: &arete_sdk::Session,
        mut options: ProtocolClientOptions,
    ) -> Result<Self, ProtocolError> {
        options.key_class = Some(protocol::ProtocolKeyClass::Publishable);
        Ok(Self {
            client: session.protocol_client(&LOCAL_TIP_JAR_PROTOCOL, options)?,
        })
    }

    /// The untyped client.
    pub fn client(&self) -> &ProtocolClient {
        &self.client
    }

    /// Load an instance and keep it current from its event stream.
    ///
    /// This protocol publishes no live stack view.
    pub async fn instance_handle(
        &self,
        instance: &str,
    ) -> Result<protocol::ProtocolInstanceHandle, ProtocolError> {
        self.client.instance_handle(instance).await
    }
}

impl std::ops::Deref for LocalTipJarPublishableClient {
    type Target = ProtocolClient;

    fn deref(&self) -> &ProtocolClient {
        &self.client
    }
}

/// A client for a secret or agent key (`a4_sk_...`, `a4_ak_...`): it can prepare
/// every client-callable step. Keep it on servers.
///
/// Reads, submit, metadata and the event stream come from [`ProtocolClient`]
/// through `Deref`.
#[derive(Debug, Clone)]
pub struct LocalTipJarSecretClient {
    client: ProtocolClient,
}

impl LocalTipJarSecretClient {
    /// Authenticate with a secret or agent key.
    pub fn new(secret_key: impl Into<String>) -> Result<Self, ProtocolError> {
        Self::with_options(ProtocolClientOptions::default().with_secret_key(secret_key))
    }

    /// Authenticate with `ARETE_API_KEY`, or else the `a4` CLI login.
    pub fn from_env() -> Result<Self, ProtocolError> {
        Self::with_options(ProtocolClientOptions::default())
    }

    /// Full options: tokens, token providers, URL overrides, an HTTP client.
    pub fn with_options(mut options: ProtocolClientOptions) -> Result<Self, ProtocolError> {
        options.key_class = Some(protocol::ProtocolKeyClass::Secret);
        Ok(Self {
            client: ProtocolClient::new(&LOCAL_TIP_JAR_PROTOCOL, options)?,
        })
    }

    /// A client on `session`'s auth whose instance handles follow the
    /// session's stack members; see `Session::protocol_client`.
    pub fn from_session(
        session: &arete_sdk::Session,
        mut options: ProtocolClientOptions,
    ) -> Result<Self, ProtocolError> {
        options.key_class = Some(protocol::ProtocolKeyClass::Secret);
        Ok(Self {
            client: session.protocol_client(&LOCAL_TIP_JAR_PROTOCOL, options)?,
        })
    }

    /// The untyped client.
    pub fn client(&self) -> &ProtocolClient {
        &self.client
    }

    /// Load an instance and keep it current from its event stream.
    ///
    /// This protocol publishes no live stack view.
    pub async fn instance_handle(
        &self,
        instance: &str,
    ) -> Result<protocol::ProtocolInstanceHandle, ProtocolError> {
        self.client.instance_handle(instance).await
    }

    /// Prepare `close` (instance step, role `recipient` authority): Close the tip jar.
    ///
    /// Resolves with the intent and the transactions for `wallet` to sign, or
    /// with a rejection carrying a [`LocalTipJarCloseGuardCode`] or an access code.
    pub async fn prepare_close(
        &self,
        instance: &str,
        wallet: &str,
        args: &LocalTipJarCloseArgs,
        options: ProtocolPrepareOptions,
    ) -> Result<ProtocolPrepareResult<LocalTipJarCloseGuardCode>, ProtocolError> {
        self.client
            .prepare("close", Some(instance), wallet, args, options)
            .await
    }

    /// Prepare `open` (create step, creator authority): Open a tip jar.
    ///
    /// Resolves with the intent and the transactions for `wallet` to sign, or
    /// with a rejection carrying a [`LocalTipJarOpenGuardCode`] or an access code.
    pub async fn prepare_open(
        &self,
        wallet: &str,
        args: &LocalTipJarOpenArgs,
        options: ProtocolPrepareOptions,
    ) -> Result<ProtocolPrepareResult<LocalTipJarOpenGuardCode>, ProtocolError> {
        self.client
            .prepare("open", None, wallet, args, options)
            .await
    }
}

impl std::ops::Deref for LocalTipJarSecretClient {
    type Target = ProtocolClient;

    fn deref(&self) -> &ProtocolClient {
        &self.client
    }
}

/// A webhook delivery of this protocol's events; read its event with [`LocalTipJarEvent::of`].
pub type LocalTipJarWebhookPayload = protocol::ProtocolEventPayloadV1;

/// Verify a signed webhook delivery for this protocol's events. Pass the raw
/// request body exactly as received.
pub fn verify_local_tip_jar_webhook(
    secret: impl AsRef<[u8]>,
    body: impl AsRef<[u8]>,
    headers: &(impl protocol::WebhookHeaders + ?Sized),
    options: protocol::VerifyWebhookOptions,
) -> Result<protocol::VerifiedWebhook<LocalTipJarWebhookPayload>, protocol::WebhookVerificationError> {
    protocol::verify_webhook(secret, body, headers, options)
}