Skip to content

Commit

Permalink
tx events endpoint returns error code and status (#96)
Browse files Browse the repository at this point in the history
* tx events endpoint returns error codes and status
* update readme
  • Loading branch information
jordy25519 authored Dec 9, 2024
1 parent 5aa8c6a commit 1b2cca8
Show file tree
Hide file tree
Showing 6 changed files with 75 additions and 29 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,4 @@ jobs:
run: |
cargo -V
cp libdrift_ffi_sys.so ./target/debug/deps
cargo test --all -- --test-threads=3
cargo test --all -- --test-threads=2
25 changes: 23 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,14 @@ the provided user will be returned.
$ curl localhost:8080/v2/transactionEvent/5JuobpnzPzwgdha4d7FpUHpvkinhyXCJhnPPkwRkdAJ1REnsJPK82q7C3vcMC4BhCQiABR4wfdbaa9StMDkCd9y5?subAccountId=0
```

A successful tx must bed confirm onchain and also execute successfully, the following table shows the possible responses from this endpoint:

| | execute ok | execute fail |
|-------------------|------------------------------------------|-------------------------|
| confirm ok | `200, {"success": true, "events": [...] }` | `200, { "success": false, "error": "msg" }` |
| confirm fail | `404` | `404`


**Response**

A response with a fill belonging to sub-account 0
Expand All @@ -496,7 +504,8 @@ A response with a fill belonging to sub-account 0
"signature": "5JuobpnzPzwgdha4d7FpUHpvkinhyXCJhnPPkwRkdAJ1REnsJPK82q7C3vcMC4BhCQiABR4wfdbaa9StMDkCd9y5"
}
}
]
],
"success":true
}
```

Expand All @@ -513,9 +522,21 @@ A response for a transaction that was found, but doesn't contain any events for

```json
{
"events": []
"events": [],
"success":true
}
```

A response for a transaction that was confirmed onchain but failed execution e.g. due to exceeding slippage

```json
{
"events": [],
"error": "program error: 6015",
"success": false
}
```
full list of error codes [here](https://drift-labs.github.io/v2-teacher/#errors)

### Get SOL balance
Return the on-chain SOL balance of the transaction signer (`DRIFT_GATEWAY_KEY`)
Expand Down
40 changes: 29 additions & 11 deletions src/controller.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,16 +409,15 @@ impl AppState {
.into_iter()
.filter(|o| {
if let Some(GetOrdersRequest { ref market }) = req {
o.market_index == market.market_index
&& o.market_type == market.market_type.into()
o.market_index == market.market_index && o.market_type == market.market_type
} else {
true
}
})
.map(|o| {
let base_decimals = get_market_decimals(
self.client.program_data(),
Market::new(o.market_index, o.market_type.into()),
Market::new(o.market_index, o.market_type),
);
Order::from_sdk_order(o, base_decimals)
})
Expand Down Expand Up @@ -586,17 +585,36 @@ impl AppState {
OptionSerializer::None | OptionSerializer::Skip => {}
}
}
Ok(TxEventsResponse::new(events))
Ok(TxEventsResponse::new(events, true, None))
}
Err(err) => {
let tx_error = err.get_transaction_error();
warn!(target: LOG_TARGET, "failed to get transaction: {err:?}, tx_error: {tx_error:?}");
if matches!(err.kind(), ClientErrorKind::SerdeJson(_)) {
Err(ControllerError::TxNotFound {
warn!(target: LOG_TARGET, "failed to get transaction: {err:?}, tx_error: {err:?}");
match err.kind() {
ClientErrorKind::SerdeJson(_) => Err(ControllerError::TxNotFound {
tx_sig: tx_sig.to_string(),
})
} else {
Ok(TxEventsResponse::default())
}),
_ => {
let err: SdkError = err.into();
if let Some(code) = err.to_anchor_error_code() {
return Ok(TxEventsResponse::new(
Default::default(),
false,
Some(format!("program error: {code}")),
));
}
if err.to_out_of_sol_error().is_some() {
return Ok(TxEventsResponse::new(
Default::default(),
false,
Some("ouf of sol, top-up account".into()),
));
}
Ok(TxEventsResponse::new(
Default::default(),
false,
Some(err.to_string()),
))
}
}
}
}
Expand Down
8 changes: 5 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,8 @@ mod tests {
"txIdx": 6
}
}
]
],
"success": true,
});
assert_eq!(events, expect_body, "incorrect resp body");
}
Expand Down Expand Up @@ -664,13 +665,14 @@ mod tests {
let body_bytes = test::read_body(resp).await;
let events: serde_json::Value = serde_json::from_slice(&body_bytes).unwrap();
let expect_body = json!({
"events": []
"events": [],
"success": true
});
assert_eq!(events, expect_body, "incorrect resp body");
}

#[actix_web::test]
async fn get_tx_events_doesnt_exit() {
async fn get_tx_events_doesnt_exist() {
let controller = setup_controller(Some(
Pubkey::from_str("8kEGX9UNrtKATDjL3ED1dmURzyASsXDe9vGzncMhsTN2").expect("pubkey"),
))
Expand Down
15 changes: 11 additions & 4 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ impl Order {

Order {
market_index: value.market_index,
market_type: value.market_type.into(),
market_type: value.market_type,
price: Decimal::new(value.price as i64, PRICE_DECIMALS),
amount: Decimal::new(value.base_asset_amount as i64 * to_sign, base_decimals),
filled: Decimal::new(value.base_asset_amount_filled as i64, base_decimals),
Expand Down Expand Up @@ -313,7 +313,7 @@ impl PlaceOrder {

OrderParams {
market_index: self.market.market_index,
market_type: self.market.market_type.into(),
market_type: self.market.market_type,
order_type: self.order_type,
base_asset_amount: base_amount,
direction: if self.amount.is_sign_negative() {
Expand Down Expand Up @@ -494,11 +494,18 @@ impl TxResponse {
#[derive(Serialize, Deserialize, Debug, Default)]
pub struct TxEventsResponse {
events: Vec<AccountEvent>,
success: bool,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
}

impl TxEventsResponse {
pub fn new(events: Vec<AccountEvent>) -> Self {
Self { events }
pub fn new(events: Vec<AccountEvent>, success: bool, error: Option<String>) -> Self {
Self {
events,
success,
error,
}
}
}

Expand Down
14 changes: 6 additions & 8 deletions src/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ impl OrderWithDecimals {
order_id: value.order_id,
market_index: value.market_index,
order_type: value.order_type,
market_type: value.market_type.into(),
market_type: value.market_type,
user_order_id: value.user_order_id,
direction: value.direction,
reduce_only: value.reduce_only,
Expand Down Expand Up @@ -502,10 +502,8 @@ pub(crate) fn map_drift_event_for_account(
tx_idx,
ts,
} => {
let decimals = get_market_decimals(
program_data,
Market::new(*market_index, (*market_type).into()),
);
let decimals =
get_market_decimals(program_data, Market::new(*market_index, *market_type));
let fill = if *maker == Some(sub_account_address) {
Some(AccountEvent::fill(
maker_side.unwrap(),
Expand All @@ -519,7 +517,7 @@ pub(crate) fn map_drift_event_for_account(
signature,
*tx_idx,
*market_index,
(*market_type).into(),
*market_type,
(*maker).map(|x| x.to_string()),
Some(*maker_order_id),
Some(*maker_fee),
Expand All @@ -540,7 +538,7 @@ pub(crate) fn map_drift_event_for_account(
signature,
*tx_idx,
*market_index,
(*market_type).into(),
*market_type,
(*maker).map(|x| x.to_string()),
Some(*maker_order_id),
Some(*maker_fee),
Expand Down Expand Up @@ -614,7 +612,7 @@ pub(crate) fn map_drift_event_for_account(
} => {
let decimals = get_market_decimals(
program_data,
Market::new(order.market_index, order.market_type.into()),
Market::new(order.market_index, order.market_type),
);
(
Channel::Orders,
Expand Down

0 comments on commit 1b2cca8

Please sign in to comment.