diff --git a/Cargo.lock b/Cargo.lock index 10a07f4d11..3aab60ae64 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -880,8 +880,8 @@ dependencies = [ "blake2", "criterion", "datasize", + "displaydoc", "ed25519-dalek", - "failure", "getrandom 0.2.2", "hex", "hex_fmt", @@ -897,6 +897,7 @@ dependencies = [ "serde", "serde_json", "serde_test", + "thiserror", "uint", "version-sync", ] @@ -1543,6 +1544,17 @@ dependencies = [ "winapi 0.3.9", ] +[[package]] +name = "displaydoc" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adc2ab4d5a16117f9029e9a6b5e4e79f4c67f6519bc134210d4d4a04ba31f41b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "dns-parser" version = "0.8.0" @@ -1893,27 +1905,6 @@ dependencies = [ "casper-types", ] -[[package]] -name = "failure" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d32e9bd16cc02eae7db7ef620b392808b89f6a5e16bb3497d159c6b92a0f4f86" -dependencies = [ - "failure_derive", -] - -[[package]] -name = "failure_derive" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - [[package]] name = "fake-simd" version = "0.1.2" diff --git a/types/Cargo.toml b/types/Cargo.toml index 924c84adda..ecca6de1af 100644 --- a/types/Cargo.toml +++ b/types/Cargo.toml @@ -17,8 +17,7 @@ bitflags = "1" blake2 = { version = "0.9.0", default-features = false } datasize = { version = "0.2.4", default-features = false } ed25519-dalek = { version = "1.0.0", default-features = false, features = ["rand", "u64_backend"] } -# TODO: Replace failure with thiserror once no_std support is landed https://github.com/dtolnay/thiserror/pull/64 -failure = { version = "0.1.8", default-features = false, features = ["failure_derive"] } +thiserror = { version = "1.0.20", default-features = false, optional = true } hex = { version = "0.4.2", default-features = false } hex_fmt = "0.3.0" k256 = { version = "0.4.2", default-features = false, features = ["ecdsa", "zeroize"] } @@ -33,6 +32,7 @@ serde = { version = "1", default-features = false, features = ["derive"] } serde_json = { version = "1.0.59", default-features = false } uint = { version = "0.8.3", default-features = false } once_cell = "1.5.2" +displaydoc = { version = "0.1", default-features = false, optional = true } [dev-dependencies] bincode = "1.3.1" @@ -44,7 +44,7 @@ version-sync = "0.9" serde_test = "1.0.117" [features] -default = ["base16/alloc", "serde/alloc", "serde_json/alloc"] +default = ["base16/alloc", "serde/alloc", "serde_json/alloc", "displaydoc"] std = [ "base16/std", "base64/std", @@ -54,7 +54,8 @@ std = [ "k256/std", "serde/std", "serde_json/std", - "schemars" + "schemars", + "thiserror" ] gens = ["std", "proptest/std"] diff --git a/types/src/account.rs b/types/src/account.rs index 8c9f0f5ac1..bdbeee7da0 100644 --- a/types/src/account.rs +++ b/types/src/account.rs @@ -15,7 +15,6 @@ use blake2::{ VarBlake2b, }; use datasize::DataSize; -use failure::Fail; use rand::{ distributions::{Distribution, Standard}, Rng, @@ -23,6 +22,8 @@ use rand::{ #[cfg(feature = "std")] use schemars::{gen::SchemaGenerator, schema::Schema, JsonSchema}; use serde::{de::Error as SerdeError, Deserialize, Deserializer, Serialize, Serializer}; +#[cfg(feature = "std")] +use thiserror::Error; use crate::{ bytesrepr::{Error, FromBytes, ToBytes, U8_SERIALIZED_LENGTH}, @@ -106,22 +107,33 @@ impl TryFrom for ActionType { /// Errors that can occur while changing action thresholds (i.e. the total [`Weight`]s of signing /// [`AccountHash`]s required to perform various actions) on an account. #[repr(i32)] -#[derive(Debug, Fail, PartialEq, Eq, Copy, Clone)] +#[derive(Debug, PartialEq, Eq, Copy, Clone)] +#[cfg_attr(feature = "std", derive(Error))] pub enum SetThresholdFailure { /// Setting the key-management threshold to a value lower than the deployment threshold is /// disallowed. - #[fail(display = "New threshold should be greater than or equal to deployment threshold")] + #[cfg_attr( + feature = "std", + error("New threshold should be greater than or equal to deployment threshold") + )] KeyManagementThreshold = 1, /// Setting the deployment threshold to a value greater than any other threshold is disallowed. - #[fail(display = "New threshold should be lower than or equal to key management threshold")] + #[cfg_attr( + feature = "std", + error("New threshold should be lower than or equal to key management threshold") + )] DeploymentThreshold = 2, /// Caller doesn't have sufficient permissions to set new thresholds. - #[fail(display = "Unable to set action threshold due to insufficient permissions")] + #[cfg_attr( + feature = "std", + error("Unable to set action threshold due to insufficient permissions") + )] PermissionDeniedError = 3, /// Setting a threshold to a value greater than the total weight of associated keys is /// disallowed. - #[fail( - display = "New threshold should be lower or equal than total weight of associated keys" + #[cfg_attr( + feature = "std", + error("New threshold should be lower or equal than total weight of associated keys") )] InsufficientTotalWeight = 4, } @@ -396,19 +408,29 @@ impl Distribution for Standard { } /// Errors that can occur while adding a new [`AccountHash`] to an account's associated keys map. -#[derive(PartialEq, Eq, Fail, Debug, Copy, Clone)] +#[derive(PartialEq, Eq, Debug, Copy, Clone)] +#[cfg_attr(feature = "std", derive(Error))] #[repr(i32)] pub enum AddKeyFailure { /// There are already [`MAX_ASSOCIATED_KEYS`] [`AccountHash`]s associated with the given /// account. - #[fail(display = "Unable to add new associated key because maximum amount of keys is reached")] + #[cfg_attr( + feature = "std", + error("Unable to add new associated key because maximum amount of keys is reached") + )] MaxKeysLimit = 1, /// The given [`AccountHash`] is already associated with the given account. - #[fail(display = "Unable to add new associated key because given key already exists")] + #[cfg_attr( + feature = "std", + error("Unable to add new associated key because given key already exists") + )] DuplicateKey = 2, /// Caller doesn't have sufficient permissions to associate a new [`AccountHash`] with the /// given account. - #[fail(display = "Unable to add new associated key due to insufficient permissions")] + #[cfg_attr( + feature = "std", + error("Unable to add new associated key due to insufficient permissions") + )] PermissionDenied = 3, } @@ -428,19 +450,26 @@ impl TryFrom for AddKeyFailure { } /// Errors that can occur while removing a [`AccountHash`] from an account's associated keys map. -#[derive(Fail, Debug, Eq, PartialEq, Copy, Clone)] +#[derive(Debug, Eq, PartialEq, Copy, Clone)] +#[cfg_attr(feature = "std", derive(Error))] #[repr(i32)] pub enum RemoveKeyFailure { /// The given [`AccountHash`] is not associated with the given account. - #[fail(display = "Unable to remove a key that does not exist")] + #[cfg_attr(feature = "std", error("Unable to remove a key that does not exist"))] MissingKey = 1, /// Caller doesn't have sufficient permissions to remove an associated [`AccountHash`] from the /// given account. - #[fail(display = "Unable to remove associated key due to insufficient permissions")] + #[cfg_attr( + feature = "std", + error("Unable to remove associated key due to insufficient permissions") + )] PermissionDenied = 2, /// Removing the given associated [`AccountHash`] would cause the total weight of all remaining /// `AccountHash`s to fall below one of the action thresholds for the given account. - #[fail(display = "Unable to remove a key which would violate action threshold constraints")] + #[cfg_attr( + feature = "std", + error("Unable to remove a key which would violate action threshold constraints") + )] ThresholdViolation = 3, } @@ -465,20 +494,30 @@ impl TryFrom for RemoveKeyFailure { /// Errors that can occur while updating the [`Weight`] of a [`AccountHash`] in an account's /// associated keys map. -#[derive(PartialEq, Eq, Fail, Debug, Copy, Clone)] +#[derive(PartialEq, Eq, Debug, Copy, Clone)] +#[cfg_attr(feature = "std", derive(Error))] #[repr(i32)] pub enum UpdateKeyFailure { /// The given [`AccountHash`] is not associated with the given account. - #[fail(display = "Unable to update the value under an associated key that does not exist")] + #[cfg_attr( + feature = "std", + error("Unable to update the value under an associated key that does not exist") + )] MissingKey = 1, /// Caller doesn't have sufficient permissions to update an associated [`AccountHash`] from the /// given account. - #[fail(display = "Unable to update associated key due to insufficient permissions")] + #[cfg_attr( + feature = "std", + error("Unable to update associated key due to insufficient permissions") + )] PermissionDenied = 2, /// Updating the [`Weight`] of the given associated [`AccountHash`] would cause the total /// weight of all `AccountHash`s to fall below one of the action thresholds for the given /// account. - #[fail(display = "Unable to update weight that would fall below any of action thresholds")] + #[cfg_attr( + feature = "std", + error("Unable to update weight that would fall below any of action thresholds") + )] ThresholdViolation = 3, } diff --git a/types/src/bytesrepr.rs b/types/src/bytesrepr.rs index d422440e00..4156cbbff6 100644 --- a/types/src/bytesrepr.rs +++ b/types/src/bytesrepr.rs @@ -15,10 +15,11 @@ use alloc::{ use core::any; use core::{mem, ptr::NonNull}; -use failure::Fail; use num_integer::Integer; use num_rational::Ratio; use serde::{Deserialize, Serialize}; +#[cfg(feature = "std")] +use thiserror::Error; pub use bytes::Bytes; @@ -98,20 +99,21 @@ pub fn allocate_buffer(to_be_serialized: &T) -> Result, Erro } /// Serialization and deserialization errors. -#[derive(Debug, Fail, PartialEq, Eq, Clone, Serialize, Deserialize)] +#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] +#[cfg_attr(feature = "std", derive(Error))] #[repr(u8)] pub enum Error { /// Early end of stream while deserializing. - #[fail(display = "Deserialization error: early end of stream")] + #[cfg_attr(feature = "std", error("Deserialization error: early end of stream"))] EarlyEndOfStream = 0, /// Formatting error while deserializing. - #[fail(display = "Deserialization error: formatting")] + #[cfg_attr(feature = "std", error("Deserialization error: formatting"))] Formatting, /// Not all input bytes were consumed in [`deserialize`]. - #[fail(display = "Deserialization error: left-over bytes")] + #[cfg_attr(feature = "std", error("Deserialization error: left-over bytes"))] LeftOverBytes, /// Out of memory error. - #[fail(display = "Serialization error: out of memory")] + #[cfg_attr(feature = "std", error("Serialization error: out of memory"))] OutOfMemory, } diff --git a/types/src/cl_value.rs b/types/src/cl_value.rs index db84f71a0c..5e6d895d2b 100644 --- a/types/src/cl_value.rs +++ b/types/src/cl_value.rs @@ -5,11 +5,12 @@ use alloc::{string::String, vec::Vec}; use core::fmt; use datasize::DataSize; -use failure::Fail; #[cfg(feature = "std")] use schemars::{gen::SchemaGenerator, schema::Schema, JsonSchema}; use serde::{de::Error as SerdeError, Deserialize, Deserializer, Serialize, Serializer}; use serde_json::Value; +#[cfg(feature = "std")] +use thiserror::Error; use crate::{ bytesrepr::{self, Bytes, FromBytes, ToBytes, U32_SERIALIZED_LENGTH}, @@ -39,13 +40,14 @@ impl fmt::Display for CLTypeMismatch { } /// Error relating to [`CLValue`] operations. -#[derive(Fail, PartialEq, Eq, Clone, Debug)] +#[derive(PartialEq, Eq, Clone, Debug)] +#[cfg_attr(feature = "std", derive(Error))] pub enum CLValueError { /// An error while serializing or deserializing the underlying data. - #[fail(display = "CLValue error: {}", _0)] + #[cfg_attr(feature = "std", error("CLValue error: {}", _0))] Serialization(bytesrepr::Error), /// A type mismatch while trying to convert a [`CLValue`] into a given type. - #[fail(display = "Type mismatch: {}", _0)] + #[cfg_attr(feature = "std", error("Type mismatch: {}", _0))] Type(CLTypeMismatch), } diff --git a/types/src/semver.rs b/types/src/semver.rs index 9db116a63a..7f8813bf72 100644 --- a/types/src/semver.rs +++ b/types/src/semver.rs @@ -2,9 +2,13 @@ use alloc::vec::Vec; use core::{convert::TryFrom, fmt, num::ParseIntError}; use datasize::DataSize; -use failure::Fail; use serde::{Deserialize, Serialize}; +#[cfg(not(feature = "std"))] +use displaydoc::Display; +#[cfg(feature = "std")] +use thiserror::Error; + use crate::bytesrepr::{self, Error, FromBytes, ToBytes, U32_SERIALIZED_LENGTH}; /// Length of SemVer when serialized @@ -81,11 +85,15 @@ impl fmt::Display for SemVer { } } -#[derive(Fail, Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(Error))] +#[cfg_attr(not(feature = "std"), derive(Display))] pub enum ParseSemVerError { - #[fail(display = "Invalid version format")] + /// Invalid version format + #[cfg_attr(feature = "std", error("Invalid version format"))] InvalidVersionFormat, - #[fail(display = "{}", _0)] + /// {0} + #[cfg_attr(feature = "std", error("{}", _0))] ParseIntError(ParseIntError), } diff --git a/types/src/system/auction/error.rs b/types/src/system/auction/error.rs index b7b750c4e7..887b1b30ff 100644 --- a/types/src/system/auction/error.rs +++ b/types/src/system/auction/error.rs @@ -5,7 +5,8 @@ use core::{ result, }; -use failure::Fail; +#[cfg(feature = "std")] +use thiserror::Error; use crate::{ bytesrepr::{self, FromBytes, ToBytes, U8_SERIALIZED_LENGTH}, @@ -13,141 +14,148 @@ use crate::{ }; /// Errors which can occur while executing the Auction contract. -#[derive(Fail, Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(Error))] #[repr(u8)] pub enum Error { /// Unable to find named key in the contract's named keys. - #[fail(display = "Missing key")] + #[cfg_attr(feature = "std", error("Missing key"))] MissingKey = 0, /// Given named key contains invalid variant. - #[fail(display = "Invalid key variant")] + #[cfg_attr(feature = "std", error("Invalid key variant"))] InvalidKeyVariant = 1, /// Value under an uref does not exist. This means the installer contract didn't work properly. - #[fail(display = "Missing value")] + #[cfg_attr(feature = "std", error("Missing value"))] MissingValue = 2, /// ABI serialization issue while reading or writing. - #[fail(display = "Serialization error")] + #[cfg_attr(feature = "std", error("Serialization error"))] Serialization = 3, /// Triggered when contract was unable to transfer desired amount of tokens into a bid purse. - #[fail(display = "Transfer to bid purse error")] + #[cfg_attr(feature = "std", error("Transfer to bid purse error"))] TransferToBidPurse = 4, /// User passed invalid amount of tokens which might result in wrong values after calculation. - #[fail(display = "Invalid amount")] + #[cfg_attr(feature = "std", error("Invalid amount"))] InvalidAmount = 5, /// Unable to find a bid by account hash in `active_bids` map. - #[fail(display = "Bid not found")] + #[cfg_attr(feature = "std", error("Bid not found"))] BidNotFound = 6, /// Validator's account hash was not found in the map. - #[fail(display = "Validator not found")] + #[cfg_attr(feature = "std", error("Validator not found"))] ValidatorNotFound = 7, /// Delegator's account hash was not found in the map. - #[fail(display = "Delegator not found")] + #[cfg_attr(feature = "std", error("Delegator not found"))] DelegatorNotFound = 8, /// Storage problem. - #[fail(display = "Storage error")] + #[cfg_attr(feature = "std", error("Storage error"))] Storage = 9, /// Raised when system is unable to bond. - #[fail(display = "Bonding error")] + #[cfg_attr(feature = "std", error("Bonding error"))] Bonding = 10, /// Raised when system is unable to unbond. - #[fail(display = "Unbonding error")] + #[cfg_attr(feature = "std", error("Unbonding error"))] Unbonding = 11, /// Raised when Mint contract is unable to release founder stake. - #[fail(display = "Unable to release founder stake")] + #[cfg_attr(feature = "std", error("Unable to release founder stake"))] ReleaseFounderStake = 12, /// Raised when the system is unable to determine purse balance. - #[fail(display = "Unable to get purse balance")] + #[cfg_attr(feature = "std", error("Unable to get purse balance"))] GetBalance = 13, /// Raised when an entry point is called from invalid account context. - #[fail(display = "Invalid context")] + #[cfg_attr(feature = "std", error("Invalid context"))] InvalidContext = 14, /// Raised whenever a validator's funds are still locked in but an attempt to withdraw was /// made. - #[fail(display = "Validator's funds are locked")] + #[cfg_attr(feature = "std", error("Validator's funds are locked"))] ValidatorFundsLocked = 15, /// Raised when caller is not the system account. - #[fail(display = "Function must be called by system account")] + #[cfg_attr(feature = "std", error("Function must be called by system account"))] InvalidCaller = 16, /// Raised when function is supplied a public key that does match the caller's. - #[fail(display = "Supplied public key does not match caller's public key")] + #[cfg_attr( + feature = "std", + error("Supplied public key does not match caller's public key") + )] InvalidPublicKey = 17, /// Validator is not not bonded. - #[fail(display = "Validator's bond not found")] + #[cfg_attr(feature = "std", error("Validator's bond not found"))] BondNotFound = 18, /// Unable to create purse. - #[fail(display = "Unable to create purse")] + #[cfg_attr(feature = "std", error("Unable to create purse"))] CreatePurseFailed = 19, /// Attempted to unbond an amount which was too large. - #[fail(display = "Unbond is too large")] + #[cfg_attr(feature = "std", error("Unbond is too large"))] UnbondTooLarge = 20, /// Attempted to bond with a stake which was too small. - #[fail(display = "Bond is too small")] + #[cfg_attr(feature = "std", error("Bond is too small"))] BondTooSmall = 21, /// Raised when rewards are to be distributed to delegators, but the validator has no /// delegations. - #[fail(display = "Validators has not received any delegations")] + #[cfg_attr(feature = "std", error("Validators has not received any delegations"))] MissingDelegations = 22, /// The validators returned by the consensus component should match /// current era validators when distributing rewards. - #[fail(display = "Mismatched era validator sets to distribute rewards")] + #[cfg_attr( + feature = "std", + error("Mismatched era validator sets to distribute rewards") + )] MismatchedEraValidators = 23, /// Failed to mint reward tokens. - #[fail(display = "Failed to mint rewards")] + #[cfg_attr(feature = "std", error("Failed to mint rewards"))] MintReward = 24, /// Invalid number of validator slots. - #[fail(display = "Invalid number of validator slots")] + #[cfg_attr(feature = "std", error("Invalid number of validator slots"))] InvalidValidatorSlotsValue = 25, /// Failed to reduce total supply. - #[fail(display = "Failed to reduce total supply")] + #[cfg_attr(feature = "std", error("Failed to reduce total supply"))] MintReduceTotalSupply = 26, /// Triggered when contract was unable to transfer desired amount of tokens into a delegators /// purse. - #[fail(display = "Transfer to delegators purse error")] + #[cfg_attr(feature = "std", error("Transfer to delegators purse error"))] TransferToDelegatorPurse = 27, /// Triggered when contract was unable to perform a transfer to distribute validators reward. - #[fail(display = "Reward transfer to validator error")] + #[cfg_attr(feature = "std", error("Reward transfer to validator error"))] ValidatorRewardTransfer = 28, /// Triggered when contract was unable to perform a transfer to distribute delegators rewards. - #[fail(display = "Rewards transfer to delegator error")] + #[cfg_attr(feature = "std", error("Rewards transfer to delegator error"))] DelegatorRewardTransfer = 29, /// Failed to transfer desired amount while withdrawing delegators reward. - #[fail(display = "Withdraw delegator reward error")] + #[cfg_attr(feature = "std", error("Withdraw delegator reward error"))] WithdrawDelegatorReward = 30, /// Failed to transfer desired amount while withdrawing validators reward. - #[fail(display = "Withdraw validator reward error")] + #[cfg_attr(feature = "std", error("Withdraw validator reward error"))] WithdrawValidatorReward = 31, /// Failed to transfer desired amount into unbonding purse. - #[fail(display = "Transfer to unbonding purse error")] + #[cfg_attr(feature = "std", error("Transfer to unbonding purse error"))] TransferToUnbondingPurse = 32, /// Failed to record era info. - #[fail(display = "Record era info error")] + #[cfg_attr(feature = "std", error("Record era info error"))] RecordEraInfo = 33, /// Failed to create a [`crate::CLValue`]. - #[fail(display = "CLValue error")] + #[cfg_attr(feature = "std", error("CLValue error"))] CLValue = 34, /// Missing seigniorage recipients for given era. - #[fail(display = "Missing seigniorage recipients for given era")] + #[cfg_attr(feature = "std", error("Missing seigniorage recipients for given era"))] MissingSeigniorageRecipients = 35, /// Failed to transfer funds. - #[fail(display = "Transfer error")] + #[cfg_attr(feature = "std", error("Transfer error"))] Transfer = 36, /// Delegation rate exceeds rate. - #[fail(display = "Delegation rate too large")] + #[cfg_attr(feature = "std", error("Delegation rate too large"))] DelegationRateTooLarge = 37, /// Raised whenever a delegator's funds are still locked in but an attempt to undelegate was /// made. - #[fail(display = "Delegator's funds are locked")] + #[cfg_attr(feature = "std", error("Delegator's funds are locked"))] DelegatorFundsLocked = 38, // NOTE: These variants below and related plumbing will be removed once support for WASM // system contracts will be dropped. #[doc(hidden)] - #[fail(display = "GasLimit")] + #[cfg_attr(feature = "std", error("GasLimit"))] GasLimit, #[cfg(test)] #[doc(hidden)] - #[fail(display = "Sentinel error")] + #[cfg_attr(feature = "std", error("Sentinel error"))] Sentinel, } diff --git a/types/src/system/handle_payment/error.rs b/types/src/system/handle_payment/error.rs index 2e24ff113d..e09e39443a 100644 --- a/types/src/system/handle_payment/error.rs +++ b/types/src/system/handle_payment/error.rs @@ -1,9 +1,10 @@ //! Home of the Handle Payment contract's [`Error`] type. -use failure::Fail; - use alloc::vec::Vec; use core::result; +#[cfg(feature = "std")] +use thiserror::Error; + use crate::{ bytesrepr::{self, ToBytes, U8_SERIALIZED_LENGTH}, CLType, CLTyped, @@ -11,118 +12,119 @@ use crate::{ /// Errors which can occur while executing the Handle Payment contract. // TODO: Split this up into user errors vs. system errors. -#[derive(Fail, Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(Error))] #[repr(u8)] pub enum Error { // ===== User errors ===== /// The given validator is not bonded. - #[fail(display = "Not bonded")] + #[cfg_attr(feature = "std", error("Not bonded"))] NotBonded = 0, /// There are too many bonding or unbonding attempts already enqueued to allow more. - #[fail(display = "Too many events in queue")] + #[cfg_attr(feature = "std", error("Too many events in queue"))] TooManyEventsInQueue, /// At least one validator must remain bonded. - #[fail(display = "Cannot unbond last validator")] + #[cfg_attr(feature = "std", error("Cannot unbond last validator"))] CannotUnbondLastValidator, /// Failed to bond or unbond as this would have resulted in exceeding the maximum allowed /// difference between the largest and smallest stakes. - #[fail(display = "Spread is too high")] + #[cfg_attr(feature = "std", error("Spread is too high"))] SpreadTooHigh, /// The given validator already has a bond or unbond attempt enqueued. - #[fail(display = "Multiple requests")] + #[cfg_attr(feature = "std", error("Multiple requests"))] MultipleRequests, /// Attempted to bond with a stake which was too small. - #[fail(display = "Bond is too small")] + #[cfg_attr(feature = "std", error("Bond is too small"))] BondTooSmall, /// Attempted to bond with a stake which was too large. - #[fail(display = "Bond is too large")] + #[cfg_attr(feature = "std", error("Bond is too large"))] BondTooLarge, /// Attempted to unbond an amount which was too large. - #[fail(display = "Unbond is too large")] + #[cfg_attr(feature = "std", error("Unbond is too large"))] UnbondTooLarge, /// While bonding, the transfer from source purse to the Handle Payment internal purse failed. - #[fail(display = "Bond transfer failed")] + #[cfg_attr(feature = "std", error("Bond transfer failed"))] BondTransferFailed, /// While unbonding, the transfer from the Handle Payment internal purse to the destination /// purse failed. - #[fail(display = "Unbond transfer failed")] + #[cfg_attr(feature = "std", error("Unbond transfer failed"))] UnbondTransferFailed, // ===== System errors ===== /// Internal error: a [`BlockTime`](crate::BlockTime) was unexpectedly out of sequence. - #[fail(display = "Time went backwards")] + #[cfg_attr(feature = "std", error("Time went backwards"))] TimeWentBackwards, /// Internal error: stakes were unexpectedly empty. - #[fail(display = "Stakes not found")] + #[cfg_attr(feature = "std", error("Stakes not found"))] StakesNotFound, /// Internal error: the Handle Payment contract's payment purse wasn't found. - #[fail(display = "Payment purse not found")] + #[cfg_attr(feature = "std", error("Payment purse not found"))] PaymentPurseNotFound, /// Internal error: the Handle Payment contract's payment purse key was the wrong type. - #[fail(display = "Payment purse has unexpected type")] + #[cfg_attr(feature = "std", error("Payment purse has unexpected type"))] PaymentPurseKeyUnexpectedType, /// Internal error: couldn't retrieve the balance for the Handle Payment contract's payment /// purse. - #[fail(display = "Payment purse balance not found")] + #[cfg_attr(feature = "std", error("Payment purse balance not found"))] PaymentPurseBalanceNotFound, /// Internal error: the Handle Payment contract's bonding purse wasn't found. - #[fail(display = "Bonding purse not found")] + #[cfg_attr(feature = "std", error("Bonding purse not found"))] BondingPurseNotFound, /// Internal error: the Handle Payment contract's bonding purse key was the wrong type. - #[fail(display = "Bonding purse key has unexpected type")] + #[cfg_attr(feature = "std", error("Bonding purse key has unexpected type"))] BondingPurseKeyUnexpectedType, /// Internal error: the Handle Payment contract's refund purse key was the wrong type. - #[fail(display = "Refund purse key has unexpected type")] + #[cfg_attr(feature = "std", error("Refund purse key has unexpected type"))] RefundPurseKeyUnexpectedType, /// Internal error: the Handle Payment contract's rewards purse wasn't found. - #[fail(display = "Rewards purse not found")] + #[cfg_attr(feature = "std", error("Rewards purse not found"))] RewardsPurseNotFound, /// Internal error: the Handle Payment contract's rewards purse key was the wrong type. - #[fail(display = "Rewards purse has unexpected type")] + #[cfg_attr(feature = "std", error("Rewards purse has unexpected type"))] RewardsPurseKeyUnexpectedType, // TODO: Put these in their own enum, and wrap them separately in `BondingError` and // `UnbondingError`. /// Internal error: failed to deserialize the stake's key. - #[fail(display = "Failed to deserialize stake's key")] + #[cfg_attr(feature = "std", error("Failed to deserialize stake's key"))] StakesKeyDeserializationFailed, /// Internal error: failed to deserialize the stake's balance. - #[fail(display = "Failed to deserialize stake's balance")] + #[cfg_attr(feature = "std", error("Failed to deserialize stake's balance"))] StakesDeserializationFailed, /// The invoked Handle Payment function can only be called by system contracts, but was called /// by a user contract. - #[fail(display = "System function was called by user account")] + #[cfg_attr(feature = "std", error("System function was called by user account"))] SystemFunctionCalledByUserAccount, /// Internal error: while finalizing payment, the amount spent exceeded the amount available. - #[fail(display = "Insufficient payment for amount spent")] + #[cfg_attr(feature = "std", error("Insufficient payment for amount spent"))] InsufficientPaymentForAmountSpent, /// Internal error: while finalizing payment, failed to pay the validators (the transfer from /// the Handle Payment contract's payment purse to rewards purse failed). - #[fail(display = "Transfer to rewards purse has failed")] + #[cfg_attr(feature = "std", error("Transfer to rewards purse has failed"))] FailedTransferToRewardsPurse, /// Internal error: while finalizing payment, failed to refund the caller's purse (the transfer /// from the Handle Payment contract's payment purse to refund purse or account's main purse /// failed). - #[fail(display = "Transfer to account's purse failed")] + #[cfg_attr(feature = "std", error("Transfer to account's purse failed"))] FailedTransferToAccountPurse, /// Handle Payment contract's "set_refund_purse" method can only be called by the payment code /// of a deploy, but was called by the session code. - #[fail(display = "Set refund purse was called outside payment")] + #[cfg_attr(feature = "std", error("Set refund purse was called outside payment"))] SetRefundPurseCalledOutsidePayment, /// Raised when the system is unable to determine purse balance. - #[fail(display = "Unable to get purse balance")] + #[cfg_attr(feature = "std", error("Unable to get purse balance"))] GetBalance, /// Raised when the system is unable to put named key. - #[fail(display = "Unable to put named key")] + #[cfg_attr(feature = "std", error("Unable to put named key"))] PutKey, /// Raised when the system is unable to remove given named key. - #[fail(display = "Unable to remove named key")] + #[cfg_attr(feature = "std", error("Unable to remove named key"))] RemoveKey, /// Failed to transfer funds. - #[fail(display = "Failed to transfer funds")] + #[cfg_attr(feature = "std", error("Failed to transfer funds"))] Transfer, // NOTE: These variants below will be removed once support for WASM system contracts will be // dropped. #[doc(hidden)] - #[fail(display = "GasLimit")] + #[cfg_attr(feature = "std", error("GasLimit"))] GasLimit, } diff --git a/types/src/system/mint/error.rs b/types/src/system/mint/error.rs index 8a84f508ce..a9ac0a1e86 100644 --- a/types/src/system/mint/error.rs +++ b/types/src/system/mint/error.rs @@ -3,7 +3,8 @@ use alloc::{fmt, vec::Vec}; use core::convert::{TryFrom, TryInto}; -use failure::Fail; +#[cfg(feature = "std")] +use thiserror::Error; use crate::{ bytesrepr::{self, FromBytes, ToBytes, U8_SERIALIZED_LENGTH}, @@ -11,73 +12,74 @@ use crate::{ }; /// Errors which can occur while executing the Mint contract. -#[derive(Fail, Debug, Copy, Clone, PartialEq, Eq)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +#[cfg_attr(feature = "std", derive(Error))] #[repr(u8)] pub enum Error { /// Insufficient funds to complete the transfer. - #[fail(display = "Insufficient funds")] + #[cfg_attr(feature = "std", error("Insufficient funds"))] InsufficientFunds = 0, /// Source purse not found. - #[fail(display = "Source not found")] + #[cfg_attr(feature = "std", error("Source not found"))] SourceNotFound = 1, /// Destination purse not found. - #[fail(display = "Destination not found")] + #[cfg_attr(feature = "std", error("Destination not found"))] DestNotFound = 2, /// See [`PurseError::InvalidURef`]. - #[fail(display = "Invalid URef")] + #[cfg_attr(feature = "std", error("Invalid URef"))] InvalidURef = 3, /// See [`PurseError::InvalidAccessRights`]. - #[fail(display = "Invalid AccessRights")] + #[cfg_attr(feature = "std", error("Invalid AccessRights"))] InvalidAccessRights = 4, /// Tried to create a new purse with a non-zero initial balance. - #[fail(display = "Invalid non-empty purse creation")] + #[cfg_attr(feature = "std", error("Invalid non-empty purse creation"))] InvalidNonEmptyPurseCreation = 5, /// Failed to read from local or global storage. - #[fail(display = "Storage error")] + #[cfg_attr(feature = "std", error("Storage error"))] Storage = 6, /// Purse not found while trying to get balance. - #[fail(display = "Purse not found")] + #[cfg_attr(feature = "std", error("Purse not found"))] PurseNotFound = 7, /// Unable to obtain a key by its name. - #[fail(display = "Missing key")] + #[cfg_attr(feature = "std", error("Missing key"))] MissingKey = 8, /// Total supply not found. - #[fail(display = "Total supply not found")] + #[cfg_attr(feature = "std", error("Total supply not found"))] TotalSupplyNotFound = 9, /// Failed to record transfer. - #[fail(display = "Failed to record transfer")] + #[cfg_attr(feature = "std", error("Failed to record transfer"))] RecordTransferFailure = 10, /// Invalid attempt to reduce total supply. - #[fail(display = "Invalid attempt to reduce total supply")] + #[cfg_attr(feature = "std", error("Invalid attempt to reduce total supply"))] InvalidTotalSupplyReductionAttempt = 11, /// Failed to create new uref. - #[fail(display = "Failed to create new uref")] + #[cfg_attr(feature = "std", error("Failed to create new uref"))] NewURef = 12, /// Failed to put key. - #[fail(display = "Failed to put key")] + #[cfg_attr(feature = "std", error("Failed to put key"))] PutKey = 13, /// Failed to write local key. - #[fail(display = "Failed to write local key")] + #[cfg_attr(feature = "std", error("Failed to write local key"))] WriteLocal = 14, /// Failed to create a [`crate::CLValue`]. - #[fail(display = "Failed to create a CLValue")] + #[cfg_attr(feature = "std", error("Failed to create a CLValue"))] CLValue = 15, /// Failed to serialize data. - #[fail(display = "Failed to serialize data")] + #[cfg_attr(feature = "std", error("Failed to serialize data"))] Serialize = 16, /// Source and target purse [`crate::URef`]s are equal. - #[fail(display = "Invalid target purse")] + #[cfg_attr(feature = "std", error("Invalid target purse"))] EqualSourceAndTarget = 17, // NOTE: These variants below will be removed once support for WASM system contracts will be // dropped. #[doc(hidden)] - #[fail(display = "GasLimit")] + #[cfg_attr(feature = "std", error("GasLimit"))] GasLimit = 18, #[cfg(test)] #[doc(hidden)] - #[fail(display = "Sentinel error")] + #[cfg_attr(feature = "std", error("Sentinel error"))] Sentinel, } diff --git a/types/src/system/mod.rs b/types/src/system/mod.rs index e92bc7afa4..e4b8d8f4d2 100644 --- a/types/src/system/mod.rs +++ b/types/src/system/mod.rs @@ -1,5 +1,4 @@ //! System modules, formerly known as "system contracts" - pub mod auction; pub mod handle_payment; pub mod mint; @@ -11,21 +10,23 @@ pub use system_contract_type::{ }; mod error { - use failure::Fail; + #[cfg(feature = "std")] + use thiserror::Error; use crate::system::{auction, handle_payment, mint}; /// An aggregate enum error with variants for each system contract's error. - #[derive(Fail, Debug, Copy, Clone)] + #[derive(Debug, Copy, Clone)] + #[cfg_attr(feature = "std", derive(Error))] pub enum Error { /// Contains a [`mint::Error`]. - #[fail(display = "Mint error: {}", _0)] + #[cfg_attr(feature = "std", error("Mint error: {}", _0))] Mint(mint::Error), /// Contains a [`handle_payment::Error`]. - #[fail(display = "HandlePayment error: {}", _0)] + #[cfg_attr(feature = "std", error("HandlePayment error: {}", _0))] HandlePayment(handle_payment::Error), /// Contains a [`auction::Error`]. - #[fail(display = "Auction error: {}", _0)] + #[cfg_attr(feature = "std", error("Auction error: {}", _0))] Auction(auction::Error), }