Skip to content

Commit

Permalink
docs: improve AMM and Leverage LP docs (#637)
Browse files Browse the repository at this point in the history
* docs: improve AMM spec

* docs: add additional doc for leverage lp

---------

Co-authored-by: Amit Yadav <[email protected]>
  • Loading branch information
cosmic-vagabond and amityadav0 authored Jul 4, 2024
1 parent 34d1069 commit a294b42
Show file tree
Hide file tree
Showing 10 changed files with 256 additions and 118 deletions.
56 changes: 51 additions & 5 deletions architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,52 @@ This section contains documentation on the architecture of the Elys chain, inclu
<details>
<summary>Click to expand/collapse</summary>

## Overview

The diagram below illustrates the architecture of Elys Network, outlining its various modules and their interactions. The system is organized into six layers, each with specific functionalities crucial for the overall operation.

![./modules.png](./docs/assets/modules.png)

### Layers and Components

1. **Core Components:**

- **Parameters:** Configuration settings for the overall network.
- **Epochs:** Time-based intervals for system operations.
- **Clock:** Execute CosmWasm contracts sudo operations.
- **Transferhook:** Extends basic IBC transfer capabilities by integrating with the AMM module.

2. **Data Layer:**

- **Oracle:** Provides external data inputs, such as price feeds.
- **Asset Profile:** Maintains information about the different assets managed within the network.

3. **Liquidity Management:**

- **AMM (Automated Market Maker):** Facilitates decentralized trading by maintaining liquidity pools.
- **StableStake:** Manages staking of stable assets.
- **Commitment:** Handles token lockups, vesting schedules, and staking interactions.
- **Estaking:** Extends basic staking capabilities with additional functionalities.

4. **Pool Aggregation:**

- **Accounted Pool:** Ensures accurate accounting of assets within pools.

5. **Trading Mechanisms:**

- **Perpetual:** Implements perpetual trading contracts.
- **LeverageLP:** Enables leverage trading by borrowing assets from the StableStake module.

6. **Revenue Model:**
- **Masterchef/Incentive:** Manages rewards distribution to liquidity providers.
- **Tier:** Implements membership tiers for users based on their activity.
- **Burner:** Handles token burning mechanisms to manage supply.
- **Tokenomics:** Manages the economic model and token distribution.

### Interaction Flow

The interaction flow between layers is depicted with arrows. Data from the Core Components feeds into the Data Layer. The Liquidity Management layer uses this data to manage liquidity, which is then aggregated in the Pool Aggregation layer. Trading mechanisms utilize the pooled liquidity for various trading activities. The Revenue Model layer ensures economic incentives and sustainability of the system.

## Boilerplate Generation

The boilerplate was generated using `ignite CLI`, which provides a convenient way to generate new chains, modules, messages, and more. The initial modules that are part of the repository include `AssetProfile` and few others, both of which were generated using the `ignite CLI`.
Expand Down Expand Up @@ -40,11 +86,11 @@ Here are the definitions and current values of each individual parameter of the
<details>
<summary>Click to expand/collapse</summary>

## Minting
### Minting

Defines the rules for automated minting of new tokens. In the current implementation, minting is entirely disabled.

## Staking
### Staking

Defines the rules for staking and delegating tokens in the network. Validators and delegators must lock their tokens for a certain period to participate in consensus and receive rewards. The `unbonding_time` parameter specifies the duration for which a validator's tokens are locked after they unbond.

Expand All @@ -54,7 +100,7 @@ Defines the rules for staking and delegating tokens in the network. Validators a
- `Max_validators`: The maximum number of validators that can be active at once. Current value: 100.
- `Bond_denom: The denomination used for staking tokens. Current value: `uelys`.

## Governance
### Governance

Defines the rules for proposing and voting on changes to the network. To make a proposal, a minimum deposit of ELYS is required. The proposal must then go through a voting process where a certain percentage of bonded tokens must vote, and a certain percentage of those votes must be in favor of the proposal for it to pass.

Expand All @@ -65,14 +111,14 @@ Defines the rules for proposing and voting on changes to the network. To make a
- `Veto_threshold`: The percentage of no votes required to veto a proposal. Current value: 33.4%.
- `Voting_period`: The period for which voting on a proposal is open. Current value: 60.

## Distribution
### Distribution

Defines the distribution of rewards and fees in the network. Block proposers receive a portion of the block rewards as an incentive to maintain the network.

- `Base_proposer_reward`: The base percentage of block rewards given to proposers. Current value: 1%.
- `Bonus_proposer_reward`: The additional percentage of block rewards given to proposers if they include all valid transactions. Current value: 4%.

## Slashing
### Slashing

Defines the penalties for validators who violate the network rules or fail to perform their duties. Validators who sign blocks incorrectly or go offline for too long will be penalized with a percentage of their bonded tokens being slashed. The `signed_blocks_window` parameter specifies the number of blocks used to determine a validator's uptime percentage, and the `min_signed_per_window` parameter specifies the minimum percentage of blocks that a validator must sign in each window to avoid being slashed. The `downtime_jail_duration` parameter specifies the duration for which a validator is jailed if they miss too many blocks.

Expand Down
Binary file added docs/assets/modules.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
62 changes: 0 additions & 62 deletions x/amm/spec/05_slippage.md

This file was deleted.

63 changes: 63 additions & 0 deletions x/amm/spec/06_slippage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<!--
order: 6
-->

# Slippage Model

In the Oracle Pool, to prevent bots from exploiting slippage by splitting trades into smaller pieces, we introduce the **stacked slippage model**. This model accumulates slippage within a block, making it less advantageous for bots to break down trades.

## Dynamic Weight Model

The Oracle Pool employs a dynamic weight model. The weight is updated at the start of the swap transactions execution and remains constant until the end of the block. As a result, slippage is recalculated based on the liquidity changes within the block. Multiple trades within a single block will cumulatively increase slippage, particularly for swaps in the same direction, leading to the "stacked slippage" model.

## Slippage Calculation

The slippage amount is calculated as follows:

$
SlippageAmount = Max(0, OracleOutAmount - BalancerOutAmount)
$

When $BalancerOutAmount$ exceeds $OracleOutAmount$, slippage is considered zero, not negative.

For trades with a negative slippage tolerance due to numerous opposite side trades, the value is set to 0%, aligning with the oracle price.

## Dynamic Weight Adjustment Criteria

To illustrate the dynamic weight adjustment:

- Suppose the pool contains 1000 ATOM and 10000 USDC, with the oracle providing a price of $11 for 1 ATOM.
- The pool's ratio is updated to 11:10 based on the USD value of each asset.

## Bot Prevention Mechanism

The stacked slippage model discourages bots by increasing slippage with consecutive same-direction swaps within a block:

- Initial swaps have minimal slippage based on the oracle price.
- Subsequent swaps face increased slippage, preventing lower overall slippage even if the trade is split.

For example, a bot attempting to swap 1000 ATOM for USDC with 1% slippage:

- Splitting the trade into 1000 swaps of 1 ATOM each would result in increasing slippage for each swap, cumulatively ensuring the overall slippage does not drop below 1%.

This mechanism ensures that splitting trades does not offer a better deal than a single trade within the block.

## Role of the Oracle

The oracle provides price and external liquidity data without additional information. This ensures price accuracy and consistency across trades.

## Dynamic Weight Model and Slippage

Oracle-based pools use the balancer slippage model to prevent arbitrage opportunities with other DEXs. The slippage is calculated from the balancer model, considering the weight and liquidity of the pool. When the weight is updated based on the oracle price, the pool's weight aligns with the oracle price, ensuring price consistency.

## Computational Considerations

Weights are updated when the first swap transaction is executed within a block, with all swap transactions executed at the end of the block. This does not directly impact users' swap gas fees since the transaction is only scheduled at this stage. The time complexity for executing swap transactions at the end of the block is O(n), where n is the number of swaps within the block.

## Handling Volatile Markets

In volatile markets, arbitrage opportunities arise due to price differences across platforms. The oracle provides the average price from these platforms and applies slippage on top, minimizing arbitrage opportunities with other platforms during volatile conditions.

## User Information on Slippage

Slippage is determined by liquidity, external liquidity, and oracle price. Users can estimate slippage using the balancer formula and set a minimum acceptable out amount, accounting for stacked slippage within the block. Similar to Uniswap, users can estimate the output amount, though it may vary due to other trades.
34 changes: 0 additions & 34 deletions x/amm/spec/06_swap_txs_reordering.md

This file was deleted.

45 changes: 45 additions & 0 deletions x/amm/spec/07_swap_txs_reordering.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<!--
order: 7
-->

# Swap Transactions Reordering

This documentation describes the mechanism used to reorder swap transactions to minimize slippage and prevent MEV (Miner Extractable Value) attacks.

## Overview

To achieve the lowest possible slippage within a block, this module reorders swap requests into a specific sequence. This approach mitigates the risk of MEV attacks, which exploit transaction ordering. Instead of executing transactions as they are received from the validator, the requests are stored in a transient store during the endblocker and then executed in an optimal order.

## Key Considerations

When designing the reordering algorithm, the following factors are taken into account:

- Transactions that swap an exact amount in
- Transactions that swap for an exact amount out
- Multihop transactions
- Pools involving two or more tokens
- Algorithm complexity

## Algorithm

1. **Grouping Transactions**: Transactions are grouped by pool and token pairs (In -> Out).
- For multihop transactions, only the first pool and the first in/out tokens are considered to reduce complexity.
2. **Selection and Execution**:

- Select a random swap request.
- Attempt to execute it in a cache context and check the resulting stacked slippage.
- Check for an existing request in the opposite direction (same pool ID with opposite in/out tokens).
- If such an opposite request exists, attempt to execute it in a cache context and check the resulting stacked slippage.
- Apply the swap request that results in lower stacked slippage.
- If either swap fails, discard the swap request without applying any changes.

3. **Iteration**:
- Repeat the selection and execution process until all swap requests are processed.

### Algorithm Complexity

The complexity of the algorithm is `O(n)`, where `n` is the number of swap requests within the block.

### Algorithm Accuracy

This algorithm provides a semi-optimized solution, balancing accuracy and complexity.
19 changes: 2 additions & 17 deletions x/amm/spec/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,5 @@
3. **[Keeper](03_keeper.md)**
4. **[Endpoints](04_endpoints.md)**
5. **[Risk Management](05_risk_management.md)**

## References

Resources:
https://www.notion.so/5-Molecule-Token-Adding-Liquidity-to-a-Multi-Asset-Pool-1fc49e859f96457a9469d9c9ed5d06cf

Vault contract (Main logic seems to be here)
https://arbiscan.io/address/0x489ee077994B6658eAfA855C308275EAd8097C4A#code

Reward Router - https://arbiscan.io/address/0xB95DB5B167D75e6d04227CfFFA61069348d271F5#code

GLP manager - https://arbiscan.io/address/0x3963FfC9dff443c2A94f21b129D429891E32ec18#code

GLP documenet

- https://gmxio.gitbook.io/gmx/glp
- https://app.gmx.io/#/buy_glp
6. **[Slippage Model](06_slippage.md)**
7. **[Swap Transactions Reordering](07_swap_txs_reordering.md)**
Loading

0 comments on commit a294b42

Please sign in to comment.