Skip to content

Commit

Permalink
refactor: Error type
Browse files Browse the repository at this point in the history
  • Loading branch information
hal3e committed Feb 8, 2024
1 parent fcc6f8c commit 487dc7d
Show file tree
Hide file tree
Showing 79 changed files with 791 additions and 919 deletions.
105 changes: 30 additions & 75 deletions examples/contracts/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ mod tests {
use fuels::{
core::codec::DecoderConfig,
prelude::{Config, LoadConfiguration, StorageConfiguration},
types::{errors::Result, Bits256},
types::{
errors::{transaction::Reason, Result},
Bits256,
},
};

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

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

Expand Down Expand Up @@ -440,80 +443,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
1 change: 0 additions & 1 deletion examples/rust_bindings/src/rust_bindings_formatted.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,4 +120,3 @@ pub mod abigen_bindings {
pub use abigen_bindings::my_contract_mod::MyContract;
pub use abigen_bindings::my_contract_mod::MyContractConfigurables;
pub use abigen_bindings::my_contract_mod::MyContractMethods;

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(())
}
}
53 changes: 9 additions & 44 deletions packages/fuels-accounts/src/account.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{collections::HashMap, fmt::Display};
use std::collections::HashMap;

use async_trait::async_trait;
use fuel_core_client::client::pagination::{PaginatedResult, PaginationRequest};
Expand All @@ -10,7 +10,7 @@ use fuels_core::{
bech32::{Bech32Address, Bech32ContractId},
coin::Coin,
coin_type::CoinType,
errors::{Error, Result},
errors::Result,
input::Input,
message::Message,
transaction::{Transaction, TxPolicies},
Expand All @@ -26,36 +26,11 @@ use crate::{
provider::{Provider, ResourceFilter},
};

#[derive(Debug)]
pub struct AccountError(String);

impl AccountError {
pub fn no_provider() -> Self {
Self("No provider was setup: make sure to set_provider in your account!".to_string())
}
}

impl Display for AccountError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}

impl std::error::Error for AccountError {}

impl From<AccountError> for Error {
fn from(e: AccountError) -> Self {
Error::AccountError(e.0)
}
}

pub type AccountResult<T> = std::result::Result<T, AccountError>;

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait ViewOnlyAccount: std::fmt::Debug + Send + Sync + Clone {
fn address(&self) -> &Bech32Address;

fn try_provider(&self) -> AccountResult<&Provider>;
fn try_provider(&self) -> Result<&Provider>;

async fn get_transactions(
&self,
Expand All @@ -82,7 +57,6 @@ pub trait ViewOnlyAccount: std::fmt::Debug + Send + Sync + Clone {
self.try_provider()?
.get_asset_balance(self.address(), *asset_id)
.await
.map_err(Into::into)
}

/// Gets all unspent messages owned by the account.
Expand All @@ -94,10 +68,7 @@ pub trait ViewOnlyAccount: std::fmt::Debug + Send + Sync + Clone {
/// the coins because we are only returning the sum of UTXOs coins amount and not the UTXOs
/// coins themselves.
async fn get_balances(&self) -> Result<HashMap<String, u64>> {
self.try_provider()?
.get_balances(self.address())
.await
.map_err(Into::into)
self.try_provider()?.get_balances(self.address()).await
}

/// Get some spendable resources (coins and messages) of asset `asset_id` owned by the account
Expand All @@ -115,10 +86,7 @@ pub trait ViewOnlyAccount: std::fmt::Debug + Send + Sync + Clone {
..Default::default()
};

self.try_provider()?
.get_spendable_resources(filter)
.await
.map_err(Into::into)
self.try_provider()?.get_spendable_resources(filter).await
}
}

Expand Down Expand Up @@ -225,7 +193,7 @@ pub trait Account: ViewOnlyAccount {
balance: u64,
asset_id: AssetId,
tx_policies: TxPolicies,
) -> std::result::Result<(String, Vec<Receipt>), Error> {
) -> Result<(String, Vec<Receipt>)> {
let provider = self.try_provider()?;

let zeroes = Bytes32::zeroed();
Expand Down Expand Up @@ -277,7 +245,7 @@ pub trait Account: ViewOnlyAccount {
to: &Bech32Address,
amount: u64,
tx_policies: TxPolicies,
) -> std::result::Result<(TxId, Nonce, Vec<Receipt>), Error> {
) -> Result<(TxId, Nonce, Vec<Receipt>)> {
let provider = self.try_provider()?;

let inputs = self
Expand Down Expand Up @@ -324,16 +292,13 @@ mod tests {
use crate::wallet::WalletUnlocked;

#[tokio::test]
async fn sign_and_verify() -> std::result::Result<(), Box<dyn std::error::Error>> {
async fn sign_and_verify() -> Result<()> {
// ANCHOR: sign_message
let mut rng = StdRng::seed_from_u64(2322u64);
let mut secret_seed = [0u8; 32];
rng.fill_bytes(&mut secret_seed);

let secret = secret_seed
.as_slice()
.try_into()
.expect("The seed size is valid");
let secret = secret_seed.as_slice().try_into()?;

// Create a wallet using the private key created above.
let wallet = WalletUnlocked::new_from_private_key(secret, None);
Expand Down
Loading

0 comments on commit 487dc7d

Please sign in to comment.