Skip to content

Commit b6b06f2

Browse files
authored
Merge pull request #148 from Winnie579/docs/math-spec
docs: Add liquidity pool math guide for new developers
2 parents a931430 + 437b8e0 commit b6b06f2

1 file changed

Lines changed: 80 additions & 0 deletions

File tree

docs/MATH_SPEC.md

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# Liquidity Pool Math Guide
2+
3+
This guide explains the constant-product formula, and how swaps work when a trading fee is introduced in TradeFlow-Core. It is written to be easy to follow for new developers.
4+
5+
---
6+
7+
## 1. Explanation: The Constant Product Formula: x * y = k
8+
9+
Every pool keeps a constant balance between two tokens (when people trade) using this rule:
10+
11+
` x * y = k `
12+
13+
14+
- \(**x**\) = reserve of token_A in the pool (e.g., XLM)
15+
- \(**y**\) = reserve of token_B in the pool (e.g., USDC)
16+
- \(**k**\) = constant value that doesn’t change during a trade (unless fees are added)
17+
18+
---
19+
20+
## 2. Fee Logic
21+
A protocol fee is deducted from a user's input amount before a swap is executed.
22+
23+
* **Fee Rate:** 0.3%
24+
* **Formula:** `amount_in * (1-Fee) = amount_in_scaled`
25+
26+
---
27+
28+
## 3. How To Calculate Swaps
29+
30+
When you put tokens in, the pool gives you some of the other token back.
31+
The math looks like this:
32+
33+
34+
```
35+
amount_out_scaled = (reserve_out_scaled * amount_in_scaled) / (reserve_in_scaled + amount_in_scaled)
36+
```
37+
- **Reserve_out:** Total balance of the token the user is taking out of the pool
38+
- **Reserve_in:** Total balance of the token the user is depositing into the pool
39+
40+
Before you run the above formula, you need to deduct a **0.3% fee** from your input.
41+
That fee remains in the pool to reward liquidity providers.
42+
43+
---
44+
45+
## 4. Step-by-Step Example: 100 XLM → USDC
46+
47+
**Scenario:** Imagine the pool has:
48+
- 10,000 XLM
49+
- 5,000 USDC
50+
51+
You want to swap **100 XLM** for **USDC :**
52+
53+
### **Step 1: Fee deduction**
54+
55+
56+
```100 XLM * (1 - 0.003) = 99.7 XLM```
57+
58+
This gives the `amount_in_scaled`.
59+
60+
### **Step 2: Apply `amount_out` formula**
61+
62+
amount_out_scaled = (reserve_out_scaled * amount_in_scaled) / (reserve_in_scaled + amount_in_scaled)
63+
64+
```
65+
amount_out = (5000 * 99.7) /(10000 + 99.7)
66+
```
67+
68+
### **Step 3: Result**
69+
You get `amount_out` at approx **49.36 USDC**.
70+
71+
---
72+
## 5. Source Code Reference
73+
The formula is defined in the following locations:
74+
| Logic | Code Reference |
75+
| ----------- | -------------- |
76+
| Source Code | [`contracts/amm_pool/src/llib.rs`](../contracts/amm_pool/src/lib.rs)|
77+
| Associated Manifest | [`contracts/amm_pool/Cargo.toml`](../contracts/amm_pool/Cargo.toml)|
78+
79+
---
80+

0 commit comments

Comments
 (0)