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/provider round cost #807

Merged
merged 1 commit into from
Nov 23, 2020
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions agent/provider/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ libc = "0.2"
log = "0.4.8"
log-derive = "0.4"
notify = "4.0.15"
num-bigint = "0.2.6"
num_cpus = "1.13.0"
path-clean = "0.1.0"
semver = { version = "0.10.0", features = ["serde"] }
Expand Down
63 changes: 61 additions & 2 deletions agent/provider/src/payments/agreement.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use anyhow::{anyhow, bail, Result};
use bigdecimal::BigDecimal;
use bigdecimal::{BigDecimal, Signed, ToPrimitive};
use num_bigint::BigInt;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
Expand All @@ -11,12 +12,49 @@ use super::model::{PaymentDescription, PaymentModel};
use ya_agreement_utils::AgreementView;
use ya_client::activity::ActivityProviderApi;

const PAYMENT_PRECISION: i64 = 18; // decimal places

#[derive(Clone, PartialEq)]
pub struct CostInfo {
pub usage: Vec<f64>,
pub cost: BigDecimal,
}

impl CostInfo {
pub fn new(usage: Vec<f64>, cost: BigDecimal) -> Self {
let cost = round(cost, PAYMENT_PRECISION);
CostInfo { usage, cost }
}
}

/// Return number rounded to round_digits precision after the decimal point
/// Copied from https://docs.rs/bigdecimal/0.2.0/src/bigdecimal/lib.rs.html#589-612
/// TODO: Remove when we update to bigdecimal 0.2.0
fn round(value: BigDecimal, round_digits: i64) -> BigDecimal {
let (bigint, decimal_part_digits) = value.as_bigint_and_exponent();
let need_to_round_digits = decimal_part_digits - round_digits;
if round_digits >= 0 && need_to_round_digits <= 0 {
return value;
}

let mut number = bigint.to_i128().unwrap();
if number < 0 {
number = -number;
}
for _ in 0..(need_to_round_digits - 1) {
number /= 10;
}
let digit = number % 10;

if digit <= 4 {
value.with_scale(round_digits)
} else if bigint.is_negative() {
value.with_scale(round_digits) - BigDecimal::new(BigInt::from(1), round_digits)
} else {
value.with_scale(round_digits) + BigDecimal::new(BigInt::from(1), round_digits)
}
}

#[derive(PartialEq)]
//TODO: Remove last_debit_note in future. Payment api
// should deduce it based on activity id.
Expand Down Expand Up @@ -162,7 +200,7 @@ impl AgreementPayment {
},
);

CostInfo { cost, usage }
CostInfo::new(usage, cost)
}

pub fn list_activities(&self) -> Vec<String> {
Expand Down Expand Up @@ -224,3 +262,24 @@ impl ActivitiesWaiter {
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;

#[test]
fn test_round() {
let x = BigDecimal::from_str("12345.123456789").unwrap();
let y = BigDecimal::from_str("12345.12346").unwrap();
assert_eq!(round(x, 5), y);

let x = BigDecimal::from_str("12345.123456789").unwrap();
let y = BigDecimal::from_str("12345").unwrap();
assert_eq!(round(x, 0), y);

let x = BigDecimal::from_str("12345").unwrap();
let y = BigDecimal::from_str("12345").unwrap();
assert_eq!(round(x, 15), y);
}
}
4 changes: 2 additions & 2 deletions agent/provider/src/payments/payments.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use actix::prelude::*;
use anyhow::{anyhow, Error, Result};
use bigdecimal::BigDecimal;
use bigdecimal::{BigDecimal, Zero};
use chrono::Utc;
use log;
use serde_json::json;
Expand Down Expand Up @@ -131,7 +131,7 @@ impl Payments {
agreements: HashMap::new(),
context: Arc::new(provider_ctx),
invoices_to_pay: vec![],
earnings: BigDecimal::from(0.0),
earnings: BigDecimal::zero(),
}
}

Expand Down