DEV Community

Joe Simo
Joe Simo

Posted on Edited on

How trust lines work on the XRP Ledger, in one TypeScript script

I build things with TypeScript and React, and when I started reading about tokens on the XRP Ledger, one idea kept tripping me up: nobody can send you a token you did not agree to hold. On the XRPL, that agreement is a trust line, and it has a number attached to it.

Reading about it only got me so far. So I wrote one small script that runs the whole story on the public Testnet, then broke it on purpose to see what the ledger says. This post walks through that script and the real results.

This is my entry for the XRP Ledger Foundation's #XRPEducationMonth.

The plan

The script does six things:

  1. Gets two fresh Testnet accounts from the faucet: an issuer and a holder.
  2. The issuer turns on Default Ripple with an AccountSet transaction.
  3. The holder sends a TrustSet saying "I will hold up to 100 LRN from this issuer."
  4. The issuer sends the holder 40 LRN with a Payment. That payment is what creates the tokens.
  5. The script reads the trust line from both sides with account_lines, and the issuer's totals with gateway_balances.
  6. The issuer tries to send 70 more LRN, which would push the holder to 110, past the 100 limit.

LRN is just a made-up three-character code. Per the currency formats page, a standard code is exactly 3 ASCII characters, and XRP is the only one you can't use.

Setup

You need Node.js. Then:

mkdir xrpl-trust-lines && cd xrpl-trust-lines
npm init -y
npm i xrpl
npm i -D tsx
Enter fullscreen mode Exit fullscreen mode

Testnet XRP comes free from the faucet and exists only for testing, so this is a safe place to experiment. The script keeps wallet seeds in memory and never prints them. Make that a habit even on Testnet.

The script

Save this as issued-assets.ts and run npx tsx issued-assets.ts.

// issued-assets.ts: issue a token on the XRPL Testnet and watch the trust line work.
// Run with: npx tsx issued-assets.ts
import { Client, Wallet, AccountSetAsfFlags, TrustSetFlags, type SubmittableTransaction } from "xrpl";

// Any public Testnet server works. Override with XRPL_WS if a port is blocked on your network.
const TESTNET = process.env.XRPL_WS ?? "wss://s.altnet.rippletest.net:51233";
const CURRENCY = "LRN"; // 3-letter currency code
const EXPLORER = "https://testnet.xrpl.org/transactions/";

async function submit(client: Client, wallet: Wallet, tx: SubmittableTransaction, label: string) {
  const result = await client.submitAndWait(tx, { autofill: true, wallet });
  const meta = result.result.meta;
  const code = typeof meta === "object" && meta ? meta.TransactionResult : "unknown";
  console.log(`${label}: ${code}`);
  console.log(`  ${EXPLORER}${result.result.hash}`);
  return code;
}

async function main() {
  const client = new Client(TESTNET);
  await client.connect();

  // 1. Two fresh Testnet accounts from the faucet. Seeds stay in memory only.
  const faucet = { faucetHost: "faucet.altnet.rippletest.net" };
  const { wallet: issuer } = await client.fundWallet(null, faucet);
  const { wallet: holder } = await client.fundWallet(null, faucet);
  console.log(`Issuer: ${issuer.address}`);
  console.log(`Holder: ${holder.address}`);

  // 2. Issuer turns on Default Ripple so its trust lines allow rippling.
  await submit(client, issuer, {
    TransactionType: "AccountSet",
    Account: issuer.address,
    SetFlag: AccountSetAsfFlags.asfDefaultRipple,
  }, "AccountSet asfDefaultRipple");

  // 3. Holder opens a trust line to the issuer: "I will hold up to 100 LRN from you."
  //    The holder also turns on No Ripple for its own side, as xrpl.org recommends for non-issuers.
  await submit(client, holder, {
    TransactionType: "TrustSet",
    Account: holder.address,
    Flags: TrustSetFlags.tfSetNoRipple,
    LimitAmount: { currency: CURRENCY, issuer: issuer.address, value: "100" },
  }, "TrustSet limit 100 LRN");

  // 4. Issuer sends 40 LRN. This creates the tokens.
  await submit(client, issuer, {
    TransactionType: "Payment",
    Account: issuer.address,
    Destination: holder.address,
    Amount: { currency: CURRENCY, issuer: issuer.address, value: "40" },
  }, "Payment 40 LRN");

  // 5. Read the trust line from both sides, plus the issuer's obligations.
  const holderLines = await client.request({ command: "account_lines", account: holder.address, ledger_index: "validated" });
  const issuerLines = await client.request({ command: "account_lines", account: issuer.address, ledger_index: "validated" });
  const gateway = await client.request({ command: "gateway_balances", account: issuer.address, ledger_index: "validated" });
  const show = (l: { account: string; balance: string; limit: string; limit_peer: string; currency: string; no_ripple?: boolean; no_ripple_peer?: boolean }) =>
    ({ peer: l.account, currency: l.currency, balance: l.balance, limit: l.limit, limit_peer: l.limit_peer, no_ripple: l.no_ripple ?? false, no_ripple_peer: l.no_ripple_peer ?? false });
  console.log("Holder account_lines:", JSON.stringify(holderLines.result.lines.map(show), null, 2));
  console.log("Issuer account_lines:", JSON.stringify(issuerLines.result.lines.map(show), null, 2));
  console.log("Issuer gateway_balances obligations:", JSON.stringify(gateway.result.obligations));

  // 6. Try to push the holder past the limit: 40 already held + 70 = 110 > 100.
  try {
    await submit(client, issuer, {
      TransactionType: "Payment",
      Account: issuer.address,
      Destination: holder.address,
      Amount: { currency: CURRENCY, issuer: issuer.address, value: "70" },
    }, "Payment 70 LRN (over the limit)");
  } catch (err) {
    console.log("Over-limit payment was rejected:", (err as Error).message);
  }

  const after = await client.request({ command: "account_lines", account: holder.address, ledger_index: "validated" });
  console.log(`Holder balance after the over-limit attempt: ${after.result.lines[0]?.balance} ${CURRENCY}`);

  await client.disconnect();
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
Enter fullscreen mode Exit fullscreen mode

A note on the server URL: the default is Ripple's Testnet server from the public servers list. The machine I ran this on blocks port 51233, so I set XRPL_WS=wss://testnet.xrpl-labs.com, which is another Testnet server on that same list. Same network, same ledger. Because the faucet host can't be guessed from that URL, the script names it explicitly.

The real output

Here is what my run printed (addresses are throwaway Testnet accounts):

Issuer: rpNNBsJdVpubtwaPsM6BDoMd7pHvS77C53
Holder: rEagPsjDBUPV8DpYjr2TLvLHYaKyL7G2GM
AccountSet asfDefaultRipple: tesSUCCESS
TrustSet limit 100 LRN: tesSUCCESS
Payment 40 LRN: tesSUCCESS
Holder account_lines:  balance "40",  limit "100", limit_peer "0",   no_ripple true,  no_ripple_peer false
Issuer account_lines:  balance "-40", limit "0",   limit_peer "100", no_ripple false, no_ripple_peer true
Issuer gateway_balances obligations: {"LRN":"40"}
Payment 70 LRN (over the limit): tecPATH_PARTIAL
Holder balance after the over-limit attempt: 40 LRN
Enter fullscreen mode Exit fullscreen mode

(I squeezed the two account_lines results onto one line each. The full JSON is in the raw output.)

You can open every transaction in the Testnet explorer:

Step Result Transaction
AccountSet (Default Ripple) tesSUCCESS 4D4D1E8E...B9877
TrustSet, limit 100 LRN tesSUCCESS CDF0E75F...3ED83
Payment, 40 LRN tesSUCCESS 592E5F48...620B3
Payment, 70 LRN tecPATH_PARTIAL DA4D6C76...1945D

What you just saw

A trust line is one shared balance

The trust line tokens page explains that a trust line is a single ledger entry (a RippleState entry) between two accounts for one currency code. It holds one shared balance that is positive from one side and negative from the other.

That is exactly what account_lines showed. From the holder's side the balance is 40. From the issuer's side the same line reads -40. Nothing was copied or moved from a stash. The issuer's Payment simply created the tokens by pushing the shared balance into negative territory on its own side.

Why the issuer looks negative

The docs put it plainly: the side with the negative balance is generally considered the issuer. A negative balance here is not a debt to the network. It is a record of obligations: 40 LRN that the issuer has put into other accounts. The gateway_balances method sums that up across all of an issuer's trust lines, which is why it returned {"LRN":"40"}. If the holder sent the 40 back to the issuer, those tokens would be burned and the obligation would drop to zero.

One practical note from that page: some public servers disable gateway_balances because it can be expensive. It worked on the server I used.

Limits belong to each side

Each side of a trust line sets its own limit, and it starts at 0. The holder set 100; the issuer never set one, so its limit is 0 and it sees the holder's limit as limit_peer: "100". The rule from the docs: payments and other accounts' actions can't push your balance above your limit. Only your own actions can (for example, lowering your limit after you already hold tokens).

So when the issuer tried to send 70 LRN to a holder already at 40, the ledger refused. The engine result was tecPATH_PARTIAL, which the tec codes reference describes as "the provided paths did not have enough liquidity to send the full amount." In plain words: there was no room on the trust line for 70 more. The holder's balance stayed at 40.

Two details I found useful here:

  • submitAndWait did not throw for this failure. It returned normally, and I had to read meta.TransactionResult. Check the result code yourself.
  • A tec result still lands in a validated ledger. Per the docs, the transaction cost is destroyed and the sequence number is used, even though the payment failed. In my run that cost was 12 drops of Testnet XRP.

Rippling, and why the issuer turns it on

Rippling is how trust line tokens move between two holders. If Holder A sends LRN to Holder B, the balance on A's line to the issuer goes down and the balance on the issuer's line to B goes up. The tokens pass through the issuer, and the issuer's total obligations don't change.

For that to work, the issuer's trust lines must allow rippling. The AccountSet flag asfDefaultRipple (value 8) enables rippling on the account's trust lines by default. It only affects lines that other accounts open to you, and it doesn't change lines that existed before you set it. That's why the script sets it first, before the holder opens the line. On the issuer's side you can see no_ripple: false.

Regular holders usually want the opposite. The xrpl.org docs recommend that non-issuers disable rippling, because otherwise payments can shift balances through your account in ways you didn't plan. So the holder's TrustSet includes the tfSetNoRipple flag, and the holder's side reads no_ripple: true. The two flags are tracked separately per side, which is why one line shows both no_ripple and no_ripple_peer.

A small detail about reserves

A trust line takes space in the ledger, so it counts toward an owner reserve. The docs say that generally the account that created the line pays that reserve, not the issuer. Here that's the holder. There is also a small exception: if an account owns at most two ledger objects including the new trust line, its owner reserve is treated as zero, so a brand new account can still open one. See reserves for the full rules.

Try it yourself

A few changes worth making to the script:

  • Lower the second payment to 60. That lands exactly on the limit, so it should go through.
  • Add a second holder and send LRN from one holder to the other. That's rippling in action.
  • Remove the asfDefaultRipple step and try the holder to holder payment again.

If you want the official step by step version, xrpl.org has a full issue a fungible token tutorial and a JavaScript tutorials section.

What clicked for me: a token on the XRPL isn't a thing sitting in a wallet. It is a balance on a line that both sides agreed to, with a ceiling the holder controls.


I wrote this with help from AI tools; I ran every code sample on the XRPL Testnet and checked the facts against xrpl.org.

Top comments (0)