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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
use std::{
    collections::BTreeMap,
    fs::File,
    io::{Read, Write},
    str::FromStr,
    time::{SystemTime, UNIX_EPOCH},
};

use anyhow::{ensure, Context, Result};
use ark_ff::UniformRand;
use decaf377::{Fq, Fr};
use ibc_proto::ibc::core::client::v1::{
    query_client::QueryClient as IbcClientQueryClient, QueryClientStateRequest,
};
use ibc_proto::ibc::core::connection::v1::query_client::QueryClient as IbcConnectionQueryClient;
use ibc_proto::ibc::core::{
    channel::v1::{query_client::QueryClient as IbcChannelQueryClient, QueryChannelRequest},
    connection::v1::QueryConnectionRequest,
};
use ibc_types::core::{
    channel::{ChannelId, PortId},
    client::Height as IbcHeight,
};
use ibc_types::lightclients::tendermint::client_state::ClientState as TendermintClientState;
use rand_core::OsRng;
use regex::Regex;

use crate::command::tx::auction::AuctionCmd;
use liquidity_position::PositionCmd;
use penumbra_asset::{asset, asset::Metadata, Value, STAKING_TOKEN_ASSET_ID};
use penumbra_dex::{lp::position, swap_claim::SwapClaimPlan};
use penumbra_governance::{proposal::ProposalToml, proposal_state::State as ProposalState, Vote};
use penumbra_keys::{keys::AddressIndex, Address};
use penumbra_num::Amount;
use penumbra_proto::{
    core::component::{
        dex::v1::{
            query_service_client::QueryServiceClient as DexQueryServiceClient,
            LiquidityPositionByIdRequest, PositionId,
        },
        governance::v1::{
            query_service_client::QueryServiceClient as GovernanceQueryServiceClient,
            NextProposalIdRequest, ProposalDataRequest, ProposalInfoRequest, ProposalInfoResponse,
            ProposalRateDataRequest,
        },
        sct::v1::{
            query_service_client::QueryServiceClient as SctQueryServiceClient, EpochByHeightRequest,
        },
        stake::v1::{
            query_service_client::QueryServiceClient as StakeQueryServiceClient,
            ValidatorPenaltyRequest,
        },
    },
    view::v1::GasPricesRequest,
};
use penumbra_shielded_pool::Ics20Withdrawal;
use penumbra_stake::rate::RateData;
use penumbra_stake::{DelegationToken, IdentityKey, Penalty, UnbondingToken, UndelegateClaimPlan};
use penumbra_transaction::gas::swap_claim_gas_cost;
use penumbra_view::{SpendableNoteRecord, ViewClient};
use penumbra_wallet::plan::{self, Planner};
use proposal::ProposalCmd;

use crate::App;

mod auction;
mod liquidity_position;
mod proposal;
mod replicate;

#[derive(Debug, clap::Subcommand)]
pub enum TxCmd {
    /// Auction related commands.
    #[clap(display_order = 600, subcommand)]
    Auction(AuctionCmd),
    /// Send funds to a Penumbra address.
    #[clap(display_order = 100)]
    Send {
        /// The destination address to send funds to.
        #[clap(long, display_order = 100)]
        to: String,
        /// The amounts to send, written as typed values 1.87penumbra, 12cubes, etc.
        values: Vec<String>,
        /// Only spend funds originally received by the given account.
        #[clap(long, default_value = "0", display_order = 300)]
        source: u32,
        /// Optional. Set the transaction's memo field to the provided text.
        #[clap(long)]
        memo: Option<String>,
        /// The selected fee tier to multiply the fee amount by.
        #[clap(short, long, value_enum, default_value_t)]
        fee_tier: FeeTier,
    },
    /// Deposit stake into a validator's delegation pool.
    #[clap(display_order = 200)]
    Delegate {
        /// The identity key of the validator to delegate to.
        #[clap(long, display_order = 100)]
        to: String,
        /// The amount of stake to delegate.
        amount: String,
        /// Only spend funds originally received by the given account.
        #[clap(long, default_value = "0", display_order = 300)]
        source: u32,
        /// The selected fee tier to multiply the fee amount by.
        #[clap(short, long, value_enum, default_value_t)]
        fee_tier: FeeTier,
    },
    /// Withdraw stake from a validator's delegation pool.
    #[clap(display_order = 200)]
    Undelegate {
        /// The amount of delegation tokens to undelegate.
        amount: String,
        /// Only spend funds originally received by the given account.
        #[clap(long, default_value = "0", display_order = 300)]
        source: u32,
        /// The selected fee tier to multiply the fee amount by.
        #[clap(short, long, value_enum, default_value_t)]
        fee_tier: FeeTier,
    },
    /// Claim any undelegations that have finished unbonding.
    #[clap(display_order = 200)]
    UndelegateClaim {
        /// The selected fee tier to multiply the fee amount by.
        #[clap(short, long, value_enum, default_value_t)]
        fee_tier: FeeTier,
    },
    /// Swap tokens of one denomination for another using the DEX.
    ///
    /// Swaps are batched and executed at the market-clearing price.
    ///
    /// A swap generates two transactions: an initial "swap" transaction that
    /// submits the swap, and a "swap claim" transaction that privately mints
    /// the output funds once the batch has executed.  The second transaction
    /// will be created and submitted automatically.
    #[clap(display_order = 300)]
    Swap {
        /// The input amount to swap, written as a typed value 1.87penumbra, 12cubes, etc.
        input: String,
        /// The denomination to swap the input into, e.g. `gm`
        #[clap(long, display_order = 100)]
        into: String,
        /// Only spend funds originally received by the given account.
        #[clap(long, default_value = "0", display_order = 300)]
        source: u32,
        /// The selected fee tier to multiply the fee amount by.
        #[clap(short, long, value_enum, default_value_t)]
        fee_tier: FeeTier,
    },
    /// Vote on a governance proposal in your role as a delegator (see also: `pcli validator vote`).
    #[clap(display_order = 400)]
    Vote {
        /// Only spend funds and vote with staked delegation tokens originally received by the given
        /// account.
        #[clap(long, default_value = "0", global = true, display_order = 300)]
        source: u32,
        #[clap(subcommand)]
        vote: VoteCmd,
        /// The selected fee tier to multiply the fee amount by.
        #[clap(short, long, value_enum, default_value_t)]
        fee_tier: FeeTier,
    },
    /// Submit or withdraw a governance proposal.
    #[clap(display_order = 500, subcommand)]
    Proposal(ProposalCmd),
    /// Deposit funds into the Community Pool.
    #[clap(display_order = 600)]
    CommunityPoolDeposit {
        /// The amounts to send, written as typed values 1.87penumbra, 12cubes, etc.
        values: Vec<String>,
        /// Only spend funds originally received by the given account.
        #[clap(long, default_value = "0", display_order = 300)]
        source: u32,
        /// The selected fee tier to multiply the fee amount by.
        #[clap(short, long, value_enum, default_value_t)]
        fee_tier: FeeTier,
    },
    /// Manage liquidity positions.
    #[clap(display_order = 500, subcommand, visible_alias = "lp")]
    Position(PositionCmd),
    /// Consolidate many small notes into a few larger notes.
    ///
    /// Since Penumbra transactions reveal their arity (how many spends,
    /// outputs, etc), but transactions are unlinkable from each other, it is
    /// slightly preferable to sweep small notes into larger ones in an isolated
    /// "sweep" transaction, rather than at the point that they should be spent.
    ///
    /// Currently, only zero-fee sweep transactions are implemented.
    #[clap(display_order = 990)]
    Sweep,

    /// Perform an ICS-20 withdrawal, moving funds from the Penumbra chain
    /// to a counterparty chain.
    ///
    /// For a withdrawal to be processed on the counterparty, IBC packets must be relayed between
    /// the two chains. Relaying is out of scope for the `pcli` tool.
    #[clap(display_order = 250)]
    Withdraw {
        /// Address on the receiving chain,
        /// e.g. cosmos1grgelyng2v6v3t8z87wu3sxgt9m5s03xvslewd. The chain_id for the counterparty
        /// chain will be discovered automatically, based on the `--channel` setting.
        #[clap(long)]
        to: String,
        /// The value to withdraw, eg "1000upenumbra"
        value: String,
        /// The IBC channel on the primary Penumbra chain to use for performing the withdrawal.
        /// This channel must already exist, as configured by a relayer client.
        /// You can search for channels via e.g. `pcli query ibc channel transfer 0`.
        #[clap(long)]
        channel: u64,
        /// Block height on the counterparty chain, after which the withdrawal will be considered
        /// invalid if not already relayed. Must be specified as a tuple of revision number and block
        /// height, e.g. `5-1000000` means "chain revision 5, block height of 1000000".
        /// You must know the chain id of the counterparty chain beforehand, e.g. `osmosis-testnet-5`,
        /// to know the revision number.
        #[clap(long, display_order = 100)]
        timeout_height: Option<IbcHeight>,
        /// Timestamp, specified in epoch time, after which the withdrawal will be considered
        /// invalid if not already relayed.
        #[clap(long, default_value = "0", display_order = 150)]
        timeout_timestamp: u64,
        /// Only withdraw funds from the specified wallet id within Penumbra.
        #[clap(long, default_value = "0", display_order = 200)]
        source: u32,
        /// The selected fee tier to multiply the fee amount by.
        #[clap(short, long, value_enum, default_value_t)]
        fee_tier: FeeTier,
    },
}

// A fee tier enum suitable for use with clap.
#[derive(Copy, Clone, clap::ValueEnum, Debug)]
pub enum FeeTier {
    Low,
    Medium,
    High,
}

impl Default for FeeTier {
    fn default() -> Self {
        Self::Low
    }
}

// Convert from the internal fee tier enum to the clap-compatible enum.
impl From<penumbra_fee::FeeTier> for FeeTier {
    fn from(tier: penumbra_fee::FeeTier) -> Self {
        match tier {
            penumbra_fee::FeeTier::Low => Self::Low,
            penumbra_fee::FeeTier::Medium => Self::Medium,
            penumbra_fee::FeeTier::High => Self::High,
        }
    }
}

// Convert from the the clap-compatible fee tier enum to the internal fee tier enum.
impl From<FeeTier> for penumbra_fee::FeeTier {
    fn from(tier: FeeTier) -> Self {
        match tier {
            FeeTier::Low => Self::Low,
            FeeTier::Medium => Self::Medium,
            FeeTier::High => Self::High,
        }
    }
}

/// Vote on a governance proposal.
#[derive(Debug, Clone, Copy, clap::Subcommand)]
pub enum VoteCmd {
    /// Vote in favor of a proposal.
    #[clap(display_order = 100)]
    Yes {
        /// The proposal ID to vote on.
        #[clap(long = "on")]
        proposal_id: u64,
    },
    /// Vote against a proposal.
    #[clap(display_order = 200)]
    No {
        /// The proposal ID to vote on.
        #[clap(long = "on")]
        proposal_id: u64,
    },
    /// Abstain from voting on a proposal.
    #[clap(display_order = 300)]
    Abstain {
        /// The proposal ID to vote on.
        #[clap(long = "on")]
        proposal_id: u64,
    },
}

impl From<VoteCmd> for (u64, Vote) {
    fn from(cmd: VoteCmd) -> (u64, Vote) {
        match cmd {
            VoteCmd::Yes { proposal_id } => (proposal_id, Vote::Yes),
            VoteCmd::No { proposal_id } => (proposal_id, Vote::No),
            VoteCmd::Abstain { proposal_id } => (proposal_id, Vote::Abstain),
        }
    }
}

impl TxCmd {
    /// Determine if this command requires a network sync before it executes.
    pub fn offline(&self) -> bool {
        match self {
            TxCmd::Send { .. } => false,
            TxCmd::Sweep { .. } => false,
            TxCmd::Swap { .. } => false,
            TxCmd::Delegate { .. } => false,
            TxCmd::Undelegate { .. } => false,
            TxCmd::UndelegateClaim { .. } => false,
            TxCmd::Vote { .. } => false,
            TxCmd::Proposal(proposal_cmd) => proposal_cmd.offline(),
            TxCmd::CommunityPoolDeposit { .. } => false,
            TxCmd::Position(lp_cmd) => lp_cmd.offline(),
            TxCmd::Withdraw { .. } => false,
            TxCmd::Auction(_) => false,
        }
    }

    pub async fn exec(&self, app: &mut App) -> Result<()> {
        // TODO: use a command line flag to determine the fee token,
        // and pull the appropriate GasPrices out of this rpc response,
        // the rest should follow
        let gas_prices = app
            .view
            .as_mut()
            .context("view service must be initialized")?
            .gas_prices(GasPricesRequest {})
            .await?
            .into_inner()
            .gas_prices
            .expect("gas prices must be available")
            .try_into()?;

        match self {
            TxCmd::Send {
                values,
                to,
                source: from,
                memo,
                fee_tier,
            } => {
                // Parse all of the values provided.
                let values = values
                    .iter()
                    .map(|v| v.parse())
                    .collect::<Result<Vec<Value>, _>>()?;
                let to = to
                    .parse::<Address>()
                    .map_err(|_| anyhow::anyhow!("address is invalid"))?;

                let mut planner = Planner::new(OsRng);

                planner
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into());
                for value in values.iter().cloned() {
                    planner.output(value, to.clone());
                }
                let plan = planner
                    .memo(memo.clone().unwrap_or_default())
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        AddressIndex::new(*from),
                    )
                    .await
                    .context("can't build send transaction")?;
                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::CommunityPoolDeposit {
                values,
                source,
                fee_tier,
            } => {
                let values = values
                    .iter()
                    .map(|v| v.parse())
                    .collect::<Result<Vec<Value>, _>>()?;

                let mut planner = Planner::new(OsRng);
                planner
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into());
                for value in values {
                    planner.community_pool_deposit(value);
                }
                let plan = planner
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        AddressIndex::new(*source),
                    )
                    .await?;
                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::Sweep => loop {
                let plans = plan::sweep(
                    app.view
                        .as_mut()
                        .context("view service must be initialized")?,
                    OsRng,
                )
                .await?;
                let num_plans = plans.len();

                for (i, plan) in plans.into_iter().enumerate() {
                    println!("building sweep {i} of {num_plans}");
                    app.build_and_submit_transaction(plan).await?;
                }
                if num_plans == 0 {
                    println!("finished sweeping");
                    break;
                }
            },
            TxCmd::Swap {
                input,
                into,
                source,
                fee_tier,
            } => {
                let input = input.parse::<Value>()?;
                let into = asset::REGISTRY.parse_unit(into.as_str()).base();
                let fee_tier: FeeTier = (*fee_tier).into();

                let fvk = app.config.full_viewing_key.clone();

                // If a source address was specified, use it for the swap, otherwise,
                // use the default address.
                let (claim_address, _dtk_d) =
                    fvk.incoming().payment_address(AddressIndex::new(*source));

                let mut planner = Planner::new(OsRng);
                planner
                    .set_gas_prices(gas_prices.clone())
                    .set_fee_tier(fee_tier.into());

                // We don't expect much of a drift in gas prices in a few blocks, and the fee tier
                // adjustments should be enough to cover it.
                let estimated_claim_fee = gas_prices
                    .fee(&swap_claim_gas_cost())
                    .apply_tier(fee_tier.into());

                planner.swap(input, into.id(), estimated_claim_fee, claim_address)?;

                let plan = planner
                    .plan(app.view(), AddressIndex::new(*source))
                    .await
                    .context("can't plan swap transaction")?;

                // Hold on to the swap plaintext to be able to claim.
                let swap_plaintext = plan
                    .swap_plans()
                    .next()
                    .expect("swap plan must be present")
                    .swap_plaintext
                    .clone();

                // Submit the `Swap` transaction, waiting for confirmation,
                // at which point the swap will be available for claiming.
                app.build_and_submit_transaction(plan).await?;

                // Fetch the SwapRecord with the claimable swap.
                let swap_record = app
                    .view()
                    .swap_by_commitment(swap_plaintext.swap_commitment())
                    .await?;

                let asset_cache = app.view().assets().await?;

                let pro_rata_outputs = swap_record
                    .output_data
                    .pro_rata_outputs((swap_plaintext.delta_1_i, swap_plaintext.delta_2_i));
                println!("Swap submitted and batch confirmed!");
                println!(
                    "You will receive outputs of {} and {}. Claiming now...",
                    Value {
                        amount: pro_rata_outputs.0,
                        asset_id: swap_record.output_data.trading_pair.asset_1()
                    }
                    .format(&asset_cache),
                    Value {
                        amount: pro_rata_outputs.1,
                        asset_id: swap_record.output_data.trading_pair.asset_2()
                    }
                    .format(&asset_cache),
                );

                let params = app
                    .view
                    .as_mut()
                    .context("view service must be initialized")?
                    .app_params()
                    .await?;

                let mut planner = Planner::new(OsRng);
                planner
                    .set_gas_prices(gas_prices)
                    .set_fee_tier(fee_tier.into());
                let plan = planner
                    .swap_claim(SwapClaimPlan {
                        swap_plaintext,
                        position: swap_record.position,
                        output_data: swap_record.output_data,
                        epoch_duration: params.sct_params.epoch_duration,
                        proof_blinding_r: Fq::rand(&mut OsRng),
                        proof_blinding_s: Fq::rand(&mut OsRng),
                    })
                    .plan(app.view(), AddressIndex::new(*source))
                    .await
                    .context("can't plan swap claim")?;

                // Submit the `SwapClaim` transaction.
                // BUG: this doesn't wait for confirmation, see
                // https://github.com/penumbra-zone/penumbra/pull/2091/commits/128b24a6303c2f855a708e35f9342987f1dd34ec
                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::Delegate {
                to,
                amount,
                source,
                fee_tier,
            } => {
                let unbonded_amount = {
                    let Value { amount, asset_id } = amount.parse::<Value>()?;
                    if asset_id != *STAKING_TOKEN_ASSET_ID {
                        anyhow::bail!("staking can only be done with the staking token");
                    }
                    amount
                };

                let to = to.parse::<IdentityKey>()?;

                let mut stake_client = StakeQueryServiceClient::new(app.pd_channel().await?);
                let rate_data: RateData = stake_client
                    .current_validator_rate(tonic::Request::new(to.into()))
                    .await?
                    .into_inner()
                    .try_into()?;

                let mut sct_client = SctQueryServiceClient::new(app.pd_channel().await?);
                let latest_sync_height = app.view().status().await?.full_sync_height;
                let epoch = sct_client
                    .epoch_by_height(EpochByHeightRequest {
                        height: latest_sync_height,
                    })
                    .await?
                    .into_inner()
                    .epoch
                    .expect("epoch must be available")
                    .into();

                let mut planner = Planner::new(OsRng);
                planner
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into());
                let plan = planner
                    .delegate(epoch, unbonded_amount, rate_data)
                    .plan(app.view(), AddressIndex::new(*source))
                    .await
                    .context("can't plan delegation")?;

                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::Undelegate {
                amount,
                source,
                fee_tier,
            } => {
                let delegation_value @ Value {
                    amount: _,
                    asset_id,
                } = amount.parse::<Value>()?;

                // TODO: it's awkward that we can't just pull the denom out of the `amount` string we were already given
                let delegation_token: DelegationToken = app
                    .view()
                    .assets()
                    .await?
                    .get(&asset_id)
                    .ok_or_else(|| anyhow::anyhow!("unknown asset id {}", asset_id))?
                    .clone()
                    .try_into()
                    .context("could not parse supplied denomination as a delegation token")?;

                let from = delegation_token.validator();

                let mut stake_client = StakeQueryServiceClient::new(app.pd_channel().await?);
                let rate_data: RateData = stake_client
                    .current_validator_rate(tonic::Request::new(from.into()))
                    .await?
                    .into_inner()
                    .try_into()?;

                let mut sct_client = SctQueryServiceClient::new(app.pd_channel().await?);
                let latest_sync_height = app.view().status().await?.full_sync_height;
                let epoch = sct_client
                    .epoch_by_height(EpochByHeightRequest {
                        height: latest_sync_height,
                    })
                    .await?
                    .into_inner()
                    .epoch
                    .expect("epoch must be available")
                    .into();

                let mut planner = Planner::new(OsRng);
                planner
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into());

                let plan = planner
                    .undelegate(epoch, delegation_value.amount, rate_data)
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        AddressIndex::new(*source),
                    )
                    .await
                    .context("can't build undelegate plan")?;

                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::UndelegateClaim { fee_tier } => {
                let channel = app.pd_channel().await?;
                let view: &mut dyn ViewClient = app
                    .view
                    .as_mut()
                    .context("view service must be initialized")?;

                let current_height = view.status().await?.full_sync_height;
                let mut client = SctQueryServiceClient::new(channel.clone());
                let current_epoch = client
                    .epoch_by_height(EpochByHeightRequest {
                        height: current_height,
                    })
                    .await?
                    .into_inner()
                    .epoch
                    .context("unable to get epoch for current height")?;
                let asset_cache = view.assets().await?;

                // Query the view client for the list of undelegations that are ready to be claimed.
                // We want to claim them into the same address index that currently holds the tokens.
                let notes = view.unspent_notes_by_address_and_asset().await?;

                let notes: Vec<(
                    AddressIndex,
                    Vec<(UnbondingToken, Vec<SpendableNoteRecord>)>,
                )> = notes
                    .into_iter()
                    .map(|(address_index, notes_by_asset)| {
                        let mut filtered_notes: Vec<(UnbondingToken, Vec<SpendableNoteRecord>)> =
                            notes_by_asset
                                .into_iter()
                                .filter_map(|(asset_id, notes)| {
                                    // Filter for notes that are unbonding tokens.
                                    let denom = asset_cache
                                        .get(&asset_id)
                                        .expect("asset ID should exist in asset cache")
                                        .clone();
                                    match UnbondingToken::try_from(denom) {
                                        Ok(token) => Some((token, notes)),
                                        Err(_) => None,
                                    }
                                })
                                .collect();

                        filtered_notes.sort_by_key(|(token, _)| token.unbonding_start_height());

                        (address_index, filtered_notes)
                    })
                    .collect();

                for (address_index, notes_by_asset) in notes.into_iter() {
                    for (token, notes) in notes_by_asset.into_iter() {
                        println!("claiming {}", token.denom().default_unit());

                        let validator_identity = token.validator();
                        let unbonding_start_height = token.unbonding_start_height();
                        let end_epoch_index = current_epoch.index;

                        let mut sct_client = SctQueryServiceClient::new(channel.clone());
                        let epoch_start = sct_client
                            .epoch_by_height(EpochByHeightRequest {
                                height: unbonding_start_height,
                            })
                            .await
                            .expect("can get epoch by height")
                            .into_inner()
                            .epoch
                            .context("unable to get epoch for unbonding start height")?;

                        let mut stake_client = StakeQueryServiceClient::new(channel.clone());
                        let penalty: Penalty = stake_client
                            .validator_penalty(tonic::Request::new(ValidatorPenaltyRequest {
                                identity_key: Some(validator_identity.into()),
                                start_epoch_index: epoch_start.index,
                                end_epoch_index,
                            }))
                            .await?
                            .into_inner()
                            .penalty
                            .ok_or_else(|| {
                                anyhow::anyhow!(
                                    "no penalty returned for validator {}",
                                    validator_identity
                                )
                            })?
                            .try_into()?;

                        let mut planner = Planner::new(OsRng);
                        planner
                            .set_gas_prices(gas_prices.clone())
                            .set_fee_tier((*fee_tier).into());
                        let unbonding_amount = notes.iter().map(|n| n.note.amount()).sum();

                        let plan = planner
                            .undelegate_claim(UndelegateClaimPlan {
                                validator_identity,
                                unbonding_start_height,
                                penalty,
                                unbonding_amount,
                                balance_blinding: Fr::rand(&mut OsRng),
                                proof_blinding_r: Fq::rand(&mut OsRng),
                                proof_blinding_s: Fq::rand(&mut OsRng),
                            })
                            .plan(
                                app.view
                                    .as_mut()
                                    .context("view service must be initialized")?,
                                address_index,
                            )
                            .await?;
                        app.build_and_submit_transaction(plan).await?;
                    }
                }
            }
            TxCmd::Proposal(ProposalCmd::Submit {
                file,
                source,
                deposit_amount,
                fee_tier,
            }) => {
                let mut proposal_file = File::open(file).context("can't open proposal file")?;
                let mut proposal_string = String::new();
                proposal_file
                    .read_to_string(&mut proposal_string)
                    .context("can't read proposal file")?;
                let proposal_toml: ProposalToml =
                    toml::from_str(&proposal_string).context("can't parse proposal file")?;
                let proposal = proposal_toml
                    .try_into()
                    .context("can't parse proposal file")?;

                let deposit_amount: Value = deposit_amount.parse()?;
                ensure!(
                    deposit_amount.asset_id == *STAKING_TOKEN_ASSET_ID,
                    "deposit amount must be in staking token"
                );

                let mut planner = Planner::new(OsRng);
                planner
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into());
                let plan = planner
                    .proposal_submit(proposal, deposit_amount.amount)
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        AddressIndex::new(*source),
                    )
                    .await?;
                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::Proposal(ProposalCmd::Withdraw {
                proposal_id,
                reason,
                source,
                fee_tier,
            }) => {
                let mut planner = Planner::new(OsRng);
                planner
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into());
                let plan = planner
                    .proposal_withdraw(*proposal_id, reason.clone())
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        AddressIndex::new(*source),
                    )
                    .await?;

                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::Proposal(ProposalCmd::Template { file, kind }) => {
                let app_params = app.view().app_params().await?;

                // Find out what the latest proposal ID is so we can include the next ID in the template:
                let mut client = GovernanceQueryServiceClient::new(app.pd_channel().await?);
                let next_proposal_id: u64 = client
                    .next_proposal_id(NextProposalIdRequest {})
                    .await?
                    .into_inner()
                    .next_proposal_id;

                let toml_template: ProposalToml = kind
                    .template_proposal(&app_params, next_proposal_id)?
                    .into();

                if let Some(file) = file {
                    File::create(file)
                        .with_context(|| format!("cannot create file {file:?}"))?
                        .write_all(toml::to_string_pretty(&toml_template)?.as_bytes())
                        .context("could not write file")?;
                } else {
                    println!("{}", toml::to_string_pretty(&toml_template)?);
                }
            }
            TxCmd::Proposal(ProposalCmd::DepositClaim {
                proposal_id,
                source,
                fee_tier,
            }) => {
                let mut client = GovernanceQueryServiceClient::new(app.pd_channel().await?);
                let proposal = client
                    .proposal_data(ProposalDataRequest {
                        proposal_id: *proposal_id,
                    })
                    .await?
                    .into_inner();
                let state: ProposalState = proposal
                    .state
                    .context(format!(
                        "proposal state for proposal {} was not found",
                        proposal_id
                    ))?
                    .try_into()?;
                let deposit_amount: Amount = proposal
                    .proposal_deposit_amount
                    .context(format!(
                        "proposal deposit amount for proposal {} was not found",
                        proposal_id
                    ))?
                    .try_into()?;

                let outcome = match state {
                    ProposalState::Voting => anyhow::bail!(
                        "proposal {} is still voting, so the deposit cannot yet be claimed",
                        proposal_id
                    ),
                    ProposalState::Withdrawn { reason: _ } => {
                        anyhow::bail!("proposal {} has been withdrawn but voting has not yet concluded, so the deposit cannot yet be claimed", proposal_id);
                    }
                    ProposalState::Finished { outcome } => outcome.map(|_| ()),
                    ProposalState::Claimed { outcome: _ } => {
                        anyhow::bail!("proposal {} has already been claimed", proposal_id)
                    }
                };

                let plan = Planner::new(OsRng)
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into())
                    .proposal_deposit_claim(*proposal_id, deposit_amount, outcome)
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        AddressIndex::new(*source),
                    )
                    .await?;

                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::Vote {
                vote,
                source,
                fee_tier,
            } => {
                let (proposal_id, vote): (u64, Vote) = (*vote).into();

                // Before we vote on the proposal, we have to gather some information about it so
                // that we can prepare our vote:
                // - the start height, so we can select the votable staked notes to vote with
                // - the start position, so we can submit the appropriate public `start_position`
                //   input for stateless proof verification
                // - the rate data for every validator at the start of the proposal, so we can
                //   convert staked notes into voting power and mint the correct amount of voting
                //   receipt tokens to ourselves

                let mut client = GovernanceQueryServiceClient::new(app.pd_channel().await?);
                let ProposalInfoResponse {
                    start_block_height,
                    start_position,
                } = client
                    .proposal_info(ProposalInfoRequest { proposal_id })
                    .await?
                    .into_inner();
                let start_position = start_position.into();

                let mut rate_data_stream = client
                    .proposal_rate_data(ProposalRateDataRequest { proposal_id })
                    .await?
                    .into_inner();

                let mut start_rate_data = BTreeMap::new();
                while let Some(response) = rate_data_stream.message().await? {
                    let rate_data: RateData = response
                        .rate_data
                        .ok_or_else(|| {
                            anyhow::anyhow!("proposal rate data stream response missing rate data")
                        })?
                        .try_into()
                        .context("invalid rate data")?;
                    start_rate_data.insert(rate_data.identity_key.clone(), rate_data);
                }

                let plan = Planner::new(OsRng)
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into())
                    .delegator_vote(
                        app.view(),
                        AddressIndex::new(*source),
                        proposal_id,
                        vote,
                        start_block_height,
                        start_position,
                        start_rate_data,
                    )
                    .await?
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        AddressIndex::new(*source),
                    )
                    .await?;

                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::Position(PositionCmd::Order(order)) => {
                let asset_cache = app.view().assets().await?;

                tracing::info!(?order);
                let source = AddressIndex::new(order.source());
                let position = order.as_position(&asset_cache, OsRng)?;
                tracing::info!(?position);

                let plan = Planner::new(OsRng)
                    .set_gas_prices(gas_prices)
                    .set_fee_tier(order.fee_tier().into())
                    .position_open(position)
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        source,
                    )
                    .await?;
                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::Withdraw {
                to,
                value,
                timeout_height,
                timeout_timestamp,
                channel,
                source,
                fee_tier,
            } => {
                let destination_chain_address = to;

                let (ephemeral_return_address, _) = app
                    .config
                    .full_viewing_key
                    .ephemeral_address(OsRng, AddressIndex::from(*source));

                let timeout_height = match timeout_height {
                    Some(h) => h.clone(),
                    None => {
                        // look up the height for the counterparty and add 2 days of block time
                        // (assuming 10 seconds per block) to it

                        // look up the client state from the channel by looking up channel id -> connection id -> client state
                        let mut ibc_channel_client =
                            IbcChannelQueryClient::new(app.pd_channel().await?);

                        let req = QueryChannelRequest {
                            port_id: PortId::transfer().to_string(),
                            channel_id: format!("channel-{}", channel),
                        };

                        let channel = ibc_channel_client
                            .channel(req)
                            .await?
                            .into_inner()
                            .channel
                            .ok_or_else(|| anyhow::anyhow!("channel not found"))?;

                        let connection_id = channel.connection_hops[0].clone();

                        let mut ibc_connection_client =
                            IbcConnectionQueryClient::new(app.pd_channel().await?);

                        let req = QueryConnectionRequest {
                            connection_id: connection_id.clone(),
                        };
                        let connection = ibc_connection_client
                            .connection(req)
                            .await?
                            .into_inner()
                            .connection
                            .ok_or_else(|| anyhow::anyhow!("connection not found"))?;

                        let mut ibc_client_client =
                            IbcClientQueryClient::new(app.pd_channel().await?);
                        let req = QueryClientStateRequest {
                            client_id: connection.client_id,
                        };
                        let client_state = ibc_client_client
                            .client_state(req)
                            .await?
                            .into_inner()
                            .client_state
                            .ok_or_else(|| anyhow::anyhow!("client state not found"))?;

                        let tm_client_state = TendermintClientState::try_from(client_state)?;

                        let last_update_height = tm_client_state.latest_height;

                        // 10 seconds per block, 2 days
                        let timeout_n_blocks = ((24 * 60 * 60) / 10) * 2;

                        IbcHeight {
                            revision_number: last_update_height.revision_number,
                            revision_height: last_update_height.revision_height + timeout_n_blocks,
                        }
                    }
                };

                // get the current time on the local machine
                let current_time_ns = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .expect("Time went backwards")
                    .as_nanos() as u64;

                let mut timeout_timestamp = *timeout_timestamp;
                if timeout_timestamp == 0u64 {
                    // add 2 days to current time
                    timeout_timestamp = current_time_ns + 1.728e14 as u64;
                }

                // round to the nearest 10 minutes
                timeout_timestamp += 600_000_000_000 - (timeout_timestamp % 600_000_000_000);

                fn parse_denom_and_amount(value_str: &str) -> anyhow::Result<(Amount, Metadata)> {
                    let denom_re = Regex::new(r"^([0-9.]+)(.+)$").context("denom regex invalid")?;
                    if let Some(captures) = denom_re.captures(value_str) {
                        let numeric_str = captures.get(1).expect("matched regex").as_str();
                        let denom_str = captures.get(2).expect("matched regex").as_str();

                        let display_denom = asset::REGISTRY.parse_unit(denom_str);
                        let amount = display_denom.parse_value(numeric_str)?;
                        let denom = display_denom.base();

                        Ok((amount, denom))
                    } else {
                        Err(anyhow::anyhow!("could not parse value"))
                    }
                }

                let (amount, denom) = parse_denom_and_amount(value)?;

                let withdrawal = Ics20Withdrawal {
                    destination_chain_address: destination_chain_address.to_string(),
                    denom,
                    amount,
                    timeout_height,
                    timeout_time: timeout_timestamp,
                    return_address: ephemeral_return_address,
                    // TODO: impl From<u64> for ChannelId
                    source_channel: ChannelId::from_str(format!("channel-{}", channel).as_ref())?,
                };

                let plan = Planner::new(OsRng)
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into())
                    .ics20_withdrawal(withdrawal)
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        AddressIndex::new(*source),
                    )
                    .await?;
                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::Position(PositionCmd::Close {
                position_id,
                source,
                fee_tier,
            }) => {
                let plan = Planner::new(OsRng)
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into())
                    .position_close(*position_id)
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        AddressIndex::new(*source),
                    )
                    .await?;
                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::Position(PositionCmd::CloseAll {
                source,
                trading_pair,
                fee_tier,
            }) => {
                let view: &mut dyn ViewClient = app
                    .view
                    .as_mut()
                    .context("view service must be initialized")?;

                let owned_position_ids = view
                    .owned_position_ids(Some(position::State::Opened), *trading_pair)
                    .await?;

                if owned_position_ids.is_empty() {
                    println!("No open positions are available to close.");
                    return Ok(());
                }

                let mut planner = Planner::new(OsRng);
                planner
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into());

                for position_id in owned_position_ids {
                    // Close the position
                    planner.position_close(position_id);
                }

                let final_plan = planner
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        AddressIndex::new(*source),
                    )
                    .await?;
                app.build_and_submit_transaction(final_plan).await?;
            }
            TxCmd::Position(PositionCmd::WithdrawAll {
                source,
                trading_pair,
                fee_tier,
            }) => {
                let view: &mut dyn ViewClient = app
                    .view
                    .as_mut()
                    .context("view service must be initialized")?;

                let owned_position_ids = view
                    .owned_position_ids(Some(position::State::Closed), *trading_pair)
                    .await?;

                if owned_position_ids.is_empty() {
                    println!("No closed positions are available to withdraw.");
                    return Ok(());
                }

                let mut planner = Planner::new(OsRng);
                planner
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into());

                let mut client = DexQueryServiceClient::new(app.pd_channel().await?);

                for position_id in owned_position_ids {
                    // Withdraw the position

                    // Fetch the information regarding the position from the view service.
                    let position = client
                        .liquidity_position_by_id(LiquidityPositionByIdRequest {
                            position_id: Some(position_id.into()),
                        })
                        .await?
                        .into_inner();

                    let reserves = position
                        .data
                        .clone()
                        .expect("missing position metadata")
                        .reserves
                        .expect("missing position reserves");
                    let pair = position
                        .data
                        .expect("missing position")
                        .phi
                        .expect("missing position trading function")
                        .pair
                        .expect("missing trading function pair");
                    planner.position_withdraw(
                        position_id,
                        reserves.try_into().expect("invalid reserves"),
                        pair.try_into().expect("invalid pair"),
                    );
                }

                let final_plan = planner
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        AddressIndex::new(*source),
                    )
                    .await?;
                app.build_and_submit_transaction(final_plan).await?;
            }
            TxCmd::Position(PositionCmd::Withdraw {
                source,
                position_id,
                fee_tier,
            }) => {
                let mut client = DexQueryServiceClient::new(app.pd_channel().await?);

                // Fetch the information regarding the position from the view service.
                let position = client
                    .liquidity_position_by_id(LiquidityPositionByIdRequest {
                        position_id: Some(PositionId::from(*position_id)),
                    })
                    .await?
                    .into_inner();

                let reserves = position
                    .data
                    .clone()
                    .expect("missing position metadata")
                    .reserves
                    .expect("missing position reserves");
                let pair = position
                    .data
                    .expect("missing position")
                    .phi
                    .expect("missing position trading function")
                    .pair
                    .expect("missing trading function pair");

                let plan = Planner::new(OsRng)
                    .set_gas_prices(gas_prices)
                    .set_fee_tier((*fee_tier).into())
                    .position_withdraw(*position_id, reserves.try_into()?, pair.try_into()?)
                    .plan(
                        app.view
                            .as_mut()
                            .context("view service must be initialized")?,
                        AddressIndex::new(*source),
                    )
                    .await?;
                app.build_and_submit_transaction(plan).await?;
            }
            TxCmd::Position(PositionCmd::RewardClaim {}) => {
                unimplemented!("deprecated, remove this")
            }
            TxCmd::Position(PositionCmd::Replicate(replicate_cmd)) => {
                replicate_cmd.exec(app).await?;
            }
            TxCmd::Auction(AuctionCmd::Dutch(auction_cmd)) => {
                auction_cmd.exec(app).await?;
            }
        }
        Ok(())
    }
}