# Instructions Reference

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

> Source: [`programs/keystone-finance/src/lib.rs`](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_drift(sub_account_id, name)` | Admin            | One-time: calls Drift's `initialize_user_stats` + `initialize_user` to create the vault's Drift sub-account. Required before any perp position can be opened. |
| `enable_reverse(tag, id)`            | Admin            | One-time: calls Kamino's obligation init. Required only if reverse-basis mode will ever be used; vault can run normal + parked without it.                    |

### `InitializeParams` defaults

| Field                           | Default                     | Meaning                                             |
| ------------------------------- | --------------------------- | --------------------------------------------------- |
| `liquidity_buffer_bps`          | 1\_000 (10%)                | Idle USDC kept on-vault for instant withdrawals     |
| `funding_threshold_normal_bps`  | +200 (+2% APR)              | Open normal basis above this funding rate           |
| `funding_threshold_reverse_bps` | −1\_200 (−12% APR)          | Open reverse basis below this funding rate          |
| `perf_fee_bps`                  | 2\_000 (20%)                | Performance fee above HWM                           |
| `reserve_skim_bps`              | 500 (5%)                    | Of accrued perf fees, routed to reserve fund        |
| `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`              | 1\_000\_000\_000\_000 ($1M) | Cached-NAV cap on new deposits                      |
| `drift_subaccount_id`           | 0                           | Drift sub-account index                             |
| `drift_perp_market_index`       | 0                           | Drift perp market — `0 = SOL-PERP` on mainnet       |

***

## User flow (anyone)

| Instruction                  | Description                                                                                                                                                         |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `deposit(usdc_amount)`       | Transfer USDC to the vault, mint ksUSD at current share price. → [Deposit](/keystone-finance/deposit.md)                                                            |
| `withdraw_instant(shares)`   | Burn ksUSD, receive USDC from the liquidity buffer. Reverts with `InsufficientLiquidityBuffer` if not enough idle USDC. → [Withdraw](/keystone-finance/withdraw.md) |
| `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.                                                              |

***

## Strategy (keeper-cranked, permissionless)

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

| Instruction                                                                                                                                                                        | Description                                                                                                                                                                |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open_position(usdc_amount, perp_short_base_amount, jupiter_swap_data, jupiter_account_count, drift_deposit_account_count)`                                                        | **Normal basis open.** USDC → jitoSOL via Jupiter → Drift deposit (cross-margin collateral) → short SOL-PERP at 1× notional.                                               |
| `close_position(perp_close_account_count, settle_account_count, drift_withdraw_account_count, jupiter_swap_data)`                                                                  | **Normal basis close.** Reduce-only long order → `settle_pnl` → withdraw jitoSOL → swap jitoSOL→USDC.                                                                      |
| `open_reverse(usdc_collateral_amount, jitosol_borrow_amount, perp_long_base_amount, jupiter_swap_data, refresh_account_count, jupiter_account_count, drift_deposit_account_count)` | **Reverse basis open.** USDC → Kamino collateral → refresh → borrow jitoSOL → Jupiter sell → Drift deposit USDC → long SOL-PERP.                                           |
| `close_reverse(perp_close_account_count, settle_account_count, drift_withdraw_account_count, jupiter_account_count, jupiter_swap_data)`                                            | **Reverse basis close.** Reduce-only short order → settle → withdraw USDC → swap USDC→jitoSOL → repay Kamino (`u64::MAX` auto-clamp) → refresh → withdraw USDC collateral. |
| `settle()`                                                                                                                                                                         | Read Drift SOL-PERP funding, call `settle_pnl` if a position is open, refresh peak share price, log drawdown if guard tripped. Permissionless.                             |
| `emergency_close(perp_close_account_count, drift_withdraw_account_count, jupiter_swap_data)`                                                                                       | Force close on drawdown breach or while vault is paused. Auto-pauses vault on exit. Permissionless once tripped.                                                           |

***

## 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)` | Two-step admin handover to a multisig or successor.                                   |
| `collect_fees()`            | Mint performance-fee shares (above HWM) to the treasury; route reserve skim.          |

***

## Account-context groups for `remaining_accounts`

Strategy instructions pack multiple downstream CPIs (Drift + Kamino + Jupiter) into one transaction. Each group's account list is documented in the handler source — link below per instruction.

| Instruction       | Groups                                                                                                         |
| ----------------- | -------------------------------------------------------------------------------------------------------------- |
| `open_position`   | Jupiter swap → Drift deposit → Drift place\_perp\_order                                                        |
| `close_position`  | place\_perp\_order (reduce-only) → settle\_pnl → Drift withdraw → Jupiter swap                                 |
| `open_reverse`    | Kamino refresh → Jupiter swap (jitoSOL→USDC) → Drift deposit → Drift place\_perp\_order                        |
| `close_reverse`   | place\_perp\_order (reduce-only) → settle\_pnl → Drift withdraw → Jupiter swap → Kamino refresh+repay+withdraw |
| `settle`          | Drift settle\_pnl margin re-eval accounts (when position open)                                                 |
| `emergency_close` | place\_perp\_order → Drift withdraw → Jupiter swap                                                             |

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

***

## Errors

See [Errors](/for-developers/errors.md) for the full `KsusdError` enum and exit codes.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.keystonefi.xyz/for-developers/instructions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
