# Building on the Lithos API

> Reading the SigmaFi book and sending SigmaFi transactions through a Lithos client's /sigmafi/zc API, with the check-then-send pattern, limits, outcomes and examples.

Source: https://lithosprotocol.org/docs/sigmafi/api

**Level:** Advanced

*Assumes you can send HTTP requests and read JSON, and have read the [SigmaFi overview](https://lithosprotocol.org/docs/sigmafi/overview).*

Every Lithos client serves SigmaFi under `/sigmafi/zc/`. The client tracks every ZC box from its Ergo
node, follows the [zcs1 off-chain standard](https://lithosprotocol.org/docs/sigmafi/offchain-standard), and signs with its own wallet, so a
script can read the book and trade without building transactions itself. This page explains how the API
behaves and walks through common flows. Every field of every route is in the [API reference](https://lithosprotocol.org/docs/api), under
**SigmaFi ZC Standard**.

## Before you start

You need the following:

- A running Lithos client with `sigmafi.zc.enabled = true`, which ships on. With it off, every
  `/sigmafi/zc` route answers `503`.
- The client's address. The client listens on port 9000, so a local client is at
  `http://localhost:9000`.
- For anything that signs or reads your wallet, the client's API key, sent in the `api_key` header.
  Setting the key is covered in [Node connection and security](https://lithosprotocol.org/docs/configuration/node#client-api-security).

The following need no key: every read of the book, `POST /sigmafi/zc/assets`, `POST /sigmafi/zc/simulate`
and every `/check` preview that does not read your wallet. The following need the key:
`GET /sigmafi/zc/portfolio`, `GET /sigmafi/zc/activity`, every write that sends, and the `/check` previews
of repay, add collateral, extinguish, claim, wrap, unwrap and cancel, since each reads what your wallet holds.

> **Danger: The key signs with your wallet**
>
> Anyone who holds the API key can spend your client's wallet through these routes. Keep the client's port
> off the open internet.

## Units and identifiers

The API uses the following conventions:

| Value | Format |
|---|---|
| Amounts | Raw units as integers or integer strings: nanoERG for ERG, cents for SigUSD. Responses send them as strings so no client loses precision |
| Market | `ERG` or `SigUSD`, in a path or a body |
| Yields | Integer basis points per 262,800 blocks |
| Heights, durations | Integer block heights and block counts |
| Ids | 64 hex characters: a box id, a bond token id (the order box id), a share token id or a wrap receipt id |

Every read carries `at`: the height, block id and indexed height its snapshot was taken at, a `revision`,
whether the mempool is laid over the confirmed book, and `cut` when the book is at its size cap and left
boxes out.

## Reading the book

The read routes are the following:

| Route | Returns |
|---|---|
| `GET /sigmafi/zc/info` | The snapshot every read answers from: the oracle, each market's contract tree hashes, template hashes and addresses, each expression's hash, the zcs1 defaults and the pinned Sigma-Finance-V2 commit |
| `GET /sigmafi/zc/markets/{market}/asks` | Borrow orders and asks in one market, each with its quote now, status, checks and `borrowedByMe` |
| `GET /sigmafi/zc/markets/{market}/offers` | Lend offers with their curves, budgets, current batcher reward and status |
| `GET /sigmafi/zc/markets/{market}/curves` | The best bid line, the ask dots and line, and market totals, computed by the batcher's own rules |
| `GET /sigmafi/zc/markets/{market}/orderbook` | Asks and bids around a maturity. A bid and an ask are compared only at the same maturity |
| `GET /sigmafi/zc/markets/{market}/fills` | New bonds and ask purchases, newest first, with values at the fill |
| `GET /sigmafi/zc/matches/{id}` | For an offer, what it would buy now in the zcs1 order. For an order or ask, the offers that would take it |
| `GET /sigmafi/zc/auctions` | Open lot auctions and share-vault auctions, with what a buyer pays now |
| `GET /sigmafi/zc/lookup/{id}` | Any ZC box, bond token, share token or wrap receipt: its record, the current box of its chain, any pending spend, and its checks |
| `GET /sigmafi/zc/search?q=` | Open boxes and tokens whose id starts with at least 4 hex characters |
| `POST /sigmafi/zc/assets` | Up to 50 token ids, each with its name, decimals and, for SigmaFi tokens, its proven origin |
| `POST /sigmafi/zc/simulate` | Runs the zcs1 batch with a draft order, offer or ask added, or prices a wallet lend across the best sources |
| `GET /sigmafi/zc/portfolio` | Every bond unit and share token your wallet holds, with cost, mark and the actions open now, and the loans you borrow on |
| `GET /sigmafi/zc/activity` | Your wallet's SigmaFi events, newest first, led by pending ones from the mempool |

Lists page with `limit`, from 1 to 200 and 50 by default, and `cursor`, the `next` value of the last page.
`POST /sigmafi/zc/simulate` allows 5 calls at once per caller, then 1 a second, and answers `429` past
that.

### Polling without waste

Pass the last `at.revision` you saw as `ifRevision` on `GET /sigmafi/zc/info`. The client answers `304`
when nothing any read returns has changed, the mempool included. Re-read the routes you care about only
after a `200`.

### Fill history and wallet history

`GET /sigmafi/zc/markets/{market}/fills` reads the client's own fill index, which starts at
`sigmafi.zc.fillsFromHeight`. Its `status` says how far the index has read:

| Status | Meaning |
|---|---|
| `ready` | The index has read every block the node has indexed |
| `catching-up` | The index is still reading older blocks |
| `loading` | The index has not read its first block yet, including on a chain not yet at the start height |
| `not-configured` | `fillsFromHeight` is 0, so the index is off |
| `disabled` | ZC tracking is off |
| `stale`, `unavailable` | A read failed. The index tries again on its next cycle |

`GET /sigmafi/zc/activity` reads your wallet's transactions from the same start height.

## Sending a transaction

Every write is a pair of routes: `.../check` and the send. Both take the same body.

1. **Check.** `POST .../check` returns a quote and signs nothing. The quote lists what you pay and
   receive, every fee and whether it is spent, locked, refundable or earned, every output that does not
   come to you, the resolved terms, the heights it is valid through, `warnings`, and `refusals`. A write
   that cannot run now answers `200` with its `refusals` filled in.
2. **Send.** `POST` the same body to the send route. The client rebuilds the transaction from current
   state, checks it, signs it and sends it.

Put `limits` in the send body to bound what the rebuilt transaction may do. `maxPay` is the most it may
take from you and `minReceive` the least it must give you, in the action's market unit, with the miner fee
included for ERG. If the rebuilt transaction falls outside them, the send answers `409` and sends
nothing. Copy the bounds from the quote you approved.

A send answers with `txId`, the first output's `boxId`, the minted `assetId` for a fill, `warnings`, and
an `outcome`:

| Outcome | Meaning |
|---|---|
| `accepted` | The node accepted the transaction into its mempool |
| `rejected` | The node refused it. The reason is in the response |
| `uncertain` | The node did not answer clearly. Check `GET /sigmafi/zc/activity` or the transaction id before sending again |
| `held` | The write reads the box a pending oracle refresh creates, and a miner could reach the write first. Nothing was sent yet. The client retries every 30 seconds for 10 minutes, rebuilt and checked against `limits` each time. `retriesUntil` says when it stops. A held write lives in memory, so a restart drops it |

The error statuses are the following:

| Status | Meaning |
|---|---|
| `400` | A malformed field, or terms the contracts refuse |
| `403` | A missing or wrong `api_key` |
| `404` | No such box or token, or not your wallet's |
| `409` | A pending transaction already spends a box this needs, or the rebuild fell outside `limits`. Check again, then resend |
| `422` | Valid but not possible now. The message is the reason `/check` lists in `refusals` |
| `503` | ZC tracking is off or not seeded, or the node, its index or the wallet did not answer. Nothing was sent |

## The write routes

The write routes are the following. Each has a `/check` twin at the same path plus `/check`:

| Route | Action |
|---|---|
| `POST /sigmafi/zc/orders` | Post a borrow order |
| `POST /sigmafi/zc/offers` | Post a lend offer |
| `POST /sigmafi/zc/asks` | List bond units or shares for sale |
| `POST /sigmafi/zc/lots` | Post a lot auction |
| `POST /sigmafi/zc/orders/{boxId}/fill` | Fill an order from your wallet |
| `POST /sigmafi/zc/asks/{boxId}/buy` | Buy from an ask |
| `POST /sigmafi/zc/lots/{boxId}/buy` | Buy a lot at its current price |
| `POST /sigmafi/zc/vaults/{boxId}/buy` | Buy an open share-vault auction |
| `POST /sigmafi/zc/vaults/{boxId}/pull` | Pull a settled loan into its share vault, keeping the pull fee |
| `POST /sigmafi/zc/bonds/{assetId}/repay` | Repay a loan, optionally from its collateral |
| `POST /sigmafi/zc/bonds/{assetId}/recollateralize` | Add collateral |
| `POST /sigmafi/zc/bonds/{assetId}/liquidate` | Liquidate a loan the rule allows, keeping the fee reserve |
| `POST /sigmafi/zc/bonds/{assetId}/extinguish` | Close your own loan with its circulating unit |
| `POST /sigmafi/zc/bonds/{assetId}/fractionalize` | Put a bond unit into a share mint request |
| `POST /sigmafi/zc/claims/{tokenId}` | Claim a settled loan with its unit or shares |
| `POST /sigmafi/zc/wraps` | Wrap a token |
| `POST /sigmafi/zc/wraps/{receiptId}/unwrap` | Unwrap a token |
| `POST /sigmafi/zc/mints/{boxId}` | Run a pending share or wrap mint, keeping the mint fee |
| `POST /sigmafi/zc/boxes/{boxId}/cancel` | Cancel an order, offer, ask, lot or request you made |

## Example: posting an order

The following body asks for a 10 ERG loan repaying 10.5 ERG at a fixed maturity about 60 days out,
against 25 ERG of collateral, liquidated at a 150% oracle ratio:

```json title="order.json"
{
  "market": "ERG",
  "principal": "10000000000",
  "repayment": "10500000000",
  "timing": { "mode": "fixed", "blocks": 43200 },
  "collateral": { "nanoErg": "25000000000", "tokens": [] },
  "rule": { "kind": "oracle", "ratioBps": 15000 }
}
```

The body's fields are the following:

| Field | Meaning |
|---|---|
| `principal`, `repayment` | nanoERG |
| `timing` | `blocks` from now, snapped to the 21,600-block grid. Add `"exact": true` to keep the height, or use `{ "mode": "term", "duration": ... }` or a window |
| `rule` | The oracle rule at 150%. Its oracle age defaults to 60 blocks, and the fill guard defaults to the same ratio |

Preview it, then send it with the API key:

```bash
curl -s -X POST http://localhost:9000/sigmafi/zc/orders/check \
  -H "Content-Type: application/json" -d @order.json

curl -s -X POST http://localhost:9000/sigmafi/zc/orders \
  -H "Content-Type: application/json" -H "api_key: YOUR_API_KEY" -d @order.json
```

The quote's `terms` show the snapped maturity and the expiry, `fees` show the 0.005 ERG expiry fee as
refundable, and `matchesNow` shows the simulation of this order against the book: which offers would
fill it now.

## Example: lending to the best order

To lend from your wallet, do the following:

1. Read `GET /sigmafi/zc/markets/ERG/asks` and pick an order. Each listing's quote gives its yield and
   principal now, and its checks say whether the client could prove it.
2. Call `POST /sigmafi/zc/orders/{boxId}/fill/check` with `{}`, or with `maturity` for a window order.
3. Confirm the quote's `paysNanoErgs` and that `refusals` is empty.
4. Send `POST /sigmafi/zc/orders/{boxId}/fill` with the same body and `limits`, for example
   `{"limits": {"maxPay": "10060000000"}}`.

The response's `assetId` is your new bond token. `GET /sigmafi/zc/activity` shows the fill while it is
pending, and `GET /sigmafi/zc/portfolio` lists the unit.

## Example: claiming when a loan ends

Read `GET /sigmafi/zc/portfolio`. A settled holding lists a claim among its open actions. Call
`POST /sigmafi/zc/claims/{tokenId}/check` with the bond token or share token id. For shares, a quote with
`requires: ["pull"]` or `requires: ["auction"]` names what must happen first. Anyone can run the pull
with `POST /sigmafi/zc/vaults/{boxId}/pull`, and batchers do so for the fee.

## Next steps

- [API reference](https://lithosprotocol.org/docs/api): every route's request and response schema.
- [The zcs1 off-chain standard](https://lithosprotocol.org/docs/sigmafi/offchain-standard): the rules the client follows when it builds for you.
- [ZC Standard contracts](https://lithosprotocol.org/docs/sigmafi/contracts): the boxes behind every record the API returns.
- [The Lithos client and panel](https://lithosprotocol.org/docs/extensions/sigmafi-bonds): the panel built on these same routes.
