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

refactor: returned shared structs from services #90

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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: 12 additions & 1 deletion orm/src/balances.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use std::str::FromStr;

use bigdecimal::BigDecimal;
use diesel::{Insertable, Queryable, Selectable};
use shared::balance::Balance;
use shared::balance::{Amount, Balance};
use shared::id::Id;

use crate::schema::balances;

Expand All @@ -27,3 +28,13 @@ impl BalancesInsertDb {
}
}
}

impl From<BalanceDb> for Balance {
fn from(balance: BalanceDb) -> Self {
Self {
owner: Id::from_account_str(&balance.owner),
token: Id::from_account_str(&balance.token),
amount: Amount::from(balance.raw_amount),
}
}
}
13 changes: 11 additions & 2 deletions orm/src/crawler_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use diesel::sql_types::Nullable;
use diesel::{Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use shared::crawler_state::{
BlockCrawlerState, ChainCrawlerState, CrawlerName, EpochCrawlerState,
IntervalCrawlerState,
BlockCrawlerState, ChainCrawlerState, CrawlerName, CrawlerTimestamp,
EpochCrawlerState, IntervalCrawlerState,
};

use crate::schema::crawler_state;
Expand Down Expand Up @@ -273,3 +273,12 @@ impl From<(CrawlerName, IntervalCrawlerState)> for IntervalStateInsertDb {
}
}
}

impl From<CrawlerStateDb> for CrawlerTimestamp {
fn from(value: CrawlerStateDb) -> Self {
Self {
name: value.name.to_string(),
timestamp: value.timestamp.and_utc().timestamp(),
}
}
}
26 changes: 26 additions & 0 deletions orm/src/parameters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,29 @@ impl From<(Parameters, Genesis, Checksums, EpochSwitchBlocksDelay)>
}
}
}

impl From<ParametersDb>
for (Parameters, Genesis, Checksums, EpochSwitchBlocksDelay)
{
fn from(parameters: ParametersDb) -> Self {
(
Parameters {
unbonding_length: parameters.unbonding_length as u64,
pipeline_length: parameters.pipeline_length as u64,
epochs_per_year: parameters.epochs_per_year as u64,
min_num_of_blocks: parameters.min_num_of_blocks as u64,
min_duration: parameters.min_duration as u64,
max_block_time: parameters.max_block_time as u64,
apr: parameters.apr,
native_token_address: parameters.native_token_address,
},
Genesis {
chain_id: parameters.chain_id,
genesis_time: parameters.genesis_time,
},
serde_json::from_value(parameters.checksums)
.expect("Failed to deserialize checksums"),
parameters.epoch_switch_blocks_delay as u32,
)
}
}
6 changes: 6 additions & 0 deletions shared/src/crawler_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,9 @@ pub struct EpochCrawlerState {
pub struct IntervalCrawlerState {
pub timestamp: i64,
}

#[derive(Debug)]
pub struct CrawlerTimestamp {
pub name: String,
pub timestamp: i64,
}
8 changes: 8 additions & 0 deletions shared/src/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,11 @@ impl From<common::PublicKey> for Id {
Id::Account(value.to_string())
}
}

impl Id {
pub fn from_account_str(address: &str) -> Self {
let account =
NamadaAddress::from_str(address).expect("Invalid address");
Self::from(account)
}
}
5 changes: 4 additions & 1 deletion webserver/src/handler/balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,8 @@ pub async fn get_address_balance(
) -> Result<Json<Vec<AddressBalance>>, ApiError> {
let balances = state.balance_service.get_address_balances(address).await?;

Ok(Json(balances))
let balances_response: Vec<AddressBalance> =
balances.iter().cloned().map(AddressBalance::from).collect();

Ok(Json(balances_response))
}
2 changes: 1 addition & 1 deletion webserver/src/handler/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ pub async fn get_parameters(
) -> Result<Json<Parameters>, ApiError> {
let parameters = state.chain_service.find_latest_parameters().await?;

Ok(Json(parameters))
Ok(Json(Parameters::from(parameters)))
}

pub async fn get_rpc_url(State(state): State<CommonState>) -> Json<RpcUrl> {
Expand Down
11 changes: 4 additions & 7 deletions webserver/src/handler/crawler_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ use strum::VariantArray;

use crate::dto::crawler_state::{CrawlerNameDto, CrawlerStateQueryParams};
use crate::error::api::ApiError;
use crate::response::crawler_state::CrawlersTimestamps;
use crate::response::crawler_state::CrawlerTimestamp;
use crate::state::common::CommonState;

pub async fn get_crawlers_timestamps(
_headers: HeaderMap,
Query(query): Query<CrawlerStateQueryParams>,
State(state): State<CommonState>,
) -> Result<Json<Vec<CrawlersTimestamps>>, ApiError> {
) -> Result<Json<Vec<CrawlerTimestamp>>, ApiError> {
let crawler_names = query.crawler_names.unwrap_or(vec![]);

let timestamps = state
Expand All @@ -38,11 +38,8 @@ pub async fn get_crawlers_timestamps(
.iter()
.find(|timestamp| timestamp.name == variant.to_string())
.map_or_else(
|| CrawlersTimestamps {
name: variant.to_string(),
timestamp: 0,
},
|ct| ct.clone(),
|| CrawlerTimestamp::empty(variant.to_string()),
CrawlerTimestamp::from,
)
})
.collect::<Vec<_>>();
Expand Down
12 changes: 7 additions & 5 deletions webserver/src/response/balance.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use orm::balances::BalanceDb;
use serde::{Deserialize, Serialize};
use shared::balance::{Balance, DenominatedAmount};

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
Expand All @@ -8,11 +8,13 @@ pub struct AddressBalance {
pub balance: String,
}

impl From<BalanceDb> for AddressBalance {
fn from(value: BalanceDb) -> Self {
impl From<Balance> for AddressBalance {
fn from(value: Balance) -> Self {
Self {
token_address: value.token,
balance: value.raw_amount.to_string(),
token_address: value.token.to_string(),
// TODO: temporary solution as we only store NAM balances
balance: DenominatedAmount::native(value.amount.clone())
.to_string_precise(),
}
}
}
24 changes: 13 additions & 11 deletions webserver/src/response/chain.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use orm::parameters::ParametersDb;
use serde::{Deserialize, Serialize};
use serde_json::Value as SerdeJSONValue;

use crate::service::chain::LatestParameters;

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Parameters {
Expand All @@ -19,23 +20,24 @@ pub struct Parameters {
pub epoch_switch_blocks_delay: String,
}

impl From<ParametersDb> for Parameters {
fn from(parameters: ParametersDb) -> Self {
impl From<LatestParameters> for Parameters {
fn from(
(parameters, genesis, checksums, epoch_switch_blocks_delay): LatestParameters,
) -> Parameters {
Self {
unbonding_length: parameters.unbonding_length.to_string(),
pipeline_length: parameters.pipeline_length.to_string(),
epochs_per_year: parameters.epochs_per_year.to_string(),
apr: parameters.apr,
native_token_address: parameters.native_token_address,
chain_id: parameters.chain_id,
genesis_time: parameters.genesis_time.to_string(),
apr: parameters.apr.to_string(),
native_token_address: parameters.native_token_address.to_string(),
chain_id: genesis.chain_id.to_string(),
genesis_time: genesis.genesis_time.to_string(),
min_duration: parameters.min_duration.to_string(),
min_num_of_blocks: parameters.min_num_of_blocks.to_string(),
max_block_time: parameters.max_block_time.to_string(),
checksums: parameters.checksums,
epoch_switch_blocks_delay: parameters
.epoch_switch_blocks_delay
.to_string(),
checksums: serde_json::to_value(checksums)
.expect("Failed to serialize checksums"),
epoch_switch_blocks_delay: epoch_switch_blocks_delay.to_string(),
}
}
}
Expand Down
18 changes: 17 additions & 1 deletion webserver/src/response/crawler_state.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,24 @@
use serde::{Deserialize, Serialize};
use shared::crawler_state::CrawlerTimestamp as SharedCrawlerTimestamp;

#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CrawlersTimestamps {
pub struct CrawlerTimestamp {
pub name: String,
pub timestamp: i64,
}

impl CrawlerTimestamp {
pub fn empty(name: String) -> Self {
Self { name, timestamp: 0 }
}
}

impl From<&SharedCrawlerTimestamp> for CrawlerTimestamp {
fn from(shared: &SharedCrawlerTimestamp) -> Self {
Self {
name: shared.name.clone(),
timestamp: shared.timestamp,
}
}
}
24 changes: 6 additions & 18 deletions webserver/src/service/balance.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use shared::balance::{Amount, DenominatedAmount};
use shared::balance::Balance;

use crate::appstate::AppState;
use crate::error::balance::BalanceError;
use crate::repository::balance::{BalanceRepo, BalanceRepoTrait};
use crate::response::balance::AddressBalance;

#[derive(Clone)]
pub struct BalanceService {
Expand All @@ -20,27 +19,16 @@ impl BalanceService {
pub async fn get_address_balances(
&self,
address: String,
) -> Result<Vec<AddressBalance>, BalanceError> {
let balances = self
) -> Result<Vec<Balance>, BalanceError> {
let balances_db = self
.balance_repo
.get_address_balances(address)
.await
.map_err(BalanceError::Database)?;

// TODO: temporary solution as we only store NAM balances
let denominated_balances: Vec<AddressBalance> = balances
.iter()
.cloned()
.map(|balance| AddressBalance {
token_address: balance.token,
// TODO: change native to new once we support multiple tokens
balance: DenominatedAmount::native(Amount::from(
balance.raw_amount,
))
.to_string_precise(),
})
.collect();
let balances: Vec<Balance> =
balances_db.iter().cloned().map(Balance::from).collect();

Ok(denominated_balances)
Ok(balances)
}
}
12 changes: 9 additions & 3 deletions webserver/src/service/chain.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
use shared::checksums::Checksums;
use shared::genesis::Genesis;
use shared::parameters::{EpochSwitchBlocksDelay, Parameters};

use crate::appstate::AppState;
use crate::error::chain::ChainError;
use crate::repository::chain::{ChainRepository, ChainRepositoryTrait};
use crate::response::chain::Parameters;

#[derive(Clone)]
pub struct ChainService {
chain_repo: ChainRepository,
}

pub type LatestParameters =
(Parameters, Genesis, Checksums, EpochSwitchBlocksDelay);

impl ChainService {
pub fn new(app_state: AppState) -> Self {
Self {
Expand All @@ -17,12 +23,12 @@ impl ChainService {

pub async fn find_latest_parameters(
&self,
) -> Result<Parameters, ChainError> {
) -> Result<LatestParameters, ChainError> {
let parameters = self
.chain_repo
.find_chain_parameters()
.await
.map(Parameters::from)
.map(LatestParameters::from)
.map_err(ChainError::Database)?;

Ok(parameters)
Expand Down
11 changes: 4 additions & 7 deletions webserver/src/service/crawler_state.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use diesel::{ExpressionMethods, QueryDsl, RunQueryDsl};
use orm::crawler_state::{CrawlerNameDb, CrawlerStateDb};
use orm::schema::crawler_state;
use shared::crawler_state::CrawlerTimestamp;

use crate::appstate::AppState;
use crate::dto::crawler_state::CrawlerNameDto;
use crate::error::crawler_state::CrawlerStateError;
use crate::response::crawler_state::CrawlersTimestamps;

#[derive(Clone)]
pub struct CrawlerStateService {
Expand All @@ -20,7 +20,7 @@ impl CrawlerStateService {
pub async fn get_timestamps(
&self,
names: Vec<CrawlerNameDto>,
) -> Result<Vec<CrawlersTimestamps>, CrawlerStateError> {
) -> Result<Vec<CrawlerTimestamp>, CrawlerStateError> {
let conn = self.app_state.get_db_connection().await;
let names_db = names
.iter()
Expand All @@ -46,11 +46,8 @@ impl CrawlerStateService {
crawlers_db.map(|crawlers| {
crawlers
.into_iter()
.map(|crawler| CrawlersTimestamps {
name: crawler.name.to_string(),
timestamp: crawler.timestamp.and_utc().timestamp(),
})
.collect::<Vec<CrawlersTimestamps>>()
.map(CrawlerTimestamp::from)
.collect::<Vec<_>>()
})
}

Expand Down
Loading