# Price Oracles

[Price Oracles](https://xrpl.org/docs/concepts/decentralized-storage/price-oracles) on the XRP Ledger bring real-world pricing data on-chain—bridging external market data with decentralized applications (dApps). This feature enables dApps, decentralized exchanges, and DeFi protocols to function with up-to-date, verifiable price feeds.

***

### Price Oracles Explained

#### What Are Price Oracles?

Price Oracles are on-chain ledger objects that store external price information (e.g., XRP/USD). They are created and updated via the **OracleSet** transaction, and can be removed using the **OracleDelete** transaction. dApps can access this data to trigger smart contract logic, perform asset conversions, or maintain stablecoins.

#### Why Use Price Oracles?

* **Reliable Data Feeds**: Provide verified, real-time pricing data from trusted providers.
* **Decentralized Trust**: Price data is recorded on the immutable XRPL ledger.
* **Data Aggregation**: Multiple oracle instances can be aggregated to calculate mean, median, or trimmed mean values, reducing the impact of outliers.

#### How Price Oracles Work

The PriceOracle object includes fields such as `Owner`, `Provider`, `PriceDataSeries`, and `LastUpdateTime`. You use an **OracleSet** transaction to create or update an oracle instance, while the **OracleDelete** transaction removes it from the ledger. Additionally, the `get_aggregate_price` API allows for combining data from multiple Price Oracle objects to generate reliable price statistics.

***

### Advantages of Price Oracles

1. **Real-World Data Integration**\
   Seamlessly integrate external pricing data into on-chain applications.
2. **Enhanced Transparency and Security**\
   Data stored on XRPL is verifiable and tamper-resistant.
3. **Robust Data Aggregation**\
   Aggregating data from several oracles minimizes anomalies and improves reliability.
4. **Dynamic Data Management**\
   Easily update or remove price feeds with dedicated transactions.

***

## Price Oracles in Action

### Prerequisites

Before working with Price Oracles, ensure you have:

* An active **Owner** account on the XRPL that meets the XRP reserve requirements.
* Sufficient XRP to cover transaction fees.
* Trust in your external data provider (e.g., a reputable API or on-chain oracle service).

#### Initialize the Client and Wallet

Begin by installing the XRPL library:

```bash
npm install xrpl
```

Then, initialize your XRPL client and wallet:

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

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

// Initialize your owner wallet (replace with your actual secret)
const ownerWallet = Wallet.fromSeed("sXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
```

### Example: Creating/Updating a Price Oracle

Submit an **OracleSet** transaction to create or update a Price Oracle instance:

```javascript
const oracleSetTx = {
    TransactionType: "OracleSet",
    Account: ownerWallet.classicAddress,
    OracleDocumentID: 34,  // Unique identifier for this Price Oracle instance
    Provider: "70726F7669646572", // Hex-encoded provider identifier (e.g., "provider")
    AssetClass: "63757272656E6379", // Hex-encoded asset class (e.g., "currency")
    LastUpdateTime: Math.floor(Date.now() / 1000), // Current Unix time
    PriceDataSeries: [
        {
            PriceData: {
                BaseAsset: "XRP",
                QuoteAsset: "USD",
                AssetPrice: 740,  // Example: represents 7.40 with a Scale of 2
                Scale: 2
            }
        }
    ]
};

try {
    const response = await client.submitAndWait(oracleSetTx, { autofill: true, wallet: ownerWallet });
    console.log("OracleSet Transaction Result:", response);
} catch (error) {
    console.error("Failed to submit OracleSet transaction:", error);
}
```

### Retrieving a Price Oracle

Use the `ledger_entry` API to fetch the on-chain Price Oracle object:

```javascript
const ledgerEntryRequest = {
    method: "ledger_entry",
    oracle: {
        account: ownerWallet.classicAddress,
        oracle_document_id: 34
    },
    ledger_index: "validated"
};

const ledgerEntryResponse = await client.request(ledgerEntryRequest);
console.log("Retrieved Price Oracle:", ledgerEntryResponse.result.node);
```

#### Convert AssetPrice to Integer

To get a decimal representation of the AssetPrice convert it from HEX to a Number:

```javascript
const AssetPriceHex = '0x' + '2e4'
const price = Number(AssetPriceHex)
```

### Aggregating Price Data

Aggregate data from multiple oracles with the `get_aggregate_price` API:

```javascript
const aggregatePriceRequest = {
    method: "get_aggregate_price",
    ledger_index: "current",
    base_asset: "XRP",
    quote_asset: "USD",
    trim: 20, // Trim 20% of outlier data
    oracles: [
        {
            account: ownerWallet.classicAddress,
            oracle_document_id: 34
        }
        // Include additional oracle objects as needed
    ]
};

const aggregatePriceResponse = await client.request(aggregatePriceRequest);
console.log("Aggregated Price Data:", aggregatePriceResponse.result);
```

### Additionally Delete the Oracle Object

To delete the Oracle Object from your Account perform an `OracleDelete` Transaction.

```javascript
const oracleDeleteTx = {
  TransactionType: "OracleDelete",
  Account: ownerWallet.classicAddress,
  OracleDocumentID: 34
};

try {
    const response = await client.submitAndWait(oracleDeleteTx, { autofill: true, wallet: ownerWallet });
    console.log("OracleDelete Transaction Result:", response);
} catch (error) {
    console.error("Failed to submit OracleDelete transaction:", error);
}
```

***

## Key Considerations

#### XRP Reserve Requirements

* Ensure your account meets the reserve requirement, especially when including more than five token pairs in `PriceDataSeries`.

#### Data Accuracy and Validity

* Validate that the `LastUpdateTime` reflects current pricing data.
* Maintain consistency for the `Provider` and `AssetClass` fields across updates.

#### Transaction Signing

* All OracleSet and OracleDelete transactions must be signed by the owner account or its authorized multi-signers.

***

## Advantages in Financial Applications

Price Oracles empower the XRPL ecosystem by enabling:

1. **Decentralized Finance (DeFi)**\
   Utilize real-world price data to support lending, derivatives, and other DeFi products.
2. **Stablecoin Management**\
   Maintain stablecoin peg values with aggregated price feeds.
3. **Efficient Trading and DEX Integration**\
   Provide reliable market data for order matching and automated market making.

By integrating Price Oracles, developers can build robust, data-driven applications that benefit from transparent and up-to-date market insights.

***

Remember to disconnect your client after operations:

```javascript
await client.disconnect();
```

Happy building with Price Oracles on XRPL!


---

# 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/price-oracles.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.
