# Introduction

**ksUSD turns SOL staking into dollar yield.** It is a vault share, not a pegged dollar — the price floats with what the vault holds.

* **Deposit** USDC, get ksUSD at the current share price.
* **Hold** it. Nothing to stake, nothing to claim — yield accrues into the price.
* **Withdraw** anytime. Small amounts pay out instantly, larger ones queue.

With the money it stakes, hedges the price away, and parks in USDC lending when the hedge stops paying for itself. It picks between those from an on-chain funding signal, on a schedule, with nobody steering it. [What is ksUSD? →](/start-here/reserve-asset)

**Staking is the engine, not funding.** Staking accrues on every hedged day and nothing is traded for it; funding decides whether the hedge is worth putting on. On this window funding is the larger leg at the margin: take staking out of the backtest and the vault nets 5.20% against a published 7.19%; take funding out and it never hedges at all, netting 4.52%. Neither leg alone gets near the combined figure. [Where the yield comes from →](/how-it-works/strategy-and-modes/historical-simulation#where-the-yield-comes-from)

Backtested on Phoenix's own funding, over every day the venue has quoted a SOL perp: **7.19% net, −0.314% max drawdown** across 316 days. The window's last month, September 2026 (+22% funding), is the venue's best; ending a month earlier gives 5.86%. [Historical simulation →](/how-it-works/strategy-and-modes/historical-simulation)

{% hint style="warning" %}
**Pre-deployment.** Not yet on mainnet; audit pending. v1 hedges on Phoenix Perps (Ellipsis Labs), posting USDC as margin via Ember with jitoSOL held unlevered as the spot leg. Phoenix's SOL perp opened 18 November 2025, so the backtest covers the venue's entire life — 316 days, which is a young venue's record rather than a market cycle.
{% endhint %}

***

## Where to go next

**Depositing?** [What is ksUSD?](/start-here/reserve-asset) → [Deposit](/start-here/deposit) → [What it costs](/start-here/fees) → [What can go wrong](/start-here/volatility-risk-management)

**Building on it?** [Quick start](/build-on-it/quick-start) → [Instructions](/build-on-it/quick-start/instructions) → [Accounts](/build-on-it/quick-start/accounts)

**Running a keeper?** [Keeper bot](/run-it/keeper-bot) → [Monitoring](/run-it/keeper-bot/monitoring) → [Admin ops](/run-it/keeper-bot/admin-ops)

**Just want the mechanism?** [Strategy & Modes](/how-it-works/strategy-and-modes) for the modes, the funding threshold and the rebalancing rules; the [whitepaper](/how-it-works/whitepaper) for the derivations, the risk disclosures and why the design only assembles on Solana; the [Hylo comparison](/how-it-works/whitepaper/hylo) for the closest Solana-native alternative.

**Unfamiliar term?** The [glossary](/reference/glossary) defines funding, delta-hedged, NAV and the rest.

***

## Program

| Network | Program                                        | Address                                        |
| ------- | ---------------------------------------------- | ---------------------------------------------- |
| Devnet  | `keystone_finance` (ksUSD vault)               | `E7tpCcxtvuTXLAckBGWb1AsndpLQ1Y9hQA3iGYSXz2vJ` |
| Mainnet | `E7tpCcxtvuTXLAckBGWb1AsndpLQ1Y9hQA3iGYSXz2vJ` | Pending audit / deploy                         |


# What is ksUSD?

**It is a vault share, not a pegged dollar.** ksUSD defends no peg and is not redeemable for a fixed $1. Deposits mint at the current share price and redemptions burn at it, so a share is worth whatever the vault's assets are worth. The price is meant to rise as yield accrues — and it can fall. A bad unwind or a jitoSOL depeg lands in the share price rather than being absorbed somewhere else.

Under the hood it's deliberately small: one Anchor program, one vault account the program itself controls, and one token.

## What the vault does

* **It stakes.** Holds jitoSOL, which earns 4.94% APR — but earns it in SOL, which is no use if you account in dollars.
* **It hedges.** It shorts the same amount of SOL on Phoenix, so SOL's price moves cancel and what's left is the staking yield in dollars. When funding is positive, the short is paid to sit there on top.
* **It parks.** When funding stops covering the cost of the hedge, the vault closes the short, sells the jitoSOL, and lends everything as USDC on Kamino — always USDC lending, never tokenized T-bills.

It picks its mode from an on-chain funding signal and rebalances on a schedule; nobody steers it. Which mode runs is not a judgement call. It falls out of whether staking plus funding beats lending, and the vault recomputes that break-even from live rates every cycle. [Strategy & Modes](/how-it-works/strategy-and-modes) has the full mechanics, the funding threshold, and the guardrails around switching.

## Where the yield comes from

Three sources, and they are not equal — the first is the engine and the other two are conditional:

| Yield source              | Active when       | Mechanism                                                                                                                                                                                                               |
| ------------------------- | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **jitoSOL staking yield** | Normal basis      | **Earned on every hedged day.** 4.94% APR, embedded in the jitoSOL/SOL rate. This is the spot leg of the hedge, and nothing is traded for it.                                                                           |
| Phoenix SOL-PERP funding  | Normal basis      | Conditional. The vault shorts the perp and collects funding whenever traders are paying it. It has averaged +3.49% APR since the venue opened, and by month it has run from −14% to +22%, the top being September 2026. |
| USDC lending carry        | Buffer and parked | Lent on the Kamino USDC reserve at 4.51% (seven-day median, measured 13 Oct 2026). Everything the vault holds runs here whenever hedging isn't worth it, which makes lending the floor.                                 |

Staking accrual is hedged too. jitoSOL gains against SOL at roughly 4.94% a year, and that gain *is* the staking yield. Selling it forward is what turns it into a dollar return instead of a growing pile of SOL whose value floats.

Read the funding row as an average with wide months inside it, not as a rate you can add to the other two. The vault collects more than the average, because it parks when funding turns: its hedged days ran +8.68%.

Removing funding from the backtest costs **267 bps**, because without it the vault never hedges; staking alone falls just short of lending once the margin earns nothing. Removing staking costs 199 bps. So on this window funding is the larger leg at the margin, and neither alone gets near the combined 7.19%. The full leg-by-leg accounting is in [Historical simulation](/how-it-works/strategy-and-modes/historical-simulation#where-the-yield-comes-from).

***

## Related

* [Whitepaper](/how-it-works/whitepaper) — full design, NAV math, security, risk disclosures
* [Deposit](/start-here/deposit) · [Withdraw](/start-here/withdraw) · [Check position & NAV](/start-here/check-position)
* [Risk management](/start-here/volatility-risk-management) — drawdown guard, slippage bounds, dwell timers, depeg and staleness guards
* [Fee structure](/start-here/fees) — 0% management, 20% performance above the high-water mark


# Deposit

Send USDC to the ksUSD vault and get `ksUSD` back at the current share price. How many tokens you get depends on that price, so a deposit made later buys fewer tokens, each worth more.

> **New here?** Read [What is ksUSD?](/start-here/reserve-asset) first.

***

## The instruction

```rust
deposit(usdc_amount: u64)
```

One transaction does all three steps, or none of them:

* Moves your USDC into the vault's USDC account
* Mints `ksUSD` to you at the current share price
* Updates the vault's record of what it holds

The accounts below use two Solana conventions. A **PDA** is an account the program controls directly, with no private key behind it. An **ATA** is the standard token account a wallet holds a given token in.

| Account              | Mutability | Purpose                                                                                                                   |
| -------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------- |
| `vault`              | mut        | Vault PDA (seeds: `[b"vault"]`)                                                                                           |
| `vault_usdc_account` | mut        | Vault's USDC ATA — receives the deposit                                                                                   |
| `ksusd_mint`         | mut        | ksUSD share mint — vault PDA is authority                                                                                 |
| `user_usdc_account`  | mut        | Depositor's USDC source ATA                                                                                               |
| `user_ksusd_account` | mut        | Depositor's ksUSD destination ATA                                                                                         |
| `user`               | signer     | Depositor                                                                                                                 |
| `phoenix_trader`     | —          | Phoenix trader account — read to true up the venue's contribution to NAV before pricing. Pinned to `vault.phoenix_trader` |
| `sol_oracle`         | —          | Pyth SOL/USD — values the perp leg for that same correction. Pinned to `vault.sol_oracle`                                 |
| `token_program`      | —          | SPL token program                                                                                                         |

`phoenix_trader` and `sol_oracle` are required on **every** deposit, not only in Normal mode. While the vault is Parked they are read and ignored; in Normal mode the deposit re-books the venue's real equity into NAV first, so the shares you mint are priced against the position as it actually stands.

***

## Share-price math

In plain terms, one division:

```
ksUSD you get = USDC you send ÷ current share price
```

Deposit $100 while a share is worth $1.03 and you get 97.09 ksUSD. Deposit $100 while it's worth $1.00 and you get 100. Either way you own $100 of the vault the moment the transaction lands; the price only decides how many tokens that is.

The same thing in the integers the program actually stores:

```
effective_nav_usdc = cached_nav_usdc − queue_pending_usdc − pending_perf_fees_usdc
share_price_1e9    = effective_nav_usdc × 1e9 / max(total_shares, 1)
shares_to_mint     = usdc_amount × 1e9 / share_price_1e9    // both sides 6 decimals
```

`share_price_1e9` is dollars scaled by 1e9, so `1_030_000_000` reads as $1.03. Multiplying by `1e9` before dividing by it cancels the scale out, which is why `usdc_amount` and `shares_to_mint` are both plain 6-decimal amounts. The division truncates, so any fraction of a base unit is left in the vault rather than minted, so it can never round in the depositor's favour at other holders' expense.

`deposit` calls `accrue_perf_fees` before it prices your mint. That advances the high-water mark to the current price first, so you're never charged a performance fee on gains the vault made before you arrived.

The first deposit into an empty vault mints shares 1:1 at $1.00, since the starting `share_price_1e9` is `1_000_000_000`. Every deposit after that mints fewer shares, because the share price has drifted up with the carry earned so far. Full derivation and a worked example in [NAV & share pricing](/how-it-works/strategy-and-modes/nav-calculation).

***

## Capacity

The vault ships with a **$500k deposit cap**. That isn't a demand estimate. It is roughly the largest short Phoenix's book can absorb, and it re-sizes as the venue grows.

It's a hard cap rather than a soft target because the vault only earns while its dollars are *in* the hedge. Whatever it can't short sits in USDC lending instead. A cap set above what the venue can hold doesn't add yield; it dilutes the part that does, until ksUSD is a Kamino deposit wearing a wrapper, carrying all of the operational risk for none of the carry.

So the cap tracks the venue:

```
max short = min( 15% of Phoenix SOL-PERP OI , 25% of the 30-day MEDIAN daily volume )
```

The volume limb is a quarter of a day's flow because exit is harder than entry: that is about what a clean unwind can take. On Phoenix's numbers measured 16 September 2026 the open-interest limb binds, by roughly 2.2×: $4.73M of OI gives $709k, against $1.59M from volume. In early August it was the other way round, so the rule takes whichever is tighter.

The word *median* matters. A few spike days can sit inside any 30-day window and pull the mean above the median, and sizing off the mean would imply a short the venue couldn't absorb on an ordinary day.

### The ramp

| Phase                     | Cap        | Opens when Phoenix has              |
| ------------------------- | ---------- | ----------------------------------- |
| **Launch (private beta)** | **$500k**  | roughly today's book                |
| Next tier                 | $1M        | roughly twice today's open interest |
| Public                    | $5M → $25M | a far deeper book                   |

Tiers open against the live book, not on a date. There is no second Solana perp venue deep enough to split the short across, so the ramp follows Phoenix.

### Reading the cap live

`deposit_cap_usdc` is a `u64` on the `Vault` account. `0` pauses deposits outright, `u64::MAX` means uncapped, anything else is a hard ceiling.

```ts
const vault = await program.account.vault.fetch(vaultPda);

// Headroom is measured against CACHED nav, not effective nav: queued
// withdrawals are netted out of TVL but still occupy
// cap room, so effective NAV would overstate what you can actually deposit.
const remaining = BN.max(
  vault.depositCapUsdc.sub(vault.cachedNavUsdc),
  new BN(0)
);
```

Admins move the cap with `update_params`. Recompute it against the live book first, rather than trusting a constant, since both inputs move week to week.

***

## Guardrails

A deposit can be blocked by any of three things:

* **The vault is paused.** The admin can pause it with `set_pause` in an emergency.
* **The deposit cap is hit.** A deposit reverts with `DepositCapExceeded` if `cached_nav_usdc + usdc_amount > deposit_cap_usdc`. See [Capacity](#capacity) above.
* **The amount is zero.** `usdc_amount` must be greater than 0.

***

## TypeScript example

```ts
import { Program, BN } from "@coral-xyz/anchor";
import { PublicKey } from "@solana/web3.js";
import { TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync } from "@solana/spl-token";

const PROGRAM_ID = new PublicKey("E7tpCcxtvuTXLAckBGWb1AsndpLQ1Y9hQA3iGYSXz2vJ");

const [vaultPda] = PublicKey.findProgramAddressSync(
  [Buffer.from("vault")],
  PROGRAM_ID
);

const vault = await program.account.vault.fetch(vaultPda);
const userUsdcAta  = getAssociatedTokenAddressSync(vault.usdcMint,  user.publicKey);
const userKsusdAta = getAssociatedTokenAddressSync(vault.ksusdMint, user.publicKey);
const vaultUsdcAta = getAssociatedTokenAddressSync(vault.usdcMint,  vaultPda, true);

const tx = await program.methods
  .deposit(new BN("100_000_000"))         // 100 USDC (6 decimals)
  .accountsStrict({
    vault: vaultPda,
    vaultUsdcAccount: vaultUsdcAta,
    ksusdMint: vault.ksusdMint,
    userUsdcAccount: userUsdcAta,
    userKsusdAccount: userKsusdAta,
    user: user.publicKey,
    phoenixTrader: vault.phoenixTrader,   // required on every deposit
    solOracle: vault.solOracle,
    tokenProgram: TOKEN_PROGRAM_ID,
  })
  .rpc();
```

***

## Events

`DepositEvent` is emitted on success:

```rust
pub struct DepositEvent {
    pub user: Pubkey,
    pub usdc_amount: u64,
    pub shares_minted: u64,
    pub share_price_1e9: u64,
    pub new_total_shares: u64,
    pub timestamp: i64,
}
```

***

## Related

* [Withdraw](/start-here/withdraw) — instant vs. queued paths
* [Check position & NAV](/start-here/check-position)
* [NAV & share pricing](/how-it-works/strategy-and-modes/nav-calculation)
* [Errors](/build-on-it/quick-start/errors)


# Withdraw

You hand back `ksUSD` and get USDC. There are two normal ways to do that, plus a third that only applies if the vault is ever shut down.

| Path                                                     | When to use                                  | Speed                                                                                                     |
| -------------------------------------------------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| **Instant** (`withdraw_instant`)                         | Vault has enough idle USDC                   | One transaction                                                                                           |
| **Queued** (`request_withdrawal` + `process_withdrawal`) | Withdrawal larger than the liquidity buffer  | Burned immediately at locked price; USDC paid out (FIFO, strict) after the keeper unwinds enough position |
| **Wind-down** (`claim_wind_down`)                        | Active only when `position_mode == WindDown` | Pro-rata redemption against the vault's idle USDC; no queue, no FIFO                                      |

Instant is the path almost everyone uses. The vault keeps a liquidity buffer of idle USDC on hand, 10% of what it holds by default, so ordinary-size withdrawals pay out on the spot.

***

## Instant withdrawal

```rust
withdraw_instant(shares: u64)
```

* Burns `shares` of `ksUSD`
* Pays out USDC from the vault's idle balance at the current share price

| Account              | Mutability | Purpose                                                                                                                   |
| -------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------- |
| `vault`              | mut        | Vault PDA                                                                                                                 |
| `vault_usdc_account` | mut        | Vault USDC ATA — source of payout                                                                                         |
| `ksusd_mint`         | mut        | ksUSD share mint                                                                                                          |
| `user_ksusd_account` | mut        | User's ksUSD ATA (must hold ≥ `shares`)                                                                                   |
| `user_usdc_account`  | mut        | User's USDC destination                                                                                                   |
| `user`               | signer     | Withdrawer                                                                                                                |
| `phoenix_trader`     | —          | Phoenix trader account — read to true up the venue's contribution to NAV before pricing. Pinned to `vault.phoenix_trader` |
| `sol_oracle`         | —          | Pyth SOL/USD — values the perp leg for that same correction. Pinned to `vault.sol_oracle`                                 |
| `token_program`      | —          | SPL token program                                                                                                         |

Math — the deposit division, run backwards:

```
USDC you get = ksUSD you burn × current share price

usdc_owed    = shares × share_price_1e9 / 1e9      // 1e9 undoes the price scale
```

Burn 97.09 ksUSD while a share is worth $1.05 and you get $101.94. There is no withdrawal fee and no exit penalty, so what comes back is exactly your slice of NAV at the moment the transaction lands. Like the mint, the division truncates in the vault's favour by under one base unit.

If `vault_usdc_account.amount < usdc_owed`, this reverts with `InsufficientLiquidityBuffer`. Use the queued path instead.

***

## Queued withdrawal

This is what happens when the vault doesn't have enough idle USDC to pay you on the spot.

Your shares burn right away at the current share price, so the dollar amount you're owed is locked in at that moment and can't drift while you wait. The request is recorded in its own account. Once the keeper has unwound enough of the position to refill the buffer, anyone can trigger the payout, including you.

### Step 1 — request

```rust
request_withdrawal(shares: u64)
```

* Burns shares
* Creates a request PDA at `[b"withdrawal_request", vault, queue_next_id]`
* Locks `usdc_owed = shares × share_price_1e9 / 1e9` on the request record — the same math as the instant path, priced at the moment you queue

| Account              | Mutability  | Purpose                                                   |
| -------------------- | ----------- | --------------------------------------------------------- |
| `vault`              | mut         | Vault PDA                                                 |
| `withdrawal_request` | init        | New per-request PDA (payer = user)                        |
| `ksusd_mint`         | mut         | ksUSD share mint                                          |
| `user_ksusd_account` | mut         | User's ksUSD ATA (burned from)                            |
| `user_usdc_account`  | —           | User's USDC destination (recorded on the request)         |
| `user`               | signer, mut | Requester (pays rent)                                     |
| `token_program`      | —           | SPL token program                                         |
| `system_program`     | —           | Required — the request PDA is created by this instruction |

### Step 2 — process (permissionless crank)

```rust
process_withdrawal()
```

**In practice you do nothing here — the keeper calls this for you.** It checks the queue every tick (\~5 minutes) and pays out whatever the vault can cover, oldest first, up to 8 requests per tick. Refilling the buffer is part of the same loop: the keeper folds what the queue owes into its idle-USDC target and pulls the shortfall back out of Kamino, and only if that is still not enough does it de-lever the position to raise the rest. If the head of the queue has been waiting more than an hour, the keeper pages an operator.

"Permissionless" is the guarantee behind that, not the normal path: **the payout does not depend on the keeper being alive.** If it stops, anyone can crank the queue — you, another depositor, a bot — and the money still moves. Nobody can be paid ahead of you, because the ordering is enforced on-chain rather than by whoever sends the transaction.

The mechanics:

* Anyone may call it, including the person who queued the request.
* Strictly first-in, first-out: the next request processed must have `request_id == vault.queue_processed_through`. Anything else reverts with `WithdrawalNotNextInQueue`, so a cranker cannot skip the head of the queue to reach their own request.
* The payout is capped at the live share price. If the vault's value has fallen since you queued, you get your fair share of it and no more.
* The request account closes on payout, refunding its rent to whoever opened it.
* It is blocked while the vault is paused. Pending requests wait — the shares are already burned and the amount owed is locked — until an admin unpauses.

| Account              | Mutability | Purpose                                      |
| -------------------- | ---------- | -------------------------------------------- |
| `vault`              | mut        | Vault PDA                                    |
| `withdrawal_request` | mut        | The queued request (will be closed)          |
| `vault_usdc_account` | mut        | Vault USDC ATA — source of payout            |
| `user_usdc_account`  | mut        | Recorded destination from the request        |
| `recipient_for_rent` | mut        | Original requester (rent refund destination) |
| `cranker`            | signer     | Anyone can crank                             |
| `token_program`      | —          | —                                            |

***

## TypeScript — instant path

```ts
const tx = await program.methods
  .withdrawInstant(new BN("25_000_000"))    // 25 ksUSD
  .accountsStrict({
    vault: vaultPda,
    vaultUsdcAccount: vaultUsdcAta,
    ksusdMint: vault.ksusdMint,
    userKsusdAccount: userKsusdAta,
    userUsdcAccount: userUsdcAta,
    user: user.publicKey,
    phoenixTrader: vault.phoenixTrader,   // required, as on deposit
    solOracle: vault.solOracle,
    tokenProgram: TOKEN_PROGRAM_ID,
  })
  .rpc();
```

## TypeScript — queued path

```ts
const nextId = vault.queueNextId.toString();
const [requestPda] = PublicKey.findProgramAddressSync(
  [
    Buffer.from("withdrawal_request"),
    vaultPda.toBuffer(),
    new BN(nextId).toArrayLike(Buffer, "le", 8),
  ],
  PROGRAM_ID
);

await program.methods
  .requestWithdrawal(new BN("100_000_000_000"))   // 100,000 ksUSD
  .accountsStrict({
    vault: vaultPda,
    withdrawalRequest: requestPda,
    ksusdMint: vault.ksusdMint,
    userKsusdAccount: userKsusdAta,
    userUsdcAccount: userUsdcAta,
    user: user.publicKey,
    tokenProgram: TOKEN_PROGRAM_ID,
    systemProgram: SystemProgram.programId,
  })
  .rpc();

// Later, after the keeper has unwound enough position:
await program.methods
  .processWithdrawal()
  .accountsStrict({
    vault: vaultPda,
    withdrawalRequest: requestPda,
    vaultUsdcAccount: vaultUsdcAta,
    userUsdcAccount: userUsdcAta,
    recipientForRent: user.publicKey,
    cranker: anyWallet.publicKey,
    tokenProgram: TOKEN_PROGRAM_ID,
  })
  .rpc();
```

***

## Wind-down path

This only applies if the vault is being shut down for good. It is not a normal operating mode.

Once the admin calls `init_wind_down`, the vault stops taking deposits and stops opening positions. Everyone then redeems with:

```rust
claim_wind_down(shares: u64)
```

* Pays out your share of the vault's idle USDC at the live `effective_nav` share price.
* No queue, no ordering, and no rent refund.
* Reverts unless `position_mode == WindDown`.

***

## Events

* `WithdrawEvent` — emitted by `withdraw_instant`
* `WithdrawalRequested` — emitted by `request_withdrawal`
* `WithdrawalProcessed` — emitted by `process_withdrawal`
* `WindDownClaimed` — emitted by `claim_wind_down`

***

## Related

* [Deposit](/start-here/deposit) · [Check position & NAV](/start-here/check-position)
* [Fees](/start-here/fees) — no withdrawal fees on either path
* [Errors](/build-on-it/quick-start/errors)


# Check Position & NAV

How to read your `ksUSD` balance, the current share price, and the total value of what the vault holds (its NAV).

Your balance never changes on its own. What changes is the share price, so the same balance is worth more over time.

***

## Your position

```ts
import { PublicKey } from "@solana/web3.js";
import { getAccount, getAssociatedTokenAddressSync } from "@solana/spl-token";

const [vaultPda] = PublicKey.findProgramAddressSync(
  [Buffer.from("vault")],
  PROGRAM_ID
);

const vault = await program.account.vault.fetch(vaultPda);
const userKsusdAta = getAssociatedTokenAddressSync(vault.ksusdMint, user.publicKey);
const ksusdAccount = await getAccount(connection, userKsusdAta);

const shares = BigInt(ksusdAccount.amount.toString());
console.log("Your ksUSD:", Number(shares) / 1e6);   // 6 decimals
```

***

## Current share price

```ts
// Mirrors the on-chain Vault::share_price_1e9() helper.
const cachedNav = BigInt(vault.cachedNavUsdc.toString());
const queuePending = BigInt(vault.queuePendingUsdc.toString());
const pendingPerfFees = BigInt(vault.pendingPerfFeesUsdc.toString());
const totalShares = BigInt(vault.totalShares.toString());

// Gross basis: what the high-water mark is measured against.
const grossEffectiveNav = cachedNav - queuePending;
// Net basis: what deposits and withdrawals actually price against.
const effectiveNav = grossEffectiveNav - pendingPerfFees;

const sharePrice1e9 = totalShares === 0n
  ? 1_000_000_000n
  : (effectiveNav * 1_000_000_000n) / totalShares;                 // 1e9-scaled

const sharePriceUsdc = Number(sharePrice1e9) / 1e9;                // dollars per ksUSD
console.log("Share price:", sharePriceUsdc.toFixed(6));
```

The price is stored as dollars × 1e9, so `1_030_000_000` is $1.03. Everything above is one division: the dollars the vault holds for shareholders, divided by the ksUSD outstanding. See [NAV & share pricing](/how-it-works/strategy-and-modes/nav-calculation) for why two items come out of NAV before that division.

The share price starts at `1.000000` and rises as carry accrues. It only goes down in a drawdown.

Performance fees apply only to new gains above the highest price the vault has previously reached, tracked as `hwm_share_price_1e9`. So recovering from a dip is free.

***

## Your USDC-equivalent value

Your balance times the price — the same arithmetic `withdraw_instant` runs:

```ts
// shares and sharePrice1e9 are both BigInt; dividing by 1e9 undoes the price scale.
const yourUsdc = (shares * sharePrice1e9) / 1_000_000_000n;
console.log("Withdrawable USDC:", Number(yourUsdc) / 1e6);
```

***

## Vault-level NAV

```ts
console.log("Cached NAV (USDC):       ", Number(vault.cachedNavUsdc.toString()) / 1e6);
console.log("Effective NAV (USDC):    ", Number(effectiveNav) / 1e6);
console.log("Queue pending (USDC):    ", Number(vault.queuePendingUsdc.toString()) / 1e6);
console.log("Accrued perf fees (USDC):", Number(vault.pendingPerfFeesUsdc.toString()) / 1e6);
console.log("Total shares (ksUSD):    ", Number(vault.totalShares.toString()) / 1e6);
console.log("Position mode:           ", vault.positionMode);   // Idle / Normal / WindDown
console.log("Liquidity buffer bps:    ", vault.liquidityBufferBps);
console.log("Last settle ts:          ", new Date(Number(vault.lastSettleTs) * 1000));
console.log("Last NAV attest ts:      ", new Date(Number(vault.lastNavAttestTs) * 1000));
console.log("Funding EMA (bps):       ", vault.fundingAprSmoothedBps);
console.log("Peak share price 1e9:    ", vault.peakSharePrice1e9.toString());
console.log("HWM share price 1e9:     ", vault.hwmSharePrice1e9.toString());
console.log("Paused:                  ", vault.paused);
```

`cached_nav_usdc` refreshes on every deposit, withdrawal, and fee collection, and whenever someone runs `settle` or `attest_nav`. In between it holds the last recorded snapshot, so any profit or loss sitting open on the perp venue shows up at the next refresh rather than in real time.

***

## Pending queued withdrawal (if any)

```ts
// Derive your most recent withdrawal request PDA.
const [requestPda] = PublicKey.findProgramAddressSync(
  [
    Buffer.from("withdrawal_request"),
    vaultPda.toBuffer(),
    new BN(myRequestId).toArrayLike(Buffer, "le", 8),  // recorded when you called request_withdrawal
  ],
  PROGRAM_ID
);

const req = await program.account.withdrawalRequest.fetchNullable(requestPda);
if (req) {
  console.log("USDC owed:    ", Number(req.usdcOwed.toString()) / 1e6);
  console.log("Requested at: ", new Date(Number(req.requestedTs) * 1000));
  console.log("Processed:    ", req.processed);
}
```

The request account closes once `process_withdrawal` runs, and its rent deposit comes back to you.

***

## Related

* [Deposit](/start-here/deposit) · [Withdraw](/start-here/withdraw)
* [NAV & share pricing](/how-it-works/strategy-and-modes/nav-calculation)
* [Account structure](/build-on-it/quick-start/accounts) — full `Vault` and `WithdrawalRequest` layouts
* [Events](/build-on-it/quick-start/events) — programmatic subscription to NAV-changing events


# What it costs

{% hint style="info" %}
**TL;DR** 0% management fee. 20% performance fee, only above a high-water mark *and* a hurdle at the USDC lending rate: the vault must beat a Kamino deposit before it charges anything.
{% endhint %}

**The floor is a Kamino deposit; the upside is 80% of everything above it.** The performance fee applies only above a benchmark set to the USDC lending rate. A year spent merely matching what the same dollars would have earned lending costs nothing, so the fee cannot put a holder behind the benchmark. Above it, they keep 80 cents of every dollar of edge.

There's one fee schedule, and it applies to the vault as a whole rather than to individual holders.

Fees are paid in USDC out of the vault. They are not paid by minting new tokens, and nothing is ever taken out of your balance. What you see afterward is a share price that reflects the money that actually left.

***

## Rates

The whole schedule, before any of the reasoning below:

| Fee                     | Rate                                                                      | Mechanism                                                                                                                                                                               |
| ----------------------- | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Management              | **0%**                                                                    | Not charged. Capital does not pay rent.                                                                                                                                                 |
| Performance             | **20% above the HWM, itself above a hurdle set to the USDC lending rate** | Accrues only on gains that beat both the high-water mark and the benchmark, and is set aside as it's earned. The hurdle is `hurdle_apr_bps`, measured live at deploy rather than fixed. |
| Rebalance / mode switch | **0%**                                                                    | No fee charged on internal position rotation.                                                                                                                                           |
| Withdrawal              | **0%**                                                                    | Neither instant nor queued path charges a fee.                                                                                                                                          |

***

## High-water mark (HWM)

The high-water mark is the highest **gross** share price the vault has ever reached, stored as `vault.hwm_share_price_1e9`. Performance fees accrue only while the gross price is above it.

The practical effect: if the vault dips and then recovers, you pay nothing on the recovery. You're only charged on genuinely new gains.

### The hurdle: the HWM ratchets at the benchmark rate

A plain high-water mark charges a fifth of *every* dollar of gain, including gains the vault didn't really add. The vault spends much of its life Parked, which is USDC lent on Kamino — something any holder can do directly in one click. Charging a performance fee on that leaves the holder behind where they'd have been without the vault at all, which is not a fee schedule anyone should defend.

So the HWM advances *on its own* at `hurdle_apr_bps` per year, whether or not the vault earns anything:

```
dt      = now − last_fee_accrual_ts
hwm    += hwm × hurdle_apr_bps × dt / (10_000 × SECONDS_PER_YEAR)
```

Only the excess over that ratchet is fee-bearing. A year that returns exactly the hurdle rate costs nothing; a year above it is charged only on the part above.

**`hurdle_apr_bps` is not a compiled-in rate.** The bootstrap script reads the live Kamino USDC supply APY at deploy and writes that value. On mainnet a failed read aborts the deploy rather than falling back, because the fallback would be exactly the stale constant the hurdle exists to avoid. (The default in `InitializeParams` is a tests-and-localnet value, not the launch one.) After deploy it's adjustable via `update_params`, capped at 20%/yr, so it can track the benchmark as that moves. Setting it to `0` restores the plain HWM exactly.

The drift is real: the rate has moved by most of a point within a few days. Any rate printed in these docs is a dated snapshot; the live one is whatever `hurdle_apr_bps` currently reads on the vault account.

### What the hurdle is worth

The hurdle changes only the fee; strategy, gross return and drawdown are the same either way. Over the 316-day [backtest window](/how-it-works/strategy-and-modes/historical-simulation) it lifts net APY from **6.23% to 7.19%**, worth 96 bps a year. Fees paid fall from $1.34 to $0.55 per $100 over the window, a 59% cut; $0.55 over 316 days is a take rate of 0.63% a year.

Gross is 7.84% and net 7.19%, so the gap between them is 65 bps; that gap is the fee's effect on the compounded return, not a second fee. Parked, you keep the lending rate in full. Net of fees, the edge over lending is about 268 bps.

```bash
npm run fund:backtest                    # with the hurdle (current)
HURDLE_APR_BPS=0 npm run fund:backtest   # flat 20% fee, no hurdle
```

### What happens when lending spikes

Measuring the rate at deploy fixes the starting value, not the drift. USDC lending goes rich during liquidation cascades, and nothing updates the stored number on its own. That cuts both ways.

**A stale hurdle is worse than no hurdle.** If lending runs at triple the stored rate, the vault charges a performance fee on return the holder could have had by lending directly, and the overcharge scales with the spike. The hurdle has to be maintained; it is not set-and-forget.

**But chasing the spike is also wrong**, because the ratchet is one-way. Raise the hurdle, leave it a month, revert: the benchmark has already advanced and there is no un-ratchet, so a transient spike would suppress fees permanently.

Two mechanisms resolve that:

* **On-chain, the gap is capped.** The ratchet stops once the HWM sits `MAX_HURDLE_GAP_BPS` (5%) above the current gross share price. Over-reacting to a spike therefore costs a bounded amount rather than an unbounded one, which makes tracking the benchmark honestly a safe thing to do. It also stops a long flat stretch from putting the HWM so far overhead that every later recovery is fee-free forever.
* **Off-chain, the keeper watches the drift.** The `watchdog` duty compares `hurdle_apr_bps` against the *smoothed* lending APY rather than the spot rate, and warns once they diverge. Smoothing is the point: it fires on a rate that has actually moved, not on the first hour of a cascade.

**The operator rule:** raise the hurdle when the smoothed benchmark has held above it for a sustained stretch, not on a single spike. The cap means being late is cheap and being early is bounded.

There's a second-order effect too. A lending spike raises the opportunity cost of being hedged, so the keeper's dynamic threshold will already be pushing the vault toward Parked. The hurdle question and the regime question move together.

The implementation handles a few edge cases deliberately:

* **An empty vault does not ratchet.** A vault at zero shares for a year would otherwise hand the first depositor a hurdle debt to climb out of.
* **The ratchet won't run over intervals under an hour.** It rounds to whole units, so a short interval throws away most of its own increment, and because `settle` is permissionless, a fast crank could otherwise have quietly shrunk the hurdle. Short intervals are banked until an hour has accumulated, so the hurdle comes out the same however often anyone cranks.
* **A zero `last_fee_accrual_ts` does not ratchet.** The field is zero on a vault whose state predates it; without the guard `dt` would be the entire Unix epoch and the hurdle would swallow every fee the vault ever earns. The first accrual just sets the clock.

### Fees accrue continuously, not at collection

Fees are set aside as they're earned. `accrue_perf_fees` runs on every price change (`settle`, `attest_nav`) and again before any deposit mints shares:

```
gross_price      = gross_effective_nav_usdc × 1e9 / total_shares
if gross_price <= hwm_share_price_1e9:  nothing accrues
gain_per_share   = gross_price − hwm_share_price_1e9
fee              = gain_per_share × total_shares × perf_fee_bps / 1e13   // 1e9 price × 1e4 bps
pending_perf_fees_usdc += fee        (capped at gross_effective_nav_usdc)
hwm_share_price_1e9     = gross_price
```

Two consequences follow:

* **`pending_perf_fees_usdc` is subtracted from `effective_nav_usdc`.** So the share price is always already net of fees owed, and collecting them later doesn't step the price down. An exiting holder also can't dodge a fee they've already accrued.
* **The HWM advances before new shares are minted.** A fresh depositor is never charged on appreciation that happened before they arrived. Accruing incrementally is what avoids that: recomputing `(price − HWM) × total_shares` once at collection time would apply a stale HWM to a grown share count and overcharge anyone who entered above it.

### What `collect_fees` does

By the time it runs, the amount is already determined. Collection just moves money.

1. Requires `position_mode == Idle` (Parked) and `!paused`, and only the admin can call it.
2. Calls `accrue_perf_fees` to catch up to the current price, then reads `pending_perf_fees_usdc`. If it's zero, the call is a no-op.
3. Requires the vault's main USDC account to hold at least the full fee, or reverts with `InsufficientLiquidityBuffer`.
4. Transfers the fee to the admin's USDC account and reduces `cached_nav_usdc` by the same amount.
5. Zeroes `pending_perf_fees_usdc` and lowers the HWM by exactly the per-share amount paid out (`perf_fee_usdc × 1e9 / total_shares`), updating the peak if the new price is a high.

   **Why "lower by the payout" and not "re-anchor to the current price".** Those agree when you collect at a high, but accrued fees survive a dip; collection is the only thing that zeroes them. Re-anchoring while the price was below the HWM would drop the bar to the bottom of the dip and charge the whole recovery a second time, breaking the guarantee above. Subtracting only the payout keeps the gap intact, so a recovery over ground you have already paid for stays free, and the hurdle's accumulated benchmark survives too.

Because step 5 removes exactly what step 4 accounted for, collection is **share-price-neutral**.

***

## No reserve fund

There is no reserve or insurance fund, and that is a design choice rather than a gap to close later.

* [**ksUSD defends no peg**](/start-here/reserve-asset)**.** An insurance fund is what a pegged dollar needs, because a discount there is an existential failure. Here the share price is the shock absorber: NAV is marked at market, the price is designed to be able to fall, and a holder exiting into a bad unwind bears it rather than passing it to the holders who stayed. Reserving against market risk would contradict all of that.
* **The arithmetic could not work anyway.** A 1% jitoSOL discount costs **0.82% of NAV**. No skim on a 20% performance fee gets near that, and a reserve too small to cover a single incident is machinery without a purpose. Every instruction and state field it needs is audit surface.

**What Keystone does stand behind** is narrower: shortfalls the *protocol* caused (a bad fill, an oracle mismark later corrected, an accounting gap): cases where the vault did something to a holder rather than the market doing it to everyone. The operator makes those whole from its own fees by sending USDC to the vault's main account; `settle` counts idle USDC into NAV, so the share price reflects it at the next crank. No instruction is needed and no capital sits idle against an event that has not happened.

***

## Who can call `collect_fees`

* Only the admin can call `collect_fees`
* The math is fully on-chain and reproducible from `cached_nav_usdc`, `queue_pending_usdc`, `pending_perf_fees_usdc`, `total_shares`, and `hwm_share_price_1e9`
* `pending_perf_fees_usdc` is readable at any time, so the fee owed is visible before anyone collects it
* Anyone can check the fee delta before and after. Calling it needs the admin; auditing it needs nobody.

***

## Worked example

**Start:**

* Vault holds $1,000,000 NAV, 1,000,000 ksUSD outstanding
* Share price = $1.0000 · HWM = $1.0000

**Carry accrues** over a quarter. `cached_nav_usdc` grows to $1,030,000, and each `settle` along the way calls `accrue_perf_fees`. By the end:

* Gross share price: $1.0300, so gross gain per share is $0.0300
* Accrued fee: 0.0300 × 1,000,000 × 0.20 = **$6,000**, held in `pending_perf_fees_usdc`
* HWM has advanced to **$1.0300** (gross)
* Net share price: ($1,030,000 − $6,000) / 1,000,000 = **$1.0240**

Holders have been seeing $1.0240 all along, because the accrued fee was already carved out. Now the admin runs `close_position` to move the vault to Parked, then calls `collect_fees`:

* **$6,000** → admin's USDC account
* `cached_nav_usdc`: $1,030,000 − $6,000 = **$1,024,000**
* `pending_perf_fees_usdc` → 0
* Net share price: $1,024,000 / 1,000,000 = **$1.0240**, unchanged
* HWM drops by the $0.0060 paid per share, to **$1.0240**

The share price doesn't move at collection, which is the whole design goal. The next fee only accrues above $1.0240, so recovering from a drawdown is free.

***

## Related

* [NAV & share pricing](/how-it-works/strategy-and-modes/nav-calculation) — share-price math, `effective_nav_usdc`
* [Admin operations](/run-it/keeper-bot/admin-ops) — `collect_fees`
* [Security model](/reference/security) — admin role and HWM monotonicity guarantee
* [Whitepaper — Yield sources & fees](/how-it-works/whitepaper#iv-the-share-and-what-it-costs)


# What can go wrong

{% hint style="info" %}
**TL;DR** The hedge removes most of SOL's price move, not all. The residual has three sources: jitoSOL/SOL depeg (the largest, with nothing in front of it), delta drift inside the rebalance band, and the perp trading away from spot. This page sizes each.
{% endhint %}

How the ksUSD vault handles volatility, slippage, and oracle stress.

**NAV** below is the total dollar value of everything the vault holds. A **settle** is a routine update anyone can trigger that refreshes the vault's numbers from the venues it uses.

***

## Built-in protections

Each of these is enforced on-chain rather than by the keeper, so none of them depends on someone being awake:

| Layer                       | Mechanism                                                                                                                                                            | Default                               |
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- |
| **Liquidity buffer**        | Idle USDC kept on-vault for instant withdrawals                                                                                                                      | 10% of NAV                            |
| **Drawdown guard**          | `emergency_close` callable by anyone once `(peak − current) / peak ≥ emergency_close_dd_bps` AND `consecutive_dd_settles_observed ≥ consecutive_dd_settles_required` | 5% NAV drop, sustained 2 settles      |
| **Mode-switch dwell**       | Minimum time between mode changes to prevent ping-pong on noisy funding                                                                                              | 12 h                                  |
| **Funding EMA + staleness** | Smoothed funding on-chain; opens revert if stale                                                                                                                     | 6 h staleness                         |
| **Drawdown latency**        | Two consecutive sub-threshold settles required before drawdown trips                                                                                                 | `consecutive_dd_settles_required = 2` |
| **Slippage cap**            | Jupiter swaps revert if executed price worse than `max_swap_slippage_bps`                                                                                            | 0.5%                                  |
| **Oracle staleness**        | Pyth feed must have an update within the staleness window                                                                                                            | 5 min                                 |
| **Oracle confidence**       | Pyth `confidence / price` must be tight                                                                                                                              | < 2%                                  |
| **LST depeg check**         | `settle` auto-pauses if `jitoSOL / SOL < 1 − lst_depeg_bps`                                                                                                          | 5%                                    |
| **NAV change cap**          | `attest_nav` delta bounded per hour                                                                                                                                  | ±10%/hr                               |
| **HWM monotonicity**        | Performance fees can't be charged twice on the same gains                                                                                                            | Always                                |
| **Deposit cap**             | Total NAV cap to bound systemic exposure during early operation                                                                                                      | $500k at launch                       |
| **Wind-down path**          | Terminal admin instruction that blocks new state and switches users to pro-rata claim                                                                                | Manual                                |
| **Minimum margin**          | `open_position` rejects a position that posts less margin than this at the venue                                                                                     | ≥9% of deployed capital               |
| **Margin ceiling**          | `add_margin` refuses to post more than half of effective NAV to the venue                                                                                            | 50% of NAV                            |
| **Margin top-up**           | Keeper adds collateral when health falls, restoring it before liquidation                                                                                            | Automatic                             |

"EMA" above is an exponential moving average, a running average that weights recent readings more heavily. The vault uses one to smooth the funding rate so a single odd hour can't move the decision.

***

## On stress events

### Deeply negative funding

Phoenix funding averaged −14% across February 2026, and single hours run far beyond any monthly mean. The smoothed funding rate and the dwell timer stop the vault from flipping on one bad sample, so it waits for a sustained signal.

An open short is held until the 7-day mean falls below the exit line (−2.88%). Then the vault closes it and parks in USDC lending rather than paying funding or trying to harvest it; v1 has no mode that borrows. In February that exit came on the 3rd, and the month still closed positive.

### jitoSOL depeg

`settle` reads both Pyth feeds. If `jitoSOL/SOL` falls below `1 − lst_depeg_bps`, it reverts with `LstDepeg` and pauses the vault. Any existing position stays open, but nothing new can be opened. The admin then investigates and either unpauses or calls `emergency_close`.

### Oracle outage

The Pyth staleness and confidence checks make every strategy instruction that needs a SOL/USD price revert. Deposits and instant withdrawals don't read the oracle at all, so those keep working through a brief outage.

### Phoenix outage / market halt

Strategy instructions fail at the point where they call into Phoenix. Open positions keep accruing funding, since the venue settles that internally, and the next `settle` refreshes NAV. If a position has to be exited urgently, `emergency_close` can run as soon as the market can be read again.

### Sharp SOL rally

**The vault is not levered.** Its total exposure equals its NAV, and the short is sized 1:1 against the jitoSOL it holds — that 1:1 is what makes the book neutral in the first place. A SOL rally can't hurt the portfolio.

It can still hurt the *position*, because the two legs sit in different places. Only about 8% of NAV (9.1% of deployed capital) is posted at Phoenix as margin; the rest of what backs that short is the jitoSOL held here in the vault, which Phoenix cannot see. So on a rally the short's loss eats visible margin while the exactly offsetting jitoSOL gain sits somewhere outside Phoenix's accounting. From the venue's point of view the position looks thinly collateralised, and its liquidation engine acts on its own view — closing a position that was never economically at risk and turning a paper wash into a real loss.

The drawdown guard cannot catch this. `emergency_close` triggers on NAV falling, and NAV *doesn't* fall in a hedged rally, because the legs offset. The vault reads healthy right up to the moment Phoenix liquidates.

So the keeper watches it directly. The `margin-health` duty runs every tick, right after `settle`, and moves USDC into Phoenix margin when the cushion thins, funded by the leg that is gaining at that same moment. Every top-up is bounded twice: it can never draw on the withdrawal buffer, and total posted margin can never exceed half of effective NAV.

Margin only moves one way. There is no instruction that takes collateral back off a live position; surplus returns when the position closes, which the vault does on its own at the next mode flip. That costs a little yield while it sits, and buys the guarantee that nothing in the system can under-collateralise a live short.

Topping margin up is an active defence rather than a static cushion, so on its own it would depend on the keeper running. It doesn't, because there is a second defence underneath it.

**Below a hard margin floor, anyone can de-lever the position.** Not top it up but shrink it: buy back part of the short and sell the matching slice of jitoSOL, both legs by the same fraction, so net exposure never moves. Notional falls and collateral rises at once, and margin health improves from both directions. A permissionless caller can only route the proceeds back to margin, never to the buffer, so the path cannot be used to drain the position.

That floor ships **disabled** (`hard_margin_floor_bps` defaults to 0) and wants a deliberate value set alongside the first position. Until it is set, the keeper is the only line of defence, and if auto-margin is off or the keeper is down, the position should be closed rather than left to sit. Thresholds and the measured move sizes behind them: [keeper bot](/run-it/keeper-bot#the-keeper-moves-margin-autonomously) and [instructions](/build-on-it/quick-start/instructions#why-margin-is-its-own-instruction).

### NAV reconciliation drift

If a keeper-reported NAV would move more than `max_nav_change_bps_per_hour` in one step, `attest_nav` reverts with `NavChangeExceedsCap`. The keeper then stages several smaller updates across consecutive hours. An outsized jump is a signal to investigate, not something to push through.

***

## What's *not* protected

* **Residual price risk. The hedge is near-zero, not zero.** The vault is delta-hedged by design, but three things stop the offset being exact:

  * **jitoSOL is not SOL.** The spot leg is jitoSOL and the short is SOL-PERP, so the two only cancel while the jitoSOL/SOL ratio behaves. A depeg is a direct loss; a 5% move trips the auto-pause, and the loss lands on NAV with no reserve fund in front of it (see the whitepaper).
  * **Delta drifts between rebalances.** The short is sized when the position opens, and jitoSOL then appreciates against SOL at the staking rate, about 1.35 basis points a day. `rebalance_hedge` sweeps that back whenever the drift passes the **25 bps band**, roughly every two and a half weeks, so the book is never more than a quarter of a percent off-hedge in normal conditions. The program computes the target itself from the spot balance and the stake-pool redemption rate; the keeper supplies no size, and cannot steer the hedge. Corrections are clipped per call so a large one walks in over several orders rather than one thin sweep.
  * **The perp can trade away from spot.** Mark and index diverge, especially under stress, and the position is marked against the perp.

  Staking accrual is hedged too. The appreciation *is* the yield, and left unhedged it would be denominated in SOL, its dollar value floating with the market.

  None of this is large in normal conditions, and the backtest's −0.314% max drawdown is measured through a month in which Phoenix funding averaged −14%. But "no price risk" would be the wrong claim, and it is not the one made here.
* **A falling staking rate.** Staking is the engine, and Solana's emission schedule takes it down: **SIMD-0550** passed on 28 August 2026 and doubles disinflation from −15%/yr to −30%/yr from early 2027, pulling the 1.5% terminal rate forward to roughly 2029. Nothing in the vault offsets that. As the staking rate falls the mode threshold rises, the vault parks more of the time, and the return leans harder on funding — gradually rather than breaking, because parking is a floor. On the backtest window the edge over lending narrows from +268 bps at 4.94% jitoSOL to +152 bps at 3.00% and never turns negative across the 2.00–5.50% sweep (its low is +110 bps at 2.80%), though the low-staking rows are mode-behaviour noise and rest on a window whose last month was the venue's best. The schedule, the two break-evens and the full sweep are in [the whitepaper's staking runway](/how-it-works/whitepaper#vii-the-staking-runway).
* **Smart-contract bugs.** The program is unaudited until the planned pre-mainnet audit. Don't deploy significant capital until the results are published.
* **Counterparty insolvency.** A critical exploit or a compromised upgrade key at Phoenix, Ember, Kamino, Jupiter, or Jito would flow straight through into NAV losses.
* **Black-swan slippage.** The modelled max drawdown of **−0.314%** charges a fixed 10 bps of perp slippage a side and does not simulate price impact in a thin book. A depeg plus a \~50 bps round-trip reprice on the basis leg gives a month of −1.64% at a 1% discount, −2.45% at 2% and −4.91% at 5%, and it lands on the share price.
* **Regulatory action.** A jurisdiction restricting access to Solana DeFi could squeeze redemption liquidity for affected users.

***

## Related

* [Security model](/reference/security)
* [NAV & share pricing](/how-it-works/strategy-and-modes/nav-calculation) · [Whitepaper — Risk](/how-it-works/whitepaper#risks)


# Strategy & Modes

ksUSD runs one trade. The vault holds staked SOL and shorts the same amount of SOL on a perp market, so the two largely cancel and SOL's price mostly stops mattering. Traders call this a delta-neutral basis trade; the offset is close but not exact, which is why this book says delta-hedged.

At any moment the trade is either on or off. A funding-rate signal decides which, and a keeper bot flips the switch. Either way the vault's net SOL exposure stays near zero, so holding ksUSD is not a bet on SOL's price.

<figure><img src="https://54366478-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKGeChFh17iBDmI2WymJg%2Fuploads%2Fgit-blob-522088733452f823bb43484d00e0063223a2efdf%2Fmodes-1-two-modes.svg?alt=media" alt="Two modes: Normal basis shorts SOL-PERP at 1× and holds jitoSOL unlevered, earning funding plus staking; Parked holds no perp and lends the entire NAV as USDC on Kamino, earning lending yield."><figcaption><p>The protocol is always in exactly one of two states.</p></figcaption></figure>

***

## The two modes

**Normal basis, the trade is on.** The vault holds jitoSOL outright, with nothing borrowed against it. This is the spot leg, and it earns staking yield whatever the perp market is doing.

Against it, the vault shorts an equal amount of SOL-PERP on Phoenix, posting USDC as margin through Ember. jitoSOL is never posted as perp collateral. Funding on the short is the price of leverage on Phoenix's book, so it swings with the traders on it: since the venue opened it has averaged +3.49% APR, from −14% to +22% by month.

The vault collects both at once: staking on the jitoSOL and funding on the short. SOL price moves largely cancel, but not exactly, since jitoSOL can drift against SOL and delta moves between rebalances (see [Risk](/start-here/volatility-risk-management)).

**Parked, the trade is off.** The vault closes the short, sells the jitoSOL back to USDC, and lends everything on Kamino. This is the default whenever funding doesn't pay enough to be worth it. The liquidity buffer stays in the vault's own USDC account the whole time, so instant withdrawals keep working.

***

## When does the vault turn the trade on?

Most basis products just ask "is funding positive?" That's the wrong question here, because the jitoSOL you hold while short is *also* earning staking yield. The real question is whether staking plus funding beats plain USDC lending, after costs.

Work that out and the break-even lands at slightly *positive* funding: **+0.12%** at jitoSOL's 4.94% published pool APY and the 4.51% Kamino USDC rate (seven-day median, measured 13 Oct 2026). Staking on its own falls just short of USDC lending once the margin earns nothing, so the short has to earn a little before hedging beats parking.

Use the pool's rate here, not Solana's 5.30% *network* rate. The vault holds jitoSOL, so what counts is what the pool pays after validator commission and Jito's fee.

That means the entry point isn't a fixed number. It's a formula:

```
threshold = LEND / (1 − m) − STAKE + fees + buffer
```

| Term     | Meaning                                                                 |
| -------- | ----------------------------------------------------------------------- |
| `LEND`   | USDC lending APY — what parking the cash earns                          |
| `STAKE`  | jitoSOL staking APY — what the spot leg earns                           |
| `m`      | margin fraction (9.1% of deployed capital, 8.2% of NAV; earns 0%)       |
| `fees`   | round-trip perp + swap cost                                             |
| `buffer` | risk cushion: perp exposure, liquidation on a rally, jitoSOL depeg tail |

When USDC lending gets rich, parking competes harder and the threshold rises: at 5.00% lending it would be **+0.66%**. When staking runs hot it falls, crossing zero at 5.06% jitoSOL. The keeper recalculates it each cycle from live rates.

### Why there's a band, not a line

Funding is noisy. The vault picks its mode on a 7-day average but earns or pays day by day, so sitting exactly on the threshold would flip it in and out constantly, and each switch costs about 20 bps.

So the vault uses a band of ±3 percentage points around the threshold. At +0.12% it enters Normal basis only above **+3.12%** funding, exits below **−2.88%**, and does nothing in between.

The band is the largest modelling choice in the backtest, worth **351 bps**. Removing it drops net APY from 7.19% to 3.68%, below lending, because Phoenix's funding swings between −14% and +22% by month. The band cuts the switches from 22 to 4, which avoids about 416 bps a year of switching cost (18 × 20 bps over 316 days), and gives about 65 bps back in worse mode selection.

The entry gate sits just below Phoenix's mean funding (+3.49%) but above its median day (+1.25%), so on a typical day the band binds. On a flat-zero funding series the vault would never enter Normal basis and would park permanently. 3 points is the best width tested on this window, but it comes from a 30-day payback rule rather than from fitting; the [historical simulation](/how-it-works/strategy-and-modes/historical-simulation#the-hysteresis-band) has the derivation and the sweep. Because the band is centred on the threshold, it moves when the threshold does.

### Why the threshold sits just above zero

Staking and lending set the threshold: while the hedge is on, jitoSOL earns 4.94% on 81.8% of NAV whether funding is positive or not. At 4.51% lending that is just short of enough on its own, so the short has to earn at least 12 bps a year before parking loses.

The vault deploys with its on-chain floor at that break-even, `funding_threshold_normal_bps = 12`, and the keeper can only be tighter than the floor, never looser. So the program never opens a short below +0.12% funding, and the keeper's dynamic rule decides when above that it actually does.

The band still holds an open short through negative funding down to −2.88%, which holds jitoSOL for longer, and that is depeg exposure. The 12-hour dwell bounds how often that happens and the depeg auto-pause bounds how bad it gets.

***

## Why Parked stays in USDC lending, not T-bills

Parked always means USDC lending, never a tokenized T-bill like USDY or OUSG:

* Tokenized securities carry permissioned transfer hooks, which break permissionless holding and redemption.
* Their non-US-person restrictions shrink the addressable market.
* They add a securities-law surface.

Anyone who wants T-bill exposure can redeem and buy a bill directly. ksUSD measures itself against USDC lending, not a T-bill rate.

***

## Keeping the hedge the right size

The two legs cancel on the day the position opens. They don't stay cancelled.

jitoSOL earns its yield by appreciating against SOL, so the spot leg gains SOL value while the short stays exactly the size it was: about 1.35 bps a day, the staking rate. Left alone, the vault accumulates real directional exposure to SOL without ever placing a trade. That is the opposite of what it promises to hold.

So the short gets resized. Two different operations do it, and the difference between them is the whole point.

|                      | Short exposure | Long (jitoSOL) exposure | Net exposure           |
| -------------------- | -------------- | ----------------------- | ---------------------- |
| **Resize the hedge** | changes        | unchanged               | moves back toward zero |
| **De-lever**         | decreases      | decreases               | **stays where it was** |

**Resizing the hedge moves one leg.** The vault reads its own jitoSOL balance and the jitoSOL/SOL rate, works out how much SOL it is actually holding, and trades the perp to match. It takes no size instruction from anyone; the target is arithmetic on the balance. Under-hedged, it sells more; over-hedged, it buys some back. Either direction, it only ever moves net exposure *toward* zero, never past it. There is no way to use it to take a position.

It also has a ceiling. Growing a short raises the margin the venue demands, so the increase is capped at what the posted collateral can actually carry. If the target needs more than that, the vault does as much as it can afford and flags the shortfall rather than rebalancing itself toward a liquidation.

**De-levering moves both legs together.** Buy back part of the short, sell the matching slice of jitoSOL. The position gets smaller, net exposure doesn't move. This is what funds a withdrawal queue larger than the buffer, and what defends margin when it runs thin.

The obvious shortcut, selling some jitoSOL to raise cash, is the one thing that must not happen. Margin runs short when SOL **rallies**, because that is when the short is losing. Selling jitoSOL then would shrink the long leg while the short stayed whole, leaving the vault net **short** into a rising market, with losses compounding in exactly the scenario that triggered the top-up. Moving both legs by the same fraction is what stops the rescue from becoming the risk.

Below a hard margin floor, anyone can trigger the de-lever, not just the keeper. A defence that depends on our bot being awake is not a defence. Such a caller can only push the proceeds back to margin, never to the buffer, so it cannot be used to drain the position.

***

## Mode-switch guardrails

The funding signal decides *whether* to switch. These parameters bound *how*.

The keeper only executes; it doesn't decide. It's a permissioned key (`authorized_keeper`) that cannot open a position the funding rule forbids. And the drawdown, depeg, and oracle-divergence guards can pause the vault without anyone's permission.

| Guard                             | Default                                               | Effect                                                                                                              |
| --------------------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| Funding threshold                 | +0.12% break-even (on-chain floor +12), ±3-point band | Vault shorts only above +3.12% and holds until funding drops below −2.88%; the band and the 7-day mean stop whipsaw |
| `min_dwell_seconds`               | 12 h                                                  | Minimum time in a mode before it can switch again                                                                   |
| `funding_max_staleness_seconds`   | 6 h                                                   | Opens revert with `FundingSignalStale` if `settle` is overdue                                                       |
| `consecutive_dd_settles_required` | 2                                                     | A drawdown trip needs two consecutive bad settles                                                                   |
| `lst_depeg_bps`                   | 5%                                                    | `settle` auto-pauses the vault on a jitoSOL depeg                                                                   |
| `max_swap_slippage_bps`           | 0.5%                                                  | Jupiter swaps revert past this realized slippage                                                                    |

***

## Related

* [What is ksUSD?](/start-here/reserve-asset) — overview and yield sources
* [Risk management](/start-here/volatility-risk-management) — drawdown guard, slippage bounds, dwell timers, depeg and staleness guards
* [Whitepaper](/how-it-works/whitepaper) — full design, NAV math, security, risk disclosures


# NAV & Share Pricing

ksUSD prices itself the way sUSDe does. Your `ksUSD` balance never changes. What changes is the price of each token, which drifts up as carry accrues. So you don't watch for new tokens arriving; you watch the price.

***

## The whole idea, in one line

```
share price = the dollars the vault holds for shareholders ÷ ksUSD in circulation
```

That dollar figure is the vault's **NAV**, its net asset value. Divide it by the token count and you have what one token is worth.

Two examples, and they are the only two operations there are:

* **Deposit.** Put in $100 while the price is $1.03 → you get `100 ÷ 1.03 = 97.09` ksUSD.
* **Redeem.** Hand back 97.09 ksUSD while the price is $1.05 → you get `97.09 × 1.05 = $101.94`.

Everything below is that one division, written precisely enough to implement.

***

## Share price

There are two NAV figures, and the difference between them is the accrued performance fee.

```
gross_effective_nav_usdc = cached_nav_usdc − queue_pending_usdc
effective_nav_usdc       = gross_effective_nav_usdc − pending_perf_fees_usdc

share_price_1e9       = effective_nav_usdc × 1e9 / total_shares         (when total_shares > 0)
                      = 1_000_000_000 (= $1.00)                         (when total_shares = 0)
gross_share_price_1e9 = gross_effective_nav_usdc × 1e9 / total_shares
```

The **net** price (`share_price_1e9`) is what deposits and withdrawals use, so it's the one that matters to you. The **gross** price is what the high-water mark is measured against. Net is always ≤ gross.

* `cached_nav_usdc` — USDC base units (6 decimals)
* `total_shares` — ksUSD base units (6 decimals)
* Rust helpers: `Vault::share_price_1e9()` and `Vault::gross_share_price_1e9()`

### Reading the `1e9` scale

A Solana account stores integers, not decimals, so the price is carried as dollars × 1,000,000,000. To read one, move the decimal point nine places left:

| Stored `share_price_1e9` | Dollars per ksUSD |
| ------------------------ | ----------------- |
| `1_000_000_000`          | $1.000000         |
| `1_030_000_000`          | $1.030000         |
| `1_002_500_000`          | $1.002500         |

The scale is 1e9 rather than the token's own 1e6 so that a day of carry, a few hundredths of a cent per token, doesn't round away to nothing. It's wide enough to price accurately without pushing the arithmetic past a `u128` intermediate.

### Why two things come out of NAV

The vault holds some money that isn't shareholders'. Each subtraction takes one of those out before the division, so the price reflects only what holders actually own.

| Subtraction              | Reason                                                                                                                                                                                                                                                                        |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `queue_pending_usdc`     | These shares are already burned and the vault owes real USDC against them. Leaving that money in the count would let new depositors mark the price up against a liability that's already locked.                                                                              |
| `pending_perf_fees_usdc` | Performance fees are set aside as they're earned, not at collection time. Carving them out here means the share price is already net of fees owed, so collecting them later doesn't step the price down, and a holder who exits first can't dodge a fee they already accrued. |

***

## What `cached_nav_usdc` includes

The vault recalculates `cached_nav_usdc` any time its state changes. It adds up:

```
NAV = idle USDC in the vault's USDC ATA
    + USDC lent on Kamino (idle-USDC leg)
    + (jitoSOL spot holdings × oracle jitoSOL price)    [normal basis — the unlevered spot leg]
    + perp-venue margin balance (settled funding + PnL) [normal basis — USDC margin on Phoenix]
```

Between updates, funding and profit still sitting open on the perp venue are not counted in `cached_nav_usdc`. Anyone can run `settle` to refresh the margin figures from the venue. For open profit and loss the keeper can also run `attest_nav(new_nav_usdc)`, which is capped per hour by `max_nav_change_bps_per_hour`.

***

## Oracle pricing

jitoSOL and SOL/USD prices come from Pyth. Every single read is checked twice before the vault will use it:

| Check      | Threshold                          | Effect                                               |
| ---------- | ---------------------------------- | ---------------------------------------------------- |
| Staleness  | < 5 minutes since last Pyth update | Stale → revert with `StaleOracle`                    |
| Confidence | conf / price < 2%                  | Out of band → revert with `OracleConfidenceExceeded` |

The thresholds are tight enough to catch an oracle outage or a manipulated feed, but loose enough not to trip on ordinary market activity.

***

## Drawdown peak

`vault.peak_share_price_1e9` holds the highest share price any `settle` has ever seen. The drawdown guard measures how far the price has fallen from that peak:

```
drawdown_bps = (peak - current) × 10_000 / peak
if drawdown_bps >= emergency_close_dd_bps:
    emergency_close is permissionless to crank
```

A single bad reading can't force an emergency exit. The condition has to hold across `consecutive_dd_settles_required` settles in a row, which defaults to 2, and firing early reverts with `DrawdownTriggerLatent`.

Only the admin can reset the peak, using `reset_peak`; collecting fees doesn't touch it. And note that the drawdown watches the live share price, not the post-fee high-water mark used for fees.

***

## Worked example

A vault holding $1M against 1M ksUSD, which then earns $30,000 of carry. The left column is what a holder sees; the right is what's stored on-chain.

|                            | In dollars      | On-chain (base units)                 |
| -------------------------- | --------------- | ------------------------------------- |
| **Start** — NAV            | $1,000,000      | `cached_nav_usdc = 1_000_000_000_000` |
| **Start** — supply         | 1,000,000 ksUSD | `total_shares = 1_000_000_000_000`    |
| **Start** — price          | $1.0000         | `share_price_1e9 = 1_000_000_000`     |
| **After $30k carry** — NAV | $1,030,000      | `cached_nav_usdc = 1_030_000_000_000` |
| **After carry** — supply   | unchanged       | `total_shares = 1_000_000_000_000`    |
| **After carry** — price    | $1.0300         | `share_price_1e9 = 1_030_000_000`     |

Nobody's balance moved when the vault earned. The price did the work.

Now a new depositor sends 100 USDC. They get `$100 ÷ $1.03 = 97.087…` ksUSD:

```
shares_minted = 100_000_000 × 1e9 / 1_030_000_000
              = 97_087_378.6…  →  truncated to 97_087_378 ksUSD base units
```

Vault after: `total_shares ≈ 1_000_097_087_378`, `cached_nav_usdc = 1_030_100_000_000`, and the price is still $1.0300: $100 of new money bought exactly $100 of shares. The truncation rounds against the depositor by under one base unit, a millionth of a token, which is what stops a mint from nudging the price down for everyone else.

So the new holder has \~97.087 ksUSD worth the same \~$100 they put in: fewer tokens than the earlier depositor got, each one worth more.

> This example ignores fees to keep the arithmetic clear. In the real path, `deposit` calls `accrue_perf_fees` before it prices the mint, so the share price is already net of fees owed and the new depositor is never charged on gains that happened before they arrived.

***

## Related

* [Fee structure](/start-here/fees) — HWM math and the hurdle
* [Check position & NAV](/start-here/check-position) — TypeScript snippets to query share price live
* [Security model](/reference/security) — oracle, slippage, drawdown guard


# Historical Simulation

{% hint style="info" %}
**TL;DR** Every complete month of Phoenix SOL-perp history, 2025-11-19 to 2026-09-30 (316 days), on Phoenix's own funding: **7.19% net APY**, **−0.314%** worst drawdown, hedged 57.9% of days. September was the venue's best month; end in August and net is 5.86%.
{% endhint %}

*Daily resolution, on measured inputs: Phoenix funding, jitoSOL staking 4.94%, USDC lending 4.51%. The window ends on the last complete month and rolls forward with it.*

## What this is

A day-by-day replay of the two modes v1 has, normal basis and parked, over every day the venue has existed.

The window is short on purpose. Phoenix's SOL perp began quoting on **2025-11-18**, and its funding is the only funding this strategy will ever collect. A longer window would mean substituting another venue's funding for Phoenix's.

That substitution fails on the data. Over the 316 days both series cover, Phoenix averaged **+3.53% APR** while Binance averaged **−0.70%**, and the two disagreed on sign for weeks at a time. Funding is set by which side of a particular book is crowded, so ten and a half months of the real series beats four years of a proxy.

| Input   | Source                                                                                                                                                |
| ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| Funding | Phoenix SOL perp, hourly, from inception (`/v1/funding/SOL/rates`)                                                                                    |
| Staking | jitoSOL 4.94%, checked against the pool's on-chain redemption rate (2.08 bp/epoch × 231 epochs/yr); MEV included, net of commission and Jito's 4% fee |
| Lending | Kamino main-market USDC 4.51%, the seven-day median of `supplyInterestAPY`, measured 2026-10-13                                                       |

## The result

$100 compounded to **$106.19** over the 316 days. The worst peak-to-trough fall was −0.314%.

| Metric               | Value                   |
| -------------------- | ----------------------- |
| Max drawdown         | **−0.314%**             |
| Net APY              | **7.19%** (7.84% gross) |
| $100 →               | $106.19 over 316 days   |
| Days hedged / parked | 57.9% / 42.1%           |
| Mode switches        | 4                       |
| Edge vs USDC lending | +268 bps                |

The worst day was **2026-02-03, −0.188%**, which is a mode switch rather than a market move. No month closed negative; the weakest was February 2026 at +0.08%.

Month-end NAV, base 100, 2025-11 → 2026-09:

`100.24, 100.66, 101.12, 101.20, 101.58, 101.85, 103.02, 103.13, 103.52, 104.57, 106.19`

### How NAV is allocated

Every figure on this page runs on the allocation the program uses. The 10% redemption buffer splits into a 2% instant tranche held as raw USDC and 8% lent on Kamino. Margin is a fraction of *deployed* capital: 9.1% of it, which is 8.2% of NAV.

Per $100 of NAV in Normal mode:

|                  | Weight | Earns         |
| ---------------- | ------ | ------------- |
| jitoSOL basis    | $81.8  | 4.94% staking |
| USDC perp margin | $8.2   | 0%            |
| Buffer, lent     | $8.0   | 4.51% Kamino  |
| Buffer, raw      | $2.0   | 0%            |

The derivation is in the [whitepaper](/how-it-works/whitepaper#what-the-conversion-costs).

{% hint style="info" %}
These are backtest figures. The funding rate in the app's regime widget is a live snapshot, not a backtest APY.
{% endhint %}

## What Phoenix has paid

Phoenix funding has averaged **+3.49% APR** since the venue opened. The median day paid +1.25%, and 62.8% of days were positive. By month it ran from −14% to +22%, and the vault's own month never went negative:

| Month   | Funding mean APR | Funding median | Positive hours | ksUSD month |
| ------- | ---------------- | -------------- | -------------- | ----------- |
| 2025-11 | +3.35%           | +1.38%         | 72%            | +0.24%      |
| 2025-12 | +0.92%           | 0.00%          | 50%            | +0.42%      |
| 2026-01 | +1.48%           | +0.66%         | 57%            | +0.45%      |
| 2026-02 | **−14.06%**      | −13.90%        | 3%             | +0.08%      |
| 2026-03 | −3.46%           | −3.03%         | 30%            | +0.38%      |
| 2026-04 | +0.41%           | 0.00%          | 43%            | +0.26%      |
| 2026-05 | +12.58%          | +13.78%        | 84%            | +1.15%      |
| 2026-06 | +0.24%           | 0.00%          | 43%            | +0.10%      |
| 2026-07 | −0.06%           | 0.00%          | 38%            | +0.38%      |
| 2026-08 | +13.51%          | +9.64%         | 88%            | +1.02%      |
| 2026-09 | **+22.05%**      | +20.91%        | 98%            | **+1.56%**  |

**September is the venue's best month on record, and it closes the window.** It is why the headline sits above the 5.86% the same run gives through August. One +22% month at the end of a 316-day sample is a reason to discount the headline. Funding has stayed hot into October, which the window does not include.

February is the month to read for risk. Funding averaged −14% and the vault still closed the month positive, because the short is a hedge. Most of the −0.314% drawdown is the vault's own trading: with switching costs at zero the worst fall is −0.126%.

Of all hours in the series, **12.8% printed exactly zero funding**, from 0.4% of hours in September 2026 to 33.2% in June. Those are hours where mark and index sat close enough that nothing accrued.

## Where the yield comes from

Fully hedged, per $100 of NAV per year:

| Leg                                                          | Per year    |
| ------------------------------------------------------------ | ----------- |
| $81.8 of jitoSOL @ 4.94% staking                             | +$4.04      |
| $8.2 of USDC margin at Phoenix @ 0%                          | $0.00       |
| $8.0 of redemption buffer, lent @ 4.51%                      | +$0.36      |
| $2.0 of buffer held raw for instant redemption               | $0.00       |
| Funding on the short, at the +8.68% its hedged days averaged | +$7.10      |
| Perp fees, charged per day held                              | −$0.08      |
| **Hedged run rate**                                          | **+$11.42** |

That is the rate while the position is on. Hedged days averaged +8.68% funding, well above the venue's +3.49%, because the vault parks when funding turns: the days it sat out averaged −3.57%.

Two things take the run rate down to the gross: the vault is hedged only a little over half the time, and moving between modes costs money.

|                                                                    | Per year   |
| ------------------------------------------------------------------ | ---------- |
| Hedged run rate, 57.9% of days                                     | +$6.61     |
| Parked at 4.42% (lending, less the instant tranche), 42.1% of days | +$1.86     |
| 4 mode switches @ 20 bps                                           | −$0.92     |
| Compounding                                                        | +$0.29     |
| **Gross**                                                          | **+$7.84** |

Switching gives back **22%** of the funding the vault collects: $0.92 against the $4.11 that +8.68% on 57.9% of days is worth.

### Each leg on its own

Switching each leg off shows what it contributes:

|                           | Net APY | Days hedged |
| ------------------------- | ------- | ----------- |
| Published                 | 7.19%   | 57.9%       |
| Funding off entirely      | 4.52%   | 0%          |
| Staking off, funding only | 5.20%   | 57.9%       |

With funding removed the vault never opens the hedge. Staking alone does not beat lending once the margin earns nothing, so it parks throughout and earns 4.52%.

Funding alone does beat lending on this window, at 5.20%, and that is mostly September. Neither leg gets near the combined 7.19%.

At the margin, removing funding costs **267 bps** and removing staking costs **199 bps**. The two legs behave differently: staking accrues on every hedged day with nothing traded, while funding decides *whether* to hedge and arrives in bursts.

The two fail differently too. Thin funding parks the vault at the lending rate, which is a floor. A falling staking rate raises the bar for hedging at all, so the vault parks more often.

## Sensitivity

Each input is moved alone below, with the mode threshold re-derived wherever staking or lending changes. The largest modelling choice is the [hysteresis band](#the-hysteresis-band), worth 351 bps; the hurdle is worth 96 bps and the redemption buffer costs 46.

### Staking

The vault holds jitoSOL, so the input is the stake pool's rate, not Solana's network rate. We measure it from the pool's redemption rate, `total_lamports / pool_token_supply`, which steps only at epoch boundaries and by a very stable amount:

|                 |                                                                                                               |
| --------------- | ------------------------------------------------------------------------------------------------------------- |
| Per-epoch step  | 2.09, 2.09, 2.08, 2.07 bp *(4 consecutive epochs to 2026-09-04)*                                              |
| Epoch length    | 136,794 s = **1.5833 days**, the mean over four epoch boundaries (slots run \~316 ms, not the nominal 400 ms) |
| Epochs per year | 230.54                                                                                                        |
| **Implied APY** | **4.92%** (4.89–4.94% across the step range)                                                                  |

The published 4.94% sits at the top of that range, so the headline is about 2 bp generous. That is too small to move any figure downstream, so the model keeps the pool's own number.

Reproduce it with `npm run rate:jito` (one snapshot per epoch) and `npm run rate:jito -- --apy`. The second reads `scripts/simulations/data/jitosol_redemption_rate.csv` and refuses to annualize a span shorter than three epochs.

Do not annualize by differencing calendar days. The snapshots are irregularly spaced, and a 7-day window catches three or four epoch steps depending on where it lands, so naive differencing reads anywhere from 3.9% to 4.7%.

Two other rates get quoted for jitoSOL, and the vault earns neither:

| Rate  | Source                                    | Why not this one                                                                                             |
| ----- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| 4.99% | Jito's site, 2026-09-05                   | A trailing, MEV-inclusive estimate. Reaching it needs a 2.11 bp step per epoch, above all four on record.    |
| 5.30% | `getInflationRate` 3.666% ÷ 69.22% staked | Solana's *network* rate. It includes validator commission and Jito's 4% fee, which the vault never receives. |

**SIMD-0550 passed on 28 August 2026** (67.001% of participating stake, activating early 2027). It doubles Solana's disinflation from −15%/yr to −30%/yr, so the next three years take the staking rate down through most of the table below. The threshold is re-derived at every row as `f* = 5.06% − staking`:

| jitoSOL                                          | Threshold  | Gross     | Net       | Hedged    | Perf fee /$100 | vs lending   |
| ------------------------------------------------ | ---------- | --------- | --------- | --------- | -------------- | ------------ |
| 5.50%                                            | −0.44%     | 7.74%     | 7.10%     | 77.2%     | $0.53          | +259 bps     |
| 5.06% *(staking alone just justifies the hedge)* | 0.00%      | 7.90%     | 7.24%     | 57.9%     | $0.56          | +273 bps     |
| **4.94%&#x20;*****(measured, headline)***        | **+0.12%** | **7.84%** | **7.19%** | **57.9%** | **$0.55**      | **+268 bps** |
| 4.60%                                            | +0.46%     | 7.68%     | 7.06%     | 57.3%     | $0.52          | +255 bps     |
| 4.05% *(≈2027)*                                  | +1.01%     | 6.87%     | 6.41%     | 55.4%     | $0.39          | +190 bps     |
| 3.50%                                            | +1.56%     | 6.59%     | 6.20%     | 55.1%     | $0.34          | +169 bps     |
| 3.00%                                            | +2.06%     | 6.39%     | 6.03%     | 53.2%     | $0.30          | +152 bps     |
| 2.80% *(≈2028)*                                  | +2.26%     | 5.86%     | 5.61%     | 35.4%     | $0.21          | +110 bps     |
| 2.10% *(≈2029)*                                  | +2.96%     | 6.22%     | 5.90%     | 33.2%     | $0.28          | +139 bps     |
| 2.00%                                            | +3.06%     | 6.18%     | 5.86%     | 32.9%     | $0.27          | +135 bps     |

What to read off it:

* **Today's rate is already below the first break-even.** At 4.94% staking against 4.51% lending, the short has to earn +0.12% before hedging beats parking.
* **Net degrades gracefully.** Parking is a floor, and on this window the edge over lending never goes negative; the lowest row is +110 bps.
* **The performance fee halves**, from $0.55 per $100 to $0.27, because September's funding still clears the hurdle at every staking rate.

The rows below about 4% are dominated by mode behaviour. The vault parks roughly half to two thirds of the time there, so the result turns on a handful of decisions (mostly whether it is hedged for September) and does not fall monotonically. Read those rows as direction, not forecast.

Two simplifications make the table harsher than it should be:

* It scales jitoSOL proportionally with the network rate, but MEV is not inflation-linked and should survive the taper.
* It holds lending at 4.51% throughout, though rates have historically moved with staking.

### The lending benchmark

Across lending rates from 3.61% to 5.00% the edge over lending stays between **246 and 278 bps**; at 5.50% it falls to +188 bps. The rate matters twice: parked mode earns it, and the fee hurdle ratchets at it.

| Kamino USDC                                    | Threshold  | Net       | Hedged    | vs lending   |
| ---------------------------------------------- | ---------- | --------- | --------- | ------------ |
| 3.61%                                          | −0.87%     | 6.39%     | 78.2%     | +278 bps     |
| 3.69%                                          | −0.78%     | 6.41%     | 77.8%     | +272 bps     |
| 4.19%                                          | −0.23%     | 6.65%     | 76.9%     | +246 bps     |
| 4.44% *(30-day median)*                        | +0.04%     | 7.15%     | 57.9%     | +271 bps     |
| **4.51%&#x20;*****(7-day median, published)*** | **+0.12%** | **7.19%** | **57.9%** | **+268 bps** |
| 4.75% *(spot)*                                 | +0.39%     | 7.34%     | 57.3%     | +259 bps     |
| 5.00%                                          | +0.66%     | 7.48%     | 57.0%     | +248 bps     |
| 5.50%                                          | +1.21%     | 7.38%     | 55.4%     | +188 bps     |

Net APY rises with the benchmark because the vault parks more and collects the richer lending rate. That is not reassurance; the column to read is the edge. A rising benchmark pulls the vault toward a plain Kamino deposit.

The published row is the seven-day median, not the spot print. The hurdle only ratchets one way and this reserve throws utilisation spikes, so a spot read at the wrong moment could write a hurdle the strategy never clears. `rates.ts` takes the median for that reason and `init-v1.ts` writes what it returns.

### The cost of a switch

Every mode change is charged 20 bps of NAV: 5 bps perp fee and 10 bps perp slippage on the short, plus 5 bps of swap on the jitoSOL leg. It is the one headline input the venue's data cannot confirm, because `/v1/market/SOL/stats` keeps about a day of history and there is no past depth to size a fill against.

| Per switch                        | Gross     | Net       | Max DD      | vs lending   |
| --------------------------------- | --------- | --------- | ----------- | ------------ |
| 0 bps                             | 8.84%     | 7.98%     | −0.126%     | +347 bps     |
| 10 bps                            | 8.34%     | 7.59%     | −0.214%     | +308 bps     |
| **20 bps&#x20;*****(published)*** | **7.84%** | **7.19%** | **−0.314%** | **+268 bps** |
| 30 bps                            | 7.34%     | 6.79%     | −0.414%     | +228 bps     |
| 40 bps                            | 6.85%     | 6.40%     | −0.514%     | +189 bps     |
| 60 bps                            | 5.86%     | 5.61%     | −0.714%     | +110 bps     |
| 80 bps                            | 4.88%     | 4.82%     | −0.968%     | +31 bps      |
| 100 bps                           | 3.91%     | 3.84%     | −1.367%     | −67 bps      |

The vault makes the same 4 switches at every cost; the price of a decision changes what it costs, not which decisions get made.

**This is the input the drawdown is most exposed to.** The yield has room: the edge survives to about 85 bps a switch, four times the published assumption. The drawdown has less. From 30 bps up February closes negative, and only 12.6 bps of the published 31.4 is market; the rest is switching cost. A reader who doubts the slippage assumption should discount the drawdown first.

Two things bound it the other way. The jitoSOL side of the switch is measured: a $1.3M swap fills flat, so the 5 bps charged there is about eight times too conservative. And the 20 bps is charged on all of NAV when only 81.8% of it is in the position.

### The hysteresis band

The threshold applies as a ±3-point band rather than a line. The vault enters only when funding clears the threshold by 3 points (+3.12%), exits only when it falls 3 points below (−2.88%), and holds in between.

The band is worth **351 bps**. Without it the vault switches 22 times and nets 3.68%, below lending. Cutting the switches from 22 to 4 avoids about **416 bps** a year of switching cost (18 × 20 bps over 316 days), and the band gives about **65 bps** back in worse mode selection.

The width is a payback rule. A switch costs 20 bps and the edge accrues on the 81.8% basis leg, so requiring a move to repay itself within `T` days gives:

```
(f − f*) × 0.8181 × T/365 > 0.0020        →        band = 0.893 / T  points

T = 30 days  →  2.97 points        (the 3.00 in the code)
T = 60 days  →  1.49 points
T = 90 days  →  0.99 points
```

On this window it is also the best width tested:

| Band                            | Gross     | Net       | Hedged    | Switches |
| ------------------------------- | --------- | --------- | --------- | -------- |
| 0                               | 3.71%     | 3.68%     | 62.7%     | 22       |
| 0.5 pp                          | 4.11%     | 4.08%     | 65.2%     | 20       |
| 1.0 pp                          | 6.55%     | 6.16%     | 69.9%     | 10       |
| 1.5 pp                          | 6.45%     | 6.08%     | 71.2%     | 10       |
| 2.0 pp                          | 6.93%     | 6.47%     | 76.3%     | 8        |
| **3.0 pp&#x20;*****(shipped)*** | **7.84%** | **7.19%** | **57.9%** | **4**    |
| 4.0 pp                          | 7.79%     | 7.15%     | 57.3%     | 4        |
| 6.0 pp                          | 7.60%     | 7.00%     | 52.8%     | 4        |

We did not tune it to this result. The runs differ by up to eighteen switching decisions over 316 days, and fitting a switching parameter on so few events is how a backtest gets optimised into something that does not generalise. The payback rule does not depend on the sample, and it happens to land on the best value here.

The four switches are two round trips: out **2026-02-03**, back **04-17**; out **06-08**, back **08-07**, then hedged through September. The first is February's funding collapse, the case the rule exists for. Both trips lasted two months or more, so a 21-day minimum dwell changes nothing on this window.

Because entry requires clearing the threshold *by* the band, the entry line (+3.12%) sits just below Phoenix's mean funding of +3.49% and well above its +1.25% median day. On a typical day the band binds. On a permanently flat funding series the vault would never open the position. As a falling staking rate raises the threshold, the entry line rises with it: +4.01% at the 2027 threshold of +1.01%.

### Model choices

| Variant                                                | Gross     | Net       | Max DD      | Hedged    |
| ------------------------------------------------------ | --------- | --------- | ----------- | --------- |
| **Published**                                          | **7.84%** | **7.19%** | **−0.314%** | **57.9%** |
| No redemption buffer                                   | 8.43%     | 7.65%     | −0.331%     | 57.9%     |
| No margin haircut *(unreachable: margin is USDC-only)* | 8.53%     | 7.74%     | −0.327%     | 57.9%     |
| Hysteresis band 0.5 pp                                 | 4.11%     | 4.08%     | −0.892%     | 65.2%     |
| Hysteresis band 0                                      | 3.71%     | 3.68%     | −1.265%     | 62.7%     |
| Flat 20% fee, no hurdle                                | 7.84%     | 6.23%     | −0.314%     | 57.9%     |

The last row is what the hurdle is worth to a holder: **96 bps**.

## Holder flow, and what it costs

Getting the vault out of jitoSOL is close to free; moving the book for a holder who joins or leaves is not, and the program charges neither side for it.

The vault exits its spot leg by swapping rather than queuing a stake-pool withdrawal, so the market sets the cost. Quoted against the on-chain redemption rate of **1.299513895 SOL/jitoSOL**:

| Size               | Implied rate | vs redemption rate | Price impact |
| ------------------ | ------------ | ------------------ | ------------ |
| 100 jitoSOL        | 1.299437     | −0.6 bp            | 0.000%       |
| 1,000              | 1.299437     | −0.6 bp            | 0.000%       |
| 4,000              | 1.299437     | −0.6 bp            | 0.000%       |
| 10,000 *(\~$1.3M)* | 1.299437     | −0.6 bp            | 0.000%       |

That is flat to $1.3M, well past the deposit cap, so the model's 5 bps swap charge is roughly eight times too conservative.

`process_withdrawal` pays `min(requested, current claim)`, which stops a redeemer collecting a stale high price, but there is no exit fee. Past the 2% instant tranche a redemption draws the buffer, and rebuilding it means closing that slice of the short (15 bps) and swapping that slice of jitoSOL back (5 bps). The holders who stay pay that.

Deposits cost the same 20 bps in the other direction, and there is no entry fee either, so a new holder's build cost dilutes those already in. During a ramp that is the larger half.

The headline models no flow: a static $100 that nobody joins or leaves. The drag is published beside it instead. Rows are gross two-way flow, deposits plus redemptions:

| Flow                                        | Gross     | Net       | Cost vs static |
| ------------------------------------------- | --------- | --------- | -------------- |
| **0% of NAV / month&#x20;*****(headline)*** | **7.84%** | **7.19%** | —              |
| 2% / month                                  | 7.81%     | 7.16%     | −3 bps         |
| 5% / month                                  | 7.77%     | 7.13%     | −6 bps         |
| 10% / month                                 | 7.69%     | 7.07%     | −12 bps        |
| 25% / month                                 | 7.46%     | 6.89%     | −30 bps        |

Even heavy churn costs tens of basis points. It scales with the same 20 bps as a mode switch, so a reader who marks that assumption up should mark this table up with it. Reproduce with `FLOW_MONTHLY=0.05 npm run fund:backtest`.

## What the venue data cannot tell us

The funding series is real. Three things around it cannot be verified, and all three flatter the result:

* **The venue is gated.** `/v1/view/exchange/status` returns `"gated": true`, so every day in this window is a day we could not have traded. The capability grant is agreed and is enabled once the program is on mainnet.
* **There is no historical order-book depth.** `/v1/market/SOL/stats` keeps about one day, so past open interest and volume cannot be reconstructed. The model assumes the hedge was placeable in full every day at the parametric slippage, and nothing in the venue's data supports or refutes that.
* **Funding is treated as exogenous, and at our size it isn't.** Open interest measured 16 September 2026 was **$4.73M**, so a fully hedged $500k vault is about **11% of the book**. Its short pushes mark toward index and reduces the funding shorts receive. The capacity rule caps the vault at 15% of OI for this reason, but the yield figure does not carry the effect.

## Methodology

| Input          | Value                                                                                                                  |
| -------------- | ---------------------------------------------------------------------------------------------------------------------- |
| Window         | 2025-11-19 – 2026-09-30 (316 days), Phoenix SOL perp inception to last complete month                                  |
| Funding        | Phoenix's own hourly prints, unscaled (`FUNDING_SOURCE=phoenix`)                                                       |
| Staking        | 4.94% (`STAKE_APY`), jitoSOL's published pool APY                                                                      |
| Lending        | 4.51% (`LEND_APR`); parked mode earns it and the hurdle ratchets at it                                                 |
| Mode threshold | +0.12% (`STD_THRESHOLD`), the basis-vs-parked break-even at those rates, with a ±3-point band                          |
| Margin haircut | Over-margined well inside the venue's limit: 9.1% of deployed capital sits as USDC margin earning nothing, 8.2% of NAV |
| Costs          | 5 bps perp fee + 10 bps slippage per side, 5 bps swap per side; 20 bps per mode switch                                 |
| Fees           | 0% management; 20% performance above the HWM and the 4.51% lending-rate hurdle                                         |

Every cost is inside the gross return. The only step from gross to net is the performance fee, charged above the high-water mark and the [lending-rate hurdle](/start-here/fees#the-hurdle-the-hwm-ratchets-at-the-benchmark-rate). 7.19% is fully loaded.

### Where the +0.12% threshold comes from

Set the two modes equal on the allocation above. Parked, the whole $100 earns the lending rate except the $2 instant tranche. Hedged, $81.8 earns staking plus funding minus the amortized perp round-trip, the $8 lent buffer earns lending, and the $8.2 of margin earns nothing:

```
(staking + f − perp_drag) × 0.8181 + lending × 0.08  =  lending × 0.98
(4.94% + f − 0.10%)      × 0.8181 + 0.361%           =  4.420%
                                                   f  =  +0.12%
```

Once the margin earns nothing, staking alone falls just short of lending, so the short has to earn a little before hedging beats parking.

Both rates are measured, so the threshold moves: a richer lending market raises it and a higher staking rate lowers it. The keeper recomputes it each cycle from live rates. See [Strategy & Modes](/how-it-works/strategy-and-modes#when-does-the-vault-turn-the-trade-on).

{% hint style="warning" %}
**Deploy setting.** These figures assume an on-chain funding floor of **+12**, which is what `init-v1.ts` writes. The floor moves with both rates, so it is derived at deploy rather than carried from this page.
{% endhint %}

### Reproduce

```bash
npm run fund:phoenix     # refresh the venue funding series
npm run fund:backtest
```

The inputs above are the script's defaults, so the command reproduces this page with no environment set. Each is overridable for sweeps:

| Env knob         | Default                                                                   |
| ---------------- | ------------------------------------------------------------------------- |
| `FUNDING_SOURCE` | `phoenix`, the venue itself, unscaled                                     |
| `STAKE_APY`      | `0.0494`, jitoSOL published pool APY                                      |
| `STD_THRESHOLD`  | `0.0012`, break-even threshold                                            |
| `HYST`           | `0.03`, hysteresis band                                                   |
| `HURDLE_APR_BPS` | `451`, performance-fee hurdle, the live lending rate                      |
| `LEND_APR`       | `0.0451`, USDC lending rate; parked mode and the lent buffer earn it      |
| `FLOW_MONTHLY`   | `0`, gross two-way holder flow per month, charged at `FLOW_COST_BPS` (20) |

## What's not in the model

* **Perp price impact.** Slippage is a fixed 10 bps a side. Real fills depend on depth at the time, which the venue does not retain. [The cost of a switch](#the-cost-of-a-switch) prices being wrong about it, in the yield and the drawdown alike.
* **A full cycle.** 316 days is a young venue's record. The window already carries a −14% funding month and a hedged SOL fall; what it lacks is a stress event that takes perp depth and jitoSOL liquidity at the same time.
* **A long sample for the band.** Its 351 bps rests on four decisions across the window.
* **Holder flow.** Deposits and redemptions both cost 20 bps and the program charges neither party; the [sensitivity](#holder-flow-and-what-it-costs) sits beside the headline rather than inside it.
* **Sub-daily behaviour.** Modes are classified once per UTC day against a 7-day mean, so an intraday move a live keeper would react to is not modelled. Funding itself aggregates exactly (hourly prints averaged, accrual linear in the rate), so this is decision resolution rather than a missing cost.

## Related

* [Whitepaper](/how-it-works/whitepaper#vi-what-the-backtest-shows) — what the backtest shows
* [Strategy & Modes](/how-it-works/strategy-and-modes) — the mode rule and the break-even
* [Fee structure](/start-here/fees) — the lending-rate hurdle
* [Backtest data CSVs](https://github.com/kamwithak/keystone-contracts/tree/main/scripts/simulations/data/README.md)


# Whitepaper

{% hint style="info" %}
**TL;DR** Keystone holds jitoSOL and shorts the same amount of SOL on Phoenix, so staking yield arrives in dollars. Both legs move in one transaction. When the hedge costs more than it earns, it closes and parks in USDC lending. Backtest on Phoenix's own funding, 2025-11-19 to 2026-09-30: **7.19% net, −0.314% max drawdown**.
{% endhint %}

*Keystone Finance · Whitepaper v2.0 · 13 October 2026 · Kamran Choudhry*

***

## ksUSD turns SOL staking into dollar yield

Deposit USDC. Keystone buys staked SOL and shorts the same amount of SOL perp. Price risk cancels down to a small residual, and the staking yield is what is left. You hold a vault share, not a pegged dollar: your balance is fixed, and the share price rises as that yield accrues — and can fall. Nothing is emitted, nothing sits off-chain, and every position is verifiable on Solana.

**One program · one vault · one share mint.**

| Where the yield comes from                                                                                                | Net APY                 | Across 2.00–5.50% staking (§VII) | Floor              | Max drawdown                   |
| ------------------------------------------------------------------------------------------------------------------------- | ----------------------- | -------------------------------- | ------------------ | ------------------------------ |
| jitoSOL staking on \~82% of NAV while hedged, plus funding on the short, less the \~22% of funding spent on mode switches | **7.19%** (7.84% gross) | 5.61% to 7.24%                   | 4.51% USDC lending | **−0.314%** (316-day backtest) |

**Status: pre-deployment.** v1 hedges on Phoenix Perps (Ellipsis Labs) with USDC margin via the Ember program; jitoSOL is held unlevered as the spot leg. Devnet only, audit pending. Phoenix's SOL perp opened 18 November 2025, so the backtest window is the venue's entire life to its last complete month: 316 days of its own funding, unscaled. That is a young venue's record, not a market cycle.

## I. Where the yield comes from

Almost every yield-bearing dollar on-chain is, underneath, a bet on perp funding. This one parks when funding turns, so its floor is the lending rate, not funding's cycle.

Funding is the obvious thing to build on, and the first thing to go when you need it. Ethena showed both halves: sUSDe rode positive funding to around 15% through 2025, then settled back to 3.7% as funding compressed.¹ Build a dollar on funding and you inherit funding's cycle. Here, staking pays for the conversion and funding decides when it is worth running.

Fully hedged, per $100 of NAV per year:

| Leg                                                          | Per year    |
| ------------------------------------------------------------ | ----------- |
| $81.8 of jitoSOL @ 4.94% staking                             | **+$4.04**  |
| $8.2 of USDC margin at Phoenix @ 0%                          | $0.00       |
| $8.0 of redemption buffer, lent @ 4.51%                      | +$0.36      |
| $2.0 of buffer held raw for instant redemption               | $0.00       |
| Funding on the short, at the +8.68% its hedged days averaged | +$7.10      |
| Perp fees, charged per day held                              | −$0.08      |
| **Hedged run rate**                                          | **+$11.42** |

That is the rate while the position is on. The vault is hedged a little over half the time, earns 4.42% parked the rest, and pays $0.92 a year to move between modes, which takes the run rate down to the 7.84% gross.

Phoenix has averaged **+3.49% APR** since inception, positive on 62.8% of days. It also swings from −14% to +22% by month, and reacting to those swings gives back 22% of what the vault collects. The $7.10 is high because the vault parks when funding turns; the days it sat out averaged −3.57%.

Switch each leg off in the backtest to see what it contributes. With funding off, Keystone never hedges and earns lending, **4.52%**. With staking off, funding alone nets **5.20%**, 69 bps above lending, mostly on September. Neither leg gets near the combined 7.19%. On this window funding is the larger marginal leg, 267 bps against staking's 199; staking is the one nothing is traded for.

Funding pays only if the vault holds through its swings rather than trading them. With the hysteresis band off, the vault nets 3.68%, below the 4.52% it earns with no funding at all, because every move costs 20 bps. That is why the band (below) is worth 351 bps.

Funding is the price of leverage on a given venue, paid by whichever side of *its* book is crowded, so Phoenix's cannot be inferred from anyone else's. Over the 316 days both series cover, Phoenix averaged **+3.53%** while Binance averaged **−0.70%**, and the two disagreed on sign for weeks at a time. (The +3.53% is the matched comparison window; the venue's average since it opened, used everywhere else in this paper, is +3.49%.)

Phoenix's book is young, and funding arrives with traders. The headline claims only what the venue has already paid. Two things follow:

* **The correlation profile differs from both incumbents.** RWA dollars move with the Fed. Ethena moves with the crypto leverage cycle. This moves with Solana network activity.
* **Neither yield risk reaches the floor.** Thin funding costs the edge: below the entry gate Keystone parks in USDC lending, where it still earns. A falling staking rate narrows the spread from the other side, and Solana's is on a schedule to fall (§VII).

## II. How it works

### Two modes, one rule

Keystone is only ever in one of two states, and the same comparison decides which:

| Mode             | Position                                                                     | Earns                              |
| ---------------- | ---------------------------------------------------------------------------- | ---------------------------------- |
| **Normal basis** | long jitoSOL spot (unlevered) + short SOL-PERP on Phoenix at 1×, USDC margin | jitoSOL staking + funding received |
| **Parked**       | all capital in USDC lending (Kamino)                                         | lending yield (4.51%)              |

jitoSOL is held outright as the spot leg and USDC is posted as perp margin via Ember: no LST is used as perp collateral. Mode switches cost ≈20–40 bps round-trip. There is no reverse mode: harvesting negative funding means borrowing, which adds a borrow surface for very little return. Parked covers negative funding instead, and **v1 never borrows**.

<figure><img src="https://54366478-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FKGeChFh17iBDmI2WymJg%2Fuploads%2Fgit-blob-b3d313a8567ec33b746dd2cfa9a8942aab2970f7%2Fmodes-2-the-switch.svg?alt=media" alt="Smoothed perp funding decides the mode: when funding clears the dynamic threshold (+0.12%) Keystone moves to Normal basis (short plus staking); when funding is below it Keystone moves to Parked (USDC lending). Transitions are automatic, driven by the funding signal."><figcaption><p>One on-chain signal, smoothed funding, decides the mode.</p></figcaption></figure>

### When it switches

Keystone stays hedged for as long as hedging beats parking. Compare the two on $100:

|                      | Parked             | Normal basis                                 |
| -------------------- | ------------------ | -------------------------------------------- |
| Where the money sits | $90 lent on Kamino | $81.8 in jitoSOL, $8.2 as perp margin        |
| What it earns        | 4.51% on all of it | 4.94% on the $81.8; the margin earns nothing |
| **Per year**         | **$4.06**          | **$4.04**                                    |

Hedging starts **$0.02 behind**, so the short has to earn its way in. The short covers $81.8 of SOL, so $0.02 is **0.02%** of it; add the amortized perp round-trip and the break-even lands at **+0.12%**. Funding must clear that before Keystone is better off hedged.

That is the whole rule. Not "is funding positive?" but "does the short earn back the gap to parking?" The keeper recalculates that number each cycle from live staking and lending rates, so it moves when they do.

**Why the spread matters.** The threshold sits where staking and lending put it, not at zero. Lending has already risen to meet staking: the threshold is positive, and the entry gate above it, +3.12%, sits just under the +3.49% Phoenix has averaged and well over its +1.25% median day. So Keystone hedges only when funding runs hot.

That same gap names the failure. The further lending rises, the less often funding clears it, until Keystone is a Kamino deposit carrying the operational risk of a hedged one. A falling staking rate closes the gap from the other side. The keeper measures both rates every cycle because a constant on either side would leave the rule blind to the thing that ends the strategy.

**What the floor is set to.** Keystone ships with its on-chain floor at **+12**, the break-even itself, and the keeper can only ever be tighter than the floor, never looser. The program will not open a short below +0.12% funding; the keeper's dynamic rule decides when it actually does.

The threshold applies as a ±3-point hysteresis band rather than a line. Keystone opens only once funding clears the threshold by the band (+3.12%), and holds an open short until funding falls below −2.88%. The width is a payback rule: a switch costs 20 bps, and the edge accrues on the 81.8% basis leg, so requiring `(f − f*) × 0.8181 × T/365 > 20 bps` says "only move if the move repays itself within T". At **T = 30 days that is 2.97 points** — the 3.00 in the code.

On Phoenix's measured funding the band is worth **351 bps**. Removing it drops net from 7.19% to 3.68%, below lending, because funding swings from −14% to +22% by month and every move costs 20 bps. The band cuts the switches from 22 to 4, which avoids about 416 bps a year of switching cost (18 × 20 bps over 316 days), and gives about 65 bps back in worse mode selection. Without it the vault does not beat lending.

Sweeping the width across 0–6 points moves net between 3.68% and 7.19%, and **3 points is the best value tested on this window**; 2 points returns 6.47% and 4 points 7.15%.

That it scores best is not evidence for it. The runs differ by up to eighteen switching decisions over 316 days, and every width from 3 points up makes the same four. Fitting a switching parameter on so few events is how a backtest gets optimised into something that does not generalise; the payback rule does not depend on the sample. The [historical simulation](/how-it-works/strategy-and-modes/historical-simulation#the-hysteresis-band) carries the full sweep.

Transitions run automatically: the smoothed on-chain funding signal decides, a keeper bot executes, and a 7-day mean plus a 12-hour minimum hold filter out the noise. See [Strategy & Modes](/how-it-works/strategy-and-modes#when-does-the-vault-turn-the-trade-on).

### Near zero, not zero

Three things stop the legs cancelling exactly. The spot leg is jitoSOL while the short is SOL-PERP, so they offset only while the jitoSOL/SOL ratio holds; a depeg is a straight loss. Delta drifts inside a 25 basis point band between rebalances. A correction is bounded four ways: that band, a per-call clip, the position cap, and the collateral posted at the venue, since a short can only be as large as its margin carries. And the perp can trade away from spot, with the position marked against the perp.

Staking accrual is not a fourth item, because it is hedged rather than carried. The appreciation *is* the yield: jitoSOL gains about 4.94% a year against SOL, and leaving that alone would leave the return denominated in SOL rather than dollars. A resize sells it forward each time the drift passes the band, roughly every two and a half weeks.

None of the three that remain is large in ordinary conditions. Together they are still enough that "no price risk" would be the wrong claim. See [Risk](/start-here/volatility-risk-management).

### What the conversion costs

Every dollar posted as margin is a dollar not earning staking yield. At v1 sizing about **9.1% of deployed capital sits at Phoenix as USDC margin earning nothing**, which is about 8.2% of NAV, against 81.8% in jitoSOL earning the staking rate. A further 10% of NAV is the redemption buffer: 8% lent on Kamino, 2% held raw. That allocation is already inside every net figure here: the staking leg contributes $4.04 of the $11.42 hedged run rate.

The obvious dismissal is that this is a hedged jitoSOL wrapper. The difference shows up when funding inverts. A naive hedged LST keeps paying to hold its short and bleeds; ksUSD closes and parks in USDC lending. That exit costs 20–40 bps, is written into the program, and runs automatically on a signal nobody has to interpret.

## III. Why the hedge is the product

The hedge performs the conversion, so anything that can break the hedge breaks the product. That isn't a risk sitting beside the design; it is a hole in it. A venue that halts trading, or auto-deleverages a profitable short to cover someone else's loss, doesn't give ksUSD a bad day. It removes the leg that makes the yield a *dollar* yield, while Keystone still holds the jitoSOL.

So the venue choice carries weight rather than being a footnote. Phoenix settles on-chain. The vault opens, defends and closes its own hedge by calling the program directly, the position is visible on Solana, and no operator sits in between. That doesn't remove venue risk (§VIII is specific about what remains), but it puts the mechanism somewhere it can be inspected, which is the minimum you should want from the thing the product depends on.

## IV. The share, and what it costs

ksUSD is a **non-rebasing** share token. Your balance stays fixed and the share price rises as carry accrues. Redemption is against NAV, instant from the liquidity buffer and queued for larger size.

It is a share in a hedged carry vault, not a dollar-pegged stablecoin. No fixed yield, no RWA, no emissions, no view on where SOL goes. The architecture is small on purpose: one program, one vault, one rule set.

| Yield source        | Active when             | Contribution                                                     |
| ------------------- | ----------------------- | ---------------------------------------------------------------- |
| **jitoSOL staking** | Normal basis (spot leg) | **4.94% APR**                                                    |
| Phoenix funding     | Normal basis            | −14% to +22% by month; **+3.49% average** since the venue opened |
| USDC lending        | Buffer + parked         | 4.51% APR                                                        |

| Fee         | Rate                             |
| ----------- | -------------------------------- |
| Management  | **0%**                           |
| Performance | **20%, and only above a hurdle** |
| Withdrawal  | **0%**                           |

**The floor is a Kamino deposit; the upside is 80% of everything above it.** The hurdle is the USDC lending rate — what the same capital would earn sitting in Kamino by itself — so the performance fee applies only to what Keystone adds on top. A year that returns exactly the hurdle costs nothing, so the fee cannot drag a holder under the benchmark. Above it, they keep 80 cents of every dollar of edge.

Parked mode is why this matters. Parked, Keystone *is* a Kamino USDC deposit: no perp, no hedge, nothing the holder couldn't do themselves in a single transaction. Taking a fifth of that return would be charging a performance fee for holding a deposit, and it would leave a parked holder behind where they'd have been lending the USDC directly.

The hurdle gives those days' yield back in full, so the fee starts only where the strategy does. Across the backtest window it is worth 96 bps a year to the holder: a flat 20% would take net from 7.19% to 6.23%.

The rate isn't fixed in code. The hurdle is read from Kamino's live supply APY at deploy and maintained against the smoothed rate afterwards. See [Fees](/start-here/fees).

## V. Why this only assembles on Solana

The design needs four things on one chain, close enough together to compose:

* **An on-chain perp.** Keystone opens its hedge by calling into Phoenix Perps with USDC margin from its own program. Phoenix settles on-chain, and that direct call is the part that doesn't port.
* **Funding it receives**, rather than a pool borrow-fee it pays.
* **A high-yield LST and deep USDC lending.** jitoSOL held unlevered as the spot leg; Kamino for the liquidity buffer and parked NAV.
* **Fees low enough** that regular rebalancing stays economic.

On Ethereum these don't line up. Gas makes rebalancing expensive, the deepest perps sit off-chain or on separate domains, and LST yield, funding and lending live apart from each other. The spot leg also earns more here: Solana staking plus MEV tips leave jitoSOL paying 4.94% after validator commission and Jito's fee, against roughly 3% for Ethereum LSTs. The staking leg is the part of the return nothing is traded for, so that gap matters more than the composability argument does.

## VI. What the backtest shows

Daily resolution over every complete month Phoenix has quoted a SOL perp, 2025-11-19 to 2026-09-30. The v1 set, normal plus parked, turned $100 into **$106.19** over 316 days while never giving back more than **0.314%** from a peak. It held the hedge on 57.9% of days and switched modes four times.

| Variant                  | Net APY       | Gross APY | $100 net →  | Max DD                |
| ------------------------ | ------------- | --------- | ----------- | --------------------- |
| **Normal + parked (v1)** | **7.19%**     | 7.84%     | **$106.19** | **−0.314%**           |
| USDC lending benchmark   | 4.51%         | —         | —           | flat floor            |
| sUSDe benchmark          | \~3.7% recent | —         | —           | bleeds in low funding |

**The drawdown is the number worth reading, and worth attributing.** February 2026, the month Phoenix funding averaged −14%, closed *positive* — the short is a hedge, not the revenue. The 0.314% is mostly the vault's own trading: hold switching costs at zero and the worst fall is **0.126%**. The worst day in the published run is a mode change rather than a market day, and no month closed negative.

That 7.19% is fully loaded. The performance fee, the margin-capital haircut where USDC posted as margin earns nothing, and trading costs are all inside it. Against USDC lending it leaves about 268 bps of edge.

**It also leans on one month.** September 2026, +22% funding, is the venue's best month on record and the last in a short window, with the vault hedged through all of it. End the window a month earlier and net is 5.86%; that single month moves the headline by 133 bps. Funding has stayed hot into October, which the window does not include. Don't extrapolate it.

### What the result depends on

The window is 316 days, short of a full cycle, so what can be shown is which input the answer rests on. Move the lending benchmark from 3.61% to 5.00% and the edge over lending stays between **246 and 278 bps**. Move the staking rate across what the next three years can plausibly deliver, 5.50% down to 2.00%, and net APY stays between **5.61% and 7.24%**, never below the lending benchmark. That sweep and the schedule behind it are §VII, and staking is the input that decides how long this works.

The input the answer is *most* exposed to is what a mode change costs. The model charges 20 bps and the venue retains no historical depth to check it against. At 30 bps net is 6.79% and February closes negative; at 40 bps it is **6.40%**, 189 bps above the lending benchmark, and the drawdown rises to 0.514%. The edge is gone near 85 bps a switch.

Both headline numbers move on the same parameter, so a reader who marks the slippage assumption up should discount the drawdown as well as the yield.

### Method

Staking runs at jitoSOL's **4.94%** published pool APY: the stake pool's rate, MEV included and net of validator commission and Jito's fee. Solana's 5.30% network rate is not used, because the vault does not receive it. USDC lending runs at Kamino's 4.51% (7-day median, measured 2026-10-13), which parked mode earns and the fee hurdle ratchets at. Funding is Phoenix's own hourly record, unscaled.

The mode threshold is the break-even, +0.12%, with a ±3-point band. The perp leg is over-margined well inside the venue's 15× limit, so 8.2% of NAV sits as margin at zero yield. Costs are 5 bps perp fee and 10 bps slippage per side plus 5 bps of swap, 20 bps per switch.

Three things the venue's data cannot settle, all cutting the same way. Phoenix is still **gated** (`/v1/view/exchange/status` returns `"gated": true`), so every day in this window is a day we could not have traded. Historical order-book depth is not retained, so nothing supports or refutes the assumption that the hedge was placeable in full each day. And funding is treated as exogenous when at our size it is not: open interest measured 16 September was **$4.73M**, so a fully hedged $500k vault is \~11% of the book, and its own short pushes mark toward index and reduces the funding it collects.

Alongside those, 316 days is a young venue's life rather than a cycle. The model also runs a static $100: deposits and redemptions each cost 20 bps and the program charges neither party, so that drag is published beside the headline rather than folded into it. Detail: [historical-simulation.md](/how-it-works/strategy-and-modes/historical-simulation).

## VII. The staking runway

{% hint style="warning" %}
**The short answer.** Disinflation takes the spread, not the floor. Parked, ksUSD earns the lending rate, and net never falls below 5.61% anywhere in the sweep, so the schedule is a yield question rather than a safety one. At today's rates staking alone does not pay for the short, so whether the vault hedges at all is a funding call; on the schedule as passed the edge over lending stays above 110 bps through 2029 on this window's funding, which includes its best month. What narrows is what the vault earns above a Kamino deposit, and the fee that funds Keystone roughly halves.
{% endhint %}

Staking is the leg nothing is traded for, and Solana's staking rate is on a schedule to fall. **SIMD-0550 passed on 28 August 2026** with 67.001% of participating stake, doubling disinflation from −15%/yr to −30%/yr and pulling the 1.5% terminal rate forward to roughly 2029. Activation is expected in early 2027.

Two break-evens follow from the allocation, and they hold regardless of whether any projection is right. Parked earns the lending rate on all but the instant tranche, 4.42%. Hedged earns staking plus funding on the 81.8% basis leg, so the funding the short must earn is `f* = 5.06% − staking`.

| Below this jitoSOL rate… | …this stops being true                                                                                                                                                                                                           |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **5.06%**                | Staking alone justifies the hedge. Under it, the threshold is positive: the short has to earn positive funding before hedging beats parking, so the vault becomes funding-dependent.                                             |
| **1.57%**                | Average funding is enough. At 1.57% the threshold reaches +3.49%, Phoenix's average since it opened, so under it even an average funding day would not make hedging beat parking, and the vault is in practice a Kamino deposit. |

jitoSOL pays **4.94%** today. Mapping the passed schedule onto those lines, at the measured jitoSOL/network ratio of 0.9327:

|       | Network | jitoSOL   | Threshold  |
| ----- | ------- | --------- | ---------- |
| Today | 5.30%   | **4.94%** | **+0.12%** |
| 2027  | 4.34%   | 4.05%     | +1.01%     |
| 2028  | 3.00%   | 2.80%     | +2.26%     |
| 2029  | 2.25%   | 2.10%     | +2.96%     |

**The first line is already crossed.** jitoSOL pays 4.94% against a 5.06% break-even, so the threshold is positive today and the short has to earn its place. The funding sign therefore already decides whether the hedge goes on at all: the vault is still staking-based, but it is funding-dependent. The second line sits below the 2029 rate; only the 1.5% terminal network rate, about 1.40% jitoSOL, crosses it.

Running the backtest across that range, with the threshold re-derived at each step:

| jitoSOL                      | Threshold  | Gross     | Net       | Hedged    | Perf fee /$100 | vs lending   |
| ---------------------------- | ---------- | --------- | --------- | --------- | -------------- | ------------ |
| 5.50%                        | −0.44%     | 7.74%     | 7.10%     | 77.2%     | $0.53          | +259 bps     |
| 5.06% *(break-even 1)*       | 0.00%      | 7.90%     | 7.24%     | 57.9%     | $0.56          | +273 bps     |
| **4.94%&#x20;*****(today)*** | **+0.12%** | **7.84%** | **7.19%** | **57.9%** | **$0.55**      | **+268 bps** |
| 4.60%                        | +0.46%     | 7.68%     | 7.06%     | 57.3%     | $0.52          | +255 bps     |
| 4.05% *(2027)*               | +1.01%     | 6.87%     | 6.41%     | 55.4%     | $0.39          | +190 bps     |
| 3.50%                        | +1.56%     | 6.59%     | 6.20%     | 55.1%     | $0.34          | +169 bps     |
| 3.00%                        | +2.06%     | 6.39%     | 6.03%     | 53.2%     | $0.30          | +152 bps     |
| 2.80% *(2028)*               | +2.26%     | 5.86%     | 5.61%     | 35.4%     | **$0.21**      | **+110 bps** |
| 2.10% *(2029)*               | +2.96%     | 6.22%     | 5.90%     | 33.2%     | **$0.28**      | +139 bps     |
| 2.00%                        | +3.06%     | 6.18%     | 5.86%     | 32.9%     | $0.27          | +135 bps     |

**Net APY degrades gracefully, and so does the fee.** Parking is a floor, and on this window's funding the edge over lending never drops below 110 bps. The performance fee roughly halves, from $0.55 per $100 to $0.27, because the hurdle ratchets at the lending rate and the gap the fee is charged on narrows from the top. Both outlive the staking decline here, on funding that ends in the venue's best month.

Four qualifications. The first three suggest the table is too harsh; the fourth says how far to trust its lower rows:

* The projection scales jitoSOL's rate proportionally with the network rate. **MEV is not inflation-linked**, so a growing share of the pool's yield should survive the taper and the tail is understated. How much could not be established: Jito's published MEV series implies 4.48% APR against pool TVL, which cannot sit inside a 4.94% total, so it is not the pool's own share and no decomposition is offered here.
* The schedule cuts emissions, and a staker's yield is emissions divided by the staked share, so the cut lands one-for-one only if that share holds at today's 69%. Stake that leaves as the rate falls lifts the yield of what stays.
* The lending benchmark is held at 4.51% throughout. If rates fall with staking — and they have historically moved together — the spread closes far more slowly than this.
* The low-staking rows are **mode-behaviour dominated**. At those thresholds the vault parks roughly half to two thirds of the time, so those returns turn on a handful of decisions rather than on a stable edge, and they do not fall monotonically. Read them as direction, not as forecast.

## VIII. What can go wrong

### How redemption works

Share price is NAV divided by shares, marked from on-chain balances and oracle-priced legs. Deposits and instant withdrawals do not price off a keeper attestation at all: they read the Phoenix trader account and the SOL oracle directly and mark the perp leg themselves, so the number a depositor transacts at is computed from chain state at the moment they transact.

Attestation still carries NAV between those moments, bounded by a per-hour change cap and checked against the program's own reading of the position rather than a wide sanity band.

A 10%-of-NAV buffer covers normal redemptions instantly. Larger ones burn at the locked price and settle against what the unwind actually realizes, through a permissionless crank. A queued payout in stressed markets can therefore come in below marked NAV.

### Risks

**Structural — the ones that can end the conversion**

| Risk                           | Mitigation                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Hedge removed by the venue** | The one that matters most, per §III. A market halt, or auto-deleveraging that force-closes a profitable short to cover another trader's loss, ends the conversion while Keystone still holds jitoSOL — leaving it long SOL until it can re-hedge or sell. On-chain settlement means Keystone can see and act on this itself, and an emergency unwind can close the spot leg once the market is readable, but neither prevents an ADL. Sizing the short at a small fraction of open interest is the main defence, and it is why the deposit cap tracks the venue rather than demand. |
| jitoSOL depeg or slashing      | **Marked at market**, via the Pyth jitoSOL/USD feed — so a liquidity discount hits NAV and the share price immediately, not on sale. A discount past the depeg guard, measured against the Jito stake pool's redemption rate, auto-pauses Keystone and arms the emergency unwind. Slashing is unhedgeable, and neither Jito nor any third party reimburses it.                                                                                                                                                                                                                      |
| Smart-contract                 | Pre-mainnet audit scheduled; devnet only until then.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |

**Venue & counterparty**

| Risk                  | Mitigation                                                                                                                                                                                                                                                                                                          |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Perp-venue dependency | Phoenix is the only hedge venue, so an exploit, outage, or socialized loss hits ksUSD directly. Phoenix is in private beta, and trading needs an Ellipsis capability grant on the vault's trader account, agreed and enabled once the program is on mainnet. A second venue is the structural fix and is not in v1. |
| Counterparty          | Phoenix, Ember, Kamino, Jupiter, Jito. No single one holds all NAV, but nothing stands in front of a venue failure either — there is no insurance fund, see below.                                                                                                                                                  |
| Swap router           | Jupiter V6 routes every USDC↔jitoSOL swap. Slippage is bounded on-chain. An outage stalls mode rotation; buffer redemptions stay open.                                                                                                                                                                              |
| Oracle                | Pyth reads gated by 5-min staleness and 2% confidence; outages past that can still cause loss.                                                                                                                                                                                                                      |

**Yield**

| Risk                     | Mitigation                                                                                                                                          |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| Staking-rate compression | Quantified in §VII: two break-evens, at 5.06% (already crossed) and 1.57% jitoSOL, and the schedule that approaches the second.                     |
| Funding compression      | Costs the edge, not the floor. Keystone parks and earns 4.51%; on this window most of the edge above that is funding, and none of it is guaranteed. |

**Operational**

| Risk                    | Mitigation                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Liquidation             | The short is over-margined and the keeper tops margin up actively — idle USDC first, then a Kamino recall. Both are needed: the jitoSOL sits in Keystone while the margin sits at Phoenix, so the venue cannot see the collateral backing the short. When both sources are exhausted, Keystone de-levers instead: it buys back part of the short and sells the matching fraction of jitoSOL in one transaction, so notional and the collateral requirement fall together and the hedge never opens. Proportional is the whole point — selling jitoSOL alone is the obvious way to raise cash and the one that turns a squeeze into a loss, shrinking the long leg while the short stays whole and leaving Keystone net short into the very rally that caused the shortfall. Anyone may call it once margin falls below the floor, and a caller who is not the keeper may only route the proceeds back to margin — so a stranger can defend the position but cannot drain it. |
| Redemption under stress | Buffer and queue absorb normal flow, and a queue larger than both can be funded by de-levering a proportional slice of the position rather than waiting for a mode flip; an extended liquidity drought still lengthens the queue and widens unwind slippage.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| Regime-transition       | Mode switches cost 20–40 bps and can mistime fast funding flips; the 7-day mean and 12-hour minimum hold trade a little latency for far less whipsaw.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| Keeper outage           | Buffer withdrawals stay open; rotation and queue processing pause until cranking resumes. Anyone can crank.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |

### How big are these, in numbers

The risk tables above say what can go wrong; these say how much. They come from one stress run on the headline constants. The depeg and bad-month figures use the backtest window; the margin count uses two years of SOL prices, because 316 days is too few to count rare moves.

**A jitoSOL discount is the largest unhedged exposure.** The short covers SOL, not jitoSOL, so a discount lands directly on the $81.8 basis leg with nothing offsetting it. The depeg alone, before any cost of trading out:

| Discount | NAV impact |                                             |
| -------- | ---------- | ------------------------------------------- |
| 0.5%     | −0.41%     |                                             |
| 1.0%     | −0.82%     |                                             |
| 2.0%     | −1.64%     | nearly three months of net yield            |
| 5.0%     | −4.09%     | marking NAV auto-pauses, opening hard-fails |
| 10.0%    | −8.18%     |                                             |
| 20.0%    | −16.36%    |                                             |

The 5% guard measures against the Jito stake pool's redemption rate rather than against 1.0. That matters: jitoSOL appreciates against SOL as rewards accrue, so a guard anchored at 1.0 would drift out of reach and fire on nothing. Slashing sits underneath all of it and is unhedgeable: Jito runs no insurance fund and nobody reimburses it.

**No insurance fund.** There is no reserve standing in front of any of this, and that is a design choice rather than a gap. A reserve sized against market risk would have to be large: a 1% jitoSOL discount costs 0.82% of NAV, and no skim on a 20% performance fee gets near it. A reserve too small to cover an incident is machinery without a purpose.

**ksUSD defends no peg.** An insurance fund is what a pegged dollar needs, since a discount there is an existential failure. Here the share price absorbs the shock: NAV is marked at market, the price is designed to be able to fall, and a holder exiting into a bad unwind bears it rather than passing it to the holders who stayed.

What Keystone does stand behind is narrower: shortfalls the *protocol* caused rather than the market: a bad fill, an oracle mismark later corrected, an accounting gap. Holders did not sign up for those, and the operator makes them whole from its own fees by sending USDC to the vault, which the share price reflects at the next settle. That needs no instruction and holds no capital idle against an event that has not happened.

**How often the short's margin comes under pressure.** The short is the leg that liquidates, so the adverse direction is SOL *up*. Counting intraday highs against the previous close, over 730 days of SOL prices (2024-08-01 to 2026-07-31):

| Adverse move | Days | Share |                                                                    |
| ------------ | ---- | ----- | ------------------------------------------------------------------ |
| ≥ 3%         | 289  | 39.6% |                                                                    |
| ≥ 5%         | 139  | 19.0% | about half the entry margin; where a maintenance requirement bites |
| ≥ 9%         | 27   | 3.7%  | exhausts the entry margin outright                                 |
| ≥ 15%        | 4    | 0.5%  |                                                                    |

Entry margin is 9.1% of deployed capital, so a 5% move does not liquidate the position outright. It removes roughly half the cushion, and the margin top-up exists to replace it. The 5% row is not a liquidation count.

**A realistic bad month.** No modelled month closed negative; the weakest was February 2026 at +0.08%, with funding at −14% and no depeg. Add a depeg plus a \~50 bps round-trip reprice on the basis leg and the month comes to −1.64% at a 1% discount, −2.45% at 2% and −4.91% at 5%. A bad month is dominated by depeg rather than by funding.

### Failure modes

Funding compression parks Keystone. Perp-venue trouble triggers an oracle-divergence auto-pause and a permissionless emergency unwind. Margin falling below its floor opens de-levering to anyone, so it does not wait for the keeper. A depeg auto-pauses. Wind-down turns Keystone into a pro-rata USDC claim, and redemption works whether or not the team is present.

## IX. Position

Where this sits against the other yield-bearing dollars, by what actually produces the yield:

|                | Yield source                                                   | Behaviour when funding dies                                             | Transparency             | Venues                                           |
| -------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------- | ------------------------ | ------------------------------------------------ |
| **ksUSD**      | **Staking and funding**, plus lending                          | Parks at the lending floor                                              | Fully on-chain           | Phoenix, Kamino, Jito (Solana-native)            |
| Hylo (hyUSD)   | LST staking across the whole collateral pool, financed by xSOL | Unaffected by funding; tracks leveraged-SOL demand and rebalancing cost | On-chain                 | LST issuers + its own xSOL tranche and Earn Pool |
| Ethena (sUSDe) | Delta-hedged perp funding                                      | Yield follows funding down                                              | Off-chain CEX, attested  | CEXs + custodians                                |
| MakerDAO / Sky | Stability fees + RWA/savings                                   | Unaffected; tracks rates instead                                        | On-chain + off-chain RWA | RWA counterparties                               |
| Perena (USD\*) | Swap fees + stable yields                                      | Tracks volume instead                                                   | On-chain                 | Solana AMM/DEX                                   |

**Hylo (hyUSD) is the closest Solana-native design, and it out-yields this one today:** ≈9.7% against 7.19% net here. It overcollateralises hyUSD with a basket of LSTs and issues xSOL, a junior tranche that absorbs SOL's volatility so hyUSD can hold its peg, and its savings token earns on the whole pool because xSOL and unstaked holders forgo their share. Both designs are claims on the same engine: Solana staking pays both. Hylo levers it through its tranche; Keystone hedges it with a perp.

That rate is a participation ratio rather than a spread, so it converges downward as the product grows — toward the collateral ratio times the LST yield, which at Hylo's 150% target puts it at 9.5–10.5%. It has already made most of that move: 52.4% in Q1 2026, 9.7% the quarter after.

The difference that outlasts the rate gap is that **Keystone has a cash state and Hylo does not**. When the trade stops paying, this parks in USDC lending, while Hylo's V2 reaches neutrality by charging rebalance subsidies to its own savers in exactly the drawdowns they bought the token to sit out. Full teardown, including eHYUSD: [Hylo comparison](/how-it-works/whitepaper/hylo).

Ethena showed there is real demand for a yield-bearing dollar, and showed what happens when the one source of that yield compresses. The answer here is a different engine, Solana staking, and a cash state to fall back on when funding turns.

The longer goal is dollar yield that comes from the market it lives on, and can be checked against it.

*Simulated performance does not predict future results.*

¹ *Ethena figures are directional, from public dashboards over 2025–2026.*

***

[app.keystonefi.xyz](https://app.keystonefi.xyz) · [docs.keystonefi.xyz](https://docs.keystonefi.xyz) · *Simulated figures only. Not investment advice.*

***

## Related

* [Strategy & Modes](/how-it-works/strategy-and-modes) — the two modes, the funding threshold, and the switch
* [What can go wrong](/start-here/volatility-risk-management) — drawdown guard, slippage bounds, depeg and staleness guards
* [Historical Simulation](/how-it-works/strategy-and-modes/historical-simulation) — the backtest behind the headline numbers
* [Fees](/start-here/fees) — HWM math and the hurdle ratchet
* [NAV & Share Pricing](/how-it-works/strategy-and-modes/nav-calculation) — how a share is priced
* [Security Model](/reference/security) — oracle, authority, and permissionless paths


# Hylo comparison

Hylo is the closest Solana-native design to ksUSD, and the most useful one to reason against: it makes a claim on the same engine, Solana staking yield, and reaches a dollar by a different route. This page is the long form. The [whitepaper](/how-it-works/whitepaper#ix-position) carries the two-paragraph version.

## The design

Hylo overcollateralises hyUSD with a basket of LSTs and issues **xSOL**, a junior tranche that absorbs SOL's volatility so hyUSD can hold its peg. Its savings token then earns on the whole collateral pool, because xSOL holders and unstaked hyUSD holders forgo their share.

That is the structural difference in one line: **Hylo levers staking yield through an internal tranche; ksUSD hedges it with an external perp.** Both are claims on the same underlying return. The lasting difference is the leverage multiple and where the risk is parked, not the source.

## The rate is a participation ratio, not a spread

Hylo's savings rate is roughly the LST yield times pool value over staked supply. That has a specific consequence: **it is highest when fewest holders are staked, and it converges downward as the product succeeds.** The convergence target is the collateral ratio times the LST yield.

Hylo targets a 150% collateral ratio inside a 135–165% band. At roughly 7% LST yields that puts convergence at **9.5–10.5%**.

| Quarter | Observed  | Reading                               |
| ------- | --------- | ------------------------------------- |
| Q1 2026 | **52.4%** | Not a durable yield — see below       |
| Q2 2026 | **9.7%**  | Inside the predicted convergence band |

The 52.4% was not a yield in any durable sense. The stability pool had converted savings backing into xSOL during the drawdown, so the print is **xSOL recovering off its lows** — a leveraged-SOL result wearing a savings-rate label. Protocol TVL fell from $52M to $22.8M over the same quarter.

The compression happened, and it happened the way the mechanism predicts. It out-yields ksUSD today at 9.7% against 7.19% net, and that gap is real; it is also a gap that narrows as Hylo grows, by construction.

## V2: eHYUSD, and where the risk moved

In July 2026 sHYUSD became **eHYUSD**, marketed as fully delta-neutral. The way it reaches neutrality is the whole argument.

There is no external hedge. Hylo's documentation describes no perpetual and no off-chain derivative position. Neutrality is reached by selling collateral into USDC when the ratio falls, and *"every rebalance settles its profit or subsidy against the Earn Pool by minting or burning hyUSD"* — so *"subsidized rebalances under stress draw it down, the cost of de-risking the system."*

That is the same risk in a new place. The old design left the saver exposed once the tranche thinned. The new one **charges the saver the cost of de-risking as it happens**, in exactly the drawdowns the savings token exists to sit out. The spread schedule is fixed rather than a function of live market data, so the subsidy is not repriced when a fast market makes de-risking expensive.

## What the comparison comes down to

ksUSD moves the same risk to the perp market, and that market can halt in the same drawdown. The difference worth defending is narrower than a pitch would make it:

* A **hedge counterparty can be replaced.** An internal rebalance charged to your own principal cannot, because it *is* the design.
* ksUSD has a **cash state**: it parks in USDC lending when the trade stops paying. Hylo has no equivalent.
* Once Hylo's coverage falls past 100%, the tranche is gone and **hyUSD carries SOL's volatility directly**. The holder who bought a dollar is left holding the exposure they bought it to avoid. That is a different instrument, not a bad quarter.

ksUSD can be hurt too. The difference is that the damage lands on the share price, marked at market: it degrades, it does not turn into something the holder never bought.

## Related

* [Whitepaper §IX — Position](/how-it-works/whitepaper#ix-position)
* [Historical simulation](/how-it-works/strategy-and-modes/historical-simulation)


# Quick Start

Read the vault's state and call it from your own code.

The vault is a singleton, deployed and initialized by the Keystone admin. You don't stand one up yourself; you point a client at the existing program and read or transact against it.

***

## Prerequisites

Only Node.js 20+ is needed to build against the vault. The Rust and Anchor toolchain below is for compiling the program from source, which you only need if you're reviewing or modifying it.

| Tool       | Version                | Needed for                 |
| ---------- | ---------------------- | -------------------------- |
| Node.js    | 20+                    | Client integration         |
| Rust       | 1.79+ (rustup-managed) | Building the program       |
| Anchor CLI | 0.32.1+                | Building the program / IDL |
| Solana CLI | 1.18+                  | Building the program       |

```bash
git clone https://github.com/kamwithak/keystone-contracts.git
cd keystone-contracts
npm install
```

***

## Program ID

| Network | Program ID                                     |
| ------- | ---------------------------------------------- |
| Devnet  | `E7tpCcxtvuTXLAckBGWb1AsndpLQ1Y9hQA3iGYSXz2vJ` |
| Mainnet | *pending audit*                                |

* Single Anchor program: `keystone_finance`
* Implements the ksUSD vault end-to-end
* 26 instructions · 52 errors · 26 events · 2 account types

***

## Build

```bash
# Rust check (fast, no BPF toolchain required)
cargo check -p keystone-finance

# Generate / refresh IDL from source (uses idl-build feature)
PATH="$HOME/.cargo/bin:$PATH" anchor idl build \
  -o target/idl/keystone_finance.json
```

* IDL: `target/idl/keystone_finance.json`, regenerated from source
* TS types: `target/types/keystone_finance.ts`, derived from the IDL

***

## What you can call

Anyone can call these, and they're the whole surface most integrations need:

| Instruction                                           | Does                                               |
| ----------------------------------------------------- | -------------------------------------------------- |
| `deposit(usdc_amount)`                                | USDC in, ksUSD out at the current share price      |
| `withdraw_instant(shares)`                            | ksUSD in, USDC out of the liquidity buffer         |
| `request_withdrawal(shares)` + `process_withdrawal()` | Queued path for withdrawals larger than the buffer |

Position management (`open_position`, `close_position`, `attest_nav`, the lending cranks) is gated to the vault's authorized keeper. `settle`, `process_withdrawal`, and `emergency_close` need no permission at all. Full list in the [instructions reference](/build-on-it/quick-start/instructions).

***

## TypeScript client

```ts
import * as anchor from "@coral-xyz/anchor";
import { Program } from "@coral-xyz/anchor";
import { Connection, PublicKey } from "@solana/web3.js";
import idl from "../target/idl/keystone_finance.json" with { type: "json" };

const PROGRAM_ID = new PublicKey("E7tpCcxtvuTXLAckBGWb1AsndpLQ1Y9hQA3iGYSXz2vJ");
const connection = new Connection("https://api.devnet.solana.com", "confirmed");

const provider = new anchor.AnchorProvider(connection, wallet, { commitment: "confirmed" });
anchor.setProvider(provider);

const program = new Program(idl as any, provider);

const [vaultPda] = PublicKey.findProgramAddressSync(
  [Buffer.from("vault")],
  PROGRAM_ID
);

const vault = await program.account.vault.fetch(vaultPda);
```

***

## Related

* [Instructions reference](/build-on-it/quick-start/instructions) — every entry point
* [Account structure](/build-on-it/quick-start/accounts) — `Vault` and `WithdrawalRequest` layouts
* [Events](/build-on-it/quick-start/events) · [Errors](/build-on-it/quick-start/errors)
* [Deposit](/start-here/deposit) · [Withdraw](/start-here/withdraw) · [Check position & NAV](/start-here/check-position)


# Instructions Reference

The entry points exposed by the `keystone_finance` program (ksUSD vault). Grouped by caller role.

{% hint style="warning" %}
v1 hedges on Phoenix Perps (USDC margin via Ember, CPI through the Rise SDK).
{% endhint %}

> Source: [the program entrypoints](https://github.com/kamwithak/keystone-contracts/blob/main/programs/keystone-finance/src/lib.rs) · IDL: `target/idl/keystone_finance.json`

***

## One-time setup (admin)

| Instruction                     | Caller           | Description                                                                                                                                                                                                        |
| ------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `initialize(params)`            | Admin (deployer) | Creates the vault PDA at seeds `[b"vault"]` and the ksUSD share mint. Sets all risk parameters. Idempotent guard via PDA `init`.                                                                                   |
| `enable_phoenix(perp_asset_id)` | Admin            | One-time: pins the vault's Phoenix trader, market, global config, canonical mint and canonical ATA. `perp_asset_id` is the SOL-PERP id in the `PerpAssetMap` (0). Required before any perp position can be opened. |
| `enable_lending()`              | Admin            | One-time: pins the Kamino USDC reserve and the vault's cToken ATA. Required before any `lend_idle_usdc` call.                                                                                                      |
| `set_oracles()`                 | Admin            | Pins the Pyth SOL/USD and jitoSOL/USD accounts. Re-callable to rotate feeds.                                                                                                                                       |

### `InitializeParams` defaults

| Field                             | Default                    | Meaning                                                                                                                          |
| --------------------------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `liquidity_buffer_bps`            | 1\_000 (10%)               | Idle USDC kept on-vault for instant withdrawals                                                                                  |
| `instant_buffer_bps`              | 200 (2%)                   | Part of the buffer held raw for instant redemption; the rest is lent                                                             |
| `funding_threshold_normal_bps`    | 12 (+0.12%)                | On-chain floor, the basis-vs-parked break-even; the keeper applies the dynamic threshold above it                                |
| `perf_fee_bps`                    | 2\_000 (20%)               | Performance fee above HWM                                                                                                        |
| `min_dwell_seconds`               | 43\_200 (12 h)             | Minimum time between mode switches                                                                                               |
| `max_swap_slippage_bps`           | 50 (0.5%)                  | Jupiter swap slippage cap                                                                                                        |
| `emergency_close_dd_bps`          | 500 (5%)                   | NAV drawdown from peak that trips `emergency_close`                                                                              |
| `deposit_cap_usdc`                | 500\_000\_000\_000 ($500k) | Cached-NAV cap on new deposits. `u64::MAX` = uncapped, `0` = deposits paused                                                     |
| `min_request_shares`              | 1\_000\_000 (1 ksUSD)      | Minimum size for a queued withdrawal request                                                                                     |
| `max_pending_queue_usdc`          | `u64::MAX` (uncapped)      | Ceiling on total USDC owed to the withdrawal queue                                                                               |
| `max_nav_change_bps_per_hour`     | 1\_000 (10%/hr)            | Bound on a single `attest_nav` delta                                                                                             |
| `funding_max_staleness_seconds`   | 21\_600 (6 h)              | Opens revert if the funding signal is older than this                                                                            |
| `consecutive_dd_settles_required` | 2                          | Bad settles needed in a row before drawdown trips                                                                                |
| `authorized_keeper`               | `Pubkey::default()`        | Gates strategy instructions. The default matches no signer, so they stay blocked until a key is pinned; it must not be the admin |
| `lst_depeg_bps`                   | 500 (5%)                   | jitoSOL/SOL deviation that auto-pauses on `settle`                                                                               |
| `min_margin_bps`                  | 900 (9%)                   | Minimum margin as a share of deployed capital, which bounds leverage at \~10.1×                                                  |
| `hurdle_apr_bps`                  | 400 (4%)                   | Test and localnet fallback only; the deploy script measures the live Kamino rate and writes that                                 |

`phoenix_perp_asset_id`, the Phoenix accounts, the Kamino reserve, and the oracles are **not** set here. They're pinned separately by `enable_phoenix`, `enable_lending`, and `set_oracles`.

***

## User flow (anyone)

| Instruction                  | Description                                                                                                                                                |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `deposit(usdc_amount)`       | Transfer USDC to the vault, mint ksUSD at current share price. → [Deposit](/start-here/deposit)                                                            |
| `withdraw_instant(shares)`   | Burn ksUSD, receive USDC from the liquidity buffer. Reverts with `InsufficientLiquidityBuffer` if not enough idle USDC. → [Withdraw](/start-here/withdraw) |
| `request_withdrawal(shares)` | Burn ksUSD immediately, lock redemption price, create a queued `WithdrawalRequest` PDA.                                                                    |
| `process_withdrawal()`       | Permissionless crank — fulfill a queued request, close the PDA, refund rent to the original requester.                                                     |
| `claim_wind_down(shares)`    | Wind-down only. Burn ksUSD for a pro-rata share of the vault's idle USDC. Reverts unless `position_mode == WindDown`.                                      |

***

## Strategy (keeper-gated unless noted)

All strategy instructions take a 3- to 5-group `remaining_accounts` layout. The keeper builds these off-chain (with the Rise SDK and the Jupiter quote API) and passes the per-group counts as u8 arguments so the handler can split safely.

### `open_position`

```
open_position(usdc_amount, margin_usdc, perp_short_base_lots, min_base_lots_to_fill,
              min_quote_lots_to_fill, min_jitosol_out, jupiter_swap_data,
              jupiter_account_count, arena_account_count)
```

**Normal basis open.** Requires `Idle`. Splits the USDC and builds both legs in one transaction:

1. Buy jitoSOL via Jupiter: the unlevered spot leg.
2. Post `margin_usdc` on Phoenix, via Ember.
3. Short SOL-PERP delta-neutral against the spot leg.

`margin_usdc` must be at least `min_margin_bps` of `usdc_amount`, which is what bounds leverage.

### `close_position`

```
close_position(arena_account_count, min_base_lots_to_fill, min_quote_lots_to_fill,
               min_usdc_out, jupiter_swap_data)
```

**Normal basis close.** Reduce-only long order → settle funding → withdraw USDC margin → sell jitoSOL→USDC.

### `settle`

```
settle(funding_apr_bps_now)
```

Refresh NAV and peak share price, settle funding if a position is open, log drawdown if the guard tripped.

Permissionless, but the `funding_apr_bps_now` EMA update only applies when the **authorized keeper** signs, so a stranger can keep NAV fresh without steering the regime signal.

### `emergency_close`

```
emergency_close(arena_account_count, min_base_lots_to_fill, min_quote_lots_to_fill,
                jupiter_swap_data)
```

* Force closes on a drawdown breach, or while the vault is paused.
* Auto-pauses the vault on exit.
* Permissionless once tripped.

### `attest_nav`

```
attest_nav(new_nav_usdc)
```

Refresh `cached_nav_usdc` to include unrealized perp PnL. The delta is bounded by `max_nav_change_bps_per_hour`; over that it reverts with `NavChangeExceedsCap`. Calls `accrue_perf_fees`.

### `lend_idle_usdc` / `unlend_usdc`

```
lend_idle_usdc(usdc_amount)
unlend_usdc(collateral_amount)
```

Move idle USDC into and out of the Kamino USDC reserve. Lending reverts with `LendingBreachesBuffer` if it would eat the liquidity buffer.

### `add_margin`

```
add_margin(usdc_amount, arena_account_count)
```

Move USDC margin **to** the Phoenix trader without touching the position. This is the defence against segregated-collateral liquidation (see below). Respects the liquidity buffer and a ceiling of `effective_nav / 2`.

There is no counterpart: margin returns only via `close_position`, which withdraws it in full.

### `rebalance_hedge`

```
rebalance_hedge(arena_account_count, min_base_lots_to_fill, min_quote_lots_to_fill)
```

**Delta correction: moves the short only.** Resizes the short to match the jitoSOL leg in SOL terms. It takes no size argument: the program reads the spot balance and the jitoSOL/SOL rate and computes the target itself.

* Reverts with `DeltaWithinBand` unless `|delta| / NAV` clears `delta_band_bps`.
* Under-hedged sells more (not reduce-only); over-hedged buys back (reduce-only, so an overstated size cannot flip the book long).
* Increases are capped by `max_position_base_lots` on the resulting **total**, not the increment.
* They are clamped again to what posted collateral supports at `min_margin_bps`: clamped rather than rejected, with `collateral_capped` set on the event.

### `reduce_position`

```
reduce_position(lots, arena_account_count, min_base_lots_to_fill, min_quote_lots_to_fill,
                min_usdc_out, jupiter_swap_data, destination)
```

**De-lever: moves both legs.** Buys back `lots` of the short and sells the matching slice of jitoSOL, so net exposure is unchanged while the position gets smaller.

`destination` picks where the proceeds go:

* `Buffer`: proceeds and proportional margin land in the vault USDC ATA, funding the withdrawal queue.
* `Margin`: margin stays on the venue and spot proceeds are posted on top; notional falls while collateral rises.

Keeper-gated normally, and **permissionless** below `hard_margin_floor_bps`. A permissionless caller is bounded three ways:

* It may only route to `Margin`: defend, never drain.
* It may only close the slice that restores health to `min_margin_bps`, not the whole book.
* It must supply a real Jupiter route, because a `lots` with no route would shrink the short while the whole spot leg stayed, leaving the vault net long.

The pause check is deliberately skipped on this path: a pause must not disable the margin defence. A full de-lever returns the vault to `Idle` and restarts the dwell clock.

## Admin

| Instruction                 | Description                                                                                                                                                                   |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `set_pause(paused)`         | Halt new deposits + new positions. Withdrawals from the liquidity buffer remain open.                                                                                         |
| `update_params(args)`       | Adjust risk parameters within bounds. Cannot move admin or mints.                                                                                                             |
| `transfer_admin(new_admin)` | Step 1 of the handover: records `pending_admin`. Does not change the admin.                                                                                                   |
| `accept_admin()`            | Step 2: the pending admin signs to take over. Completes the handover.                                                                                                         |
| `collect_fees()`            | Pay out `pending_perf_fees_usdc` **in USDC** to the admin. No shares are minted, and the share price doesn't move. Requires Parked and not paused. → [Fees](/start-here/fees) |
| `reset_peak()`              | Re-anchor `peak_share_price_1e9` for the drawdown guard. Does not touch the HWM.                                                                                              |
| `init_wind_down()`          | Terminal. Blocks deposits and new positions; holders redeem via `claim_wind_down`.                                                                                            |

***

## Account-context groups for `remaining_accounts`

Strategy instructions pack multiple downstream CPIs into one transaction. Each group's account list is documented in the handler source. The Phoenix + Ember groups are assembled via the Rise SDK.

| Instruction       | Groups                                                                                   |
| ----------------- | ---------------------------------------------------------------------------------------- |
| `open_position`   | Jupiter swap → Ember margin deposit → Phoenix place\_perp\_order                         |
| `add_margin`      | Ember margin deposit only — arena slices only, no Jupiter group                          |
| `rebalance_hedge` | Phoenix place\_perp\_order only — arena slices only, no Jupiter group                    |
| `reduce_position` | place\_perp\_order (reduce-only) → Ember margin move → Jupiter swap                      |
| `close_position`  | place\_perp\_order (reduce-only) → settle funding → Ember margin withdraw → Jupiter swap |
| `settle`          | Phoenix funding / margin re-eval accounts (when position open)                           |
| `emergency_close` | place\_perp\_order → Ember margin withdraw → Jupiter swap                                |

See [Keeper bot](/run-it/keeper-bot) for the off-chain account-assembly conventions.

***

## Errors

See [Errors](/build-on-it/quick-start/errors) for the full `KsusdError` enum and exit codes.

***

## Why margin is its own instruction

The book is delta-neutral, but the two legs live in different places: the jitoSOL spot leg sits in the vault, the margin sits on Phoenix. **Phoenix can only see its own side.** On a rally the short's loss eats margin while the exactly offsetting jitoSOL gain sits somewhere Phoenix cannot count, so an economically hedged position gets liquidated, turning a paper wash into a realised loss.

`emergency_close` does not cover this. It triggers on NAV drawdown, and NAV doesn't fall in a hedged rally. The vault reads healthy right up to liquidation.

**These multiples describe the perp leg only, not the vault.** The vault is not levered: total exposure equals NAV, and the short is sized 1:1 against the jitoSOL. The multiple is what the position looks like *from Phoenix's side*, where only `min_margin_bps` of the deployed capital is visible as collateral. It is the right unit for reasoning about liquidation distance and the wrong one for describing the product.

Measured over 730 days of SOL prices, 2024-08-01 to 2026-07-31 (intraday high against the previous close, which is what pressures a short). The trigger column assumes a maintenance requirement at half the entry margin, with no top-up:

| Leverage                         | Maintenance bites at | Days breached | Frequency    |
| -------------------------------- | -------------------- | ------------- | ------------ |
| 3x                               | 16.7%                | 2 / 730       | \~1x/yr      |
| 5x                               | 10.0%                | 20 / 730      | \~10x/yr     |
| **10x (`min_margin_bps = 900`)** | **5.0%**             | **139 / 730** | **\~70x/yr** |

At that frequency a static buffer is not a defence. 10x is acceptable only because the keeper actively tops margin up: `add_margin` is what makes it so, and the `margin-health` keeper duty is what calls it. These are not liquidation counts for the defended position. Without active defence the position would have to run nearer 3x, which puts a third of deployed capital in margin earning nothing.


# Account Structure

The ksUSD vault uses two on-chain account types: a single `Vault` PDA and one `WithdrawalRequest` PDA per queued withdrawal.

{% hint style="warning" %}
v1 hedges on **Phoenix Perps** (Ellipsis Labs) with USDC margin via the **Ember** program; jitoSOL is held unlevered as the spot leg. The perp-venue account set below follows the Rise SDK (TraderHeader, PermissionAccount, GlobalConfig, PerpAssetMap).
{% endhint %}

> Source: [the vault account definition](https://github.com/kamwithak/keystone-contracts/blob/main/programs/keystone-finance/src/state/vault.rs)
>
> Anchor client name: `program.account.vault.fetch(vaultPda)` and `program.account.withdrawalRequest.fetch(requestPda)`.

***

## `Vault` (singleton)

PDA seed: `[b"vault"]` · authority for ksUSD mint, vault USDC ATA, vault jitoSOL ATA, Phoenix trader account, and the lend cToken ATA.

### Identity

| Field           | Type     | Meaning                                                                       |
| --------------- | -------- | ----------------------------------------------------------------------------- |
| `admin`         | `Pubkey` | Admin authority (transferable via two-step `transfer_admin` + `accept_admin`) |
| `pending_admin` | `Pubkey` | Pending admin during a transfer; `Pubkey::default()` = none pending           |
| `bump`          | `u8`     | Vault PDA bump                                                                |
| `usdc_mint`     | `Pubkey` | USDC mint (depositor token)                                                   |
| `jitosol_mint`  | `Pubkey` | jitoSOL mint (LST spot leg, held unlevered for staking)                       |
| `ksusd_mint`    | `Pubkey` | ksUSD share mint; vault PDA is mint + freeze authority                        |

### Phoenix integration

| Field                    | Type     | Meaning                                                                                                                                         |
| ------------------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `phoenix_trader`         | `Pubkey` | The vault's Phoenix cross-margin trader PDA (authority = vault). Registered and capability-enabled off-chain via the Rise SDK, then pinned here |
| `phoenix_market`         | `Pubkey` | SOL-PERP orderbook (market) account                                                                                                             |
| `phoenix_global_config`  | `Pubkey` | Phoenix GlobalConfig — constrained on every Phoenix CPI                                                                                         |
| `canonical_mint`         | `Pubkey` | Ember canonical collateral mint. USDC wraps into this 1:1 to become Phoenix margin                                                              |
| `phoenix_canonical_ata`  | `Pubkey` | The vault's canonical-token ATA, i.e. its Phoenix margin token account                                                                          |
| `phoenix_perp_asset_id`  | `u64`    | SOL-PERP asset id in the `PerpAssetMap` (0), used to read the signed position                                                                   |
| `phoenix_initialized`    | `bool`   | `true` after `enable_phoenix` succeeds                                                                                                          |
| `phoenix_perp_asset_map` | `Pubkey` | Phoenix's perp asset map for `phoenix_market`, pinned at `enable_phoenix`. Every order instruction address-checks it                            |
| `perp_base_lot_lamports` | `u64`    | Size of one Phoenix base lot in lamports (SOL-PERP = 0.01 SOL = `10_000_000`). Converts lots ↔ SOL for hedge sizing and the fill-price bound    |
| `client_order_seq`       | `u64`    | Monotonic `client_order_id` for venue orders, unique by construction rather than derived from the clock                                         |

Trading capability itself is **not** a vault field. It lives on the Phoenix trader account as capability flags, granted by Ellipsis's `risk_authority`. A freshly registered trader can hold funds but can't post margin until that grant lands.

### Lending venues

| Field                        | Type     | Meaning                                                 |
| ---------------------------- | -------- | ------------------------------------------------------- |
| `kamino_lend_reserve`        | `Pubkey` | Pinned Kamino USDC reserve (set by `enable_lending`)    |
| `vault_lend_collateral_ata`  | `Pubkey` | Vault's cToken ATA for Kamino lending                   |
| `kamino_lending_initialized` | `bool`   | `true` after `enable_lending` succeeds                  |
| `usdc_lent_kamino`           | `u64`    | USDC base units deposited at Kamino from vault main ATA |

### Oracles (set by `set_oracles`)

| Field                 | Type     | Meaning                                                                                     |
| --------------------- | -------- | ------------------------------------------------------------------------------------------- |
| `sol_oracle`          | `Pubkey` | Pyth SOL/USD pull-oracle account                                                            |
| `jitosol_oracle`      | `Pubkey` | Pyth jitoSOL/USD pull-oracle account                                                        |
| `oracles_initialized` | `bool`   | `true` after `set_oracles` succeeds                                                         |
| `jito_stake_pool`     | `Pubkey` | Jito stake pool: source of the jitoSOL/SOL redemption rate the depeg guard measures against |

### NAV & share accounting (USDC base units, 6 decimals)

| Field                | Type  | Meaning                                                      |
| -------------------- | ----- | ------------------------------------------------------------ |
| `total_shares`       | `u64` | Total ksUSD outstanding (6 decimals)                         |
| `cached_nav_usdc`    | `u64` | Last computed NAV in USDC base units                         |
| `last_settle_ts`     | `i64` | Last `settle` crank timestamp                                |
| `last_nav_attest_ts` | `i64` | Last `attest_nav` timestamp; anchors the per-hour change cap |

### Performance fee

| Field                    | Type  | Meaning                                                                                                                                                                                                                                                                                                                            |
| ------------------------ | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `hwm_share_price_1e9`    | `u64` | High-water mark, measured against the **gross** share price (1e9 scale). Advances on its own at `hurdle_apr_bps`/yr, and falls only by the per-share amount `collect_fees` pays out. See [Fees](/start-here/fees)                                                                                                                  |
| `hurdle_apr_bps`         | `u16` | Benchmark the vault must beat before any performance fee applies. Not a fixed constant: `init-v1.ts` measures the live Kamino USDC supply APY at deploy and writes it (451 from the 4.51% seven-day median measured 13 Oct 2026), and the keeper's `watchdog` warns when it drifts from the smoothed rate. `0` disables the hurdle |
| `last_fee_accrual_ts`    | `i64` | When `accrue_perf_fees` last ran. Drives the hurdle ratchet; `0` means "never initialised" and suppresses it                                                                                                                                                                                                                       |
| `peak_share_price_1e9`   | `u64` | Rolling peak share price (drawdown anchor). Reset only by `reset_peak`, never by fee collection                                                                                                                                                                                                                                    |
| `pending_perf_fees_usdc` | `u64` | Performance fees accrued but not yet collected. Crystallized by `accrue_perf_fees` on every price change, and **subtracted from `effective_nav_usdc`** so the share price is net of fees owed. Zeroed by `collect_fees`                                                                                                            |

### Position state

| Field                  | Type           | Meaning                                                                                                   |
| ---------------------- | -------------- | --------------------------------------------------------------------------------------------------------- |
| `position_mode`        | `PositionMode` | `Idle` / `Normal` / `WindDown`                                                                            |
| `position_base_amount` | `i64`          | Signed Phoenix position in **base lots** (negative = short SOL-PERP). SOL-PERP uses `baseLotDecimals = 2` |
| `usdc_margin_posted`   | `u64`          | USDC base units currently posted as Phoenix margin via Ember                                              |
| `last_mode_change_ts`  | `i64`          | Anchors the `min_dwell_seconds` guard                                                                     |
| `last_rebalance_ts`    | `i64`          | When `rebalance_hedge` last corrected delta                                                               |

### Withdrawal queue cursors

| Field                     | Type  | Meaning                                                     |
| ------------------------- | ----- | ----------------------------------------------------------- |
| `queue_next_id`           | `u64` | Next request\_id to assign                                  |
| `queue_processed_through` | `u64` | Smallest request\_id not yet processed (strict FIFO cursor) |
| `queue_pending_usdc`      | `u64` | Total USDC owed across pending requests                     |

### Configurable parameters

| Field                             | Type  | Default                                                                                                                                                          |
| --------------------------------- | ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `liquidity_buffer_bps`            | `u16` | 1\_000 (10%)                                                                                                                                                     |
| `funding_threshold_normal_bps`    | `i32` | 12 (+0.12%, the break-even; the keeper applies the dynamic threshold above it)                                                                                   |
| `perf_fee_bps`                    | `u16` | 2\_000                                                                                                                                                           |
| `hurdle_apr_bps`                  | `u16` | measured live at init (Kamino USDC supply APY). `400` in `InitializeParams::default()` is a tests/localnet fallback only; mainnet init aborts rather than use it |
| `min_margin_bps`                  | `u16` | 900 (bounds leverage at \~10x)                                                                                                                                   |
| `min_dwell_seconds`               | `u32` | 43\_200 (12 h)                                                                                                                                                   |
| `max_swap_slippage_bps`           | `u16` | 50                                                                                                                                                               |
| `emergency_close_dd_bps`          | `u16` | 500                                                                                                                                                              |
| `deposit_cap_usdc`                | `u64` | 500\_000\_000\_000 ($500k launch cap). `u64::MAX` = uncapped; `0` = paused.                                                                                      |
| `min_request_shares`              | `u64` | 1\_000\_000 (1 ksUSD)                                                                                                                                            |
| `max_pending_queue_usdc`          | `u64` | `u64::MAX` (disabled)                                                                                                                                            |
| `max_nav_change_bps_per_hour`     | `u16` | 1\_000 (±10%/hr on keeper attestations; deposits/withdrawals write `cached_nav_usdc` directly and are not capped by it)                                          |
| `funding_max_staleness_seconds`   | `u32` | 21\_600 (6 h)                                                                                                                                                    |
| `consecutive_dd_settles_required` | `u8`  | 2                                                                                                                                                                |
| `consecutive_dd_settles_observed` | `u8`  | Running counter                                                                                                                                                  |
| `lst_depeg_bps`                   | `u16` | 500 (5%)                                                                                                                                                         |
| `max_position_base_lots`          | `u64` | Absolute ceiling on position size, in base lots. Breach reverts with `PerpShortExceedsSizeCap`                                                                   |
| `instant_buffer_bps`              | `u16` | 200 (2%). Raw-USDC floor reserved for `withdraw_instant`, as bps of NAV                                                                                          |
| `delta_band_bps`                  | `u16` | Delta drift, as bps of NAV, that must accumulate before `rebalance_hedge` will act. `0` disables rebalancing                                                     |
| `max_rebalance_clip_lots`         | `u64` | Per-call ceiling on a rebalance order, in base lots. `0` = unclipped. Bounds market impact, not price                                                            |
| `hard_margin_floor_bps`           | `u16` | Margin health below which **anyone** may call `reduce_position` to `Margin`. `0` leaves the margin defence entirely dependent on the keeper being alive          |
| `mint_window_seconds`             | `u64` | Length of the deposit rate-limit window. `0` disables the flow cap                                                                                               |
| `mint_limit_per_window_usdc`      | `u64` | USDC that may be minted within one window. A flow cap, distinct from the `deposit_cap_usdc` stock cap                                                            |
| `mint_window_start_ts`            | `i64` | Start of the current mint window                                                                                                                                 |
| `minted_in_window_usdc`           | `u64` | USDC minted so far in the current window                                                                                                                         |

### Risk flags & keeper allowlist

| Field               | Type     | Meaning                                                                                                                                                                                                                                                                     |
| ------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `paused`            | `bool`   | Halts deposits + new positions; instant withdraw stays open                                                                                                                                                                                                                 |
| `authorized_keeper` | `Pubkey` | Gates the funding-signal update in `settle`, strategy opens and closes, and the lending cranks. **Exact match required**: `Pubkey::default()` (the post-init state) blocks every keeper-gated instruction until the admin runs `update_params { authorized_keeper: <key> }` |

### Smoothed funding signal

| Field                      | Type  | Meaning                                                                |
| -------------------------- | ----- | ---------------------------------------------------------------------- |
| `funding_apr_smoothed_bps` | `i32` | EMA of SOL-PERP funding, updated on every `settle`                     |
| `funding_smooth_last_ts`   | `i64` | Last EMA update timestamp. `0` sentinel = first settle hasn't run yet. |

***

## `PositionMode` (enum)

| Variant    | Value | Meaning                                                                                                                                                   |
| ---------- | ----- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Idle`     | 0     | **Parked** (v1 name). No active perp position; capital in vault USDC (lent on Kamino).                                                                    |
| `Normal`   | 1     | Long jitoSOL spot (unlevered) + short SOL-PERP on Phoenix at 1× notional, USDC margin.                                                                    |
| `WindDown` | 3     | Terminal. New positions / deposits blocked; users claim pro-rata via `claim_wind_down`. (Value 2 belonged to the removed reverse mode and is not reused.) |

***

## `WithdrawalRequest`

PDA seed: `[b"withdrawal_request", vault.key(), request_id_le_bytes]` · created by `request_withdrawal`, closed by `process_withdrawal` (rent refunded to the original requester).

| Field               | Type     | Meaning                                                         |
| ------------------- | -------- | --------------------------------------------------------------- |
| `vault`             | `Pubkey` | Vault this request belongs to                                   |
| `user`              | `Pubkey` | Original requester (rent refund recipient)                      |
| `user_usdc_account` | `Pubkey` | USDC destination; must match at process time                    |
| `usdc_owed`         | `u64`    | Upper bound USDC owed at burn time (FIFO at request)            |
| `shares_burned`     | `u64`    | Shares burned at request, used for the price-at-process haircut |
| `request_id`        | `u64`    | Sequential ID assigned at enqueue                               |
| `requested_ts`      | `i64`    | Timestamp of request                                            |
| `bump`              | `u8`     | PDA bump                                                        |

`process_withdrawal` price-at-process haircut:

* Re-prices `usdc_owed` against the current share price
* Takes the **lower** of locked vs. live
* Depositors can never extract more than their pro-rata share if NAV has fallen since they queued

***

## Derivation helpers (TypeScript)

```ts
const [vaultPda] = PublicKey.findProgramAddressSync(
  [Buffer.from("vault")],
  PROGRAM_ID
);

const [requestPda] = PublicKey.findProgramAddressSync(
  [
    Buffer.from("withdrawal_request"),
    vaultPda.toBuffer(),
    new BN(requestId).toArrayLike(Buffer, "le", 8),
  ],
  PROGRAM_ID
);

// Vault ATAs (PDA-owned)
const vaultUsdcAta    = getAssociatedTokenAddressSync(vault.usdcMint,    vaultPda, true);
const vaultJitosolAta = getAssociatedTokenAddressSync(vault.jitosolMint, vaultPda, true);
const lendCollateral  = vault.vaultLendCollateralAta; // pinned at enable_lending
```

***

## Related

* [Instructions](/build-on-it/quick-start/instructions) · [Events](/build-on-it/quick-start/events) · [Errors](/build-on-it/quick-start/errors)
* [Quick start](/build-on-it/quick-start) — getting a Program instance set up


# Events Reference

The ksUSD vault emits an event for nearly every state-changing instruction. Subscribe via `program.addEventListener("EventName", cb)` or parse logs from confirmed transactions.

> Sources: `programs/keystone-finance/src/instructions/*.rs` (search for `#[event]`).

| Event                   | Emitted by           | Notable fields                                                                                                                                                                                                                                                                                                      |
| ----------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `DepositEvent`          | `deposit`            | `user`, `usdc_amount`, `shares_minted`, `share_price_1e9`, `new_total_shares`, `timestamp`                                                                                                                                                                                                                          |
| `WithdrawEvent`         | `withdraw_instant`   | `user`, `shares_burned`, `usdc_paid`, `share_price_1e9`, `new_total_shares`, `timestamp`                                                                                                                                                                                                                            |
| `WithdrawalRequested`   | `request_withdrawal` | `user`, `request_id`, `shares_burned`, `usdc_owed`, `timestamp`                                                                                                                                                                                                                                                     |
| `WithdrawalProcessed`   | `process_withdrawal` | `user`, `request_id`, `usdc_paid`, `cranker`, `timestamp`                                                                                                                                                                                                                                                           |
| `MarginAdded`           | `add_margin`         | amount, new posted total, the health ratio that triggered it                                                                                                                                                                                                                                                        |
| `PositionOpened`        | `open_position`      | `mode` (`Normal`), `usdc_in`, `jitosol_purchased`, `perp_base_amount`, `timestamp`                                                                                                                                                                                                                                  |
| `PositionClosed`        | `close_position`     | `usdc_out`, `realized_pnl_signed`, `timestamp`                                                                                                                                                                                                                                                                      |
| `PositionReduced`       | `reduce_position`    | `requested_lots`, `closed_lots`, `before_base_lots`, `after_base_lots`, `jitosol_sold`, `usdc_from_spot`, `margin_withdrawn`, `margin_added`, `health_bps_before`, `permissionless`, `timestamp` — `permissionless` records whether a stranger cranked the de-lever or the keeper did                               |
| `DeltaObserved`         | `rebalance_hedge`    | `target_base_lots`, `current_base_lots`, `delta_bps`, `band_bps`, `breaches_band`, `perp_equity_usdc`, `timestamp` — emitted even when the band is not breached, so drift is observable between corrections                                                                                                         |
| `DeltaRebalanced`       | `rebalance_hedge`    | `target_base_lots`, `before_base_lots`, `after_base_lots`, `filled_lots`, `clipped`, `collateral_capped`, `observed_delta_bps`, `residual_lots`, `timestamp` — `residual_lots` is the correction still outstanding; a non-zero value with `collateral_capped` means margin, not the clip, is the binding constraint |
| `NavAttesterStalled`    | `settle`             | `last_nav_attest_ts`, `stalled_seconds`, `timestamp` — emitted when `settle` auto-pauses after NAV attestation has been dead for 2h, re-opening the permissionless `emergency_close` route                                                                                                                          |
| `OraclesSet`            | `set_oracles`        | `sol_oracle`, `jitosol_oracle`, `timestamp`                                                                                                                                                                                                                                                                         |
| `PhoenixEnabled`        | `enable_phoenix`     | `trader`, `market`, `canonical_ata`, `timestamp`                                                                                                                                                                                                                                                                    |
| `LendingEnabled`        | `enable_lending`     | `kamino_lend_reserve`, `vault_lend_collateral_ata`, `timestamp`                                                                                                                                                                                                                                                     |
| `IdleLent`              | `lend_idle_usdc`     | `usdc_amount`, `new_usdc_lent_kamino`, `timestamp`                                                                                                                                                                                                                                                                  |
| `IdleUnlent`            | `unlend_usdc`        | `collateral_amount`, `usdc_received`, `new_usdc_lent_kamino`, `timestamp`                                                                                                                                                                                                                                           |
| `NavAttested`           | `attest_nav`         | `old_nav_usdc`, `new_nav_usdc`, `change_bps`, `last_nav_attest_ts`, `timestamp`                                                                                                                                                                                                                                     |
| `WindDownInitiated`     | `init_wind_down`     | `cached_nav_usdc`, `total_shares`, `timestamp`                                                                                                                                                                                                                                                                      |
| `WindDownClaimed`       | `claim_wind_down`    | `user`, `shares_burned`, `usdc_paid`, `timestamp`                                                                                                                                                                                                                                                                   |
| `PauseToggled`          | `set_pause`          | `paused`, `timestamp`                                                                                                                                                                                                                                                                                               |
| `PeakReset`             | `reset_peak`         | `new_peak_share_price_1e9`, `timestamp`                                                                                                                                                                                                                                                                             |
| `FeesCollected`         | `collect_fees`       | `perf_fee_usdc`, `new_hwm_share_price_1e9`, `timestamp`                                                                                                                                                                                                                                                             |
| `DepegAutoPaused`       | `settle`             | `timestamp` — emitted when a jitoSOL depeg auto-pauses the vault                                                                                                                                                                                                                                                    |
| `ParamsUpdated`         | `update_params`      | every configurable parameter plus `authorized_keeper`, `max_position_base_lots`, `timestamp`                                                                                                                                                                                                                        |
| `AdminTransferProposed` | `transfer_admin`     | `current_admin`, `pending_admin`, `timestamp`                                                                                                                                                                                                                                                                       |
| `AdminTransferred`      | `accept_admin`       | `previous_admin`, `new_admin`, `timestamp`                                                                                                                                                                                                                                                                          |

> `emergency_close`, and `settle` apart from the two events above, log via `msg!` rather than `#[event]`; subscribe to program logs if you need them programmatically.

***

## Subscribing in TypeScript

```ts
const listener = program.addEventListener("DepositEvent", (event, _slot, _sig) => {
  console.log("deposit", {
    user: event.user.toBase58(),
    usdc: Number(event.usdcAmount.toString()) / 1e6,
    shares: Number(event.sharesMinted.toString()) / 1e6,
    price: Number(event.sharePrice1e9.toString()) / 1e9,
  });
});

// later
await program.removeEventListener(listener);
```

For historical events, parse transaction logs with `EventParser`:

```ts
import { EventParser } from "@coral-xyz/anchor";

const parser = new EventParser(program.programId, program.coder);
for (const event of parser.parseLogs(tx.meta.logMessages)) {
  console.log(event.name, event.data);
}
```

***

## Related

* [Instructions](/build-on-it/quick-start/instructions) · [Account structure](/build-on-it/quick-start/accounts) · [Errors](/build-on-it/quick-start/errors)


# Error Codes

The `KsusdError` enum lists every program-level error the ksUSD vault can return. Each maps to an Anchor exit code (starting at `0x1770`; the IDL has the exact codes).

> Source: [the error definitions](https://github.com/kamwithak/keystone-contracts/blob/main/programs/keystone-finance/src/errors.rs)

***

## General

| Variant                | Meaning                                   | Common cause                                                                                                 |
| ---------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `Unauthorized`         | Admin / keeper signature required         | A non-admin called a privileged instruction, or a non-keeper called strategy when `authorized_keeper` is set |
| `Paused`               | Vault is paused                           | Admin paused; only `withdraw_instant` and `claim_wind_down` still work                                       |
| `MathOverflow`         | Math overflow                             | Bad input or share-price edge case                                                                           |
| `InvalidParams`        | Invalid configuration                     | Param outside allowed range (e.g. `perf_fee_bps > 5000`) or remaining-accounts split overflow                |
| `KeeperMustNotBeAdmin` | `authorized_keeper` must not be the admin | The keeper key runs hot on a crank box; the admin key must not                                               |

## Deposit / withdraw

| Variant                       | Meaning                                                                                                                    |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `ZeroDeposit`                 | `usdc_amount == 0`                                                                                                         |
| `DepositCapExceeded`          | New deposit would push `cached_nav_usdc` past `deposit_cap_usdc`                                                           |
| `InsufficientShares`          | User's ksUSD ATA holds less than requested                                                                                 |
| `InsufficientLiquidityBuffer` | Vault doesn't have enough idle USDC for instant withdrawal; use `request_withdrawal` instead                               |
| `SlippageExceeded`            | Realized swap slippage exceeds `max_swap_slippage_bps`                                                                     |
| `MintRateLimited`             | Deposit exceeds the mint rate limit for the current window (`mint_window_*`). A flow cap, distinct from `deposit_cap_usdc` |

## Position state

| Variant                   | Meaning                                                                                                                                                                                   |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PositionAlreadyOpen`     | Calling `open_position` while a position is already open                                                                                                                                  |
| `MarginBelowMinimum`      | `margin_usdc` is under `min_margin_bps` of the amount deployed, i.e. the requested leverage exceeds the on-chain bound                                                                    |
| `MarginExceedsCap`        | The resulting posted margin would exceed `effective_nav / 2`. Bounds how much of the vault a compromised keeper can move onto the venue                                                   |
| `PositionNotOpen`         | Calling `add_margin`, `close_position` or `emergency_close` with no active position                                                                                                       |
| `HedgeSizeMismatch`       | On `open_position`, the perp short does not match the jitoSOL spot leg at the redemption rate                                                                                             |
| `FundingThresholdNotMet`  | Keeper attempted to open a mode whose funding-rate threshold wasn't cleared                                                                                                               |
| `MinDwellNotElapsed`      | Less than `min_dwell_seconds` since last mode change                                                                                                                                      |
| `PerpFillIncomplete`      | The perp order filled for less than the requested size, so the hedge would not cover the spot leg. `open_position` reverts the whole transaction rather than record a half-hedge as whole |
| `DeltaWithinBand`         | Delta is inside `delta_band_bps`: there is nothing to correct, so `rebalance_hedge` declines rather than pay spread for noise                                                             |
| `RebalanceDisabled`       | `delta_band_bps` or `perp_base_lot_lamports` is unset (`0`), so rebalancing cannot run                                                                                                    |
| `RebalanceWrongDirection` | The correction would move the position the wrong way; a guard against acting on a position that is not the short the vault expects                                                        |
| `MarginAboveFloor`        | Margin health is at or above `hard_margin_floor_bps`, so the permissionless `reduce_position` path is closed. Only the keeper may de-lever a healthy position                             |

## External venues

| Variant                   | Meaning                                                                            |
| ------------------------- | ---------------------------------------------------------------------------------- |
| `PhoenixCpiFailed`        | The Phoenix CPI returned an error                                                  |
| `EmberCpiFailed`          | The Ember CPI returned an error: USDC↔canonical margin wrap/unwrap failed          |
| `KaminoCpiFailed`         | The Kamino KLend CPI returned an error                                             |
| `JupiterSwapFailed`       | The Jupiter V6 route CPI failed                                                    |
| `InvalidMint`             | Account constraint mismatched expected mint                                        |
| `PhoenixMarketNotActive`  | Phoenix SOL-PERP is halted, in settlement, or delisted (the venue circuit breaker) |
| `PerpShortExceedsSizeCap` | The short would exceed `max_position_base_lots`, the absolute size cap             |

## Oracle

| Variant                    | Meaning                                              |
| -------------------------- | ---------------------------------------------------- |
| `StaleOracle`              | Pyth price update older than the staleness threshold |
| `OracleConfidenceExceeded` | Pyth confidence interval > 2% of the price           |

## Risk

| Variant                 | Meaning                                                                                                             |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `EmergencyDrawdown`     | NAV dropped more than `emergency_close_dd_bps` from peak                                                            |
| `LstDepeg`              | jitoSOL price deviated beyond `lst_depeg_bps`; `settle` auto-pauses                                                 |
| `DrawdownTriggerLatent` | Drawdown trigger requires N consecutive settles below threshold (set by `consecutive_dd_settles_required`)          |
| `FundingSignalStale`    | Smoothed funding signal older than `funding_max_staleness_seconds`; run `settle` first                              |
| `FundingRateInsane`     | Funding rate sanity check failed (absurd value reported by the perp venue, most likely an oracle or venue incident) |

## Withdrawal queue

| Variant                      | Meaning                                                                               |
| ---------------------------- | ------------------------------------------------------------------------------------- |
| `WithdrawalAlreadyProcessed` | `process_withdrawal` called on a request that's already settled                       |
| `WithdrawalUserMismatch`     | Recorded `user_usdc_account` doesn't match the passed destination                     |
| `WithdrawalNotNextInQueue`   | Queued requests must be processed strictly in FIFO order — pass the next `request_id` |
| `BelowMinRequestShares`      | `request_withdrawal` shares below `min_request_shares`                                |
| `QueueCapExceeded`           | Queue would exceed `max_pending_queue_usdc`                                           |

## NAV attestation

| Variant                 | Meaning                                                               |
| ----------------------- | --------------------------------------------------------------------- |
| `NavChangeExceedsCap`   | `attest_nav` delta exceeds `max_nav_change_bps_per_hour`              |
| `NavStale`              | NAV stale; `settle` or `attest_nav` required before this operation    |
| `NavDisagreesWithVenue` | The attested NAV disagrees with the position the venue actually shows |

## Lending

| Variant                 | Meaning                                                           |
| ----------------------- | ----------------------------------------------------------------- |
| `LendingNotEnabled`     | `lend_idle_usdc` called without prior `enable_lending`            |
| `LendingBreachesBuffer` | Lending more would drop idle USDC below `liquidity_buffer_target` |

## Wind-down / admin transfer

| Variant                  | Meaning                                                                                                                                    |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `WindDownActive`         | Vault is in wind-down: new deposits, positions and un-pause are blocked                                                                    |
| `WindDownRequiresUnlent` | `init_wind_down` called while USDC is still lent on Kamino. `claim_wind_down` pays from the vault USDC ATA, and only the keeper can unlend |
| `NoPendingAdmin`         | `accept_admin` called when no pending admin is set                                                                                         |
| `NotPendingAdmin`        | `accept_admin` signer doesn't match `pending_admin`                                                                                        |

## Bootstrap

| Variant                 | Meaning                                                                            |
| ----------------------- | ---------------------------------------------------------------------------------- |
| `BootstrapResidualUsdc` | Vault USDC ATA must be empty before the first deposit (prevents dilution griefing) |

***

## Reading errors from a client

```ts
try {
  await program.methods.withdrawInstant(new BN(amount)).accountsStrict({...}).rpc();
} catch (e: any) {
  // AnchorError exposes .error.errorCode.code (string) and .error.errorMessage
  if (e.error?.errorCode?.code === "InsufficientLiquidityBuffer") {
    // fall back to request_withdrawal
  }
  throw e;
}
```

In raw transaction logs the error appears as e.g. `AnchorError caused by account: ... InsufficientLiquidityBuffer.` followed by the exit code.

***

## Related

* [Instructions](/build-on-it/quick-start/instructions) · [Account structure](/build-on-it/quick-start/accounts) · [Events](/build-on-it/quick-start/events)


# Protocol Integrations

The vault works with other Solana protocols by calling them directly from its own program, a pattern called CPI. Every one of those calls is signed by the vault itself, so no private key is involved.

{% hint style="warning" %}
v1 hedges on **Phoenix Perps** (Ellipsis Labs) via on-chain CPI, with USDC margin through **Ember**. Phoenix's capability grant for the vault is enabled once the program is on mainnet.
{% endhint %}

For Phoenix, Keystone uses the **Rise SDK** (`github.com/Ellipsis-Labs/rise-public`) and reads Phoenix's account layouts from it. The other integrations build their instructions and account lists by hand.

***

## Venues

| Role                    | Program / Asset                                            | Address                                        |
| ----------------------- | ---------------------------------------------------------- | ---------------------------------------------- |
| Perp venue (mainnet)    | Phoenix Perps (Ellipsis Labs)                              | `EtrnLzgbS7nMMy5fbD42kXiUzGg8XQzJ972Xtk1cjWih` |
| Margin (USDC → Phoenix) | Ember                                                      | `EMBERpYNE6ehWmXymZZS2skiFmCa9V5dp14e1iduM5qy` |
| Spot leg                | jitoSOL (LST, held for staking — **not** posted as margin) | `J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn` |
| Lending / parked        | Kamino USDC reserve                                        | `D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59` |
| Quote / settlement      | USDC                                                       | `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` |

***

## Dependencies

| Protocol                          | Purpose                                                                   | Where used                                                                       |
| --------------------------------- | ------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| **Phoenix Perps** (Ellipsis Labs) | SOL-PERP short; USDC margin (posted via Ember); real two-sided funding    | `open_position`, `close_position`, `settle`, `emergency_close`, `enable_phoenix` |
| **Ember**                         | Routes USDC → Phoenix perp margin                                         | `open_position`, `close_position` (margin post/withdraw)                         |
| **Kamino KLend**                  | USDC lending for buffer + parked capital                                  | `enable_lending`, `lend_idle_usdc`, `unlend_usdc`                                |
| **Jupiter V6**                    | All token swaps (USDC ↔ jitoSOL); off-chain quote, on-chain execution     | Every open/close path that crosses tokens                                        |
| **Pyth (pull oracles)**           | SOL/USD + jitoSOL/USD for NAV math, drawdown guard, depeg check           | `settle`, `open_*`, `close_*`, `set_oracles`                                     |
| **Jito (jitoSOL)**                | Liquid staking; held **unlevered as the spot leg** (not posted as margin) | Implicit — staking yield is embedded in the jitoSOL/SOL exchange rate            |

***

## Verified mainnet addresses

| Item                                  | Address                                        |
| ------------------------------------- | ---------------------------------------------- |
| Phoenix Perps Program                 | `EtrnLzgbS7nMMy5fbD42kXiUzGg8XQzJ972Xtk1cjWih` |
| Ember Program (USDC → Phoenix margin) | `EMBERpYNE6ehWmXymZZS2skiFmCa9V5dp14e1iduM5qy` |
| Phoenix SOL-PERP market               | resolved via `PerpAssetMap` (Rise SDK)         |
| Kamino KLend Program                  | `KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD`  |
| Kamino Main Market                    | `7u3HeHxYDLhnCoErrtycNokbQYbWGzLs6JSDqGAv5PfF` |
| Kamino USDC Reserve                   | `D6q6wuQSrifJKZYpR1M8R4YawnLDtDsMmWM1NbBmgJ59` |
| Kamino USDT Reserve                   | `H3t6qZ1JkguCNTi9uzVKqQ7dvt2cum4XiXWom6Gn5e5S` |
| Jupiter V6 Program                    | `JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4`  |
| jitoSOL mint                          | `J1toso1uCk3RLmjorhTtrVwY9HJ7X8V9yYac6Y7kGCPn` |
| USDC mint                             | `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v` |

***

## CPI surface (Rust)

| Module                | Helpers                                                                                                                                                                                                                                                                                        |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `utils::phoenix_cpi`  | Onboard trader (Rise builder path), post/withdraw USDC margin via Ember, `place_perp_order`, `cancel_orders`, settle funding, `read_phoenix_funding_rate` — built on the `phoenix-rise` account views (`TraderHeader`, `TraderPositions`, `PerpAssetMap`, `GlobalConfig`, `PermissionAccount`) |
| `utils::kamino`       | `deposit_reserve_liquidity`, `redeem_reserve_collateral`, `refresh_reserve`                                                                                                                                                                                                                    |
| `utils::jupiter_swap` | `route_swap`, `require_min_received`                                                                                                                                                                                                                                                           |
| `utils::oracle`       | Pyth pull-oracle staleness + confidence wrappers, jitoSOL/SOL depeg check                                                                                                                                                                                                                      |

* Every helper passes the vault's signer seeds (`[b"vault", &[bump]]`), which is how the vault authorizes the call.
* Phoenix account layouts come from the `phoenix-rise` crate, read in place without copying. Kamino's return data is checked with minimal Borsh decoding.
* Kamino's byte offsets are hard-coded against a layout verified on-chain. Phoenix uses the Rise definitions instead of hand-written offsets.

***

## Off-chain account assembly

Strategy instructions expect 3–5 groups of accounts in `remaining_accounts`, plus a count for each group. The keeper assembles those off-chain:

* **Phoenix** — the Rise SDK (`github.com/Ellipsis-Labs/rise-public`) provides the correct account ordering for trader onboarding, margin in and out through Ember, `place_perp_order`, and funding settlement.
* **Kamino** — the same idea. The `refresh_obligation` and collateral instructions follow a fixed pattern documented in the Kamino IDL.
* **Jupiter** — Jupiter's `/swap-instructions` endpoint returns both the swap data (passed as `jupiter_swap_data`) and the account list that goes with it (passed as the matching account group).

See [Keeper bot](/run-it/keeper-bot) for the off-chain orchestration pattern.

***

## Related

* [Whitepaper](/how-it-works/whitepaper) — design overview of the system
* [Instructions reference](/build-on-it/quick-start/instructions) — per-instruction account-context groups
* [Quick start](/build-on-it/quick-start)


# Keeper Bot

The keeper is an off-chain bot that cranks settlement, lending, mode transitions, and withdrawals on a schedule. Mode transitions are automatic: the bot opens or closes the basis when the on-chain smoothed funding signal and guardrails permit, with no manual intervention. The position, NAV-attestation, and lending instructions require the vault's `authorized_keeper` to sign — so the keeper is a permissioned *executor*, bounded by the on-chain rules, not a decision-maker. `settle`, `process_withdrawal`, and `emergency_close` are permissionless, so anyone can keep the vault safe and redeemable if the keeper goes offline.

{% hint style="warning" %}
v1 hedges on Phoenix Perps (USDC margin via Ember). The keeper assembles the Phoenix and Ember account groups with the Rise SDK. Mode transitions run automatically off the on-chain funding signal; the keeper bot executes them and cranks settlement, lending, and withdrawals.
{% endhint %}

> Reference implementation: [the keeper](https://github.com/kamwithak/keystone-contracts/tree/main/scripts/keeper/README.md) — `index.ts` is the loop, `duties/` are the individual cranks, shared plumbing is in [its shared libraries](https://github.com/kamwithak/keystone-contracts/tree/main/scripts/lib/README.md). TypeScript + Anchor + Jupiter API. Run with `npm run keeper` (`KEEPER_MODE=dry-run` to plan only, `KEEPER_MODE=simulate` to build and simulate without sending). `npm run config:check` validates the configuration first and refuses anything that would run but not work.

***

## Cadence

The keeper ticks every `KEEPER_INTERVAL` seconds — 300 by default, and **hard capped at 900 on mainnet**, because deposits and withdrawals revert `NavStale` once NAV is 30 minutes old. That is a liveness constraint, not a preference: the keeper refuses to start with a longer interval.

| Instruction                      | Frequency                                                                                                                         | Trigger                                                                                                                                                                                                                                                                                                                                                                                                    |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `settle`                         | Every tick                                                                                                                        | Refresh funding EMA, drawdown peak, LST depeg check, `settle_pnl` if open. While parked it is the only thing keeping NAV fresh.                                                                                                                                                                                                                                                                            |
| `rebalance_hedge`                | When \|delta\| / NAV clears `delta_band_bps` (25 bps ≈ every two and a half weeks)                                                | Sweep the unhedged jitoSOL accrual back onto the short. Bounded by `max_rebalance_clip_lots`, which admin must set — see [the clip](#the-rebalance-clip).                                                                                                                                                                                                                                                  |
| `attest_nav(new_nav_usdc)`       | After `settle`                                                                                                                    | Snap NAV to live position value when on-chain reads can't capture unrealized PnL. Bounded by `max_nav_change_bps_per_hour`.                                                                                                                                                                                                                                                                                |
| `open_position`                  | When the smoothed funding signal clears the dynamic threshold by the 3-point band (+3.12% at today's rates) and dwell has elapsed | One-shot per mode entry                                                                                                                                                                                                                                                                                                                                                                                    |
| `close_position`                 | When the signal falls 3 points below the threshold (−2.88% at today's rates)                                                      | One-shot per mode exit                                                                                                                                                                                                                                                                                                                                                                                     |
| `lend_idle_usdc` / `unlend_usdc` | Whenever idle vault USDC exceeds the buffer target by > a margin (or buffer is short)                                             | Keep USDC productive without breaching `liquidity_buffer_target`                                                                                                                                                                                                                                                                                                                                           |
| `process_withdrawal`             | When the queue has unprocessed requests AND vault holds enough idle USDC for the **next** request (FIFO)                          | Permissionless — anyone can crank                                                                                                                                                                                                                                                                                                                                                                          |
| `emergency_close`                | When drawdown guard trips OR vault is paused with a position open                                                                 | Permissionless once tripped                                                                                                                                                                                                                                                                                                                                                                                |
| `add_margin`                     | Every tick while a position is open, when margin health drops below 2.5                                                           | **The keeper moves funds on its own here** — see below                                                                                                                                                                                                                                                                                                                                                     |
| `reduce_position`                | When the withdrawal queue still falls short after redeeming the whole Kamino position, and that shortfall persists across ticks   | De-lever both legs to fund the queue: buy back part of the short and sell the matching slice of jitoSOL, so net exposure never moves. It waits deliberately — tearing down part of the hedge realises slippage on both legs and permanently shrinks the position, so a queue one deposit would satisfy must not trigger it. Also the margin backstop, and **permissionless below `hard_margin_floor_bps`** |

**Every perp fill is priced against the oracle, whoever sent it.** `open_position`, `close_position`, `rebalance_hedge`, `reduce_position` and `emergency_close` all band the realized fill against the pinned SOL/USD mark by `max_swap_slippage_bps`, computed from the position delta the trader account records. The keeper's `min_base_lots_to_fill` / `min_quote_lots_to_fill` are its own floor on top; the program's bound does not depend on the keeper getting them right, which matters most on `emergency_close`, where the caller is a stranger.

**Margin only ever moves onto the venue to defend the position.** Nothing the keeper does reduces collateral on a short that stays the same size. The only way collateral comes back is if the short itself gets smaller, which `reduce_position` does by shrinking both legs together. Surplus margin raises a `margin-surplus` warning so an operator can judge whether the drag is worth closing early, and when idle USDC and the Kamino balance can no longer fund a top-up, `reduce_position` de-levers both legs proportionally rather than pulling collateral out from under the short.

### The rebalance clip

`initialize` turns rebalancing **on** — `delta_band_bps = 25` — but leaves `max_rebalance_clip_lots` at `0`, which means *unclipped*: one order may take the entire correction. That is deliberate, because the right ceiling is a function of the venue's book depth and the program never sees the book. It is also the one thing that must not be left at its initial value.

It matters because `rebalance_hedge` places an IOC market order with `min_base_lots_to_fill = 0` and no `price_in_ticks`. The fill price is bounded after the fact (`assert_fill_price_within` bands it against the pinned SOL/USD mark), so the clip is what bounds how much size one order pushes into the book, and how far that order walks the book.

The keeper knows and will warn (`clip-unset`, `clip-oversized`) but cannot fix it: `update_params` is admin-gated. Measure and set it:

```bash
npm run phoenix:capacity                       # prints the measured clip
npm run params:set -- --clip=auto              # or --clip=<lots>
npm run freeze:check                           # "rebalance bounds" should be green
```

Re-measure after any large move in Phoenix volume. The clip is 1% of a typical day, and a book that halves makes yesterday's clip twice as aggressive.

***

## Signal pipeline (open / close decisions)

*The normal↔parked transition is decided by the on-chain funding signal; the keeper bot assembles and submits the switch automatically whenever the rules below permit. The pipeline is that funding logic.*

1. **Read funding.** `settle` parses the last funding rate + timestamp from the perp venue's SOL-PERP market and updates the on-chain EMA (`funding_apr_smoothed_bps`). Sanity-bounded: absurd values revert with `FundingRateInsane`.
2. **Stale check.** If `now - funding_smooth_last_ts > funding_max_staleness_seconds`, opens revert with `FundingSignalStale`. Run `settle` first.
3. **Threshold + dwell + drawdown latency.**

* If parked, the smoothed funding clears the keeper's dynamic threshold plus the 3-point band, it also clears the on-chain floor `funding_threshold_normal_bps`, AND `now − last_mode_change_ts ≥ min_dwell_seconds` → call `open_position`.
* Else if hedged and the signal has fallen 3 points below the dynamic threshold → call `close_position`.
* Drawdown trips require `consecutive_dd_settles_observed ≥ consecutive_dd_settles_required` (default 2) before `emergency_close` can fire on a NAV breach; single-tick noise is rejected with `DrawdownTriggerLatent`.

4. **Build the transaction.** Assemble per-instruction `remaining_accounts` groups (see [Instructions](/build-on-it/quick-start/instructions)) and the Jupiter swap data via the Jupiter `/swap-instructions` endpoint.
5. **Submit.** Wrap with priority-fee compute budget instructions. Retry on slot-out / blockhash-not-found.

***

## Assembling `remaining_accounts`

* Strategy instructions pack multiple CPIs into one transaction
* Each group needs a precise account list — wrong order or missing accounts reverts the CPI
* Use the venue's official client / API to build each group:
* **Phoenix margin (Ember) / place\_perp\_order / settle funding** — use the **Rise SDK** (`github.com/Ellipsis-Labs/rise-public`) instruction builders and extract the `keys` array.
* **Kamino lending (`lend_idle_usdc` / `unlend_usdc`)** — use the Kamino IDL and PDA derivation utilities to build the USDC reserve deposit/withdraw account groups.
* **Jupiter route\_swap** — call Jupiter's `/swap-instructions` HTTP endpoint with `userPublicKey = vaultPda`, then pass the returned `swapInstruction.data` as `jupiter_swap_data` and the returned `keys` as the relevant remaining-accounts group.

> Pass per-group counts as the u8 instruction args (`jupiter_account_count`, `phoenix_deposit_account_count`, etc.) so the on-chain handler can split safely.

***

## Process-withdrawal cranking

**Strict FIFO:**

* Next-in-line request\_id is `vault.queue_processed_through` itself (both counters start at 0, and `process_withdrawal` requires `request_id == queue_processed_through`)
* Any other request errors with `WithdrawalNotNextInQueue`
* Anyone can crank (including the original requester)
* Rent refunds to the original requester even if a different wallet pays the tx

**Liquidity shortfall:**

* Reverts with `InsufficientLiquidityBuffer` if vault USDC is short of the next `usdc_owed`
* Keeper should `unlend_usdc` first if Kamino USDC can cover the shortfall
* Otherwise, if the shortfall persists across ticks, `reduce_position` de-levers both legs to fund it

***

## Failure modes

| Symptom                                              | Cause                                                                  | Resolution                                                                                                       |
| ---------------------------------------------------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `MinDwellNotElapsed`                                 | Tried to switch modes too soon                                         | Wait for `last_mode_change_ts + min_dwell_seconds`                                                               |
| `FundingThresholdNotMet`                             | Smoothed funding hasn't crossed the threshold                          | Re-read `funding_apr_smoothed_bps`                                                                               |
| `FundingSignalStale`                                 | EMA older than `funding_max_staleness_seconds`                         | Run `settle` first                                                                                               |
| `SlippageExceeded`                                   | Jupiter route filled at worse price than expected                      | Refresh the quote, narrow the bound, retry                                                                       |
| `PhoenixCpiFailed`                                   | Phoenix returned an error, usually margin or oracle                    | Inspect program logs; may need to settle funding first                                                           |
| `InsufficientLiquidityBuffer` (`process_withdrawal`) | Not enough idle USDC for the next request                              | `unlend_usdc` to refill, then `reduce_position` if the shortfall persists                                        |
| `LendingBreachesBuffer`                              | `lend_idle_usdc` would drop the buffer below `liquidity_buffer_target` | Reduce amount or run `unlend_usdc` instead                                                                       |
| `NavChangeExceedsCap`                                | `attest_nav` delta > `max_nav_change_bps_per_hour`                     | Stage with smaller deltas over multiple hours, or admin raises the cap if the position genuinely moved that much |
| `DrawdownTriggerLatent`                              | Drawdown observed but not yet across consecutive settles               | Wait one more settle cycle; this is by design                                                                    |
| `LstDepeg`                                           | jitoSOL/SOL deviation > `lst_depeg_bps`                                | `settle` auto-pauses; admin investigates and either unpauses or emergency-closes                                 |

***

## Idempotency

* All open / close instructions assert `position_mode` invariants on entry
* Duplicate calls during a retry storm revert cleanly without state damage
* `settle` is fully idempotent within an hour (no state change beyond the EMA refresh)

***

## The keeper moves margin autonomously

Unlike every other duty, `margin-health` can move vault funds without a human. That is deliberate: liquidation on a delta-hedged short can arrive in minutes, and an alert you read an hour later is not a defence.

The mechanism it defends against is unintuitive. The jitoSOL leg is in the vault and the margin is on Phoenix, and **Phoenix can only see its own side**. On a rally the short loses margin while the offsetting jitoSOL gain sits somewhere Phoenix cannot count, so a hedged position gets liquidated anyway. `emergency_close` will not save it, because NAV doesn't fall in a hedged rally.

Bounds on that autonomy:

* it can never draw on the withdrawal buffer
* total posted margin can never exceed **half of effective NAV** (enforced on-chain, not just in the keeper)
* collateral never falls on a short that stays the same size; de-levering closes part of the position and the matching spot leg together
* `KEEPER_AUTO_MARGIN=0` reduces it to alert-only, but then you must be reachable within minutes

If the keeper is down, or auto-margin is off, the thin-margin policy (`min_margin_bps = 900`) is not justified; close the position rather than leave it sitting. Note the 10× this implies is the venue's view of the perp leg, not portfolio leverage: the vault's total exposure equals its NAV.

***

## Related

* [Admin operations](/run-it/keeper-bot/admin-ops)
* [Monitoring](/run-it/keeper-bot/monitoring)
* **Deploying it** — `scripts/keeper/deploy/README.md`: Railway setup, dead-man's switch, kill switch (`KEEPER_READ_ONLY=1`), key rotation, and the keeper-down procedure
* [Instructions reference](/build-on-it/quick-start/instructions) — every entry point and who may call it
* [Errors](/build-on-it/quick-start/errors) — what a revert means


# Admin Operations

Admin-only instructions on the ksUSD vault. All signed by the `vault.admin` keypair (or successor after `transfer_admin` + `accept_admin`).

> Source: [the admin instructions](https://github.com/kamwithak/keystone-contracts/blob/main/programs/keystone-finance/src/instructions/admin.rs) · [wind-down](https://github.com/kamwithak/keystone-contracts/blob/main/programs/keystone-finance/src/instructions/init_wind_down.rs) · [lending setup](https://github.com/kamwithak/keystone-contracts/blob/main/programs/keystone-finance/src/instructions/enable_lending.rs) · [oracle setup](https://github.com/kamwithak/keystone-contracts/blob/main/programs/keystone-finance/src/instructions/set_oracles.rs)

***

## One-time setup

| Instruction                     | When                                                                                                     |
| ------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `initialize(params)`            | First deploy. Creates the vault PDA, ksUSD mint, vault USDC ATA.                                         |
| `enable_phoenix(perp_asset_id)` | After init, before opening any perp position. Pins the Phoenix trader, market and SOL-PERP asset id (0). |
| `enable_lending()`              | After init, before any `lend_idle_usdc`. Pins the Kamino USDC reserve + the vault's cToken ATA.          |
| `set_oracles()`                 | After init, before strategy paths that read SOL/USD or jitoSOL/USD.                                      |

***

## `set_pause(paused: bool)`

* Halts new deposits and new positions
* Instant withdrawals and `claim_wind_down` stay open by design, so depositors can always exit
* Cannot un-pause while `position_mode == WindDown` (reverts with `WindDownActive`)

**When to use:**

* Pre-audit incident response
* Investigating an oracle / venue anomaly
* During an admin handover (briefly, to flush in-flight state)

```ts
await program.methods.setPause(true).accountsStrict({
  vault: vaultPda,
  admin: adminWallet.publicKey,
}).rpc();
```

Emits `PauseToggled`.

***

## `update_params(args)`

* Adjust risk parameters in place
* Each field on `UpdateParamsArgs` is `Option<T>`; only the fields you pass get written

| Field                             | Bounds                                                                                                                             |
| --------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `liquidity_buffer_bps`            | 0–5\_000 (≤ 50% of NAV)                                                                                                            |
| `funding_threshold_normal_bps`    | i32; expected positive                                                                                                             |
| `perf_fee_bps`                    | 0–5\_000 (≤ 50%)                                                                                                                   |
| `min_dwell_seconds`               | 0–`u32::MAX`                                                                                                                       |
| `max_swap_slippage_bps`           | 0–1\_000 (≤ 10%)                                                                                                                   |
| `emergency_close_dd_bps`          | 0–10\_000                                                                                                                          |
| `deposit_cap_usdc`                | `u64::MAX` = uncapped, `0` = pause new deposits, else USDC base units                                                              |
| `authorized_keeper`               | Pubkey; **exact match required**. `Pubkey::default()` (the post-init state) blocks all keeper-gated ix until admin sets a real key |
| `min_request_shares`              | u64                                                                                                                                |
| `max_pending_queue_usdc`          | `u64::MAX` = disabled                                                                                                              |
| `max_nav_change_bps_per_hour`     | 0–10\_000                                                                                                                          |
| `funding_max_staleness_seconds`   | u32                                                                                                                                |
| `consecutive_dd_settles_required` | ≥ 1                                                                                                                                |

* Invalid bounds → `InvalidParams`
* Mints, admin, oracles, Phoenix / Kamino refs are **immutable** through this instruction, set once at `initialize` / `enable_*` / `set_oracles`

```ts
await program.methods.updateParams({
  liquidityBufferBps: 800,            // tighten buffer to 8%
  emergencyCloseDdBps: 400,           // tighten drawdown guard to 4%
  // omit other fields to leave them unchanged
}).accountsStrict({
  vault: vaultPda,
  admin: adminWallet.publicKey,
}).rpc();
```

***

## `transfer_admin(new_admin)` + `accept_admin()`

Two-step admin handover:

* **Step 1**: records `new_admin` as a pending successor (signed by current admin)
* **Step 2**: finalizes (signed by the new admin)
* Prevents accidentally transferring to a dead key

**Target end-state:** a multisig (Squads / similar) once mainnet is live.

```ts
// Step 1 — current admin proposes
await program.methods.transferAdmin(squadsMultisig).accountsStrict({
  vault: vaultPda,
  admin: currentAdmin.publicKey,
}).rpc();

// Step 2 — new admin accepts
await program.methods.acceptAdmin().accountsStrict({
  vault: vaultPda,
  newAdmin: squadsMultisig,
}).rpc();
```

Errors: `NoPendingAdmin` (step 2 called without a pending), `NotPendingAdmin` (step 2 signer mismatch).

***

## `collect_fees()`

* Pays the performance fee in USDC (no dilutive share mint)
* Only callable when `position_mode == Idle` (Parked) and not paused. Fees accrue continuously; collection only moves USDC that is already set aside
* See [Fees](/start-here/fees) for the math
* Fee → `admin_usdc_account`
* HWM drops by exactly the per-share payout, so the share price does not move at collection

**When to call:**

* On a regular cadence (monthly is conventional; weekly is fine)
* Before any planned parameter change that affects share-price computation
* Before mainnet upgrade events (clean accounting boundary)

```ts
await program.methods.collectFees().accountsStrict({
  vault: vaultPda,
  vaultUsdcAccount: vaultUsdcAta,
  adminUsdcAccount: adminUsdcAta,
  admin: adminWallet.publicKey,
  tokenProgram: TOKEN_PROGRAM_ID,
}).rpc();
```

A no-op when nothing has accrued (`pending_perf_fees_usdc == 0`). Emits `FeesCollected`.

***

## `reset_peak()`

* Re-anchors `peak_share_price_1e9` to the current share price and resets `consecutive_dd_settles_observed`
* Use after a legitimate recovery; it prevents a stale peak from keeping the drawdown guard armed against routine volatility

```ts
await program.methods.resetPeak().accountsStrict({
  vault: vaultPda,
  admin: adminWallet.publicKey,
}).rpc();
```

Emits `PeakReset`.

***

## `init_wind_down()`

Terminal mode switch. Sets `position_mode = WindDown` and pauses the vault. After this:

* `deposit` reverts (`WindDownActive`)
* Strategy `open_*` reverts (`WindDownActive`)
* Existing positions must be closed via `close_position` / `emergency_close`
* Users redeem pro-rata via `claim_wind_down(shares)` against the vault's idle USDC

Cannot be undone via `set_pause(false)`.

### Both preconditions, and why they are enforced

`init_wind_down` requires `position_mode == Idle` **and** `usdc_lent_kamino == 0` (`WindDownRequiresUnlent`). The lending one matters because `claim_wind_down` pays out of the vault's USDC ATA but sizes each payout off `effective_nav_usdc()`, which counts the Kamino basis, so entering with USDC lent would make the lent fraction permanently unclaimable. `unlend_usdc` is keeper-only, and WindDown is exactly when the keeper stands down, so nothing would be left that could recover it.

So run the drain first, and wait for it to finish:

```bash
KEEPER_DRAIN_LENDING=1 npm run keeper      # redeems everything, lends nothing
npm run keeper:status                      # until both lent figures read 0
```

Then close any position, then `init_wind_down`.

```ts
await program.methods.initWindDown().accountsStrict({
  vault: vaultPda,
  admin: adminWallet.publicKey,
}).rpc();
```

Emits `WindDownInitiated`.

***

## Operational checklist

| Cadence                      | Action                                                                                                                                                      |
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Daily**                    | Verify `cached_nav_usdc` against on-chain Phoenix / Kamino reads (off-chain script).                                                                        |
| **Weekly**                   | `collect_fees` if share price has crossed HWM. Refresh keeper bot keys if rotated.                                                                          |
| **Monthly**                  | Review `peak_share_price_1e9` vs. live share price; `reset_peak` if a stale peak is dragging the drawdown guard.                                            |
| **On incident**              | `set_pause(true)`, investigate, then either resolve and unpause or invoke `emergency_close`.                                                                |
| **On admin rotation**        | `transfer_admin` + `accept_admin` (two transactions).                                                                                                       |
| **On legitimate retirement** | `KEEPER_DRAIN_LENDING=1` until both lent figures read 0, close any open position, `init_wind_down`, broadcast `claim_wind_down` instructions to depositors. |

***

## Related

* [Keeper bot](/run-it/keeper-bot) — non-admin strategy operations
* [Monitoring](/run-it/keeper-bot/monitoring) — what to watch
* [Errors](/build-on-it/quick-start/errors) — what reverts look like
* [Fees](/start-here/fees) — `collect_fees` math


# Monitoring & Alerts

The ksUSD vault is one PDA, so most monitoring reduces to watching that account plus a few external signals.

{% hint style="warning" %}
v1 monitors the **Phoenix** position and Ember margin.
{% endhint %}

***

## Key metrics

| Metric                                  | Source                                                                   | Alert when                                                                                       |
| --------------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| Share price (`share_price_1e9`)         | Derived from `effective_nav_usdc / total_shares`                         | Drops > 2% in 24h, or > `emergency_close_dd_bps` from `peak_share_price_1e9`                     |
| `cached_nav_usdc` vs. computed-live NAV | On-chain vs. off-chain reconciliation against Phoenix / Kamino positions | Discrepancy > 1%                                                                                 |
| Pyth SOL/USD staleness                  | Last-update timestamp on the Pyth feed                                   | > 5 min                                                                                          |
| Pyth confidence                         | `confidence / price`                                                     | > 1.5% (program reverts at 2%)                                                                   |
| jitoSOL/SOL depeg                       | Derived from `jitosol_oracle.price / sol_oracle.price`                   | > 80% of `lst_depeg_bps`                                                                         |
| `cached_nav_usdc` cap utilization       | `cached_nav_usdc / deposit_cap_usdc`                                     | > 90% (raise cap or pause new deposits)                                                          |
| `position_mode`                         | `vault.position_mode`                                                    | `Parked` (`Idle`) for > 24h while funding signal is active                                       |
| `position_base_amount`                  | `vault.position_base_amount`                                             | Drifts > 1% from expected (1× of the jitoSOL spot leg)                                           |
| `funding_apr_smoothed_bps` staleness    | `now - funding_smooth_last_ts`                                           | Approaching `funding_max_staleness_seconds`                                                      |
| `consecutive_dd_settles_observed`       | `vault.consecutive_dd_settles_observed`                                  | ≥ 1 (single-tick warning before lethal)                                                          |
| Perp-venue health factor                | Phoenix trader-account margin                                            | < 1.5                                                                                            |
| SOL-PERP funding rate                   | Phoenix `PerpAssetMap`                                                   | Crosses the entry or exit line (threshold ± 3 points) and holds past dwell without a mode switch |
| Pending withdrawals                     | `queue_next_id − queue_processed_through`                                | > 0 for more than one keeper cycle                                                               |
| Lending balances                        | `usdc_lent_kamino`                                                       | Sudden drop without a matching `unlend_*` event = Kamino-side anomaly                            |
| `vault.paused`                          | bool                                                                     | Unexpected `true` = investigate `LstDepeg` or admin action                                       |
| `vault.position_mode == WindDown`       | enum                                                                     | Terminal — only `claim_wind_down` should run                                                     |

***

## Reconciliation

Once per cycle, an off-chain script should compute the "true" NAV by summing:

1. Vault USDC ATA balance
2. `usdc_lent_kamino × kamino USDC reserve cToken exchange rate` (lent vault USDC, current value)
3. `(jitoSOL spot holdings) × Pyth jitoSOL price`: the unlevered spot leg (normal basis only)
4. Phoenix trader-account margin balance: posted USDC margin + settled funding + accrued PnL

Compare against `vault.cached_nav_usdc`. A discrepancy > 1% means:

* `settle` is overdue, **or**
* `attest_nav` is needed to capture unrealized PnL

***

## Emergency conditions

| Signal                                                                                | Response                                                                       |
| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| Pyth SOL/USD stale > 10 min OR confidence > 2%                                        | Pause new deposits + positions; manual `emergency_close` if a position is open |
| jitoSOL depeg > `lst_depeg_bps`                                                       | `settle` auto-pauses; investigate and either unpause or emergency-close        |
| Phoenix outage / market halted                                                        | Same — pause and investigate                                                   |
| NAV drawdown ≥ `emergency_close_dd_bps` for `consecutive_dd_settles_required` settles | Anyone can call `emergency_close` permissionlessly; keeper should do it first  |
| `position_mode == WindDown`                                                           | Stop the keeper; broadcast `claim_wind_down` instructions to depositors        |

***

## Suggested external infra

* A serverless function (Cloudflare Workers / AWS Lambda) running every 5 min: fetch `vault` + Pyth + Phoenix trader account, compute the deltas, push to Grafana / Datadog / PagerDuty.
* A `program.addEventListener` consumer that subscribes to `DepositEvent`, `WithdrawEvent`, `WithdrawalRequested`, `WithdrawalProcessed`, `FeesCollected`, `PositionOpened`, `PositionClosed`, `NavAttested`, `IdleLent`, `IdleUnlent`, `WindDownInitiated`, and writes to a database for audit / reporting.
* A page in the operator dashboard tying `cached_nav_usdc` to the reconciliation script's live computation, with a visible delta and an "attest now" button that calls `attest_nav` when the delta crosses an internal threshold.

***

## Related

* [Keeper bot](/run-it/keeper-bot) · [Admin operations](/run-it/keeper-bot/admin-ops)
* [Events](/build-on-it/quick-start/events) · [Errors](/build-on-it/quick-start/errors)


# Utilization Metrics

How to work out where the vault's money is sitting at any given moment.

> Everything here comes from `vault.cached_nav_usdc` and the position fields. There are no view helpers to call; just read the `Vault` account directly.

***

## Buckets

Everything the vault holds falls into one of these:

| Bucket            | Source                                                                                     |
| ----------------- | ------------------------------------------------------------------------------------------ |
| Liquidity buffer  | Vault USDC ATA balance — sized to `liquidity_buffer_bps × cached_nav_usdc / 10_000` target |
| Parked capital    | Kamino USDC reserve via `lend_idle_usdc`                                                   |
| jitoSOL spot leg  | jitoSOL held unlevered (normal basis) — `spot holdings × oracle jitoSOL price`             |
| Perp-venue margin | USDC margin on Phoenix via Ember (normal basis)                                            |
| Perp PnL          | Settled funding + mark-vs-entry PnL on the open position                                   |

***

## Derived ratios

```ts
const buffer        = vaultUsdcAtaBalance;          // off-chain query
const target        = vault.cachedNavUsdc.muln(vault.liquidityBufferBps).divn(10_000);
const bufferUtilBps = Number(buffer.mul(10_000n).div(target.toBigInt()));  // 10_000 = exactly on target

const queuePendingRatioBps = vault.queuePendingUsdc * 10_000n / vault.cachedNavUsdc;
const navPerShare1e9       = vault.cachedNavUsdc * 1_000_000_000n / vault.totalShares;
```

| Ratio                  | What it means                                                                                                                                                               |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bufferUtilBps`        | Whether the buffer holds enough to cover instant withdrawals. 10,000 means exactly on target. Below 9,000 it's underfunded and the keeper should move more capital into it. |
| `queuePendingRatioBps` | How much USDC is owed to queued withdrawals, as a share of NAV. If this stays above 10%, the keeper needs to unwind position to free up cash.                               |
| `navPerShare1e9`       | The live share price, scaled by 1e9. Drifts up with carry, and only ever starts at par on the very first deposit.                                                           |

***

## When to alert

| Condition                                                           | Interpretation                                                                |
| ------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `bufferUtilBps < 5_000` for > 1h                                    | The buffer is under half its target, so instant withdrawals may start failing |
| `queuePendingRatioBps > 1_500` for > 6h                             | The queue is over 15% of NAV; the keeper should unwind position faster        |
| Perp margin or jitoSOL value drifts > 5% from what the mode implies | Something is wrong with margin, the oracle, or settlement. Investigate.       |

***

## Related

* [NAV & share pricing](/how-it-works/strategy-and-modes/nav-calculation) — full NAV formula
* [Monitoring](/run-it/keeper-bot/monitoring) — what to watch
* [Withdraw](/start-here/withdraw) — instant vs. queued paths


# Mainnet Checklist

{% hint style="info" %}
**TL;DR** Not on mainnet. The gate is an external audit, not yet booked. The program, keeper and fork proofs are done. One program, one vault, one mint.

This page is the inventory of what is and is not complete. To execute a launch, follow [the runbook](https://github.com/kamwithak/keystone-contracts/blob/main/docs/MAINNET_LAUNCH_RUNBOOK.md) — the single ordered path, with the key ceremony and a rollback plan per stage.
{% endhint %}

{% hint style="warning" %}
**Pre-deployment (v1).** The perp venue is **Phoenix Perps (Ellipsis Labs)**, USDC margin via **Ember**, integrated by on-chain CPI (Rise SDK). Before it can post margin, the vault's trader PDA needs its `CAN_DEPOSIT`/`CAN_WITHDRAW` capabilities enabled. Our contact at Phoenix has agreed to enable them **once the program is deployed to mainnet**, so this closes after deploy rather than before it. It is requested at Stage 6 and confirmed at Stage 8, and the deposit cap stays at the operator's own seed until the hedge is on — outside money does not arrive before the position it is meant to be in. The self-serve onboarding endpoint still reports itself gated, which is why the agreed path runs through the contact.
{% endhint %}

***

## Phase 1 — Engineering (in progress)

* [x] Single-program rewrite: one `keystone_finance` program, one vault, one share mint
* [x] **Phoenix Perps CPI via the Rise SDK** — Ember USDC-margin path, trader onboarding, funding/position reads (`phoenix-rise` account views). Fork-proven: `open_position` → `close_position`, base lots 0 → −1 → 0, with the Jupiter spot leg
* [x] **Real-Pyth build of the perp path** — `prepare-pyth-fork.ts` injects the real mainnet `PriceUpdateV2` accounts restamped to boot, so the fork round-trip runs the same reader mainnet does (verified 2026-08-23; the fork suite also asserts it rejects stale / skewed / wrong-feed / wide-confidence / bad-owner / bad-discriminator accounts)
* [ ] **Phoenix capability grant** on the vault's trader PDA — flags 6 → 63 (only the two margin bits, `1<<4 | 1<<5`, are required); agreed with our Phoenix contact for after deploy, so this box closes post-mainnet
* [x] Kamino KLend CPI surface (idle USDC lending)
* [x] Jupiter V6 swap CPI helper with explicit `min_*_out` slippage bounds
* [x] Hardened account-context offsets (`checked_add` on all slice math)
* [x] Funding EMA + staleness guard on-chain (`funding_apr_smoothed_bps`, `FundingSignalStale`)
* [x] Drawdown latency (`consecutive_dd_settles_required`, `DrawdownTriggerLatent`)
* [x] LST depeg auto-pause (`lst_depeg_bps`, `LstDepeg`)
* [x] Wind-down terminal path (`init_wind_down`, `claim_wind_down`)
* [x] Mainnet-fork test harness (`scripts/fork/start-fork.sh` + `tests/fork/`) — the verification standard, because **devnet is not a usable target**: Phoenix/Ember, Kamino, Jupiter and Pyth have no devnet deployments to integrate against, so a devnet run proves nothing about the hedged path
* [x] **Keeper Tier B implemented** — `attest_nav`, automatic regime transitions and `emergency_close`, behind the single `KEEPER_PERP` interlock, which the one `mainnet` profile arms. Proven on a mainnet fork 2026-08-23: `attest_nav` accepted by the program against a live 7-lot short, keeper-built `open_position` simulating green with a real Jupiter route
* [x] **Transaction layer able to carry the perp instructions** — address-lookup-table support in `lib/tx.ts` (a Jupiter route does not fit a static v0 message), and the sizing simulation set to the 1.4M CU ceiling. At Solana's 200k default every instruction over 200k would be unsendable through the duty runner, and `open_position` measures \~416k
* [ ] Keeper driven end-to-end against the mainnet fork — `npm run test:fork:keeper` (`scripts/fork/keeper-e2e.ts`) drives the real duties in runner order and exits non-zero on any leg. **6 of 10 legs green today:** preflight, oracle-refresh, settle, the funding-EMA seed, and both Kamino lend cranks. The regime transition reaches `open_position`, Jupiter V6 executes the swap, and the program's own slippage guard then refuses the fill — the pinned `jupiter-route.json` is quoted for a different notional than the driver deposits, so re-quoting the fixture at the driver's size is what closes this. `attest_nav`, `margin-health` and `emergency_close` sit behind it and report skipped rather than passing vacuously
* [x] **Replay-protected admin transfer proven** — `transfer_admin` records the proposal without moving the authority, only the proposed account may accept, and a consumed proposal cannot be replayed. Green on a mainnet fork (`npm run test:fork`)
* [ ] Keeper runs clean for a full day before the first deposit (runbook Stage 6). The devnet soak covers the parked-mode duties only; the perp integrations exist only on mainnet, so the soak for the hedged path is the cap-limited private beta in Phase 4
* [x] Bootstrap dry-run against mainnet RPC — verified 2026-08-23: every pinned account resolves on mainnet (mints, Kamino reserve + cToken, both Pyth feeds, Jito stake pool) and `initialize` / `enable_lending` / `set_oracles` all encode cleanly. Nothing sent

***

## Phase 2 — Audit

* [ ] Audit firm engaged (Ottersec / Sec3 / Neodyme — pick one)
* [ ] **Legal position settled — this page and the runbook cover none of it, and it books on someone else's calendar the way the audit does.** At minimum: which entity issues ksUSD and where; terms of service and a risk disclosure the app links; whether the published APY is a forward-looking statement anywhere it appears; whether any jurisdiction is geofenced at the front end; and who is liable if the keeper mis-executes. Answers belong with counsel — what belongs here is the checkbox, so it cannot be skipped by not being written down
* [ ] All issues triaged; high / critical findings resolved
* [ ] Public audit report published in the repo and linked from the whitepaper
* [ ] Bug bounty stood up (Immunefi or equivalent)

***

## Phase 3 — Mainnet deployment

The program deploy itself is one script, run via `npm run mainnet:deploy`, which builds, preflights, deploys, verifies the on-chain binary against the local build, writes the IDL, and records the deploy. Run `--check` first (no transactions), and `--rehearse` against devnet to walk the identical path.

```bash
npm run mainnet:deploy:check     # preflight only, sends nothing
npm run mainnet:deploy           # the real thing
npm run mainnet:deploy:verify    # re-verify on-chain binary vs local build
npm run mainnet:deploy:rehearse  # identical path against devnet
```

* [ ] **Toolchain pinned: `anchor --version` reports 0.32.1**, matching `Anchor.toml`. A stale standalone binary at `~/.cargo/bin/anchor` (0.31.1) shadows the avm shim; `deploy-mainnet.sh` puts `~/.avm/bin` first to compensate, but a hand-run build through the shadowed binary will not reproduce from the audit-locked commit
* [ ] Final program build under audit-locked commit; `anchor idl build` regenerated
* [ ] Verifiable build produced and the sha256 recorded (`anchor build --verifiable`; `solana-verify` 0.4.9 is installed for the on-chain attestation)
* [ ] Admin multisig provisioned and tested on devnet — a Squads-of-1 (<https://squads.xyz/multisig>) with the hardware wallet as sole signer, so signers can be added later without moving authority. Record the **Vault** address, not the Squad address: the Vault (index 0) is the PDA that signs, and it is what `<multisig>` means in every step below
* [ ] `deploy-mainnet.sh --check` clean on the audit-locked commit
* [ ] Program deployed to mainnet at `E7tpCcxtvuTXLAckBGWb1AsndpLQ1Y9hQA3iGYSXz2vJ` — the launch ID, deliberately not rotated. (`--rotate-id` stays available as a *recovery* path: `initialize` runs once per program id, so a bad init is fixed by redeploying under a fresh one)
* [ ] On-chain binary hash verified against the local build (the script does this and fails loudly)
* [ ] On-chain IDL upgraded
* [ ] `deployments/mainnet-<utc>.json` committed as the deploy record
* [ ] `initialize` with conservative launch params — **signed by the program's upgrade authority**, which at this point is still the deploy key. `initialize` is gated on that authority, so moving it to the multisig first turns this and every parameter below into multisig transactions over an empty vault. Hand both authorities over afterwards, not before. The gate is also why there is no race to initialize: nobody else can take the vault. These are what `init-v1.ts` actually sets — keep this list and the script in lockstep.
  * `deposit_cap_usdc` = $500k (venue-derived; recompute with `npm run phoenix:capacity` on the day, raise after 30 days of clean operation)
  * `liquidity_buffer_bps` = 1\_000 (10%)
  * `instant_buffer_bps` = 200 (2% raw-USDC floor for instant withdrawals)
  * `max_swap_slippage_bps` = 50 — the program also enforces an oracle-derived floor on every swap, so this is the tighter of two bounds, not the only one
  * `emergency_close_dd_bps` = 500 (5% drawdown auto-trip)
  * `consecutive_dd_settles_required` = 2
  * `perf_fee_bps` = 2\_000 (20% above HWM)
  * `hurdle_apr_bps` = measured at init from the live USDC lending rate (\~450), not hardcoded
  * `lst_depeg_bps` = 500 (5%, measured against the stake-pool redemption rate, not 1.0)
  * `max_nav_change_bps_per_hour` = **1\_000 (±10%/hr)**
  * `funding_threshold_normal_bps` = **+12** — derived at deploy from the live lending rate; a safety *floor* ("never short into worse than break-even"), not the entry rule; the keeper applies a tighter dynamic threshold above it
  * `min_dwell_seconds` = 43\_200 (12h) **at init, and raised to 21 days at Stage 8, once the first position exists — see below.** It cannot start long: `initialize` stamps `last_mode_change_ts`, and `open_position` measures dwell against it, so a 21-day value here blocks the *first* hedge for 21 days
  * `min_margin_bps` = 900 (bounds effective leverage at \~10x)
  * `authorized_keeper` = the keeper's own pubkey, from `KEEPER_PUBKEY`. The script **refuses** to default it to the admin wallet on mainnet: the keeper runs hot and the admin is meant to be cold, and `initialize` runs once
  * `funding_max_staleness_seconds` = 21\_600 (6h) — how old the funding EMA may be before `open_position` rejects it
  * `min_request_shares` = 1\_000\_000 (1 ksUSD) — dust floor on a withdrawal request
  * `max_pending_queue_usdc` = `u64::MAX` — the queue is deliberately unbounded; `deposit_cap_usdc` is what bounds the vault
* [ ] `set_oracles` with Pyth pull-oracle pubkeys for SOL/USD + jitoSOL/USD. **Not optional and not deferrable:** `settle` hard-requires `oracles_initialized`, and while Idle `settle` is the only writer of `last_nav_attest_ts` — so until this runs, every deposit and withdrawal starts failing `NavStale` 30 minutes after `initialize`
* [ ] **Vault jitoSOL ATA created** — `init-v1.ts` does it as its fifth step, because no instruction does: `open_position` takes the account as a plain `Account<TokenAccount>` rather than `init_if_needed`, so without it the first hedge reverts `AccountNotInitialized`. Confirm the address it prints exists on-chain
* [ ] `enable_phoenix` — onboard the vault PDA as a Phoenix trader (Rise builder path) and pin the Phoenix/Ember accounts
* [ ] `enable_lending` against Kamino USDC reserve
* [ ] **Arm the four guards that ship at `0`,** where `0` means *off*, not *default*. Set with `update_params`, and set them **before `transfer_admin`** — afterwards each change needs a multisig transaction.
  * `max_rebalance_clip_lots` — per-order ceiling on a rebalance, in base lots. It bounds how much **size** one IOC pushes into the book; price is bounded separately by the oracle band on every fill. Measure the book, don't guess
  * `max_position_base_lots` — absolute size ceiling, checked against the *resulting total* rather than the increment
  * `hard_margin_floor_bps` — below this, anyone may `reduce_position` to Margin. Zero leaves margin defence entirely dependent on the keeper being alive
  * `mint_window_seconds` + `mint_limit_per_window_usdc` — the deposit *rate* limit. `deposit_cap_usdc` bounds total size but not how fast it fills; both halves are needed or the guard is off
* [ ] **Check the two that ship already set** — these are not zeroed, so they are a review step rather than an arming step. A wrong value is worse than a zero: zero makes `rebalance_hedge` stop with `RebalanceDisabled`, where a wrong one keeps working off a bad number.
  * `perp_base_lot_lamports` = `10_000_000` (0.01 SOL) — the venue's lot size. Confirm against Phoenix's live SOL-PERP market before the first position
  * `delta_band_bps` = `25` — how far delta may drift before a rebalance
* [ ] `npm run freeze:check` reports every safety guard armed — it decodes the live vault and fails on an unset one, so this is the gate rather than the list above
* [ ] `transfer_admin` → `accept_admin` to the multisig (two-step)
* [ ] Upgrade authority moved to the multisig (`deploy-mainnet.sh --transfer-authority <PK>`), IDL authority moved with it

***

## Phase 4 — Private beta

* [ ] Invite-only; raise `deposit_cap_usdc` $500k → $1M once the launch cap fills cleanly (gated by live OI, not demand)
* [ ] Keeper deployed on Railway (`Dockerfile` + `railway.toml`; see `scripts/keeper/deploy/README.md`). `railway.toml` declares the correctness constraints (`numReplicas = 1`, `overlapSeconds = 0`, `drainingSeconds = 180`, `sleepApplication = false`, and `requiredMountPath = "/data"`, which fails the deploy without the volume), plus a dead-man's switch on `KEEPER_HEARTBEAT_URL`. Redundancy is a **warm spare**: a second service kept stopped. Two keepers cranking one vault would plan the same actions from the same state and double-submit; true multi-operator redundancy needs leader election and is post-v1
* [ ] **Raise `min_dwell_seconds` 43\_200 → 1\_814\_400 (21 days), once the first position is open.** A multisig `update_params` by this point, and deliberately not done at init, where it would gate the first entry rather than the whipsaw it exists to stop. It is insurance, not a backtest gain: on the 316-day window every round trip lasts 50 days or more, so 21 days changes nothing there — but 12h is not a guard at the cadence the keeper runs. It matches the T = 30 days the hysteresis width is already derived from, and it is entry-only, so it can never trap the vault: `close_position`, `reduce_position` and `emergency_close` do not consult it. Program caps it at 30 days
* [ ] `lend_idle_usdc` running so the buffer's excess sits in Kamino productively
* [ ] Monitoring + alerting wired ([/for-operators/monitoring.md](/run-it/keeper-bot/monitoring))
* [ ] First `collect_fees` cycle after 30 days
* [ ] Public dashboard with live NAV, share price, position mode, queue depth

***

## Phase 5 — Public launch

* [ ] Raise `deposit_cap_usdc` to $5M, then $25M as TVL fills
* [ ] First composability integration (Kamino accepts ksUSD as collateral)
* [ ] DAO / treasury wrappers announced (Solana-aligned partners)
* [ ] Public docs polish + integrator quickstarts

***

## Rollback / circuit-breaker plan

If any of the following occur in the first 90 days post-launch:

| Trigger                                        | Action                                                                                                                   |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| Audit reveals a missed critical issue          | `set_pause(true)` immediately; if non-recoverable, `init_wind_down` and coordinate redeploy under new program ID         |
| NAV drawdown exceeds 3% within a week          | `emergency_close` + `set_pause(true)`; investigate before resuming                                                       |
| Phoenix or Kamino announce a critical incident | `set_pause(true)` until the dependency is verified safe                                                                  |
| Pyth feed instability for > 1h                 | `set_pause(true)`; instant withdrawals stay open                                                                         |
| LST depeg auto-trip                            | Vault is already paused by `settle`; admin investigates and either unpauses or emergency-closes                          |
| `attest_nav` stalls > 2h in Normal mode        | Vault is already paused by `settle` (`NavAttesterStalled`); restart the NAV duty, or `emergency_close` to unwind to Idle |

> **While paused, instant withdrawals from the liquidity buffer remain available**, but they require a NAV attested within the last 30 minutes, so they stay open only as long as something is refreshing NAV. In `Idle` the permissionless `settle` crank does that, so the buffer really is always open. In `Normal` mode only `attest_nav` does, and if it stops, every user path — deposit, queued withdrawal, and instant withdrawal alike — reverts `NavStale` 30 minutes later. `settle` auto-pauses the vault after 2 hours of this, which is what re-opens the permissionless `emergency_close` path back to `Idle`. The duty is implemented (Phase 1), but **do not enable Normal mode until you have watched it run for a full day**: in Normal mode it is the only thing standing between the vault and every user path freezing.

***

## Related

* [**Launch runbook**](https://github.com/kamwithak/keystone-contracts/blob/main/docs/MAINNET_LAUNCH_RUNBOOK.md) — the ordered path this page inventories
* [Security model](/reference/security) · [Admin operations](/run-it/keeper-bot/admin-ops)
* [Pre-mainnet audit notes](https://github.com/kamwithak/keystone-contracts/blob/main/docs/PRE_MAINNET_AUDIT.md)
* [Whitepaper](/how-it-works/whitepaper)


# Glossary

Quick definitions for terms used across the ksUSD docs.

A few come up everywhere, so they're defined once here:

* **Carry** — income you collect for holding a position, rather than for correctly guessing a price move.
* **Funding** — a payment perp traders make to each other every few hours to keep the perp price near spot. When more traders are long than short, longs pay shorts, so a short position gets paid to sit there. It is the price of leverage on *that venue*, so a young book can pay very differently from a mature one on the same asset.
* **NAV** — net asset value, the total dollar value of everything the vault holds.
* **Delta-hedged** — holding an asset and shorting the same amount of it, so its price largely stops affecting your return. Traders call the trade delta-neutral; the offset here is close but not exact, so this book says hedged.

***

## Product

* **ksUSD** — Solana staking yield, hedged. A vault share, not a pegged dollar: a share is worth whatever the vault's assets are worth, drifts up as yield accrues, and can fall. What the vault does to earn it is the [Introduction](/).
* **Vault** — the single Anchor program and its account, which holds the assets, mints ksUSD, and runs the strategy.
* **Coordinates carry** — ksUSD gathers jitoSOL staking, Phoenix funding, and lending carry into one token, run by one vault.
* **Gross effective NAV** — `cached_nav_usdc − queue_pending_usdc`. What the high-water mark is measured against.
* **Effective NAV** — `gross_effective_nav_usdc − pending_perf_fees_usdc`. What holders actually own, and what deposits and withdrawals price against.
* **Share price** — what 1 ksUSD is worth in USDC: the dollars the vault holds for shareholders, divided by the ksUSD outstanding. On-chain that is `effective_nav_usdc × 1e9 / total_shares`, stored as dollars × 1e9, so `1_030_000_000` reads as $1.03. Deposits mint at it, redemptions burn at it.
* **HWM** — high-water mark: the highest *gross* share price the vault has ever reached. Performance fees accrue only above it. It moves down only by exactly what a fee collection pays out per share, which keeps collection price-neutral.
* **Accrued perf fees** — `pending_perf_fees_usdc`. Performance fees already earned but not yet paid out. Set aside as they're earned, so the share price is always net of them.

## Modes (`PositionMode`)

* **Parked** — no perp position. Everything sits in USDC, lent on Kamino via `lend_idle_usdc`. This is where the vault sits when funding has not cleared the entry line (+3.12%), and where it goes when an open short's funding falls below the exit line (−2.88%). (The enum variant is named `Idle`.)
* **Normal basis** — hold jitoSOL outright for staking yield, and short an equal amount of SOL-PERP on Phoenix (1× notional) with USDC as margin. Runs once funding clears the threshold by the ±3-point band. The threshold is the basis-vs-parked break-even, +0.12% at the current staking and lending rates: staking alone falls just short of lending, so the short has to earn a little before hedging beats parking. It moves with both rates. The on-chain floor ships at +12.
* **WindDown** — the shutdown mode, set by `init_wind_down`. No new deposits or positions; everyone redeems their share via `claim_wind_down`.
* **Dwell** — the minimum time the vault must stay in one mode before it can switch again. Default 12 hours.
* **Funding EMA** — a running average of the funding rate that weights recent readings more heavily (`funding_apr_smoothed_bps`). Updated on every `settle` and compared against `funding_threshold_*_bps` to pick the mode.

## Withdrawal

* **Liquidity buffer** — idle USDC the vault keeps on hand so withdrawals can pay out instantly. Default 10% of NAV.
* **Instant withdrawal** — `withdraw_instant`. One transaction, paid straight out of the buffer.
* **Queued withdrawal** — `request_withdrawal` burns your shares and locks the amount you're owed. Later, `process_withdrawal` pays it out and closes the request. Anyone can trigger that second step.
* **Queue cursor** — `queue_next_id` and `queue_processed_through` on the vault. Together they track which requests are still outstanding.

## On-chain accounts

A **PDA** is an account the program controls directly, with no private key behind it. An **ATA** is the standard account a wallet holds a particular token in.

* **Vault PDA** — seeds `[b"vault"]`. Signs every token operation, and is the authority over the ksUSD mint and all vault-owned token accounts.
* **WithdrawalRequest** — one account per queued request, at `[b"withdrawal_request", vault, request_id]`. Closed by `process_withdrawal`. Processed strictly in order via `queue_processed_through`.
* **Phoenix trader account** — the Phoenix Perps trader and subaccount PDAs the vault owns, set up through the Rise SDK builder path. Created by `enable_phoenix`.
* **Kamino lending cTokens** — the receipts for USDC lent on Kamino: `vault_lend_collateral_ata`.

## External protocols

"CPI" below means one Solana program calling another within a transaction, which is how the vault operates on these venues.

* **Phoenix Perps** — the on-chain perp exchange from Ellipsis Labs, with real two-sided funding. It's the v1 hedge venue. USDC margin goes in through **Ember**, and the vault calls it directly on-chain using the Rise SDK. Program `EtrnLzgbS7nMMy5fbD42kXiUzGg8XQzJ972Xtk1cjWih`.
* **Ember** — the program that turns USDC into Phoenix perp margin. Program `EMBERpYNE6ehWmXymZZS2skiFmCa9V5dp14e1iduM5qy`.
* **Kamino KLend** — the lending protocol the vault uses for USDC (`lend_idle_usdc`).
* **Jupiter V6** — a swap aggregator. Every USDC ↔ jitoSOL swap routes through it.
* **Pyth (pull oracles)** — the price source for SOL/USD and jitoSOL/USD. Every read is checked for staleness (5 min) and confidence (2%). Set via `set_oracles`.
* **Jito (jitoSOL)** — a liquid staking token. Its yield comes from staking rewards plus MEV tips, both baked into the jitoSOL/SOL exchange rate.

## Off-chain

* **Keeper** — the off-chain bot that runs the vault's routine instructions on a schedule. Its key is pinned as `authorized_keeper`, and it's the only signer that can open or close positions, move capital in and out of lending, or call `attest_nav`.
* **Cranker** — anyone who pays to run an instruction that needs no permission: `settle`, `process_withdrawal`, and `emergency_close` once tripped. One nuance on `settle`: anyone can call it to refresh NAV and the depeg guard, but only the keeper's call updates the funding signal that gates position entry.
* **Admin** — whoever holds the admin key. Required for `set_pause`, `update_params`, `transfer_admin`, and `collect_fees`. This becomes a multisig before launch.

## Backtest

* **Target APY** — **7.19% net** on the venue's own measured funding, with a worst drawdown of **−0.314%** through a month in which Phoenix funding averaged −14%. Fully loaded: already net of fees, trading costs, and the margin haircut. The window is 316 days, the whole life of the venue, so there is no through-cycle band to quote. Its last month, September 2026 (+22% funding), is the venue's best; ending a month earlier gives 5.86%.
* **Daily backtest** — daily figures over 2025-11-19 – 2026-09-30, every day Phoenix has quoted a SOL perp, covering the two modes v1 actually runs. Funding is Phoenix's own, unscaled. Method: [historical-simulation.md](/how-it-works/strategy-and-modes/historical-simulation).
* **Funding proxy** — not used. The backtest reads Phoenix's own funding history and applies no scale factor. A CEX proxy does not survive the comparison: over the 316 days both cover, Phoenix averaged +3.53% APR while Binance averaged −0.70%, and the two disagree on sign for weeks. Funding is set by which side of *Phoenix's* book is crowded.


# Security Model

ksUSD is one Anchor program, one vault account the program controls, and one token. There isn't much surface area to attack, which is deliberate.

***

## Access control

| Role          | Capabilities                                                                                                                                                                                                                                                                                                                     |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Admin**     | `initialize`, `enable_phoenix`, `enable_lending`, `set_oracles`, `set_pause`, `update_params`, `collect_fees`, `transfer_admin`, `accept_admin`, `reset_peak`, `init_wind_down`                                                                                                                                                  |
| **Keeper**    | `attest_nav`, `open_position`, `close_position`, `lend_idle_usdc`, `unlend_usdc`. Gated by **exact match** against `authorized_keeper`. Note the direction: `Pubkey::default()` (the post-`initialize` state) matches no signer, so these stay **blocked** until the admin pins a real key. It is not a permissionless fallback. |
| **Any user**  | `deposit`, `withdraw_instant`, `request_withdrawal`, `process_withdrawal`, `claim_wind_down` (during wind-down), `settle`, `emergency_close` (once tripped). None of these consult the keeper key.                                                                                                                               |
| **Vault PDA** | Signs every token operation for the vault. It's derived from the program, so there's no private key anyone could steal.                                                                                                                                                                                                          |

Admin control moves in two steps, `transfer_admin` then `accept_admin`, so it can't be handed to a wrong or unreachable address by a single mistake. Once mainnet is live the admin becomes a multisig, Squads or similar.

***

## Protections

| Protection               | Mechanism                                                                                                                                                                                                    |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Emergency pause          | Admin halt of new deposits + new positions; instant withdrawals stay open                                                                                                                                    |
| Wind-down                | Terminal `init_wind_down` blocks new state; users redeem pro-rata via `claim_wind_down`                                                                                                                      |
| Deposit cap              | `cached_nav_usdc + usdc_amount > deposit_cap_usdc` reverts; `0` fully pauses deposits                                                                                                                        |
| Bootstrap residual guard | First deposit reverts if vault USDC ATA is non-empty (`BootstrapResidualUsdc`) — prevents dilution griefing                                                                                                  |
| Oracle validation        | Pyth staleness (5 min) + confidence (2%) checks; revert on either                                                                                                                                            |
| LST depeg auto-pause     | `settle` reverts AND pauses the vault if jitoSOL/SOL deviates beyond `lst_depeg_bps`                                                                                                                         |
| Integer arithmetic       | `checked_add` / `checked_mul` everywhere; 128-bit intermediates for NAV math; no floating point                                                                                                              |
| Slippage protection      | Jupiter swaps gated by `max_swap_slippage_bps` (default 0.5%) plus explicit `min_*_out` arguments                                                                                                            |
| HWM monotonicity         | Performance fees never charged twice on the same gains; the HWM falls only by exactly what a fee collection pays out per share                                                                               |
| Drawdown guard           | `emergency_close` is callable by anyone once `peak − current ≥ emergency_close_dd_bps` AND observed across `consecutive_dd_settles_required` settles                                                         |
| Drawdown latency         | Single-tick drawdown reverts with `DrawdownTriggerLatent`                                                                                                                                                    |
| Mode-switch dwell        | `min_dwell_seconds` (default 12 h) between mode transitions — prevents ping-pong                                                                                                                             |
| Funding signal staleness | Opens revert with `FundingSignalStale` if the EMA hasn't been refreshed within `funding_max_staleness_seconds`                                                                                               |
| Funding signal integrity | `settle` is open to anyone, but only the authorized keeper's call updates the funding EMA. Otherwise any caller could steer the signal (or seed it outright on the first call) to force or block basis entry |
| Venue circuit breaker    | Opens revert with `PhoenixMarketNotActive` if SOL-PERP is halted, settling, or delisted                                                                                                                      |
| Position size caps       | The short is bounded by `max_position_base_lots` in absolute base lots (`PerpShortExceedsSizeCap`). There is no on-chain open-interest check; OI discipline is applied off-chain when that cap is set        |
| Funding rate sanity      | Venue-reported rates outside a hard sanity band revert with `FundingRateInsane`                                                                                                                              |
| NAV change cap           | `attest_nav` deltas bounded by `max_nav_change_bps_per_hour`                                                                                                                                                 |
| Withdrawal FIFO          | Strict FIFO order via `WithdrawalNotNextInQueue` guard; per-request price-at-process haircut so depositors never extract more than pro-rata                                                                  |

***

## Account-context layering (strategy instructions)

`open_position`, `close_position`, and `emergency_close` each call several other programs in a single transaction: Phoenix, Ember, Kamino, and Jupiter. Since every one of those needs its own set of accounts, the handler has to divide up one long list. It does that in three steps:

1. Takes the number of accounts per group as `u8` arguments.
2. Splits `remaining_accounts` using `checked_add(...).ok_or(InvalidParams)`, so an offset that would overflow reverts instead of wrapping around.
3. Hands each slice to the right helper, which then checks the accounts it was given.

The result is that the program never reads past the accounts it was actually handed, even if someone passes deliberately bad arguments. And each venue still validates its own accounts, so the vault isn't the only thing standing between a bad call and a bad outcome.

***

## Audit status

The program is **currently unaudited**. An audit is planned before mainnet with a top-tier Solana firm (Ottersec, Sec3, or Neodyme). The scope is small enough to audit properly: one Anchor crate and one state struct.

Internal pre-audit notes are in [the source](https://github.com/kamwithak/keystone-contracts/blob/main/docs/PRE_MAINNET_AUDIT.md).

**Don't deploy significant capital before the audit.**

***

## Reporting

Suspected vulnerabilities:

* Open a private GitHub security advisory on [github.com/kamwithak/keystone-contracts](https://github.com/kamwithak/keystone-contracts/security/advisories), **or**
* Contact the maintainer directly

A formal bug bounty stands up alongside the mainnet audit.

***

## Related

* [Whitepaper — Risk](/how-it-works/whitepaper#risks)
* [Fees](/start-here/fees) · [NAV & share pricing](/how-it-works/strategy-and-modes/nav-calculation)
* [Errors](/build-on-it/quick-start/errors) — every revert path enumerated


# Roadmap

**ksUSD in one line:** deposit USDC, receive and hold ksUSD, earn carry. The yield is jitoSOL staking plus perp funding when it pays, with USDC lending as the floor. No peg to defend, no position to manage.

This is the plain-English version of where we are and what's left before launch.

***

## How it earns

The vault holds two things at once:

* **Staked SOL (jitoSOL)**, which earns a staking yield.
* **A short SOL position** on a perp venue, which offsets most of SOL's price swings and often pays you to hold it. That payment is called funding.

The short is what turns a SOL-denominated yield into a dollar one, so you collect the staking yield with almost none of SOL's volatility, plus the funding when it's being paid. Staking accrues every day the hedge is on; funding swings, and over the backtest window it was the larger of the two.

When funding stops paying, the vault parks: it drops the short and holds plain USDC lent on Kamino until funding is worth it again. An on-chain signal decides when to switch and a bot does the work. You never touch it.

In v1 the hedge runs on Phoenix Perps, with margin posted through Ember.

> Backtested on Phoenix's own funding across every day the venue has existed, the worst drawdown was **−0.314%**, carried through a month in which funding averaged −14%. Yield: **7.19% net**. Staking is the steady part; funding is the swing. The window is 316 days, and its last month, September 2026 (+22% funding), is the venue's best; ending a month earlier gives 5.86%. Treat it as a young venue's record rather than a through-cycle one. *Simulated, not a promise.*

***

## Where we are

**The program is finished.** What's left is a soak test, an audit, and the money to pay for it.

We've run the whole money path on a copy of mainnet, against real protocol state, in both modes. Parked: deposit → lend → earn → redeem. And hedged: buy jitoSOL through Jupiter, open the Phoenix short, close it, unwind cleanly. jitoSOL staking (Jito), USDC lending (Kamino), and USDC↔jitoSOL swaps (Jupiter) are all wired and proven.

The last piece, finished on 23 August, was the hedge reading real Pyth price accounts rather than a test stub, so the rehearsal uses the same price plumbing mainnet will. The test suite also checks it *refuses* bad prices — stale ones, ones from the wrong feed, ones with too much uncertainty attached.

One step happens after we deploy rather than before: Phoenix has to switch on the vault's permission to post margin. Our contact there has agreed to do it once the program is live on mainnet. Until it happens the vault runs parked on Kamino lending, which is fully proven and is a real product on its own.

***

## Getting to mainnet

Two things, running in parallel:

1. **A security audit** by a top Solana firm. This is the hard gate before real money, and good firms book months out, so we're shortlisting now.
2. **A seed raise** ($200–500K) to fund the audit and runway. A DAO treasury pre-committing capital de-risks it and seeds day-one deposits.

When those clear, we deploy with a **$500k launch cap** and open an invite-only private beta.

### Why $500k

$500k is about the most the venue can hold today. We run a permanent one-directional short, so the cap is whichever of two limits binds first:

**Whichever is smaller: 15% of open interest, or a quarter of a median day's volume.**

On Phoenix's numbers measured 16 September, open interest binds, roughly twice as tight as volume. In early August it was the other way round, which is the point of taking whichever is tighter rather than picking one and trusting it.

Note that it uses the **median** day, not the average: a handful of spike days sit inside any 30-day window, and sizing off the mean would badly overstate what the book can actually take. And a **bigger cap would make the product worse.** If most of a large vault can't be hedged, the rest sits in lending and ksUSD becomes a Kamino deposit wearing a wrapper — all of the operational risk, none of the carry.

It also self-corrects: if our own size ever pushed funding below the line, the vault just parks, so it can't run itself into a loss.

*Measured live against the venue, never quoted from memory.*

***

## After launch

Once there's a real track record, two things scale it:

* **Composability.** Get ksUSD accepted as collateral, starting with Kamino, so holding it earns carry and unlocks borrowing. That's what makes deposits sticky. It's the sUSDe playbook.
* **Distribution.** A USDC↔ksUSD pool and Jupiter routing for one-click in and out, plus yield-marketplace listings and DAO-treasury allocations.

The cap ramps $500k → $1M → $5M → $25M, each step gated by that same rule, not by demand and not by a date.

**We grow with Phoenix.** That's the whole sizing policy. Open interest is the side that binds today, so each step up needs the venue's book to be correspondingly deeper. There is no second Solana perp venue with the depth to split the short across. Phoenix's SOL-PERP open interest has trended up over recent weeks but swings a lot week to week, so we treat it as a level to measure rather than a trend to extrapolate. We won't put a date on someone else's order book. The vault gets bigger exactly when the venue can hedge it.

***

## Timeline

| When                      | What                                                                                            |
| ------------------------- | ----------------------------------------------------------------------------------------------- |
| **Now**                   | Audit-firm shortlist · seed raise · anchor conversations · a 30-day hands-off run on devnet     |
| **Q3 2026**               | **Reached.** Both modes proven end-to-end on a copy of mainnet. Mainnet-ready pending the audit |
| **Q4 2026 – Q1 2027**     | Audit done · mainnet deploy at the $500k cap · private beta, invite-only                        |
| **H1 2027**               | Public launch · USDC↔ksUSD pool + Jupiter routing · first collateral listing                    |
| **When the venue allows** | $1M, then $5M → $25M — opened by Phoenix's depth, not by a date                                 |

Two clocks:

* **The dates** ride on the audit slot and the raise, not on the engineering — which is done.
* **The caps** don't ride on dates at all — they track Phoenix's open interest and volume, live.

So we won't quote a TVL target for a given quarter: we can promise what we ship and how we size, not how deep someone else's book gets.

***

## Not in v1

* Multiple staking tokens (mSOL, jupSOL): later.
* A second USDC lending venue: later. v1 is Kamino only, with no venue scaffolding in vault state.

***

## Related

* [Download the full roadmap (PDF)](https://www.keystonefi.xyz/roadmap.pdf)
* [Strategy & Modes](/how-it-works/strategy-and-modes) · [Whitepaper](/how-it-works/whitepaper) · [Version history](/reference/versions)


# Version History

What shipped when, newest first.

* Tracks meaningful releases of the ksUSD vault program + surrounding docs / scripts
* Older entries cover the legacy multi-strategy architecture, retained for reference
* Canonical product: single-vault ksUSD design as of v2.0

***

## v2.1 — Jun 2026 · *current*

**Venue pivot to Phoenix Perps + two-mode scope.** Design changes for the v1 mainnet path.

### Venue

* Perp venue: **Phoenix Perps (Ellipsis Labs)** — program `EtrnLzgbS7nMMy5fbD42kXiUzGg8XQzJ972Xtk1cjWih`, USDC margin via Ember, on-chain CPI via the Rise SDK.
* USDC margin posted via the **Ember** program (`EMBERpYNE6ehWmXymZZS2skiFmCa9V5dp14e1iduM5qy`); integration is on-chain CPI using the **Rise SDK** (`github.com/Ellipsis-Labs/rise-public`).

### Architecture

* jitoSOL is held **unlevered** as the spot leg for staking yield; **USDC** is the perp margin. No LST is ever posted as perp collateral.

### Modes

* v1 ships **two modes — normal basis + parked** — with transitions **automated on-chain**: the smoothed funding signal plus a keeper **dynamic threshold with a ±3-point hysteresis band** (lending-vs-staking spread, floored on-chain at the +12 bps break-even) decides the mode and the keeper bot executes the switch, no manual intervention. The band covers the round-trip switch cost and prevents whipsaw.

### Backtest

* Recut on the Phoenix venue's own funding history, unscaled: **−0.314% max drawdown**, **7.19% net**, fully loaded, over the 316 days the SOL perp has existed. Full method and caveats: [`reference/historical-simulation.md`](/how-it-works/strategy-and-modes/historical-simulation).

***

## v2.0 — May 2026

**The ksUSD pivot.** Wholesale repositioning and code rewrite.

### Positioning

* Current canonical framing: *"Keystone Finance is the carry coordination layer for Solana."*
* Superseded: *"Keystone Finance coordinates carry across Solana's DeFi ecosystem."*
* Earlier framings retired: "on-chain analog of a multi-strategy hedge fund", "Layer 1 / Layer 2 architecture", "three risk profiles", "monetary layer", "productive reserve asset"

### Program

* Single Anchor program: `keystone_finance` (program ID `E7tpCcxtvuTXLAckBGWb1AsndpLQ1Y9hQA3iGYSXz2vJ` on devnet)
* Single state struct: `Vault` PDA at seeds `[b"vault"]` (replaces legacy `FundState` + `PortfolioState` hierarchy)
* Single share mint: `ksUSD` (6 decimals) — replaces `ksALPHA`, `ksNEUTRAL`, `ksDEFENSE`, `ksCORE`
* Two internal modes — normal basis and idle — chosen automatically by the SOL-PERP funding rate
* An on-chain perp venue (replaces Jupiter Perps in the legacy Neutral fund)
* Full entry-point list: [Instructions](/build-on-it/quick-start/instructions)

### Fee structure

* Management fee: **0%** (was 0.5% / yr on legacy Alpha & Neutral).
* Performance fee: **20% above HWM** (unchanged).
* Withdrawal fee: **0%** on both instant and queued paths.

### Withdrawal queue

* Two-path withdrawal: `withdraw_instant` (from liquidity buffer) and `request_withdrawal` + `process_withdrawal` (queued). Replaces the legacy single `withdraw` path.

### Backtest

* Established the canonical method: daily resolution, 7-day mean funding with a ±3-point hysteresis band for mode classification. Superseded in detail by the recut onto measured Phoenix funding; see [`reference/historical-simulation.md`](/how-it-works/strategy-and-modes/historical-simulation).

### Docs

* New whitepaper at `gitbook/reference/whitepaper.md` (v2.0) — single-vault design, full NAV math, security model, risk disclosures.
* Marketing site (`keystone-marketing/`) rebuilt around ksUSD with a single Performance chart sourced from the canonical backtest.
* Investor memo, PRD, and outreach summary at `docs/KSUSD_*.md` updated to v0.4.

### Breaking changes

* All legacy program IDs (`keystoneAlpha`, `keystoneDefense`, `keystoneCore`) are no longer deployed. The on-chain footprint is now one program.
* `ksCORE` / `ksALPHA` / `ksNEUTRAL` / `ksDEFENSE` mints are unsupported. Integrators should consume `ksUSD` only.
* `rebalance`, `migrate_portfolio`, and all multi-fund admin instructions are gone.

***

## Pre-pivot history (legacy)

Pre-v2.0 covered the multi-strategy design:

* **Keystone Alpha** — directional LST accumulation
* **Keystone Neutral** — basis carry on Jupiter Perps
* **Keystone Defense** — JupSOL baseline + dislocation deployment
* **Keystone Core** — portfolio orchestration with ksCORE

Detailed entries are retained in git history; active narrative is v2.0+.

**Key milestones:**

* **v1.x** — multi-strategy architecture in development; Jupiter Perps as the perp venue
* **v0.11.5** (Apr 2026) — last release of the multi-strategy design; portfolio rebalancing live on devnet
* **v0.10.0** — `deploy_capital` consolidated with auto-unpark; `unpark_capital` retired

For the historical narrative and per-version technical notes, see commits on `main` prior to the May 2026 pivot.


# Team

## Kamran Choudhry — Founder

I'm a full-stack engineer with 7+ years building in DeFi and Web3. I studied Computer Science at McGill (with a minor in Economics), and I've spent most of my career shipping trading and on-chain infrastructure.

Before Keystone, I built front-end and full-stack systems across the space:

* **Sei Labs** — full-stack engineering on DeFi infrastructure
* **Vertex Protocol** — built the trading app that grew the exchange from $0 to $100M+ peak TVL
* **Insrt Labs** — full-stack GameFi
* **Charged Particles** — front-end for NFT products

I work across TypeScript, Rust, and Solana programs, with a focus on product engineering, DEX/AMM design, and smart-contract security. Keystone is where all of that comes together.

***

## Get in touch

* **Website** — [kamwithak.github.io](https://kamwithak.github.io/)
* **X / Twitter** — [@kamranwithak](https://x.com/kamranwithak)


