> For the complete documentation index, see [llms.txt](https://docs.anchored.finance/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.anchored.finance/trading-api/getting-started/product-and-contracts.md).

# RWA Product Overview

This page explains the contract and accounting model behind the RWA API. The API does not replace on-chain rules. It helps you **build `StockRouter` calldata**, **submit or delegate transactions**, and **track state** across wallet balances, `Cashier`, `Stock`, and asynchronous settlement.

If you are debugging a concrete trade, start with [trader-questions.md](/trading-api/getting-started/trader-questions.md). This page explains the system design; the playbook turns it into request, execution, and reconciliation checks.

## Overall Design

The RWA API supports funding, market and limit orders, cash and stock movement between wallet and contracts, and portfolio state queries. It behaves like a trading account at the API layer, but accounting and permissions are enforced by on-chain contracts. The API prepares the right transactions and tracks asynchronous results after those transactions are mined.

The system is built from on-chain contracts plus backend processing. The contracts hold accounting state and enforce the transaction path. Backend processing connects that on-chain state to market execution, final settlement, status updates, and API indexing.

Core on-chain contracts:

| Contract         | Role                                                                                                                                                                        |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `StockRouter`    | Public entrypoint. It receives transactions, uses ERC-20 allowance as spender when wallet tokens are needed, and calls `Cashier` or `Stock` with the original user address. |
| `Cashier`        | Tracks `mUSD`. The API surfaces this as `mUsdBalance`. Deposits increase it; withdrawals deduct it.                                                                         |
| `Stock`          | Tracks stock order state and stock tokens credited to users as `Stock.stockBalance`, surfaced by the API as `exchangeBalance`. Plain sells spend this balance.              |
| `OneClickRouter` | Optional delegated execution router. It forwards approved One Click actions to `StockRouter` while preserving the original user address.                                    |

With these contracts, a user can:

| User need       | What the product supports                                                                                                        |
| --------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Fund account    | Convert approved USDC into `mUSD`.                                                                                               |
| Buy stock       | Use `mUSD`, or use `/orders/with-deposit/*` to deposit cash and buy in one transaction.                                          |
| Sell stock      | Sell from `exchangeBalance`, or use `/orders/with-deposit/*` to deposit approved wallet stock and sell in one transaction.       |
| Withdraw cash   | Convert `mUSD` back to USDC.                                                                                                     |
| Move stock      | Use `/stock/deposits/*` to deposit wallet stock into `Stock`, or `/stock/withdrawals/*` to withdraw `exchangeBalance` to wallet. |
| Track portfolio | Read wallet balances, `mUsdBalance`, `exchangeBalance`, orders, and cash operation status.                                       |

The API prepares `StockRouter` transactions and indexes the lifecycle after submission. A mined transaction is not always the final business state; orders, cash operations, and portfolio balances can update after backend processing and settlement.

## Core Accounting Concepts

### mUSD

`mUSD` is a 1:1 USD-backed accounting unit reflecting real-time purchasing power. It is a digital representation of credit exclusively for Anchored RWA trading. `mUSD` is not a cryptocurrency, stablecoin, or transferable virtual asset. In this API guide, treat `mUSD` as the accounting balance a user can use to buy RWA stock or request a withdrawal.

| Concept              | Where it lives   | What it means                                                                                                                                                                         |
| -------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mUSD`               | `Cashier`        | Used for buys and withdrawals. The API surfaces this as `mUsdBalance`.                                                                                                                |
| USDC wallet balance  | User wallet      | ERC-20 cash token. Must be deposited before it becomes `mUSD`.                                                                                                                        |
| Stock wallet balance | User wallet      | ERC-20 stock token held directly by the user. `StockRouter` can pull it only after user approval.                                                                                     |
| `Stock.stockBalance` | `Stock` contract | Accounting record for ERC-20 stock tokens held by `Stock` and credited to the user. The API surfaces this as `exchangeBalance`. Bought stock lands here; plain sells spend from here. |
| `walletAllowance`    | ERC-20 allowance | Whether `StockRouter` can pull a wallet token for a deposit or other token-pulling flow.                                                                                              |

Stock `walletBalance` and `exchangeBalance` are different. `walletBalance` is the ERC-20 stock token in the user's wallet. `exchangeBalance` is the API view of `Stock.stockBalance`, where stock is held by `Stock` and credited to the user. Plain sells spend `exchangeBalance`; wallet-held stock must be approved before `StockRouter` can pull it into `Stock` for selling.

### Deposit and Withdrawal Conversion

Cash movement is not just an on-chain token transfer. Deposited USDC ultimately needs to become USD usable for trading and settlement, and withdrawals need cash to come back before USDC can be paid out. That final cash path can take time.

To reduce API-visible waiting time, `Cashier` uses pre-funded buffers. When a buffer can safely cover the request, `Cashier` can apply the result immediately while final cash settlement catches up later.

Deposits convert wallet cash tokens into `mUSD`. The user first approves `StockRouter` as the cash token spender, then submits a deposit; `StockRouter` transfers the token to `Cashier`. If the deposit is instant, `Cashier` credits `mUSD` immediately. If it is queued, `mUSD` is credited after final cash settlement.

Withdrawals convert `mUSD` back into wallet cash tokens. The user requests a withdrawal through `StockRouter`, and `Cashier` deducts `mUSD`. If the withdrawal is instant, USDC is sent to the wallet immediately. If it is queued, USDC is sent after final cash settlement.

A mined transaction means the request reached the contracts. For queued operations, the final `mUSD` credit or USDC payout can happen later. See [cash/buffer-mechanism.md](/trading-api/cash-operations/buffer-mechanism.md) for buffer rules.

## Buy and Sell Paths

* **Plain buy:** spends existing `mUSD`.
* **Order-with-deposit buy:** uses approved cash token allowance, requires instant deposit, credits `mUSD`, then places the buy in one transaction.
* **Plain sell:** spends existing `exchangeBalance`, the API view of `Stock.stockBalance`.
* **Order-with-deposit sell:** transfers approved wallet stock into `Stock`, then places the sell in one transaction.

Buy paths lock `mUSD` before execution. A plain buy uses existing `mUSD`; an order-with-deposit buy first transfers approved cash token to `Cashier` and credits `mUSD`, but only when instant deposit is available and the buffer can cover the conversion.

```mermaid
sequenceDiagram
    participant U as User
    participant R as Contract: StockRouter
    participant C as Contract: Cashier
    participant S as Contract: Stock
    participant B as Backend bots

    alt Plain buy
        U->>R: place buy order
        R->>C: Lock existing mUSD
    else Order-with-deposit buy
        U->>R: deposit cash and place buy
        R->>C: Transfer cash token and credit mUSD
        R->>C: Lock mUSD
    end

    B->>B: Execute order
    B->>C: Apply mUSD spend or refund
    B->>S: Credit bought stock
    U->>U: Query API for order and balances
```

Sell paths lock stock before execution. A plain sell uses existing `exchangeBalance`; an order-with-deposit sell first transfers approved wallet stock into `Stock` and credits it there.

```mermaid
sequenceDiagram
    participant U as User
    participant R as Contract: StockRouter
    participant S as Contract: Stock
    participant C as Contract: Cashier
    participant B as Backend bots

    alt Plain sell
        U->>R: place sell order
        R->>S: Lock exchangeBalance
    else Order-with-deposit sell
        U->>R: deposit wallet stock and place sell
        R->>S: Transfer wallet stock and credit stockBalance
        R->>S: Lock stockBalance
    end

    B->>B: Execute order
    B->>S: Return unfilled stock if needed
    B->>C: Credit mUSD proceeds
    U->>U: Query API for order and balances
```

Market buys specify maximum `mUSD` to spend; market sells specify stock quantity. Limit orders specify quantity, limit price, and `timeInForce`; current production contracts accept only `DAY`. Limit orders can remain open and can be canceled while open. `txHash` is available as soon as the transaction is broadcast. `orderId` is created by the on-chain placement transaction and becomes available after the transaction is mined and indexed.

Cash endpoints are only for cash-token flows into or out of `Cashier`. Use `/stock/deposits/*` and `/stock/withdrawals/*` for stock token movement.

Any router flow that pulls wallet tokens requires ERC-20 **approve** first. Cash deposits require approval for the cash token; stock deposits require approval for the stock token. See [cash/deposits.md](/trading-api/cash-operations/deposits.md).

## Fees

Fees can appear in both cash operations and order results. Do not hardcode fee assumptions; read the returned fields from operation and order responses.

| Area            | Common fields                                          | Meaning                                                              |
| --------------- | ------------------------------------------------------ | -------------------------------------------------------------------- |
| Cash operations | `amount`, `creditAmount`, `feeAmount`                  | Token amount, resulting `mUSD`, and cash operation fee when present. |
| Order history   | `mintFee`, `protocolFee`, `settlePay`, `settleReceive` | Trading/mint/protocol fees and final fill amounts when present.      |

For deposits, the credited `mUsdBalance` may differ from the token amount if a fee applies. For orders, final received stock or cash depends on traditional-market execution: orders can fill at the executed price, partially fill, or receive no fill. Use settlement fields such as `settlePay`, `settleReceive`, `mintFee`, and `protocolFee` as the authoritative final amounts, not only the original order input.

## Contract stack (integrator view)

State-changing transactions go through **`StockRouter`**. When wallet tokens are needed, `StockRouter` uses the user's ERC-20 allowance as spender and transfers the tokens to `Cashier` or `Stock`; it does not custody deposits as the final destination.

```mermaid
flowchart TB
    User[User wallet]
    OCR[OneClickRouter optional]
    Router["StockRouter<br/>API calldata target"]

    Cashier["Cashier<br/>mUSD"]
    Stock["Stock<br/>orders and stockBalance"]

    User -->|"direct tx"| Router
    User -.->|"EIP-712 delegate"| OCR
    OCR -->|"ERC-2771 forward"| Router

    Router --> Cashier
    Router --> Stock

    Cashier -.- C1["cash deposits and withdrawals<br/>change mUSD"]
    Stock -.- S1["orders<br/>stockBalance"]
```

Use `x-api-p: Anchored` for Anchored RWA trading. The active API docs do not require other product contexts.

## Router operations map to API flows

Calldata responses give `toAddress`, `value`, and `callData` for your wallet client. `toAddress` is the `StockRouter` address. See [guides/demo-code.md](/trading-api/guides/demo-code.md).

| User action              | Router method      | Self-submit endpoint                         | One Click endpoint              |
| ------------------------ | ------------------ | -------------------------------------------- | ------------------------------- |
| Deposit cash             | `deposit`          | `POST /cash/deposits/calldata` then `/tx`    | `POST /cash/deposits/send`      |
| Withdraw cash            | `withdraw`         | `POST /cash/withdrawals/calldata` then `/tx` | `POST /cash/withdrawals/send`   |
| Market buy or plain sell | `placeMarketOrder` | `POST /orders/calldata` then `/tx`           | `POST /orders/send`             |
| Limit buy or plain sell  | `placeLimitOrder`  | `POST /orders/calldata` then `/tx`           | `POST /orders/send`             |
| Cancel limit             | `cancelLimitOrder` | `DELETE /orders/{orderId}/calldata`          | `DELETE /orders/{orderId}/send` |

Stock deposit and withdrawal are exposed through `/stock/deposits/*` and `/stock/withdrawals/*`.

## Portfolio API vs on-chain state

Use `GET /users/{userId}/balance` as the API view of wallet and exchange state.

| Field             | Meaning                                   | Integration note                                                         |
| ----------------- | ----------------------------------------- | ------------------------------------------------------------------------ |
| `mUsdBalance`     | `mUSD` tracked by `Cashier`               | Use for buy power and withdrawable credit                                |
| `walletBalance`   | ERC-20 tokens in wallet                   | Custody balance; `StockRouter` needs allowance before it can pull tokens |
| `exchangeBalance` | API name for `Stock.stockBalance`         | Use for plain sell availability                                          |
| `walletAllowance` | Token approval to spender / `StockRouter` | Check before token-pulling flows                                         |

Bought stock normally appears as `exchangeBalance` first because the ERC-20 stock tokens are held by `Stock` and credited to the user there. A user can withdraw stock from `Stock.stockBalance` to wallet custody. If wallet-held stock should be sold, the user must approve `StockRouter`; the selected flow can then deposit the stock into `Stock.stockBalance` separately or as part of the sell transaction. For API checks, use `mUsdBalance` for buy power and `exchangeBalance` for sell power.

## Two execution modes (same contracts)

| Mode        | How it works                                                                                                                |
| ----------- | --------------------------------------------------------------------------------------------------------------------------- |
| Self-submit | API returns calldata; the user wallet signs and broadcasts the `StockRouter` transaction; the integration records `txHash`. |
| One Click   | User signs delegation once; `/send` submits through `OneClickRouter` to the same `StockRouter` methods.                     |

One Click is scoped for safety: the delegate wallet is bound to one user wallet, limited to supported RWA router actions, cannot freely transfer user ERC-20 tokens, and can be disabled.

## Design principles

| Principle           | What it means for integrators                                                                                                                                               |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Router-only entry   | API calldata targets `StockRouter`; state-changing integrations should not call `Cashier` or `Stock` directly.                                                              |
| Lock then settle    | Open orders lock `mUSD` or `Stock.stockBalance`; final balances update asynchronously.                                                                                      |
| Off-chain execution | Quotes and fills come from trading services; chain state catches up asynchronously.                                                                                         |
| Wallet vs exchange  | Portfolio shows both wallet and exchange balances; plain sells use `exchangeBalance`, while wallet-held stock can be pulled into `Stock` by an approved `StockRouter` flow. |
| Cash timing         | Deposits/withdrawals can be instant or queued; watch `operationStatus`.                                                                                                     |

## Where to go next

| Step            | Doc                                                                                                                         |
| --------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Authenticate    | [../authenticate/](https://github.com/AnchoredLabs/anchored-knowledge/blob/main/02-products/rwa/api/authenticate/README.md) |
| Trader playbook | [trader-questions.md](/trading-api/getting-started/trader-questions.md)                                                     |
| Portfolio       | [../portfolio/overview.md](/trading-api/portfolio/overview.md)                                                              |
| Trading         | [../trading/overview.md](/trading-api/trading/overview.md)                                                                  |
| Cash            | [../cash/](/trading-api/cash-operations/cash.md)                                                                            |
| Demo code       | [../guides/demo-code.md](/trading-api/guides/demo-code.md)                                                                  |
| Reference       | [../reference/](/trading-api/reference/reference.md)                                                                        |

Deep contract docs: [anchored-contracts/docs/contract-architecture.md](https://github.com/AnchoredLabs/anchored-contracts/blob/main/docs/contract-architecture.md) · [anchored-contracts/docs/flows/](https://github.com/AnchoredLabs/anchored-contracts/blob/main/docs/flows/README.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.anchored.finance/trading-api/getting-started/product-and-contracts.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
