Skip to content

Commit

Permalink
funds-manager: handlers: Handle quote fetch and execution
Browse files Browse the repository at this point in the history
  • Loading branch information
joeykraut committed Aug 9, 2024
1 parent cf43283 commit 46d592d
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 26 deletions.
2 changes: 1 addition & 1 deletion funds-manager/funds-manager-api/src/serialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub(crate) mod address_string_serialization {

/// Serialize an address to a string
pub fn serialize<S: Serializer>(address: &Address, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&address.to_string())
s.serialize_str(&format!("{address:#x}"))
}

/// Deserialize a string to an address
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

use std::{error::Error, fmt::Display};

use warp::reject::Reject;

/// An error returned by the execution client
#[derive(Debug, Clone)]
pub enum ExecutionClientError {
Expand Down Expand Up @@ -44,8 +46,8 @@ impl Display for ExecutionClientError {
write!(f, "{}", msg)
}
}

impl Error for ExecutionClientError {}
impl Reject for ExecutionClientError {}

impl From<reqwest::Error> for ExecutionClientError {
fn from(e: reqwest::Error) -> Self {
Expand Down
23 changes: 15 additions & 8 deletions funds-manager/funds-manager-server/src/execution_client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ use ethers::{
providers::{Http, Provider},
signers::LocalWallet,
};
use http::StatusCode;
use reqwest::{Client, Url};
use serde::Deserialize;
use tracing::error;

use self::error::ExecutionClientError;

Expand Down Expand Up @@ -71,14 +73,19 @@ impl ExecutionClient {
params: &[(&str, &str)],
) -> Result<T, ExecutionClientError> {
let url = self.build_url(endpoint, params)?;
self.http_client
.get(url)
.header(API_KEY_HEADER, &self.api_key)
.send()
.await?
.json::<T>()
.await
.map_err(ExecutionClientError::http)
let response =
self.http_client.get(url).header(API_KEY_HEADER, &self.api_key).send().await?;

let status = response.status();
if status != StatusCode::OK {
let body = response.text().await?;
error!("Unexpected status code: {status}\nbody: {body}");
return Err(ExecutionClientError::http(format!(
"Unexpected status code: {status}\nbody: {body}"
)));
}

response.json::<T>().await.map_err(ExecutionClientError::http)
}

/// Get an instance of a signer middleware with the http provider attached
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use ethers::{
use funds_manager_api::quoters::ExecutionQuote;
use tracing::info;

use crate::helpers::ERC20;
use crate::helpers::{TransactionHash, ERC20};

use super::{error::ExecutionClientError, ExecutionClient};

Expand All @@ -20,7 +20,7 @@ impl ExecutionClient {
&self,
quote: ExecutionQuote,
wallet: LocalWallet,
) -> Result<(), ExecutionClientError> {
) -> Result<TransactionHash, ExecutionClientError> {
// Approve the necessary ERC20 allowance
self.approve_erc20_allowance(
quote.sell_token_address,
Expand All @@ -32,8 +32,9 @@ impl ExecutionClient {

// Execute the swap
let receipt = self.execute_swap_tx(quote, wallet).await?;
info!("Swap executed at {}", receipt.transaction_hash);
Ok(())
let tx_hash = receipt.transaction_hash;
info!("Swap executed at {tx_hash}");
Ok(tx_hash)
}

/// Approve an erc20 allowance
Expand Down
36 changes: 25 additions & 11 deletions funds-manager/funds-manager-server/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ use funds_manager_api::hot_wallets::{
TransferToVaultRequest, WithdrawToHotWalletRequest,
};
use funds_manager_api::quoters::{
DepositAddressResponse, ExecuteSwapRequest, GetExecutionQuoteRequest, WithdrawFundsRequest,
DepositAddressResponse, ExecuteSwapRequest, ExecuteSwapResponse, GetExecutionQuoteRequest,
GetExecutionQuoteResponse, WithdrawFundsRequest,
};
use itertools::Itertools;
use serde_json::json;
Expand Down Expand Up @@ -117,22 +118,35 @@ pub(crate) async fn get_deposit_address_handler(

/// Handler for getting an execution quote
pub(crate) async fn get_execution_quote_handler(
_quote_request: GetExecutionQuoteRequest,
_server: Arc<Server>,
req: GetExecutionQuoteRequest,
server: Arc<Server>,
) -> Result<Json, warp::Rejection> {
// TODO: Implement this handler
println!("Getting execution quote");
Ok(warp::reply::json(&"Quote fetched"))
// Fetch the quoter hot wallet information
let vault = DepositWithdrawSource::Quoter.vault_name();
let hot_wallet = server.custody_client.get_hot_wallet_by_vault(vault).await?;
let recipient = format!("0x{}", hot_wallet.address);
let quote = server
.execution_client
.get_quote(&req.buy_token_address, &req.sell_token_address, req.sell_amount, &recipient)
.await
.map_err(|e| warp::reject::custom(ApiError::InternalError(e.to_string())))?;

let resp = GetExecutionQuoteResponse { quote };
Ok(warp::reply::json(&resp))
}

/// Handler for executing a swap
pub(crate) async fn execute_swap_handler(
_swap_request: ExecuteSwapRequest,
_server: Arc<Server>,
req: ExecuteSwapRequest,
server: Arc<Server>,
) -> Result<Json, warp::Rejection> {
// TODO: Implement this handler
println!("Executing swap");
Ok(warp::reply::json(&"Swap executed"))
let vault = DepositWithdrawSource::Quoter.vault_name();
let hot_wallet = server.custody_client.get_hot_wallet_by_vault(vault).await?;
let wallet = server.custody_client.get_hot_wallet_private_key(&hot_wallet.address).await?;

let tx = server.execution_client.execute_swap(req.quote, wallet).await?;
let resp = ExecuteSwapResponse { tx_hash: tx.to_string() };
Ok(warp::reply::json(&resp))
}

// --- Gas --- //
Expand Down
5 changes: 4 additions & 1 deletion funds-manager/funds-manager-server/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@

use aws_config::SdkConfig;
use aws_sdk_secretsmanager::client::Client as SecretsManagerClient;
use ethers::contract::abigen;
use ethers::{contract::abigen, types::H256};
use renegade_util::err_str;

use crate::error::FundsManagerError;

/// A readable type alias for a transaction hash
pub type TransactionHash = H256;

// ---------
// | ERC20 |
// ---------
Expand Down

0 comments on commit 46d592d

Please sign in to comment.