> For the complete documentation index, see [llms.txt](https://docs.keystonefi.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.keystonefi.xyz/build-on-it/quick-start/errors.md).

# 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                                                                                                                                  |
| `PositionNotOpen`         | Calling `add_margin` while Parked                                                                                                                                                         |
| `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 `close_position` / `emergency_close` with no active position                                                                                                                      |
| `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 / 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` / `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 / un-pause blocked |
| `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.md) · [Account structure](/build-on-it/quick-start/accounts.md) · [Events](/build-on-it/quick-start/events.md)
