Credit Market & Loan Engine
The Shamwari Credit Market & Loan Engine (nxt.ms.Loan, nxt.ms.CurrencyLending, nxt.ms.LoanRepayment, nxt.ms.LoanRescue) provides a protocol-native, decentralized peer-to-peer lending infrastructure built directly into the Shamwari core runtime.
Unlike smart-contract-based lending protocols that demand heavy over-collateralization and incur VM gas execution costs, Shamwari delivers structured credit markets with multi-lender crowdfunding, totem asset collateralization, quantitative risk scoring across eight credit tiers, lender portfolio diversification guardrails, and automated lifecycle management—including crowd-funded disbursements, partial payment tracking, and emergency third-party loan rescue.
Core Capabilities & Architecture
- Protocol-Native Credit Execution: Executed directly inside
nxt.ms, bypassing virtual machine smart contracts to eliminate reentrancy vulnerabilities, gas dependencies, and execution overhead. - Multi-Lender Crowdfunding: Loan applications function as time-boxed crowdfunding campaigns (
LoanFundManager), enabling multiple lenders to pool capital into a single loan. - Totem Asset Collateralization: Borrowers can lock native asset units (
totemId,totemQNT) as loan collateral, which is automatically returned upon full repayment or transferred to a rescuer in a default event. - Automated Lifecycle Processing: Block-height listeners (
AFTER_BLOCK_APPLY) handle automated loan activations, overdue partial distributions, and collateral/fund refunds for expired applications. - Distressed Loan Rescue: Emergency recovery mechanism (
nxt.ms.LoanRescue) allowing third-party accounts to repay outstanding debt on defaulted loans in exchange for taking ownership of the locked collateral. - Lender Portfolio Protections: Enforces single-loan caps, per-currency limits, and risk-tier concentration bounds via
CurrencyLending.LenderProtection. - Integrated Fiscal Tax Collection: Protocol-level tax deductions are calculated via
TaxCalculatorand credited to the designated BetaChain tax collector on both lending and repayment settlement events.
Loan Status & Lifecycle State Machine
A loan transitions through six distinct operational states managed by nxt.ms.Loan.LoanStatus:
| Status | Description | Condition & Trigger |
|---|---|---|
PENDING | Pending Funding | Loan application active; funding deadline (issuance_height) is in the future and total required amount is not yet raised. |
FUNDED | Active Loan | Loan fully funded (raisedAmountQNT >= amountQNT); principal disbursed to borrower; awaiting repayment prior to repayment_height. |
REPAID | Paid in Full | Borrower has settled total due amount (repaidAmountQNT >= totalDueAmountQNT); collateral released to borrower. |
OVERDUE | Overdue | Repayment deadline passed (repayment_height <= currentHeight); loan remains unpaid and unrescued. |
RESCUED | Rescued by Third Party | Defaulted loan paid off by a third-party rescuer; borrower collateral transferred to the rescuer. |
FAILED | Failed to Raise Funds | Funding deadline passed (issuance_height <= currentHeight) without raising target amount. All contributions refunded to lenders and collateral unlocked. |
┌───────────────────────────────┐
│ Loan Application Submitted │
└───────────────┬───────────────┘
│
▼
┌───────────────────────────┐
│ PENDING FUNDING │
└─────┬───────────────┬─────┘
│ │
Target Amount Raised │ │ Funding Deadline Reached
(raisedAmount >= amount) │ │ (height >= issuance_height)
▼ ▼
┌───────────┐ ┌───────────┐
│ FUNDED │ │ FAILED │
└─────┬─────┘ └───────────┘
│ ▲
Repayment Deadline │ │ (Collateral & Contributions
Reached Unpaid │ │ Refunded to Parties)
▼ │
┌───────────┐ │
│ OVERDUE │─────────┘
└─────┬─────┘
│
┌──────────────────┴──────────────────┐
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ REPAID │ │ RESCUED │
└─────────────┘ └─────────────┘
(Paid by Borrower) (Paid by Rescuer)
Data Model & Relational Schema
The Credit System maintains relational database tables indexed by transaction hashes, loan IDs, block height, and account keys.
1. Primary Credit Entities
| Table | Primary / Composite Key | Entity Class | Description |
|---|---|---|---|
public.loan | id, height | Loan | Core loan application, parameters, state flags, and borrower details. |
public.loan_fund_manager | id, height | LoanFundManager | Versioned tracking table for aggregate crowdfunding contributions raised (). |
public.loan_manager | id, height | LoanManager | Versioned tracking table for cumulative repayments made (). |
public.currency_lending | full_hash, id | CurrencyLending | Individual lender contribution records, linking loan IDs to lender accounts. |
public.loan_repayment | full_hash, id | LoanRepayment | Borrower repayment transaction logs with associated tax deductions. |
public.loan_rescue | full_hash, id | LoanRescue | Distressed loan recovery logs tracking third-party rescuer settlements. |
2. Primary Loan Record (public.loan)
| Field | Type | Description |
|---|---|---|
id | long | Transaction ID of initial loan application (globally unique handle). |
account_id | long | Borrower account ID. |
chain | int | BetaChain identifier hosting the loan transaction context. |
totem_id | long | Identifier of the locked totem collateral asset. |
totem_qnt | long | Quantity of totem units held as collateral (). |
currency_id | long | Target currency handle requested for the loan principal. |
amount | long | Requested principal amount in atomic currency units (). |
interest_rate | long | Total loan interest rate expressed in basis points (, where ). |
issuance_height | int | Funding deadline block height. Must be fully funded by this block. |
repayment_height | int | Repayment maturity block height. Total due must be repaid by this block. |
funded | boolean | Flag set to true when aggregate contributions meet or exceed principal. |
repaid | boolean | Flag set to true when cumulative repayments cover principal and interest. |
rescued | boolean | Flag set to true if a third party covered the outstanding debt. |
rescuer_id | long | Account ID of the third-party rescuer (if rescued == true). |
creation_height | int | Block height at which the loan application was submitted. |
Mathematical Formulas & Calculations
1. Total Interest & Amount Due Calculation
Interest is specified in basis points (). Interest is calculated using 8-decimal precision rounding:
2. Lender Interest Share Attribution
When a loan is repaid, each lender receives their initial principal contribution plus a pro-rata share of the collected interest based on their share of total principal contributed:
3. Partial Repayment Share Calculation
During partial repayments or overdue partial distributions, funds are disbursed proportionally across all contributing lenders:
4. Remaining Owed Amount & Funding Progress
Detailed Lifecycle Operations
1. Application Validation Rules
When nxt.ms.Loan.addLoanApplication() is invoked, the engine enforces compliance checks prior to publishing:
- Positive Principal: and . Unsecured loans cannot exceed .
- Interest Bounds: ().
- Height Hierarchy: .
- Fundraising Period: ().
- Duration Bounds: ().
- Collateral Availability: Borrower must hold sufficient unencumbered totem balance: . Collateral is locked immediately upon creation.
- Active Loan Ceiling: A borrower account cannot exceed .
2. Multi-Lender Contributions (CurrencyLending)
Lenders contribute currency units to pending loans via LendingAttachment.
- Minimum Contribution: .
- Automatic Activation: As contributions accumulate in
LoanFundManager, once ,fundAmountQNT()triggers loan activation:- Principal units are transferred from each lender to the borrower (less tax).
- The borrower's
AccountCurrencyLoanUnitsis registered with target maturity heightrepaymentHeight. - Tax is credited via
CurrencyTaxRecord.creditTaxAccount(). - Emits
Loan.Event.LOAN.
3. Settlement & Repayment Flow (LoanRepayment)
Borrowers submit repayments using LoanRepaymentAttachment.
- Cumulative Tracking: Increments
repaidAmountQNTinLoanManager. - Full Repayment Trigger: When ,
completeRepayment()executes:- Computes total returns () for each lender in
currency_lending. - Calculates protocol settlement tax using
TaxCalculator.computeTotalTax(). - Credits net funds plus tax adjustment to lender accounts.
- Unlocks and returns of locked totem collateral (
totemQNT) to the borrower's unconfirmed totem balance. - Emits
Loan.Event.LOAN_REPAYMENT.
- Computes total returns () for each lender in
4. Overdue Handling & Third-Party Rescue (LoanRescue)
If repaymentHeight is reached without full repayment:
- Overdue Processing:
processOverdueLoan()distributes any available partial repayments pro-rata to lenders based on their contribution share. - Third-Party Rescue Execution: Any third-party account can invoke
rescueLoan():// Third-party rescuer pays remaining debt and assumes collateralloan.rescueLoan(event, eventId, transaction);- Rescuer pays remaining owed units () distributed directly to lenders.
- Prior partial repayments made by the borrower are credited back to the borrower's unconfirmed balance.
- of borrower's locked collateral (
totemQNT) is transferred directly to the rescuer account. - Sets
rescued = true,repaid = true, and assignsrescuerId. EmitsLoan.Event.LOAN_RESCUE. - Safety Caps: Rescuers are limited to a maximum of rescued loans per account and .
5. Expiration of Unfunded Loans
If issuanceHeight is reached and :
- Block listener executes
processFailedLoanApplication():- of locked totem collateral is returned to the borrower.
- Aggregate contributions are refunded to each respective lender's unconfirmed currency balance.
- Loan status updates to
FAILEDand record is purged from active tables. EmitsLoan.Event.LOAN_FAILED.
Risk Management & Credit Scoring Model
Shamwari implements a quantitative credit evaluation model through RiskCalculator, scoring loan applications across key risk vectors to classify borrowers into standardized credit tiers.
1. Credit Tier Framework & Risk Premiums
| Credit Tier | Classification & Risk Profile | Quality Score Ceiling | Risk Premium (Basis Points) |
|---|---|---|---|
AAA | Excellent — Low Risk | Baseline | |
AA | Very Good — Low Risk | High Quality | |
A | Good — Moderate Risk | Standard Quality | |
BBB | Average — Moderate Risk | Acceptable | |
BB | Below Average — High Risk | ||
B | Poor — High Risk | ||
C | Very Poor — Very High Risk | ||
D | Default — Extreme Risk |
2. Multi-Factor Risk Assessment Weights
- Collateral Quality (): Asset stability, liquidity, and age of totem collateral.
- Borrower History (): On-chain track record of past repaid loans vs. defaults.
- Loan-to-Value (LTV) Ratio (): Ratio of principal requested to total collateral valuation.
- Loan Duration (): Exposure time window in block height.
- Currency Volatility (): Price stability of the borrowed currency token.
3. Lender Portfolio Diversification Guardrails (LenderProtection)
To prevent catastrophic lender concentration, CurrencyLending.LenderProtection enforces protocol-level checks prior to accepting lending transactions:
| Constraint Type | Limit Parameter | Purpose |
|---|---|---|
| Single Loan Exposure | of Portfolio | Prevents over-exposure to any single borrower or loan application. |
| Currency Concentration | of Portfolio | Mandates multi-currency diversification across active loan assets. |
| Risk-Tier Ceiling | of Portfolio | Limits capital allocation in high-risk tiers (BB through D). |
| Borrower Exposure Cap | Maximum aggregate loan exposure allowed to a single borrower account. | |
| Total Lending Cap | Maximum active aggregate lending exposure per lender account. |
Governance & Operational Parameters
Parameters governing credit markets on Shamwari Network as defined in nxt.ms.LoanConstants:
| Parameter | Value | Standard Units | Operational Scope |
|---|---|---|---|
MIN_LOAN_FUNDRAISING_PERIOD | Minimum crowdfunding window. | ||
MAX_LOAN_FUNDRAISING_PERIOD | Maximum crowdfunding window. | ||
MIN_LOAN_DURATION | Minimum loan maturity term. | ||
MAX_LOAN_DURATION | Maximum loan maturity term. | ||
MIN_LOAN_INTEREST_RATE | Minimum allowable interest rate. | ||
MAX_LOAN_INTEREST_RATE | Consumer protection interest ceiling. | ||
MAX_LOAN_AMOUNT | Maximum total loan principal. | ||
MAX_UNSECURED_LOAN_AMOUNT | Ceiling for loans without totem collateral. | ||
MAX_ACTIVE_LOANS_PER_ACCOUNT | Active Loans | Borrower concurrency limit. | |
MAX_RESCUED_LOANS_PER_ACCOUNT | Rescued Loans | Maximum defaulted loans a single account may rescue. | |
MAX_RESCUE_EXPOSURE | Maximum aggregate rescue capital per rescuer. | ||
LOAN_APPLICATION_COOLDOWN | Cooldown between subsequent application submissions. |
Event Listener Matrix
The Credit Engine exposes strongly-typed listeners across entity classes to support real-time block indexers and off-chain analytics engines:
| Entity Class | Event Enum | Trigger Condition |
|---|---|---|
Loan | Event.LOAN_APPLICATION | New loan application validated and added to order book. |
Loan | Event.LOAN | Loan crowdfunding target reached; funds disbursed to borrower. |
Loan | Event.LOAN_REPAYMENT | Borrower completes full repayment; collateral unlocked. |
Loan | Event.LOAN_RESCUE | Third party executes rescue payment and claims collateral. |
Loan | Event.LOAN_FAILED | Fundraising deadline expired without full funding; refunds issued. |
CurrencyLending | Event.LENDING | Lender contribution successfully processed into crowdfunding pool. |
LoanRepayment | Event.LOAN_REPAYMENT | Individual partial or full repayment transaction recorded. |
LoanRescue | Event.LOAN_RESCUE | Distressed loan rescue transaction recorded. |
Related APIs
| API | Description |
|---|---|
| GetLoan | Get loan by ID |
| GetLoanApplications | List loan applications |
| GetActiveLoans | List active loans |
| GetOverdueLoans | List overdue loans |
| GetPaidLoans | List paid loans |
| GetAccountCurrencyLoans | Get account currency loans |
| Loans API | All loan operations |
Primary Use Cases
- Collateralized Micro-Lending: Retail and business borrowers leverage native totem assets as collateral to secure liquidity in fiat-backed sovereign currencies (
ZWG,ZAR,BRL). - Institutional Debt Crowdfunding: Syndicated funding pools where multiple institutional lenders co-fund high-value business loans with automated pro-rata interest distribution.
- Distressed Debt Liquidation: Specialized arbitrageurs and recovery funds step in via
nxt.ms.LoanRescueto make lenders whole while acquiring collateral assets at discount valuations.