-
Notifications
You must be signed in to change notification settings - Fork 978
/
tx.rs
4154 lines (3862 loc) · 129 KB
/
tx.rs
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
//! SDK functions to construct different types of transactions
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::time::Duration;
use borsh::BorshSerialize;
use borsh_ext::BorshSerializeExt;
use masp_primitives::asset_type::AssetType;
use masp_primitives::transaction::builder::Builder;
use masp_primitives::transaction::components::sapling::fees::{
ConvertView, InputView as SaplingInputView, OutputView as SaplingOutputView,
};
use masp_primitives::transaction::components::transparent::fees::{
InputView as TransparentInputView, OutputView as TransparentOutputView,
};
use masp_primitives::transaction::components::I128Sum;
use masp_primitives::transaction::Transaction as MaspTransaction;
use namada_account::{InitAccount, UpdateAccount};
use namada_core::address::{Address, IBC, MASP};
use namada_core::arith::checked;
use namada_core::chain::Epoch;
use namada_core::collections::HashSet;
use namada_core::dec::Dec;
use namada_core::hash::Hash;
use namada_core::ibc::apps::nft_transfer::types::msgs::transfer::MsgTransfer as IbcMsgNftTransfer;
use namada_core::ibc::apps::nft_transfer::types::packet::PacketData as NftPacketData;
use namada_core::ibc::apps::nft_transfer::types::PrefixedClassId;
use namada_core::ibc::apps::transfer::types::msgs::transfer::MsgTransfer as IbcMsgTransfer;
use namada_core::ibc::apps::transfer::types::packet::PacketData;
use namada_core::ibc::apps::transfer::types::PrefixedCoin;
use namada_core::ibc::core::channel::types::timeout::{
TimeoutHeight, TimeoutTimestamp,
};
use namada_core::ibc::core::client::types::Height as IbcHeight;
use namada_core::ibc::core::host::types::identifiers::{ChannelId, PortId};
use namada_core::ibc::primitives::Timestamp as IbcTimestamp;
use namada_core::key::{self, *};
use namada_core::masp::{
AssetData, ExtendedSpendingKey, MaspEpoch, TransferSource, TransferTarget,
};
use namada_core::storage;
use namada_core::time::DateTimeUtc;
use namada_governance::cli::onchain::{
DefaultProposal, OnChainProposal, PgfFundingProposal, PgfStewardProposal,
};
use namada_governance::pgf::cli::steward::Commission;
use namada_governance::storage::proposal::{
InitProposalData, ProposalType, VoteProposalData,
};
use namada_governance::storage::vote::ProposalVote;
use namada_ibc::storage::channel_key;
use namada_ibc::trace::is_nft_trace;
use namada_ibc::{MsgNftTransfer, MsgTransfer};
use namada_io::{display_line, edisplay_line, Client, Io};
use namada_proof_of_stake::parameters::{
PosParams, MAX_VALIDATOR_METADATA_LEN,
};
use namada_proof_of_stake::types::{CommissionPair, ValidatorState};
use namada_token as token;
use namada_token::masp::shielded_wallet::ShieldedApi;
use namada_token::masp::{MaspFeeData, MaspTransferData, ShieldedTransfer};
use namada_token::storage_key::balance_key;
use namada_token::DenominatedAmount;
use namada_tx::data::pgf::UpdateStewardCommission;
use namada_tx::data::pos::{BecomeValidator, ConsensusKeyChange};
use namada_tx::data::{
compute_inner_tx_hash, pos, BatchedTxResult, DryRunResult, ResultCode,
};
pub use namada_tx::{Authorization, *};
use num_traits::Zero;
use rand_core::{OsRng, RngCore};
use crate::args::{
SdkTypes, TxShieldedTransferData, TxShieldingTransferData,
TxTransparentTransferData, TxUnshieldingTransferData,
};
use crate::control_flow::time;
use crate::error::{EncodingError, Error, QueryError, Result, TxSubmitError};
use crate::rpc::{
self, get_validator_stake, query_wasm_code_hash, validate_amount,
InnerTxResult, TxBroadcastData, TxResponse,
};
use crate::signing::{
self, validate_fee, validate_transparent_fee, SigningTxData,
};
use crate::tendermint_rpc::endpoint::broadcast::tx_sync::Response;
use crate::tendermint_rpc::error::Error as RpcError;
use crate::wallet::WalletIo;
use crate::{args, Namada};
/// Initialize account transaction WASM
pub const TX_INIT_ACCOUNT_WASM: &str = "tx_init_account.wasm";
/// Become validator transaction WASM path
pub const TX_BECOME_VALIDATOR_WASM: &str = "tx_become_validator.wasm";
/// Unjail validator transaction WASM path
pub const TX_UNJAIL_VALIDATOR_WASM: &str = "tx_unjail_validator.wasm";
/// Deactivate validator transaction WASM path
pub const TX_DEACTIVATE_VALIDATOR_WASM: &str = "tx_deactivate_validator.wasm";
/// Reactivate validator transaction WASM path
pub const TX_REACTIVATE_VALIDATOR_WASM: &str = "tx_reactivate_validator.wasm";
/// Initialize proposal transaction WASM path
pub const TX_INIT_PROPOSAL: &str = "tx_init_proposal.wasm";
/// Vote transaction WASM path
pub const TX_VOTE_PROPOSAL: &str = "tx_vote_proposal.wasm";
/// Reveal public key transaction WASM path
pub const TX_REVEAL_PK: &str = "tx_reveal_pk.wasm";
/// Update validity predicate WASM path
pub const TX_UPDATE_ACCOUNT_WASM: &str = "tx_update_account.wasm";
/// Transparent transfer transaction WASM path
pub const TX_TRANSFER_WASM: &str = "tx_transfer.wasm";
/// IBC transaction WASM path
pub const TX_IBC_WASM: &str = "tx_ibc.wasm";
/// User validity predicate WASM path
pub const VP_USER_WASM: &str = "vp_user.wasm";
/// Bond WASM path
pub const TX_BOND_WASM: &str = "tx_bond.wasm";
/// Unbond WASM path
pub const TX_UNBOND_WASM: &str = "tx_unbond.wasm";
/// Withdraw WASM path
pub const TX_WITHDRAW_WASM: &str = "tx_withdraw.wasm";
/// Claim-rewards WASM path
pub const TX_CLAIM_REWARDS_WASM: &str = "tx_claim_rewards.wasm";
/// Bridge pool WASM path
pub const TX_BRIDGE_POOL_WASM: &str = "tx_bridge_pool.wasm";
/// Change commission WASM path
pub const TX_CHANGE_COMMISSION_WASM: &str =
"tx_change_validator_commission.wasm";
/// Change consensus key WASM path
pub const TX_CHANGE_CONSENSUS_KEY_WASM: &str = "tx_change_consensus_key.wasm";
/// Change validator metadata WASM path
pub const TX_CHANGE_METADATA_WASM: &str = "tx_change_validator_metadata.wasm";
/// Resign steward WASM path
pub const TX_RESIGN_STEWARD: &str = "tx_resign_steward.wasm";
/// Update steward commission WASM path
pub const TX_UPDATE_STEWARD_COMMISSION: &str =
"tx_update_steward_commission.wasm";
/// Redelegate transaction WASM path
pub const TX_REDELEGATE_WASM: &str = "tx_redelegate.wasm";
/// Refund target alias prefix for IBC shielded transfers
const IBC_REFUND_ALIAS_PREFIX: &str = "ibc-refund-target";
/// Default timeout in seconds for requests to the `/accepted`
/// and `/applied` ABCI query endpoints.
const DEFAULT_NAMADA_EVENTS_MAX_WAIT_TIME_SECONDS: u64 = 60;
/// Capture the result of running a transaction
#[derive(Debug)]
pub enum ProcessTxResponse {
/// Result of submitting a transaction to the blockchain
Applied(TxResponse),
/// Result of submitting a transaction to the mempool
Broadcast(Response),
/// Result of dry running transaction
DryRun(DryRunResult),
}
impl ProcessTxResponse {
/// Returns a `TxResult` if the transaction applied and was it accepted by
/// all VPs. Note that this always returns false for dry-run transactions.
pub fn is_applied_and_valid(
&self,
wrapper_hash: Option<&Hash>,
cmt: &TxCommitments,
) -> Option<&BatchedTxResult> {
match self {
ProcessTxResponse::Applied(resp) => {
if resp.code == ResultCode::Ok {
if let Some(InnerTxResult::Success(result)) =
resp.batch_result().get(&compute_inner_tx_hash(
wrapper_hash,
either::Right(cmt),
))
{
return Some(result);
}
}
None
}
ProcessTxResponse::DryRun(_) | ProcessTxResponse::Broadcast(_) => {
None
}
}
}
}
/// Build and dump a transaction either to file or to screen
pub fn dump_tx<IO: Io>(io: &IO, args: &args::Tx, mut tx: Tx) -> Result<()> {
if args.dump_tx {
tx.update_header(data::TxType::Raw);
};
if args.dump_wrapper_tx && tx.header.wrapper().is_none() {
return Err(Error::Other(
"Requested wrapper-dump on a tx which is not a wrapper".to_string(),
));
}
match args.output_folder.clone() {
Some(path) => {
let tx_path = path.join(format!(
"{}.tx",
tx.header_hash().to_string().to_lowercase()
));
let out = File::create(&tx_path)
.expect("Should be able to create a file to dump tx");
tx.to_writer_json(out)
.expect("Should be able to write to file.");
display_line!(
io,
"Transaction serialized to {}.",
tx_path.to_string_lossy()
);
}
None => {
let serialized_tx = serde_json::to_string_pretty(&tx)
.expect("Should be able to json encode the tx.");
display_line!(io, "Below the serialized transaction: \n");
display_line!(io, "{}", serialized_tx)
}
}
Ok(())
}
/// Prepare a transaction for signing and submission by adding a wrapper header
/// to it.
pub async fn prepare_tx(
args: &args::Tx,
tx: &mut Tx,
fee_amount: DenominatedAmount,
fee_payer: common::PublicKey,
) -> Result<()> {
if args.dry_run || args.dump_tx {
Ok(())
} else {
signing::wrap_tx(tx, args, fee_amount, fee_payer).await
}
}
/// Submit transaction and wait for result. Returns a list of addresses
/// initialized in the transaction if any. In dry run, this is always empty.
pub async fn process_tx(
context: &impl Namada,
args: &args::Tx,
tx: Tx,
) -> Result<ProcessTxResponse> {
// NOTE: use this to print the request JSON body:
// let request =
// tendermint_rpc::endpoint::broadcast::tx_commit::Request::new(
// tx_bytes.clone().into(),
// );
// use tendermint_rpc::Request;
// let request_body = request.into_json();
// println!("HTTP request body: {}", request_body);
if args.dry_run || args.dry_run_wrapper {
expect_dry_broadcast(TxBroadcastData::DryRun(tx), context).await
} else {
// We use this to determine when the wrapper tx makes it on-chain
let tx_hash = tx.header_hash().to_string();
let cmts = tx.commitments().clone();
let wrapper_hash = tx.wrapper_hash();
// We use this to determine when the decrypted inner tx makes it
// on-chain
let to_broadcast = TxBroadcastData::Live { tx, tx_hash };
if args.broadcast_only {
broadcast_tx(context, &to_broadcast)
.await
.map(ProcessTxResponse::Broadcast)
} else {
match submit_tx(context, to_broadcast).await {
Ok(resp) => {
for cmt in cmts {
if let Some(InnerTxResult::Success(result)) =
resp.batch_result().get(&compute_inner_tx_hash(
wrapper_hash.as_ref(),
either::Right(&cmt),
))
{
save_initialized_accounts(
context,
args,
result.initialized_accounts.clone(),
)
.await;
}
}
Ok(ProcessTxResponse::Applied(resp))
}
Err(x) => Err(x),
}
}
}
}
/// Check if a reveal public key transaction is needed
pub async fn is_reveal_pk_needed<C: Client + Sync>(
client: &C,
address: &Address,
) -> Result<bool> {
// Check if PK revealed
Ok(!has_revealed_pk(client, address).await?)
}
/// Check if the public key for the given address has been revealed
pub async fn has_revealed_pk<C: Client + Sync>(
client: &C,
address: &Address,
) -> Result<bool> {
rpc::is_public_key_revealed(client, address).await
}
/// Submit transaction to reveal the given public key
pub async fn build_reveal_pk(
context: &impl Namada,
args: &args::Tx,
public_key: &common::PublicKey,
) -> Result<(Tx, SigningTxData)> {
let signing_data = signing::aux_signing_data(
context,
args,
None,
Some(public_key.into()),
vec![],
false,
)
.await?;
let (fee_amount, _) =
validate_transparent_fee(context, args, &signing_data.fee_payer)
.await?;
build(
context,
args,
args.tx_reveal_code_path.clone(),
public_key,
do_nothing,
fee_amount,
&signing_data.fee_payer,
)
.await
.map(|tx| (tx, signing_data))
}
/// Broadcast a transaction to be included in the blockchain and checks that
/// the tx has been successfully included into the mempool of a node
///
/// In the case of errors in any of those stages, an error message is returned
pub async fn broadcast_tx(
context: &impl Namada,
to_broadcast: &TxBroadcastData,
) -> Result<Response> {
let (tx, tx_hash) = match to_broadcast {
TxBroadcastData::Live { tx, tx_hash } => Ok((tx, tx_hash)),
TxBroadcastData::DryRun(tx) => {
Err(TxSubmitError::ExpectLiveRun(tx.clone()))
}
}?;
tracing::debug!(
transaction = ?to_broadcast,
"Broadcasting transaction",
);
let response = lift_rpc_error(
context.client().broadcast_tx_sync(tx.to_bytes()).await,
)?;
if response.code == 0.into() {
display_line!(context.io(), "Transaction added to mempool.");
tracing::debug!("Transaction mempool response: {response:#?}");
// Print the transaction identifiers to enable the extraction of
// acceptance/application results later
{
display_line!(context.io(), "Transaction hash: {tx_hash}",);
}
Ok(response)
} else {
Err(Error::from(TxSubmitError::TxBroadcast(RpcError::server(
serde_json::to_string(&response).map_err(|err| {
Error::from(EncodingError::Serde(err.to_string()))
})?,
))))
}
}
/// Broadcast a transaction to be included in the blockchain.
///
/// Checks that
/// 1. The tx has been successfully included into the mempool of a validator
/// 2. The tx with encrypted payload has been included on the blockchain
/// 3. The decrypted payload of the tx has been included on the blockchain.
///
/// In the case of errors in any of those stages, an error message is returned
pub async fn submit_tx(
context: &impl Namada,
to_broadcast: TxBroadcastData,
) -> Result<TxResponse> {
let (_, tx_hash) = match &to_broadcast {
TxBroadcastData::Live { tx, tx_hash } => Ok((tx, tx_hash)),
TxBroadcastData::DryRun(tx) => {
Err(TxSubmitError::ExpectLiveRun(tx.clone()))
}
}?;
// Broadcast the supplied transaction
broadcast_tx(context, &to_broadcast).await?;
#[allow(clippy::disallowed_methods)]
let deadline = time::Instant::now()
+ time::Duration::from_secs(
DEFAULT_NAMADA_EVENTS_MAX_WAIT_TIME_SECONDS,
);
tracing::debug!(
transaction = ?to_broadcast,
?deadline,
"Awaiting transaction approval",
);
// The transaction is now on chain. We wait for it to be applied
let tx_query = rpc::TxEventQuery::Applied(tx_hash.as_str());
let event = rpc::query_tx_status(context, tx_query, deadline).await?;
let response = TxResponse::from_event(event);
display_batch_resp(context, &response);
Ok(response)
}
/// Display a result of a tx batch.
pub fn display_batch_resp(context: &impl Namada, resp: &TxResponse) {
for (inner_hash, result) in resp.batch_result() {
match result {
InnerTxResult::Success(_) => {
display_line!(
context.io(),
"Transaction {} was successfully applied at height {}, \
consuming {} gas units.",
inner_hash,
resp.height,
resp.gas_used
);
}
InnerTxResult::VpsRejected(inner) => {
let changed_keys: Vec<_> = inner
.changed_keys
.iter()
.map(storage::Key::to_string)
.collect();
edisplay_line!(
context.io(),
"Transaction {} was rejected by VPs: {}\nErrors: \
{}\nChanged keys: {}",
inner_hash,
serde_json::to_string_pretty(
&inner.vps_result.rejected_vps
)
.unwrap(),
serde_json::to_string_pretty(&inner.vps_result.errors)
.unwrap(),
serde_json::to_string_pretty(&changed_keys).unwrap(),
);
}
InnerTxResult::OtherFailure => {
edisplay_line!(
context.io(),
"Transaction {} failed.\nDetails: {}",
inner_hash,
serde_json::to_string_pretty(&resp).unwrap()
);
}
}
}
tracing::debug!(
"Full result: {}",
serde_json::to_string_pretty(&resp).unwrap()
);
}
/// Save accounts initialized from a tx into the wallet, if any.
pub async fn save_initialized_accounts<N: Namada>(
context: &N,
args: &args::Tx,
initialized_accounts: Vec<Address>,
) {
let len = initialized_accounts.len();
if len != 0 {
// Store newly initialized account addresses in the wallet
display_line!(
context.io(),
"The transaction initialized {} new account{}",
len,
if len == 1 { "" } else { "s" }
);
// Store newly initialized account addresses in the wallet
for (ix, address) in initialized_accounts.iter().enumerate() {
let encoded = address.encode();
let alias: Cow<'_, str> = match &args.initialized_account_alias {
Some(initialized_account_alias) => {
if len == 1 {
// If there's only one account, use the
// alias as is
initialized_account_alias.into()
} else {
// If there're multiple accounts, use
// the alias as prefix, followed by
// index number
format!("{}{}", initialized_account_alias, ix).into()
}
}
None => N::WalletUtils::read_alias(&encoded).into(),
};
let alias = alias.into_owned();
let added = context.wallet_mut().await.insert_address(
alias.clone(),
address.clone(),
args.wallet_alias_force,
);
match added {
Some(new_alias) if new_alias != encoded => {
display_line!(
context.io(),
"Added alias {} for address {}.",
new_alias,
encoded
);
}
_ => {
display_line!(
context.io(),
"No alias added for address {}.",
encoded
)
}
};
}
}
}
/// Submit validator commission rate change
pub async fn build_change_consensus_key(
context: &impl Namada,
args::ConsensusKeyChange {
tx: tx_args,
validator,
consensus_key,
tx_code_path,
unsafe_dont_encrypt: _,
}: &args::ConsensusKeyChange,
) -> Result<(Tx, SigningTxData)> {
let consensus_key = if let Some(consensus_key) = consensus_key {
consensus_key
} else {
edisplay_line!(context.io(), "Consensus key must must be present.");
return Err(Error::from(TxSubmitError::Other(
"Consensus key must must be present.".to_string(),
)));
};
// Check that the new consensus key is unique
let consensus_keys = rpc::get_consensus_keys(context.client()).await?;
if consensus_keys.contains(consensus_key) {
edisplay_line!(
context.io(),
"The consensus key is already being used."
);
return Err(Error::from(TxSubmitError::ConsensusKeyNotUnique));
}
let data = ConsensusKeyChange {
validator: validator.clone(),
consensus_key: consensus_key.clone(),
};
let signing_data = signing::aux_signing_data(
context,
tx_args,
None,
None,
vec![consensus_key.clone()],
false,
)
.await?;
let (fee_amount, _updated_balance) =
validate_transparent_fee(context, tx_args, &signing_data.fee_payer)
.await?;
build(
context,
tx_args,
tx_code_path.clone(),
data,
do_nothing,
fee_amount,
&signing_data.fee_payer,
)
.await
.map(|tx| (tx, signing_data))
}
/// Submit validator commission rate change
pub async fn build_validator_commission_change(
context: &impl Namada,
args::CommissionRateChange {
tx: tx_args,
validator,
rate,
tx_code_path,
}: &args::CommissionRateChange,
) -> Result<(Tx, SigningTxData)> {
let default_signer = Some(validator.clone());
let signing_data = signing::aux_signing_data(
context,
tx_args,
Some(validator.clone()),
default_signer,
vec![],
false,
)
.await?;
let (fee_amount, _) =
validate_transparent_fee(context, tx_args, &signing_data.fee_payer)
.await?;
let epoch = rpc::query_epoch(context.client()).await?;
let params: PosParams = rpc::get_pos_params(context.client()).await?;
let validator = validator.clone();
if rpc::is_validator(context.client(), &validator).await? {
if *rate < Dec::zero() || *rate > Dec::one() {
edisplay_line!(
context.io(),
"Invalid new commission rate, received {}",
rate
);
return Err(Error::from(TxSubmitError::InvalidCommissionRate(
*rate,
)));
}
let pipeline_epoch_minus_one =
epoch.unchecked_add(params.pipeline_len - 1);
let CommissionPair {
commission_rate,
max_commission_change_per_epoch,
epoch: _,
} = rpc::query_commission_rate(
context.client(),
&validator,
Some(pipeline_epoch_minus_one),
)
.await?;
match (commission_rate, max_commission_change_per_epoch) {
(Some(commission_rate), Some(max_commission_change_per_epoch)) => {
if rate.is_negative() || *rate > Dec::one() {
edisplay_line!(
context.io(),
"New rate is outside of the allowed range of values \
between 0.0 and 1.0."
);
if !tx_args.force {
return Err(Error::from(
TxSubmitError::InvalidCommissionRate(*rate),
));
}
}
if rate.abs_diff(commission_rate)?
> max_commission_change_per_epoch
{
edisplay_line!(
context.io(),
"New rate is too large of a change with respect to \
the predecessor epoch in which the rate will take \
effect."
);
if !tx_args.force {
return Err(Error::from(
TxSubmitError::InvalidCommissionRate(*rate),
));
}
}
}
(None, None) => {
edisplay_line!(
context.io(),
"Error retrieving commission data from validator storage. \
This address may not yet be a validator."
);
if !tx_args.force {
return Err(Error::from(TxSubmitError::Retrieval));
}
}
_ => {
edisplay_line!(
context.io(),
"Error retrieving some of the commission data from \
validator storage, while other data was found. This is a \
bug and should be reported."
);
if !tx_args.force {
return Err(Error::from(TxSubmitError::Retrieval));
}
}
}
} else {
edisplay_line!(
context.io(),
"The given address {validator} is not a validator."
);
if !tx_args.force {
return Err(Error::from(TxSubmitError::InvalidValidatorAddress(
validator,
)));
}
}
let data = pos::CommissionChange {
validator: validator.clone(),
new_rate: *rate,
};
build(
context,
tx_args,
tx_code_path.clone(),
data,
do_nothing,
fee_amount,
&signing_data.fee_payer,
)
.await
.map(|tx| (tx, signing_data))
}
/// Submit validator metadata change
pub async fn build_validator_metadata_change(
context: &impl Namada,
args::MetaDataChange {
tx: tx_args,
validator,
email,
description,
website,
discord_handle,
avatar,
name,
commission_rate,
tx_code_path,
}: &args::MetaDataChange,
) -> Result<(Tx, SigningTxData)> {
let default_signer = Some(validator.clone());
let signing_data = signing::aux_signing_data(
context,
tx_args,
Some(validator.clone()),
default_signer,
vec![],
false,
)
.await?;
let (fee_amount, _) =
validate_transparent_fee(context, tx_args, &signing_data.fee_payer)
.await?;
let epoch = rpc::query_epoch(context.client()).await?;
let params: PosParams = rpc::get_pos_params(context.client()).await?;
// The validator must actually be a validator
let validator =
known_validator_or_err(validator.clone(), tx_args.force, context)
.await?;
// If there is a new email, it cannot be an empty string that indicates to
// remove the data (email data cannot be removed)
if let Some(email) = email.as_ref() {
if email.is_empty() {
edisplay_line!(
context.io(),
"Cannot remove a validator's email, which was implied by the \
empty string"
);
return Err(Error::from(TxSubmitError::InvalidEmail));
}
// Check that the email is within MAX_VALIDATOR_METADATA_LEN characters
if email.len() as u64 > MAX_VALIDATOR_METADATA_LEN {
edisplay_line!(
context.io(),
"Email provided is too long, must be within \
{MAX_VALIDATOR_METADATA_LEN} characters"
);
if !tx_args.force {
return Err(Error::from(TxSubmitError::MetadataTooLong));
}
}
}
// Check that any new metadata provided is within MAX_VALIDATOR_METADATA_LEN
// characters
if let Some(description) = description.as_ref() {
if description.len() as u64 > MAX_VALIDATOR_METADATA_LEN {
edisplay_line!(
context.io(),
"Description provided is too long, must be within \
{MAX_VALIDATOR_METADATA_LEN} characters"
);
if !tx_args.force {
return Err(Error::from(TxSubmitError::MetadataTooLong));
}
}
}
if let Some(website) = website.as_ref() {
if website.len() as u64 > MAX_VALIDATOR_METADATA_LEN {
edisplay_line!(
context.io(),
"Website provided is too long, must be within \
{MAX_VALIDATOR_METADATA_LEN} characters"
);
if !tx_args.force {
return Err(Error::from(TxSubmitError::MetadataTooLong));
}
}
}
if let Some(discord_handle) = discord_handle.as_ref() {
if discord_handle.len() as u64 > MAX_VALIDATOR_METADATA_LEN {
edisplay_line!(
context.io(),
"Discord handle provided is too long, must be within \
{MAX_VALIDATOR_METADATA_LEN} characters"
);
if !tx_args.force {
return Err(Error::from(TxSubmitError::MetadataTooLong));
}
}
}
if let Some(avatar) = avatar.as_ref() {
if avatar.len() as u64 > MAX_VALIDATOR_METADATA_LEN {
edisplay_line!(
context.io(),
"Avatar provided is too long, must be within \
{MAX_VALIDATOR_METADATA_LEN} characters"
);
if !tx_args.force {
return Err(Error::from(TxSubmitError::MetadataTooLong));
}
}
}
if let Some(name) = name.as_ref() {
if name.len() as u64 > MAX_VALIDATOR_METADATA_LEN {
edisplay_line!(
context.io(),
"Name provided is too long, must be within \
{MAX_VALIDATOR_METADATA_LEN} characters"
);
if !tx_args.force {
return Err(Error::from(TxSubmitError::MetadataTooLong));
}
}
}
// If there's a new commission rate, it must be valid
if let Some(rate) = commission_rate.as_ref() {
if *rate < Dec::zero() || *rate > Dec::one() {
edisplay_line!(
context.io(),
"Invalid new commission rate, received {}",
rate
);
if !tx_args.force {
return Err(Error::from(TxSubmitError::InvalidCommissionRate(
*rate,
)));
}
}
let pipeline_epoch_minus_one =
epoch.unchecked_add(params.pipeline_len - 1);
let CommissionPair {
commission_rate,
max_commission_change_per_epoch,
epoch: _,
} = rpc::query_commission_rate(
context.client(),
&validator,
Some(pipeline_epoch_minus_one),
)
.await?;
match (commission_rate, max_commission_change_per_epoch) {
(Some(commission_rate), Some(max_commission_change_per_epoch)) => {
if rate.is_negative() || *rate > Dec::one() {
edisplay_line!(
context.io(),
"New rate is outside of the allowed range of values \
between 0.0 and 1.0."
);
if !tx_args.force {
return Err(Error::from(
TxSubmitError::InvalidCommissionRate(*rate),
));
}
}
if rate.abs_diff(commission_rate)?
> max_commission_change_per_epoch
{
edisplay_line!(
context.io(),
"New rate is too large of a change with respect to \
the predecessor epoch in which the rate will take \
effect."
);
if !tx_args.force {
return Err(Error::from(
TxSubmitError::InvalidCommissionRate(*rate),
));
}
}
}
(None, None) => {
edisplay_line!(
context.io(),
"Error retrieving commission data from validator storage. \
This address may not yet be a validator."
);
if !tx_args.force {
return Err(Error::from(TxSubmitError::Retrieval));
}
}
_ => {
edisplay_line!(
context.io(),
"Error retrieving some of the commission data from \
validator storage, while other data was found. This is a \
bug and should be reported."
);
if !tx_args.force {
return Err(Error::from(TxSubmitError::Retrieval));
}
}
}
}
let data = pos::MetaDataChange {
validator: validator.clone(),
email: email.clone(),
website: website.clone(),
description: description.clone(),
discord_handle: discord_handle.clone(),
avatar: avatar.clone(),
name: name.clone(),
commission_rate: *commission_rate,
};
build(
context,
tx_args,
tx_code_path.clone(),
data,
do_nothing,
fee_amount,
&signing_data.fee_payer,
)
.await
.map(|tx| (tx, signing_data))
}
/// Craft transaction to update a steward commission
pub async fn build_update_steward_commission(
context: &impl Namada,
args::UpdateStewardCommission {
tx: tx_args,
steward,
commission,
tx_code_path,
}: &args::UpdateStewardCommission,
) -> Result<(Tx, SigningTxData)> {
let default_signer = Some(steward.clone());
let signing_data = signing::aux_signing_data(
context,
tx_args,
Some(steward.clone()),
default_signer,
vec![],
false,
)
.await?;
let (fee_amount, _) =
validate_transparent_fee(context, tx_args, &signing_data.fee_payer)
.await?;