# Auditing an AMM That Pays Swappers Tokens for Free

> ***Quick note before you read:*** *I audited TSwap, an excerpt from Cyfrin Updraft's Smart Contract Security course, and during that audit the pool turned out to hand its own reserves to whoever was swapping. TSwap is a teaching codebase, so this was a mock audit done for practice and not a paid engagement against a live protocol. Everything below is reproducible: every number comes from a Foundry test in the public repo linked at the end, and nothing here is a claim about any deployed protocol.*

## 1\. An AMM is just a promise

An automated market maker is a promise that the pool will always pay you the price its own formula says.

There is no order book and no counterparty. A liquidity provider deposits both tokens, and from then on the pool prices itself: you take some of one token out, you put enough of the other in to keep `x * y` the same. Nobody sets the price, the ratio of the two reserves is the price. Fees stay in the pool, so `k` slowly grows, and that growth is what the LP is paid for holding both assets.

That leaves only two ways for an AMM to leak money. Either the formula is implemented wrong, or someone finds a path through the pool that the formula never priced. Curve's Vyper pools lost around $70 million in July 2023 to a gap in the second category.

The maths is worth walking through once, because everything in this audit comes out of it:

```text
Pool: 100 WETH and 100 pool tokens, so k = 100 * 100 = 10,000

  reserve of pool tokens (y)
  ^
  |  *           every point on this curve is a valid pool state, the pool
  |     *        can only move along it, never off it
  |         *
  |             *
  |                 *
  +--------------------> reserve of WETH (x)

  x * y = k        price of one pool token = x / y

A swap is a walk along that curve:

  before:  x = 100.000 WETH    y = 100.000 PT    k = 10,000
  in:      +1.000 WETH, minus the 0.3% fee, so +0.997 WETH counts
  after:   x = 100.997 WETH    y = 99.013 PT     k = 10,000, held

  out to the caller   = 100.000 - 99.013 = 0.987 PT
  spot price before   = 1.000 WETH per PT
  price actually paid = 1.000 / 0.987 = 1.013 WETH per PT

  that 1.3% gap is slippage, and it exists because the pool walked the curve
```

The same idea in the codebase. The fee is applied once, and the product is rearranged instead of iterated:

```javascript
function getOutputAmountBasedOnInput(
    uint256 inputAmount,
    uint256 inputReserves,
    uint256 outputReserves
)
    public
    pure
    revertIfZero(inputAmount)
    revertIfZero(outputReserves)
    returns (uint256 outputAmount)
{
    // @AUDIT-info:: magic numbers, both 997 and 1000 should be constants
    uint256 inputAmountMinusFee = inputAmount * 997;
    uint256 numerator = inputAmountMinusFee * outputReserves;
    uint256 denominator = (inputReserves * 1000) + inputAmountMinusFee;
    return numerator / denominator;
}
```

Two contracts are in scope: `PoolFactory` at 93 lines, which creates pools and their LP tokens, and `TSwapPool` at 489 lines, which holds the reserves, does deposits, withdrawals and swaps.

I worked on the branch `audit-by-ayaan`. The commit hash in the onboarding material did not resolve, so I cut the branch from `main` and recorded it, same as the previous two audits. An audit is only valid for an exact commit, and if the docs point at a stale one, you say so in the report instead of quietly auditing whatever `main` is today.

The first thing I ran was `forge coverage`, and it told me something before I read a single line of Solidity. Almost none of the pool is exercised by the client's tests, which means the test suite itself is part of the audit surface. A protocol holding user funds with no invariant tests is not a small gap in coverage, it is an unproven claim.

## 2\. How I audited it

Order of work:

1. **Onboarding and sizing.** Read the answered onboarding questions, cloned the repo, checked coverage, ran Solidity Metrics so I knew how big the surface actually was.
2. **Static analysis first, triage second.** Two tools, because they do not report the same things.
3. **Manual review, protocol first.** I read the deposit path, then the withdrawal path, then both pricing functions side by side, because an AMM's bugs live in the maths, not in the plumbing.
4. **Invariant testing.** The client shipped unit tests only, so I built a handler-based invariant suite to check what the maths promised across sequences of calls, not on single clean runs.
5. **A proof for every High, Medium and Low.** Foundry tests, one per finding, named with an `_AUDIT` suffix so the suite documents itself.

The tooling passes, in the order I ran them:

```shell
forge coverage --report debug > coverage-report.txt

make slither
# INFO:Slither:. analyzed (13 contracts with 100 detectors), 4 result(s) found

aderyn .
# wrote report.md: 1 High, 5 Low
```

Slither's 4 results were all yellow or green: `incorrect-equality` and `missing-zero-check` in yellow, `pragma` and `unindexed-event-address` in green. Nothing that demands a stop, which is a triage result and not absolution.

Aderyn's High was worth reading: state written after an external call in `PoolFactory.createPool`. The pattern is real, but the factory holds no user funds and `createPool` is permissionless, so nothing is at risk. I logged it as Informational and wrote the reasoning down, because "the tool said High" is not an impact analysis.

At the end of the audit the whole suite is green, and this is the run I get today:

```shell
forge test

Ran 2 tests for test/unit/PoolFactoryTest.t.sol:PoolFactoryTest
Suite result: ok. 2 passed; 0 failed; 0 skipped

Ran 9 tests for test/unit/TSwapPool.t.sol:TSwapPoolTest
[PASS] testDeposit() (gas: 303267)
[PASS] testWithdraw() (gas: 390778)
[PASS] testDepositSwap() (gas: 397902)
[PASS] testCollectFees() (gas: 528150)
[PASS] test_DepositIgnoresDeadline_AUDIT() (gas: 308785)
[PASS] test_SellPoolTokensWrongAmount_AUDIT() (gas: 556956)
[PASS] test_SwapExactOutputNoMaxInput_AUDIT() (gas: 643771)
[PASS] test_SwapExactOutputOvercharges_AUDIT() (gas: 467040)
[PASS] test_SwapIncentiveBreaksInvariant_AUDIT() (gas: 1159730)
Suite result: ok. 9 passed; 0 failed; 0 skipped

Ran 3 test suites in 5.61s: 12 tests passed, 0 failed, 0 skipped (12 total tests)
```

The audit produced 22 findings: 2 High, 2 Medium, 1 Low, 17 Informational. Both Highs are pricing bugs. One of them is a single wrong digit.

## 3\. The invariant suite, and the number that gave the bug away

The pool prices two ways: exact input swaps and exact output swaps. Both are the same formula read in opposite directions, so the fairest thing you can assert is that the pool's own accounting agrees with its own quotes.

I wrote `test/invariant/Invariant.t.sol` and `test/invariant/Handler.t.sol`. The handler wraps the pool so the fuzzer only calls realistic, bounded actions instead of hammering functions with numbers that always revert, and it is wired into the fuzzer like this:

```javascript
handler = new Handler(pool);

bytes4[] memory selectors = new bytes4[](2);
selectors[0] = handler.deposit.selector;
selectors[1] = handler.swapPoolTokenForWethBasedOnOutputWeth.selector;

targetSelector(FuzzSelector({addr: address(handler), selectors: selectors}));
targetContract(address(handler));
```

The handler itself bounds every random input into the pool's valid range, and returns early instead of reverting when a sequence is not viable:

```javascript
function deposit(uint256 _wethAmount) public {
    _wethAmount = bound(_wethAmount, 0, type(uint64).max);
    expectedDeltaY = _wethAmount;
    expectedDeltaX = pool.getPoolTokensToDepositBasedOnWeth(_wethAmount);

    vm.startPrank(liquidityProvider);
    wethToken.mint(liquidityProvider, expectedDeltaY);
    poolToken.mint(liquidityProvider, expectedDeltaX);
    wethToken.approve(address(pool), type(uint256).max);
    poolToken.approve(address(pool), type(uint256).max);

    pool.deposit(expectedDeltaY, 0, expectedDeltaX, uint64(block.timestamp));
    vm.stopPrank();
}

function swapPoolTokenForWethBasedOnOutputWeth(uint256 _outputWeth) public {
    _outputWeth = bound(_outputWeth, 0, type(uint64).max);

    if (_outputWeth > wethToken.balanceOf(address(pool))) {
        return;
    }
    // ... approve, then swap, recording expectedDeltaX / expectedDeltaY
}
```

The repo ships the fuzzer config in `foundry.toml`, and the two numbers that matter are `runs` and `depth`:

```javascript
[invariant]
runs = 1000             // 1000 independent sequences
depth = 32              // 32 calls inside ONE sequence, so one shared state
fail_on_revert = true
```

The first run failed, and it failed because of me, not the pool. My handler measured reserves on `address(this)` instead of the pool, so it was comparing the pool's quote against a balance that never moves. That is a lesson I wrote into the repo notes: check the harness before you write a finding, because a broken handler produces exactly the same output as a broken protocol.

After the fix it passes:

```shell
forge test --mt invariant_constantProductFormulaStaysSame_AUDIT -vvv

[PASS] invariant_constantProductFormulaStaysSame_AUDIT() (runs: 1000, calls: 32000, reverts: 0)

| Handler  | deposit                               | 15883 calls | 0 reverts |
| Handler  | swapPoolTokenForWethBasedOnOutputWeth | 16117 calls | 0 reverts |
```

Passing here means less than it looks, and it is worth being honest about why. The handler asks the pool what the swap costs, then the pool charges what it quoted, so the check is circular: it proves the transfer matches the quote, nothing about whether the quote is fair.

What it did do is force me to put the two pricing functions on the same screen for the first time. That is where the bug appeared:

```javascript
// getOutputAmountBasedOnInput: fee applied once, base 1000
uint256 inputAmountMinusFee = inputAmount * 997;
uint256 denominator = (inputReserves * 1000) + inputAmountMinusFee;

// getInputAmountBasedOnOutput: same intent, base 10000
return ((inputReserves * outputAmount) * 10000) /
    ((outputReserves - outputAmount) * 997);
```

One function divides by `1000`, the other multiplies by `10000`. A test suite that never faces those two functions at each other will never show you that. From there the rest of the audit was arithmetic.

## 4\. Findings at a glance

- **H-1, High, TSwapPool:** the fee multiplier in `getInputAmountBasedOnOutput` is `10000` instead of `1000`, so every exact output swap charges about 10x the fair input.
- **H-2, High, TSwapPool:** `_swap` pays the caller 1e18 of the output token every tenth swap, straight out of the reserves, so `k` falls instead of holding.
- **M-1, Medium, TSwapPool:** `swapExactOutput` has no maximum input parameter, so a caller cannot bound their slippage on that path.
- **M-2, Medium, TSwapPool:** `sellPoolTokens` forwards the amount to sell as the exact WETH output, so the caller gets a different trade than the one they asked for.
- **L-1, Low, TSwapPool:** `deposit` accepts a deadline and never checks it.
- **I-1 to I-17, Informational:** 17 notes across both contracts, including `0.8.20` pinned to Shanghai so the bytecode emits `PUSH0`, magic numbers that should be the named fee constants, unindexed event addresses, missing zero address checks, a swapped argument in the `LiquidityAdded` event, `swapExactInput` returning a hardcoded `0` because its named return is never assigned, a hardcoded deadline in `sellPoolTokens`, and a factory that reverts for any token whose `name()` reverts.

Every one of those was tagged in the client's source as I found it, so the report and the code point at each other:

```javascript
// @AUDIT-HIGH:: the maths is WRONG. users are charged way too much in here!
// @AUDIT-HIGH:: free 1e18 tokens every 10th swap, breaks x*y=k and can be farmed
// @AUDIT-Medium:: Need a max input amount check just like in the swapExactInput function
// @AUDIT-Medium:: poolTokenAmount is passed as the WETH output instead of the amount being sold
// @AUDIT-Low:: deadline is passed in but never used, there is no deadline check in deposit
// @AUDIT-info:: magic numbers, both 997 and 1000 should be constants
```

## 5\. H-1: the fee that charges 10x

`getInputAmountBasedOnOutput` answers one question: how much input must a caller pay to receive an exact output amount. It answers with the wrong fee base:

```javascript
function getInputAmountBasedOnOutput(
    uint256 outputAmount,
    uint256 inputReserves,
    uint256 outputReserves
)
    public
    pure
    returns (uint256 inputAmount)
{
    // @AUDIT-HIGH:: the maths is WRONG. users are charged way too much in here!
    return ((inputReserves * outputAmount) * 10000) /
        ((outputReserves - outputAmount) * 997);
}
```

The mirror function applies the fee once, as `997 / 1000`. This one multiplies by `10000` and divides by `997`, which applies the same fee and then leaves a factor of 10 behind. So the required input comes out roughly 10x too large, and the caller pays it.

Every caller of `swapExactOutput` is overcharged, and `sellPoolTokens` routes through the same function, so a user selling through the pool's own helper is hit twice. The extra tokens stay in the pool, which means the caller loses real funds on every exact output swap while the liquidity providers gain at their expense.

The proof:

```javascript
function test_SwapExactOutputOvercharges_AUDIT() public {
    vm.startPrank(liquidityProvider);
    weth.approve(address(pool), 100e18);
    poolToken.approve(address(pool), 100e18);
    pool.deposit(100e18, 100e18, 100e18, uint64(block.timestamp));
    vm.stopPrank();

    uint256 wethReserves = weth.balanceOf(address(pool));
    uint256 poolTokenReserves = poolToken.balanceOf(address(pool));
    uint256 outputWeth = 0.5e18;

    // the same formula with the fee applied once, which is the fair price
    uint256 fairInput = (poolTokenReserves * outputWeth * 1000) /
        ((wethReserves - outputWeth) * 997);

    // what the pool actually asks for
    uint256 quotedInput = pool.getInputAmountBasedOnOutput(
        outputWeth,
        poolTokenReserves,
        wethReserves
    );

    assertGt(quotedInput, fairInput * 9);

    vm.startPrank(user);
    poolToken.approve(address(pool), type(uint256).max);
    uint256 balanceBefore = poolToken.balanceOf(user);
    pool.swapExactOutput(poolToken, weth, outputWeth, uint64(block.timestamp));
    uint256 paid = balanceBefore - poolToken.balanceOf(user);
    vm.stopPrank();

    assertEq(paid, quotedInput);
}
```

```shell
forge test --mt test_SwapExactOutputOvercharges_AUDIT -vv

Logs:
  charged input: 5040246367242430810
  fair input: 504024636724243081
  actually paid: 5040246367242430810
```

The caller pays `5.04e18` pool tokens to receive `0.5e18` WETH, where the fair price is `0.504e18`. That is a clean 10x, and the pool really takes it: the third log line is the caller's actual balance change, not the quote.

The fix is one digit, plus the reason the digit drifted in the first place:

```javascript
-    return ((inputReserves * outputAmount) * 10000) /
-        ((outputReserves - outputAmount) * 997);
+    uint256 private constant FEE_MULTIPLIER = 997;
+    uint256 private constant FEE_BASE = 1000;
+
+    return ((inputReserves * outputAmount) * FEE_BASE) /
+        ((outputReserves - outputAmount) * FEE_MULTIPLIER);
```

Naming the constants is the part that matters. `997 / 1000` is the fee factor and the exact output formula uses its inverse, so naming them after the factor keeps the two directions from drifting apart again the next time someone edits one of them.

## 6\. H-2: the tenth swap pays 1e18 for free

`_swap` is the only place where the pool's reserves move, and it ends like this:

```javascript
// @AUDIT-HIGH:: free 1e18 tokens every 10th swap, breaks x*y=k and can be farmed
swap_count++;
if (swap_count >= SWAP_COUNT_MAX) {
    swap_count = 0;
    outputToken.safeTransfer(msg.sender, 1_000_000_000_000_000_000);
}
```

Every tenth swap, the pool sends the caller an extra 1e18 of the output token, and it receives nothing for it. The pool's reserves only have one legitimate source of outflow, the swap maths, and this is a second one bolted onto the side.

Three things follow. The pool's `x * y` falls on a fixed schedule instead of holding or growing, which is a direct transfer from liquidity providers to whoever made the tenth swap. It is farmable, because the bonus is a flat 1e18 regardless of swap size, so anyone can make nine dust swaps and collect a real payout on the tenth. And because the transfer happens before the swap settles, a pool holding less than 1e18 of the output token cannot complete its tenth swap at all: it reverts, and the pool stops trading.

The shape of it, in one picture:

```text
nine swaps:     every swap leaves a little more than it took, so k creeps up
                (the fee stays in the pool, that is the LP's income)

tenth swap:     the input comes in as normal
                and 1e18 of the output token leaves as a bonus

  k before the tenth swap:  10000268662499607603075500000000000000000
  k after  the tenth swap:   9899298366356141334213000000000000000000

  -1.0% in a single swap, paid out of the LP's reserves, not out of the maths
```

This is the finding I would have missed if I had read the code instead of reading the feature. It is not hidden. It is documented in the repo as a swap incentive, and the bug is entirely in the impact rather than in the intent.

The proof:

```javascript
function test_SwapIncentiveBreaksInvariant_AUDIT() public {
    // liquidity setup, then nine normal swaps so the tenth pays the bonus
    for (uint256 i = 0; i < 9; i++) {
        pool.swapExactInput(poolToken, 0.1e18, weth, 0, uint64(block.timestamp));
    }

    uint256 kBefore = weth.balanceOf(address(pool)) *
        poolToken.balanceOf(address(pool));

    uint256 expectedOut = pool.getOutputAmountBasedOnInput(
        0.1e18,
        poolToken.balanceOf(address(pool)),
        weth.balanceOf(address(pool))
    );

    uint256 wethBefore = weth.balanceOf(user);
    pool.swapExactInput(poolToken, 0.1e18, weth, 0, uint64(block.timestamp));
    uint256 received = weth.balanceOf(user) - wethBefore;

    assertEq(received, expectedOut + 1e18);
    assertLt(weth.balanceOf(address(pool)) * poolToken.balanceOf(address(pool)), kBefore);
}
```

```shell
forge test --mt test_SwapIncentiveBreaksInvariant_AUDIT -vv

Logs:
  expected out: 97835298857383282
  actually received: 1097835298857383282
  k before: 10000268662499607603075500000000000000000
  k after: 9899298366356141334213000000000000000000
```

The caller was owed `0.0978e18` WETH and received `1.0978e18`, and `k` dropped by about 1 percent of its value in a single swap.

The fix is to delete it, because a pool's reserves should only ever move by the swap maths:

```javascript
-    uint256 private swap_count = 0;
-    uint256 private constant SWAP_COUNT_MAX = 10;
```

If the incentive is a product requirement, the honest version is to fund it from a separate rewards contract or an owner funded balance, so paying it never touches LP reserves, and to make it proportional to the swap size so it cannot be farmed with dust swaps. Also worth noting for the report: the PoC has to change with the fix, since it asserts the bonus exists. After the fix it should assert `received == expectedOut` and that `k` no longer falls.

## 7\. M-1: exact output swaps have no upper bound

`swapExactInput` takes a `minOutputAmount`, so a caller can say "I will not accept less than this". `swapExactOutput` computes the input itself and swaps, with no equivalent parameter:

```javascript
function swapExactOutput(
    IERC20 inputToken,
    IERC20 outputToken,
    uint256 outputAmount,
    uint64 deadline
)
    public
    revertIfZero(outputAmount)
    revertIfDeadlinePassed(deadline)
    returns (uint256 inputAmount)
{
    uint256 inputReserves = inputToken.balanceOf(address(this));
    uint256 outputReserves = outputToken.balanceOf(address(this));

    inputAmount = getInputAmountBasedOnOutput(
        outputAmount,
        inputReserves,
        outputReserves
    );

    // @AUDIT-Medium:: Need a max input amount check just like in the swapExactInput function
    _swap(inputToken, inputAmount, outputToken, outputAmount);
}
```

If the transaction lands after the price has moved, or after someone has sandwiched it, the swap still executes at the worse price and nothing reverts. The caller had no parameter to protect themselves with.

The proof swaps first to move the price, then executes the same exact output swap:

```shell
forge test --mt test_SwapExactOutputNoMaxInput_AUDIT -vv

Logs:
  input before the price move: 10131404313951956880
  input after the price move: 22888113791382523076
  paid at the worse price: 22888113791382523076
```

The same `1e18` WETH output cost `10.13` pool tokens before the move and `22.88` after it, a 2.26x overpay that the caller could not stop. The fix is the mirror of the parameter that already exists on the input side:

```javascript
+    error TSwapPool__InputTooHigh(uint256 inputAmount, uint256 maxInputAmount);

     function swapExactOutput(
         IERC20 inputToken,
         IERC20 outputToken,
         uint256 outputAmount,
+        uint256 maxInputAmount,
         uint64 deadline
     )
...
+        if (inputAmount > maxInputAmount) {
+            revert TSwapPool__InputTooHigh(inputAmount, maxInputAmount);
+        }
         _swap(inputToken, inputAmount, outputToken, outputAmount);
```

That changes a public function signature, so `sellPoolTokens` and any integrator calling it has to land in the same change.

## 8\. M-2: sellPoolTokens sells the wrong amount

This one is a naming bug with a money consequence. The function is documented as "sell this many pool tokens for WETH", and it forwards that number as the output:

```javascript
function sellPoolTokens(
    uint256 poolTokenAmount
) external returns (uint256 wethAmount) {
    // @AUDIT-Medium:: poolTokenAmount is passed as the WETH output instead of the amount being sold
    return
        swapExactOutput(
            i_poolToken,
            i_wethToken,
            poolTokenAmount,
            // @AUDIT-info:: deadline is block.timestamp, so the check always passes
            uint64(block.timestamp)
        );
}
```

So the caller receives exactly `poolTokenAmount` in WETH, and pays whatever number of pool tokens the pool decides it needs for that. The value it returns as `wethAmount` is wrong too, since `swapExactOutput` returns its computed input, which means `wethAmount` is really the pool tokens that were spent.

```shell
forge test --mt test_SellPoolTokensWrongAmount_AUDIT -vv

Logs:
  asked to sell: 5000000000000000000
  pool tokens actually spent: 52789948793749670062
  weth actually received: 5000000000000000000
```

A seller asking to sell `5e18` pool tokens was charged `52.79e18` of them. The same test also shows a seller holding `10e18` pool tokens, twice what they intend to sell, reverting entirely, because the pool tries to pull `52.79e18`. On top of that, the deadline is hardcoded to `block.timestamp`, so the deadline check on this path can never fail, and the missing max input from M-1 applies here too. A user of the pool's own helper has no slippage protection of any kind.

The fix is to make it a sale, which means an input based swap with a minimum the caller sets:

```javascript
+ function sellPoolTokens(
+     uint256 poolTokenAmount,
+     uint256 minWethToReceive,
+     uint64 deadline
+ ) external returns (uint256 wethAmount) {
+     wethAmount = swapExactInput(
+         i_poolToken,
+         poolTokenAmount,
+         i_wethToken,
+         minWethToReceive,
+         deadline
+     );
+ }
```

One caveat, and it is logged separately as an Informational: `swapExactInput` currently returns a hardcoded `0` because its named return value is never assigned. That has to be fixed before this return value can be trusted.

## 9\. L-1: deposit takes a deadline and ignores it

`deposit` accepts a deadline and the natspec documents it, but the `revertIfDeadlinePassed` modifier is never applied, so the parameter is never read:

```javascript
function deposit(
    uint256 wethToDeposit,
    uint256 minimumLiquidityTokensToMint,
    uint256 maximumPoolTokensToDeposit,
    // @AUDIT-Low:: deadline is passed in but never used, there is no deadline check in deposit
    uint64 deadline
)
    external
    revertIfZero(wethToDeposit)
    returns (uint256 liquidityTokensToMint)
```

The modifier already exists in the contract, and `withdraw`, `swapExactInput` and `swapExactOutput` all use it:

```javascript
modifier revertIfDeadlinePassed(uint64 deadline) {
    if (deadline < uint64(block.timestamp)) {
        revert TSwapPool__DeadlineHasPassed(deadline);
    }
    _;
}
```

```shell
forge test --mt test_DepositIgnoresDeadline_AUDIT -vv

Logs:
  lp tokens minted with an expired deadline: 100000000000000000000
```

An expired deadline was accepted by `deposit` in the same run where `withdraw` rejected it with `TSwapPool__DeadlineHasPassed`. I kept this at Low and said why in the report: on a normal deposit the pricing damage is bounded, because `minimumLiquidityTokensToMint` and `maximumPoolTokensToDeposit` are both checked there. What is missing is the deadline the user explicitly asked for, which means a transaction can sit in the mempool and land whenever it likes.

The fix is the modifier that is already sitting in the file:

```javascript
     function deposit(
         uint256 wethToDeposit,
         uint256 minimumLiquidityTokensToMint,
         uint256 maximumPoolTokensToDeposit,
         uint64 deadline
     )
         external
+        revertIfDeadlinePassed(deadline)
         revertIfZero(wethToDeposit)
         returns (uint256 liquidityTokensToMint)
```

The PoC has to be flipped after the fix, since it currently asserts that the expired deposit succeeds.

## 10\. What I would do differently

- **I should have read both pricing functions side by side on day one.** H-1 was one digit apart in two functions that sit twenty lines from each other. I found it while writing invariants, which is later than it needed to be.
- **Write the invariant suite before the manual review, not after.** It did not catch the bug by asserting anything, it caught it by forcing me to lay the two formulas next to each other.
- **Threat model the documented features, not just the code.** H-2 was a feature with a comment and a constant. Reading code for mistakes misses the class of bug where the code does exactly what it says and the protocol still bleeds.
- **Trust the harness last, not first.** My first invariant run failed because my handler measured the wrong balance, and a broken handler looks exactly like a broken protocol:

```javascript
-    startingX = wethToken.balanceOf(address(this));
-    startingY = poolToken.balanceOf(address(this));
+    startingX = wethToken.balanceOf(address(pool));
+    startingY = poolToken.balanceOf(address(pool));
```

- **Keep the report honest about the tools.** Slither's 4 results and Aderyn's High were both worth reading and neither was a finding at the severity the tool claimed. Writing down the reasoning is what makes the report usable by the next person.

## 11\. Repo, report, and what is next

- Audit repo with all findings, PoCs and reports: <https://github.com/moayaan1911/security>
- Full 26-page TSwap report (all 22 findings, PoCs, severity reasoning, fixes): [TSwap report (PDF)](https://github.com/moayaan1911/security/blob/main/05-tswap_audit/audit_data/report.pdf)
- Previous posts: "What I Learnt From My First Smart Contract Audit" and "Boss Bridge Audit: Four High Severity Findings in a Cross-Chain Bridge", both on Medium.

You can run the whole thing yourself:

```shell
git clone https://github.com/moayaan1911/security
cd security/05-tswap_audit/tswap
forge install
forge test
```

Next in this series: Thunder Loan, where a WETH-denominated fee gets charged in token units, a plain deposit inflates the exchange rate, and an upgrade moves storage into the wrong slot.

## Disclaimer

This was a **mock audit for learning purposes**, performed against Cyfrin Updraft's TSwap training codebase as part of the Cyfrin Updraft Smart Contract Security course. It is not a paid engagement, not a security guarantee, and not a review of any deployed protocol. All vulnerabilities described here exist in a deliberately vulnerable teaching repo. Nothing in this post is financial or security advice. If you are shipping an AMM, get a real audit from a qualified firm, and remember that an audit is a point-in-time snapshot, not a proof of safety.

## About the author

I am MD Ayaan Siddiqui, a blockchain developer from India with 2+ years of production experience. I have built and shipped contracts for a DeFi stablecoin protocol audited by Cyfrin and ScaleBit, worked on hardware wallet features at Cypherock, and published pre-print research on cross-chain agentic infrastructure.

Currently working through smart contract security full time: five practice audits so far (PasswordStore, Puppy Raffle, TSwap, Thunder Loan, Boss Bridge), 66 findings, all with reports and PoCs in the repo.

- Portfolio: <https://moayaan.com>
- GitHub: <https://github.com/moayaan1911>
- X: <https://x.com/moayaan1911>
- Telegram: <https://t.me/moayaan1911>
- Medium: <https://medium.com/@moayaan.eth>

If you are hiring for audit or security work, or you want a second pair of eyes on a Solidity codebase, my inbox is open.
