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
use crate::serialize::u128_dec_format;
use crate::types::{AccountId, Balance, EpochId, Gas, Nonce};
use borsh::{BorshDeserialize, BorshSerialize};
use near_crypto_v01::PublicKey;
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display};
use crate::hash::CryptoHash;
use near_rpc_error_macro::RpcError;
use near_vm_errors_v3::{CompilationError, FunctionCallErrorSer, MethodResolveError, VMLogicError};
#[derive(
BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq, Deserialize, Serialize, RpcError,
)]
pub enum TxExecutionError {
ActionError(ActionError),
InvalidTxError(InvalidTxError),
}
impl Display for TxExecutionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
TxExecutionError::ActionError(e) => write!(f, "{}", e),
TxExecutionError::InvalidTxError(e) => write!(f, "{}", e),
}
}
}
impl From<ActionError> for TxExecutionError {
fn from(error: ActionError) -> Self {
TxExecutionError::ActionError(error)
}
}
impl From<InvalidTxError> for TxExecutionError {
fn from(error: InvalidTxError) -> Self {
TxExecutionError::InvalidTxError(error)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RuntimeError {
UnexpectedIntegerOverflow,
InvalidTxError(InvalidTxError),
StorageError(StorageError),
BalanceMismatchError(BalanceMismatchError),
ReceiptValidationError(ReceiptValidationError),
ValidatorError(EpochError),
}
#[derive(BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq)]
pub enum ExternalError {
StorageError(StorageError),
ValidatorError(EpochError),
}
impl From<ExternalError> for VMLogicError {
fn from(err: ExternalError) -> Self {
VMLogicError::ExternalError(err.try_to_vec().expect("Borsh serialize cannot fail"))
}
}
#[derive(BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq)]
pub enum StorageError {
StorageInternalError,
TrieNodeMissing,
StorageInconsistentState(String),
}
impl std::fmt::Display for StorageError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
f.write_str(&format!("{:?}", self))
}
}
impl std::error::Error for StorageError {}
#[derive(
BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq, Deserialize, Serialize, RpcError,
)]
pub enum InvalidTxError {
InvalidAccessKeyError(InvalidAccessKeyError),
InvalidSignerId { signer_id: String },
SignerDoesNotExist { signer_id: AccountId },
InvalidNonce { tx_nonce: Nonce, ak_nonce: Nonce },
NonceTooLarge { tx_nonce: Nonce, upper_bound: Nonce },
InvalidReceiverId { receiver_id: String },
InvalidSignature,
NotEnoughBalance {
signer_id: AccountId,
#[serde(with = "u128_dec_format")]
balance: Balance,
#[serde(with = "u128_dec_format")]
cost: Balance,
},
LackBalanceForState {
signer_id: AccountId,
#[serde(with = "u128_dec_format")]
amount: Balance,
},
CostOverflow,
InvalidChain,
Expired,
ActionsValidation(ActionsValidationError),
TransactionSizeExceeded { size: u64, limit: u64 },
}
#[derive(
BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq, Deserialize, Serialize, RpcError,
)]
pub enum InvalidAccessKeyError {
AccessKeyNotFound { account_id: AccountId, public_key: PublicKey },
ReceiverMismatch { tx_receiver: AccountId, ak_receiver: String },
MethodNameMismatch { method_name: String },
RequiresFullAccess,
NotEnoughAllowance {
account_id: AccountId,
public_key: PublicKey,
#[serde(with = "u128_dec_format")]
allowance: Balance,
#[serde(with = "u128_dec_format")]
cost: Balance,
},
DepositWithFunctionCall,
}
#[derive(
BorshSerialize, BorshDeserialize, Serialize, Deserialize, Debug, Clone, PartialEq, Eq, RpcError,
)]
pub enum ActionsValidationError {
DeleteActionMustBeFinal,
TotalPrepaidGasExceeded { total_prepaid_gas: Gas, limit: Gas },
TotalNumberOfActionsExceeded { total_number_of_actions: u64, limit: u64 },
AddKeyMethodNamesNumberOfBytesExceeded { total_number_of_bytes: u64, limit: u64 },
AddKeyMethodNameLengthExceeded { length: u64, limit: u64 },
IntegerOverflow,
InvalidAccountId { account_id: AccountId },
ContractSizeExceeded { size: u64, limit: u64 },
FunctionCallMethodNameLengthExceeded { length: u64, limit: u64 },
FunctionCallArgumentsLengthExceeded { length: u64, limit: u64 },
UnsuitableStakingKey { public_key: PublicKey },
FunctionCallZeroAttachedGas,
}
#[derive(
BorshSerialize, BorshDeserialize, Serialize, Deserialize, Debug, Clone, PartialEq, Eq, RpcError,
)]
pub enum ReceiptValidationError {
InvalidPredecessorId { account_id: String },
InvalidReceiverId { account_id: String },
InvalidSignerId { account_id: String },
InvalidDataReceiverId { account_id: String },
ReturnedValueLengthExceeded { length: u64, limit: u64 },
NumberInputDataDependenciesExceeded { number_of_input_data_dependencies: u64, limit: u64 },
ActionsValidation(ActionsValidationError),
}
impl Display for ReceiptValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
ReceiptValidationError::InvalidPredecessorId { account_id } => {
write!(f, "The predecessor_id `{}` of a Receipt is not valid.", account_id)
}
ReceiptValidationError::InvalidReceiverId { account_id } => {
write!(f, "The receiver_id `{}` of a Receipt is not valid.", account_id)
}
ReceiptValidationError::InvalidSignerId { account_id } => {
write!(f, "The signer_id `{}` of an ActionReceipt is not valid.", account_id)
}
ReceiptValidationError::InvalidDataReceiverId { account_id } => write!(
f,
"The receiver_id `{}` of a DataReceiver within an ActionReceipt is not valid.",
account_id
),
ReceiptValidationError::ReturnedValueLengthExceeded { length, limit } => write!(
f,
"The length of the returned data {} exceeded the limit {} in a DataReceipt",
length, limit
),
ReceiptValidationError::NumberInputDataDependenciesExceeded { number_of_input_data_dependencies, limit } => write!(
f,
"The number of input data dependencies {} exceeded the limit {} in an ActionReceipt",
number_of_input_data_dependencies, limit
),
ReceiptValidationError::ActionsValidation(e) => write!(f, "{}", e),
}
}
}
impl Display for ActionsValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
ActionsValidationError::DeleteActionMustBeFinal => {
write!(f, "The delete action must be the last action in transaction")
}
ActionsValidationError::TotalPrepaidGasExceeded { total_prepaid_gas, limit } => {
write!(f, "The total prepaid gas {} exceeds the limit {}", total_prepaid_gas, limit)
}
ActionsValidationError::TotalNumberOfActionsExceeded {total_number_of_actions, limit } => {
write!(
f,
"The total number of actions {} exceeds the limit {}",
total_number_of_actions, limit
)
}
ActionsValidationError::AddKeyMethodNamesNumberOfBytesExceeded { total_number_of_bytes, limit } => write!(
f,
"The total number of bytes in allowed method names {} exceeds the maximum allowed number {} in a AddKey action",
total_number_of_bytes, limit
),
ActionsValidationError::AddKeyMethodNameLengthExceeded { length, limit } => write!(
f,
"The length of some method name {} exceeds the maximum allowed length {} in a AddKey action",
length, limit
),
ActionsValidationError::IntegerOverflow => write!(
f,
"Integer overflow during a compute",
),
ActionsValidationError::InvalidAccountId { account_id } => write!(
f,
"Invalid account ID `{}`",
account_id
),
ActionsValidationError::ContractSizeExceeded { size, limit } => write!(
f,
"The length of the contract size {} exceeds the maximum allowed size {} in a DeployContract action",
size, limit
),
ActionsValidationError::FunctionCallMethodNameLengthExceeded { length, limit } => write!(
f,
"The length of the method name {} exceeds the maximum allowed length {} in a FunctionCall action",
length, limit
),
ActionsValidationError::FunctionCallArgumentsLengthExceeded { length, limit } => write!(
f,
"The length of the arguments {} exceeds the maximum allowed length {} in a FunctionCall action",
length, limit
),
ActionsValidationError::UnsuitableStakingKey { public_key } => write!(
f,
"The staking key must be ristretto compatible ED25519 key. {} is provided instead.",
public_key,
),
ActionsValidationError::FunctionCallZeroAttachedGas => write!(
f,
"The attached amount of gas in a FunctionCall action has to be a positive number",
),
}
}
}
#[derive(
BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq, Deserialize, Serialize, RpcError,
)]
pub struct ActionError {
pub index: Option<u64>,
pub kind: ActionErrorKind,
}
#[derive(Debug, Clone, PartialEq, Eq, RpcError)]
pub enum ContractCallError {
MethodResolveError(MethodResolveError),
CompilationError(CompilationError),
ExecutionError { msg: String },
}
impl From<ContractCallError> for FunctionCallErrorSer {
fn from(e: ContractCallError) -> Self {
match e {
ContractCallError::CompilationError(e) => FunctionCallErrorSer::CompilationError(e),
ContractCallError::MethodResolveError(e) => FunctionCallErrorSer::MethodResolveError(e),
ContractCallError::ExecutionError { msg } => FunctionCallErrorSer::ExecutionError(msg),
}
}
}
impl From<FunctionCallErrorSer> for ContractCallError {
fn from(e: FunctionCallErrorSer) -> Self {
match e {
FunctionCallErrorSer::CompilationError(e) => ContractCallError::CompilationError(e),
FunctionCallErrorSer::MethodResolveError(e) => ContractCallError::MethodResolveError(e),
FunctionCallErrorSer::ExecutionError(msg) => ContractCallError::ExecutionError { msg },
FunctionCallErrorSer::LinkError { msg } => ContractCallError::ExecutionError { msg },
FunctionCallErrorSer::WasmUnknownError => {
ContractCallError::ExecutionError { msg: "unknown error".to_string() }
}
FunctionCallErrorSer::_EVMError => unreachable!(),
FunctionCallErrorSer::WasmTrap(e) => {
ContractCallError::ExecutionError { msg: format!("WASM: {:?}", e) }
}
FunctionCallErrorSer::HostError(e) => {
ContractCallError::ExecutionError { msg: format!("Host: {:?}", e) }
}
}
}
}
#[derive(
BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq, Deserialize, Serialize, RpcError,
)]
pub enum ActionErrorKind {
AccountAlreadyExists { account_id: AccountId },
AccountDoesNotExist { account_id: AccountId },
CreateAccountOnlyByRegistrar {
account_id: AccountId,
registrar_account_id: AccountId,
predecessor_id: AccountId,
},
CreateAccountNotAllowed { account_id: AccountId, predecessor_id: AccountId },
ActorNoPermission { account_id: AccountId, actor_id: AccountId },
DeleteKeyDoesNotExist { account_id: AccountId, public_key: PublicKey },
AddKeyAlreadyExists { account_id: AccountId, public_key: PublicKey },
DeleteAccountStaking { account_id: AccountId },
LackBalanceForState {
account_id: AccountId,
#[serde(with = "u128_dec_format")]
amount: Balance,
},
TriesToUnstake { account_id: AccountId },
TriesToStake {
account_id: AccountId,
#[serde(with = "u128_dec_format")]
stake: Balance,
#[serde(with = "u128_dec_format")]
locked: Balance,
#[serde(with = "u128_dec_format")]
balance: Balance,
},
InsufficientStake {
account_id: AccountId,
#[serde(with = "u128_dec_format")]
stake: Balance,
#[serde(with = "u128_dec_format")]
minimum_stake: Balance,
},
FunctionCallError(FunctionCallErrorSer),
NewReceiptValidationError(ReceiptValidationError),
OnlyImplicitAccountCreationAllowed { account_id: AccountId },
DeleteAccountWithLargeState { account_id: AccountId },
}
impl From<ActionErrorKind> for ActionError {
fn from(e: ActionErrorKind) -> ActionError {
ActionError { index: None, kind: e }
}
}
impl Display for InvalidTxError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
InvalidTxError::InvalidSignerId { signer_id } => {
write!(f, "Invalid signer account ID {:?} according to requirements", signer_id)
}
InvalidTxError::SignerDoesNotExist { signer_id } => {
write!(f, "Signer {:?} does not exist", signer_id)
}
InvalidTxError::InvalidAccessKeyError(access_key_error) => {
Display::fmt(&access_key_error, f)
}
InvalidTxError::InvalidNonce { tx_nonce, ak_nonce } => write!(
f,
"Transaction nonce {} must be larger than nonce of the used access key {}",
tx_nonce, ak_nonce
),
InvalidTxError::InvalidReceiverId { receiver_id } => {
write!(f, "Invalid receiver account ID {:?} according to requirements", receiver_id)
}
InvalidTxError::InvalidSignature => {
write!(f, "Transaction is not signed with the given public key")
}
InvalidTxError::NotEnoughBalance { signer_id, balance, cost } => write!(
f,
"Sender {:?} does not have enough balance {} for operation costing {}",
signer_id, balance, cost
),
InvalidTxError::LackBalanceForState { signer_id, amount } => {
write!(f, "Failed to execute, because the account {:?} wouldn't have enough balance to cover storage, required to have {} yoctoNEAR more", signer_id, amount)
}
InvalidTxError::CostOverflow => {
write!(f, "Transaction gas or balance cost is too high")
}
InvalidTxError::InvalidChain => {
write!(f, "Transaction parent block hash doesn't belong to the current chain")
}
InvalidTxError::Expired => {
write!(f, "Transaction has expired")
}
InvalidTxError::ActionsValidation(error) => {
write!(f, "Transaction actions validation error: {}", error)
}
InvalidTxError::NonceTooLarge { tx_nonce, upper_bound } => {
write!(
f,
"Transaction nonce {} must be smaller than the access key nonce upper bound {}",
tx_nonce, upper_bound
)
}
InvalidTxError::TransactionSizeExceeded { size, limit } => {
write!(f, "Size of serialized transaction {} exceeded the limit {}", size, limit)
}
}
}
}
impl From<InvalidAccessKeyError> for InvalidTxError {
fn from(error: InvalidAccessKeyError) -> Self {
InvalidTxError::InvalidAccessKeyError(error)
}
}
impl Display for InvalidAccessKeyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
InvalidAccessKeyError::AccessKeyNotFound { account_id, public_key } => write!(
f,
"Signer {:?} doesn't have access key with the given public_key {}",
account_id, public_key
),
InvalidAccessKeyError::ReceiverMismatch { tx_receiver, ak_receiver } => write!(
f,
"Transaction receiver_id {:?} doesn't match the access key receiver_id {:?}",
tx_receiver, ak_receiver
),
InvalidAccessKeyError::MethodNameMismatch { method_name } => write!(
f,
"Transaction method name {:?} isn't allowed by the access key",
method_name
),
InvalidAccessKeyError::RequiresFullAccess => {
write!(f, "Invalid access key type. Full-access keys are required for transactions that have multiple or non-function-call actions")
}
InvalidAccessKeyError::NotEnoughAllowance {
account_id,
public_key,
allowance,
cost,
} => write!(
f,
"Access Key {:?}:{} does not have enough balance {} for transaction costing {}",
account_id, public_key, allowance, cost
),
InvalidAccessKeyError::DepositWithFunctionCall => {
write!(f, "Having a deposit with a function call action is not allowed with a function call access key.")
}
}
}
}
#[derive(
BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq, Deserialize, Serialize, RpcError,
)]
pub struct BalanceMismatchError {
#[serde(with = "u128_dec_format")]
pub incoming_validator_rewards: Balance,
#[serde(with = "u128_dec_format")]
pub initial_accounts_balance: Balance,
#[serde(with = "u128_dec_format")]
pub incoming_receipts_balance: Balance,
#[serde(with = "u128_dec_format")]
pub processed_delayed_receipts_balance: Balance,
#[serde(with = "u128_dec_format")]
pub initial_postponed_receipts_balance: Balance,
#[serde(with = "u128_dec_format")]
pub final_accounts_balance: Balance,
#[serde(with = "u128_dec_format")]
pub outgoing_receipts_balance: Balance,
#[serde(with = "u128_dec_format")]
pub new_delayed_receipts_balance: Balance,
#[serde(with = "u128_dec_format")]
pub final_postponed_receipts_balance: Balance,
#[serde(with = "u128_dec_format")]
pub tx_burnt_amount: Balance,
#[serde(with = "u128_dec_format")]
pub slashed_burnt_amount: Balance,
#[serde(with = "u128_dec_format")]
pub other_burnt_amount: Balance,
}
impl Display for BalanceMismatchError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
let initial_balance = self
.incoming_validator_rewards
.saturating_add(self.initial_accounts_balance)
.saturating_add(self.incoming_receipts_balance)
.saturating_add(self.processed_delayed_receipts_balance)
.saturating_add(self.initial_postponed_receipts_balance);
let final_balance = self
.final_accounts_balance
.saturating_add(self.outgoing_receipts_balance)
.saturating_add(self.new_delayed_receipts_balance)
.saturating_add(self.final_postponed_receipts_balance)
.saturating_add(self.tx_burnt_amount)
.saturating_add(self.slashed_burnt_amount)
.saturating_add(self.other_burnt_amount);
write!(
f,
"Balance Mismatch Error. The input balance {} doesn't match output balance {}\n\
Inputs:\n\
\tIncoming validator rewards sum: {}\n\
\tInitial accounts balance sum: {}\n\
\tIncoming receipts balance sum: {}\n\
\tProcessed delayed receipts balance sum: {}\n\
\tInitial postponed receipts balance sum: {}\n\
Outputs:\n\
\tFinal accounts balance sum: {}\n\
\tOutgoing receipts balance sum: {}\n\
\tNew delayed receipts balance sum: {}\n\
\tFinal postponed receipts balance sum: {}\n\
\tTx fees burnt amount: {}\n\
\tSlashed amount: {}\n\
\tOther burnt amount: {}",
initial_balance,
final_balance,
self.incoming_validator_rewards,
self.initial_accounts_balance,
self.incoming_receipts_balance,
self.processed_delayed_receipts_balance,
self.initial_postponed_receipts_balance,
self.final_accounts_balance,
self.outgoing_receipts_balance,
self.new_delayed_receipts_balance,
self.final_postponed_receipts_balance,
self.tx_burnt_amount,
self.slashed_burnt_amount,
self.other_burnt_amount,
)
}
}
#[derive(BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq)]
pub struct IntegerOverflowError;
impl From<IntegerOverflowError> for InvalidTxError {
fn from(_: IntegerOverflowError) -> Self {
InvalidTxError::CostOverflow
}
}
impl From<IntegerOverflowError> for RuntimeError {
fn from(_: IntegerOverflowError) -> Self {
RuntimeError::UnexpectedIntegerOverflow
}
}
impl From<StorageError> for RuntimeError {
fn from(e: StorageError) -> Self {
RuntimeError::StorageError(e)
}
}
impl From<BalanceMismatchError> for RuntimeError {
fn from(e: BalanceMismatchError) -> Self {
RuntimeError::BalanceMismatchError(e)
}
}
impl From<InvalidTxError> for RuntimeError {
fn from(e: InvalidTxError) -> Self {
RuntimeError::InvalidTxError(e)
}
}
impl From<EpochError> for RuntimeError {
fn from(e: EpochError) -> Self {
RuntimeError::ValidatorError(e)
}
}
impl Display for ActionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
write!(f, "Action #{}: {}", self.index.unwrap_or_default(), self.kind)
}
}
impl Display for ActionErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
match self {
ActionErrorKind::AccountAlreadyExists { account_id } => {
write!(f, "Can't create a new account {:?}, because it already exists", account_id)
}
ActionErrorKind::AccountDoesNotExist { account_id } => write!(
f,
"Can't complete the action because account {:?} doesn't exist",
account_id
),
ActionErrorKind::ActorNoPermission { actor_id, account_id } => write!(
f,
"Actor {:?} doesn't have permission to account {:?} to complete the action",
actor_id, account_id
),
ActionErrorKind::LackBalanceForState { account_id, amount } => write!(
f,
"The account {} wouldn't have enough balance to cover storage, required to have {} yoctoNEAR more",
account_id, amount
),
ActionErrorKind::TriesToUnstake { account_id } => {
write!(f, "Account {:?} is not yet staked, but tries to unstake", account_id)
}
ActionErrorKind::TriesToStake { account_id, stake, locked, balance } => write!(
f,
"Account {:?} tries to stake {}, but has staked {} and only has {}",
account_id, stake, locked, balance
),
ActionErrorKind::CreateAccountOnlyByRegistrar { account_id, registrar_account_id, predecessor_id } => write!(
f,
"A top-level account ID {:?} can't be created by {:?}, short top-level account IDs can only be created by {:?}",
account_id, predecessor_id, registrar_account_id,
),
ActionErrorKind::CreateAccountNotAllowed { account_id, predecessor_id } => write!(
f,
"A sub-account ID {:?} can't be created by account {:?}",
account_id, predecessor_id,
),
ActionErrorKind::DeleteKeyDoesNotExist { account_id, .. } => write!(
f,
"Account {:?} tries to remove an access key that doesn't exist",
account_id
),
ActionErrorKind::AddKeyAlreadyExists { public_key, .. } => write!(
f,
"The public key {:?} is already used for an existing access key",
public_key
),
ActionErrorKind::DeleteAccountStaking { account_id } => {
write!(f, "Account {:?} is staking and can not be deleted", account_id)
}
ActionErrorKind::FunctionCallError(s) => write!(f, "{:?}", s),
ActionErrorKind::NewReceiptValidationError(e) => {
write!(f, "An new action receipt created during a FunctionCall is not valid: {}", e)
}
ActionErrorKind::InsufficientStake { account_id, stake, minimum_stake } => write!(f, "Account {} tries to stake {} but minimum required stake is {}", account_id, stake, minimum_stake),
ActionErrorKind::OnlyImplicitAccountCreationAllowed { account_id } => write!(f, "CreateAccount action is called on hex-characters account of length 64 {}", account_id),
ActionErrorKind::DeleteAccountWithLargeState { account_id } => write!(f, "The state of account {} is too large and therefore cannot be deleted", account_id),
}
}
}
#[derive(Eq, PartialEq, BorshSerialize, BorshDeserialize, Clone)]
pub enum EpochError {
ThresholdError { stake_sum: Balance, num_seats: u64 },
EpochOutOfBounds(EpochId),
MissingBlock(CryptoHash),
IOErr(String),
NotAValidator(AccountId, EpochId),
ShardingError(String),
#[cfg(feature = "protocol_feature_chunk_only_producers")]
NotEnoughValidators { num_validators: u64, num_shards: u64 },
}
impl std::error::Error for EpochError {}
impl Display for EpochError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EpochError::ThresholdError { stake_sum, num_seats } => write!(
f,
"Total stake {} must be higher than the number of seats {}",
stake_sum, num_seats
),
EpochError::EpochOutOfBounds(epoch_id) => {
write!(f, "Epoch {:?} is out of bounds", epoch_id)
}
EpochError::MissingBlock(hash) => write!(f, "Missing block {}", hash),
EpochError::IOErr(err) => write!(f, "IO: {}", err),
EpochError::NotAValidator(account_id, epoch_id) => {
write!(f, "{} is not a validator in epoch {:?}", account_id, epoch_id)
}
EpochError::ShardingError(err) => write!(f, "Sharding Error: {}", err),
#[cfg(feature = "protocol_feature_chunk_only_producers")]
EpochError::NotEnoughValidators { num_shards, num_validators } => {
write!(f, "There were not enough validator proposals to fill all shards. num_proposals: {}, num_shards: {}", num_validators, num_shards)
}
}
}
}
impl Debug for EpochError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EpochError::ThresholdError { stake_sum, num_seats } => {
write!(f, "ThresholdError({}, {})", stake_sum, num_seats)
}
EpochError::EpochOutOfBounds(epoch_id) => write!(f, "EpochOutOfBounds({:?})", epoch_id),
EpochError::MissingBlock(hash) => write!(f, "MissingBlock({})", hash),
EpochError::IOErr(err) => write!(f, "IOErr({})", err),
EpochError::NotAValidator(account_id, epoch_id) => {
write!(f, "NotAValidator({}, {:?})", account_id, epoch_id)
}
EpochError::ShardingError(err) => write!(f, "ShardingError({})", err),
#[cfg(feature = "protocol_feature_chunk_only_producers")]
EpochError::NotEnoughValidators { num_shards, num_validators } => {
write!(f, "NotEnoughValidators({}, {})", num_validators, num_shards)
}
}
}
}
impl From<std::io::Error> for EpochError {
fn from(error: std::io::Error) -> Self {
EpochError::IOErr(error.to_string())
}
}