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

# Minitswap Architecture

export const Flexibility = "A governance-controlled variable that modifies the Peg Keeper's tolerance towards imbalance. A higher flexibility means that a low target ratio can be maintained even with a high imbalance. When the flexibility is low, the Peg Keeper will interfere less frequently compared to high flexibility, ceteris paribus.";

export const MaxRatio = 'A governance-controlled value that dictates the largest Fully Recovered Ratio value allowed.';

export const FullyRecoveredRatio = 'Defines the ideal proportion of IbcOpInit vs. INIT in the virtual pool. For example, a ratio of 0.6 implies that the ratio of IbcOpInit to INIT is 6:4. When a user performs a swap, the pool ratio is compared to the Fully Recovered Ratio. If the current pool is greater, the Peg Keeper will swap the IbcOpInit tokens for INIT tokens.';

export const IbcOpINIT = 'The variation of the INIT token that was bridged from Initia L1 to the rollup m through OP Bridge, then subsequently back to the L1 through IBC';

export const INIT = 'The vanilla Initia INIT tokens on the Initia L1';

## Goals

* **Manipulation Resistance**: The architecture of the rollup and related
  systems themselves already has safeguards in place to prevent various forms of
  manipulation from malicious actors. The Minitswap DEX is further designed to
  ensure that, in unforeseen events, any subsequent damages are minimized.
* **Capital Efficiency**: As the number of rollups continues to increase,
  naively, the same number of DEX pairs must also exist. This results in
  liquidity fragmentation, high slippage and volatility, and subpar user
  experience.

## Design

Minitswap itself is designed as a virtual pool DEX between

<Tooltip tip={INIT}>INIT</Tooltip> and the various
<Tooltip tip={IbcOpINIT}>IbcOpINIT</Tooltip> tokens for each of the rollups. The
[StableSwap](https://docs.curve.finance/stableswap-exchange/overview/) formula
determines the exchange rates on each swap.

To achieve the above goals, Minitswap makes two main improvements to the base
StableSwap pool design:

* **Rate Limiting**: To protect against manipulation, the net amount of
  IbcOpINIT tokens that can be swapped back into INIT tokens is limited. This
  means that even if a malicious actor acquires or creates a large amount of
  IbcOpINIT tokens on their rollup, the number of tokens that can be swapped
  back into regular INIT tokens remains restricted.
* **Single INIT Token Pool**: To minimize liquidity fragmentation, there is a
  single INIT token pool that can be paired with multiple IbcOpINIT token pools,
  instead of having separate INIT token pools for each rollup.

## Swap Mechanisms

### Initia L1 to Rollups

<Frame caption="Initia L1 to Rollups Minitswap Flow">
  <img src="https://mintcdn.com/initialabs/XbiP969DLxcW6ToY/images/minitswap/minitswap_l1_l2.png?fit=max&auto=format&n=XbiP969DLxcW6ToY&q=85&s=bc024551e16e02bf1c21cc821b121ab6" alt="Initia L1 to Rollups Minitswap Flow" width="2560" height="2580" data-path="images/minitswap/minitswap_l1_l2.png" />
</Frame>

In this scenario, a user wants to efficiently bridge their $INIT$ tokens on the
Initia L1 to a rollup $m$ and ends up with the $OpINIT_m$ token for that rollup.

And while bridging from Initia L1 to a rollup is instantaneous, users may
occasionally be able to obtain a more favorable rate by utilizing Minitswap as
part of the bridging process as shown below.

1. **Initiate Swap on Minitswap DEX**: The user sends a transaction to the
   Minitswap DEX to swap their $INIT$ tokens into $IbcOpINIT_m$ tokens.
2. **Simulate Swap**: The DEX simulates swapping the user’s $INIT$ tokens into
   $IbcOpINIT_m$ tokens.
3. **Compare Swap and Direct Bridging**: The DEX compares the simulated amount
   of $IbcOpINIT_m$ tokens with the amount the user would receive if they
   bridged directly through the OP Bridge.
4. **Perform Optimal Action**
   * If the amount of $IbcOpINIT_m$ tokens from the swap is greater, the DEX
     performs the swap. The output $IbcOpINIT_m$ tokens are then bridged to the
     destination L2 through IBC.
   * If the direct bridging through the OP bridge provides a better amount, the
     DEX initiates a direct transfer to the destination rollup $m$ for the user
     using the OP bridge.
5. **Minitswap Swap Process**
   * **Calculate $IbcOpINIT_m$ Received**: Minitswap calculates how much
     $IbcOpINIT_m$ the user will receive based on the current Virtual Pool
     state, updating the state in the process.
   * **Fee Deduction**: Minitswap deducts a fee based on a predefined value and
     an additional fee from any extra $IbcOpINIT_m$ that the user receives.
   * **Peg Keeper Swap Check**: Once the user’s swap action and fee calculation
     are complete, Minitswap checks if a [Peg Keeper Swap](#peg-keeper-swaps)
     should be performed based on the latest Virtual Pool state.
   * **Internal Rebalancing Check**: After completing the Peg Keeper Swap,
     Minitswap checks if [Internal Rebalancing](#internal-rebalancing) is
     possible based on the Peg Keeper’s $IbcOpINIT$ balance. If balancing is
     possible, it is initiated.
6. **Final Outcome**: In both cases, once the OP Bridge or IBC transfer is
   complete, the user receives the most amount of $OpINIT_m$ tokens in their
   wallet on the destination rollup possible.

### Rollup to Initia L1

<Frame caption="Rollup to Initia L1 Minitswap Flow">
  <img src="https://mintcdn.com/initialabs/XbiP969DLxcW6ToY/images/minitswap/minitswap_l2_l1.png?fit=max&auto=format&n=XbiP969DLxcW6ToY&q=85&s=8da0f829b06318aeb69eecaabc8a34d4" alt="Rollup to Initia L1 Minitswap Flow" width="2560" height="2046" data-path="images/minitswap/minitswap_l2_l1.png" />
</Frame>

When bridging from a rollup to Initia L1, the user is currently holding
$OpINIT_m$ tokens on a rollup $m$ and would like to bridge it back to $INIT$
tokens on the Initia L1.

In this scenario, utilizing Minitswap will enable them to bridge their INIT back
to the Initia L1 instantaneously without waiting for the challenge period to
expire.

1. **Transfer to Initia L1 via IBC**: The user begins by transferring their
   $OpINIT_m$ tokens on the rollup $m$ back to Initia L1 using IBC. As a result,
   they receive $IbcOpINIT_m$ tokens on the Initia L1.
2. **Swap on Minitswap DEX**: Once the IBC transfer is complete and the user has
   $IbcOpINIT_m$ tokens on Initia L1, they initiate a swap transaction on the
   Minitswap DEX to convert their $IbcOpINIT_m$ tokens into $INIT$ tokens.
3. **Minitswap Swap Process**
   * **Peg Keeper Swap Check**: Minitswap first checks if a Peg Keeper Swap can
     be performed. If this is possible, the swap is executed directly through
     the Peg Keeper.
   * **Calculate $INIT$ Received**: If the Peg Keeper Swap is not applicable,
     Minitswap calculates the amount of $INIT$ the user will receive based on
     the updated state of the Virtual Pool.
   * **Fee Deduction**: Minitswap deducts a predefined fee amount from the
     transaction.
   * **Internal Rebalancing Check**: After completing the user’s swap
     transaction, Minitswap checks if
     [Internal Rebalancing](#internal-rebalancing) is possible based on the Peg
     Keeper’s $IbcOpINIT$ balance. If balancing is possible, it is executed to
     maintain market stability.
4. **Final Outcome**: If the swap is successful, the user receives $INIT$ tokens
   in their wallet on Initia L1.

### Direct Swap

In addition to the standard directional swap explained above, Minitswap also
offers a unique **Direct Swap** option. As more
[Peg Keeper Swaps](#peg-keeper-swaps) are performed, the Peg Keeper's $INIT$
balance decreases. The Direct Swap aims to incentivize users to help replenish
the Peg Keeper's $INIT$ token balance, which gets depleted over time. This
serves as an additional method of replenishing the Peg Keeper's $INIT$ balance
alongside the [Internal Rebalancing](#internal-rebalancing).

The Direct Swap allows any user to directly exchange their $INIT$ tokens for the
Peg Keeper’s $IbcOpINIT$ tokens. This exchange occurs at the average price at
which the Peg Keeper purchased $INIT$ tokens. This price could sometimes be
lower than what you would get through the traditional swap process. Initially,
the Direct Swap might not seem attractive due to the Target Ratio being close to
0.5. However, as the Peg Keeper’s balance of OP-bridged tokens increases, the
Direct Swap option becomes more appealing to users.

## Swap Logic

### Parameters

* **Max Ratio**: The Max Ratio, $R_{max}$, is an Initia L1 governance-controlled
  parameter that dictates the maximum pool ratio between IbcOpINIT and regular
  INIT.

* **Fully Recovered Ratio**: The Fully Recovered Ratio, $R_{fr}$, then uses the
  Max Ratio and the Flexibility to calculate the final target IbcOpINIT:INIT
  ratio for the pool. The ratio is calculated as follows:

$$
R_{fr}=0.5+(R_{max}-0.5) \cdot \frac{(fI)^3}{(1+|fI|^3)}
$$

### Mechanisms

#### Peg Keeper Swaps

<Frame caption="Peg Keeper Swaps">
  <img src="https://mintcdn.com/initialabs/XbiP969DLxcW6ToY/images/minitswap/minitswap_peg_keeper_swaps.png?fit=max&auto=format&n=XbiP969DLxcW6ToY&q=85&s=65100543e9342285d9162c5b66d243df" alt="Peg Keeper Swaps" width="2560" height="1296" data-path="images/minitswap/minitswap_peg_keeper_swaps.png" />
</Frame>

The Peg Keeper Swap is a mechanism designed to keep the exchange rate between
$INIT$ and $IbcOpINIT$ close to 1:1. This ensures that users always receive the
best swap rates.

When users move their INIT tokens from a rollup back to Initia L1 using
Minitswap, they are essentially selling their $IbcOpINIT$ tokens for $INIT$
tokens. As more users do this, the supply of $IbcOpINIT$ increases relative to
$INIT$, which raises the price of future rollup -> Initia L1 swaps.

To address this, the Peg Keeper Swap executes a ($INIT$ -> $IbcOpINIT$) swap to
balance the effect. When a user makes a swap, Minitswap checks the Fully
Recovered Ratio against the current pool ratio. If the current ratio exceeds the
Fully Recovered Ratio, a Peg Keeper Swap is triggered to restore balance.

When run, the Peg Keeper swap follows this procedure:

1. Calculate the current $R_{fr}$ and the `max_recover_amount`, which defines
   the maximum size of the Peg Keeper Swap that can be performed in this swap.
   This is to prevent a huge Peg Keeper Swap from happening.
2. Check if another Peg Keeper Swap has been run in the same block. Continue if
   no swaps have been run.
3. Calculate the $INIT$ amount the Peg Keeper needs to reach $R_{fr}$. Let's
   call this `swap_amount_to_reach_fr`.
4. Check if `swap_amount_to_reach_fr > max_recover_amount`
   * If true, swap only `max_recover_amount`.
   * If false, swap `swap_amount_to_reach_fr`

Note that the Peg Keeper Swap check is done

* *before* an L2 -> L1 swap to make sure the user gets the best rate possible
* *after* an L1 -> L2 swap to make sure the user's swap rate doesn't get
  affected by the Peg Keeper Swap

#### Internal Rebalancing

<Frame caption="Internal Rebalancing">
  <img src="https://mintcdn.com/initialabs/XbiP969DLxcW6ToY/images/minitswap/minitswap_internal_rebalancing.png?fit=max&auto=format&n=XbiP969DLxcW6ToY&q=85&s=b128b4c44a8ed8c207313ea219f11431" alt="Internal Rebalancing" width="2560" height="1296" data-path="images/minitswap/minitswap_internal_rebalancing.png" />
</Frame>

As more Peg Keeper Swaps are performed, the $INIT$ balance of the Peg Keeper
gradually decreases. To replenish its $INIT$ balance, the system has an internal
rebalancing procedure that converts the Peg Keeper's $IbcOpINIT$ back into
$INIT$ using IBC and OP Bridge.

The rebalancing process follows these steps:

1. Bridge the Peg Keeper's $IbcOpINIT_m$ back to the rollup $m$ using IBC,
   converting it into $OpINIT_m$.
2. Use the OP Bridge to convert $OpINIT_m$ back into $INIT$.

This process, combined with the [Direct Swap](#direct-swap), ensures that the
Peg Keeper's $INIT$ balance is replenished, allowing it to continue performing
Peg Keeper Swaps.
