1use crate::action::GlobalContractIdentifier;
2use crate::hash::CryptoHash;
3use crate::serialize::dec_format;
4use crate::shard_layout::ShardLayoutError;
5use crate::sharding::ChunkHash;
6use crate::types::{AccountId, Balance, EpochId, Gas, Nonce};
7use borsh::{BorshDeserialize, BorshSerialize};
8use near_crypto::PublicKey;
9use near_primitives_core::types::ProtocolVersion;
10use near_schema_checker_lib::ProtocolSchema;
11use std::fmt::{Debug, Display};
12
13#[derive(
15 BorshSerialize,
16 BorshDeserialize,
17 Debug,
18 Clone,
19 PartialEq,
20 Eq,
21 serde::Deserialize,
22 serde::Serialize,
23 ProtocolSchema,
24)]
25#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
26pub enum TxExecutionError {
27 ActionError(ActionError),
29 InvalidTxError(InvalidTxError),
31}
32
33impl std::error::Error for TxExecutionError {}
34
35impl Display for TxExecutionError {
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
37 match self {
38 TxExecutionError::ActionError(e) => write!(f, "{}", e),
39 TxExecutionError::InvalidTxError(e) => write!(f, "{}", e),
40 }
41 }
42}
43
44impl From<ActionError> for TxExecutionError {
45 fn from(error: ActionError) -> Self {
46 TxExecutionError::ActionError(error)
47 }
48}
49
50impl From<InvalidTxError> for TxExecutionError {
51 fn from(error: InvalidTxError) -> Self {
52 TxExecutionError::InvalidTxError(error)
53 }
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum RuntimeError {
59 UnexpectedIntegerOverflow(String),
61 InvalidTxError(InvalidTxError),
63 StorageError(StorageError),
66 ReceiptValidationError(ReceiptValidationError),
68 ValidatorError(EpochError),
70}
71
72impl std::fmt::Display for RuntimeError {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
74 f.write_str(&format!("{:?}", self))
75 }
76}
77
78impl std::error::Error for RuntimeError {}
79
80#[derive(
82 Debug,
83 Clone,
84 PartialEq,
85 Eq,
86 serde::Deserialize,
87 serde::Serialize,
88 BorshSerialize,
89 BorshDeserialize,
90 ProtocolSchema,
91)]
92#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
93pub enum MissingTrieValueContext {
94 TrieIterator,
96 TriePrefetchingStorage,
98 TrieMemoryPartialStorage,
100 TrieStorage,
102}
103
104impl MissingTrieValueContext {
105 pub fn metrics_label(&self) -> &str {
106 match self {
107 Self::TrieIterator => "trie_iterator",
108 Self::TriePrefetchingStorage => "trie_prefetching_storage",
109 Self::TrieMemoryPartialStorage => "trie_memory_partial_storage",
110 Self::TrieStorage => "trie_storage",
111 }
112 }
113}
114
115#[derive(
116 Debug,
117 Clone,
118 PartialEq,
119 Eq,
120 serde::Deserialize,
121 serde::Serialize,
122 BorshSerialize,
123 BorshDeserialize,
124 ProtocolSchema,
125)]
126#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
127pub struct MissingTrieValue {
128 pub context: MissingTrieValueContext,
129 pub hash: CryptoHash,
130}
131
132#[derive(
135 Debug,
136 Clone,
137 PartialEq,
138 Eq,
139 serde::Deserialize,
140 serde::Serialize,
141 BorshSerialize,
142 BorshDeserialize,
143 ProtocolSchema,
144)]
145#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
146pub enum StorageError {
147 StorageInternalError,
149 MissingTrieValue(MissingTrieValue),
151 UnexpectedTrieValue,
155 StorageInconsistentState(String),
161 FlatStorageBlockNotSupported(String),
165 MemTrieLoadingError(String),
167}
168
169impl std::fmt::Display for StorageError {
170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
171 f.write_str(&format!("{:?}", self))
172 }
173}
174
175impl std::error::Error for StorageError {}
176
177#[derive(
179 BorshSerialize,
180 BorshDeserialize,
181 Debug,
182 Clone,
183 PartialEq,
184 Eq,
185 serde::Deserialize,
186 serde::Serialize,
187 ProtocolSchema,
188)]
189#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
190pub enum InvalidTxError {
191 InvalidAccessKeyError(InvalidAccessKeyError),
193 InvalidSignerId {
195 signer_id: String,
196 },
197 SignerDoesNotExist {
199 signer_id: AccountId,
200 },
201 InvalidNonce {
203 tx_nonce: Nonce,
204 ak_nonce: Nonce,
205 },
206 NonceTooLarge {
208 tx_nonce: Nonce,
209 upper_bound: Nonce,
210 },
211 InvalidReceiverId {
213 receiver_id: String,
214 },
215 InvalidSignature,
217 NotEnoughBalance {
219 signer_id: AccountId,
220 #[serde(with = "dec_format")]
221 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
222 balance: Balance,
223 #[serde(with = "dec_format")]
224 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
225 cost: Balance,
226 },
227 LackBalanceForState {
229 signer_id: AccountId,
231 #[serde(with = "dec_format")]
233 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
234 amount: Balance,
235 },
236 CostOverflow,
238 InvalidChain,
240 Expired,
242 ActionsValidation(ActionsValidationError),
244 TransactionSizeExceeded {
246 size: u64,
247 limit: u64,
248 },
249 InvalidTransactionVersion,
251 StorageError(StorageError),
253 ShardCongested {
256 shard_id: u32,
258 #[cfg_attr(feature = "schemars", schemars(with = "f64"))]
260 congestion_level: ordered_float::NotNan<f64>,
261 },
262 ShardStuck {
265 shard_id: u32,
267 missed_chunks: u64,
269 },
270}
271
272impl From<StorageError> for InvalidTxError {
273 fn from(error: StorageError) -> Self {
274 InvalidTxError::StorageError(error)
275 }
276}
277
278impl std::error::Error for InvalidTxError {}
279
280#[derive(
281 BorshSerialize,
282 BorshDeserialize,
283 Debug,
284 Clone,
285 PartialEq,
286 Eq,
287 serde::Deserialize,
288 serde::Serialize,
289 ProtocolSchema,
290)]
291#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
292pub enum InvalidAccessKeyError {
293 AccessKeyNotFound { account_id: AccountId, public_key: Box<PublicKey> },
295 ReceiverMismatch { tx_receiver: AccountId, ak_receiver: String },
297 MethodNameMismatch { method_name: String },
299 RequiresFullAccess,
301 NotEnoughAllowance {
303 account_id: AccountId,
304 public_key: Box<PublicKey>,
305 #[serde(with = "dec_format")]
306 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
307 allowance: Balance,
308 #[serde(with = "dec_format")]
309 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
310 cost: Balance,
311 },
312 DepositWithFunctionCall,
314}
315
316#[derive(
318 BorshSerialize,
319 BorshDeserialize,
320 Debug,
321 Clone,
322 PartialEq,
323 Eq,
324 serde::Serialize,
325 serde::Deserialize,
326 ProtocolSchema,
327)]
328#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
329pub enum ActionsValidationError {
330 DeleteActionMustBeFinal,
332 TotalPrepaidGasExceeded { total_prepaid_gas: Gas, limit: Gas },
334 TotalNumberOfActionsExceeded { total_number_of_actions: u64, limit: u64 },
336 AddKeyMethodNamesNumberOfBytesExceeded { total_number_of_bytes: u64, limit: u64 },
338 AddKeyMethodNameLengthExceeded { length: u64, limit: u64 },
340 IntegerOverflow,
342 InvalidAccountId { account_id: String },
344 ContractSizeExceeded { size: u64, limit: u64 },
346 FunctionCallMethodNameLengthExceeded { length: u64, limit: u64 },
348 FunctionCallArgumentsLengthExceeded { length: u64, limit: u64 },
350 UnsuitableStakingKey { public_key: Box<PublicKey> },
352 FunctionCallZeroAttachedGas,
354 DelegateActionMustBeOnlyOne,
356 UnsupportedProtocolFeature { protocol_feature: String, version: ProtocolVersion },
363}
364
365#[derive(
367 BorshSerialize,
368 BorshDeserialize,
369 Debug,
370 Clone,
371 PartialEq,
372 Eq,
373 serde::Serialize,
374 serde::Deserialize,
375 ProtocolSchema,
376)]
377#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
378pub enum ReceiptValidationError {
379 InvalidPredecessorId { account_id: String },
381 InvalidReceiverId { account_id: String },
383 InvalidSignerId { account_id: String },
385 InvalidDataReceiverId { account_id: String },
387 ReturnedValueLengthExceeded { length: u64, limit: u64 },
389 NumberInputDataDependenciesExceeded { number_of_input_data_dependencies: u64, limit: u64 },
391 ActionsValidation(ActionsValidationError),
393 ReceiptSizeExceeded { size: u64, limit: u64 },
395}
396
397impl Display for ReceiptValidationError {
398 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
399 match self {
400 ReceiptValidationError::InvalidPredecessorId { account_id } => {
401 write!(f, "The predecessor_id `{}` of a Receipt is not valid.", account_id)
402 }
403 ReceiptValidationError::InvalidReceiverId { account_id } => {
404 write!(f, "The receiver_id `{}` of a Receipt is not valid.", account_id)
405 }
406 ReceiptValidationError::InvalidSignerId { account_id } => {
407 write!(f, "The signer_id `{}` of an ActionReceipt is not valid.", account_id)
408 }
409 ReceiptValidationError::InvalidDataReceiverId { account_id } => write!(
410 f,
411 "The receiver_id `{}` of a DataReceiver within an ActionReceipt is not valid.",
412 account_id
413 ),
414 ReceiptValidationError::ReturnedValueLengthExceeded { length, limit } => write!(
415 f,
416 "The length of the returned data {} exceeded the limit {} in a DataReceipt",
417 length, limit
418 ),
419 ReceiptValidationError::NumberInputDataDependenciesExceeded {
420 number_of_input_data_dependencies,
421 limit,
422 } => write!(
423 f,
424 "The number of input data dependencies {} exceeded the limit {} in an ActionReceipt",
425 number_of_input_data_dependencies, limit
426 ),
427 ReceiptValidationError::ActionsValidation(e) => write!(f, "{}", e),
428 ReceiptValidationError::ReceiptSizeExceeded { size, limit } => {
429 write!(f, "The size of the receipt exceeded the limit: {} > {}", size, limit)
430 }
431 }
432 }
433}
434
435impl std::error::Error for ReceiptValidationError {}
436
437impl Display for ActionsValidationError {
438 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
439 match self {
440 ActionsValidationError::DeleteActionMustBeFinal => {
441 write!(f, "The delete action must be the last action in transaction")
442 }
443 ActionsValidationError::TotalPrepaidGasExceeded { total_prepaid_gas, limit } => {
444 write!(f, "The total prepaid gas {} exceeds the limit {}", total_prepaid_gas, limit)
445 }
446 ActionsValidationError::TotalNumberOfActionsExceeded {
447 total_number_of_actions,
448 limit,
449 } => {
450 write!(
451 f,
452 "The total number of actions {} exceeds the limit {}",
453 total_number_of_actions, limit
454 )
455 }
456 ActionsValidationError::AddKeyMethodNamesNumberOfBytesExceeded {
457 total_number_of_bytes,
458 limit,
459 } => write!(
460 f,
461 "The total number of bytes in allowed method names {} exceeds the maximum allowed number {} in a AddKey action",
462 total_number_of_bytes, limit
463 ),
464 ActionsValidationError::AddKeyMethodNameLengthExceeded { length, limit } => write!(
465 f,
466 "The length of some method name {} exceeds the maximum allowed length {} in a AddKey action",
467 length, limit
468 ),
469 ActionsValidationError::IntegerOverflow => {
470 write!(f, "Integer overflow during a compute",)
471 }
472 ActionsValidationError::InvalidAccountId { account_id } => {
473 write!(f, "Invalid account ID `{}`", account_id)
474 }
475 ActionsValidationError::ContractSizeExceeded { size, limit } => write!(
476 f,
477 "The length of the contract size {} exceeds the maximum allowed size {} in a DeployContract action",
478 size, limit
479 ),
480 ActionsValidationError::FunctionCallMethodNameLengthExceeded { length, limit } => {
481 write!(
482 f,
483 "The length of the method name {} exceeds the maximum allowed length {} in a FunctionCall action",
484 length, limit
485 )
486 }
487 ActionsValidationError::FunctionCallArgumentsLengthExceeded { length, limit } => {
488 write!(
489 f,
490 "The length of the arguments {} exceeds the maximum allowed length {} in a FunctionCall action",
491 length, limit
492 )
493 }
494 ActionsValidationError::UnsuitableStakingKey { public_key } => write!(
495 f,
496 "The staking key must be ristretto compatible ED25519 key. {} is provided instead.",
497 public_key,
498 ),
499 ActionsValidationError::FunctionCallZeroAttachedGas => write!(
500 f,
501 "The attached amount of gas in a FunctionCall action has to be a positive number",
502 ),
503 ActionsValidationError::DelegateActionMustBeOnlyOne => {
504 write!(f, "The actions can contain the ony one DelegateAction")
505 }
506 ActionsValidationError::UnsupportedProtocolFeature { protocol_feature, version } => {
507 write!(
508 f,
509 "Transaction requires protocol feature {} / version {} which is not supported by the current protocol version",
510 protocol_feature, version,
511 )
512 }
513 }
514 }
515}
516
517impl std::error::Error for ActionsValidationError {}
518
519#[derive(
521 BorshSerialize,
522 BorshDeserialize,
523 Debug,
524 Clone,
525 PartialEq,
526 Eq,
527 serde::Deserialize,
528 serde::Serialize,
529 ProtocolSchema,
530)]
531#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
532pub struct ActionError {
533 pub index: Option<u64>,
536 pub kind: ActionErrorKind,
538}
539
540impl std::error::Error for ActionError {}
541
542#[derive(
543 BorshSerialize,
544 BorshDeserialize,
545 Debug,
546 Clone,
547 PartialEq,
548 Eq,
549 serde::Deserialize,
550 serde::Serialize,
551 ProtocolSchema,
552)]
553#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
554pub enum ActionErrorKind {
555 AccountAlreadyExists {
557 account_id: AccountId,
558 },
559 AccountDoesNotExist {
561 account_id: AccountId,
562 },
563 CreateAccountOnlyByRegistrar {
565 account_id: AccountId,
566 registrar_account_id: AccountId,
567 predecessor_id: AccountId,
568 },
569
570 CreateAccountNotAllowed {
572 account_id: AccountId,
573 predecessor_id: AccountId,
574 },
575 ActorNoPermission {
578 account_id: AccountId,
579 actor_id: AccountId,
580 },
581 DeleteKeyDoesNotExist {
583 account_id: AccountId,
584 public_key: Box<PublicKey>,
585 },
586 AddKeyAlreadyExists {
588 account_id: AccountId,
589 public_key: Box<PublicKey>,
590 },
591 DeleteAccountStaking {
593 account_id: AccountId,
594 },
595 LackBalanceForState {
597 account_id: AccountId,
599 #[serde(with = "dec_format")]
601 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
602 amount: Balance,
603 },
604 TriesToUnstake {
606 account_id: AccountId,
607 },
608 TriesToStake {
610 account_id: AccountId,
611 #[serde(with = "dec_format")]
612 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
613 stake: Balance,
614 #[serde(with = "dec_format")]
615 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
616 locked: Balance,
617 #[serde(with = "dec_format")]
618 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
619 balance: Balance,
620 },
621 InsufficientStake {
622 account_id: AccountId,
623 #[serde(with = "dec_format")]
624 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
625 stake: Balance,
626 #[serde(with = "dec_format")]
627 #[cfg_attr(feature = "schemars", schemars(with = "String"))]
628 minimum_stake: Balance,
629 },
630 FunctionCallError(FunctionCallError),
632 NewReceiptValidationError(ReceiptValidationError),
635 OnlyImplicitAccountCreationAllowed {
642 account_id: AccountId,
643 },
644 DeleteAccountWithLargeState {
646 account_id: AccountId,
647 },
648 DelegateActionInvalidSignature,
650 DelegateActionSenderDoesNotMatchTxReceiver {
652 sender_id: AccountId,
653 receiver_id: AccountId,
654 },
655 DelegateActionExpired,
657 DelegateActionAccessKeyError(InvalidAccessKeyError),
659 DelegateActionInvalidNonce {
661 delegate_nonce: Nonce,
662 ak_nonce: Nonce,
663 },
664 DelegateActionNonceTooLarge {
666 delegate_nonce: Nonce,
667 upper_bound: Nonce,
668 },
669 GlobalContractDoesNotExist {
670 identifier: GlobalContractIdentifier,
671 },
672}
673
674impl From<ActionErrorKind> for ActionError {
675 fn from(e: ActionErrorKind) -> ActionError {
676 ActionError { index: None, kind: e }
677 }
678}
679
680impl Display for InvalidTxError {
681 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
682 match self {
683 InvalidTxError::InvalidSignerId { signer_id } => {
684 write!(f, "Invalid signer account ID {:?} according to requirements", signer_id)
685 }
686 InvalidTxError::SignerDoesNotExist { signer_id } => {
687 write!(f, "Signer {:?} does not exist", signer_id)
688 }
689 InvalidTxError::InvalidAccessKeyError(access_key_error) => {
690 Display::fmt(&access_key_error, f)
691 }
692 InvalidTxError::InvalidNonce { tx_nonce, ak_nonce } => write!(
693 f,
694 "Transaction nonce {} must be larger than nonce of the used access key {}",
695 tx_nonce, ak_nonce
696 ),
697 InvalidTxError::InvalidReceiverId { receiver_id } => {
698 write!(f, "Invalid receiver account ID {:?} according to requirements", receiver_id)
699 }
700 InvalidTxError::InvalidSignature => {
701 write!(f, "Transaction is not signed with the given public key")
702 }
703 InvalidTxError::NotEnoughBalance { signer_id, balance, cost } => write!(
704 f,
705 "Sender {:?} does not have enough balance {} for operation costing {}",
706 signer_id, balance, cost
707 ),
708 InvalidTxError::LackBalanceForState { signer_id, amount } => {
709 write!(
710 f,
711 "Failed to execute, because the account {:?} wouldn't have enough balance to cover storage, required to have {} yoctoNEAR more",
712 signer_id, amount
713 )
714 }
715 InvalidTxError::CostOverflow => {
716 write!(f, "Transaction gas or balance cost is too high")
717 }
718 InvalidTxError::InvalidChain => {
719 write!(f, "Transaction parent block hash doesn't belong to the current chain")
720 }
721 InvalidTxError::Expired => {
722 write!(f, "Transaction has expired")
723 }
724 InvalidTxError::ActionsValidation(error) => {
725 write!(f, "Transaction actions validation error: {}", error)
726 }
727 InvalidTxError::NonceTooLarge { tx_nonce, upper_bound } => {
728 write!(
729 f,
730 "Transaction nonce {} must be smaller than the access key nonce upper bound {}",
731 tx_nonce, upper_bound
732 )
733 }
734 InvalidTxError::TransactionSizeExceeded { size, limit } => {
735 write!(f, "Size of serialized transaction {} exceeded the limit {}", size, limit)
736 }
737 InvalidTxError::InvalidTransactionVersion => {
738 write!(f, "Transaction version is invalid")
739 }
740 InvalidTxError::StorageError(error) => {
741 write!(f, "Storage error: {}", error)
742 }
743 InvalidTxError::ShardCongested { shard_id, congestion_level } => {
744 write!(
745 f,
746 "Shard {shard_id} is currently at congestion level {congestion_level:.3} and rejects new transactions."
747 )
748 }
749 InvalidTxError::ShardStuck { shard_id, missed_chunks } => {
750 write!(
751 f,
752 "Shard {shard_id} missed {missed_chunks} chunks and rejects new transactions."
753 )
754 }
755 }
756 }
757}
758
759impl From<InvalidAccessKeyError> for InvalidTxError {
760 fn from(error: InvalidAccessKeyError) -> Self {
761 InvalidTxError::InvalidAccessKeyError(error)
762 }
763}
764
765impl Display for InvalidAccessKeyError {
766 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
767 match self {
768 InvalidAccessKeyError::AccessKeyNotFound { account_id, public_key } => write!(
769 f,
770 "Signer {:?} doesn't have access key with the given public_key {}",
771 account_id, public_key
772 ),
773 InvalidAccessKeyError::ReceiverMismatch { tx_receiver, ak_receiver } => write!(
774 f,
775 "Transaction receiver_id {:?} doesn't match the access key receiver_id {:?}",
776 tx_receiver, ak_receiver
777 ),
778 InvalidAccessKeyError::MethodNameMismatch { method_name } => write!(
779 f,
780 "Transaction method name {:?} isn't allowed by the access key",
781 method_name
782 ),
783 InvalidAccessKeyError::RequiresFullAccess => {
784 write!(
785 f,
786 "Invalid access key type. Full-access keys are required for transactions that have multiple or non-function-call actions"
787 )
788 }
789 InvalidAccessKeyError::NotEnoughAllowance {
790 account_id,
791 public_key,
792 allowance,
793 cost,
794 } => write!(
795 f,
796 "Access Key {:?}:{} does not have enough balance {} for transaction costing {}",
797 account_id, public_key, allowance, cost
798 ),
799 InvalidAccessKeyError::DepositWithFunctionCall => {
800 write!(
801 f,
802 "Having a deposit with a function call action is not allowed with a function call access key."
803 )
804 }
805 }
806 }
807}
808
809impl std::error::Error for InvalidAccessKeyError {}
810
811#[derive(BorshSerialize, BorshDeserialize, Debug, Clone, PartialEq, Eq, ProtocolSchema)]
812pub struct IntegerOverflowError;
813
814impl std::fmt::Display for IntegerOverflowError {
815 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
816 f.write_str(&format!("{:?}", self))
817 }
818}
819
820impl std::error::Error for IntegerOverflowError {}
821
822impl From<IntegerOverflowError> for InvalidTxError {
823 fn from(_: IntegerOverflowError) -> Self {
824 InvalidTxError::CostOverflow
825 }
826}
827
828impl From<IntegerOverflowError> for RuntimeError {
829 fn from(err: IntegerOverflowError) -> Self {
830 RuntimeError::UnexpectedIntegerOverflow(err.to_string())
831 }
832}
833
834impl From<StorageError> for RuntimeError {
835 fn from(e: StorageError) -> Self {
836 RuntimeError::StorageError(e)
837 }
838}
839
840impl From<InvalidTxError> for RuntimeError {
841 fn from(e: InvalidTxError) -> Self {
842 RuntimeError::InvalidTxError(e)
843 }
844}
845
846impl From<EpochError> for RuntimeError {
847 fn from(e: EpochError) -> Self {
848 RuntimeError::ValidatorError(e)
849 }
850}
851
852impl Display for ActionError {
853 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
854 write!(f, "Action #{}: {}", self.index.unwrap_or_default(), self.kind)
855 }
856}
857
858impl Display for ActionErrorKind {
859 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
860 match self {
861 ActionErrorKind::AccountAlreadyExists { account_id } => {
862 write!(f, "Can't create a new account {:?}, because it already exists", account_id)
863 }
864 ActionErrorKind::AccountDoesNotExist { account_id } => write!(
865 f,
866 "Can't complete the action because account {:?} doesn't exist",
867 account_id
868 ),
869 ActionErrorKind::ActorNoPermission { actor_id, account_id } => write!(
870 f,
871 "Actor {:?} doesn't have permission to account {:?} to complete the action",
872 actor_id, account_id
873 ),
874 ActionErrorKind::LackBalanceForState { account_id, amount } => write!(
875 f,
876 "The account {} wouldn't have enough balance to cover storage, required to have {} yoctoNEAR more",
877 account_id, amount
878 ),
879 ActionErrorKind::TriesToUnstake { account_id } => {
880 write!(f, "Account {:?} is not yet staked, but tries to unstake", account_id)
881 }
882 ActionErrorKind::TriesToStake { account_id, stake, locked, balance } => write!(
883 f,
884 "Account {:?} tries to stake {}, but has staked {} and only has {}",
885 account_id, stake, locked, balance
886 ),
887 ActionErrorKind::CreateAccountOnlyByRegistrar {
888 account_id,
889 registrar_account_id,
890 predecessor_id,
891 } => write!(
892 f,
893 "A top-level account ID {:?} can't be created by {:?}, short top-level account IDs can only be created by {:?}",
894 account_id, predecessor_id, registrar_account_id,
895 ),
896 ActionErrorKind::CreateAccountNotAllowed { account_id, predecessor_id } => write!(
897 f,
898 "A sub-account ID {:?} can't be created by account {:?}",
899 account_id, predecessor_id,
900 ),
901 ActionErrorKind::DeleteKeyDoesNotExist { account_id, .. } => write!(
902 f,
903 "Account {:?} tries to remove an access key that doesn't exist",
904 account_id
905 ),
906 ActionErrorKind::AddKeyAlreadyExists { public_key, .. } => write!(
907 f,
908 "The public key {:?} is already used for an existing access key",
909 public_key
910 ),
911 ActionErrorKind::DeleteAccountStaking { account_id } => {
912 write!(f, "Account {:?} is staking and can not be deleted", account_id)
913 }
914 ActionErrorKind::FunctionCallError(s) => write!(f, "{:?}", s),
915 ActionErrorKind::NewReceiptValidationError(e) => {
916 write!(f, "An new action receipt created during a FunctionCall is not valid: {}", e)
917 }
918 ActionErrorKind::InsufficientStake { account_id, stake, minimum_stake } => write!(
919 f,
920 "Account {} tries to stake {} but minimum required stake is {}",
921 account_id, stake, minimum_stake
922 ),
923 ActionErrorKind::OnlyImplicitAccountCreationAllowed { account_id } => write!(
924 f,
925 "CreateAccount action is called on hex-characters account of length 64 {}",
926 account_id
927 ),
928 ActionErrorKind::DeleteAccountWithLargeState { account_id } => write!(
929 f,
930 "The state of account {} is too large and therefore cannot be deleted",
931 account_id
932 ),
933 ActionErrorKind::DelegateActionInvalidSignature => {
934 write!(f, "DelegateAction is not signed with the given public key")
935 }
936 ActionErrorKind::DelegateActionSenderDoesNotMatchTxReceiver {
937 sender_id,
938 receiver_id,
939 } => write!(
940 f,
941 "Transaction receiver {} doesn't match DelegateAction sender {}",
942 receiver_id, sender_id
943 ),
944 ActionErrorKind::DelegateActionExpired => write!(f, "DelegateAction has expired"),
945 ActionErrorKind::DelegateActionAccessKeyError(access_key_error) => {
946 Display::fmt(&access_key_error, f)
947 }
948 ActionErrorKind::DelegateActionInvalidNonce { delegate_nonce, ak_nonce } => write!(
949 f,
950 "DelegateAction nonce {} must be larger than nonce of the used access key {}",
951 delegate_nonce, ak_nonce
952 ),
953 ActionErrorKind::DelegateActionNonceTooLarge { delegate_nonce, upper_bound } => write!(
954 f,
955 "DelegateAction nonce {} must be smaller than the access key nonce upper bound {}",
956 delegate_nonce, upper_bound
957 ),
958 ActionErrorKind::GlobalContractDoesNotExist { identifier } => {
959 write!(f, "Global contract identifier {:?} not found", identifier)
960 }
961 }
962 }
963}
964
965#[derive(Eq, PartialEq, Clone)]
966pub enum EpochError {
967 ThresholdError {
970 stake_sum: Balance,
971 num_seats: u64,
972 },
973 EpochOutOfBounds(EpochId),
975 MissingBlock(CryptoHash),
977 IOErr(String),
979 NotAValidator(AccountId, EpochId),
981 ShardingError(String),
983 NotEnoughValidators {
984 num_validators: u64,
985 num_shards: u64,
986 },
987 ChunkValidatorSelectionError(String),
989 ChunkProducerSelectionError(String),
991}
992
993impl std::error::Error for EpochError {}
994
995impl Display for EpochError {
996 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
997 match self {
998 EpochError::ThresholdError { stake_sum, num_seats } => write!(
999 f,
1000 "Total stake {} must be higher than the number of seats {}",
1001 stake_sum, num_seats
1002 ),
1003 EpochError::EpochOutOfBounds(epoch_id) => {
1004 write!(f, "Epoch {:?} is out of bounds", epoch_id)
1005 }
1006 EpochError::MissingBlock(hash) => write!(f, "Missing block {}", hash),
1007 EpochError::IOErr(err) => write!(f, "IO: {}", err),
1008 EpochError::NotAValidator(account_id, epoch_id) => {
1009 write!(f, "{} is not a validator in epoch {:?}", account_id, epoch_id)
1010 }
1011 EpochError::ShardingError(err) => write!(f, "Sharding Error: {}", err),
1012 EpochError::NotEnoughValidators { num_shards, num_validators } => {
1013 write!(
1014 f,
1015 "There were not enough validator proposals to fill all shards. num_proposals: {}, num_shards: {}",
1016 num_validators, num_shards
1017 )
1018 }
1019 EpochError::ChunkValidatorSelectionError(err) => {
1020 write!(f, "Error selecting validators for a chunk: {}", err)
1021 }
1022 EpochError::ChunkProducerSelectionError(err) => {
1023 write!(f, "Error selecting chunk producer: {}", err)
1024 }
1025 }
1026 }
1027}
1028
1029impl Debug for EpochError {
1030 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1031 match self {
1032 EpochError::ThresholdError { stake_sum, num_seats } => {
1033 write!(f, "ThresholdError({}, {})", stake_sum, num_seats)
1034 }
1035 EpochError::EpochOutOfBounds(epoch_id) => write!(f, "EpochOutOfBounds({:?})", epoch_id),
1036 EpochError::MissingBlock(hash) => write!(f, "MissingBlock({})", hash),
1037 EpochError::IOErr(err) => write!(f, "IOErr({})", err),
1038 EpochError::NotAValidator(account_id, epoch_id) => {
1039 write!(f, "NotAValidator({}, {:?})", account_id, epoch_id)
1040 }
1041 EpochError::ShardingError(err) => write!(f, "ShardingError({})", err),
1042 EpochError::NotEnoughValidators { num_shards, num_validators } => {
1043 write!(f, "NotEnoughValidators({}, {})", num_validators, num_shards)
1044 }
1045 EpochError::ChunkValidatorSelectionError(err) => {
1046 write!(f, "ChunkValidatorSelectionError({})", err)
1047 }
1048 EpochError::ChunkProducerSelectionError(err) => {
1049 write!(f, "ChunkProducerSelectionError({})", err)
1050 }
1051 }
1052 }
1053}
1054
1055impl From<std::io::Error> for EpochError {
1056 fn from(error: std::io::Error) -> Self {
1057 EpochError::IOErr(error.to_string())
1058 }
1059}
1060
1061impl From<ShardLayoutError> for EpochError {
1062 fn from(error: ShardLayoutError) -> Self {
1063 EpochError::ShardingError(error.to_string())
1064 }
1065}
1066
1067#[derive(
1068 Debug,
1069 Clone,
1070 PartialEq,
1071 Eq,
1072 BorshDeserialize,
1073 BorshSerialize,
1074 serde::Deserialize,
1075 serde::Serialize,
1076 ProtocolSchema,
1077)]
1078#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1079pub enum PrepareError {
1081 Serialization,
1083 Deserialization,
1085 InternalMemoryDeclared,
1087 GasInstrumentation,
1091 StackHeightInstrumentation,
1095 Instantiate,
1100 Memory,
1102 TooManyFunctions,
1104 TooManyLocals,
1106}
1107
1108#[derive(
1110 Debug,
1111 Clone,
1112 PartialEq,
1113 Eq,
1114 BorshDeserialize,
1115 BorshSerialize,
1116 serde::Deserialize,
1117 serde::Serialize,
1118 strum::IntoStaticStr,
1119 ProtocolSchema,
1120)]
1121#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1122pub enum WasmTrap {
1123 Unreachable,
1125 IncorrectCallIndirectSignature,
1127 MemoryOutOfBounds,
1129 CallIndirectOOB,
1131 IllegalArithmetic,
1133 MisalignedAtomicAccess,
1135 IndirectCallToNull,
1137 StackOverflow,
1139 GenericTrap,
1141}
1142
1143#[derive(
1144 Debug,
1145 Clone,
1146 PartialEq,
1147 Eq,
1148 BorshDeserialize,
1149 BorshSerialize,
1150 serde::Deserialize,
1151 serde::Serialize,
1152 strum::IntoStaticStr,
1153 ProtocolSchema,
1154)]
1155#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1156pub enum HostError {
1157 BadUTF16,
1159 BadUTF8,
1161 GasExceeded,
1163 GasLimitExceeded,
1165 BalanceExceeded,
1167 EmptyMethodName,
1169 GuestPanic { panic_msg: String },
1171 IntegerOverflow,
1173 InvalidPromiseIndex { promise_idx: u64 },
1175 CannotAppendActionToJointPromise,
1177 CannotReturnJointPromise,
1179 InvalidPromiseResultIndex { result_idx: u64 },
1181 InvalidRegisterId { register_id: u64 },
1183 IteratorWasInvalidated { iterator_index: u64 },
1185 MemoryAccessViolation,
1187 InvalidReceiptIndex { receipt_index: u64 },
1189 InvalidIteratorIndex { iterator_index: u64 },
1191 InvalidAccountId,
1193 InvalidMethodName,
1195 InvalidPublicKey,
1197 ProhibitedInView { method_name: String },
1199 NumberOfLogsExceeded { limit: u64 },
1201 KeyLengthExceeded { length: u64, limit: u64 },
1203 ValueLengthExceeded { length: u64, limit: u64 },
1205 TotalLogLengthExceeded { length: u64, limit: u64 },
1207 NumberPromisesExceeded { number_of_promises: u64, limit: u64 },
1209 NumberInputDataDependenciesExceeded { number_of_input_data_dependencies: u64, limit: u64 },
1211 ReturnedValueLengthExceeded { length: u64, limit: u64 },
1213 ContractSizeExceeded { size: u64, limit: u64 },
1215 Deprecated { method_name: String },
1217 ECRecoverError { msg: String },
1219 AltBn128InvalidInput { msg: String },
1222 Ed25519VerifyInvalidInput { msg: String },
1225}
1226
1227#[derive(
1228 Debug,
1229 Clone,
1230 PartialEq,
1231 Eq,
1232 BorshDeserialize,
1233 BorshSerialize,
1234 serde::Deserialize,
1235 serde::Serialize,
1236 strum::IntoStaticStr,
1237 ProtocolSchema,
1238)]
1239#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1240pub enum MethodResolveError {
1241 MethodEmptyName,
1242 MethodNotFound,
1243 MethodInvalidSignature,
1244}
1245
1246#[derive(
1247 Debug,
1248 Clone,
1249 PartialEq,
1250 Eq,
1251 BorshDeserialize,
1252 BorshSerialize,
1253 serde::Deserialize,
1254 serde::Serialize,
1255 strum::IntoStaticStr,
1256 ProtocolSchema,
1257)]
1258#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1259pub enum CompilationError {
1260 CodeDoesNotExist {
1261 account_id: AccountId,
1262 },
1263 PrepareError(PrepareError),
1264 WasmerCompileError {
1268 msg: String,
1269 },
1270}
1271
1272#[derive(
1277 Debug,
1278 Clone,
1279 PartialEq,
1280 Eq,
1281 BorshDeserialize,
1282 BorshSerialize,
1283 serde::Serialize,
1284 serde::Deserialize,
1285 ProtocolSchema,
1286)]
1287#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1288pub enum FunctionCallError {
1289 CompilationError(CompilationError),
1291 LinkError {
1295 msg: String,
1296 },
1297 MethodResolveError(MethodResolveError),
1299 WasmTrap(WasmTrap),
1303 WasmUnknownError,
1304 HostError(HostError),
1306 _EVMError,
1309 ExecutionError(String),
1310}
1311
1312#[derive(Debug)]
1313pub enum ChunkAccessError {
1314 ChunkMissing(ChunkHash),
1315}
1316
1317impl std::fmt::Display for ChunkAccessError {
1318 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
1319 f.write_str(&format!("{:?}", self))
1320 }
1321}
1322
1323impl std::error::Error for ChunkAccessError {}