Compare commits

...

48 Commits

Author SHA1 Message Date
Maria Shodunke
be053f85b2 Add contribution cards + refactoring. 2026-04-02 16:08:29 +01:00
Maria Shodunke
d0d60edd36 Tutorials landing page v2 2026-04-01 19:49:16 +01:00
rachelflynn
c04c9042b8 Merge pull request #3547 from rachelflynn/fix-hot-topics-links
Fix: Make community icons and text clickable links
2026-03-31 10:12:17 -04:00
Maria Shodunke
7f7903a336 Merge pull request #3566 from XRPLF/fix-link-to-issue-mpt-tutorial
Fix link to Issue an MPT Tutorial
2026-03-27 16:48:53 +00:00
Maria Shodunke
78da4d6f3b Fix link to Issue an MPT Tutorial
Minor link fix. Must have been missed when we did the Tutorial revamp.
2026-03-27 11:48:59 +00:00
oeggert
17abd49d92 Merge pull request #3507 from XRPLF/go-code-samples
Add Go code samples/tutorials for Lending Protocol
2026-03-25 10:16:58 -07:00
Oliver Eggert
d0c622abf4 update xrpl-go version and lending-setup code 2026-03-24 13:44:16 -07:00
Amarantha Kulkarni
0ed490da0b Merge pull request #3553 from XRPLF/fix_ammclawback_xrp
Fix AMMClawback asset fields
2026-03-24 13:33:18 -07:00
Amarantha Kulkarni
5fe416654f Merge pull request #3552 from XRPLF/amarantha-k-patch-1
Revert change so Redocly doesn't ignore CODE-OF-CONDUCT.md
2026-03-24 12:21:28 -07:00
mDuo13
e0aeab7157 Remove problematic link from Code of Conduct 2026-03-24 11:44:25 -07:00
mDuo13
84987aa2df Fix AMMClawback asset fields (#3520) 2026-03-24 11:32:38 -07:00
Amarantha Kulkarni
175e0a96eb Revert change so Redocly doesn't ignore CODE-OF-CONDUCT.md 2026-03-24 11:29:39 -07:00
Rome Reginelli
d4be722dbc Merge pull request #3529 from XRPLF/new-delete-account-tutorial
Update deletion requirements & add new "Delete an Account" tutorial
2026-03-24 11:15:57 -07:00
oeggert
3cb15342a7 Merge pull request #3548 from XRPLF/claim-context7
add json file to claim repo
2026-03-23 15:24:51 -07:00
Oliver Eggert
4346cf9a94 add json file to claim repo 2026-03-23 15:21:39 -07:00
rachelflynn
6638ea8f6c fix: make hot topics icons and text clickable links 2026-03-23 14:33:26 -04:00
Bart
476ab17cc5 Merge pull request #3546 from XRPLF/bthomee-patch-1
Create vulnerabilitydisclosurereport-bug-mar2026.md
2026-03-23 13:43:10 -04:00
Bart
7d0b02bae9 Update sidebars.yaml 2026-03-23 13:27:33 -04:00
Bart
7ab575804a Apply suggestions from code review
Co-authored-by: oeggert <117319296+oeggert@users.noreply.github.com>
2026-03-23 13:23:07 -04:00
Amarantha Kulkarni
2801055b14 Merge pull request #3532 from interc0der/add-honeycluster
chore: add honeycluster to the list of public servers
2026-03-23 09:57:30 -07:00
Bart
1d52bd8eaa Create vulnerabilitydisclosurereport-bug-mar2026.md
This blog post describes the two liveness bugs reported by Common Prefix last year.
2026-03-23 10:39:02 -04:00
Oliver Eggert
dbabe8171d add go sample to pay-off-a-loan tutorial 2026-03-20 18:31:46 -07:00
Oliver Eggert
66522b160e add go sample for manage-a-loan tutorial 2026-03-20 18:18:48 -07:00
Oliver Eggert
16b63f9c88 add go sample for deposit-and-withdraw-cover tutorial 2026-03-20 17:32:29 -07:00
Oliver Eggert
32b14d2a14 add go sample for create-a-loan 2026-03-20 17:17:14 -07:00
Oliver Eggert
72fb4710ec add go samples to create-a-loan-broker 2026-03-20 16:57:49 -07:00
Oliver Eggert
10431480f1 add Go samples to claw-back-cover tutorial 2026-03-20 16:32:31 -07:00
Oliver Eggert
c5f81cea25 update lending-setup script 2026-03-19 20:18:22 -07:00
Oliver Eggert
9393f40366 update loan flag check to use flag.Contains() 2026-03-19 19:26:37 -07:00
Rome Reginelli
d54684f45a Apply one more suggestion
Co-authored-by: oeggert <117319296+oeggert@users.noreply.github.com>
2026-03-19 10:44:00 -07:00
Oliver Eggert
c505b992e0 update create-loan and README entry 2026-03-18 22:03:37 -07:00
Rome Reginelli
86618b900f Fix typo in Deleting Accounts intro 2026-03-17 16:05:16 -07:00
Rome Reginelli
b634b6902e Account deletion: Fix off-by-two errors & other suggestions
Co-authored-by: oeggert <117319296+oeggert@users.noreply.github.com>
2026-03-17 16:01:37 -07:00
Oliver Eggert
1540e36b8b update library to 0.1.16 2026-03-17 15:07:58 -07:00
Oliver Eggert
598a15eef5 add initial draft for create-loan and lending-setup 2026-03-17 14:59:52 -07:00
Oliver Eggert
7cd8e31a21 add reminder to update flag parsing in loan-manage 2026-03-17 14:59:52 -07:00
Oliver Eggert
e56324c57c add loan-pay go code samples and update readme 2026-03-17 14:59:52 -07:00
Oliver Eggert
5ce6218fd5 add go.sum to gitignore 2026-03-17 14:59:52 -07:00
Oliver Eggert
9934414492 add go.mod and go.sum 2026-03-17 14:59:52 -07:00
Oliver Eggert
ba7694f472 add loan-manage go code sample and update readme 2026-03-17 14:59:52 -07:00
Oliver Eggert
102a7cc8b9 add cover-deposit-and-withdraw go code and update readme 2026-03-17 14:59:52 -07:00
Oliver Eggert
0ac42f6acf add cover-clawback go code and update readme 2026-03-17 14:59:52 -07:00
Oliver Eggert
bc0bcfa89b clean up variable names in create-loan-broker 2026-03-17 14:59:52 -07:00
Oliver Eggert
f9b2bce755 add go code for create-loan-broker and update readme 2026-03-17 14:59:52 -07:00
interc0der
b20b963c8c chore: add honeycluster to the list of public servers 2026-03-03 12:01:02 -08:00
mDuo13
91380d73e1 Update delete account tutorial with more deletion conditions 2026-03-02 13:09:25 -08:00
mDuo13
1ba708467b Update account deletion docs & code 2026-02-27 21:33:05 -08:00
mDuo13
d1adbd575a New 'Delete Account' tutorial & sample code
Delete account sample code: update JS & add Python

Add account deletion tutorial
2026-02-26 16:19:16 -08:00
46 changed files with 4379 additions and 424 deletions

1
.gitignore vendored
View File

@@ -8,6 +8,7 @@ yarn-error.log
*.iml
.venv/
_code-samples/*/js/package-lock.json
_code-samples/*/go/go.sum
_code-samples/*/*/*[Ss]etup.json
# PHP

View File

@@ -1,13 +1,15 @@
import { indexPages } from './plugins/index-pages.js';
import { codeSamples } from './plugins/code-samples.js';
import { blogPosts } from './plugins/blog-posts.js';
import { tutorialLanguages } from './plugins/tutorial-languages.js'
import { tutorialLanguages } from './plugins/tutorial-languages.js';
import { tutorialMetadata } from './plugins/tutorial-metadata.js';
export default function customPlugin() {
const indexPagesInst = indexPages();
const codeSamplesInst = codeSamples();
const blogPostsInst = blogPosts();
const tutorialLanguagesInst = tutorialLanguages();
const tutorialMetadataInst = tutorialMetadata();
/** @type {import("@redocly/realm/dist/server/plugins/types").PluginInstance } */
@@ -18,12 +20,14 @@ export default function customPlugin() {
await codeSamplesInst.processContent?.(content, actions);
await blogPostsInst.processContent?.(content, actions);
await tutorialLanguagesInst.processContent?.(content, actions);
await tutorialMetadataInst.processContent?.(content, actions);
},
afterRoutesCreated: async (content, actions) => {
await indexPagesInst.afterRoutesCreated?.(content, actions);
await codeSamplesInst.afterRoutesCreated?.(content, actions);
await blogPostsInst.afterRoutesCreated?.(content, actions);
await tutorialLanguagesInst.processContent?.(content, actions);
await tutorialMetadataInst.processContent?.(content, actions);
},
};

View File

@@ -1,7 +1,15 @@
// @ts-check
import { getInnerText } from '@redocly/realm/dist/server/plugins/markdown/markdoc/helpers/get-inner-text.js'
/**
* Plugin to detect languages supported in tutorial pages by scanning for tab labels.
* Plugin to detect languages supported in tutorial pages.
*
* Detection methods (in priority order):
* 1. Tab labels in the markdown (for multi-language tutorials)
* 2. Filename patterns like "-js.md", "-py.md" (for single-language tutorials)
* 3. Title containing language name (for single-language tutorials)
*
* This creates shared data that maps tutorial paths to their supported languages.
*/
export function tutorialLanguages() {
@@ -13,15 +21,28 @@ export function tutorialLanguages() {
const tutorialLanguagesMap = {}
const allFiles = await fs.scan()
// Find all markdown files in tutorials directory
// Find all markdown files in tutorials directory (excluding the main landing page)
const tutorialFiles = allFiles.filter((file) =>
file.relativePath.match(/^docs[\/\\]tutorials[\/\\].*\.md$/)
file.relativePath.match(/^docs[\/\\]tutorials[\/\\].*\.md$/) &&
file.relativePath !== 'docs/tutorials/index.md' &&
file.relativePath !== 'docs\\tutorials\\index.md'
)
for (const { relativePath } of tutorialFiles) {
try {
const { data } = await cache.load(relativePath, 'markdown-ast')
const languages = extractLanguagesFromAst(data.ast)
// Try to detect languages from tab labels first
let languages = extractLanguagesFromAst(data.ast)
// Fallback: detect language from filename/title for single-language tutorials
if (languages.length === 0) {
const title = extractFirstHeading(data.ast) || ''
const fallbackLang = detectLanguageFromPathAndTitle(relativePath, title)
if (fallbackLang) {
languages = [fallbackLang]
}
}
if (languages.length > 0) {
// Convert file path to URL path
@@ -98,6 +119,70 @@ function normalizeLanguage(label) {
return null
}
/**
* Detect language from file path and title for single-language tutorials.
* This is a fallback when no tab labels are found in the markdown.
*/
function detectLanguageFromPathAndTitle(relativePath, title) {
const pathLower = relativePath.toLowerCase()
const titleLower = (title || '').toLowerCase()
// Check filename suffixes like "-js.md", "-py.md"
if (pathLower.endsWith('-js.md') || pathLower.includes('-javascript.md') || pathLower.includes('-in-javascript.md')) {
return 'javascript'
}
if (pathLower.endsWith('-py.md') || pathLower.includes('-python.md') || pathLower.includes('-in-python.md')) {
return 'python'
}
if (pathLower.endsWith('-java.md') || pathLower.includes('-in-java.md')) {
return 'java'
}
if (pathLower.endsWith('-go.md') || pathLower.includes('-in-go.md') || pathLower.includes('-golang.md')) {
return 'go'
}
if (pathLower.endsWith('-php.md') || pathLower.includes('-in-php.md')) {
return 'php'
}
// Check title for language indicators
if (titleLower.includes('javascript') || titleLower.includes(' js ') || titleLower.endsWith(' js')) {
return 'javascript'
}
if (titleLower.includes('python')) {
return 'python'
}
if (titleLower.includes('java') && !titleLower.includes('javascript')) {
return 'java'
}
if (titleLower.includes('golang') || (titleLower.includes(' go ') || titleLower.endsWith(' go') || titleLower.includes('using go'))) {
return 'go'
}
if (titleLower.includes('php')) {
return 'php'
}
return null
}
const EXIT = Symbol('Exit visitor')
/**
* Extract the first heading from the markdown AST
*/
function extractFirstHeading(ast) {
let heading = null
visit(ast, (node) => {
if (!isNode(node)) return
if (node.type === 'heading') {
heading = getInnerText([node])
return EXIT
}
})
return heading
}
function isNode(value) {
return !!(value?.$$mdtype === 'Node')
}
@@ -105,14 +190,16 @@ function isNode(value) {
function visit(node, visitor) {
if (!node) return
visitor(node)
const res = visitor(node)
if (res === EXIT) return res
if (node.children) {
for (const child of node.children) {
if (!child || typeof child === 'string') {
continue
}
visit(child, visitor)
const res = visit(child, visitor)
if (res === EXIT) return res
}
}
}

View File

@@ -0,0 +1,120 @@
// @ts-check
import { getInnerText } from '@redocly/realm/dist/server/plugins/markdown/markdoc/helpers/get-inner-text.js';
/**
* Plugin to extract tutorial metadata including last modified dates.
* Uses Redocly's built-in git integration for dates (same as "Last updated" display).
* This creates shared data for displaying "What's New" tutorials and
* auto-generating tutorial sections on the landing page.
*/
export function tutorialMetadata() {
/** @type {import("@redocly/realm/dist/server/plugins/types").PluginInstance } */
const instance = {
processContent: async (actions, { fs, cache }) => {
try {
/** @type {Array<{path: string, title: string, description: string, lastModified: string, category: string}>} */
const tutorials = [];
const allFiles = await fs.scan();
// Find all markdown files in tutorials directory (excluding the main landing page)
const tutorialFiles = allFiles.filter((file) =>
file.relativePath.match(/^docs[\/\\]tutorials[\/\\].*\.md$/) &&
file.relativePath !== 'docs/tutorials/index.md' &&
file.relativePath !== 'docs\\tutorials\\index.md'
);
for (const { relativePath } of tutorialFiles) {
try {
const { data: { ast } } = await cache.load(relativePath, 'markdown-ast');
const { data: { frontmatter } } = await cache.load(relativePath, 'markdown-frontmatter');
// Get last modified date using Redocly's built-in git integration
const lastModified = await fs.getLastModified(relativePath);
if (!lastModified) continue; // Skip files without dates
// Extract title from first heading
const title = extractFirstHeading(ast) || '';
if (!title) continue;
// Get description from frontmatter or first paragraph
const description = frontmatter?.seo?.description || '';
// Extract category from path (e.g., "tokens", "payments", "defi")
const pathParts = relativePath.split(/[\/\\]/);
const category = pathParts.length > 2 ? pathParts[2] : 'general';
// Convert file path to URL path
// Handle index.md files - they should produce /path/to/folder/ not /path/to/folder/index/
const urlPath = '/' + relativePath
.replace(/[\/\\]index\.md$/, '/')
.replace(/\.md$/, '/')
.replace(/\\/g, '/');
tutorials.push({
path: urlPath,
title,
description,
lastModified,
category,
});
} catch (err) {
continue; // Skip files that can't be parsed
}
}
// Sort by last modified date (newest first) for "What's New"
const sortedTutorials = tutorials.sort((a, b) =>
new Date(b.lastModified).getTime() - new Date(a.lastModified).getTime()
);
// Create shared data
actions.createSharedData('tutorial-metadata', { tutorials: sortedTutorials });
actions.addRouteSharedData('/docs/tutorials/', 'tutorial-metadata', 'tutorial-metadata');
actions.addRouteSharedData('/ja/docs/tutorials/', 'tutorial-metadata', 'tutorial-metadata');
actions.addRouteSharedData('/es-es/docs/tutorials/', 'tutorial-metadata', 'tutorial-metadata');
} catch (e) {
console.log('[tutorial-metadata] Error:', e);
}
},
};
return instance;
}
/**
* Extract the first heading from the markdown AST
*/
function extractFirstHeading(ast) {
let heading = null;
visit(ast, (node) => {
if (!isNode(node)) return;
if (node.type === 'heading') {
heading = getInnerText([node]);
return EXIT;
}
});
return heading;
}
function isNode(value) {
return !!(value?.$$mdtype === 'Node');
}
const EXIT = Symbol('Exit visitor');
function visit(node, visitor) {
if (!node) return;
const res = visitor(node);
if (res === EXIT) return res;
if (node.children) {
for (const child of node.children) {
if (!child || typeof child === 'string') continue;
const res = visit(child, visitor);
if (res === EXIT) return res;
}
}
}

View File

@@ -1,7 +1,5 @@
# Contributor Covenant Code of Conduct
For translated verisons of this document, see the [@l10n folder](@l10n/).
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of, but not limited to characteristics like age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.

View File

@@ -0,0 +1,3 @@
# Delete Account
Delete an account from the XRP Ledger, removing its data and sending its XRP to another account.

View File

@@ -0,0 +1,4 @@
# Replace the seed with the seed of the account to delete.
ACCOUNT_SEED=s████████████████████████████
# Change to secp256k1 if you generated the seed with that algorithm
ACCOUNT_ALGORITHM=ed25519

View File

@@ -0,0 +1,45 @@
# Delete Account (JavaScript)
JavaScript sample code showing how to delete an account from the XRP Ledger.
## Setup
```sh
npm i
```
## Usage
If you run the script by default, it gets an account from the faucet and outputs the details to the console. Example:
```sh
$ node delete-account.js
Got new account from faucet:
Address: rsuTU7xBF1u8jxKMw5UHvbKkLmvix7zQoe
Seed: sEdTpxrbDhe6M4YeHanSbCySFCZYrCk
Edit the .env file to add this seed, then wait until the account can be deleted.
Account is too new to be deleted.
Account sequence + 255: 15226794
Validated ledger index: 15226538
(Sequence + 255 must be less than or equal to the ledger index)
Estimate: 15 minutes until account can be deleted
OK: Account owner count (0) is low enough.
OK: Account balance (100000000 drops) is high enough.
A total of 1 problem(s) prevent the account from being deleted.
```
Edit the `.env` file to add the seed of the account to delete. For example:
```ini
# Replace the seed with the seed of the account to delete.
ACCOUNT_SEED=sEdTpxrbDhe6M4YeHanSbCySFCZYrCk
# Change to secp256k1 if you generated the seed with that algorithm
ACCOUNT_ALGORITHM=ed25519
```
Then run the script again:
```sh
node delete-account.js
```

View File

@@ -0,0 +1,205 @@
import { Client, Wallet, getBalanceChanges, validate } from 'xrpl'
import 'dotenv/config'
const client = new Client('wss://s.altnet.rippletest.net:51233')
await client.connect()
// Where to send the deleted account's remaining XRP:
const DESTINATION_ACCOUNT = 'rJjHYTCPpNA3qAM8ZpCDtip3a8xg7B8PFo' // Testnet faucet
// Load the account to delete from .env file -----------------------------------
// If the seed value is still the default, get a new account from the faucet.
// It won't be deletable immediately.
let wallet
if (!process.env.ACCOUNT_SEED || process.env.ACCOUNT_SEED === 's████████████████████████████') {
console.log("Couldn't load seed from .env; getting account from the faucet.")
wallet = (await client.fundWallet()).wallet
console.log(`Got new account from faucet:
Address: ${wallet.address}
Seed: ${wallet.seed}
`)
console.log('Edit the .env file to add this seed, then wait until the account can be deleted.')
} else {
wallet = Wallet.fromSeed(process.env.ACCOUNT_SEED, { algorithm: process.env.ACCOUNT_ALGORITHM })
console.log(`Loaded account: ${wallet.address}`)
}
// Check account info to see if account can be deleted -------------------------
let acctInfoResp
try {
acctInfoResp = await client.request({
command: 'account_info',
account: wallet.address,
ledger_index: 'validated'
})
} catch (err) {
console.error('account_info failed with error:', err)
client.disconnect()
process.exit(1)
}
let numProblems = 0
// Check if sequence number is too high
const acctSeq = acctInfoResp.result.account_data.Sequence
const lastValidatedLedgerIndex = acctInfoResp.result.ledger_index
if (acctSeq + 255 > lastValidatedLedgerIndex) {
console.error(`Account is too new to be deleted.
Account sequence + 255: ${acctSeq + 255}
Validated ledger index: ${lastValidatedLedgerIndex}
(Sequence + 255 must be less than or equal to the ledger index)`)
// Estimate time until deletability assuming ledgers close every ~3.5 seconds
const estWaitTimeS = (acctSeq + 255 - lastValidatedLedgerIndex) * 3.5
if (estWaitTimeS < 120) {
console.log(`Estimate: ${estWaitTimeS} seconds until account can be deleted`)
} else {
const estWaitTimeM = Math.round(estWaitTimeS / 60, 0)
console.log(`Estimate: ${estWaitTimeM} minutes until account can be deleted`)
}
numProblems += 1
} else {
console.log(`OK: Account sequence number (${acctSeq}) is low enough.`)
}
// Check if owner count is too high
const ownerCount = acctInfoResp.result.account_data.OwnerCount
if (ownerCount > 1000) {
console.error(`Account owns too many objects in the ledger.
Owner count: ${ownerCount}
(Must be 1000 or less)`)
numProblems += 1
} else {
console.log(`OK: Account owner count (${ownerCount}) is low enough.`)
}
// Check if XRP balance is high enough
// Look up current incremental owner reserve to compare vs account's XRP balance
// using server_state so that both are in drops
let serverStateResp
try {
serverStateResp = await client.request({
command: 'server_state'
})
} catch (err) {
console.error('server_state failed with error:', err)
client.disconnect()
process.exit(1)
}
const deletionCost = serverStateResp.result.state.validated_ledger?.reserve_inc
if (!deletionCost) {
console.error("Couldn't get reserve values from server. " +
"Maybe it's not synced to the network?")
client.disconnect()
process.exit(1)
}
const acctBalance = acctInfoResp.result.account_data.Balance
if (acctBalance < deletionCost) {
console.error(`Account does not have enough XRP to pay the cost of deletion.
Balance: ${acctBalance}
Cost of account deletion: ${deletionCost}`)
numProblems += 1
} else {
console.log(`OK: Account balance (${acctBalance} drops) is high enough.`)
}
// Check if FirstNFTSequence is too high
const firstNFTSeq = acctInfoResp.result.account_data.FirstNFTokenSequence || 0
const mintedNFTs = acctInfoResp.result.account_data.MintedNFTokens || 0
if (firstNFTSeq + mintedNFTs + 255 > lastValidatedLedgerIndex) {
console.error(`Account's FirstNFTokenSequence + MintedNFTokens + 255 is too high.
Current total: ${firstNFTSeq + mintedNFTs + 255}
Validated ledger index: ${lastValidatedLedgerIndex}
(FirstNFTokenSequence + MintedNFTokens + 255 must be less than or equal to the ledger index)`)
numProblems += 1
} else {
console.log('OK: FirstNFTokenSequence + MintedNFTokens is low enough.')
}
// Check that all issued NFTs have been burned
const burnedNFTs = acctInfoResp.result.account_data.BurnedNFTokens || 0
if (mintedNFTs > burnedNFTs) {
console.error(`Account has issued NFTs outstanding.
Number of NFTs minted: ${mintedNFTs}
Number of NFTs burned: ${burnedNFTs}`)
numProblems += 1
} else {
console.log('OK: No outstanding, un-burned NFTs')
}
// Stop if any problems were found
if (numProblems) {
console.error(`A total of ${numProblems} problem(s) prevent the account from being deleted.`)
client.disconnect()
process.exit(1)
}
// Check for deletion blockers -------------------------------------------------
const blockers = []
let marker
const ledger_index = 'validated'
while (true) {
let accountObjResp
try {
accountObjResp = await client.request({
command: 'account_objects',
account: wallet.address,
deletion_blockers_only: true,
ledger_index,
marker
})
} catch (err) {
console.error('account_objects failed with error:', err)
client.disconnect()
process.exit(1)
}
for (const obj of accountObjResp.result.account_objects) {
blockers.push(obj)
}
if (accountObjResp.result.marker) {
marker = accountObjResp.result.marker
} else {
break
}
}
if (!blockers.length) {
console.log('OK: Account has no deletion blockers.')
} else {
console.log(`Account cannot be deleted until ${blockers.length} blocker(s) are removed:`)
for (const blocker of blockers) {
console.log(JSON.stringify(blocker, null, 2))
}
client.disconnect()
process.exit(1)
}
// Delete the account ----------------------------------------------------------
const accountDeleteTx = {
TransactionType: 'AccountDelete',
Account: wallet.address,
Destination: DESTINATION_ACCOUNT
}
validate(accountDeleteTx)
console.log('Signing and submitting the AccountDelete transaction:',
JSON.stringify(accountDeleteTx, null, 2))
const deleteTxResponse = await client.submitAndWait(accountDeleteTx, { wallet, autofill: true, failHard: true })
// Check result of the AccountDelete transaction -------------------------------
console.log(JSON.stringify(deleteTxResponse.result, null, 2))
const resultCode = deleteTxResponse.result.meta.TransactionResult
if (resultCode !== 'tesSUCCESS') {
console.error(`AccountDelete failed with code ${resultCode}.`)
client.disconnect()
process.exit(1)
}
console.log('Account deleted successfully.')
const balanceChanges = getBalanceChanges(deleteTxResponse.result.meta)
console.log('Balance changes:', JSON.stringify(balanceChanges, null, 2))
client.disconnect()

View File

@@ -0,0 +1,10 @@
{
"name": "delete-account",
"version": "1.0.0",
"license": "MIT",
"dependencies": {
"dotenv": "^17.3.1",
"xrpl": "^4.6.0"
},
"type": "module"
}

View File

@@ -0,0 +1,4 @@
# Replace the seed with the seed of the account to delete.
ACCOUNT_SEED=s████████████████████████████
# Change to secp256k1 if you generated the seed with that algorithm
ACCOUNT_ALGORITHM=ed25519

View File

@@ -0,0 +1,47 @@
# Delete Account (Python)
Python sample code showing how to delete an account from the XRP Ledger.
## Setup
```sh
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```
## Usage
If you run the script by default, it gets an account from the faucet and outputs the details to the console. Example:
```sh
$ python delete-account.py
Got new account from faucet:
Address: rNqLzC9pVbphwwpTBNPjpx14QSauHH3kzv
Seed: sEdTNEJgK3cVshBEakfVic4MMtWCETY
Edit the .env file to add this seed, then wait until the account can be deleted.
Account is too new to be deleted.
Account sequence + 255: 15226905
Validated ledger index: 15226649
(Sequence + 255 must be less than or equal to the ledger index)
Estimate: 15 minutes until account can be deleted
OK: Account owner count (0) is low enough.
OK: Account balance (100000000 drops) is high enough.
A total of 1 problem(s) prevent the account from being deleted.
```
Edit the `.env` file to add the seed of the account to delete. For example:
```ini
# Replace the seed with the seed of the account to delete.
ACCOUNT_SEED=sEdTNEJgK3cVshBEakfVic4MMtWCETY
# Change to secp256k1 if you generated the seed with that algorithm
ACCOUNT_ALGORITHM=ed25519
```
Then run the script again:
```sh
python delete-account.py
```

View File

@@ -0,0 +1,199 @@
import os
import json
from dotenv import load_dotenv
from xrpl.clients import JsonRpcClient
from xrpl.wallet import Wallet, generate_faucet_wallet
from xrpl.models.requests import AccountInfo, ServerState, AccountObjects
from xrpl.models.transactions import AccountDelete
from xrpl.transaction import submit_and_wait
from xrpl.utils import get_balance_changes
client = JsonRpcClient("https://s.altnet.rippletest.net:51234")
# Where to send the deleted account's remaining XRP:
DESTINATION_ACCOUNT = "rJjHYTCPpNA3qAM8ZpCDtip3a8xg7B8PFo" # Testnet faucet
# Load the account to delete from .env file -----------------------------------
# If the seed value is still the default, get a new account from the faucet.
# It won't be deletable immediately.
load_dotenv()
account_seed = os.getenv("ACCOUNT_SEED")
account_algorithm = os.getenv("ACCOUNT_ALGORITHM", "ed25519")
if account_seed == "s████████████████████████████" or not account_seed:
print("Couldn't load seed from .env; getting account from the faucet.")
wallet = generate_faucet_wallet(client)
print(
f"Got new account from faucet:\n"
f" Address: {wallet.address}\n"
f" Seed: {wallet.seed}\n"
)
print(
"Edit the .env file to add this seed, then wait until the account can be deleted."
)
else:
wallet = Wallet.from_seed(account_seed, algorithm=account_algorithm)
print(f"Loaded account: {wallet.address}")
# Check account info to see if account can be deleted -------------------------
try:
acct_info_resp = client.request(
AccountInfo(account=wallet.address, ledger_index="validated")
)
except Exception as err:
print(f"account_info failed with error: {err}")
exit(1)
acct_info_result = acct_info_resp.result
num_problems = 0
# Check if sequence number is too high
acct_seq = acct_info_result["account_data"]["Sequence"]
last_validated_ledger_index = acct_info_result["ledger_index"]
if acct_seq + 255 > last_validated_ledger_index:
print(
f"Account is too new to be deleted.\n"
f" Account sequence + 255: {acct_seq + 255}\n"
f" Validated ledger index: {last_validated_ledger_index}\n"
f" (Sequence + 255 must be less than or equal to the ledger index)"
)
# Estimate time until deletability assuming ledgers close every ~3.5 seconds
est_wait_time_s = (acct_seq + 255 - last_validated_ledger_index) * 3.5
if est_wait_time_s < 120:
print(f"Estimate: {est_wait_time_s} seconds until account can be deleted")
else:
est_wait_time_m = round(est_wait_time_s / 60)
print(f"Estimate: {est_wait_time_m} minutes until account can be deleted")
num_problems += 1
else:
print(f"OK: Account sequence number ({acct_seq}) is low enough.")
# Check if owner count is too high
owner_count = acct_info_result["account_data"]["OwnerCount"]
if owner_count > 1000:
print(
f"Account owns too many objects in the ledger.\n"
f" Owner count: {owner_count}\n"
f" (Must be 1000 or less)"
)
num_problems += 1
else:
print(f"OK: Account owner count ({owner_count}) is low enough.")
# Check if XRP balance is high enough
# Look up current incremental owner reserve to compare vs account's XRP balance
# using server_state so that both are in drops
try:
server_state_resp = client.request(ServerState())
except Exception as err:
print("server_state failed with error:", err)
exit(1)
validated_ledger = server_state_resp.result["state"].get("validated_ledger", {})
deletion_cost = validated_ledger.get("reserve_inc")
if not deletion_cost:
print(
"Couldn't get reserve values from server. Maybe it's not synced to the network?"
)
print(json.dumps(server_state_resp.result, indent=2))
exit(1)
acct_balance = int(acct_info_result["account_data"]["Balance"])
if acct_balance < deletion_cost:
print(
f"Account does not have enough XRP to pay the cost of deletion.\n"
f" Balance: {acct_balance}\n"
f" Cost of account deletion: {deletion_cost}"
)
num_problems += 1
else:
print(f"OK: Account balance ({acct_balance} drops) is high enough.")
# Check if FirstNFTSequence is too high
first_nfq_seq = acct_info_result["account_data"].get("FirstNFTokenSequence", 0)
minted_nfts = acct_info_result["account_data"].get("MintedNFTokens", 0)
if first_nfq_seq + minted_nfts + 255 > last_validated_ledger_index:
print(f"""Account's FirstNFTokenSequence + MintedNFTokens + 255 is too high.
Current total: {first_nfq_seq + minted_nfts + 255}
Validated ledger index: {last_validated_ledger_index}
(FirstNFTokenSequence + MintedNFTokens + 255 must be less than or equal to the the ledger index)""")
num_problems += 1
else:
print("OK: FirstNFTokenSequence + MintedNFTokens is low enough.")
# Check that all issued NFTs have been burned
burned_nfts = acct_info_result["account_data"].get("BurnedNFTokens", 0)
if minted_nfts > burned_nfts:
print(f"""Account has NFTs outstanding.
Number of NFTs minted: {minted_nfts}
Number of NFTs burned: {burned_nfts}""")
num_problems += 1
else:
print("OK: No outstanding, un-burned NFTs")
# Stop if any problems were found
if num_problems:
print(
f"A total of {num_problems} problem(s) prevent the account from being deleted."
)
exit(1)
# Check for deletion blockers -------------------------------------------------
blockers = []
marker = None
ledger_index = "validated"
while True:
try:
account_obj_resp = client.request(
AccountObjects(
account=wallet.address,
deletion_blockers_only=True,
ledger_index=ledger_index,
marker=marker,
)
)
except Exception as err:
print(f"account_objects failed with error: {err}")
exit(1)
blockers.extend(account_obj_resp.result["account_objects"])
marker = account_obj_resp.result.get("marker")
if not marker:
break
if not blockers:
print("OK: Account has no deletion blockers.")
else:
print(f"Account cannot be deleted until {len(blockers)} blocker(s) are removed:")
for blocker in blockers:
print(json.dumps(blocker, indent=2))
exit(1)
# Delete the account ----------------------------------------------------------
account_delete_tx = AccountDelete(
account=wallet.address, destination=DESTINATION_ACCOUNT
)
print("Signing and submitting the AccountDelete transaction:")
print(json.dumps(account_delete_tx.to_xrpl(), indent=2))
delete_tx_response = submit_and_wait(account_delete_tx, client, wallet, fail_hard=True)
# Check result of the AccountDelete transaction -------------------------------
print(json.dumps(delete_tx_response.result, indent=2))
result_code = delete_tx_response.result["meta"]["TransactionResult"]
if result_code != "tesSUCCESS":
print(f"AccountDelete failed with code {result_code}.")
exit(1)
print("Account deleted successfully.")
balance_changes = get_balance_changes(delete_tx_response.result["meta"])
print("Balance changes:", json.dumps(balance_changes, indent=2))

View File

@@ -0,0 +1,2 @@
xrpl-py==4.5.0
python-dotenv==1.2.1

View File

@@ -0,0 +1,395 @@
# Lending Protocol Examples (Go)
This directory contains Go examples demonstrating how to create a loan broker, claw back first-loss capital, deposit and withdraw first-loss capital, create a loan, manage a loan, and repay a loan.
## Setup
All commands should be run from this `go/` directory.
Install dependencies before running any examples:
```sh
go mod tidy
```
---
## Create a Loan Broker
```sh
go run ./create-loan-broker
```
The script should output the LoanBrokerSet transaction, loan broker ID, and loan broker pseudo-account.
```sh
Loan broker/vault owner address: rLsTX2RjNTqwiwNpMn7mny3MyrXtmbhFQV
Vault ID: A300D6F7D43E1B143683F1917EE6456B0C3E84F0F763D9A1366FCD22138A11E9
=== Preparing LoanBrokerSet transaction ===
{
"Account": "rLsTX2RjNTqwiwNpMn7mny3MyrXtmbhFQV",
"ManagementFeeRate": 1000,
"TransactionType": "LoanBrokerSet",
"VaultID": "A300D6F7D43E1B143683F1917EE6456B0C3E84F0F763D9A1366FCD22138A11E9"
}
=== Submitting LoanBrokerSet transaction ===
Loan broker created successfully!
=== Loan Broker Information ===
LoanBroker ID: E4D9C485E101FAE449C8ACEC7FD039920CC02D2443687F2593DB397CC8EA670B
LoanBroker Pseudo-Account Address: rMDsnf9CVRLRJzrL12Ex7nhstbni78y8af
```
---
## Claw Back First-loss Capital
```sh
go run ./cover-clawback
```
The script should output the cover available, the LoanBrokerCoverDeposit transaction, cover available after the deposit, the LoanBrokerCoverClawback transaction, and the final cover available after the clawback.
```sh
Loan broker address: rLsTX2RjNTqwiwNpMn7mny3MyrXtmbhFQV
MPT issuer address: rfYxCEWxA9ACyvpciPZYbKujjLEVX5CCwW
LoanBrokerID: 373BEBB8A1EF735FCD330C2B0DDF2C37FD3B1589B084C94F2CA52A904FBED08D
MPT ID: 003A9D5247DC1C9997DB5500A84C3EC748F3F61D2BC56D51
=== Cover Available ===
0 TSTUSD
=== Preparing LoanBrokerCoverDeposit transaction ===
{
"Account": "rLsTX2RjNTqwiwNpMn7mny3MyrXtmbhFQV",
"Amount": {
"mpt_issuance_id": "003A9D5247DC1C9997DB5500A84C3EC748F3F61D2BC56D51",
"value": "1000"
},
"LoanBrokerID": "373BEBB8A1EF735FCD330C2B0DDF2C37FD3B1589B084C94F2CA52A904FBED08D",
"TransactionType": "LoanBrokerCoverDeposit"
}
=== Submitting LoanBrokerCoverDeposit transaction ===
Cover deposit successful!
=== Cover Available After Deposit ===
1000 TSTUSD
=== Verifying Asset Issuer ===
MPT issuer account verified: rfYxCEWxA9ACyvpciPZYbKujjLEVX5CCwW. Proceeding to clawback.
=== Preparing LoanBrokerCoverClawback transaction ===
{
"Account": "rfYxCEWxA9ACyvpciPZYbKujjLEVX5CCwW",
"Amount": {
"mpt_issuance_id": "003A9D5247DC1C9997DB5500A84C3EC748F3F61D2BC56D51",
"value": "1000"
},
"LoanBrokerID": "373BEBB8A1EF735FCD330C2B0DDF2C37FD3B1589B084C94F2CA52A904FBED08D",
"TransactionType": "LoanBrokerCoverClawback"
}
=== Submitting LoanBrokerCoverClawback transaction ===
Successfully clawed back 1000 TSTUSD!
=== Final Cover Available After Clawback ===
0 TSTUSD
```
---
## Deposit and Withdraw First-loss Capital
```sh
go run ./cover-deposit-and-withdraw
```
The script should output the LoanBrokerCoverDeposit, cover balance after the deposit, the LoanBrokerCoverWithdraw transaction, and the cover balance after the withdrawal.
```sh
Loan broker address: rU9ANkvdSCs7p59Guf2XzGrrCPSMM2tDQV
LoanBrokerID: 633375BCB82DB1440189D3E0721AF92B0888304717DA1B002C8824D631E97DC3
MPT ID: 003B6A9EE92357082A44FA2EAA26385E2F85071634BC3315
=== Preparing LoanBrokerCoverDeposit transaction ===
{
"Account": "rU9ANkvdSCs7p59Guf2XzGrrCPSMM2tDQV",
"Amount": {
"mpt_issuance_id": "003B6A9EE92357082A44FA2EAA26385E2F85071634BC3315",
"value": "2000"
},
"LoanBrokerID": "633375BCB82DB1440189D3E0721AF92B0888304717DA1B002C8824D631E97DC3",
"TransactionType": "LoanBrokerCoverDeposit"
}
=== Submitting LoanBrokerCoverDeposit transaction ===
Cover deposit successful!
=== Cover Balance ===
LoanBroker Pseudo-Account: rJoTTaGKQr8o475xKNZkEPRsmTbUkr6sbi
Cover balance after deposit: 2000 TSTUSD
=== Preparing LoanBrokerCoverWithdraw transaction ===
{
"Account": "rU9ANkvdSCs7p59Guf2XzGrrCPSMM2tDQV",
"Amount": {
"mpt_issuance_id": "003B6A9EE92357082A44FA2EAA26385E2F85071634BC3315",
"value": "1000"
},
"LoanBrokerID": "633375BCB82DB1440189D3E0721AF92B0888304717DA1B002C8824D631E97DC3",
"TransactionType": "LoanBrokerCoverWithdraw"
}
=== Submitting LoanBrokerCoverWithdraw transaction ===
Cover withdraw successful!
=== Updated Cover Balance ===
LoanBroker Pseudo-Account: rJoTTaGKQr8o475xKNZkEPRsmTbUkr6sbi
Cover balance after withdraw: 1000 TSTUSD
```
---
## Create a Loan
```sh
go run ./create-loan
```
The script should output the LoanSet transaction, the updated LoanSet transaction with the loan broker signature, the final LoanSet transaction with the borrower signature added, and then the loan information.
```sh
Loan broker address: rKHVvo9vMQwm2xz44qfhHyDC2VwYKfzgrX
Borrower address: rKU5hZEsT71BUgCnnPekEF3d2zn4AXsyqp
LoanBrokerID: 490DB29AD0CCFBDFE9A176F71AB7512497407CCA37E86F0C88CCDA1DF99A1F09
=== Preparing LoanSet transaction ===
{
"Account": "rKHVvo9vMQwm2xz44qfhHyDC2VwYKfzgrX",
"Counterparty": "rKU5hZEsT71BUgCnnPekEF3d2zn4AXsyqp",
"Fee": "2",
"GracePeriod": 604800,
"InterestRate": 500,
"LastLedgerSequence": 437349,
"LoanBrokerID": "490DB29AD0CCFBDFE9A176F71AB7512497407CCA37E86F0C88CCDA1DF99A1F09",
"LoanOriginationFee": "100",
"LoanServiceFee": "10",
"PaymentInterval": 2592000,
"PaymentTotal": 12,
"PrincipalRequested": "1000",
"Sequence": 6905,
"TransactionType": "LoanSet"
}
=== Adding loan broker signature ===
TxnSignature: 9984D6061F4B03734CDCC5A5367A928671FEE1486EFD335B6C875423FCB9FCEF2464F2A610B4DF31875567869696DC36D16F72AFB7D5F245B43C19415537F50F
SigningPubKey: ED378AB6DCCD0401D6DB3358A9135CE43455A57DAF0CBC459E8D7B6611193690B1
Signed loanSetTx for borrower to sign over:
{
"Account": "rKHVvo9vMQwm2xz44qfhHyDC2VwYKfzgrX",
"Counterparty": "rKU5hZEsT71BUgCnnPekEF3d2zn4AXsyqp",
"Fee": "2",
"GracePeriod": 604800,
"InterestRate": 500,
"LastLedgerSequence": 437349,
"LoanBrokerID": "490DB29AD0CCFBDFE9A176F71AB7512497407CCA37E86F0C88CCDA1DF99A1F09",
"LoanOriginationFee": "100",
"LoanServiceFee": "10",
"PaymentInterval": 2592000,
"PaymentTotal": 12,
"PrincipalRequested": "1000",
"Sequence": 6905,
"SigningPubKey": "ED378AB6DCCD0401D6DB3358A9135CE43455A57DAF0CBC459E8D7B6611193690B1",
"TransactionType": "LoanSet",
"TxnSignature": "9984D6061F4B03734CDCC5A5367A928671FEE1486EFD335B6C875423FCB9FCEF2464F2A610B4DF31875567869696DC36D16F72AFB7D5F245B43C19415537F50F"
}
=== Adding borrower signature ===
Borrower TxnSignature: 5578161BA5480216644D63428D4FAA6FC761BEA10D91FFB733636AB4EA7C6CC4E07E241BF5418D92FBE9F0133E97CC3E6A2CDC56C86C801438C1CBAC4497B005
Borrower SigningPubKey: ED2BF9FFE428F80E3E174476EA334E2109BAF6C7309BB08D56A6A97CE0432AD85E
Fully signed LoanSet transaction:
{
"Account": "rKHVvo9vMQwm2xz44qfhHyDC2VwYKfzgrX",
"Counterparty": "rKU5hZEsT71BUgCnnPekEF3d2zn4AXsyqp",
"CounterpartySignature": {
"SigningPubKey": "ED2BF9FFE428F80E3E174476EA334E2109BAF6C7309BB08D56A6A97CE0432AD85E",
"TxnSignature": "5578161BA5480216644D63428D4FAA6FC761BEA10D91FFB733636AB4EA7C6CC4E07E241BF5418D92FBE9F0133E97CC3E6A2CDC56C86C801438C1CBAC4497B005"
},
"Fee": "2",
"GracePeriod": 604800,
"InterestRate": 500,
"LastLedgerSequence": 437349,
"LoanBrokerID": "490DB29AD0CCFBDFE9A176F71AB7512497407CCA37E86F0C88CCDA1DF99A1F09",
"LoanOriginationFee": "100",
"LoanServiceFee": "10",
"PaymentInterval": 2592000,
"PaymentTotal": 12,
"PrincipalRequested": "1000",
"Sequence": 6905,
"SigningPubKey": "ED378AB6DCCD0401D6DB3358A9135CE43455A57DAF0CBC459E8D7B6611193690B1",
"TransactionType": "LoanSet",
"TxnSignature": "9984D6061F4B03734CDCC5A5367A928671FEE1486EFD335B6C875423FCB9FCEF2464F2A610B4DF31875567869696DC36D16F72AFB7D5F245B43C19415537F50F"
}
=== Submitting signed LoanSet transaction ===
Loan created successfully!
=== Loan Information ===
{
"Borrower": "rKU5hZEsT71BUgCnnPekEF3d2zn4AXsyqp",
"GracePeriod": 604800,
"InterestRate": 500,
"LoanBrokerID": "490DB29AD0CCFBDFE9A176F71AB7512497407CCA37E86F0C88CCDA1DF99A1F09",
"LoanOriginationFee": "100",
"LoanSequence": 4,
"LoanServiceFee": "10",
"NextPaymentDueDate": 829803181,
"PaymentInterval": 2592000,
"PaymentRemaining": 12,
"PeriodicPayment": "83.55610375293148956",
"PrincipalOutstanding": "1000",
"StartDate": 827211181,
"TotalValueOutstanding": "1003"
}
```
---
## Manage a Loan
```sh
go run ./loan-manage
```
The script should output the initial status of the loan, the LoanManage transaction, and the updated loan status and grace period after impairment. The script will countdown the grace period before outputting another LoanManage transaction, and then the final flags on the loan.
```sh
Loan broker address: rN7eCZhKHcq5LEC2W2RrrGcUPBYwZagEPX
LoanID: 2BD3F3F587D1BD4FB247B0935FB098E2DC6E3B571F493472CED914216990EC6C
=== Loan Status ===
Total Amount Owed: 1001 TSTUSD.
Payment Due Date: 2026-03-23 01:23:40
=== Preparing LoanManage transaction to impair loan ===
{
"Account": "rN7eCZhKHcq5LEC2W2RrrGcUPBYwZagEPX",
"Flags": 131072,
"LoanID": "2BD3F3F587D1BD4FB247B0935FB098E2DC6E3B571F493472CED914216990EC6C",
"TransactionType": "LoanManage"
}
=== Submitting LoanManage impairment transaction ===
Loan impaired successfully!
New Payment Due Date: 2026-02-21 00:24:10
Grace Period: 60 seconds
=== Countdown until loan can be defaulted ===
Grace period expired. Loan can now be defaulted.
=== Preparing LoanManage transaction to default loan ===
{
"Account": "rN7eCZhKHcq5LEC2W2RrrGcUPBYwZagEPX",
"Flags": 65536,
"LoanID": "2BD3F3F587D1BD4FB247B0935FB098E2DC6E3B571F493472CED914216990EC6C",
"TransactionType": "LoanManage"
}
=== Submitting LoanManage default transaction ===
Loan defaulted successfully!
=== Checking final loan status ===
Final loan flags: [tfLoanDefault tfLoanImpair]
```
---
## Pay a Loan
```sh
go run ./loan-pay
```
The script should output the amount required to totally pay off a loan, the LoanPay transaction, the amount due after the payment, the LoanDelete transaction, and then the status of the loan ledger entry.
```sh
Borrower address: rFx8s3P5J66MAvWkp5rMj5bBF76gQUCt2
LoanID: D0455CD5F9C2FEC62FC67F31BD97134FBA877D7FE1AE7130EE0006D10661325A
MPT ID: 003B8FC2F51C1BC4E0211E6370EC4FC78BB20D5C4069F07B
=== Loan Status ===
Amount Owed: 1001 TSTUSD
Loan Service Fee: 10 TSTUSD
Total Payment Due (including fees): 1011 TSTUSD
=== Preparing LoanPay transaction ===
{
"Account": "rFx8s3P5J66MAvWkp5rMj5bBF76gQUCt2",
"Amount": {
"mpt_issuance_id": "003B8FC2F51C1BC4E0211E6370EC4FC78BB20D5C4069F07B",
"value": "1011"
},
"LoanID": "D0455CD5F9C2FEC62FC67F31BD97134FBA877D7FE1AE7130EE0006D10661325A",
"TransactionType": "LoanPay"
}
=== Submitting LoanPay transaction ===
Loan paid successfully!
=== Loan Status After Payment ===
Outstanding Loan Balance: Loan fully paid off!
=== Preparing LoanDelete transaction ===
{
"Account": "rFx8s3P5J66MAvWkp5rMj5bBF76gQUCt2",
"LoanID": "D0455CD5F9C2FEC62FC67F31BD97134FBA877D7FE1AE7130EE0006D10661325A",
"TransactionType": "LoanDelete"
}
=== Submitting LoanDelete transaction ===
Loan deleted successfully!
=== Verifying Loan Deletion ===
Loan has been successfully removed from the XRP Ledger!
```

View File

@@ -0,0 +1,210 @@
// IMPORTANT: This example deposits and claws back first-loss capital from a
// preconfigured LoanBroker entry. The first-loss capital is an MPT
// with clawback enabled.
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"github.com/Peersyst/xrpl-go/xrpl/queries/common"
"github.com/Peersyst/xrpl-go/xrpl/queries/ledger"
"github.com/Peersyst/xrpl-go/xrpl/transaction"
"github.com/Peersyst/xrpl-go/xrpl/transaction/types"
"github.com/Peersyst/xrpl-go/xrpl/wallet"
"github.com/Peersyst/xrpl-go/xrpl/websocket"
wstypes "github.com/Peersyst/xrpl-go/xrpl/websocket/types"
)
// mptIssuanceEntryRequest looks up an MPTIssuance ledger entry by its MPT ID.
// The library's GetLedgerEntry() method only supports lookup by ledger entry ID,
// so this custom type is used with the generic Request() method.
type mptIssuanceEntryRequest struct {
common.BaseRequest
MPTIssuance string `json:"mpt_issuance"`
LedgerIndex common.LedgerSpecifier `json:"ledger_index,omitempty"`
}
func (*mptIssuanceEntryRequest) Method() string { return "ledger_entry" }
func (*mptIssuanceEntryRequest) Validate() error { return nil }
func (*mptIssuanceEntryRequest) APIVersion() int { return 2 }
func main() {
// Connect to the network ----------------------
client := websocket.NewClient(
websocket.NewClientConfig().
WithHost("wss://s.devnet.rippletest.net:51233"),
)
defer client.Disconnect()
if err := client.Connect(); err != nil {
panic(err)
}
// Check for setup data; run lending-setup if missing
if _, err := os.Stat("lending-setup.json"); os.IsNotExist(err) {
fmt.Printf("\n=== Lending tutorial data doesn't exist. Running setup script... ===\n\n")
cmd := exec.Command("go", "run", "./lending-setup")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
panic(err)
}
}
// Load preconfigured accounts and LoanBrokerID
data, err := os.ReadFile("lending-setup.json")
if err != nil {
panic(err)
}
var setup map[string]any
if err := json.Unmarshal(data, &setup); err != nil {
panic(err)
}
// You can replace these values with your own
loanBrokerWallet, err := wallet.FromSecret(setup["loanBroker"].(map[string]any)["seed"].(string))
if err != nil {
panic(err)
}
mptIssuerWallet, err := wallet.FromSecret(setup["depositor"].(map[string]any)["seed"].(string))
if err != nil {
panic(err)
}
loanBrokerID := setup["loanBrokerID"].(string)
mptID := setup["mptID"].(string)
fmt.Printf("\nLoan broker address: %s\n", loanBrokerWallet.ClassicAddress)
fmt.Printf("MPT issuer address: %s\n", mptIssuerWallet.ClassicAddress)
fmt.Printf("LoanBrokerID: %s\n", loanBrokerID)
fmt.Printf("MPT ID: %s\n", mptID)
// Check cover available ----------------------
fmt.Printf("\n=== Cover Available ===\n\n")
coverInfo, err := client.GetLedgerEntry(&ledger.EntryRequest{
Index: loanBrokerID,
LedgerIndex: common.Validated,
})
if err != nil {
panic(err)
}
currentCoverAvailable := "0"
if ca, ok := coverInfo.Node["CoverAvailable"].(string); ok {
currentCoverAvailable = ca
}
fmt.Printf("%s TSTUSD\n", currentCoverAvailable)
// Prepare LoanBrokerCoverDeposit transaction ----------------------
fmt.Printf("\n=== Preparing LoanBrokerCoverDeposit transaction ===\n\n")
coverDepositTx := transaction.LoanBrokerCoverDeposit{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.ClassicAddress,
},
LoanBrokerID: loanBrokerID,
Amount: types.MPTCurrencyAmount{
MPTIssuanceID: mptID,
Value: "1000",
},
}
// Flatten() converts the struct to a map and adds the TransactionType field
flatCoverDepositTx := coverDepositTx.Flatten()
coverDepositTxJSON, _ := json.MarshalIndent(flatCoverDepositTx, "", " ")
fmt.Printf("%s\n", string(coverDepositTxJSON))
// Sign, submit, and wait for deposit validation ----------------------
fmt.Printf("\n=== Submitting LoanBrokerCoverDeposit transaction ===\n\n")
depositResponse, err := client.SubmitTxAndWait(flatCoverDepositTx, &wstypes.SubmitOptions{
Autofill: true,
Wallet: &loanBrokerWallet,
})
if err != nil {
panic(err)
}
if depositResponse.Meta.TransactionResult != "tesSUCCESS" {
fmt.Printf("Error: Unable to deposit cover: %s\n", depositResponse.Meta.TransactionResult)
os.Exit(1)
}
fmt.Printf("Cover deposit successful!\n")
// Extract updated cover available after deposit ----------------------
fmt.Printf("\n=== Cover Available After Deposit ===\n\n")
for _, node := range depositResponse.Meta.AffectedNodes {
if node.ModifiedNode != nil && node.ModifiedNode.LedgerEntryType == "LoanBroker" {
currentCoverAvailable = node.ModifiedNode.FinalFields["CoverAvailable"].(string)
break
}
}
fmt.Printf("%s TSTUSD\n", currentCoverAvailable)
// Verify issuer of cover asset matches ----------------------
// Only the issuer of the asset can submit clawback transactions.
// The asset must also have clawback enabled.
fmt.Printf("\n=== Verifying Asset Issuer ===\n\n")
assetIssuerInfo, err := client.Request(&mptIssuanceEntryRequest{
MPTIssuance: mptID,
LedgerIndex: common.Validated,
})
if err != nil {
panic(err)
}
issuer := assetIssuerInfo.Result["node"].(map[string]any)["Issuer"].(string)
if issuer != string(mptIssuerWallet.ClassicAddress) {
fmt.Printf("Error: %s does not match account (%s) attempting clawback!\n", issuer, mptIssuerWallet.ClassicAddress)
os.Exit(1)
}
fmt.Printf("MPT issuer account verified: %s. Proceeding to clawback.\n", mptIssuerWallet.ClassicAddress)
// Prepare LoanBrokerCoverClawback transaction ----------------------
fmt.Printf("\n=== Preparing LoanBrokerCoverClawback transaction ===\n\n")
lbID := types.LoanBrokerID(loanBrokerID)
coverClawbackTx := transaction.LoanBrokerCoverClawback{
BaseTx: transaction.BaseTx{
Account: mptIssuerWallet.ClassicAddress,
},
LoanBrokerID: &lbID,
Amount: types.MPTCurrencyAmount{
MPTIssuanceID: mptID,
Value: currentCoverAvailable,
},
}
flatCoverClawbackTx := coverClawbackTx.Flatten()
coverClawbackTxJSON, _ := json.MarshalIndent(flatCoverClawbackTx, "", " ")
fmt.Printf("%s\n", string(coverClawbackTxJSON))
// Sign, submit, and wait for clawback validation ----------------------
fmt.Printf("\n=== Submitting LoanBrokerCoverClawback transaction ===\n\n")
clawbackResponse, err := client.SubmitTxAndWait(flatCoverClawbackTx, &wstypes.SubmitOptions{
Autofill: true,
Wallet: &mptIssuerWallet,
})
if err != nil {
panic(err)
}
if clawbackResponse.Meta.TransactionResult != "tesSUCCESS" {
fmt.Printf("Error: Unable to clawback cover: %s\n", clawbackResponse.Meta.TransactionResult)
os.Exit(1)
}
fmt.Printf("Successfully clawed back %s TSTUSD!\n", currentCoverAvailable)
// Extract final cover available ----------------------
fmt.Printf("\n=== Final Cover Available After Clawback ===\n\n")
for _, node := range clawbackResponse.Meta.AffectedNodes {
if node.ModifiedNode != nil && node.ModifiedNode.LedgerEntryType == "LoanBroker" {
finalCover := "0"
if ca, ok := node.ModifiedNode.FinalFields["CoverAvailable"].(string); ok {
finalCover = ca
}
fmt.Printf("%s TSTUSD\n", finalCover)
break
}
}
}

View File

@@ -0,0 +1,151 @@
// IMPORTANT: This example deposits and withdraws first-loss capital from a
// preconfigured LoanBroker entry.
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"github.com/Peersyst/xrpl-go/xrpl/transaction"
"github.com/Peersyst/xrpl-go/xrpl/transaction/types"
"github.com/Peersyst/xrpl-go/xrpl/wallet"
"github.com/Peersyst/xrpl-go/xrpl/websocket"
wstypes "github.com/Peersyst/xrpl-go/xrpl/websocket/types"
)
func main() {
// Connect to the network ----------------------
client := websocket.NewClient(
websocket.NewClientConfig().
WithHost("wss://s.devnet.rippletest.net:51233"),
)
defer client.Disconnect()
if err := client.Connect(); err != nil {
panic(err)
}
// Check for setup data; run lending-setup if missing
if _, err := os.Stat("lending-setup.json"); os.IsNotExist(err) {
fmt.Printf("\n=== Lending tutorial data doesn't exist. Running setup script... ===\n\n")
cmd := exec.Command("go", "run", "./lending-setup")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
panic(err)
}
}
// Load preconfigured accounts and LoanBrokerID
data, err := os.ReadFile("lending-setup.json")
if err != nil {
panic(err)
}
var setup map[string]any
if err := json.Unmarshal(data, &setup); err != nil {
panic(err)
}
// You can replace these values with your own
loanBrokerWallet, err := wallet.FromSecret(setup["loanBroker"].(map[string]any)["seed"].(string))
if err != nil {
panic(err)
}
loanBrokerID := setup["loanBrokerID"].(string)
mptID := setup["mptID"].(string)
fmt.Printf("\nLoan broker address: %s\n", loanBrokerWallet.ClassicAddress)
fmt.Printf("LoanBrokerID: %s\n", loanBrokerID)
fmt.Printf("MPT ID: %s\n", mptID)
// Prepare LoanBrokerCoverDeposit transaction ----------------------
fmt.Printf("\n=== Preparing LoanBrokerCoverDeposit transaction ===\n\n")
coverDepositTx := transaction.LoanBrokerCoverDeposit{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.ClassicAddress,
},
LoanBrokerID: loanBrokerID,
Amount: types.MPTCurrencyAmount{
MPTIssuanceID: mptID,
Value: "2000",
},
}
// Flatten() converts the struct to a map and adds the TransactionType field
flatCoverDepositTx := coverDepositTx.Flatten()
coverDepositTxJSON, _ := json.MarshalIndent(flatCoverDepositTx, "", " ")
fmt.Printf("%s\n", string(coverDepositTxJSON))
// Sign, submit, and wait for deposit validation ----------------------
fmt.Printf("\n=== Submitting LoanBrokerCoverDeposit transaction ===\n\n")
depositResponse, err := client.SubmitTxAndWait(flatCoverDepositTx, &wstypes.SubmitOptions{
Autofill: true,
Wallet: &loanBrokerWallet,
})
if err != nil {
panic(err)
}
if depositResponse.Meta.TransactionResult != "tesSUCCESS" {
fmt.Printf("Error: Unable to deposit cover: %s\n", depositResponse.Meta.TransactionResult)
os.Exit(1)
}
fmt.Printf("Cover deposit successful!\n")
// Extract cover balance from the transaction result
fmt.Printf("\n=== Cover Balance ===\n\n")
for _, node := range depositResponse.Meta.AffectedNodes {
if node.ModifiedNode != nil && node.ModifiedNode.LedgerEntryType == "LoanBroker" {
// First-loss capital is stored in the LoanBroker's pseudo-account.
fmt.Printf("LoanBroker Pseudo-Account: %s\n", node.ModifiedNode.FinalFields["Account"])
fmt.Printf("Cover balance after deposit: %s TSTUSD\n", node.ModifiedNode.FinalFields["CoverAvailable"])
break
}
}
// Prepare LoanBrokerCoverWithdraw transaction ----------------------
fmt.Printf("\n=== Preparing LoanBrokerCoverWithdraw transaction ===\n\n")
coverWithdrawTx := transaction.LoanBrokerCoverWithdraw{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.ClassicAddress,
},
LoanBrokerID: loanBrokerID,
Amount: types.MPTCurrencyAmount{
MPTIssuanceID: mptID,
Value: "1000",
},
}
flatCoverWithdrawTx := coverWithdrawTx.Flatten()
coverWithdrawTxJSON, _ := json.MarshalIndent(flatCoverWithdrawTx, "", " ")
fmt.Printf("%s\n", string(coverWithdrawTxJSON))
// Sign, submit, and wait for withdraw validation ----------------------
fmt.Printf("\n=== Submitting LoanBrokerCoverWithdraw transaction ===\n\n")
withdrawResponse, err := client.SubmitTxAndWait(flatCoverWithdrawTx, &wstypes.SubmitOptions{
Autofill: true,
Wallet: &loanBrokerWallet,
})
if err != nil {
panic(err)
}
if withdrawResponse.Meta.TransactionResult != "tesSUCCESS" {
fmt.Printf("Error: Unable to withdraw cover: %s\n", withdrawResponse.Meta.TransactionResult)
os.Exit(1)
}
fmt.Printf("Cover withdraw successful!\n")
// Extract updated cover balance from the transaction result
fmt.Printf("\n=== Updated Cover Balance ===\n\n")
for _, node := range withdrawResponse.Meta.AffectedNodes {
if node.ModifiedNode != nil && node.ModifiedNode.LedgerEntryType == "LoanBroker" {
fmt.Printf("LoanBroker Pseudo-Account: %s\n", node.ModifiedNode.FinalFields["Account"])
fmt.Printf("Cover balance after withdraw: %s TSTUSD\n", node.ModifiedNode.FinalFields["CoverAvailable"])
break
}
}
}

View File

@@ -0,0 +1,105 @@
// IMPORTANT: This example creates a loan broker using an existing account
// that has already created a PRIVATE vault.
// If you want to create a loan broker for a PUBLIC vault, you can replace the vaultID
// and loanBroker values with your own.
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"github.com/Peersyst/xrpl-go/xrpl/transaction"
"github.com/Peersyst/xrpl-go/xrpl/transaction/types"
"github.com/Peersyst/xrpl-go/xrpl/wallet"
"github.com/Peersyst/xrpl-go/xrpl/websocket"
wstypes "github.com/Peersyst/xrpl-go/xrpl/websocket/types"
)
func main() {
// Connect to the network ----------------------
client := websocket.NewClient(
websocket.NewClientConfig().
WithHost("wss://s.devnet.rippletest.net:51233"),
)
defer client.Disconnect()
if err := client.Connect(); err != nil {
panic(err)
}
// Check for setup data; run lending-setup if missing
if _, err := os.Stat("lending-setup.json"); os.IsNotExist(err) {
fmt.Printf("\n=== Lending tutorial data doesn't exist. Running setup script... ===\n\n")
cmd := exec.Command("go", "run", "./lending-setup")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
panic(err)
}
}
// Load preconfigured accounts and VaultID
data, err := os.ReadFile("lending-setup.json")
if err != nil {
panic(err)
}
var setup map[string]any
if err := json.Unmarshal(data, &setup); err != nil {
panic(err)
}
// You can replace these values with your own
loanBrokerWallet, err := wallet.FromSecret(setup["loanBroker"].(map[string]any)["seed"].(string))
if err != nil {
panic(err)
}
vaultID := setup["vaultID"].(string)
fmt.Printf("\nLoan broker/vault owner address: %s\n", loanBrokerWallet.ClassicAddress)
fmt.Printf("Vault ID: %s\n", vaultID)
// Prepare LoanBrokerSet transaction ----------------------
fmt.Printf("\n=== Preparing LoanBrokerSet transaction ===\n\n")
mgmtFeeRate := types.InterestRate(1000)
loanBrokerSetTx := transaction.LoanBrokerSet{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.ClassicAddress,
},
VaultID: vaultID,
ManagementFeeRate: &mgmtFeeRate,
}
// Flatten() converts the struct to a map and adds the TransactionType field
flatLoanBrokerSetTx := loanBrokerSetTx.Flatten()
loanBrokerSetTxJSON, _ := json.MarshalIndent(flatLoanBrokerSetTx, "", " ")
fmt.Printf("%s\n", string(loanBrokerSetTxJSON))
// Submit, sign, and wait for validation ----------------------
fmt.Printf("\n=== Submitting LoanBrokerSet transaction ===\n\n")
loanBrokerSetResponse, err := client.SubmitTxAndWait(flatLoanBrokerSetTx, &wstypes.SubmitOptions{
Autofill: true,
Wallet: &loanBrokerWallet,
})
if err != nil {
panic(err)
}
if loanBrokerSetResponse.Meta.TransactionResult != "tesSUCCESS" {
fmt.Printf("Error: Unable to create loan broker: %s\n", loanBrokerSetResponse.Meta.TransactionResult)
os.Exit(1)
}
fmt.Printf("Loan broker created successfully!\n")
// Extract loan broker information from the transaction result
fmt.Printf("\n=== Loan Broker Information ===\n\n")
for _, node := range loanBrokerSetResponse.Meta.AffectedNodes {
if node.CreatedNode != nil && node.CreatedNode.LedgerEntryType == "LoanBroker" {
fmt.Printf("LoanBroker ID: %s\n", node.CreatedNode.LedgerIndex)
fmt.Printf("LoanBroker Pseudo-Account Address: %s\n", node.CreatedNode.NewFields["Account"])
break
}
}
}

View File

@@ -0,0 +1,153 @@
// IMPORTANT: This example creates a loan using a preconfigured
// loan broker, borrower, and private vault.
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"github.com/Peersyst/xrpl-go/xrpl/transaction"
"github.com/Peersyst/xrpl-go/xrpl/transaction/types"
"github.com/Peersyst/xrpl-go/xrpl/wallet"
"github.com/Peersyst/xrpl-go/xrpl/websocket"
)
// ptr is a helper that returns a pointer to the given value,
// used for setting optional transaction fields in Go.
func ptr[T any](v T) *T { return &v }
func main() {
// Connect to the network ----------------------
client := websocket.NewClient(
websocket.NewClientConfig().
WithHost("wss://s.devnet.rippletest.net:51233"),
)
defer client.Disconnect()
if err := client.Connect(); err != nil {
panic(err)
}
// Check for setup data; run lending-setup if missing
if _, err := os.Stat("lending-setup.json"); os.IsNotExist(err) {
fmt.Printf("\n=== Lending tutorial data doesn't exist. Running setup script... ===\n\n")
cmd := exec.Command("go", "run", "./lending-setup")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
panic(err)
}
}
// Load preconfigured accounts and LoanBrokerID
data, err := os.ReadFile("lending-setup.json")
if err != nil {
panic(err)
}
var setup map[string]any
if err := json.Unmarshal(data, &setup); err != nil {
panic(err)
}
// You can replace these values with your own
loanBrokerWallet, err := wallet.FromSecret(setup["loanBroker"].(map[string]any)["seed"].(string))
if err != nil {
panic(err)
}
borrowerWallet, err := wallet.FromSecret(setup["borrower"].(map[string]any)["seed"].(string))
if err != nil {
panic(err)
}
loanBrokerID := setup["loanBrokerID"].(string)
fmt.Printf("\nLoan broker address: %s\n", loanBrokerWallet.ClassicAddress)
fmt.Printf("Borrower address: %s\n", borrowerWallet.ClassicAddress)
fmt.Printf("LoanBrokerID: %s\n", loanBrokerID)
// Prepare LoanSet transaction ----------------------
// Account and Counterparty accounts can be swapped, but determines signing order.
// Account signs first, Counterparty signs second.
fmt.Printf("\n=== Preparing LoanSet transaction ===\n\n")
counterparty := borrowerWallet.ClassicAddress
loanSetTx := transaction.LoanSet{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.ClassicAddress,
},
LoanBrokerID: loanBrokerID,
PrincipalRequested: "1000",
Counterparty: &counterparty,
InterestRate: ptr(types.InterestRate(500)),
PaymentTotal: ptr(types.PaymentTotal(12)),
PaymentInterval: ptr(types.PaymentInterval(2592000)),
GracePeriod: ptr(types.GracePeriod(604800)),
LoanOriginationFee: ptr(types.XRPLNumber("100")),
LoanServiceFee: ptr(types.XRPLNumber("10")),
}
// Flatten() converts the struct to a map and adds the TransactionType field.
// The result is cast to FlatTransaction, which is required by Autofill and signing methods.
flatLoanSetTx := transaction.FlatTransaction(loanSetTx.Flatten())
// Autofill the transaction
if err := client.Autofill(&flatLoanSetTx); err != nil {
panic(err)
}
loanSetTxJSON, _ := json.MarshalIndent(flatLoanSetTx, "", " ")
fmt.Printf("%s\n", string(loanSetTxJSON))
// Loan broker signs first
fmt.Printf("\n=== Adding loan broker signature ===\n\n")
_, _, err = loanBrokerWallet.Sign(flatLoanSetTx)
if err != nil {
panic(err)
}
fmt.Printf("TxnSignature: %s\n", flatLoanSetTx["TxnSignature"])
fmt.Printf("SigningPubKey: %s\n\n", flatLoanSetTx["SigningPubKey"])
loanBrokerSignedJSON, _ := json.MarshalIndent(flatLoanSetTx, "", " ")
fmt.Printf("Signed loanSetTx for borrower to sign over:\n%s\n", string(loanBrokerSignedJSON))
// Borrower signs second
fmt.Printf("\n=== Adding borrower signature ===\n\n")
fullySignedBlob, _, err := wallet.SignLoanSetByCounterparty(borrowerWallet, &flatLoanSetTx, nil)
if err != nil {
panic(err)
}
borrowerSignatures := flatLoanSetTx["CounterpartySignature"].(map[string]any)
fmt.Printf("Borrower TxnSignature: %s\n", borrowerSignatures["TxnSignature"])
fmt.Printf("Borrower SigningPubKey: %s\n", borrowerSignatures["SigningPubKey"])
fullySignedJSON, _ := json.MarshalIndent(flatLoanSetTx, "", " ")
fmt.Printf("\nFully signed LoanSet transaction:\n%s\n", string(fullySignedJSON))
// Submit and wait for validation ----------------------
fmt.Printf("\n=== Submitting signed LoanSet transaction ===\n\n")
loanSetResponse, err := client.SubmitTxBlobAndWait(fullySignedBlob, false)
if err != nil {
panic(err)
}
if loanSetResponse.Meta.TransactionResult != "tesSUCCESS" {
fmt.Printf("Error: Unable to create loan: %s\n", loanSetResponse.Meta.TransactionResult)
os.Exit(1)
}
fmt.Printf("Loan created successfully!\n")
// Extract loan information from the transaction result
fmt.Printf("\n=== Loan Information ===\n\n")
for _, node := range loanSetResponse.Meta.AffectedNodes {
if node.CreatedNode != nil && node.CreatedNode.LedgerEntryType == "Loan" {
loanJSON, _ := json.MarshalIndent(node.CreatedNode.NewFields, "", " ")
fmt.Printf("%s\n", string(loanJSON))
break
}
}
}

View File

@@ -0,0 +1,19 @@
module github.com/XRPLF
go 1.24.3
require github.com/Peersyst/xrpl-go v0.1.17
require (
github.com/bsv-blockchain/go-sdk v1.2.9 // indirect
github.com/decred/dcrd/crypto/ripemd160 v1.0.2 // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/crypto v0.44.0 // indirect
)

View File

@@ -0,0 +1,656 @@
// Setup script for lending protocol tutorials
package main
import (
"encoding/hex"
"encoding/json"
"fmt"
"os"
"time"
"github.com/Peersyst/xrpl-go/pkg/crypto"
"github.com/Peersyst/xrpl-go/xrpl/faucet"
ledger "github.com/Peersyst/xrpl-go/xrpl/ledger-entry-types"
"github.com/Peersyst/xrpl-go/xrpl/queries/account"
"github.com/Peersyst/xrpl-go/xrpl/queries/common"
requests "github.com/Peersyst/xrpl-go/xrpl/queries/transactions"
"github.com/Peersyst/xrpl-go/xrpl/rpc"
rpctypes "github.com/Peersyst/xrpl-go/xrpl/rpc/types"
"github.com/Peersyst/xrpl-go/xrpl/transaction"
"github.com/Peersyst/xrpl-go/xrpl/transaction/types"
"github.com/Peersyst/xrpl-go/xrpl/wallet"
)
// ptr is a helper that returns a pointer to the given value,
// used for setting optional transaction fields in Go.
func ptr[T any](v T) *T { return &v }
func main() {
fmt.Print("Setting up tutorial: 0/7\r")
// Connect to devnet
cfg, err := rpc.NewClientConfig(
"https://s.devnet.rippletest.net:51234",
rpc.WithFaucetProvider(faucet.NewDevnetFaucetProvider()),
)
if err != nil {
panic(err)
}
client := rpc.NewClient(cfg)
submitOpts := func(w *wallet.Wallet) *rpctypes.SubmitOptions {
return &rpctypes.SubmitOptions{Autofill: true, Wallet: w}
}
// Create and fund wallets concurrently
createAndFund := func(ch chan<- wallet.Wallet) {
w, err := wallet.New(crypto.ED25519())
if err != nil {
panic(err)
}
if err := client.FundWallet(&w); err != nil {
panic(err)
}
// Poll until account is validated on ledger
funded := false
for range 20 {
_, err := client.Request(&account.InfoRequest{
Account: w.GetAddress(),
LedgerIndex: common.Validated,
})
if err == nil {
funded = true
break
}
time.Sleep(time.Second)
}
if !funded {
panic("Issue funding account: " + w.GetAddress().String())
}
ch <- w
}
lbWalletCh := make(chan wallet.Wallet, 1)
brWalletCh := make(chan wallet.Wallet, 1)
depWalletCh := make(chan wallet.Wallet, 1)
credWalletCh := make(chan wallet.Wallet, 1)
go createAndFund(lbWalletCh)
go createAndFund(brWalletCh)
go createAndFund(depWalletCh)
go createAndFund(credWalletCh)
loanBrokerWallet := <-lbWalletCh
borrowerWallet := <-brWalletCh
depositorWallet := <-depWalletCh
credIssuerWallet := <-credWalletCh
fmt.Print("Setting up tutorial: 1/7\r")
// Create tickets for parallel transactions
extractTickets := func(resp *requests.TxResponse) []uint32 {
var tickets []uint32
for _, node := range resp.Meta.AffectedNodes {
if node.CreatedNode != nil && node.CreatedNode.LedgerEntryType == "Ticket" {
ticketSeq, _ := node.CreatedNode.NewFields["TicketSequence"].(json.Number).Int64()
tickets = append(tickets, uint32(ticketSeq))
}
}
return tickets
}
ciTicketCh := make(chan []uint32, 1)
lbTicketCh := make(chan []uint32, 1)
brTicketCh := make(chan []uint32, 1)
dpTicketCh := make(chan []uint32, 1)
go func() {
resp, err := client.SubmitTxAndWait((&transaction.TicketCreate{
BaseTx: transaction.BaseTx{
Account: credIssuerWallet.GetAddress(),
},
TicketCount: 4,
}).Flatten(), submitOpts(&credIssuerWallet))
if err != nil {
panic(err)
}
ciTicketCh <- extractTickets(resp)
}()
go func() {
resp, err := client.SubmitTxAndWait((&transaction.TicketCreate{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.GetAddress(),
},
TicketCount: 4,
}).Flatten(), submitOpts(&loanBrokerWallet))
if err != nil {
panic(err)
}
lbTicketCh <- extractTickets(resp)
}()
go func() {
resp, err := client.SubmitTxAndWait((&transaction.TicketCreate{
BaseTx: transaction.BaseTx{
Account: borrowerWallet.GetAddress(),
},
TicketCount: 2,
}).Flatten(), submitOpts(&borrowerWallet))
if err != nil {
panic(err)
}
brTicketCh <- extractTickets(resp)
}()
go func() {
resp, err := client.SubmitTxAndWait((&transaction.TicketCreate{
BaseTx: transaction.BaseTx{
Account: depositorWallet.GetAddress(),
},
TicketCount: 2,
}).Flatten(), submitOpts(&depositorWallet))
if err != nil {
panic(err)
}
dpTicketCh <- extractTickets(resp)
}()
ciTickets := <-ciTicketCh
lbTickets := <-lbTicketCh
brTickets := <-brTicketCh
dpTickets := <-dpTicketCh
fmt.Print("Setting up tutorial: 2/7\r")
// Issue MPT with depositor
// Set up credentials and domain with credentialIssuer
credentialType := hex.EncodeToString([]byte("KYC-Verified"))
mptData := types.ParsedMPTokenMetadata{
Ticker: "TSTUSD",
Name: "Test USD MPT",
Desc: ptr("A sample non-yield-bearing stablecoin backed by U.S. Treasuries."),
Icon: "https://example.org/tstusd-icon.png",
AssetClass: "rwa",
AssetSubclass: ptr("stablecoin"),
IssuerName: "Example Treasury Reserve Co.",
URIs: []types.ParsedMPTokenMetadataURI{
{
URI: "https://exampletreasury.com/tstusd",
Category: "website",
Title: "Product Page",
},
{
URI: "https://exampletreasury.com/tstusd/reserve",
Category: "docs",
Title: "Reserve Attestation",
},
},
AdditionalInfo: map[string]any{
"reserve_type": "U.S. Treasury Bills",
"custody_provider": "Example Custodian Bank",
"audit_frequency": "Monthly",
"last_audit_date": "2026-01-15",
"pegged_currency": "USD",
},
}
mptMetadataHex, err := types.EncodeMPTokenMetadata(mptData)
if err != nil {
panic(err)
}
mptCh := make(chan *requests.TxResponse, 1)
domainCh := make(chan *requests.TxResponse, 1)
credLbCh := make(chan struct{}, 1)
credBrCh := make(chan struct{}, 1)
credDpCh := make(chan struct{}, 1)
// MPT issuance
go func() {
resp, err := client.SubmitTxAndWait((&transaction.MPTokenIssuanceCreate{
BaseTx: transaction.BaseTx{
Account: depositorWallet.GetAddress(),
Flags: transaction.TfMPTCanTransfer | transaction.TfMPTCanClawback | transaction.TfMPTCanTrade,
},
MaximumAmount: ptr(types.XRPCurrencyAmount(100000000)),
TransferFee: ptr(uint16(0)),
MPTokenMetadata: &mptMetadataHex,
}).Flatten(), submitOpts(&depositorWallet))
if err != nil {
panic(err)
}
mptCh <- resp
}()
// PermissionedDomainSet
go func() {
resp, err := client.SubmitTxAndWait((&transaction.PermissionedDomainSet{
BaseTx: transaction.BaseTx{
Account: credIssuerWallet.GetAddress(),
Sequence: 0,
TicketSequence: ciTickets[0],
},
AcceptedCredentials: types.AuthorizeCredentialList{
{
Credential: types.Credential{
Issuer: credIssuerWallet.GetAddress(),
CredentialType: types.CredentialType(credentialType),
},
},
},
}).Flatten(), submitOpts(&credIssuerWallet))
if err != nil {
panic(err)
}
domainCh <- resp
}()
// CredentialCreate for loan broker
go func() {
_, err := client.SubmitTxAndWait((&transaction.CredentialCreate{
BaseTx: transaction.BaseTx{
Account: credIssuerWallet.GetAddress(),
Sequence: 0,
TicketSequence: ciTickets[1],
},
CredentialType: types.CredentialType(credentialType),
Subject: loanBrokerWallet.GetAddress(),
}).Flatten(), submitOpts(&credIssuerWallet))
if err != nil {
panic(err)
}
credLbCh <- struct{}{}
}()
// CredentialCreate for borrower
go func() {
_, err := client.SubmitTxAndWait((&transaction.CredentialCreate{
BaseTx: transaction.BaseTx{
Account: credIssuerWallet.GetAddress(),
Sequence: 0,
TicketSequence: ciTickets[2],
},
CredentialType: types.CredentialType(credentialType),
Subject: borrowerWallet.GetAddress(),
}).Flatten(), submitOpts(&credIssuerWallet))
if err != nil {
panic(err)
}
credBrCh <- struct{}{}
}()
// CredentialCreate for depositor
go func() {
_, err := client.SubmitTxAndWait((&transaction.CredentialCreate{
BaseTx: transaction.BaseTx{
Account: credIssuerWallet.GetAddress(),
Sequence: 0,
TicketSequence: ciTickets[3],
},
CredentialType: types.CredentialType(credentialType),
Subject: depositorWallet.GetAddress(),
}).Flatten(), submitOpts(&credIssuerWallet))
if err != nil {
panic(err)
}
credDpCh <- struct{}{}
}()
mptResp := <-mptCh
domainResp := <-domainCh
<-credLbCh
<-credBrCh
<-credDpCh
// Extract MPT issuance ID
mptID := string(*mptResp.Meta.MPTIssuanceID)
// Extract domain ID from transaction meta
var domainID string
for _, node := range domainResp.Meta.AffectedNodes {
if node.CreatedNode != nil && node.CreatedNode.LedgerEntryType == "PermissionedDomain" {
domainID = node.CreatedNode.LedgerIndex
break
}
}
fmt.Print("Setting up tutorial: 3/7\r")
// Accept credentials and authorize MPT for each account
lbCredCh := make(chan struct{}, 1)
lbMptCh := make(chan struct{}, 1)
brCredCh := make(chan struct{}, 1)
brMptCh := make(chan struct{}, 1)
depCredCh := make(chan struct{}, 1)
// Loan broker: accept credential
go func() {
_, err := client.SubmitTxAndWait((&transaction.CredentialAccept{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.GetAddress(),
Sequence: 0,
TicketSequence: lbTickets[0],
},
CredentialType: types.CredentialType(credentialType),
Issuer: credIssuerWallet.GetAddress(),
}).Flatten(), submitOpts(&loanBrokerWallet))
if err != nil {
panic(err)
}
lbCredCh <- struct{}{}
}()
// Loan broker: authorize MPT
go func() {
_, err := client.SubmitTxAndWait((&transaction.MPTokenAuthorize{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.GetAddress(),
Sequence: 0,
TicketSequence: lbTickets[1],
},
MPTokenIssuanceID: mptID,
}).Flatten(), submitOpts(&loanBrokerWallet))
if err != nil {
panic(err)
}
lbMptCh <- struct{}{}
}()
// Borrower: accept credential
go func() {
_, err := client.SubmitTxAndWait((&transaction.CredentialAccept{
BaseTx: transaction.BaseTx{
Account: borrowerWallet.GetAddress(),
Sequence: 0,
TicketSequence: brTickets[0],
},
CredentialType: types.CredentialType(credentialType),
Issuer: credIssuerWallet.GetAddress(),
}).Flatten(), submitOpts(&borrowerWallet))
if err != nil {
panic(err)
}
brCredCh <- struct{}{}
}()
// Borrower: authorize MPT
go func() {
_, err := client.SubmitTxAndWait((&transaction.MPTokenAuthorize{
BaseTx: transaction.BaseTx{
Account: borrowerWallet.GetAddress(),
Sequence: 0,
TicketSequence: brTickets[1],
},
MPTokenIssuanceID: mptID,
}).Flatten(), submitOpts(&borrowerWallet))
if err != nil {
panic(err)
}
brMptCh <- struct{}{}
}()
// Depositor: accept credential only
go func() {
_, err := client.SubmitTxAndWait((&transaction.CredentialAccept{
BaseTx: transaction.BaseTx{
Account: depositorWallet.GetAddress(),
},
CredentialType: types.CredentialType(credentialType),
Issuer: credIssuerWallet.GetAddress(),
}).Flatten(), submitOpts(&depositorWallet))
if err != nil {
panic(err)
}
depCredCh <- struct{}{}
}()
<-lbCredCh
<-lbMptCh
<-brCredCh
<-brMptCh
<-depCredCh
fmt.Print("Setting up tutorial: 4/7\r")
// Create private vault and distribute MPT to accounts concurrently
vaultCh := make(chan *requests.TxResponse, 1)
distLbCh := make(chan struct{}, 1)
distBrCh := make(chan struct{}, 1)
go func() {
resp, err := client.SubmitTxAndWait((&transaction.VaultCreate{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.GetAddress(),
Flags: transaction.TfVaultPrivate,
},
Asset: ledger.Asset{MPTIssuanceID: mptID},
DomainID: &domainID,
}).Flatten(), submitOpts(&loanBrokerWallet))
if err != nil {
panic(err)
}
vaultCh <- resp
}()
go func() {
_, err := client.SubmitTxAndWait((&transaction.Payment{
BaseTx: transaction.BaseTx{
Account: depositorWallet.GetAddress(),
Sequence: 0,
TicketSequence: dpTickets[0],
},
Destination: loanBrokerWallet.GetAddress(),
Amount: types.MPTCurrencyAmount{
MPTIssuanceID: mptID,
Value: "5000",
},
}).Flatten(), submitOpts(&depositorWallet))
if err != nil {
panic(err)
}
distLbCh <- struct{}{}
}()
go func() {
_, err := client.SubmitTxAndWait((&transaction.Payment{
BaseTx: transaction.BaseTx{
Account: depositorWallet.GetAddress(),
Sequence: 0,
TicketSequence: dpTickets[1],
},
Destination: borrowerWallet.GetAddress(),
Amount: types.MPTCurrencyAmount{
MPTIssuanceID: mptID,
Value: "2500",
},
}).Flatten(), submitOpts(&depositorWallet))
if err != nil {
panic(err)
}
distBrCh <- struct{}{}
}()
vaultResp := <-vaultCh
<-distLbCh
<-distBrCh
var vaultID string
for _, node := range vaultResp.Meta.AffectedNodes {
if node.CreatedNode != nil && node.CreatedNode.LedgerEntryType == "Vault" {
vaultID = node.CreatedNode.LedgerIndex
break
}
}
fmt.Print("Setting up tutorial: 5/7\r")
// Create LoanBroker and deposit MPT into vault
lbSetCh := make(chan *requests.TxResponse, 1)
vaultDepCh := make(chan struct{}, 1)
go func() {
resp, err := client.SubmitTxAndWait((&transaction.LoanBrokerSet{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.GetAddress(),
},
VaultID: vaultID,
}).Flatten(), submitOpts(&loanBrokerWallet))
if err != nil {
panic(err)
}
lbSetCh <- resp
}()
go func() {
_, err := client.SubmitTxAndWait((&transaction.VaultDeposit{
BaseTx: transaction.BaseTx{
Account: depositorWallet.GetAddress(),
},
VaultID: types.Hash256(vaultID),
Amount: types.MPTCurrencyAmount{
MPTIssuanceID: mptID,
Value: "50000000",
},
}).Flatten(), submitOpts(&depositorWallet))
if err != nil {
panic(err)
}
vaultDepCh <- struct{}{}
}()
lbSetResp := <-lbSetCh
<-vaultDepCh
var loanBrokerID string
for _, node := range lbSetResp.Meta.AffectedNodes {
if node.CreatedNode != nil && node.CreatedNode.LedgerEntryType == "LoanBroker" {
loanBrokerID = node.CreatedNode.LedgerIndex
break
}
}
fmt.Print("Setting up tutorial: 6/7\r")
// Create 2 identical loans with complete repayment due in 30 days
// Helper function to create, sign, and submit a LoanSet transaction
createLoan := func(ticketSequence uint32) *requests.TxResponse {
counterparty := borrowerWallet.GetAddress()
loanSetTx := &transaction.LoanSet{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.GetAddress(),
Sequence: 0,
TicketSequence: ticketSequence,
},
LoanBrokerID: loanBrokerID,
PrincipalRequested: "1000",
Counterparty: &counterparty,
InterestRate: ptr(types.InterestRate(500)),
PaymentTotal: ptr(types.PaymentTotal(1)),
PaymentInterval: ptr(types.PaymentInterval(2592000)),
LoanOriginationFee: ptr(types.XRPLNumber("100")),
LoanServiceFee: ptr(types.XRPLNumber("10")),
}
flatTx := transaction.FlatTransaction(loanSetTx.Flatten())
if err := client.Autofill(&flatTx); err != nil {
panic(err)
}
// Loan broker signs first
_, _, err := loanBrokerWallet.Sign(flatTx)
if err != nil {
panic(err)
}
// Borrower signs second
blob, _, err := wallet.SignLoanSetByCounterparty(borrowerWallet, &flatTx, nil)
if err != nil {
panic(err)
}
// Submit and wait for validation
resp, err := client.SubmitTxBlobAndWait(blob, false)
if err != nil {
panic(err)
}
return resp
}
loan1Ch := make(chan *requests.TxResponse, 1)
loan2Ch := make(chan *requests.TxResponse, 1)
go func() { loan1Ch <- createLoan(lbTickets[2]) }()
go func() { loan2Ch <- createLoan(lbTickets[3]) }()
loan1Resp := <-loan1Ch
loan2Resp := <-loan2Ch
var loanID1, loanID2 string
for _, node := range loan1Resp.Meta.AffectedNodes {
if node.CreatedNode != nil && node.CreatedNode.LedgerEntryType == "Loan" {
loanID1 = node.CreatedNode.LedgerIndex
break
}
}
for _, node := range loan2Resp.Meta.AffectedNodes {
if node.CreatedNode != nil && node.CreatedNode.LedgerEntryType == "Loan" {
loanID2 = node.CreatedNode.LedgerIndex
break
}
}
fmt.Print("Setting up tutorial: 7/7\r")
// Write setup data to JSON file.
// Using a struct to preserve field order.
setupData := struct {
Description string `json:"description"`
LoanBroker any `json:"loanBroker"`
Borrower any `json:"borrower"`
Depositor any `json:"depositor"`
CredentialIssuer any `json:"credentialIssuer"`
DomainID string `json:"domainID"`
MptID string `json:"mptID"`
VaultID string `json:"vaultID"`
LoanBrokerID string `json:"loanBrokerID"`
LoanID1 string `json:"loanID1"`
LoanID2 string `json:"loanID2"`
}{
Description: "This file is auto-generated by lending-setup. It stores XRPL account info for use in lending protocol tutorials.",
LoanBroker: map[string]string{
"address": string(loanBrokerWallet.ClassicAddress),
"seed": loanBrokerWallet.Seed,
},
Borrower: map[string]string{
"address": string(borrowerWallet.ClassicAddress),
"seed": borrowerWallet.Seed,
},
Depositor: map[string]string{
"address": string(depositorWallet.ClassicAddress),
"seed": depositorWallet.Seed,
},
CredentialIssuer: map[string]string{
"address": string(credIssuerWallet.ClassicAddress),
"seed": credIssuerWallet.Seed,
},
DomainID: domainID,
MptID: mptID,
VaultID: vaultID,
LoanBrokerID: loanBrokerID,
LoanID1: loanID1,
LoanID2: loanID2,
}
jsonData, err := json.MarshalIndent(setupData, "", " ")
if err != nil {
panic(err)
}
if err := os.WriteFile("lending-setup.json", jsonData, 0644); err != nil {
panic(err)
}
fmt.Println("Setting up tutorial: Complete!")
}

View File

@@ -0,0 +1,195 @@
// IMPORTANT: This example impairs an existing loan, which has a 60 second grace period.
// After the 60 seconds pass, this example defaults the loan.
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"time"
"github.com/Peersyst/xrpl-go/xrpl/flag"
"github.com/Peersyst/xrpl-go/xrpl/queries/common"
"github.com/Peersyst/xrpl-go/xrpl/queries/ledger"
xrpltime "github.com/Peersyst/xrpl-go/xrpl/time"
"github.com/Peersyst/xrpl-go/xrpl/transaction"
"github.com/Peersyst/xrpl-go/xrpl/wallet"
"github.com/Peersyst/xrpl-go/xrpl/websocket"
wstypes "github.com/Peersyst/xrpl-go/xrpl/websocket/types"
)
func main() {
// Connect to the network ----------------------
client := websocket.NewClient(
websocket.NewClientConfig().
WithHost("wss://s.devnet.rippletest.net:51233"),
)
defer client.Disconnect()
if err := client.Connect(); err != nil {
panic(err)
}
// Check for setup data; run lending-setup if missing
if _, err := os.Stat("lending-setup.json"); os.IsNotExist(err) {
fmt.Printf("\n=== Lending tutorial data doesn't exist. Running setup script... ===\n\n")
cmd := exec.Command("go", "run", "./lending-setup")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
panic(err)
}
}
// Load preconfigured accounts and LoanID
data, err := os.ReadFile("lending-setup.json")
if err != nil {
panic(err)
}
var setup map[string]any
if err := json.Unmarshal(data, &setup); err != nil {
panic(err)
}
// You can replace these values with your own
loanBrokerWallet, err := wallet.FromSecret(setup["loanBroker"].(map[string]any)["seed"].(string))
if err != nil {
panic(err)
}
loanID := setup["loanID1"].(string)
fmt.Printf("\nLoan broker address: %s\n", loanBrokerWallet.ClassicAddress)
fmt.Printf("LoanID: %s\n", loanID)
// Check loan status before impairment ----------------------
fmt.Printf("\n=== Loan Status ===\n\n")
loanStatus, err := client.GetLedgerEntry(&ledger.EntryRequest{
Index: loanID,
LedgerIndex: common.Validated,
})
if err != nil {
panic(err)
}
fmt.Printf("Total Amount Owed: %s TSTUSD.\n", loanStatus.Node["TotalValueOutstanding"])
// Convert Ripple Epoch timestamp to local date and time
nextPaymentDueDate := int64(loanStatus.Node["NextPaymentDueDate"].(float64))
paymentDue := time.UnixMilli(xrpltime.RippleTimeToUnixTime(nextPaymentDueDate))
fmt.Printf("Payment Due Date: %s\n", paymentDue.Local().Format(time.DateTime))
// Prepare LoanManage transaction to impair the loan ----------------------
fmt.Printf("\n=== Preparing LoanManage transaction to impair loan ===\n\n")
loanManageImpair := transaction.LoanManage{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.ClassicAddress,
},
LoanID: loanID,
}
loanManageImpair.SetLoanImpairFlag()
// Flatten() converts the struct to a map and adds the TransactionType field
flatLoanManageImpair := loanManageImpair.Flatten()
loanManageImpairJSON, _ := json.MarshalIndent(flatLoanManageImpair, "", " ")
fmt.Printf("%s\n", string(loanManageImpairJSON))
// Sign, submit, and wait for impairment validation ----------------------
fmt.Printf("\n=== Submitting LoanManage impairment transaction ===\n\n")
impairResponse, err := client.SubmitTxAndWait(flatLoanManageImpair, &wstypes.SubmitOptions{
Autofill: true,
Wallet: &loanBrokerWallet,
})
if err != nil {
panic(err)
}
if impairResponse.Meta.TransactionResult != "tesSUCCESS" {
fmt.Printf("Error: Unable to impair loan: %s\n", impairResponse.Meta.TransactionResult)
os.Exit(1)
}
fmt.Printf("Loan impaired successfully!\n")
// Extract loan impairment info from transaction results ----------------------
var loanNode map[string]any
for _, node := range impairResponse.Meta.AffectedNodes {
if node.ModifiedNode != nil && node.ModifiedNode.LedgerEntryType == "Loan" {
loanNode = node.ModifiedNode.FinalFields
break
}
}
// Check grace period and next payment due date
gracePeriod := int64(loanNode["GracePeriod"].(float64))
nextPaymentDueDate = int64(loanNode["NextPaymentDueDate"].(float64))
defaultTime := nextPaymentDueDate + gracePeriod
paymentDue = time.UnixMilli(xrpltime.RippleTimeToUnixTime(nextPaymentDueDate))
fmt.Printf("New Payment Due Date: %s\n", paymentDue.Local().Format(time.DateTime))
fmt.Printf("Grace Period: %d seconds\n", gracePeriod)
// Convert current time to Ripple Epoch timestamp
currentTime := xrpltime.UnixTimeToRippleTime(time.Now().Unix())
// Add a small buffer (5 seconds) to account for ledger close time
secondsUntilDefault := defaultTime - currentTime + 5
// Countdown until loan can be defaulted ----------------------
fmt.Printf("\n=== Countdown until loan can be defaulted ===\n\n")
for secondsUntilDefault >= 0 {
fmt.Printf("\r%d seconds...", secondsUntilDefault)
time.Sleep(time.Second)
secondsUntilDefault--
}
fmt.Print("\rGrace period expired. Loan can now be defaulted.\n")
// Prepare LoanManage transaction to default the loan ----------------------
fmt.Printf("\n=== Preparing LoanManage transaction to default loan ===\n\n")
loanManageDefault := transaction.LoanManage{
BaseTx: transaction.BaseTx{
Account: loanBrokerWallet.ClassicAddress,
},
LoanID: loanID,
}
loanManageDefault.SetLoanDefaultFlag()
flatLoanManageDefault := loanManageDefault.Flatten()
loanManageDefaultJSON, _ := json.MarshalIndent(flatLoanManageDefault, "", " ")
fmt.Printf("%s\n", string(loanManageDefaultJSON))
// Sign, submit, and wait for default validation ----------------------
fmt.Printf("\n=== Submitting LoanManage default transaction ===\n\n")
defaultResponse, err := client.SubmitTxAndWait(flatLoanManageDefault, &wstypes.SubmitOptions{
Autofill: true,
Wallet: &loanBrokerWallet,
})
if err != nil {
panic(err)
}
if defaultResponse.Meta.TransactionResult != "tesSUCCESS" {
fmt.Printf("Error: Unable to default loan: %s\n", defaultResponse.Meta.TransactionResult)
os.Exit(1)
}
fmt.Printf("Loan defaulted successfully!\n")
// Verify loan default status from transaction results ----------------------
fmt.Printf("\n=== Checking final loan status ===\n\n")
for _, node := range defaultResponse.Meta.AffectedNodes {
if node.ModifiedNode != nil && node.ModifiedNode.LedgerEntryType == "Loan" {
loanNode = node.ModifiedNode.FinalFields
break
}
}
loanFlags := uint32(loanNode["Flags"].(float64))
// Check which loan flags are set
activeFlags := []string{}
if flag.Contains(loanFlags, transaction.TfLoanDefault) {
activeFlags = append(activeFlags, "tfLoanDefault")
}
if flag.Contains(loanFlags, transaction.TfLoanImpair) {
activeFlags = append(activeFlags, "tfLoanImpair")
}
fmt.Printf("Final loan flags: %v\n", activeFlags)
}

View File

@@ -0,0 +1,179 @@
// IMPORTANT: This example pays off an existing loan and then deletes it.
package main
import (
"encoding/json"
"fmt"
"math/big"
"os"
"os/exec"
"github.com/Peersyst/xrpl-go/xrpl/queries/common"
"github.com/Peersyst/xrpl-go/xrpl/queries/ledger"
"github.com/Peersyst/xrpl-go/xrpl/transaction"
"github.com/Peersyst/xrpl-go/xrpl/transaction/types"
"github.com/Peersyst/xrpl-go/xrpl/wallet"
"github.com/Peersyst/xrpl-go/xrpl/websocket"
wstypes "github.com/Peersyst/xrpl-go/xrpl/websocket/types"
)
func main() {
// Connect to the network ----------------------
client := websocket.NewClient(
websocket.NewClientConfig().
WithHost("wss://s.devnet.rippletest.net:51233"),
)
defer client.Disconnect()
if err := client.Connect(); err != nil {
panic(err)
}
// Check for setup data; run lending-setup if missing
if _, err := os.Stat("lending-setup.json"); os.IsNotExist(err) {
fmt.Printf("\n=== Lending tutorial data doesn't exist. Running setup script... ===\n\n")
cmd := exec.Command("go", "run", "./lending-setup")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
panic(err)
}
}
// Load preconfigured accounts and LoanID
data, err := os.ReadFile("lending-setup.json")
if err != nil {
panic(err)
}
var setup map[string]any
if err := json.Unmarshal(data, &setup); err != nil {
panic(err)
}
// You can replace these values with your own
borrowerWallet, err := wallet.FromSecret(setup["borrower"].(map[string]any)["seed"].(string))
if err != nil {
panic(err)
}
loanID := setup["loanID2"].(string)
mptID := setup["mptID"].(string)
fmt.Printf("\nBorrower address: %s\n", borrowerWallet.ClassicAddress)
fmt.Printf("LoanID: %s\n", loanID)
fmt.Printf("MPT ID: %s\n", mptID)
// Check initial loan status ----------------------
fmt.Printf("\n=== Loan Status ===\n\n")
loanStatus, err := client.GetLedgerEntry(&ledger.EntryRequest{
Index: loanID,
LedgerIndex: common.Validated,
})
if err != nil {
panic(err)
}
totalValueOutstanding := loanStatus.Node["TotalValueOutstanding"].(string)
loanServiceFee := loanStatus.Node["LoanServiceFee"].(string)
outstanding, _ := new(big.Int).SetString(totalValueOutstanding, 10)
serviceFee, _ := new(big.Int).SetString(loanServiceFee, 10)
totalPayment := new(big.Int).Add(outstanding, serviceFee).String()
fmt.Printf("Amount Owed: %s TSTUSD\n", totalValueOutstanding)
fmt.Printf("Loan Service Fee: %s TSTUSD\n", loanServiceFee)
fmt.Printf("Total Payment Due (including fees): %s TSTUSD\n", totalPayment)
// Prepare LoanPay transaction ----------------------
fmt.Printf("\n=== Preparing LoanPay transaction ===\n\n")
loanPayTx := transaction.LoanPay{
BaseTx: transaction.BaseTx{
Account: borrowerWallet.ClassicAddress,
},
LoanID: loanID,
Amount: types.MPTCurrencyAmount{
MPTIssuanceID: mptID,
Value: totalPayment,
},
}
// Flatten() converts the struct to a map and adds the TransactionType field
flatLoanPayTx := loanPayTx.Flatten()
loanPayTxJSON, _ := json.MarshalIndent(flatLoanPayTx, "", " ")
fmt.Printf("%s\n", string(loanPayTxJSON))
// Sign, submit, and wait for payment validation ----------------------
fmt.Printf("\n=== Submitting LoanPay transaction ===\n\n")
payResponse, err := client.SubmitTxAndWait(flatLoanPayTx, &wstypes.SubmitOptions{
Autofill: true,
Wallet: &borrowerWallet,
})
if err != nil {
panic(err)
}
if payResponse.Meta.TransactionResult != "tesSUCCESS" {
fmt.Printf("Error: Unable to pay loan: %s\n", payResponse.Meta.TransactionResult)
os.Exit(1)
}
fmt.Printf("Loan paid successfully!\n")
// Extract updated loan info from transaction results ----------------------
fmt.Printf("\n=== Loan Status After Payment ===\n\n")
for _, node := range payResponse.Meta.AffectedNodes {
if node.ModifiedNode != nil && node.ModifiedNode.LedgerEntryType == "Loan" {
if balance, ok := node.ModifiedNode.FinalFields["TotalValueOutstanding"].(string); ok {
fmt.Printf("Outstanding Loan Balance: %s TSTUSD\n", balance)
} else {
fmt.Printf("Outstanding Loan Balance: Loan fully paid off!\n")
}
break
}
}
// Prepare LoanDelete transaction ----------------------
// Either the loan broker or borrower can submit this transaction.
fmt.Printf("\n=== Preparing LoanDelete transaction ===\n\n")
loanDeleteTx := transaction.LoanDelete{
BaseTx: transaction.BaseTx{
Account: borrowerWallet.ClassicAddress,
},
LoanID: loanID,
}
flatLoanDeleteTx := loanDeleteTx.Flatten()
loanDeleteTxJSON, _ := json.MarshalIndent(flatLoanDeleteTx, "", " ")
fmt.Printf("%s\n", string(loanDeleteTxJSON))
// Sign, submit, and wait for deletion validation ----------------------
fmt.Printf("\n=== Submitting LoanDelete transaction ===\n\n")
deleteResponse, err := client.SubmitTxAndWait(flatLoanDeleteTx, &wstypes.SubmitOptions{
Autofill: true,
Wallet: &borrowerWallet,
})
if err != nil {
panic(err)
}
if deleteResponse.Meta.TransactionResult != "tesSUCCESS" {
fmt.Printf("Error: Unable to delete loan: %s\n", deleteResponse.Meta.TransactionResult)
os.Exit(1)
}
fmt.Printf("Loan deleted successfully!\n")
// Verify loan deletion ----------------------
fmt.Printf("\n=== Verifying Loan Deletion ===\n\n")
_, err = client.GetLedgerEntry(&ledger.EntryRequest{
Index: loanID,
LedgerIndex: common.Validated,
})
if err != nil {
if err.Error() == "entryNotFound" {
fmt.Printf("Loan has been successfully removed from the XRP Ledger!\n")
} else {
panic(err)
}
} else {
fmt.Printf("Warning: Loan still exists in the ledger.\n")
}
}

View File

@@ -0,0 +1,101 @@
---
category: 2026
date: "2026-03-23"
template: '../../@theme/templates/blogpost'
seo:
description: This vulnerability disclosure report contains technical details of the XRP Ledger bug reported on June 9, 2025.
labels:
- Advisories
markdown:
editPage:
hide: true
---
# Vulnerability Disclosure Report: Transaction Set Handling
This vulnerability disclosure report contains technical details of the XRP Ledger bug reported on June 9, 2025.
**Date Reported:** June 9, 2025
**Affected Version(s):** rippled up to 2.6.2
## Summary of Vulnerability
Two vulnerabilities that affected XRPL's liveness were discovered by **Common Prefix**, which could have prevented the network from making forward progress. A UNL validator would need to have been compromised in order to exploit the bugs. Fixes for both vulnerabilities were released as part of version 3.0.0 of rippled.
## Impact
If a UNL validator had been compromised before these vulnerabilities were fixed, a modified version of rippled could have been deployed that exploited the bugs. In particular, by manipulating the transaction data in transaction sets, the compromised validator could then cause a crash in all other validators that directly received the modified message. Crashes could then be triggered repeatedly until removal of the compromised validator from the UNL.
## Technical Details
### Discovery
**Nikolaos Kamarinakis** from **Common Prefix** reported the vulnerabilities via a responsible disclosure report. Ripple engineering teams validated the report with an independent proof-of-concept that reproduced both bugs in a separate network.
### Root Cause
A consensus round between validators is an attempt to agree on a set of transactions so they can be processed and included in the ledger. Each validator proposes a set of unprocessed transactions that they know about, and exchanges messages with other validators to establish a final set of transactions that a supermajority of them can agree on. The two vulnerabilities arose from how the transaction sets disputes were handled in our code.
Both vulnerabilities required one of the ~35 UNL validators to have been compromised, which would open the door to sending a maliciously crafted message that in turn would trigger any receiving node to crash. Even though compromising a UNL validator is challenging since they typically hide behind proxy nodes and only communicate with those nodes, it is not impossible.
### Vulnerability 1: comparing transactions
When a validator receives a transaction set from another validator, it compares that transaction set with its own and identifies the transactions that are different ("disputed"). This is where the first vulnerability came into play, as a compromised validator was able to claim that a certain transaction could be found in a node in the SHAMap where it actually was not located. Any validator who received the malicious transaction set would then crash the moment it tried to look up the transaction ID using the invalid node ID.
### Vulnerability 2: relaying transactions
When a validator has come across disputed transactions, it will relay them to its peers. The second vulnerability leveraged this functionality, whereby a compromised validator sent a transaction set in which the transaction data was an arbitrary hash. Any validator who received the malicious transaction set would identify this as a disputed transaction and would want to relay it to its peers.
Before relaying a transaction, a validator first checks if it is a pseudo transaction, as those should not be relayed. In this case, when a validator would try to perform this inspection, the invalid data in the transaction set would cause it to crash.
## Steps to reproduce
### Vulnerability 1: comparing transactions
1. A compromised validator constructs a `TxSet` where the `TxId` is not in the correct node.
2. The validator sends an accompanying proposal to its peers.
3. Peer validators receive the position, acquire the `TxSet`, and attempt to create disputes. This results in a crash when the node ID is used to look up the transaction ID.
### Vulnerability 2: relaying transactions
1. A compromised validator constructs a `TxSet` containing a `SHAMapItem` with data that cannot be read by the `STTx` constructor.
2. The validator sends an accompanying proposal to its peers.
3. Peer validators receive the position, acquire the `TxSet`, create disputes and attempt to relay them. This results in a crash when the pseudo transaction check is performed.
## Remediation
- To protect against the first vulnerability we added an extra check to confirm that a transaction can really be found in the node where the proposal said it would be.
- To protect against the second vulnerability we added a try-catch to handle the exception that the code will throw when a malicious transaction is inspected.
- To replicate the findings of Common Prefix, we deployed a modified version of rippled in our testing platform to simulate a compromised UNL validator. Without the first fix, the first attack would indeed crash all nodes that received a malicious message sent by the compromised validator. The same thing happened without the second fix when the second attack was launched. After applying both fixes, nodes that received the manipulated messages would no longer crash.
## Security enhancements roadmap
We continue to strengthen XRPLs security posture through multiple initiatives:
- Expanded security audits to preemptively find issues in unreleased code.
- AI-assisted code reviews to identify security issues.
- Hackathons and increased bug bounty incentives.
## Fixes / Patches Available
The fixes were released as part of [**rippled 3.0.0**](../2025/rippled-3.0.0.md).
## Acknowledgements
We extend our deepest gratitude to **Common Prefix** for responsibly disclosing both vulnerabilities and for giving us time and assistance to fix them.
## Contact
For more information or to report further issues, please see the [Bug Bounty Program](https://ripple.com/legal/bug-bounty) page.
## Incident Response Timeline
| Key Action | Date | Description |
|---|---|---|
| Initial discovery | 9 June 2025 | Nikolaos Kamarinakis from Common Prefix submits a bug report. |
| Test bed deployed | 10 July 2025 | Testing set up in place. |
| Bug reproduction | 6 August 2025 | First vulnerability reproduced. |
| Bug reproduction | 11 August 2025 | Second vulnerability reproduced. |
| Fixes created | 19 August 2025 | Fixes created in a private repository and in review. |
| Fixes tested | 10 October 2025 | Common Prefix tests the fixes. |
| Fixes approved | 16 October 2025 | Common Prefix approves the fixes. |
| Fixes released | 9 December 2025 | Fixes included in 3.0.0 release. |
| Report published | 23 March 2026 | Public vulnerability disclosure report published. |

View File

@@ -10,6 +10,7 @@
- group: '2026'
expanded: false
items:
- page: 2026/vulnerabilitydisclosurereport-bug-mar2026.md
- page: 2026/rippled-3.1.2.md
- page: 2026/vulnerabilitydisclosurereport-bug-feb2026.md
- page: 2026/rippled-3.1.1.md

View File

@@ -730,12 +730,22 @@ const CommunityPage: React.FC = () => {
<tbody>
<tr>
<td className="td-img">
<a
href="https://discord.gg/xrpl"
target="_blank"
>
<img className="discord-icon" alt="discord icon" />
</a>
</td>
<td>
{translate(
"Join the XRPL Discord to connect and network with builders, validators, and cryptocurrency enthusiasts."
)}
<a
href="https://discord.gg/xrpl"
target="_blank"
>
{translate(
"Join the XRPL Discord to connect and network with builders, validators, and cryptocurrency enthusiasts."
)}
</a>
</td>
<td>
<a
@@ -749,12 +759,22 @@ const CommunityPage: React.FC = () => {
</tr>
<tr>
<td className="td-img">
<img className="twitter-icon" alt="twitter icon" />
<a
href="https://x.com/RippleXDev"
target="_blank"
>
<img className="twitter-icon" alt="twitter icon" />
</a>
</td>
<td>
{translate(
"Follow @RippleXDev on X for the latest updates on the XRP Ledger ecosystem."
)}
<a
href="https://x.com/RippleXDev"
target="_blank"
>
{translate(
"Follow @RippleXDev on X for the latest updates on the XRP Ledger ecosystem."
)}
</a>
</td>
<td>
<a
@@ -768,12 +788,22 @@ const CommunityPage: React.FC = () => {
</tr>
<tr>
<td className="td-img">
<img className="youtube-icon" alt="youtube icon" />
<a
href="https://youtube.com/playlist?list=PLl-QsmXvjodqxEjtUqEv3u2o2Zd6zqkNA&feature=shared"
target="_blank"
>
<img className="youtube-icon" alt="youtube icon" />
</a>
</td>
<td>
{translate(
"APEX 2025: View keynote sessions from the Apex 2025 where developers, entrepreneurs, and industry leaders come together to learn, build, and celebrate all things XRP Ledger."
)}
<a
href="https://youtube.com/playlist?list=PLl-QsmXvjodqxEjtUqEv3u2o2Zd6zqkNA&feature=shared"
target="_blank"
>
{translate(
"APEX 2025: View keynote sessions from the Apex 2025 where developers, entrepreneurs, and industry leaders come together to learn, build, and celebrate all things XRP Ledger."
)}
</a>
</td>
<td>
<a
@@ -787,12 +817,22 @@ const CommunityPage: React.FC = () => {
</tr>
<tr className="final-tr">
<td className="td-img">
<a
href="https://learn.xrpl.org/react-3d-game/"
target="_blank"
>
<img className="xrpl-icon" alt="xrpl icon" />
</a>
</td>
<td>
<a
href="https://learn.xrpl.org/react-3d-game/"
target="_blank"
>
{translate(
"Explore DeFi-Island: A 3D open-source world on the XRPL testnet. Chat with residents, complete quests, and dive into this React.js-powered experience—all in your web browser."
)}
</a>
</td>
<td>
<a

4
context7.json Normal file
View File

@@ -0,0 +1,4 @@
{
"url": "https://context7.com/xrplf/xrpl-dev-portal",
"public_key": "pk_dOzui5DRlEAqAN0pGtYMi"
}

View File

@@ -273,6 +273,8 @@
[XChainAddClaimAttestation transaction]: /docs/references/protocol/transactions/types/xchainaddclaimattestation.md
[XChainAddClaimAttestation transactions]: /docs/references/protocol/transactions/types/xchainaddclaimattestation.md
[XChainBridge amendment]: /resources/known-amendments.md#xchainbridge
[XChainClaim transaction]: /docs/references/protocol/transactions/types/xchainclaim.md
[XChainClaim transactions]: /docs/references/protocol/transactions/types/xchainclaim.md
[XChainCreateBridge transaction]: /docs/references/protocol/transactions/types/xchaincreatebridge.md
[XChainCreateBridge transactions]: /docs/references/protocol/transactions/types/xchaincreatebridge.md
[XChainCreateBridge]: /docs/references/protocol/transactions/types/xchaincreatebridge.md
@@ -370,6 +372,7 @@
[gateway_balances method]: /docs/references/http-websocket-apis/public-api-methods/account-methods/gateway_balances.md
[get_counts command]: /docs/references/http-websocket-apis/admin-api-methods/status-and-debugging-methods/get_counts.md
[get_counts method]: /docs/references/http-websocket-apis/admin-api-methods/status-and-debugging-methods/get_counts.md
[Get Started Using Go]: /docs/tutorials/get-started/get-started-go.md
[Get Started Using JavaScript]: /docs/tutorials/get-started/get-started-javascript.md
[Get Started Using Python]: /docs/tutorials/get-started/get-started-python.md
[hexadecimal]: https://en.wikipedia.org/wiki/Hexadecimal
@@ -487,5 +490,6 @@
[vault_info method]: /docs/references/http-websocket-apis/public-api-methods/vault-methods/vault_info.md
[wallet_propose command]: /docs/references/http-websocket-apis/admin-api-methods/key-generation-methods/wallet_propose.md
[wallet_propose method]: /docs/references/http-websocket-apis/admin-api-methods/key-generation-methods/wallet_propose.md
[xrpl-go library]: https://github.com/XRPLF/xrpl-go
[xrpl.js library]: https://github.com/XRPLF/xrpl.js
[xrpl-py library]: https://github.com/XRPLF/xrpl-py

View File

@@ -6,7 +6,7 @@ labels:
---
# Deleting Accounts
The owner of an account can send an [AccountDelete transaction][] to deletes the account and related entries from the ledger, sending most of the account's remaining XRP balance to another account. To discourage wasteful creation and deletion of accounts, deleting an account requires burning a higher than usual amount of XRP as the [transaction cost](../transactions/transaction-cost.md).
The owner of an account can send an [AccountDelete transaction][] to delete the account and related entries from the ledger, sending most of the account's remaining XRP balance to another account. To discourage wasteful creation and deletion of accounts, deleting an account requires burning a higher than usual amount of XRP as the [transaction cost](../transactions/transaction-cost.md).
Some types of associated ledger entries block an account from being deleted. For example, the issuer of a fungible token can't be deleted while anyone holds a nonzero balance of that token.
@@ -16,22 +16,32 @@ After an account has been deleted, it can be re-created in the ledger through th
To be deleted, an account must meet the following requirements:
- The account's `Sequence` number plus 256 must be less than the current [Ledger Index][].
- The account must not have any "deletion blockers" in its owner directory. This includes cases where the account is a sender _or_ receiver of funds. See below for a full list of deletion blockers.
- The account must own fewer than 1000 objects in the ledger.
- The account's `Sequence` number plus 255 must be less than or equal to the current [Ledger Index][]. This is to protect against replaying old transactions.
- The account must not have any "deletion blockers" in its owner directory. Deletion blockers are generally ledger entries that represent assets, obligations, or transfers of funds. See below for a full list of deletion blockers.
- The account must own 1000 or fewer objects in the ledger.
- The transaction must pay a special [transaction cost][] equal to at least the [owner reserve](reserves.md) for one item (currently {% $env.PUBLIC_OWNER_RESERVE %}).
- If the account has issued any [NFTs](../tokens/nfts/index.md), they must all have been burned. Additionally, the account's `FirstNFTSequence` number plus `MintedNFTokens` number plus 255 must be less than or equal to the current ledger index. This is to protect against reusing `NFTokenID` values. {% amendment-disclaimer name="fixNFTokenRemint" /%}
### Deletion Blockers
## Deletion Blockers
The following [ledger entry types](../../references/protocol/ledger-data/ledger-entry-types/index.md) are deletion blockers:
The following table shows which [ledger entry types](../../references/protocol/ledger-data/ledger-entry-types/index.md) are deletion blockers. Any other types of ledger entries that an account owns are automatically deleted along with the account.
- `Escrow`
- `PayChannel`
- `RippleState` (trust line)
- `Check`
- `PermissionedDomain` {% amendment-disclaimer name="PermissionedDomains" /%}
Some deletion blockers cannot be removed unilaterally. For example, if you have issued a token to someone else, you cannot delete your account as long as they hold your token. In other cases, you can remove the deletion blocker by sending a transaction that causes the entry to be removed from the ledger.
Any other types of ledger entries that an account owns are automatically deleted along with the account.
| Entry Type | Related Amendment | How to remove |
|---|---|---|
| [Bridge][Bridge entry] | {% amendment-disclaimer name="XChainBridge" compact=true /%} | Cannot be removed. |
| [Check][Check entry] | {% amendment-disclaimer name="Checks" compact=true /%} | Send a [CheckCancel transaction][] to cancel the check. |
| [Escrow][Escrow entry] | (Core protocol) | Send an [EscrowCancel transaction][] to cancel the transaction if it has expired; send [EscrowFinish transaction][] to finish it if you can satisfy the timed and/or conditional requirements of the escrow. Otherwise, you can't remove the entry. |
| [PayChannel][PayChannel entry] | (Core protocol) | Send a [PaymentChannelClaim transaction][] with the `tfClose` flag to request closing the channel; after the settle delay has passed, send another [PaymentChannelClaim transaction][] to fully close and remove the channel. |
| [PermissionedDomain][PermissionedDomain entry] | {% amendment-disclaimer name="PermissionedDomains" compact=true /%} | Send a [PermissionedDomainDelete transaction][] to delete the domain. |
| [RippleState][RippleState entry] | (Core protocol) | You can only remove the entry if the counterparty's settings are entirely default. If they are, you can remove it by getting the balance to 0 and setting your own settings to the default with a [TrustSet transaction][]. In the common case, the holder can remove the entry but the issuer cannot. |
| [MPToken][MPToken entry] | {% amendment-disclaimer name="MPTokensV1" compact=true /%} | If you are the holder of the MPT, reduce your balance to 0 (for example, using a payment), then send an [MPTokenAuthorize transaction][] with the `tfMPTUnauthorize` flag. If you are the issuer of the MPT, you can't remove the entry. |
| [MPTokenIssuance][MPTokenIssuance entry] | {% amendment-disclaimer name="MPTokensV1" compact=true /%} | Send an [MPTokenIssuanceDestroy transaction][]. You can only do this if there are no holders of the MPT. |
| [NFTokenPage][NFTokenPage entry] | {% amendment-disclaimer name="NonFungibleTokensV1_1" compact=true /%} | Send [NFTokenBurn transactions][] to burn, or [NFTokenCreateOffer transactions][] to sell or transfer, each NFT you hold. |
| [Vault][Vault entry] | {% amendment-disclaimer name="SingleAssetVault" compact=true /%} | Send a [VaultDelete transaction][] to delete the vault. You can only do this if the vault is empty. |
| [XChainOwnedClaimID][XChainOwnedClaimID entry] | {% amendment-disclaimer name="XChainBridge" compact=true /%} | Send an [XChainClaim transaction][] to complete the cross-chain transfer. |
| [XChainOwned<br>CreateAccountClaimID][XChainOwnedCreateAccountClaimID entry] | {% amendment-disclaimer name="XChainBridge" compact=true /%} | Send enough attestations ([XChainAddAccountCreateAttestation transactions][]) to create the new account. |
## Cost of Deleting

View File

@@ -45,9 +45,8 @@ Clawback is disabled by default. To use clawback, you must send an [AccountSet t
| Field | JSON Type | [Internal Type][] | Required | Description |
|:----------|:---------------------|:------------------|:---------|:------------------|
| `Account` | String - [Address][] | AccountID | Yes | The issuer of the asset being clawed back. Only the issuer can submit this transaction. |
| `Asset` | Object | Issue | Yes | Specifies the asset that the issuer wants to claw back from the AMM pool. The asset can be XRP, a token, or an MPT (see: [Specifying Without Amounts][]). The `issuer` field must match with `Account`. |
| `Asset2` | Object | Issue | Yes | Specifies the other asset in the AMM's pool. The asset can be XRP, a token, or an MPT (see: [Specifying Without Amounts][]). |
| `Asset` | Object | Issue | Yes | The asset to claw back, which can be a trust line token or MPT (see: [Specifying Without Amounts][]). The issuer must be the sender of this transaction. |
| `Asset2` | Object | Issue | Yes | The other asset of the AMM pool to claw back from. The asset can be XRP, a trust line token, or an MPT (see: [Specifying Without Amounts][]). |
| `Amount` | [Currency Amount][] | Amount | No | The maximum amount to claw back from the AMM account. The `currency` and `issuer` subfields should match the `Asset` subfields. If this field isn't specified, or the `value` subfield exceeds the holder's available tokens in the AMM, all of the holder's tokens are clawed back. |
| `Holder` | String - [Address][] | AccountID | Yes | The account holding the asset to be clawed back. |

View File

@@ -0,0 +1,240 @@
---
seo:
description: Delete an account, sending its remaining XRP to another account.
labels:
- Accounts
---
# Delete an Account
This tutorial shows how to delete an [account](../../../concepts/accounts/index.md) from the XRP Ledger, including checking that it meets the [requirements for deletion](../../../concepts/accounts/deleting-accounts.md).
## Goals
By following this tutorial, you should learn how to:
- Check if an account can be deleted.
- Delete an account.
## Prerequisites
To complete this tutorial, you should:
- Have a basic understanding of the XRP Ledger.
- Have an XRP Ledger [client library](../../../references/client-libraries.md), such as **xrpl.js**, installed.
- Have an XRP Ledger Testnet account to delete. If you create a new account as part of the tutorial, you must wait about 15 minutes for it to become eligible for deletion.
- Know an address where you want to send the deleted account's remaining XRP. For this tutorial, you can use the address `rJjHYTCPpNA3qAM8ZpCDtip3a8xg7B8PFo` to return funds to the Testnet faucet.
## Steps
### 1. Install dependencies
{% tabs %}
{% tab label="JavaScript" %}
From the code sample folder, use `npm` to install dependencies:
```sh
npm i
```
{% /tab %}
{% tab label="Python" %}
From the code sample folder, set up a virtual environment and use `pip` to install dependencies:
```sh
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```
{% /tab %}
{% /tabs %}
### 2. Connect and get accounts
To get started, import the client library and instantiate an API client. To delete an account, you need the address of an account to receive the deleted account's remaining XRP.
{% tabs %}
{% tab label="JavaScript" %}
The sample code also imports `dotenv` so that it can load environment variables from a `.env` file.
{% code-snippet file="/_code-samples/delete-account/js/delete-account.js" language="js" before="// Load the account to delete" /%}
{% /tab %}
{% tab label="Python" %}
The sample code also imports `python-dotenv` so that it can load environment variables from a `.env` file.
{% code-snippet file="/_code-samples/delete-account/py/delete-account.py" language="py" before="# Load the account to delete" /%}
{% /tab %}
{% /tabs %}
You need to instantiate a wallet instance for the account you want to delete. Since you can only delete an account that is at least ~15 minutes old, the sample code loads a seed value from a `.env` file. If you don't have an account seed defined in the `.env` file, you can get a new account from the faucet, but it won't be possible to delete it right away.
{% tabs %}
{% tab label="JavaScript" %}
{% code-snippet file="/_code-samples/delete-account/js/delete-account.js" language="js" from="// Load the account to delete" before="// Check account info" /%}
{% /tab %}
{% tab label="Python" %}
{% code-snippet file="/_code-samples/delete-account/py/delete-account.py" language="py" from="# Load the account to delete" before="# Check account info" /%}
{% /tab %}
{% /tabs %}
### 3. Check to see if the account can be deleted
Before deleting an account, you should check that it meets the requirements for deletion.
#### 3.1. Get account info
The first step to checking if an account can be deleted is to get its account info as of the latest validated ledger.
{% tabs %}
{% tab label="JavaScript" %}
{% code-snippet file="/_code-samples/delete-account/js/delete-account.js" language="js" from="// Check account info" before="// Check if sequence number is too high" /%}
{% /tab %}
{% tab label="Python" %}
{% code-snippet file="/_code-samples/delete-account/py/delete-account.py" language="py" from="# Check account info" before="# Check if sequence number is too high" /%}
{% /tab %}
{% /tabs %}
#### 3.2. Check sequence number
Check that the account's current sequence number, in the `Sequence` field of the account data, is low enough compared with the latest validated ledger index. For the account to be deletable, its sequence number plus 255 must be lower than or equal to the ledger index.
{% tabs %}
{% tab label="JavaScript" %}
{% code-snippet file="/_code-samples/delete-account/js/delete-account.js" language="js" from="// Check if sequence number is too high" before="// Check if owner count is too high" /%}
{% /tab %}
{% tab label="Python" %}
{% code-snippet file="/_code-samples/delete-account/py/delete-account.py" language="py" from="# Check if sequence number is too high" before="# Check if owner count is too high" /%}
{% /tab %}
{% /tabs %}
#### 3.3. Check owner count
Check the `OwnerCount` field of the account data to see if the account owns too many other ledger entries. For an account to be deletable, it must own 1000 or fewer entries (of any type) in the ledger.
{% tabs %}
{% tab label="JavaScript" %}
{% code-snippet file="/_code-samples/delete-account/js/delete-account.js" language="js" from="// Check if owner count is too high" before="// Check if XRP balance is high enough" /%}
{% /tab %}
{% tab label="Python" %}
{% code-snippet file="/_code-samples/delete-account/py/delete-account.py" language="py" from="# Check if owner count is too high" before="# Check if XRP balance is high enough" /%}
{% /tab %}
{% /tabs %}
#### 3.4. Check XRP balance
Deleting an account requires a special [transaction cost][] equal to the incremental owner reserve, so an account can't be deleted if its current XRP balance is less than that. To check if an account has enough XRP, use the [server_state method][] to look up the current incremental reserve and compare with the account's XRP balance in the `Balance` field of the account data.
{% admonition type="warning" name="Caution" %}The [server_info method][] returns reserve values as decimal XRP, whereas [server_state][server_state method] returns drops of XRP. An account's `Balance` field is in drops of XRP. Be sure to compare equivalent units! (1 XRP = 1 million drops){% /admonition %}
{% tabs %}
{% tab label="JavaScript" %}
{% code-snippet file="/_code-samples/delete-account/js/delete-account.js" language="js" from="// Check if XRP balance is high enough" before="// Check if FirstNFTSequence is too high" /%}
{% /tab %}
{% tab label="Python" %}
{% code-snippet file="/_code-samples/delete-account/py/delete-account.py" language="py" from="# Check if XRP balance is high enough" before="# Check if FirstNFTSequence is too high" /%}
{% /tab %}
{% /tabs %}
#### 3.5. Check NFT sequence number
Check the `FirstNFTokenSequence` and `MintedNFTokens` fields of the account. (If either field is absent, you can treat its value as `0` for this purpose.) For the account to be deletable, the sum of these two numbers plus 255 must be lower than or equal to the current ledger index.
{% tabs %}
{% tab label="JavaScript" %}
{% code-snippet file="/_code-samples/delete-account/js/delete-account.js" language="js" from="// Check if FirstNFTSequence is too high" before="// Check that all issued NFTs have been burned" /%}
{% /tab %}
{% tab label="Python" %}
{% code-snippet file="/_code-samples/delete-account/py/delete-account.py" language="py" from="# Check if FirstNFTSequence is too high" before="# Check that all issued NFTs have been burned" /%}
{% /tab %}
{% /tabs %}
#### 3.6. Check that all issued NFTs have been burned
If the account has issued any NFTs that are still present in the ledger, the account cannot be deleted. You can check to see if any exist by comparing the `MintedNFTokens` field and `BurnedNFTokens` fields of the account. (In both cases, if the field is omitted, treat its value as `0`.) If the `MintedNFTokens` value is larger, the account has issued at least one NFT that has not been burned yet.
{% tabs %}
{% tab label="JavaScript" %}
{% code-snippet file="/_code-samples/delete-account/js/delete-account.js" language="js" from="// Check that all issued NFTs have been burned" before="// Stop if any problems were found" /%}
{% /tab %}
{% tab label="Python" %}
{% code-snippet file="/_code-samples/delete-account/py/delete-account.py" language="py" from="# Check that all issued NFTs have been burned" before="# Stop if any problems were found" /%}
{% /tab %}
{% /tabs %}
#### 3.7. Stop if the account can't be deleted
If any of the previous checks failed, you can't delete the account. Resolving the problems varies by type:
- If the account sequence or NFT sequence number is too low, wait for the ledger index to advance automatically and try again later. About 15 minutes should be enough.
- If the account owns too many objects, or has issued NFTs outstanding, remove the offending objects.
- If the account does not have enough XRP, you can send XRP to it so that it can pay the deletion cost, but of course in this case the account does not have enough XRP for you to recover any by deleting it. You can also wait and try again if the network [votes to lower the reserve requirements](../../../concepts/consensus-protocol/fee-voting.md), which would also lower the cost to delete an account.
The sample code does not try to handle these problems, and quits if any problems were found:
{% tabs %}
{% tab label="JavaScript" %}
{% code-snippet file="/_code-samples/delete-account/js/delete-account.js" language="js" from="// Stop if any problems were found" before="// Check for deletion blockers" /%}
{% /tab %}
{% tab label="Python" %}
{% code-snippet file="/_code-samples/delete-account/py/delete-account.py" language="py" from="# Stop if any problems were found" before="# Check for deletion blockers" /%}
{% /tab %}
{% /tabs %}
### 4. Check for deletion blockers and remove them if possible
Some types of ledger entries can block an account from being deleted. You can check for these types of entries using the [account_objects method][] with the `"deletion_blockers_only": true` parameter.
{% tabs %}
{% tab label="JavaScript" %}
{% code-snippet file="/_code-samples/delete-account/js/delete-account.js" language="js" from="// Check for deletion blockers" before="// Delete the account" /%}
{% /tab %}
{% tab label="Python" %}
{% code-snippet file="/_code-samples/delete-account/py/delete-account.py" language="py" from="# Check for deletion blockers" before="# Delete the account" /%}
{% /tab %}
{% /tabs %}
If the account has deletion blockers, you may or may not be able to remove them by sending other transactions, depending on the ledger entry. For example, if one of the blockers is a `RippleState` entry, you may be able to remove it by reducing your balance to zero through payments or offers and using a [TrustSet transaction][] to return your settings to the default state. Since there are many possibilities, the sample code does not show how to remove deletion blockers.
### 5. Delete the account
If all the checks passed, send an [AccountDelete transaction][] to delete the account. Since this transaction type requires a much higher [transaction cost][] than normal, it's a good idea to submit the transaction with the "fail hard" setting enabled. This can save you from paying the transaction cost if the transaction was going to fail with a [`tec` result code](../../../references/protocol/transactions/transaction-results/tec-codes.md). (Fail hard stops the server from relaying the transaction to the network if the transaction provisionally fails, which catches common errors before the transaction can achieve a consensus.)
{% tabs %}
{% tab label="JavaScript" %}
{% code-snippet file="/_code-samples/delete-account/js/delete-account.js" language="js" from="// Delete the account" before="// Check result of the AccountDelete transaction" /%}
If the transaction is successful, you can use [getBalanceChanges(...)](https://js.xrpl.org/functions/getBalanceChanges.html) to check the metadata and see how much XRP was delivered from the deleted account to the destination account.
{% code-snippet file="/_code-samples/delete-account/js/delete-account.js" language="js" from="// Check result of the AccountDelete transaction" /%}
{% /tab %}
{% tab label="Python" %}
{% code-snippet file="/_code-samples/delete-account/py/delete-account.py" language="py" from="# Delete the account" before="# Check result of the AccountDelete transaction" /%}
If the transaction is successful, you can use [get_balance_changes(...)](https://xrpl-py.readthedocs.io/en/stable/source/xrpl.utils.html#xrpl.utils.get_balance_changes) to check the metadata and see how much XRP was delivered from the deleted account to the destination account.
{% code-snippet file="/_code-samples/delete-account/py/delete-account.py" language="py" from="# Check result of the AccountDelete transaction" /%}
{% /tab %}
{% /tabs %}
## See Also
- **Concepts:**
- [Deleting Accounts](../../../concepts/accounts/deleting-accounts.md)
- [Transaction Cost](../../../concepts/transactions/transaction-cost.md)
- **References:**
- [AccountDelete transaction][]
- [account_info method][]
- [account_objects method][]
- [server_state method][]
{% raw-partial file="/docs/_snippets/common-links.md" /%}

View File

@@ -31,6 +31,7 @@ To complete this tutorial, you should:
- Have an XRP Ledger client library set up in your development environment. This page provides examples for the following:
- **JavaScript** with the [xrpl.js library][]. See [Get Started Using JavaScript][] for setup steps.
- **Python** with the [xrpl-py library][]. See [Get Started Using Python][] for setup steps.
- **Go** with the [xrpl-go library][]. See [Get Started Using Go][] for setup steps.
## Source Code
@@ -57,6 +58,13 @@ source .venv/bin/activate
pip install -r requirements.txt
```
{% /tab %}
{% tab label="Go" %}
From the code sample folder, use `go` to install dependencies.
```bash
go mod tidy
```
{% /tab %}
{% /tabs %}
### 2. Set up client and accounts
@@ -77,6 +85,13 @@ To get started, import the necessary libraries and instantiate a client to conne
{% code-snippet file="/_code-samples/lending-protocol/py/cover_clawback.py" language="py" before="# This step checks" /%}
{% /tab %}
{% tab label="Go" %}
- `xrpl-go`: Used for XRPL client connection, transaction submission, and wallet handling.
- `encoding/json` and `fmt`: Used for formatting and printing results to the console.
- `os` and `os/exec`: Used to run tutorial set up scripts.
{% code-snippet file="/_code-samples/lending-protocol/go/cover-clawback/main.go" language="go" before="// Check for setup data" /%}
{% /tab %}
{% /tabs %}
Next, load the loan broker account, MPT issuer account, loan broker ID, and MPT ID.
@@ -92,6 +107,11 @@ This example uses preconfigured accounts, MPTs, and loan broker data from the `l
This example uses preconfigured accounts, MPTs, and loan broker data from the `lending_setup.py` script, but you can replace `loan_broker`, `mpt_issuer`, `loan_broker_id`, and `mpt_id` with your own values.
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-clawback/main.go" language="go" from="// Check for setup data" before="// Check cover available" /%}
This example uses preconfigured accounts, MPTs, and loan broker data from the `lending-setup` script, but you can replace `loanBrokerWallet`, `mptIssuerWallet`, `loanBrokerID`, and `mptID` with your own values.
{% /tab %}
{% /tabs %}
### 3. Check initial cover available
@@ -105,6 +125,9 @@ Check the initial cover (first-loss capital) available using the [ledger_entry m
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/cover_clawback.py" language="py" from="# Check cover available" before="# Prepare LoanBrokerCoverDeposit" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-clawback/main.go" language="go" from="// Check cover available" before="// Prepare LoanBrokerCoverDeposit" /%}
{% /tab %}
{% /tabs %}
If the `CoverAvailable` field is missing, it means no first-loss capital has been deposited.
@@ -124,6 +147,11 @@ The `Amount` field specifies the MPT and amount to deposit as first-loss capital
The `amount` field specifies the MPT and amount to deposit as first-loss capital.
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-clawback/main.go" language="go" from="// Prepare LoanBrokerCoverDeposit" before="// Sign, submit, and wait for deposit validation" /%}
The `Amount` field specifies the MPT and amount to deposit as first-loss capital.
{% /tab %}
{% /tabs %}
If the transaction succeeds, the amount is deposited and held in the pseudo-account associated with the `LoanBroker` entry.
@@ -139,6 +167,9 @@ Sign and submit the `LoanBrokerCoverDeposit` transaction to the XRP Ledger.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/cover_clawback.py" language="py" from="# Sign, submit, and wait for deposit validation" before="# Extract updated cover available" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-clawback/main.go" language="go" from="// Sign, submit, and wait for deposit validation" before="// Extract updated cover available" /%}
{% /tab %}
{% /tabs %}
Verify that the transaction succeeded by checking for a `tesSUCCESS` result code.
@@ -154,6 +185,9 @@ Retrieve the cover available from the transaction result by checking the `LoanBr
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/cover_clawback.py" language="py" from="# Extract updated cover available" before="# Verify issuer of cover asset" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-clawback/main.go" language="go" from="// Extract updated cover available" before="// Verify issuer of cover asset" /%}
{% /tab %}
{% /tabs %}
### 7. Verify the asset issuer
@@ -167,6 +201,9 @@ Before executing a clawback, verify that the account submitting the transaction
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/cover_clawback.py" language="py" from="# Verify issuer of cover asset" before="# Prepare LoanBrokerCoverClawback" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-clawback/main.go" language="go" from="// Verify issuer of cover asset" before="// Prepare LoanBrokerCoverClawback" /%}
{% /tab %}
{% /tabs %}
Clawback functionality is disabled by default. In the case of MPTs, the `tfMPTCanClawback` flag must be enabled when the [MPTokenIssuanceCreate transaction][] is submitted. This tutorial uses an MPT that is already configured for clawback.
@@ -182,6 +219,9 @@ Create the [LoanBrokerCoverClawback transaction][] object.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/cover_clawback.py" language="py" from="# Prepare LoanBrokerCoverClawback" before="# Sign, submit, and wait for clawback validation" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-clawback/main.go" language="go" from="// Prepare LoanBrokerCoverClawback" before="// Sign, submit, and wait for clawback validation" /%}
{% /tab %}
{% /tabs %}
In this example we claw back the entire amount, but you can specify any amount so long as it doesn't exceed the available cover or reduce the cover below the minimum required by the `LoanBroker`.
@@ -197,6 +237,9 @@ Sign and submit the `LoanBrokerCoverClawback` transaction to the XRP Ledger.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/cover_clawback.py" language="py" from="# Sign, submit, and wait for clawback validation" before="# Extract final cover available" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-clawback/main.go" language="go" from="// Sign, submit, and wait for clawback validation" before="// Extract final cover available" /%}
{% /tab %}
{% /tabs %}
Verify that the transaction succeeded by checking for a `tesSUCCESS` result code.
@@ -212,6 +255,9 @@ Retrieve the final cover available from the transaction result.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/cover_clawback.py" language="py" from="# Extract final cover available" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-clawback/main.go" language="go" from="// Extract final cover available" /%}
{% /tab %}
{% /tabs %}
## See Also

View File

@@ -30,6 +30,7 @@ To complete this tutorial, you should:
- Have an XRP Ledger client library set up in your development environment. This page provides examples for the following:
- **JavaScript** with the [xrpl.js library][]. See [Get Started Using JavaScript][] for setup steps.
- **Python** with the [xrpl-py library][]. See [Get Started Using Python][] for setup steps.
- **Go** with the [xrpl-go library][]. See [Get Started Using Go][] for setup steps.
## Source Code
@@ -56,6 +57,13 @@ source .venv/bin/activate
pip install -r requirements.txt
```
{% /tab %}
{% tab label="Go" %}
From the code sample folder, use `go` to install dependencies.
```bash
go mod tidy
```
{% /tab %}
{% /tabs %}
### 2. Set up client and accounts
@@ -76,6 +84,13 @@ To get started, import the necessary libraries and instantiate a client to conne
{% code-snippet file="/_code-samples/lending-protocol/py/create_loan_broker.py" language="py" before="# This step checks" /%}
{% /tab %}
{% tab label="Go" %}
- `xrpl-go`: Used for XRPL client connection, transaction submission, and wallet handling.
- `encoding/json` and `fmt`: Used for formatting and printing results to the console.
- `os` and `os/exec`: Used to run tutorial set up scripts.
{% code-snippet file="/_code-samples/lending-protocol/go/create-loan-broker/main.go" language="go" before="// Check for setup data" /%}
{% /tab %}
{% /tabs %}
Next, load the vault owner account and vault ID. The vault owner will also be the loan broker.
@@ -91,6 +106,11 @@ This example uses preconfigured accounts and vault data from the `lendingSetup.j
This example uses preconfigured accounts and vault data from the `lending_setup.py` script, but you can replace `loan_broker` and `vault_id` with your own values.
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/create-loan-broker/main.go" language="go" from="// Check for setup data" before="// Prepare LoanBrokerSet" /%}
This example uses preconfigured accounts and vault data from the `lending-setup` script, but you can replace `loanBrokerWallet` and `vaultID` with your own values.
{% /tab %}
{% /tabs %}
### 3. Prepare LoanBrokerSet transaction
@@ -104,6 +124,9 @@ Create the [LoanBrokerSet transaction][] object.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/create_loan_broker.py" language="py" from="# Prepare LoanBrokerSet" before="# Submit, sign" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/create-loan-broker/main.go" language="go" from="// Prepare LoanBrokerSet" before="// Submit, sign" /%}
{% /tab %}
{% /tabs %}
The management fee rate is set in 1/10th basis points. A value of `1000` equals 1% (100 basis points).
@@ -119,6 +142,9 @@ Sign and submit the `LoanBrokerSet` transaction to the XRP Ledger.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/create_loan_broker.py" language="py" from="# Submit, sign" before="# Extract loan broker" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/create-loan-broker/main.go" language="go" from="// Submit, sign" before="// Extract loan broker" /%}
{% /tab %}
{% /tabs %}
Verify that the transaction succeeded by checking for a `tesSUCCESS` result code.
@@ -134,6 +160,9 @@ Retrieve the loan broker's information from the transaction result by checking f
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/create_loan_broker.py" language="py" from="# Extract loan broker" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/create-loan-broker/main.go" language="go" from="// Extract loan broker" /%}
{% /tab %}
{% /tabs %}
The loan broker pseudo-account is a special account that holds first-loss capital.

View File

@@ -33,6 +33,7 @@ To complete this tutorial, you should:
- Have an XRP Ledger client library set up in your development environment. This page provides examples for the following:
- **JavaScript** with the [xrpl.js library][]. See [Get Started Using JavaScript][] for setup steps.
- **Python** with the [xrpl-py library][]. See [Get Started Using Python][] for setup steps.
- **Go** with the [xrpl-go library][]. See [Get Started Using Go][] for setup steps.
## Source Code
@@ -59,6 +60,13 @@ source .venv/bin/activate
pip install -r requirements.txt
```
{% /tab %}
{% tab label="Go" %}
From the code sample folder, use `go` to install dependencies.
```bash
go mod tidy
```
{% /tab %}
{% /tabs %}
### 2. Set up client and accounts
@@ -79,6 +87,13 @@ To get started, import the necessary libraries and instantiate a client to conne
{% code-snippet file="/_code-samples/lending-protocol/py/create_loan.py" language="py" before="# This step checks" /%}
{% /tab %}
{% tab label="Go" %}
- `xrpl-go`: Used for XRPL client connection, transaction submission, and wallet handling.
- `encoding/json` and `fmt`: Used for formatting and printing results to the console.
- `os` and `os/exec`: Used to run tutorial set up scripts.
{% code-snippet file="/_code-samples/lending-protocol/go/create-loan/main.go" language="go" before="// Check for setup data" /%}
{% /tab %}
{% /tabs %}
Next, load the loan broker account, borrower account, and loan broker ID.
@@ -94,6 +109,11 @@ This example uses preconfigured accounts and loan broker data from the `lendingS
This example uses preconfigured accounts and loan broker data from the `lending_setup.py` script, but you can replace `loan_broker`, `borrower`, and `loan_broker_id` with your own values.
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/create-loan/main.go" language="go" from="// Check for setup data" before="// Prepare LoanSet" /%}
This example uses preconfigured accounts and loan broker data from the `lending-setup` script, but you can replace `loanBrokerWallet`, `borrowerWallet`, and `loanBrokerID` with your own values.
{% /tab %}
{% /tabs %}
### 3. Prepare LoanSet transaction
@@ -129,6 +149,20 @@ The loan terms include:
- `loan_origination_fee`: A one-time fee charged when the loan is created, paid in the borrowed asset.
- `loan_service_fee`: A fee charged with every loan payment, paid in the borrowed asset.
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/create-loan/main.go" language="go" from="// Prepare LoanSet" before="// Loan broker signs first" /%}
The `Account` field is the loan broker, and the `Counterparty` field is the borrower. These fields can be swapped, but determine the signing order: the `Account` signs first, and the `Counterparty` signs second.
The loan terms include:
- `PrincipalRequested`: The amount of an asset requested by the borrower. You don't have to specify the type of asset in this field.
- `InterestRate`: The annualized interest rate in 1/10th basis points (500 = 0.5%).
- `PaymentTotal`: The number of payments to be made.
- `PaymentInterval`: The number of seconds between payments (2592000 = 30 days).
- `GracePeriod`: The number of seconds after a missed payment before the loan can be defaulted (604800 = 7 days).
- `LoanOriginationFee`: A one-time fee charged when the loan is created, paid in the borrowed asset.
- `LoanServiceFee`: A fee charged with every loan payment, paid in the borrowed asset.
{% /tab %}
{% /tabs %}
### 4. Add loan broker signature
@@ -142,6 +176,9 @@ The loan broker (the `Account`) signs the transaction first, adding their `TxnSi
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/create_loan.py" language="py" from="# Loan broker signs first" before="# Borrower signs second" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/create-loan/main.go" language="go" from="// Loan broker signs first" before="// Borrower signs second" /%}
{% /tab %}
{% /tabs %}
### 5. Add borrower signature
@@ -155,6 +192,9 @@ The borrower (the `Counterparty`) signs the transaction second. Their `TxnSignat
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/create_loan.py" language="py" from="# Borrower signs second" before="# Submit and wait" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/create-loan/main.go" language="go" from="// Borrower signs second" before="// Submit and wait" /%}
{% /tab %}
{% /tabs %}
### 6. Submit LoanSet transaction
@@ -168,6 +208,9 @@ Submit the fully signed `LoanSet` transaction to the XRP Ledger.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/create_loan.py" language="py" from="# Submit and wait" before="# Extract loan information" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/create-loan/main.go" language="go" from="// Submit and wait" before="// Extract loan information" /%}
{% /tab %}
{% /tabs %}
Verify that the transaction succeeded by checking for a `tesSUCCESS` result code.
@@ -183,6 +226,9 @@ Retrieve the loan's information from the transaction result by checking for the
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/create_loan.py" language="py" from="# Extract loan information" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/create-loan/main.go" language="go" from="// Extract loan information" /%}
{% /tab %}
{% /tabs %}
## See Also

View File

@@ -32,6 +32,7 @@ To complete this tutorial, you should:
- Have an XRP Ledger client library set up in your development environment. This page provides examples for the following:
- **JavaScript** with the [xrpl.js library][]. See [Get Started Using JavaScript][] for setup steps.
- **Python** with the [xrpl-py library][]. See [Get Started Using Python][] for setup steps.
- **Go** with the [xrpl-go library][]. See [Get Started Using Go][] for setup steps.
## Source Code
@@ -58,6 +59,13 @@ source .venv/bin/activate
pip install -r requirements.txt
```
{% /tab %}
{% tab label="Go" %}
From the code sample folder, use `go` to install dependencies.
```bash
go mod tidy
```
{% /tab %}
{% /tabs %}
### 2. Set up client and accounts
@@ -78,6 +86,13 @@ To get started, import the necessary libraries and instantiate a client to conne
{% code-snippet file="/_code-samples/lending-protocol/py/cover_deposit_and_withdraw.py" language="py" before="# This step checks" /%}
{% /tab %}
{% tab label="Go" %}
- `xrpl-go`: Used for XRPL client connection, transaction submission, and wallet handling.
- `encoding/json` and `fmt`: Used for formatting and printing results to the console.
- `os` and `os/exec`: Used to run tutorial set up scripts.
{% code-snippet file="/_code-samples/lending-protocol/go/cover-deposit-and-withdraw/main.go" language="go" before="// Check for setup data" /%}
{% /tab %}
{% /tabs %}
Next, load the loan broker account, loan broker ID, and MPT issuance ID.
@@ -93,6 +108,11 @@ This example uses preconfigured accounts and loan broker data from the `lendingS
This example uses preconfigured accounts and loan broker data from the `lending_setup.py` script, but you can replace `loan_broker`, `loan_broker_id`, and `mpt_id` with your own values.
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-deposit-and-withdraw/main.go" language="go" from="// Check for setup data" before="// Prepare LoanBrokerCoverDeposit" /%}
This example uses preconfigured accounts and loan broker data from the `lending-setup` script, but you can replace `loanBrokerWallet`, `loanBrokerID`, and `mptID` with your own values.
{% /tab %}
{% /tabs %}
### 3. Prepare LoanBrokerCoverDeposit transaction
@@ -110,6 +130,11 @@ The `Amount` field specifies the MPT and amount to deposit as first-loss capital
The `amount` field specifies the MPT and amount to deposit as first-loss capital.
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-deposit-and-withdraw/main.go" language="go" from="// Prepare LoanBrokerCoverDeposit" before="// Sign, submit, and wait for deposit" /%}
The `Amount` field specifies the MPT and amount to deposit as first-loss capital.
{% /tab %}
{% /tabs %}
If the transaction succeeds, the amount is deposited and held in the pseudo-account associated with the `LoanBroker` entry.
@@ -125,6 +150,9 @@ Sign and submit the `LoanBrokerCoverDeposit` transaction to the XRP Ledger.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/cover_deposit_and_withdraw.py" language="py" from="# Sign, submit, and wait for deposit" before="# Extract cover balance" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-deposit-and-withdraw/main.go" language="go" from="// Sign, submit, and wait for deposit" before="// Extract cover balance" /%}
{% /tab %}
{% /tabs %}
Verify that the transaction succeeded by checking for a `tesSUCCESS` result code.
@@ -140,6 +168,9 @@ Retrieve the cover balance from the transaction result by checking the `LoanBrok
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/cover_deposit_and_withdraw.py" language="py" from="# Extract cover balance" before="# Prepare LoanBrokerCoverWithdraw" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-deposit-and-withdraw/main.go" language="go" from="// Extract cover balance" before="// Prepare LoanBrokerCoverWithdraw" /%}
{% /tab %}
{% /tabs %}
The `LoanBroker` pseudo-account address is the `Account` field, and `CoverAvailable` shows the cover balance.
@@ -155,6 +186,9 @@ Create the [LoanBrokerCoverWithdraw transaction][] object.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/cover_deposit_and_withdraw.py" language="py" from="# Prepare LoanBrokerCoverWithdraw" before="# Sign, submit, and wait for withdraw" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-deposit-and-withdraw/main.go" language="go" from="// Prepare LoanBrokerCoverWithdraw" before="// Sign, submit, and wait for withdraw" /%}
{% /tab %}
{% /tabs %}
### 7. Submit LoanBrokerCoverWithdraw transaction
@@ -168,6 +202,9 @@ Sign and submit the `LoanBrokerCoverWithdraw` transaction to the XRP Ledger.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/cover_deposit_and_withdraw.py" language="py" from="# Sign, submit, and wait for withdraw" before="# Extract updated cover balance" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-deposit-and-withdraw/main.go" language="go" from="// Sign, submit, and wait for withdraw" before="// Extract updated cover balance" /%}
{% /tab %}
{% /tabs %}
Verify that the transaction succeeded by checking for a `tesSUCCESS` result code.
@@ -183,6 +220,9 @@ Retrieve the updated cover balance from the transaction result.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/cover_deposit_and_withdraw.py" language="py" from="# Extract updated cover balance" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/cover-deposit-and-withdraw/main.go" language="go" from="// Extract updated cover balance" /%}
{% /tab %}
{% /tabs %}
The `CoverAvailable` field now shows the reduced balance after the withdrawal.

View File

@@ -33,6 +33,7 @@ To complete this tutorial, you should:
- Have an XRP Ledger client library set up in your development environment. This page provides examples for the following:
- **JavaScript** with the [xrpl.js library][]. See [Get Started Using JavaScript][] for setup steps.
- **Python** with the [xrpl-py library][]. See [Get Started Using Python][] for setup steps.
- **Go** with the [xrpl-go library][]. See [Get Started Using Go][] for setup steps.
## Source Code
@@ -59,6 +60,13 @@ source .venv/bin/activate
pip install -r requirements.txt
```
{% /tab %}
{% tab label="Go" %}
From the code sample folder, use `go` to install dependencies.
```bash
go mod tidy
```
{% /tab %}
{% /tabs %}
### 2. Set up client and accounts
@@ -80,6 +88,14 @@ To get started, import the necessary libraries and instantiate a client to conne
{% code-snippet file="/_code-samples/lending-protocol/py/loan_manage.py" language="py" before="# This step checks" /%}
{% /tab %}
{% tab label="Go" %}
- `xrpl-go`: Used for XRPL client connection, transaction submission, and wallet handling.
- `encoding/json` and `fmt`: Used for formatting and printing results to the console.
- `os` and `os/exec`: Used to run tutorial set up scripts.
- `time`: Used for grace period countdown and date formatting.
{% code-snippet file="/_code-samples/lending-protocol/go/loan-manage/main.go" language="go" before="// Check for setup data" /%}
{% /tab %}
{% /tabs %}
Next, load the loan broker account and loan ID.
@@ -95,6 +111,11 @@ This example uses preconfigured accounts and loan data from the `lendingSetup.js
This example uses preconfigured accounts and loan data from the `lending_setup.py` script, but you can replace `loan_broker` and `loan_id` with your own values.
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-manage/main.go" language="go" from="// Check for setup data" before="// Check loan status" /%}
This example uses preconfigured accounts and loan data from the `lending-setup` script, but you can replace `loanBrokerWallet` and `loanID` with your own values.
{% /tab %}
{% /tabs %}
### 3. Check loan status
@@ -108,6 +129,9 @@ Check the current status of the loan using the [ledger_entry method][].
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_manage.py" language="py" from="# Check loan status" before="# Prepare LoanManage transaction to impair" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-manage/main.go" language="go" from="// Check loan status" before="// Prepare LoanManage transaction to impair" /%}
{% /tab %}
{% /tabs %}
This shows the total amount owed and the next payment due date. The [Ripple Epoch][] timestamp is converted to a readable date format.
@@ -123,6 +147,9 @@ Create the [LoanManage transaction][] with the `tfLoanImpair` flag.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_manage.py" language="py" from="# Prepare LoanManage transaction to impair" before="# Sign, submit, and wait for impairment" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-manage/main.go" language="go" from="// Prepare LoanManage transaction to impair" before="// Sign, submit, and wait for impairment" /%}
{% /tab %}
{% /tabs %}
### 5. Submit LoanManage impairment transaction
@@ -136,6 +163,9 @@ Sign and submit the `LoanManage` transaction to impair the loan.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_manage.py" language="py" from="# Sign, submit, and wait for impairment" before="# Extract loan impairment info" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-manage/main.go" language="go" from="// Sign, submit, and wait for impairment" before="// Extract loan impairment info" /%}
{% /tab %}
{% /tabs %}
Verify that the transaction succeeded by checking for a `tesSUCCESS` result code.
@@ -151,6 +181,9 @@ Retrieve the loan's grace period and updated payment due date from the transacti
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_manage.py" language="py" from="# Extract loan impairment info" before="# Countdown until loan can be defaulted" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-manage/main.go" language="go" from="// Extract loan impairment info" before="// Countdown until loan can be defaulted" /%}
{% /tab %}
{% /tabs %}
The loan can only be defaulted after the grace period expires. The example calculates when the grace period ends and displays a countdown.
@@ -166,6 +199,9 @@ This countdown displays the remaining seconds in real-time. Once the grace perio
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_manage.py" language="py" from="# Countdown until loan can be defaulted" before="# Prepare LoanManage transaction to default" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-manage/main.go" language="go" from="// Countdown until loan can be defaulted" before="// Prepare LoanManage transaction to default" /%}
{% /tab %}
{% /tabs %}
### 8. Prepare LoanManage transaction to default the loan
@@ -179,6 +215,9 @@ After the grace period expires, create a `LoanManage` transaction with the `tfLo
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_manage.py" language="py" from="# Prepare LoanManage transaction to default" before="# Sign, submit, and wait for default" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-manage/main.go" language="go" from="// Prepare LoanManage transaction to default" before="// Sign, submit, and wait for default" /%}
{% /tab %}
{% /tabs %}
### 9. Submit LoanManage default transaction
@@ -192,6 +231,9 @@ Sign and submit the `LoanManage` transaction to default the loan.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_manage.py" language="py" from="# Sign, submit, and wait for default" before="# Verify loan default status" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-manage/main.go" language="go" from="// Sign, submit, and wait for default" before="// Verify loan default status" /%}
{% /tab %}
{% /tabs %}
Verify that the transaction succeeded by checking for a `tesSUCCESS` result code.
@@ -207,6 +249,9 @@ Confirm the loan has been defaulted by checking the loan flags.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_manage.py" language="py" from="# Verify loan default status" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-manage/main.go" language="go" from="// Verify loan default status" /%}
{% /tab %}
{% /tabs %}
The loan flags are parsed to confirm the `tfLoanDefault` flag is now set.

View File

@@ -33,6 +33,7 @@ To complete this tutorial, you should:
- Have an XRP Ledger client library set up in your development environment. This page provides examples for the following:
- **JavaScript** with the [xrpl.js library][]. See [Get Started Using JavaScript][] for setup steps.
- **Python** with the [xrpl-py library][]. See [Get Started Using Python][] for setup steps.
- **Go** with the [xrpl-go library][]. See [Get Started Using Go][] for setup steps.
## Source Code
@@ -59,6 +60,13 @@ source .venv/bin/activate
pip install -r requirements.txt
```
{% /tab %}
{% tab label="Go" %}
From the code sample folder, use `go` to install dependencies.
```bash
go mod tidy
```
{% /tab %}
{% /tabs %}
### 2. Set up client and accounts
@@ -79,6 +87,14 @@ To get started, import the necessary libraries and instantiate a client to conne
{% code-snippet file="/_code-samples/lending-protocol/py/loan_pay.py" language="py" before="# This step checks" /%}
{% /tab %}
{% tab label="Go" %}
- `xrpl-go`: Used for XRPL client connection, transaction submission, and wallet handling.
- `encoding/json` and `fmt`: Used for formatting and printing results to the console.
- `math/big`: Used for calculating the total payment amount.
- `os` and `os/exec`: Used to run tutorial set up scripts.
{% code-snippet file="/_code-samples/lending-protocol/go/loan-pay/main.go" language="go" before="// Check for setup data" /%}
{% /tab %}
{% /tabs %}
Next, load the borrower account, loan ID, and MPT issuance ID.
@@ -94,6 +110,11 @@ This example uses preconfigured accounts and loan data from the `lendingSetup.js
This example uses preconfigured accounts and loan data from the `lending_setup.py` script, but you can replace `borrower`, `loan_id`, and `mpt_id` with your own values.
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-pay/main.go" language="go" from="// Check for setup data" before="// Check initial loan status" /%}
This example uses preconfigured accounts and loan data from the `lending-setup` script, but you can replace `borrowerWallet`, `loanID`, and `mptID` with your own values.
{% /tab %}
{% /tabs %}
### 3. Check loan status
@@ -107,6 +128,9 @@ Check the current status of the loan using the [ledger_entry method][].
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_pay.py" language="py" from="# Check initial loan status" before="# Prepare LoanPay transaction" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-pay/main.go" language="go" from="// Check initial loan status" before="// Prepare LoanPay transaction" /%}
{% /tab %}
{% /tabs %}
The `TotalValueOutstanding` field contains the remaining principal plus accrued interest; the `LoanServiceFee` is an additional fee charged per payment. Add these together to calculate the total payment.
@@ -126,6 +150,9 @@ Create the [LoanPay transaction][] with the total payment amount.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_pay.py" language="py" from="# Prepare LoanPay transaction" before="# Sign, submit, and wait for payment validation" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-pay/main.go" language="go" from="// Prepare LoanPay transaction" before="// Sign, submit, and wait for payment validation" /%}
{% /tab %}
{% /tabs %}
### 5. Submit LoanPay transaction
@@ -139,6 +166,9 @@ Sign and submit the `LoanPay` transaction to the XRP Ledger.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_pay.py" language="py" from="# Sign, submit, and wait for payment validation" before="# Extract updated loan info" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-pay/main.go" language="go" from="// Sign, submit, and wait for payment validation" before="// Extract updated loan info" /%}
{% /tab %}
{% /tabs %}
Verify that the transaction succeeded by checking for a `tesSUCCESS` result code.
@@ -154,6 +184,9 @@ Retrieve the loan balance from the transaction result by checking for the `Loan`
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_pay.py" language="py" from="# Extract updated loan info" before="# Prepare LoanDelete transaction" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-pay/main.go" language="go" from="// Extract updated loan info" before="// Prepare LoanDelete transaction" /%}
{% /tab %}
{% /tabs %}
If `TotalValueOutstanding` is absent from the loan metadata, the loan has been fully paid off and is ready for deletion.
@@ -169,6 +202,9 @@ Create a [LoanDelete transaction][] to remove the paid loan from the XRP Ledger.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_pay.py" language="py" from="# Prepare LoanDelete transaction" before="# Sign, submit, and wait for deletion validation" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-pay/main.go" language="go" from="// Prepare LoanDelete transaction" before="// Sign, submit, and wait for deletion validation" /%}
{% /tab %}
{% /tabs %}
Either the loan broker or the borrower can submit a `LoanDelete` transaction. In this example, the borrower deletes their own paid off loan.
@@ -184,6 +220,9 @@ Sign and submit the `LoanDelete` transaction.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_pay.py" language="py" from="# Sign, submit, and wait for deletion validation" before="# Verify loan deletion" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-pay/main.go" language="go" from="// Sign, submit, and wait for deletion validation" before="// Verify loan deletion" /%}
{% /tab %}
{% /tabs %}
Verify that the transaction succeeded by checking for a `tesSUCCESS` result code.
@@ -199,6 +238,9 @@ Confirm that the loan has been removed from the XRP Ledger.
{% tab label="Python" %}
{% code-snippet file="/_code-samples/lending-protocol/py/loan_pay.py" language="py" from="# Verify loan deletion" /%}
{% /tab %}
{% tab label="Go" %}
{% code-snippet file="/_code-samples/lending-protocol/go/loan-pay/main.go" language="go" from="// Verify loan deletion" /%}
{% /tab %}
{% /tabs %}
If the `ledger_entry` method returns an `entryNotFound` error, the loan has been successfully deleted.

View File

@@ -1,5 +1,51 @@
import { useThemeHooks } from "@redocly/theme/core/hooks"
import { Link } from "@redocly/theme/components/Link/Link"
import { useState } from "react"
type TutorialLanguagesMap = Record<string, string[]>
interface TutorialMetadataItem {
path: string
title: string
description: string
lastModified: string
category: string
}
interface Tutorial {
title: string
body?: string
path: string
// External community contribution fields (optional)
author?: { name: string; url: string }
github?: string
externalUrl?: string
}
interface TutorialSection {
id: string
title: string
description: string
tutorials: Tutorial[]
}
// External community contribution - manually curated with author/repo/demo info
interface PinnedExternalTutorial {
title: string
description: string
author: { name: string; url: string }
github: string
url?: string
}
// Pinned tutorial entry:
// - string: internal path (uses frontmatter title/description)
// - object with `path`: internal path with optional description override
// - PinnedExternalTutorial: external community contribution with author/repo/demo
type PinnedTutorial = string | { path: string; description?: string } | PinnedExternalTutorial
const MAX_WHATS_NEW = 3
const MAX_TUTORIALS_PER_SECTION = 6
export const frontmatter = {
seo: {
@@ -19,243 +65,93 @@ const langIcons: Record<string, { src: string; alt: string }> = {
xrpl: { src: "/img/logos/xrp-mark.svg", alt: "XRP Ledger" },
}
// Type for the tutorial languages map from the plugin
type TutorialLanguagesMap = Record<string, string[]>
interface Tutorial {
title: string
body?: string
path: string
icon?: string // Single language icon (for single-language tutorials)
}
interface TutorialSection {
id: string
title: string
description: string
tutorials: Tutorial[]
}
// Get Started tutorials -----------------
const getStartedTutorials: Tutorial[] = [
// Section configuration - defines display order, titles, and descriptions.
// "whats-new" and "get-started" are rendered separately; the rest are auto-populated category sections.
const sectionConfig: { id: string; title: string; description: string }[] = [
{
title: "JavaScript",
body: "Using the xrpl.js client library.",
path: "/docs/tutorials/get-started/get-started-javascript/",
icon: "javascript",
id: "whats-new",
title: "What's New",
description: "Recently added/updated tutorials to help you build on the XRP Ledger.",
},
{
title: "Python",
body: "Using xrpl.py, a pure Python library.",
path: "/docs/tutorials/get-started/get-started-python/",
icon: "python",
id: "get-started",
title: "Get Started with SDKs",
description: "These tutorials walk you through the basics of building a very simple XRP Ledger-connected application using your favorite programming language.",
},
{
title: "Go",
body: "Using xrpl-go, a pure Go library.",
path: "/docs/tutorials/get-started/get-started-go/",
icon: "go",
},
{
title: "Java",
body: "Using xrpl4j, a pure Java library.",
path: "/docs/tutorials/get-started/get-started-java/",
icon: "java",
},
{
title: "PHP",
body: "Using the XRPL_PHP client library.",
path: "/docs/tutorials/get-started/get-started-php/",
icon: "php",
},
{
title: "HTTP & WebSocket APIs",
body: "Access the XRP Ledger directly through the APIs of its core server.",
path: "/docs/tutorials/get-started/get-started-http-websocket-apis/",
icon: "http",
},
]
// Other tutorial sections -----------------
// Languages are auto-detected from the markdown files by the tutorial-languages plugin.
// Only specify `icon` for single-language tutorials without tabs.
const sections: TutorialSection[] = [
{
id: "tokens",
title: "Tokens",
description: "Create and manage tokens on the XRP Ledger.",
tutorials: [
{
title: "Issue a Multi-Purpose Token",
body: "Issue new tokens using the v2 fungible token standard.",
path: "/docs/tutorials/tokens/mpts/issue-a-multi-purpose-token/",
},
{
title: "Issue a Fungible Token",
body: "Issue new tokens using the v1 fungible token standard.",
path: "/docs/tutorials/tokens/fungible-tokens/issue-a-fungible-token/",
},
{
title: "Mint and Burn NFTs Using JavaScript",
body: "Create new NFTs, retrieve existing tokens, and burn the ones you no longer need.",
path: "/docs/tutorials/tokens/nfts/mint-and-burn-nfts-js/",
icon: "javascript",
},
],
},
{
id: "payments",
title: "Payments",
description: "Transfer XRP and issued currencies using various payment types.",
tutorials: [
{
title: "Send XRP",
body: "Send a direct XRP payment to another account.",
path: "/docs/tutorials/payments/send-xrp/",
},
{
title: "Sending MPTs in JavaScript",
body: "Send a Multi-Purpose Token (MPT) to another account with the JavaScript SDK.",
path: "/docs/tutorials/tokens/mpts/sending-mpts-in-javascript/",
icon: "javascript",
},
{
title: "Create Trust Line and Send Currency in JavaScript",
body: "Set up trust lines and send issued currencies with the JavaScript SDK.",
path: "/docs/tutorials/payments/create-trust-line-send-currency-in-javascript/",
icon: "javascript",
},
{
title: "Create Trust Line and Send Currency in Python",
body: "Set up trust lines and send issued currencies with the Python SDK.",
path: "/docs/tutorials/payments/create-trust-line-send-currency-in-python/",
icon: "python",
},
{
title: "Send a Conditional Escrow",
body: "Send an escrow that can be released when a specific crypto-condition is fulfilled.",
path: "/docs/tutorials/payments/send-a-conditional-escrow/",
},
{
title: "Send a Timed Escrow",
body: "Send an escrow whose only condition for release is that a specific time has passed.",
path: "/docs/tutorials/payments/send-a-timed-escrow/",
},
],
},
{
id: "defi",
title: "DeFi",
description: "Trade, provide liquidity, and lend using native XRP Ledger DeFi features.",
tutorials: [
{
title: "Create an Automated Market Maker",
body: "Set up an AMM for a token pair and provide liquidity.",
path: "/docs/tutorials/defi/dex/create-an-automated-market-maker/",
},
{
title: "Trade in the Decentralized Exchange",
body: "Buy and sell tokens in the Decentralized Exchange (DEX).",
path: "/docs/tutorials/defi/dex/trade-in-the-decentralized-exchange/",
},
{
title: "Create a Loan Broker",
body: "Set up a loan broker to create and manage loans.",
path: "/docs/tutorials/defi/lending/use-the-lending-protocol/create-a-loan-broker/",
},
{
title: "Create a Loan",
body: "Create a loan on the XRP Ledger.",
path: "/docs/tutorials/defi/lending/use-the-lending-protocol/create-a-loan/",
},
{
title: "Create a Single Asset Vault",
body: "Create a single asset vault on the XRP Ledger.",
path: "/docs/tutorials/defi/lending/use-single-asset-vaults/create-a-single-asset-vault/",
},
{
title: "Deposit into a Vault",
body: "Deposit assets into a vault and receive shares.",
path: "/docs/tutorials/defi/lending/use-single-asset-vaults/deposit-into-a-vault/",
},
],
},
{
id: "best-practices",
title: "Best Practices",
description: "Learn recommended patterns for building reliable, secure applications on the XRP Ledger.",
tutorials: [
{
title: "API Usage",
body: "Best practices for using XRP Ledger APIs.",
path: "/docs/tutorials/best-practices/api-usage/",
},
{
title: "Use Tickets",
body: "Use tickets to send transactions out of the normal order.",
path: "/docs/tutorials/best-practices/transaction-sending/use-tickets/",
},
{
title: "Send a Single Account Batch Transaction",
body: "Group multiple transactions together and execute them as a single atomic operation.",
path: "/docs/tutorials/best-practices/transaction-sending/send-a-single-account-batch-transaction/",
},
{
title: "Assign a Regular Key Pair",
body: "Assign a regular key pair for signing transactions.",
path: "/docs/tutorials/best-practices/key-management/assign-a-regular-key-pair/",
},
{
title: "Set Up Multi-Signing",
body: "Configure multi-signing for enhanced security.",
path: "/docs/tutorials/best-practices/key-management/set-up-multi-signing/",
},
{
title: "Send a Multi-Signed Transaction",
body: "Send a transaction with multiple signatures.",
path: "/docs/tutorials/best-practices/key-management/send-a-multi-signed-transaction/",
},
],
},
{
id: "sample-apps",
title: "Sample Apps",
description: "Build complete, end-to-end applications like wallets and credential services.",
tutorials: [
{
title: "Build a Browser Wallet in JavaScript",
body: "Build a browser wallet for the XRP Ledger using JavaScript and various libraries.",
path: "/docs/tutorials/sample-apps/build-a-browser-wallet-in-javascript/",
icon: "javascript",
},
{
title: "Build a Desktop Wallet in JavaScript",
body: "Build a desktop wallet for the XRP Ledger using JavaScript, the Electron Framework, and various libraries.",
path: "/docs/tutorials/sample-apps/build-a-desktop-wallet-in-javascript/",
icon: "javascript",
},
{
title: "Build a Desktop Wallet in Python",
body: "Build a desktop wallet for the XRP Ledger using Python and various libraries.",
path: "/docs/tutorials/sample-apps/build-a-desktop-wallet-in-python/",
icon: "python",
},
{
title: "Credential Issuing Service in JavaScript",
body: "Build a credential issuing service using the JavaScript SDK.",
path: "/docs/tutorials/sample-apps/credential-issuing-service-in-javascript/",
icon: "javascript",
},
{
title: "Credential Issuing Service in Python",
body: "Build a credential issuing service using the Python SDK.",
path: "/docs/tutorials/sample-apps/credential-issuing-service-in-python/",
icon: "python",
},
],
},
]
// Pinned tutorials - these always appear in their designated sections.
// Use an object with `description` to override the frontmatter description.
// Use an object with `github` for external community contributions.
const pinnedTutorials: Record<string, PinnedTutorial[]> = {
"get-started": [
{ path: "/docs/tutorials/get-started/get-started-javascript/", description: "Using the xrpl.js client library." },
{ path: "/docs/tutorials/get-started/get-started-python/", description: "Using xrpl.py, a pure Python library." },
{ path: "/docs/tutorials/get-started/get-started-go/", description: "Using xrpl-go, a pure Go library." },
{ path: "/docs/tutorials/get-started/get-started-java/", description: "Using xrpl4j, a pure Java library." },
{ path: "/docs/tutorials/get-started/get-started-php/", description: "Using the XRPL_PHP client library." },
{ path: "/docs/tutorials/get-started/get-started-http-websocket-apis/", description: "Access the XRP Ledger directly through the APIs of its core server." },
],
tokens: [
{ path: "/docs/tutorials/tokens/mpts/issue-a-multi-purpose-token/", description: "Issue new tokens using the v2 fungible token standard." },
{ path: "/docs/tutorials/tokens/fungible-tokens/issue-a-fungible-token/", description: "Issue new tokens using the v1 fungible token standard."},
{ path: "/docs/tutorials/tokens/nfts/mint-and-burn-nfts-js/", description: "Create new NFTs, retrieve existing tokens, and burn the ones you no longer need." },
],
payments: [
"/docs/tutorials/payments/send-xrp/",
"/docs/tutorials/tokens/mpts/sending-mpts-in-javascript/",
"/docs/tutorials/payments/create-trust-line-send-currency-in-javascript/",
"/docs/tutorials/payments/send-a-conditional-escrow/",
"/docs/tutorials/payments/send-a-timed-escrow/",
],
defi: [
"/docs/tutorials/defi/dex/create-an-automated-market-maker/",
"/docs/tutorials/defi/dex/trade-in-the-decentralized-exchange/",
"/docs/tutorials/defi/lending/use-the-lending-protocol/create-a-loan/",
"/docs/tutorials/defi/lending/use-single-asset-vaults/create-a-single-asset-vault/",
],
"best-practices": [
"/docs/tutorials/best-practices/api-usage/",
],
"sample-apps": [
{
title: "XRPL Lending Protocol Demo",
description: "A full-stack web application that demonstrates the end-to-end flow of the Lending Protocol and Single Asset Vaults.",
author: { name: "Aaditya-T", url: "https://github.com/Aaditya-T" },
github: "https://github.com/Aaditya-T/lending_test",
url: "https://lending-test-lovat.vercel.app/",
},
],
}
// ── Components ──────────────────────────────────────────────────────────────
function TutorialCard({
tutorial,
detectedLanguages,
@@ -267,12 +163,10 @@ function TutorialCard({
showFooter?: boolean
translate: (text: string) => string
}) {
// Get icons: manual icon takes priority, then auto-detected languages, then XRPL fallback
const icons = tutorial.icon && langIcons[tutorial.icon]
? [langIcons[tutorial.icon]]
: detectedLanguages && detectedLanguages.length > 0
? detectedLanguages.map((lang) => langIcons[lang]).filter(Boolean)
: [langIcons.xrpl]
// Get icons from auto-detected languages, fallback to XRPL icon
const icons = detectedLanguages && detectedLanguages.length > 0
? detectedLanguages.map((lang) => langIcons[lang]).filter(Boolean)
: [langIcons.xrpl]
return (
<Link to={tutorial.path} className="card">
@@ -292,6 +186,188 @@ function TutorialCard({
)
}
// Inline meta link used in ContributionCard
function MetaLink({ href, icon, label }: {
href: string
icon: string
label: string
}) {
return (
<a href={href} target="_blank" rel="noopener noreferrer" className="meta-link">
<i className={`fa fa-${icon}`} aria-hidden="true" />
{label}
</a>
)
}
// Community Contribution Card
function ContributionCard({
tutorial,
translate,
}: {
tutorial: Tutorial
translate: (text: string) => string
}) {
const primaryUrl = tutorial.externalUrl || tutorial.github!
const handleCardClick = (e: React.MouseEvent | React.KeyboardEvent) => {
if ((e.target as HTMLElement).closest(".card-meta-row")) return
window.open(primaryUrl, "_blank", "noopener,noreferrer")
}
return (
<div
className="card contribution-card"
onClick={handleCardClick}
onKeyDown={(e) => { if (e.key === "Enter") handleCardClick(e) }}
role="link"
tabIndex={0}
>
<div className="card-header contribution-header">
<span className="circled-logo contribution-icon">
<i className="fa fa-users" aria-hidden="true" />
</span>
<div className="card-meta-row">
{tutorial.author && (
<>
<MetaLink href={tutorial.author.url} icon="user" label={tutorial.author.name} />
<span className="meta-dot" aria-hidden="true">·</span>
</>
)}
<MetaLink href={tutorial.github!} icon="github" label={translate("GitHub")} />
</div>
</div>
<div className="card-body">
<h4 className="card-title h5">
{translate(tutorial.title)}
<span className="card-external-icon" aria-label={translate("External link")}>
<i className="fa fa-external-link" aria-hidden="true" />
</span>
</h4>
{tutorial.body && <p className="card-text">{translate(tutorial.body)}</p>}
</div>
</div>
)
}
// Reusable section block for rendering tutorial sections
function TutorialSectionBlock({
id,
title,
description,
tutorials,
tutorialLanguages,
showFooter = false,
maxTutorials,
className = "",
translate,
}: {
id: string
title: string
description: string
tutorials: Tutorial[]
tutorialLanguages: TutorialLanguagesMap
showFooter?: boolean
maxTutorials?: number
className?: string
translate: (text: string) => string
}) {
const displayTutorials = maxTutorials ? tutorials.slice(0, maxTutorials) : tutorials
return (
<section className={`container-new pt-10 pb-14 ${className}`.trim()} id={id}>
<div className="col-12 col-xl-8 p-0">
<h3 className="h4 mb-3">{translate(title)}</h3>
<p className="mb-4">{translate(description)}</p>
</div>
<div className="row tutorial-cards">
{displayTutorials.map((tutorial) => (
<div key={tutorial.path} className="col-lg-4 col-md-6 mb-5">
{tutorial.github ? (
<ContributionCard tutorial={tutorial} translate={translate} />
) : (
<TutorialCard
tutorial={tutorial}
detectedLanguages={tutorialLanguages[tutorial.path]}
showFooter={showFooter}
translate={translate}
/>
)}
</div>
))}
</div>
</section>
)
}
// Copyable URL component with click-to-copy functionality
function CopyableUrl({ url, translate }: { url: string; translate: (text: string) => string }) {
const [copied, setCopied] = useState(false)
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(url)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (err) {
console.error("Failed to copy:", err)
}
}
return (
<button
type="button"
className={`quick-ref-value-btn ${copied ? "copied" : ""}`}
onClick={handleCopy}
title={copied ? translate("Copied!") : translate("Click to copy")}
>
<code className="quick-ref-value">{url}</code>
<span className="copy-icon">{copied ? "✓" : ""}</span>
</button>
)
}
// Quick reference card showing public server URLs and faucet link
function QuickReferenceCard({ translate }: { translate: (text: string) => string }) {
return (
<div className="quick-ref-card">
<div className="quick-ref-section">
<span className="quick-ref-label">{translate("PUBLIC SERVERS")}</span>
<div className="quick-ref-group">
<span className="quick-ref-key"><strong>{translate("Mainnet")}</strong></span>
<div className="quick-ref-urls">
<span className="quick-ref-protocol">{translate("WebSocket")}</span>
<CopyableUrl url="wss://xrplcluster.com" translate={translate} />
<span className="quick-ref-protocol">{translate("JSON-RPC")}</span>
<CopyableUrl url="https://xrplcluster.com" translate={translate} />
</div>
</div>
<div className="quick-ref-group">
<span className="quick-ref-key"><strong>{translate("Testnet")}</strong></span>
<div className="quick-ref-urls">
<span className="quick-ref-protocol">{translate("WebSocket")}</span>
<CopyableUrl url="wss://s.altnet.rippletest.net:51233" translate={translate} />
<span className="quick-ref-protocol">{translate("JSON-RPC")}</span>
<CopyableUrl url="https://s.altnet.rippletest.net:51234" translate={translate} />
</div>
</div>
<Link to="/docs/tutorials/public-servers/" className="quick-ref-link">
{translate("View all servers")}
</Link>
</div>
<div className="quick-ref-divider"></div>
<div className="quick-ref-section">
<Link to="/resources/dev-tools/xrp-faucets/" className="quick-ref-faucet">
<span>{translate("Get Test XRP")}</span>
<span className="quick-ref-arrow"></span>
</Link>
</div>
</div>
)
}
// ── Page Component ──────────────────────────────────────────────────────────
export default function TutorialsIndex() {
const { useTranslate, usePageSharedData } = useThemeHooks()
const { translate } = useTranslate()
@@ -299,65 +375,166 @@ export default function TutorialsIndex() {
// Get auto-detected languages from the plugin (maps tutorial paths to language arrays).
const tutorialLanguages = usePageSharedData<TutorialLanguagesMap>("tutorial-languages") || {}
// Get tutorial metadata from the tutorial-metadata plugin.
const tutorialMetadata = usePageSharedData<{ tutorials: TutorialMetadataItem[] }>("tutorial-metadata")
const allTutorials = tutorialMetadata?.tutorials || []
// Build Get Started tutorials from pinned config.
const getStartedPinnedEntries = pinnedTutorials["get-started"] || []
const getStartedTutorials = buildPinnedTutorials(getStartedPinnedEntries, allTutorials)
// Get Started paths to exclude from "What's New".
const getStartedPaths = new Set(getStartedPinnedEntries.map(getPinnedPath))
// Get recent tutorials for "What's New" section.
// Shows the most recently modified tutorials (excluding only Get Started).
// Pinned tutorials in other sections CAN appear here if recently updated.
const whatsNewTutorials: Tutorial[] = allTutorials
.filter((t) => !getStartedPaths.has(t.path))
.slice(0, MAX_WHATS_NEW)
.map((t) => toTutorial(t))
// Build category sections: pinned tutorials first, then auto-populated.
const categorySectionIds = new Set(["whats-new", "get-started"])
const allPinnedPaths = new Set(
Object.values(pinnedTutorials).flat().map(getPinnedPath)
)
const sections: TutorialSection[] = sectionConfig
.filter((config) => !categorySectionIds.has(config.id))
.map((config) => {
const pinned = buildPinnedTutorials(pinnedTutorials[config.id] || [], allTutorials)
// allTutorials is already sorted by lastModified (newest first) from the plugin.
const autoTutorials = allTutorials
.filter((t) => t.category === config.id && !allPinnedPaths.has(t.path))
.map((t) => toTutorial(t))
return { ...config, tutorials: [...pinned, ...autoTutorials] }
})
.filter((section) => section.tutorials.length > 0)
const whatsNewConfig = getSectionConfig("whats-new")
const getStartedConfig = getSectionConfig("get-started")
return (
<main className="landing page-tutorials landing-builtin-bg">
<section className="container-new py-26">
<div className="col-lg-8 mx-auto text-lg-center">
<div className="d-flex flex-column-reverse">
<h1 className="mb-0">
{translate("Crypto Wallet and Blockchain Development Tutorials")}
</h1>
<h6 className="eyebrow mb-3">{translate("Tutorials")}</h6>
{/* Hero Section */}
<section className="container-new py-20">
<div className="row align-items-center">
<div className="col-lg-7">
<div className="d-flex flex-column-reverse">
<h1 className="mb-0">
{translate("Crypto Wallet and Blockchain Development Tutorials")}
</h1>
<h6 className="eyebrow mb-3">{translate("Tutorials")}</h6>
</div>
<nav className="mt-4">
<ul className="page-toc no-sideline d-flex flex-wrap gap-2 mb-0">
{whatsNewTutorials.length > 0 && (
<li><a href={`#${whatsNewConfig.id}`}>{translate(whatsNewConfig.title)}</a></li>
)}
{getStartedTutorials.length > 0 && (
<li><a href={`#${getStartedConfig.id}`}>{translate(getStartedConfig.title)}</a></li>
)}
{sections.map((section) => (
<li key={section.id}><a href={`#${section.id}`}>{translate(section.title)}</a></li>
))}
</ul>
</nav>
</div>
<div className="col-lg-5 mt-6 mt-lg-0">
<QuickReferenceCard translate={translate} />
</div>
{/* Table of Contents */}
<nav className="mt-4">
<ul className="page-toc no-sideline d-flex flex-wrap justify-content-center gap-2 mb-0">
<li><a href="#get-started">{translate("Get Started with SDKs")}</a></li>
{sections.map((section) => (
<li key={section.id}><a href={`#${section.id}`}>{translate(section.title)}</a></li>
))}
</ul>
</nav>
</div>
</section>
{/* What's New */}
{whatsNewTutorials.length > 0 && (
<TutorialSectionBlock
id={whatsNewConfig.id}
title={whatsNewConfig.title}
description={whatsNewConfig.description}
tutorials={whatsNewTutorials}
tutorialLanguages={tutorialLanguages}
showFooter
className="whats-new-section pb-20"
translate={translate}
/>
)}
{/* Get Started */}
<section className="container-new pt-10 pb-20" id="get-started">
<div className="col-12 col-xl-8 p-0">
<h3 className="h4 mb-3">{translate("Get Started with SDKs")}</h3>
<p className="mb-4">
{translate("These tutorials walk you through the basics of building a very simple XRP Ledger-connected application using your favorite programming language.")}
</p>
</div>
<div className="row tutorial-cards">
{getStartedTutorials.map((tutorial, idx) => (
<div key={idx} className="col-lg-4 col-md-6 mb-5">
<TutorialCard tutorial={tutorial} showFooter translate={translate} />
</div>
))}
</div>
</section>
{getStartedTutorials.length > 0 && (
<TutorialSectionBlock
id={getStartedConfig.id}
title={getStartedConfig.title}
description={getStartedConfig.description}
tutorials={getStartedTutorials}
tutorialLanguages={tutorialLanguages}
showFooter
className="pb-20"
translate={translate}
/>
)}
{/* Other Tutorials */}
{sections.map((section) => (
<section className="container-new pt-10 pb-10" key={section.id} id={section.id}>
<div className="col-12 col-xl-8 p-0">
<h3 className="h4 mb-3">{translate(section.title)}</h3>
<p className="mb-4">{translate(section.description)}</p>
</div>
<div className="row tutorial-cards">
{section.tutorials.slice(0, 6).map((tutorial, idx) => (
<div key={idx} className="col-lg-4 col-md-6 mb-5">
<TutorialCard
tutorial={tutorial}
detectedLanguages={tutorialLanguages[tutorial.path]}
translate={translate}
/>
</div>
))}
</div>
</section>
<TutorialSectionBlock
key={section.id}
id={section.id}
title={section.title}
description={section.description}
tutorials={section.tutorials}
tutorialLanguages={tutorialLanguages}
maxTutorials={MAX_TUTORIALS_PER_SECTION}
translate={translate}
/>
))}
</main>
)
}
// ── Helpers ──────────────────────────────────────────────────────────────────
/** Look up a section's config by id */
function getSectionConfig(id: string) {
return sectionConfig.find((s) => s.id === id)!
}
/** Type guard for external community contributions */
function isExternalContribution(entry: PinnedTutorial): entry is PinnedExternalTutorial {
return typeof entry !== "string" && "github" in entry
}
/** Get path from pinned tutorial entry (external contributions return their github URL) */
function getPinnedPath(entry: PinnedTutorial): string {
return typeof entry === "string" ? entry : isExternalContribution(entry) ? entry.github : entry.path
}
/** Convert tutorial metadata to the common Tutorial type */
function toTutorial(t: TutorialMetadataItem, descriptionOverride?: string): Tutorial {
return {
title: t.title,
body: descriptionOverride || t.description,
path: t.path,
}
}
/** Build Tutorial objects from pinned entries, resolving metadata for internal paths */
function buildPinnedTutorials(entries: PinnedTutorial[], allTutorials: TutorialMetadataItem[]): Tutorial[] {
return entries
.map((entry): Tutorial | null => {
if (isExternalContribution(entry)) {
return {
title: entry.title,
body: entry.description,
path: entry.url || entry.github,
author: entry.author,
github: entry.github,
externalUrl: entry.url,
}
}
const path = getPinnedPath(entry)
const descOverride = typeof entry === "string" ? undefined : entry.description
const metadata = allTutorials.find((t) => t.path === path)
return metadata ? toTutorial(metadata, descOverride) : null
})
.filter((t): t is Tutorial => t !== null)
}

View File

@@ -12,6 +12,7 @@ If you don't [run your own `rippled` server](../infrastructure/installation/inde
## Non-Commercial
| Operator | [Network][] | JSON-RPC URL | WebSocket URL | Notes |
|:----------|:------------|:-------------|:--------------|:---------------------|
| Honeycluster | **Mainnet** | `https://honeycluster.io/` | `wss://honeycluster.io/` | Full history server cluster with Clio |
| InFTF | **Mainnet** | `https://xrplcluster.com/` <br> `https://xrpl.ws/` [²][] | `wss://xrplcluster.com/` <br> `wss://xrpl.ws/` [²][] | Full history server cluster with CORS support. |
| Ripple[¹][] | **Mainnet** | `https://s1.ripple.com:51234/` | `wss://s1.ripple.com/` | General purpose server cluster |
| Ripple[¹][] | **Mainnet** | `https://s2.ripple.com:51234/` | `wss://s2.ripple.com/` | [Full-history server](../concepts/networks-and-servers/ledger-history.md#full-history) cluster |
@@ -28,10 +29,12 @@ If you don't [run your own `rippled` server](../infrastructure/installation/inde
| Operator | [Network][] | JSON-RPC URL | WebSocket URL | Notes |
|:----------|:------------|:-------------|:--------------|:---------------------|
| Ripple[¹][] | Testnet | `https://s.altnet.rippletest.net:51234/` | `wss://s.altnet.rippletest.net:51233/` | Testnet public server |
| Honeycluster | Testnet | `https://testnet.honeycluster.io/` | `wss://testnet.honeycluster.io/` | Testnet public server |
| XRPL Labs | Testnet | `https://testnet.xrpl-labs.com/` | `wss://testnet.xrpl-labs.com/` | Testnet public server with CORS support |
| Ripple[¹][] | Testnet (Clio) | `https://clio.altnet.rippletest.net:51234/` | `wss://clio.altnet.rippletest.net:51233/` | Testnet public server with Clio |
| Ripple[¹][] | Devnet | `https://s.devnet.rippletest.net:51234/` | `wss://s.devnet.rippletest.net:51233/` | Devnet public server |
| Ripple[¹][] | Devnet (Clio) | `https://clio.devnet.rippletest.net:51234/` | `wss://clio.devnet.rippletest.net:51233/` | Devnet public server with Clio |
| Honeycluster | Devnet | `https://devnet.honeycluster.io/` | `wss://devnet.honeycluster.io/` | Devnet public server |
| XRPL Labs | Xahau Testnet | `https://xahau-test.net/` | `wss://xahau-test.net/` | [Hooks-enabled](https://hooks.xrpl.org/) Xahau Testnet |

View File

@@ -28,7 +28,7 @@ To learn about MPTs in general, go to the **Concept** page. For developer-focuse
{% card-grid %}
{% xrpl-card title="Concept: MultiPurpose Tokens" body="Read the concept documentation to learn more about Multi-Purpose Tokens." href="docs/concepts/tokens/fungible-tokens/multi-purpose-tokens/" /%}
{% xrpl-card title="Tutorial: Issue a MultiPurpose Token" body="Stepbystep, handson tutorial to issue an MPT using the XRP Ledger SDKs." href="docs/tutorials/issue-a-multi-purpose-token/" /%}
{% xrpl-card title="Tutorial: Issue a MultiPurpose Token" body="Stepbystep, handson tutorial to issue an MPT using the XRP Ledger SDKs." href="docs/tutorials/tokens/mpts/issue-a-multi-purpose-token" /%}
{% xrpl-card title="MPT Generator" body="Download the MPT Generator and learn how to create an asset-backed Treasury bill." href="#mpt-generator"/%}
{% /card-grid %}

View File

@@ -6,7 +6,6 @@ ignore:
- _code-samples/create-amm/ts/tsconfig.json
- resources/contribute-blog/_blog-template.md
- resources/contribute-documentation/_tutorial-template.md
- CODE-OF-CONDUCT.md
l10n:
defaultLocale: en-US
locales:

View File

@@ -326,7 +326,8 @@
- page: docs/tutorials/best-practices/key-management/remove-a-regular-key-pair.md
- page: docs/tutorials/best-practices/key-management/offline-account-setup.md
- page: docs/tutorials/best-practices/key-management/set-up-multi-signing.md
- page: docs/tutorials/best-practices/key-management/send-a-multi-signed-transaction.md
- page: docs/tutorials/best-practices/key-management/send-a-multi-signed-transaction.md
- page: docs/tutorials/best-practices/key-management/delete-an-account.md
- group: Advanced Developer Topics
groupTranslationKey: sidebar.docs.tutorials.advancedDeveloperTopics
expanded: false

File diff suppressed because one or more lines are too long

View File

@@ -320,128 +320,3 @@ main article .card-grid {
margin-bottom: 0.25rem;
margin-top: 0.5rem;
}
/* Tutorial cards */
.page-tutorials .tutorial-cards {
> div {
display: flex;
}
.card {
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
min-height: 280px;
transition: all 0.35s ease-out;
cursor: pointer;
&:hover {
transform: translateY(-16px);
}
.card-header {
border-bottom: none;
background: transparent;
padding: 1.5rem 1.5rem 0 2rem;
}
.circled-logo {
margin-left: -10px;
display: inline-flex;
align-items: center;
justify-content: center;
}
.card-body {
padding: 1rem 1.5rem;
flex: 1;
}
.card-title {
font-weight: 700;
margin-bottom: 1rem;
}
.card-text {
font-size: 1rem;
margin-bottom: 1.5rem;
}
.card-footer {
background-color: transparent;
border-top: none;
padding: 0;
height: 40px;
background-size: cover;
background-position: bottom;
background-repeat: no-repeat;
margin-top: auto;
}
}
// Apply colored footers to each card
> div:nth-child(1) .card .card-footer {
background-image: url("../img/cards/3-col-pink.svg");
}
> div:nth-child(2) .card .card-footer {
background-image: url("../img/cards/3col-blue-light-blue.svg");
}
> div:nth-child(3) .card .card-footer {
background-image: url("../img/cards/3-col-light-blue.svg");
}
> div:nth-child(4) .card .card-footer {
background-image: url("../img/cards/3col-blue-green.svg");
}
> div:nth-child(5) .card .card-footer {
background-image: url("../img/cards/3col-magenta.svg");
}
> div:nth-child(6) .card .card-footer {
background-image: url("../img/cards/3-col-orange.svg");
}
}
.light .page-tutorials .tutorial-cards .circled-logo img[alt="HTTP / WebSocket"] {
filter: invert(1);
}
// TOC buttons for tutorials page
.page-tutorials .page-toc.no-sideline {
border-left: none;
gap: 0.75rem;
li {
a {
border-radius: 100px;
padding: 0.5rem 1rem;
margin: 0;
background-color: $gray-800;
color: $gray-200;
font-weight: 500;
transition: all 0.2s ease;
&:hover,
&:focus,
&:active {
background-color: $blue-purple-500;
color: $white;
border-left: none;
margin-left: 0;
}
}
}
}
.light .page-tutorials .page-toc.no-sideline {
li a {
background-color: $gray-200;
color: $gray-800;
&:hover,
&:focus,
&:active {
background-color: $blue-purple-500;
color: $white;
}
}
}

460
styles/_tutorials.scss Normal file
View File

@@ -0,0 +1,460 @@
// Tutorials landing page styles
// Card footer gradient images
$card-footers: (
"3-col-pink",
"3col-blue-light-blue",
"3-col-light-blue",
"3col-blue-green",
"3col-magenta",
"3-col-orange"
);
$whats-new-footers: (
"3col-green-purple",
"3col-purple-blue-green",
"3col-green-blue"
);
// Tutorial cards
.page-tutorials .tutorial-cards {
> div {
display: flex;
}
.card {
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
min-height: 300px;
transition: all 0.35s ease-out;
cursor: pointer;
&:hover {
transform: translateY(-16px);
}
.card-header {
border-bottom: none;
background: transparent;
padding: 1.5rem 1.5rem 0 2rem;
}
.circled-logo {
margin-left: -10px;
display: inline-flex;
align-items: center;
justify-content: center;
}
.card-body {
padding: 1rem 1.5rem;
flex: 1;
}
.card-title {
font-weight: 700;
margin-bottom: 1rem;
}
.card-text {
font-size: 1rem;
margin-bottom: 1.5rem;
}
.card-footer {
background-color: transparent;
border-top: none;
padding: 0;
height: 40px;
background-size: cover;
background-position: bottom;
background-repeat: no-repeat;
margin-top: auto;
}
}
// Apply colored footers to each card
@for $i from 1 through length($card-footers) {
> div:nth-child(#{$i}) .card .card-footer {
background-image: url("../img/cards/#{nth($card-footers, $i)}.svg");
}
}
}
// Light mode: invert HTTP/WebSocket icon
.light .page-tutorials .tutorial-cards .circled-logo img[alt="HTTP / WebSocket"] {
filter: invert(1);
}
// Contribution Card - community contribution with meta links
.page-tutorials .tutorial-cards .contribution-card {
.contribution-header {
display: flex;
align-items: center;
gap: 0.6rem;
}
.contribution-icon {
background: rgba($blue-purple-500, 0.15);
color: $blue-purple-300;
font-size: 26px;
}
.card-external-icon {
font-size: 0.85rem;
margin-left: 0.35rem;
color: $gray-500;
vertical-align: middle;
}
.card-meta-row {
display: flex;
align-items: center;
gap: 0.4rem;
font-size: 0.8rem;
flex-wrap: wrap;
margin-left: auto;
margin-top: -4px;
.meta-link {
display: inline-flex;
align-items: center;
gap: 0.35rem;
color: $gray-300;
text-decoration: none;
transition: color 0.15s ease;
.fa {
font-size: 0.8rem;
}
&:hover {
color: $blue-purple-300;
}
}
.meta-dot {
color: $gray-500;
font-weight: bold;
user-select: none;
}
}
}
// Light mode: Contribution Card
.light .page-tutorials .tutorial-cards .contribution-card {
.contribution-icon {
background: rgba($blue-purple-500, 0.1);
color: $blue-purple-600;
}
.card-meta-row {
.meta-link {
color: $gray-600;
&:hover {
color: $blue-purple-600;
}
}
.meta-dot {
color: $gray-500;
}
}
}
// TOC navigation buttons
.page-tutorials .page-toc.no-sideline {
border-left: none;
gap: 0.75rem;
li {
a {
border-radius: 100px;
padding: 0.5rem 1rem;
margin: 0;
background-color: $gray-800;
color: $gray-200;
font-weight: 500;
transition: all 0.2s ease;
&:hover,
&:focus,
&:active {
background-color: $blue-purple-500;
color: $white;
border-left: none;
margin-left: 0;
}
}
}
}
// Light mode: TOC buttons
.light .page-tutorials .page-toc.no-sideline {
li a {
background-color: $gray-200;
color: $gray-800;
&:hover,
&:focus,
&:active {
background-color: $blue-purple-500;
color: $white;
}
}
}
// What's New section
.whats-new-section {
// Gradient underline on section title
h3 {
display: inline-block;
position: relative;
padding-bottom: 8px;
&::after {
content: "";
position: absolute;
bottom: 0;
left: 0;
width: 60px;
height: 3px;
background: linear-gradient(90deg, $blue-purple-500, $green-400);
border-radius: 2px;
}
}
// Different footer colors for What's New cards
.tutorial-cards {
@for $i from 1 through length($whats-new-footers) {
> div:nth-child(#{$i}) .card .card-footer {
background-image: url("../img/cards/#{nth($whats-new-footers, $i)}.svg");
}
}
}
}
// Quick Reference Card
.page-tutorials .quick-ref-card {
background: rgba($gray-800, 0.7);
border: 1px solid $gray-700;
border-left: 3px solid $blue-purple-500;
border-radius: 12px;
padding: 1rem 1.5rem;
backdrop-filter: blur(8px);
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
margin-left: auto;
max-width: 480px;
@media (max-width: 991px) {
margin-left: 0;
max-width: 100%;
}
.quick-ref-section {
padding: 0.25rem 0;
}
.quick-ref-label {
display: block;
font-size: 0.7rem;
font-weight: 700;
letter-spacing: 0.08em;
color: $blue-purple-300;
margin-bottom: 0.75rem;
}
.quick-ref-group {
margin-bottom: 0.75rem;
&:last-of-type {
margin-bottom: 0.5rem;
}
}
.quick-ref-key {
display: block;
font-size: 0.85rem;
color: $gray-300;
margin-bottom: 0.35rem;
strong {
font-weight: 700;
color: $white;
}
}
.quick-ref-urls {
display: grid;
grid-template-columns: auto auto;
gap: 0.25rem 0.75rem;
align-items: center;
width: fit-content;
max-width: 100%;
@media (max-width: 576px) {
grid-template-columns: 1fr;
gap: 0.2rem;
}
}
.quick-ref-protocol {
font-size: 0.7rem;
font-weight: 500;
color: $gray-500;
letter-spacing: 0.02em;
}
.quick-ref-value {
font-size: 0.75rem;
color: $blue-purple-300;
background: rgba($gray-900, 0.5);
padding: 0.2rem 0.5rem;
border-radius: 4px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 100%;
}
.quick-ref-value-btn {
display: inline-flex;
align-items: center;
gap: 0.35rem;
background: none;
border: none;
padding: 0;
cursor: pointer;
transition: opacity 0.2s ease;
max-width: 100%;
overflow: hidden;
&:hover {
opacity: 0.8;
.quick-ref-value {
background: rgba($gray-800, 0.8);
}
}
&.copied .quick-ref-value {
background: rgba($green-500, 0.2);
color: $green-400;
}
.copy-icon {
font-size: 0.7rem;
color: $green-400;
min-width: 0.8rem;
flex-shrink: 0;
}
@media (max-width: 576px) {
margin-bottom: 0.5rem;
}
}
.quick-ref-link {
display: inline-block;
font-size: 0.8rem;
color: $blue-purple-300;
margin-top: 0.35rem;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
.quick-ref-divider {
height: 1px;
background: $gray-700;
margin: 0.5rem 0;
}
.quick-ref-faucet {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.9rem;
font-weight: 500;
color: $white;
text-decoration: none;
padding: 0.25rem 0;
&:hover {
color: $blue-purple-300;
}
.quick-ref-arrow {
color: $blue-purple-400;
}
}
}
// Light mode: Quick Reference Card
.light .page-tutorials .quick-ref-card {
background: rgba($white, 0.95);
border-color: $gray-300;
border-left: 3px solid $blue-purple-500;
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
.quick-ref-label {
color: $blue-purple-600;
}
.quick-ref-key {
color: $gray-700;
strong {
color: $gray-900;
}
}
.quick-ref-protocol {
color: $gray-500;
}
.quick-ref-value {
color: $blue-purple-600;
background: rgba($gray-300, 0.6);
}
.quick-ref-value-btn {
&:hover .quick-ref-value {
background: rgba($gray-400, 0.6);
}
&.copied .quick-ref-value {
background: rgba($green-500, 0.15);
color: $green-700;
}
.copy-icon {
color: $green-600;
}
}
.quick-ref-link {
color: $blue-purple-600;
}
.quick-ref-divider {
background: $gray-200;
}
.quick-ref-faucet {
color: $gray-900;
&:hover {
color: $blue-purple-600;
}
.quick-ref-arrow {
color: $blue-purple-500;
}
}
}

View File

@@ -69,6 +69,7 @@ $line-height-base: 1.5;
@import "_pages.scss";
@import "_rpc-tool.scss";
@import "_blog.scss";
@import "_tutorials.scss";
@import "_feedback.scss";
@import "_video.scss";
@import "_contribute.scss";