# PathFinding

Pathfinding on the XRP Ledger (XRPL) enables efficient payment routing by discovering the optimal path for transferring value between accounts. This feature facilitates cross-currency transactions, ensuring payments can be made even when the sender and receiver use different currencies.

***

### Pathfinding Explained

#### What Is Pathfinding?

Pathfinding is a feature on the XRPL that identifies the most cost-effective route for payments involving multiple currencies. It leverages the decentralized exchange (DEX) on the XRPL, which supports cross-currency transactions by converting currencies seamlessly using order books.

#### Why Use Pathfinding?

Pathfinding ensures that payments are completed with minimal fees and optimal exchange rates, even if the sender and receiver operate in entirely different currencies. This makes XRPL a robust platform for international remittances and currency exchanges.

#### How Pathfinding Works

When initiating a cross-currency transaction, XRPL scans its order books and liquidity pools to identify the best combination of offers to complete the payment. This process includes:

1. **Finding Direct Offers**: Direct currency pairs between the sender and receiver.
2. **Building Complex Paths**: Identifying intermediate steps involving multiple currencies if no direct offer is available.

***

### Advantages of Pathfinding

1. **Efficient Cross-Currency Payments**\
   Pathfinding automatically converts currencies using the best available rates, eliminating the need for intermediaries.
2. **Optimized Transaction Costs**\
   By leveraging competitive offers on the XRPL’s DEX, pathfinding minimizes fees associated with currency conversion.
3. **Global Reach**\
   Enables seamless payments across borders, even in currencies that are not natively linked.
4. **Automated Exchange**\
   Eliminates manual intervention by automating the selection of the best path for payments.

***

## Pathfinding in Action

### Prerequisites

To use the pathfinding feature, ensure the following:

* Both the sender and receiver accounts are active on XRPL.
* Sufficient XRP balance is maintained to cover transaction fees.
* The sender has trustlines established for any non-XRP currencies involved in the payment.
* The currencies involved in the transaction must be active on the DEX with some trading activity. If you are using a testnet, you may need to create an active market using bots to simulate trading activity.

#### Initialize the wallets

Begin by installing `npm i xrpl`

```javascript
import { Client, Wallet } from "xrpl";

// To test pathfinding the best way is to use MainNet as we need active trading on the currencies. You can do this on testnet, this would require to make an active market between Currency 1 <> XRP <> Currency 2

const client = new Client("wss://xrplcluster.com");
await client.connect();

// The source and destination address can be the same, you will now effectively swap between a currency pair
const sourceWallet =  Wallet.fromSeed("s...");
const destinationWallet = Wallet.fromSeed("s...");
```

### Example: Cross-Currency Payment

#### Retrieve Payment Paths

To initiate a cross-currency payment, start by retrieving available paths with the [pathfinding method](https://xrpl.org/docs/references/http-websocket-apis/public-api-methods/path-and-order-book-methods/path_find).

```javascript
client.on('path_find', (path_find) => {
    console.log('New path: ', path_find);
});

const pathfindRequest = {
    command: "path_find",
    subcommand: "create",
    source_account: sourceWallet.classicAddress,  // Sender's account
    destination_account: destinationWallet.classicAddress, // Receiver's account
    send_max: "1000000", // Maximum amount the sender is willing to spend (optional) 
    destination_amount: {
        currency: "USD",
        value: -1, // Using -1 to indicate unspecified destination amount
        issuer: "rIssuerAddress" // Issuer of the destination currency
    }
};

const paths = await client.request(pathfindRequest);
console.log('Available Paths:', paths.result.alternatives);
```

**Alternative Example 2: Specified destination Amount**

This way you will replace the other request and you will see what you need to spend in order for the destination address to receive a specified amount. This requires a list of source currencies.

```javascript
const pathfindRequest = {
    command: "path_find",
    subcommand: "create",
    source_account: sourceWallet.classicAddress,  // Sender's account
    destination_account: destinationWallet.classicAddress, // Receiver's account
    destination_amount: {
        currency: "USD",
        value: "100", // Specify the exact amount the destination should receive
        issuer: "rIssuerAddress" // Issuer of the destination currency
    },
    source_currencies: [{
        currency: "524C555344000000000000000000000000000000", // RLUSD
        issuer: "rMxCKbEDwqr76QuheSUMdEGf4B9xJ8m5De"
    }]
};
```

#### Send the Payment

Once a suitable path is identified, construct the [payment transaction](https://xrpl.org/docs/references/protocol/transactions/types/payment).

```javascript
const paymentTransaction = {
    TransactionType: "Payment",
    Account: "rSenderAddress",
    Destination: "rReceiverAddress",
    Amount: {
        currency: "USD",
        value: "100",
        issuer: "rIssuerAddress"
    },
    SendMax: {
        currency: "EUR",
        value: "90",
        issuer: "rIssuerAddress" // Specify the maximum amount in source currency
    },
    Paths: paths.result.alternatives[0].paths_computed // Include computed path
};

try {
    const response = await client.submitAndWait(paymentTransaction, { autofill: true, wallet: sourceWallet });
    console.log('Transaction Result:', response);
} catch (error) {
    console.error('Failed to submit payment:', error);
}

// Don't forget to close it!
await client.request({
    command: 'path_find',
    subcommand: 'close'
});
```

***

## Key Considerations

#### Trustlines

For non-XRP currencies, both the sender and receiver must establish trustlines with the respective issuers.

#### Liquidity

Pathfinding depends on the liquidity of the currency pairs in the XRPL’s order books. Ensure sufficient market depth for transactions.

#### Fees

Each path incurs minimal fees, determined by the order book offers and XRPL’s transaction costs.

#### Currency Conversion

The conversion rate depends on the offers available on the DEX. Using higher-liquidity pairs generally results in better rates.

***

## Advantages in Multi-Currency Ecosystems

Pathfinding is a cornerstone of XRPL’s utility in financial ecosystems that require:

1. **International Remittances**\
   Facilitates seamless currency exchanges for cross-border payments.
2. **Decentralized Finance (DeFi)**\
   Powers complex financial workflows by automating currency conversions.
3. **Multi-Currency Wallets**\
   Enhances user experience by enabling payments in any supported currency.

Pathfinding on XRPL underscores the ledger’s commitment to efficiency and accessibility in global financial transactions. By leveraging its DEX and automated routing, XRPL ensures that payments are seamless, cost-effective, and scalable across diverse currencies.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.xrpl-commons.org/xrpl-basics/path-finding.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
