Skip to content

Commit

Permalink
Type safety + refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
Dzejkop committed Jun 3, 2024
1 parent b4980cb commit 649d485
Show file tree
Hide file tree
Showing 11 changed files with 334 additions and 157 deletions.
2 changes: 1 addition & 1 deletion src/broadcast_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ pub async fn should_send_relayer_transactions(
return Ok(false);
}

for gas_limit in &relayer.gas_price_limits.0 {
for gas_limit in &relayer.gas_price_limits {
let chain_fees = app
.db
.get_latest_block_fees_by_chain_id(relayer.chain_id)
Expand Down
9 changes: 4 additions & 5 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ use tracing::instrument;

Check warning on line 11 in src/db.rs

View workflow job for this annotation

GitHub Actions / cargo fmt

Diff in /home/runner/work/tx-sitter-monolith/tx-sitter-monolith/src/db.rs
use crate::broadcast_utils::gas_estimation::FeesEstimate;
use crate::config::DatabaseConfig;
use crate::new_server::types::NetworkInfo;
use crate::types::{RelayerInfo, RelayerUpdate, TransactionPriority};
use crate::types::{RelayerInfo, NetworkInfo, RelayerUpdate, TransactionPriority};

pub mod data;

Expand Down Expand Up @@ -1230,7 +1229,7 @@ mod tests {
use postgres_docker_utils::DockerContainerGuard;

use super::*;
use crate::db::data::U256Wrapper;
use crate::types::wrappers::u256::U256Wrapper;
use crate::types::RelayerGasPriceLimit;

async fn setup_db() -> eyre::Result<(Database, DockerContainerGuard)> {
Expand Down Expand Up @@ -1372,7 +1371,7 @@ mod tests {
assert_eq!(relayer.nonce, 0);
assert_eq!(relayer.current_nonce, 0);
assert_eq!(relayer.max_inflight_txs, 5);
assert_eq!(relayer.gas_price_limits.0, vec![]);
assert_eq!(relayer.gas_price_limits, vec![]);

db.update_relayer(
relayer_id,
Expand Down Expand Up @@ -1401,7 +1400,7 @@ mod tests {
assert_eq!(relayer.max_inflight_txs, 10);
assert_eq!(relayer.max_queued_txs, 20);
assert_eq!(
relayer.gas_price_limits.0,
relayer.gas_price_limits,
vec![RelayerGasPriceLimit {
chain_id: 1,
value: U256Wrapper(U256::from(10_123u64)),
Expand Down
98 changes: 3 additions & 95 deletions src/db/data.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
use ethers::types::{Address, H256, U256};
use ethers::types::{H256, U256};
use serde::{Deserialize, Serialize};
use sqlx::database::{HasArguments, HasValueRef};
use sqlx::postgres::{PgHasArrayType, PgTypeInfo};
use sqlx::prelude::FromRow;
use sqlx::Database;

use crate::broadcast_utils::gas_estimation::FeesEstimate;
use crate::types::wrappers::address::AddressWrapper;
use crate::types::wrappers::u256::U256Wrapper;
use crate::types::TransactionPriority;

#[derive(Debug, Clone, FromRow)]
Expand Down Expand Up @@ -76,103 +78,9 @@ pub struct BlockFees {
pub gas_price: U256,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct AddressWrapper(pub Address);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct U256Wrapper(pub U256);

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct H256Wrapper(pub H256);

impl<'r, DB> sqlx::Decode<'r, DB> for AddressWrapper
where
DB: Database,
Vec<u8>: sqlx::Decode<'r, DB>,
{
fn decode(
value: <DB as HasValueRef<'r>>::ValueRef,
) -> Result<Self, sqlx::error::BoxDynError> {
let bytes = <Vec<u8> as sqlx::Decode<DB>>::decode(value)?;

let address = Address::from_slice(&bytes);

Ok(Self(address))
}
}

impl<DB: Database> sqlx::Type<DB> for AddressWrapper
where
Vec<u8>: sqlx::Type<DB>,
{
fn type_info() -> DB::TypeInfo {
<Vec<u8> as sqlx::Type<DB>>::type_info()
}

fn compatible(ty: &DB::TypeInfo) -> bool {
*ty == Self::type_info()
}
}

impl From<Address> for AddressWrapper {
fn from(value: Address) -> Self {
Self(value)
}
}

impl<'r, DB> sqlx::Decode<'r, DB> for U256Wrapper
where
DB: Database,
[u8; 32]: sqlx::Decode<'r, DB>,
{
fn decode(
value: <DB as HasValueRef<'r>>::ValueRef,
) -> Result<Self, sqlx::error::BoxDynError> {
let bytes = <[u8; 32] as sqlx::Decode<DB>>::decode(value)?;

let value = U256::from_big_endian(&bytes);

Ok(Self(value))
}
}

impl<DB: Database> sqlx::Type<DB> for U256Wrapper
where
[u8; 32]: sqlx::Type<DB>,
{
fn type_info() -> DB::TypeInfo {
<[u8; 32] as sqlx::Type<DB>>::type_info()
}

fn compatible(ty: &DB::TypeInfo) -> bool {
*ty == Self::type_info()
}
}

impl<'q, DB> sqlx::Encode<'q, DB> for U256Wrapper
where
DB: Database,
[u8; 32]: sqlx::Encode<'q, DB>,
{
fn encode_by_ref(
&self,
buf: &mut <DB as HasArguments<'q>>::ArgumentBuffer,
) -> sqlx::encode::IsNull {
let mut bytes = [0u8; 32];
self.0.to_big_endian(&mut bytes);

<[u8; 32] as sqlx::Encode<DB>>::encode_by_ref(&bytes, buf)
}
}

impl From<U256> for U256Wrapper {
fn from(value: U256) -> Self {
Self(value)
}
}

impl<'r, DB> sqlx::Decode<'r, DB> for H256Wrapper
where
DB: Database,
Expand Down
41 changes: 34 additions & 7 deletions src/new_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,19 @@ use ethers::signers::Signer;
use poem::http::StatusCode;
use poem::listener::{Acceptor, Listener, TcpListener};
use poem::web::{Data, LocalAddr};
use poem::{Endpoint, EndpointExt, Result, Route};
use poem::{EndpointExt, Result, Route};
use poem_openapi::param::Path;
use poem_openapi::payload::{Json, PlainText};
use poem_openapi::{ApiResponse, OpenApi, OpenApiService};
use types::NetworkInfo;
use url::Url;

use crate::app::App;
use crate::service::Service;
use crate::task_runner::TaskRunner;
use crate::types::{
CreateRelayerRequest, CreateRelayerResponse, NetworkInfo, NewNetworkInfo,
RelayerInfo,
};

pub mod types;

Expand All @@ -23,7 +26,7 @@ struct AdminApi;
#[derive(ApiResponse)]
enum AdminResponse {
#[oai(status = 200)]
RelayerCreated(Json<types::CreateRelayerResponse>),
RelayerCreated(Json<CreateRelayerResponse>),

#[oai(status = 200)]
NetworkCreated,

Check failure on line 32 in src/new_server.rs

View workflow job for this annotation

GitHub Actions / cargo test

variant `NetworkCreated` is never constructed
Expand All @@ -38,7 +41,7 @@ impl AdminApi {
async fn create_relayer(
&self,
app: Data<&Arc<App>>,
req: Json<types::CreateRelayerRequest>,
req: Json<CreateRelayerRequest>,
) -> AdminResponse {
let (key_id, signer) = match app.keys_source.new_signer(&req.name).await
{
Expand Down Expand Up @@ -77,18 +80,42 @@ impl AdminApi {
}
}

AdminResponse::RelayerCreated(Json(types::CreateRelayerResponse {
AdminResponse::RelayerCreated(Json(CreateRelayerResponse {
relayer_id,
address: format!("{address:?}"),
address: address.into(),
}))
}

#[oai(path = "/relayers", method = "get")]
async fn get_relayers(
&self,
app: Data<&Arc<App>>,
) -> Result<Json<Vec<RelayerInfo>>> {
let relayer_info = app.db.get_relayers().await?;

Ok(Json(relayer_info))
}

#[oai(path = "/relayer/:relayer_id", method = "get")]
async fn update_relayer(&self, app: Data<&Arc<App>>) -> AdminResponse {

Check failure on line 100 in src/new_server.rs

View workflow job for this annotation

GitHub Actions / cargo test

unused variable: `app`
todo!()
}

#[oai(path = "/relayer/:relayer_id/reset", method = "post")]
async fn purge_unsent_txs(
&self,
app: Data<&Arc<App>>,

Check failure on line 107 in src/new_server.rs

View workflow job for this annotation

GitHub Actions / cargo test

unused variable: `app`
Path(relayer_id): Path<String>,

Check failure on line 108 in src/new_server.rs

View workflow job for this annotation

GitHub Actions / cargo test

unused variable: `relayer_id`
) -> AdminResponse {
todo!()
}

#[oai(path = "/network/:chain_id", method = "post")]
async fn create_network(
&self,
app: Data<&Arc<App>>,
Path(chain_id): Path<u64>,
Json(network): Json<types::NewNetworkInfo>,
Json(network): Json<NewNetworkInfo>,
) -> Result<()> {
let http_url: Url = network
.http_rpc
Expand Down
42 changes: 0 additions & 42 deletions src/new_server/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,45 +2,3 @@ use poem_openapi::Object;
use serde::{Deserialize, Serialize};

Check failure on line 2 in src/new_server/types.rs

View workflow job for this annotation

GitHub Actions / cargo test

unused imports: `Deserialize`, `Serialize`
use sqlx::FromRow;

Check failure on line 3 in src/new_server/types.rs

View workflow job for this annotation

GitHub Actions / cargo test

unused import: `sqlx::FromRow`

#[derive(Debug, Default, Clone, Serialize, Deserialize, Object)]
#[serde(rename_all = "camelCase")]
#[oai(rename_all = "camelCase")]
pub struct NewNetworkInfo {
pub name: String,
pub http_rpc: String,
pub ws_rpc: String,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize, FromRow, Object)]
#[serde(rename_all = "camelCase")]
#[oai(rename_all = "camelCase")]
pub struct NetworkInfo {
#[sqlx(try_from = "i64")]
pub chain_id: u64,
pub name: String,
pub http_rpc: String,
pub ws_rpc: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, Object)]
#[serde(rename_all = "camelCase")]
#[oai(rename_all = "camelCase")]
pub struct CreateRelayerRequest {
/// New relayer name
pub name: String,
/// The chain id of the relayer
pub chain_id: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize, Object)]
#[serde(rename_all = "camelCase")]
#[oai(rename_all = "camelCase")]
pub struct CreateRelayerResponse {
/// ID of the created relayer
pub relayer_id: String,
// TODO: Make type safe
/// Address of the created relayer
///
/// Hex encoded, example "0x1234...5678"
pub address: String,
}
Loading

0 comments on commit 649d485

Please sign in to comment.