Metadata-Version: 2.4
Name: olive-solana-sdk
Version: 4.2.0
Summary: Async Python SDK for market makers quoting Olive Solana options
Project-URL: Documentation, https://devnet-docs.olive.ag
Project-URL: Repository, https://github.com/macols77/olive
Project-URL: Issues, https://github.com/macols77/olive/issues
Author: Olive
License-Expression: MIT
License-File: LICENSE
Keywords: market-maker,olive,options,rfq,solana
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: jsonschema<5,>=4.23
Requires-Dist: solders<1,>=0.26
Requires-Dist: websockets<18,>=15
Provides-Extra: dev
Requires-Dist: build<2,>=1.2; extra == 'dev'
Requires-Dist: mypy<2,>=1.15; extra == 'dev'
Requires-Dist: pytest-asyncio<2,>=0.25; extra == 'dev'
Requires-Dist: pytest<10,>=8.3; extra == 'dev'
Requires-Dist: ruff<1,>=0.11; extra == 'dev'
Requires-Dist: twine<7,>=6; extra == 'dev'
Requires-Dist: types-jsonschema<5,>=4.23; extra == 'dev'
Description-Content-Type: text/markdown

# Olive Solana Python SDK

Olive's Long Calls and Long Puts are cash-settled: both pay intrinsic value in
USDC, and holders never supply an exercise payment.

This SDK implements the V14 program (`OLIVE_OPTIONS_PROGRAM_ID`; the deployment's id comes from `olive.env`)
and the native `/maker/v4/ws` protocol (`protocolVersion` `5.0`) and nothing else. There is no translation or
compatibility layer: earlier clients are refused by the server, and quotes signed for earlier programs cannot be carried
forward. 4.0 is a hard cut: the bot API is the one shape below (see the CHANGELOG for what was removed).

`olive_solana` is the maker-facing surface. The V14 program contract the maker needs (account decoders, the generic
instruction codec, quote digests, PDAs, and the part of the risk mirror the need model uses) is `olive_solana.v14`. The Python SDK is maker-only: keeper and
settlement builders (Lazer, events, compute budgets) are in the TypeScript SDK. 4.0 ships no V13 code.

What can go wrong and who handles it: [Risks and who handles them](https://devnet-docs.olive.ag/developers/maker-risks).

## Install

```bash
# From this repository:
pip install -e "packages/python-sdk"

# After the distribution is published:
pip install "olive-solana-sdk"
```

Python 3.11 or newer is required. The SDK needs no database.

## Write a bot

A maker bot is four functions and one setting. `ManagedMaker` does everything else: it connects, checks and signs your
quotes, reconnects, keeps your book (`maker.book`, rebuilt from Olive on every connect: no database), runs Olive's
onboarding test request through your `on_entry` (so "Ready" means your pricer answered), declines and alerts when your
pricing fails, logs every step, and turns every money or operations situation into an alert with one `action` sentence.

| You write | What it does |
| --- | --- |
| `on_entry(rfq)` | Price a sale: a user buys a call or put from you. Return `rfq.quote(premium=...)` or `rfq.decline(reason)`. |
| `on_exit(rfq)` | Price a buyback: a holder sells back early. Return `rfq.quote(exit_amount=...)` or `rfq.decline(reason)`. |
| `on_fill(fill)` | Hedge. One function for both sides: `fill.side` is `"entry"` or `"exit"`, `fill.data` the whole fill. |
| `on_alert(alert)` | Page a human. Every money or operations situation arrives here with a stable `code`, a plain `message`, one `action` sentence (what to do now) and `alert.data` with the amount, the deadline, the expiry, the bucket and the position. |
| `funding_signer` | The one money setting: who signs deposits and the buyback allowance. `"none"` (alerts only), `LocalKeypairFundingSigner` or `FordefiApiFundingSigner`. |

Olive checks your margin before it sends you a request, again when you quote and when your quote is selected, and the
program checks it at the fill across your whole book, so the bot needs no margin code.

```python
import asyncio

from olive_solana import MakerAlert, MakerFill, ManagedEntryRfq, ManagedExitRfq, ManagedMaker


# Price a sale. rfq.leg is the call or put the user buys (kind_name, strike_e8, size, maturity).
def on_entry(rfq: ManagedEntryRfq):
    premium = my_premium(rfq.leg, rfq.request)  # USDC base units for rfq.leg.size, or None
    return rfq.quote(premium=premium) if premium else rfq.decline("outside_risk_limits")


# Price a buyback of rfq.request["fractionBps"] of the position. It is paid from your funding wallet.
def on_exit(rfq: ManagedExitRfq):
    amount = my_buyback(rfq.leg, rfq.request)
    return rfq.quote(exit_amount=amount) if amount else rfq.decline("outside_risk_limits")


# A sale or a buyback, final on chain; maker.book already reflects it. Olive may deliver a fill twice:
# hedge to the target your book implies, never by adding the fill's size.
async def on_fill(fill: MakerFill) -> None:
    await my_hedger.rebalance(maker.book)


# alert.code is stable (funding_due, true_up_pending, buyback_allowance_low, ...); alert.message is plain English and
# alert.action is the one thing to do now ("Approve the pending deposit in your custody.").
def on_alert(alert: MakerAlert) -> None:
    my_pager.send(alert.severity, alert.code, f"{alert.message} {alert.action}", alert.data)


# Reads olive.env and the bot key file (OLIVE_QUOTE_SIGNER_KEYPAIR); SOLANA_RPC_URL lets the SDK plan funding deadlines.
maker = ManagedMaker.from_env(
    on_entry=on_entry, on_exit=on_exit, on_fill=on_fill, on_alert=on_alert,
    funding_signer="none",  # alerts only: your desk deposits and sets the buyback allowance by hand
)
asyncio.run(maker.run())
```

`maker.book` is a read-only mapping of every active position of the session's assets, keyed by position address. The SDK
rebuilds it from Olive on start and every reconnect, and keeps it current from fills, buybacks, redemptions, expiries and
handovers.

### What your pricer gets, and how long it has

- **Units.** `rfq.leg.size` is in underlying base units (`rfq.request["underlyingDecimals"]`), `rfq.leg.strike_e8` is USD ×
  1e8, and `premium` / `exit_amount` are whole USDC base units (1 USDC = 1,000,000): use `round(usd * 1_000_000)`, never a float.
- **The rules a quote must meet.** A premium above 0 for the quote's maximum size (the user's fill must pay at least 5 USDC,
  so a maximum premium under 5 USDC can never fill and the SDK declines it); an exit amount above 0. There is no budget
  field: you quote any price and the app warns the user.
- **Entries are a price per contract up to a maximum size (partial fills).** `rfq.quote(premium=...)` is the premium for the
  size the request asks for (`rfq.leg.size`), the most the user may buy. The user is filled the largest size their amount buys
  at your price per contract: `fill_premium(premium, fill_qty, max_qty)` is `ceil(premium * fill / max)`, the entry fee is `min(notional fee, premium-cap fee)` on that fill (`protocol_fee`, `premium_cap_fee`, `notional_fee`),
  and one fill happens per quote. The RFQ's `feeBps` is the premium cap in basis points (750 at launch; `fee_premium_cap_bps` in this SDK). It is also
  the signed quote's `fee_bps`: `ManagedMaker` echoes it, and a custom quote must echo the RFQ's value, never a hardcoded one. The notional rate is
  protocol config and is not signed. To quote a smaller maximum pass `max_size` (underlying base units;
  `rfq.quote_usd(usd, max_size=0.25)` takes units): `premium` is then the premium for `max_size`, and it may not exceed the
  request. `min_size` is the smallest fill you accept (default **0: any size**; the fill must still pay at least 5 USDC). A
  maker that hedges per quote can set `min_size` up to `max_size` for all-or-nothing; `min_size` above `max_size` is declined,
  never signed. Your capacity is reserved for the maximum while the quote lives and freed when it fills or expires.
- **Time.** A first auction is open up to 1 s after the request, a refresh 700 ms (never under 100 ms after the last invitation). Your handler gets `pricing_timeout_ms` (default
  `DEFAULT_PRICING_TIMEOUT_MS`, 800 ms; 0 turns it off). An `async def` handler is cancelled at the limit; a plain `def` runs
  on the event loop, holds up the other requests and cannot be interrupted (one that finishes late is declined `too_slow`), so
  write CPU-heavy pricing as `async def on_entry(rfq): return await asyncio.to_thread(price, rfq)`. A signed quote is firm
  until its expiry: quotes live what the RFQ asks (`maxQuoteLifetimeSeconds`, 10 s at launch), and the price band (100 bps around the reference price by default) protects it.
- **When pricing fails, the SDK says so.** A handler that raises, runs past `pricing_timeout_ms` or returns an invalid quote
  (not whole base units, under the minimum, neither `rfq.quote(...)` nor `rfq.decline(...)`) makes the SDK
  decline the RFQ (`SDK_DECLINE_REASONS`: `pricer_error`, `too_slow`, `too_slow_for_auction`, `invalid_quote`), log one line saying why, call
  `on_error`, and raise `handler_failed` or `quote_invalid`. The next request is priced as usual.

### The money setting

`funding_signer` is required. The SDK works out what each funding deadline (24 hours before an expiry, when the full margin
requirement must be in your margin account) needs from your maker's accounts and alerts 36, 30 and 25 hours before it
(`funding_due`), then from the deadline while money is missing (`funding_overdue`, `deadline_roll_pending`,
`underfunded_past_deadline`). It reads the accounts over `SOLANA_RPC_URL` (with `from_env`) or
`funding=ManagedFundingOptions(rpc=rpc_multiple_accounts_reader(url))`. The alerts come from Olive's funding notices
(`maker.funding_notice`, the calculation that also pauses routing), so a bot without a reader still gets them; with one the
local calculation cross-checks each notice and alerts for a 25 h or overdue need Olive did not notice.

- **`"none"`.** The SDK never moves money. Each alert carries the amount and the deadline; your desk deposits and sets the
  buyback allowance by hand.
- **`LocalKeypairFundingSigner(keypair, rpc)`.** A key in this process signs and sends. For tests and a small float wallet.
- **`FordefiApiFundingSigner(vault_id=..., rpc=...)`.** Your Fordefi vault signs after your Fordefi policy approves (the
  Fordefi API path). While a deposit waits there, `funding_due` / `funding_overdue` say "Approve the pending deposit in your
  custody." (`action`) with `data["waitingOn"] == "custody"`.
  Approval stays with your Fordefi policy; watch the first requests in Fordefi and keep your own alerting on funding deadlines.
- Any other custody: implement `FundingSigner` (`submit(prepared, purpose=..., reference=...)` and
  `wait_landed(handle, timeout_ms)`).

With a signer, the SDK asks it for each deposit (custody approves it; nothing moves without that approval) and keeps the
buyback allowance topped up through it. Olive builds every transaction unsigned (`maker.prepareDeposit`,
`maker.prepareAllowance`); the SDK checks it instruction by instruction against the pinned USDC mint (`OLIVE_USDC_MINT`)
before the signer sees it. Prepared transactions carry a recent blockhash (no durable nonces); a custody signer signs with its own fresh one, as Fordefi does. A signer needs `usdc_mint` and a need reader.
Run one `ManagedMaker` per maker: pending requests live in the process's memory.

### Alerts

| `code` | When | Key `data` |
| --- | --- | --- |
| `funding_due` | 36, 30 and 25 hours before a funding deadline | `amount`, `deadline`, `reasons`, `onTheWay`, `request` |
| `funding_overdue` | from the deadline while money is missing (hourly for 6 hours, then every 6 hours) | as `funding_due`; `blocked` when the maker is defaulted or inactive |
| `deadline_roll_pending` | a deadline passed and its buckets have not rolled yet: entries wait for the roll | as `funding_due` |
| `underfunded_past_deadline` | the margin account is short after a funding deadline: entries and withdrawals are refused until you deposit | as `funding_due` |
| `funding_ok` | an alerted need is covered | `need` |
| `true_up_pending` | an expiry settled short: pay within 4 hours | `amount`, `deadline`, `expiry` |
| `credit_breached` | your need is above what your margin account carries; sales that need new margin wait | `amount` (over the limit), `creditLimit`, `need`, `poolBalance` |
| `routing_paused` / `routing_ok` | Olive stopped / resumed sending you entry requests | `reason`, `amount`, `expiry`, `bucket` / `resumedAt` |
| `not_receiving_rfqs` | Olive is not routing entry requests to some markets | `reasons`, `markets` |
| `buyback_allowance_low` | the allowance is low, its refill failed, or its 24 h refill budget is used | `current`, `wanted`, `needed` |
| `unquoted_exit` | a buyback filled against a quote this process did not sign. Action: revoke the buyback allowance, then replace your bot key | `amount`, `position`, `quoteId` |
| `quote_signer_disabled` | the guardian disabled your bot key: every request is declined until a different key is installed | `quoteSigner` |
| `maker_defaulted` / `default_cleared` | an expiry settled short and you are in default / the default cleared | `amount`, `expiry` / `active` |
| `insurance_drawn`, `settlement_lapsed` | Olive's insurance paid for you (repaid first from any withdrawal; it blocks reactivation) / a 4-hour shortfall window ended unpaid | `amount`, `expiry` |
| `bucket_handed_over` | governance moved a bucket between makers | `lost`, `bucket`, `expiry`, `positions` |
| `credit_limit_changed`, `maker_standing_changed` | governance changed a limit on your maker / your maker's standing | `creditLimit` / `standing` |
| `entry_rate_abnormal` | Olive saw an abnormal entry rate for your maker (a stolen bot key looks like this): warning above 3x your normal 15-minute rate (and at least 100,000 USDC), critical above 2,000,000 USDC in 15 minutes; alert only, nothing is disabled automatically. If the entries are not yours, stop the bot and tell Olive | `notional`, `baselineNotional`, `windowSeconds`, `trigger` |
| `needs_admin_fallback` | ops: a settlement finishes through Olive's admin fallback; nothing for you to do | `programError` |
| `handler_failed` | your `on_entry` / `on_exit` raised or ran past `pricing_timeout_ms` (declined `pricer_error` / `too_slow`), or an event handler failed (`blocksEntries`) | `rfqId`, `kind`, `reason`, `declineReason`, `test` |
| `quote_invalid` | your handler returned a quote the SDK will not sign (declined `invalid_quote`) | `rfqId`, `kind`, `reason`, `declineReason`, `test` |
| `fee_sol_low` | at start: the funding wallet holds less SOL than it needs for transaction fees | `wallet`, `lamports`, `minimumLamports` |
| `funding_wallet_unreadable` | at start: the funding wallet's USDC account could not be read, so buybacks are quoted without checking it can pay | `exitSource`, `reason` |
| `gateway_unreachable` | the bot could not open a connection to Olive's gateway in several tries in a row (wrong `OLIVE_MAKER_WS_URL`, DNS, TLS, an HTTP refusal). Raised once per outage, the bot keeps trying | `attempts`, `error` |
| `gateway_refused` | Olive's gateway opened the connection and closed it before the bot signed in, several times in a row. Raised once per outage, the bot keeps trying | `attempts`, `closeCode`, `closeReason` |

Amounts are USDC base units, times unix seconds, keys camelCase. Every alert has `action`, one short sentence saying what
to do now, and is also a log line. `alert.event` is the lifecycle event that raised the alert,
when one did (`{"method": ..., "params": ...}`), so nothing it carried is lost. The same alert (same `key`) is raised at most
once an hour (`alert_repeat_ms`). `bucket.settled` fires when an expiry's bucket is
counted, with zero money amounts: it is never a payment and raises no alert.

### The bot key and buybacks

The bot key (the quote signer) signs quotes and the login only; it holds no money and cannot withdraw. A stolen bot key can
still sign sales up to your whole margin headroom in seconds, and the guardian disabling the key does not unwind positions
already filled. So keep the quote key in a signer that enforces per-quote and per-hour notional limits (`CallbackMakerSigner`
over your HSM or signing service, below), and keep the buyback allowance small.

An exit quote must expire by the maturity less the exit cutoff and 10 seconds (`T - 610 s` in release: the program refuses an
exit from 10 minutes before the maturity). ManagedMaker clamps your `validity_seconds` to that and declines an exit that cannot
keep a quote valid until then (`exit_cutoff_seconds` is 30 in the local and rehearsal builds). If you sign exit quotes yourself,
set `expiry <= T - 610`.

Buybacks are paid from your funding wallet through an SPL approval of the exit delegate, only up to that allowance. The SDK
declines (never raises) a buyback above the allowance or above the wallet's balance (with `funding_wallet_balance=`), and
tells you why (`exit_declined`, `buyback_allowance_low`). With a funding signer it restores the
allowance to `ManagedExitApproval.target_usdc` (default 25,000 USDC) when it falls below half, but adds at most
`max_refill_usdc_per_24h` in any rolling 24 hours (**default one target**): the most a stolen bot key can take through
buybacks is the allowance plus the 24 h refill budget. A fill against a quote this process did not sign raises
`unquoted_exit`: revoke the buyback allowance first, then replace your bot key.

### Low level

`on_event(event)` (advanced — most makers never need this) sees every lifecycle event after the SDK handled it (settlement
prices, redemptions, quote selection) and
`on_status(status)` every connection and quote status; a bot does not need them. The raw WebSocket client (`MakerWsClient`)
remains for custom orchestration.

## Olive's onboarding test request

While a maker is onboarding, Olive sends each chosen asset one test request (an `rfq.request` with `test: true`) the first time
the software subscribes, so the first-quote check completes in seconds. It is never an auction and can never be filled.
It goes through your `on_entry` like a real request (a quote under the five-USDC minimum is sent at the minimum); when
`on_entry` declines or fails, `ManagedMaker` still answers with the minimum so the connection check passes, and the log (and,
for a failure, a `handler_failed` / `quote_invalid` alert) says what your pricer did. The RFQ carries
`test: true`. The `test_rfq_answered` status says whether your pricer answered (`source` `"pricer"`) or the SDK did (`"sdk_minimum"`). `load_olive_env()` reads the `olive.env` the onboarding page gives you (a variable already set wins).

## Maker money: legs, exits and headroom

- **Legs.** Entry RFQs, quotes and positions carry `legs`: `{kind, maturity, strikeE8, qty}` (`kind`
  0 = call, 1 = put; `qty` the unsigned size the user buys). The program accepts exactly one user-long call or put.
  `ManagedMaker` declines any other structure itself (`unsupported_structure`) before your code sees it, and `rfq.leg`
  (`LaunchLeg`: `kind`, `kind_name`, `strike_e8`, `size`, `maturity`) is the leg to price. Maturities sit on the 08:00 UTC
  grid; an off-grid leg is declined as `invalid_maturity`.
- **Exits** remove quantity from the position and pay the holder from the maker's funding wallet
  (`exit_source_address(funding_authority, usdc_mint)`) through the PDA `exit_delegate_address(program, maker)`
  (`approve_exit_delegate_instruction`, signed by the funding authority, never the quote signer;
  `revoke_exit_delegate_instruction` stops every exit). `read_exit_approval` / `check_exit_approval` tell you where it
  stands (`ExitDelegateNotApproved`, `ExitAllowanceExceeded`).
- **The money log.** Every event that moves or endangers your money is also logged to stderr by default (`logger=` to send
  it elsewhere, `quiet=True` to turn it off), with amounts in USDC and the transaction signature.
- **Headroom.** `maker.capacity` returns the maker `ledger` and one row per market and product; a row is `available` while
  the V14 cover check admits a fill on one of your expiries at the reference strike. For an exact size at another strike,
  run the TypeScript SDK's risk mirror (`maxSizeForQuote`) on your own chain reads. Olive re-checks every quote at
  the state the entry lands on; a quote it cannot take comes back through `on_status` as `quote_rejected` (with `max_size`).
  `maker_balance(capacity)` / `ManagedMaker.balance()` give one maker-level view.

## Bidding for positions (secondary sales)

Secondary sales are part of V14 and on for every maker; there is nothing to switch on. When a holder sells, Olive shows
the better of the carrier's buyback and the best bid from any other maker. Olive sends your session a sale request
(`rfq.request` with `kind: "sale"`) for every position another maker carries, and you may bid. Bidding is at your
discretion: declining, or not answering, is fine and never counts against you (sale auctions are left out of answer-rate
scoring and every KPI).

**A bid is a quote signed with your quote key.** You sign no transaction and need no extra key. The seller submits your
quote with `accept_sale_quote`: the program pays the price from your funding wallet through the same buyback allowance
your exits use, the seller receives the price less the protocol sale fee, and the position is owned by your funding
authority (it can be bought back by the carrier or redeemed at expiry, but not sold on to another maker).

Without `on_sale` or a Solana connection your maker starts normally, prints one loud warning at startup, and declines every
sale request with `sales_not_configured`. To bid, pass `on_sale` and set `SOLANA_RPC_URL`:

```python
maker = ManagedMaker.from_env(
    on_entry=on_entry, on_exit=on_exit,
    on_sale=lambda rfq: rfq.bid_usd(price(rfq)) if rfq.years_to_expiry > 0.01 else rfq.decline("too_close"),
    sale=ManagedSaleOptions(validity_seconds=15, max_amount_usdc=5_000_000_000, buyback_reserve_usdc=2_000_000_000, daily_limit_usdc=20_000_000_000),
)
```

- **What the SDK does for each request.** It reads the position, its bucket, the carrier, your maker account and the protocol
  account on chain (`read_sale_state`) and declines unless the chain agrees with the request: the position is active, owned by
  the seller, not bought by a maker, whole (`remaining_bps`), with the request's terms, outside the exit cutoff; the carrier
  is the request's, active, out of default, with no debt, no short settlement batches and no ledger fault; your quote key is
  the one registered; your funding authority can own the position. It then signs the quote and answers inside the auction
  deadline. The chain's `Clock` must agree with this machine's within 30 s.
- **The price you name is what you pay.** `rfq.bid(amount)` / `rfq.bid_usd(usd)` is the total taken from your funding wallet.
  The seller receives it less the protocol sale fee (`max(minimum, bps x price)`; read from the protocol account when you
  quote, never hard-coded). A bid not above the fee is declined `sale_amount_invalid`.
- **The price band is yours.** Quotes are signed with a half-width of 100 bps (sale.band_bps) around the request's reference price, or
  around YOUR reference with `rfq.bid(amount, ref_price_e8=..., max_dev_bps=...)` (the gateway chose the request's, so pass your own spot to take the centre out of its
  hands). The sale reads the price at the moment it lands and fails if it is outside the band. A request whose `minMaxDevBps` is
  wider than your band is declined `sale_amount_invalid`, never widened.
- **Your buyback allowance is guarded.** A bid that would take the exit-delegate allowance (less bids still open) below
  `sale.buyback_reserve_usdc` (default 1,000 USDC) is declined `sale_reserve`; one that does not fit the allowance or the
  funding wallet is `sale_insufficient_usdc`. A rolling 24 hour spend limit, `sale.daily_limit_usdc` (default 10,000 USDC),
  counts every bid you SIGNED (not only the fills the gateway reports), for 24 hours: over it is `sale_daily_limit`. Change either in
  `sale`. The allowance and the wallet balance are read from the chain (the exit source token account), not from the API. The check
  and the hold are one step, so bids at the same moment cannot spend the same allowance twice. The signed bids are kept in
  `olive-sales-<first 8 of the maker config>.json` in `OLIVE_STATE_DIR` (sale.spend_ledger_path / sale.spend_store to change it), so a restart keeps the 24 hours;
  a file that cannot be read stops the maker from starting.
- **A carrier that may still default is not bid for.** A carrier with a pending gap, or with a maturity that has passed and is still
  unresolved on chain, is declined `sale_carrier_unfit`: a resolve in the same transaction could default it.
- **Quote life.** `sale.validity_seconds` (default 15 s), inside the request's lifetime window (5 to 300 s) and never past
  the exit cutoff.
- **Decline reasons** (`SALE_DECLINE_REASONS`): `sales_not_configured`, `sale_state_mismatch`, `sale_carrier_unfit`,
  `sale_inside_exit_cutoff`, `sale_insufficient_usdc`, `sale_reserve`, `sale_daily_limit`, `sale_amount_invalid`,
  `sale_own_position`, `sale_chain_unreadable`, `sale_clock_unreliable`, `sale_fee_unreadable`. Failures of `on_sale` use the
  usual `pricer_error`, `too_slow`, `too_slow_for_auction`. A sale decline never raises an alert.
- **When it lands** you get `sale.filled` (`on_sale_filled`: `rfqId`, `position`, `amountUsdc`, `saleFee`, `sellerProceeds`,
  `seller`, `owner`, `signature`). It is not a `trade.filled`: you did not carry the position, so it is not in `maker.book`
  and does not reach `on_fill`. A refused quote is `INVALID_SALE` (-32006, `details.reason`) and arrives as the
  `submission_rejected` status.
- **The quote signer sees a new purpose.** `sign_digest(digest, SignerContext("sale_quote", ...))`. A custody signer with a
  purpose allow-list must allow `sale_quote`.
- **Low level.** `read_sale_state`, `build_sale_quote`, `SaleBudget`, `v14.quotes.sale_quote_digest`, `v14.quotes.sale_fee`,
  `accept_sale_quote_instruction` (15 accounts), `MakerWsClient.submit_sale`.
- **Positions you bought** are owned by your funding authority like any other holder's. `list_held_positions(RpcSaleChain(url),
  program_id, funding_authority)` lists them (needs `getProgramAccounts`: Helius or Triton) with `maker_held` and `entry_expiry`.
  They pay out automatically at expiry. To sell one back early, your funding authority exits it through Olive's app like any
  holder: the carrier's normal buyback.

## State without a database

Olive already keeps everything a maker would otherwise persist: it refuses a reused nonce or quote id per maker, settles
each fill exactly once on chain, and keeps the durable event log server-side. So the SDK keeps no state across restarts:

- On start and after every reconnect the SDK pages `maker.positions` (active) and reads `maker.capacity` before any event
  or RFQ of that connection reaches your code, and rebuilds `maker.book` (the `synced` status). A sync that fails is retried
  with backoff (`sync_failed`); RFQs wait for it until their auction ends (`rfq_skipped` otherwise).
- Delivery is at least once. A fill is acknowledged after `on_fill` returns; one that raises is retried and stays
  unacknowledged, and Olive redelivers it. Make hedging target-based, not incremental.
- `maker.position(address)` reads one of the maker's positions, in any status.
- A signed quote is remembered in memory, bounded, so the same RFQ offered again after a reconnect gets the exact same signed
  quote. Every in-process map is bounded (`MANAGED_MAKER_LIMITS`, `limits=`).

## A remote or HSM quote key

`LocalKeypairMakerSigner` (what `from_env` builds from the key file) is for laptop tests or a tightly controlled
key-file deployment. Production remote/HSM integrations use `CallbackMakerSigner` and never pass private-key bytes to the
maker process; that is where per-quote and per-hour notional limits belong:


```python
from olive_solana import CallbackMakerSigner, SignerContext


async def sign_with_remote_provider(
    digest: bytes,
    context: SignerContext,
) -> bytes:
    if len(digest) != 32:
        raise ValueError("expected a 32-byte Olive digest")
    signature = await remote_provider.sign_ed25519(
        key_id="olive-quote-signer",
        message=digest,
        audit_context={"purpose": context.purpose},
    )
    if len(signature) != 64:
        raise ValueError("expected a 64-byte Ed25519 signature")
    return signature


signer = CallbackMakerSigner(
    public_key="<remote Ed25519 public key in canonical base58>",
    callback=sign_with_remote_provider,
)
```

The callback signs the supplied raw 32-byte `SHA-256(preimage)` digest with
ordinary Ed25519 and returns the raw 64-byte signature. Do not hash again, sign
encoded text/the full preimage, or use Ed25519ph. The remote public key may be
the finalized on-chain `MakerConfig.quoteSigner`.

Keep `takeover_existing_session=False` for ordinary starts; enable
it only for an intentional failover.

After a silent network drop the gateway may still hold your session. Since 3.0 the
reconnect names the lost connection (`previousConnectionId` in `auth.respond`) and
the gateway replaces that session at once; a second instance of your maker cannot
name it and is still refused. If a reconnect is refused anyway, a client that had a
session of its own reports `session_release_wait` through `on_status` and retries,
at most about 2 seconds apart, for the lease plus 30 seconds from the moment it lost
the connection; refusals past that, or on a first connect, still raise.
`ManagedMaker` does not retry a sync while disconnected: `sync_failed` is a failure
on a live connection.

## One session per asset

Since 1.3.0 every session owns an explicit set of assets: `assets` (1-32 unique
lowercase topics) is required on `ManagedMakerOptions`, `MakerWsClientOptions` and
`MakerDoctorOptions` (`--assets` / `OLIVE_ASSETS` on the CLI), and `topics` must be a
subset. List every asset to quote them all in one session. There is no all-assets
mode. The gateway fixes the claim for the session's whole life: `maker.hello.assets`
lists it, and the client fails terminally if it differs from the request.

- Run one process per asset if you like; each session syncs and acknowledges its own
  assets' events (maker-wide events go to every session). The processes of one maker share one refill ledger
  file (`OLIVE_STATE_DIR`, locked on every write), so the 24 h refill budget and the halt after an unquoted exit are maker-wide.
- `SESSION_ACTIVE` names the sessions in the way in `conflicting_assets` on the
  `MakerWsRpcFailure` (the terminal error's `__cause__`) and in the
  `session_release_wait` status. `takeover_existing_session=True` replaces every
  overlapping session (close 4001), only for the assets you claim. The restart wait of
  1.2.1 works per asset session.
- Funding and the routing pause stay maker-wide: `maker.capacity` shows
  `ledger.reservedCredit` across all sessions, while its other rows and
  `maker.positions` are filtered to the session's assets.
- Stagger process starts by about one second. `FORBIDDEN` with `session_limit`
  reports `maxSessionsPerMaker`; `asset_not_claimed` means the session does not own
  the topic it used.

## Register from a server

If your keys live on a server, one command registers your maker. The console gives you an `olive.env` of five lines
(`OLIVE_NETWORK`, `OLIVE_MAKER_ID`, `OLIVE_ASSETS`, `SOLANA_RPC_URL`, `OLIVE_QUOTE_SIGNER_KEYPAIR`). `OLIVE_NETWORK` (`devnet` or
`mainnet`) stands for the program id, genesis hash, chain tag, USDC mint, gateway and maker account. A line that repeats one of them
must carry the network's own value, or the SDK stops at startup naming the line. Add the public addresses of your vault and funding
wallet as `OLIVE_MAKER_AUTHORITY=` / `OLIVE_FUNDING_AUTHORITY=` lines (`OLIVE_QUOTE_SIGNER` defaults to the public key of the bot key
file, `./quote-signer.json` unless `OLIVE_QUOTE_SIGNER_KEYPAIR` says otherwise; `OLIVE_PREMIUM_RECEIVER_OWNER` is optional). Make the
bot key with `solana-keygen new --outfile quote-signer.json`, or let the starter bot make it: `ensure_bot_key_file()` writes the file in
that format with mode 0600 if it is missing, never overwrites one, and returns only the public key. An `olive.env` that still has keys
SDK 4.0 removed (`OLIVE_TOPICS` and the like) must be downloaded again from the console. Then:

```bash
pip install olive-solana-sdk==4.2.0
olive-maker register --env-file olive.env --keypair ./authority.json --deposit 50000
```

The command reads only `olive.env`. It prints every key, plus the maker account and pool vault, for your desk to confirm
with Olive, builds `register_maker` itself with a fresh blockhash (Olive prepares no transaction), signs it, and waits for
the maker account on chain (`--wait <seconds>`, default 900). Then it prints "Registered. Olive will activate you." It is
safe to rerun: it never registers twice. Flags:

- `--signer key|fordefi|squads` (default `key`). `key` signs with `--keypair`, the maker authority's key file. `fordefi` signs
  through the Fordefi API (`--fordefi-vault-id`, or `FORDEFI_VAULT_ID`; token in `FORDEFI_API_TOKEN`); Fordefi sets its own
  blockhash and fee. `squads` prints the unsigned transaction in base58 and base64 for the Squads transaction-builder
  Import, and the vault's members approve it in Squads.
- `--deposit <usdc>` adds `deposit_pool` to the same transaction, only when the maker authority is also the funding
  authority and its wallet already holds the USDC (otherwise the deposit is skipped with a message: deposit after activation). A deposit before activation is safe: you can withdraw it until Olive activates you.
- `--yes` skips the confirmation.

Registering costs the maker authority about 0.061 SOL of rent. On devnet, set `OLIVE_ONBOARDING_TOKEN` (from the onboarding
page's "Register from a server" dialog) and the command asks Olive's faucet for that SOL.

Olive then checks the registered keys against what your desk confirmed and activates the maker. Start your bot
(`python olive_maker.py`; it reads `olive.env` itself). You approve the buyback allowance in the desk. With funding signer `none`
the bot warns at start ("Approve your buyback allowance in the desk.") until you do. With a funding signer the SDK also tops the
allowance up to its target. The bot answers Olive's test request, and the page shows Ready. At start it also warns when
`SOLANA_RPC_URL` is a public endpoint ("SOLANA_RPC_URL is the public endpoint. Quotes will be slow. Set your own in olive.env."). A wrong or squatted
registration is closed by Olive and your desk registers again.

Separate keys need no extra flags: put the quote signer and funding authority public addresses in `olive.env`, and register
with the maker authority's key.

## Operational preflight

The doctor authenticates without subscribing, taking over a live maker, or
submitting quotes. Its convenience CLI intentionally uses a local test keypair:

```bash
olive-maker-doctor --assets btc,sol    # or leave --assets out when olive.env has OLIVE_ASSETS

olive-maker-doctor --json > maker-doctor.json
```

Connection and deployment values default from `OLIVE_NETWORK` and `OLIVE_MAKER_ID` (which give `OLIVE_MAKER_WS_URL`,
`OLIVE_MAKER_CONFIG`, `OLIVE_PROGRAM_ID`, `OLIVE_GENESIS_HASH` and
`OLIVE_CHAIN_TAG`, as an older `olive.env` spells them out) and from `OLIVE_QUOTE_SIGNER_KEYPAIR`. `--exit-approval-target <usdc>` (default 25000) is the approval you
intend to keep, and `--rpc-url` lets the doctor read the funding wallet's USDC.

By default the doctor reads `maker.capacity` with scope `all` and reports
`pool` (fail while defaulted, warning with what to
deposit before the next funding deadline), `insurance` (fail while insurance
draws are unrepaid), `bucket_margin` (requirement, collateral and unfunded per
open bucket; fail when a bucket is unfunded past its funding deadline),
`routing` (fail while Olive has paused new entry requests) and `true_up` (fail
while a settled bucket owes a true-up). The same checks are available as
`margin_checks(capacity, now_seconds)`. `capacity_state` fails while the maker is frozen
(`underfundedPastDeadline`) and `exit_approval` reports what the funding wallet has approved to the exit
delegate (fail at 0 and below half of the target, warning below the target). `exit_wallet` compares the funding
wallet's USDC with the approval (fail below the approval, warning below the target or when not checked). Pass `--exit-only`
(`exit_only=True`) to read only the ledger scope.

Remote/HSM deployments MUST NOT export their private key to use the CLI. Call
`run_maker_doctor(MakerDoctorOptions(..., signer=signer, assets=["btc"]))` programmatically with
the same `CallbackMakerSigner` used by the managed maker, and retain
`report.to_dict()` as the machine-readable preflight record.

## Strike grid

Entry strikes sit on a fixed grid of round levels per market. The step depends
on how far the strike is from the request's reference price (`referencePriceE8`):

| Market | within 5% | 5% to 15% | beyond 15% |
| --- | --- | --- | --- |
| BTC | $1,000 | $2,000 | $5,000 |
| SOL | $1 | $2 | $5 |
| GOLD / PAXG | $25 | $50 | $100 |
| SP500 / SPYX | $5 | $10 | $10 (one tier beyond 5%) |

- Symbols are case-insensitive, and both the app names (GOLD, SP500) and the
  on-chain names (PAXG, SPYX) work.
- **Re-striking.** If the price falls so far that the finest step is wider than
  5% of spot, every step is divided by ten until it fits: SOL at $15 strikes on
  $0.10 / $0.20 / $0.50, BTC at $15,000 on $100 / $200 / $500.
- **Boundary tolerance.** Near a tier boundary the API accepts a strike that is
  a multiple of either neighbouring tier's step, within 1 percentage point
  (`STRIKE_GRID_SLACK_PCT`). With BTC at $98,000, $103,000 is 5.1% out, where
  the step is $2,000, but it is accepted because it is within 1 point of the
  $1,000 tier.
- A market without a configured grid gets one tier with a 1-2-5 step near 0.1%
  of spot.

The API rejects an off-grid entry RFQ (`INVALID_STRIKE`, reason
`strike_off_grid`), so a maker should never receive one. The SDK lets you
check anyway, with exact decimal arithmetic (no binary floats):

```python
from olive_solana import (
    STRIKE_GRID_SLACK_PCT, entry_strike_grid_warning, grid_levels, grid_step,
    nearest_strike, on_grid, strike_grid_for,
)

grid = strike_grid_for("BTC", "112480")          # tuple of StrikeTier(within_pct, step)
on_grid(grid, "112480", "113000", STRIKE_GRID_SLACK_PCT)   # True
grid_step(grid, "112480", "130000")              # Decimal('5000')
nearest_strike(grid, 0, "112480")                # Decimal('113000'), call side
nearest_strike(grid, 1, "112480")                # Decimal('112000'), put side
grid_levels(grid, "112480", "100000", "125000")  # every level in the range

entry_strike_grid_warning(rfq.request)           # None when on grid, else a message
```

Prices can be `Decimal`, `int`, `str`, `Fraction` or (converted through their
decimal text) `float`. `entry_strike_grid_warning` reads `underlyingSymbol`,
`legs[*].strikeE8` and `referencePriceE8` and judges each strike exactly as the API does.
The grid matches the TypeScript SDK (the one the app and the API use); the repository's
`packages/solana-sdk/test/vectors/strike-grid.golden.json` holds the shared test vectors.

Conformance runs can pass the entry requests they received as
`run_maker_conformance_suite(..., observed_entry_requests=[...])`. Any off-grid
request is listed as a `[WARN]` line under `entry_quoting`; it does not fail
the report, because it points at a gateway or fixture problem, not at the
maker.

## Wire types and schema

The complete required/optional DTO catalog is published at
[`maker-websocket.schema.json`](https://devnet-docs.olive.ag/schemas/maker-websocket.schema.json)
and included in the wheel at
`olive_solana/schemas/maker-websocket.schema.json`. Python exports typed RFQ,
quote, selected, filled, decline, and error/result shapes from `olive_solana`.
Missing required fields fail before maker callbacks run; unknown additive server
fields are preserved, while outbound quotes remain strict. The normative
semantics and signing preimages are in the
[maker WebSocket specification](https://devnet-docs.olive.ag/developers/maker-websocket-spec) (protocol 5.0).

## Reliability contract

- Wire integers remain canonical decimal strings.
- Olive refuses a reused entry nonce or quote id per maker; exit quotes have no wire
  nonce and are replay-safe because each binds the position's `remainingBps`, which the
  exit changes, and its leg as opened, so it never matches a later position at that address.
- A reconnect resends only the exact signed quote the process already submitted.
- Durable events are acknowledged after their handler returns; a lifecycle event
  carrying one of this maker's quotes must match the quote this process submitted
  or verify against the quote signer, otherwise it is neither dispatched nor
  acknowledged (`event_rejected`).
- `quote.selected` and `exit_quote.selected` are not fills. Only finalized
  `trade.filled` and `exit.filled` are canonical execution signals.
- Signatures and private signer data are never included in SDK status events.

Releases must pass the shared fixture/digest suite and all
fail-closed maker conformance scenarios.

## Development

```bash
python -m venv .venv
.venv/bin/pip install -e ".[dev]"
.venv/bin/ruff check .
.venv/bin/mypy src
.venv/bin/pytest
.venv/bin/python -m build
```

## Release

PyPI releases use trusted publishing from
`.github/workflows/publish-python-sdk.yml`; no long-lived API token is stored in
GitHub. Configure the PyPI publisher for repository `macols77/olive`, workflow
`publish-python-sdk.yml`, and environment `pypi`. The environment has no
reviewers: the typed `PUBLISH` is the deliberate act.

Pushing a `python-sdk-v<pyproject version>` tag only builds and verifies; it
never uploads. The build job:

- requires the tag's commit to be on `origin/main` (merge first, then tag the
  merged commit);
- when a `coordinated_tag` (`solana-sdk-v*`) is given, requires it to point at
  the same commit, and otherwise warns with the TypeScript tags found on that
  commit;
- requires the SDK's program id to equal the program's `declare_id!` and to be
  live (executable) on devnet;
- requires the tag to equal `python-sdk-v<pyproject version>`;
- runs ruff, mypy and pytest, builds and `twine check`s the wheel and sdist,
  and reruns the tests against the built wheel in a clean environment.

To publish, run the workflow manually (**Run workflow**) with `release_tag` set
to the existing tag, `publish` typed as `PUBLISH`, and `coordinated_tag` set to
the sibling TypeScript tag for a coordinated release. The publish job uploads
both distributions. The same
dispatch retries a failed release.
