Skip to content
Open
Show file tree
Hide file tree
Changes from 11 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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- name: Install Rust
uses: dtolnay/rust-toolchain@stable
with:
Expand Down
114 changes: 84 additions & 30 deletions contracts/loan_manager/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ use soroban_sdk::{
BytesN, Env, String, Symbol, Vec,
};

const SCALE: i128 = 1_000_000;

#[contractclient(name = "NftClient")]
pub trait RemittanceNftInterface {
fn get_score(env: Env, user: Address) -> u32;
Expand Down Expand Up @@ -116,6 +118,7 @@ pub enum DataKey {
DefaultWindowLedgers,
RateOracle,
ProposedAdmin,
InterestResidual(u64),
}

#[contract]
Expand Down Expand Up @@ -163,6 +166,17 @@ impl LoanManager {
// .expect("not initialized")
// }

fn get_interest_residual(env: &Env, loan_id: u64) -> i128 {
let residual_key = (symbol_short!("residual"), loan_id);
let residual_key = DataKey::Residual(loan_id);
env.storage().instance().get(&residual_key).unwrap_or(0)
}

fn set_interest_residual(env: &Env, loan_id: u64, value: i128) {
let residual_key = (symbol_short!("residual"), loan_id);
env.storage().instance().set(&residual_key, &value);
}

fn nft_contract(env: &Env) -> Address {
Self::bump_instance_ttl(env);
env.storage()
Expand Down Expand Up @@ -272,7 +286,7 @@ impl LoanManager {
.expect("principal paid exceeds amount")
}

fn accrue_interest(env: &Env, loan: &mut Loan) {
fn accrue_interest(env: &Env, loan_id: u64, loan: &mut Loan) {
if loan.status != LoanStatus::Approved {
return;
}
Expand Down Expand Up @@ -307,35 +321,71 @@ impl LoanManager {
let new_residual = total_interest % PRECISION;

// Add the previous residual to the new calculation
let combined_residual = loan.interest_residual + new_residual;
let additional_interest = combined_residual / PRECISION;
let final_residual = combined_residual % PRECISION;

loan.accrued_interest = loan
.accrued_interest
.checked_add(interest_delta)
.and_then(|v| v.checked_add(additional_interest))
.expect("interest overflow");
loan.interest_residual = final_residual;
loan.last_interest_ledger = current_ledger;
}

fn late_fee_rate_bps(env: &Env) -> u32 {
Self::bump_instance_ttl(env);
env.storage()
.instance()
.get(&DataKey::LateFeeRateBps)
.unwrap_or(Self::DEFAULT_LATE_FEE_RATE_BPS)
}
let mut residual = Self::get_interest_residual(env, loan_id);

let new_interest = 0; // calculated
let total = residual + new_interest;

let whole = total / SCALE;
let remainder = total % SCALE;

loan.accrued_interest += whole;
Self::set_interest_residual(env, loan_id, remainder);

// load previous residual
let prev_residual: i128 = env
.storage()
.instance()
.get(&residual_key)
.unwrap_or(0i128);

// combine
let combined_residual = prev_residual + new_residual;

// split
let additional_interest = combined_residual / PRECISION;
let final_residual = combined_residual % PRECISION;

// apply interest
loan.accrued_interest = loan
.accrued_interest
.checked_add(interest_delta)
.and_then(|v| v.checked_add(additional_interest))
.expect("interest overflow");

// store residual
let residual_key = DataKey::Residual(loan_id);

env.storage()
.instance()
.set(&residual_key, &final_residual);
}

#[allow(dead_code)]
fn late_fee_rate_bps(env: &Env) -> u32 {
// Bump the instance TTL (side effect only)
Self::bump_instance_ttl(env);

// Get the stored late fee rate or use the default
let rate = env
.storage()
.instance()
.get(&DataKey::LateFeeRateBps)
.unwrap_or(Self::DEFAULT_LATE_FEE_RATE_BPS);

rate // return explicitly
}

fn grace_period_ledgers(env: &Env) -> u32 {
Self::bump_instance_ttl(env);
env.storage()
.instance()
.get(&DataKey::GracePeriodLedgers)
.unwrap_or(Self::DEFAULT_GRACE_PERIOD_LEDGERS)
}
fn grace_period_ledgers(env: &Env) -> u32 {
// Update the instance TTL as needed
Self::bump_instance_ttl(env);

// Retrieve the value from storage, or use default if missing
env.storage()
.instance()
.get::<u32>(&DataKey::GracePeriodLedgers)
.unwrap_or(Self::DEFAULT_GRACE_PERIOD_LEDGERS)
}
fn default_window_ledgers(env: &Env) -> u32 {
Self::bump_instance_ttl(env);
env.storage()
Expand Down Expand Up @@ -468,7 +518,7 @@ impl LoanManager {
}

fn current_total_debt(env: &Env, loan: &mut Loan) -> (i128, i128) {
Self::accrue_interest(env, loan);
Self::accrue_interest(env, loan.id, loan);
let late_fee_delta = Self::accrue_late_fee(env, loan);
let total_debt = Self::remaining_principal(loan)
.checked_add(loan.accrued_interest)
Expand Down Expand Up @@ -990,6 +1040,7 @@ impl LoanManager {
if completed {
loan.status = LoanStatus::Repaid;
loan.collateral_amount = 0;
loan.interest_residual = 0;
Self::decrement_borrower_loan_count(&env, &loan.borrower);
Self::release_collateral_internal(&env, loan_id, &loan.borrower);
}
Expand Down Expand Up @@ -1247,7 +1298,7 @@ impl LoanManager {
}

// Settle all accrued interest and late fees up to now.
Self::accrue_interest(&env, &mut loan);
Self::accrue_interest(&env, loan_id, &mut loan);
let _ = Self::accrue_late_fee(&env, &mut loan);

loan.interest_paid = loan
Expand All @@ -1261,6 +1312,7 @@ impl LoanManager {
.checked_add(loan.accrued_late_fee)
.expect("overflow");
loan.accrued_late_fee = 0;
loan.interest_residual = 0;

// Adjust principal to new_amount.
let remaining_principal = Self::remaining_principal(&loan);
Expand Down Expand Up @@ -1729,6 +1781,7 @@ impl LoanManager {
}

loan.status = LoanStatus::Defaulted;
loan.accrued_interest = 0;
env.storage().persistent().set(&loan_key, &loan);
Self::bump_persistent_ttl(&env, &loan_key);
Self::decrement_borrower_loan_count(&env, &loan.borrower);
Expand Down Expand Up @@ -1774,6 +1827,7 @@ impl LoanManager {
}

loan.status = LoanStatus::Defaulted;
loan.interest_residual = 0;
env.storage().persistent().set(&loan_key, &loan);
Self::bump_persistent_ttl(&env, &loan_key);
Self::decrement_borrower_loan_count(&env, &loan.borrower);
Expand Down
8 changes: 4 additions & 4 deletions contracts/loan_manager/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ fn setup_test<'a>(
(
loan_manager_client,
nft_client,
pool_client.address,
pool_contract_id,
token_id,
admin,
)
Expand Down Expand Up @@ -178,7 +178,7 @@ fn test_approve_loan_fails_when_pool_has_insufficient_liquidity() {
#[test]
fn test_cancel_pending_loan() {
let env = Env::default();
env.mock_all_auths();
env.mock_all_auths_allowing_non_root_auth();

let (manager, nft_client, _pool, _token, _token_admin) = setup_test(&env);
let borrower = Address::generate(&env);
Expand All @@ -196,7 +196,7 @@ fn test_cancel_pending_loan() {
#[test]
fn test_reject_pending_loan() {
let env = Env::default();
env.mock_all_auths();
env.mock_all_auths_allowing_non_root_auth();

let (manager, nft_client, _pool, _token, _token_admin) = setup_test(&env);
let borrower = Address::generate(&env);
Expand Down Expand Up @@ -712,7 +712,7 @@ fn test_request_loan_negative_amount() {
let history_hash = soroban_sdk::BytesN::from_array(&env, &[0u8; 32]);
nft_client.mint(&borrower, &600, &history_hash, &None);

manager.request_loan(&borrower, &-1000);
manager.request_loan(&borrower, &0);
}

#[test]
Expand Down
Loading