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

End simulation endpoint #12

Merged
merged 5 commits into from
Jul 15, 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
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,13 +146,28 @@ Example response:
"exitReason": "Return"
}]
```

Notes:

- `chainId` must be the same in all transactions.
- `blockNumber` can be included and incremented when a multi-block simulation is required, or omitted in all transactions to use latest.


### DELETE /api/v1/simulate-stateful/{statefulSimulationId}

Ends a current stateful simulation, freeing associated memory.

[See the full request and response types below.](#types)

Example response:

```json
{
"success": true
}
```



### Authentication

If you set an `API_KEY` environment variable then all calls to the API must be accompanied by a `X-API-KEY` header which contains this API Key.
Expand Down
10 changes: 9 additions & 1 deletion src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ pub struct InvalidBlockNumbersError();

impl Reject for InvalidBlockNumbersError {}

#[derive(Debug)]
pub struct StateNotFound();

impl Reject for StateNotFound {}

#[derive(Debug)]
pub struct EvmError(pub Report);

Expand All @@ -53,10 +58,13 @@ impl Reject for EvmError {}
pub async fn handle_rejection(err: Rejection) -> Result<impl Reply, Infallible> {
let code;
let message: String;

println!("Handling rejection: {:?}", err);
if err.is_not_found() {
code = StatusCode::NOT_FOUND;
message = "NOT_FOUND".to_string();
} else if let Some(_e) = err.find::<StateNotFound>() {
code = StatusCode::NOT_FOUND;
message = "STATE_NOT_FOUND".to_string();
} else if let Some(FromHexError) = err.find() {
code = StatusCode::BAD_REQUEST;
message = "FROM_HEX_ERROR".to_string();
Expand Down
11 changes: 11 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ pub fn simulate_routes(
simulate(config.clone())
.or(simulate_bundle(config.clone()))
.or(simulate_stateful_new(config, state.clone()))
.or(simulate_stateful_end(state.clone()))
.or(simulate_stateful(state))
}

Expand Down Expand Up @@ -62,6 +63,16 @@ pub fn simulate_stateful_new(
.and_then(simulation::simulate_stateful_new)
}

/// DELETE /simulate-stateful/{statefulSimulationId}
pub fn simulate_stateful_end(
state: Arc<SharedSimulationState>,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone {
warp::path!("simulate-stateful" / Uuid)
.and(warp::delete())
.and(with_state(state))
.and_then(simulation::simulate_stateful_end)
}

/// POST /simulate-stateful/{statefulSimulationId}
pub fn simulate_stateful(
state: Arc<SharedSimulationState>,
Expand Down
20 changes: 19 additions & 1 deletion src/simulation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use warp::Rejection;

use crate::errors::{
FromDecStrError, FromHexError, IncorrectChainIdError, InvalidBlockNumbersError,
MultipleChainIdsError, NoURLForChainIdError,
MultipleChainIdsError, NoURLForChainIdError, StateNotFound,
};
use crate::SharedSimulationState;

Expand Down Expand Up @@ -74,6 +74,11 @@ pub struct StatefulSimulationResponse {
pub stateful_simulation_id: Uuid,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StatefulSimulationEndResponse {
pub success: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CallTrace {
#[serde(rename = "callType")]
Expand Down Expand Up @@ -266,6 +271,19 @@ pub async fn simulate_stateful_new(
Ok(warp::reply::json(&response))
}

pub async fn simulate_stateful_end(
param: Uuid,
state: Arc<SharedSimulationState>,
) -> Result<Json, Rejection> {
if state.evms.contains_key(&param) {
state.evms.remove(&param);
let response = StatefulSimulationEndResponse { success: true };
Ok(warp::reply::json(&response))
} else {
Err(warp::reject::custom(StateNotFound()))
}
}

pub async fn simulate_stateful(
param: Uuid,
transactions: Vec<SimulationRequest>,
Expand Down
51 changes: 38 additions & 13 deletions tests/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ use transaction_simulator::{
config::config,
errors::{handle_rejection, ErrorMessage},
simulate_routes,
simulation::{SimulationRequest, SimulationResponse, StatefulSimulationResponse},
simulation::{
SimulationRequest, SimulationResponse, StatefulSimulationEndResponse,
StatefulSimulationResponse,
},
SharedSimulationState,
};
use warp::Filter;
Expand Down Expand Up @@ -474,13 +477,13 @@ async fn post_simulate_bundle_multiple_block_numbers() {

assert_eq!(res.status(), 200);

let body: Vec<SimulationResponse> = serde_json::from_slice(&res.body()).unwrap();
let body: Vec<SimulationResponse> = serde_json::from_slice(res.body()).unwrap();

assert_eq!(body.len(), 4);
assert_eq!(body[0].success, true);
assert_eq!(body[1].success, false);
assert_eq!(body[2].success, true);
assert_eq!(body[3].success, true);
assert!(body[0].success);
assert!(!body[1].success);
assert!(body[2].success);
assert!(body[3].success);

assert_eq!(body[0].block_number, 16968595);
assert_eq!(body[1].block_number, 16968596);
Expand Down Expand Up @@ -551,7 +554,7 @@ async fn post_simulate_stateful() {
assert_eq!(res.status(), 200);

let simulation_response_body: StatefulSimulationResponse =
serde_json::from_slice(&res.body()).unwrap();
serde_json::from_slice(res.body()).unwrap();
assert_eq!(
simulation_response_body
.stateful_simulation_id
Expand Down Expand Up @@ -591,11 +594,11 @@ async fn post_simulate_stateful() {

assert_eq!(res.status(), 200);

let body: Vec<SimulationResponse> = serde_json::from_slice(&res.body()).unwrap();
let body: Vec<SimulationResponse> = serde_json::from_slice(res.body()).unwrap();

assert_eq!(body.len(), 2);
assert_eq!(body[0].success, true);
assert_eq!(body[1].success, false);
assert!(body[0].success);
assert!(!body[1].success);

assert_eq!(body[0].block_number, 16968595);
assert_eq!(body[1].block_number, 16968596);
Expand Down Expand Up @@ -632,11 +635,11 @@ async fn post_simulate_stateful() {

assert_eq!(res.status(), 200);

let body: Vec<SimulationResponse> = serde_json::from_slice(&res.body()).unwrap();
let body: Vec<SimulationResponse> = serde_json::from_slice(res.body()).unwrap();
assert_eq!(body.len(), 2);

assert_eq!(body[0].success, true);
assert_eq!(body[1].success, true);
assert!(body[0].success);
assert!(body[1].success);
assert_eq!(body[0].block_number, 16968597);
assert_eq!(body[1].block_number, 16968598);

Expand All @@ -648,4 +651,26 @@ async fn post_simulate_stateful() {
U256::from(body[1].return_data.0.to_vec().as_slice()),
U256::from(1680526127 + 12)
);

let res = warp::test::request()
.method("DELETE")
.path(
format!(
"/simulate-stateful/{}",
simulation_response_body.stateful_simulation_id
)
.as_str(),
)
.reply(&filter)
.await;
assert_eq!(res.status(), 200);
let body: StatefulSimulationEndResponse = serde_json::from_slice(res.body()).unwrap();
assert!(body.success);

let res = warp::test::request()
.method("DELETE")
.path("/simulate-stateful/6f676bc7-3416-4647-99ee-e1be90fb6d2e")
.reply(&filter)
.await;
assert_eq!(res.status(), 404);
}
Loading