Skip to content

Commit

Permalink
cargo fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
IgorKoval committed Aug 14, 2024
1 parent d882f7a commit 859f305
Show file tree
Hide file tree
Showing 48 changed files with 3,879 additions and 2,424 deletions.
218 changes: 145 additions & 73 deletions src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,19 @@
* See the License for the specific EVERX DEV software governing permissions and
* limitations under the License.
*/
use std::sync::Arc;
use crate::helpers::{check_dir, create_client_verbose, json_account, print_account, query_account_field};
use crate::config::Config;
use serde_json::{json, Value};
use crate::decode::print_account_data;
use crate::helpers::{
check_dir, create_client_verbose, json_account, print_account, query_account_field,
};
use ever_block::{Account, Deserializable, Serializable};
use ever_client::error::ClientError;
use ever_client::net::{ParamsOfQueryCollection, query_collection, ResultOfSubscription, ParamsOfSubscribeCollection};
use ever_client::net::{
query_collection, ParamsOfQueryCollection, ParamsOfSubscribeCollection, ResultOfSubscription,
};
use ever_client::utils::{calc_storage_fee, ParamsOfCalcStorageFee};
use ever_block::{Account, Deserializable, Serializable};
use crate::decode::print_account_data;
use serde_json::{json, Value};
use std::sync::Arc;

const ACCOUNT_FIELDS: &str = r#"
id
Expand All @@ -33,7 +37,11 @@ const ACCOUNT_FIELDS: &str = r#"

const DEFAULT_PATH: &str = ".";

async fn query_accounts(config: &Config, addresses: Vec<String>, fields: &str) -> Result<Vec<Value>, String> {
async fn query_accounts(
config: &Config,
addresses: Vec<String>,
fields: &str,
) -> Result<Vec<Value>, String> {
let ton = create_client_verbose(config)?;

if !config.is_json {
Expand Down Expand Up @@ -64,18 +72,27 @@ async fn query_accounts(config: &Config, addresses: Vec<String>, fields: &str) -
limit: Some(cnt as u32),
..Default::default()
},
).await.map_err(|e| format!("failed to query account info: {}", e))?;
)
.await
.map_err(|e| format!("failed to query account info: {}", e))?;
res.append(query_result.result.as_mut());
}
Ok(res)
}

pub async fn get_account(config: &Config, addresses: Vec<String>, dumptvc: Option<&str>, dumpboc: Option<&str>, is_boc: bool) -> Result<(), String> {
pub async fn get_account(
config: &Config,
addresses: Vec<String>,
dumptvc: Option<&str>,
dumpboc: Option<&str>,
is_boc: bool,
) -> Result<(), String> {
if is_boc {
let mut accounts = vec![];
for path in addresses {
let account = Account::construct_from_file(&path)
.map_err(|e| format!(" failed to load account from the boc file {}: {}", path, e))?;
let account = Account::construct_from_file(&path).map_err(|e| {
format!(" failed to load account from the boc file {}: {}", path, e)
})?;
accounts.push(account);
}
if !config.is_json {
Expand All @@ -92,53 +109,59 @@ pub async fn get_account(config: &Config, addresses: Vec<String>, dumptvc: Optio
}
let mut found_addresses = vec![];
if !accounts.is_empty() {
let mut json_res = json!({ });
let mut json_res = json!({});
for acc in accounts.iter() {
let address = acc["id"].as_str().unwrap_or("Undefined").to_owned();
found_addresses.push(address.clone());
let acc_type = acc["acc_type_name"].as_str().unwrap_or("Undefined").to_owned();
let acc_type = acc["acc_type_name"]
.as_str()
.unwrap_or("Undefined")
.to_owned();
if acc_type != "NonExist" {
let bal = acc["balance"].as_str();
let balance =
if bal.is_some() {
let bal = bal.unwrap();
if config.balance_in_tons {
let bal = u64::from_str_radix(bal, 10)
.map_err(|e| format!("failed to decode balance: {}", e))?;
let int_bal = bal as f64 / 1e9;
let frac_balance = (bal as f64 / 1e6 + 0.5) as u64 % 1000;
let balance_str = format!("{}", int_bal as u64);
format!("{}.{}{}", balance_str.chars()
let balance = if bal.is_some() {
let bal = bal.unwrap();
if config.balance_in_tons {
let bal = u64::from_str_radix(bal, 10)
.map_err(|e| format!("failed to decode balance: {}", e))?;
let int_bal = bal as f64 / 1e9;
let frac_balance = (bal as f64 / 1e6 + 0.5) as u64 % 1000;
let balance_str = format!("{}", int_bal as u64);
format!(
"{}.{}{}",
balance_str
.chars()
.collect::<Vec<char>>()
.rchunks(3)
.map(|c| c.iter().collect::<String>())
.rev()
.collect::<Vec<String>>()
.join(" "),
frac_balance,
if config.is_json {
""
} else {
" ton"
}
)
} else {
format!("{}{}", bal,
if config.is_json {
""
} else {
" nanoton"
}
)
}
frac_balance,
if config.is_json { "" } else { " ton" }
)
} else {
"Undefined".to_owned()
};
let last_paid = format!("{}", acc["last_paid"].as_u64().ok_or("failed to decode last_paid".to_owned())?);
let last_trans_id = acc["last_trans_lt"].as_str().unwrap_or("Undefined").to_owned();
format!("{}{}", bal, if config.is_json { "" } else { " nanoton" })
}
} else {
"Undefined".to_owned()
};
let last_paid = format!(
"{}",
acc["last_paid"]
.as_u64()
.ok_or("failed to decode last_paid".to_owned())?
);
let last_trans_id = acc["last_trans_lt"]
.as_str()
.unwrap_or("Undefined")
.to_owned();
let data = acc["data"].as_str();
let data_boc = if data.is_some() {
hex::encode(base64::decode(data.unwrap()).map_err(|e| format!("failed to decode account data: {}", e))?)
hex::encode(
base64::decode(data.unwrap())
.map_err(|e| format!("failed to decode account data: {}", e))?,
)
} else {
"null".to_owned()
};
Expand Down Expand Up @@ -168,9 +191,28 @@ pub async fn get_account(config: &Config, addresses: Vec<String>, dumptvc: Optio
);
}
} else if config.is_json {
json_res = json_account(Some(acc_type), Some(address.clone()), None, None, None, None, None, None);
json_res = json_account(
Some(acc_type),
Some(address.clone()),
None,
None,
None,
None,
None,
None,
);
} else {
print_account(config, Some(acc_type), Some(address.clone()), None, None, None, None, None, None);
print_account(
config,
Some(acc_type),
Some(address.clone()),
None,
None,
None,
None,
None,
None,
);
}
if !config.is_json {
println!();
Expand Down Expand Up @@ -200,15 +242,24 @@ pub async fn get_account(config: &Config, addresses: Vec<String>, dumptvc: Optio

if dumptvc.is_some() || dumpboc.is_some() && addresses.len() == 1 && accounts.len() == 1 {
let acc = &accounts[0];
let boc = acc["boc"].as_str()
let boc = acc["boc"]
.as_str()
.ok_or("failed to get boc of the account".to_owned())?;
let account = Account::construct_from_base64(boc)
.map_err(|e| format!("failed to load account from the boc: {}", e))?;
if dumptvc.is_some() {
if account.state_init().is_some() {
account.state_init().unwrap()
account
.state_init()
.unwrap()
.write_to_file(dumptvc.unwrap())
.map_err(|e| format!("failed to write data to the file {}: {}", dumptvc.unwrap(), e))?;
.map_err(|e| {
format!(
"failed to write data to the file {}: {}",
dumptvc.unwrap(),
e
)
})?;
} else {
return Err("account doesn't contain state init.".to_owned());
}
Expand All @@ -217,8 +268,13 @@ pub async fn get_account(config: &Config, addresses: Vec<String>, dumptvc: Optio
}
}
if dumpboc.is_some() {
account.write_to_file(dumpboc.unwrap())
.map_err(|e| format!("failed to write data to the file {}: {}", dumpboc.unwrap(), e))?;
account.write_to_file(dumpboc.unwrap()).map_err(|e| {
format!(
"failed to write data to the file {}: {}",
dumpboc.unwrap(),
e
)
})?;
if !config.is_json {
println!("Saved account to file {}", &dumpboc.unwrap());
}
Expand All @@ -234,19 +290,17 @@ pub async fn calc_storage(config: &Config, addr: &str, period: u32) -> Result<()
println!("Processing...");
}

let boc = query_account_field(
ton.clone(),
addr,
"boc",
).await?;
let boc = query_account_field(ton.clone(), addr, "boc").await?;

let res = calc_storage_fee(
ton.clone(),
ParamsOfCalcStorageFee {
account: boc,
period,
}
).await.map_err(|e| format!("failed to calculate storage fee: {}", e))?;
},
)
.await
.map_err(|e| format!("failed to calculate storage fee: {}", e))?;

if !config.is_json {
println!("Storage fee per {} seconds: {} nanotons", period, res.fee);
Expand All @@ -259,22 +313,30 @@ pub async fn calc_storage(config: &Config, addr: &str, period: u32) -> Result<()
Ok(())
}

pub async fn dump_accounts(config: &Config, addresses: Vec<String>, path: Option<&str>) -> Result<(), String> {
pub async fn dump_accounts(
config: &Config,
addresses: Vec<String>,
path: Option<&str>,
) -> Result<(), String> {
let accounts = query_accounts(config, addresses.clone(), "id boc").await?;
let mut addresses = addresses.clone();
check_dir(path.unwrap_or(""))?;
for account in accounts.iter() {
let mut address = account["id"].as_str()
let mut address = account["id"]
.as_str()
.ok_or("Failed to parse address in the query result".to_owned())?
.to_owned();
match addresses.iter().position(|el| el == &address) {
Some(index) => { addresses.remove(index) },
None => { return Err("Query contains an unexpected address.".to_string()); }
Some(index) => addresses.remove(index),
None => {
return Err("Query contains an unexpected address.".to_string());
}
};

address.replace_range(..address.find(':').unwrap_or(0) + 1, "");
let path = format!("{}/{}.boc", path.unwrap_or(DEFAULT_PATH), address);
let boc = account["boc"].as_str()
let boc = account["boc"]
.as_str()
.ok_or("Failed to parse boc in the query result".to_owned())?;
Account::construct_from_base64(boc)
.map_err(|e| format!("Failed to load account from the boc: {}", e))?
Expand Down Expand Up @@ -302,7 +364,11 @@ fn extract_last_trans_lt(v: &serde_json::Value) -> Option<&str> {
v.as_object()?["last_trans_lt"].as_str()
}

pub async fn wait_for_change(config: &Config, account_address: &str, wait_secs: u64) -> Result<(), String> {
pub async fn wait_for_change(
config: &Config,
account_address: &str,
wait_secs: u64,
) -> Result<(), String> {
let context = create_client_verbose(config)?;

let query = ever_client::net::query_collection(
Expand All @@ -317,8 +383,10 @@ pub async fn wait_for_change(config: &Config, account_address: &str, wait_secs:
limit: None,
order: None,
result: "last_trans_lt".to_owned(),
}
).await.map_err(|e| format!("Failed to query the account: {}", e))?;
},
)
.await
.map_err(|e| format!("Failed to query the account: {}", e))?;

let last_trans_lt = extract_last_trans_lt(&query.result[0])
.ok_or_else(|| format!("Failed to parse query result: {}", query.result[0]))?;
Expand All @@ -338,9 +406,7 @@ pub async fn wait_for_change(config: &Config, account_address: &str, wait_secs:
Err(format!("Can't parse the result: {}", res.result))
}
}
Err(e) => {
Err(format!("Client error: {}", e))
}
Err(e) => Err(format!("Client error: {}", e)),
};
s.send(res).await.unwrap()
}
Expand All @@ -360,16 +426,22 @@ pub async fn wait_for_change(config: &Config, account_address: &str, wait_secs:
})),
result: "last_trans_lt".to_owned(),
},
callback
).await.map_err(|e| format!("Failed to subscribe: {}", e))?;
callback,
)
.await
.map_err(|e| format!("Failed to subscribe: {}", e))?;

tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(wait_secs)).await;
s.send(Err("Timeout".to_owned())).await.unwrap()
});

let res = r.recv().await.ok_or_else(|| "Sender has dropped".to_owned())?;
ever_client::net::unsubscribe(context.clone(), subscription).await
let res = r
.recv()
.await
.ok_or_else(|| "Sender has dropped".to_owned())?;
ever_client::net::unsubscribe(context.clone(), subscription)
.await
.map_err(|e| format!("Failed to unsubscribe: {}", e))?;

if !config.is_json {
Expand Down
Loading

0 comments on commit 859f305

Please sign in to comment.