Skip to content

Commit

Permalink
use view balance instead of get balance
Browse files Browse the repository at this point in the history
  • Loading branch information
igor-aptos committed Oct 8, 2024
1 parent 4cbf13f commit 2607526
Show file tree
Hide file tree
Showing 16 changed files with 115 additions and 98 deletions.
12 changes: 6 additions & 6 deletions crates/aptos-api-tester/src/tests/coin_transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,11 +204,11 @@ async fn check_account_balance(
address: AccountAddress,
) -> Result<(), TestFailure> {
// expected
let expected = U64(TRANSFER_AMOUNT);
let expected = TRANSFER_AMOUNT;

// actual
let actual = match client.get_account_balance(address).await {
Ok(response) => response.into_inner().coin.value,
let actual = match client.view_apt_account_balance(address).await {
Ok(response) => response.into_inner(),
Err(e) => {
error!(
"test: coin_transfer part: check_account_balance ERROR: {}, with error {:?}",
Expand Down Expand Up @@ -236,14 +236,14 @@ async fn check_account_balance_at_version(
transaction_version: u64,
) -> Result<(), TestFailure> {
// expected
let expected = U64(0);
let expected = 0;

// actual
let actual = match client
.get_account_balance_at_version(address, transaction_version - 1)
.view_apt_account_balance_at_version(address, transaction_version - 1)
.await
{
Ok(response) => response.into_inner().coin.value,
Ok(response) => response.into_inner(),
Err(e) => {
error!(
"test: coin_transfer part: check_account_balance_at_version ERROR: {}, with error {:?}",
Expand Down
6 changes: 3 additions & 3 deletions crates/aptos-api-tester/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,8 @@ pub async fn check_balance(
expected: U64,
) -> Result<(), TestFailure> {
// actual
let actual = match client.get_account_balance(address).await {
Ok(response) => response.into_inner().coin.value,
let actual = match client.view_apt_account_balance(address).await {
Ok(response) => response.into_inner(),
Err(e) => {
error!(
"test: {} part: check_account_data ERROR: {}, with error {:?}",
Expand All @@ -195,7 +195,7 @@ pub async fn check_balance(
};

// compare
if expected != actual {
if expected.0 != actual {
error!(
"test: {} part: check_account_data FAIL: {}, expected {:?}, got {:?}",
&test_name.to_string(),
Expand Down
4 changes: 2 additions & 2 deletions crates/aptos-faucet/core/src/funder/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use aptos_sdk::{
account_address::AccountAddress,
chain_id::ChainId,
transaction::{authenticator::AuthenticationKey, SignedTransaction, TransactionPayload},
AptosCoinType, LocalAccount,
LocalAccount,
},
};
use async_trait::async_trait;
Expand Down Expand Up @@ -314,7 +314,7 @@ impl FunderTrait for TransferFunder {
let account_address = self.faucet_account.read().await.address();
let funder_balance = match self
.get_api_client()
.get_account_balance_bcs::<AptosCoinType>(account_address)
.view_apt_account_balance(account_address)
.await
{
Ok(response) => response.into_inner(),
Expand Down
22 changes: 14 additions & 8 deletions crates/aptos-faucet/core/src/server/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -836,10 +836,10 @@ mod test {

// Assert that the account exists now with the expected balance.
let response = aptos_node_api_client
.get_account_balance(AccountAddress::from_str(&fund_request.address.unwrap()).unwrap())
.view_account_balance(AccountAddress::from_str(&fund_request.address.unwrap()).unwrap())
.await?;

assert_eq!(response.into_inner().get(), 10);
assert_eq!(response.into_inner(), 10);

Ok(())
}
Expand Down Expand Up @@ -894,10 +894,12 @@ mod test {

// Assert that the account exists now with the expected balance.
let response = aptos_node_api_client
.get_account_balance(AccountAddress::from_str(&fund_request.address.unwrap()).unwrap())
.view_apt_account_balance(
AccountAddress::from_str(&fund_request.address.unwrap()).unwrap(),
)
.await?;

assert_eq!(response.into_inner().get(), 10);
assert_eq!(response.into_inner(), 10);

Ok(())
}
Expand Down Expand Up @@ -942,10 +944,12 @@ mod test {

// Confirm that the account was given the full 1000 OCTA as requested.
let response = aptos_node_api_client
.get_account_balance(AccountAddress::from_str(&fund_request.address.unwrap()).unwrap())
.view_apt_account_balance(
AccountAddress::from_str(&fund_request.address.unwrap()).unwrap(),
)
.await?;

assert_eq!(response.into_inner().get(), 1000);
assert_eq!(response.into_inner(), 1000);

// This time, don't include the auth token. We request more than maximum_amount,
// but later we'll see that the faucet will only give us maximum_amount, not
Expand All @@ -960,10 +964,12 @@ mod test {

// Confirm that the account was only given 100 OCTA (maximum_amount), not 1000.
let response = aptos_node_api_client
.get_account_balance(AccountAddress::from_str(&fund_request.address.unwrap()).unwrap())
.view_apt_account_balance(
AccountAddress::from_str(&fund_request.address.unwrap()).unwrap(),
)
.await?;

assert_eq!(response.into_inner().get(), 100);
assert_eq!(response.into_inner(), 100);

Ok(())
}
Expand Down
82 changes: 44 additions & 38 deletions crates/aptos-rest-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@ pub mod state;
pub mod types;

pub use crate::client_builder::{AptosBaseUrl, ClientBuilder};
use crate::{
aptos::{AptosVersion, Balance},
error::RestError,
};
use crate::{aptos::AptosVersion, error::RestError};
use anyhow::{anyhow, Result};
pub use aptos_api_types::{
self, IndexResponseBcs, MoveModuleBytecode, PendingTransaction, Transaction,
Expand All @@ -34,21 +31,23 @@ use aptos_crypto::HashValue;
use aptos_logger::{debug, info, sample, sample::SampleRate};
use aptos_types::{
account_address::AccountAddress,
account_config::{AccountResource, CoinStoreResource, NewBlockEvent, CORE_CODE_ADDRESS},
account_config::{AccountResource, NewBlockEvent, CORE_CODE_ADDRESS},
contract_event::EventWithVersion,
state_store::state_key::StateKey,
transaction::SignedTransaction,
CoinType,
};
use move_core_types::language_storage::StructTag;
use move_core_types::{
ident_str,
language_storage::{ModuleId, StructTag, TypeTag},
};
use reqwest::{
header::{ACCEPT, CONTENT_TYPE},
Client as ReqwestClient, StatusCode,
};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::{json, Value};
pub use state::State;
use std::{collections::BTreeMap, future::Future, time::Duration};
use std::{collections::BTreeMap, future::Future, str::FromStr, time::Duration};
use tokio::time::Instant;
pub use types::{deserialize_from_prefixed_hex_string, Account, Resource};
use url::Url;
Expand Down Expand Up @@ -205,51 +204,58 @@ impl Client {
Ok(response.and_then(|inner| bcs::from_bytes(&inner))?)
}

pub async fn get_account_balance(
async fn view_account_balance_bcs_impl(
&self,
address: AccountAddress,
) -> AptosResult<Response<Balance>> {
let resp = self
.get_account_resource(address, "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>")
coin_type: &str,
version: Option<u64>,
) -> AptosResult<Response<u64>> {
let resp: Response<Vec<u64>> = self
.view_bcs(
&ViewFunction {
module: ModuleId::new(AccountAddress::ONE, ident_str!("coin").into()),
function: ident_str!("balance").into(),
ty_args: vec![TypeTag::Struct(Box::new(
StructTag::from_str(coin_type).unwrap(),
))],
args: vec![bcs::to_bytes(&address).unwrap()],
},
version,
)
.await?;
resp.and_then(|resource| {
if let Some(res) = resource {
Ok(serde_json::from_value::<Balance>(res.data)?)

resp.and_then(|result| {
if result.len() != 1 {
Err(anyhow!("Wrong data size returned: {:?}", result).into())
} else {
Err(anyhow!("No data returned").into())
Ok(result[0])
}
})
}

pub async fn get_account_balance_bcs<C: CoinType>(
pub async fn view_apt_account_balance_at_version(
&self,
address: AccountAddress,
version: u64,
) -> AptosResult<Response<u64>> {
let resp = self
.get_account_resource_bcs::<CoinStoreResource<C>>(address, &C::type_tag().to_string())
.await?;
resp.and_then(|resource| Ok(resource.coin()))
self.view_account_balance_bcs_impl(
address,
"0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>",
Some(version),
)
.await
}

pub async fn get_account_balance_at_version(
pub async fn view_apt_account_balance(
&self,
address: AccountAddress,
version: u64,
) -> AptosResult<Response<Balance>> {
let resp = self
.get_account_resource_at_version(
address,
"0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>",
version,
)
.await?;
resp.and_then(|resource| {
if let Some(res) = resource {
Ok(serde_json::from_value::<Balance>(res.data)?)
} else {
Err(anyhow!("No data returned").into())
}
})
) -> AptosResult<Response<u64>> {
self.view_account_balance_bcs_impl(
address,
"0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>",
None,
)
.await
}

pub async fn get_index(&self) -> AptosResult<Response<IndexResponse>> {
Expand Down
4 changes: 2 additions & 2 deletions crates/aptos/src/common/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1899,7 +1899,7 @@ impl TransactionOptions {
let sequence_number = account.sequence_number;

let balance = client
.get_account_balance_at_version(sender_address, version)
.view_apt_account_balance_at_version(sender_address, version)
.await
.map_err(|err| CliError::ApiError(err.to_string()))?
.into_inner();
Expand All @@ -1908,7 +1908,7 @@ impl TransactionOptions {
if gas_unit_price == 0 {
DEFAULT_MAX_GAS
} else {
std::cmp::min(balance.coin.value.0 / gas_unit_price, DEFAULT_MAX_GAS)
std::cmp::min(balance / gas_unit_price, DEFAULT_MAX_GAS)
}
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ use aptos_sdk::types::{AccountKey, EphemeralKeyPair, KeylessAccount, LocalAccoun
use aptos_transaction_generator_lib::ReliableTransactionSubmitter;
use aptos_types::keyless::{Claims, OpenIdSig, Pepper, ZeroKnowledgeSig};
use async_trait::async_trait;
use futures::StreamExt;
use rand::rngs::StdRng;
use std::{
fs::File,
io::{self, BufRead},
};
use futures::StreamExt;

const QUERY_PARALLELISM: usize = 300;

Expand Down Expand Up @@ -174,7 +174,13 @@ impl LocalAccountGenerator for KeylessAccountGenerator {
.iter()
.map(|address| txn_executor.query_sequence_number(*address))
.collect::<Vec<_>>();
let seq_nums: Vec<_> = try_join_all(result_futures).await?.into_iter().collect();

let seq_nums = futures::stream::iter(result_futures)
.buffered(QUERY_PARALLELISM)
.collect::<Vec<_>>()
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()?;

let accounts = keyless_accounts
.into_iter()
Expand Down
2 changes: 1 addition & 1 deletion crates/transaction-emitter-lib/src/emitter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ use tokio::{runtime::Handle, task::JoinHandle, time};
const MAX_TXNS: u64 = 1_000_000_000;

// TODO Transfer cost increases during Coin => FA migration, we can reduce back later.
pub const EXPECTED_GAS_PER_TRANSFER: u64 = 10;
pub const EXPECTED_GAS_PER_TRANSFER: u64 = 22;
pub const EXPECTED_GAS_PER_ACCOUNT_CREATE: u64 = 1100 + 20;

const MAX_RETRIES: usize = 12;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -469,9 +469,9 @@ pub async fn submit_transactions(
None
};
let balance = client
.get_account_balance(sender)
.view_apt_account_balance(sender)
.await
.map_or(-1, |v| v.into_inner().get() as i64);
.map_or(-1, |v| v.into_inner() as i64);

warn!(
"[{:?}] Failed to submit {} txns in a batch, first failure due to {:?}, for account {}, chain id: {:?}, first asked: {}, failed seq nums: {:?}, failed error codes: {:?}, balance of {} and last transaction for account: {:?}",
Expand Down
25 changes: 17 additions & 8 deletions crates/transaction-emitter-lib/src/emitter/transaction_executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,9 +189,9 @@ async fn warn_detailed_error(
(None, None)
};
let balance = rest_client
.get_account_balance(sender)
.view_apt_account_balance(sender)
.await
.map_or(-1, |v| v.into_inner().get() as i128);
.map_or(-1, |v| v.into_inner() as i128);

warn!(
"[{:?}] Failed {} transaction: {:?}, seq num: {}, gas: unit {} and max {}, for account {}, last seq_num {:?}, balance of {} and last transaction for account: {:?}",
Expand Down Expand Up @@ -301,13 +301,22 @@ fn is_account_not_found(error: &RestError) -> bool {
impl ReliableTransactionSubmitter for RestApiReliableTransactionSubmitter {
async fn get_account_balance(&self, account_address: AccountAddress) -> Result<u64> {
Ok(FETCH_ACCOUNT_RETRY_POLICY
.retry(move || {
self.random_rest_client()
.get_account_balance(account_address)
})
.retry_if(
move || {
self.random_rest_client()
.view_apt_account_balance(account_address)
},
|error: &RestError| match error {
RestError::Api(error) => !matches!(
error.error.error_code,
AptosErrorCode::AccountNotFound | AptosErrorCode::InvalidInput
),
RestError::Unknown(_) => false,
_ => true,
},
)
.await?
.into_inner()
.get())
.into_inner())
}

async fn query_sequence_number(&self, account_address: AccountAddress) -> Result<u64> {
Expand Down
4 changes: 2 additions & 2 deletions sdk/src/coin_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,10 @@ impl<'a> CoinClient<'a> {
pub async fn get_account_balance(&self, account: &AccountAddress) -> Result<u64> {
let response = self
.api_client
.get_account_balance(*account)
.view_apt_account_balance(*account)
.await
.context("Failed to get account balance")?;
Ok(response.inner().get())
Ok(response.into_inner())
}
}

Expand Down
4 changes: 2 additions & 2 deletions testsuite/forge-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2525,10 +2525,10 @@ pub async fn check_account_balance(
expected: u64,
) -> Result<()> {
let balance = client
.get_account_balance(account_address)
.view_apt_account_balance(account_address)
.await?
.into_inner();
assert_eq!(balance.get(), expected);
assert_eq!(balance, expected);

Ok(())
}
Expand Down
Loading

0 comments on commit 2607526

Please sign in to comment.