cargo-tangle 0.7.1

A command-line tool to create and deploy blueprints on Tangle Network
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
use super::chain::log_tx;
use alloy_primitives::{Address, U256};
use blueprint_client_tangle::BlueprintSelectionMode;
use cargo_tangle::command::{
    delegator,
    tangle::{TangleClientArgs, parse_address},
};
use clap::Subcommand;
use color_eyre::eyre::{Result, ensure, eyre};

#[derive(clap::ValueEnum, Clone, Copy, Debug)]
pub(super) enum DelegationSelection {
    /// Delegation applies to all blueprints the operator supports.
    All,
    /// Delegation is pinned to specific blueprint IDs.
    Fixed,
}

#[derive(Subcommand, Debug)]
pub(super) enum DelegatorCommands {
    /// Show all staking positions for a delegator.
    ///
    /// Displays deposits, locks, active delegations, and pending requests.
    Positions {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Delegator address to query (defaults to your address).
        #[arg(long)]
        delegator: Option<String>,
        /// Token contract address (0x0 for native ETH/TNT).
        #[arg(long, default_value = "0x0000000000000000000000000000000000000000")]
        token: String,
        /// Output as JSON instead of formatted table.
        #[arg(long)]
        json: bool,
    },
    /// List active delegations from a delegator to operators.
    Delegations {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Delegator address to query (defaults to your address).
        #[arg(long)]
        delegator: Option<String>,
        /// Output as JSON instead of formatted table.
        #[arg(long)]
        json: bool,
    },
    /// List pending unstake requests waiting for unbonding period.
    PendingUnstakes {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Delegator address to query (defaults to your address).
        #[arg(long)]
        delegator: Option<String>,
        /// Output as JSON instead of formatted table.
        #[arg(long)]
        json: bool,
    },
    /// List pending withdrawal requests waiting for unbonding period.
    PendingWithdrawals {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Delegator address to query (defaults to your address).
        #[arg(long)]
        delegator: Option<String>,
        /// Output as JSON instead of formatted table.
        #[arg(long)]
        json: bool,
    },
    /// Check ERC20 token allowance for the staking contract.
    ///
    /// Shows how many tokens the contract can spend on your behalf.
    Allowance {
        #[command(flatten)]
        network: TangleClientArgs,
        /// ERC20 token contract address.
        #[arg(long)]
        token: String,
        /// Token owner address (defaults to your address).
        #[arg(long)]
        owner: Option<String>,
        /// Spender address (defaults to staking contract).
        #[arg(long)]
        spender: Option<String>,
        /// Output as JSON instead of formatted table.
        #[arg(long)]
        json: bool,
    },
    /// Check ERC20 token balance.
    Balance {
        #[command(flatten)]
        network: TangleClientArgs,
        /// ERC20 token contract address.
        #[arg(long)]
        token: String,
        /// Address to check balance for (defaults to your address).
        #[arg(long)]
        owner: Option<String>,
        /// Output as JSON instead of formatted table.
        #[arg(long)]
        json: bool,
    },
    /// Approve ERC20 tokens for staking.
    ///
    /// Required before depositing ERC20 tokens. Sets the allowance for
    /// the staking contract to transfer tokens on your behalf.
    Approve {
        #[command(flatten)]
        network: TangleClientArgs,
        /// ERC20 token contract address.
        #[arg(long)]
        token: String,
        /// Amount to approve in wei (smallest token unit).
        #[arg(long)]
        amount: u128,
        /// Spender address (defaults to staking contract).
        #[arg(long)]
        spender: Option<String>,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Deposit tokens into the staking contract.
    ///
    /// Deposits tokens that can later be delegated to operators.
    /// For ERC20 tokens, you must approve() first.
    Deposit {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Token contract address (0x0 for native ETH/TNT).
        #[arg(long, default_value = "0x0000000000000000000000000000000000000000")]
        token: String,
        /// Amount to deposit in wei (smallest token unit).
        #[arg(long)]
        amount: u128,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Delegate deposited tokens to an operator.
    ///
    /// Assigns your stake to an operator who provides economic security for services.
    /// You earn rewards when the operator participates in services.
    Delegate {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Operator address to delegate stake to.
        #[arg(long)]
        operator: String,
        /// Amount to delegate in wei (smallest token unit).
        #[arg(long)]
        amount: u128,
        /// Token contract address (0x0 for native ETH/TNT).
        #[arg(long, default_value = "0x0000000000000000000000000000000000000000")]
        token: String,
        /// Blueprint selection: all (any blueprint) or fixed (specific blueprints).
        #[arg(long, value_enum, default_value = "all")]
        selection: DelegationSelection,
        /// Blueprint IDs for fixed selection (requires --selection=fixed).
        #[arg(long = "blueprint-id")]
        blueprint_ids: Vec<u64>,
        /// Delegate from existing deposit balance instead of new deposit.
        #[arg(long)]
        from_deposit: bool,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Request to undelegate stake from an operator.
    ///
    /// Initiates the unbonding period. Use execute-unstake after the period ends.
    Undelegate {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Operator address to undelegate from.
        #[arg(long)]
        operator: String,
        /// Amount to undelegate in wei (smallest token unit).
        #[arg(long)]
        amount: u128,
        /// Token contract address (0x0 for native ETH/TNT).
        #[arg(long, default_value = "0x0000000000000000000000000000000000000000")]
        token: String,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Execute all matured unstake requests.
    ///
    /// Completes undelegation for requests past the unbonding period.
    /// Tokens move back to your deposit balance.
    ExecuteUnstake {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Execute a specific unstake and withdraw in one transaction.
    ///
    /// Completes undelegation and immediately withdraws to your wallet.
    ExecuteUnstakeWithdraw {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Operator address from the original delegation.
        #[arg(long)]
        operator: String,
        /// Token contract address (0x0 for native ETH/TNT).
        #[arg(long, default_value = "0x0000000000000000000000000000000000000000")]
        token: String,
        /// Share amount from your pending unstake.
        #[arg(long)]
        shares: u128,
        /// Round number from the pending unstake request.
        #[arg(long)]
        requested_round: u64,
        /// Recipient address (defaults to your address).
        #[arg(long)]
        receiver: Option<String>,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Request to withdraw deposited tokens.
    ///
    /// Initiates the unbonding period for non-delegated deposits.
    /// Use execute-withdraw after the period ends.
    ScheduleWithdraw {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Token contract address (0x0 for native ETH/TNT).
        #[arg(long, default_value = "0x0000000000000000000000000000000000000000")]
        token: String,
        /// Amount to withdraw in wei (smallest token unit).
        #[arg(long)]
        amount: u128,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Execute all matured withdrawal requests.
    ///
    /// Transfers tokens back to your wallet for requests past the unbonding period.
    ExecuteWithdraw {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
}

pub(super) async fn run(command: DelegatorCommands) -> Result<()> {
    match command {
        DelegatorCommands::Positions {
            network,
            delegator,
            token,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let delegator_address = if let Some(value) = delegator {
                parse_address(&value, "DELEGATOR")?
            } else {
                client.account()
            };
            let token_address = parse_address(&token, "TOKEN")?;
            let deposit = client
                .get_deposit_info(delegator_address, token_address)
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            let locks = client
                .get_locks(delegator_address, token_address)
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            let delegations = client
                .get_delegations_with_blueprints(delegator_address)
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            let unstakes = client
                .get_pending_unstakes(delegator_address)
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            let withdrawals = client
                .get_pending_withdrawals(delegator_address)
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            delegator::print_positions(
                delegator_address,
                token_address,
                &deposit,
                &locks,
                &delegations,
                &unstakes,
                &withdrawals,
                json,
            );
        }
        DelegatorCommands::Delegations {
            network,
            delegator,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let delegator_address = if let Some(value) = delegator {
                parse_address(&value, "DELEGATOR")?
            } else {
                client.account()
            };
            let delegations = client
                .get_delegations_with_blueprints(delegator_address)
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            delegator::print_delegations(delegator_address, &delegations, json);
        }
        DelegatorCommands::PendingUnstakes {
            network,
            delegator,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let delegator_address = if let Some(value) = delegator {
                parse_address(&value, "DELEGATOR")?
            } else {
                client.account()
            };
            let unstakes = client
                .get_pending_unstakes(delegator_address)
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            delegator::print_pending_unstakes(delegator_address, &unstakes, json);
        }
        DelegatorCommands::PendingWithdrawals {
            network,
            delegator,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let delegator_address = if let Some(value) = delegator {
                parse_address(&value, "DELEGATOR")?
            } else {
                client.account()
            };
            let withdrawals = client
                .get_pending_withdrawals(delegator_address)
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            delegator::print_pending_withdrawals(delegator_address, &withdrawals, json);
        }
        DelegatorCommands::Allowance {
            network,
            token,
            owner,
            spender,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let token_address = parse_address(&token, "TOKEN")?;
            ensure!(
                token_address != Address::ZERO,
                "Token address must be non-zero for ERC20 allowance"
            );
            let owner_address = if let Some(value) = owner {
                parse_address(&value, "OWNER")?
            } else {
                client.account()
            };
            let spender_address = if let Some(value) = spender {
                parse_address(&value, "SPENDER")?
            } else {
                client.config.settings.staking_contract
            };
            let allowance = client
                .erc20_allowance(token_address, owner_address, spender_address)
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            delegator::print_erc20_allowance(
                owner_address,
                spender_address,
                token_address,
                allowance,
                json,
            );
        }
        DelegatorCommands::Balance {
            network,
            token,
            owner,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let token_address = parse_address(&token, "TOKEN")?;
            ensure!(
                token_address != Address::ZERO,
                "Token address must be non-zero for ERC20 balance"
            );
            let owner_address = if let Some(value) = owner {
                parse_address(&value, "OWNER")?
            } else {
                client.account()
            };
            let balance = client
                .erc20_balance(token_address, owner_address)
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            delegator::print_erc20_balance(owner_address, token_address, balance, json);
        }
        command => transact(command).await?,
    }
    Ok(())
}

async fn transact(command: DelegatorCommands) -> Result<()> {
    match command {
        DelegatorCommands::Approve {
            network,
            token,
            amount,
            spender,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let token_address = parse_address(&token, "TOKEN")?;
            ensure!(
                token_address != Address::ZERO,
                "Token address must be non-zero for ERC20 approvals"
            );
            let spender_address = if let Some(value) = spender {
                parse_address(&value, "SPENDER")?
            } else {
                client.config.settings.staking_contract
            };
            let tx = client
                .erc20_approve(token_address, spender_address, U256::from(amount))
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            log_tx("Delegator approve", &tx, json);
        }
        DelegatorCommands::Deposit {
            network,
            token,
            amount,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let token_address = parse_address(&token, "TOKEN")?;
            let tx = if token_address == Address::ZERO {
                client
                    .deposit_native(U256::from(amount))
                    .await
                    .map_err(|e| eyre!(e.to_string()))?
            } else {
                client
                    .deposit_erc20(token_address, U256::from(amount))
                    .await
                    .map_err(|e| eyre!(e.to_string()))?
            };
            log_tx("Delegator deposit", &tx, json);
        }
        DelegatorCommands::Delegate {
            network,
            operator,
            amount,
            token,
            selection,
            blueprint_ids,
            from_deposit,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let operator_address = parse_address(&operator, "OPERATOR")?;
            let token_address = parse_address(&token, "TOKEN")?;
            let selection_mode = match selection {
                DelegationSelection::All => BlueprintSelectionMode::All,
                DelegationSelection::Fixed => BlueprintSelectionMode::Fixed,
            };
            if matches!(selection_mode, BlueprintSelectionMode::Fixed) && blueprint_ids.is_empty() {
                return Err(eyre!(
                    "Fixed selection requires at least one --blueprint-id"
                ));
            }
            let tx = if from_deposit {
                client
                    .delegate_with_options(
                        operator_address,
                        token_address,
                        U256::from(amount),
                        selection_mode,
                        blueprint_ids,
                    )
                    .await
            } else {
                client
                    .deposit_and_delegate_with_options(
                        operator_address,
                        token_address,
                        U256::from(amount),
                        selection_mode,
                        blueprint_ids,
                    )
                    .await
            }
            .map_err(|e| eyre!(e.to_string()))?;
            log_tx("Delegator delegate", &tx, json);
        }
        DelegatorCommands::Undelegate {
            network,
            operator,
            amount,
            token,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let operator_address = parse_address(&operator, "OPERATOR")?;
            let token_address = parse_address(&token, "TOKEN")?;
            let tx = client
                .schedule_delegator_unstake(operator_address, token_address, U256::from(amount))
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            log_tx("Delegator undelegate", &tx, json);
        }
        DelegatorCommands::ExecuteUnstake { network, json } => {
            let client = network.connect(0, None).await?;
            let tx = client
                .execute_delegator_unstake()
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            log_tx("Delegator execute-unstake", &tx, json);
        }
        DelegatorCommands::ExecuteUnstakeWithdraw {
            network,
            operator,
            token,
            shares,
            requested_round,
            receiver,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let operator_address = parse_address(&operator, "OPERATOR")?;
            let token_address = parse_address(&token, "TOKEN")?;
            let receiver = if let Some(value) = receiver {
                parse_address(&value, "RECEIVER")?
            } else {
                client.account()
            };
            let tx = client
                .execute_delegator_unstake_and_withdraw(
                    operator_address,
                    token_address,
                    U256::from(shares),
                    requested_round,
                    receiver,
                )
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            log_tx("Delegator execute-unstake-withdraw", &tx, json);
        }
        DelegatorCommands::ScheduleWithdraw {
            network,
            token,
            amount,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let token_address = parse_address(&token, "TOKEN")?;
            let tx = client
                .schedule_withdraw(token_address, U256::from(amount))
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            log_tx("Delegator schedule-withdraw", &tx, json);
        }
        DelegatorCommands::ExecuteWithdraw { network, json } => {
            let client = network.connect(0, None).await?;
            let tx = client
                .execute_withdraw()
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            log_tx("Delegator execute-withdraw", &tx, json);
        }
        _ => unreachable!("command dispatched by its owning module"),
    }
    Ok(())
}