Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Error type #1270

Merged
merged 22 commits into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/src/calling-contracts/logs.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,4 @@ You can use the `decode_logs()` function to retrieve a `LogResult` struct contai

Due to possible performance hits, it is not recommended to use `decode_logs()` outside of a debugging scenario.

> **Note:** String slices can not be logged directly. Use the `__to_str_array()` function to convert it to a `str[N]` first.
> **Note:** String slices cannot be logged directly. Use the `__to_str_array()` function to convert it to a `str[N]` first.
3 changes: 1 addition & 2 deletions examples/contracts/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
#[cfg(test)]
mod tests {
use fuels::core::codec::EncoderConfig;
use fuels::{
core::codec::DecoderConfig,
core::codec::{DecoderConfig, EncoderConfig},
prelude::{Config, LoadConfiguration, StorageConfiguration},
types::{
errors::{transaction::Reason, Result},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use std::default::Default;

use fuel_abi_types::abi::full_program::FullProgramABI;
use proc_macro2::{Ident, TokenStream};
use quote::quote;
use std::default::Default;

use crate::{
error::Result,
Expand Down
4 changes: 2 additions & 2 deletions packages/fuels-core/src/codec/abi_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -792,7 +792,7 @@ mod tests {
let result = decoder.decode(&param_type, &[]);

// then
result.expect("Element count to be reset");
result.expect("element count to be reset");
}

fn assert_decoding_failed_w_data(
Expand All @@ -806,7 +806,7 @@ mod tests {
let err = decoder.decode(param_type, data);

let Err(Error::Codec(actual_msg)) = err else {
panic!("unexpected an Codec error! Got: {err:?}");
panic!("expected a `Codec` error! Got: `{err:?}`");
};

assert_eq!(actual_msg, msg);
Expand Down
40 changes: 4 additions & 36 deletions packages/fuels-core/src/codec/abi_decoder/bounded_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@ const B256_BYTES_SIZE: usize = 4 * WORD_SIZE;

impl BoundedDecoder {
pub(crate) fn new(config: DecoderConfig) -> Self {
let depth_tracker = CounterWithLimit::new(config.max_depth, "depth");
let token_tracker = CounterWithLimit::new(config.max_tokens, "token");
let depth_tracker =
CounterWithLimit::new(config.max_depth, "depth", CodecDirection::Decoding);
let token_tracker =
CounterWithLimit::new(config.max_tokens, "token", CodecDirection::Decoding);
Self {
depth_tracker,
token_tracker,
Expand Down Expand Up @@ -373,40 +375,6 @@ struct Decoded {
bytes_read: usize,
}

struct CounterWithLimit {
count: usize,
max: usize,
name: String,
}

impl CounterWithLimit {
fn new(max: usize, name: impl Into<String>) -> Self {
Self {
count: 0,
max,
name: name.into(),
}
}

fn increase(&mut self) -> Result<()> {
self.count += 1;
if self.count > self.max {
Err(error!(
Codec,
"{} limit `{}` reached while decoding. Try increasing it", self.name, self.max
))
} else {
Ok(())
}
}

fn decrease(&mut self) {
if self.count > 0 {
self.count -= 1;
}
}
}

fn peek_u128(bytes: &[u8]) -> Result<u128> {
let slice = peek_fixed::<U128_BYTES_SIZE>(bytes)?;
Ok(u128::from_be_bytes(*slice))
Expand Down
19 changes: 11 additions & 8 deletions packages/fuels-core/src/codec/abi_encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,19 @@ impl ABIEncoder {

#[cfg(test)]
mod tests {
use std::slice;

use itertools::chain;
use sha2::{Digest, Sha256};
use std::slice;

use super::*;
use crate::types::errors::Error;
use crate::{
codec::first_four_bytes_of_sha256_hash,
constants::WORD_SIZE,
types::{enum_variants::EnumVariants, param_types::ParamType, StaticStringToken, U256},
types::{
enum_variants::EnumVariants, errors::Error, param_types::ParamType, StaticStringToken,
U256,
},
};

const VEC_METADATA_SIZE: usize = 3 * WORD_SIZE;
Expand Down Expand Up @@ -1106,23 +1109,23 @@ mod tests {
max_depth: MAX_DEPTH,
..Default::default()
};
let msg = "Depth limit (2) reached while encoding. Try increasing it.".to_string();
let msg = "depth limit `2` reached while encoding. Try increasing it".to_string();

[nested_struct, nested_enum, nested_tuple, nested_array]
.iter()
.map(|fun| fun(MAX_DEPTH + 1))
.for_each(|token| {
assert_decoding_failed(config, token, &msg);
assert_encoding_failed(config, token, &msg);
})
}

fn assert_decoding_failed(config: EncoderConfig, token: Token, msg: &str) {
fn assert_encoding_failed(config: EncoderConfig, token: Token, msg: &str) {
let encoder = ABIEncoder::new(config);

let err = encoder.encode(&[token]);

let Err(Error::InvalidType(actual_msg)) = err else {
panic!("Unexpected an InvalidType error! Got: {err:?}");
let Err(Error::Codec(actual_msg)) = err else {
panic!("expected a Codec error! Got: `{err:?}`");
};
assert_eq!(actual_msg, msg);
}
Expand Down
17 changes: 10 additions & 7 deletions packages/fuels-core/src/codec/abi_encoder/bounded_encoder.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use crate::codec::utils::CodecDirection;
use fuel_types::bytes::padded_len_usize;

use crate::{
checked_round_up_to_word_alignment,
codec::{utils::CounterWithLimit, EncoderConfig},
codec::{
utils::{CodecDirection, CounterWithLimit},
EncoderConfig,
},
error,
types::{
errors::Result,
Expand All @@ -10,7 +14,6 @@ use crate::{
EnumSelector, StaticStringToken, Token, U256,
},
};
use fuel_types::bytes::padded_len_usize;

pub(crate) struct BoundedEncoder {
depth_tracker: CounterWithLimit,
Expand All @@ -21,9 +24,9 @@ pub(crate) struct BoundedEncoder {
impl BoundedEncoder {
pub(crate) fn new(config: EncoderConfig) -> Self {
let depth_tracker =
CounterWithLimit::new(config.max_depth, "Depth", CodecDirection::Encoding);
CounterWithLimit::new(config.max_depth, "depth", CodecDirection::Encoding);
let token_tracker =
CounterWithLimit::new(config.max_tokens, "Token", CodecDirection::Encoding);
CounterWithLimit::new(config.max_tokens, "token", CodecDirection::Encoding);
Self {
depth_tracker,
token_tracker,
Expand Down Expand Up @@ -191,8 +194,8 @@ impl BoundedEncoder {

if enum_width_in_bytes > self.max_total_enum_width {
return Err(error!(
InvalidData,
"Cannot encode Enum with variants {variants:?}: it is {enum_width_in_bytes} bytes wide. Try increasing encoder max memory."
Codec,
"cannot encode enum with variants: {variants:?}. It is `{enum_width_in_bytes}` bytes wide. Try increasing encoder max memory."
));
}
let padding_amount = variants.compute_padding_amount_in_bytes(variant_param_type)?;
Expand Down
4 changes: 2 additions & 2 deletions packages/fuels-core/src/codec/logs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ impl LogFormatter {
#[cfg(not(experimental))]
fn can_decode_log_with_type<T: Parameterize>() -> Result<()> {
match T::param_type() {
// String slices can not be decoded from logs as they are encoded as ptr, len
// String slices cannot be decoded from logs as they are encoded as ptr, len
// TODO: Once https://github.com/FuelLabs/sway/issues/5110 is resolved we can remove this
ParamType::StringSlice => Err(error!(
Codec,
"string slices can not be decoded from logs. Convert the slice to `str[N]` with `__to_str_array`"
"string slices cannot be decoded from logs. Convert the slice to `str[N]` with `__to_str_array`"
)),
_ => Ok(()),
}
Expand Down
4 changes: 2 additions & 2 deletions packages/fuels-core/src/codec/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ impl CounterWithLimit {
self.count += 1;
if self.count > self.max {
return Err(error!(
InvalidType,
"{} limit ({}) reached while {}. Try increasing it.",
Codec,
"{} limit `{}` reached while {}. Try increasing it",
self.name,
self.max,
self.direction
Expand Down
2 changes: 1 addition & 1 deletion packages/fuels-core/src/types/enum_variants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub struct EnumVariants {
impl EnumVariants {
pub fn new(param_types: Vec<ParamType>) -> Result<EnumVariants> {
if param_types.is_empty() {
return Err(error!(Other, "enum variants can not be empty!"));
return Err(error!(Other, "enum variants cannot be empty!"));
}
Ok(EnumVariants { param_types })
}
Expand Down
2 changes: 1 addition & 1 deletion packages/fuels-core/src/types/transaction_builders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ macro_rules! impl_tx_trait {
if num_witnesses + self.unresolved_signers.len() > 256 {
return Err(error_transaction!(
Builder,
"tx can not have more than 256 witnesses"
"tx cannot have more than 256 witnesses"
));
}

Expand Down
2 changes: 1 addition & 1 deletion packages/fuels-macros/src/derive/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ pub(crate) fn extract_variants(
validate_variant_type(&variant)?;

let discriminant = discriminant.try_into().map_err(|_| {
Error::new_spanned(&variant.ident, "enums can not have more than 256 variants")
Error::new_spanned(&variant.ident, "enums cannot have more than 256 variants")
})?;

Ok(ExtractedVariant::Normal {
Expand Down
4 changes: 2 additions & 2 deletions packages/fuels-macros/src/parse_utils/unique_name_values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ impl UniqueNameValues {
.map(|name| {
Error::new_spanned(
name.clone(),
format!("attribute '{name}' not recognized! Expected one of: {expected_names}"),
format!("attribute '{name}' not recognized. Expected one of: {expected_names}"),
)
})
.validate_no_errors()
Expand Down Expand Up @@ -187,7 +187,7 @@ mod tests {

assert_eq!(
err.to_string(),
"attribute 'other' not recognized! Expected one of: 'name', 'other_is_not_allowed'"
"attribute 'other' not recognized. Expected one of: 'name', 'other_is_not_allowed'"
);

Ok(())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
error: attribute 'unknown' not recognized! Expected one of: 'name', 'abi'
error: attribute 'unknown' not recognized. Expected one of: 'name', 'abi'
--> tests/ui/abigen/unrecognized_attribute.rs:6:5
|
6 | unknown = "something"
Expand Down
4 changes: 2 additions & 2 deletions packages/fuels-programs/src/call_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ pub(crate) fn build_script_data_from_contract_calls(
.encoded_args
.as_ref()
.map(|ub| ub.resolve(encoded_args_start_offset as Word))
.map_err(|e| error!(InvalidData, "Cannot encode contract call arguments: {e}"))?;
.map_err(|e| error!(Other, "cannot encode contract call arguments: {e}"))?;
script_data.extend(bytes);

// the data segment that holds the parameters for the next call
Expand Down Expand Up @@ -815,7 +815,7 @@ mod test {
expected_contract_ids.remove(&contract_id);
}
_ => {
panic!("Expected only inputs of type Input::Contract");
panic!("expected only inputs of type `Input::Contract`");
}
}
}
Expand Down
3 changes: 1 addition & 2 deletions packages/fuels-programs/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ use fuel_tx::{
AssetId, Bytes32, Contract as FuelContract, ContractId, Output, Receipt, Salt, StorageSlot,
};
use fuels_accounts::{provider::TransactionCost, Account};
use fuels_core::codec::EncoderConfig;
use fuels_core::{
codec::{ABIEncoder, DecoderConfig, LogDecoder},
codec::{ABIEncoder, DecoderConfig, EncoderConfig, LogDecoder},
constants::{BASE_ASSET_ID, DEFAULT_CALL_PARAMS_AMOUNT},
traits::{Parameterize, Tokenizable},
types::{
Expand Down
2 changes: 1 addition & 1 deletion packages/fuels-programs/src/script_calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ where
.encoded_args
.as_ref()
.map(|ub| ub.resolve(script_offset as u64))
.map_err(|e| error!(InvalidData, "Cannot encode script call arguments: {e}"))
.map_err(|e| error!(Other, "cannot encode script call arguments: {e}"))
}

async fn prepare_inputs_outputs(&self) -> Result<(Vec<Input>, Vec<Output>)> {
Expand Down
37 changes: 21 additions & 16 deletions packages/fuels/tests/configurables.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,27 +174,32 @@ async fn script_configurables() -> Result<()> {
}

#[tokio::test]
async fn test_configurable_encoder_config_is_applied() {
async fn configurable_encoder_config_is_applied() {
abigen!(Script(name="MyScript", abi="packages/fuels/tests/scripts/script_configurables/out/debug/script_configurables-abi.json"));

let new_struct = StructWithGeneric {
field_1: 16u8,
field_2: 32,
};

let _configurables = MyScriptConfigurables::default()
.with_STRUCT(new_struct.clone())
.expect("No encoder config, it works");

let encoder_config = EncoderConfig {
max_tokens: 1,
..Default::default()
};
// Fails when an encoder config is set
let configurables_error = MyScriptConfigurables::new(encoder_config)
.with_STRUCT(new_struct)
.unwrap_err();
assert!(configurables_error
.to_string()
.contains("Token limit (1) reached while encoding. Try increasing it."),)
{
let _configurables = MyScriptConfigurables::default()
.with_STRUCT(new_struct.clone())
.expect("no encoder config, it works");
}
{
let encoder_config = EncoderConfig {
max_tokens: 1,
..Default::default()
};

// Fails when a wrong encoder config is set
let configurables_error = MyScriptConfigurables::new(encoder_config)
.with_STRUCT(new_struct)
.expect_err("should error");

assert!(configurables_error
.to_string()
.contains("token limit `1` reached while encoding. Try increasing it"),)
}
}
Loading
Loading