Skip to content

Commit

Permalink
clippy
Browse files Browse the repository at this point in the history
  • Loading branch information
fluiderson committed Mar 5, 2024
1 parent 6d7deca commit 9a94b3c
Show file tree
Hide file tree
Showing 8 changed files with 109 additions and 112 deletions.
26 changes: 13 additions & 13 deletions kalatori-ah/src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ struct DaemonInfo {
}

pub struct Database {
database: redb::Database,
db: redb::Database,
properties: Arc<RwLock<ChainProperties>>,
pair: Pair,
rpc: String,
Expand Down Expand Up @@ -169,8 +169,8 @@ impl Database {
}
(Some(encoded_db_version), Some(daemon_info), last_block_option) => {
let Compact::<Version>(db_version) =
decode_slot(encoded_db_version, DB_VERSION_KEY)?;
let DaemonInfo { rpc: db_rpc, key } = decode_slot(daemon_info, DAEMON_INFO)?;
decode_slot(&encoded_db_version, DB_VERSION_KEY)?;
let DaemonInfo { rpc: db_rpc, key } = decode_slot(&daemon_info, DAEMON_INFO)?;

if db_version != DATABASE_VERSION {
anyhow::bail!(
Expand Down Expand Up @@ -203,7 +203,7 @@ impl Database {
}

if let Some(encoded_last_block) = last_block_option {
Some(decode_slot::<Compact<BlockNumber>>(encoded_last_block, LAST_BLOCK)?.0)
Some(decode_slot::<Compact<BlockNumber>>(&encoded_last_block, LAST_BLOCK)?.0)
} else {
None
}
Expand All @@ -222,16 +222,16 @@ impl Database {
.context("failed to compact the database")?;

if compacted {
log::debug!("The database was successfully compacted.")
log::debug!("The database was successfully compacted.");
} else {
log::debug!("The database doesn't need the compaction.")
log::debug!("The database doesn't need the compaction.");
}

log::info!("Public key from the given seed: \"{public_formatted}\".");

Ok((
Arc::new(Self {
database,
db: database,
properties: chain,
pair,
rpc: given_rpc,
Expand All @@ -250,14 +250,14 @@ impl Database {
}

pub fn write(&self) -> Result<WriteTransaction<'_>> {
self.database
self.db
.begin_write()
.map(WriteTransaction)
.context("failed to begin a write transaction for the database")
}

pub fn read(&self) -> Result<ReadTransaction<'_>> {
self.database
self.db
.begin_read()
.map(ReadTransaction)
.context("failed to begin a read transaction for the database")
Expand Down Expand Up @@ -296,7 +296,7 @@ impl ReadInvoices<'_> {
.context("failed to get an invoice from the database")
}

pub fn iter(
pub fn try_iter(
&self,
) -> Result<impl Iterator<Item = Result<(AccessGuard<'_, &[u8; 32]>, AccessGuard<'_, Invoice>)>>>
{
Expand Down Expand Up @@ -360,12 +360,12 @@ impl Root<'_, '_> {
fn get_slot(table: &Table<'_, '_, &str, Vec<u8>>, key: &str) -> Result<Option<Vec<u8>>> {
table
.get(key)
.map(|slot_option| slot_option.map(|slot| slot.value().to_vec()))
.map(|slot_option| slot_option.map(|slot| slot.value().clone()))
.with_context(|| format!("failed to get the {key:?} slot"))
}

fn decode_slot<T: Decode>(slot: Vec<u8>, key: &str) -> Result<T> {
T::decode(&mut slot.as_ref()).with_context(|| format!("failed to decode the {key:?} slot"))
fn decode_slot<T: Decode>(mut slot: &[u8], key: &str) -> Result<T> {
T::decode(&mut slot).with_context(|| format!("failed to decode the {key:?} slot"))
}

fn insert_daemon_info(
Expand Down
13 changes: 5 additions & 8 deletions kalatori-ah/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use anyhow::{Context, Error, Result};
use database::Database;
use env_logger::{Builder, Env};
use environment_variables::*;
use environment_variables::{
DATABASE, DECIMALS, DESTINATION, HOST, IN_MEMORY_DB, LOG, LOG_STYLE, OVERRIDE_RPC, RPC, SEED,
};
use log::LevelFilter;
use rpc::Processor;
use serde::Deserialize;
Expand All @@ -10,13 +12,7 @@ use std::{
future::Future,
};
use subxt::{
config::{
signed_extensions::{
AnyOf, ChargeAssetTxPayment, ChargeTransactionPayment, CheckGenesis, CheckMortality,
CheckNonce, CheckSpecVersion, CheckTxVersion,
},
DefaultExtrinsicParams, Header,
},
config::{DefaultExtrinsicParams, Header},
ext::{
codec::{Decode, Encode},
scale_decode::DecodeAsType,
Expand Down Expand Up @@ -129,6 +125,7 @@ enum Junction {
}

#[doc(hidden)]
#[allow(clippy::too_many_lines)]
#[tokio::main]
pub async fn main() -> Result<()> {
let mut builder = Builder::new();
Expand Down
66 changes: 27 additions & 39 deletions kalatori-ah/src/rpc.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::{
database::{Database, Invoice, InvoiceStatus, ReadInvoices},
shutdown, Account, Balance, BlockNumber, Decimals, Hash, Junction, Junctions, MultiLocation,
Nonce, OnlineClient, RuntimeConfig, EXPECTED_USDT_FEE, SCANNER_TO_LISTENER_SWITCH_POINT,
USDT_ID,
shutdown, Account, Balance, BlockNumber, Decimals, Hash, Nonce, OnlineClient, RuntimeConfig,
EXPECTED_USDT_FEE, SCANNER_TO_LISTENER_SWITCH_POINT, USDT_ID,
};
use anyhow::{Context, Result};
use reconnecting_jsonrpsee_ws_client::ClientBuilder;
Expand All @@ -20,12 +19,7 @@ use subxt::{
Backend, BackendExt, RuntimeVersion,
},
blocks::{Block, BlocksClient},
config::{
signed_extensions::{
ChargeAssetTxPaymentParams, ChargeTransactionPaymentParams, CheckMortalityParams,
},
DefaultExtrinsicParamsBuilder, Header,
},
config::{DefaultExtrinsicParamsBuilder, Header},
constants::ConstantsClient,
dynamic::{self, Value},
error::RpcError,
Expand Down Expand Up @@ -53,7 +47,6 @@ const BLOCK_NONCE_ERROR: &str = "failed to fetch an account nonce by the scanner
// Pallets

const SYSTEM: &str = "System";
const BALANCES: &str = "Balances";
const UTILITY: &str = "Utility";
const ASSETS: &str = "Assets";

Expand Down Expand Up @@ -143,7 +136,7 @@ pub struct ChainProperties {
}

impl ChainProperties {
async fn fetch_only_constants(
fn fetch_only_constants(
existential_deposit: Balance,
decimals: Decimals,
constants: &ConstantsClient<RuntimeConfig, OnlineClient>,
Expand Down Expand Up @@ -221,8 +214,7 @@ pub async fn prepare(
.await?,
)
.await?;
let properties =
ChainProperties::fetch_only_constants(min_balance, decimals, &constants).await?;
let properties = ChainProperties::fetch_only_constants(min_balance, decimals, &constants)?;

log::info!(
"Chain properties:\n\
Expand Down Expand Up @@ -334,8 +326,7 @@ impl Updater {
current_properties.existential_deposit,
current_properties.decimals,
&self.constants,
)
.await?;
)?;

let mut changed = String::new();
let mut add_change = |message: Arguments<'_>| {
Expand Down Expand Up @@ -458,7 +449,7 @@ impl ProcessorFinalized {
// TODO:
// Design a new DB format to store unpaid accounts in a separate table.

for invoice_result in self.database.read()?.invoices()?.iter()? {
for invoice_result in self.database.read()?.invoices()?.try_iter()? {
let invoice = invoice_result?;

match invoice.1.value().status {
Expand Down Expand Up @@ -590,12 +581,11 @@ impl ProcessorFinalized {
let mut invoices_changes = HashMap::new();

for event_result in events.iter() {
let event = event_result.context("failed to decode an event")?;
let metadata = event.event_metadata();

const UPDATE: &str = "CodeUpdated";
const TRANSFERRED: &str = "Transferred";
const ASSET_MIN_BALANCE_CHANGED: &str = "AssetMinBalanceChanged";
let event = event_result.context("failed to decode an event")?;
let metadata = event.event_metadata();

match (metadata.pallet.name(), &*metadata.variant.name) {
(SYSTEM, UPDATE) => update = true,
Expand Down Expand Up @@ -988,11 +978,10 @@ impl Processor {
let mut invoices_changes = HashMap::new();

for event_result in events.iter() {
let event = event_result.context("failed to decode an event")?;
let metadata = event.event_metadata();

const UPDATE: &str = "CodeUpdated";
const TRANSFERRED: &str = "Transferred";
let event = event_result.context("failed to decode an event")?;
let metadata = event.event_metadata();

match (metadata.pallet.name(), &*metadata.variant.name) {
(SYSTEM, UPDATE) => update = true,
Expand All @@ -1009,13 +998,12 @@ impl Processor {

for (invoice, changes) in invoices_changes {
let price = match changes.invoice.status {
InvoiceStatus::Unpaid(price) => price,
InvoiceStatus::Paid(price) => price,
InvoiceStatus::Unpaid(price) | InvoiceStatus::Paid(price) => price,
};

self.process_unpaid(&block, changes, hash, invoice, price)
.await
.context("failed to process an unpaid invoice")?
.context("failed to process an unpaid invoice")?;
}

if update {
Expand Down Expand Up @@ -1203,15 +1191,15 @@ impl Processor {
Ok(())
}

async fn process_paid(
&self,
_invoice: Account,
_block: &Block<RuntimeConfig, OnlineClient>,
_changes: InvoiceChanges,
_hash: Hash,
) -> Result<()> {
Ok(())
}
// async fn process_paid(
// &self,
// _invoice: Account,
// _block: &Block<RuntimeConfig, OnlineClient>,
// _changes: InvoiceChanges,
// _hash: Hash,
// ) -> Result<()> {
// Ok(())
// }
}

fn construct_transfer(to: &Account, amount: Balance) -> Value {
Expand All @@ -1231,11 +1219,11 @@ fn construct_transfer(to: &Account, amount: Balance) -> Value {
.into_value()
}

async fn calculate_estimate_fee(
extrinsic: &SubmittableExtrinsic<RuntimeConfig, OnlineClient>,
) -> Result<Balance> {
Ok(EXPECTED_USDT_FEE)
}
// async fn calculate_estimate_fee(
// extrinsic: &SubmittableExtrinsic<RuntimeConfig, OnlineClient>,
// ) -> Result<Balance> {
// Ok(EXPECTED_USDT_FEE)
// }

#[derive(Debug)]
struct InvoiceChanges {
Expand Down
19 changes: 12 additions & 7 deletions kalatori-ah/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,17 +116,19 @@ async fn handler(

async fn abcd(
database: Arc<Database>,
rrecipient: Option<String>,
recipient_option: Option<String>,
order: String,
pprice: f64,
price_f64: f64,
) -> Result<Success, anyhow::Error> {
let recipient = rrecipient.context("destionation address isn't set")?;
let recipient = recipient_option.context("destionation address isn't set")?;
let decoded_recip = hex::decode(&recipient[2..])?;
let recipient_account = Account::try_from(decoded_recip.as_ref())
.map_err(|()| anyhow::anyhow!("Unknown address length"))?;
let properties = database.properties().await;
#[allow(clippy::cast_precision_loss)]
let mul = 10u128.pow(properties.decimals.try_into()?) as f64;
let price = (pprice * mul).round() as u128;
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let price = (price_f64 * mul).round() as u128;
let order_encoded = DeriveJunction::hard(&order).unwrap_inner();
let invoice_account: Account = database
.pair()
Expand Down Expand Up @@ -154,8 +156,9 @@ async fn abcd(
Ok(Success {
pay_account: format!("0x{}", HexDisplay::from(&invoice_account.as_ref())),
price: match invoice.status {
InvoiceStatus::Unpaid(uprice) => convert(properties.decimals, uprice)?,
InvoiceStatus::Paid(uprice) => convert(properties.decimals, uprice)?,
InvoiceStatus::Unpaid(invoice_price) | InvoiceStatus::Paid(invoice_price) => {
convert(properties.decimals, invoice_price)?
}
},
wss: database.rpc().to_string(),
mul: properties.decimals,
Expand Down Expand Up @@ -184,7 +187,7 @@ async fn abcd(

Ok(Success {
pay_account: format!("0x{}", HexDisplay::from(&invoice_account.as_ref())),
price: pprice,
price: price_f64,
wss: database.rpc().to_string(),
mul: properties.decimals,
recipient,
Expand All @@ -196,7 +199,9 @@ async fn abcd(
}

fn convert(dec: u64, num: u128) -> Result<f64> {
#[allow(clippy::cast_precision_loss)]
let numfl = num as f64;
#[allow(clippy::cast_precision_loss)]
let mul = 10u128.pow(dec.try_into()?) as f64;

Ok(numfl / mul)
Expand Down
Loading

0 comments on commit 9a94b3c

Please sign in to comment.