Browse Source

Merge #400

400: Cleanup `unwrap`s throughout the codebase r=da-kami a=thomaseizinger

- Make function that never fails non-fallible
- Disallow `.unwrap` in prod code and use expect for remaining ones
- Rewrite matrix_solve to not contain `unwrap`


Co-authored-by: Thomas Eizinger <thomas@eizinger.io>
contact-taker-before-changing-cfd-state
bors[bot] 3 years ago
committed by GitHub
parent
commit
57334c75ce
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      daemon/src/bitmex_price_feed.rs
  2. 2
      daemon/src/lib.rs
  3. 2
      daemon/src/monitor.rs
  4. 12
      daemon/src/payout_curve.rs
  5. 37
      daemon/src/payout_curve/csr_tools.rs
  6. 8
      daemon/src/payout_curve/curve.rs
  7. 2
      daemon/src/payout_curve/curve_factory.rs
  8. 10
      daemon/src/payout_curve/splineobject.rs
  9. 4
      daemon/src/to_sse_event.rs

2
daemon/src/bitmex_price_feed.rs

@ -74,7 +74,7 @@ impl Quote {
pub fn for_taker(&self) -> Usd {
// TODO: verify whether this is correct
self.mid_range().unwrap()
self.mid_range().expect("decimal arithmetic to not fail")
}
fn mid_range(&self) -> Result<Usd> {

2
daemon/src/lib.rs

@ -1,3 +1,5 @@
#![cfg_attr(not(test), warn(clippy::unwrap_used))]
pub mod actors;
pub mod auth;
pub mod bitmex_price_feed;

2
daemon/src/monitor.rs

@ -93,7 +93,7 @@ impl Actor<bdk::electrum_client::Client> {
if let Some(model::cfd::CollaborativeSettlement { tx, ..}
) = cfd.state.get_collaborative_close() {
let close_params = (tx.txid(),
tx.output.first().expect("have output").script_pubkey.clone());
tx.output.first().context("transaction has zero outputs")?.script_pubkey.clone());
actor.monitor_close_finality(close_params,cfd.order.id);
}
}

12
daemon/src/payout_curve.rs

@ -270,7 +270,7 @@ impl PayoutCurve {
}
fn build_sampling_vector_upper_bounded(&self, n_segs: usize) -> Array1<f64> {
let knots = &self.curve.spline.knots(0, None).unwrap()[0];
let knots = &self.curve.spline.knots(0, None)[0];
let klen = knots.len();
let n_64 = (n_segs + 1) as f64;
let d = knots[klen - 2] - knots[1];
@ -300,7 +300,7 @@ impl PayoutCurve {
}
fn build_sampling_vector_upper_unbounded(&self, n_segs: usize) -> Array1<f64> {
let knots = &self.curve.spline.knots(0, None).unwrap()[0];
let knots = &self.curve.spline.knots(0, None)[0];
let klen = knots.len();
let n_64 = (n_segs + 1) as f64;
let d = knots[klen - 1] - knots[1];
@ -351,7 +351,7 @@ impl PayoutCurve {
vec.push(arr[[i, 1]]);
}
*arr = Array2::<f64>::from_shape_vec((capacity, 2), vec).unwrap();
*arr = Array2::<f64>::from_shape_vec((capacity, 2), vec).expect("vec is a 2D array");
}
fn modify_samples_unbounded(&self, arr: &mut Array2<f64>) {
@ -377,7 +377,7 @@ impl PayoutCurve {
vec.push(arr[[i, 1]]);
}
*arr = Array2::<f64>::from_shape_vec((capacity, 2), vec).unwrap();
*arr = Array2::<f64>::from_shape_vec((capacity, 2), vec).expect("vec is a 2D array");
}
/// this should only be used on an array `arr` that has been
@ -397,7 +397,7 @@ impl PayoutCurve {
}
}
*arr = Array2::<f64>::from_shape_vec((capacity / 3, 3), vec).unwrap();
*arr = Array2::<f64>::from_shape_vec((capacity / 3, 3), vec).expect("vec is a 2D array");
}
}
@ -446,7 +446,7 @@ fn create_long_payout_function(
vec.push(eval);
}
Array2::<f64>::from_shape_vec((t.len(), 2), vec).unwrap()
Array2::<f64>::from_shape_vec((t.len(), 2), vec).expect("vec is a 2D array")
}
}

37
daemon/src/payout_curve/csr_tools.rs

@ -1,5 +1,6 @@
use crate::payout_curve::compat::{To1DArray, ToNAlgebraMatrix};
use crate::payout_curve::Error;
use itertools::Itertools;
use ndarray::prelude::*;
use std::ops::Mul;
@ -49,29 +50,19 @@ impl CSR {
// is horrible.
pub fn matrix_solve(&self, b_arr: &Array2<f64>) -> Result<Array2<f64>, Error> {
let a_arr = self.todense();
let ncols = b_arr.shape()[1];
let mut temp = (0..ncols)
.rev()
.map(|e| {
let b = b_arr.slice(s![.., e]).to_owned();
let sol = lu_solve(&a_arr, &b)?;
Ok(sol.to_vec())
})
.collect::<Result<Vec<_>, Error>>()?;
let nrows = temp[0].len();
let mut raveled = Vec::with_capacity(nrows * temp.len());
for _ in 0..nrows {
for vec in &mut temp {
raveled.push(vec.pop().unwrap());
}
}
raveled.reverse();
let result = Array2::<f64>::from_shape_vec((nrows, ncols), raveled)?.to_owned();
let zeros = Array2::zeros((b_arr.nrows(), 0));
let result = b_arr
.columns()
.into_iter()
.map(|b| lu_solve(&a_arr, &b.to_owned()))
.fold_ok(zeros, |mut result, column| {
result
.push_column(column.view())
.expect("shape was initialized correctly");
result
})?;
Ok(result)
}

8
daemon/src/payout_curve/curve.rs

@ -126,8 +126,8 @@ impl Curve {
let p = max(p1, p2);
let old_knot = self.spline.knots(0, Some(true))?[0].clone();
let mut add_knot = extending_curve.spline.knots(0, Some(true))?[0].clone();
let old_knot = self.spline.knots(0, Some(true))[0].clone();
let mut add_knot = extending_curve.spline.knots(0, Some(true))[0].clone();
add_knot -= add_knot[0];
add_knot += old_knot[old_knot.len() - 1];
@ -212,7 +212,7 @@ impl Curve {
/// * t0: lower integration limit
/// * t1: upper integration limit
pub fn length(&self, t0: Option<f64>, t1: Option<f64>) -> Result<f64, Error> {
let mut knots = &self.spline.knots(0, Some(false))?[0];
let mut knots = &self.spline.knots(0, Some(false))[0];
// keep only integration boundaries within given start (t0) and stop (t1) interval
let new_knots_0 = t0
@ -419,7 +419,7 @@ impl Curve {
&self,
target: impl Fn(&Array1<f64>) -> Array2<f64>,
) -> Result<(Array1<f64>, f64), Error> {
let knots = &self.spline.knots(0, Some(false))?[0];
let knots = &self.spline.knots(0, Some(false))[0];
let n = self.spline.order(0)?[0];
let gleg = GaussLegendreQuadrature::new(n + 1)?;

2
daemon/src/payout_curve/curve_factory.rs

@ -105,7 +105,7 @@ pub fn fit(
let scale_64 = 12_f64;
while target > rtol && err_max > atol {
let knot_span = &crv.spline.knots(0, Some(false))?[0];
let knot_span = &crv.spline.knots(0, Some(false))[0];
let target_error = (rtol * length).powi(2) / err_l2.len() as f64;
for i in 0..err_l2.len() {
// figure out how many new knots we require in this knot interval:

10
daemon/src/payout_curve/splineobject.rs

@ -248,7 +248,7 @@ impl SplineObject {
// this ends up being F-contiguous, every time
let res_slice = result.select(Axis(axis_r), &idx[..]).to_owned();
let raveled = res_slice.to_shape(((n_res,), Order::C)).unwrap();
let raveled = res_slice.to_shape(((n_res,), Order::C))?;
let fixed = raveled.to_shape((res_slice.shape(), Order::C))?.to_owned();
result = fixed;
@ -267,11 +267,7 @@ impl SplineObject {
/// * direction: Direction number (axis) in which to get the knots.
/// * with_multiplicities: If true, return knots with multiplicities \
/// (i.e. repeated).
pub fn knots(
&self,
direction: isize,
with_multiplicities: Option<bool>,
) -> Result<Vec<Array1<f64>>, Error> {
pub fn knots(&self, direction: isize, with_multiplicities: Option<bool>) -> Vec<Array1<f64>> {
let with_multiplicities = with_multiplicities.unwrap_or(false);
let out;
@ -298,7 +294,7 @@ impl SplineObject {
}
}
Ok(out)
out
}
/// This will manipulate one or both to ensure that they are both rational

4
daemon/src/to_sse_event.rs

@ -262,8 +262,8 @@ impl ToSseEvent for CfdsWithAuxData {
// TODO: Depending on the state the margin might be set (i.e. in Open we save it
// in the DB internally) and does not have to be calculated
margin: cfd.margin().unwrap(),
margin_counterparty: cfd.counterparty_margin().unwrap(),
margin: cfd.margin().expect("margin to be available"),
margin_counterparty: cfd.counterparty_margin().expect("margin to be available"),
details,
expiry_timestamp: cfd.expiry_timestamp(),
}

Loading…
Cancel
Save