> For the complete documentation index, see [llms.txt](https://docs.predy.finance/predy-v5/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.predy.finance/predy-v5/points-for-improvement-of-predy-v5/rebalance-fee.md).

# Rebalance fee

#### Fix rebalance fee

Related section: <https://predy.gitbook.io/predy-v3.2/product-recipe#fee>

There is a problem with the current calculation of the rebalance fee.

<https://github.com/predyprotocol/sqrt-contracts/blob/main/src/libraries/PerpFee.sol#L129>

The rebalance fee is the interest that the protocol has paid for after rebalancing until the user first updates their position. In the implementation of v3.2, there are the following problems.

* The rebalance fee is charged even after the user has settled.
* The rebalance fee is also charged for new positions.

**Variables**

| name                           | parent struct | type    | description                                               |
| ------------------------------ | ------------- | ------- | --------------------------------------------------------- |
| rebalanceFeeGrowth             | Perp          | uint256 | accumulated rebalance fee                                 |
| lastRebalanceTotalSquartAmount | Perp          | uint256 | Total Squart Amount at the last rebalance                 |
| numRebalance                   | Perp          | uint64  | Number of rebalances, Rebalance ID                        |
| rebalanceFeeGrowthCache        | Perp          | mapping | Cache of rebalanceFeeGrowth at each rebalance             |
| lastNumRebalance               | User          | uint64  | Rebalance ID at the time of the last rebalance settlement |

**Logic of v5.0**

* At the time of rebalancing
  * Save TotalSquartAmount in lastRebalanceTotalSquartAmount
    * This is for sharing the rebalance fee with the Squart owners at the time of rebalance
  * At the time of rebalance, `rebalanceFeeGrowthCache[numRebalance] = rebalanceFeeGrowth`
  * Increment numRebalance.
* Before each trade
  * Let rebalanceFeeGrowth grow.
    * `growth += rebalanceFee * ONE / lastRebalanceTotalSquartAmount`
    * This is to share the rebalance fee with the Squart owners at the time of rebalance
* When a user trades
  * Only when settleUserBalance is done, settle the rebalance fee.
    * if `lastNumRebalance < numRebalance`
  * Only when Squart was owned at the time of rebalance, settle the fee.
    * `rebalanceFeeGrowth - rebalanceFeeGrowthCache[lastNumRebalance]`
  * If there was a trade, update lastNumRebalance.
    * `lastNumRebalance = numRebalance`
  * Subtract the settled SquartAmount from lastRebalanceTotalSquartAmount
