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/emulate mode #20

Merged
merged 2 commits into from
Jan 25, 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
18 changes: 14 additions & 4 deletions Cargo.lock

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

18 changes: 13 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export DRIFT_GATEWAY_KEY=</PATH/TO/KEY.json | seedBase58>
drift-gateway --dev https://api.devnet.solana.com

# or mainnet
# NB: `api.mainnet-beta.solana.com`` cannot be used due to rate limits on certain RPC calls
# NB: `api.mainnet-beta.solana.com` cannot be used due to rate limits on certain RPC calls
drift-gateway https://rpc-provider.example.com
```

Expand All @@ -28,7 +28,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>] [--delegate <delegate>]
Usage: drift-gateway <rpc_host> [--dev] [--host <host>] [--port <port>] [--delegate <delegate>] [--emulate <emulate>]

Drift gateway server

Expand All @@ -39,8 +39,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>`
--delegate use delegated signing mode, provide the delegator pubkey
--emulate run the gateway in read-only mode for given authority pubkey
--help display usage information
```

Expand Down Expand Up @@ -448,10 +448,18 @@ this event may be safely ignored, it is added in an effort to help order life-cy
}
```

## Emulation Mode
Passing the `--emulate <EMULATED_PUBBKEY>` flag will instruct the gateway to run in read-only mode.

The gateway will receive all events, positions, etc. as normal but be unable to send transactions.

note therefore `DRIFT_GATEWAY_KEY` is not required to be set.


## 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`.
In this mode, the gateway will act for `DELEGATOR_PUBKEY` and sub-accounts while signing with the key provided via `DRIFT_GATEWAY_KEY` (i.e delegate 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.
Expand Down
39 changes: 28 additions & 11 deletions src/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,21 +49,13 @@ impl AppState {
pub fn default_sub_account(&self) -> Pubkey {
self.wallet.default_sub_account()
}
pub async fn new(
secret_key: &str,
endpoint: &str,
devnet: bool,
delegate: Option<Pubkey>,
) -> Self {
pub async fn new(endpoint: &str, devnet: bool, wallet: Wallet) -> Self {
let context = if devnet {
Context::DevNet
} else {
Context::MainNet
};
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(context, endpoint, account_provider)
.await
Expand Down Expand Up @@ -316,7 +308,7 @@ impl AppState {
Cow::Borrowed(account_data),
)
.payer(self.wallet.signer())
.modify_orders(params)
.modify_orders(params.as_slice())
.build();

self.client
Expand Down Expand Up @@ -373,3 +365,28 @@ fn build_cancel_ix(
Ok(builder.cancel_all_orders())
}
}

/// Initialize a wallet for controller, possible valid configs:
///
/// 1) keypair
/// 2) keypair + delegated
/// 3) emulation/RO mode
pub fn create_wallet(
secret_key: Option<String>,
emulate: Option<Pubkey>,
delegate: Option<Pubkey>,
) -> Wallet {
match (&secret_key, emulate, delegate) {
(Some(secret_key), _, delegate) => {
let mut wallet = Wallet::try_from_str(secret_key).expect("valid key");
if let Some(authority) = delegate {
wallet.to_delegated(authority);
}
wallet
}
(None, Some(emulate), None) => Wallet::read_only(emulate),
_ => {
panic!("expected 'DRIFT_GATEWAY_KEY' or --emulate <pubkey>");
}
}
}
24 changes: 18 additions & 6 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ use actix_web::{
App, Either, HttpResponse, HttpServer, Responder,
};
use argh::FromArgs;
use log::{error, info};
use log::{error, info, warn};

use controller::{AppState, ControllerError};
use controller::{create_wallet, AppState, ControllerError};
use drift_sdk::Pubkey;
use serde_json::json;
use std::{borrow::Borrow, str::FromStr, sync::Arc};
Expand Down Expand Up @@ -137,11 +137,15 @@ async fn main() -> std::io::Result<()> {
env_logger::Builder::from_default_env()
.filter_level(log::LevelFilter::Info)
.init();
let secret_key = std::env::var("DRIFT_GATEWAY_KEY").expect("missing DRIFT_GATEWAY_KEY");
let secret_key = std::env::var("DRIFT_GATEWAY_KEY");
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;
let emulate = config
.emulate
.map(|ref x| Pubkey::from_str(x).expect("valid pubkey"));
let wallet = create_wallet(secret_key.ok(), emulate, delegate);
let state = AppState::new(&config.rpc_host, config.dev, wallet).await;

info!(
"🏛️ gateway listening at http://{}:{}",
Expand All @@ -161,6 +165,9 @@ async fn main() -> std::io::Result<()> {
state.authority(),
state.default_sub_account()
);
if emulate.is_some() {
warn!("using emulation mode, tx signing unavailable");
}
}

let client = Box::leak(Box::new(Arc::clone(state.client.borrow())));
Expand Down Expand Up @@ -206,9 +213,11 @@ struct GatewayConfig {
#[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>,
/// run the gateway in read-only mode for given authority pubkey
#[argh(option)]
emulate: Option<String>,
}

fn handle_result<T>(result: Result<T, ControllerError>) -> Either<HttpResponse, Json<T>> {
Expand Down Expand Up @@ -265,6 +274,8 @@ mod tests {

use crate::types::Market;

use self::controller::create_wallet;

use super::*;

const TEST_ENDPOINT: &str = "https://api.devnet.solana.com";
Expand All @@ -276,7 +287,8 @@ mod tests {
}

async fn setup_controller() -> AppState {
AppState::new(&get_seed(), TEST_ENDPOINT, true, None).await
let wallet = create_wallet(Some(get_seed()), None, None);
AppState::new(TEST_ENDPOINT, true, wallet).await
}

#[actix_web::test]
Expand Down
Loading