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

feat: add new provider api and tests #637

Closed
wants to merge 27 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
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
13 changes: 11 additions & 2 deletions docs/src/wallets/checking-balances-and-coins.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,24 @@ First, one should remember that, with UTXOs, each _coin_ is unique. Each UTXO co
```rust,ignore
{{#include ../../../examples/wallets/src/lib.rs:get_asset_balance}}
```
If you want to get all spendable coins, you can use:

If you want to query all the balances (i.e., get the balance for each asset ID in that wallet), then it is as simple as:
```rust,ignore
{{#include ../../../examples/wallets/src/lib.rs:get_spendable_coins}}
```

If you want to query all the balances (i.e., get the balance for each asset ID in that wallet), you can use:

```rust,ignore
{{#include ../../../examples/wallets/src/lib.rs:get_balances}}
```

The return type is a `HashMap`, where the key is the _asset ID's_ hex string, and the value is the corresponding balance. For example, we can get the base asset balance with:
`get_balances(num_results: u64)` is a paginated request and the input is the number of results that you want to have per page. The `Pager` struct can be used to set the `cursor` and the pagination direction. To get the actual results, you have to use the `call()` method. The return type of `call()` is a `Page` struct. The `Page` struct includes the current `cursor`, `results` and information on whether we have the next and previous page (`has_next_page`, `has_previous_page`).

In this case, the `results` variable is a `HashMap`, where the key is an `AssetId`, and the value is the corresponding balance. For example, we can get the base asset balance with:

```rust,ignore
{{#include ../../../examples/wallets/src/lib.rs:get_balance_hashmap}}
```

> **Note:** That `get_coins`, `get_messages` and `get_transactions` are also paginated requests and are used in the same way as `get_balances`.
17 changes: 11 additions & 6 deletions examples/cookbook/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,6 @@ mod tests {
async fn transfer_multiple() -> Result<(), Error> {
// ANCHOR: transfer_multiple
use fuels::prelude::*;
use std::str::FromStr;

// ANCHOR: transfer_multiple_setup
let mut wallet_1 = WalletUnlocked::new_random(None);
Expand All @@ -137,13 +136,15 @@ mod tests {
// ANCHOR_END: transfer_multiple_setup

// ANCHOR: transfer_multiple_inout
let balances = wallet_1.get_balances().await?;
let balances = wallet_1
.get_balances(NUM_ASSETS * NUM_COINS)?
.call()
.await?
.results;

let mut inputs = vec![];
let mut outputs = vec![];
for (id_string, amount) in balances {
let id = AssetId::from_str(&id_string).unwrap();

for (id, amount) in balances {
// leave the base asset to cover transaction fees
if id == BASE_ASSET_ID {
continue;
Expand All @@ -162,7 +163,11 @@ mod tests {

let _receipts = provider.send_transaction(&tx).await?;

let balances = wallet_2.get_balances().await?;
let balances = wallet_2
.get_balances(NUM_ASSETS * NUM_COINS)?
.call()
.await?
.results;

assert_eq!(balances.len(), (NUM_ASSETS - 1) as usize);
for (_, balance) in balances {
Expand Down
12 changes: 6 additions & 6 deletions examples/predicates/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,16 +78,16 @@ mod tests {
.await?;

let predicate_balance = provider
.get_asset_balance(predicate.address(), asset_id)
.get_asset_balance(predicate.address(), &asset_id)
.await?;
assert_eq!(predicate_balance, amount_to_predicate);
// ANCHOR_END: predicate_send

// ANCHOR: predicate_signatures
let data_to_sign = [0; 32];
let signature1 = wallet.sign_message(&data_to_sign).await?.to_vec();
let signature2 = wallet2.sign_message(&data_to_sign).await?.to_vec();
let signature3 = wallet3.sign_message(&data_to_sign).await?.to_vec();
let signature1 = wallet.sign_message(data_to_sign).await?.to_vec();
let signature2 = wallet2.sign_message(data_to_sign).await?.to_vec();
let signature3 = wallet3.sign_message(data_to_sign).await?.to_vec();

let signatures = vec![signature1, signature2, signature3];
// ANCHOR_END: predicate_signatures
Expand All @@ -107,12 +107,12 @@ mod tests {
.await?;

let receiver_balance_after = provider
.get_asset_balance(receiver.address(), asset_id)
.get_asset_balance(receiver.address(), &asset_id)
.await?;
assert_eq!(amount_to_predicate, receiver_balance_after);

let predicate_balance = provider
.get_asset_balance(predicate.address(), asset_id)
.get_asset_balance(predicate.address(), &asset_id)
.await?;
assert_eq!(predicate_balance, 0);
// ANCHOR_END: predicate_spend
Expand Down
14 changes: 11 additions & 3 deletions examples/providers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,19 +59,27 @@ mod tests {
// ANCHOR_END: setup_test_blockchain

// ANCHOR: get_coins
let coins = provider.get_coins(wallet.address(), BASE_ASSET_ID).await?;
let coins = provider
.get_coins(wallet.address(), &BASE_ASSET_ID, number_of_coins)
.call()
.await?
.results;
assert_eq!(coins.len(), 1);
// ANCHOR_END: get_coins

// ANCHOR: get_spendable_coins
let spendable_coins = provider
.get_spendable_coins(wallet.address(), BASE_ASSET_ID, 1)
.get_spendable_coins(wallet.address(), &BASE_ASSET_ID, 1)
.await?;
assert_eq!(spendable_coins.len(), 1);
// ANCHOR_END: get_spendable_coins

// ANCHOR: get_balances
let _balances = provider.get_balances(wallet.address()).await?;
let _balances = provider
.get_balances(wallet.address(), number_of_coins)
.call()
.await?
.results;
// ANCHOR_END: get_balances

Ok(())
Expand Down
51 changes: 37 additions & 14 deletions examples/wallets/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,15 @@ mod tests {
.transfer(wallets[1].address(), 1, asset_id, TxParameters::default())
.await?;

let wallet_2_final_coins = wallets[1].get_coins(BASE_ASSET_ID).await?;
let wallet2_num_coins = 2;
let wallet_2_final_coins = wallets[1]
.get_coins(BASE_ASSET_ID, wallet2_num_coins)?
.call()
.await?
.results;

// Check that wallet 2 now has 2 coins
assert_eq!(wallet_2_final_coins.len(), 2);
assert_eq!(wallet_2_final_coins.len() as u64, wallet2_num_coins);

// ANCHOR_END: wallet_transfer
Ok(())
Expand Down Expand Up @@ -181,10 +186,13 @@ mod tests {

// ANCHOR: wallet_contract_transfer
// Check the current balance of the contract with id 'contract_id'
let num_coins = 1;
let contract_balances = wallet
.get_provider()?
.get_contract_balances(&contract_id)
.await?;
.get_contract_balances(&contract_id, num_coins)
.call()
.await?
.results;
assert!(contract_balances.is_empty());

// Transfer an amount of 300 to the contract
Expand All @@ -197,13 +205,16 @@ mod tests {
// Check that the contract now has 1 coin
let contract_balances = wallet
.get_provider()?
.get_contract_balances(&contract_id)
.await?;
assert_eq!(contract_balances.len(), 1);

let random_asset_id_key = format!("{:#x}", random_asset_id);
let random_asset_balance = contract_balances.get(&random_asset_id_key).unwrap();
assert_eq!(*random_asset_balance, 300);
.get_contract_balances(&contract_id, num_coins)
.call()
.await?
.results;
assert_eq!(contract_balances.len() as u64, num_coins);

let random_asset_balance = contract_balances
.get(&random_asset_id)
.expect("could not find any balance for the provided asset_id");
assert_eq!(*random_asset_balance, amount);
// ANCHOR_END: wallet_contract_transfer

Ok(())
Expand Down Expand Up @@ -319,13 +330,25 @@ mod tests {
let asset_id: AssetId = BASE_ASSET_ID;
let balance: u64 = wallet.get_asset_balance(&asset_id).await?;
// ANCHOR_END: get_asset_balance

// ANCHOR: get_spendable_coins
let asset_id: AssetId = BASE_ASSET_ID;
let amount = 32;
let coins = wallet.get_spendable_coins(&asset_id, amount).await?;
// ANCHOR_END: get_spendable_coins

// ANCHOR: get_balances
let balances: HashMap<String, u64> = wallet.get_balances().await?;
let pager = wallet
.get_balances(DEFAULT_NUM_COINS)?
.with_cursor(None)
.forward();
let page = pager.call().await?;
let balances: HashMap<AssetId, u64> = page.results;
// ANCHOR_END: get_balances

// ANCHOR: get_balance_hashmap
let asset_id_key = format!("{:#x}", asset_id);
let asset_balance = balances.get(&asset_id_key).unwrap();
let asset_id: AssetId = BASE_ASSET_ID;
let asset_balance = balances.get(&asset_id).unwrap();
// ANCHOR_END: get_balance_hashmap

assert_eq!(*asset_balance, DEFAULT_COIN_AMOUNT * DEFAULT_NUM_COINS);
Expand Down
2 changes: 1 addition & 1 deletion packages/fuels-contract/src/script.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ impl Script {
required_asset_amounts: &[(AssetId, u64)],
) -> Result<Vec<Coin>, Error> {
stream::iter(required_asset_amounts)
.map(|(asset_id, amount)| wallet.get_spendable_coins(*asset_id, *amount))
.map(|(asset_id, amount)| wallet.get_spendable_coins(asset_id, *amount))
.buffer_unordered(10)
.collect::<Vec<_>>()
.await
Expand Down
8 changes: 4 additions & 4 deletions packages/fuels-core/src/code_gen/abigen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ impl Abigen {
use fuels::core::abi_decoder::ABIDecoder;
use fuels::core::code_gen::function_selector::resolve_fn_selector;
use fuels::core::types::*;
use fuels::signers::WalletUnlocked;
use fuels::tx::{ContractId, Address, Receipt};
use fuels::signers::{provider::Paginator, WalletUnlocked};
use fuels::tx::{ContractId, Address, Receipt, AssetId};
use fuels::types::bech32::Bech32ContractId;
use fuels::types::ResolvedLog;
use fuels::types::errors::Error as SDKError;
Expand Down Expand Up @@ -147,8 +147,8 @@ impl Abigen {
Ok(Self { contract_id: self.contract_id.clone(), wallet: wallet, logs_lookup: self.logs_lookup.clone() })
}

pub async fn get_balances(&self) -> Result<HashMap<String, u64>, SDKError> {
self.wallet.get_provider()?.get_contract_balances(&self.contract_id).await.map_err(Into::into)
pub fn get_balances(&self, num_results: u64) -> Result<Paginator<String, HashMap<AssetId, u64>>, SDKError> {
Ok(self.wallet.get_provider()?.get_contract_balances(&self.contract_id, num_results))
}

pub fn logs_with_type<D: Tokenizable + Parameterize>(&self, receipts: &[Receipt]) -> Result<Vec<D>, SDKError> {
Expand Down
1 change: 1 addition & 0 deletions packages/fuels-signers/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ serde = { version = "1.0.124", default-features = true, features = ["derive"] }
sha2 = { version = "0.9.8", default-features = false }
thiserror = { version = "1.0.30", default-features = false }
tokio = { version = "1.10.1", features = ["full"] }
futures = "0.3.21"

[dev-dependencies]
fuels = { path = "../fuels" }
Expand Down
Loading