# @zkp2p/indexer-schema

> GraphQL schema and TypeScript types for the ZKP2P on-chain indexer. Source of truth for all downstream consumers (curator, SDK, notification server).

ZKP2P is a peer-to-peer fiat-to-crypto exchange protocol on Base (chain 8453). Makers deposit USDC liquidity with conversion rates. Takers signal intents to buy, make off-chain fiat payments (Venmo, Wise, etc.), then submit TLS proofs to release escrowed funds on-chain.

## How to use this package

```ts
// TypeScript types for all indexed entities
import type { Deposit, Intent, QuoteCandidate, MethodCurrency } from '@zkp2p/indexer-schema';
import { DepositStatus, IntentStatus } from '@zkp2p/indexer-schema';

// Raw GraphQL SDL string
import { schemaSDL } from '@zkp2p/indexer-schema';

// For codegen configs: node_modules/@zkp2p/indexer-schema/dist/schema.graphql
```

## Reading Conventions

- `Deposit.id` is the canonical join key for deposit-scoped rows: `escrowAddress_depositId`.
- `Intent.id` is the canonical join key for intent-scoped rows: `chainId_intentHash`.
- `@derivedFrom` relationships exist only where the schema declares them. Most other relationships are implicit string joins.
- Amount fields are stored in the token's smallest unit. In practice this indexer is restricted to supported USDC deployments, so most token amounts are 6-decimal USDC amounts.
- Conversion-rate fields use 1e18 fixed-point precision unless noted otherwise.
- `BigInt` fields are serialized as **strings** (too large for JSON numbers).
- `Int` fields are **numbers**.
- Addresses and hashes are lowercase hex strings.
- Currency codes are bytes32 keccak hashes.
- Timestamps are Unix seconds as BigInt strings.
- Basis points: 10000 = 100%.

## Entity Relationship Map

```
Deposit (1)──────(N) DepositPaymentMethod
   │                        │
   │                        │ (shares paymentMethodHash)
   │                        │
   ├──(N) MethodCurrency ───┘  (1 per deposit × method × currency)
   │         │
   │         └── rates: minConversionRate, managerRate, conversionRate, takerConversionRate
   │             oracle: adapter, feed, oracleRate, effectiveOracleRate
   │
   ├──(N) Intent
   │         │── status: SIGNALED → FULFILLED | PRUNED | MANUALLY_RELEASED
   │         │── payment proof: paymentAmount, paymentCurrency, paymentId
   │         └── settlement: releasedAmount, takerAmountNetFees
   │
   ├──(N) DepositFundActivity  (append-only ledger)
   │
   └──(N) DepositDailySnapshot (daily rollup)

QuoteCandidate = denormalized join of Deposit + MethodCurrency + DepositPaymentMethod
                 (optimized for rate-first quoting queries)

MakerStats ←── aggregated from Deposits + Intents (per maker address)
TakerStats ←── aggregated from Intents (per taker address)
MakerPlatformStats ←── per maker × payment method
MakerCurrencyStats ←── per maker × currency

RateManager (1)──(N) RateManagerRate (per method × currency)
     │
     ├──(N) ManagerStats (per deposit under this manager)
     ├──(1) ManagerAggregateStats (totals across all deposits)
     └──(N) ManagerDailySnapshot (daily TVL, volume, fees)

PriceSnapshot ←── daily FX rates (USD/EUR/GBP/etc.)
MakerProfitSnapshot ←── per-intent profit: quote rate vs oracle FX rate
ReferralFeeDistribution ←── per-intent referral fee breakdown
```

### Explicit Schema Edges

- `Deposit -> Intent` via `Intent.depositId` and `Deposit.intents @derivedFrom(field: "depositId")`
- `Deposit -> DepositPaymentMethod` via `DepositPaymentMethod.depositId`
- `Deposit -> MethodCurrency` via `MethodCurrency.depositId`
- `Deposit -> DepositFundActivity` via `DepositFundActivity.depositId`
- `Deposit -> DepositDailySnapshot` via `DepositDailySnapshot.depositId`

### Implicit Joins Used by Handlers and Consumers

- `DepositPaymentMethod <-> MethodCurrency` by `(depositId, paymentMethodHash)`
- `MethodCurrency <-> QuoteCandidate` by identical tuple identity; `QuoteCandidate.id` matches `MethodCurrency.id`
- `Intent <-> ReferralFeeDistribution` by `ReferralFeeDistribution.intentId = Intent.id`
- `Deposit/Intent -> maker stats` by maker address (`Deposit.depositor`)
- `Intent -> taker stats` by taker address (`Intent.owner`)
- `Deposit/MethodCurrency/Intent -> rate-manager entities` by `(chainId, rateManagerAddress, rateManagerId)`
- `MakerProfitSnapshot -> PriceSnapshot` by `priceSnapshotId`

### Denormalized/Projection Entities

- `QuoteCandidate` is a read-optimized projection over `Deposit + DepositPaymentMethod + MethodCurrency`.
- `MakerStats`, `MakerPlatformStats`, `MakerCurrencyStats`, `TakerStats`, `ManagerAggregateStats`, `ManagerStats`, `DepositDailySnapshot`, and `ManagerDailySnapshot` are aggregation/snapshot entities, not raw event mirrors.

## Enum Reference

### `DepositStatus`

- `ACTIVE`: Deposit can still participate in the maker lifecycle. Whether it is currently quoteable also depends on `acceptingIntents`, remaining liquidity, payment-method activity, and a non-zero resolved rate.
- `CLOSED`: Deposit has been explicitly closed on-chain. Quote candidates for closed deposits are deleted.

### `IntentStatus`

- `SIGNALED`: Intent exists and funds may be locked, but settlement is not final yet.
- `FULFILLED`: Intent completed normally.
- `PRUNED`: Intent was cancelled/unlocked on-chain.
- `MANUALLY_RELEASED`: Funds were released through the manual-release path rather than the normal verifier path.

### `PriceSnapshotStatus`

- `LIVE`: Snapshot was fetched during normal live indexing.
- `BACKFILL`: Snapshot was created during historical catch-up or another non-live backfill flow.

### `ProfitStatus`

- `COMPUTED`: Profit could be computed because a usable FX snapshot existed.
- `PENDING`: Profit row exists, but the oracle side of the comparison was unavailable at write time.

## Domain Entities — Full Field Reference

### `Deposit`

Canonical maker-owned escrow position. This is the root entity for most business queries. Deposit rows are created from deposit-received events and then mutated by funding, withdrawal, closing, intent lock/unlock, delegated-rate-manager, and oracle-resolution flows.

**Relationships:**
- Parent of `Intent`, `DepositPaymentMethod`, `MethodCurrency`, `DepositFundActivity`, and `DepositDailySnapshot`
- Indirect source for `QuoteCandidate`
- Optional many-to-one relationship to `RateManager`
- Source record for `MakerStats`, `ManagerStats`, and manager aggregate balances

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Canonical deposit key `escrowAddress_depositId`. This exists because raw on-chain `depositId` is not globally unique across escrows. |
| `chainId` | `number` | Chain where the escrow contract lives. |
| `escrowAddress` | `string` | Escrow contract address that owns the deposit funds and scopes the deposit namespace. |
| `depositId` | `string (BigInt)` | Raw on-chain deposit identifier emitted by the escrow contract. |
| `depositor` | `string` | Maker address that created and owns the deposit. |
| `token` | `string` | ERC20 token being sold. In practice the indexer only materializes supported USDC addresses. |
| `delegate` | `string` | Address currently allowed to manage deposit settings on behalf of the maker. |
| `intentAmountMin` | `string (BigInt)` | Smallest token amount the maker will accept for a single intent. |
| `intentAmountMax` | `string (BigInt)` | Largest token amount the maker will accept for a single intent. |
| `acceptingIntents` | `boolean` | Explicit maker toggle. Quotes should be suppressed when this is `false` even if liquidity still exists. |
| `status` | `DepositStatus` | Coarse lifecycle state. `CLOSED` means the deposit was explicitly closed; it is stronger than merely having no liquidity. |
| `remainingDeposits` | `string (BigInt)` | Immediately available maker liquidity that can still be locked into new intents or withdrawn. |
| `outstandingIntentAmount` | `string (BigInt)` | Liquidity currently reserved by signaled intents that have not been fully resolved yet. |
| `totalAmountTaken` | `string (BigInt)` | All-time amount that actually left the deposit to takers through fulfillment or manual release. |
| `totalWithdrawn` | `string (BigInt)` | All-time amount withdrawn back to the maker through withdrawal events. |
| `totalIntents` | `number` | Total number of intents ever locked against the deposit. |
| `signaledIntents` | `number` | Count of intent-lock events seen for this deposit. |
| `fulfilledIntents` | `number` | Count of intents that finished successfully or via manual release. |
| `prunedIntents` | `number` | Count of intents that were unlocked/cancelled without fulfillment. |
| `successRateBps` | `number` | Deposit-level quality score in basis points. New deposits start at `10000`; later it tracks `fulfilled / total` in basis points. |
| `blockNumber` | `string (BigInt)` | Block in which the deposit was first seen. |
| `timestamp` | `string (BigInt)` | Creation timestamp from the deposit-received event. |
| `txHash` | `string` | Transaction that created the deposit row. |
| `updatedAt` | `string (BigInt)` | Timestamp of the most recent mutation to this deposit row. |
| `rateManagerId` | `string?` | Optional delegated rate-manager identifier currently assigned to the deposit. |
| `rateManagerAddress` | `string?` | Optional rate-manager contract address paired with `rateManagerId`. |
| `delegatedAt` | `string? (BigInt)` | Timestamp when the current delegated manager assignment was applied. |

**Balance identity:** `balance = remainingDeposits + outstandingIntentAmount`
**Gross deposited (all-time):** `remainingDeposits + outstandingIntentAmount + totalAmountTaken + totalWithdrawn`

### `DepositPaymentMethod`

Deposit-scoped payment platform configuration. Each row says "this deposit accepts this payment-method hash, with these payee details and optional gating requirements."

**Relationships:**
- Many-to-one to `Deposit` through `depositId`
- Logical sibling of `MethodCurrency` on `(depositId, paymentMethodHash)`
- One of the three source entities used to materialize `QuoteCandidate`

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `escrowAddress_depositId_paymentMethodHash`. |
| `chainId` | `number` | Chain where the parent deposit lives. |
| `depositId` | `string` | Foreign-key string to `Deposit.id`. |
| `depositIdOnContract` | `string (BigInt)` | Raw on-chain deposit id copied for convenience and external correlation. |
| `paymentMethodHash` | `string` | Canonical bytes32-like payment-method identifier used by contracts and quoting. |
| `intentGatingService` | `string` | Optional external service address/string that must authorize or gate takers before they can use this method. |
| `payeeDetailsHash` | `string` | Hash of the off-chain payee details that the taker must prove they paid. |
| `active` | `boolean` | Method-level on/off toggle. `QuoteCandidate.isActive` also depends on this value. |

### `MethodCurrency`

Per `(deposit, payment method, fiat currency)` pricing configuration. This is the most important rate-resolution entity in the schema. It stores the depositor's fixed floor, delegated manager input, oracle configuration and snapshots, and the final resolved rate that quoting and validation use.

**Relationships:**
- Many-to-one to `Deposit`
- Logical many-to-one to `DepositPaymentMethod` by `(depositId, paymentMethodHash)`
- Optional many-to-one to `RateManager` through `rateManagerId` plus the deposit's `rateManagerAddress`
- Source record for `QuoteCandidate`; the quote row reuses this entity's identity

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `escrowAddress_depositId_paymentMethodHash_currencyCode`. |
| `chainId` | `number` | Chain where the parent deposit lives. |
| `depositId` | `string` | Foreign-key string to `Deposit.id`. |
| `depositIdOnContract` | `string (BigInt)` | Raw on-chain deposit id for cross-checking with contract logs. |
| `paymentMethodHash` | `string` | Payment-method component of the tuple. |
| `currencyCode` | `string` | Fiat currency component of the tuple. |
| `minConversionRate` | `string (BigInt)` | Maker-defined fixed floor for the tuple. In legacy flows this can also be the directly used static rate. |
| `managerRate` | `string? (BigInt)` | Delegated manager quote before floor enforcement and before manager fee is applied. |
| `managerFee` | `string? (BigInt)` | Delegated manager fee rate in 1e18 precision. This does not lower `conversionRate`; it is turned into a taker-facing markup when computing `takerConversionRate`. |
| `conversionRate` | `string? (BigInt)` | Final gross resolved rate used for intent validation and contract-aligned quote logic. |
| `takerConversionRate` | `string? (BigInt)` | Final all-in rate shown to takers. In delegated mode this incorporates manager fee on top of the gross rate. |
| `rateSource` | `string?` | Resolution reason for `conversionRate`: `MANAGER` \| `ORACLE` \| `ESCROW_FLOOR` \| `MANAGER_DISABLED` \| `ORACLE_HALTED` \| `NO_FLOOR`. |
| `rateManagerId` | `string?` | Delegated manager id that supplied the current delegated rate, if any. |
| `adapter` | `string?` | Oracle adapter contract address used to interpret `adapterConfig`. |
| `adapterConfig` | `string?` | Encoded adapter config bytes stored exactly as emitted. |
| `feed` | `string?` | Resolved oracle feed address or feed id after decoding the adapter config. |
| `feedDecimals` | `number?` | Feed decimals used to normalize oracle answers into the shared 1e18 rate format. |
| `spreadBps` | `number?` | Maker-configured markup applied to raw oracle output before final floor/manager resolution. |
| `maxStaleness` | `string? (BigInt)` | Maximum acceptable oracle age in seconds before the tuple is considered stale. |
| `invert` | `boolean?` | Whether the oracle answer must be inverted before being converted into the shared rate representation. |
| `oracleRate` | `string? (BigInt)` | Raw oracle-derived rate before spread markup. |
| `effectiveOracleRate` | `string? (BigInt)` | Oracle rate after applying `spreadBps`. |
| `lastOracleUpdatedAt` | `string? (BigInt)` | Timestamp of the latest accepted oracle datapoint used by this row. |
| `kind` | `string?` | Decoded oracle kind, currently `oracle_chainlink`, `oracle_pyth`, or `oracle_unknown`. |

**Rate resolution order:** Manager rate (if delegated) → Oracle rate (if configured) → Escrow floor (minConversionRate). The `rateSource` field records which path was taken.

### `Intent`

Canonical taker intent row. An `Intent` starts when the taker signals intent and ends in fulfillment or prune. This entity intentionally separates on-chain lifecycle (`status`) from off-chain expiry reconciliation (`isExpired`).

**Relationships:**
- Many-to-one to `Deposit`
- Parent of `ReferralFeeDistribution`
- Feeds `TakerStats`, maker stats rollups, profit snapshots, and manager aggregates

**Lifecycle:** `SIGNALED` → `FULFILLED` | `PRUNED` | `MANUALLY_RELEASED`

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Canonical key `chainId_intentHash`. |
| `intentHash` | `string` | Raw on-chain intent hash. |
| `orchestratorAddress` | `string` | Contract address that coordinated the intent. In legacy v2 this is effectively the escrow address; in newer flows it is the orchestrator. |
| `depositId` | `string` | Foreign-key string to `Deposit.id`. |
| `verifier` | `string` | Verifier contract or address associated with the payment proof. In v21 it is updated again when payment verification arrives. |
| `paymentMethodHash` | `string?` | Payment-method hash associated with the intent. Optional because some legacy flows populate it indirectly. |
| `owner` | `string` | Taker wallet that owns the intent. |
| `toAddress` | `string` | Recipient address for the released token payout. |
| `amount` | `string (BigInt)` | Token amount signaled for the intent. This is the nominal amount, not necessarily the realized release amount. |
| `fiatCurrency` | `string` | Fiat currency signaled at quote time. |
| `conversionRate` | `string (BigInt)` | Quote-time rate captured on the intent. |
| `status` | `IntentStatus` | On-chain lifecycle state only. This does not encode off-chain expiry reconciliation. |
| `isExpired` | `boolean` | Off-chain reconciler flag that says the lock has timed out and liquidity was already unlocked off-chain. An intent can be `status = SIGNALED` and `isExpired = true` at the same time. |
| `signalTxHash` | `string` | Transaction that created/signaled the intent. |
| `signalTimestamp` | `string (BigInt)` | Signal timestamp taken from the emitted event/proof context. |
| `fulfillTxHash` | `string?` | Transaction that fulfilled or manually released the intent. |
| `fulfillTimestamp` | `string? (BigInt)` | Timestamp of fulfillment/manual release. |
| `pruneTxHash` | `string?` | Transaction that pruned/unlocked the intent. |
| `pruneTimestamp` | `string? (BigInt)` | Timestamp of prune/unlock. |
| `expiryTime` | `string (BigInt)` | Canonical expiry timestamp used by the block reconciler. It is refined by lock/extend events after the signal event. |
| `updatedAt` | `string (BigInt)` | Last mutation timestamp for this intent row. |
| `paymentAmount` | `string? (BigInt)` | Actual fiat amount proven by the verifier. This may differ from `amount` in partial-payment scenarios. |
| `paymentCurrency` | `string?` | Actual fiat currency proven by the verifier. This may differ from `fiatCurrency`. |
| `paymentTimestamp` | `string? (BigInt)` | Timestamp contained in the verified payment proof. |
| `paymentId` | `string?` | External payment identifier from the payment rail/provider. |
| `releasedAmount` | `string? (BigInt)` | Gross token amount released from escrow before protocol or referral fees. May differ from `amount`. |
| `takerAmountNetFees` | `string? (BigInt)` | Net token amount actually received by the taker after protocol and referrer deductions. |
| `rateManagerId` | `string?` | Snapshotted delegated manager id relevant to this intent, if a manager fee applied. |
| `managerFee` | `string? (BigInt)` | Snapshotted manager fee rate in 1e18 precision. |
| `managerFeeRecipient` | `string?` | Address that receives the manager fee on settlement. |
| `managerFeeAmount` | `string? (BigInt)` | Signal-time fee estimate based on the signaled intent amount. |
| `realizedManagerFeeAmount` | `string? (BigInt)` | Release-time manager fee based on the actual released amount. |
| `totalReferralFeeAmount` | `string? (BigInt)` | Sum of all `ReferralFeeDistribution.feeAmount` rows written for this intent. |

### `ReferralFeeDistribution`

Per-recipient referral-fee settlement rows for v2.2. The `Intent` stores the aggregate; this entity preserves recipient-level detail.

**Relationships:**
- Many-to-one to `Intent` through `intentId`

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `chainId_intentHash_feeRecipient`. |
| `chainId` | `number` | Chain where the parent intent settled. |
| `intentHash` | `string` | Raw on-chain intent hash. |
| `intentId` | `string` | Foreign-key string to `Intent.id`. |
| `feeRecipient` | `string` | Address that received this referral-fee slice. |
| `feeAmount` | `string (BigInt)` | Actual token amount distributed to `feeRecipient`. |
| `txHash` | `string` | Transaction that emitted the distribution event. |
| `timestamp` | `string (BigInt)` | Settlement timestamp for this distribution row. |

### `QuoteCandidate`

Read-optimized quoting view. This is intentionally denormalized so curator/quote APIs do not need to join `Deposit`, `DepositPaymentMethod`, and `MethodCurrency` at request time.

**Relationships:**
- Derived from exactly one `(Deposit, DepositPaymentMethod, MethodCurrency)` tuple
- `id` intentionally equals the corresponding `MethodCurrency.id`

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Same composite identity as the backing `MethodCurrency`: `escrowAddress_depositId_paymentMethodHash_currencyCode`. |
| `chainId` | `number` | Chain where the quoteable deposit lives. |
| `depositIdOnContract` | `string (BigInt)` | Raw on-chain deposit id. |
| `depositId` | `string` | Foreign-key string to `Deposit.id`. |
| `escrowAddress` | `string` | Escrow contract address copied from `Deposit`. |
| `depositor` | `string` | Maker address copied from `Deposit`. |
| `token` | `string` | Token address copied from `Deposit`. |
| `paymentMethodHash` | `string` | Payment-method hash copied from the tuple. |
| `currencyCode` | `string` | Fiat currency copied from the tuple. |
| `conversionRate` | `string? (BigInt)` | Final gross resolved rate copied from `MethodCurrency`. |
| `takerConversionRate` | `string? (BigInt)` | Final all-in taker-facing rate copied from `MethodCurrency`. |
| `managerFee` | `string? (BigInt)` | Manager fee rate copied from `MethodCurrency`, defaulting to zero if absent. |
| `availableTokenAmount` | `string (BigInt)` | Current immediately available maker liquidity, copied from `Deposit.remainingDeposits`. |
| `maxTokenAvailablePerIntent` | `string (BigInt)` | `min(availableTokenAmount, intentAmountMax)`, used for quote ordering and max-per-intent checks. |
| `maxFiatAvailablePerIntent` | `string (BigInt)` | Fiat value of `maxTokenAvailablePerIntent` using the taker-facing rate. |
| `maxQuoteableFiat` | `string (BigInt)` | Fiat value of the full currently available liquidity using the taker-facing rate. |
| `intentAmountMin` | `string (BigInt)` | Minimum quoteable token amount copied from `Deposit`. |
| `intentAmountMax` | `string (BigInt)` | Maximum quoteable token amount copied from `Deposit`. |
| `successRateBps` | `number` | Deposit-level success signal copied from `Deposit`. |
| `payeeDetailsHash` | `string` | Hashed payee details copied from `DepositPaymentMethod`. |
| `intentGatingService` | `string?` | Optional gating service copied from `DepositPaymentMethod`. |
| `isActive` | `boolean` | Final quoteability flag. It is `true` only when the payment method is active, the deposit is accepting intents, and the taker-facing rate is non-zero. |
| `hasMinLiquidity` | `boolean` | Whether `availableTokenAmount >= intentAmountMin`. |
| `minFiatSupported` | `string (BigInt)` | Fiat value of `intentAmountMin` using the taker-facing rate. |
| `maxFiatSupported` | `string (BigInt)` | Fiat value of `intentAmountMax` using the taker-facing rate. |
| `maxFiatAvail` | `string (BigInt)` | Fiat value of `availableTokenAmount` using the taker-facing rate. |
| `updatedAt` | `string (BigInt)` | Last time the denormalized row was recomputed. |

### `TakerStats`

Per-owner behavioral aggregate. This row is updated from signaled, fulfilled/manual-release, and prune flows. In v21 it also carries a `lockScore` penalty based on how long cancelled intents kept liquidity locked.

**Relationships:**
- Implicit many-to-one from all `Intent` rows whose `owner` matches `TakerStats.owner`

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `chainId_owner`, with the owner lowercased. |
| `chainId` | `number` | Chain on which the taker activity occurred. |
| `owner` | `string` | Lowercased taker address used as the aggregation key. |
| `lifetimeSignaledCount` | `number` | Number of intents ever signaled by this taker. |
| `lifetimeFulfilledCount` | `number` | Number of non-manual intents that fulfilled successfully. |
| `lifetimeManualReleaseCount` | `number` | Number of intents that ended via manual release. |
| `lifetimePruneCount` | `number` | Number of intents that were pruned/cancelled. Same-tx prune-then-fulfill cases are rolled back. |
| `totalCancelledVolume` | `string (BigInt)` | Sum of token amount from cancelled/pruned intents, with rollback if a same-tx prune later fulfills. |
| `totalFulfilledVolume` | `string (BigInt)` | Sum of token amount from fulfilled/manual-release intents. |
| `lockScore` | `string (BigInt)` | Penalty-style score derived from cancelled intent lock duration. Currently meaningful only in the v21 path. |
| `lastIntentAt` | `string? (BigInt)` | Timestamp of the taker's most recent intent signal. |
| `lastFulfilledAt` | `string? (BigInt)` | Timestamp of the taker's most recent fulfillment/manual release. |
| `firstSeenAt` | `string? (BigInt)` | Timestamp of the taker's first observed intent. |
| `updatedAt` | `string (BigInt)` | Last time this aggregate row changed. |

### `MakerStats`

Per-maker aggregate across every deposit owned by the maker on a chain. This is deposit-derived state plus realized-profit rollups.

**Relationships:**
- Implicit aggregation over all `Deposit` rows where `Deposit.depositor = MakerStats.maker`
- Parent summary for `MakerPlatformStats` and `MakerCurrencyStats`

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `chainId_maker`, with maker lowercased in the id. |
| `chainId` | `number` | Chain on which the maker operates. |
| `maker` | `string` | Maker/depositor address used as the aggregation key. |
| `totalAmountTaken` | `string (BigInt)` | Sum of `Deposit.totalAmountTaken` across the maker's deposits. |
| `grossDeposited` | `string (BigInt)` | All-time gross capital committed by the maker, derived per deposit as `remaining + outstanding + taken + withdrawn`. |
| `totalWithdrawn` | `string (BigInt)` | Sum of maker withdrawals across all deposits. |
| `outstandingIntentAmount` | `string (BigInt)` | Sum of liquidity currently locked in active intents across all deposits. |
| `activeDepositCount` | `number` | Number of deposits that are both `ACTIVE` and `acceptingIntents = true`. |
| `totalDepositCount` | `number` | Number of deposit rows ever created for the maker. |
| `fulfilledIntents` | `number` | Sum of `Deposit.fulfilledIntents` across the maker's deposits. |
| `prunedIntents` | `number` | Sum of `Deposit.prunedIntents` across the maker's deposits. |
| `signaledIntents` | `number` | Sum of `Deposit.signaledIntents` across the maker's deposits. |
| `totalIntents` | `number` | Sum of `Deposit.totalIntents` across the maker's deposits. |
| `manualReleaseCount` | `number` | Number of maker fills that happened through manual release. |
| `successRateBps` | `number` | Maker-level fulfillment rate in basis points, derived from aggregate `fulfilledIntents / totalIntents`. |
| `realizedProfitUsdCents` | `string (BigInt)` | Sum of computed realized profit across all maker profit snapshots. |
| `aprBps` | `number?` | Reserved APR-style metric. It is present in the schema but not currently maintained by handlers. |
| `firstSeenAt` | `string? (BigInt)` | Timestamp of the maker's earliest observed deposit. |
| `updatedAt` | `string (BigInt)` | Last time the aggregate changed. |

### `MakerPlatformStats`

Per-maker, per-payment-method aggregate. This lets consumers break a maker's business down by payment rail or method hash.

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `chainId_maker_paymentMethodHash`. |
| `chainId` | `number` | Chain on which the activity occurred. |
| `maker` | `string` | Maker address. |
| `paymentMethodHash` | `string` | Payment-method aggregation dimension. |
| `totalAmountTaken` | `string (BigInt)` | Sum of fulfilled/manual-release volume for this maker-method pair. |
| `fulfilledIntents` | `number` | Count of fulfilled/manual-release intents for this pair. |
| `prunedIntents` | `number` | Count of pruned intents for this pair. |
| `manualReleaseCount` | `number` | Count of manual-release fills for this pair. |
| `realizedProfitUsdCents` | `string (BigInt)` | Sum of realized profit allocated to this maker-method pair. |
| `computedProfitSnapshots` | `number` | Number of profit snapshots that successfully contributed realized profit to this pair. |
| `updatedAt` | `string (BigInt)` | Last time the row changed. |

### `MakerCurrencyStats`

Per-maker, per-fiat-currency aggregate.

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `chainId_maker_currencyCode`. |
| `chainId` | `number` | Chain on which the activity occurred. |
| `maker` | `string` | Maker address. |
| `currencyCode` | `string` | Fiat-currency aggregation dimension. |
| `totalAmountTaken` | `string (BigInt)` | Sum of fulfilled/manual-release volume for this maker-currency pair. |
| `fulfilledIntents` | `number` | Count of fulfilled/manual-release intents for this pair. |
| `prunedIntents` | `number` | Count of pruned intents for this pair. |
| `manualReleaseCount` | `number` | Count of manual releases for this pair. |
| `updatedAt` | `string (BigInt)` | Last time the row changed. |

### `PriceSnapshot`

Daily FX snapshot used to translate local-fiat quote rates into a USD-denominated profitability view.

**Relationships:**
- Referenced by `MakerProfitSnapshot.priceSnapshotId`
- Used indirectly by manager aggregate PnL computation

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `currencyCode_timestampDay`. |
| `currencyCode` | `string` | Normalized fiat currency code of the quote being converted to USD. |
| `timestampDay` | `string (BigInt)` | Start-of-day UTC bucket in seconds. |
| `rateUsd` | `string (BigInt)` | Provider-supplied fiat-to-USD conversion rate in provider precision. |
| `ratePrecision` | `number` | Precision/scaling factor associated with `rateUsd`. |
| `provider` | `string` | Upstream provider name used to fetch the quote. |
| `source` | `string` | Source string or provider endpoint label. |
| `status` | `PriceSnapshotStatus` | Whether this snapshot came from live indexing or backfill. |
| `effectiveAt` | `string (BigInt)` | Timestamp at which the provider says the quote is valid/effective. |
| `retrievedAt` | `string (BigInt)` | Timestamp when the indexer fetched the quote. |
| `createdAt` | `string (BigInt)` | First time this snapshot row was written. |
| `updatedAt` | `string (BigInt)` | Last time this snapshot row was written. Usually equal to `createdAt`. |

### `MakerProfitSnapshot`

Per-intent realized-profit record for makers. This is the bridge between intent settlement and USD-denominated reporting.

**Relationships:**
- One row per settled `Intent` (`id = intentId`)
- Many-to-one to `Deposit`
- Optional many-to-one to `PriceSnapshot`

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Equal to `intentId`, enforcing one profit row per intent. |
| `chainId` | `number` | Chain where the intent settled. |
| `maker` | `string` | Maker address that owned the deposit. |
| `intentId` | `string` | Foreign-key string to `Intent.id`. |
| `depositId` | `string` | Foreign-key string to `Deposit.id`. |
| `fiatCurrency` | `string` | Fiat currency used for the quote/profit comparison. |
| `quoteConversionRate` | `string (BigInt)` | Quote-time rate captured from the intent. |
| `oracleRate` | `string? (BigInt)` | USD-derived market reference rate computed from the linked `PriceSnapshot`. |
| `spreadBps` | `number?` | Basis-point difference between `quoteConversionRate` and `oracleRate`. |
| `amount` | `string (BigInt)` | Token amount used for the profit calculation. |
| `notionalFiatUsdCents` | `string? (BigInt)` | USD-cent value of the local-fiat notional implied by the quote. |
| `feeUsd` | `string? (BigInt)` | Reserved fee field. It is currently written as zero. |
| `realizedProfitUsdCents` | `string? (BigInt)` | Realized profit in USD cents. Can be negative. |
| `priceSnapshotId` | `string?` | Optional reference to the `PriceSnapshot` used to compute `oracleRate`. |
| `status` | `ProfitStatus` | `COMPUTED` when an FX reference existed, `PENDING` otherwise. |
| `createdAt` | `string (BigInt)` | Timestamp when the profit row was created. |
| `updatedAt` | `string (BigInt)` | Last update timestamp for the profit row. |

### `RateManager`

Registry row for a delegated rate manager. A deposit can point at one of these via `(rateManagerAddress, rateManagerId)`.

**Relationships:**
- Parent of `RateManagerRate`
- Parent/source of `ManagerAggregateStats`, `ManagerDailySnapshot`, and `ManagerStats`
- Optional target of deposit delegation

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `chainId_rateManagerAddress_rateManagerId`. |
| `chainId` | `number` | Chain where the manager contract exists. |
| `rateManagerAddress` | `string` | Rate-manager contract address. |
| `rateManagerId` | `string` | On-contract manager identifier. |
| `manager` | `string` | Account recognized as the logical manager/operator. |
| `feeRecipient` | `string` | Account that receives manager fees on settlement. |
| `maxFee` | `string (BigInt)` | Maximum allowed fee configured at manager creation. |
| `fee` | `string (BigInt)` | Current fee rate in 1e18 precision. |
| `minLiquidity` | `string (BigInt)` | Configured minimum liquidity threshold advertised by the manager contract. |
| `name` | `string?` | Optional human-readable name. |
| `uri` | `string?` | Optional metadata URI. |
| `createdAt` | `string (BigInt)` | First-seen timestamp. |
| `updatedAt` | `string (BigInt)` | Last config update timestamp. |

### `RateManagerRate`

Per-manager quote sheet. Each row is a manager-supplied rate for one payment-method/currency pair. Deposits delegated to that manager read these rows when resolving `MethodCurrency.conversionRate`.

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `chainId_rateManagerAddress_rateManagerId_paymentMethodHash_currencyCode`. |
| `chainId` | `number` | Chain where the manager contract exists. |
| `rateManagerAddress` | `string` | Manager contract address. |
| `rateManagerId` | `string` | Manager identifier. |
| `paymentMethodHash` | `string` | Payment-method dimension for the manager quote. |
| `currencyCode` | `string` | Fiat-currency dimension for the manager quote. |
| `managerRate` | `string (BigInt)` | Gross manager-provided rate before floor enforcement. |
| `updatedAt` | `string (BigInt)` | Timestamp of the last rate update event for this pair. |

### `ManagerAggregateStats`

Portfolio-level aggregate for one delegated rate manager. This is the top-level manager reporting row.

**Relationships:**
- One-to-one logical summary for one `RateManager`
- Source for `ManagerDailySnapshot`
- Updated from delegated deposit balance changes and fulfilled intents

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Same identity as the corresponding `RateManager.id`. |
| `chainId` | `number` | Chain on which the manager operates. |
| `rateManagerAddress` | `string` | Manager contract address. |
| `rateManagerId` | `string` | Manager identifier. |
| `manager` | `string` | Manager account/operator. |
| `totalFilledVolume` | `string (BigInt)` | Cumulative token volume filled across all delegated deposits. |
| `totalFeeAmount` | `string (BigInt)` | Cumulative manager fee amount actually earned across fills. |
| `totalPnlUsdCents` | `string (BigInt)` | Cumulative USD-cent PnL measured against daily FX snapshots. |
| `fulfilledIntents` | `number` | Number of fulfilled delegated intents. |
| `currentDelegatedBalance` | `string (BigInt)` | Current delegated TVL: sum of `remainingDeposits + outstandingIntentAmount` across delegated deposits. |
| `currentDelegatedDeposits` | `number` | Number of deposits currently delegated to this manager. |
| `firstSeenAt` | `string? (BigInt)` | First timestamp the manager aggregate was created. |
| `updatedAt` | `string (BigInt)` | Last time the aggregate changed. |

### `ManagerDailySnapshot`

Daily bucketed snapshot for `ManagerAggregateStats`.

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `chainId_rateManagerAddress_rateManagerId_dayTimestamp`. |
| `chainId` | `number` | Chain on which the manager operates. |
| `rateManagerAddress` | `string` | Manager contract address. |
| `rateManagerId` | `string` | Manager identifier. |
| `dayTimestamp` | `string (BigInt)` | Start-of-day UTC bucket in seconds. |
| `tvl` | `string (BigInt)` | End-of-update delegated balance for that day. |
| `delegatedDeposits` | `number` | Number of currently delegated deposits at snapshot time. |
| `dailyVolume` | `string (BigInt)` | Volume filled during that day. |
| `dailyFees` | `string (BigInt)` | Manager fees earned during that day. |
| `dailyPnlUsdCents` | `string (BigInt)` | Daily PnL in USD cents. |
| `dailyFulfilledIntents` | `number` | Number of fulfilled intents on that day. |
| `cumulativeVolume` | `string (BigInt)` | Cumulative filled volume up to this snapshot. |
| `cumulativeFees` | `string (BigInt)` | Cumulative manager fees up to this snapshot. |
| `cumulativePnlUsdCents` | `string (BigInt)` | Cumulative PnL up to this snapshot. |
| `cumulativeFulfilledIntents` | `number` | Cumulative fulfilled-intent count up to this snapshot. |
| `updatedAt` | `string (BigInt)` | Last mutation time for the day's bucket. |

### `DepositFundActivity`

Append-only normalized ledger of deposit funding activity. This is easier to query than replaying all raw event families.

**Relationships:**
- Many-to-one to `Deposit`

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `txHash_logIndex`. |
| `chainId` | `number` | Chain where the activity happened. |
| `depositId` | `string` | Foreign-key string to `Deposit.id`. |
| `depositor` | `string` | Maker address that owns the deposit. |
| `activityType` | `string` | Normalized activity class: `DEPOSIT_RECEIVED`, `FUNDS_ADDED`, `WITHDRAWN`, or `CLOSED`. |
| `amount` | `string (BigInt)` | Token amount relevant to the activity. `CLOSED` can legitimately record zero amount. |
| `blockNumber` | `string (BigInt)` | Block number for the activity. |
| `timestamp` | `string (BigInt)` | Timestamp for the activity. |
| `txHash` | `string` | Transaction hash for the activity. |

### `DepositDailySnapshot`

Daily bucketed snapshot of one deposit's state and realized profitability.

**Relationships:**
- Many-to-one to `Deposit`
- Receives daily-volume and daily-PnL deltas from fulfillment flows

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `depositId_dayTimestamp`. |
| `chainId` | `number` | Chain where the deposit exists. |
| `depositId` | `string` | Foreign-key string to `Deposit.id`. |
| `depositor` | `string` | Maker address that owns the deposit. |
| `dayTimestamp` | `string (BigInt)` | Start-of-day UTC bucket in seconds. |
| `remainingDeposits` | `string (BigInt)` | Deposit liquidity available at the time of the last update to that bucket. |
| `outstandingIntentAmount` | `string (BigInt)` | Deposit liquidity currently locked in intents at the last update. |
| `totalAmountTaken` | `string (BigInt)` | Cumulative taken volume at the last update. |
| `totalWithdrawn` | `string (BigInt)` | Cumulative withdrawn volume at the last update. |
| `signaledIntents` | `number` | Cumulative signal count at the last update. |
| `fulfilledIntents` | `number` | Cumulative fulfillment count at the last update. |
| `prunedIntents` | `number` | Cumulative prune count at the last update. |
| `successRateBps` | `number` | Deposit success rate at the last update. |
| `dailyVolume` | `string (BigInt)` | Volume taken during that day only. |
| `dailyPnlUsdCents` | `string (BigInt)` | Realized PnL accrued during that day only. |
| `cumulativeVolume` | `string (BigInt)` | All-time volume through the deposit as of this bucket. |
| `cumulativePnlUsdCents` | `string (BigInt)` | All-time realized PnL through the deposit as of this bucket. |
| `updatedAt` | `string (BigInt)` | Last mutation time for the day's bucket. |

### `ManagerStats`

Per-deposit stats row for a delegated manager. Where `ManagerAggregateStats` is portfolio-level, `ManagerStats` is deposit-level attribution.

**Relationships:**
- Many-to-one to `Deposit`
- Many-to-one to `RateManager`

| Field | Type | Meaning |
|-------|------|---------|
| `id` | `string` | Composite key `chainId_rateManagerAddress_rateManagerId_depositId`. |
| `chainId` | `number` | Chain on which the delegation exists. |
| `rateManagerAddress` | `string` | Manager contract address. |
| `rateManagerId` | `string` | Manager identifier. |
| `depositId` | `string` | Foreign-key string to `Deposit.id`. |
| `depositor` | `string` | Maker that owns the delegated deposit. |
| `currentDelegatedBalance` | `string (BigInt)` | Current delegated balance for this one deposit: `remainingDeposits + outstandingIntentAmount`. |
| `totalAmountTaken` | `string (BigInt)` | Deposit's all-time taken amount while tracked under the manager. |
| `totalWithdrawn` | `string (BigInt)` | Deposit's all-time withdrawn amount while tracked under the manager. |
| `fulfilledIntents` | `number` | Deposit-level fulfillment count. |
| `prunedIntents` | `number` | Deposit-level prune count. |
| `successRateBps` | `number` | Deposit-level success rate. |
| `updatedAt` | `string (BigInt)` | Last mutation time for the row. |

## ID Format Conventions

| Entity | ID Format |
|--------|-----------|
| Deposit | `{escrowAddress}_{depositId}` |
| Intent | `{chainId}_{intentHash}` |
| MethodCurrency | `{escrow}_{depositId}_{methodHash}_{currencyCode}` |
| QuoteCandidate | same as MethodCurrency |
| DepositPaymentMethod | `{escrow}_{depositId}_{paymentMethodHash}` |
| ReferralFeeDistribution | `{chainId}_{intentHash}_{feeRecipient}` |
| MakerStats | `{chainId}_{makerAddress}` |
| TakerStats | `{chainId}_{ownerAddress}` |
| MakerPlatformStats | `{chainId}_{maker}_{paymentMethodHash}` |
| MakerCurrencyStats | `{chainId}_{maker}_{currencyCode}` |
| PriceSnapshot | `{currencyCode}_{timestampDay}` |
| MakerProfitSnapshot | `{intentId}` |
| RateManager | `{chainId}_{rateManagerAddress}_{rateManagerId}` |
| RateManagerRate | `{chainId}_{rateManagerAddress}_{rateManagerId}_{paymentMethodHash}_{currencyCode}` |
| ManagerAggregateStats | same as RateManager |
| ManagerDailySnapshot | `{chainId}_{rateManagerAddress}_{rateManagerId}_{dayTimestamp}` |
| ManagerStats | `{chainId}_{rateManagerAddress}_{rateManagerId}_{depositId}` |
| DepositFundActivity | `{txHash}_{logIndex}` |
| DepositDailySnapshot | `{depositId}_{dayTimestamp}` |

## Known Currency Hashes

| Currency | Hash |
|----------|------|
| USD | `0xc4ae21aac0c6549d71dd96035b7e0bdb6c79ebdba8891b666115bc976d16a29e` |
| EUR | `0xfff16d60be267153303bbfa66e593fb8d06e24ea5ef24b6acca5224c2ca6b907` |
| GBP | `0x90832e2dc3221e4d56977c1aa8f6a6706b9ad6542fbbdaac13097d0fa5e42e67` |
| CAD | `0x221012e06ebf59a20b82e3003cf5d6ee973d9008bdb6e2f604faa89a27235522` |
| SGD | `0xc241cc1f9752d2d53d1ab67189223a3f330e48b75f73ebf86f50b2c78fe8df88` |
