Skip to content
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
31 changes: 21 additions & 10 deletions common/src/asset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl<T: AssetClass> FungibleAsset<T> {
match self.kind {
FungibleAssetKind::Nep141(ref contract_id) => ext_ft_core::ext(contract_id.clone())
.with_attached_deposit(NearToken::from_yoctonear(1))
.ft_transfer(receiver_id, amount.to_u128().into(), None),
.ft_transfer(receiver_id, u128::from(amount).into(), None),
}
}

Expand All @@ -39,6 +39,7 @@ impl<T: AssetClass> FungibleAsset<T> {
}

pub fn is_nep141(&self, account_id: &AccountId) -> bool {
#[allow(irrefutable_let_patterns)]
if let FungibleAssetKind::Nep141(ref contract_id) = self.kind {
contract_id == account_id
} else {
Expand All @@ -47,7 +48,7 @@ impl<T: AssetClass> FungibleAsset<T> {
}

pub fn into_nep141(self) -> Option<AccountId> {
#[allow(clippy::match_wildcard_for_single_variants)]
#[allow(clippy::match_wildcard_for_single_variants, unreachable_patterns)]
match self.kind {
FungibleAssetKind::Nep141(contract_id) => Some(contract_id),
_ => None,
Expand Down Expand Up @@ -147,14 +148,6 @@ impl<T: AssetClass> FungibleAssetAmount<T> {
self.amount.0 == 0
}

pub fn to_u128(&self) -> u128 {
self.amount.0
}

pub fn to_decimal(&self) -> Decimal {
self.amount.0.into()
}

pub fn split(&mut self, amount: impl Into<Self>) -> Option<Self> {
let a = amount.into();
self.amount.0 = self.amount.0.checked_sub(a.amount.0)?;
Expand All @@ -167,6 +160,24 @@ impl<T: AssetClass> FungibleAssetAmount<T> {
}
}

impl<T: AssetClass> From<FungibleAssetAmount<T>> for Decimal {
fn from(value: FungibleAssetAmount<T>) -> Self {
value.amount.0.into()
}
}

impl<T: AssetClass> From<FungibleAssetAmount<T>> for u128 {
fn from(value: FungibleAssetAmount<T>) -> Self {
value.amount.0
}
}

impl<T: AssetClass> std::fmt::Display for FungibleAssetAmount<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.amount.0)
}
}

pub type BorrowAssetAmount = FungibleAssetAmount<BorrowAsset>;
pub type CollateralAssetAmount = FungibleAssetAmount<CollateralAsset>;

Expand Down
7 changes: 4 additions & 3 deletions common/src/borrow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -203,14 +203,15 @@ impl<M: Borrow<Market>> LinkedBorrowPosition<M> {
let interest_rate = market.get_interest_rate_for_snapshot(last_snapshot);
let duration_ms = Decimal::from(env::block_timestamp_ms() - last_snapshot.timestamp_ms.0);
let ms_in_a_year = Decimal::from(MS_IN_A_YEAR);
let interest_rate_part = interest_rate * duration_ms / ms_in_a_year;
let interest = interest_rate_part * self.position.get_borrow_asset_principal().to_decimal();
let interest_rate_part: Decimal = interest_rate * duration_ms / ms_in_a_year;
let interest =
interest_rate_part * Decimal::from(self.position.get_borrow_asset_principal());

interest.to_u128_ceil().unwrap().into()
}

pub(crate) fn calculate_interest(&self, limit: u32) -> AccumulationRecord<BorrowAsset> {
let principal = self.position.get_borrow_asset_principal().to_decimal();
let principal: Decimal = self.position.get_borrow_asset_principal().into();
let mut next_snapshot_index = self.position.borrow_asset_fees.get_next_snapshot_index();

let mut accumulated = Decimal::ZERO;
Expand Down
4 changes: 2 additions & 2 deletions common/src/fee.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ impl<T: AssetClass> Fee<T> {
pub fn of(&self, amount: FungibleAssetAmount<T>) -> Option<FungibleAssetAmount<T>> {
match self {
Fee::Flat(f) => Some(*f),
Fee::Proportional(factor) => (factor * amount.to_u128())
Fee::Proportional(factor) => (factor * u128::from(amount))
.to_u128_ceil()
.map(FungibleAssetAmount::new),
}
Expand Down Expand Up @@ -75,7 +75,7 @@ impl<T: AssetClass> TimeBasedFee<T> {
TimeBasedFeeFunction::Linear => {
(Decimal::from(self.duration.0.saturating_sub(duration))
/ Decimal::from(self.duration.0)
* base_fee.to_u128())
* u128::from(base_fee))
.to_u128_ceil()
.map(FungibleAssetAmount::new)
}
Expand Down
12 changes: 6 additions & 6 deletions common/src/market/balance_oracle_configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,11 @@ impl<T: AssetClass> Price<T> {
}

pub fn value_optimistic(&self, amount: FungibleAssetAmount<T>) -> Decimal {
amount.to_decimal() * self.upper_bound()
Decimal::from(amount) * self.upper_bound()
}

pub fn value_pessimistic(&self, amount: FungibleAssetAmount<T>) -> Decimal {
amount.to_decimal() * self.lower_bound()
Decimal::from(amount) * self.lower_bound()
}
}

Expand Down Expand Up @@ -151,7 +151,7 @@ impl AssetConversion<CollateralAsset, BorrowAsset> for PricePair {
&self,
amount: FungibleAssetAmount<CollateralAsset>,
) -> FungibleAssetAmount<BorrowAsset> {
(amount.to_decimal() * self.collateral_asset_price.upper_bound()
(Decimal::from(amount) * self.collateral_asset_price.upper_bound()
/ self.borrow_asset_price.lower_bound())
.to_u128_ceil()
.unwrap()
Expand All @@ -162,7 +162,7 @@ impl AssetConversion<CollateralAsset, BorrowAsset> for PricePair {
&self,
amount: FungibleAssetAmount<CollateralAsset>,
) -> FungibleAssetAmount<BorrowAsset> {
(amount.to_decimal() * self.collateral_asset_price.lower_bound()
(Decimal::from(amount) * self.collateral_asset_price.lower_bound()
/ self.borrow_asset_price.upper_bound())
.to_u128_floor()
.unwrap()
Expand All @@ -175,7 +175,7 @@ impl AssetConversion<BorrowAsset, CollateralAsset> for PricePair {
&self,
amount: FungibleAssetAmount<BorrowAsset>,
) -> FungibleAssetAmount<CollateralAsset> {
(amount.to_decimal() * self.borrow_asset_price.upper_bound()
(Decimal::from(amount) * self.borrow_asset_price.upper_bound()
/ self.collateral_asset_price.lower_bound())
.to_u128_ceil()
.unwrap()
Expand All @@ -186,7 +186,7 @@ impl AssetConversion<BorrowAsset, CollateralAsset> for PricePair {
&self,
amount: FungibleAssetAmount<BorrowAsset>,
) -> FungibleAssetAmount<CollateralAsset> {
(amount.to_decimal() * self.borrow_asset_price.lower_bound()
(Decimal::from(amount) * self.borrow_asset_price.lower_bound()
/ self.collateral_asset_price.upper_bound())
.to_u128_floor()
.unwrap()
Expand Down
2 changes: 1 addition & 1 deletion common/src/market/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ impl MarketConfiguration {
// must still fit in u128.
#[allow(clippy::unwrap_used)]
((1u32 - self.liquidation_maximum_spread)
* price_pair.convert_pessimistic(amount).to_u128())
* u128::from(price_pair.convert_pessimistic(amount)))
.to_u128_ceil()
.unwrap(),
)
Expand Down
11 changes: 5 additions & 6 deletions common/src/market/impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,14 +140,13 @@ impl Market {
// Safe because factor is guaranteed to be <=1, so value must still fit in u128.
#[allow(clippy::unwrap_used)]
let must_retain = ((1u32 - self.configuration.borrow_asset_maximum_usage_ratio)
* self.borrow_asset_deposited.to_decimal())
* Decimal::from(self.borrow_asset_deposited))
.to_u128_ceil()
.unwrap();

self.borrow_asset_deposited
.to_u128()
.saturating_sub(self.borrow_asset_borrowed.to_u128())
.saturating_sub(self.borrow_asset_in_flight.to_u128())
u128::from(self.borrow_asset_deposited)
.saturating_sub(u128::from(self.borrow_asset_borrowed))
.saturating_sub(u128::from(self.borrow_asset_in_flight))
.saturating_sub(must_retain)
.into()
}
Expand Down Expand Up @@ -288,7 +287,7 @@ impl Market {
// First, static yield.

let total_weight = u128::from(u16::from(self.configuration.yield_weights.total_weight()));
let total_amount = amount.to_u128();
let total_amount = u128::from(amount);
if total_weight != 0 {
for (account_id, share) in &self.configuration.yield_weights.r#static {
#[allow(clippy::unwrap_used)]
Expand Down
2 changes: 1 addition & 1 deletion common/src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ impl Snapshot {
} else if self.borrowed >= self.deposited {
Decimal::ONE
} else {
self.borrowed.to_decimal() / self.deposited.to_decimal()
Decimal::from(self.borrowed) / Decimal::from(self.deposited)
}
}
}
12 changes: 6 additions & 6 deletions common/src/supply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,13 @@ impl<M: Borrow<Market>> LinkedSupplyPosition<M> {
}

pub fn calculate_last_snapshot_yield(&self) -> BorrowAssetAmount {
let deposit = self.position.get_borrow_asset_deposit().to_decimal();
let deposit: Decimal = self.position.get_borrow_asset_deposit().into();
if deposit.is_zero() {
return BorrowAssetAmount::zero();
}

let last_snapshot = self.market.borrow().get_last_snapshot();
let total_deposited = last_snapshot.deposited.to_decimal();
let total_deposited: Decimal = last_snapshot.deposited.into();
if total_deposited.is_zero() {
// divzero safety
return BorrowAssetAmount::zero();
Expand All @@ -130,7 +130,7 @@ impl<M: Borrow<Market>> LinkedSupplyPosition<M> {
.total_weight()
.get(),
);
let total_yield_distribution = last_snapshot.yield_distribution.to_decimal();
let total_yield_distribution: Decimal = last_snapshot.yield_distribution.into();
let estimate_current_snapshot =
total_yield_distribution * deposit * supply_weight / total_deposited / total_weight;

Expand All @@ -144,7 +144,7 @@ impl<M: Borrow<Market>> LinkedSupplyPosition<M> {
return AccumulationRecord::empty(next_snapshot_index);
}

let amount = self.position.get_borrow_asset_deposit().to_decimal();
let amount: Decimal = self.position.get_borrow_asset_deposit().into();

let mut accumulated = Decimal::ZERO;

Expand All @@ -157,8 +157,8 @@ impl<M: Borrow<Market>> LinkedSupplyPosition<M> {
#[allow(clippy::cast_possible_truncation)]
|(i, s)| (i as u32, s),
) {
accumulated +=
amount * snapshot.yield_distribution.to_decimal() / snapshot.deposited.to_decimal();
accumulated += amount * Decimal::from(snapshot.yield_distribution)
/ Decimal::from(snapshot.deposited);

next_snapshot_index = i + 1;
}
Expand Down
2 changes: 1 addition & 1 deletion common/src/withdrawal_queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ impl WithdrawalQueue {
WithdrawalQueueStatus {
depth: self
.iter()
.map(|(_, amount)| amount.to_u128())
.map(|(_, amount)| u128::from(amount))
.sum::<u128>()
.into(),
length: self.len(),
Expand Down
2 changes: 1 addition & 1 deletion contract/market/src/impl_helper.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use near_sdk::{
env, json_types::U128, near, require, serde_json, AccountId, Promise, PromiseError,
PromiseOrValue, PromiseResult,
PromiseResult,
};
use templar_common::{
asset::{BorrowAssetAmount, CollateralAssetAmount},
Expand Down
8 changes: 4 additions & 4 deletions contract/market/src/impl_market_external.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,13 +231,13 @@ impl MarketExternalInterface for Contract {
fn get_last_yield_rate(&self) -> Decimal {
let last_snapshot = self.get_last_snapshot();
let last_interest_rate = self.get_interest_rate_for_snapshot(last_snapshot);
let deposited = last_snapshot.deposited.to_decimal();
let deposited: Decimal = last_snapshot.deposited.into();
if deposited.is_zero() {
return Decimal::ZERO;
}
let borrowed = last_snapshot.borrowed.to_decimal();
let supply_weight = Decimal::from(self.configuration.yield_weights.supply.get());
let total_weight = Decimal::from(self.configuration.yield_weights.total_weight().get());
let borrowed: Decimal = last_snapshot.borrowed.into();
let supply_weight: Decimal = self.configuration.yield_weights.supply.get().into();
let total_weight: Decimal = self.configuration.yield_weights.total_weight().get().into();

last_interest_rate * borrowed * supply_weight / deposited / total_weight
}
Expand Down
26 changes: 7 additions & 19 deletions contract/market/tests/compounding_yield.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ async fn compounding_yield(
let position = c.get_borrow_position(borrow_user.id()).await.unwrap();
c.repay(
&borrow_user,
position.get_total_borrow_asset_liability().to_u128() * 120 / 100,
u128::from(position.get_total_borrow_asset_liability()) * 120 / 100,
)
.await;
c.borrow(&borrow_user, principal).await;
Expand All @@ -66,25 +66,13 @@ async fn compounding_yield(
async { c.get_supply_position(supply_user_2.id()).await.unwrap() },
);

let supply_yield_1 = supply_position_1_after.get_borrow_asset_deposit().to_u128()
+ supply_position_1_after
.borrow_asset_yield
.get_total()
.to_u128()
+ supply_position_1_after
.borrow_asset_yield
.pending_estimate
.to_u128()
let supply_yield_1 = u128::from(supply_position_1_after.get_borrow_asset_deposit())
+ u128::from(supply_position_1_after.borrow_asset_yield.get_total())
+ u128::from(supply_position_1_after.borrow_asset_yield.pending_estimate)
- principal * 5;
let supply_yield_2 = supply_position_2_after.get_borrow_asset_deposit().to_u128()
+ supply_position_2_after
.borrow_asset_yield
.get_total()
.to_u128()
+ supply_position_2_after
.borrow_asset_yield
.pending_estimate
.to_u128()
let supply_yield_2 = u128::from(supply_position_2_after.get_borrow_asset_deposit())
+ u128::from(supply_position_2_after.borrow_asset_yield.get_total())
+ u128::from(supply_position_2_after.borrow_asset_yield.pending_estimate)
- principal * 5;

eprintln!("supply 1 yield: {supply_yield_1:#?}");
Expand Down
Loading