Skip to content

Commit a1b79dd

Browse files
committed
use ratio
1 parent 47d9b3c commit a1b79dd

File tree

4 files changed

+22
-7
lines changed

4 files changed

+22
-7
lines changed

Cargo.lock

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ edition = "2021"
1414
borsh = { version = "^1", default-features = false }
1515
const-crypto = { version = "^0.3", default-features = false }
1616
generic-array-struct = { version = "=0.3.0-bc", default-features = false }
17+
sanctum-u64-ratio = { version = "^1", default-features = false }
1718

1819
# dev deps
1920
bs58 = { version = "^0.5", default-features = false }

core/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ edition.workspace = true
77
borsh = { workspace = true, features = ["derive"] }
88
const-crypto = { workspace = true }
99
generic-array-struct = { workspace = true }
10+
sanctum-u64-ratio = { workspace = true }
1011

1112
[dev-dependencies]
1213
bs58 = { workspace = true }

core/src/typedefs/exchange_rate.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use borsh::{BorshDeserialize, BorshSerialize};
2+
use sanctum_u64_ratio::{Floor, Ratio};
23

34
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, BorshDeserialize, BorshSerialize)]
45
pub struct ExchangeRate {
@@ -13,15 +14,20 @@ impl ExchangeRate {
1314
///
1415
/// Returns None on arithmetic failure
1516
#[inline]
16-
pub fn quote_withdraw_stake(&self, stsol_amount: u64) -> Option<u64> {
17-
if self.st_sol_supply == 0 {
17+
pub const fn quote_withdraw_stake(&self, stsol_amount: u64) -> Option<u64> {
18+
let ratio = self.sol_balance_over_st_sol_supply();
19+
if ratio.0.is_zero() {
1820
return None;
1921
}
20-
// unchecked mul: 2 u64s will not overflow u128
21-
// unchecked div: nonzero denom checked above
22-
let res = (u128::from(stsol_amount) * u128::from(self.sol_balance))
23-
/ u128::from(self.st_sol_supply);
24-
res.try_into().ok()
22+
ratio.apply(stsol_amount)
23+
}
24+
25+
#[inline]
26+
pub const fn sol_balance_over_st_sol_supply(&self) -> Floor<Ratio<u64, u64>> {
27+
Floor(Ratio {
28+
n: self.sol_balance,
29+
d: self.st_sol_supply,
30+
})
2531
}
2632
}
2733

0 commit comments

Comments
 (0)