Skip to content

Commit a510a92

Browse files
Merge branch 'master' into scripts
Signed-off-by: Haythem Sellami <[email protected]>
2 parents ff22f3b + 54c1af6 commit a510a92

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+2584
-756
lines changed

.DS_Store

-6 KB
Binary file not shown.

.gitignore

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,8 @@ script/json/out/
1313
.env
1414

1515
# Coverage file
16-
lcov.info
16+
lcov.info
17+
18+
# MAC files
19+
.DS_Store
20+
__MACOSX

README.md

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
# EulerSwap
22

3-
EulerSwap is an Automated Market Maker (AMM) that uses [Euler lending vaults](https://docs.euler.finance/euler-vault-kit-white-paper/) as leveraged lending products in order to extend the range of its reserves and thereby improve the capital efficiency of liquidity provisioning.
3+
EulerSwap is an automated market maker (AMM) that integrates with Euler [credit vaults](https://docs.euler.finance/euler-vault-kit-white-paper/) to provide deeper liquidity for swaps. When a user initiates a swap, a smart contract called an EulerSwap operator borrows the required output token using the input token as collateral. This model enables up to 40x the liquidity depth of traditional AMMs by making idle assets in Euler more efficient. Unlike traditional AMMs, which often fragment liquidity across multiple pools, EulerSwap further increases capital efficiency by allowing a single, cross-collateralised credit vault to support multiple asset pairs at once. At its core, EulerSwap uses a flexible AMM curve to optimise swap pricing, ensuring deep liquidity while maintaining market balance. By combining just-in-time liquidity, shared liquidity across pools, and customisable AMM mechanics, EulerSwap reduces inefficiencies in liquidity provision, offering deeper markets, lower costs, and greater control for liquidity providers.
44

5-
To swappers, EulerSwap presents a hopefully familiar Uniswap2-style interface but internally it supports borrow and repaying, custom pricing curves, and other advanced functionality. Although useable by anyone, it is primarily intended to be invoked by sophisticated actors such as swap aggregators, intents solvers, and MEV bots. Similar to Uniswap, there is a careful separation between the critical core functionality for servicing swaps and the surrounding periphery functions for quoting, etc.
6-
7-
For more information, refer to the [white paper](./docs/white-paper/EulerSwap_White_Paper.pdf).
5+
For more information, refer to the [white paper](./docs/whitepaper/EulerSwap_White_Paper.pdf).
86

97
## Usage
108

@@ -44,6 +42,12 @@ forge test
4442
forge coverage
4543
```
4644

45+
## Smart Contracts Documentation
46+
47+
```sh
48+
forge doc --serve --port 4000
49+
```
50+
4751
## Private Deployment
4852

4953
- EulerSwapFactory: 0x04C54FF83e4BC428FD1eDA2f41cdBd583A2e9cF8
@@ -59,7 +63,7 @@ Always include thorough tests when using EulerSwap to ensure it interacts correc
5963

6064
## Known limitations
6165

62-
Refer to the [white paper](./docs/white-paper/EulerSwap_White_Paper.pdf) for a list of known limitations and security considerations.
66+
Refer to the [white paper](./docs/whitepaper/EulerSwap_White_Paper.pdf) for a list of known limitations and security considerations.
6367

6468
## Contributing
6569

SECURITY.md

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,25 @@
1-
# Security policy
1+
# Euler Security Policy
22

3-
## Reporting a vulnerability
3+
## Vulnerability Disclosure and Bug Bounty
44

5-
If you discover a security vulnerability, please report it responsibly. Do not publicly disclose the issue until your report has been addressed. Resources for reporting:
5+
Security is a top priority at Euler, and we engage in regular security reviews and have an active bug bounty program to ensure the integrity of our systems.
66

7-
- **Email:** [email protected]
8-
- **Further reading:** https://docs.euler.finance/security/overview
7+
To report a vulnerability, **please submit it through our bug bounty program**:
8+
[Euler Bug Bounty](https://euler.finance/bug-bounty)
9+
10+
**Reports sent via email will not be accepted.** Email should only be used for general security inquiries.
11+
12+
## Security Team Contact Details
13+
14+
For security-related questions or inquiries (not vulnerability reports), you can contact us via:
15+
- **Email**: [[email protected]](mailto:[email protected])
16+
- **PGP Encryption**: [Euler Public Key](https://euler.finance/.well-known/public-key.asc)
17+
18+
## Previous Security Reviews
19+
20+
Euler undergoes regular security audits. You can find details of previous security reviews here:
21+
[Euler Security Reviews](https://docs.euler.finance/security/security-reviews)
22+
23+
## Preferred Languages
24+
25+
We accept security-related inquiries in **English (en)**

TODO

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,18 @@
1-
! Don't make quotes that would cause a swap to fail if supply/borrow caps exceeded
2-
* Better revert messages when a swap fails due to maglev debt-limit/vault utilisation/etc
3-
* currently it's an arithmetic underflow
1+
* Better revert messages when a swap fails due to debt-limit/vault utilisation/etc
2+
* currently they are errors thrown by the vaults or arithmetic underflows
43

54

65
TESTING
76

87
* when exchange rate in vaults != 1
9-
* uniswap callback, flash swaps
10-
* hitting reserve/utilisation limits
11-
* AssetsOutOfOrderOrEqual
128

139

1410
MISC
1511

1612
? A really small swap could fail because deposit() results in 0 shares, which causes EVK to revert. Call convertToShares() first? Seems like overkill...
17-
? permit2 instead of regular approval: measure gas savings
1813
* Improve the efficiency of on-chain quoting
1914
* Probably necessary for supporting non-zero slippage swaps
20-
* Use unchecked math in verify() (needs careful boundary analysis)
21-
* Closed-form quoting solutions
15+
* Use fInverse() Closed-form quoting solutions
2216
* "Range hints" for the binary search
2317

2418

@@ -34,7 +28,3 @@ IDEAS
3428
* Could current reserves be calculated dynamically based on balances/debts/debt limits?
3529
* I guess you would lose a chunk of interest to arbitrage
3630
* Donation attacks?
37-
* What can we do to make this easily integrated with aggregators/MEV bots/etc?
38-
* How to handle a discovery/tracking of the different Maglev instances?
39-
? Factory? Registry? Maybe a fake factory that reads the actually installed operators from a set of addresses?
40-
? Transparent proxy so a Maglev address can stay constant

audits/eulerswap-audit-report.pdf

417 KB
Binary file not shown.

docs/.DS_Store

-6 KB
Binary file not shown.

docs/architecture.md

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,19 @@
22

33
## Overview
44

5-
EulerSwap is an automated market maker (AMM) that integrates with Euler lending vaults to provide deeper liquidity for swaps.
6-
7-
Unlike traditional AMMs that use shared liquidity pools, EulerSwap operates with independent swap accounts, where each account manages liquidity for a single user or entity.
5+
EulerSwap is an automated market maker (AMM) that integrates with Euler credit vaults to provide deeper liquidity for swaps.
86

97
Each EulerSwap instance is a lightweight smart contract that functions as an [EVC operator](https://evc.wtf/docs/whitepaper/#operators) while implementing a highly customizable AMM curve to determine swap output amounts.
108

11-
When a user initiates a swap, the swap account borrows the required output token using the input token as collateral. The swap account’s AMM curve governs the exchange rate, ensuring deep liquidity over short timeframes while maintaining a balance between collateral and debt over the long term.
9+
When a user initiates a swap, the EulerSwap operator borrows the required output token using the input token as collateral. The operator’s internal AMM curve governs the exchange rate, ensuring deep liquidity over short timeframes while maintaining a balance between collateral and debt over the long term.
1210

1311
## Code structure
1412

1513
EulerSwap’s code is split into two main smart contracts:
1614

1715
### EulerSwap core (`EulerSwap.sol`)
1816

19-
- Handles collateralization via EVC and Euler lending vaults.
17+
- Handles collateralization via EVC and Euler credit vaults.
2018
- Implements AMM curve invariant checks through the `verify()` function.
2119

2220
### EulerSwap periphery (`EulerSwapPeriphery.sol`)
@@ -26,10 +24,10 @@ EulerSwap’s code is split into two main smart contracts:
2624

2725
## Operational flow
2826

29-
The following steps outline how a swap account is created and configured:
27+
The following steps outline how an EulerSwap operator is created and configured:
3028

31-
1. Deposit initial liquidity into one or both of the vaults to enable swaps.
32-
2. Deploy the EulerSwap contract, specifying AMM curve parameters and the `fee`.
29+
1. Deposit initial liquidity into one or both of the underlying credit vaults to enable swaps.
30+
2. Deploy an instance of EulerSwap, specifying AMM curve parameters and the `fee`.
3331
3. Set the [virtual reserves](#virtual-reserves) by invoking `setVirtualReserves()`.
3432
4. Install the EulerSwap contract as an operator for the user's account.
3533
5. Invoke the `configure()` function on the EulerSwap contract.

docs/boundary-analysis.md

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
# Boundary analysis
2+
3+
## Introduction
4+
5+
The EulerSwap automated market maker (AMM) curve is governed by two key functions: f() and fInverse(). These functions are critical to maintaining protocol invariants and ensuring accurate swap calculations within the AMM. This document provides a detailed boundary analysis of both functions, assessing their Solidity implementations against the equations in the white paper. It ensures that appropriate safety measures are in place to avoid overflow, underflow, and precision loss, and that unchecked operations are thoroughly justified.
6+
7+
## Implementation of function `f()`
8+
9+
The `f()` function is part of the EulerSwap core, defined in `EulerSwap.sol`, and corresponds to equation (2) in the EulerSwap white paper. The `f()` function is a parameterisable curve in the `EulerSwap` contract that defines the permissible boundary for points in EulerSwap AMMs. The curve allows points on or above and to the right of the curve while restricting others. Its primary purpose is to act as an invariant validator by checking if a hypothetical state `(x, y)` within the AMM is valid. It also calculates swap output amounts for given inputs, though some swap scenarios require `fInverse()`.
10+
11+
### Derivation
12+
13+
This derivation shows how to implement the `f()` function in Solidity, starting from the theoretical model described in the EulerSwap white paper. The initial equation from the EulerSwap white paper is:
14+
15+
\[
16+
y_0 + \left(\frac{p_x}{p_y}\right) (x_0 - x) \left(c + (1 - c) \frac{x_0}{x}\right)
17+
\]
18+
19+
Multiply the second term by \(\frac{x}{x}\) and scale `c` by \(1e18\):
20+
21+
\[
22+
y_0 + \left(\frac{p_x}{p_y}\right) (x_0 - x) \frac{(c \cdot x) + (1e18 - c) \cdot x_0}{x \cdot 1e18}
23+
\]
24+
25+
Reorder division by \(p_y\) to prepare for Solidity implementation:
26+
27+
\[
28+
y_0 + p_x \cdot (x_0 - x) \cdot \frac{(c \cdot x) + (1e18 - c) \cdot x_0}{x \cdot 1e18} \cdot \frac{1}{p_y}
29+
\]
30+
31+
To avoid intermediate overflow, use `Math.mulDiv` in Solidity, which combines multiplication and division safely:
32+
33+
\[
34+
y_0 + \frac{\text{Math.mulDiv}(p_x \cdot (x_0 - x), c \cdot x + (1e18 - c) \cdot x_0, x \cdot 1e18)}{p_y}
35+
\]
36+
37+
Applying ceiling rounding with `Math.Rounding.Ceil` ensures accuracy:
38+
39+
\[
40+
y_0 + \left(\text{Math.mulDiv}(p_x \cdot (x_0 - x), c \cdot x + (1e18 - c) \cdot x_0, x \cdot 1e18, \text{Math.Rounding.Ceil}) + (p_y - 1)\right) / p_y
41+
\]
42+
43+
Adding `(p_y - 1)` ensures proper ceiling rounding by making sure the result is rounded up when the numerator is not perfectly divisible by `p_y`.
44+
45+
### Boundary analysis
46+
47+
#### Pre-conditions
48+
49+
- \(x \leq x_0\)
50+
- \(1e18 \leq p_x, p_y \leq 1e36\) (60 to 120 bits)
51+
- \(1 \leq x_0, y_0 \leq 2^{112} - 1 \approx 5.19e33\) (0 to 112 bits)
52+
- \(1 < c \leq 1e18\) (0 to 60 bits)
53+
54+
#### Step-by-step
55+
56+
The arguments to `mulDiv` are safe from overflow:
57+
58+
- **Arg 1:** `px * (x0 - x)``1e36 * (2**112 - 1)` ≈ 232 bits
59+
- **Arg 2:** `c * x + (1e18 - c) * x0``1e18 * (2**112 - 1) * 2` ≈ 173 bits
60+
- **Arg 3:** `x * 1e18``1e18 * (2**112 - 1)` ≈ 172 bits
61+
62+
If `mulDiv` or the addition with `y0` overflows, the result would exceed `type(uint112).max`. When `mulDiv` overflows, its result would be > `2**256 - 1`. Dividing by `py` (`1e36` max) gives ~`2**136`, which exceeds the `2**112 - 1` limit, meaning these results are invalid as they cannot be satisfied by any swapper.
63+
64+
#### Unchecked math considerations
65+
66+
The arguments to `mulDiv` are protected from overflow as demonstrated above. The `mulDiv` output is further limited to `2**248 - 1` to prevent overflow in subsequent operations:
67+
68+
```solidity
69+
unchecked {
70+
uint256 v = Math.mulDiv(px * (x0 - x), c * x + (1e18 - c) * x0, x * 1e18, Math.Rounding.Ceil);
71+
require(v <= type(uint248).max, Overflow());
72+
return y0 + (v + (py - 1)) / py;
73+
}
74+
```
75+
76+
This does not introduce additional failure cases. Even values between `2**248 - 1` and `2**256 - 1` would not reduce to `2**112 - 1`, aligning with the boundary analysis.
77+
78+
## Implementation of function `fInverse()`
79+
80+
The `fInverse()` function, defined in `EulerSwapPeriphery.sol`, is part of the periphery because it is not required as an invariant. Instead, its sole purpose is to facilitate specific swap input and output calculations that cannot be managed by `f()`. This function maps to equation (22) in the Appendix of the EulerSwap white paper.
81+
82+
### Boundary analysis
83+
84+
#### Pre-conditions
85+
86+
- \(y > y_0\)
87+
- \(1e18 \leq p_x, p_y \leq 1e36\) (60 to 120 bits)
88+
- \(1 \leq x_0, y_0 \leq 2^{112} - 1 \approx 5.19e33\) (0 to 112 bits)
89+
- \(1 < c \leq 1e18\) (0 to 60 bits)
90+
91+
#### Step-by-step
92+
93+
1. **A component (`A = 2 * c`)**
94+
95+
- Since `c <= 1e18`, `A = 2 * c <= 2e18`, well within `uint256` capacity (max `2**256 - 1`).
96+
97+
2. **B component calculation**
98+
99+
- `B = int256((px * (y - y0) + py - 1) / py) - int256((x0 * (2 * c - 1e18) + 1e18 - 1) / 1e18)`
100+
- The first term is bounded by `(px * (y - y0)) / py`, where `px, py <= 1e36` and `(y - y0) <= 2**112 - 1`.
101+
- The second term scales `x0` with `(2 * c - 1e18)`, keeping the result well within the `int256` bounds due to controlled arithmetic and the limits on `c` and `x0`.
102+
103+
3. **Absolute value and B² computation**
104+
105+
- `absB = B < 0 ? uint256(-B) : uint256(B)`
106+
- `squaredB = Math.mulDiv(absB, absB, 1e18, Math.Rounding.Ceil)`
107+
- As `absB` is derived from `B`, and `B` is bounded, `squaredB` remains within a safe range.
108+
109+
4. **4AC Component (`AC4 = AC4a * AC4b / 1e18`)**
110+
111+
- `AC4a = Math.mulDiv(4 * c, (1e18 - c), 1e18, Math.Rounding.Ceil)`
112+
- `4 * c * (1e18 - c)` has a maximum of `1e18 * 1e18 = 1e36`, divided by `1e18`, the result ≤ `1e18`.
113+
- `AC4b = Math.mulDiv(x0, x0, 1e18, Math.Rounding.Ceil)`
114+
- The maximum value of `x0 * x0` is `(2**112 - 1)² ≈ 2**224`, safely within the `uint256` range.
115+
116+
5. **Discriminant calculation**
117+
118+
- `discriminant = (squaredB + AC4) * 1e18`
119+
- Since both `squaredB` and `AC4` are bounded by `uint256`, multiplying by `1e18` does not cause overflow.
120+
121+
6. **Square root computation and adjustment**
122+
123+
- `uint256 sqrt = Math.sqrt(discriminant)`
124+
- The square root of a `uint256` value is always within `uint128`, making this operation safe.
125+
- Adjustment step `sqrt = (sqrt * sqrt < discriminant) ? sqrt + 1 : sqrt` maintains precision without overflow.
126+
127+
7. **Final computation of `x`**
128+
- `Math.mulDiv(uint256(int256(sqrt) - B), 1e18, A, Math.Rounding.Ceil)`
129+
- The subtraction and multiplication are controlled by previous bounds, ensuring no overflow.
130+
- Division by `A` is safe as `A` is non-zero and small (`≤ 2e18`).
131+
132+
#### Unchecked math considerations
133+
134+
As above, the use of unchecked arithmetic is safe because all inputs are bounded by pre-conditions.
135+
136+
## Conclusion
137+
138+
The `f()` and `fInverse()` functions of EulerSwap are implemented with rigorous safety measures, using `Math.mulDiv` for safe arithmetic and applying ceiling rounding to maintain precision. Boundary analysis shows that all potential overflow scenarios are precluded by pre-condition checks and bounded operations, justifying the use of unchecked math in the Solidity implementation.

docs/interfaces.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -42,17 +42,17 @@ The `IEulerSwap` interface defines the core functionality for executing token sw
4242

4343
- **description**: Returns the address of asset 1.
4444

45-
#### `myAccount() external view returns (address);`
45+
#### `eulerAccount() external view returns (address);`
4646

4747
- **description**: Returns the address of the account managing EulerSwap.
4848

49-
#### `initialReserve0() external view returns (uint112);`
49+
#### `equilibriumReserve0() external view returns (uint112);`
5050

51-
- **description**: Returns the initial reserve amount of asset 0.
51+
- **description**: Returns the equilibrium reserve amount of asset 0.
5252

53-
#### `initialReserve1() external view returns (uint112);`
53+
#### `equilibriumReserve1() external view returns (uint112);`
5454

55-
- **description**: Returns the initial reserve amount of asset 1.
55+
- **description**: Returns the equilibrium reserve amount of asset 1.
5656

5757
#### `feeMultiplier() external view returns (uint256);`
5858

@@ -66,11 +66,11 @@ The `IEulerSwap` interface defines the core functionality for executing token sw
6666

6767
#### `priceX() external view returns (uint256);`
6868

69-
- **description**: Returns the price of asset X in terms of asset Y.
69+
- **description**: Returns the marginal price of asset X in terms of asset Y at the equilibrium point.
7070

7171
#### `priceY() external view returns (uint256);`
7272

73-
- **description**: Returns the price of asset Y in terms of asset X.
73+
- **description**: Returns the marginal price of asset Y in terms of asset X at the equilibrium point.
7474

7575
#### `concentrationX() external view returns (uint256);`
7676

0 commit comments

Comments
 (0)