コンテンツへスキップ
最終更新:

Migrate a Payments or FX Stack to the XRP Ledger

If you're already running a payments or FX stack on another chain and want to move it to the XRP Ledger, this guide is for you. The XRP Ledger simplifies your migration by reducing the number of components you have to build, secure, and maintain yourself. Many of the capabilities you'd implement as smart contracts on other chains are built into the protocol, so there's less to write, deploy, or audit.

This guide assumes familiarity with your current payment flows and a basic understanding of core XRP Ledger concepts, such as fungible tokens and payment types. The six steps below walk you through the path from mapping your stack to a live pilot.

1. Map Your Stack to XRP Ledger Primitives

Many features that you'd implement as a smart contract on other chains are supported as native transaction types on the XRP Ledger. Before you port anything, examine which capabilities your stack uses and compare them to the built-in primitives:

What You NeedXRP Ledger Native Capability
Conditional or time-locked release of fundsEscrow
Shared/multi-party control of an accountMulti-signing
Currency or asset issuance and managementTrust Line Tokens / Multi-Purpose Tokens (MPTs)
On-chain currency conversionDEX order book, AMM, and pathfinding
Rate quoting and price discoveryPathfinding (ripple_path_find) and order book queries (book_offers)
Market making and liquidity provisionDEX offers and AMMs
Compliance-gated tradingPermissioned DEXes

See Transaction Types for a comprehensive list of built-in transaction types. Some primitives depend on recently enabled amendments, so be sure to check the amendment status on your target network before you design around it. For logic that doesn't map to a primitive, such as custom business rules, you still need off-ledger code.

2. Choose Your Infrastructure Path

Once you've mapped the capabilities to XRP Ledger primitives, you have to decide how to connect to the network. You can choose one of two paths, depending on your infrastructure experience and custody preferences:

  • Custodian integration: Your provider's API handles keys, signing, submission, and node access in the background. Lowest security load and fastest integration, but provides least control over funds and features, vendor lock-in, and potential compliance implications.
  • Direct XRP Ledger integration: You hold your own keys and use a client library to interact with the XRP Ledger. Choose one of the following methods:
    • Managed node provider: Fastest way to ship with low upfront costs. Someone else runs the nodes while you hold your keys and signing. Provides less control over history retention, query privacy, and configuration, and you depend on their SLA.
    • Self-hosted xrpld and Clio servers: Most control over ledger history, query privacy, and throughput, without third-party dependencies. Requires high operational overhead for hardware and maintaining synced servers. Suited to teams with higher volume or strict SLA needs. See Install and Run.

For more information, see the payments overview.

Pick a Client Library

After selecting your infrastructure, decide which library you'll use. The library builds, signs, and submits native transactions and reads the ledger state, so there is no smart-contract layer to call. If you use a custodian integration, the custodian's API is typically your client library, so you can skip ahead to Step 4.

The best place to start is by matching the library to your backend's primary language. XRPLF maintains xrpl.js (JavaScript/TypeScript), xrpl-py (Python), and xrpl4j (Java). You can use xrpl.js if you currently build with viem or ethers, xrpl-py if you build with web3.py, or xrpl4j if you build with web3j.

Other libraries, such as xrpl-go (Go) and XRPL_PHP (PHP), vary in release cadence and amendment support. Check the repositories for recent releases and confirm they support the amendments and features your integration needs before committing to one.

If you don't find a library that matches your backend, you can connect to the XRP Ledger using the HTTP / WebSocket APIs.

3. Set Up Your Accounts

With your chosen client library, you can create and fund the accounts your integration will use to submit transactions and hold balances. On the XRP Ledger, a few things about accounts work differently:

  • An account doesn't exist until it's funded. You can generate a key pair offline, but the address isn't active on the ledger until it receives the base reserve.
  • Its reserve has two parts: a fixed base reserve every account holds, plus an owner reserve that adds a set amount for each ledger entry it owns (for example, a trust line, offer, or escrow). You can't spend below the two combined, which doubles as one of the ledger's anti-spam mechanisms.
  • Each account must opt in to a token before it can receive it, unlike many EVM chains where tokens can arrive unsolicited. If the issuer requires authorization, they must also approve the holder. Every opt-in creates a ledger entry that adds to the account's owner reserve. The way an account opts in depends on the token type:
  • Other chains frequently use one deposit address per customer, while the XRP Ledger uses destination tags to route an incoming payment to the correct customer in a single shared (omnibus) account. Since every address needs its own reserve, one account per customer ties up XRP for each customer (see Receive and Credit).
Note

If you use a custodian integration, your custodian creates and manages these accounts and keys. The rest of this section only applies when you hold your own keys.

Fund Your Account

You can fund accounts on Testnet and Devnet using a faucet. On Mainnet, you fund an account by sending it XRP from an exchange or an already-funded account. See Accounts for more on account creation and configuration.

On a test network, creating and funding an account is a single call (in Python, import generate_faucet_wallet from xrpl.wallet):

import xrpl from 'xrpl'

const client = new xrpl.Client('wss://s.altnet.rippletest.net:51233')
await client.connect()

console.log('Funding new wallet from faucet...')
const { wallet } = await client.fundWallet()
console.log(`Funded. Master key pair:
  Address: ${wallet.address}
  Seed: ${wallet.seed}
`)
Caution

This example handles seeds directly to keep the Testnet example simple. In production, never log or hardcode a seed. Store it in a secret manager and use secure signing.

Plan Account Roles and Keys

You might separate roles across multiple accounts, using a treasury for reserves and balances, operating accounts for submission, and a SignerList where an account needs multi-party control. Because these accounts hold real funds and on-ledger actions are irreversible, protect their keys from the start:

  • Generate each master key pair with offline account setup.
  • Operate through a regular key, and keep the offline master key as your recovery path.
  • Optionally, disable the master key if you want transactions signed only by a regular key or multi-signing. Confirm that your regular key or signer list works first, because disabling the master key removes the default way to authorize transactions and your offline recovery path.

4. Build Your Integration

Now that your accounts are funded, you can port your business logic into built-in transaction types.

Note

If you use a custodian integration, your custodian's API replaces the client library calls in the code samples below, so you don't build, sign, or submit transactions yourself. The concepts still apply, so check your custodian's documentation for how it reports transaction results, partial payments, and incoming payments.

Some concepts you may know from other chains work like this on the XRP Ledger:

Concept from Other ChainsXRP Ledger Field
NonceSequence numbers order transactions serially per account.
GasFee is a low base cost that rises with network load.
MempoolLastLedgerSequence bounds how long a transaction stays pending. After that ledger, the transaction expires and can never be applied.
RetriesSequence makes a resubmitted transaction apply at most once.

For more on how these fields work together, see Reliable Transaction Submission.

Send a Payment

This example runs the entire payment lifecycle by autofilling Fee, Sequence, and LastLedgerSequence, signing locally, submitting, and waiting for a validated result before reading the outcome from the metadata.

  // Prepare transaction -------------------------------------------------------
  const prepared = await client.autofill({
    "TransactionType": "Payment",
    "Account": wallet.address,
    "DeliverMax": xrpl.xrpToDrops("22"),
    "Destination": "rPT1Sjq2YGrBMTttX4GZHjKu9dyfzbpAYe"
  })
  const max_ledger = prepared.LastLedgerSequence
  console.log("Prepared transaction instructions:", prepared)
  console.log("Transaction cost:", xrpl.dropsToXrp(prepared.Fee), "XRP")
  console.log("Transaction expires after ledger:", max_ledger)

  // Sign prepared instructions ------------------------------------------------
  const signed = wallet.sign(prepared)
  console.log("Identifying hash:", signed.hash)
  console.log("Signed blob:", signed.tx_blob)

  // Submit signed blob --------------------------------------------------------
  const tx = await client.submitAndWait(signed.tx_blob)

  // Wait for validation -------------------------------------------------------
  // submitAndWait() handles this automatically, but it can take 4-7s.

  // Check transaction results -------------------------------------------------
  console.log("Transaction result:", tx.result.meta.TransactionResult)
  console.log("Balance changes:", JSON.stringify(xrpl.getBalanceChanges(tx.result.meta), null, 2))

  
Caution

This example handles seeds directly to keep the Testnet example simple. In production, never log or hardcode a seed. Store it in a secret manager and use secure signing.

Convert Across Currencies

Cross-currency payments follow the same lifecycle as sending payments, with two differences:

  • Amount names the currency and issuer the destination receives (this differs from what the source spends).
  • SendMax caps the source spend.
Note

Cross-currency payments currently support only XRP and trust line tokens. MPTs require the MPTokensV2 amendment, which is still in development.

Both the sending and receiving accounts need a trust line to the issuer of any non-XRP currency they handle. Issuers can restrict who holds their currency with authorized trust lines.

By default, a payment converts directly through the DEX order book or AMM between the two currencies. For better routes, including ones bridged through XRP, pass the result of ripple_path_find in Paths. There's no external router to integrate.

On-chain conversion draws on both the order book and the AMM, and pathfinding estimates the route rather than guaranteeing it. Bound each conversion: SendMax caps what the source spends, and a DeliverMin with the tfPartialPayment flag floors what the destination receives.

The following example spends XRP and delivers USD to the destination, with SendMax and DeliverMin set:

// Prepare cross-currency Payment ----------------------
// Deliver 100 USD to the receiver while spending no more than 30 XRP from the
// source. The ledger routes XRP -> USD through the DEX automatically, so there
// is no router to integrate. SendMax caps what the source spends. DeliverMin,
// together with the tfPartialPayment flag, floors what the destination receives.
console.log(`\n=== Preparing cross-currency Payment ===\n`)
const paymentTx = {
  TransactionType: 'Payment',
  Account: sender.address,
  Destination: receiverAddress,
  Amount: { currency, issuer: issuerAddress, value: '100' },
  SendMax: xrpl.xrpToDrops('30'),
  DeliverMin: { currency, issuer: issuerAddress, value: '95' },
  Flags: 131072 // tfPartialPayment
}

xrpl.validate(paymentTx)
console.log(JSON.stringify(paymentTx, null, 2))

// Submit, sign, and wait for validation ----------------------
console.log(`\n=== Submitting cross-currency Payment ===\n`)
const response = await client.submitAndWait(paymentTx, { wallet: sender, autofill: true })

const resultCode = response.result.meta.TransactionResult
if (resultCode !== 'tesSUCCESS') {
  console.error('Error: payment failed with', resultCode)
  await client.disconnect()
  process.exit(1)
}

// Credit the amount that ACTUALLY arrived, from metadata, never the Amount field
console.log(`\n=== Payment delivered ===\n`)
console.log('delivered_amount:', response.result.meta.delivered_amount)
// 

A cross-currency payment can also name a domain ID to keep the conversion from trading against accounts you haven't approved, by consuming only offers from the matching permissioned DEX. An account can trade in a domain if it owns the domain or holds a credential that the domain accepts. A payment that names a domain ID can't use AMM liquidity, so it has less to draw on than an unrestricted conversion.

Receive and Credit

Your stack also has to detect payments arriving in your accounts and credit the correct customer. Subscribe to your accounts with transaction streams to see payments as they validate. For production monitoring, see Robustly Monitoring for Payments.

Caution

Avoid three common mistakes that can cause you to credit the wrong amount or the wrong customer:

  • Credit the amount that actually arrived. A partial payment can deliver less than the Amount field shows. Read the delivered_amount metadata field, not Amount, to avoid the partial payments exploit.
  • Attribute pooled funds with destination tags. When many customers share one treasury or operating account, require destination tags with RequireDest so each payment maps to the right customer.
  • Only credit successful transactions. Validated ledgers include tec results, which are final and consume the Fee but deliver nothing. Credit a customer only when the result is tesSUCCESS.

Supply Liquidity

If you supply the liquidity that payments consume, you can publish and manage your own offers on the DEX (see Trade in the Decentralized Exchange). Each offer you leave in the ledger counts toward your owner reserve. Issuers can also set a tick size that limits the precision of your offers' exchange rates.

You can also supply liquidity passively by depositing into an AMM pool.

5. Test on Testnet or Devnet

Before going live, complete your end-to-end testing on a public test network:

  • Testnet: Closely mirrors Mainnet's amendment status and behavior. Primary environment for pre-launch validation.
  • Devnet: Runs beta releases, so use it only to test pre-release features or amendments that are not yet on Mainnet.

Neither test network uses real money, but both are usually centralized and come with no stability guarantees. Don't rely on persistence or treat them like stable environments.

Then, test how your integration handles XRP Ledger-specific cases that can cause failed, stuck, or misattributed payments, such as:

  • Crediting delivered_amount on partial payments.
  • Attributing pooled funds with destination tags.
  • Enforcing reserve and trust line limits.
  • Holding SendMax/DeliverMin under thin liquidity.
  • Clearing submissions when the fee rises under load.

A validated ledger includes both successful transactions and tec failures. tesSUCCESS and tec result codes are both final and consume the Fee, but only tesSUCCESS means the transaction succeeded.

If a transaction expires without validation, build a replacement with the same Sequence and a new LastLedgerSequence.

6. Pilot a Live Corridor and Launch

After testing on Testnet or Devnet, run a live pilot with real traffic through one narrow corridor (or a single partner), and verify results against your internal records before scaling.

To do so:

  1. Switch your endpoint from a test network to Mainnet, and use funded accounts.
  2. Send real transactions through the same lifecycle (see Build Your Integration) and verify each one reached a validated ledger.
  3. Verify on-ledger results against your internal records. Reconcile with account_tx, using marker to page through results. Make reconciliation idempotent so replaying a ledger range never double-counts. Subscribe to transaction streams for real-time monitoring instead of polling (see Robustly Monitoring for Payments).
  4. Enforce any KYC or travel-rule obligations for the corridor. For example, use credentials to attest a holder's verified status on-ledger.
  5. Widen scope once verified. If reconciliation fails, delay the cutover and keep your existing rail live as the fallback.

Once a transaction is in a validated ledger, it's immutable and can't be reversed, so there's no probabilistic-settlement tail to account for (see Finality of Results).

Your custody model impacts the way you cut over:

  • Custodial setups switch in a single window: snapshot your balances, fund the accounts on the XRP Ledger with the tokens you plan to hold (see Stablecoins), and flip the payment engine.
  • Self-custodial flows rely on end users who move their own balances, so plan for a longer arc. Customer communication is usually the slowest piece.

Once your pilot cleanly reconciles, you have a repeatable path to map the stack, choose infrastructure, set up accounts, build, test, and pilot. Use the same path for each additional corridor.

See Also