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

Add delegated mode #12

Merged
merged 1 commit into from
Dec 21, 2023
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
56 changes: 28 additions & 28 deletions Cargo.lock

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

15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Self hosted API gateway to easily interact with Drift V2 Protocol
# build
cargo build --release

# configure the gateway wallet key
# configure the gateway signing key
export DRIFT_GATEWAY_KEY=</PATH/TO/KEY.json | seedBase58>

# '--dev' to toggle devnet markets (default is mainnet)
Expand All @@ -27,7 +27,7 @@ docker run -e DRIFT_GATEWAY_KEY=<BASE58_SEED> -p 8080:8080 drift-gateway https:/

## Usage
```bash
Usage: drift-gateway <rpc_host> [--dev] [--host <host>] [--port <port>]
Usage: drift-gateway <rpc_host> [--dev] [--host <host>] [--port <port>] [--delegate <delegate>]

Drift gateway server

Expand All @@ -38,6 +38,8 @@ Options:
--dev run in devnet mode
--host gateway host address
--port gateway port
--delegate use delegated signing mode, provide the delegator's pubkey
e.g. `--delegate <DELEGATOR_PUBKEY>`
--help display usage information
```

Expand Down Expand Up @@ -178,7 +180,7 @@ get positions by market
```bash
$ curl -X GET \
-H 'content-type: application/json' \
-d '{"marketIndex":0,"marketType":"perp"} \
-d '{"marketIndex":0,"marketType":"perp"}' \
localhost:8080/v2/positions
```

Expand Down Expand Up @@ -301,6 +303,13 @@ $ curl localhost:8080/v2/orders/cancelAndPlace -X POST -H 'content-type: applica
}'
```

## Delegated Signing Mode
Passing the `--delegate <DELEGATOR_PUBKEY>` flag will instruct the gateway to run in delegated signing mode.
In this mode, the gateway will act for `DELEGATOR_PUBKEY` and sub-accounts while signing with the key provided via `DRIFT_GATEWAY_KEY`.

Use the drift UI or Ts/Python SDK to assign a delegator key.
see [Delegated Accounts](https://docs.drift.trade/delegated-accounts) for more information.

## Sub-account Switching
By default the gateway uses the drift sub-account (index 0)
A `subAccountId` URL query parameter may be supplied to switch the sub-account per request basis.
Expand Down
20 changes: 16 additions & 4 deletions src/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,20 +36,32 @@ pub struct AppState {
}

impl AppState {
/// Configured drift signing address + fee payer
pub fn authority(&self) -> Pubkey {
/// Configured drift authority address
pub fn authority(&self) -> &Pubkey {
self.wallet.authority()
}
/// Configured drift signing address
pub fn signer(&self) -> Pubkey {
self.wallet.signer()
}
pub fn default_sub_account(&self) -> Pubkey {
self.wallet.default_sub_account()
}
pub async fn new(secret_key: &str, endpoint: &str, devnet: bool) -> Self {
pub async fn new(
secret_key: &str,
endpoint: &str,
devnet: bool,
delegate: Option<Pubkey>,
) -> Self {
let context = if devnet {
Context::DevNet
} else {
Context::MainNet
};
let wallet = Wallet::try_from_str(secret_key).expect("valid key");
let mut wallet = Wallet::try_from_str(secret_key).expect("valid key");
if let Some(authority) = delegate {
wallet.to_delegated(authority);
}
let account_provider = WsAccountProvider::new(endpoint).await.expect("ws connects");
let client = DriftClient::new(endpoint, account_provider)
.await
Expand Down
33 changes: 26 additions & 7 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ use argh::FromArgs;
use log::{error, info};

use controller::{AppState, ControllerError};
use drift_sdk::Pubkey;
use serde_json::json;
use std::str::FromStr;
use types::{
CancelAndPlaceRequest, CancelOrdersRequest, GetOrderbookRequest, ModifyOrdersRequest,
PlaceOrdersRequest,
Expand Down Expand Up @@ -135,17 +137,30 @@ async fn main() -> std::io::Result<()> {
.filter_level(log::LevelFilter::Info)
.init();
let secret_key = std::env::var("DRIFT_GATEWAY_KEY").expect("missing DRIFT_GATEWAY_KEY");
let state = AppState::new(secret_key.as_str(), &config.rpc_host, config.dev).await;
let delegate = config
.delegate
.map(|ref x| Pubkey::from_str(x).expect("valid pubkey"));
let state = AppState::new(secret_key.as_str(), &config.rpc_host, config.dev, delegate).await;

info!(
"🏛️ gateway listening at http://{}:{}",
config.host, config.port
);
info!(
"🪪: authority: {:?}, default sub-account: {:?}",
state.authority(),
state.default_sub_account()
);

if delegate.is_some() {
info!(
"🪪: authority: {:?}, default sub-account: {:?}, 🔑 delegate: {:?}",
state.authority(),
state.default_sub_account(),
state.signer(),
);
} else {
info!(
"🪪: authority: {:?}, default sub-account: {:?}",
state.authority(),
state.default_sub_account()
);
}

HttpServer::new(move || {
App::new().app_data(web::Data::new(state.clone())).service(
Expand Down Expand Up @@ -180,6 +195,10 @@ struct GatewayConfig {
/// gateway port
#[argh(option, default = "8080")]
port: u16,
/// use delegated signing mode, provide the delegator's pubkey
/// e.g. `--delegate <DELEGATOR_PUBKEY>`
#[argh(option)]
delegate: Option<String>,
}

fn handle_result<T>(result: Result<T, ControllerError>) -> Either<HttpResponse, Json<T>> {
Expand Down Expand Up @@ -239,7 +258,7 @@ mod tests {
}

async fn setup_controller() -> AppState {
AppState::new(&get_seed(), TEST_ENDPOINT, true).await
AppState::new(&get_seed(), TEST_ENDPOINT, true, None).await
}

#[actix_web::test]
Expand Down
Loading