mirror of
https://github.com/XRPLF/xrpl-dev-portal.git
synced 2026-04-06 11:52:29 +00:00
Compare commits
22 Commits
add-calcul
...
release-no
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0e99161bb | ||
|
|
a441171000 | ||
|
|
892714550e | ||
|
|
b6388ccb13 | ||
|
|
6ab5de13bb | ||
|
|
38000f19d6 | ||
|
|
ad9e5e14fa | ||
|
|
663cd6df6a | ||
|
|
6bee1983eb | ||
|
|
9df53455e9 | ||
|
|
13dddb8b22 | ||
|
|
b47c96d91a | ||
|
|
93abc4dc09 | ||
|
|
ae266aba7f | ||
|
|
ab9eec63f5 | ||
|
|
8b8ed4c6ea | ||
|
|
6aaca7f568 | ||
|
|
a045e9e40c | ||
|
|
ad9327c4c0 | ||
|
|
53983bf8e2 | ||
|
|
4bceb09b1b | ||
|
|
0da3a1e13c |
19
.claude/CLAUDE.md
Normal file
19
.claude/CLAUDE.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# XRPL Dev Portal — Claude Code Instructions
|
||||
|
||||
## Quick Reference
|
||||
|
||||
- **Framework:** Redocly Realm
|
||||
- **Production branch:** `master`
|
||||
- **Local preview:** `npm start`
|
||||
|
||||
## Localization
|
||||
|
||||
- Default: `en-US`
|
||||
- Japanese: `ja`
|
||||
- Translations mirror `docs/` structure under `@l10n/<language-code>/`
|
||||
|
||||
## Navigation
|
||||
|
||||
- Update `sidebars.yaml` when adding new doc pages
|
||||
- Blog posts have a separate `blog/sidebars.yaml`
|
||||
- Redirects go in `redirects.yaml`
|
||||
7
.claude/settings.json
Normal file
7
.claude/settings.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"permissions": {
|
||||
"deny": [
|
||||
"Bash(git push *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
117
.claude/skills/generate-release-notes/SKILL.md
Normal file
117
.claude/skills/generate-release-notes/SKILL.md
Normal file
@@ -0,0 +1,117 @@
|
||||
---
|
||||
name: generate-release-notes
|
||||
description: Generate and sort rippled release notes from GitHub commit history
|
||||
argument-hint: --from <ref> --to <ref> [--date YYYY-MM-DD]
|
||||
allowed-tools: Bash, Read, Edit, Write, Grep, Glob
|
||||
effort: max
|
||||
---
|
||||
|
||||
# Generate rippled Release Notes
|
||||
|
||||
This skill generates a draft release notes blog post for a new rippled version, then sorts the entries into the correct subsections.
|
||||
|
||||
## Execution constraints
|
||||
|
||||
- **Do NOT write scripts** to sort or process the file. Prefer the Edit tool for targeted changes. Use Write only when replacing large sections that are impractical to edit incrementally.
|
||||
- **Output progress**: Before each major step (generating raw release notes, reviewing file, processing amendments, sorting entries, reformatting, cleanup), output a brief status message so the user can see progress.
|
||||
|
||||
## Step 1: Generate the raw release notes
|
||||
|
||||
Run the Python script from the repo root. Pass through all arguments from `$ARGUMENTS`:
|
||||
|
||||
```bash
|
||||
python3 tools/generate-release-notes.py $ARGUMENTS
|
||||
```
|
||||
|
||||
If the user didn't provide `--from` or `--to`, ask them for the base and target refs (tags or branches).
|
||||
|
||||
The script will:
|
||||
- Fetch the version string from `BuildInfo.cpp`
|
||||
- Fetch all commits between the two refs
|
||||
- Fetch PR details (title, link, labels, files, description) via GraphQL
|
||||
- Compare `features.macro` between refs to identify amendment changes
|
||||
- Auto-sort amendment entries into the Amendments section
|
||||
- Output all other entries as unsorted with full context
|
||||
|
||||
## Step 2: Review the generated file
|
||||
|
||||
Read the output file (path shown in script output). Note the **Full Changelog** structure:
|
||||
- **Amendments section**: Contains auto-sorted entries and an HTML comment listing which amendments to include or remove
|
||||
- **Empty subsections**: Features, Breaking Changes, Bug Fixes, Refactors, Documentation, Testing, CI/Build
|
||||
- **Unsorted entries**: After the **Bug Bounties and Responsible Disclosures** section is an unsorted list of entries with title, link, labels, files, and description for context
|
||||
|
||||
## Step 3: Process amendments
|
||||
|
||||
Handle Amendments first, before sorting other entries.
|
||||
|
||||
**3a. Process the auto-sorted Amendments subsection:**
|
||||
The HTML comment contains three lists — follow them exactly:
|
||||
- **Include**: Keep these entries.
|
||||
- **Exclude**: Remove these entries.
|
||||
- Entries on **neither** list: Remove these entries.
|
||||
|
||||
**3b. Scan unsorted entries for unreleased amendment work:**
|
||||
Search through ALL unsorted entries for titles, labels, descriptions, or files that reference amendments on the "Exclude" or "Other amendments not part of this release" lists. Remove entries that directly implement, enable, fix, or refactor these amendments. Keep entries that are general changes that merely reference the amendment as motivation — if the code change is useful on its own regardless of whether the amendment ships, keep it.
|
||||
|
||||
**3c. If you disagree with any amendment decisions, make a note to the user but do NOT deviate from the rules.**
|
||||
|
||||
## Step 4: Sort remaining unsorted entries into subsections
|
||||
|
||||
Move each remaining unsorted entry into the appropriate subsection.
|
||||
|
||||
Use these signals to categorize:
|
||||
|
||||
**Files changed** (strongest signal):
|
||||
- Only `.github/`, `CMakeLists.txt`, `conan*`, CI config files → **CI/Build**
|
||||
- Only `src/test/`, `*_test.cpp` files → **Testing**
|
||||
- Only `*.md`, `docs/` files → **Documentation**
|
||||
|
||||
**Labels** (strong signal):
|
||||
- `Bug` label → **Bug Fixes**
|
||||
|
||||
**Title prefixes** (medium signal):
|
||||
- `fix:` → **Bug Fixes**
|
||||
- `feat:` → **Features**
|
||||
- `refactor:` → **Refactors**
|
||||
- `docs:` → **Documentation**
|
||||
- `test:` → **Testing**
|
||||
- `ci:`, `build:`, `chore:` → **CI/Build**
|
||||
|
||||
**Description content** (when other signals are ambiguous):
|
||||
- Read the PR description to understand the change's purpose
|
||||
- PRs that change API behavior, remove features, or have "Breaking change" checked in their description → **Breaking Changes**
|
||||
|
||||
Additional sorting guidance:
|
||||
- Watch for revert pairs: If a PR was committed and then reverted (or vice versa), check that the net effect is accounted for — don't include both.
|
||||
|
||||
## Step 5: Reformat sorted entries
|
||||
|
||||
After sorting, reformat each entry to match the release notes style.
|
||||
|
||||
**Amendment entries** should follow this format:
|
||||
```markdown
|
||||
- **amendmentName**: Description of what the amendment does. ([#1234](https://github.com/XRPLF/rippled/pull/1234))
|
||||
```
|
||||
- Use more detail for amendment descriptions since they are the most important. Use present tense.
|
||||
- If there are multiple entries for the same amendment, merge into one, prioritizing the entry that describes the actual amendment.
|
||||
|
||||
**Feature and Breaking Change entries** should follow this format:
|
||||
```markdown
|
||||
- Description of the change. ([#1234](https://github.com/XRPLF/rippled/pull/1234))
|
||||
```
|
||||
- Keep the description concise. Use past tense.
|
||||
|
||||
**All other entries** should follow this format:
|
||||
```markdown
|
||||
- The PR title of the entry. ([#1234](https://github.com/XRPLF/rippled/pull/1234))
|
||||
```
|
||||
- Copy the PR title as-is. Only fix capitalization, remove conventional commit prefixes (fix:, feat:, ci:, refactor:, docs:, test:, chore:, build:), and adjust to past tense if needed. Do NOT rewrite, paraphrase, or summarize.
|
||||
|
||||
## Step 6: Clean up
|
||||
|
||||
- Add a short and generic description of changes to the existing `seo.description` frontmatter, e.g., "This version introduces new amendments and bug fixes." Do not create long lists of detailed changes.
|
||||
- Add a more detailed summary of the release to the existing "Introducing XRP Ledger Version X.Y.Z" section. Include amendment names (organized in a list if more than 2), featuress, and breaking changes. Limit this to 1 paragraph.
|
||||
- Do NOT delete the **Credits** or **Bug Bounties and Responsible Disclosures** sections
|
||||
- Remove empty subsections that have no entries
|
||||
- Remove all HTML comments (sorting instructions)
|
||||
- Do a final review of the release notes. If you see anything strange, or were forced to take unintuitive actions by these instructions, notify the user, but don't make changes.
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -8,7 +8,6 @@ yarn-error.log
|
||||
*.iml
|
||||
.venv/
|
||||
_code-samples/*/js/package-lock.json
|
||||
_code-samples/*/go/go.sum
|
||||
_code-samples/*/*/*[Ss]etup.json
|
||||
|
||||
# PHP
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
// @ts-check
|
||||
|
||||
import { getInnerText } from '@redocly/realm/dist/markdoc/helpers/get-inner-text.js';
|
||||
import { getInnerText } from '@redocly/realm/dist/server/plugins/markdown/markdoc/helpers/get-inner-text.js';
|
||||
|
||||
import { dirname, relative, join as joinPath } from 'path';
|
||||
import markdoc from '@markdoc/markdoc';
|
||||
import moment from "moment";
|
||||
|
||||
export function blogPosts() {
|
||||
/** @type {import("@redocly/realm/dist/server/types").ExternalPlugin } */
|
||||
/** @type {import("@redocly/realm/dist/server/plugins/types").PluginInstance } */
|
||||
const instance = {
|
||||
id: 'blog-posts',
|
||||
processContent: async (actions, { fs, cache }) => {
|
||||
try {
|
||||
const posts = [];
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
// @ts-check
|
||||
|
||||
import { getInnerText } from '@redocly/realm/dist/markdoc/helpers/get-inner-text.js';
|
||||
import { getInnerText } from '@redocly/realm/dist/server/plugins/markdown/markdoc/helpers/get-inner-text.js';
|
||||
|
||||
import { dirname, relative, join as joinPath } from 'path';
|
||||
|
||||
export function codeSamples() {
|
||||
/** @type {import("@redocly/realm/dist/server/types").ExternalPlugin } */
|
||||
/** @type {import("@redocly/realm/dist/server/plugins/types").PluginInstance } */
|
||||
const instance = {
|
||||
id: 'code-samples',
|
||||
processContent: async (actions, { fs, cache }) => {
|
||||
try {
|
||||
const samples = [];
|
||||
|
||||
@@ -3,9 +3,8 @@ import { readSharedData } from '@redocly/realm/dist/server/utils/shared-data.js'
|
||||
const INDEX_PAGE_INFO_DATA_KEY = 'index-page-items';
|
||||
|
||||
export function indexPages() {
|
||||
/** @type {import("@redocly/realm/dist/server/types").ExternalPlugin } */
|
||||
/** @type {import("@redocly/realm/dist/server/plugins/types").PluginInstance } */
|
||||
const instance = {
|
||||
id: 'index-pages',
|
||||
// hook that gets executed after all routes were created
|
||||
async afterRoutesCreated(actions, { cache }) {
|
||||
// get all the routes that are ind pages
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# 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.
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
|
||||
// Set up client ----------------------
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/Peersyst/xrpl-go/xrpl/queries/account"
|
||||
"github.com/Peersyst/xrpl-go/xrpl/queries/server"
|
||||
"github.com/Peersyst/xrpl-go/xrpl/transaction/types"
|
||||
"github.com/Peersyst/xrpl-go/xrpl/websocket"
|
||||
)
|
||||
|
||||
func main() {
|
||||
client := websocket.NewClient(
|
||||
websocket.NewClientConfig().
|
||||
WithHost("wss://s.devnet.rippletest.net:51233"),
|
||||
)
|
||||
defer client.Disconnect()
|
||||
|
||||
if err := client.Connect(); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Look up reserve values ----------------------
|
||||
|
||||
res, err := client.Request(&server.InfoRequest{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
var serverInfo server.InfoResponse
|
||||
if err := res.GetResult(&serverInfo); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
baseReserve := serverInfo.Info.ValidatedLedger.ReserveBaseXRP
|
||||
reserveInc := serverInfo.Info.ValidatedLedger.ReserveIncXRP
|
||||
|
||||
fmt.Printf("Base reserve: %v XRP\n", baseReserve)
|
||||
fmt.Printf("Incremental reserve: %v XRP\n", reserveInc)
|
||||
|
||||
// Look up owner count ----------------------
|
||||
|
||||
address := types.Address("rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh")
|
||||
accountInfo, err := client.GetAccountInfo(&account.InfoRequest{Account: address})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
ownerCount := accountInfo.AccountData.OwnerCount
|
||||
|
||||
// Calculate total reserve ----------------------
|
||||
|
||||
totalReserve := float64(baseReserve) + (float64(ownerCount) * float64(reserveInc))
|
||||
|
||||
fmt.Printf("Owner count: %v\n", ownerCount)
|
||||
fmt.Printf("Total reserve: %v XRP\n", totalReserve)
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
module calculate-reserves
|
||||
|
||||
go 1.26.1
|
||||
|
||||
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/mitchellh/mapstructure v1.5.0 // 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
|
||||
)
|
||||
@@ -1,30 +0,0 @@
|
||||
github.com/Peersyst/xrpl-go v0.1.17 h1:jOI2es/dzzRm6/WMVCjr7H3fci47XB2kRkezfbddDB0=
|
||||
github.com/Peersyst/xrpl-go v0.1.17/go.mod h1:38j60Mr65poIHdhmjvNXnwbcUFNo8J7CBDot7ZWgrb8=
|
||||
github.com/bsv-blockchain/go-sdk v1.2.9 h1:LwFzuts+J5X7A+ECx0LNowtUgIahCkNNlXckdiEMSDk=
|
||||
github.com/bsv-blockchain/go-sdk v1.2.9/go.mod h1:KiHWa/hblo3Bzr+IsX11v0sn1E6elGbNX0VXl5mOq6E=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/decred/dcrd/crypto/blake256 v1.1.0 h1:zPMNGQCm0g4QTY27fOCorQW7EryeQ/U0x++OzVrdms8=
|
||||
github.com/decred/dcrd/crypto/blake256 v1.1.0/go.mod h1:2OfgNZ5wDpcsFmHmCK5gZTPcCXqlm2ArzUIkw9czNJo=
|
||||
github.com/decred/dcrd/crypto/ripemd160 v1.0.2 h1:TvGTmUBHDU75OHro9ojPLK+Yv7gDl2hnUvRocRCjsys=
|
||||
github.com/decred/dcrd/crypto/ripemd160 v1.0.2/go.mod h1:uGfjDyePSpa75cSQLzNdVmWlbQMBuiJkvXw/MNKRY4M=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1 h1:5RVFMOWjMyRy8cARdy79nAmgYw3hK/4HUq48LQ6Wwqo=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.1/go.mod h1:ZXNYxsqcloTdSy/rNShjYzMhyjf0LaoftYK0p+A3h40=
|
||||
github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc=
|
||||
github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs=
|
||||
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
|
||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
|
||||
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
golang.org/x/crypto v0.44.0 h1:A97SsFvM3AIwEEmTBiaxPPTYpDC47w720rdiiUvgoAU=
|
||||
golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -1,47 +0,0 @@
|
||||
|
||||
// Set up client ----------------------
|
||||
|
||||
import okhttp3.HttpUrl;
|
||||
import org.xrpl.xrpl4j.client.JsonRpcClientErrorException;
|
||||
import org.xrpl.xrpl4j.client.XrplClient;
|
||||
import org.xrpl.xrpl4j.model.client.accounts.AccountInfoRequestParams;
|
||||
import org.xrpl.xrpl4j.model.client.common.LedgerSpecifier;
|
||||
import org.xrpl.xrpl4j.model.transactions.Address;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class CalculateReserves {
|
||||
public static void main(String[] args) throws JsonRpcClientErrorException {
|
||||
HttpUrl rippledUrl = HttpUrl.get("https://s.devnet.rippletest.net:51234/");
|
||||
XrplClient xrplClient = new XrplClient(rippledUrl);
|
||||
|
||||
// Look up reserve values ----------------------
|
||||
|
||||
var serverInfo = xrplClient.serverInformation();
|
||||
var validatedLedger = serverInfo.info().validatedLedger().get();
|
||||
|
||||
BigDecimal baseReserve = validatedLedger.reserveBaseXrp().toXrp();
|
||||
BigDecimal reserveInc = validatedLedger.reserveIncXrp().toXrp();
|
||||
|
||||
System.out.println("Base reserve: " + baseReserve + " XRP");
|
||||
System.out.println("Incremental reserve: " + reserveInc + " XRP");
|
||||
|
||||
// Look up owner count ----------------------
|
||||
|
||||
Address address = Address.of("rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh");
|
||||
var accountInfo = xrplClient.accountInfo(
|
||||
AccountInfoRequestParams.builder()
|
||||
.account(address)
|
||||
.ledgerSpecifier(LedgerSpecifier.VALIDATED)
|
||||
.build()
|
||||
);
|
||||
|
||||
long ownerCount = accountInfo.accountData().ownerCount().longValue();
|
||||
|
||||
// Calculate total reserve ----------------------
|
||||
|
||||
BigDecimal totalReserve = baseReserve.add(reserveInc.multiply(BigDecimal.valueOf(ownerCount)));
|
||||
|
||||
System.out.println("Owner count: " + ownerCount);
|
||||
System.out.println("Total reserve: " + totalReserve + " XRP");
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.example</groupId>
|
||||
<artifactId>calculate-reserves</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.source>11</maven.compiler.source>
|
||||
<maven.compiler.target>11</maven.compiler.target>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.xrpl</groupId>
|
||||
<artifactId>xrpl4j-client</artifactId>
|
||||
<version>3.0.0</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -1,46 +0,0 @@
|
||||
// Set up client ----------------------
|
||||
|
||||
import okhttp3.HttpUrl;
|
||||
import org.xrpl.xrpl4j.client.JsonRpcClientErrorException;
|
||||
import org.xrpl.xrpl4j.client.XrplClient;
|
||||
import org.xrpl.xrpl4j.model.client.accounts.AccountInfoRequestParams;
|
||||
import org.xrpl.xrpl4j.model.client.common.LedgerSpecifier;
|
||||
import org.xrpl.xrpl4j.model.transactions.Address;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class CalculateReserves {
|
||||
public static void main(String[] args) throws JsonRpcClientErrorException {
|
||||
HttpUrl rippledUrl = HttpUrl.get("https://s.devnet.rippletest.net:51234/");
|
||||
XrplClient xrplClient = new XrplClient(rippledUrl);
|
||||
|
||||
// Look up reserve values ----------------------
|
||||
|
||||
var serverInfo = xrplClient.serverInformation();
|
||||
var validatedLedger = serverInfo.info().validatedLedger().get();
|
||||
|
||||
BigDecimal baseReserve = validatedLedger.reserveBaseXrp().toXrp();
|
||||
BigDecimal reserveInc = validatedLedger.reserveIncXrp().toXrp();
|
||||
|
||||
System.out.println("Base reserve: " + baseReserve + " XRP");
|
||||
System.out.println("Incremental reserve: " + reserveInc + " XRP");
|
||||
|
||||
// Look up owner count ----------------------
|
||||
|
||||
Address address = Address.of("rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh");
|
||||
var accountInfo = xrplClient.accountInfo(
|
||||
AccountInfoRequestParams.builder()
|
||||
.account(address)
|
||||
.ledgerSpecifier(LedgerSpecifier.VALIDATED)
|
||||
.build()
|
||||
);
|
||||
|
||||
long ownerCount = accountInfo.accountData().ownerCount().longValue();
|
||||
|
||||
// Calculate total reserve ----------------------
|
||||
|
||||
BigDecimal totalReserve = baseReserve.add(reserveInc.multiply(BigDecimal.valueOf(ownerCount)));
|
||||
|
||||
System.out.println("Owner count: " + ownerCount);
|
||||
System.out.println("Total reserve: " + totalReserve + " XRP");
|
||||
}
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
|
||||
// Set up client ----------------------
|
||||
|
||||
import xrpl from 'xrpl'
|
||||
|
||||
const client = new xrpl.Client('wss://s.devnet.rippletest.net:51233')
|
||||
await client.connect()
|
||||
|
||||
// Look up reserve values ----------------------
|
||||
|
||||
const serverInfo = await client.request({ command: 'server_info' })
|
||||
const validatedLedger = serverInfo.result.info.validated_ledger
|
||||
|
||||
const baseReserve = validatedLedger.reserve_base_xrp
|
||||
const reserveInc = validatedLedger.reserve_inc_xrp
|
||||
|
||||
console.log(`Base reserve: ${baseReserve} XRP`)
|
||||
console.log(`Incremental reserve: ${reserveInc} XRP`)
|
||||
|
||||
// Look up owner count ----------------------
|
||||
|
||||
const address = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" // replace with any address
|
||||
const accountInfo = await client.request({ command: "account_info", account: address })
|
||||
const ownerCount = accountInfo.result.account_data.OwnerCount
|
||||
|
||||
// Calculate total reserve ----------------------
|
||||
|
||||
const totalReserve = baseReserve + (ownerCount * reserveInc)
|
||||
|
||||
console.log(`Owner count: ${ownerCount}`)
|
||||
console.log(`Total reserve: ${totalReserve} XRP`)
|
||||
|
||||
await client.disconnect()
|
||||
@@ -1,34 +0,0 @@
|
||||
|
||||
# Set up client ----------------------
|
||||
|
||||
from xrpl.clients import JsonRpcClient
|
||||
|
||||
client = JsonRpcClient("https://s.devnet.rippletest.net:51234")
|
||||
|
||||
# Look up reserve values ----------------------
|
||||
|
||||
from xrpl.models.requests import ServerInfo
|
||||
|
||||
response = client.request(ServerInfo())
|
||||
validated_ledger = response.result["info"]["validated_ledger"]
|
||||
|
||||
base_reserve = validated_ledger["reserve_base_xrp"]
|
||||
reserve_inc = validated_ledger["reserve_inc_xrp"]
|
||||
|
||||
print(f"Base reserve: {base_reserve} XRP")
|
||||
print(f"Incremental reserve: {reserve_inc} XRP")
|
||||
|
||||
# Look up owner count ----------------------
|
||||
|
||||
from xrpl.models.requests import AccountInfo
|
||||
|
||||
address = "rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh" # replace with any address
|
||||
response = client.request(AccountInfo(account=address))
|
||||
owner_count = response.result["account_data"]["OwnerCount"]
|
||||
|
||||
# Calculate total reserve ----------------------
|
||||
|
||||
total_reserve = base_reserve + (owner_count * reserve_inc)
|
||||
|
||||
print(f"Owner count: {owner_count}")
|
||||
print(f"Total reserve: {total_reserve} XRP")
|
||||
@@ -1,3 +0,0 @@
|
||||
# Delete Account
|
||||
|
||||
Delete an account from the XRP Ledger, removing its data and sending its XRP to another account.
|
||||
@@ -1,4 +0,0 @@
|
||||
# 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
|
||||
@@ -1,45 +0,0 @@
|
||||
# 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
|
||||
```
|
||||
@@ -1,205 +0,0 @@
|
||||
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()
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"name": "delete-account",
|
||||
"version": "1.0.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dotenv": "^17.3.1",
|
||||
"xrpl": "^4.6.0"
|
||||
},
|
||||
"type": "module"
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
# 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
|
||||
@@ -1,47 +0,0 @@
|
||||
# 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
|
||||
```
|
||||
@@ -1,199 +0,0 @@
|
||||
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))
|
||||
@@ -1,2 +0,0 @@
|
||||
xrpl-py==4.5.0
|
||||
python-dotenv==1.2.1
|
||||
@@ -1,395 +0,0 @@
|
||||
# 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!
|
||||
```
|
||||
@@ -1,210 +0,0 @@
|
||||
// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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
|
||||
)
|
||||
@@ -1,656 +0,0 @@
|
||||
// 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!")
|
||||
}
|
||||
@@ -1,195 +0,0 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
// 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")
|
||||
}
|
||||
}
|
||||
@@ -730,22 +730,12 @@ 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>
|
||||
<a
|
||||
href="https://discord.gg/xrpl"
|
||||
target="_blank"
|
||||
>
|
||||
{translate(
|
||||
"Join the XRPL Discord to connect and network with builders, validators, and cryptocurrency enthusiasts."
|
||||
)}
|
||||
</a>
|
||||
{translate(
|
||||
"Join the XRPL Discord to connect and network with builders, validators, and cryptocurrency enthusiasts."
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<a
|
||||
@@ -759,22 +749,12 @@ const CommunityPage: React.FC = () => {
|
||||
</tr>
|
||||
<tr>
|
||||
<td className="td-img">
|
||||
<a
|
||||
href="https://x.com/RippleXDev"
|
||||
target="_blank"
|
||||
>
|
||||
<img className="twitter-icon" alt="twitter icon" />
|
||||
</a>
|
||||
<img className="twitter-icon" alt="twitter icon" />
|
||||
</td>
|
||||
<td>
|
||||
<a
|
||||
href="https://x.com/RippleXDev"
|
||||
target="_blank"
|
||||
>
|
||||
{translate(
|
||||
"Follow @RippleXDev on X for the latest updates on the XRP Ledger ecosystem."
|
||||
)}
|
||||
</a>
|
||||
{translate(
|
||||
"Follow @RippleXDev on X for the latest updates on the XRP Ledger ecosystem."
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<a
|
||||
@@ -788,22 +768,12 @@ const CommunityPage: React.FC = () => {
|
||||
</tr>
|
||||
<tr>
|
||||
<td className="td-img">
|
||||
<a
|
||||
href="https://youtube.com/playlist?list=PLl-QsmXvjodqxEjtUqEv3u2o2Zd6zqkNA&feature=shared"
|
||||
target="_blank"
|
||||
>
|
||||
<img className="youtube-icon" alt="youtube icon" />
|
||||
</a>
|
||||
<img className="youtube-icon" alt="youtube icon" />
|
||||
</td>
|
||||
<td>
|
||||
<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>
|
||||
{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."
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<a
|
||||
@@ -817,22 +787,12 @@ 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
|
||||
|
||||
@@ -273,8 +273,6 @@
|
||||
[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
|
||||
@@ -372,7 +370,6 @@
|
||||
[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
|
||||
@@ -490,6 +487,5 @@
|
||||
[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
|
||||
|
||||
@@ -6,7 +6,7 @@ labels:
|
||||
---
|
||||
# Deleting Accounts
|
||||
|
||||
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).
|
||||
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).
|
||||
|
||||
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,32 +16,22 @@ 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 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 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 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 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.
|
||||
The following [ledger entry types](../../references/protocol/ledger-data/ledger-entry-types/index.md) are deletion blockers:
|
||||
|
||||
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.
|
||||
- `Escrow`
|
||||
- `PayChannel`
|
||||
- `RippleState` (trust line)
|
||||
- `Check`
|
||||
- `PermissionedDomain` {% amendment-disclaimer name="PermissionedDomains" /%}
|
||||
|
||||
| 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. |
|
||||
Any other types of ledger entries that an account owns are automatically deleted along with the account.
|
||||
|
||||
## Cost of Deleting
|
||||
|
||||
|
||||
@@ -45,8 +45,9 @@ Clawback is disabled by default. To use clawback, you must send an [AccountSet t
|
||||
|
||||
| Field | JSON Type | [Internal Type][] | Required | Description |
|
||||
|:----------|:---------------------|:------------------|:---------|:------------------|
|
||||
| `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][]). |
|
||||
| `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][]). |
|
||||
| `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. |
|
||||
|
||||
|
||||
@@ -1,150 +0,0 @@
|
||||
---
|
||||
seo:
|
||||
description: Look up and calculate base and owner reserve requirements for an XRPL account.
|
||||
labels:
|
||||
- Accounts
|
||||
---
|
||||
# Calculate Account Reserves
|
||||
|
||||
This tutorial demonstrates how to look up and calculate the [reserve requirements](https://xrpl.org/docs/concepts/accounts/reserves) for an XRP Ledger account. Reserves are the minimum amount of XRP an account must hold based on its activity on the ledger.
|
||||
|
||||
## Goals
|
||||
|
||||
By the end of this tutorial, you should be able to:
|
||||
- Look up an account's current [base](https://xrpl.org/docs/concepts/accounts/reserves#base-reserve-and-owner-reserve) and incremental reserve values.
|
||||
- Determine an account's [owner reserve](https://xrpl.org/docs/concepts/accounts/reserves#owner-reserves).
|
||||
- Calculate an account's total reserve requirement.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
To complete this tutorial, you need:
|
||||
|
||||
- A basic understanding of the XRP Ledger.
|
||||
- An XRP Ledger [client library](https://xrpl.org/docs/references/client-libraries) set up.
|
||||
|
||||
## Source Code
|
||||
|
||||
You can find this tutorial's example source code in the [code samples section of this website's repository](https://github.com/XRPLF/xrpl-dev-portal/tree/master/_code-samples/calculate-reserves).
|
||||
|
||||
## Steps
|
||||
|
||||
### 1. Install dependencies
|
||||
|
||||
Install dependencies for your language from the code sample folder.
|
||||
|
||||
{% tabs %}
|
||||
{% tab label="JavaScript" %}
|
||||
|
||||
```bash
|
||||
npm install xrpl
|
||||
```
|
||||
{% /tab %}
|
||||
{% tab label="Python" %}
|
||||
|
||||
```bash
|
||||
pip install xrpl-py
|
||||
```
|
||||
{% /tab %}
|
||||
{% tab label="Go" %}
|
||||
|
||||
```bash
|
||||
go mod tidy
|
||||
```
|
||||
{% /tab %}
|
||||
{% tab label="Java" %}
|
||||
```bash
|
||||
mvn compile
|
||||
```
|
||||
{% /tab %}
|
||||
{% /tabs %}
|
||||
|
||||
### 2. Set up client
|
||||
|
||||
Import the XRPL library and create a client connection to a testnet server.
|
||||
|
||||
{% tabs %}
|
||||
{% tab label="JavaScript" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/js/calculate_reserves.js" language="js" from="// Set up client" to="// Look up reserve values" /%}
|
||||
{% /tab %}
|
||||
{% tab label="Python" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/py/calculate_reserves.py" language="py" from="# Set up client" to="# Look up reserve values" /%}
|
||||
{% /tab %}
|
||||
{% tab label="Go" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/go/calculate_reserves.go" language="go" from="// Set up client" to="// Look up reserve values" /%}
|
||||
{% /tab %}
|
||||
{% tab label="Java" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/java/CalculateReserves.java" language="java" from="// Set up client" to="// Look up reserve values" /%}
|
||||
{% /tab %}
|
||||
{% /tabs %}
|
||||
|
||||
### 3. Look up reserve values
|
||||
|
||||
Retrieve the base and incremental reserve values using the [`server_info`](https://xrpl.org/docs/references/http-websocket-apis/public-api-methods/server-info-methods/server_info) or [`server_state`](https://xrpl.org/docs/references/http-websocket-apis/public-api-methods/server-info-methods/server_state) method. This example uses `server_info` to return values in decimal XRP instead of integer drops.
|
||||
|
||||
{% tabs %}
|
||||
{% tab label="JavaScript" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/js/calculate_reserves.js" language="js" from="// Look up reserve values" to="// Look up owner count"/%}
|
||||
{% /tab %}
|
||||
{% tab label="Python" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/py/calculate_reserves.py" language="py" from="# Look up reserve values" to="# Look up owner count"/%}
|
||||
{% /tab %}
|
||||
{% tab label="Go" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/go/calculate_reserves.go" language="go" from="// Look up reserve values" to="// Look up owner count"/%}
|
||||
{% /tab %}
|
||||
{% tab label="Java" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/java/CalculateReserves.java" language="java" from="// Look up reserve values" to="// Look up owner count" /%}
|
||||
{% /tab %}
|
||||
{% /tabs %}
|
||||
|
||||
### 4. Determine owner reserve
|
||||
|
||||
Once you have the incremental reserve value, multiply that by the number of objects the account owns to determine the owner reserve. You can call [`account_info`](https://xrpl.org/docs/references/http-websocket-apis/public-api-methods/account-methods/account_info) and take `account_data.OwnerCount` to retrieve an account's total number of objects.
|
||||
|
||||
{% tabs %}
|
||||
{% tab label="JavaScript" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/js/calculate_reserves.js" language="js" from="// Look up owner count" to="// Calculate total reserve"/%}
|
||||
{% /tab %}
|
||||
{% tab label="Python" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/py/calculate_reserves.py" language="py" from="# Look up owner count" to="# Calculate total reserve"/%}
|
||||
{% /tab %}
|
||||
{% tab label="Go" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/go/calculate_reserves.go" language="go" from="// Look up owner count" to="// Calculate total reserve" /%}
|
||||
{% /tab %}
|
||||
{% tab label="Java" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/java/CalculateReserves.java" language="java" from="// Look up owner count" to="// Calculate total reserve" /%}
|
||||
{% /tab %}
|
||||
{% /tabs %}
|
||||
|
||||
### 5. Calculate total reserve
|
||||
|
||||
Use the following formula to calculate an account's total reserve requirement:
|
||||
|
||||
`total reserve = reserve_base_xrp + (OwnerCount × reserve_inc_xrp)`
|
||||
|
||||
{% tabs %}
|
||||
{% tab label="JavaScript" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/js/calculate_reserves.js" language="js" from="// Calculate total reserve"/%}
|
||||
{% /tab %}
|
||||
{% tab label="Python" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/py/calculate_reserves.py" language="py" from="# Calculate total reserve"/%}
|
||||
{% /tab %}
|
||||
{% tab label="Go" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/go/calculate_reserves.go" language="go" from="// Calculate total reserve" /%}
|
||||
{% /tab %}
|
||||
{% tab label="Java" %}
|
||||
{% code-snippet file="/_code-samples/calculate-reserves/java/CalculateReserves.java" language="java" from="// Calculate total reserve" /%}
|
||||
{% /tab %}
|
||||
{% /tabs %}
|
||||
|
||||
## See Also
|
||||
|
||||
Concepts:
|
||||
- [Reserves](https://xrpl.org/docs/concepts/accounts/reserves)
|
||||
|
||||
Tutorials:
|
||||
- [Calculate and Display the Reserve Requirement (Python)](https://xrpl.org/docs/tutorials/sample-apps/build-a-desktop-wallet-in-python#3-display-an-account)
|
||||
|
||||
References:
|
||||
- [server_info](https://xrpl.org/docs/references/http-websocket-apis/public-api-methods/server-info-methods/server_info)
|
||||
- [server_state](https://xrpl.org/docs/references/http-websocket-apis/public-api-methods/server-info-methods/server_state)
|
||||
- [account_info](https://xrpl.org/docs/references/http-websocket-apis/public-api-methods/account-methods/account_info)
|
||||
@@ -1,240 +0,0 @@
|
||||
---
|
||||
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" /%}
|
||||
@@ -31,7 +31,6 @@ 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,13 +57,6 @@ 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
|
||||
@@ -85,13 +77,6 @@ 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.
|
||||
@@ -107,11 +92,6 @@ 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
|
||||
@@ -125,9 +105,6 @@ 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.
|
||||
@@ -147,11 +124,6 @@ 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.
|
||||
@@ -167,9 +139,6 @@ 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.
|
||||
@@ -185,9 +154,6 @@ 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
|
||||
@@ -201,9 +167,6 @@ 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.
|
||||
@@ -219,9 +182,6 @@ 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`.
|
||||
@@ -237,9 +197,6 @@ 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.
|
||||
@@ -255,9 +212,6 @@ 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
|
||||
|
||||
@@ -30,7 +30,6 @@ 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,13 +56,6 @@ 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
|
||||
@@ -84,13 +76,6 @@ 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.
|
||||
@@ -106,11 +91,6 @@ 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
|
||||
@@ -124,9 +104,6 @@ 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).
|
||||
@@ -142,9 +119,6 @@ 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.
|
||||
@@ -160,9 +134,6 @@ 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.
|
||||
|
||||
@@ -33,7 +33,6 @@ 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
|
||||
|
||||
@@ -60,13 +59,6 @@ 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
|
||||
@@ -87,13 +79,6 @@ 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.
|
||||
@@ -109,11 +94,6 @@ 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
|
||||
@@ -149,20 +129,6 @@ 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
|
||||
@@ -176,9 +142,6 @@ 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
|
||||
@@ -192,9 +155,6 @@ 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
|
||||
@@ -208,9 +168,6 @@ 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.
|
||||
@@ -226,9 +183,6 @@ 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
|
||||
|
||||
@@ -32,7 +32,6 @@ 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,13 +58,6 @@ 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
|
||||
@@ -86,13 +78,6 @@ 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.
|
||||
@@ -108,11 +93,6 @@ 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
|
||||
@@ -130,11 +110,6 @@ 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.
|
||||
@@ -150,9 +125,6 @@ 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.
|
||||
@@ -168,9 +140,6 @@ 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.
|
||||
@@ -186,9 +155,6 @@ 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
|
||||
@@ -202,9 +168,6 @@ 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.
|
||||
@@ -220,9 +183,6 @@ 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.
|
||||
|
||||
@@ -33,7 +33,6 @@ 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
|
||||
|
||||
@@ -60,13 +59,6 @@ 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
|
||||
@@ -88,14 +80,6 @@ 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.
|
||||
@@ -111,11 +95,6 @@ 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
|
||||
@@ -129,9 +108,6 @@ 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.
|
||||
@@ -147,9 +123,6 @@ 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
|
||||
@@ -163,9 +136,6 @@ 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.
|
||||
@@ -181,9 +151,6 @@ 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.
|
||||
@@ -199,9 +166,6 @@ 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
|
||||
@@ -215,9 +179,6 @@ 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
|
||||
@@ -231,9 +192,6 @@ 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.
|
||||
@@ -249,9 +207,6 @@ 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.
|
||||
|
||||
@@ -33,7 +33,6 @@ 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
|
||||
|
||||
@@ -60,13 +59,6 @@ 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
|
||||
@@ -87,14 +79,6 @@ 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.
|
||||
@@ -110,11 +94,6 @@ 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
|
||||
@@ -128,9 +107,6 @@ 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.
|
||||
@@ -150,9 +126,6 @@ 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
|
||||
@@ -166,9 +139,6 @@ 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.
|
||||
@@ -184,9 +154,6 @@ 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.
|
||||
@@ -202,9 +169,6 @@ 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.
|
||||
@@ -220,9 +184,6 @@ 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.
|
||||
@@ -238,9 +199,6 @@ 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.
|
||||
|
||||
@@ -28,7 +28,7 @@ To learn about MPTs in general, go to the **Concept** page. For developer-focuse
|
||||
{% card-grid %}
|
||||
|
||||
{% xrpl-card title="Concept: Multi‑Purpose 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 Multi‑Purpose Token" body="Step‑by‑step, hands‑on tutorial to issue an MPT using the XRP Ledger SDKs." href="docs/tutorials/tokens/mpts/issue-a-multi-purpose-token" /%}
|
||||
{% xrpl-card title="Tutorial: Issue a Multi‑Purpose Token" body="Step‑by‑step, hands‑on tutorial to issue an MPT using the XRP Ledger SDKs." href="docs/tutorials/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 %}
|
||||
|
||||
|
||||
1237
package-lock.json
generated
1237
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -15,7 +15,7 @@
|
||||
"@codemirror/state": "6.5.2",
|
||||
"@codemirror/view": "^6.22.2",
|
||||
"@lezer/highlight": "^1.2.0",
|
||||
"@redocly/realm": "0.131.2",
|
||||
"@redocly/realm": "0.130.4",
|
||||
"@uiw/codemirror-themes": "4.21.21",
|
||||
"@uiw/react-codemirror": "^4.21.21",
|
||||
"@xrplf/isomorphic": "^1.0.0-beta.1",
|
||||
@@ -30,7 +30,7 @@
|
||||
"react18-json-view": "^0.2.6",
|
||||
"smol-toml": "^1.3.1",
|
||||
"use-query-params": "^2.2.1",
|
||||
"xrpl": "^4.6.0"
|
||||
"xrpl": "^4.2.5"
|
||||
},
|
||||
"overrides": {
|
||||
"react": "^19.1.0",
|
||||
|
||||
@@ -6,6 +6,7 @@ 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:
|
||||
|
||||
697
tools/generate-release-notes.py
Normal file
697
tools/generate-release-notes.py
Normal file
@@ -0,0 +1,697 @@
|
||||
"""
|
||||
Generate rippled release notes from GitHub commit history.
|
||||
|
||||
Usage (from repo root):
|
||||
python3 tools/generate-release-notes.py --from release-3.0 --to release-3.1 [--date 2026-03-24] [--output path/to/file.md]
|
||||
|
||||
Arguments:
|
||||
--from (required) Base ref — must match exact tag or branch to compare from.
|
||||
--to (required) Target ref — must match exact tag or branch to compare to.
|
||||
--date (optional) Release date in YYYY-MM-DD format. Defaults to today.
|
||||
--output (optional) Output file path. Defaults to blog/<year>/rippled-<version>.md.
|
||||
|
||||
Requires: gh CLI (authenticated)
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import date, datetime
|
||||
|
||||
|
||||
# Emails to exclude from credits (Ripple employees not using @ripple.com).
|
||||
# Commits from @ripple.com addresses are already filtered automatically.
|
||||
EXCLUDED_EMAILS = {
|
||||
"3maisons@gmail.com", # Luc des Trois Maisons
|
||||
"a1q123456@users.noreply.github.com", # Jingchen Wu
|
||||
"bthomee@users.noreply.github.com", # Bart Thomee
|
||||
"21219765+ckeshava@users.noreply.github.com", # Chenna Keshava B S
|
||||
"gregtatcam@users.noreply.github.com", # Gregory Tsipenyuk
|
||||
"kuzzz99@gmail.com", # Sergey Kuznetsov
|
||||
"legleux@users.noreply.github.com", # Michael Legleux
|
||||
"mathbunnyru@users.noreply.github.com", # Ayaz Salikhov
|
||||
"mvadari@gmail.com", # Mayukha Vadari
|
||||
"115580134+oleks-rip@users.noreply.github.com", # Oleksandr Pidskopnyi
|
||||
"3397372+pratikmankawde@users.noreply.github.com", # Pratik Mankawde
|
||||
"35279399+shawnxie999@users.noreply.github.com", # Shawn Xie
|
||||
"5780819+Tapanito@users.noreply.github.com", # Vito Tumas
|
||||
"13349202+vlntb@users.noreply.github.com", # Valentin Balaschenko
|
||||
"129996061+vvysokikh1@users.noreply.github.com", # Vladislav Vysokikh
|
||||
"vvysokikh@gmail.com", # Vladislav Vysokikh
|
||||
}
|
||||
|
||||
|
||||
# Pre-compiled patterns for skipping version commits
|
||||
SKIP_PATTERNS = [
|
||||
re.compile(r"^Set version to", re.IGNORECASE),
|
||||
re.compile(r"^Version \d", re.IGNORECASE),
|
||||
re.compile(r"bump version to", re.IGNORECASE),
|
||||
re.compile(r"^Merge tag ", re.IGNORECASE),
|
||||
]
|
||||
|
||||
|
||||
# --- API helpers ---
|
||||
|
||||
def run_gh_rest(endpoint):
|
||||
"""Run a gh api REST command and return parsed JSON."""
|
||||
result = subprocess.run(
|
||||
["gh", "api", endpoint],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
print(f"Error running gh api: {result.stderr}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def run_gh_graphql(query):
|
||||
"""Run a gh api graphql command and return parsed JSON.
|
||||
Handles partial failures (e.g., missing PRs) by returning
|
||||
whatever data is available alongside errors.
|
||||
"""
|
||||
result = subprocess.run(
|
||||
["gh", "api", "graphql", "-f", f"query={query}"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
try:
|
||||
return json.loads(result.stdout)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
print(f"Error running graphql: {result.stderr}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def fetch_commit_files(sha):
|
||||
"""Fetch list of files changed in a commit via REST API.
|
||||
Returns empty list on failure instead of exiting.
|
||||
"""
|
||||
result = subprocess.run(
|
||||
["gh", "api", f"repos/XRPLF/rippled/commits/{sha}"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if result.returncode != 0:
|
||||
print(f" Warning: Could not fetch files for commit {sha[:7]}", file=sys.stderr)
|
||||
return []
|
||||
data = json.loads(result.stdout)
|
||||
return [f["filename"] for f in data.get("files", [])]
|
||||
|
||||
|
||||
# --- Data fetching ---
|
||||
|
||||
def fetch_version_info(ref):
|
||||
"""Fetch version string and version-setting commit info in a single GraphQL call.
|
||||
Returns (version_string, formatted_commit_block).
|
||||
"""
|
||||
data = run_gh_graphql(f"""
|
||||
{{
|
||||
repository(owner: "XRPLF", name: "rippled") {{
|
||||
file: object(expression: "{ref}:src/libxrpl/protocol/BuildInfo.cpp") {{
|
||||
... on Blob {{ text }}
|
||||
}}
|
||||
ref: object(expression: "{ref}") {{
|
||||
... on Commit {{
|
||||
history(first: 1, path: "src/libxrpl/protocol/BuildInfo.cpp") {{
|
||||
nodes {{
|
||||
oid
|
||||
message
|
||||
author {{
|
||||
name
|
||||
email
|
||||
date
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
}}
|
||||
""")
|
||||
repo = data.get("data", {}).get("repository", {})
|
||||
|
||||
# Extract version string from BuildInfo.cpp
|
||||
file_text = (repo.get("file") or {}).get("text", "")
|
||||
match = re.search(r'versionString\s*=\s*"([^"]+)"', file_text)
|
||||
if not match:
|
||||
print("Warning: Could not find versionString in BuildInfo.cpp. Using placeholder.", file=sys.stderr)
|
||||
version = match.group(1) if match else "TODO"
|
||||
|
||||
# Extract version commit info
|
||||
nodes = (repo.get("ref") or {}).get("history", {}).get("nodes", [])
|
||||
if not nodes:
|
||||
commit_block = "commit TODO\nAuthor: TODO\nDate: TODO\n\n Set version to TODO"
|
||||
else:
|
||||
commit = nodes[0]
|
||||
raw_date = commit["author"]["date"]
|
||||
try:
|
||||
dt = datetime.fromisoformat(raw_date)
|
||||
formatted_date = dt.strftime("%a %b %-d %H:%M:%S %Y %z")
|
||||
except ValueError:
|
||||
formatted_date = raw_date
|
||||
|
||||
name = commit["author"]["name"]
|
||||
email = commit["author"]["email"]
|
||||
sha = commit["oid"]
|
||||
message = commit["message"].split("\n")[0]
|
||||
commit_block = f"commit {sha}\nAuthor: {name} <{email}>\nDate: {formatted_date}\n\n {message}"
|
||||
|
||||
return version, commit_block
|
||||
|
||||
|
||||
def fetch_commits(from_ref, to_ref):
|
||||
"""Fetch all commits between two refs using the GitHub compare API."""
|
||||
commits = []
|
||||
page = 1
|
||||
while True:
|
||||
data = run_gh_rest(
|
||||
f"repos/XRPLF/rippled/compare/{from_ref}...{to_ref}?per_page=250&page={page}"
|
||||
)
|
||||
batch = data.get("commits", [])
|
||||
commits.extend(batch)
|
||||
if len(batch) < 250:
|
||||
break
|
||||
page += 1
|
||||
return commits
|
||||
|
||||
|
||||
def parse_features_macro(text):
|
||||
"""Parse features.macro into {amendment_name: status_string} dict."""
|
||||
results = {}
|
||||
for match in re.finditer(
|
||||
r'XRPL_(FEATURE|FIX)\s*\(\s*(\w+)\s*,\s*Supported::(\w+)\s*,\s*VoteBehavior::(\w+)', text):
|
||||
macro_type, name, supported, vote = match.groups()
|
||||
key = f"fix{name}" if macro_type == "FIX" else name
|
||||
results[key] = f"{supported}, {vote}"
|
||||
for match in re.finditer(r'XRPL_RETIRE(?:_(FEATURE|FIX))?\s*\(\s*(\w+)\s*\)', text):
|
||||
macro_type, name = match.groups()
|
||||
key = f"fix{name}" if macro_type == "FIX" else name
|
||||
results[key] = "retired"
|
||||
return results
|
||||
|
||||
|
||||
def fetch_amendment_diff(from_ref, to_ref):
|
||||
"""Compare features.macro between two refs to find amendment changes.
|
||||
Returns (changes, unchanged) where:
|
||||
- changes: {name: True/False} for amendments that changed status
|
||||
- unchanged: {name: True/False} for amendments with no status change
|
||||
True = include; False = exclude
|
||||
"""
|
||||
macro_path = "repos/XRPLF/rippled/contents/include/xrpl/protocol/detail/features.macro"
|
||||
|
||||
from_data = run_gh_rest(f"{macro_path}?ref={from_ref}")
|
||||
from_text = base64.b64decode(from_data["content"]).decode()
|
||||
from_amendments = parse_features_macro(from_text)
|
||||
|
||||
to_data = run_gh_rest(f"{macro_path}?ref={to_ref}")
|
||||
to_text = base64.b64decode(to_data["content"]).decode()
|
||||
to_amendments = parse_features_macro(to_text)
|
||||
|
||||
changes = {}
|
||||
for name, to_status in to_amendments.items():
|
||||
if name not in from_amendments:
|
||||
# New amendment — include only if Supported::yes
|
||||
changes[name] = to_status.startswith("yes")
|
||||
elif from_amendments[name] != to_status:
|
||||
# Include if either old or new status involves yes (voting-ready)
|
||||
from_status = from_amendments[name]
|
||||
changes[name] = from_status.startswith("yes") or to_status.startswith("yes")
|
||||
|
||||
# Removed amendments — include only if they were Supported::yes
|
||||
for name in from_amendments:
|
||||
if name not in to_amendments:
|
||||
changes[name] = from_amendments[name].startswith("yes")
|
||||
|
||||
# Unchanged amendments to also exclude (unreleased work)
|
||||
unchanged = sorted(
|
||||
name for name, to_status in to_amendments.items()
|
||||
if name not in changes and to_status != "retired" and not to_status.startswith("yes")
|
||||
)
|
||||
|
||||
return changes, unchanged
|
||||
|
||||
|
||||
def fetch_prs_graphql(pr_numbers):
|
||||
"""Fetch PR details in batches using GitHub GraphQL API.
|
||||
Falls back to issue lookup for numbers that aren't PRs.
|
||||
Returns a dict of {number: {title, body, labels, files, type}}.
|
||||
"""
|
||||
results = {}
|
||||
missing = []
|
||||
batch_size = 50
|
||||
pr_list = list(pr_numbers)
|
||||
|
||||
# Fetch PRs
|
||||
for i in range(0, len(pr_list), batch_size):
|
||||
batch = pr_list[i:i + batch_size]
|
||||
|
||||
fragments = []
|
||||
for pr_num in batch:
|
||||
fragments.append(f"""
|
||||
pr{pr_num}: pullRequest(number: {pr_num}) {{
|
||||
title
|
||||
body
|
||||
labels(first: 10) {{
|
||||
nodes {{ name }}
|
||||
}}
|
||||
files(first: 100) {{
|
||||
nodes {{ path }}
|
||||
}}
|
||||
}}
|
||||
""")
|
||||
|
||||
query = f"""
|
||||
{{
|
||||
repository(owner: "XRPLF", name: "rippled") {{
|
||||
{"".join(fragments)}
|
||||
}}
|
||||
}}
|
||||
"""
|
||||
|
||||
data = run_gh_graphql(query)
|
||||
repo_data = data.get("data", {}).get("repository", {})
|
||||
|
||||
for alias, pr_data in repo_data.items():
|
||||
pr_num = int(alias.removeprefix("pr"))
|
||||
if pr_data:
|
||||
results[pr_num] = {
|
||||
"title": pr_data["title"],
|
||||
"body": clean_pr_body(pr_data.get("body") or ""),
|
||||
"labels": [l["name"] for l in pr_data.get("labels", {}).get("nodes", [])],
|
||||
"files": [f["path"] for f in pr_data.get("files", {}).get("nodes", [])],
|
||||
"type": "pull",
|
||||
}
|
||||
else:
|
||||
missing.append(pr_num)
|
||||
|
||||
print(f" Fetched {min(i + batch_size, len(pr_list))}/{len(pr_list)} PRs...")
|
||||
|
||||
# Fetch missing numbers as issues
|
||||
if missing:
|
||||
print(f" Looking up {len(missing)} missing PR numbers as Issues...")
|
||||
for i in range(0, len(missing), batch_size):
|
||||
batch = missing[i:i + batch_size]
|
||||
|
||||
fragments = []
|
||||
for num in batch:
|
||||
fragments.append(f"""
|
||||
issue{num}: issue(number: {num}) {{
|
||||
title
|
||||
body
|
||||
labels(first: 10) {{
|
||||
nodes {{ name }}
|
||||
}}
|
||||
}}
|
||||
""")
|
||||
|
||||
query = f"""
|
||||
{{
|
||||
repository(owner: "XRPLF", name: "rippled") {{
|
||||
{"".join(fragments)}
|
||||
}}
|
||||
}}
|
||||
"""
|
||||
|
||||
data = run_gh_graphql(query)
|
||||
repo_data = data.get("data", {}).get("repository", {})
|
||||
|
||||
for alias, issue_data in repo_data.items():
|
||||
if issue_data:
|
||||
num = int(alias.removeprefix("issue"))
|
||||
results[num] = {
|
||||
"title": issue_data["title"],
|
||||
"body": clean_pr_body(issue_data.get("body") or ""),
|
||||
"labels": [l["name"] for l in issue_data.get("labels", {}).get("nodes", [])],
|
||||
"type": "issues",
|
||||
}
|
||||
|
||||
return results
|
||||
|
||||
|
||||
# --- Utilities ---
|
||||
|
||||
def clean_pr_body(text):
|
||||
"""Strip HTML comments and PR template boilerplate from body text."""
|
||||
# Remove HTML comments
|
||||
text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)
|
||||
# Remove unchecked checkbox lines, keep checked ones
|
||||
text = re.sub(r"^- \[ \] .+$", "", text, flags=re.MULTILINE)
|
||||
# Remove all markdown headings
|
||||
text = re.sub(r"^#{1,6} .+$", "", text, flags=re.MULTILINE)
|
||||
# Convert bare GitHub URLs to markdown links
|
||||
text = re.sub(r"(?<!\()https://github\.com/XRPLF/rippled/(pull|issues)/(\d+)(#[^\s)]*)?", r"[#\2](https://github.com/XRPLF/rippled/\1/\2\3)", text)
|
||||
# Convert remaining bare PR/issue references (#1234) to full GitHub links
|
||||
text = re.sub(r"(?<!\[)#(\d+)(?!\])", r"[#\1](https://github.com/XRPLF/rippled/pull/\1)", text)
|
||||
# Collapse multiple blank lines into one
|
||||
text = re.sub(r"\n{3,}", "\n\n", text)
|
||||
return text.strip()
|
||||
|
||||
|
||||
def extract_pr_number(commit_message):
|
||||
"""Extract PR number from commit message like 'Title (#1234)'."""
|
||||
match = re.search(r"#(\d+)", commit_message)
|
||||
return int(match.group(1)) if match else None
|
||||
|
||||
|
||||
def should_skip(title):
|
||||
"""Check if a commit should be skipped."""
|
||||
return any(pattern.search(title) for pattern in SKIP_PATTERNS)
|
||||
|
||||
|
||||
def is_amendment(files):
|
||||
"""Check if any file in the list is features.macro."""
|
||||
return any("features.macro" in f for f in files)
|
||||
|
||||
|
||||
# --- Formatting ---
|
||||
|
||||
def format_commit_entry(sha, title, body="", files=None):
|
||||
"""Format an entry linked to a commit (no PR/Issue found)."""
|
||||
short_sha = sha[:7]
|
||||
url = f"https://github.com/XRPLF/rippled/commit/{sha}"
|
||||
parts = [
|
||||
f"- **{title.strip()}**",
|
||||
f" - Link: [{short_sha}]({url})",
|
||||
]
|
||||
if files:
|
||||
parts.append(f" - Files: {', '.join(files)}")
|
||||
if body:
|
||||
desc = re.sub(r"\s+", " ", clean_pr_body(body)).strip()
|
||||
if desc:
|
||||
parts.append(f" - Description: {desc}")
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def format_uncategorized_entry(pr_number, title, labels, body, files=None, link_type="pull"):
|
||||
"""Format an uncategorized entry with full context for AI sorting."""
|
||||
url = f"https://github.com/XRPLF/rippled/{link_type}/{pr_number}"
|
||||
parts = [
|
||||
f"- **{title.strip()}**",
|
||||
f" - Link: [#{pr_number}]({url})",
|
||||
]
|
||||
if labels:
|
||||
parts.append(f" - Labels: {', '.join(labels)}")
|
||||
if files:
|
||||
parts.append(f" - Files: {', '.join(files)}")
|
||||
if body:
|
||||
# Collapse to single line to prevent markdown formatting conflicts
|
||||
desc = re.sub(r"\s+", " ", body).strip()
|
||||
if desc:
|
||||
parts.append(f" - Description: {desc}")
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def generate_markdown(version, release_date, amendment_diff, amendment_unchanged, amendment_entries, entries, authors, version_commit):
|
||||
"""Generate the full markdown release notes."""
|
||||
year = release_date.split("-")[0]
|
||||
parts = []
|
||||
|
||||
parts.append(f"""---
|
||||
category: {year}
|
||||
date: "{release_date}"
|
||||
template: '../../@theme/templates/blogpost'
|
||||
seo:
|
||||
title: Introducing XRP Ledger version {version}
|
||||
description: rippled version {version} is now available.
|
||||
labels:
|
||||
- rippled Release Notes
|
||||
markdown:
|
||||
editPage:
|
||||
hide: true
|
||||
---
|
||||
# Introducing XRP Ledger version {version}
|
||||
|
||||
Version {version} of `rippled`, the reference server implementation of the XRP Ledger protocol, is now available.
|
||||
|
||||
|
||||
## Action Required
|
||||
|
||||
If you run an XRP Ledger server, upgrade to version {version} as soon as possible to ensure service continuity.
|
||||
|
||||
|
||||
## Install / Upgrade
|
||||
|
||||
On supported platforms, see the [instructions on installing or updating `rippled`](../../docs/infrastructure/installation/index.md).
|
||||
|
||||
| Package | SHA-256 |
|
||||
|:--------|:--------|
|
||||
| [RPM for Red Hat / CentOS (x86-64)](https://repos.ripple.com/repos/rippled-rpm/stable/rippled-{version}-1.el9.x86_64.rpm) | `TODO` |
|
||||
| [DEB for Ubuntu / Debian (x86-64)](https://repos.ripple.com/repos/rippled-deb/pool/stable/rippled_{version}-1_amd64.deb) | `TODO` |
|
||||
|
||||
For other platforms, please [build from source](https://github.com/XRPLF/rippled/blob/master/BUILD.md). The most recent commit in the git log should be the change setting the version:
|
||||
|
||||
```text
|
||||
{version_commit}
|
||||
```
|
||||
|
||||
|
||||
## Full Changelog
|
||||
""")
|
||||
|
||||
# Amendments section (auto-sorted by features.macro detection with diff guidance for AI)
|
||||
parts.append("\n### Amendments\n")
|
||||
if amendment_diff or amendment_unchanged:
|
||||
included = sorted(name for name, include in amendment_diff.items() if include)
|
||||
excluded = sorted(name for name, include in amendment_diff.items() if not include)
|
||||
comment_lines = ["<!-- Amendment sorting instructions. Remove this comment after sorting."]
|
||||
if included:
|
||||
comment_lines.append(f"Include: {', '.join(included)}")
|
||||
if excluded:
|
||||
comment_lines.append(f"Exclude: {', '.join(excluded)}")
|
||||
if amendment_unchanged:
|
||||
comment_lines.append(f"Other amendments not part of this release: {', '.join(amendment_unchanged)}")
|
||||
comment_lines.append("-->")
|
||||
parts.append("\n".join(comment_lines) + "\n")
|
||||
for entry in amendment_entries:
|
||||
parts.append(entry)
|
||||
|
||||
# Remaining empty subsection headings for manual/AI sorting
|
||||
sections = [
|
||||
"Features", "Breaking Changes", "Bug Fixes",
|
||||
"Refactors", "Documentation", "Testing", "CI/Build",
|
||||
]
|
||||
for section in sections:
|
||||
parts.append(f"\n### {section}\n")
|
||||
|
||||
# Credits
|
||||
parts.append("\n\n## Credits\n")
|
||||
if authors:
|
||||
parts.append("The following RippleX teams and GitHub users contributed to this release:\n")
|
||||
else:
|
||||
parts.append("The following RippleX teams contributed to this release:\n")
|
||||
parts.append("- RippleX Engineering")
|
||||
parts.append("- RippleX Docs")
|
||||
parts.append("- RippleX Product")
|
||||
for author in sorted(authors):
|
||||
parts.append(f"- {author}")
|
||||
|
||||
parts.append("""
|
||||
|
||||
## Bug Bounties and Responsible Disclosures
|
||||
|
||||
We welcome reviews of the `rippled` code and urge researchers to responsibly disclose any issues they may find.
|
||||
|
||||
For more information, see:
|
||||
|
||||
- [Ripple's Bug Bounty Program](https://ripple.com/legal/bug-bounty/)
|
||||
- [`rippled` Security Policy](https://github.com/XRPLF/rippled/blob/develop/SECURITY.md)
|
||||
""")
|
||||
|
||||
# Unsorted entries with full context (after all published sections)
|
||||
parts.append("<!-- Sort the entries below into the Full Changelog subsections. Remove this comment after sorting. -->\n")
|
||||
for entry in entries:
|
||||
parts.append(entry)
|
||||
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
# --- Main ---
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Generate rippled release notes")
|
||||
parser.add_argument("--from", dest="from_ref", required=True, help="Base ref (tag or branch)")
|
||||
parser.add_argument("--to", dest="to_ref", required=True, help="Target ref (tag or branch)")
|
||||
parser.add_argument("--date", help="Release date (YYYY-MM-DD). Defaults to today.")
|
||||
parser.add_argument("--output", help="Output file path (default: blog/<year>/rippled-<version>.md)")
|
||||
args = parser.parse_args()
|
||||
|
||||
args.date = args.date or date.today().isoformat()
|
||||
try:
|
||||
date.fromisoformat(args.date)
|
||||
except ValueError:
|
||||
print(f"Error: Invalid date format '{args.date}'. Use YYYY-MM-DD.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Fetching version info from {args.to_ref}...")
|
||||
version, version_commit = fetch_version_info(args.to_ref)
|
||||
print(f"Version: {version}")
|
||||
|
||||
year = args.date.split("-")[0]
|
||||
output_path = args.output or f"blog/{year}/rippled-{version}.md"
|
||||
|
||||
print(f"Fetching commits: {args.from_ref}...{args.to_ref}")
|
||||
commits = fetch_commits(args.from_ref, args.to_ref)
|
||||
print(f"Found {len(commits)} commits")
|
||||
|
||||
# Extract unique PR (in rare cases Issues) numbers and track authors
|
||||
pr_numbers = {}
|
||||
pr_shas = {} # PR/issue number → commit SHA (for file lookups on Issues)
|
||||
pr_bodies = {} # PR/issue number → commit body (for fallback descriptions)
|
||||
orphan_commits = [] # Commits with no PR/Issues link
|
||||
authors = set()
|
||||
|
||||
for commit in commits:
|
||||
full_message = commit["commit"]["message"]
|
||||
message = full_message.split("\n")[0]
|
||||
body = "\n".join(full_message.split("\n")[1:]).strip()
|
||||
sha = commit["sha"]
|
||||
author = commit["commit"]["author"]["name"]
|
||||
email = commit["commit"]["author"].get("email", "")
|
||||
|
||||
# Skip Ripple employees from credits
|
||||
login = (commit.get("author") or {}).get("login")
|
||||
if not email.lower().endswith("@ripple.com") and email not in EXCLUDED_EMAILS:
|
||||
if login:
|
||||
authors.add(f"@{login}")
|
||||
else:
|
||||
authors.add(author)
|
||||
|
||||
if should_skip(message):
|
||||
continue
|
||||
|
||||
pr_number = extract_pr_number(message)
|
||||
if pr_number:
|
||||
pr_numbers[pr_number] = message
|
||||
pr_shas[pr_number] = sha
|
||||
pr_bodies[pr_number] = body
|
||||
else:
|
||||
orphan_commits.append({"sha": sha, "message": message, "body": body})
|
||||
|
||||
print(f"Unique PRs after filtering: {len(pr_numbers)}")
|
||||
if orphan_commits:
|
||||
print(f"Commits without PR or Issue linked: {len(orphan_commits)}")
|
||||
# Fetch amendment diff between refs
|
||||
print(f"Comparing features.macro between {args.from_ref} and {args.to_ref}...")
|
||||
amendment_diff, amendment_unchanged = fetch_amendment_diff(args.from_ref, args.to_ref)
|
||||
if amendment_diff:
|
||||
for name, include in sorted(amendment_diff.items()):
|
||||
status = "include" if include else "exclude"
|
||||
print(f" Amendment {name}: {status}")
|
||||
else:
|
||||
print(" No amendment changes detected")
|
||||
|
||||
print(f"Building changelog entries...")
|
||||
|
||||
# Fetch all PR details in batches via GraphQL
|
||||
pr_details = fetch_prs_graphql(list(pr_numbers.keys()))
|
||||
|
||||
# Build entries, sorting amendments automatically
|
||||
amendment_entries = []
|
||||
entries = []
|
||||
for pr_number, commit_msg in pr_numbers.items():
|
||||
pr_data = pr_details.get(pr_number)
|
||||
|
||||
if pr_data:
|
||||
title = pr_data["title"]
|
||||
body = pr_data.get("body", "")
|
||||
labels = pr_data.get("labels", [])
|
||||
files = pr_data.get("files", [])
|
||||
link_type = pr_data.get("type", "pull")
|
||||
|
||||
# For issues (no files from GraphQL), fetch files from the commit
|
||||
if not files and pr_number in pr_shas:
|
||||
print(f" Building entry for Issue #{pr_number} via commit...")
|
||||
files = fetch_commit_files(pr_shas[pr_number])
|
||||
|
||||
if is_amendment(files) and amendment_diff:
|
||||
# Amendment entry — add to amendments section (AI will sort further)
|
||||
entry = format_uncategorized_entry(pr_number, title, labels, body, link_type=link_type)
|
||||
amendment_entries.append(entry)
|
||||
else:
|
||||
entry = format_uncategorized_entry(pr_number, title, labels, body, files, link_type)
|
||||
entries.append(entry)
|
||||
else:
|
||||
# Fallback to commit lookup for invalid PR and Issues link
|
||||
sha = pr_shas[pr_number]
|
||||
print(f" #{pr_number} not found as PR or Issue, building from commit {sha[:7]}...")
|
||||
files = fetch_commit_files(sha)
|
||||
if is_amendment(files) and amendment_diff:
|
||||
entry = format_commit_entry(sha, commit_msg, pr_bodies[pr_number])
|
||||
amendment_entries.append(entry)
|
||||
else:
|
||||
entry = format_commit_entry(sha, commit_msg, pr_bodies[pr_number], files)
|
||||
entries.append(entry)
|
||||
|
||||
# Build entries for orphan commits (no PR/Issue linked)
|
||||
for orphan in orphan_commits:
|
||||
sha = orphan["sha"]
|
||||
print(f" Building commit-only entry for {sha[:7]}...")
|
||||
files = fetch_commit_files(sha)
|
||||
if is_amendment(files) and amendment_diff:
|
||||
entry = format_commit_entry(sha, orphan["message"], orphan["body"])
|
||||
amendment_entries.append(entry)
|
||||
else:
|
||||
entry = format_commit_entry(sha, orphan["message"], orphan["body"], files)
|
||||
entries.append(entry)
|
||||
|
||||
# Generate markdown
|
||||
markdown = generate_markdown(version, args.date, amendment_diff, amendment_unchanged, amendment_entries, entries, authors, version_commit)
|
||||
|
||||
# Write output
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
with open(output_path, "w") as f:
|
||||
f.write(markdown)
|
||||
|
||||
print(f"\nRelease notes written to: {output_path}")
|
||||
|
||||
# Update blog/sidebars.yaml
|
||||
sidebars_path = "blog/sidebars.yaml"
|
||||
# Derive sidebar path and year from actual output path
|
||||
relative_path = output_path.removeprefix("blog/")
|
||||
sidebar_year = relative_path.split("/")[0]
|
||||
new_entry = f" - page: {relative_path}"
|
||||
try:
|
||||
with open(sidebars_path, "r") as f:
|
||||
sidebar_content = f.read()
|
||||
|
||||
if relative_path in sidebar_content:
|
||||
print(f"{sidebars_path} already contains {relative_path}")
|
||||
else:
|
||||
# Find the year group and insert at the top of its items
|
||||
year_marker = f" - group: '{sidebar_year}'"
|
||||
if year_marker not in sidebar_content:
|
||||
# Year group doesn't exist — find the right chronological position
|
||||
new_group = f" - group: '{sidebar_year}'\n expanded: false\n items:\n{new_entry}\n"
|
||||
# Find all existing year groups and insert before the first one with a smaller year
|
||||
year_groups = list(re.finditer(r" - group: '(\d{4})'", sidebar_content))
|
||||
insert_pos = None
|
||||
for match in year_groups:
|
||||
existing_year = match.group(1)
|
||||
if int(sidebar_year) > int(existing_year):
|
||||
insert_pos = match.start()
|
||||
break
|
||||
if insert_pos is not None:
|
||||
sidebar_content = sidebar_content[:insert_pos] + new_group + sidebar_content[insert_pos:]
|
||||
else:
|
||||
# New year is older than all existing — append at the end
|
||||
sidebar_content = sidebar_content.rstrip() + "\n" + new_group
|
||||
else:
|
||||
# Insert after the year group's "items:" line
|
||||
year_idx = sidebar_content.index(year_marker)
|
||||
items_idx = sidebar_content.index(" items:", year_idx)
|
||||
insert_pos = items_idx + len(" items:\n")
|
||||
sidebar_content = sidebar_content[:insert_pos] + new_entry + "\n" + sidebar_content[insert_pos:]
|
||||
|
||||
with open(sidebars_path, "w") as f:
|
||||
f.write(sidebar_content)
|
||||
print(f"Added {relative_path} to {sidebars_path}")
|
||||
except FileNotFoundError:
|
||||
print(f"Warning: {sidebars_path} not found, skipping sidebar update", file=sys.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user