Skip to content

Commit

Permalink
Fix: Autoswap rework
Browse files Browse the repository at this point in the history
  • Loading branch information
RichoKD committed Dec 19, 2024
1 parent 2e57b4b commit 0e0bdbf
Show file tree
Hide file tree
Showing 5 changed files with 153 additions and 102 deletions.
149 changes: 149 additions & 0 deletions src/http/auto_swap.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
use std::str::FromStr;

use super::types::{
AutoSwapRequest, AutoSwapResponse, SubscriptionData, SwapSubscriptionFromTokenData,
};
use crate::api_error::ApiError;
use crate::config::env_var;
use crate::AppState;
use axum::{extract::State, Json};
// use serde_json::{json, Value};

use starknet::{
accounts::{Account, ExecutionEncoding, SingleOwnerAccount},
core::{
chain_id,
types::{Call, Felt},
utils::get_selector_from_name,
},
providers::{
jsonrpc::{HttpTransport, JsonRpcClient},
Url,
},
signers::{LocalWallet, SigningKey},
};

async fn call_contract(from: &str, to: &str, value: f64) {
let provider = JsonRpcClient::new(HttpTransport::new(
Url::parse(&env_var("STARKNET_RPC_URL")).unwrap(),
));

let private_key =
Felt::from_hex(env_var("PRIVATE_KEY").trim()).expect("Invalid PRIVATE_KEY format");

// Initialize the wallet
let signer = LocalWallet::from(SigningKey::from_secret_scalar(private_key));
// Initialize the account
// println!("Account address: {}", private_key);

let id: Felt = match env_var("APP_ENVIRONMENT").as_str() {
"production" => chain_id::MAINNET,
_ => chain_id::SEPOLIA,
};

let account_address = Felt::from_str(&env_var("OWNER_ADDRESS"));

// println!("Account address: {}", account_address);

let account = SingleOwnerAccount::new(
provider,
signer,
account_address.unwrap(),
id,
ExecutionEncoding::New,
);

let calldata = vec![
Felt::from_hex(from).unwrap(),
Felt::from_hex(to).unwrap(),
Felt::from(value as i128),
];

let contract_address = Felt::from_hex(env_var("AUTOSWAP_CONTRACT_ADDRESS").as_str()).unwrap();

let call = Call {
to: contract_address,
selector: get_selector_from_name("auto_swap").unwrap(),
calldata,
};

match account.execute_v3(vec![call]).send().await {
Ok(response) => {
println!(
"Call successful! Transaction hash: {}",
response.transaction_hash
);
}
Err(e) => {
eprintln!("Error during call: {}", e);
}
}
}

pub async fn auto_swap(
State(app_state): State<AppState>,
Json(payload): Json<AutoSwapRequest>,
) -> Result<Json<AutoSwapResponse>, ApiError> {
// validate_address(&payload.from)?;
// validate_address(&payload.to);
if !payload.from.starts_with("0x") && payload.from.len() != 42 {
return Err(ApiError::InvalidRequest(
"Invalid 'from' address format".to_string(),
));
}
if !payload.to.starts_with("0x") && payload.to.len() != 42 {
return Err(ApiError::InvalidRequest(
"Invalid 'to' address format".to_string(),
));
}

// println!("Payload: {:#?}", payload);

let row: SubscriptionData = sqlx::query_as::<_, SubscriptionData>(
r#"
SELECT
wallet_address,
to_token,
is_active,
FROM swap_subscription
WHERE wallet_address = $1
"#,
)
.bind(&payload.to)
.fetch_one(&app_state.db.pool)
.await
.map_err(ApiError::DatabaseError)?;

if !row.is_active {
return Err(ApiError::InvalidRequest(
"Subscription is not active".to_string(),
));
}

let row2: SwapSubscriptionFromTokenData = sqlx::query_as::<_, SwapSubscriptionFromTokenData>(
r#"
SELECT
wallet_address,
from_token,
percentage
FROM swap_subscription
WHERE wallet_address = $1
"#,
)
.bind(row.wallet_address)
.fetch_one(&app_state.db.pool)
.await
.map_err(ApiError::DatabaseError)?;

call_contract(
&row2.from_token,
&payload.to,
(row2.percentage as f64 / 100.0) * payload.value as f64,
)
.await;

Ok(Json(AutoSwapResponse {
status: "success".to_string(),
message: "Auto swap started".to_string(),
}))
}
2 changes: 2 additions & 0 deletions src/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use axum::{
Router,
};
mod activity_log_retrieval;
mod auto_swap;
mod health_check;
mod percentage_update;
mod subscription;
Expand All @@ -27,4 +28,5 @@ pub fn router() -> Router<AppState> {
"/update-percentage",
post(percentage_update::update_percentage),
)
.route("/auto-swap", post(auto_swap::auto_swap))
}
14 changes: 2 additions & 12 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use autoswappr_backend::{service::auto_swap::swap, telemetry, Configuration, Db};
use tokio::{net::TcpListener, task};
use autoswappr_backend::{telemetry, Configuration, Db};
use tokio::net::TcpListener;

#[tokio::main]
async fn main() {
Expand All @@ -23,16 +23,6 @@ async fn main() {
tracing::debug!("Running Migrations");
db.migrate().await.expect("Failed to run migrations");

tracing::info!("Running swap service");
task::spawn(async move {
if let Err(e) = swap().await {
tracing::error!("Swap function failed: {}", e);
Err(e) // Return the error
} else {
Ok(()) // Return Ok if no error
}
});

// Listen for requests on specified port.
tracing::info!("Starting server on {}", config.listen_address);
let listener = TcpListener::bind(&config.listen_address)
Expand Down
89 changes: 0 additions & 89 deletions src/service/auto_swap.rs

This file was deleted.

1 change: 0 additions & 1 deletion src/service/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
pub mod auto_swap;
pub mod transaction_logs;

0 comments on commit 0e0bdbf

Please sign in to comment.