Compare commits

...

17 Commits

Author SHA1 Message Date
Vito
cb69f06ea2 removes side-effects from tryOverpayment 2025-12-05 13:32:37 +01:00
Vito
edc4db7534 adds unit-test for overpaymnet 2025-12-05 13:32:37 +01:00
Vito
72b23068c6 fixes valueChange calculation 2025-12-05 13:32:36 +01:00
Vito
12c6a4748b cleans up tryOverpayment 2025-12-05 13:32:36 +01:00
Vito
36687245db adds loanState to loanProperties 2025-12-05 13:32:35 +01:00
Vito
ca961fd061 fixes formatting 2025-12-05 13:32:35 +01:00
Vito
ed82e37dc4 removes unused code 2025-12-05 13:32:34 +01:00
Vito
2193832222 tests fullPaymentInterest 2025-12-05 13:32:34 +01:00
Vito
50ebc45a97 formatting issues 2025-12-05 13:32:33 +01:00
Vito
96fa98fdd4 addresses review comments 2025-12-05 13:32:33 +01:00
Vito
13033c4a0b fixes formatting 2025-12-05 13:32:33 +01:00
Vito
a0a0d456f1 removes unused methods 2025-12-05 13:32:32 +01:00
Vito
fd73c81632 adds additional unit tests to cover math calculations 2025-12-05 13:32:32 +01:00
Vito
3c2981cb4d adds additional tests 2025-12-05 13:32:31 +01:00
Vito
f0233ee93f fixes formatting issues 2025-12-05 13:32:31 +01:00
Vito
55c508da1b fixes overpayment interest calculation 2025-12-05 13:32:30 +01:00
Ed Hennis
0650e6e89d Fix LCOV exclusion 2025-12-03 19:49:47 -05:00
6 changed files with 1002 additions and 274 deletions

View File

@@ -0,0 +1,748 @@
#include <xrpl/beast/unit_test/suite.h>
// DO NOT REMOVE
#include <test/jtx.h>
#include <test/jtx/Account.h>
#include <test/jtx/amount.h>
#include <test/jtx/mpt.h>
#include <xrpld/app/misc/LendingHelpers.h>
#include <xrpld/app/misc/LoadFeeTrack.h>
#include <xrpld/app/tx/detail/Batch.h>
#include <xrpld/app/tx/detail/LoanSet.h>
#include <xrpl/beast/xor_shift_engine.h>
#include <xrpl/protocol/SField.h>
#include <string>
#include <vector>
namespace ripple {
namespace test {
class LendingHelpers_test : public beast::unit_test::suite
{
void
testComputeRaisedRate()
{
using namespace jtx;
using namespace ripple::detail;
struct TestCase
{
std::string name;
Number periodicRate;
std::uint32_t paymentsRemaining;
Number expectedRaisedRate;
};
auto const testCases = std::vector<TestCase>{
{
.name = "Zero payments remaining",
.periodicRate = Number{5, -2},
.paymentsRemaining = 0,
.expectedRaisedRate = Number{1}, // (1 + r)^0 = 1
},
{
.name = "One payment remaining",
.periodicRate = Number{5, -2},
.paymentsRemaining = 1,
.expectedRaisedRate = Number{105, -2},
}, // 1.05^1
{
.name = "Multiple payments remaining",
.periodicRate = Number{5, -2},
.paymentsRemaining = 3,
.expectedRaisedRate = Number{1157625, -6},
}, // 1.05^3
{
.name = "Zero periodic rate",
.periodicRate = Number{0},
.paymentsRemaining = 5,
.expectedRaisedRate = Number{1}, // (1 + 0)^5 = 1
}};
for (auto const& tc : testCases)
{
testcase("computeRaisedRate: " + tc.name);
auto const computedRaisedRate =
computeRaisedRate(tc.periodicRate, tc.paymentsRemaining);
BEAST_EXPECTS(
computedRaisedRate == tc.expectedRaisedRate,
"Raised rate mismatch: expected " +
to_string(tc.expectedRaisedRate) + ", got " +
to_string(computedRaisedRate));
}
}
void
testComputePaymentFactor()
{
using namespace jtx;
using namespace ripple::detail;
struct TestCase
{
std::string name;
Number periodicRate;
std::uint32_t paymentsRemaining;
Number expectedPaymentFactor;
};
auto const testCases = std::vector<TestCase>{
{
.name = "Zero periodic rate",
.periodicRate = Number{0},
.paymentsRemaining = 4,
.expectedPaymentFactor = Number{25, -2},
}, // 1/4 = 0.25
{
.name = "One payment remaining",
.periodicRate = Number{5, -2},
.paymentsRemaining = 1,
.expectedPaymentFactor = Number{105, -2},
}, // 0.05/1 = 1.05
{
.name = "Multiple payments remaining",
.periodicRate = Number{5, -2},
.paymentsRemaining = 3,
.expectedPaymentFactor = Number{367208564631245, -15},
}, // from calc
{
.name = "Zero payments remaining",
.periodicRate = Number{5, -2},
.paymentsRemaining = 0,
.expectedPaymentFactor = Number{0},
} // edge case
};
for (auto const& tc : testCases)
{
testcase("computePaymentFactor: " + tc.name);
auto const computedPaymentFactor =
computePaymentFactor(tc.periodicRate, tc.paymentsRemaining);
BEAST_EXPECTS(
computedPaymentFactor == tc.expectedPaymentFactor,
"Payment factor mismatch: expected " +
to_string(tc.expectedPaymentFactor) + ", got " +
to_string(computedPaymentFactor));
}
}
void
testLoanPeriodicPayment()
{
using namespace jtx;
using namespace ripple::detail;
struct TestCase
{
std::string name;
Number principalOutstanding;
Number periodicRate;
std::uint32_t paymentsRemaining;
Number expectedPeriodicPayment;
};
auto const testCases = std::vector<TestCase>{
{
.name = "Zero principal outstanding",
.principalOutstanding = Number{0},
.periodicRate = Number{5, -2},
.paymentsRemaining = 5,
.expectedPeriodicPayment = Number{0},
},
{
.name = "Zero payments remaining",
.principalOutstanding = Number{1'000},
.periodicRate = Number{5, -2},
.paymentsRemaining = 0,
.expectedPeriodicPayment = Number{0},
},
{
.name = "Zero periodic rate",
.principalOutstanding = Number{1'000},
.periodicRate = Number{0},
.paymentsRemaining = 4,
.expectedPeriodicPayment = Number{250},
},
{
.name = "Standard case",
.principalOutstanding = Number{1'000},
.periodicRate =
loanPeriodicRate(TenthBips32(100'000), 30 * 24 * 60 * 60),
.paymentsRemaining = 3,
.expectedPeriodicPayment =
Number{3895690663961231, -13}, // from calc
},
};
for (auto const& tc : testCases)
{
testcase("loanPeriodicPayment: " + tc.name);
auto const computedPeriodicPayment = loanPeriodicPayment(
tc.principalOutstanding, tc.periodicRate, tc.paymentsRemaining);
BEAST_EXPECTS(
computedPeriodicPayment == tc.expectedPeriodicPayment,
"Periodic payment mismatch: expected " +
to_string(tc.expectedPeriodicPayment) + ", got " +
to_string(computedPeriodicPayment));
}
}
void
testLoanPrincipalFromPeriodicPayment()
{
using namespace jtx;
using namespace ripple::detail;
struct TestCase
{
std::string name;
Number periodicPayment;
Number periodicRate;
std::uint32_t paymentsRemaining;
Number expectedPrincipalOutstanding;
};
auto const testCases = std::vector<TestCase>{
{
.name = "Zero periodic payment",
.periodicPayment = Number{0},
.periodicRate = Number{5, -2},
.paymentsRemaining = 5,
.expectedPrincipalOutstanding = Number{0},
},
{
.name = "Zero payments remaining",
.periodicPayment = Number{1'000},
.periodicRate = Number{5, -2},
.paymentsRemaining = 0,
.expectedPrincipalOutstanding = Number{0},
},
{
.name = "Zero periodic rate",
.periodicPayment = Number{250},
.periodicRate = Number{0},
.paymentsRemaining = 4,
.expectedPrincipalOutstanding = Number{1'000},
},
{
.name = "Standard case",
.periodicPayment = Number{3895690663961231, -13}, // from calc
.periodicRate =
loanPeriodicRate(TenthBips32(100'000), 30 * 24 * 60 * 60),
.paymentsRemaining = 3,
.expectedPrincipalOutstanding = Number{1'000},
},
};
for (auto const& tc : testCases)
{
testcase("loanPrincipalFromPeriodicPayment: " + tc.name);
auto const computedPrincipalOutstanding =
loanPrincipalFromPeriodicPayment(
tc.periodicPayment, tc.periodicRate, tc.paymentsRemaining);
BEAST_EXPECTS(
computedPrincipalOutstanding == tc.expectedPrincipalOutstanding,
"Principal outstanding mismatch: expected " +
to_string(tc.expectedPrincipalOutstanding) + ", got " +
to_string(computedPrincipalOutstanding));
}
}
void
testComputeOverpaymentComponents()
{
testcase("computeOverpaymentComponents");
using namespace jtx;
using namespace ripple::detail;
Account const issuer{"issuer"};
PrettyAsset const IOU = issuer["IOU"];
int32_t const loanScale = 1;
auto const overpayment = Number{1'000};
auto const overpaymentInterestRate = TenthBips32{10'000}; // 10%
auto const overpaymentFeeRate = TenthBips32{50'000}; // 50%
auto const managementFeeRate = TenthBips16{10'000}; // 10%
auto const expectedOverpaymentFee = Number{500}; // 50% of 1,000
auto const expectedOverpaymentInterestGross =
Number{100}; // 10% of 1,000
auto const expectedOverpaymentInterestNet =
Number{90}; // 100 - 10% of 100
auto const expectedOverpaymentManagementFee = Number{10}; // 10% of 100
auto const expectedPrincipalPortion = Number{400}; // 1,000 - 100 - 500
auto const components = detail::computeOverpaymentComponents(
IOU,
loanScale,
overpayment,
overpaymentInterestRate,
overpaymentFeeRate,
managementFeeRate);
BEAST_EXPECT(
components.untrackedManagementFee == expectedOverpaymentFee);
BEAST_EXPECT(
components.untrackedInterest == expectedOverpaymentInterestNet);
BEAST_EXPECT(
components.trackedManagementFeeDelta ==
expectedOverpaymentManagementFee);
BEAST_EXPECT(
components.trackedPrincipalDelta == expectedPrincipalPortion);
BEAST_EXPECT(
components.trackedManagementFeeDelta +
components.untrackedInterest ==
expectedOverpaymentInterestGross);
BEAST_EXPECT(
components.trackedManagementFeeDelta +
components.untrackedInterest +
components.trackedPrincipalDelta +
components.untrackedManagementFee ==
overpayment);
}
void
testComputeInterestAndFeeParts()
{
using namespace jtx;
using namespace ripple::detail;
struct TestCase
{
std::string name;
Number interest;
TenthBips16 managementFeeRate;
Number expectedInterestPart;
Number expectedFeePart;
};
Account const issuer{"issuer"};
PrettyAsset const IOU = issuer["IOU"];
std::int32_t const loanScale = 1;
auto const testCases = std::vector<TestCase>{
{.name = "Zero interest",
.interest = Number{0},
.managementFeeRate = TenthBips16{10'000},
.expectedInterestPart = Number{0},
.expectedFeePart = Number{0}},
{.name = "Zero fee rate",
.interest = Number{1'000},
.managementFeeRate = TenthBips16{0},
.expectedInterestPart = Number{1'000},
.expectedFeePart = Number{0}},
{.name = "10% fee rate",
.interest = Number{1'000},
.managementFeeRate = TenthBips16{10'000},
.expectedInterestPart = Number{900},
.expectedFeePart = Number{100}},
};
for (auto const& tc : testCases)
{
testcase("computeInterestAndFeeParts: " + tc.name);
auto const [computedInterestPart, computedFeePart] =
computeInterestAndFeeParts(
IOU, tc.interest, tc.managementFeeRate, loanScale);
BEAST_EXPECTS(
computedInterestPart == tc.expectedInterestPart,
"Interest part mismatch: expected " +
to_string(tc.expectedInterestPart) + ", got " +
to_string(computedInterestPart));
BEAST_EXPECTS(
computedFeePart == tc.expectedFeePart,
"Fee part mismatch: expected " + to_string(tc.expectedFeePart) +
", got " + to_string(computedFeePart));
}
}
void
testLoanLatePaymentInterest()
{
using namespace jtx;
using namespace ripple::detail;
struct TestCase
{
std::string name;
Number principalOutstanding;
TenthBips32 lateInterestRate;
NetClock::time_point parentCloseTime;
std::uint32_t nextPaymentDueDate;
Number expectedLateInterest;
};
auto const testCases = std::vector<TestCase>{
{
.name = "On-time payment",
.principalOutstanding = Number{1'000},
.lateInterestRate = TenthBips32{10'000}, // 10%
.parentCloseTime =
NetClock::time_point{NetClock::duration{3'000}},
.nextPaymentDueDate = 3'000,
.expectedLateInterest = Number{0},
},
{
.name = "Early payment",
.principalOutstanding = Number{1'000},
.lateInterestRate = TenthBips32{10'000}, // 10%
.parentCloseTime =
NetClock::time_point{NetClock::duration{3'000}},
.nextPaymentDueDate = 4'000,
.expectedLateInterest = Number{0},
},
{
.name = "No principal outstanding",
.principalOutstanding = Number{0},
.lateInterestRate = TenthBips32{10'000}, // 10%
.parentCloseTime =
NetClock::time_point{NetClock::duration{3'000}},
.nextPaymentDueDate = 2'000,
.expectedLateInterest = Number{0},
},
{
.name = "No late interest rate",
.principalOutstanding = Number{1'000},
.lateInterestRate = TenthBips32{0}, // 0%
.parentCloseTime =
NetClock::time_point{NetClock::duration{3'000}},
.nextPaymentDueDate = 2'000,
.expectedLateInterest = Number{0},
},
{
.name = "Late payment",
.principalOutstanding = Number{1'000},
.lateInterestRate = TenthBips32{100'000}, // 100%
.parentCloseTime =
NetClock::time_point{NetClock::duration{3'000}},
.nextPaymentDueDate = 2'000,
.expectedLateInterest =
Number{3170979198376459, -17}, // from calc
},
};
for (auto const& tc : testCases)
{
testcase("loanLatePaymentInterest: " + tc.name);
auto const computedLateInterest = loanLatePaymentInterest(
tc.principalOutstanding,
tc.lateInterestRate,
tc.parentCloseTime,
tc.nextPaymentDueDate);
BEAST_EXPECTS(
computedLateInterest == tc.expectedLateInterest,
"Late interest mismatch: expected " +
to_string(tc.expectedLateInterest) + ", got " +
to_string(computedLateInterest));
}
}
void
testLoanAccruedInterest()
{
using namespace jtx;
using namespace ripple::detail;
struct TestCase
{
std::string name;
Number principalOutstanding;
Number periodicRate;
NetClock::time_point parentCloseTime;
std::uint32_t startDate;
std::uint32_t prevPaymentDate;
std::uint32_t paymentInterval;
Number expectedAccruedInterest;
};
auto const testCases = std::vector<TestCase>{
{
.name = "Zero principal outstanding",
.principalOutstanding = Number{0},
.periodicRate = Number{5, -2},
.parentCloseTime =
NetClock::time_point{NetClock::duration{3'000}},
.startDate = 2'000,
.prevPaymentDate = 2'500,
.paymentInterval = 30 * 24 * 60 * 60,
.expectedAccruedInterest = Number{0},
},
{
.name = "Before start date",
.principalOutstanding = Number{1'000},
.periodicRate = Number{5, -2},
.parentCloseTime =
NetClock::time_point{NetClock::duration{1'000}},
.startDate = 2'000,
.prevPaymentDate = 1'500,
.paymentInterval = 30 * 24 * 60 * 60,
.expectedAccruedInterest = Number{0},
},
{
.name = "Zero periodic rate",
.principalOutstanding = Number{1'000},
.periodicRate = Number{0},
.parentCloseTime =
NetClock::time_point{NetClock::duration{3'000}},
.startDate = 2'000,
.prevPaymentDate = 2'500,
.paymentInterval = 30 * 24 * 60 * 60,
.expectedAccruedInterest = Number{0},
},
{
.name = "Zero payment interval",
.principalOutstanding = Number{1'000},
.periodicRate = Number{5, -2},
.parentCloseTime =
NetClock::time_point{NetClock::duration{3'000}},
.startDate = 2'000,
.prevPaymentDate = 2'500,
.paymentInterval = 0,
.expectedAccruedInterest = Number{0},
},
{
.name = "Standard case",
.principalOutstanding = Number{1'000},
.periodicRate = Number{5, -2},
.parentCloseTime =
NetClock::time_point{NetClock::duration{3'000}},
.startDate = 1'000,
.prevPaymentDate = 2'000,
.paymentInterval = 30 * 24 * 60 * 60,
.expectedAccruedInterest =
Number{1929012345679012, -17}, // from calc
},
};
for (auto const& tc : testCases)
{
testcase("loanAccruedInterest: " + tc.name);
auto const computedAccruedInterest = loanAccruedInterest(
tc.principalOutstanding,
tc.periodicRate,
tc.parentCloseTime,
tc.startDate,
tc.prevPaymentDate,
tc.paymentInterval);
BEAST_EXPECTS(
computedAccruedInterest == tc.expectedAccruedInterest,
"Accrued interest mismatch: expected " +
to_string(tc.expectedAccruedInterest) + ", got " +
to_string(computedAccruedInterest));
}
}
// This test overlaps with testLoanAccruedInterest, the test cases only
// exercise the computeFullPaymentInterest parts unique to it.
void
testComputeFullPaymentInterest()
{
using namespace jtx;
using namespace ripple::detail;
struct TestCase
{
std::string name;
Number rawPrincipalOutstanding;
Number periodicRate;
NetClock::time_point parentCloseTime;
std::uint32_t paymentInterval;
std::uint32_t prevPaymentDate;
std::uint32_t startDate;
TenthBips32 closeInterestRate;
Number expectedFullPaymentInterest;
};
auto const testCases = std::vector<TestCase>{
{
.name = "Zero principal outstanding",
.rawPrincipalOutstanding = Number{0},
.periodicRate = Number{5, -2},
.parentCloseTime =
NetClock::time_point{NetClock::duration{3'000}},
.paymentInterval = 30 * 24 * 60 * 60,
.prevPaymentDate = 2'000,
.startDate = 1'000,
.closeInterestRate = TenthBips32{10'000},
.expectedFullPaymentInterest = Number{0},
},
{
.name = "Zero close interest rate",
.rawPrincipalOutstanding = Number{1'000},
.periodicRate = Number{5, -2},
.parentCloseTime =
NetClock::time_point{NetClock::duration{3'000}},
.paymentInterval = 30 * 24 * 60 * 60,
.prevPaymentDate = 2'000,
.startDate = 1'000,
.closeInterestRate = TenthBips32{0},
.expectedFullPaymentInterest =
Number{1929012345679012, -17}, // from calc
},
{
.name = "Standard case",
.rawPrincipalOutstanding = Number{1'000},
.periodicRate = Number{5, -2},
.parentCloseTime =
NetClock::time_point{NetClock::duration{3'000}},
.paymentInterval = 30 * 24 * 60 * 60,
.prevPaymentDate = 2'000,
.startDate = 1'000,
.closeInterestRate = TenthBips32{10'000},
.expectedFullPaymentInterest =
Number{1000192901234568, -13}, // from calc
},
};
for (auto const& tc : testCases)
{
testcase("computeFullPaymentInterest: " + tc.name);
auto const computedFullPaymentInterest = computeFullPaymentInterest(
tc.rawPrincipalOutstanding,
tc.periodicRate,
tc.parentCloseTime,
tc.paymentInterval,
tc.prevPaymentDate,
tc.startDate,
tc.closeInterestRate);
BEAST_EXPECTS(
computedFullPaymentInterest == tc.expectedFullPaymentInterest,
"Full payment interest mismatch: expected " +
to_string(tc.expectedFullPaymentInterest) + ", got " +
to_string(computedFullPaymentInterest));
}
}
void
testTryOverpaymentValueChange()
{
// This test ensures that overpayment value change is computed
// correctly. I am sorry, this unit test will be a pain in the ass.
testcase("tryOverpay - Value Change is the decrease in interest");
using namespace jtx;
using namespace ripple::detail;
Env env{*this};
Account const issuer{"issuer"};
PrettyAsset const asset = issuer["USD"];
// Interest delta is 40 (100 - 50 - 10)
ExtendedPaymentComponents const overpaymentComponents = {
PaymentComponents{
.trackedValueDelta = Number{50, 0},
.trackedPrincipalDelta = Number{50, 0},
.trackedManagementFeeDelta = Number{0, 0},
.specialCase = PaymentSpecialCase::extra,
},
numZero,
numZero,
};
TenthBips16 managementFeeRate{20'000}; // 10%
TenthBips32 loanInterestRate{10'000}; // 20%
Number loanPrincipal{1'000};
std::uint32_t paymentInterval = 30 * 24 * 60 * 60;
std::uint32_t paymentsRemaining = 10;
std::int32_t loanScale = -5;
auto const periodicRate =
loanPeriodicRate(loanInterestRate, paymentInterval);
auto loanProperites = computeLoanProperties(
asset,
loanPrincipal,
loanInterestRate,
paymentInterval,
paymentsRemaining,
managementFeeRate,
loanScale);
std::cout << loanProperites.periodicPayment << std::endl;
std::cout << loanProperites.loanState.valueOutstanding << std::endl;
std::cout << loanProperites.loanState.interestOutstanding()
<< std::endl;
Number periodicPayment = loanProperites.periodicPayment;
auto const ret = tryOverpayment(
asset,
loanScale,
overpaymentComponents,
loanProperites.loanState,
periodicPayment,
periodicRate,
paymentsRemaining,
managementFeeRate,
env.journal);
BEAST_EXPECT(ret);
auto const& [actualPaymentParts, newLoanProperties] = *ret;
auto const newState = newLoanProperties.loanState;
BEAST_EXPECTS(
actualPaymentParts.valueChange ==
newState.interestDue - loanProperites.loanState.interestDue,
" valueChange mismatch: expected " +
to_string(
newState.interestDue -
loanProperites.loanState.interestDue) +
", got " + to_string(actualPaymentParts.valueChange));
BEAST_EXPECTS(
actualPaymentParts.feePaid ==
loanProperites.loanState.managementFeeDue -
newState.managementFeeDue,
" feePaid mismatch: expected " +
to_string(
loanProperites.loanState.managementFeeDue -
newState.managementFeeDue) +
", got " + to_string(actualPaymentParts.feePaid));
BEAST_EXPECTS(
actualPaymentParts.principalPaid ==
loanProperites.loanState.principalOutstanding -
newState.principalOutstanding,
" principalPaid mismatch: expected " +
to_string(
loanProperites.loanState.principalOutstanding -
newState.principalOutstanding) +
", got " + to_string(actualPaymentParts.principalPaid));
BEAST_EXPECTS(
actualPaymentParts.interestPaid ==
loanProperites.loanState.interestDue - newState.interestDue,
" interestPaid mismatch: expected " +
to_string(
loanProperites.loanState.interestDue -
newState.interestDue) +
", got " + to_string(actualPaymentParts.interestPaid));
}
public:
void
run() override
{
testTryOverpaymentValueChange();
testComputeFullPaymentInterest();
testLoanAccruedInterest();
testLoanLatePaymentInterest();
testLoanPeriodicPayment();
testLoanPrincipalFromPeriodicPayment();
testComputeRaisedRate();
testComputePaymentFactor();
testComputeOverpaymentComponents();
testComputeInterestAndFeeParts();
}
};
BEAST_DEFINE_TESTSUITE(LendingHelpers, app, ripple);
} // namespace test
} // namespace ripple

View File

@@ -705,8 +705,9 @@ protected:
<< "\tManagement Fee Rate: " << feeRate << std::endl
<< "\tTotal Payments: " << total << std::endl
<< "\tPeriodic Payment: " << props.periodicPayment << std::endl
<< "\tTotal Value: " << props.totalValueOutstanding << std::endl
<< "\tManagement Fee: " << props.managementFeeOwedToBroker
<< "\tTotal Value: " << props.loanState.valueOutstanding
<< std::endl
<< "\tManagement Fee: " << props.loanState.managementFeeDue
<< std::endl
<< "\tLoan Scale: " << props.loanScale << std::endl
<< "\tFirst payment principal: " << props.firstPaymentPrincipal
@@ -1485,9 +1486,9 @@ protected:
startDate + *loanParams.payInterval,
*loanParams.payTotal,
state.loanScale,
loanProperties.totalValueOutstanding,
loanProperties.loanState.valueOutstanding,
principalRequestAmount,
loanProperties.managementFeeOwedToBroker,
loanProperties.loanState.managementFeeDue,
loanProperties.periodicPayment,
loanFlags | 0);
@@ -1542,9 +1543,9 @@ protected:
nextDueDate,
*loanParams.payTotal,
loanProperties.loanScale,
loanProperties.totalValueOutstanding,
loanProperties.loanState.valueOutstanding,
principalRequestAmount,
loanProperties.managementFeeOwedToBroker,
loanProperties.loanState.managementFeeDue,
loanProperties.periodicPayment,
loanFlags | 0);
@@ -6145,15 +6146,16 @@ protected:
// Accrued + prepayment-penalty interest based on current periodic
// schedule
auto const fullPaymentInterest = computeFullPaymentInterest(
after.periodicPayment,
detail::loanPrincipalFromPeriodicPayment(
after.periodicPayment, periodicRate2, after.paymentRemaining),
periodicRate2,
after.paymentRemaining,
env.current()->parentCloseTime(),
after.paymentInterval,
after.previousPaymentDate,
static_cast<std::uint32_t>(
after.startDate.time_since_epoch().count()),
closeInterestRate);
// Round to asset scale and split interest/fee parts
auto const roundedInterest =
roundToAsset(asset.raw(), fullPaymentInterest, after.loanScale);
@@ -6181,9 +6183,9 @@ protected:
// window by clamping prevPaymentDate to 'now' for the full-pay path.
auto const prevClamped = std::min(after.previousPaymentDate, nowSecs);
auto const fullPaymentInterestClamped = computeFullPaymentInterest(
after.periodicPayment,
detail::loanPrincipalFromPeriodicPayment(
after.periodicPayment, periodicRate2, after.paymentRemaining),
periodicRate2,
after.paymentRemaining,
env.current()->parentCloseTime(),
after.paymentInterval,
prevClamped,

View File

@@ -84,46 +84,6 @@ struct LoanPaymentParts
operator==(LoanPaymentParts const& other) const;
};
/* Describes the initial computed properties of a loan.
*
* This structure contains the fundamental calculated values that define a
* loan's payment structure and amortization schedule. These properties are
* computed:
* - At loan creation (LoanSet transaction)
* - When loan terms change (e.g., after an overpayment that reduces the loan
* balance)
*/
struct LoanProperties
{
// The unrounded amount to be paid at each regular payment period.
// Calculated using the standard amortization formula based on principal,
// interest rate, and number of payments.
// The actual amount paid in the LoanPay transaction must be rounded up to
// the precision of the asset and loan.
Number periodicPayment;
// The total amount the borrower will pay over the life of the loan.
// Equal to periodicPayment * paymentsRemaining.
// This includes principal, interest, and management fees.
Number totalValueOutstanding;
// The total management fee that will be paid to the broker over the
// loan's lifetime. This is a percentage of the total interest (gross)
// as specified by the broker's management fee rate.
Number managementFeeOwedToBroker;
// The scale (decimal places) used for rounding all loan amounts.
// This is the maximum of:
// - The asset's native scale
// - A minimum scale required to represent the periodic payment accurately
// All loan state values (principal, interest, fees) are rounded to this
// scale.
std::int32_t loanScale;
// The principal portion of the first payment.
Number firstPaymentPrincipal;
};
/** This structure captures the parts of a loan state.
*
* Whether the values are raw (unrounded) or rounded will depend on how it was
@@ -161,6 +121,39 @@ struct LoanState
}
};
/* Describes the initial computed properties of a loan.
*
* This structure contains the fundamental calculated values that define a
* loan's payment structure and amortization schedule. These properties are
* computed:
* - At loan creation (LoanSet transaction)
* - When loan terms change (e.g., after an overpayment that reduces the loan
* balance)
*/
struct LoanProperties
{
// The unrounded amount to be paid at each regular payment period.
// Calculated using the standard amortization formula based on principal,
// interest rate, and number of payments.
// The actual amount paid in the LoanPay transaction must be rounded up to
// the precision of the asset and loan.
Number periodicPayment;
// The loan's current state, with all values rounded to the loan's scale.
LoanState loanState;
// The scale (decimal places) used for rounding all loan amounts.
// This is the maximum of:
// - The asset's native scale
// - A minimum scale required to represent the periodic payment accurately
// All loan state values (principal, interest, fees) are rounded to this
// scale.
std::int32_t loanScale;
// The principal portion of the first payment.
Number firstPaymentPrincipal;
};
// Some values get re-rounded to the vault scale any time they are adjusted. In
// addition, they are prevented from ever going below zero. This helps avoid
// accumulated rounding errors and leftover dust amounts.
@@ -202,14 +195,6 @@ computeRawLoanState(
std::uint32_t const paymentRemaining,
TenthBips32 const managementFeeRate);
LoanState
computeRawLoanState(
Number const& periodicPayment,
TenthBips32 interestRate,
std::uint32_t paymentInterval,
std::uint32_t const paymentRemaining,
TenthBips32 const managementFeeRate);
// Constructs a valid LoanState object from arbitrary inputs
LoanState
constructLoanState(
@@ -239,17 +224,6 @@ computeFullPaymentInterest(
std::uint32_t startDate,
TenthBips32 closeInterestRate);
Number
computeFullPaymentInterest(
Number const& periodicPayment,
Number const& periodicRate,
std::uint32_t paymentRemaining,
NetClock::time_point parentCloseTime,
std::uint32_t paymentInterval,
std::uint32_t prevPaymentDate,
std::uint32_t startDate,
TenthBips32 closeInterestRate);
namespace detail {
// These classes and functions should only be accessed by LendingHelper
// functions and unit tests
@@ -387,6 +361,70 @@ struct LoanStateDeltas
nonNegative();
};
Expected<std::pair<LoanPaymentParts, LoanProperties>, TER>
tryOverpayment(
Asset const& asset,
std::int32_t loanScale,
ExtendedPaymentComponents const& overpaymentComponents,
LoanState const& roundedLoanState,
Number const& periodicPayment,
Number const& periodicRate,
std::uint32_t paymentRemaining,
TenthBips16 const managementFeeRate,
beast::Journal j);
Number
computeRaisedRate(Number const& periodicRate, std::uint32_t paymentsRemaining);
Number
computePaymentFactor(
Number const& periodicRate,
std::uint32_t paymentsRemaining);
std::pair<Number, Number>
computeInterestAndFeeParts(
Asset const& asset,
Number const& interest,
TenthBips16 managementFeeRate,
std::int32_t loanScale);
Number
loanPeriodicPayment(
Number const& principalOutstanding,
Number const& periodicRate,
std::uint32_t paymentsRemaining);
Number
loanPrincipalFromPeriodicPayment(
Number const& periodicPayment,
Number const& periodicRate,
std::uint32_t paymentsRemaining);
Number
loanLatePaymentInterest(
Number const& principalOutstanding,
TenthBips32 lateInterestRate,
NetClock::time_point parentCloseTime,
std::uint32_t nextPaymentDueDate);
Number
loanAccruedInterest(
Number const& principalOutstanding,
Number const& periodicRate,
NetClock::time_point parentCloseTime,
std::uint32_t startDate,
std::uint32_t prevPaymentDate,
std::uint32_t paymentInterval);
ExtendedPaymentComponents
computeOverpaymentComponents(
Asset const& asset,
int32_t const loanScale,
Number const& overpayment,
TenthBips32 const overpaymentInterestRate,
TenthBips32 const overpaymentFeeRate,
TenthBips16 const managementFeeRate);
PaymentComponents
computePaymentComponents(
Asset const& asset,
@@ -413,13 +451,22 @@ operator+(LoanState const& lhs, detail::LoanStateDeltas const& rhs);
LoanProperties
computeLoanProperties(
Asset const& asset,
Number principalOutstanding,
Number const& principalOutstanding,
TenthBips32 interestRate,
std::uint32_t paymentInterval,
std::uint32_t paymentsRemaining,
TenthBips32 managementFeeRate,
std::int32_t minimumScale);
LoanProperties
computeLoanProperties(
Asset const& asset,
Number const& principalOutstanding,
Number const& periodicRate,
std::uint32_t paymentsRemaining,
TenthBips32 managementFeeRate,
std::int32_t minimumScale);
bool
isRounded(Asset const& asset, Number const& value, std::int32_t scale);

View File

@@ -2,6 +2,8 @@
// DO NOT REMOVE forces header file include to sort first
#include <xrpld/app/tx/detail/VaultCreate.h>
#include <utility>
namespace ripple {
bool
@@ -100,6 +102,9 @@ computePaymentFactor(
Number const& periodicRate,
std::uint32_t paymentsRemaining)
{
if (paymentsRemaining == 0)
return numZero;
// For zero interest, payment factor is simply 1/paymentsRemaining
if (periodicRate == beast::zero)
return Number{1} / paymentsRemaining;
@@ -132,27 +137,6 @@ loanPeriodicPayment(
computePaymentFactor(periodicRate, paymentsRemaining);
}
/* Calculates the periodic payment amount from annualized interest rate.
* Converts the annual rate to periodic rate before computing payment.
*
* Equation (7) from XLS-66 spec, Section A-2 Equation Glossary
*/
Number
loanPeriodicPayment(
Number const& principalOutstanding,
TenthBips32 interestRate,
std::uint32_t paymentInterval,
std::uint32_t paymentsRemaining)
{
if (principalOutstanding == 0 || paymentsRemaining == 0)
return 0;
Number const periodicRate = loanPeriodicRate(interestRate, paymentInterval);
return loanPeriodicPayment(
principalOutstanding, periodicRate, paymentsRemaining);
}
/* Reverse-calculates principal from periodic payment amount.
* Used to determine theoretical principal at any point in the schedule.
*
@@ -164,6 +148,9 @@ loanPrincipalFromPeriodicPayment(
Number const& periodicRate,
std::uint32_t paymentsRemaining)
{
if (paymentsRemaining == 0)
return numZero;
if (periodicRate == 0)
return periodicPayment * paymentsRemaining;
@@ -171,21 +158,6 @@ loanPrincipalFromPeriodicPayment(
computePaymentFactor(periodicRate, paymentsRemaining);
}
/* Splits gross interest into net interest (to vault) and management fee (to
* broker). Returns pair of (net interest, management fee).
*
* Equation (33) from XLS-66 spec, Section A-2 Equation Glossary
*/
std::pair<Number, Number>
computeInterestAndFeeParts(
Number const& interest,
TenthBips16 managementFeeRate)
{
auto const fee = tenthBipsOfValue(interest, managementFeeRate);
return std::make_pair(interest - fee, fee);
}
/*
* Computes the interest and management fee parts from interest amount.
*
@@ -216,6 +188,12 @@ loanLatePaymentInterest(
NetClock::time_point parentCloseTime,
std::uint32_t nextPaymentDueDate)
{
if (principalOutstanding == beast::zero)
return numZero;
if (lateInterestRate == TenthBips32{0})
return numZero;
auto const now = parentCloseTime.time_since_epoch().count();
// If the payment is not late by any amount of time, then there's no late
@@ -248,6 +226,9 @@ loanAccruedInterest(
if (periodicRate == beast::zero)
return numZero;
if (paymentInterval == 0)
return numZero;
auto const lastPaymentDate = std::max(prevPaymentDate, startDate);
auto const now = parentCloseTime.time_since_epoch().count();
@@ -403,21 +384,15 @@ doPayment(
* The function preserves accumulated rounding errors across the re-amortization
* to ensure the loan state remains consistent with its payment history.
*/
Expected<LoanPaymentParts, TER>
Expected<std::pair<LoanPaymentParts, LoanProperties>, TER>
tryOverpayment(
Asset const& asset,
std::int32_t loanScale,
ExtendedPaymentComponents const& overpaymentComponents,
Number& totalValueOutstanding,
Number& principalOutstanding,
Number& managementFeeOutstanding,
Number& periodicPayment,
TenthBips32 interestRate,
std::uint32_t paymentInterval,
LoanState const& roundedOldState,
Number const& periodicPayment,
Number const& periodicRate,
std::uint32_t paymentRemaining,
std::uint32_t prevPaymentDate,
std::optional<std::uint32_t> nextDueDate,
TenthBips16 const managementFeeRate,
beast::Journal j)
{
@@ -425,15 +400,11 @@ tryOverpayment(
auto const raw = computeRawLoanState(
periodicPayment, periodicRate, paymentRemaining, managementFeeRate);
// Get the actual loan state (with accumulated rounding from past payments)
auto const rounded = constructLoanState(
totalValueOutstanding, principalOutstanding, managementFeeOutstanding);
// Calculate the accumulated rounding errors. These need to be preserved
// across the re-amortization to maintain consistency with the loan's
// payment history. Without preserving these errors, the loan could end
// up with a different total value than what the borrower has actually paid.
auto const errors = rounded - raw;
auto const errors = roundedOldState - raw;
// Compute the new principal by applying the overpayment to the raw
// (theoretical) principal. Use max with 0 to ensure we never go negative.
@@ -447,8 +418,7 @@ tryOverpayment(
auto newLoanProperties = computeLoanProperties(
asset,
newRawPrincipal,
interestRate,
paymentInterval,
periodicRate,
paymentRemaining,
managementFeeRate,
loanScale);
@@ -456,7 +426,7 @@ tryOverpayment(
JLOG(j.debug()) << "new periodic payment: "
<< newLoanProperties.periodicPayment
<< ", new total value: "
<< newLoanProperties.totalValueOutstanding
<< newLoanProperties.loanState.valueOutstanding
<< ", first payment principal: "
<< newLoanProperties.firstPaymentPrincipal;
@@ -475,37 +445,35 @@ tryOverpayment(
// rounding errors. This ensures the loan's tracked state remains
// consistent with its payment history.
principalOutstanding = std::clamp(
auto const principalOutstanding = std::clamp(
roundToAsset(
asset, newRaw.principalOutstanding, loanScale, Number::upward),
numZero,
rounded.principalOutstanding);
totalValueOutstanding = std::clamp(
roundedOldState.principalOutstanding);
auto const totalValueOutstanding = std::clamp(
roundToAsset(
asset,
principalOutstanding + newRaw.interestOutstanding(),
loanScale,
Number::upward),
numZero,
rounded.valueOutstanding);
managementFeeOutstanding = std::clamp(
roundedOldState.valueOutstanding);
auto const managementFeeOutstanding = std::clamp(
roundToAsset(asset, newRaw.managementFeeDue, loanScale),
numZero,
rounded.managementFeeDue);
roundedOldState.managementFeeDue);
auto const newRounded = constructLoanState(
auto const roundedNewState = constructLoanState(
totalValueOutstanding, principalOutstanding, managementFeeOutstanding);
// Update newLoanProperties so that checkLoanGuards can make an accurate
// evaluation.
newLoanProperties.totalValueOutstanding = newRounded.valueOutstanding;
newLoanProperties.loanState = roundedNewState;
JLOG(j.debug()) << "new rounded value: " << newRounded.valueOutstanding
<< ", principal: " << newRounded.principalOutstanding
<< ", interest gross: " << newRounded.interestOutstanding();
// Update the periodic payment to reflect the re-amortized schedule
periodicPayment = newLoanProperties.periodicPayment;
JLOG(j.debug()) << "new rounded value: " << roundedNewState.valueOutstanding
<< ", principal: " << roundedNewState.principalOutstanding
<< ", interest gross: "
<< roundedNewState.interestOutstanding();
// check that the loan is still valid
if (auto const ter = checkLoanGuards(
@@ -515,7 +483,7 @@ tryOverpayment(
// small interest amounts, that may have already been paid
// off. Check what's still outstanding. This should
// guarantee that the interest checks pass.
newRounded.interestOutstanding() != beast::zero,
roundedNewState.interestOutstanding() != beast::zero,
paymentRemaining,
newLoanProperties,
j))
@@ -529,61 +497,64 @@ tryOverpayment(
// Validate that all computed properties are reasonable. These checks should
// never fail under normal circumstances, but we validate defensively.
if (newLoanProperties.periodicPayment <= 0 ||
newLoanProperties.totalValueOutstanding <= 0 ||
newLoanProperties.managementFeeOwedToBroker < 0)
newLoanProperties.loanState.valueOutstanding <= 0 ||
newLoanProperties.loanState.managementFeeDue < 0)
{
// LCOV_EXCL_START
JLOG(j.warn()) << "Overpayment not allowed: Computed loan "
"properties are invalid. Does "
"not compute. TotalValueOutstanding: "
<< newLoanProperties.totalValueOutstanding
<< newLoanProperties.loanState.valueOutstanding
<< ", PeriodicPayment : "
<< newLoanProperties.periodicPayment
<< ", ManagementFeeOwedToBroker: "
<< newLoanProperties.managementFeeOwedToBroker;
<< newLoanProperties.loanState.managementFeeDue;
return Unexpected(tesSUCCESS);
// LCOV_EXCL_STOP
}
auto const deltas = rounded - newRounded;
auto const deltas = roundedOldState - roundedNewState;
// The change in loan management fee is equal to the change between the old
// and the new outstanding management fees
XRPL_ASSERT_PARTS(
deltas.managementFee ==
rounded.managementFeeDue - managementFeeOutstanding,
roundedOldState.managementFeeDue - managementFeeOutstanding,
"ripple::detail::tryOverpayment",
"no fee change");
auto const hypotheticalValueOutstanding =
rounded.valueOutstanding - deltas.principal;
// Calculate how the loan's value changed due to the overpayment.
// This should be negative (value decreased) or zero. A principal
// overpayment should never increase the loan's value.
auto const valueChange =
newRounded.valueOutstanding - hypotheticalValueOutstanding;
auto const valueChange = -deltas.interest;
if (valueChange > 0)
{
JLOG(j.warn()) << "Principal overpayment would increase the value of "
"the loan. Ignore the overpayment";
return Unexpected(tesSUCCESS);
}
return LoanPaymentParts{
// Principal paid is the reduction in principal outstanding
.principalPaid = deltas.principal,
// Interest paid is the reduction in interest due
.interestPaid =
deltas.interest + overpaymentComponents.untrackedInterest,
// Value change includes both the reduction from paying down principal
// (negative) and any untracked interest penalties (positive, e.g., if
// the overpayment itself incurs a fee)
.valueChange =
valueChange + overpaymentComponents.trackedInterestPart(),
// Fee paid includes both the reduction in tracked management fees and
// any untracked fees on the overpayment itself
.feePaid = deltas.managementFee +
overpaymentComponents.untrackedManagementFee};
return std::make_pair(
LoanPaymentParts{
// Principal paid is the reduction in principal outstanding
.principalPaid = deltas.principal,
// Interest paid is the reduction in interest due
.interestPaid =
deltas.interest + overpaymentComponents.untrackedInterest,
// Value change includes both the reduction from paying down
// principal
// (negative) and any untracked interest penalties (positive, e.g.,
// if
// the overpayment itself incurs a fee)
.valueChange =
valueChange + overpaymentComponents.trackedInterestPart(),
// Fee paid includes both the reduction in tracked management fees
// and
// any untracked fees on the overpayment itself
.feePaid = deltas.managementFee +
overpaymentComponents.untrackedManagementFee,
},
newLoanProperties);
}
/* Validates and applies an overpayment to the loan state.
@@ -607,23 +578,16 @@ doOverpayment(
NumberProxy& principalOutstandingProxy,
NumberProxy& managementFeeOutstandingProxy,
NumberProxy& periodicPaymentProxy,
TenthBips32 const interestRate,
std::uint32_t const paymentInterval,
Number const& periodicRate,
std::uint32_t const paymentRemaining,
std::uint32_t const prevPaymentDate,
std::optional<std::uint32_t> const nextDueDate,
TenthBips16 const managementFeeRate,
beast::Journal j)
{
// Create temporary copies of the loan state that can be safely modified
// and discarded if the overpayment doesn't work out. This prevents
// corrupting the actual ledger data if validation fails.
Number totalValueOutstanding = totalValueOutstandingProxy;
Number principalOutstanding = principalOutstandingProxy;
Number managementFeeOutstanding = managementFeeOutstandingProxy;
Number periodicPayment = periodicPaymentProxy;
auto const loanState = constructLoanState(
totalValueOutstandingProxy,
principalOutstandingProxy,
managementFeeOutstandingProxy);
auto const periodicPayment = periodicPaymentProxy;
JLOG(j.debug())
<< "overpayment components:"
<< ", totalValue before: " << *totalValueOutstandingProxy
@@ -642,33 +606,28 @@ doOverpayment(
asset,
loanScale,
overpaymentComponents,
totalValueOutstanding,
principalOutstanding,
managementFeeOutstanding,
loanState,
periodicPayment,
interestRate,
paymentInterval,
periodicRate,
paymentRemaining,
prevPaymentDate,
nextDueDate,
managementFeeRate,
j);
if (!ret)
return Unexpected(ret.error());
auto const& loanPaymentParts = *ret;
auto const& [loanPaymentParts, newLoanProperties] = *ret;
auto const newRoundedLoanState = newLoanProperties.loanState;
// Safety check: the principal must have decreased. If it didn't (or
// increased!), something went wrong in the calculation and we should
// reject the overpayment.
if (principalOutstandingProxy <= principalOutstanding)
if (principalOutstandingProxy <= newRoundedLoanState.principalOutstanding)
{
// LCOV_EXCL_START
JLOG(j.warn()) << "Overpayment not allowed: principal "
<< "outstanding did not decrease. Before: "
<< *principalOutstandingProxy
<< ". After: " << principalOutstanding;
<< *principalOutstandingProxy << ". After: "
<< newRoundedLoanState.principalOutstanding;
return Unexpected(tesSUCCESS);
// LCOV_EXCL_STOP
}
@@ -679,28 +638,29 @@ doOverpayment(
XRPL_ASSERT_PARTS(
overpaymentComponents.trackedPrincipalDelta ==
principalOutstandingProxy - principalOutstanding,
principalOutstandingProxy -
newRoundedLoanState.principalOutstanding,
"ripple::detail::doOverpayment",
"principal change agrees");
// I'm not 100% sure the following asserts are correct. If in doubt, and
// everything else works, remove any that cause trouble.
JLOG(j.debug()) << "valueChange: " << loanPaymentParts.valueChange
<< ", totalValue before: " << *totalValueOutstandingProxy
<< ", totalValue after: " << totalValueOutstanding
<< ", totalValue delta: "
<< (totalValueOutstandingProxy - totalValueOutstanding)
<< ", principalDelta: "
<< overpaymentComponents.trackedPrincipalDelta
<< ", principalPaid: " << loanPaymentParts.principalPaid
<< ", Computed difference: "
<< overpaymentComponents.trackedPrincipalDelta -
(totalValueOutstandingProxy - totalValueOutstanding);
JLOG(j.debug())
<< "valueChange: " << loanPaymentParts.valueChange
<< ", totalValue before: " << *totalValueOutstandingProxy
<< ", totalValue after: " << newRoundedLoanState.valueOutstanding
<< ", totalValue delta: "
<< (totalValueOutstandingProxy - newRoundedLoanState.valueOutstanding)
<< ", principalDelta: " << overpaymentComponents.trackedPrincipalDelta
<< ", principalPaid: " << loanPaymentParts.principalPaid
<< ", Computed difference: "
<< overpaymentComponents.trackedPrincipalDelta -
(totalValueOutstandingProxy - newRoundedLoanState.valueOutstanding);
XRPL_ASSERT_PARTS(
loanPaymentParts.valueChange ==
totalValueOutstanding -
newRoundedLoanState.valueOutstanding -
(totalValueOutstandingProxy -
overpaymentComponents.trackedPrincipalDelta) +
overpaymentComponents.trackedInterestPart(),
@@ -715,10 +675,10 @@ doOverpayment(
// All validations passed, so update the proxy objects (which will
// modify the actual Loan ledger object)
totalValueOutstandingProxy = totalValueOutstanding;
principalOutstandingProxy = principalOutstanding;
managementFeeOutstandingProxy = managementFeeOutstanding;
periodicPaymentProxy = periodicPayment;
totalValueOutstandingProxy = newRoundedLoanState.valueOutstanding;
principalOutstandingProxy = newRoundedLoanState.principalOutstanding;
managementFeeOutstandingProxy = newRoundedLoanState.managementFeeDue;
periodicPaymentProxy = newLoanProperties.periodicPayment;
return loanPaymentParts;
}
@@ -1225,17 +1185,12 @@ computeOverpaymentComponents(
// This interest doesn't follow the normal amortization schedule - it's
// a one-time charge for paying early.
// Equation (20) and (21) from XLS-66 spec, Section A-2 Equation Glossary
auto const [rawOverpaymentInterest, _] = [&]() {
Number const interest =
tenthBipsOfValue(overpayment, overpaymentInterestRate);
return detail::computeInterestAndFeeParts(interest, managementFeeRate);
}();
// Round the penalty interest components to the loan scale
auto const [roundedOverpaymentInterest, roundedOverpaymentManagementFee] =
[&]() {
Number const interest =
roundToAsset(asset, rawOverpaymentInterest, loanScale);
auto const interest = roundToAsset(
asset,
tenthBipsOfValue(overpayment, overpaymentInterestRate),
loanScale);
return detail::computeInterestAndFeeParts(
asset, interest, managementFeeRate, loanScale);
}();
@@ -1316,7 +1271,7 @@ checkLoanGuards(
beast::Journal j)
{
auto const totalInterestOutstanding =
properties.totalValueOutstanding - principalRequested;
properties.loanState.valueOutstanding - principalRequested;
// Guard 1: if there is no computed total interest over the life of the
// loan for a non-zero interest rate, we cannot properly amortize the
// loan
@@ -1371,13 +1326,13 @@ checkLoanGuards(
NumberRoundModeGuard mg(Number::upward);
if (std::int64_t const computedPayments{
properties.totalValueOutstanding / roundedPayment};
properties.loanState.valueOutstanding / roundedPayment};
computedPayments != paymentTotal)
{
JLOG(j.warn()) << "Loan Periodic payment ("
<< properties.periodicPayment << ") rounding ("
<< roundedPayment << ") on a total value of "
<< properties.totalValueOutstanding
<< properties.loanState.valueOutstanding
<< " can not complete the loan in the specified "
"number of payments ("
<< computedPayments << " != " << paymentTotal << ")";
@@ -1429,31 +1384,6 @@ computeFullPaymentInterest(
return accruedInterest + prepaymentPenalty;
}
Number
computeFullPaymentInterest(
Number const& periodicPayment,
Number const& periodicRate,
std::uint32_t paymentRemaining,
NetClock::time_point parentCloseTime,
std::uint32_t paymentInterval,
std::uint32_t prevPaymentDate,
std::uint32_t startDate,
TenthBips32 closeInterestRate)
{
Number const rawPrincipalOutstanding =
detail::loanPrincipalFromPeriodicPayment(
periodicPayment, periodicRate, paymentRemaining);
return computeFullPaymentInterest(
rawPrincipalOutstanding,
periodicRate,
parentCloseTime,
paymentInterval,
prevPaymentDate,
startDate,
closeInterestRate);
}
/* Calculates the theoretical loan state at maximum precision for a given point
* in the amortization schedule.
*
@@ -1515,21 +1445,6 @@ computeRawLoanState(
.managementFeeDue = rawManagementFeeOutstanding};
};
LoanState
computeRawLoanState(
Number const& periodicPayment,
TenthBips32 interestRate,
std::uint32_t paymentInterval,
std::uint32_t const paymentRemaining,
TenthBips32 const managementFeeRate)
{
return computeRawLoanState(
periodicPayment,
loanPeriodicRate(interestRate, paymentInterval),
paymentRemaining,
managementFeeRate);
}
/* Constructs a LoanState from rounded Loan ledger object values.
*
* This function creates a LoanState structure from the three tracked values
@@ -1600,7 +1515,7 @@ computeManagementFee(
LoanProperties
computeLoanProperties(
Asset const& asset,
Number principalOutstanding,
Number const& principalOutstanding,
TenthBips32 interestRate,
std::uint32_t paymentInterval,
std::uint32_t paymentsRemaining,
@@ -1611,7 +1526,24 @@ computeLoanProperties(
XRPL_ASSERT(
interestRate == 0 || periodicRate > 0,
"ripple::computeLoanProperties : valid rate");
return computeLoanProperties(
asset,
principalOutstanding,
periodicRate,
paymentsRemaining,
managementFeeRate,
minimumScale);
}
LoanProperties
computeLoanProperties(
Asset const& asset,
Number const& principalOutstanding,
Number const& periodicRate,
std::uint32_t paymentsRemaining,
TenthBips32 managementFeeRate,
std::int32_t minimumScale)
{
auto const periodicPayment = detail::loanPeriodicPayment(
principalOutstanding, periodicRate, paymentsRemaining);
@@ -1645,12 +1577,12 @@ computeLoanProperties(
// Since we just figured out the loan scale, we haven't been able to
// validate that the principal fits in it, so to allow this function to
// succeed, round it here, and let the caller do the validation.
principalOutstanding = roundToAsset(
auto const roundedPrincipalOutstanding = roundToAsset(
asset, principalOutstanding, loanScale, Number::to_nearest);
// E<quation (31) from XLS-66 spec, Section A-2 Equation Glossary
auto const totalInterestOutstanding =
totalValueOutstanding - principalOutstanding;
totalValueOutstanding - roundedPrincipalOutstanding;
auto const feeOwedToBroker = computeManagementFee(
asset, totalInterestOutstanding, managementFeeRate, loanScale);
@@ -1680,10 +1612,13 @@ computeLoanProperties(
return LoanProperties{
.periodicPayment = periodicPayment,
.totalValueOutstanding = totalValueOutstanding,
.managementFeeOwedToBroker = feeOwedToBroker,
.loanState = constructLoanState(
totalValueOutstanding,
roundedPrincipalOutstanding,
feeOwedToBroker),
.loanScale = loanScale,
.firstPaymentPrincipal = firstPaymentPrincipal};
.firstPaymentPrincipal = firstPaymentPrincipal,
};
}
/*
@@ -2012,12 +1947,8 @@ loanMakePayment(
principalOutstandingProxy,
managementFeeOutstandingProxy,
periodicPaymentProxy,
interestRate,
paymentInterval,
periodicRate,
paymentRemainingProxy,
prevPaymentDateProxy,
nextDueDateProxy,
managementFeeRate,
j))
totalParts += *overResult;

View File

@@ -67,7 +67,7 @@ LoanBrokerDelete::preclaim(PreclaimContext const& ctx)
JLOG(ctx.j.warn()) << "LoanBrokerDelete: Debt total is "
<< debtTotal << ", which rounds to " << rounded;
return tecHAS_OBLIGATIONS;
// LCOV_EXCL_START
// LCOV_EXCL_STOP
}
}

View File

@@ -417,7 +417,7 @@ LoanSet::doApply()
JLOG(j_.warn())
<< field.f->getName() << " (" << *value
<< ") has too much precision. Total loan value is "
<< properties.totalValueOutstanding << " with a scale of "
<< properties.loanState.valueOutstanding << " with a scale of "
<< properties.loanScale;
return tecPRECISION_LOSS;
}
@@ -434,8 +434,8 @@ LoanSet::doApply()
return ret;
// Check that the other computed values are valid
if (properties.managementFeeOwedToBroker < 0 ||
properties.totalValueOutstanding <= 0 ||
if (properties.loanState.managementFeeDue < 0 ||
properties.loanState.valueOutstanding <= 0 ||
properties.periodicPayment <= 0)
{
// LCOV_EXCL_START
@@ -446,9 +446,9 @@ LoanSet::doApply()
}
LoanState const state = constructLoanState(
properties.totalValueOutstanding,
properties.loanState.valueOutstanding,
principalRequested,
properties.managementFeeOwedToBroker);
properties.loanState.managementFeeDue);
auto const originationFee = tx[~sfLoanOriginationFee].value_or(Number{});
@@ -588,8 +588,8 @@ LoanSet::doApply()
// Set dynamic / computed fields to their initial values
loan->at(sfPrincipalOutstanding) = principalRequested;
loan->at(sfPeriodicPayment) = properties.periodicPayment;
loan->at(sfTotalValueOutstanding) = properties.totalValueOutstanding;
loan->at(sfManagementFeeOutstanding) = properties.managementFeeOwedToBroker;
loan->at(sfTotalValueOutstanding) = properties.loanState.valueOutstanding;
loan->at(sfManagementFeeOutstanding) = properties.loanState.managementFeeDue;
loan->at(sfPreviousPaymentDate) = 0;
loan->at(sfNextPaymentDueDate) = startDate + paymentInterval;
loan->at(sfPaymentRemaining) = paymentTotal;