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

Fix panic when MetaMask returns error #549

Merged
merged 4 commits into from
Sep 30, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
91 changes: 85 additions & 6 deletions src/transports/eip_1193.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ use crate::{
DuplexTransport, Error, RequestId, Transport,
};
use futures::{channel::mpsc, future::LocalBoxFuture, Stream};
use jsonrpc_core::types::request::{Call, MethodCall};
use jsonrpc_core::{
error::{Error as RPCError, ErrorCode as RPCErrorCode},
types::request::{Call, MethodCall},
};
use serde::{
de::{value::StringDeserializer, IntoDeserializer},
Deserialize,
Expand Down Expand Up @@ -234,15 +237,45 @@ impl Provider {
get_provider_js()
}

async fn request_wrapped(&self, args: RequestArguments) -> error::Result<serde_json::value::Value> {
let js_result = self.request(args).await;
let parsed_value = js_result.map(|res| res.into_serde()).map_err(|err| err.into_serde());
fn parse_response(resp: Result<JsValue, JsValue>) -> error::Result<serde_json::value::Value> {
// Fix #544
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RPCErrorExtra {
/// Code
pub code: RPCErrorCode,
/// Message
pub message: String,
/// Optional data
pub data: Option<serde_json::value::Value>,
/// Optional stack
pub stack: Option<serde_json::value::Value>,
}

impl Into<RPCError> for RPCErrorExtra {
fn into(self) -> RPCError {
RPCError {
code: self.code,
message: self.message,
data: self.data,
}
}
}

let parsed_value = resp
.map(|res| res.into_serde())
.map_err(|err| err.into_serde::<RPCErrorExtra>());
match parsed_value {
Ok(Ok(res)) => Ok(res),
Err(Ok(err)) => Err(Error::Rpc(err)),
err => unreachable!("Unable to parse request response: {:?}", err),
Err(Ok(err)) => Err(Error::Rpc(err.into())),
err => Err(Error::InvalidResponse(format!("{:?}", err))),
}
}

async fn request_wrapped(&self, args: RequestArguments) -> error::Result<serde_json::value::Value> {
let response = self.request(args).await;
Self::parse_response(response)
}
}

/// Keep the provider and the event listeners attached to it together so we can remove them in the
Expand Down Expand Up @@ -299,3 +332,49 @@ impl RequestArguments {
self.params.clone()
}
}

#[cfg(test)]
mod tests {
use super::*;
use wasm_bindgen_test::*;

fn json_to_js(json: &str) -> JsValue {
let json_value = serde_json::from_str::<serde_json::Value>(json).unwrap();
let js_value = JsValue::from_serde(&json_value).unwrap();
js_value
}

#[wasm_bindgen_test]
fn parses_valid_response_correctly() {
let value = serde_json::from_str::<serde_json::Value>(r#"[1, false, null, "string"]"#).unwrap();
let response = Ok(JsValue::from_serde(&value).unwrap());
let expected_result = Ok(value);
assert_eq!(Provider::parse_response(response), expected_result);

let response = Err(json_to_js(
r#"{"code": 15, "message": "string1", "data": "string2", "stack": "string3"}"#,
));
let expected_result = Err(Error::Rpc(RPCError {
code: RPCErrorCode::from(15),
message: "string1".to_string(),
data: Some(serde_json::Value::String("string2".to_string())),
}));
assert_eq!(Provider::parse_response(response), expected_result);
}

#[wasm_bindgen_test]
fn returns_error_on_invalid_response() {
assert!(matches!(
Provider::parse_response(Err(json_to_js(r#"{"code": "red", "message": ""}"#))),
Err(Error::InvalidResponse(_))
));
assert!(matches!(
Provider::parse_response(Err(json_to_js(r#"{"code": 0, "message": "", "extra": true}"#))),
Err(Error::InvalidResponse(_))
));
assert!(matches!(
Provider::parse_response(Err(json_to_js(r#"{}"#))),
Err(Error::InvalidResponse(_))
));
}
}