Skip to content

Commit

Permalink
decimal & hex U256 abstractions
Browse files Browse the repository at this point in the history
  • Loading branch information
Dzejkop committed Jun 4, 2024
1 parent 4b12a60 commit c12a5d3
Show file tree
Hide file tree
Showing 18 changed files with 378 additions and 106 deletions.
10 changes: 8 additions & 2 deletions src/api_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::str::FromStr;

use base64::Engine;
use poem_openapi::registry::{MetaSchema, MetaSchemaRef};
use poem_openapi::types::{ParseFromJSON, ToJSON};
use poem_openapi::types::{ParseFromJSON, ParseFromParameter, ToJSON};
use rand::rngs::OsRng;
use rand::Rng;
use serde::Serialize;
Expand Down Expand Up @@ -138,7 +138,7 @@ impl poem_openapi::types::Type for ApiKey {
let mut schema_ref = MetaSchema::new_with_format("string", "api-key");

schema_ref.example = Some(serde_json::Value::String(
"MyDwh6wBRyOAkrA-ANOGjViioo3fXMa53nbdLhezV4s=".to_string(),
"G5CKNF3BTS2hRl60bpdYMNPqXvXsP-QZd2lrtmgctsk=".to_string(),
));
schema_ref.title = Some("Api Key".to_string());
schema_ref.description = Some("Base64 encoded API key");
Expand Down Expand Up @@ -176,6 +176,12 @@ impl ToJSON for ApiKey {
}
}

Check warning on line 177 in src/api_key.rs

View workflow job for this annotation

GitHub Actions / cargo fmt

Diff in /home/runner/work/tx-sitter-monolith/tx-sitter-monolith/src/api_key.rs

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())
}
}

impl ApiKey {
pub fn reveal(&self) -> eyre::Result<String> {
let relayer_id = uuid::Uuid::parse_str(&self.relayer_id)
Expand Down
6 changes: 3 additions & 3 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1229,7 +1229,7 @@ mod tests {
use postgres_docker_utils::DockerContainerGuard;

use super::*;
use crate::types::wrappers::u256::U256Wrapper;
use crate::types::wrappers::hex_u256::HexU256;
use crate::types::RelayerGasPriceLimit;

async fn setup_db() -> eyre::Result<(Database, DockerContainerGuard)> {
Expand Down Expand Up @@ -1381,7 +1381,7 @@ mod tests {
max_queued_txs: Some(20),
gas_price_limits: Some(vec![RelayerGasPriceLimit {
chain_id: 1,
value: U256Wrapper(U256::from(10_123u64)),
value: HexU256(U256::from(10_123u64)),
}]),
enabled: None,
},
Expand All @@ -1403,7 +1403,7 @@ mod tests {
relayer.gas_price_limits,
vec![RelayerGasPriceLimit {
chain_id: 1,
value: U256Wrapper(U256::from(10_123u64)),
value: HexU256(U256::from(10_123u64)),
}]
);

Expand Down
18 changes: 9 additions & 9 deletions src/db/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ 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::wrappers::hex_u256::HexU256;
use crate::types::TransactionPriority;

#[derive(Debug, Clone, FromRow)]
Expand All @@ -16,8 +16,8 @@ pub struct UnsentTx {
pub id: String,
pub tx_to: AddressWrapper,
pub data: Vec<u8>,
pub value: U256Wrapper,
pub gas_limit: U256Wrapper,
pub value: HexU256,
pub gas_limit: HexU256,
pub priority: TransactionPriority,
#[sqlx(try_from = "i64")]
pub nonce: u64,
Expand All @@ -33,16 +33,16 @@ pub struct TxForEscalation {
pub id: String,
pub tx_to: AddressWrapper,
pub data: Vec<u8>,
pub value: U256Wrapper,
pub gas_limit: U256Wrapper,
pub value: HexU256,
pub gas_limit: HexU256,
#[sqlx(try_from = "i64")]
pub nonce: u64,
pub blobs: Option<Vec<Vec<u8>>>,
pub key_id: String,
#[sqlx(try_from = "i64")]
pub chain_id: u64,
pub initial_max_fee_per_gas: U256Wrapper,
pub initial_max_priority_fee_per_gas: U256Wrapper,
pub initial_max_fee_per_gas: HexU256,
pub initial_max_priority_fee_per_gas: HexU256,
#[sqlx(try_from = "i64")]
pub escalation_count: usize,
}
Expand All @@ -52,8 +52,8 @@ pub struct ReadTxData {
pub tx_id: String,
pub to: AddressWrapper,
pub data: Vec<u8>,
pub value: U256Wrapper,
pub gas_limit: U256Wrapper,
pub value: HexU256,
pub gas_limit: HexU256,
#[sqlx(try_from = "i64")]
pub nonce: u64,
pub blobs: Option<Vec<Vec<u8>>>,
Expand Down
99 changes: 95 additions & 4 deletions src/new_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use crate::service::Service;
use crate::task_runner::TaskRunner;
use crate::types::{
CreateRelayerRequest, CreateRelayerResponse, NetworkInfo, NewNetworkInfo,
RelayerInfo, RelayerUpdate,
RelayerInfo, RelayerUpdate, SendTxResponse,
};

mod security;
Expand Down Expand Up @@ -252,10 +252,101 @@ impl AdminApi {
}
}

struct ConsumerApi;
struct RelayerApi;

#[OpenApi(prefix_path = "/1/api/")]
impl ConsumerApi {}
impl RelayerApi {
/// Send Transaction
#[oai(path = "/:api_token/tx", method = "post")]
async fn send_tx(
&self,
Data(app): Data<&Arc<App>>,
Path(api_token): Path<ApiKey>,
// Json(req): Json<SendTxRequest>,
) -> Result<Json<SendTxResponse>> {
api_token.validate(app).await?;

// let tx_id = if let Some(id) = req.tx_id {
// id
// } else {
// uuid::Uuid::new_v4().to_string()
// };

// let relayer = app.db.get_relayer(api_token.relayer_id()).await?;

// if !relayer.enabled {
// return Err(ApiError::RelayerDisabled);
// }

// let relayer_queued_tx_count = app
// .db
// .get_relayer_pending_txs(api_token.relayer_id())
// .await?;

// if relayer_queued_tx_count > relayer.max_queued_txs as usize {
// return Err(ApiError::TooManyTransactions {
// max: relayer.max_queued_txs as usize,
// current: relayer_queued_tx_count,
// });
// }

// app.db
// .create_transaction(
// &tx_id,
// req.to,
// req.data.as_ref().map(|d| &d[..]).unwrap_or(&[]),
// req.value,
// req.gas_limit,
// req.priority,
// req.blobs,
// api_token.relayer_id(),
// )
// .await?;

// tracing::info!(tx_id, "Transaction created");

// Ok(Json(SendTxResponse { tx_id }))

todo!()
}

/// Get Transaction
#[oai(path = "/:api_token/tx/:tx_id", method = "get")]
async fn get_tx(
&self,
Data(app): Data<&Arc<App>>,
Path(api_token): Path<ApiKey>,
Path(tx_id): Path<String>,

Check failure on line 319 in src/new_server.rs

View workflow job for this annotation

GitHub Actions / cargo test

unused variable: `tx_id`
) -> Result<Json<SendTxResponse>> {
api_token.validate(app).await?;

todo!()
}

/// Get Transactions
#[oai(path = "/:api_token/txs", method = "get")]
async fn get_txs(
&self,
Data(app): Data<&Arc<App>>,
Path(api_token): Path<ApiKey>,
) -> Result<()> {
api_token.validate(app).await?;

Ok(())
}

/// Relayer RPC
#[oai(path = "/:api_token/rpc", method = "post")]
async fn relayer_rpc(
&self,
Data(app): Data<&Arc<App>>,
Path(api_token): Path<ApiKey>,
) -> Result<()> {
api_token.validate(app).await?;

Ok(())
}
}

struct ServiceApi;

Expand Down Expand Up @@ -292,7 +383,7 @@ impl ServerHandle {

pub async fn spawn_server(app: Arc<App>) -> eyre::Result<ServerHandle> {
let mut api_service = OpenApiService::new(
(AdminApi, ConsumerApi, ServiceApi),
(AdminApi, RelayerApi, ServiceApi),
"Tx Sitter",
version::version!(),
);
Expand Down
23 changes: 23 additions & 0 deletions src/new_server/security.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use poem::Result;
use poem_openapi::{auth, SecurityScheme};

use crate::api_key::ApiKey;
use crate::app::App;

#[derive(SecurityScheme)]
Expand All @@ -23,3 +24,25 @@ impl BasicAuth {
Ok(())
}
}

impl ApiKey {
pub async fn validate(&self, app: impl AsRef<App>) -> Result<()> {
let app = app.as_ref();

let is_authorized = app.is_authorized(self).await.map_err(|err| {
poem::error::Error::from_string(
err.to_string(),
poem::http::StatusCode::INTERNAL_SERVER_ERROR,
)
})?;

if !is_authorized {
return Err(poem::error::Error::from_string(
"Unauthorized".to_string(),
poem::http::StatusCode::UNAUTHORIZED,
));
}

Ok(())
}
}
1 change: 0 additions & 1 deletion src/serde_utils.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
pub mod base64_binary;
pub mod decimal_u256;
42 changes: 0 additions & 42 deletions src/serde_utils/decimal_u256.rs

This file was deleted.

25 changes: 11 additions & 14 deletions src/server/routes/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,17 @@ use crate::api_key::ApiKey;
use crate::app::App;
use crate::db::TxStatus;
use crate::server::ApiError;
use crate::types::wrappers::decimal_u256::DecimalU256;
use crate::types::TransactionPriority;

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SendTxRequest {
pub to: Address,
#[serde(with = "crate::serde_utils::decimal_u256")]
pub value: U256,
pub value: DecimalU256,
#[serde(default)]
pub data: Option<Bytes>,
#[serde(with = "crate::serde_utils::decimal_u256")]
pub gas_limit: U256,
pub gas_limit: DecimalU256,
#[serde(default)]
pub priority: TransactionPriority,
#[serde(default)]
Expand Down Expand Up @@ -49,10 +48,8 @@ pub struct GetTxResponse {
pub to: Address,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data: Option<Bytes>,
#[serde(with = "crate::serde_utils::decimal_u256")]
pub value: U256,
#[serde(with = "crate::serde_utils::decimal_u256")]
pub gas_limit: U256,
pub value: DecimalU256,
pub gas_limit: DecimalU256,
pub nonce: u64,

// Sent tx data
Expand Down Expand Up @@ -115,8 +112,8 @@ pub async fn send_tx(
&tx_id,
req.to,
req.data.as_ref().map(|d| &d[..]).unwrap_or(&[]),
req.value,
req.gas_limit,
req.value.0,
req.gas_limit.0,
req.priority,
req.blobs,
api_token.relayer_id(),
Expand Down Expand Up @@ -160,8 +157,8 @@ pub async fn get_txs(
} else {
Some(tx.data.into())
},
value: tx.value.0,
gas_limit: tx.gas_limit.0,
value: tx.value.into(),
gas_limit: tx.gas_limit.into(),
nonce: tx.nonce,
tx_hash: tx.tx_hash.map(|h| h.0),
status: tx.status.map(GetTxResponseStatus::TxStatus).unwrap_or(
Expand Down Expand Up @@ -192,8 +189,8 @@ pub async fn get_tx(
} else {
Some(tx.data.into())
},
value: tx.value.0,
gas_limit: tx.gas_limit.0,
value: tx.value.into(),
gas_limit: tx.gas_limit.into(),
nonce: tx.nonce,
tx_hash: tx.tx_hash.map(|h| h.0),
status: tx
Expand Down
Loading

0 comments on commit c12a5d3

Please sign in to comment.