sqlite in coordinator, anyhow result in coordinator, restructuring coordinator, loading env variable, removing cli parsing with clap

This commit is contained in:
f321x
2024-06-24 17:17:01 +00:00
parent 8a8a93e184
commit ad58758e99
4 changed files with 689 additions and 432 deletions

File diff suppressed because it is too large Load Diff

View File

@ -7,11 +7,10 @@ edition = "2021"
anyhow = "1.0.86"
axum = "0.7.5"
bdk = "0.29.0"
clap = { version = "4.5.4", features = ["derive", "cargo"] }
dotenv = "0.15.0"
frost-secp256k1 = "1.0.0"
reqwest = { version = "0.12.4", features = ["blocking", "json"] }
serde = "1.0.203"
sqlx = { version = "0.7.4", features = ["runtime-tokio", "sqlite"] }
tokio = "1.38.0"
[profile.release]

View File

@ -2,59 +2,89 @@ mod api;
use super::*;
use api::{BondRequirementResponse, BondSubmissionRequest, OrderActivatedResponse, OrderRequest};
use axum::{routing::post, Json, Router};
use axum::{
http::StatusCode, response::IntoResponse, response::Response, routing::post, Extension, Json,
Router,
};
use sqlx::sqlite::SqliteLockingMode;
use std::net::SocketAddr;
use tokio::net::TcpListener;
// Handler function to process the received data
async fn receive_order(Json(order): Json<OrderRequest>) -> Json<BondRequirementResponse> {
// Print the received data to the console
println!("Received order: {:?}", order);
async fn receive_order(
Extension(state): Extension<Arc<Coordinator>>,
Json(order): Json<OrderRequest>,
) -> Result<Json<BondRequirementResponse>, AppError> {
// Connecting to SQLite database
let db_pool = state.db_pool.clone();
let mut conn = db_pool.acquire().await.unwrap();
// Access individual fields
// let robohash = &order.robohash_hex;
let amount = order.amount_satoshi;
// let order_type = &order.is_buy_order;
let bond_ratio = order.bond_ratio;
// let offer_duration= order.offer_duration_ts;
// sqlx::query!(
// "INSERT INTO orders (field1, field2) VALUES (?, ?)",
// order.field1,
// order.field2
// )
// Create a response struct
let response = BondRequirementResponse {
bond_address: "Order received successfully".to_string(),
// Add any other fields you want to include in your response
locking_amount_sat: (amount * bond_ratio as u64 / 100),
};
// Return the response as JSON
Json(response)
println!("Coordinator received new offer: {:?}", order);
Ok(Json(BondRequirementResponse {
bond_address: bond_address,
locking_amount_sat: order.amount_satoshi * order.bond_ratio as u64 / 100,
}))
}
async fn submit_maker_bond(
Json(payload): Json<BondSubmissionRequest>,
) -> Json<OrderActivatedResponse> {
// Process the payload
// For now, we'll just return a dummy success response
let response = OrderActivatedResponse {
bond_locked_until_timestamp: 0 as u128,
order_id_hex: "Bond submitted successfully".to_string(),
};
// async fn submit_maker_bond(
// Json(payload): Json<BondSubmissionRequest>,
// ) -> Result<Json<OrderActivatedResponse>, AppError> {
// // Process the payload
// // For now, we'll just return a dummy success response
// let response = OrderActivatedResponse {
// bond_locked_until_timestamp: 0 as u128,
// order_id_hex: "Bond submitted successfully".to_string(),
// };
// Create the JSON response
Json(response)
}
// // Create the JSON response
// Json(response)
// }
pub async fn api_server() -> Result<()> {
pub async fn api_server(coordinator: Coordinator) -> Result<()> {
let app = Router::new()
.route("/create-offer", post(receive_order))
.route("/submit-maker-bond", post(submit_maker_bond));
// .route("/submit-maker-bond", post(submit_maker_bond));
.layer(Extension(coordinator));
// add other routes here
// Run the server on localhost:9999
let addr = SocketAddr::from(([127, 0, 0, 1], 9999));
println!("Listening on {}", addr);
let tcp = TcpListener::bind(&addr).await.unwrap();
axum::serve(tcp, app).await?;
println!("Listening on {}", addr);
Ok(())
}
// ANYHOW ERROR HANDLING
// --------------
// Make our own error that wraps `anyhow::Error`.
struct AppError(anyhow::Error);
// Tell axum how to convert `AppError` into a response.
impl IntoResponse for AppError {
fn into_response(self) -> Response {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {}", self.0),
)
.into_response()
}
}
// This enables using `?` on functions that return `Result<_, anyhow::Error>` to turn them into
// `Result<_, AppError>`. That way you don't need to do that manually.
impl<E> From<E> for AppError
where
E: Into<anyhow::Error>,
{
fn from(err: E) -> Self {
Self(err.into())
}
}

View File

@ -1,17 +1,34 @@
mod communication;
mod coordinator;
use anyhow::{anyhow, Result};
use anyhow::{anyhow, Error, Result};
use communication::api_server;
use dotenv::dotenv;
use serde::{Deserialize, Serialize};
use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite};
use std::env;
use std::sync::Arc;
#[derive(Clone, Debug)]
pub struct Coordinator {
pub db_pool: Arc<Pool<Sqlite>>,
}
// populate .env with values before starting
#[tokio::main]
async fn main() -> Result<()> {
dotenv().ok();
// Initialize the database pool
let db_pool = SqlitePoolOptions::new()
.connect("sqlite:./db/trades.db")
.await
.unwrap();
let shared_db_pool: Arc<sqlx::Pool<sqlx::Sqlite>> = Arc::new(db_pool);
api_server().await?;
let coordinator = Coordinator {
db_pool: shared_db_pool,
};
api_server(coordinator).await?;
Ok(())
}