use jsonrpsee::types::{error::ErrorCode, ErrorObject, ErrorObjectOwned};
pub fn check_if_safe(ext: &jsonrpsee::Extensions) -> Result<(), UnsafeRpcError> {
match ext.get::<DenyUnsafe>().map(|deny_unsafe| deny_unsafe.check_if_safe()) {
Some(Ok(())) => Ok(()),
Some(Err(e)) => Err(e),
None => unreachable!("DenyUnsafe extension is always set by the substrate rpc server; qed"),
}
}
#[derive(Clone, Copy, Debug)]
pub enum DenyUnsafe {
Yes,
No,
}
impl DenyUnsafe {
pub fn check_if_safe(self) -> Result<(), UnsafeRpcError> {
match self {
DenyUnsafe::Yes => Err(UnsafeRpcError),
DenyUnsafe::No => Ok(()),
}
}
}
#[derive(Debug)]
pub struct UnsafeRpcError;
impl std::fmt::Display for UnsafeRpcError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "RPC call is unsafe to be called externally")
}
}
impl std::error::Error for UnsafeRpcError {}
impl From<UnsafeRpcError> for ErrorObjectOwned {
fn from(e: UnsafeRpcError) -> ErrorObjectOwned {
ErrorObject::owned(ErrorCode::MethodNotFound.code(), e.to_string(), None::<()>)
}
}