Skip to content

Commit

Permalink
Clippy + fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
Dzejkop committed Jun 5, 2024
1 parent bf37bb2 commit 1ed4d67
Show file tree
Hide file tree
Showing 11 changed files with 80 additions and 157 deletions.
17 changes: 9 additions & 8 deletions src/api_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ use std::str::FromStr;

use base64::Engine;
use poem_openapi::registry::{MetaSchema, MetaSchemaRef};
use poem_openapi::types::{ParseFromJSON, ParseFromParameter, ToJSON};
use poem_openapi::types::{
ParseError, ParseFromJSON, ParseFromParameter, ToJSON,
};
use rand::rngs::OsRng;
use rand::Rng;
use serde::Serialize;
Expand Down Expand Up @@ -161,12 +163,9 @@ impl ParseFromJSON for ApiKey {
fn parse_from_json(
value: Option<serde_json::Value>,
) -> poem_openapi::types::ParseResult<Self> {
// TODO: Better error handling
let value = value
.ok_or_else(|| poem_openapi::types::ParseError::expected_input())?;
let value = value.ok_or_else(ParseError::expected_input)?;

serde_json::from_value(value)
.map_err(|_| poem_openapi::types::ParseError::expected_input())
serde_json::from_value(value).map_err(ParseError::custom)
}
}

Expand All @@ -177,8 +176,10 @@ impl ToJSON for ApiKey {
}

impl ParseFromParameter for ApiKey {
fn parse_from_parameter(value: &str) -> poem_openapi::types::ParseResult<Self> {
value.parse().map_err(|_| poem_openapi::types::ParseError::expected_input())
fn parse_from_parameter(
value: &str,
) -> poem_openapi::types::ParseResult<Self> {
value.parse().map_err(|_| ParseError::expected_input())
}
}

Expand Down
38 changes: 12 additions & 26 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,18 @@ impl TxSitterClient {
self
}

fn creds(&self) -> (&str, &str) {
self.credentials
.as_ref()
.map(|(u, p)| (u.as_str(), p.as_str()))
.unwrap_or_default()
}

async fn post<R>(&self, url: &str) -> Result<R, ClientError>
where
R: serde::de::DeserializeOwned,
{
let (username, password) = self
.credentials
.as_ref()
.map(|(u, p)| (u.as_str(), p.as_str()))
.unwrap_or_default()
.clone();
let (username, password) = self.creds();

let response = self
.client
Expand All @@ -80,12 +82,7 @@ impl TxSitterClient {
T: serde::Serialize,
R: serde::de::DeserializeOwned,
{
let (username, password) = self
.credentials
.as_ref()
.map(|(u, p)| (u.as_str(), p.as_str()))
.unwrap_or_default()
.clone();
let (username, password) = self.creds();

let response = self
.client
Expand All @@ -104,12 +101,7 @@ impl TxSitterClient {
where
R: serde::de::DeserializeOwned,
{
let (username, password) = self
.credentials
.as_ref()
.map(|(u, p)| (u.as_str(), p.as_str()))
.unwrap_or_default()
.clone();
let (username, password) = self.creds();

let response = self
.client
Expand Down Expand Up @@ -155,17 +147,11 @@ impl TxSitterClient {
relayer_id: &str,
relayer_update: RelayerUpdate,
) -> Result<(), ClientError> {
let this = &self;
let url: &str = &format!("{}/1/admin/relayer/{relayer_id}", self.url);

let (username, password) = this
.credentials
.as_ref()
.map(|(u, p)| (u.as_str(), p.as_str()))
.unwrap_or_default()
.clone();
let (username, password) = self.creds();

let response = this
let response = self
.client
.post(url)
.json(&relayer_update)
Expand Down
4 changes: 3 additions & 1 deletion src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ use tracing::instrument;
use crate::broadcast_utils::gas_estimation::FeesEstimate;
use crate::config::DatabaseConfig;
use crate::types::wrappers::h256::H256Wrapper;
use crate::types::{NetworkInfo, RelayerInfo, RelayerUpdate, TransactionPriority, TxStatus};
use crate::types::{
NetworkInfo, RelayerInfo, RelayerUpdate, TransactionPriority, TxStatus,
};

pub mod data;

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ pub mod client;
pub mod config;
pub mod db;
pub mod keys;
pub mod serde_utils;
pub mod new_server;
pub mod serde_utils;
pub mod service;
pub mod shutdown;
pub mod task_runner;
Expand Down
81 changes: 11 additions & 70 deletions src/new_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,46 +41,22 @@ impl AdminApi {
) -> Result<Json<CreateRelayerResponse>> {
basic_auth.validate(app).await?;

let (key_id, signer) = match app.keys_source.new_signer(&req.name).await
{
Ok(signer) => signer,
Err(e) => {
tracing::error!("Failed to create signer: {:?}", e);

return Err(poem::error::Error::from_string(
"Failed to create signer".to_string(),
StatusCode::INTERNAL_SERVER_ERROR,
));
}
};
let (key_id, signer) = app.keys_source.new_signer(&req.name).await?;

let address = signer.address();

let relayer_id = uuid::Uuid::new_v4();
let relayer_id = relayer_id.to_string();

let result = app
.db
app.db
.create_relayer(
&relayer_id,
&req.name,
req.chain_id,
&key_id,
address,
)
.await;

match result {
Ok(()) => {}
Err(e) => {
tracing::error!("Failed to create relayer: {:?}", e);

return Err(poem::error::Error::from_string(
"Failed to create relayer".to_string(),
StatusCode::INTERNAL_SERVER_ERROR,
));
}
}
.await?;

Ok(Json(CreateRelayerResponse {
relayer_id,
Expand Down Expand Up @@ -112,13 +88,7 @@ impl AdminApi {
) -> Result<Json<RelayerInfo>> {
basic_auth.validate(app).await?;

let relayer_info =
app.db.get_relayer(&relayer_id).await.map_err(|err| {
poem::error::Error::from_string(
err.to_string(),
StatusCode::INTERNAL_SERVER_ERROR,
)
})?;
let relayer_info = app.db.get_relayer(&relayer_id).await?;

Ok(Json(relayer_info))
}
Expand All @@ -134,15 +104,7 @@ impl AdminApi {
) -> Result<()> {
basic_auth.validate(app).await?;

app.db
.update_relayer(&relayer_id, &req)
.await
.map_err(|err| {
poem::error::Error::from_string(
err.to_string(),
StatusCode::INTERNAL_SERVER_ERROR,
)
})?;
app.db.update_relayer(&relayer_id, &req).await?;

Ok(())
}
Expand All @@ -159,12 +121,7 @@ impl AdminApi {
) -> Result<()> {
basic_auth.validate(app).await?;

app.db.purge_unsent_txs(&relayer_id).await.map_err(|err| {
poem::error::Error::from_string(
err.to_string(),
StatusCode::INTERNAL_SERVER_ERROR,
)
})?;
app.db.purge_unsent_txs(&relayer_id).await?;

Ok(())
}
Expand Down Expand Up @@ -202,12 +159,12 @@ impl AdminApi {
let http_url: Url = network
.http_rpc
.parse::<Url>()
.map_err(|err| poem::error::BadRequest(err))?;
.map_err(poem::error::BadRequest)?;

let ws_url: Url = network
.ws_rpc
.parse::<Url>()
.map_err(|err| poem::error::BadRequest(err))?;
.map_err(poem::error::BadRequest)?;

app.db
.upsert_network(
Expand All @@ -216,21 +173,10 @@ impl AdminApi {
http_url.as_str(),
ws_url.as_str(),
)
.await
.map_err(|err| {
poem::error::Error::from_string(
err.to_string(),
StatusCode::INTERNAL_SERVER_ERROR,
)
})?;
.await?;

let task_runner = TaskRunner::new(app.clone());
Service::spawn_chain_tasks(&task_runner, chain_id).map_err(|err| {
poem::error::Error::from_string(
err.to_string(),
StatusCode::INTERNAL_SERVER_ERROR,
)
})?;
Service::spawn_chain_tasks(&task_runner, chain_id)?;

Ok(())
}
Expand All @@ -244,12 +190,7 @@ impl AdminApi {
) -> Result<Json<Vec<NetworkInfo>>> {
basic_auth.validate(app).await?;

let networks = app.db.get_networks().await.map_err(|err| {
poem::error::Error::from_string(
err.to_string(),
StatusCode::INTERNAL_SERVER_ERROR,
)
})?;
let networks = app.db.get_networks().await?;

Ok(Json(networks))
}
Expand Down
25 changes: 13 additions & 12 deletions src/types/wrappers/address.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use ethers::types::Address;
use poem_openapi::registry::{MetaSchema, MetaSchemaRef};
use poem_openapi::types::{ParseFromJSON, ToJSON};
use poem_openapi::types::{ParseError, ParseFromJSON, ToJSON};
use serde::{Deserialize, Serialize};
use sqlx::database::HasValueRef;
use sqlx::Database;
Expand Down Expand Up @@ -56,11 +56,11 @@ impl poem_openapi::types::Type for AddressWrapper {
}

fn schema_ref() -> MetaSchemaRef {
let mut schema_ref = MetaSchema::new_with_format(
"string", "address",
);
let mut schema_ref = MetaSchema::new_with_format("string", "address");

schema_ref.example = Some(serde_json::Value::String("0x000000000000000000000000000000000000000f".to_string()));
schema_ref.example = Some(serde_json::Value::String(
"0x000000000000000000000000000000000000000f".to_string(),
));
schema_ref.title = Some("Address".to_string());
schema_ref.description = Some("Hex encoded ethereum address");

Expand All @@ -82,12 +82,10 @@ impl ParseFromJSON for AddressWrapper {
fn parse_from_json(
value: Option<serde_json::Value>,
) -> poem_openapi::types::ParseResult<Self> {
// TODO: Better error handling
let value = value
.ok_or_else(|| poem_openapi::types::ParseError::expected_input())?;
let value = value.ok_or_else(ParseError::expected_input)?;

let value = serde_json::from_value(value)
.map_err(|_| poem_openapi::types::ParseError::expected_input())?;
let value =
serde_json::from_value(value).map_err(ParseError::custom)?;

Ok(value)
}
Expand All @@ -108,10 +106,13 @@ mod tests {

#[test]
fn deserialize() {
let address: AddressWrapper = serde_json::from_str(r#""1Ed53d680B8890DAe2a63f673a85fFDE1FD5C7a2""#).unwrap();
let address: AddressWrapper = serde_json::from_str(
r#""1Ed53d680B8890DAe2a63f673a85fFDE1FD5C7a2""#,
)
.unwrap();

let expected = H160(hex!("1Ed53d680B8890DAe2a63f673a85fFDE1FD5C7a2"));

assert_eq!(address.0, expected);
}
}
}
13 changes: 4 additions & 9 deletions src/types/wrappers/decimal_u256.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::borrow::Cow;

use ethers::types::U256;
use poem_openapi::registry::{MetaSchema, MetaSchemaRef};
use poem_openapi::types::{ParseFromJSON, ToJSON};
use poem_openapi::types::{ParseError, ParseFromJSON, ToJSON};
use serde::{Deserialize, Serialize};
use sqlx::database::{HasArguments, HasValueRef};
use sqlx::Database;
Expand Down Expand Up @@ -122,15 +122,10 @@ impl ParseFromJSON for DecimalU256 {
fn parse_from_json(
value: Option<serde_json::Value>,
) -> poem_openapi::types::ParseResult<Self> {
// TODO: Better error handling
let value = value
.ok_or_else(|| poem_openapi::types::ParseError::expected_input())?;
let value = value.ok_or_else(ParseError::expected_input)?;

let value = serde_json::from_value(value).map_err(|err| {
tracing::error!("Error deserializing DecimalU256: {:?}", err);

poem_openapi::types::ParseError::expected_input()
})?;
let value =
serde_json::from_value(value).map_err(ParseError::custom)?;

Ok(value)
}
Expand Down
11 changes: 5 additions & 6 deletions src/types/wrappers/h256.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use ethers::types::H256;
use poem_openapi::registry::{MetaSchema, MetaSchemaRef};
use poem_openapi::types::{ParseFromJSON, ToJSON};
use poem_openapi::types::{ParseError, ParseFromJSON, ToJSON};
use serde::{Deserialize, Serialize};
use sqlx::database::{HasArguments, HasValueRef};
use sqlx::postgres::{PgHasArrayType, PgTypeInfo};
Expand Down Expand Up @@ -100,11 +100,10 @@ impl ParseFromJSON for H256Wrapper {
value: Option<serde_json::Value>,
) -> poem_openapi::types::ParseResult<Self> {
// TODO: Better error handling
let value = value
.ok_or_else(|| poem_openapi::types::ParseError::expected_input())?;
let value = value.ok_or_else(ParseError::expected_input)?;

let inner = serde_json::from_value(value)
.map_err(|_| poem_openapi::types::ParseError::expected_input())?;
let inner =
serde_json::from_value(value).map_err(ParseError::custom)?;

Ok(Self(inner))
}
Expand All @@ -114,4 +113,4 @@ impl ToJSON for H256Wrapper {
fn to_json(&self) -> Option<serde_json::Value> {
serde_json::to_value(self.0).ok()
}
}
}
Loading

0 comments on commit 1ed4d67

Please sign in to comment.