> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hadron.fi/llms.txt
> Use this file to discover all available pages before exploring further.

# Pool Functions

> Complete guide to creating and using Hadron in Rust.

## Initializing a new pool

### Hadron::initialize

Builds all the instructions needed to create a new on-chain pool: account allocation + initialization. Returns the instructions, derived pool address, and seed.

The allocate instruction(s) must be confirmed **before** sending the initialize instruction (they can be in separate transactions, or together if they fit).

```rust theme={null}
use hadron_sdk_v2::hadron::Hadron;
use hadron_sdk_v2::types::InitializeParams;
use hadron_sdk_v2::helpers::math::to_q32;
use hadron_sdk_v2::constants::HADRON_PROGRAM_ID;

let (instructions, pool_address, seed) = Hadron::initialize(&payer, &InitializeParams {
    seed: None,                              // auto-generated
    mint_x,
    mint_y,
    authority: payer,
    creator: None,                           // defaults to `authority`
    initial_midprice_q32: to_q32(1.0),       // midprice = 1.0
    lp_self_rotate: false,                   // false = custodial (admin can rotate LP authorities)
    max_prefab_slots: None,                  // default: 2
    max_curve_points: None,                  // default: 16
    combined_factor_max_q32: None,           // defaults to Q32_ONE (1.0)
    token_program_x: None,                   // default: SPL Token
    token_program_y: None,                   // default: SPL Token
}, &HADRON_PROGRAM_ID);

// Send the instructions (group into transactions as needed)
```

| Param                            | Type             | Description                                                                                                                      |
| -------------------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `payer`                          | `&Pubkey`        | Transaction fee payer and account funder                                                                                         |
| `params.seed`                    | `Option<u64>`    | Pool seed. Auto-generated if `None`. Allows multiple pools per token pair.                                                       |
| `params.mint_x`                  | `Pubkey`         | Base token mint                                                                                                                  |
| `params.mint_y`                  | `Pubkey`         | Quote token mint                                                                                                                 |
| `params.authority`               | `Pubkey`         | Pool authority (manages curves, oracle, state)                                                                                   |
| `params.creator`                 | `Option<Pubkey>` | Creator of the curve prefabs account (must sign `AllocateCurvePrefabs`). Defaults to `authority`.                                |
| `params.initial_midprice_q32`    | `u64`            | Starting midprice in Q32 fixed-point format                                                                                      |
| `params.lp_self_rotate`          | `bool`           | `false` = custodial (admin can rotate deposit/withdraw authorities); `true` = only the LP role-holder can. Immutable after init. |
| `params.token_program_x`         | `Option<Pubkey>` | Token program for X (default: SPL Token)                                                                                         |
| `params.token_program_y`         | `Option<Pubkey>` | Token program for Y (default: SPL Token)                                                                                         |
| `params.max_prefab_slots`        | `Option<u8>`     | Max curve prefab slots (default: 2)                                                                                              |
| `params.max_curve_points`        | `Option<u8>`     | Max points per curve (default: 16)                                                                                               |
| `params.combined_factor_max_q32` | `Option<u64>`    | Hard ceiling on the combined price×risk factor. Defaults to `Q32_ONE` (1.0).                                                     |

**Returns** `(Vec<Instruction>, Pubkey, u64)` — instructions, pool address, seed

<Note>
  With default parameters the CurvePrefabs account is \~15 KB, so two allocate instructions are returned (Solana's single-instruction realloc limit is 10 KB). Send the allocates first, then the initialize.
</Note>

***

## Loading an existing pool

### Hadron::from\_accounts

Create a `Hadron` instance from raw account data bytes. This is sync — no RPC calls. You fetch the accounts however you like (RPC, Geyser, etc.) and pass the raw data in.

```rust theme={null}
use hadron_sdk_v2::hadron::Hadron;

let pool = Hadron::from_accounts(
    pool_address,
    &config_data,
    &oracle_data,
    &curve_meta_data,
    &curve_prefabs_data,
    &fee_config_data,
)?;
```

| Param                | Type     | Description                                                                  |
| -------------------- | -------- | ---------------------------------------------------------------------------- |
| `pool_address`       | `Pubkey` | The pool's on-chain address                                                  |
| `config_data`        | `&[u8]`  | Raw config account data                                                      |
| `oracle_data`        | `&[u8]`  | Raw midprice oracle account data                                             |
| `curve_meta_data`    | `&[u8]`  | Raw curve metadata account data                                              |
| `curve_prefabs_data` | `&[u8]`  | Raw curve prefabs account data                                               |
| `fee_config_data`    | `&[u8]`  | Raw fee config account data (pool-specific when `has_pool_fee`, else global) |

**Returns** `Result<Hadron, HadronSdkError>`

<Tip>
  Enable the `rpc` feature (`cargo add hadron-sdk-v2 --features rpc`) for a convenience
  `Hadron::load(&rpc_client, &pool_address)` method that fetches accounts over RPC.
</Tip>

***

## Reading pool state

### get\_midprice

Current midprice decoded from the on-chain Q32 oracle value.

```rust theme={null}
let mid = pool.get_midprice(); // e.g. 1.0023
```

**Returns** `f64`

### get\_spread\_factor / get\_spread\_bps

Current spread factor and basis-point equivalent.

```rust theme={null}
let factor = pool.get_spread_factor(); // e.g. 0.9995
let bps    = pool.get_spread_bps();    // e.g. 5.0
```

**Returns** `f64`

### get\_active\_curve\_slots

Returns the slot index for each active curve.

```rust theme={null}
let slots = pool.get_active_curve_slots();
// ActiveCurveSlots { price_bid: 0, price_ask: 0, risk_bid: 0, risk_ask: 0 }
```

**Returns** `ActiveCurveSlots`

### get\_active\_curves

Decodes and returns all four active curves from prefab data.

```rust theme={null}
let curves = pool.get_active_curves()?;
// curves.price_bid.points, curves.price_ask.points, etc.
```

**Returns** `Result<ActiveCurves, HadronSdkError>`

Each `CurveSide` contains:

| Field                   | Type                     | Description                       |
| ----------------------- | ------------------------ | --------------------------------- |
| `num_points`            | `u8`                     | Number of curve points            |
| `default_interpolation` | `Interpolation`          | Default interpolation mode        |
| `x_mode`                | `CurveXMode`             | X-axis mode (Native or Alternate) |
| `risk_mode`             | `RiskMode`               | Virtual or Integrated             |
| `points`                | `Vec<DecodedCurvePoint>` | The curve point array             |

### get\_curve\_slot

Decode a specific curve slot by type and index.

```rust theme={null}
use hadron_sdk_v2::types::CurveType;

let curve = pool.get_curve_slot(CurveType::PriceBid, 1)?;
```

| Param        | Type        | Description                                         |
| ------------ | ----------- | --------------------------------------------------- |
| `curve_type` | `CurveType` | One of `PriceBid`, `PriceAsk`, `RiskBid`, `RiskAsk` |
| `slot`       | `u8`        | Slot index                                          |

**Returns** `Result<CurveSide, HadronSdkError>`

***

## Building instructions

All methods below return an `Instruction`. They do **not** send a transaction — add the instruction to a `Transaction` and submit it yourself.

### swap

Build a swap instruction.

```rust theme={null}
use hadron_sdk_v2::types::SwapParams;

let ix = pool.swap(&user, &SwapParams {
    is_x: true,               // true = sell X for Y, false = sell Y for X
    amount_in: 1_000_000,
    min_out: 0,                // set > 0 for slippage protection
    fee_recipient,
    expiration: None,
});
```

| Param                  | Type          | Description                            |
| ---------------------- | ------------- | -------------------------------------- |
| `user`                 | `&Pubkey`     | The user's wallet                      |
| `params.is_x`          | `bool`        | Direction: `true` = X→Y, `false` = Y→X |
| `params.amount_in`     | `u64`         | Input amount in token atoms            |
| `params.min_out`       | `u64`         | Minimum output (slippage protection)   |
| `params.fee_recipient` | `Pubkey`      | Address to receive fees                |
| `params.expiration`    | `Option<i64>` | Optional slot expiration               |

### deposit

Build a deposit instruction.

```rust theme={null}
use hadron_sdk_v2::types::DepositParams;

let ix = pool.deposit(&user, &DepositParams {
    amount_x: 1_000_000,
    amount_y: 2_000_000,
    expiration: None,
});
```

| Param               | Type          | Description                             |
| ------------------- | ------------- | --------------------------------------- |
| `user`              | `&Pubkey`     | The user's wallet                       |
| `params.amount_x`   | `u64`         | Amount of token X to deposit (in atoms) |
| `params.amount_y`   | `u64`         | Amount of token Y to deposit (in atoms) |
| `params.expiration` | `Option<i64>` | Optional slot expiration                |

### withdraw

Build a withdraw instruction.

```rust theme={null}
use hadron_sdk_v2::types::WithdrawParams;

let ix = pool.withdraw(&user, &WithdrawParams {
    amount_x: 500_000,
    amount_y: 1_000_000,
    expiration: None,
});
```

| Param               | Type          | Description                              |
| ------------------- | ------------- | ---------------------------------------- |
| `user`              | `&Pubkey`     | The user's wallet                        |
| `params.amount_x`   | `u64`         | Amount of token X to withdraw (in atoms) |
| `params.amount_y`   | `u64`         | Amount of token Y to withdraw (in atoms) |
| `params.expiration` | `Option<i64>` | Optional slot expiration                 |

***

## Curve management

### set\_curve

Write a price curve to a prefab slot.

```rust theme={null}
use hadron_sdk_v2::types::*;
use hadron_sdk_v2::helpers::math::to_q32;

let ix = pool.set_curve(&authority, &SetCurveParams {
    side: Side::Bid,
    default_interpolation: Interpolation::Linear,
    points: vec![
        SetCurvePointInput {
            amount_in: 100_000,
            price_factor_q32: to_q32(0.99),
            interpolation: None,
            params: None,
        },
        SetCurvePointInput {
            amount_in: 500_000,
            price_factor_q32: to_q32(0.95),
            interpolation: None,
            params: None,
        },
    ],
    slot: Some(0),
    x_mode: None,
});
```

| Param                          | Type                      | Description                                                                                       |
| ------------------------------ | ------------------------- | ------------------------------------------------------------------------------------------------- |
| `authority`                    | `&Pubkey`                 | Pool authority                                                                                    |
| `params.side`                  | `Side`                    | `Bid` or `Ask`                                                                                    |
| `params.default_interpolation` | `Interpolation`           | `Step`, `Linear`, `MarginalStep`, `Hyperbolic`, `Quadratic`, `Cubic`                              |
| `params.points`                | `Vec<SetCurvePointInput>` | Array of curve points with `amount_in`, `price_factor_q32`, optional `interpolation` and `params` |
| `params.slot`                  | `Option<u8>`              | Target prefab slot (default: 0)                                                                   |
| `params.x_mode`                | `Option<CurveXMode>`      | X-axis mode                                                                                       |

### set\_risk\_curve

Write a risk curve using percent-of-vault x-axis.

| Param                          | Type                          | Description                                          |
| ------------------------------ | ----------------------------- | ---------------------------------------------------- |
| `authority`                    | `&Pubkey`                     | Pool authority                                       |
| `params.side`                  | `Side`                        | `Bid` or `Ask`                                       |
| `params.default_interpolation` | `Interpolation`               | Interpolation mode                                   |
| `params.points`                | `Vec<SetRiskCurvePointInput>` | Points with `pct_base_q32`, `price_factor_q32`, etc. |
| `params.slot`                  | `Option<u8>`                  | Target prefab slot                                   |
| `params.x_mode`                | `Option<CurveXMode>`          | X-axis mode                                          |
| `params.risk_mode`             | `Option<RiskMode>`            | `Virtual` or `Integrated`                            |

### set\_risk\_curve\_absolute

Write a risk curve using absolute token amounts on the x-axis.

| Param                          | Type                                  | Description                                           |
| ------------------------------ | ------------------------------------- | ----------------------------------------------------- |
| `authority`                    | `&Pubkey`                             | Pool authority                                        |
| `params.side`                  | `Side`                                | `Bid` or `Ask`                                        |
| `params.default_interpolation` | `Interpolation`                       | Interpolation mode                                    |
| `params.points`                | `Vec<SetRiskCurveAbsolutePointInput>` | Points with `vault_balance`, `price_factor_q32`, etc. |
| `params.slot`                  | `Option<u8>`                          | Target prefab slot                                    |
| `params.risk_mode`             | `Option<RiskMode>`                    | `Virtual` or `Integrated`                             |

### switch\_price\_curve / switch\_risk\_curve

Activate a previously written curve slot (hot path — no curve data uploaded).

```rust theme={null}
let ix1 = pool.switch_price_curve(&authority, &SwitchCurveParams { sequence: 1, side: Side::Bid, slot: 1 });
let ix2 = pool.switch_risk_curve(&authority, &SwitchCurveParams { sequence: 1, side: Side::Ask, slot: 2 });
```

| Param             | Type      | Description                                                                                                 |
| ----------------- | --------- | ----------------------------------------------------------------------------------------------------------- |
| `authority`       | `&Pubkey` | Pool authority                                                                                              |
| `params.sequence` | `u64`     | Monotonic ordering guard. Must be ≥ the pool's current switch sequence (`pool.curve_meta.switch_sequence`). |
| `params.side`     | `Side`    | `Bid` or `Ask`                                                                                              |
| `params.slot`     | `u8`      | Slot to activate                                                                                            |

### submit\_curve\_updates / apply\_curve\_updates

Two-step batched curve editing. Submit a list of point edits, then apply them.

```rust theme={null}
// `sequence` must be >= the CurveUpdates account's current sequence (monotonic guard).
let ix1 = pool.submit_curve_updates(&authority, 1, &[
    CurveUpdateOp {
        curve_type: CurveType::PriceBid,
        op_kind: CurveUpdateOpKind::Edit,
        point_index: 0,
        interpolation: Interpolation::Linear,
        amount_in: 200_000,
        price_factor_q32: to_q32(0.98),
        params: [0; 4],
        target_slot: 0,      // active slot this op targets — apply rejects on mismatch
        expected_x_in: 0,    // expected current x_in at point_index (ignored for Add)
    },
]);
let ix2 = pool.apply_curve_updates(&authority);
```

***

## Oracle management

### update\_midprice

```rust theme={null}
use hadron_sdk_v2::types::UpdateMidpriceParams;

let ix = pool.update_midprice(&authority, &UpdateMidpriceParams {
    midprice_q32: to_q32(1.05),
    sequence: None,
});
```

| Param                 | Type          | Description                           |
| --------------------- | ------------- | ------------------------------------- |
| `params.midprice_q32` | `u64`         | New midprice in Q32 format            |
| `params.sequence`     | `Option<u64>` | Optional sequence number for ordering |

### update\_base\_spread

```rust theme={null}
use hadron_sdk_v2::types::UpdateBaseSpreadParams;

let ix = pool.update_base_spread(&authority, &UpdateBaseSpreadParams {
    spread_factor_q32: spread_bps_to_q32(5), // 5 bps
    sequence: None,
});
```

| Param                      | Type          | Description                                                         |
| -------------------------- | ------------- | ------------------------------------------------------------------- |
| `params.spread_factor_q32` | `u64`         | Spread discount factor in Q32 (e.g. `spread_bps_to_q32(5)` = 5 bps) |
| `params.sequence`          | `Option<u64>` | Optional sequence number                                            |

### update\_midprice\_and\_base\_spread

Atomic update of both values in a single instruction.

```rust theme={null}
use hadron_sdk_v2::types::UpdateMidpriceAndBaseSpreadParams;

let ix = pool.update_midprice_and_base_spread(&authority, &UpdateMidpriceAndBaseSpreadParams {
    midprice_q32: to_q32(1.05),
    spread_factor_q32: spread_bps_to_q32(5),
    sequence: None,
});
```

***

## Admin

### nominate\_authority / accept\_authority

Two-step authority transfer.

```rust theme={null}
use hadron_sdk_v2::types::NominateAuthorityParams;

let ix1 = pool.nominate_authority(&authority, &NominateAuthorityParams {
    new_authority: new_pk,
    expiry_slot: 300_000_000,
});
// ... new_authority signs:
let ix2 = pool.accept_authority(&new_pk);
```

### set\_pool\_state

```rust theme={null}
use hadron_sdk_v2::types::{SetPoolStateParams, PoolState};

let ix = pool.set_pool_state(&authority, &SetPoolStateParams {
    new_state: PoolState::Paused,
});
```

States: `Uninitialized`, `Initialized`, `Paused`, `RejectSwaps`, `Closed` (set via `close_pool`). `set_pool_state` only accepts `Initialized`, `Paused`, or `RejectSwaps`.

### update\_delta\_staleness

```rust theme={null}
use hadron_sdk_v2::types::UpdateDeltaStalenessParams;

let ix = pool.update_delta_staleness(&authority, &UpdateDeltaStalenessParams {
    delta_staleness: 150,
});
```

### close\_pool

Closes the pool and reclaims rent. Requires authority and all vaults to be empty.

```rust theme={null}
let ix = pool.close_pool(&authority);
```

***

## Properties

These are available on any `Hadron` instance:

| Property                  | Type                    | Description                                                |
| ------------------------- | ----------------------- | ---------------------------------------------------------- |
| `pool.program_id`         | `Pubkey`                | Program ID                                                 |
| `pool.pool_address`       | `Pubkey`                | The pool's on-chain address                                |
| `pool.addresses`          | `PoolAddresses`         | All derived PDA addresses for this pool                    |
| `pool.config`             | `DecodedConfig`         | Decoded config account data                                |
| `pool.oracle`             | `DecodedMidpriceOracle` | Decoded oracle data                                        |
| `pool.curve_meta`         | `DecodedCurveMeta`      | Decoded curve metadata                                     |
| `pool.curve_prefabs_data` | `Vec<u8>`               | Raw curve prefabs data (decode with `get_active_curves()`) |
