> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/reserve-protocol/reserve-index-dtf/llms.txt
> Use this file to discover all available pages before exploring further.

# Utility Libraries

> Core libraries for Folio operations: FolioLib, RebalancingLib, and MathLib

## Overview

Reserve Folio uses three primary utility libraries that implement core protocol logic. These libraries are used via `delegatecall` from Folio contracts to reduce deployment size and improve code reusability.

### Library Overview

* **FolioLib**: Fee calculations and governance operations
* **RebalancingLib**: Auction mechanics and rebalancing logic
* **MathLib**: Fixed-point math operations

## FolioLib

Handles fee calculations and fee recipient management.

### Set Fee Recipients

Configure the fee recipient table for a Folio.

```solidity FolioLib.sol theme={null}
function setFeeRecipients(
    IFolio.FeeRecipient[] storage feeRecipients,
    IFolio.FeeRecipient[] calldata _feeRecipients
) external
```

<Info>
  Fee recipients must be provided in ascending address order with no duplicates. Portions must sum to exactly 1e18 (100%). An empty table results in all fees going to the DAO.
</Info>

### Compute Fee Shares

Calculate TVL fee shares owed to DAO and fee recipients.

```solidity FolioLib.sol theme={null}
function computeFeeShares(
    FeeSharesParams calldata params,
    IFolioDAOFeeRegistry daoFeeRegistry
) external view returns (
    uint256 _daoPendingFeeShares,
    uint256 _feeRecipientsPendingFeeShares
)
```

**Parameters:**

* `currentDaoPending`: Existing DAO pending shares
* `currentFeeRecipientsPending`: Existing recipient pending shares
* `tvlFee`: Per-second TVL fee rate (D18)
* `folioFeeForSelf`: Fraction of recipient shares to burn (D18)
* `supply`: Current total supply
* `elapsed`: Time elapsed since last fee calculation

### Set TVL Fee

Convert annual TVL fee to per-second rate.

```solidity FolioLib.sol theme={null}
function setTVLFee(
    uint256 _newFeeAnnually
) external returns (uint256 _tvlFee)
```

<Info>
  Converts annual percentage to per-second using formula: `1 - (1 - feeAnnually)^(1/31536000)`. This ensures accurate compounding over time.
</Info>

### Compute Mint Fees

Calculate fee shares for minting operations.

```solidity FolioLib.sol theme={null}
function computeMintFees(
    MintFeeParams calldata params,
    IFolioDAOFeeRegistry daoFeeRegistry
) external returns (
    uint256 sharesOut,
    uint256 daoFeeShares,
    uint256 feeRecipientFeeShares
)
```

**Parameters:**

* `shares`: Total shares being minted (before fees)
* `mintFee`: Mint fee percentage (D18)
* `folioFeeForSelf`: Fraction of recipient fees to burn (D18)
* `minSharesOut`: Minimum shares caller must receive

## RebalancingLib

Implements auction mechanics and rebalancing operations.

### Start Rebalance

Initiate a new rebalancing operation.

```solidity RebalancingLib.sol theme={null}
function startRebalance(
    address[] calldata oldTokens,
    IFolio.RebalanceControl storage rebalanceControl,
    IFolio.Rebalance storage rebalance,
    IFolio.TokenRebalanceParams[] calldata tokens,
    IFolio.RebalanceLimits calldata limits,
    uint256 auctionLauncherWindow,
    uint256 ttl,
    bool bidsEnabled
) external
```

<Warning>
  Validates all token parameters, weights, prices, and limits. Reverts if any are inconsistent or out of bounds.
</Warning>

### Open Auction

Open a new auction within an ongoing rebalance.

```solidity RebalancingLib.sol theme={null}
function openAuction(
    IFolio.Rebalance storage rebalance,
    mapping(uint256 auctionId => IFolio.Auction) storage auctions,
    uint256 auctionId,
    address[] memory tokens,
    IFolio.WeightRange[] memory weights,
    IFolio.PriceRange[] calldata prices,
    IFolio.RebalanceLimits calldata limits,
    uint256 auctionLength
) external
```

<Info>
  Auctions begin after a 30-second warmup period (`AUCTION_WARMUP`). Atomic swaps (constant price) start and end at the same timestamp.
</Info>

### Get Bid

Calculate bid parameters for a token pair at current timestamp.

```solidity RebalancingLib.sol theme={null}
function getBid(
    IFolio.Rebalance storage rebalance,
    IFolio.Auction storage auction,
    IERC20 sellToken,
    IERC20 buyToken,
    GetBidParams memory params
) external view returns (
    uint256 sellAmount,
    uint256 bidAmount,
    uint256 price
)
```

**Returns:**

* `sellAmount`: Amount of sell token to transfer (in sellTok)
* `bidAmount`: Amount of buy token required (in buyTok)
* `price`: Current Dutch auction price (D27 format)

### Bid

Execute a bid in an ongoing auction.

```solidity RebalancingLib.sol theme={null}
function bid(
    IFolio.Auction storage auction,
    uint256 auctionId,
    IERC20 sellToken,
    IERC20 buyToken,
    uint256 sellAmount,
    uint256 bidAmount,
    bool withCallback,
    bytes calldata data
) external returns (bool shouldRemoveFromBasket)
```

<Info>
  If `withCallback` is true, the caller must implement `IBidderCallee.bidCallback()`. Otherwise, the caller must have pre-approved the buy token.
</Info>

### Price Calculation

Internal function for Dutch auction pricing using exponential decay:

```
P(t) = P_0 * e^(-kt)
```

Where:

* `P_0`: Starting price (sellPriceHigh / buyPriceLow)
* `P_t`: Ending price (sellPriceLow / buyPriceHigh)
* `k`: Decay constant = `ln(P_0 / P_t) / auctionLength`
* `t`: Time elapsed since auction start

## MathLib

Fixed-point mathematical operations using PRBMath.

### Power

Raise a number to a fractional power.

```solidity MathLib.sol theme={null}
function pow(uint256 x, uint256 y) external pure returns (uint256 z)
```

<ParamField path="x" type="uint256">
  Base (D18 fixed point)
</ParamField>

<ParamField path="y" type="uint256">
  Exponent (D18 fixed point)
</ParamField>

<Info>
  Used for compound interest calculations: `(1 - fee)^time`
</Info>

### Power (Unsigned)

Raise a number to an integer power.

```solidity MathLib.sol theme={null}
function powu(uint256 x, uint256 y) external pure returns (uint256 z)
```

<ParamField path="x" type="uint256">
  Base (D18 fixed point)
</ParamField>

<ParamField path="y" type="uint256">
  Exponent (whole number, not fixed point)
</ParamField>

### Natural Logarithm

Compute the natural logarithm of a number.

```solidity MathLib.sol theme={null}
function ln(uint256 x) internal pure returns (uint256 z)
```

<ParamField path="x" type="uint256">
  Input (D18 fixed point)
</ParamField>

<Info>
  Used in Dutch auction price decay calculations.
</Info>

### Exponential

Compute e raised to a power.

```solidity MathLib.sol theme={null}
function exp(int256 x) internal pure returns (uint256 z)
```

<ParamField path="x" type="int256">
  Exponent (D18 fixed point, can be negative)
</ParamField>

<Info>
  Used for exponential decay in auction pricing: `P_0 * e^(-kt)`
</Info>

## Constants

Key constants used across libraries:

### Fixed Point Scaling

<ParamField path="D18" type="uint256" default="1e18">
  18-decimal fixed point (standard for fees and ratios)
</ParamField>

<ParamField path="D27" type="uint256" default="1e27">
  27-decimal fixed point (high precision for weights and prices)
</ParamField>

### Fee Limits

<ParamField path="MAX_TVL_FEE" type="uint256" default="0.1e18">
  Maximum annual TVL fee: 10%
</ParamField>

<ParamField path="MIN_MINT_FEE" type="uint256" default="0.0003e18">
  Minimum mint fee: 3 bps
</ParamField>

<ParamField path="MAX_FEE_RECIPIENTS" type="uint256" default="10">
  Maximum number of fee recipients
</ParamField>

### Rebalancing Limits

<ParamField path="MAX_WEIGHT" type="uint256" default="1e54">
  Maximum token weight (D27 \* 1e27)
</ParamField>

<ParamField path="MAX_LIMIT" type="uint256" default="1e27">
  Maximum BU limit per share
</ParamField>

<ParamField path="MAX_TOKEN_PRICE" type="uint256" default="1e45">
  Maximum token price (D27 \* 1e18)
</ParamField>

<ParamField path="MAX_TOKEN_PRICE_RANGE" type="uint256" default="1000">
  Maximum ratio between high and low price
</ParamField>

<ParamField path="MAX_TOKEN_BUY_AMOUNT" type="uint256" default="1e36">
  Maximum single token purchase amount
</ParamField>

### Auction Settings

<ParamField path="AUCTION_WARMUP" type="uint256" default="30">
  Warmup period before auction bidding opens (seconds)
</ParamField>

<ParamField path="MAX_TTL" type="uint256" default="30 days">
  Maximum rebalance time-to-live
</ParamField>

### Time Constants

<ParamField path="ONE_OVER_YEAR" type="uint256">
  1/31536000 in D18 format (for annual to per-second conversion)
</ParamField>

## Usage in Contracts

Libraries are typically used with `using` directives:

```solidity theme={null}
contract Folio {
    using FolioLib for *;
    using RebalancingLib for *;
    using MathLib for *;
    
    // Library functions become available
    function setFees(...) external {
        tvlFee = FolioLib.setTVLFee(newFeeAnnually);
    }
}
```

<Warning>
  Library functions that modify storage must be called with the correct storage pointers. Ensure you pass storage references, not memory copies.
</Warning>
