Skip to content

Commit 6e8227e

Browse files
committed
better way to convert from u64 to i64
1 parent 03bb5a2 commit 6e8227e

File tree

3 files changed

+17
-7
lines changed

3 files changed

+17
-7
lines changed

pyth-sdk/src/error.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,7 @@ pub enum LiquidityOracleError {
99
#[error("final discount rate should not be greater than the discount precision")]
1010
FinalDiscountExceedsPrecision,
1111
#[error("None encountered")]
12-
NoneEncountered
12+
NoneEncountered,
13+
#[error("i64 try from error")]
14+
I64ConversionError,
1315
}

pyth-sdk/src/price.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -135,13 +135,13 @@ impl Price {
135135
return Err(LiquidityOracleError::FinalDiscountExceedsPrecision.into());
136136
}
137137

138-
let remaining_depositable = (max_deposits-deposits) as i64;
139-
let diff_discount_precision_initial = (discount_precision-discount_initial) as i64;
140-
let diff_discount_precision_final = (discount_precision-discount_final) as i64;
138+
let remaining_depositable = utils::u64_to_i64(max_deposits-deposits)?;
139+
let diff_discount_precision_initial = utils::u64_to_i64(discount_precision-discount_initial)?;
140+
let diff_discount_precision_final = utils::u64_to_i64(discount_precision-discount_final)?;
141141

142142
// get fractions for deposits
143143
let deposits_as_price = Price {
144-
price: deposits as i64,
144+
price: utils::u64_to_i64(deposits)?,
145145
conf: 0,
146146
expo: 0,
147147
publish_time: 0,
@@ -153,7 +153,7 @@ impl Price {
153153
publish_time: 0,
154154
};
155155
let max_deposits_as_price = Price {
156-
price: max_deposits as i64,
156+
price: utils::u64_to_i64(max_deposits)?,
157157
conf: 1,
158158
expo: 0,
159159
publish_time: 0,
@@ -176,7 +176,7 @@ impl Price {
176176
publish_time: 0,
177177
};
178178
let discount_precision_as_price = Price {
179-
price: discount_precision as i64,
179+
price: utils::u64_to_i64(discount_precision)?,
180180
conf: 1,
181181
expo: 0,
182182
publish_time: 0,

pyth-sdk/src/utils.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
use std::convert::TryFrom;
2+
3+
use crate::error::LiquidityOracleError;
4+
15
/// This module helps serde to serialize deserialize some fields as String
26
///
37
/// The reason this is added is that `#[serde(with = "String")]` does not work
@@ -30,3 +34,7 @@ pub mod as_string {
3034
.map_err(|_| D::Error::custom("Input is not valid"))
3135
}
3236
}
37+
38+
pub fn u64_to_i64(value: u64) -> Result<i64, LiquidityOracleError> {
39+
i64::try_from(value).map_err(|_| LiquidityOracleError::I64ConversionError)
40+
}

0 commit comments

Comments
 (0)