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
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
use super::{
    blueprint::resolve_runtime_options,
    chain::{log_tx, upgrade_tx_ctx, upgrade_view_ctx},
};
use alloy_primitives::{Address, Bytes, U256};
use blueprint_client_tangle::contracts::ITangleTypes;
use cargo_tangle::command::list;
use cargo_tangle::command::run::tangle::{RunOpts, run_blueprint};
use cargo_tangle::command::service::{
    approve_service, approve_service_with_commitments, build_request_params, join_service,
    leave_service, reject_service, request_service, with_security_requirements,
};
use cargo_tangle::command::tangle::{
    PreferredSourceArg, SpawnMethod, TangleClientArgs, parse_address,
};
use cargo_tangle::settings::RuntimePreferences;
use clap::Subcommand;
use color_eyre::eyre::{Context, Result, ensure, eyre};
use serde_json::json;
use std::{fs, path::PathBuf, str::FromStr};
use url::Url;

#[derive(Subcommand, Debug)]
pub(super) enum ServiceCommands {
    /// Request a new service instance from operators.
    ///
    /// Creates a service request that operators can approve or reject.
    /// Payment and security requirements can be specified to filter operators.
    Request {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Blueprint ID to instantiate.
        #[arg(long)]
        blueprint_id: u64,
        /// Operator addresses to include (can specify multiple times).
        #[arg(long = "operator", required = true)]
        operators: Vec<String>,
        /// Exposure per operator in basis points (10000 = 100%). Matches --operator order.
        #[arg(long = "operator-exposure-bps")]
        operator_exposures: Vec<u16>,
        /// Addresses allowed to submit jobs (in addition to requester).
        #[arg(long = "permitted-caller")]
        permitted_callers: Vec<String>,
        /// File containing service configuration (raw bytes).
        #[arg(long = "config-file", value_name = "PATH")]
        config_file: Option<PathBuf>,
        /// Hex-encoded service configuration.
        #[arg(long = "config-hex", value_name = "HEX")]
        config_hex: Option<String>,
        /// Time-to-live in seconds (0 = no expiration).
        #[arg(long, default_value_t = 600)]
        ttl: u64,
        /// ERC20 token for payment (0x0 = native token).
        #[arg(long, default_value = "0x0000000000000000000000000000000000000000")]
        payment_token: String,
        /// Payment amount in wei.
        #[arg(long, default_value_t = 0)]
        payment_amount: u128,
        /// Security requirement (format: KIND:TOKEN:MIN:MAX, can repeat).
        ///
        /// KIND: 0=native, 1=erc20. MIN/MAX are stake bounds in wei.
        #[arg(
            long = "security-requirement",
            value_name = "KIND:TOKEN:MIN:MAX",
            value_parser = parse_security_requirement
        )]
        security_requirements: Vec<SecurityRequirementArg>,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Approve a pending service request as an operator.
    ///
    /// Commits your stake to the service and enables job execution.
    Approve {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Request ID to approve.
        #[arg(long)]
        request_id: u64,
        /// Percentage of your stake to commit to this service (0-100).
        #[arg(long = "staking-percent", default_value_t = 50)]
        staking_percent: u8,
        /// Explicit security commitment (format: KIND:TOKEN:EXPOSURE, can repeat).
        ///
        /// Overrides automatic allocation. EXPOSURE is in wei.
        #[arg(
            long = "security-commitment",
            value_name = "KIND:TOKEN:EXPOSURE",
            value_parser = parse_security_commitment
        )]
        security_commitments: Vec<SecurityCommitmentArg>,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Reject a pending service request as an operator.
    ///
    /// Declines participation in the service. If all operators reject,
    /// the request fails and payment is refunded to the requester.
    Reject {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Request ID to reject.
        #[arg(long)]
        request_id: u64,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Join a running dynamic service as an operator.
    ///
    /// For services with open membership, allows operators to join after creation.
    Join {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Service ID to join.
        #[arg(long)]
        service_id: u64,
        /// Stake exposure in basis points (10000 = 100% of your delegated stake).
        #[arg(long, default_value_t = MAX_BPS)]
        exposure_bps: u16,
        /// Asset security commitment in format KIND:TOKEN:EXPOSURE_BPS.
        /// KIND: native/eth or erc20.
        /// TOKEN: Token/vault address (use _ or 0 for native).
        /// EXPOSURE_BPS: Exposure in basis points (e.g., 5000 = 50%).
        /// Can be specified multiple times for multiple commitments.
        /// Example: --commitment erc20:0x1234...abcd:5000
        #[arg(long, value_name = "KIND:TOKEN:EXPOSURE_BPS")]
        commitment: Vec<String>,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Leave a dynamic service as an operator.
    ///
    /// Exits the service and recovers your committed stake after the unbonding period.
    Leave {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Service ID to leave.
        #[arg(long)]
        service_id: u64,
        /// Output transaction details as JSON.
        #[arg(long)]
        json: bool,
    },
    /// Spawn a local service runtime for testing.
    ///
    /// Starts the blueprint runtime locally without full network participation.
    /// Useful for development and debugging.
    Spawn {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Blueprint ID defining the service logic.
        #[arg(long)]
        blueprint_id: u64,
        /// Service ID to spawn runtime for.
        #[arg(long)]
        service_id: u64,
        /// Runtime execution mode: vm (sandboxed) or native.
        #[arg(long, value_enum, default_value_t = SpawnMethod::Vm)]
        spawn_method: SpawnMethod,
        /// Directory for blueprint data and state.
        #[arg(long, value_name = "PATH")]
        data_dir: Option<PathBuf>,
        /// Allow unchecked attestations (testing only, insecure).
        #[arg(long)]
        allow_unchecked_attestations: bool,
        /// Simulate execution without on-chain transactions.
        #[arg(long)]
        dry_run: bool,
        /// Override blueprint source: wasm, binary, or container.
        #[arg(long, value_enum)]
        preferred_source: Option<PreferredSourceArg>,
        /// Force VM sandbox execution.
        #[arg(long)]
        vm: bool,
        /// Disable VM sandbox (use native execution).
        #[arg(long)]
        no_vm: bool,
    },
    /// List all active services.
    List {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Output as JSON instead of formatted table.
        #[arg(long)]
        json: bool,
    },
    /// List all pending service requests.
    Requests {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Output as JSON instead of formatted table.
        #[arg(long)]
        json: bool,
    },
    /// Show details for a specific service request.
    Show {
        #[command(flatten)]
        network: TangleClientArgs,
        /// Request ID to display.
        #[arg(long)]
        request_id: u64,
    },

    /// Set this service's upgrade policy: AUTO follows the blueprint owner's
    /// active version, APPROVE requires opt-in via `ack-version`, MANUAL pins
    /// to genesis.
    SetPolicy {
        #[command(flatten)]
        network: TangleClientArgs,
        #[arg(long)]
        service_id: u64,
        /// Policy to apply.
        #[arg(long, value_enum)]
        policy: cargo_tangle::command::upgrade::UpgradePolicyArg,
        #[arg(long)]
        json: bool,
    },

    /// Acknowledge a binary version for this service (under APPROVE policy).
    AckVersion {
        #[command(flatten)]
        network: TangleClientArgs,
        #[arg(long)]
        service_id: u64,
        #[arg(long)]
        version_id: u64,
        #[arg(long)]
        json: bool,
    },

    /// Show the binary version a service is currently effectively running.
    EffectiveVersion {
        #[command(flatten)]
        network: TangleClientArgs,
        #[arg(long)]
        service_id: u64,
        /// Blueprint ID hosting this service. Required to resolve the
        /// effective version's blueprint context.
        #[arg(long)]
        blueprint_id: u64,
        #[arg(long)]
        json: bool,
    },

    /// Show the service's upgrade policy + acked vs. available versions.
    UpgradeStatus {
        #[command(flatten)]
        network: TangleClientArgs,
        #[arg(long)]
        service_id: u64,
        /// Blueprint ID hosting this service.
        #[arg(long)]
        blueprint_id: u64,
        #[arg(long)]
        json: bool,
    },

    /// List the binary versions available for this service.
    ///
    /// Talks to the local blueprint-manager (not the chain) and asks it to
    /// enumerate the published versions for the underlying blueprint, with
    /// the currently-running one flagged. Useful as the entrypoint for
    /// MANUAL-with-assist workflows (`upgrade-local`, `upgrade-whitelist`).
    Upgrades {
        #[arg(long)]
        service_id: u64,
        /// blueprint-manager local RPC base URL. Falls back to
        /// `BLUEPRINT_MANAGER_URL` env, then `http://127.0.0.1:9000`.
        #[arg(long, value_name = "URL")]
        manager_url: Option<Url>,
        #[arg(long)]
        json: bool,
    },

    /// Pre-authorize the manager to swap this service to `--version-id`.
    ///
    /// MANUAL-with-assist: stores a one-shot pin in the manager's local
    /// authz store. The manager will run its full verify-then-swap pipeline
    /// the next time it reconciles this service, then clear the pin. No
    /// on-chain ack tx is written; the service's upgrade policy must be
    /// MANUAL for this to take effect.
    UpgradeLocal {
        #[arg(long)]
        service_id: u64,
        #[arg(long)]
        version_id: u64,
        /// Don't actually pin — just report what the manager would do.
        #[arg(long)]
        dry_run: bool,
        #[arg(long, value_name = "URL")]
        manager_url: Option<Url>,
        #[arg(long)]
        json: bool,
    },

    /// Replace this service's MANUAL-with-assist whitelist of acceptable
    /// versions. Persisted across manager restarts. Pass `--versions ""` to
    /// clear.
    UpgradeWhitelist {
        #[arg(long)]
        service_id: u64,
        /// Comma-separated version IDs (e.g. `2,4,5`). Empty = clear.
        #[arg(long, value_name = "LIST")]
        versions: String,
        #[arg(long, value_name = "URL")]
        manager_url: Option<Url>,
        #[arg(long)]
        json: bool,
    },

    /// Record an explicit skip on a published version for this service.
    /// The manager will suppress alerts about it and never auto-swap into
    /// it even if it lands in `effectiveBinaryVersion`. Persists across
    /// manager restarts.
    UpgradeSkip {
        #[arg(long)]
        service_id: u64,
        #[arg(long)]
        version_id: u64,
        /// Required free-form reason. Lands in the manager's audit log.
        #[arg(long, value_name = "TEXT")]
        reason: String,
        #[arg(long, value_name = "URL")]
        manager_url: Option<Url>,
        #[arg(long)]
        json: bool,
    },

    /// Show the local-authz state (pinned, whitelisted, skipped) for this
    /// service along with the on-chain policy and currently-running binary.
    UpgradeAuthz {
        #[arg(long)]
        service_id: u64,
        #[arg(long, value_name = "URL")]
        manager_url: Option<Url>,
        #[arg(long)]
        json: bool,
    },
}

pub(super) async fn run(command: ServiceCommands) -> Result<()> {
    match command {
        ServiceCommands::Request {
            network,
            blueprint_id,
            operators,
            operator_exposures,
            permitted_callers,
            config_file,
            config_hex,
            ttl,
            payment_token,
            payment_amount,
            security_requirements,
            json,
        } => {
            let operators = parse_address_list(&operators, "operator")?;
            let operator_exposures =
                normalize_operator_exposures(&operator_exposures, operators.len())?;
            let permitted_callers = parse_address_list(&permitted_callers, "permitted caller")?;
            let config = load_config_payload(config_file, config_hex)?;
            let payment_token = parse_address(&payment_token, "PAYMENT_TOKEN")?;
            let security_requirements: Vec<ITangleTypes::AssetSecurityRequirement> =
                security_requirements
                    .into_iter()
                    .map(requirement_to_abi)
                    .collect();
            let client = network.connect(blueprint_id, None).await?;
            let params = with_security_requirements(
                build_request_params(
                    blueprint_id,
                    operators,
                    operator_exposures,
                    permitted_callers,
                    ttl,
                    payment_token,
                    U256::from(payment_amount),
                    config,
                ),
                security_requirements,
            );
            let (tx, request_id) = request_service(&client, params).await?;

            log_tx("Service request", &tx, json);
            if json {
                println!(
                    "{}",
                    json!({
                        "event": "service_request_id",
                        "request_id": request_id,
                        "tx_hash": format!("{:#x}", tx.tx_hash),
                    })
                );
            } else {
                println!("Request ID: {request_id}");
            }
        }
        ServiceCommands::Approve {
            network,
            request_id,
            staking_percent,
            json,
            security_commitments,
        } => {
            let client = network.connect(0, None).await?;
            let tx = if security_commitments.is_empty() {
                approve_service(&client, request_id, staking_percent).await?
            } else {
                let commitments: Vec<ITangleTypes::AssetSecurityCommitment> = security_commitments
                    .into_iter()
                    .map(commitment_to_abi)
                    .collect();
                approve_service_with_commitments(&client, request_id, commitments).await?
            };
            log_tx("Service approval", &tx, json);
        }
        ServiceCommands::Reject {
            network,
            request_id,
            json,
        } => {
            let client = network.connect(0, None).await?;
            let tx = reject_service(&client, request_id).await?;
            log_tx("Service rejection", &tx, json);
        }
        ServiceCommands::Join {
            network,
            service_id,
            exposure_bps,
            commitment,
            json,
        } => {
            ensure!(exposure_bps > 0, "Exposure must be greater than 0 bps");
            ensure!(
                exposure_bps <= MAX_BPS,
                "Exposure cannot exceed {MAX_BPS} bps"
            );
            let client = network.connect(0, Some(service_id)).await?;
            let tx = if commitment.is_empty() {
                join_service(&client, service_id, exposure_bps).await?
            } else {
                let commitments = parse_commitments(&commitment)?;
                client
                    .join_service_with_commitments(service_id, exposure_bps, commitments)
                    .await
                    .map_err(|e| eyre!(e.to_string()))?
            };
            log_tx("Service join", &tx, json);
            if json {
                println!(
                    "{}",
                    json!({
                        "event": "service_joined",
                        "service_id": service_id,
                        "exposure_bps": exposure_bps,
                        "tx_hash": format!("{:#x}", tx.tx_hash),
                    })
                );
            } else {
                println!("Joined service {service_id} with exposure {exposure_bps} bps");
            }
        }
        ServiceCommands::Leave {
            network,
            service_id,
            json,
        } => {
            let client = network.connect(0, Some(service_id)).await?;
            let operator = client.account();
            let operator_info = client
                .get_service_operator(service_id, operator)
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            ensure!(
                operator_info.active,
                "Operator is not active in service {service_id}"
            );

            let tx = leave_service(&client, service_id).await?;
            log_tx("Service leave", &tx, json);
            if json {
                println!(
                    "{}",
                    json!({
                        "event": "service_left",
                        "service_id": service_id,
                        "tx_hash": format!("{:#x}", tx.tx_hash),
                    })
                );
            } else {
                println!("Left service {service_id}");
            }
        }
        ServiceCommands::Spawn {
            network,
            blueprint_id,
            service_id,
            spawn_method,
            data_dir,
            allow_unchecked_attestations,
            dry_run,
            preferred_source,
            vm,
            no_vm,
        } => {
            let client_config = network.client_config(blueprint_id, Some(service_id))?;
            let settings = client_config.settings.clone();
            let (preferred_source_value, use_vm_value) = resolve_runtime_options(
                spawn_method,
                RuntimePreferences::default(),
                preferred_source,
                vm,
                no_vm,
            )?;
            let run_opts = RunOpts {
                http_rpc_url: client_config.http_rpc_endpoint.clone(),
                ws_rpc_url: client_config.ws_rpc_endpoint.clone(),
                blueprint_id,
                service_id: Some(service_id),
                tangle_contract: settings.tangle_contract,
                staking_contract: settings.staking_contract,
                status_registry_contract: settings.status_registry_contract,
                keystore_path: network.keystore_path()?.display().to_string(),
                data_dir,
                allow_unchecked_attestations,
                registration_mode: false,
                registration_capture_only: false,
                preferred_source: preferred_source_value,
                use_vm: use_vm_value,
                dry_run,
                shutdown_after: None,
            };
            run_blueprint(run_opts).await?;
        }
        ServiceCommands::List { network, json } => {
            let client = network.connect(0, None).await?;
            let services = list::services::list_services(&client).await?;
            list::services::print_services(&services, json);
        }
        ServiceCommands::Requests { network, json } => {
            let client = network.connect(0, None).await?;
            let requests = list::requests::list_requests(&client).await?;
            list::requests::print_requests(&requests, json);
        }
        ServiceCommands::Show {
            network,
            request_id,
        } => {
            let client = network.connect(0, None).await?;
            let request = client
                .get_service_request_info(request_id)
                .await
                .map_err(|e| eyre!(e.to_string()))?;
            list::requests::print_request(&request);
        }
        command => run_upgrade(command).await?,
    }
    Ok(())
}

pub(super) fn parse_address_list(values: &[String], label: &str) -> Result<Vec<Address>> {
    values
        .iter()
        .map(|value| parse_address(value, label))
        .collect()
}

fn normalize_operator_exposures(
    exposures: &[u16],
    operator_len: usize,
) -> Result<Option<Vec<u16>>> {
    if exposures.is_empty() {
        return Ok(None);
    }
    ensure!(
        exposures.len() == operator_len,
        "Expected {operator_len} operator exposure values but received {}",
        exposures.len()
    );
    exposures
        .iter()
        .enumerate()
        .try_for_each(|(idx, value)| -> Result<()> {
            ensure!(
                *value <= MAX_BPS,
                "Operator exposure #{idx} exceeds {MAX_BPS} bps"
            );
            Ok(())
        })?;
    Ok(Some(exposures.to_vec()))
}

#[derive(Clone, Debug)]
pub(super) struct SecurityRequirementArg {
    kind: AssetKindArg,
    token: Address,
    min: u16,
    max: u16,
}

#[derive(Clone, Debug)]
pub(super) struct SecurityCommitmentArg {
    kind: AssetKindArg,
    token: Address,
    exposure: u16,
}

#[derive(Clone, Copy, Debug)]
pub(super) enum AssetKindArg {
    Native,
    Erc20,
}

fn parse_security_requirement(value: &str) -> std::result::Result<SecurityRequirementArg, String> {
    let parts: Vec<_> = value.split(':').collect();
    if parts.len() != 4 {
        return Err("Expected format KIND:TOKEN:MIN:MAX".to_string());
    }
    let kind = parse_asset_kind(parts[0])?;
    let token = parse_token(kind, parts[1])?;
    let min = parse_bps(parts[2], "min exposure")?;
    let max = parse_bps(parts[3], "max exposure")?;
    if min == 0 {
        return Err("minimum exposure must be greater than 0".to_string());
    }
    if min > max {
        return Err("minimum exposure cannot exceed maximum exposure".to_string());
    }
    Ok(SecurityRequirementArg {
        kind,
        token,
        min,
        max,
    })
}

fn parse_security_commitment(value: &str) -> std::result::Result<SecurityCommitmentArg, String> {
    let parts: Vec<_> = value.split(':').collect();
    if parts.len() != 3 {
        return Err("Expected format KIND:TOKEN:EXPOSURE".to_string());
    }
    let kind = parse_asset_kind(parts[0])?;
    let token = parse_token(kind, parts[1])?;
    let exposure = parse_bps(parts[2], "exposure")?;
    Ok(SecurityCommitmentArg {
        kind,
        token,
        exposure,
    })
}

fn parse_asset_kind(value: &str) -> std::result::Result<AssetKindArg, String> {
    match value.to_lowercase().as_str() {
        "native" | "eth" => Ok(AssetKindArg::Native),
        "erc20" => Ok(AssetKindArg::Erc20),
        other => Err(format!("unsupported asset kind '{other}'")),
    }
}

fn parse_token(kind: AssetKindArg, raw: &str) -> std::result::Result<Address, String> {
    match kind {
        AssetKindArg::Native => {
            if raw.is_empty() || raw == "_" || raw == "0" {
                return Ok(Address::ZERO);
            }
            if raw.eq_ignore_ascii_case("native") {
                return Ok(Address::ZERO);
            }
            let addr = Address::from_str(raw)
                .map_err(|e| format!("invalid native token placeholder '{raw}': {e}"))?;
            if addr != Address::ZERO {
                return Err("native asset must use the zero address placeholder".to_string());
            }
            Ok(Address::ZERO)
        }
        AssetKindArg::Erc20 => {
            Address::from_str(raw).map_err(|e| format!("invalid ERC-20 address '{raw}': {e}"))
        }
    }
}

fn parse_bps(value: &str, label: &str) -> std::result::Result<u16, String> {
    let parsed = value
        .parse::<u16>()
        .map_err(|e| format!("invalid {label} '{value}': {e}"))?;
    if parsed > MAX_BPS {
        return Err(format!("{label} '{value}' exceeds {MAX_BPS} bps"));
    }
    Ok(parsed)
}

fn requirement_to_abi(arg: SecurityRequirementArg) -> ITangleTypes::AssetSecurityRequirement {
    ITangleTypes::AssetSecurityRequirement {
        asset: asset_to_abi(arg.kind, arg.token),
        minExposureBps: arg.min,
        maxExposureBps: arg.max,
    }
}

fn commitment_to_abi(arg: SecurityCommitmentArg) -> ITangleTypes::AssetSecurityCommitment {
    ITangleTypes::AssetSecurityCommitment {
        asset: asset_to_abi(arg.kind, arg.token),
        exposureBps: arg.exposure,
    }
}

/// Parse a list of commitment strings into ABI-compatible commitment structures.
pub(super) fn parse_commitments(
    commitments: &[String],
) -> Result<Vec<ITangleTypes::AssetSecurityCommitment>> {
    commitments
        .iter()
        .map(|s| {
            parse_security_commitment(s)
                .map(commitment_to_abi)
                .map_err(|e| eyre!("Invalid commitment '{}': {}", s, e))
        })
        .collect()
}

fn asset_to_abi(kind: AssetKindArg, token: Address) -> ITangleTypes::Asset {
    let kind_value = match kind {
        AssetKindArg::Native => ITangleTypes::AssetKind::from_underlying(0).into_underlying(),
        AssetKindArg::Erc20 => ITangleTypes::AssetKind::from_underlying(1).into_underlying(),
    };
    ITangleTypes::Asset {
        kind: kind_value,
        token,
    }
}

const MAX_BPS: u16 = 10_000;
fn load_config_payload(config_file: Option<PathBuf>, config_hex: Option<String>) -> Result<Bytes> {
    if let Some(path) = config_file {
        let data = fs::read(&path)
            .with_context(|| format!("Failed to read config file {}", path.display()))?;
        return Ok(Bytes::from(data));
    }

    if let Some(hex_value) = config_hex {
        let trimmed = hex_value.trim_start_matches("0x");
        let bytes = hex::decode(trimmed).context("invalid config hex")?;
        return Ok(Bytes::from(bytes));
    }

    Ok(Bytes::new())
}

async fn run_upgrade(command: ServiceCommands) -> Result<()> {
    match command {
        ServiceCommands::SetPolicy {
            network,
            service_id,
            policy,
            json,
        } => {
            let ctx = upgrade_tx_ctx(&network)?;
            let tx = cargo_tangle::command::upgrade::set_service_policy(&ctx, service_id, policy)
                .await?;
            cargo_tangle::command::upgrade::print_simple_tx(
                &format!("set-policy({} -> {})", service_id, policy.as_str()),
                &tx,
                json,
            );
        }
        ServiceCommands::AckVersion {
            network,
            service_id,
            version_id,
            json,
        } => {
            let ctx = upgrade_tx_ctx(&network)?;
            let tx =
                cargo_tangle::command::upgrade::ack_version(&ctx, service_id, version_id).await?;
            cargo_tangle::command::upgrade::print_simple_tx(
                &format!("ack-version(service={service_id}, version={version_id})"),
                &tx,
                json,
            );
        }
        ServiceCommands::EffectiveVersion {
            network,
            service_id,
            blueprint_id,
            json,
        } => {
            let view = upgrade_view_ctx(&network, None)?;
            let v = cargo_tangle::command::upgrade::get_effective_version(
                &view,
                blueprint_id,
                service_id,
            )
            .await?;
            cargo_tangle::command::upgrade::print_effective_version(service_id, &v, json);
        }
        ServiceCommands::UpgradeStatus {
            network,
            service_id,
            blueprint_id,
            json,
        } => {
            let view = upgrade_view_ctx(&network, None)?;
            let policy =
                cargo_tangle::command::upgrade::get_service_policy(&view, service_id).await?;
            let acked =
                cargo_tangle::command::upgrade::get_service_acked_version_id(&view, service_id)
                    .await?;
            let active =
                cargo_tangle::command::upgrade::get_active_version_id(&view, blueprint_id).await?;
            let effective = cargo_tangle::command::upgrade::get_effective_version(
                &view,
                blueprint_id,
                service_id,
            )
            .await?;
            let versions =
                cargo_tangle::command::upgrade::list_versions(&view, blueprint_id).await?;
            let latest = versions
                .last()
                .map(|v| v.version_id)
                .unwrap_or(effective.version_id);
            let up_to_date = effective.version_id == latest;
            let status = cargo_tangle::command::upgrade::UpgradeStatus {
                service_id,
                policy,
                acked_version_id: acked,
                active_version_id: active,
                effective_version_id: effective.version_id,
                latest_version_id: latest,
                up_to_date,
            };
            cargo_tangle::command::upgrade::print_upgrade_status(&status, json);
        }
        ServiceCommands::Upgrades {
            service_id,
            manager_url,
            json,
        } => {
            let manager =
                cargo_tangle::command::upgrade_local::resolve_manager_url(manager_url.as_ref())?;
            let list =
                cargo_tangle::command::upgrade_local::list_upgrades(&manager, service_id).await?;
            cargo_tangle::command::upgrade_local::print_available(&list, json);
        }
        ServiceCommands::UpgradeLocal {
            service_id,
            version_id,
            dry_run,
            manager_url,
            json,
        } => {
            let manager =
                cargo_tangle::command::upgrade_local::resolve_manager_url(manager_url.as_ref())?;
            let result = cargo_tangle::command::upgrade_local::pin_version(
                &manager, service_id, version_id, dry_run,
            )
            .await?;
            cargo_tangle::command::upgrade_local::print_pin_result(service_id, &result, json);
        }
        ServiceCommands::UpgradeWhitelist {
            service_id,
            versions,
            manager_url,
            json,
        } => {
            let manager =
                cargo_tangle::command::upgrade_local::resolve_manager_url(manager_url.as_ref())?;
            let parsed = cargo_tangle::command::upgrade_local::parse_version_list(&versions)?;
            let result =
                cargo_tangle::command::upgrade_local::set_whitelist(&manager, service_id, parsed)
                    .await?;
            cargo_tangle::command::upgrade_local::print_whitelist_result(service_id, &result, json);
        }
        ServiceCommands::UpgradeSkip {
            service_id,
            version_id,
            reason,
            manager_url,
            json,
        } => {
            let manager =
                cargo_tangle::command::upgrade_local::resolve_manager_url(manager_url.as_ref())?;
            let result = cargo_tangle::command::upgrade_local::add_skip(
                &manager, service_id, version_id, reason,
            )
            .await?;
            cargo_tangle::command::upgrade_local::print_skip_result(service_id, &result, json);
        }
        ServiceCommands::UpgradeAuthz {
            service_id,
            manager_url,
            json,
        } => {
            let manager =
                cargo_tangle::command::upgrade_local::resolve_manager_url(manager_url.as_ref())?;
            let view =
                cargo_tangle::command::upgrade_local::show_authz(&manager, service_id).await?;
            cargo_tangle::command::upgrade_local::print_authz(&view, json);
        }
        _ => unreachable!("command dispatched by its owning module"),
    }
    Ok(())
}