-
Notifications
You must be signed in to change notification settings - Fork 8
/
xrpl_conversion.rs
362 lines (326 loc) · 9.99 KB
/
xrpl_conversion.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
//! Conversions between XRP drops and native number types.
use crate::utils::exceptions::XRPRangeException;
use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use regex::Regex;
use rust_decimal::prelude::*;
use rust_decimal::Decimal;
/// Indivisible unit of XRP
pub(crate) const _ONE_DROP: Decimal = Decimal::from_parts(1, 0, 0, false, 6);
/// One drop in decimal form.
pub const ONE_DROP: &str = "0.000001";
/// 100 billion decimal XRP
pub const MAX_XRP: u64 = u64::pow(10, 11);
/// Maximum possible drops of XRP
pub const MAX_DROPS: u64 = u64::pow(10, 17);
/// Drops in one XRP
pub const XRP_DROPS: u64 = 1000000;
/// Minimum IC exponent
pub const MIN_IOU_EXPONENT: i32 = -96;
/// Maximum IC exponent
pub const MAX_IOU_EXPONENT: i32 = 80;
/// Maximum IC precision
pub const MAX_IOU_PRECISION: u8 = 16;
/// TODO Make less bootleg
/// Get the precision of a number.
fn _calculate_precision(value: &str) -> Result<usize, XRPRangeException> {
let decimal = Decimal::from_str(value)?.normalize();
let regex = Regex::new("[^1-9]").expect("_calculate_precision");
if decimal.checked_rem(Decimal::ONE).is_some() {
let stripped = regex
.replace(&decimal.to_string(), "")
.replace(['.', '0'], "");
Ok(stripped.len())
} else {
let quantized = decimal.round_dp_with_strategy(2, RoundingStrategy::MidpointAwayFromZero);
let stripped = regex
.replace(&quantized.to_string(), "")
.replace(['.', '0'], "");
Ok(stripped.len())
}
}
/// Ensure that the value after being multiplied by the
/// exponent does not contain a decimal.
fn _verify_no_decimal(decimal: Decimal) -> Result<(), XRPRangeException> {
let decimal = Decimal::from_u32(decimal.scale()).expect("_verify_no_decimal");
let value: String = if decimal == Decimal::ZERO {
decimal.mantissa().to_string()
} else {
decimal
.checked_mul(decimal)
.unwrap_or(Decimal::ZERO)
.to_string()
};
if value.contains('.') {
Err(XRPRangeException::InvalidValueContainsDecimal)
} else {
Ok(())
}
}
/// Convert a numeric XRP amount to drops of XRP.
/// Return an equivalent amount in drops of XRP.
///
/// # Examples
///
/// ## Basic usage
///
/// ```
/// use xrpl::utils::xrp_to_drops;
/// use xrpl::utils::exceptions::XRPRangeException;
///
/// let xrp: &str = "100.000001";
/// let drops: String = "100000001".to_string();
///
/// let conversion: Option<String> = match xrp_to_drops(xrp) {
/// Ok(xrp) => Some(xrp),
/// Err(e) => match e {
/// XRPRangeException::InvalidXRPAmountTooLarge { max: _, found: _ } => None,
/// XRPRangeException::InvalidXRPAmountTooSmall { min: _, found: _ } => None,
/// _ => None,
/// },
/// };
///
/// assert_eq!(Some(drops), conversion);
/// ```
pub fn xrp_to_drops(xrp: &str) -> Result<String, XRPRangeException> {
let xrp_d = Decimal::from_str(xrp)?;
if xrp_d < _ONE_DROP && xrp_d != Decimal::ZERO {
Err(XRPRangeException::InvalidXRPAmountTooSmall {
min: ONE_DROP.to_string(),
found: xrp.to_string(),
})
} else if xrp_d.gt(&Decimal::new(MAX_XRP as i64, 0)) {
Err(XRPRangeException::InvalidXRPAmountTooLarge {
max: MAX_XRP,
found: xrp.into(),
})
} else {
Ok(format!("{}", (xrp_d / _ONE_DROP).trunc()))
}
}
/// Convert from drops to decimal XRP.
/// Return an equivalent amount of XRP from drops.
///
/// # Examples
///
/// ## Basic usage
///
/// ```
/// use xrpl::utils::drops_to_xrp;
/// use xrpl::utils::exceptions::XRPRangeException;
///
/// let drops: &str = "100000000";
/// let xrp: String = "100".to_string();
///
/// let conversion: Option<String> = match drops_to_xrp(drops) {
/// Ok(xrp) => Some(xrp),
/// Err(e) => match e {
/// XRPRangeException::InvalidDropsAmountTooLarge { max: _, found: _ } => None,
/// _ => None,
/// },
/// };
///
/// assert_eq!(Some(xrp), conversion);
/// ```
pub fn drops_to_xrp(drops: &str) -> Result<String, XRPRangeException> {
let drops_d = Decimal::from_str(drops)?;
let xrp = drops_d * _ONE_DROP;
if xrp.gt(&Decimal::new(MAX_XRP as i64, 0)) {
Err(XRPRangeException::InvalidDropsAmountTooLarge {
max: MAX_XRP.to_string(),
found: drops.to_string(),
})
} else {
Ok(xrp.normalize().to_string())
}
}
/// Validate if a provided XRP amount is valid.
///
/// # Examples
///
/// ## Basic usage
///
/// ```
/// use xrpl::utils::verify_valid_xrp_value;
/// use xrpl::utils::exceptions::XRPRangeException;
///
/// let valid: bool = match verify_valid_xrp_value("0.000001") {
/// Ok(()) => true,
/// Err(e) => match e {
/// XRPRangeException::InvalidXRPAmountTooSmall { min: _, found: _ } => false,
/// XRPRangeException::InvalidXRPAmountTooLarge { max: _, found: _ } => false,
/// _ => false,
/// },
/// };
///
/// assert!(valid);
/// ```
pub fn verify_valid_xrp_value(xrp_value: &str) -> Result<(), XRPRangeException> {
let decimal = Decimal::from_str(xrp_value)?;
let max = Decimal::new(MAX_DROPS as i64, 0);
match decimal {
xrp if xrp.is_zero() => Ok(()),
xrp if xrp.ge(&_ONE_DROP) && xrp.le(&max) => Ok(()),
xrp if xrp.lt(&_ONE_DROP) => Err(XRPRangeException::InvalidXRPAmountTooSmall {
min: ONE_DROP.to_string(),
found: xrp.to_string(),
}),
xrp if xrp.gt(&max) => Err(XRPRangeException::InvalidDropsAmountTooLarge {
max: MAX_XRP.to_string(),
found: xrp.to_string(),
}),
// Should never occur
_ => Err(XRPRangeException::InvalidXRPAmount),
}
}
/// Validates the format of an issued currency amount value.
///
/// # Examples
///
/// ## Basic usage
///
/// ```
/// use xrpl::utils::verify_valid_ic_value;
/// use xrpl::utils::exceptions::XRPRangeException;
///
/// let valid: bool = match verify_valid_ic_value("1111111111111111.0") {
/// Ok(()) => true,
/// Err(e) => match e {
/// XRPRangeException::InvalidICPrecisionTooSmall { min: _, found: _ } => false,
/// XRPRangeException::InvalidICPrecisionTooLarge { max: _, found: _ } => false,
/// _ => false,
/// },
/// };
///
/// assert!(valid);
/// ```
pub fn verify_valid_ic_value(ic_value: &str) -> Result<(), XRPRangeException> {
let decimal = Decimal::from_str(ic_value)?.normalize();
let scale = -(decimal.scale() as i32);
let prec = _calculate_precision(ic_value)?;
match decimal {
ic if ic.is_zero() => Ok(()),
_ if prec > MAX_IOU_PRECISION as usize || scale > MAX_IOU_EXPONENT => {
Err(XRPRangeException::InvalidICPrecisionTooLarge {
max: MAX_IOU_EXPONENT,
found: scale,
})
}
_ if prec > MAX_IOU_PRECISION as usize || scale < MIN_IOU_EXPONENT => {
Err(XRPRangeException::InvalidICPrecisionTooSmall {
min: MIN_IOU_EXPONENT,
found: scale,
})
}
_ => _verify_no_decimal(decimal),
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::alloc::string::ToString;
extern crate std;
#[test]
fn test_one_drop_decimal() {
assert_eq!(Ok(_ONE_DROP), Decimal::from_str("0.000001"));
}
#[test]
fn test_xrp_to_drops() {
assert_eq!(
Ok((100 * XRP_DROPS + 1).to_string()),
xrp_to_drops("100.000001")
);
}
#[test]
fn test_drops_to_xrp() {
assert_eq!(
drops_to_xrp("100000001"),
Ok(Decimal::new(100000001, 6).to_string())
);
}
#[test]
fn test_verify_valid_xrp_value() {
assert!(verify_valid_xrp_value(ONE_DROP).is_ok());
assert!(verify_valid_xrp_value(&MAX_DROPS.to_string()).is_ok());
assert!(verify_valid_xrp_value("0.0000001").is_err());
assert!(verify_valid_xrp_value("100000000000000001").is_err());
}
#[test]
fn test_verify_valid_ic_value() {
// { zero, pos, negative } * fractional, large, small
let valid = [
"0",
"0.0",
"1",
"1.1111",
"-1",
"-1.1",
"1111111111111111.0",
"-1111111111111111.0",
"0.00000000001",
"0.00000000001",
"-0.00000000001",
"0.001111111111111111",
"-0.001111111111111111",
];
let invalid = ["-0.0011111111111111111"];
for case in valid {
assert!(verify_valid_ic_value(case).is_ok());
}
for case in invalid {
assert!(verify_valid_ic_value(case).is_err());
}
}
#[test]
fn accept_one_xrp() {
assert_eq!(xrp_to_drops("1"), Ok("1000000".to_string()));
}
#[test]
fn accept_zero_xrp() {
assert_eq!(xrp_to_drops("0"), Ok("0".to_string()));
}
#[test]
fn accept_min_xrp() {
assert_eq!(xrp_to_drops("0.000001"), Ok("1".to_string()));
}
#[test]
fn accept_max_xrp() {
assert_eq!(
xrp_to_drops(&MAX_XRP.to_string()),
Ok("100000000000000000".to_string())
);
}
#[test]
fn accept_too_small_xrp() {
assert!(xrp_to_drops("0.0000001").is_err());
}
#[test]
fn accept_too_big_xrp() {
let xrp = (MAX_XRP + 1).to_string();
assert!(xrp_to_drops(&xrp).is_err());
}
#[test]
fn accept_one_drop() {
assert_eq!(drops_to_xrp("1"), Ok(ONE_DROP.to_string()));
}
#[test]
fn accept_zero_drops() {
assert_eq!(drops_to_xrp("0"), Ok("0".to_string()));
}
#[test]
fn accept_1mil_drops() {
assert_eq!(drops_to_xrp("1000000"), Ok(Decimal::new(1, 0).to_string()));
}
#[test]
fn accept_max_drops() {
assert_eq!(
drops_to_xrp(&MAX_DROPS.to_string()),
Ok(Decimal::new(MAX_XRP as i64, 0).to_string())
);
}
#[test]
fn accept_too_big_drops() {
assert!(xrp_to_drops(&(MAX_XRP + 1).to_string()).is_err());
}
}