Skip to content

Commit

Permalink
refactor: Error type (#1270)
Browse files Browse the repository at this point in the history
closes: #1236

All the suggestions from the issue were incorporated. In addition, error
messages were changed to follow the guidelines from
[rust-api-guidelines](https://rust-lang.github.io/api-guidelines/interoperability.html?highlight=lowercase#error-types-are-meaningful-and-well-behaved-c-good-err)
i.e. `The error message given by the Display representation of an error
type should be lowercase without trailing punctuation, and typically
concise.`

BREAKING CHANGE: the `fuels-rs` `Error` type is changed together with
the error messages.
  • Loading branch information
hal3e authored Feb 20, 2024
1 parent 9d8e675 commit 86e3cc7
Show file tree
Hide file tree
Showing 87 changed files with 1,003 additions and 1,052 deletions.
2 changes: 1 addition & 1 deletion docs/src/calling-contracts/call-params.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Then, in Rust, after setting up and deploying the above contract, you can config
<!-- payable:example:start -->
`call_params` returns a result to ensure you don't forward assets to a contract method that isn't payable.
<!-- payable:example:end -->
In the following example, we try to forward an amount of 100 of the base asset to `non_payable`. As its name suggests, `non_payable` isn't annotated with `#[payable]` in the contract code. Passing `CallParameters` with an amount other than 0 leads to an `InvalidCallParameters` error:
In the following example, we try to forward an amount of `100` of the base asset to `non_payable`. As its name suggests, `non_payable` isn't annotated with `#[payable]` in the contract code. Passing `CallParameters` with an amount other than `0` leads to an error:

```rust,ignore
{{#include ../../../packages/fuels/tests/contracts.rs:non_payable_params}}
Expand Down
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.
108 changes: 31 additions & 77 deletions examples/contracts/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
#[cfg(test)]
mod tests {
use fuels::core::codec::EncoderConfig;
use fuels::{
core::codec::DecoderConfig,
core::codec::{DecoderConfig, EncoderConfig},
prelude::{Config, LoadConfiguration, StorageConfiguration},
types::{errors::Result, Bits256},
types::{
errors::{transaction::Reason, Result},
Bits256,
},
};

#[tokio::test]
Expand Down Expand Up @@ -403,7 +405,7 @@ mod tests {

assert!(matches!(
response,
Err(Error::RevertTransactionError { .. })
Err(Error::Transaction(Reason::Reverted { .. }))
));
// ANCHOR_END: dependency_estimation_fail

Expand Down Expand Up @@ -438,80 +440,32 @@ mod tests {
#[tokio::test]
#[allow(unused_variables)]
async fn get_contract_outputs() -> Result<()> {
use fuels::{prelude::*, tx::Receipt};
{
abigen!(Contract(
name = "TestContract",
abi =
"packages/fuels/tests/contracts/contract_test/out/debug/contract_test-abi.json"
));
let wallet = launch_provider_and_get_wallet().await?;

let contract_id = Contract::load_from(
"../../packages/fuels/tests/contracts/contract_test/out/debug/contract_test.bin",
LoadConfiguration::default(),
)?
.deploy(&wallet, TxPolicies::default())
.await?;
use fuels::prelude::*;

let contract_methods = TestContract::new(contract_id, wallet).methods();

let response = contract_methods.increment_counter(162).call().await?;
let response = contract_methods.increment_counter(162).call().await;
match response {
// The transaction is valid and executes to completion
Ok(call_response) => {
let receipts: Vec<Receipt> = call_response.receipts;
// Do things with logs and receipts
}
// The transaction is malformed
Err(Error::ValidationError(e)) => {
println!("Transaction is malformed (ValidationError): {e}");
}
// Failed request to provider
Err(Error::ProviderError(reason)) => {
println!("Provider request failed with reason: {reason}");
}
// The transaction is valid but reverts
Err(Error::RevertTransactionError {
reason, receipts, ..
}) => {
println!("ContractCall failed with reason: {reason}");
println!("Transaction receipts are: {receipts:?}");
}
Err(_) => {}
}
}
{
// ANCHOR: deployed_contracts
abigen!(Contract(
name = "MyContract",
// Replace with your contract ABI.json path
abi =
"packages/fuels/tests/contracts/contract_test/out/debug/contract_test-abi.json"
));
let wallet_original = launch_provider_and_get_wallet().await?;

let wallet = wallet_original.clone();
// Your bech32m encoded contract ID.
let contract_id: Bech32ContractId =
"fuel1vkm285ypjesypw7vhdlhnty3kjxxx4efckdycqh3ttna4xvmxtfs6murwy"
.parse()
.expect("Invalid ID");

let connected_contract_instance = MyContract::new(contract_id, wallet);
// You can now use the `connected_contract_instance` just as you did above!
// ANCHOR_END: deployed_contracts

let wallet = wallet_original;
// ANCHOR: deployed_contracts_hex
let contract_id: ContractId =
"0x65b6a3d081966040bbccbb7f79ac91b48c635729c59a4c02f15ae7da999b32d3"
.parse()
.expect("Invalid ID");
let connected_contract_instance = MyContract::new(contract_id, wallet);
// ANCHOR_END: deployed_contracts_hex
}
// ANCHOR: deployed_contracts
abigen!(Contract(
name = "MyContract",
// Replace with your contract ABI.json path
abi = "packages/fuels/tests/contracts/contract_test/out/debug/contract_test-abi.json"
));
let wallet_original = launch_provider_and_get_wallet().await?;

let wallet = wallet_original.clone();
// Your bech32m encoded contract ID.
let contract_id: Bech32ContractId =
"fuel1vkm285ypjesypw7vhdlhnty3kjxxx4efckdycqh3ttna4xvmxtfs6murwy".parse()?;

let connected_contract_instance = MyContract::new(contract_id, wallet);
// You can now use the `connected_contract_instance` just as you did above!
// ANCHOR_END: deployed_contracts

let wallet = wallet_original;
// ANCHOR: deployed_contracts_hex
let contract_id: ContractId =
"0x65b6a3d081966040bbccbb7f79ac91b48c635729c59a4c02f15ae7da999b32d3".parse()?;

let connected_contract_instance = MyContract::new(contract_id, wallet);
// ANCHOR_END: deployed_contracts_hex

Ok(())
}
Expand Down
6 changes: 2 additions & 4 deletions examples/cookbook/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,7 @@ mod tests {

// ANCHOR: liquidity_wallet
let base_asset_id: AssetId =
"0x9ae5b658754e096e4d681c548daf46354495a437cc61492599e33fc64dcdc30c"
.parse()
.unwrap();
"0x9ae5b658754e096e4d681c548daf46354495a437cc61492599e33fc64dcdc30c".parse()?;

let asset_ids = [AssetId::default(), base_asset_id];
let asset_configs = asset_ids
Expand Down Expand Up @@ -171,7 +169,7 @@ mod tests {
let mut inputs = vec![];
let mut outputs = vec![];
for (id_string, amount) in balances {
let id = AssetId::from_str(&id_string).unwrap();
let id = AssetId::from_str(&id_string)?;

// leave the base asset to cover transaction fees
if id == BASE_ASSET_ID {
Expand Down
12 changes: 3 additions & 9 deletions examples/predicates/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,13 @@ mod tests {
async fn predicate_example() -> Result<()> {
// ANCHOR: predicate_wallets
let secret_key1: SecretKey =
"0x862512a2363db2b3a375c0d4bbbd27172180d89f23f2e259bac850ab02619301"
.parse()
.unwrap();
"0x862512a2363db2b3a375c0d4bbbd27172180d89f23f2e259bac850ab02619301".parse()?;

let secret_key2: SecretKey =
"0x37fa81c84ccd547c30c176b118d5cb892bdb113e8e80141f266519422ef9eefd"
.parse()
.unwrap();
"0x37fa81c84ccd547c30c176b118d5cb892bdb113e8e80141f266519422ef9eefd".parse()?;

let secret_key3: SecretKey =
"0x976e5c3fa620092c718d852ca703b6da9e3075b9f2ecb8ed42d9f746bf26aafb"
.parse()
.unwrap();
"0x976e5c3fa620092c718d852ca703b6da9e3075b9f2ecb8ed42d9f746bf26aafb".parse()?;

let mut wallet = WalletUnlocked::new_from_private_key(secret_key1, None);
let mut wallet2 = WalletUnlocked::new_from_private_key(secret_key2, None);
Expand Down
11 changes: 5 additions & 6 deletions examples/providers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ mod tests {
let provider = Provider::connect("beta-4.fuel.network").await.unwrap();

// Setup a private key
let secret =
SecretKey::from_str("a1447cd75accc6b71a976fd3401a1f6ce318d27ba660b0315ee6ac347bf39568")
.unwrap();
let secret = SecretKey::from_str(
"a1447cd75accc6b71a976fd3401a1f6ce318d27ba660b0315ee6ac347bf39568",
)?;

// Create the wallet
let wallet = WalletUnlocked::new_from_private_key(secret, Some(provider));
Expand All @@ -33,10 +33,9 @@ mod tests {
let port = provider.url().split(':').last().unwrap();

// ANCHOR: local_node_address
let _provider = Provider::connect(format!("127.0.0.1:{port}"))
.await
.unwrap();
let _provider = Provider::connect(format!("127.0.0.1:{port}")).await?;
// ANCHOR_END: local_node_address

Ok(())
}

Expand Down
12 changes: 5 additions & 7 deletions examples/types/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ mod tests {

// From a hex string.
let hex_str = "0x0000000000000000000000000000000000000000000000000000000000000000";
let b256 = Bytes32::from_str(hex_str).expect("failed to create Bytes32 from string");
let b256 = Bytes32::from_str(hex_str)?;
assert_eq!([0u8; 32], *b256);
// ANCHOR_END: bytes32

Expand Down Expand Up @@ -62,7 +62,7 @@ mod tests {

// From a string.
let hex_str = "0x0000000000000000000000000000000000000000000000000000000000000000";
let address = Address::from_str(hex_str).expect("failed to create Address from string");
let address = Address::from_str(hex_str)?;
assert_eq!([0u8; 32], *address);
// ANCHOR_END: address
Ok(())
Expand All @@ -83,8 +83,7 @@ mod tests {

// From a string.
let address = "fuel1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqsx2mt2";
let bech32_address =
Bech32Address::from_str(address).expect("failed to create Bech32 address from string");
let bech32_address = Bech32Address::from_str(address)?;
assert_eq!([0u8; 32], *bech32_address.hash());

// From Address
Expand Down Expand Up @@ -120,7 +119,7 @@ mod tests {

// From a string.
let hex_str = "0x0000000000000000000000000000000000000000000000000000000000000000";
let asset_id = AssetId::from_str(hex_str).expect("failed to create AssetId from string");
let asset_id = AssetId::from_str(hex_str)?;
assert_eq!([0u8; 32], *asset_id);
// ANCHOR_END: asset_id
Ok(())
Expand All @@ -146,8 +145,7 @@ mod tests {

// From a string.
let hex_str = "0x0000000000000000000000000000000000000000000000000000000000000000";
let contract_id =
ContractId::from_str(hex_str).expect("failed to create ContractId from string");
let contract_id = ContractId::from_str(hex_str)?;
assert_eq!([0u8; 32], *contract_id);
// ANCHOR_END: contract_id
Ok(())
Expand Down
9 changes: 5 additions & 4 deletions examples/wallets/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,9 +353,9 @@ mod tests {
let wallet = wallets.first().unwrap();

let amount = 1000;
let base_layer_address =
Address::from_str("0x4710162c2e3a95a6faff05139150017c9e38e5e280432d546fae345d6ce6d8fe")
.expect("Invalid address.");
let base_layer_address = Address::from_str(
"0x4710162c2e3a95a6faff05139150017c9e38e5e280432d546fae345d6ce6d8fe",
)?;
let base_layer_address = Bech32Address::from(base_layer_address);
// Transfer an amount of 1000 to the specified base layer address
let (tx_id, msg_id, _receipts) = wallet
Expand All @@ -369,12 +369,13 @@ mod tests {
.try_provider()?
.get_message_proof(&tx_id, &msg_id, None, Some(2))
.await?
.expect("Failed to retrieve message proof.");
.expect("failed to retrieve message proof");

// Verify the amount and recipient
assert_eq!(proof.amount, amount);
assert_eq!(proof.recipient, base_layer_address);
// ANCHOR_END: wallet_withdraw_to_base

Ok(())
}
}
1 change: 0 additions & 1 deletion packages/fuels-accounts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ fuel-crypto = { workspace = true, features = ["random"] }
fuel-tx = { workspace = true }
fuel-types = { workspace = true, features = ["random"] }
fuels-core = { workspace = true, default-features = false }
hex = { workspace = true, default-features = false, features = ["std"] }
rand = { workspace = true, default-features = false }
semver = { workspace = true }
tai64 = { workspace = true, features = ["serde"] }
Expand Down
Loading

0 comments on commit 86e3cc7

Please sign in to comment.