domino_cli 0.1.1

Client to interact with a domino application running on holochain
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
use crate::CommonOpts;
use crate::{display::format_table, ham::Ham};
use anyhow::Result;
use colored::Colorize;
use dialoguer::{Confirm, Input, Select};
use holochain_client::Timestamp;
use holochain_types::dna::ActionHash;
use rave_engine::types::entries::{
    AddressBook, GlobalDefinition, GlobalDefinitionExt, SystemSAVEDAgreements,
    TransactionFeeCompute, UnitDefinition, UnitDefinitionExt,
};
use rave_engine::types::{ActionHashB64, AgentPubKeyB64};
use serde_json::Value;
use std::str::FromStr;
use std::time::Duration;
use zfuel::fuel::ZFuel;

pub async fn initialize_global_definition(
    value: CommonOpts,
    effective_start_date: Option<u64>,
    expiration_duration_days: Option<u64>,
    pay_transaction_fee_agreement: Option<ActionHashB64>,
    compute_credit_limit_agreement: Option<ActionHashB64>,
    executor: Option<Option<AddressBook>>,
    additional_saved_agreements: Option<Vec<ActionHashB64>>,
) -> Result<()> {
    let agent = Ham::connect(value.clone()).await?;
    println!("{}", "\nGlobal Definition Setup".bold().underline());

    // 1. Get effective start date
    let effective_start_date = if effective_start_date.is_none() {
        let use_current = Select::new()
            .with_prompt("When should this global definition become effective?")
            .items(&["Use current time", "Specify custom date"])
            .default(0)
            .interact()?;

        if use_current == 0 {
            None
        } else {
            let days: u64 = Input::new()
                .with_prompt("Enter number of days from now")
                .default(0)
                .interact()?;
            Some(Timestamp::now().as_micros() as u64 + (days * 24 * 60 * 60 * 1_000_000))
        }
    } else {
        effective_start_date
    };

    // 2. Get expiration duration
    let expiration_duration_days = if expiration_duration_days.is_none() {
        let days: u64 = Input::new()
            .with_prompt("Enter global definition duration in days (default 30)")
            .default(30)
            .interact()?;
        Some(days)
    } else {
        expiration_duration_days
    };

    // 3. Get agreements if not provided
    let pay_transaction_fee_agreement = if pay_transaction_fee_agreement.is_none() {
        let input: String = Input::new()
            .with_prompt("Enter transaction fee agreement hash")
            .interact()?;
        Some(ActionHashB64::from_str(&input)?)
    } else {
        pay_transaction_fee_agreement
    };

    let compute_credit_limit_agreement = if compute_credit_limit_agreement.is_none() {
        let input: String = Input::new()
            .with_prompt("Enter credit limit agreement hash")
            .interact()?;
        Some(ActionHashB64::from_str(&input)?)
    } else {
        compute_credit_limit_agreement
    };

    // 4. Get special agents
    let executor = if executor.is_none() {
        let mut agents: Option<AddressBook> = None;

        println!("\n{}", "Special Agents Setup".bold());
        println!("These agents will be authorized to collect transaction fees");

        loop {
            let action = Select::new()
                .with_prompt("Executor Menu")
                .items(&["Add agent", "Done"])
                .default(0)
                .interact()?;

            match action {
                0 => {
                    // Add agent
                    let agent: String = Input::new()
                        .with_prompt("Enter agent public key")
                        .interact()?;

                    match AgentPubKeyB64::from_str(&agent) {
                        Ok(agent_key) => {
                            let address_book = AddressBook {
                                pub_key: agent_key,
                                address_book_data: Value::Null,
                            };
                            agents = Some(address_book);
                            println!("✓ Agent added");
                        }
                        Err(_) => println!("✗ Invalid agent public key, try again"),
                    };
                }
                _ => break,
            }
        }

        if agents.is_none() {
            println!("\n{}", "Warning: No executor added. This means no one will be able to collect transaction fees.".yellow());
            if !Confirm::new()
                .with_prompt("Continue without executor?")
                .default(false)
                .interact()?
            {
                return Err(anyhow::anyhow!("Cancelled - no executor added"));
            }
        }

        agents
    } else {
        executor.unwrap()
    };

    // 5. Get additional saved agreements
    let additional_saved_agreements = if additional_saved_agreements.is_none() {
        let mut agreements = Vec::new();

        println!("\n{}", "Additional SAVED Agreements Setup".bold());
        println!("These are optional agreements that will be added to the global");

        loop {
            let action = Select::new()
                .with_prompt("Additional Agreements Menu")
                .items(&[
                    "Add agreement",
                    "List agreements",
                    "Remove agreement",
                    "Done",
                ])
                .default(0)
                .interact()?;

            match action {
                0 => {
                    // Add agreement
                    let agreement_hash: String = Input::new()
                        .with_prompt("Enter agreement hash")
                        .interact()?;

                    match ActionHashB64::from_str(&agreement_hash) {
                        Ok(agreement_id) => {
                            // Get special agents for this agreement
                            let mut agreement_agents = Vec::new();

                            loop {
                                let agent_action = Select::new()
                                    .with_prompt("Special Agents for this Agreement")
                                    .items(&["Add agent", "List agents", "Remove agent", "Done"])
                                    .default(0)
                                    .interact()?;

                                match agent_action {
                                    0 => {
                                        let agent: String = Input::new()
                                            .with_prompt("Enter agent public key")
                                            .interact()?;

                                        match AgentPubKeyB64::from_str(&agent) {
                                            Ok(agent_key) => {
                                                agreement_agents.push(agent_key);
                                                println!("✓ Agent added");
                                            }
                                            Err(_) => println!("✗ Invalid agent public key"),
                                        }
                                    }
                                    1 => {
                                        if agreement_agents.is_empty() {
                                            println!("No agents added yet");
                                        } else {
                                            println!("\nCurrent agents for this agreement:");
                                            for (i, agent) in agreement_agents.iter().enumerate() {
                                                println!("{}. {}", i + 1, agent);
                                            }
                                        }
                                    }
                                    2 => {
                                        if agreement_agents.is_empty() {
                                            println!("No agents to remove");
                                            continue;
                                        }

                                        let choices: Vec<String> = agreement_agents
                                            .iter()
                                            .map(|a| a.to_string())
                                            .collect();

                                        let selection = Select::new()
                                            .with_prompt("Select agent to remove")
                                            .items(&choices)
                                            .interact()?;

                                        agreement_agents.remove(selection);
                                        println!("✓ Agent removed");
                                    }
                                    _ => break,
                                }
                            }

                            agreements.push(agreement_id.into());
                            println!("✓ Agreement added");
                        }
                        Err(_) => println!("✗ Invalid agreement hash"),
                    }
                }
                1 => {
                    // List agreements
                    if agreements.is_empty() {
                        println!("No agreements added yet");
                    } else {
                        println!("\nCurrent agreements:");
                        for (i, agreement) in agreements.iter().enumerate() {
                            println!("{}. Agreement ID: {}", i + 1, agreement);
                        }
                    }
                }
                2 => {
                    // Remove agreement
                    if agreements.is_empty() {
                        println!("No agreements to remove");
                        continue;
                    }

                    let choices: Vec<String> =
                        agreements.iter().map(|a| format!("ID: {} ", a)).collect();

                    let selection = Select::new()
                        .with_prompt("Select agreement to remove")
                        .items(&choices)
                        .interact()?;

                    agreements.remove(selection);
                    println!("✓ Agreement removed");
                }
                _ => break,
            }
        }

        agreements
    } else {
        additional_saved_agreements.unwrap()
    };

    // Create and submit global definition
    let effective_start_date = if let Some(start) = effective_start_date {
        Timestamp::from_micros(start as i64)
    } else {
        Timestamp::now()
    };

    let days = expiration_duration_days.unwrap_or(30);
    let duration = Duration::from_secs(days * 24 * 60 * 60);
    let expiration_date = (effective_start_date + duration)?;

    let additional_special_agents = if let Some(executor) = executor.clone() {
        vec![executor]
    } else {
        vec![]
    };
    let global_definition = GlobalDefinition {
        effective_start_date,
        expiration_date,
        system_saved_agreements: SystemSAVEDAgreements {
            compute_credit_limit: compute_credit_limit_agreement.unwrap().into(),
            compute_transaction_fee: TransactionFeeCompute {
                agreement: pay_transaction_fee_agreement.unwrap().into(),
                fee_trigger: ZFuel::from_str("10").unwrap(),
                fee_percentage: 1,
            },
        },
        additional_special_agents,
        additional_saved_agreements: additional_saved_agreements.clone(),
    };

    // Show summary before submitting
    println!("\n{}", "Review Global Definition".bold());
    println!("Effective Start: {}", effective_start_date);
    println!("Expiration Date: {}", expiration_date);
    println!("Executor: {:?}", executor);
    println!(
        "Additional Agreements: {}",
        additional_saved_agreements.len()
    );

    let confirm = Select::new()
        .with_prompt("Submit global definition?")
        .items(&["Yes", "No"])
        .default(0)
        .interact()?;

    if confirm == 1 {
        println!("Cancelled");
        return Ok(());
    }

    let result: ActionHash = agent
        .zome_call(
            "alliance",
            "transactor",
            "initialize_global_definition",
            global_definition,
        )
        .await?;

    println!("\n{}", "Global Definition Initialized:".green());
    println!("Action Hash: {}", result);

    Ok(())
}

pub async fn get_current_global_definition(value: CommonOpts) -> Result<()> {
    let agent = Ham::connect(value).await?;

    let result: GlobalDefinitionExt = agent
        .zome_call(
            "alliance",
            "transactor",
            "get_current_global_definition",
            (),
        )
        .await?;

    println!("{}", "Global Definitions:".bold());
    println!("{:?}", result);

    Ok(())
}

pub async fn add_global_units(value: CommonOpts, unit_definition: UnitDefinition) -> Result<()> {
    let agent = Ham::connect(value).await?;

    let result: ActionHash = agent
        .zome_call(
            "alliance",
            "transactor",
            "add_global_units",
            unit_definition,
        )
        .await?;

    println!("Global Units Added:");
    println!("Action Hash: {:?}", result);

    Ok(())
}

pub async fn update_global_units(
    value: CommonOpts,
    unit_definition: UnitDefinitionExt,
) -> Result<()> {
    let agent = Ham::connect(value).await?;

    let result: ActionHash = agent
        .zome_call(
            "alliance",
            "transactor",
            "update_global_units",
            unit_definition,
        )
        .await?;

    println!("Global Units Updated:");
    println!("Action Hash: {:?}", result);

    Ok(())
}

pub async fn get_global_units_details(value: CommonOpts) -> Result<()> {
    let agent = Ham::connect(value).await?;

    let result: Vec<UnitDefinitionExt> = agent
        .zome_call("alliance", "transactor", "get_global_units_details", ())
        .await?;

    println!("Global Units Details:");
    if !result.is_empty() {
        let table = format_table(&result, "Global Units");
        table.printstd();
    } else {
        println!("{}", "No global units".dimmed());
    }

    Ok(())
}