> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ondb.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# PriceIndex

> Value-based payment model with automatic revenue sharing

PriceIndex is a special index type that changes how payments work, enabling revenue-sharing business models for applications built on OnDB.

## Traditional vs PriceIndex Payment

| Aspect              | Traditional (BTree/Hash)         | PriceIndex                 |
| ------------------- | -------------------------------- | -------------------------- |
| **Cost basis**      | Data size                        | Field value                |
| **Formula**         | `cost = data_size_kb * rate`     | `cost = field_value`       |
| **Revenue sharing** | None                             | Automatic                  |
| **Example**         | 10 KB order costs \~\$0.001 USDC | $100 order costs $100 USDC |

## How It Works

```
User Creates Order
  totalPrice: $100 USDC
           |
 Payment Required: $100 USDC
           |
 Automatic Revenue Split (Server-Side)
           |
      +----+----+
      |         |
   $80 USDC  $20 USDC
   App       Platform
  Wallet   (OnDB)
```

## Creating a PriceIndex

```typescript theme={null}
const db = client.database('your-app-id');

// Create PriceIndex on totalPrice field
await db.createIndex({
  name: 'idx_orders_totalPrice',
  collection: 'orders',
  field_name: 'totalPrice',
  index_type: 'price'
});

// Revenue split is configurable via createWriteIndex()
// Default: 80% to app owner, 20% to platform
```

## Using PriceIndex in Applications

```typescript theme={null}
// Calculate order total
const orderTotal = items.reduce((sum, item) =>
  sum + (item.price * item.quantity), 0
);

// Create order with PriceIndex payment
await client.store(
  {
    collection: 'orders',
    data: [{
      customerAddress: userWallet,
      items: orderItems,
      totalPrice: orderTotal, // This field has PriceIndex!
      status: 'confirmed'
    }]
  },
  async (quote) => {
    const txHash = await processPayment(quote);
    return { txHash, network: quote.network, sender: walletAddress, chainType: quote.chainType, paymentMethod: 'native' };
  },
  true
);

// Backend automatically:
// 1. Detects PriceIndex on totalPrice field
// 2. Uses totalPrice value as payment amount
// 3. Splits payment automatically (default: 80% app, 20% platform)
// 4. Credits app wallet balance
```

## Use Cases

PriceIndex is perfect for:

| Use Case      | PriceIndex Field    |
| ------------- | ------------------- |
| E-commerce    | `orderTotal`        |
| Ticketing     | `ticketPrice`       |
| Marketplace   | `transactionAmount` |
| Subscriptions | `planPrice`         |
| Service fees  | `feeAmount`         |

Not suitable for:

* Product catalogs (use BTree for filtering by price range)
* Free/public data storage
* Internal analytics data
* User-generated content without pricing

## Complete E-commerce Example

```typescript theme={null}
import { createClient } from '@ondb/sdk';

const client = createClient({
  endpoint: 'https://api.ondb.io',
  appId: 'my-store',
  appKey: process.env.ONDB_APP_KEY
});

// Setup: Create collections with indexes
async function setupStore() {
  const db = client.database('my-store');

  // Products - use btree for price range queries
  await db.createIndex({
    name: 'idx_products_category',
    collection: 'products',
    field_name: 'category',
    index_type: 'hash'
  });

  await db.createIndex({
    name: 'idx_products_price',
    collection: 'products',
    field_name: 'price',
    index_type: 'btree'
  });

  // Orders - use PriceIndex for payment-based pricing!
  await db.createIndex({
    name: 'idx_orders_customerId',
    collection: 'orders',
    field_name: 'customerId',
    index_type: 'hash'
  });

  await db.createIndex({
    name: 'idx_orders_totalPrice',
    collection: 'orders',
    field_name: 'totalPrice',
    index_type: 'price' // <-- PriceIndex!
  });
}

// Checkout: Create order with PriceIndex payment
async function checkout(cart, userWallet, paymentTxHash) {
  const orderTotal = cart.items.reduce(
    (sum, item) => sum + (item.price * item.quantity),
    0
  );

  const result = await client.store(
    {
      collection: 'orders',
      data: [{
        customerId: userWallet,
        items: cart.items,
        totalPrice: orderTotal,
        status: 'confirmed',
        createdAt: new Date().toISOString()
      }]
    },
    async (quote) => {
      return { txHash: paymentTxHash, network: quote.network, sender: userWallet, chainType: quote.chainType, paymentMethod: 'native' };
    },
    true
  );

  return result;
}
```

## Checking App Wallet Balance

Your application's revenue share is credited to the app wallet balance:

```typescript theme={null}
// Check app wallet balance
const response = await fetch(
  `${endpoint}/api/apps/${appId}/wallet/balance`
);
const balance = await response.json();

console.log('App balance:', balance.amount, 'USDC');
```

## Revenue Split Configuration

The default revenue split is:

* **80%** to the application owner
* **20%** to the platform (OnDB)

You can customize pricing when creating a write index via `createWriteIndex()`:

```typescript theme={null}
await db.createWriteIndex('orders', 'totalPrice', {
  pricing_model: 'field_value',   // Use the field value as the cost
});

// Or with per-record pricing
await db.createWriteIndex('orders', 'totalPrice', {
  pricing_model: 'per_record',
  price_per_record: 1_000_000     // 1 USDC per record
});
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Paid Reads" icon="book" href="/payments/paid-reads">
    HTTP 402 for read operations
  </Card>

  <Card title="Cost Estimation" icon="calculator" href="/payments/cost-estimation">
    Estimate operation costs
  </Card>
</CardGroup>
