Skip to main content

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 TaxCalculator and 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:

StatusDescriptionCondition & Trigger
PENDINGPending FundingLoan application active; funding deadline (issuance_height) is in the future and total required amount is not yet raised.
FUNDEDActive LoanLoan fully funded (raisedAmountQNT >= amountQNT); principal disbursed to borrower; awaiting repayment prior to repayment_height.
REPAIDPaid in FullBorrower has settled total due amount (repaidAmountQNT >= totalDueAmountQNT); collateral released to borrower.
OVERDUEOverdueRepayment deadline passed (repayment_height <= currentHeight); loan remains unpaid and unrescued.
RESCUEDRescued by Third PartyDefaulted loan paid off by a third-party rescuer; borrower collateral transferred to the rescuer.
FAILEDFailed to Raise FundsFunding 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

TablePrimary / Composite KeyEntity ClassDescription
public.loanid, heightLoanCore loan application, parameters, state flags, and borrower details.
public.loan_fund_managerid, heightLoanFundManagerVersioned tracking table for aggregate crowdfunding contributions raised (QNTQNT).
public.loan_managerid, heightLoanManagerVersioned tracking table for cumulative repayments made (QNTQNT).
public.currency_lendingfull_hash, idCurrencyLendingIndividual lender contribution records, linking loan IDs to lender accounts.
public.loan_repaymentfull_hash, idLoanRepaymentBorrower repayment transaction logs with associated tax deductions.
public.loan_rescuefull_hash, idLoanRescueDistressed loan recovery logs tracking third-party rescuer settlements.

2. Primary Loan Record (public.loan)

FieldTypeDescription
idlongTransaction ID of initial loan application (globally unique handle).
account_idlongBorrower account ID.
chainintBetaChain identifier hosting the loan transaction context.
totem_idlongIdentifier of the locked totem collateral asset.
totem_qntlongQuantity of totem units held as collateral (QNTQNT).
currency_idlongTarget currency handle requested for the loan principal.
amountlongRequested principal amount in atomic currency units (QNTQNT).
interest_ratelongTotal loan interest rate expressed in basis points (0 to 10,0000 \text{ to } 10,000, where 100 bps=1%100 \text{ bps} = 1\%).
issuance_heightintFunding deadline block height. Must be fully funded by this block.
repayment_heightintRepayment maturity block height. Total due must be repaid by this block.
fundedbooleanFlag set to true when aggregate contributions meet or exceed principal.
repaidbooleanFlag set to true when cumulative repayments cover principal and interest.
rescuedbooleanFlag set to true if a third party covered the outstanding debt.
rescuer_idlongAccount ID of the third-party rescuer (if rescued == true).
creation_heightintBlock height at which the loan application was submitted.

Mathematical Formulas & Calculations

1. Total Interest & Amount Due Calculation

Interest is specified in basis points (1 bps=0.01%1 \text{ bps} = 0.01\%). Interest is calculated using 8-decimal precision rounding:

InterestQNT=amountQNT×interestRate10000\text{InterestQNT} = \left\lfloor \text{amountQNT} \times \frac{\text{interestRate}}{10000} \right\rfloor

TotalDueAmountQNT=amountQNT+InterestQNT\text{TotalDueAmountQNT} = \text{amountQNT} + \text{InterestQNT}

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:

LenderInterestShareQNT=InterestQNT×lenderUnitsQNTamountQNT\text{LenderInterestShareQNT} = \left\lfloor \text{InterestQNT} \times \frac{\text{lenderUnitsQNT}}{\text{amountQNT}} \right\rfloor

TotalLenderReturnQNT=lenderUnitsQNT+LenderInterestShareQNT\text{TotalLenderReturnQNT} = \text{lenderUnitsQNT} + \text{LenderInterestShareQNT}

3. Partial Repayment Share Calculation

During partial repayments or overdue partial distributions, funds are disbursed proportionally across all contributing lenders:

LenderProRataShareQNT=totalRepaidQNT×lenderUnitsQNTamountQNT\text{LenderProRataShareQNT} = \left\lfloor \text{totalRepaidQNT} \times \frac{\text{lenderUnitsQNT}}{\text{amountQNT}} \right\rfloor

4. Remaining Owed Amount & Funding Progress

OwedAmountQNT=TotalDueAmountQNTrepaidAmountQNT\text{OwedAmountQNT} = \text{TotalDueAmountQNT} - \text{repaidAmountQNT}

FundingProgress (%)=(raisedAmountQNTamountQNT)×100\text{FundingProgress (\%)} = \left( \frac{\text{raisedAmountQNT}}{\text{amountQNT}} \right) \times 100

RemainingDays=max(0,repaymentHeightcurrentHeight7200)\text{RemainingDays} = \max \left( 0, \frac{\text{repaymentHeight} - \text{currentHeight}}{7200} \right)


Detailed Lifecycle Operations

1. Application Validation Rules

When nxt.ms.Loan.addLoanApplication() is invoked, the engine enforces compliance checks prior to publishing:

  1. Positive Principal: amountQNT>0\text{amountQNT} > 0 and amountQNT1,000,000,000,000\text{amountQNT} \le 1,000,000,000,000. Unsecured loans cannot exceed 1,000,000,000 QNT1,000,000,000 \text{ QNT}.
  2. Interest Bounds: 100interestRate5000 bps100 \le \text{interestRate} \le 5000 \text{ bps} (1% to 50%1\% \text{ to } 50\%).
  3. Height Hierarchy: currentHeight<issuanceHeight<repaymentHeight\text{currentHeight} < \text{issuanceHeight} < \text{repaymentHeight}.
  4. Fundraising Period: 1,440(issuanceHeightcurrentHeight)43,200 blocks1,440 \le (\text{issuanceHeight} - \text{currentHeight}) \le 43,200 \text{ blocks} (1 to 30 days1 \text{ to } 30 \text{ days}).
  5. Duration Bounds: 1,440(repaymentHeightissuanceHeight)432,000 blocks1,440 \le (\text{repaymentHeight} - \text{issuanceHeight}) \le 432,000 \text{ blocks} (1 to 300 days1 \text{ to } 300 \text{ days}).
  6. Collateral Availability: Borrower must hold sufficient unencumbered totem balance: totemBalanceQNTtotemQNT\text{totemBalanceQNT} \ge \text{totemQNT}. Collateral is locked immediately upon creation.
  7. Active Loan Ceiling: A borrower account cannot exceed MAX_ACTIVE_LOANS_PER_ACCOUNT=5\text{MAX\_ACTIVE\_LOANS\_PER\_ACCOUNT} = 5.

2. Multi-Lender Contributions (CurrencyLending)

Lenders contribute currency units to pending loans via LendingAttachment.

  • Minimum Contribution: MIN_LENDING_AMOUNT=1,000,000 QNT\text{MIN\_LENDING\_AMOUNT} = 1,000,000 \text{ QNT}.
  • Automatic Activation: As contributions accumulate in LoanFundManager, once raisedAmountQNTamountQNT\text{raisedAmountQNT} \ge \text{amountQNT}, fundAmountQNT() triggers loan activation:
    1. Principal units are transferred from each lender to the borrower (less tax).
    2. The borrower's AccountCurrencyLoanUnits is registered with target maturity height repaymentHeight.
    3. Tax is credited via CurrencyTaxRecord.creditTaxAccount().
    4. Emits Loan.Event.LOAN.

3. Settlement & Repayment Flow (LoanRepayment)

Borrowers submit repayments using LoanRepaymentAttachment.

  • Cumulative Tracking: Increments repaidAmountQNT in LoanManager.
  • Full Repayment Trigger: When repaidAmountQNTTotalDueAmountQNT\text{repaidAmountQNT} \ge \text{TotalDueAmountQNT}, completeRepayment() executes:
    1. Computes total returns (principal+pro-rata interest\text{principal} + \text{pro-rata interest}) for each lender in currency_lending.
    2. Calculates protocol settlement tax using TaxCalculator.computeTotalTax().
    3. Credits net funds plus tax adjustment to lender accounts.
    4. Unlocks and returns 100%100\% of locked totem collateral (totemQNT) to the borrower's unconfirmed totem balance.
    5. Emits Loan.Event.LOAN_REPAYMENT.

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 collateral
    loan.rescueLoan(event, eventId, transaction);
    1. Rescuer pays remaining owed units (TotalDueAmountQNTrepaidAmountQNT\text{TotalDueAmountQNT} - \text{repaidAmountQNT}) distributed directly to lenders.
    2. Prior partial repayments made by the borrower are credited back to the borrower's unconfirmed balance.
    3. 100%100\% of borrower's locked collateral (totemQNT) is transferred directly to the rescuer account.
    4. Sets rescued = true, repaid = true, and assigns rescuerId. Emits Loan.Event.LOAN_RESCUE.
    5. Safety Caps: Rescuers are limited to a maximum of 1010 rescued loans per account and MAX_RESCUE_EXPOSURE=50,000,000,000 QNT\text{MAX\_RESCUE\_EXPOSURE} = 50,000,000,000 \text{ QNT}.

5. Expiration of Unfunded Loans

If issuanceHeight is reached and raisedAmountQNT<amountQNT\text{raisedAmountQNT} < \text{amountQNT}:

  • Block listener executes processFailedLoanApplication():
    1. 100%100\% of locked totem collateral is returned to the borrower.
    2. Aggregate contributions are refunded to each respective lender's unconfirmed currency balance.
    3. Loan status updates to FAILED and record is purged from active tables. Emits Loan.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 TierClassification & Risk ProfileQuality Score CeilingRisk Premium (Basis Points)
AAAExcellent — Low RiskBaseline50 bps (0.5%)50 \text{ bps } (0.5\%)
AAVery Good — Low RiskHigh Quality100 bps (1.0%)100 \text{ bps } (1.0\%)
AGood — Moderate RiskStandard Quality200 bps (2.0%)200 \text{ bps } (2.0\%)
BBBAverage — Moderate RiskAcceptable350 bps (3.5%)350 \text{ bps } (3.5\%)
BBBelow Average — High Risk0.50\ge 0.50500 bps (5.0%)500 \text{ bps } (5.0\%)
BPoor — High Risk0.40\ge 0.40750 bps (7.5%)750 \text{ bps } (7.5\%)
CVery Poor — Very High Risk0.30\ge 0.301,000 bps (10.0%)1,000 \text{ bps } (10.0\%)
DDefault — Extreme Risk<0.30< 0.301,500 bps (15.0%)1,500 \text{ bps } (15.0\%)

2. Multi-Factor Risk Assessment Weights

Srisk=0.35Wcollateral+0.25Whistory+0.20WLTV+0.15Wduration+0.05WcurrencyS_{\text{risk}} = 0.35 \cdot W_{\text{collateral}} + 0.25 \cdot W_{\text{history}} + 0.20 \cdot W_{\text{LTV}} + 0.15 \cdot W_{\text{duration}} + 0.05 \cdot W_{\text{currency}}

  • Collateral Quality (35%35\%): Asset stability, liquidity, and age of totem collateral.
  • Borrower History (25%25\%): On-chain track record of past repaid loans vs. defaults.
  • Loan-to-Value (LTV) Ratio (20%20\%): Ratio of principal requested to total collateral valuation.
  • Loan Duration (15%15\%): Exposure time window in block height.
  • Currency Volatility (5%5\%): 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 TypeLimit ParameterPurpose
Single Loan Exposure10%\le 10\% of PortfolioPrevents over-exposure to any single borrower or loan application.
Currency Concentration30%\le 30\% of PortfolioMandates multi-currency diversification across active loan assets.
Risk-Tier Ceiling40%\le 40\% of PortfolioLimits capital allocation in high-risk tiers (BB through D).
Borrower Exposure Cap10,000,000,000 QNT10,000,000,000 \text{ QNT}Maximum aggregate loan exposure allowed to a single borrower account.
Total Lending Cap100,000,000,000 QNT100,000,000,000 \text{ QNT}Maximum active aggregate lending exposure per lender account.

Governance & Operational Parameters

Parameters governing credit markets on Shamwari Network as defined in nxt.ms.LoanConstants:

ParameterValueStandard UnitsOperational Scope
MIN_LOAN_FUNDRAISING_PERIOD1,440 blocks1,440 \text{ blocks}1 Day\sim 1 \text{ Day}Minimum crowdfunding window.
MAX_LOAN_FUNDRAISING_PERIOD43,200 blocks43,200 \text{ blocks}30 Days\sim 30 \text{ Days}Maximum crowdfunding window.
MIN_LOAN_DURATION1,440 blocks1,440 \text{ blocks}1 Day\sim 1 \text{ Day}Minimum loan maturity term.
MAX_LOAN_DURATION432,000 blocks432,000 \text{ blocks}300 Days\sim 300 \text{ Days}Maximum loan maturity term.
MIN_LOAN_INTEREST_RATE100 bps100 \text{ bps}1.0%1.0\%Minimum allowable interest rate.
MAX_LOAN_INTEREST_RATE5,000 bps5,000 \text{ bps}50.0%50.0\%Consumer protection interest ceiling.
MAX_LOAN_AMOUNT1,000,000,000,000 QNT1,000,000,000,000 \text{ QNT}10,000 Units10,000 \text{ Units}Maximum total loan principal.
MAX_UNSECURED_LOAN_AMOUNT1,000,000,000 QNT1,000,000,000 \text{ QNT}10 Units10 \text{ Units}Ceiling for loans without totem collateral.
MAX_ACTIVE_LOANS_PER_ACCOUNT55Active LoansBorrower concurrency limit.
MAX_RESCUED_LOANS_PER_ACCOUNT1010Rescued LoansMaximum defaulted loans a single account may rescue.
MAX_RESCUE_EXPOSURE50,000,000,000 QNT50,000,000,000 \text{ QNT}500 Units500 \text{ Units}Maximum aggregate rescue capital per rescuer.
LOAN_APPLICATION_COOLDOWN1,440 blocks1,440 \text{ blocks}1 Day\sim 1 \text{ Day}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 ClassEvent EnumTrigger Condition
LoanEvent.LOAN_APPLICATIONNew loan application validated and added to order book.
LoanEvent.LOANLoan crowdfunding target reached; funds disbursed to borrower.
LoanEvent.LOAN_REPAYMENTBorrower completes full repayment; collateral unlocked.
LoanEvent.LOAN_RESCUEThird party executes rescue payment and claims collateral.
LoanEvent.LOAN_FAILEDFundraising deadline expired without full funding; refunds issued.
CurrencyLendingEvent.LENDINGLender contribution successfully processed into crowdfunding pool.
LoanRepaymentEvent.LOAN_REPAYMENTIndividual partial or full repayment transaction recorded.
LoanRescueEvent.LOAN_RESCUEDistressed loan rescue transaction recorded.

APIDescription
GetLoanGet loan by ID
GetLoanApplicationsList loan applications
GetActiveLoansList active loans
GetOverdueLoansList overdue loans
GetPaidLoansList paid loans
GetAccountCurrencyLoansGet account currency loans
Loans APIAll 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.LoanRescue to make lenders whole while acquiring collateral assets at discount valuations.