> ## 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.

# Managing Rebalances

> Start and manage rebalances to adjust your Folio's asset composition

## Overview

Rebalancing allows you to adjust the composition of assets in your Folio's basket. The process involves:

1. Starting a rebalance with target weights and price ranges
2. Opening auctions to execute trades
3. Bidding on auctions (or using trusted fillers)
4. Closing auctions and ending the rebalance

<Note>
  Only the `REBALANCE_MANAGER` role can start rebalances. The `AUCTION_LAUNCHER` role controls how auctions execute during the restricted period.
</Note>

## Starting a Rebalance

<Steps>
  <Step title="Define Token Parameters">
    Specify weights, price ranges, and constraints for each token in the rebalance:

    ```solidity theme={null}
    IFolio.TokenRebalanceParams[] memory tokens = new IFolio.TokenRebalanceParams[](3);

    // USDC - target weight with ranges
    tokens[0] = IFolio.TokenRebalanceParams({
        token: address(usdc),
        weight: IFolio.WeightRange({
            low: 0.3e27,   // 30% minimum
            spot: 0.33e27, // 33% target
            high: 0.36e27  // 36% maximum
        }),
        price: IFolio.PriceRange({
            low: 0.99e27,   // $0.99 pessimistic
            high: 1.01e27   // $1.01 optimistic
        }),
        maxAuctionSize: 100_000e6, // Max 100k USDC per auction
        inRebalance: true
    });

    // WETH - increasing allocation
    tokens[1] = IFolio.TokenRebalanceParams({
        token: address(weth),
        weight: IFolio.WeightRange({
            low: 0.48e27,
            spot: 0.50e27,
            high: 0.52e27
        }),
        price: IFolio.PriceRange({
            low: 2200e27,  // $2200
            high: 2400e27  // $2400
        }),
        maxAuctionSize: 10e18,
        inRebalance: true
    });

    // DAI - decreasing allocation
    tokens[2] = IFolio.TokenRebalanceParams({
        token: address(dai),
        weight: IFolio.WeightRange({
            low: 0.14e27,
            spot: 0.17e27,
            high: 0.20e27
        }),
        price: IFolio.PriceRange({
            low: 0.98e27,
            high: 1.02e27
        }),
        maxAuctionSize: 50_000e18,
        inRebalance: true
    });
    ```

    <Info>
      **Weight Ranges:**

      * Weights are in D27 format (27 decimals) representing `tok/BU`
      * Total weights don't need to equal 100%, they define ratios
      * `spot` is used for unrestricted auctions
      * `AUCTION_LAUNCHER` can narrow ranges if `weightControl` is enabled
    </Info>
  </Step>

  <Step title="Set Basket Unit Limits">
    Define the target basket unit (BU) range per share:

    ```solidity theme={null}
    IFolio.RebalanceLimits memory limits = IFolio.RebalanceLimits({
        low: 0.95e18,  // Buy assets until we reach 0.95 BU per share
        spot: 1.0e18,  // Target: 1 BU per share
        high: 1.05e18  // Sell assets until we reach 1.05 BU per share
    });
    ```

    <Tip>
      A Basket Unit (BU) is typically 1:1 with shares (1e18), but can be configured in the range (0, 1e27]. The BU defines the target composition of assets.
    </Tip>
  </Step>

  <Step title="Configure Time Windows">
    Set how long the rebalance and restriction periods last:

    ```solidity theme={null}
    uint256 auctionLauncherWindow = 3 days; // AUCTION_LAUNCHER has 3 days
    uint256 ttl = 7 days; // Total rebalance duration
    ```

    **Time Periods:**

    * **Restricted Period**: Only `AUCTION_LAUNCHER` can open auctions
    * **Unrestricted Period**: Anyone can open auctions with spot values
    * **Total TTL**: Maximum time before rebalance expires

    <Warning>
      The `AUCTION_LAUNCHER` period can be extended automatically if auctions are ongoing, but cannot extend past the TTL.
    </Warning>
  </Step>

  <Step title="Execute Start Rebalance">
    Call the `startRebalance` function:

    ```solidity theme={null}
    // Must have REBALANCE_MANAGER role
    folio.startRebalance(
        tokens,
        limits,
        auctionLauncherWindow,
        ttl
    );
    ```

    This will:

    * Increment the rebalance nonce
    * Store all token parameters
    * Set time windows
    * Close any ongoing auction from a previous rebalance
    * Add new tokens to the basket if not already present
  </Step>
</Steps>

## Opening Auctions

Once a rebalance is started, auctions must be opened to execute trades.

### Restricted Auctions (AUCTION\_LAUNCHER)

<Steps>
  <Step title="Select Tokens for Auction">
    Choose which tokens from the rebalance to include:

    ```solidity theme={null}
    address[] memory auctionTokens = new address[](2);
    auctionTokens[0] = address(usdc);
    auctionTokens[1] = address(weth);
    ```
  </Step>

  <Step title="Narrow Ranges (Optional)">
    The `AUCTION_LAUNCHER` can progressively tighten ranges:

    ```solidity theme={null}
    IFolio.WeightRange[] memory newWeights = new IFolio.WeightRange[](2);
    newWeights[0] = IFolio.WeightRange({
        low: 0.32e27,  // Narrowed from 0.30e27
        spot: 0.33e27,
        high: 0.34e27  // Narrowed from 0.36e27
    });
    newWeights[1] = IFolio.WeightRange({
        low: 0.49e27,
        spot: 0.50e27,
        high: 0.51e27
    });

    IFolio.PriceRange[] memory newPrices = new IFolio.PriceRange[](2);
    newPrices[0] = IFolio.PriceRange({
        low: 0.995e27,  // Narrowed price range
        high: 1.005e27
    });
    newPrices[1] = IFolio.PriceRange({
        low: 2250e27,
        high: 2350e27
    });
    ```

    <Check>
      All ranges must stay within the original bounds set in `startRebalance`.
    </Check>
  </Step>

  <Step title="Launch the Auction">
    ```solidity theme={null}
    IFolio.RebalanceLimits memory auctionLimits = IFolio.RebalanceLimits({
        low: 0.98e18,  // Progressively tightening
        spot: 1.0e18,
        high: 1.02e18
    });

    uint256 auctionLength = 6 hours;

    uint256 auctionId = folio.openAuction(
        rebalanceNonce, // Current rebalance nonce
        auctionTokens,
        newWeights,
        newPrices,
        auctionLimits,
        auctionLength
    );
    ```

    The auction will:

    * Have a 30-second warmup period (skipped if atomic swap)
    * Run Dutch auctions on all surplus/deficit pairs
    * Use exponential price decay from optimistic to pessimistic
  </Step>
</Steps>

### Unrestricted Auctions

After the restricted period expires, anyone can open auctions:

```solidity theme={null}
// Anyone can call this after restrictedUntil timestamp
uint256 auctionId = folio.openAuctionUnrestricted(rebalanceNonce);
```

Unrestricted auctions:

* Include all tokens in the rebalance
* Use spot weights (collapsing high/low ranges)
* Use initial price ranges from `startRebalance`
* Use spot limits
* Run for `maxAuctionLength` duration

## Monitoring Auction Progress

<Steps>
  <Step title="Check Auction Status">
    ```solidity theme={null}
    (uint256 nonce, 
     IFolio.PriceControl priceControl,
     IFolio.TokenRebalanceParams[] memory tokens,
     IFolio.RebalanceLimits memory limits,
     IFolio.RebalanceTimestamps memory timestamps,
     bool bidsEnabled) = folio.getRebalance();

    // Check if rebalance is still active
    require(block.timestamp < timestamps.availableUntil, "Rebalance expired");
    ```
  </Step>

  <Step title="View Current Prices">
    ```solidity theme={null}
    // Get current price for a token in the auction
    IFolio.PriceRange memory usdcPrice = folio.getAuctionPrice(
        auctionId,
        address(usdc)
    );
    ```
  </Step>

  <Step title="Query Available Bids">
    ```solidity theme={null}
    (uint256 sellAmount, uint256 bidAmount, uint256 price) = folio.getBid(
        auctionId,
        IERC20(weth),    // Sell token (in surplus)
        IERC20(usdc),    // Buy token (in deficit)
        10e18            // Max WETH willing to sell
    );
    ```
  </Step>
</Steps>

## Closing Auctions and Rebalances

Privileged roles can manually close auctions or end rebalances:

```solidity theme={null}
// Close a specific auction early
// Callable by: ADMIN, REBALANCE_MANAGER, or AUCTION_LAUNCHER
folio.closeAuction(auctionId);

// End the entire rebalance (ongoing auction continues)
// Callable by: ADMIN, REBALANCE_MANAGER, or AUCTION_LAUNCHER
folio.endRebalance();
```

<Warning>
  **Important:**

  * `closeAuction()` stops the auction immediately
  * `endRebalance()` prevents new auctions but lets the current one finish
  * Starting a new rebalance automatically closes any ongoing auction
</Warning>

## Best Practices

<AccordionGroup>
  <Accordion title="Progressive Narrowing">
    Use multiple auctions to progressively narrow BU limits and weight ranges. This implements DCA (dollar-cost averaging) and reduces price impact.

    ```solidity theme={null}
    // Auction 1: Wide ranges
    // Auction 2: 75% of original range
    // Auction 3: 50% of original range
    // Continue until target is reached
    ```
  </Accordion>

  <Accordion title="Price Range Updates">
    If `priceControl` is `PARTIAL`, monitor market prices and update auction prices to reflect current conditions without going outside initial bounds.
  </Accordion>

  <Accordion title="Max Auction Size">
    Set `maxAuctionSize` to prevent single large trades from dominating the rebalance. Break large rebalances into multiple smaller auctions.
  </Accordion>

  <Accordion title="Emergency Stops">
    Monitor for:

    * Market prices moving outside initial price ranges
    * Unexpected token behavior
    * Low bidder participation

    Use `endRebalance()` to stop if conditions warrant.
  </Accordion>
</AccordionGroup>

## Code Reference

* Rebalance start: `contracts/Folio.sol:632-665`
* Open auction: `contracts/Folio.sol:675-707`
* Unrestricted auction: `contracts/Folio.sol:712-766`
* Rebalancing logic: `contracts/utils/RebalancingLib.sol:24-119`

## Next Steps

<CardGroup cols={2}>
  <Card title="Participate in Auctions" icon="gavel" href="/guides/auction-participation">
    Learn how to bid on auctions and earn arbitrage profits
  </Card>

  <Card title="Governance Setup" icon="landmark" href="/guides/governance-setup">
    Configure governance for rebalancing decisions
  </Card>
</CardGroup>
