# LB Pair Module

#### Structs

**`LBPair<X, Y>`**

```move
struct LBPair<phantom X, phantom Y> has key, store {
    id: UID,
    is_pause: bool,
    bin_step: u16,
    parameters: PairParameters,
    protocol_fee_x: u64,
    protocol_fee_y: u64,
    bin_manager: BinManager,
    oracle: Oracle,
    position_manager: LBPositionManager,
    balance_x: Balance<X>,
    balance_y: Balance<Y>,
    rewarder_manager: RewarderManager,
    global_reward_state: GlobalRewardState,
}
```

* **Purpose**: Core trading pair implementation

**`GlobalRewardState`**

```move
struct GlobalRewardState has store {
    reward_per_fee_cumulative: vector<u128>,        
    total_fees_ever: u128,
    last_update_time: u64,
}
```

* **Purpose**: Tracks fees for reward distribution

**`FlashLoanReceipt`**

```move
struct FlashLoanReceipt {
    pool_id: ID,
    loan_x: bool,
    amount: u64,
    fee_amount: u64,
}
```

* **Purpose**: Receipt for flash loan repayment validation

#### Events

**`SwapEvent`**

```move
struct SwapEvent has copy, drop {
    sender: address,
    pair: ID,
    id_before: u32,
    id_after: u32,
    swap_for_y: bool,
    amounts_in_x: u64,
    amounts_in_y: u64,
    amounts_out_x: u64,
    amounts_out_y: u64,
    volatility_accumulator: u32,
    total_fees_x: u64,
    total_fees_y: u64,
    protocol_fees_x: u64,
    protocol_fees_y: u64,
    current_bin: Bin,
}
```

* **Emitted**: When swap is executed

**`CollectedProtocolFeesEvent`**

```move
struct CollectedProtocolFeesEvent has copy, drop {
    fee_recipient: address,
    protocol_fees_x: u64,
    protocol_fees_y: u64,
}
```

* **Emitted**: When protocol fees are collected

**`OracleLengthIncreasedEvent`**

```move
struct OracleLengthIncreasedEvent has copy, drop {
    sender: address,
    new_length: u16,
}
```

* **Emitted**: When oracle capacity is increased

**`ForcedDecayEvent`**

```move
struct ForcedDecayEvent has copy, drop {
    sender: address,
    id_reference: u32,
    volatility_reference: u32,
}
```

* **Emitted**: When volatility decay is forced

**`StaticFeeParametersSetEvent`**

```move
struct StaticFeeParametersSetEvent has copy, drop {
    sender: address,
    base_factor: u32,
    filter_period: u16,
    decay_period: u16,
    reduction_factor: u16,
    variable_fee_control: u32,
    protocol_share: u16,
    max_volatility_accumulator: u32,
}
```

* **Emitted**: When fee parameters are updated

**`CompositionFeesEvent`**

```move
struct CompositionFeesEvent has copy, drop {
    id: u32,
    fee_x: u64,
    fee_y: u64,
}
```

* **Emitted**: When composition fees are charged

**`FeesCollectedEvent`**

```move
struct FeesCollectedEvent has copy, drop {
    position: ID,
    bin_ids: vector<u32>,
    amounts_x: vector<u64>,
    amounts_y: vector<u64>,
}
```

* **Emitted**: When position fees are collected

**`RewarderAddedEvent`**

```move
struct RewarderAddedEvent has copy, drop {
    pool: ID,
    rewarder_type: TypeName,
}
```

* **Emitted**: When new rewarder is added

**`RewarderEmissionUpdatedEvent`**

```move
struct RewarderEmissionUpdatedEvent has copy, drop {
    pool: ID,
    rewarder_type: TypeName,
    emissions_per_second: u128,
}
```

* **Emitted**: When emission rate is updated

**`RewardsCollectedEvent`**

```move
struct RewardsCollectedEvent has copy, drop {
    pool: ID,
    bucket_id: ID,
    reward_type: TypeName,
    amount: u64,
}
```

* **Emitted**: When rewards are collected

**`FeeParametersQueriedEvent`**

```move
struct FeeParametersQueriedEvent has copy, drop {
    base_factor: u32,
    filter_period: u16,
    decay_period: u16,
    reduction_factor: u16,
    variable_fee_control: u32,
    protocol_share: u16,
    max_volatility_accumulator: u32,
    volatility_accumulator: u32,
    volatility_reference: u32,
    id_reference: u32,
    time_of_last_update: u64,
}
```

* **Emitted**: When fee parameters are queried

**`OracleParametersQueriedEvent`**

```move
struct OracleParametersQueriedEvent has copy, drop {
    sample_lifetime: u8,
    size: u16,
    active_size: u16,
    last_updated: u64,
    first_timestamp: u64,
}
```

* **Emitted**: When oracle parameters are queried

**`OracleSampleQueriedEvent`**

```move
struct OracleSampleQueriedEvent has copy, drop {
    time: u64,
    cumulative_id: u64,
    cumulative_volatility: u64,
    cumulative_bin_crossed: u64,
}
```

* **Emitted**: When oracle sample is queried

**`PriceFromIdQueriedEvent`**

```move
struct PriceFromIdQueriedEvent has copy, drop {
    id: u32,
    price: u128,
}
```

* **Emitted**: When price is calculated from ID

**`IdFromPriceQueriedEvent`**

```move
struct IdFromPriceQueriedEvent has copy, drop {
    price: u128,
    id: u32,
}
```

* **Emitted**: When ID is calculated from price

**`FlashLoanEvent`**

```move
struct FlashLoanEvent has copy, drop {
    pool: ID,
    loan_x: bool,
    amount: u64,
    fee_amount: u64,
}
```

* **Emitted**: When flash loan is taken

**`OpenPositionEvent`**

```move
struct OpenPositionEvent has copy, drop {
    pair: ID,
    position: ID,
    owner: address,
}
```

* **Emitted**: When position is opened

**`ClosePositionEvent`**

```move
struct ClosePositionEvent has copy, drop {
    pair: ID,
    position: ID,
    owner: address,
}
```

* **Emitted**: When position is closed

**`AddLiquidityEvent`**

```move
struct AddLiquidityEvent has copy, drop {
    pair: ID,
    position: ID,
    ids: vector<u32>,
    amounts_x: vector<u64>,
    amounts_y: vector<u64>,
    tokens: vector<u128>,
}
```

* **Emitted**: When liquidity is added

**`RemoveLiquidityEvent`**

```move
struct RemoveLiquidityEvent has copy, drop {
    pair: ID,
    position: ID,
    ids: vector<u32>,
    tokens_x: u64,
    tokens_y: u64,
    token_bins_x: vector<u64>,
    token_bins_y: vector<u64>,
    liquidity_burned: vector<u128>,
}
```

* **Emitted**: When liquidity is removed

**`LockPositionEvent`**

```move
struct LockPositionEvent has copy, drop {
    pair: ID,
    position: ID,
    lock_until: u64,
    owner: address,
}
```

* **Emitted**: When position is locked

**`PairPausedEvent`**

```move
struct PairPausedEvent has copy, drop {
    pair: ID,
    paused: bool,
}
```

* **Emitted**: When pair is paused/unpaused

#### Trading Functions

**`swap<X, Y>`**

* **Purpose**: Execute token swaps
* **Parameters**:
  * `swap_for_y`: Direction of swap
  * `min_amount_out`: Slippage protection
  * `amount_in_x`, `amount_in_y`: Input tokens
* **Returns**: Output tokens after swap

**`get_swap_in` / `get_swap_out`**

* **Purpose**: Calculate swap amounts (view functions)
* **Use Cases**: Price quotation, slippage calculation
* **Returns**: Expected amounts and fees

#### Liquidity Management

**`add_liquidity<X, Y>`**

* **Purpose**: Add liquidity to specific price bins
* **Parameters**:
  * `ids`: Target bin IDs
  * `distribution_x`, `distribution_y`: Liquidity distribution
  * `coin_x`, `coin_y`: Token amounts
* **Features**: Handles composition fees and refunds

**`remove_liquidity<X, Y>`**

* **Purpose**: Remove liquidity from positions
* **Parameters**:
  * `ids`: Bin IDs to remove from
* **Returns**: Withdrawn tokens
* **Validations**: Position ownership, lock period

#### Position Management

**`open_position<X, Y>`**

* **Purpose**: Create new liquidity position
* **Returns**: NFT-like position object
* **Features**: Optional time lock mechanism

**`close_position<X, Y>`**

* **Purpose**: Destroy empty position
* **Requirements**: Position must be completely empty

#### Fee Collection

**`collect_position_fees<X, Y>`**

* **Purpose**: Collect accumulated trading fees
* **Parameters**: `bin_ids` - specific bins to collect from
* **Returns**: Fee tokens earned
* **Side Effects**: Updates global reward tracking

**`collect_protocol_fees<X, Y>`**

* **Purpose**: Collect protocol revenue (admin only)
* **Returns**: Protocol fee tokens

#### Reward System

**`add_rewarder<X, Y, RewardCoin>`**

* **Purpose**: Add new reward token (admin only)
* **Limits**: Maximum 5 reward types per pair

**`update_emission<X, Y, RewardCoin>`**

* **Purpose**: Update reward emission rate (admin only)
* **Validation**: Sufficient vault balance

**`collect_position_rewards<X, Y, RewardCoin>`**

* **Purpose**: Claim earned rewards
* **Returns**: Reward tokens based on fee generation

#### Flash Loans

**`flash_loan<X, Y>`**

* **Purpose**: Borrow tokens temporarily
* **Returns**: Borrowed tokens and repayment receipt
* **Fee**: Configurable flash loan fee

**`repay_flash_loan<X, Y>`**

* **Purpose**: Repay borrowed tokens with fee
* **Requirements**: Must repay principal + fee

#### View Functions

* **`get_reserves`**: Current token reserves
* **`get_active_id`**: Current active price bin
* **`get_bin`**: Specific bin reserves
* **`get_protocol_fees`**: Accumulated protocol fees
* **`get_pending_rewards`**: Unclaimed rewards for position
* **`get_pending_fees`**: Unclaimed fees for position


---

# 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.ferra.ag/integration/dlmm/smart-contract/lb-pair-module.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.
