Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/collateral #51

Merged
merged 1 commit into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ edition = "2021"
[dependencies]
actix-web = "4.4.0"
argh = "0.1.12"
drift-sdk = { git = "https://github.com/drift-labs/drift-rs", rev = "8384f6" }
drift-sdk = { git = "https://github.com/drift-labs/drift-rs", rev = "6749bcd" }
env_logger = "0.10.1"
futures-util = "0.3.29"
log = "0.4.20"
Expand Down
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ Self hosted API gateway to easily interact with Drift V2 Protocol
- [`GET` SOL Balance](#get-sol-balance)
- [`GET` Margin Info](#get-margin-info)
- [`GET` Leverage](#get-leverage)
- [`GET` Collateral](#get-collateral)
- [`POST` Place Orders](#place-orders)
- [`PATCH` Modify Orders](#modify-orders)
- [`DELETE` Cancel Orders](#cancel-orders)
Expand Down Expand Up @@ -225,6 +226,22 @@ $ curl localhost:8080/v2/leverage
}
```

## Get Collateral
Returns the account's maintenance collateral

```bash
$ curl localhost:8080/v2/collateral
```

**Response**

```json
{
"total":"1661.195815",
"free":"1653.531255"
}
```

## Get Market Info

Returns market details (perps only)
Expand Down
21 changes: 19 additions & 2 deletions src/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ use drift_sdk::{
dlob_client::DLOBClient,
event_subscriber::{try_parse_log, CommitmentConfig},
math::liquidation::{
calculate_liquidation_price_and_unrealized_pnl, calculate_margin_requirements,
calculate_collateral, calculate_liquidation_price_and_unrealized_pnl,
calculate_margin_requirements, MarginCategory,
},
types::{
self, MarketId, MarketType, ModifyOrderParams, RpcSendTransactionConfig, SdkError,
Expand All @@ -21,13 +22,14 @@ use solana_transaction_status::{option_serializer::OptionSerializer, UiTransacti
use std::{borrow::Cow, str::FromStr, sync::Arc};
use thiserror::Error;

use crate::types::UserCollateralResponse;
use crate::{
types::{
get_market_decimals, AllMarketsResponse, CancelAndPlaceRequest, CancelOrdersRequest,
GetOrderbookRequest, GetOrdersRequest, GetOrdersResponse, GetPositionsRequest,
GetPositionsResponse, Market, MarketInfoResponse, ModifyOrdersRequest, Order, OrderbookL2,
PerpPosition, PerpPositionExtended, PlaceOrdersRequest, SolBalanceResponse, SpotPosition,
TxEventsResponse, TxResponse, UserMarginResponse, UserLeverageResponse, PRICE_DECIMALS,
TxEventsResponse, TxResponse, UserLeverageResponse, UserMarginResponse, PRICE_DECIMALS,
},
websocket::map_drift_event_for_account,
Context, LOG_TARGET,
Expand Down Expand Up @@ -227,6 +229,21 @@ impl AppState {
.map_err(|err| ControllerError::Sdk(err))
}

pub async fn get_collateral(
&self,
ctx: Context,
margin_category: Option<MarginCategory>,
) -> GatewayResult<UserCollateralResponse> {
let sub_account = self.resolve_sub_account(ctx.sub_account_id);
calculate_collateral(
&self.client,
&self.client.get_user_account(&sub_account).await?,
margin_category.unwrap_or(MarginCategory::Maintenance),
)
.map(Into::into)
.map_err(|err| ControllerError::Sdk(err))
}

pub async fn get_position_extended(
&self,
ctx: Context,
Expand Down
11 changes: 10 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,14 @@ async fn get_leverage(controller: web::Data<AppState>, ctx: web::Query<Context>)
handle_result(controller.get_leverage(ctx.0).await)
}

#[get("/collateral")]
async fn get_collateral(
controller: web::Data<AppState>,
ctx: web::Query<Context>,
) -> impl Responder {
handle_result(controller.get_collateral(ctx.0, None).await)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
let config: GatewayConfig = argh::from_env();
Expand Down Expand Up @@ -283,7 +291,8 @@ async fn main() -> std::io::Result<()> {
.service(get_tx_events)
.service(get_market_info)
.service(get_margin_info)
.service(get_leverage),
.service(get_leverage)
.service(get_collateral),
)
})
.keep_alive(Duration::from_secs(config.keep_alive_timeout as u64))
Expand Down
18 changes: 18 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
//! - gateway request/responses
//! - wrappers for presenting drift program types with less implementation detail
//!
use drift_sdk::constants::QUOTE_PRECISION;
use drift_sdk::math::liquidation::CollateralInfo;
use drift_sdk::{
constants::{ProgramData, BASE_PRECISION, PRICE_PRECISION},
dlob_client::{L2Level, L2Orderbook},
Expand All @@ -18,6 +20,7 @@ use crate::websocket::AccountEvent;

/// decimal places in price values
pub const PRICE_DECIMALS: u32 = PRICE_PRECISION.ilog10();
pub const QUOTE_DECIMALS: u32 = QUOTE_PRECISION.ilog10();

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -629,6 +632,21 @@ impl From<u128> for UserLeverageResponse {
}
}

#[derive(Serialize, Debug)]
pub struct UserCollateralResponse {
pub total: Decimal,
pub free: Decimal,
}

impl From<CollateralInfo> for UserCollateralResponse {
fn from(value: CollateralInfo) -> Self {
Self {
total: Decimal::from_i128_with_scale(value.total, QUOTE_DECIMALS).normalize(),
free: Decimal::from_i128_with_scale(value.free, QUOTE_DECIMALS).normalize(),
}
}
}

#[cfg(test)]
mod tests {
use drift_sdk::{
Expand Down
Loading