Lending Protocol Guide (XLS-66d)
This guide explains how to use the XRPL Lending Protocol with the XrplCSharp SDK. The lending protocol enables on-ledger collateralized loans managed through loan brokers and vaults.
Note: The Lending Protocol requires the
LendingProtocolamendment (XLS-66d). This feature is in draft and subject to change. Requires rippled 3.1.0+.
Table of Contents
- Overview
- Key Concepts
- Transaction Types
- Step-by-Step: Setting Up a Loan Broker
- Step-by-Step: Creating and Managing a Loan
- CounterpartySignature (LoanSet Co-Signing)
- Ledger Objects
- Number Type
- Common Errors
- Best Practices
Overview
The XRPL Lending Protocol introduces on-ledger collateralized lending with the following architecture:
Broker (Lender) Borrower
┌──────────────────────┐ ┌──────────────────────┐
│ │ LoanSet │ │
│ Vault ◄── Deposit │ ◄──────────► │ Receives principal │
│ Cover ◄── Deposit │ (co-signed)│ Repays via LoanPay │
│ LoanBroker ── Loan │ │ │
└──────────────────────┘ └──────────────────────┘
A broker (lender) creates a vault to hold lending assets, sets up a loan broker with lending parameters, and issues loans to borrowers. The borrower co-signs the loan agreement and repays through periodic payments.
Key Concepts
Vault
A vault holds the assets available for lending. Created via VaultCreate, it stores XRP or IOU tokens that the broker can lend out. Before creating a loan broker, you must create and fund a vault.
With the LendingProtocolV1_1 amendment a loan broker can only be attached to a closed-ended vault; LoanBrokerSet on an open-ended one fails with tecNO_PERMISSION. A closed-ended vault moves through three phases fixed at creation, and deposits, withdrawals and new loans are each tied to a phase:
| Phase | Lasts | Allowed |
|---|---|---|
| Subscription | until SubscriptionDate |
VaultDeposit, VaultWithdraw |
| Investment | from SubscriptionDate to RedemptionDate |
LoanSet; VaultDeposit fails with tecEXPIRED, VaultWithdraw with tecTOO_SOON |
| Redemption | from RedemptionDate |
VaultWithdraw; LoanSet fails with tecEXPIRED |
Creating the broker and depositing cover are not tied to a phase. See "Vault Kind (LendingProtocolV1_1)" in the Vault Guide for the date limits. On a network without the amendment, create the vault without VaultKind, SubscriptionDate and RedemptionDate; a node that does not know the amendment refuses them.
Loan Broker
A LoanBroker is a ledger object that represents a lending entity. It references a vault and defines lending parameters such as cover rates, management fees, and debt limits. Created via LoanBrokerSet.
Cover
The broker must deposit cover (collateral from the broker's side) into the loan broker. Cover protects borrowers and ensures the broker has skin in the game. Managed via LoanBrokerCoverDeposit and LoanBrokerCoverWithdraw.
Loan
A Loan is a ledger object representing an active loan between a broker and a borrower. Created via LoanSet (requires co-signing by both parties). The loan tracks principal, interest rates, payment schedule, and outstanding balances.
CounterpartySignature
LoanSet is a special transaction that requires two signatures: the broker (submitter) signs the transaction normally, and the borrower (counterparty) provides a CounterpartySignature. Both sign the same transaction, each under its own hash prefix since rippled's fixCleanup3_4_0.
Number Type
Loan-specific numeric fields (e.g., PrincipalRequested, DebtMaximum) use the XRPL Number type — a 12-byte format consisting of an 8-byte signed mantissa and a 4-byte signed exponent. This is different from the standard Amount type used for payments.
Transaction Types
| Transaction | Purpose | Who Submits |
|---|---|---|
LoanBrokerSet |
Create or update a loan broker | Broker |
LoanBrokerDelete |
Delete a loan broker | Broker |
LoanBrokerCoverDeposit |
Deposit cover into a broker | Broker |
LoanBrokerCoverWithdraw |
Withdraw cover from a broker | Broker |
LoanBrokerCoverClawback |
Clawback cover from a holder | Broker |
LoanSet |
Create a new loan (co-signed) | Broker + Borrower |
LoanDelete |
Delete a fully repaid loan | Broker |
LoanManage |
Manage loan state (default/impair/unimpair) | Broker |
LoanPay |
Make a payment on a loan | Borrower |
Step-by-Step: Setting Up a Loan Broker
1. Create a Vault
The broker first creates a closed-ended vault to hold lending assets:
using Xrpl.Models.Transactions;
using Xrpl.Models.Common;
using Xrpl.Models.Ledger; // VaultKind, LedgerIndexType
using Xrpl.Models.Methods;
using Xrpl.Sugar;
using static Xrpl.Models.Common.Common;
// Phase dates are compared with the ledger's close time, not the machine clock
LOLedger ledger = await client.Ledger(
new LedgerRequest { LedgerIndex = new LedgerIndex(LedgerIndexType.Validated) }).Typed();
DateTime now = ((LedgerEntity)ledger.LedgerEntity).CloseTime.Value;
VaultCreate vaultTx = new VaultCreate
{
Account = walletBroker.ClassicAddress,
Asset = new IssuedCurrency { Currency = "XRP" },
VaultKind = (uint)VaultKind.ClosedEnded,
SubscriptionDate = now.AddHours(1), // the deposit in step 2 must happen before this
RedemptionDate = now.AddDays(90), // every loan must be repaid 60 s before this
};
vaultTx = await client.Autofill(vaultTx);
TransactionSummary vaultResult = await client.SubmitAndWait(vaultTx, walletBroker, true);
// Extract VaultID from metadata
string vaultId = GetCreatedObjectId(vaultResult, LedgerEntryType.Vault);
2. Deposit Assets into the Vault
Fund the vault so the broker has assets to lend. Deposits are accepted only in the subscription phase, before SubscriptionDate:
VaultDeposit depositTx = new VaultDeposit
{
Account = walletBroker.ClassicAddress,
VaultID = vaultId,
Amount = new Currency { Value = "100000000", CurrencyCode = "XRP" }, // 100 XRP
};
depositTx = await client.Autofill(depositTx);
await client.SubmitAndWait(depositTx, walletBroker, true);
3. Create the Loan Broker
Create a broker that references the funded vault. The three rates are optional; leave them out for a broker with none:
LoanBrokerSet brokerTx = new LoanBrokerSet
{
Account = walletBroker.ClassicAddress,
VaultID = vaultId,
// Optional rates, fixed at creation. All are in 1/10th of a basis point: 100000 = 100%
CoverRateMinimum = 15000, // 15% of outstanding debt must be covered by first-loss capital
CoverRateLiquidation = 12000, // 12% of the minimum cover is moved to the vault on a default
ManagementFeeRate = 100, // 0.1% management fee
};
brokerTx = await client.Autofill(brokerTx);
TransactionSummary brokerResult = await client.SubmitAndWait(brokerTx, walletBroker, true);
string brokerId = GetCreatedObjectId(brokerResult, LedgerEntryType.LoanBroker);
The rates can only be set here. A LoanBrokerSet that modifies an existing broker carries LoanBrokerID and must not include them: rippled rejects it with temINVALID.
CoverRateMinimum and CoverRateLiquidation range from 0 to 100000 and must be both zero or both non-zero. ManagementFeeRate ranges from 0 to 10000 (10%).
4. Deposit Cover
Deposit cover into the broker to enable loan issuance:
LoanBrokerCoverDeposit coverTx = new LoanBrokerCoverDeposit
{
Account = walletBroker.ClassicAddress,
LoanBrokerID = brokerId,
Amount = new Currency { Value = "50000000", CurrencyCode = "XRP" }, // 50 XRP
};
coverTx = await client.Autofill(coverTx);
await client.SubmitAndWait(coverTx, walletBroker, true);
The owner can withdraw cover only down to the minimum: CoverRateMinimum of the broker's DebtTotal, rounded up. A LoanBrokerCoverWithdraw that would leave less fails with tecINSUFFICIENT_FUNDS, and the fee is still charged. The rounding of the minimum changed with fixCleanup3_2_0, so compute it with LoanBrokerCover rather than by hand. MaxWithdrawable returns the largest withdrawal the node accepts, in the asset's own unit (drops for XRP):
// broker and vault: the LoanBroker and Vault entries, read with ledger_entry
LedgerRules rules = await LedgerRules.FromNodeAsync(client);
decimal withdrawable = LoanBrokerCover.MaxWithdrawable(broker, vault, rules);
decimal minimum = LoanBrokerCover.MinimumCover(broker, vault, rules);
LoanBrokerCoverWithdraw withdrawTx = new LoanBrokerCoverWithdraw
{
Account = walletBroker.ClassicAddress,
LoanBrokerID = brokerId,
Amount = new Currency { Value = withdrawable.ToString(CultureInfo.InvariantCulture), CurrencyCode = "XRP" },
};
TransactionPreview<LoanBrokerCoverOutcome> preview = await client.PreviewLoanBrokerCoverWithdraw(withdrawTx, rules);
// preview.Outcome.CoverBefore, CoverAfter, MinimumCover, MaxWithdrawable
LoanBrokerCover.CheckDeposit, CheckWithdraw and CheckClawback return a LoanBrokerCoverQuote with the amount that moves, the cover before and after, and the Refusal the node would give. Under fixCleanup3_2_0 a deposit is rounded down to the scale of CoverAvailable, so the cover can be credited less than the Amount sent. PreviewLoanBrokerCoverDeposit and PreviewLoanBrokerCoverClawback preview the other two transactions.
Step-by-Step: Creating and Managing a Loan
1. Create a Loan (LoanSet)
LoanSet requires co-signing by both the broker and the borrower. See CounterpartySignature for the full signing flow.
A loan can only be originated in the vault's investment phase: after SubscriptionDate (tecTOO_SOON before it) and before RedemptionDate (tecEXPIRED after it). Its final payment must fall at least 60 seconds before RedemptionDate, or LoanSet fails with tecNO_PERMISSION.
LoanSet loanTx = new LoanSet
{
Account = walletBroker.ClassicAddress,
LoanBrokerID = brokerId,
Counterparty = walletBorrower.ClassicAddress,
PrincipalRequested = 10000000, // Number type (not drops)
};
// Requires special co-signing — see CounterpartySignature section below
TransactionSummary result = await SubmitLoanSetWithCounterpartySig(
client, loanTx, walletBroker, walletBorrower);
string loanId = GetCreatedObjectId(result, LedgerEntryType.Loan);
Terms and schedule before the borrower signs
PreviewLoanSet runs the LoanSet through simulate before either party signs. The borrower's signature is not needed: the preview sends an empty CounterpartySignature, which simulate accepts without verifying. The result carries the exact terms the node would give the loan:
TransactionPreview<LoanSetOutcome> preview = await client.PreviewLoanSet(loanTx);
if (preview.WouldSucceed)
{
LoanSetOutcome terms = preview.Outcome;
// terms.Loan.PeriodicPayment, terms.Loan.TotalValueOutstanding, terms.BorrowerReceives,
// terms.InterestTotal, terms.ServiceFeesTotal, terms.TotalToRepay
}
LoanOrigination.Compute gives the same terms without a node, from the transaction and the vault and broker entries. It computes what LoanSet would store - PeriodicPayment, TotalValueOutstanding, ManagementFeeOutstanding, LoanScale - and repeats the checks that depend on the amounts: the vault's available assets, a value the asset cannot hold or that is finer than the loan's scale, and the amortization guards. The preview remains the complete check: limits, cover, reserves and authorization are not repeated offline.
LoanOriginationTerms offline = LoanOrigination.Compute(loanTx, vault, broker, startDate: null, options);
if (offline.IsAccepted)
{
// offline.Loan: the Loan entry LoanSet would create
}
else
{
// offline.Refusal: "tecPRECISION_LOSS" or "tecINSUFFICIENT_FUNDS"; offline.RefusalReason says why
}
LoanSchedule.Project turns those terms, or a Loan read from the ledger, into the full schedule of regular payments. It repeats rippled's computePaymentComponents for each period. The management fee rate comes from the LoanBroker, and LedgerRules.FromNodeAsync reads the amendments that change the rounding:
LedgerRules options = await LedgerRules.FromNodeAsync(client);
IReadOnlyList<LoanScheduleRow> schedule = LoanSchedule.Project(
terms.Loan, terms.Asset, broker.ManagementFeeRate ?? 0, options);
foreach (LoanScheduleRow row in schedule)
{
// row.DueDate, row.Principal, row.Interest, row.ManagementFee, row.ServiceFee, row.Total
}
The projection computes in the node's own arithmetic, XrplNumber rounded as rippled's Number rounds, so each row is what the node charges for an on-time regular payment, to the last unit of the asset; late payments add late interest and LatePaymentFee. The Blazor test client in Tests/TestsClients/Blazor-WebAssembly has a Loan preview tab that shows both for a broker on any node.
2. Make a Loan Payment
The borrower makes payments on the loan:
LoanPay payTx = new LoanPay
{
Account = walletBorrower.ClassicAddress,
LoanID = loanId,
Amount = new Currency { Value = "10000000", CurrencyCode = "XRP" },
};
payTx = await client.Autofill(payTx);
TransactionSummary result = await client.SubmitAndWait(payTx, walletBorrower, true);
How much to pay
LoanPayments.RegularPaymentCap reads the Loan entry and returns an amount that always settles the next regular payment, in the asset's own unit (drops for XRP). On the final payment it is exact: TotalValueOutstanding plus LoanServiceFee. Before that it is PeriodicPayment rounded up to the asset, plus LoanServiceFee. The node charges what the amortization schedule calls for, which can be one rounding unit less, and it takes only what it charges, not the whole Amount.
To see exactly what a payment will do before submitting it, preview it. PreviewLoanPay autofills the transaction, runs it through simulate and reads the split from the metadata:
LOLoan loan = (LOLoan)(await client.LedgerEntry(new LedgerEntryRequest { Index = loanId }).Typed()).Node;
// null when the entry carries no payment figures, or one beyond decimal: then choose the amount
// yourself and let the preview below show what the node would take.
if (LoanPayments.RegularPaymentCap(loan, new IssuedCurrency { Currency = "XRP" }) is not decimal cap)
return;
LoanPay payTx = new LoanPay
{
Account = walletBorrower.ClassicAddress,
LoanID = loanId,
Amount = new Currency { Value = cap.ToString(CultureInfo.InvariantCulture), CurrencyCode = "XRP" },
};
TransactionPreview<LoanPaymentOutcome> preview = await client.PreviewLoanPay(payTx);
if (preview.WouldSucceed)
{
LoanPaymentOutcome outcome = preview.Outcome;
// outcome.PrincipalPaid, outcome.InterestToVault, outcome.PaidToBroker, outcome.TotalPaid,
// outcome.PaymentsMade, outcome.LoanAfter
await client.SubmitAndWait(preview.Transaction, walletBorrower, false);
}
LoanPaymentOutcome.FromMetadata reads the same split from a validated transaction's metadata. The split follows the money: the vault receives principal and interest, and the broker receives the rest (management, service, late and close fees). LoanPayments.IsPaymentLate and LoanPayments.IsPastGracePeriod tell whether a payment would be late and whether the broker may default the loan. A late payment adds late interest and LatePaymentFee above the cap.
LoanPayments.LatePaymentDue and LoanPayments.FullPaymentDue compute what a late payment (tfLoanLatePayment) and closing the loan early (tfLoanFullPayment) cost, the way the node computes them: the regular payment with the late fee and late interest, or the outstanding balance with accrued interest, the prepayment penalty and ClosePaymentFee. Both need the close time of the ledger before the one the payment lands in, because interest runs to that time; the validated ledger's close time is the usual estimate, and a payment that lands a ledger later accrues a few more seconds. Both return null when the node would refuse that kind of payment at that time.
LedgerRules rules = await LedgerRules.FromNodeAsync(client);
DateTime at = /* close time of the latest validated ledger */;
LoanPaymentDue late = LoanPayments.LatePaymentDue(loan, asset, broker.ManagementFeeRate ?? 0, at, rules);
LoanPaymentDue full = LoanPayments.FullPaymentDue(loan, asset, broker.ManagementFeeRate ?? 0, at, rules);
// late.Total, full.Total: the amount due; .Principal, .InterestToVault, .PaidToBroker: the split
LoanPayments.PaymentForAmount computes what a regular payment does with a given Amount: the node makes as many regular payments as the amount covers, up to 100 in one transaction, and with tfLoanOverpayment on a loan created with that flag applies the rest as an overpayment. The overpayment pays OverpaymentFee and penalty interest at OverpaymentInterestRate, repays principal with the remainder, and re-amortizes the loan over the payments left, so PeriodicPayment falls. The node takes only what it applies: an amount without the flag, or an overpayment its fees would consume, leaves the rest with the payer.
LoanAmountPayment plan = LoanPayments.PaymentForAmount(
loan, asset, broker.ManagementFeeRate ?? 0, amount: 25_000_000, at, overpayment: true, rules);
if (plan.IsAccepted)
{
// plan.Due.Total: what the node takes; plan.PaymentsMade; plan.IsOverpaid;
// plan.LoanAfter.PeriodicPayment, plan.LoanAfter.PrincipalOutstanding: the loan it leaves
}
// otherwise plan.Refusal: tecINSUFFICIENT_PAYMENT, tecEXPIRED, tecNO_PERMISSION, ...
3. Delete a Fully Repaid Loan
After the loan is fully repaid, the broker can delete it:
LoanDelete deleteTx = new LoanDelete
{
Account = walletBroker.ClassicAddress,
LoanID = loanId,
};
deleteTx = await client.Autofill(deleteTx);
await client.SubmitAndWait(deleteTx, walletBroker, true);
Important: You cannot delete a loan that has outstanding obligations (
tecHAS_OBLIGATIONS). The loan must be fully repaid first.
4. Manage Loan State
The broker can mark a loan as defaulted, impaired, or restore it:
// Mark loan as defaulted
LoanManage manageTx = new LoanManage
{
Account = walletBroker.ClassicAddress,
LoanID = loanId,
Flags = LoanManageFlags.tfLoanDefault,
};
manageTx = await client.Autofill(manageTx);
await client.SubmitAndWait(manageTx, walletBroker, true);
LoanManage flags (mutually exclusive):
tfLoanDefault— mark loan as defaultedtfLoanImpair— mark loan as impairedtfLoanUnimpair— restore loan from impaired state
A LoanManage with no action flag is valid and leaves the loan unchanged.
5. Delete the Loan Broker
When the broker has no outstanding loans:
LoanBrokerDelete deletebrokerTx = new LoanBrokerDelete
{
Account = walletBroker.ClassicAddress,
LoanBrokerID = brokerId,
};
deletebrokerTx = await client.Autofill(deletebrokerTx);
await client.SubmitAndWait(deletebrokerTx, walletBroker, true);
CounterpartySignature (LoanSet Co-Signing)
LoanSet is unique among XRPL transactions — it requires two signatures. The broker signs the transaction as normal (TxnSignature), and the borrower provides a CounterpartySignature — an inner STObject containing the borrower's SigningPubKey and TxnSignature.
The SDK provides LoanSigningHelper and XrplWallet.SignAsLoanCounterparty() with three signing patterns, analogous to Batch signing (V1/V2/V3).
The two roles are the submitter (Account) and the counterparty (Counterparty, or the LoanBroker's owner when the field is omitted). One of them must be the broker owner and the other one is the borrower, so either party can submit:
- the broker owner submits with
Counterpartyset to the borrower, and the borrower co-signs; - the borrower submits,
Counterpartyis the broker owner or omitted, and the broker owner co-signs.
The examples below use the first arrangement. For the second, swap the wallets: the borrower prepares and submits, and the broker owner signs as counterparty. LoanSigningHelper.SignLoanSet accepts the two wallets in either order and assigns the roles by Account; its overload with a brokerOwner argument also checks the counterparty when Counterparty is omitted.
Preparation (Common to All Patterns)
using Xrpl.Wallet;
// Autofill handles fee calculation (including CounterpartySignature overhead)
loanTx = await client.Autofill(loanTx);
// PrepareForSigning sets broker's SigningPubKey and removes signature fields
JsonObject prepared = LoanSigningHelper.PrepareForSigning(loanTx, brokerWallet);
V1 — Automatic (Both Keys Available Locally)
Use when both broker and borrower wallets are available on the same device:
SignatureResult result = LoanSigningHelper.SignLoanSet(prepared, brokerWallet, borrowerWallet);
await client.SubmitRequest(result.TxBlob);
V2 — Parallel (Keys on Separate Devices, Sign Independently)
Use when broker and borrower sign independently and a third party combines the signatures:
// Device A (broker): signs the transaction normally
var brokerDict = JsonSerializer.Deserialize<Dictionary<string, object>>(
prepared.ToJsonString(), XrplJsonOptions.Default);
SignatureResult brokerSig = brokerWallet.Sign(brokerDict);
// Device B (borrower): signs as counterparty (independent copy of the payload)
var borrowerDict = JsonSerializer.Deserialize<Dictionary<string, object>>(
prepared.ToJsonString(), XrplJsonOptions.Default);
SignatureResult counterpartySig = borrowerWallet.SignAsLoanCounterparty(borrowerDict);
// Combiner: merge both signatures into a single blob
SignatureResult combined = LoanSigningHelper.CombineLoanSignatures(
brokerSig.TxBlob, counterpartySig.TxBlob);
await client.SubmitRequest(combined.TxBlob);
V3 — Sequential (Borrower Signs First, Passes to Broker)
Use in the real-world scenario where the borrower signs first and sends the partially signed blob to the broker:
// Step 1: Borrower receives prepared tx JSON, signs as counterparty
var txDict = JsonSerializer.Deserialize<Dictionary<string, object>>(
prepared.ToJsonString(), XrplJsonOptions.Default);
SignatureResult withCounterparty = borrowerWallet.SignAsLoanCounterparty(txDict);
// withCounterparty.TxBlob is sent to the broker (e.g. via API, QR code, etc.)
// Step 2: Broker receives the partially signed blob, adds TxnSignature
SignatureResult fullySigned = LoanSigningHelper.SubmitterSign(
withCounterparty.TxBlob, brokerWallet);
await client.SubmitRequest(fullySigned.TxBlob);
Important: Do not use
brokerWallet.Sign()on a partially signed LoanSet blob — it does not handleCounterpartySignaturecorrectly. Always useLoanSigningHelper.SubmitterSign()for the V3 pattern.
Multisig Borrower (Counterparty with a SignerList)
CounterpartySignature takes the multisig form when the borrower is a multisig account: an empty SigningPubKey and a Signers array that the node checks against the counterparty's SignerList, under the counterparty multisign prefix, which since fixCleanup3_4_0 is not the one tx.Signers uses. Each signer of the borrower's list signs with the standard multisign call - the SDK sees that the broker signs single and works the side out for itself - and the composer places the entries.
// The fee covers one base fee per counterparty signer (rippled LoanSet::calculateBaseFee),
// so autofill with the signer count before anyone signs
Dictionary<string, object> autofilled = await client.Autofill(loanTx.ToDictionary(), signersCount: 2);
JsonObject prepared = LoanSigningHelper.PrepareForSigning(
JsonNode.Parse(JsonSerializer.Serialize(autofilled, XrplJsonOptions.Default)).AsObject(), brokerWallet);
var preparedDict = JsonSerializer.Deserialize<Dictionary<string, object>>(prepared.ToJsonString(), XrplJsonOptions.Default);
// Broker: single main signature. Borrower's signers: portable multisign entries
SignatureResult brokerPart = brokerWallet.Sign(new Dictionary<string, object>(preparedDict));
SignatureResult part1 = signer1.Sign(new Dictionary<string, object>(preparedDict), multisign: true);
SignatureResult part2 = signer2.Sign(new Dictionary<string, object>(preparedDict), multisign: true);
// Ledger-driven: the composer looks the signers up in the Counterparty's SignerList
// and pre-checks the quorum by weight
SignatureResult composed = await client.ComposeSignatures(new[] { brokerPart.TxBlob, part1.TxBlob, part2.TxBlob });
// Offline: name the borrower's signers yourself
SignatureResult offline = LoanSigningHelper.CombineLoanSignatures(
new[] { brokerPart.TxBlob, part1.TxBlob, part2.TxBlob },
new[] { signer1.ClassicAddress, signer2.ClassicAddress });
await client.SubmitRequest(composed.TxBlob);
A signer that appears in more than one SignerList (the broker's, the sponsor's, the borrower's) is an error for the ledger-driven composer; compose offline with explicit sides in that case.
Key Points
- Both parties sign the same transaction (serialized for signing, without any signature fields), each under the hash prefix of its role
- The signing preimage uses the broker's
SigningPubKey(the submitting account) CounterpartySignatureis an STObject withisSigningField = false— it is excluded from the signing preimageAutofillautomatically calculates the correct fee for LoanSet (includes CounterpartySignature overhead)
Ledger Objects
The lending protocol creates the following ledger objects:
| Object | Description | Created By |
|---|---|---|
Vault |
Holds lending assets | VaultCreate |
LoanBroker |
Lending entity with parameters and cover | LoanBrokerSet |
Loan |
Active loan between broker and borrower | LoanSet |
LoanBroker Fields
| Field | Type | Description |
|---|---|---|
Owner |
AccountID | Broker owner, the account that submitted the creating LoanBrokerSet |
Account |
AccountID | Broker pseudo-account |
VaultID |
Hash256 | Vault the broker lends from |
LoanSequence |
UInt32 | Sequence number assigned to the next loan |
OwnerCount |
UInt32 | Number of loans the broker owns |
CoverAvailable |
Number | Available first-loss capital |
DebtTotal |
Number | Total outstanding debt |
DebtMaximum |
Number | Maximum allowed debt |
CoverRateMinimum |
UInt32 | Share of debt the cover must reach, 1/10th of a basis point (15000 = 15%) |
CoverRateLiquidation |
UInt32 | Share of the minimum cover moved to the vault on a default, 1/10th of a basis point |
ManagementFeeRate |
UInt16 | Management fee, 1/10th of a basis point (0-10000, up to 10%) |
Loan Fields
| Field | Type | Description |
|---|---|---|
Borrower |
AccountID | Borrower account |
LoanBrokerID |
Hash256 | Reference to loan broker |
LoanSequence |
UInt32 | Sequence number within the broker |
PrincipalOutstanding |
Number | Remaining principal |
TotalValueOutstanding |
Number | Total amount owed |
PeriodicPayment |
Number | Amount due per interval |
InterestRate |
UInt32 | Annualized interest rate, 1/10th of a basis point (5000 = 5%) |
PaymentInterval |
UInt32 | Seconds between payments |
GracePeriod |
UInt32 | Seconds before late fees apply |
PaymentRemaining |
UInt32 | Remaining payments |
StartDate |
UInt32 | Loan start (Ripple epoch) |
Counterparty,PrincipalRequestedandPaymentTotalare fields of theLoanSettransaction, not of theLoanobject. rippled records the requested principal asPrincipalOutstanding, so the ledger entry carries noPrincipalRequested— and neither doesLOLoan.
Querying Loan State
Use account_objects to retrieve loans owned by an account:
using Xrpl.Models.Methods;
var request = new AccountObjectsRequest(walletBorrower.ClassicAddress);
var response = await client.AccountObjects(request);
foreach (var obj in response.AccountObjectList)
{
if (obj.LedgerEntryType == LedgerEntryType.Loan)
{
Console.WriteLine($"Loan: {obj}");
}
}
Number Type
Loan fields use the XRPL Number type instead of Amount. The Number type is a 12-byte format:
- 8 bytes — signed int64 mantissa (big-endian)
- 4 bytes — signed int32 exponent (big-endian)
The actual value = mantissa × 10^exponent.
Normalization
Non-zero values are normalized so that the mantissa is in the range [10^18, long.MaxValue]. Zero is represented as mantissa=0, exponent=Int32.MinValue.
Example
The value 10000000000000 (10^13) is normalized to:
- Mantissa:
1000000000000000000(10^18) - Exponent:
-5 - Binary:
0x0DE0B6B3A7640000 FFFFFFFB(12 bytes)
In Transaction Models
Number fields are XrplNumber? in C# models (namespace Xrpl.BinaryCodec.Numbers). An int converts implicitly (PrincipalRequested = 10000000); other values come from XrplNumber.Parse("1.5") or an explicit cast from long or decimal. The binary codec handles normalization and serialization automatically.
A value the ledger cannot hold exactly - more than 19 significant digits - is refused with a FormatException (or OverflowException for a cast) instead of being rounded, the way rippled refuses it in JSON. Round such a value yourself before assigning it.
Fields read from the ledger arrive in the form rippled writes them, for example "1e13" for 10^13. Compare them by value (==, <) rather than as text, and use TryToDecimal when you need decimal arithmetic.
Common Errors
| Error Code | Cause | Solution |
|---|---|---|
tecINSUFFICIENT_FUNDS |
Broker vault lacks funds for the loan | Deposit more assets into the vault via VaultDeposit |
tecHAS_OBLIGATIONS |
Cannot delete a loan with outstanding balance | Fully repay the loan via LoanPay before deleting |
tecNO_ENTRY |
Referenced LoanBrokerID or LoanID not found | Verify the ID is correct and the object exists |
tecNO_PERMISSION |
Action not allowed: a broker on an open-ended vault, a loan ending less than 60 s before RedemptionDate, an overpayment on a loan created without tfLoanOverpayment |
Use a closed-ended vault; shorten the loan; check the account's permissions |
tecTOO_SOON |
LoanSet in the subscription phase, VaultWithdraw in the investment phase |
Wait until SubscriptionDate (for a withdrawal, RedemptionDate) has passed |
tecEXPIRED |
VaultDeposit after SubscriptionDate, LoanSet after RedemptionDate |
Deposit during the subscription phase; originate loans during the investment phase |
tecINSUFFICIENT_PAYMENT |
Payment amount too small | Increase the payment amount |
temBAD_SIGNER |
Missing or invalid CounterpartySignature | Ensure borrower co-signs the LoanSet (see co-signing section) |
telINSUF_FEE_P |
Fee too low after adding CounterpartySignature | Re-run Autofill or increase the fee before submit |
invalid SerialIter geti32 |
Number type encoding error | Ensure Number fields are 12 bytes (8 mantissa + 4 exponent) |
Best Practices
Fund the vault before creating loans — create the vault, deposit assets (
VaultDeposit), create the broker (LoanBrokerSet), deposit cover (LoanBrokerCoverDeposit), then create loans. The vault deposit belongs to the subscription phase and the loans to the investment phase.Autofill handles LoanSet fee —
Autofillautomatically calculates the correct fee includingCounterpartySignatureoverhead. No manual fee adjustment is needed.Filter by LedgerEntryType when extracting IDs —
GetCreatedObjectIdshould filter by specific type (LedgerEntryType.Vault,LedgerEntryType.LoanBroker,LedgerEntryType.Loan) to avoid picking upDirectoryNodeor other created entries.Fully repay before deleting —
LoanDeletefails withtecHAS_OBLIGATIONSif any balance remains. UseLoanPayto clear the debt first.Use reasonable PrincipalRequested values — ensure the vault has sufficient assets to cover the requested principal. The value is in the Number type format.
Validate all results — always check
TransactionResultfor success:if (result.Meta?.TransactionResult != "tesSUCCESS") throw new Exception($"Transaction failed: {result.Meta?.TransactionResult}");LoanManage flags are mutually exclusive — set at most one of
tfLoanDefault,tfLoanImpair, ortfLoanUnimpairper transaction.LoanPay flags are mutually exclusive —
tfLoanOverpayment,tfLoanFullPayment, andtfLoanLatePaymentcannot be combined. Note thattfLoanOverpaymentmay require specific broker/loan configuration to be permitted.Testing on standalone — LendingProtocol amendment must be enabled on rippled 3.1.0+:
{ "command": "feature", "feature": "LendingProtocol", "vetoed": false }