Skip to content

Commit 69475ad

Browse files
committed
improvement(exchange-rate): make the scale conversion after the exchange rate is applied
1 parent 449e4a6 commit 69475ad

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

crates/interledger-service-util/src/exchange_rates_service.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -90,26 +90,25 @@ where
9090
.build()));
9191
};
9292

93-
// Note that this is not an overflow safe operation. Given realistic
94-
// assumptions, the asset scale will be <=18 and >=1.
95-
// It is doubtful that the exchange rate between two assets,
96-
// multiplied by 18 would exceed std::f64::MAX
97-
let scaled_rate = rate.normalize_scale(ConvertDetails {
93+
// Can we overflow here?
94+
let outgoing_amount = (request.prepare.amount() as f64) * rate;
95+
let outgoing_amount = outgoing_amount.normalize_scale(ConvertDetails {
9896
from: request.from.asset_scale(),
9997
to: request.to.asset_scale(),
10098
});
10199

102-
match scaled_rate {
103-
Ok(scaled_rate) => {
104-
let outgoing_amount = (request.prepare.amount() as f64) * scaled_rate;
100+
match outgoing_amount {
101+
Ok(outgoing_amount) => {
102+
// NOTE: If the f64 amount could not fit in a u64, then the
103+
// typecast makes the outgoing amount 0.
105104
request.prepare.set_amount(outgoing_amount as u64);
106105
trace!("Converted incoming amount of: {} {} (scale {}) from account {} to outgoing amount of: {} {} (scale {}) for account {}",
107106
request.original_amount, request.from.asset_code(), request.from.asset_scale(), request.from.id(),
108107
outgoing_amount, request.to.asset_code(), request.to.asset_scale(), request.to.id());
109108
}
110109
Err(_) => {
111110
return Box::new(err(RejectBuilder {
112-
code: ErrorCode::F02_UNREACHABLE,
111+
code: ErrorCode::F08_AMOUNT_TOO_LARGE,
113112
message: format!(
114113
"Could not convert exchange rate from {}:{} to: {}:{}",
115114
request.from.asset_code(),

0 commit comments

Comments
 (0)