Skip to content
Search ⌘/Ctrl+K Book a call Start a run

Type to search.

    Benchmarks

    Data generated · 31 fixtures · 289 tasks

    Crypto Security Bench is a benchmark that measures AI security agents’ ability to identify vulnerabilities in blockchain code. It includes 289 ground-truth vulnerabilities across 31 projects, spanning Solidity, Rust, C++, and Go codebases. Unlike other benchmarks like EVMBench, Crypto Security Bench includes both smart contracts as well as L1/core blockchain code. We compare our system, V12, with Codex Security, Pashov Skills (run on Claude Opus 5.5 and on Codex GPT-6 Sol), Devin Security, Devin Security (Deep), Claude Security (run on Claude Sonnet 5.5 and on Claude Opus 5.5), and Vercel Security Review.

    Overall performance

    We ran each system against the codebases in Crypto Security Bench. We report recall, the fraction of ground truth bugs each system successfully identified.

    Recall on all 289 tasks
    System Detected Recall
    V12 247 / 289 85.5%
    Devin Security (Deep) 145 / 289 50.2%
    Claude Security (Sonnet 5.5) 109 / 289 37.7%
    Claude Security (Opus 5.5) 104 / 289 36.0%
    Codex Security (GPT-6 Sol) 92 / 289 31.8%
    Devin Security 87 / 289 30.1%
    Vercel Security Review 73 / 289 25.3%

    Solidity head-to-head

    Pashov Skills only audits Solidity, so it can’t be ranked against the others on the full 289-task set. We evaluated both Pashov Skills runs on the 92 Solidity tasks:

    Recall on the 92 Solidity tasks
    System Detected Recall
    V12 87 / 92 94.6%
    Codex Security (GPT-6 Sol) 34 / 92 37.0%
    Pashov (Claude Opus 5.5 high) 67 / 92 72.8%
    Pashov (Codex GPT-6 Sol high) 56 / 92 60.9%
    Devin Security 44 / 92 47.8%
    Devin Security (Deep) 69 / 92 75.0%
    Claude Security (Sonnet 5.5) 43 / 92 46.7%
    Claude Security (Opus 5.5) 43 / 92 46.7%
    Vercel Security Review 39 / 92 42.4%

    Performance by language

    Recall grouped by language.

    Recall by language
    Language V12Codex Security (GPT-6 Sol)Pashov (Claude Opus 5.5 high)Pashov (Codex GPT-6 Sol high)Devin SecurityDevin Security (Deep)Claude Security (Sonnet 5.5)Claude Security (Opus 5.5)Vercel Security Review
    Rust 80.7% (117 of 145) 28.3% (41 of 145) Not evaluated Not evaluated 17.2% (25 of 145) 34.5% (50 of 145) 24.1% (35 of 145) 22.8% (33 of 145) 14.5% (21 of 145)
    C++ 75.0% (21 of 28) 21.4% (6 of 28) Not evaluated Not evaluated 21.4% (6 of 28) 35.7% (10 of 28) 50.0% (14 of 28) 46.4% (13 of 28) 10.7% (3 of 28)
    Solidity 94.6% (87 of 92) 37.0% (34 of 92) 72.8% (67 of 92) 60.9% (56 of 92) 47.8% (44 of 92) 75.0% (69 of 92) 46.7% (43 of 92) 46.7% (43 of 92) 42.4% (39 of 92)
    Go 91.7% (22 of 24) 45.8% (11 of 24) Not evaluated Not evaluated 50.0% (12 of 24) 66.7% (16 of 24) 70.8% (17 of 24) 62.5% (15 of 24) 41.7% (10 of 24)
    Recall per language: the share of that language's tasks each system detected. Rust 145 · C++ 28 · Solidity 92 · Go 24 tasks.

    Detailed results

    List of all ground-truth vulnerabilities included in Crypto Security Bench, along with the vulnerability reports generated by each system tested. Each fixture links to an associated human audit report.

    Show fixtures in
    • Ante Solidity Onchain prediction-market protocol. Tasks 3 V12 3/3 Codex Sec 2/3 Pashov Opus 3/3 Pashov GPT-6 3/3 Devin 3/3 Devin (Deep) 3/3 Claude Sec 1/3 Claude Opus 1/3 Vercel 1/3

      Onchain prediction-market protocol.

      Read the audit report
      • Ability to force tests to fail with gas limit ante-1 · 5 writeups Critical

        V12

        Gas-starved checks can falsely authorize settlement

        contracts/AntePool.sol:567 Predicted severity: High

        Root cause

        External-check resource failure is treated as authoritative invariant failure without enforcing an adequate check gas budget. The caller controls transaction gas, while the pool commits value-moving failure settlement based on the catch result.

        Impact

        If a connected test's cost admits this gas interval, a challenger can cause staker and queued-withdrawal ETH to be distributed as failure rewards without a genuine invariant failure. The precise gas threshold is deployment/test-dependent and was not measured; this is a conditional security mechanism on the factory's arbitrary-test integration, not a claim that every supplied example is exploitable.

        Description

        _checkTestNoRevert() forwards the available call gas to checkTestPasses() and treats every callee failure as a failed invariant. It neither gives the check an explicit required gas allowance nor distinguishes callee out-of-gas from a genuine failed assertion. For a sufficiently expensive but passing Ante test, a mature challenger can select a transaction gas limit that exhausts the test's forwarded gas while leaving the EVM's retained gas sufficient to execute the failure snapshot. The pool then irreversibly records failure even though the same test would return true with adequate gas. This admission depends on the selected test's check cost and the gas needed for settlement; the supplied short constant-time examples alone do not establish that gas interval.

        Pashov (Claude Opus 5.5 high)

        checkTest treats any revert, including a caller-induced out-of-gas, as a test failure

        contracts/AntePool.sol:565 Predicted severity: Medium

        Root cause

        Reverts from the test are interpreted as failures without telling an out-of-gas or griefed revert apart from a genuine failure. No minimum gas is reserved or checked for the test call.

        Impact

        A challenger can mark a passing test as failed and drain the staker pool (staker principal plus pending withdrawals). They receive their pro-rata share of the stakers' funds plus the 5% verifier bounty.

        Description

        _checkTestNoRevert wraps anteTest.checkTestPasses() in try/catch and returns false on any revert. By the 63/64 rule, the external call gets at most 63/64 of the remaining gas, and the caller of checkTest chooses the transaction gas limit. If the test is gas-heavy, a challenger can pick a gas limit that makes checkTestPasses run out of gas. The 1/64 of gas kept back is still enough to run updateDecay, _calculateChallengerEligibility, and the state writes that set pendingFailure = true. The same applies to tests that call other contracts inside their own try/catch and return false on error: there, starving the inner call is enough.

        Exploit scenario

        A pool's test loops over many tested contracts or does heavy external reads and needs about 10M gas, or it wraps an external call in try/catch. An eligible challenger calls checkTest with a gas limit chosen so that checkTestPasses runs out of gas while about 150k gas remains for the failure bookkeeping. The pool records the failure, and the attacker claims the staked ETH.

        Recommendation

        After a failed call, check that the failure wasn't caused by gas exhaustion, e.g. require(gasleft() > gasBefore / 64 ...), or forward a fixed, explicitly required gas amount. Alternatively, only treat an explicit false return as failure and let reverts revert the checkTest transaction.

        Pashov (Codex GPT-6 Sol high)

        Caller-controlled gas can turn a passing test into a failure

        contracts/AntePool.sol:567 Predicted severity: Medium

        Root cause

        The pool does not distinguish a false test result from a test call that reverted or ran out of gas.

        Impact

        Medium severity: on pools with a gas-heavy passing test, a challenger can irreversibly mark the pool failed and take staker collateral.

        Description

        A caller can limit gas so a costly passing test runs out of gas; the catch path treats that execution failure as a failed test.

        Exploit scenario

        For a legitimate gas-heavy test that returns true with ample gas, a challenger sends checkTest with a gas limit that makes the test call run out while leaving enough gas after the catch to complete the failure branch. The pool records pendingFailure and pays claims.

        Recommendation

        Call the test with a fixed gas budget, require enough caller gas to supply that budget and finish settlement, and reject tests that exceed the budget during initialization rather than treating caller-induced exhaustion as failure.

        Devin Security

        checkTest treats an out-of-gas revert in the Ante Test as a failure, so a caller can fake a failure on gas-heavy tests

        contracts/AntePool.sol:565 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        On pools whose Ante Test uses a lot of gas, any challenger can trigger a false test failure by choosing a low gas limit, and then claim all staker funds in that pool.

        ##### What's wrong

        This is a gas-griefing bug in a try/catch. _checkTestNoRevert treats any revert from anteTest.checkTestPasses() as a failed test, including an out-of-gas revert. Under EIP-150, the outer call keeps 1/64 of the gas after the inner call fails. The caller picks the gas limit, so the caller can make the inner call fail on purpose while keeping enough gas to finish the failure path.

        ##### Who can do it

        Alice stakes 100 ETH in a pool whose test does a lot of work, for example a test that iterates over many addresses or tokens. Mallory stakes 0.01 ETH as a challenger, waits 12 blocks, and calls checkTest with a gas limit that is too small for the test but leaves 1/64 for the rest of the function. The test reverts out of gas, the catch returns false, and the pool records a failure.

        - Mallory needs a challenger position that is older than 12 blocks. Anyone with 0.01 ETH can get one.

        - The test's checkTestPasses must use more than about 63 times the gas that the rest of the failure path needs. This depends on the specific test and is likely only a few million gas, so it is plausible for heavy tests but not for simple ones.

        ##### What they get

        Mallory becomes the verifier. She receives the 5% bounty plus a share of the remaining staker funds in proportion to her challenger stake. If she adds more challenger stake ahead of time, she can take most of Alice's 100 ETH, even though the protocol the test protects is fine. This only works on pools whose test meets the gas condition.

        ##### How it works

        1. Mallory stakes as a challenger and waits more than 12 blocks, which passes the checks in checkTest (AntePool.sol:295-299).

        2. She calls checkTest with a chosen gas limit. _checkTestNoRevert forwards 63/64 of the gas to anteTest.checkTestPasses() (AntePool.sol:568).

        3. The test runs out of gas and reverts, and the catch branch returns false (AntePool.sol:570-571).

        4. checkTest sets pendingFailure, names Mallory as verifier, and computes _bounty and _remainingStake (AntePool.sol:304-315).

        5. Mallory calls claim and receives her share of the staker funds plus the bounty (AntePool.sol:321-336, 581-590).

        Exploit scenario

        Not specified.

        Recommendation

        Do not count an out-of-gas revert as a failure. One option is to check gasleft() inside the catch and revert if it is below about 1/63 of the gas forwarded, which means the inner call ran out of gas. Another option is to require a minimum gasleft() before the call that is large enough for the test. To check the fix, write a test with a gas-heavy mock AnteTest that passes, call checkTest with a gas limit that makes the inner call run out of gas, and confirm that the transaction reverts and pendingFailure stays false.

        Devin Security (Deep)

        Out-of-gas inside checkTestPasses is treated as a test failure, letting a caller force a false failure on gas-heavy tests

        contracts/AntePool.sol:565 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        For an Ante test whose checkTestPasses costs more than roughly 9 to 10 million gas, any eligible challenger can pick a gas limit that starves the test call so it runs out of gas, which the pool records as a failure and pays the whole staker pool to challengers even though the test actually passes.

        ##### What's wrong

        This is insufficient-gas griefing through a catch-all try/catch. _checkTestNoRevert treats every revert from checkTestPasses, including running out of gas, as the test failing. Under the 63/64 rule the caller keeps 1/64 of the remaining gas, so a caller can choose a gas limit at which the inner call dies but the outer failure bookkeeping still completes.

        ##### Who can do it

        Alice writes a test for Globex that walks a large list of vaults and costs about 12 million gas. Bob stakes 100 ETH on it. Mallory stakes 0.01 ETH as a challenger, waits 12 blocks, and calls checkTest with a gas limit of about 10 million. The test call gets about 9.8 million gas and runs out; the pool keeps about 150k gas, enough to record the failure.

        Conditions that must hold:

        * The connected test's checkTestPasses needs more than roughly 63 times the gas the failure bookkeeping needs, which is about 9 to 10 million gas with one challenger and more with many. Typical Ante tests that read a few balances are far cheaper and are not affected.

        * The caller is a registered challenger whose last stake is more than 12 blocks old.

        ##### What they get

        Mallory becomes the verifier and the test is marked failed while the Globex invariant still holds. Bob's 100 ETH is split between the 5 percent bounty and the eligible challengers, so Mallory and other challengers take money from stakers for a failure that never happened, and the test reads as failed forever.

        ##### How it works

        1. Mallory calls checkTest with a chosen gas limit (contracts/AntePool.sol:292).

        2. _checkTestNoRevert forwards 63/64 of the remaining gas to anteTest.checkTestPasses() (contracts/AntePool.sol:568).

        3. The test runs out of gas; the catch block returns false (contracts/AntePool.sol:570-572).

        4. checkTest records the failure with the retained 1/64 of gas: updateDecay, verifier, failedBlock, pendingFailure, eligibility and bounty (contracts/AntePool.sol:303-314).

        5. Challengers call claim and receive stakers' ETH (contracts/AntePool.sol:319-334).

        Exploit scenario

        Not specified.

        Recommendation

        Require a minimum gas budget before calling the test, for example require(gasleft() >= MIN_CHECK_GAS) with a per-pool or per-test configured value, or distinguish out-of-gas from an explicit revert by checking gasleft() after the call against the 63/64 bound and reverting the transaction if the inner call could have run out of gas. Verify with a Hardhat test using a mock test that burns 12 million gas and passes, calling checkTest with a 10 million gas limit, and asserting the transaction reverts rather than setting pendingFailure.

      • Number of challengers is constrained by block gas limit ante-2 · 9 writeups High

        V12

        Challenger spam blocks failure finalization

        contracts/AntePool.sol:186 Predicted severity: High

        Root cause

        Permissionless constant-cost membership growth creates an unbounded mandatory settlement loop. The failure transition cannot proceed independently of complete enumeration.

        Impact

        An external actor can prevent a failed test from being finalized by accumulating enough live challenger addresses, blocking failure payouts and allowing still-enabled staker withdrawals to remove the reward capital. Challenger deposits are recoverable through normal unstake while failure cannot finalize, so the attack primarily requires temporary capital and transaction costs rather than sacrificing every deposit.

        Description

        Failure eligibility calculation enumerates the entire live challenger set in a single transaction. stake(true) lets any caller add another unique address for 0.01 ETH, and the set has no size limit. Although library insertion and removal are constant-time, successful failure finalization requires storage reads and balance calculations for every remaining member. If that work exceeds transaction or block gas limits, checkTest() reverts, including its failure flag and all eligibility accounting. No batched or resumable calculation exists in the pool.

        Codex Security (GPT-6 Sol)

        Many challenger accounts can block pool failure settlement

        contracts/AntePool.sol:193 Predicted severity: Medium

        Root cause

        The pool accepts an unbounded number of challenger addresses but computes the total eligible balance by scanning all of them during a single failure transaction. A block gas limit can reject that transaction before state changes commit.

        Impact

        The denial can block a genuine failure, but requires many funded addresses and transactions; the capital remains locked while the attack is maintained.

        Description

        An adversary can fill a pool's challenger set with distinct funded accounts. A failing checkTest then iterates the entire set in one transaction and can exceed block gas, preventing failure payouts.

        Exploit scenario

        attacker-controlled challenger count → addresses array → failure-time loop → transaction gas exhaustion

        Recommendation

        Replace full failure-time enumeration with bounded incremental accounting or claim-time proofs tied to a failure snapshot.

        Pashov (Claude Opus 5.5 high)

        Unbounded loop over all challengers in checkTest lets anyone block test failure from ever being recorded

        contracts/AntePool.sol:553 Predicted severity: High

        Root cause

        The challenger payout eligibility is computed eagerly with an O(n) loop inside the one transaction that records the failure. The number of challengers is unbounded and attacker-controlled.

        Impact

        When the set is large enough, the failing branch of checkTest needs more gas than a block allows, so checkTest always reverts on a failing test. pendingFailure can then never become true. Challengers can never claim staker funds, and stakers keep earning decay from challengers although the invariant they insured is broken. The insurance mechanism, and the funds challengers expect to receive, is effectively stolen.

        Description

        When checkTest sees the Ante Test fail, it calls _calculateChallengerEligibility. That function walks the whole challengers set. For each entry it does several cold SLOADs (address, lastStakedBlock, startAmount, startDecayMultiplier) and a storage write to eligibilityInfo.eligibleAmount. The set has no size limit. Any address that stakes at least MIN_CHALLENGER_STAKE (0.01 ETH) on the challenger side is added to it.

        Exploit scenario

        A large staker (or the protocol a test covers) expects the test may fail. They create a few thousand fresh addresses, each staking 0.01 ETH as a challenger. At about 10k gas per iteration, roughly 3,000 entries (about 30 ETH, still owned by the attacker and only slowly decaying) push the failure path past the 30M block gas limit. When the protocol is later exploited and the test fails, every checkTest call by honest challengers runs out of gas. Stakers' funds can never be taken.

        Recommendation

        Don't iterate over all challengers at failure time. Track eligible and ineligible challenger amounts incrementally, e.g. record the challenger balance staked in the last CHALLENGER_BLOCK_DELAY blocks in a per-block or checkpoint structure. Alternatively, compute eligibility lazily per user in claim(). Another option is to cap the number of challengers or raise the minimum stake substantially.

        Pashov (Codex GPT-6 Sol high)

        Dust challenger entries can block failure settlement

        contracts/AntePool.sol:553 Predicted severity: High

        Root cause

        Failure settlement iterates every live challenger, and partial unstake preserves membership even when only 1 wei remains.

        Impact

        High severity: failure cannot be finalized, so challengers cannot claim and a staker can withdraw collateral even though the test has failed.

        Description

        A user can keep arbitrarily many dust challenger positions in the settlement loop until every failed checkTest transaction runs out of gas.

        Exploit scenario

        Create many challenger addresses, deposit the 0.01 ETH minimum from each, then unstake all but 1 wei from each. A subsequent failed checkTest must iterate all entries in one transaction, eventually exceeding the block gas limit.

        Recommendation

        Use bounded or paginated failure settlement with a fixed snapshot, and enforce a meaningful minimum on active challenger entries.

        Devin Security

        Unbounded loop over challengers lets anyone block checkTest from recording a test failure

        contracts/AntePool.sol:187 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A staker who expects the test to fail can open thousands of tiny challenger positions so that checkTest always runs out of gas, which stops the pool from ever paying challengers.

        ##### What's wrong

        This is a gas-limit denial of service from an unbounded loop. When the test fails, checkTest calls _calculateChallengerEligibility, which reads storage for every address in the challengers set in one transaction. Nothing caps the size of that set.

        ##### Who can do it

        Alice, a challenger, stakes against a protocol she thinks is unsafe. Mallory has a large staker position in the same pool. Mallory sees that the test is about to fail. She stakes 0.01 ETH as a challenger from a few thousand fresh addresses. Each loop step does several cold storage reads (about 8,000 to 10,000 gas), so roughly 3,000 to 4,000 addresses push the failure path past a 30M block gas limit.

        - Mallory has about 30 to 40 ETH to lock as challenger stake. She can take it back later, minus decay.

        - She adds the addresses before anyone calls checkTest on a failing test.

        ##### What they get

        When the test fails, every checkTest call reverts out of gas, so pendingFailure is never set. Mallory and the other stakers keep their stake, and they can unstake and withdraw after 24 hours. Alice and the other challengers never get the staker funds that the pool promises them, and their own stake keeps decaying to the stakers. This defeats the main guarantee of the pool. Each attack affects one pool.

        ##### How it works

        1. stake(true) adds any address with at least 0.01 ETH to challengers with no limit on the set size (AntePool.sol:193).

        2. checkTest finds the test failing and calls _calculateChallengerEligibility in the same transaction (AntePool.sol:309).

        3. _calculateChallengerEligibility loops over every challenger and reads lastStakedBlock plus the user's stored balance from storage (AntePool.sol:555-561).

        4. With enough addresses the loop costs more than the block gas limit, so the whole failure path reverts, and nothing records the failure.

        Exploit scenario

        Not specified.

        Recommendation

        Remove the per-challenger loop from checkTest. Track the eligible amount incrementally: keep a running total of stake that is older than 12 blocks, or record the failure first and compute eligibility lazily or in paged calls after pendingFailure is set. You could also raise the minimum challenger stake, but that only raises the attack cost. To check the fix, write a test that adds several thousand challenger addresses and then confirms that checkTest on a failing test stays well under the block gas limit and sets pendingFailure.

        Devin Security (Deep)

        Unbounded challenger loop in checkTest lets sybil challengers make a pool's test unfailable

        contracts/AntePool.sol:553 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can register a few thousand throwaway challenger addresses for gas money alone, after which the failure path of checkTest needs more gas than a block allows, so the test can never be marked failed, stakers can never be slashed, and honest challengers keep paying decay for a payout they can never collect.

        ##### What's wrong

        This is an unbounded loop over user-controlled storage on a critical path. _calculateChallengerEligibility walks every address in the challengers set and does four cold storage reads and a storage write per entry. Anyone can grow that set without limit, and the only way an entry leaves is if its owner unstakes to exactly zero. Because unstake has no minimum residual, each sybil can keep 1 wei and recycle the 0.01 ETH minimum to the next address, so growing the set costs only gas.

        ##### Who can do it

        Alice runs Globex Finance and Bob stakes 300 ETH on the test "Globex vault stays solvent". Trent, an honest challenger, puts 10 ETH against it. Mallory, who also stakes on the test and wants her stake to be safe no matter what, deploys 3,500 tiny contracts. Each one calls stake(true) with 0.01 ETH and then unstake(balance - 1, true), leaving 1 wei and freeing the 0.01 ETH for the next contract. The whole thing costs roughly 800 million gas spread over many blocks and no locked capital.

        Conditions that must hold:

        * The attacker can pay roughly 230k gas per sybil address; about 3,300 eligible challengers push the failure path of checkTest past a 30 million gas block.

        * No one can remove another user's address from challengers; only the owner can, by unstaking to exactly zero.

        * The attack is silent until the test actually fails.

        ##### What they get

        When the Globex vault really breaks, Trent calls checkTest. checkTestPasses returns false, and the pool starts summing eligible balances across 3,500 addresses. The transaction cannot fit in a block and reverts, every time, forever. Bob and Mallory keep all 300 ETH of stake, and the pool keeps reporting the test as never failed. Trent cannot collect the payout he earned and his 10 ETH keeps decaying into the stakers' pockets until he gives up and withdraws what is left. Every pool is independently attackable, and partial attacks already make checkTest cost tens of millions of gas.

        ##### How it works

        1. Mallory's sybil contract calls stake(true) with 0.01 ETH; challengers.insert adds it to the set (contracts/AntePool.sol:188-194).

        2. The contract calls unstake(balance - 1, true); _unstake only removes the address when prevAmount == amount, so the 1 wei entry stays in the set and the 0.01 ETH is returned (contracts/AntePool.sol:479-495).

        3. Repeat for thousands of addresses; nothing bounds challengers.addresses.length.

        4. When the test fails, checkTest calls _calculateChallengerEligibility (contracts/AntePool.sol:302-308).

        5. The loop reads addresses[i], lastStakedBlock, startAmount, startDecayMultiplier and writes eligibleAmount for every entry, about 9,000 gas each (contracts/AntePool.sol:553-563).

        6. Above about 3,300 entries the transaction exceeds the block gas limit, so pendingFailure can never become true and claim is never reachable.

        Exploit scenario

        Not specified.

        Recommendation

        Remove the per-address loop from the failure path. Track challenger eligibility incrementally: keep a running eligibleAmount that stake and unstake adjust (for example, treat a challenger's deposit as eligible once 12 blocks have passed and account for it lazily per user at claim time using the pool-wide multiplier and the user's lastStakedBlock), so checkTest does O(1) work. Alternatively, compute each challenger's eligibility inside claim from lastStakedBlock and failedBlock and derive the eligible total as challengerInfo.totalAmount minus the amounts staked within the delay window, tracked at stake time. Also enforce MIN_CHALLENGER_STAKE on the remaining balance after a partial unstake so dust entries cannot be kept for free. Verify with a Hardhat test that registers 5,000 dust challengers, flips the test to failing, and asserts checkTest succeeds within the block gas limit.

        Claude Security (Sonnet 5.5)

        Unbounded loop over all challengers in the failure path lets an attacker make a failing test impossible to record

        contracts/AntePool.sol:555 Predicted severity: Medium

        Root cause

        Vulnerable symbol: _calculateChallengerEligibility

        Preconditions: The attacker can create thousands of challenger entries over time. The cost is mostly gas, with about 0.01 ETH of reusable capital.; The test failure occurs after the set has grown past the gas threshold.

        Offending code:

        for (uint256 i = 0; i < challengers.addresses.length; i++) {

        Impact

        The pool's core guarantee, that a failed test pays out challengers, can be disabled permanently by any unprivileged party. A staker, or the party that controls the tested protocol, therefore keeps funds that should have been paid to challengers. Legitimate challengers still recover their principal by unstaking, minus decay, but lose the expected payout and the verifier bounty. The same condition can also arise organically in a popular pool with many challengers.

        Description

        checkTest() calls _calculateChallengerEligibility() whenever the AnteTest fails. That function iterates every address in the IterableAddressSet, doing several cold SLOADs per entry. The set grows without limit, and the 0.01 ETH minimum is only enforced at stake() time, not for the residual after a partial unstake. An attacker can therefore add thousands of near-zero-cost challengers until the failure branch exceeds the block gas limit and reverts.

        Exploit scenario

        The attacker funds N fresh addresses. Each calls stake(true) with 0.01 ETH, which inserts it into the challengers set and starts its 12-block timer. It then calls unstake(balance - 1, true), which returns almost all of the ETH and leaves a 1 wei position that stays in the set. The same 0.01 ETH is reused for the next address, so the cost is gas only. Each stale entry costs about 8 to 10k gas in the failure-path loop (cold SLOADs for the array element, lastStakedBlock, startAmount and startDecayMultiplier), so about 3,000 to 4,500 entries push the failing branch of checkTest past the block gas limit. When the tested invariant later breaks, every checkTest call reverts in the failure branch, so failedBlock, pendingFailure and the payout state are never set. Stakers keep their funds and challengers cannot claim. Honest challengers cannot evict the dust entries.

        Recommendation

        Do not iterate over all challengers on the failure path. Track the eligible total incrementally at stake and unstake time, for example with checkpoints keyed by block, or compute eligibility lazily per claimer. At a minimum, bound the set size and enforce MIN_CHALLENGER_STAKE as a floor on any residual position (unstake must either remove the entry or leave at least the minimum).

        Claude Security (Opus 5.5)

        Unbounded loop over all challengers in the failure path lets a staker make test failure impossible to record

        contracts/AntePool.sol:555 Predicted severity: High

        Root cause

        Vulnerable symbol: _calculateChallengerEligibility

        Preconditions: Attacker pays gas to register a few thousand challenger addresses before the failure (capital is recoverable; see the partial-unstake dust bypass); The block gas limit bounds checkTest()

        Offending code:

        for (uint256 i = 0; i < challengers.addresses.length; i++) {

        Impact

        The test can never be marked as failed, so challengers cannot claim staker funds and stakers escape the loss the protocol is supposed to enforce.

        Description

        Anyone can add addresses to the challenger set through stake(true). checkTest() only reaches _calculateChallengerEligibility() after the test has already failed, and that function walks the whole set with several cold SLOADs per entry. The IterableAddressSet library documents O(1) operations, but AntePool iterates the full set, so a large enough set makes the only path that sets pendingFailure use more gas than a block allows.

        Exploit scenario

        A large staker, or a protocol team that stakes on its own test and plans to rug, first sets up many challenger addresses, for example CREATE2 child contracts that each call stake{value: 0.01 ether}(true). Each loop iteration reads addresses[i], lastStakedBlock, startAmount and startDecayMultiplier, roughly 9-10k gas (estimated from reading the code, not run). A few thousand entries therefore push the failure branch of checkTest() past the block gas limit. When the invariant later breaks, every checkTest() call reverts out of gas. pendingFailure is never set, claim() can never be called, and stakers unstake and withdraw after 24 hours. Challengers lose the payout they are owed and keep paying decay. The entries never leave the set unless their owners fully unstake.

        Recommendation

        Do not iterate over challengers when a failure is recorded. Track eligible challenger stake incrementally, for example with a per-block or checkpointed accumulator, or compute each challenger's eligibility lazily in claim(). Alternatively, cap the number of challengers or keep a meaningful per-address minimum.

        Vercel Security Review

        Dust challenger spam can block failure settlement and evade slashing

        contracts/AntePool.sol:555 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Grow an unrestricted challenger set** - contracts/AntePool.sol:193-194

        ```solidity title="contracts/AntePool.sol:193-194"

        challengers.insert(msg.sender);

        eligibilityInfo.lastStakedBlock[msg.sender] = block.number;

        ```

        An attacker can register arbitrarily many controlled addresses by staking the 0.01 ETH minimum.

        **2. Recycle deposits without removing entries** - contracts/AntePool.sol:485-488

        ```solidity title="contracts/AntePool.sol:485-488"

        if (isChallenger) challengers.remove(msg.sender);

        } else {

        require(amount <= prevAmount, "ANTE: Withdraw request exceeds balance.");

        user.startAmount = prevAmount.sub(amount);

        ```

        Each address can immediately withdraw all but one wei. Only full exits remove entries; subsequent decay does not prune them.

        **3. Exhaust gas during mandatory settlement** - contracts/AntePool.sol:555-558

        ```solidity title="contracts/AntePool.sol:555-558"

        for (uint256 i = 0; i < challengers.addresses.length; i++) {

        address challenger = challengers.addresses[i];

        if (eligibilityInfo.lastStakedBlock[challenger] < cutoffBlock) {

        eligibilityInfo.eligibleAmount = eligibilityInfo.eligibleAmount.add(

        ```

        Failure settlement unconditionally enumerates this set (line 308). Enough entries exceed the block gas limit, reverting failure recognition and preventing claims. Malicious stakers can then withdraw despite the broken invariant.

        Exploit scenario

        Not specified.

        Recommendation

        Replace failure-time enumeration with bounded or lazy eligibility accounting. Any balance minimum must also apply after partial withdrawals; minimum deposits alone do not bound this loop.

      • Reentrant checkTest allows pool draining ante-3 · 6 writeups Medium

        V12

        Reentrant failure settlement corrupts distributions and erases shortfalls

        contracts/AntePoolFactory.sol:27 Predicted severity: High

        Root cause

        Failure finalization is not protected against reentrancy through anteTest.checkTestPasses, and the outer frame assumes the pre-call phase still holds. The eligibility accumulator and bounty distribution assume finalization occurs exactly once, while capped payments erase claims even when that assumption has failed.

        Impact

        In deployments whose connected test can make this callback, reentrant failure finalization can permanently strand part of the slashed active and queued stakes. Interleaving a nested claim can instead leave a subsequent challenger underpaid with no remaining claim, because capped transfer settlement erases its entitlement.

        Description

        checkTest calls the mutable external Ante test while pendingFailure is still false and does not revalidate that phase when the call returns. A connected test that is itself an aged challenger can invoke a nested checkTest, return false to that nested invocation, and then return false to the original invocation. Both frames run failure finalization, and _calculateChallengerEligibility adds balances to the existing accumulator twice rather than establishing a single snapshot. If no claims occur between the frames, eligible challengers receive only half of _remainingStake in total, leaving the other half without a claimant. If the test claims its nested verifier payout before returning, the outer frame also reassigns the bounty after one bounty has already been paid, allowing a later payout to exceed available ETH. _safeTransfer then caps that payment while claim clears the claimant's entire position and records the nominal amount.

        Codex Security (GPT-6 Sol)

        A test callback can settle the same pool failure more than once

        contracts/AntePool.sol:302 Predicted severity: Medium

        Root cause

        checkTest() performs an untrusted, non-view external call before committing its failure state. A callback can reenter the same transition. The inner call makes claims available and the outer call then recalculates and overwrites settlement state without an idempotence guard.

        Impact

        The callback can distort payouts and duplicate the verifier bounty, but requires a test contract able to act as an eligible challenger and be selected for a pool.

        Description

        The pool calls a state-changing AnteTest before marking failure. A test contract that is itself an eligible challenger can reenter checkTest, settle and claim inside the callback, then let the outer call settle again, corrupting eligibility and verifier payouts.

        Exploit scenario

        untrusted AnteTest callback → nested checkTest → inner failure and claim → outer failure recalculation

        Recommendation

        Guard checkTest against reentrancy and make the failure transition idempotent before calling external test code.

        Pashov (Claude Opus 5.5 high)

        checkTest calls the external Ante Test before updating state and has no reentrancy guard, so eligibility can be double-counted

        contracts/AntePool.sol:292 Predicted severity: Low

        Root cause

        An external call to the untrusted test contract comes before the state transition, and there is no reentrancy guard.

        Impact

        eligibleAmount is inflated (e.g. doubled), so every eligible challenger gets only part of their share of _remainingStake. The rest stays locked in the pool forever. Reentrant stake/unstake during the check can also manipulate the totals the payout is based on.

        Description

        checkTest calls anteTest.checkTestPasses() while pendingFailure is still false, and no nonReentrant guard exists. A test that calls into attacker-controlled code (or is malicious itself) can re-enter checkTest, stake, or unstake. If the nested checkTest records the failure and the outer call also treats the test as failed, the failure branch runs twice. _calculateChallengerEligibility then adds every eligible balance to eligibilityInfo.eligibleAmount twice, and verifier and _bounty are overwritten.

        Exploit scenario

        A test reads a callback-capable contract. During the outer checkTest, the callback (controlled by an eligible challenger) calls checkTest again, which fails the test. Both calls then run the failure branch, eligibleAmount doubles, and half of the staker funds become unclaimable.

        Recommendation

        Add a nonReentrant guard to all state-changing functions. Re-check !pendingFailure after the external call, or call the test via staticcall.

        Pashov (Codex GPT-6 Sol high)

        Reentrant test checks can pay verifier bounty repeatedly

        contracts/AntePool.sol:299 Predicted severity: Critical

        Root cause

        The external test call precedes the failure latch, and the eligibility accumulator is additive instead of initialized to zero for one settlement.

        Impact

        Critical severity: nested checks can issue the 5% verifier bounty repeatedly until the pool is depleted, leaving honest challengers unpaid.

        Description

        A test callback can reenter checkTest before failure is recorded and make the settlement count each eligible balance more than once.

        Exploit scenario

        A test contract routes checkTestPasses callbacks through multiple mature challenger proxy addresses. The deepest check returns false, and its proxy claims the bounty. Each outer frame then records failure again with its own verifier, and that proxy claims another 5% bounty before the next frame unwinds. With 20 proxies and 100 ETH staked, repeated 5 ETH bounties can exhaust the pool.

        Recommendation

        Set a check-in-progress latch before calling the external test and finalize failure only once; prevent nested checks and snapshot eligibility once.

        Devin Security

        A malicious AnteTest can re-enter checkTest and double-count eligible challenger stake, which locks part of the payout

        contracts/AntePool.sol:292 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        The author of a malicious AnteTest can make the pool count eligible challenger stake twice, so honest challengers get only about half of the stakers' funds and the rest stays stuck in the contract.

        ##### What's wrong

        This is a reentrancy bug. checkTest calls the untrusted test contract before it sets pendingFailure, so the testNotFailed guard is still open while that call runs. The test contract can call checkTest again. Both the inner call and the outer call then add the challengers' balances to eligibilityInfo.eligibleAmount.

        ##### Who can do it

        Mallory writes an AnteTest contract and has it stake 0.01 ETH as a challenger. Later she makes checkTestPasses() call pool.checkTest() and then return false. Bob, an honest challenger, calls checkTest().

        - Mallory controls the AnteTest contract, and anyone can create a pool for any test.

        - The test contract holds a challenger stake that is at least 12 blocks old.

        ##### What they get

        The eligible amount ends up about twice its real value. Each eligible challenger receives about half of their fair share of the stakers' ETH, and the rest is locked in the pool forever. Mallory does not profit from this. She can only harm users of her own test's pool.

        ##### How it works

        1. Bob's checkTest() at AntePool.sol:292 passes the testNotFailed guard and calls the test at AntePool.sol:302.

        2. Mallory's test calls checkTest() again. The inner call also passes the guard, because pendingFailure is still false. It sets the failure state and runs _calculateChallengerEligibility.

        3. Control returns to the outer call, which runs _calculateChallengerEligibility again at AntePool.sol:308. That adds every eligible balance to eligibleAmount a second time.

        4. _calculateChallengerPayout at AntePool.sol:587 divides by the inflated eligibleAmount, so challengers are underpaid.

        Exploit scenario

        Not specified.

        Recommendation

        Add a nonReentrant guard to checkTest, stake, unstake, unstakeAll, withdrawStake, cancelPendingWithdraw and claim. Another option is to re-check pendingFailure after the external call and return early if it is already set. To check the fix, write a test with a re-entering AnteTest and confirm that eligibleAmount equals the sum of the eligible balances.

        Devin Security (Deep)

        No reentrancy guard around the untrusted test call lets a malicious test re-enter checkTest and double-count eligibility

        contracts/AntePool.sol:292 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A test author whose test contract is itself a challenger can make checkTest re-enter itself during checkTestPasses, which adds every challenger's balance to eligibleAmount twice or more, so challengers receive only a fraction of the slashed stake and the rest is stuck in the pool forever.

        ##### What's wrong

        This is a checks-effects-interactions violation. checkTest calls the author-controlled checkTestPasses while pendingFailure is still false and with no reentrancy lock, then runs _calculateChallengerEligibility, which only ever adds to eligibilityInfo.eligibleAmount and never resets it. A nested checkTest that also fails runs the loop a second time.

        ##### Who can do it

        Alice, the author of a test on Globex, deploys the test contract so that it also calls pool.stake(true) with 0.01 ETH and waits 12 blocks. Trent, an honest challenger, holds 10 ETH against the test. When Alice decides the test should fail, her test's checkTestPasses first calls pool.checkTest() from the test contract, returns false in that nested call, and then returns false again to the outer call.

        Conditions that must hold:

        * The test contract is a registered challenger with a stake more than 12 blocks old.

        * The test author controls checkTestPasses (true for every test by design).

        ##### What they get

        Alice cannot take money for herself this way, but she can deny Trent most of his payout: with one nested call eligibleAmount doubles, so Trent gets half of the staker pool he is owed and the other half stays in the contract with no function able to release it. Deeper nesting shrinks his share further. The verifier bounty and staker losses are unchanged. A test author can already harm challengers by never letting the test fail, so the added capability is limited to griefing payouts of a failure that does happen.

        ##### How it works

        1. Trent calls checkTest; the pool calls anteTest.checkTestPasses() with pendingFailure still false and no lock (contracts/AntePool.sol:302, 568).

        2. The test contract calls pool.checkTest(); the challenger and delay checks pass for it (contracts/AntePool.sol:293-297).

        3. The nested call fails the test, sets pendingFailure, and runs _calculateChallengerEligibility, adding every balance to eligibleAmount (contracts/AntePool.sol:303-312, 553-563).

        4. Control returns to the outer checkTest, which also sees false and runs the same bookkeeping again; eligibleAmount is added to a second time (contracts/AntePool.sol:558).

        5. claim divides _remainingStake by the doubled eligibleAmount, so each challenger gets half (contracts/AntePool.sol:586-588).

        Exploit scenario

        Not specified.

        Recommendation

        Add a reentrancy guard (OpenZeppelin ReentrancyGuard) to checkTest, stake, unstake, unstakeAll, cancelPendingWithdraw and claim, or set a transient lock flag before calling checkTestPasses. Also reset eligibilityInfo.eligibleAmount = 0 before the loop so a repeat run cannot accumulate. Verify with a Hardhat test using a mock test that re-enters pool.checkTest() and asserts the transaction reverts and eligibleAmount equals the sum of eligible balances.

    • Anza Token Wrap Rust SPL token wrap program. Tasks 1 V12 0/1 Codex Sec 0/1 Pashov Opus — Pashov GPT-6 — Devin 0/1 Devin (Deep) 1/1 Claude Sec 0/1 Claude Opus 0/1 Vercel 0/1

      SPL token wrap program.

      Read the audit report
      • Escrow accounts are not bound to caller, resulting in denial of service anza-token-wrap-1 · 1 writeup Medium

        Devin Security (Deep)

        Escrow account is caller-chosen, allowing fragmented escrows and unwrap griefing

        program/src/processor.rs:198 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone holding wrapped tokens can empty the specific escrow another user is about to unwrap from, making that user's unwrap fail, but no tokens are lost.

        ##### What's wrong

        The escrow is not tied to a canonical address. process_wrap accepts any token account whose owner field is the wrapped mint authority PDA, and process_unwrap performs no check on the escrow at all and relies only on the PDA signature for the transfer. Deposits for one wrapped mint can therefore be spread across many escrow accounts chosen by callers.

        ##### Who can do it

        Alice, a user at Acme, wraps 500 TOK into escrow E1 (the authority PDA's associated token account, which is what the CLI defaults to). Mallory, any user with 500 wTOK, watches the mempool. When Alice submits an Unwrap naming E1, Mallory front-runs with her own Unwrap from E1, emptying it. Alice's transaction fails with insufficient funds. Mallory re-wraps her TOK into a fresh escrow E2 she created and repeats whenever Alice retries.

        Conditions that must hold:

        - Mallory holds wrapped tokens at least equal to the balance of the escrow Alice targets.

        - Mallory can observe or predict which escrow Alice's unwrap names.

        ##### What they get

        Mallory can repeatedly block Alice from unwrapping at the cost of transaction fees only, since each front-run is a fair exchange of her wrapped tokens for unwrapped ones. She cannot take Alice's tokens. The total escrowed balance across all escrows still equals the wrapped supply, but clients that assume a single canonical escrow (such as the CLI default) will fail to find the funds.

        ##### How it works

        1. process_wrap only checks that the escrow's owner field equals the authority PDA (program/src/processor.rs:198-204), so any caller can create a new token account owned by the PDA and deposit into it.

        2. process_unwrap accepts whatever unwrapped_escrow the caller passes with no address or owner check (program/src/processor.rs:254) and signs the transfer out of it with the PDA (program/src/processor.rs:304-314).

        3. Deposits become spread across arbitrary PDA-owned accounts, and any wrapped-token holder can drain any individual escrow, so a targeted unwrap can be made to fail.

        Exploit scenario

        Not specified.

        Recommendation

        Require the escrow to be the associated token account of the wrapped mint authority PDA for the unwrapped mint and unwrapped token program, and verify this derived address in both process_wrap and process_unwrap (fail with an EscrowMismatch error otherwise). To check the fix, add tests that pass a non-ATA PDA-owned token account as the escrow to both Wrap and Unwrap and assert they are rejected, and that the ATA escrow succeeds.

    • Aori Solidity Cross-chain RFQ settlement engine. Tasks 2 V12 2/2 Codex Sec 0/2 Pashov Opus 1/2 Pashov GPT-6 1/2 Devin 0/2 Devin (Deep) 2/2 Claude Sec 0/2 Claude Opus 0/2 Vercel 2/2

      Cross-chain RFQ settlement engine.

      Read the audit report
      • Missing reentrancy guard in the cancel function aori-1 · 4 writeups High

        V12

        Reentrant cancellation spends another active order's collateral

        contracts/Aori.sol:501 Predicted severity: High

        Root cause

        cancel(bytes32) does not share the fill's reentrancy guard, and _settleSingleChainSwap relies on pre-call status validation rather than revalidating the order after external output delivery. Aggregate offerer balances hide that the specific order was already refunded.

        Impact

        A callback-capable whitelisted solver recipient can cause both an input refund and filler reimbursement for one order, consuming the locked backing allocated to another active order by the same offerer. The other order can then fail cancellation or settlement because its ledger collateral was spent, despite remaining Active; both plain ERC20 and native source deposits can supply the affected collateral.

        Description

        A same-chain fill validates Active status before transferring output to the recipient, but its later settlement never rechecks that status. cancel(bytes32) is an unguarded sibling entrypoint that a whitelisted solver can invoke while the fill's nonReentrant lock is held. A native-output recipient that is also a whitelisted solver can therefore cancel the currently filling order in its receive callback, refunding the stored input and setting Cancelled. If the offerer has another sufficient locked deposit of the same input token, _settleSingleChainSwap subsequently debits that aggregate balance, credits the filler, and overwrites the cancelled order's status with Settled. The final balance-transfer assertion passes because it snapshots balances only after the output callback and does not tie the debit to the still-active escrow resource.

        Pashov (Claude Opus 5.5 high)

        Single-chain cancel(bytes32) has no nonReentrant guard and pushes native refunds

        contracts/Aori.sol:765 Predicted severity: Informational

        Root cause

        The reentrancy guard is applied inconsistently.

        Impact

        Cross-function or read-only reentrancy risk for integrators and for future code changes.

        Description

        cancel(bytes32) is the only state-changing user entry point without nonReentrant, and it sends ETH to the offerer through a low-level call. State is updated before the transfer (CEI), so no direct exploit was found. Still, the offerer gets control while other entry points are unlocked, and view functions such as getLockedBalances can be observed mid-flow.

        Exploit scenario

        An offerer contract receiving the native refund re-enters other Aori functions, or third-party protocols that read Aori balances, while the cancellation is still in progress.

        Recommendation

        Add nonReentrant to cancel(bytes32).

        Devin Security (Deep)

        cancel(bytes32) is not reentrancy-guarded and can run inside a hook call during fill

        contracts/Aori.sol:765 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        If a whitelisted hook can be made to call back into Aori, a solver can cancel an order in the middle of filling it, so the offerer gets both a refund and the output while the solver is paid from another order's locked funds; this needs a hook that forwards arbitrary calls and a solver address that is a contract.

        ##### What's wrong

        This is a reentrancy gap. Every state-changing entry point carries nonReentrant except the single-argument cancel(bytes32). During fill(order, hook) the contract makes an external call with solver-supplied calldata (observeBalChg), and _settleSingleChainSwap samples its "initial" balances only after that call, so a cancel that happens inside the hook call is invisible to the later consistency check.

        ##### Who can do it

        Alice has two active single-chain orders in token T, each for 100 T, so 200 T is locked for her. Mallory operates a whitelisted solver whose address is a contract. The owner has whitelisted a router hook that executes caller-supplied calls. Mallory fills Alice's first order with that hook; inside the hook call, the router calls Mallory's solver contract, which calls cancel(orderId) for the same order.

        - Attacker controls a whitelisted solver, and that solver address is a contract.

        - A whitelisted hook exists whose instructions can trigger a call to an attacker-controlled contract (for example a generic multicall router).

        - The target is an Active single-chain order whose offerer has other locked balance in the same token (or the attacker colludes with the offerer).

        ##### What they get

        The reentrant cancel refunds 100 T to Alice and marks the order Cancelled. Back in fill, the output is sent to Alice's recipient, and _settleSingleChainSwap debits 100 T from Alice's remaining locked balance (which belongs to her second order) and credits Mallory 100 T. Alice has received both her input back and her output; Mallory is credited. Alice's second order is now unbacked, so when it settles the contract pays out tokens it does not hold, and the last withdrawer of token T loses. If Mallory and Alice collude, they take 100 T from the shared pool per round.

        ##### How it works

        1. Mallory calls fill(order, hook) (contracts/Aori.sol:535) for Alice's Active single-chain order.

        2. _executeDstHook runs observeBalChg (contracts/Aori.sol:604, contracts/AoriUtils.sol:412), an external call with Mallory's calldata to the whitelisted hook.

        3. The hook calls Mallory's solver contract, which calls cancel(orderId) (contracts/Aori.sol:765); there is no nonReentrant modifier, and validateSourceChainCancel accepts any whitelisted solver.

        4. _cancel (contracts/Aori.sol:814) sets the order Cancelled, reduces Alice's locked balance by 100 T, and sends her 100 T.

        5. Control returns to fill, which pays the output to the recipient (contracts/Aori.sol:558) and calls _settleSingleChainSwap (contracts/Aori.sol:714), which samples balances only now, debits 100 T from Alice's other locked funds, credits Mallory, and overwrites the status to Settled.

        Exploit scenario

        Not specified.

        Recommendation

        Add nonReentrant to cancel(bytes32) so it cannot be entered while fill or deposit is executing. Also re-check orderStatus[orderId] == Active inside _settleSingleChainSwap (or at the end of fill) before marking the order Settled. Verify with a Foundry test using a mock hook that calls cancel(orderId) from inside handleHook; the fill must revert.

        Vercel Security Review

        Reentrant cancellation creates unbacked credits that can drain pooled escrow

        contracts/Aori.sol:765 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. An allowlisted solver funds equal-input orders A (single-chain, native output) and B (cross-chain) from its EOA. A's recipient callback during fill (contracts/Aori.sol:511) can enter this unguarded cancellation and refund A.** - contracts/Aori.sol:765-766

        ```solidity title="contracts/Aori.sol:765-766"

        function cancel(bytes32 orderId) external whenNotPaused {

        Order memory order = orders[orderId];

        ```

        **2. A's outer fill then consumes B's shared locked balance and credits A, without rechecking A's cancelled status.** - contracts/Aori.sol:724-733

        ```solidity title="contracts/Aori.sol:724-727"

        if (balances[order.offerer][order.inputToken].locked >= order.inputAmount) {

        bool successLock = balances[order.offerer][order.inputToken].decreaseLockedNoRevert(

        uint128(order.inputAmount)

        );

        ```

        **3. After B is filled remotely, settlement credits B even when its locked debit fails. The subsequent return preserves that credit, enabling withdrawals against unrelated depositors' reserves.** - contracts/Aori.sol:663-671

        ```solidity title="contracts/Aori.sol:666-668"

        bool successUnlock = balances[filler][order.inputToken].increaseUnlockedNoRevert(

        uint128(order.inputAmount)

        );

        ```

        Exploit scenario

        Not specified.

        Recommendation

        Guard cancel(bytes32) with the same nonReentrant protection as fills, and finalize/debit orders before invoking recipients or revalidate their status afterward. Make _settleOrder's balance updates atomic: validate both the locked debit and unlocked credit before writing, or roll back all per-order mutations on either failure. A failed debit must never create an unlocked credit.

      • Incorrect state update on settlement failure aori-2 · 4 writeups High

        V12

        Failed settlement commits unmatched balance mutations

        contracts/Aori.sol:657 Predicted severity: High

        Root cause

        _settleOrder() treats returning from two independently mutating helpers as though it were atomic rollback. It must prevent either write unless both accounting operations can succeed together.

        Impact

        An insufficient-lock settlement can create an unbacked withdrawable credit that consumes token backing belonging to other holders. An unlocked-overflow settlement can remove an offerer's escrow entitlement without reimbursing the paying filler, producing fund loss or a requirement for privileged repair; the existence of a production token with enough units to trigger overflow is not established.

        Description

        A delivered settlement calls the nonreverting locked debit and unlocked credit separately, then returns if either reports failure. A successful first mutation is not rolled back when the second fails, and the second mutation is attempted even when the first already failed. With insufficient locked balance following an emergency debit, the filler can still receive a full unlocked credit while the order remains Active. Conversely, when the filler credit would overflow uint128, the offerer's locked balance is removed without any corresponding filler credit. Since the receive handler returns successfully and the sender has already removed the hash from its queue, the application provides no per-item failure or retry state for either outcome.

        Pashov (Codex GPT-6 Sol high)

        Failed unlocked-credit increase silently destroys the offerer's locked credit

        contracts/Aori.sol:663 Predicted severity: Medium

        Root cause

        Two dependent storage writes are handled as independent nonreverting operations, followed by an early return on partial failure.

        Impact

        A deposited order can become unwithdrawable and uncancellable, with tokens left in contract custody but no matching user credit. The reverse partial failure can grant the filler an unbacked withdrawal claim.

        Description

        Source settlement decreases the offerer's locked balance before trying to increase the filler's unlocked balance. If the second operation returns false because its uint128 field would overflow, _settleOrder returns without reverting or restoring the first write. The order remains Active, but its locked credit is gone. Conversely, if the locked debit fails but the unlocked credit succeeds, the function creates an unbacked filler credit before returning.

        Exploit scenario

        A filler with unlocked credit near the uint128 maximum receives another settlement for the same token. The offerer's locked balance is reduced, the filler-credit increase detects overflow, and the function silently skips status change. A later cancellation fails its locked-balance check.

        Recommendation

        Check both preconditions before mutating either balance, or revert the entire message on an accounting failure.

        Devin Security (Deep)

        _settleOrder credits the filler even when the offerer's locked balance could not be debited

        contracts/Aori.sol:657 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        When a settlement arrives for an order whose offerer no longer has enough locked balance, the filler is still credited the full amount, so the contract ends up owing more than it holds; this needs the locked balance to already be out of sync, which today requires an owner emergency action or another bug.

        ##### What's wrong

        This is an accounting bug (credit without debit). _settleOrder runs the locked-balance decrease and the unlocked-balance increase back to back and only afterwards checks whether either failed. The increase has already been written to storage by the time the function returns early.

        ##### Who can do it

        Alice, a trader, deposits 1,000 USDC into an order on the source chain. The Aori owner later calls emergencyWithdraw(token, amount, user, isLocked = true, recipient) to pull Alice's locked 1,000 USDC out, but the order stays Active. Sam, a solver, fills Alice's order on the destination chain and calls settle. When the settlement lands, Alice's locked debit fails, yet Sam's unlocked balance still rises by 1,000 USDC.

        - An order is Active on the source chain while its offerer's locked balance for that token is below inputAmount. The repo shows one way to reach this state: the owner's five-argument emergencyWithdraw with isLocked = true (contracts/Aori.sol:262-287). The reentrancy issue reported separately on cancel(bytes32) is another.

        - A settlement message for that order is delivered from the destination chain.

        ##### What they get

        Sam can withdraw 1,000 USDC that the contract no longer has set aside for his order. The shortfall is paid out of other users' and solvers' USDC held by the same contract, and the last person to withdraw that token fails. The order itself stays Active forever, so it can never be cleaned up without another owner action. The damage is limited to the token and amount of the mis-synced order.

        ##### How it works

        1. A settlement payload reaches _handleSettlement (contracts/Aori.sol:684) and calls _settleOrder for an Active order.

        2. decreaseLockedNoRevert (contracts/Aori.sol:663) returns false because the offerer's locked balance is too small, and writes nothing.

        3. increaseUnlockedNoRevert (contracts/Aori.sol:666) runs regardless and writes the filler's new unlocked balance to storage.

        4. The guard at contracts/Aori.sol:670 returns early, leaving the order Active and the filler credited.

        5. The filler calls withdraw (contracts/Aori.sol:859) and takes tokens that belong to other balances.

        Exploit scenario

        Not specified.

        Recommendation

        Check the debit result before crediting: call decreaseLockedNoRevert first, return immediately if it fails, and only then call increaseUnlockedNoRevert. If the credit fails after a successful debit, restore the locked balance (or revert that order's processing) so the two writes stay atomic. Verify with a Foundry test that uses emergencyWithdraw(..., isLocked = true, ...) to drain an offerer's locked balance, delivers a settlement for that order, and asserts the filler's unlocked balance is unchanged.

        Vercel Security Review

        Reentrant cancellation creates unbacked credits that can drain pooled escrow

        contracts/Aori.sol:765 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. An allowlisted solver funds equal-input orders A (single-chain, native output) and B (cross-chain) from its EOA. A's recipient callback during fill (contracts/Aori.sol:511) can enter this unguarded cancellation and refund A.** - contracts/Aori.sol:765-766

        ```solidity title="contracts/Aori.sol:765-766"

        function cancel(bytes32 orderId) external whenNotPaused {

        Order memory order = orders[orderId];

        ```

        **2. A's outer fill then consumes B's shared locked balance and credits A, without rechecking A's cancelled status.** - contracts/Aori.sol:724-733

        ```solidity title="contracts/Aori.sol:724-727"

        if (balances[order.offerer][order.inputToken].locked >= order.inputAmount) {

        bool successLock = balances[order.offerer][order.inputToken].decreaseLockedNoRevert(

        uint128(order.inputAmount)

        );

        ```

        **3. After B is filled remotely, settlement credits B even when its locked debit fails. The subsequent return preserves that credit, enabling withdrawals against unrelated depositors' reserves.** - contracts/Aori.sol:663-671

        ```solidity title="contracts/Aori.sol:666-668"

        bool successUnlock = balances[filler][order.inputToken].increaseUnlockedNoRevert(

        uint128(order.inputAmount)

        );

        ```

        Exploit scenario

        Not specified.

        Recommendation

        Guard cancel(bytes32) with the same nonReentrant protection as fills, and finalize/debit orders before invoking recipients or revalidate their status afterward. Make _settleOrder's balance updates atomic: validate both the locked debit and unlocked credit before writing, or roll back all per-order mutations on either failure. A failed debit must never create an unlocked credit.

    • Audius Solana Rust Audius reward distribution on Solana. Tasks 1 V12 1/1 Codex Sec 0/1 Pashov Opus — Pashov GPT-6 — Devin 1/1 Devin (Deep) 0/1 Claude Sec 1/1 Claude Opus 1/1 Vercel 1/1

      Audius reward distribution on Solana.

      Read the audit report
      • Missing PDA validation leading to multiple transfers audius-solana-1 · 5 writeups Critical

        V12

        Signed substitute markers permit unlimited reward replay

        solana-programs/reward-manager/program/src/processor.rs:433 Predicted severity: Critical

        Root cause

        Replay protection assumes that PDA signer seeds force the supplied creation destination to be that PDA. process_evaluate_attestations omits the explicit marker-address equality check, allowing an independently signed ordinary account to replace the replay record.

        Impact

        A rewarded recipient who retains a valid quorum and oracle signature set can repeatedly collect the same reward, draining the reward vault into their own claimable-token bank. The deterministic ID marker is never created in this sequence, so each repetition can recreate the staging account and pass the zero-lamport test.

        Description

        process_evaluate_attestations treats the supplied transfer account as unused whenever its lamport balance is zero, but never checks its key against the T_ plus ID PDA. Although the marker-creation CPI supplies that PDA's signer seeds, create_account actually creates the caller-supplied destination account. An attacker can supply a fresh ordinary keypair account with its transaction signer flag set, satisfying the System Program's destination-signature requirement independently of the PDA seeds. The resulting marker is stored at the attacker's keypair address rather than the deterministic replay-protection address. Re-submitting the same valid signatures and evaluating with another fresh signed account repeats the payout for the same ID.

        Devin Security

        EvaluateAttestations never checks the transfer account address, so one set of attestations can be paid out many times

        solana-programs/reward-manager/program/src/processor.rs:433 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who has seen one valid reward payout can repeat it again and again, draining the whole reward pool to the same recipient.

        ##### What's wrong

        This is a replay bug. The program uses a T_<id> account as a "this reward was already paid" marker, but it never checks that the account passed in is the real T_<id> address. It only checks that the passed account has zero lamports and then creates it.

        ##### Who can do it

        Mallory signs up for a free Audius account and earns one small challenge reward. The oracle and senders sign attestations for her reward, and those signatures are now public on chain. Mallory then sends her own transactions that call EvaluateAttestations many times. Each call uses a brand new keypair as the transfer account.

        - Mallory needs one set of valid attestations for any reward id. These sit in public SubmitAttestations transactions on chain.

        - Mallory needs a little SOL to pay fees and rent for each fresh transfer account.

        - No other signer or role is needed. EvaluateAttestations is permissionless.

        ##### What they get

        Mallory gets the same reward amount paid into her user bank once per call, until the reward manager's token account is empty. This drains the token pool that pays every other user's rewards. Inside one transaction she can repeat the call because the verified messages account keeps its data until the transaction ends. Across transactions she can re-submit the old, still valid attestation signatures to rebuild that account and keep going.

        ##### How it works

        1. Mallory calls EvaluateAttestations with a fresh keypair as transfer_account_info and signs with that keypair (processor.rs:698).

        2. The only replay check is that this account has zero lamports (processor.rs:434), which a fresh keypair always has.

        3. The tokens are sent to the recipient before the marker is created (processor.rs:478).

        4. create_account is called on Mallory's keypair. It succeeds because the outer transaction signature satisfies the system program, and the PDA seeds are never compared to the account key (processor.rs:489-512).

        5. The verified messages account only has its lamports zeroed and keeps its data and owner for the rest of the transaction (processor.rs:514-521), so another EvaluateAttestations in the same transaction passes again.

        6. In a later transaction, SubmitAttestations accepts the same old signed messages again because it has no freshness check (utils/signs.rs:285-321), so the verified messages account can be rebuilt.

        Exploit scenario

        Not specified.

        Recommendation

        Before the token transfer, derive the T_<id> address and require transfer_account_info.key == derived address (for example with assert_account_key). Also clear the verified messages data (or set it to uninitialized) when closing it, and reject SubmitAttestations for an id whose T_<id> account already exists. To check the fix, write a program test that calls EvaluateAttestations twice for the same id, once with the real PDA and once with a fresh keypair. The second call must fail, and so must a second EvaluateAttestations in the same transaction.

        Claude Security (Sonnet 5.5)

        EvaluateAttestations never checks the transfer (anti-replay) account is the derived PDA, so any attested disbursement can be replayed without limit

        solana-programs/reward-manager/program/src/processor.rs:505 Predicted severity: Critical

        Root cause

        Vulnerable symbol: Processor::process_evaluate_attestations

        Preconditions: The attacker needs a valid (recipient, amount, id) attestation set, which is public on-chain after any legitimate claim, or one earned legitimately; The attacker pays tx fees and the transfer-account rent, which is cheap and is refunded via the verified_messages lamports

        Offending code:

        create_account(

        Impact

        The only on-chain double-spend protection for reward disbursements is bypassed. Any user holding a valid attestation set can drain the reward vault to their own user bank. Any third party can also replay other users' public attestations to deplete the pool. The result is loss of all reward-pool funds.

        Description

        The double-spend guard is a transfer account that is supposed to live at PDA T_<id>. The caller supplies transfer_account_info, and the program only checks its lamports are 0 (line 434). It then derives the PDA but discards the derived address (let (reward_manager_authority, _, bump_seed) = find_derived_pair(, line 494) and never compares it with the supplied key. An attacker passes a fresh keypair-signed account as the transfer account, so the spl_token_transfer at line 478 can run again for the same id.

        Exploit scenario

        1. The attacker earns one legitimate reward, or watches any legitimate disbursement on-chain. The secp256k1 instructions of the N DN attestations and the oracle attestation are public. The messages carry no nonce and no reward-manager binding, so they stay valid forever. 2. The attacker builds a tx that replays the secp instructions with SubmitAttestations. verified_messages is recreated because the previous one was zeroed and purged. 3. The attacker calls EvaluateAttestations with transfer_account set to a brand-new keypair that also signs the tx. The lamports() != 0 check passes. create_account is CPI'd with that keypair's signer privilege, so the PDA seeds are irrelevant. Tokens move from the reward vault to the recipient's user bank again. 4. Repeat for as long as the vault has funds. Within one tx, evaluate can also be called several times in a row. The verified_messages data is still present after its lamports are zeroed, and each call uses a different fresh transfer account.

        Recommendation

        Bind the transfer account to the PDA. Capture the derived address from find_derived_pair and call assert_account_key(transfer_account_info, &derived_transfer_address)? before any token movement. Keep the lamports check, and use create_account only once the key is verified. Also add a test that passes an arbitrary signer account as the transfer account.

        Claude Security (Opus 5.5)

        EvaluateAttestations replay guard never checks that the transfer account is the T_<id> PDA, so one attestation set can be paid out without limit

        solana-programs/reward-manager/program/src/processor.rs:434 Predicted severity: Critical

        Root cause

        Vulnerable symbol: process_evaluate_attestations

        Preconditions: At least one valid attestation set (min_votes+1 messages) exists for the target reward manager. Any past legitimate disbursement's on-chain secp instructions are enough.

        Offending code:

        if transfer_account_info.lamports() != 0 {

        Impact

        Anyone holding one valid attestation set can drain the reward manager's entire token balance. Past attestations are public on-chain, so this is any rewarded user or any observer.

        Description

        transfer_account_info comes from the caller and is never compared to the T_<id> PDA derived at lines 489-498. Its only check is lamports()==0. Because create_account (lines 505-512) also succeeds for any fresh keypair that signs the outer transaction, a used attestation set can be paid out again through spl_token_transfer (line 478) as many times as the attacker likes. Also CWE-754: Both PDAs come from public data (reward manager + "T_"/"V_" + "challengeId:specifier", listed at the discovery /challenges/undisbursed endpoint). Lamports != 0 on the transfer address is treated as already-disbursed. A system-owned verified-messages address with lamports fails the ownership check in SubmitAttestations. Anyone can send lamports to these addresses beforehand.

        Exploit scenario

        A user receives one legitimate reward (recipient R, amount A, id I). The discovery-node and oracle secp256k1 signatures are public on-chain. In a new transaction the attacker calls SubmitAttestations once per original message, reusing the original secp instruction data with only the instruction-index offsets changed. This recreates V_I with min_votes+1 valid messages. The attacker then calls EvaluateAttestations repeatedly in one transaction, passing a different freshly generated signer keypair as account #5 (transfer account) each time. The verified_messages data stays readable for the rest of the transaction even after its lamports are zeroed. Every call passes the lamports==0 check and the message checks, and transfers A tokens from the reward manager's token account to UserBank(R). Repeating this empties the whole reward pool into the attacker's user bank. A third party can do the same to drain the pool into other users' banks.

        Recommendation

        Keep the derived T_<id> address from find_derived_pair and call assert_account_key(transfer_account_info, &derived_transfer_address) before any transfer. Also assert that verified_messages_info is the V_<id> PDA, and zero or reassign its data (not just its lamports) when closing it. Also CWE-754: Treat an existing system-owned account as 'not yet created': fund the remainder, then allocate and assign with PDA seeds instead of create_account. Check ownership and initialization state rather than lamports for replay protection.

        Vercel Security Review

        Unvalidated transfer-record address allows repeated reward payouts

        solana-programs/reward-manager/program/src/processor.rs:433 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Replay protection checks a caller-selected account** - solana-programs/reward-manager/program/src/processor.rs:433-436

        ```rust title="solana-programs/reward-manager/program/src/processor.rs:433-436"

        // Ensure the transfer account doesn't yet exist

        if transfer_account_info.lamports() != 0 {

        return Err(AudiusProgramError::AlreadySent.into());

        }

        ```

        A reward recipient can resubmit previously published attestations and supply a fresh, transaction-signed keypair instead of the existing disbursement PDA.

        **2. The expected record address is discarded** - solana-programs/reward-manager/program/src/processor.rs:494-497

        ```rust title="solana-programs/reward-manager/program/src/processor.rs:494-497"

        let (reward_manager_authority, _, bump_seed) = find_derived_pair(

        program_id,

        reward_manager_info.key,

        transfer_account_seed.as_ref(),

        ```

        No address comparison occurs; PDA signing seeds do not prohibit an independently signed destination.

        **3. The arbitrary account records an already-executed payout** - solana-programs/reward-manager/program/src/processor.rs:505-508

        ```rust title="solana-programs/reward-manager/program/src/processor.rs:505-508"

        create_account(

        program_id,

        payer_info.clone(),

        transfer_account_info.clone(),

        ```

        Each fresh account bypasses deduplication, repeatedly paying the same recipient and depleting reward funds.

        Exploit scenario

        Not specified.

        Recommendation

        Retain the derived transfer-record address and assert transfer_account_info.key equals it before testing its balance or transferring tokens. Enforce the derivation on chain rather than relying on instruction builders.

    • Bracket FI Escrow Solidity OTC escrow with seller-driven deposits. Tasks 4 V12 3/4 Codex Sec 1/4 Pashov Opus 3/4 Pashov GPT-6 2/4 Devin 1/4 Devin (Deep) 4/4 Claude Sec 1/4 Claude Opus 1/4 Vercel 1/4

      OTC escrow with seller-driven deposits.

      Read the audit report
      • Reentrancy in withdrawals bracket-fi-escrow-1 · 9 writeups Critical

        V12

        Reentrant ETH withdrawals drain pooled deposits

        src/EscrowBase.sol:116 Predicted severity: Critical

        Root cause

        withdraw performs recipient callbacks before reducing usersBalance and totalStaked, with no reentrancy exclusion. The cached balance assignment and unchecked aggregate subtraction allow repeated payouts to complete without reconciling them against the caller's original stake.

        Impact

        A depositor contract can withdraw more ETH than it deposited by recursively withdrawing against the same recorded WETH balance, taking WETH backing other depositors. The attacker can stop recursion before pooled WETH is exhausted so the transaction succeeds; repeated debits can also wrap totalStaked while the user's balance is overwritten with the same cached remainder.

        Description

        withdraw reads the caller's recorded balance and checks the requested amount before making external calls, but does not debit that balance until all transfers finish. In the ETH-unwrapping branch it unwraps pooled WETH and sends ETH to msg.sender using an unrestricted call. A contract recipient can call withdraw again from its receive callback while its original balance is still available. Each nested invocation can unwrap and transfer another portion of the pooled WETH, and the later unchecked accounting updates do not reject the repeated withdrawals. Neither concrete escrow overrides this function or adds a reentrancy guard, so this path does not require a malicious token or privileged caller.

        Codex Security (GPT-6 Sol)

        A contract depositor can drain other users' WETH through reentrant ETH withdrawals

        src/EscrowBase.sol:151 Predicted severity: Critical

        Root cause

        withdraw reads the caller's credited balance, then invokes the caller through an ETH send, and only afterward stores the debit. A reentrant caller starts another withdrawal against the unchanged balance, and each returning frame overwrites the same user-balance value. The shared WETH pool pays every nested call.

        Impact

        An unprivileged contract depositor can drain pooled WETH during the open escrow period, causing loss of other users' collateral; only a positive attacker deposit and sufficient pooled funds are needed.

        Description

        A contract depositor can call withdraw again while receiving ETH, before the escrow reduces its recorded balance. Each call pays the same entitlement, consuming WETH that backs other users.

        Exploit scenario

        Contract depositor's withdrawal amount -> unchanged usersBalance check -> WETH unwrap -> ETH callback -> nested withdrawal -> late balance overwrite

        Recommendation

        Reduce usersBalance and totalStaked before any unwrap, transfer or ETH call, and guard balance-changing entry points against reentrancy.

        Pashov (Claude Opus 5.5 high)

        Reentrancy in withdraw() ETH-unwrap path allows draining all escrowed WETH

        src/EscrowBase.sol:136 Predicted severity: Critical

        Root cause

        Checks-effects-interactions is violated: state (usersBalance and totalStaked) is updated after an untrusted external ETH call, and the final write uses a stale cached balance value. No nonReentrant modifier is present.

        Impact

        Any depositor can withdraw their balance many times over and steal the WETH/ETH deposited by every other user before the escrow breaks. totalStaked is decremented in an unchecked block once per nested call, so it can also underflow and corrupt the accounting.

        Description

        withdraw() reads the caller's balance into a local variable, performs the external transfer (for WETH with unwrap=true it unwraps and sends raw ETH via msg.sender.call), and only afterwards writes usersBalance = balance - amount in an unchecked block. There is no reentrancy guard. A contract caller re-enters withdraw() from its receive() hook while its stored balance is still unchanged, so each nested call passes the amount > balance check and is paid again.

        Exploit scenario

        The attacker deploys a contract and calls depositETH() with 1 ETH. It then calls withdraw(WETH, 1 ether, true). The escrow unwraps 1 WETH and sends 1 ETH to the attacker, whose receive() re-enters withdraw(WETH, 1 ether, true). The stored balance is still 1 ETH, so the check passes and another ETH is sent. This repeats until the escrow's WETH is exhausted. When the calls unwind, each frame writes usersBalance = 1 ether - 1 ether = 0, leaving the attacker with N ETH for a 1 ETH deposit.

        Recommendation

        Update usersBalance and totalStaked before any external call (checks-effects-interactions), use checked arithmetic, and add OpenZeppelin ReentrancyGuard (nonReentrant) to withdraw, depositToken and depositETH.

        Pashov (Codex GPT-6 Sol high)

        Reentrant withdrawal can spend the same stake more than once

        src/EscrowBase.sol:141 Predicted severity: Critical

        Root cause

        The effects on usersBalance and totalStaked occur after external interactions, without a reentrancy guard.

        Impact

        An attacker with a stake can drain assets credited to other depositors and corrupt the aggregate stake accounting.

        Description

        withdraw reads the caller's recorded stake, then transfers tokens or sends unwrapped ETH before updating that stake. A recipient callback can enter withdraw again while the original balance is still available. Each nested call passes the same balance check and sends another payout. The unchecked totalStaked subtraction also wraps when multiple nested payouts exceed the recorded total.

        Exploit scenario

        An attacker deposits WETH-equivalent ETH through a contract, then calls withdraw for that stake with unwrap=true. The ETH send invokes the attacker's receive callback, which calls withdraw again for the same stake before the first call updates accounting. Repeating this spends the same credited stake against pooled WETH.

        Recommendation

        Decrease the user balance and token total before any unwrap or transfer, and add a reentrancy guard around withdrawals. Keep the aggregate subtraction checked.

        Devin Security

        Reentrancy in withdraw ETH unwrap path lets any depositor drain all escrowed WETH

        src/EscrowBase.sol:136 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who deposits a small amount of ETH can call back into withdraw while the contract is sending them ETH and pull out every other user's WETH from the escrow.

        ##### What's wrong

        This is a reentrancy bug. A reentrancy bug happens when a contract hands control to an outside address before it updates its own records, so that address can call back in and act on stale state. In withdraw, the unwrap branch for ETH sends ETH to msg.sender with a raw call before it lowers the caller's balance. The contract has no reentrancy guard.

        ##### Who can do it

        Alice and many other users deposit ETH into the Acme escrow, which holds it as WETH. Mallory, an anonymous user, deploys a small attacker contract and has it call depositETH with 1 ETH. Her contract then calls withdraw(WETH, 1 ether, true). When the escrow sends her 1 ETH, her contract's receive function calls withdraw(WETH, 1 ether, true) again. Her recorded balance is still 1 ETH, so the check passes every time.

        - The escrow is not yet broken (block.timestamp < breakTimestamp).

        - WETH is configured with the ETH placeholder as its rebase token. Both deployment scripts do this.

        - Mallory has deposited any nonzero amount of ETH or WETH.

        ##### What they get

        Mallory repeats the callback until the escrow has no WETH left. She walks away with all ETH that every user deposited, not only her own 1 ETH. Alice and every other depositor lose their funds. After the attack, each nested call writes Mallory's balance to balance - amount and lowers totalStaked inside an unchecked block, so nothing reverts and the accounting is corrupted.

        ##### How it works

        1. Mallory's contract calls withdraw(WETH, D, true) and the code reads her balance D into a local variable (src/EscrowBase.sol:141).

        2. The unwrap branch burns D WETH for ETH through _unwrapETH (src/EscrowBase.sol:150).

        3. The contract sends D ETH to Mallory with msg.sender.call{value: amount} before it touches storage (src/EscrowBase.sol:151).

        4. Mallory's receive function calls withdraw again, and the balance check at src/EscrowBase.sol:142 passes because storage still says D.

        5. The loop continues until the escrow's WETH runs out. Each frame then writes balance - amount and decrements totalStaked without overflow checks (src/EscrowBase.sol:162-165).

        Exploit scenario

        Not specified.

        Recommendation

        Update usersBalance and totalStaked before any external call (checks-effects-interactions). Also add OpenZeppelin ReentrancyGuardUpgradeable (nonReentrant) to withdraw, depositToken, depositETH and the claim and bridge functions. To check the fix, write a Foundry test with an attacker contract whose receive() calls withdraw(WETH, amount, true) again. With the fix, the nested call should revert, and the escrow's WETH balance should drop by only the attacker's deposit.

        Devin Security (Deep)

        Reentrancy in withdraw() ETH path lets any depositor drain all users' ETH/WETH

        src/EscrowBase.sol:141 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who deposits a little ETH can call withdraw from a contract and pull out every other user's ETH and WETH, on both the Ethereum and Arbitrum escrows.

        ##### What's wrong

        This is a reentrancy bug. The withdraw function sends ETH to the caller before it lowers the caller's recorded balance, so a contract that receives that ETH can call withdraw again and pass the balance check a second time with the same, still unreduced balance.

        ##### Who can do it

        Alice and other users at Acme deposit ETH into the escrow during the 30 day deposit window. Mallory, an anonymous attacker with a wallet and a small contract, deposits some ETH into the same escrow and then calls withdraw with unwrap set to true from her contract.

        - The escrow has not reached its break timestamp, so withdraw is open to every user.

        - WETH is registered with the ETH marker as its rebase token, which both deployment scripts do.

        - Mallory calls from a contract whose fallback function calls withdraw again.

        ##### What they get

        Mallory takes all of the ETH and WETH that every user has deposited into that escrow. She can size her own deposit with a flash loan so a single reentrant call empties the pool. The escrow's internal accounting also wraps around, so the recorded total stake becomes a huge number. Users lose their deposits and the owner has no way to recover ETH that has left the contract.

        ##### How it works

        1. Mallory deposits X ETH through depositETH (src/EscrowBase.sol:116) and is credited X WETH.

        2. She calls withdraw(WETH, X, true) (src/EscrowBase.sol:136). The balance check at line 142 passes.

        3. The contract unwraps X WETH into ETH (line 150) and sends X ETH to Mallory's contract with a low level call that forwards all gas (line 151).

        4. Her contract's fallback calls withdraw(WETH, X, true) again. Her recorded balance has not been reduced yet because the update at line 163 runs only after the send, so the check at line 142 passes again and another X ETH, belonging to other users, leaves the escrow.

        5. She repeats until the escrow's WETH is gone. Every nested call then unwinds, writes the same stale value at line 163, and subtracts X from totalStaked inside unchecked at line 164, which underflows.

        Exploit scenario

        Not specified.

        Recommendation

        Move the balance and totalStaked updates (lines 162-165) above every external call so the check and the state change happen before any ETH or token leaves the contract, and remove the unchecked block around totalStaked -= amount. Also add OpenZeppelin's ReentrancyGuardUpgradeable, initialize it in _EscrowBase_init, and mark depositToken, depositETH and withdraw as nonReentrant. Verify with a Foundry test where a contract with a fallback that calls withdraw again deposits ETH and calls withdraw(WETH, amount, true); the call must revert, and after any sequence of deposits and withdrawals the escrow's WETH balance must equal the sum of all users' recorded balances and tokens[WETH].totalStaked.

        Claude Security (Sonnet 5.5)

        withdraw() sends ETH to msg.sender before updating balances, so the balance authorization check can be re-entered and the pooled WETH drained

        src/EscrowBase.sol:151 Predicted severity: Critical

        Root cause

        Vulnerable symbol: withdraw

        Preconditions: The WETH token is configured with rebase == ETH_ADDRESS, as in the deployment scripts and tests.; The escrow holds WETH deposited by other users.; The escrow is not yet broke (the time window of onlyNotBroke).; WETH.withdraw can deliver ETH to the proxy within its gas stipend. The proxy's implementation slot and address are already warm inside the withdraw transaction, so this works, and the repo's own fork tests exercise this path. This is not confirmed by execution.

        Offending code:

        (bool success,) = msg.sender.call{value: amount}("");

        Impact

        Any depositor can drain all WETH-backed ETH deposits in the escrow, up to the full pooled balance. Other users' balances become unbacked, and totalStaked underflows to a huge value.

        Description

        The only authorization for a withdrawal is amount > usersBalance[msg.sender][token] at line 142. In the ETH unwrap path the contract makes a msg.sender.call{value: amount} with full gas at line 151 and only decrements usersBalance and totalStaked at lines 162-165. The attacker's receive hook can call withdraw again while the cached balance check still passes.

        Exploit scenario

        The attacker deploys a contract and calls depositETH() with 1 ETH, so usersBalance[attacker][WETH] = 1e18. The attacker calls withdraw(WETH, 1e18, true). The escrow calls WETH.withdraw(1e18), which sends 1 ETH to the escrow's empty payable fallback, then calls attacker.call{value: 1e18}. In the attacker's receive hook, usersBalance is still 1e18, so the hook calls withdraw(WETH, 1e18, true) again. Each nested call passes the balance check, burns 1 WETH of the escrow's pooled balance, and forwards 1 ETH. The attacker repeats this until the escrow's WETH is exhausted. The unwinding frames each write balance - amount from the stale cached balance. The unchecked totalStaked subtraction wraps silently, so nothing reverts. The attacker leaves with other depositors' WETH.

        Recommendation

        Apply checks-effects-interactions. Decrement usersBalance and totalStaked (with checked arithmetic) before any external call in withdraw(). Add a nonReentrant guard to withdraw, depositToken and depositETH. Remove the unchecked block around the totalStaked subtraction.

        Claude Security (Opus 5.5)

        Reentrancy in withdraw() ETH-unwrap path lets any depositor withdraw the same balance repeatedly and drain all pooled WETH

        src/EscrowBase.sol:151 Predicted severity: Critical

        Root cause

        Vulnerable symbol: withdraw

        Preconditions: Escrow is not broke (before breakTimestamp); A token is configured with rebase == ETH_ADDRESS (WETH in all shipped configs); Escrow holds WETH deposited by other users

        Offending code:

        (bool success,) = msg.sender.call{value: amount}("");

        Impact

        An unprivileged attacker can steal every user's WETH/ETH deposit held in MainEscrow or BridgeEscrow. Honest users' usersBalance entries stay in place but nothing backs them, and totalStaked becomes corrupted.

        Description

        withdraw() checks amount <= usersBalance[msg.sender][token] (line 141-142). It then sends ETH to the caller with a full-gas msg.sender.call (line 151) before it writes the new balance (line 163). A re-entrant call therefore passes the same balance check again against the stale balance. There is no ReentrancyGuard, and line 163 assigns the cached local balance - amount instead of decrementing, so each nested frame just resets the balance to 0.

        Exploit scenario

        WETH is added with rebase ETH_ADDRESS, as in both deployment scripts and the tests. The attacker deploys a contract and calls depositETH{value: B}(), which credits B WETH. It then calls withdraw(WETH, B, true). The escrow unwraps B WETH from the shared pool and sends B ETH to the attacker. The attacker's receive() calls withdraw(WETH, B, true) again. usersBalance is still B, so the check passes, the escrow unwraps another B of other users' WETH, and sends it. This repeats k times, limited by the pool size, gas and call depth. When the frames unwind, each one sets usersBalance to B - B = 0, and totalStaked silently underflows inside the unchecked block. The attacker gets k*B ETH for a B deposit. A flash loan supplies B, so one transaction can empty all of the escrow's WETH.

        Recommendation

        Follow checks-effects-interactions: decrement usersBalance and totalStaked before any external call (unwrap, ETH send, or token transfer), and do it with checked arithmetic. Also add OpenZeppelin ReentrancyGuard (nonReentrant) to withdraw, depositToken and depositETH.

        Vercel Security Review

        ETH withdrawal reentrancy lets a depositor drain pooled WETH

        src/EscrowBase.sol:150 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. A depositor's unchanged balance authorizes recursive withdrawals** - src/EscrowBase.sol:141-142

        ```solidity title="src/EscrowBase.sol:141-142"

        uint256 balance = s.usersBalance[msg.sender][token];

        if (amount > balance) revert NotEnoughAmountStaked(balance);

        ```

        Before escrow breaks, an attacker needs only a contract account with a WETH deposit.

        **2. Paying native ETH gives that account unrestricted callback control** - src/EscrowBase.sol:150-152

        ```solidity title="src/EscrowBase.sol:150-152"

        _unwrapETH(token, amount);

        (bool success,) = msg.sender.call{value: amount}("");

        if (!success) revert ETHSendFailed();

        ```

        Its receiver can reenter withdraw; neither escrow variant adds a reentrancy guard.

        **3. Late accounting charges the user only once for repeated payouts** - src/EscrowBase.sol:162-165

        ```solidity title="src/EscrowBase.sol:162-165"

        unchecked {

        s.usersBalance[msg.sender][token] = balance - amount;

        s.tokens[token].totalStaked -= amount;

        }

        ```

        Every frame writes the same cached balance minus amount, allowing the attacker to consume other depositors' pooled WETH.

        Exploit scenario

        Not specified.

        Recommendation

        Debit the user's balance and totalStaked before any external unwrap or transfer. Add a reentrancy guard covering withdrawal and interacting deposit paths, and test a recipient that recursively attempts withdrawal.

      • Centralization Risk bracket-fi-escrow-2 · 1 writeup High

        Devin Security (Deep)

        Owner can end the escrow at any moment, reopen it, and upgrade the contract with no delay

        src/EscrowBase.sol:220 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Whoever controls the owner key can cut the promised 30-day escrow to one second and immediately sweep or bridge all user deposits, or swap the contract code, with no delay in which users could withdraw.

        ##### What's wrong

        This is a missing timelock on admin controls. setEscrowBreak accepts any future timestamp, so the owner can move the break to the next second or reopen an escrow that already broke. withdrawEscrow sends the full balance of any token to the owner once broken, and _authorizeUpgrade lets the owner replace the implementation instantly. Nothing in the contract enforces the escrow length users were promised.

        ##### Who can do it

        Alice deposits into Acme's escrow expecting she can withdraw at any time during the 30 days. Mallory, who has obtained Acme's owner key (a leaked deployer key or a rogue multisig quorum), calls setEscrowBreak(block.timestamp + 1), waits one block, and calls withdrawEscrow with the list of deposit tokens on Arbitrum, or bridges the funds to her own address on mainnet.

        - The attacker controls the owner account. The deployment scripts make the deploying key the owner.

        ##### What they get

        Every user's deposit, taken immediately. Users get no window to withdraw because the break is applied in the same block it is set. Reopening the escrow after funds were moved also re-enables withdraw() against a balance that no longer exists, so whatever remains goes first-come-first-served. The same key can also upgrade the contract to any code at any time, which gives the same result by a different route.

        ##### How it works

        1. setEscrowBreak at EscrowBase.sol:220-225 only requires the new timestamp to be in the future. It has no lower bound relative to the current break and does not check whether the escrow already broke.

        2. One block later _checkEscrowBreak at EscrowBase.sol:228-232 returns true, and onlyNotBroke blocks all user withdrawals.

        3. withdrawEscrow at MainEscrow.sol:58-68 transfers every token balance to the owner; on mainnet the bridge functions in BridgeEscrow move the funds instead.

        4. Independently, _authorizeUpgrade at EscrowBase.sol:234 allows an instant implementation swap with the same effect.

        Exploit scenario

        Not specified.

        Recommendation

        Make the break timestamp one-way: revert in setEscrowBreak if the escrow is already broken, and either disallow moving the timestamp earlier than the current value or require a minimum notice period (for example at least 7 days in the future). Put the owner role behind a timelock (OpenZeppelin TimelockController) so setEscrowBreak, withdrawEscrow, bridge calls and upgrades all have a public delay. Remove the unused CannotSetEscrowBreakInThePast error or use it. To check the fix, add tests asserting that setEscrowBreak reverts when called after the break and when called with a timestamp earlier than the current break, and that an upgrade proposed through the timelock cannot execute before the delay.

      • Nonpayable bridgeTokenArb function bracket-fi-escrow-3 · 4 writeups Medium

        V12

        Outbound request omits gateway fee and data inputs

        src/BridgeEscrow.sol:47 Predicted severity: Informational

        Root cause

        The Arbitrum outbound request hardcodes empty gateway data and zero forwarded native value while exposing only gas-limit and gas-price parameters. Its compatibility with the configured gateway's funding and decoding requirements is not established.

        Impact

        Security relevance is unresolved: does the configured canonical gateway require ABI-encoded submission-cost data and native retryable-ticket funding that this call cannot provide? If so, bridging locked escrow assets fails even if the contract is separately funded with ETH; the exact missing facts are the gateway's data decoder and retryable funding checks, searched through the empty token-bridge submodule, direct router lookup and repository-wide gateway searches.

        Description

        bridgeTokenArb() accepts maxGas and gasPrice but cannot accept native value and forwards no native value to the router. It also always supplies bytes("") as the outbound request's data argument. There is no owned path to supply an encoded submission-cost field or other gateway-required fee metadata for this request. This is an integration assumption that gas parameters alone, an empty data payload, and zero forwarded ETH suffice to create the bridge transfer. The actual router and gateway implementations are absent, so required fee/data decoding and any alternative funding semantics could not be checked.

        Pashov (Claude Opus 5.5 high)

        bridgeTokenArb is non-functional: wrong approval target, empty gateway data and no ETH for the retryable ticket

        src/BridgeEscrow.sol:47 Predicted severity: Medium

        Root cause

        Incorrect integration with the Arbitrum L1GatewayRouter/L1ArbitrumGateway interface: the approval goes to the wrong spender, the gateway data is not encoded, and no ETH is supplied for retryable ticket fees.

        Impact

        No tokens (WETH, wstETH, rETH, weETH) can be bridged to Arbitrum after the break. Users cannot withdraw after the break either, so all L1 escrow funds are frozen until the owner deploys a corrective upgrade.

        Description

        bridgeTokenArb approves bridgeRouter and calls outboundTransferCustomRefund with bytes("") and no msg.value. In the Arbitrum token bridge, the L1 gateway returned by router.getGateway(token), not the router, pulls tokens with safeTransferFrom. The gateway also abi-decodes _data as (uint256 maxSubmissionCost, bytes extraData), and the Inbox requires msg.value >= maxSubmissionCost + maxGas * gasPrice. The function is non-payable and forwards no value. Each of these makes the call revert.

        Exploit scenario

        After breakTimestamp, the owner calls bridgeTokenArb(wstETH, arbEscrow, bal, gas, price). The gateway fails decoding the empty _data, or the Inbox rejects the zero msg.value, or the gateway's transferFrom fails because the allowance was given to the router. The transaction reverts and the funds remain stuck.

        Recommendation

        Approve bridgeRouter.getGateway(token), make the function payable, and forward {value: maxSubmissionCost + maxGas * gasPrice}. Pass abi.encode(maxSubmissionCost, bytes("")) as data. Add a fork test against the real Arbitrum bridge.

        Pashov (Codex GPT-6 Sol high)

        Arbitrum gateway transfer receives no retryable ticket fee

        src/BridgeEscrow.sol:47 Predicted severity: Medium

        Root cause

        The bridge path has no way to receive or forward a retryable ticket fee and does not encode the router's expected fee data.

        Impact

        Post-break transfers through the canonical Arbitrum gateway revert, delaying or preventing migration of escrowed assets until an implementation upgrade.

        Description

        bridgeTokenArb is nonpayable and calls the Arbitrum L1 gateway router without attaching ETH, so the router receives zero value. Standard Arbitrum outbound transfers require ETH to pay retryable ticket submission and execution fees. The call also passes empty router data instead of a submission-cost payload. The router implementation is not staged, so its exact fee and data checks could not be verified locally.

        Exploit scenario

        The owner calls bridgeTokenArb with a positive amount, maxGas, and gasPrice. The router receives msg.value=0; a retryable ticket with positive submission or execution cost cannot be funded and the outbound transfer reverts.

        Recommendation

        Make the bridge operation payable or otherwise fund the gateway call, forward the required fee, and encode the gateway's expected submission-cost data. Test against the deployed gateway interface.

        Devin Security (Deep)

        Both bridge-out functions always revert (unset renzoLockbox, wrong Arbitrum approval target, empty data, no ETH), locking L1 funds after escrow break until an upgrade

        src/BridgeEscrow.sol:20 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        After the escrow breaks, neither bridge function in the Ethereum escrow can succeed, so users' funds stay locked until the owner ships an upgrade.

        ##### What's wrong

        Two functional defects in the only exit paths. bridgeTokenConnext uses the renzoLockbox variable, which is never assigned anywhere, so it calls address zero. bridgeTokenArb approves the Arbitrum router instead of the per-token gateway that actually pulls the tokens, passes empty data where the gateway expects an encoded submission cost, and is not payable so it cannot forward the ETH the retryable ticket requires.

        ##### Who can do it

        Alice deposits wstETH and ezETH into the Ethereum escrow. The escrow breaks. Acme's multisig calls bridgeTokenArb and bridgeTokenConnext to move the funds to Arbitrum. Both calls revert. No attacker is involved.

        - The escrow has passed its break timestamp, so withdraw is closed to users by onlyNotBroke.

        - BridgeEscrow has no withdrawEscrow function, so the two bridge functions are the only way funds leave.

        ##### What they get

        Nobody steals anything. Alice's funds and everyone else's stay frozen in the Ethereum escrow, and the brktETH issuance on Arbitrum that depends on the bridged assets cannot proceed, until the owner writes, tests and deploys a new implementation through the UUPS upgrade path. If the owner key is lost the funds are stuck permanently.

        ##### How it works

        1. renzoLockbox is declared (src/BridgeEscrow.sol:21) but initialize (lines 31-45) never sets it and there is no setter.

        2. bridgeTokenConnext calls renzoLockbox.XERC20() (line 63) on address zero; Solidity's code size check on high level calls makes this revert.

        3. bridgeTokenArb approves bridgeRouter (line 52), but the Arbitrum L1 router forwards the call to the token's gateway, and the gateway performs safeTransferFrom(escrow, gateway, amount), so the allowance sits on the wrong contract.

        4. The router wraps the caller's data and the gateway decodes it as (uint256 maxSubmissionCost, bytes extraData); decoding the empty bytes passed at line 53 reverts.

        5. The function is not payable and forwards no ETH (lines 47-53), but creating the retryable ticket requires msg.value to cover the submission cost and L2 gas.

        Exploit scenario

        Not specified.

        Recommendation

        Set renzoLockbox in initialize with a zero address check, or add an owner-only setter. In bridgeTokenArb, make the function payable, approve bridgeRouter.getGateway(token) instead of the router, pass abi.encode(maxSubmissionCost, bytes("")) as the data argument, and forward msg.value to outboundTransferCustomRefund. Consider adding an owner-only, post-break withdrawEscrow to BridgeEscrow as a recovery path that does not require an upgrade. Verify with mainnet fork tests that skip past the break timestamp, call both functions, and assert the escrow's token balance decreases and the expected gateway and Connext events are emitted; the BridgeEscrow test file currently lists these as TODOs.

      • Allowance given to incorrect address bracket-fi-escrow-4 · 3 writeups Medium

        V12

        Router approval assumes the actual token spender

        src/BridgeEscrow.sol:47 Predicted severity: Informational

        Root cause

        The approve-then-route flow fixes the spender to bridgeRouter without establishing that it is the contract consuming the escrow's ERC20 allowance. Downstream spender semantics are unavailable for verification.

        Impact

        Security relevance is unresolved: does the configured router pull escrow tokens itself, or does a gateway require allowance from the escrow? If the gateway is the spender, the route cannot move user funds after withdrawals are disabled; the exact missing fact is the deployed router/gateway transfer implementation, searched in lib/token-bridge-contracts and repository-wide gateway and Solidity searches.

        Description

        bridgeTokenArb() approves only bridgeRouter and then delegates transfer handling to outboundTransferCustomRefund(). The owned code neither resolves a token-specific gateway nor approves any downstream spender. This couples authorization to the routing endpoint, although the exact contract executing transferFrom is not established by any available implementation. All library Solidity searches were empty, the token-bridge submodule directory is empty, and reading L1GatewayRouter.sol failed. The candidate is therefore the fixed-spender integration assumption, not a verified claim that a particular gateway actually pulls these tokens.

        Pashov (Claude Opus 5.5 high)

        bridgeTokenArb is non-functional: wrong approval target, empty gateway data and no ETH for the retryable ticket

        src/BridgeEscrow.sol:47 Predicted severity: Medium

        Root cause

        Incorrect integration with the Arbitrum L1GatewayRouter/L1ArbitrumGateway interface: the approval goes to the wrong spender, the gateway data is not encoded, and no ETH is supplied for retryable ticket fees.

        Impact

        No tokens (WETH, wstETH, rETH, weETH) can be bridged to Arbitrum after the break. Users cannot withdraw after the break either, so all L1 escrow funds are frozen until the owner deploys a corrective upgrade.

        Description

        bridgeTokenArb approves bridgeRouter and calls outboundTransferCustomRefund with bytes("") and no msg.value. In the Arbitrum token bridge, the L1 gateway returned by router.getGateway(token), not the router, pulls tokens with safeTransferFrom. The gateway also abi-decodes _data as (uint256 maxSubmissionCost, bytes extraData), and the Inbox requires msg.value >= maxSubmissionCost + maxGas * gasPrice. The function is non-payable and forwards no value. Each of these makes the call revert.

        Exploit scenario

        After breakTimestamp, the owner calls bridgeTokenArb(wstETH, arbEscrow, bal, gas, price). The gateway fails decoding the empty _data, or the Inbox rejects the zero msg.value, or the gateway's transferFrom fails because the allowance was given to the router. The transaction reverts and the funds remain stuck.

        Recommendation

        Approve bridgeRouter.getGateway(token), make the function payable, and forward {value: maxSubmissionCost + maxGas * gasPrice}. Pass abi.encode(maxSubmissionCost, bytes("")) as data. Add a fork test against the real Arbitrum bridge.

        Devin Security (Deep)

        Both bridge-out functions always revert (unset renzoLockbox, wrong Arbitrum approval target, empty data, no ETH), locking L1 funds after escrow break until an upgrade

        src/BridgeEscrow.sol:20 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        After the escrow breaks, neither bridge function in the Ethereum escrow can succeed, so users' funds stay locked until the owner ships an upgrade.

        ##### What's wrong

        Two functional defects in the only exit paths. bridgeTokenConnext uses the renzoLockbox variable, which is never assigned anywhere, so it calls address zero. bridgeTokenArb approves the Arbitrum router instead of the per-token gateway that actually pulls the tokens, passes empty data where the gateway expects an encoded submission cost, and is not payable so it cannot forward the ETH the retryable ticket requires.

        ##### Who can do it

        Alice deposits wstETH and ezETH into the Ethereum escrow. The escrow breaks. Acme's multisig calls bridgeTokenArb and bridgeTokenConnext to move the funds to Arbitrum. Both calls revert. No attacker is involved.

        - The escrow has passed its break timestamp, so withdraw is closed to users by onlyNotBroke.

        - BridgeEscrow has no withdrawEscrow function, so the two bridge functions are the only way funds leave.

        ##### What they get

        Nobody steals anything. Alice's funds and everyone else's stay frozen in the Ethereum escrow, and the brktETH issuance on Arbitrum that depends on the bridged assets cannot proceed, until the owner writes, tests and deploys a new implementation through the UUPS upgrade path. If the owner key is lost the funds are stuck permanently.

        ##### How it works

        1. renzoLockbox is declared (src/BridgeEscrow.sol:21) but initialize (lines 31-45) never sets it and there is no setter.

        2. bridgeTokenConnext calls renzoLockbox.XERC20() (line 63) on address zero; Solidity's code size check on high level calls makes this revert.

        3. bridgeTokenArb approves bridgeRouter (line 52), but the Arbitrum L1 router forwards the call to the token's gateway, and the gateway performs safeTransferFrom(escrow, gateway, amount), so the allowance sits on the wrong contract.

        4. The router wraps the caller's data and the gateway decodes it as (uint256 maxSubmissionCost, bytes extraData); decoding the empty bytes passed at line 53 reverts.

        5. The function is not payable and forwards no ETH (lines 47-53), but creating the retryable ticket requires msg.value to cover the submission cost and L2 gas.

        Exploit scenario

        Not specified.

        Recommendation

        Set renzoLockbox in initialize with a zero address check, or add an owner-only setter. In bridgeTokenArb, make the function payable, approve bridgeRouter.getGateway(token) instead of the router, pass abi.encode(maxSubmissionCost, bytes("")) as the data argument, and forward msg.value to outboundTransferCustomRefund. Consider adding an owner-only, post-break withdrawEscrow to BridgeEscrow as a recovery path that does not require an upgrade. Verify with mainnet fork tests that skip past the break timestamp, call both functions, and assert the escrow's token balance decreases and the expected gateway and Connext events are emitted; the BridgeEscrow test file currently lists these as TODOs.

    • Celestia PFM Go Cosmos IBC packet-forward middleware. Tasks 2 V12 1/2 Codex Sec 0/2 Pashov Opus — Pashov GPT-6 — Devin 0/2 Devin (Deep) 0/2 Claude Sec 0/2 Claude Opus 0/2 Vercel 0/2

      Cosmos IBC packet-forward middleware.

      Read the audit report
      • There is no upper limit to the time-out on PFM packets celestia-pfm-1 · 1 writeup Medium

        V12

        Forwarding lifetime lacks an operational upper bound

        middleware/packet-forward-middleware/packetforward/types/forward.go:18 Predicted severity: Informational

        Root cause

        Positive memo-specified durations bypass the middleware's configured default without a maximum or cumulative-lifetime check. Deferred acknowledgements and retry scheduling use that unchecked duration as their recovery deadline.

        Impact

        A packet author can request exceptionally long-lived pending forwarding state when the next hop does not acknowledge the packet; the original transfer then depends on that hop's acknowledgement or far-future timeout for recovery. The demonstrated custody consequence concerns that packet's own funds, not unauthorized locking of another user's assets; whether sustained creation of such records threatens deployment availability is unresolved because admissible packet volume, storage budgets, and any downstream lifetime cap were not available in the searched module and simapp wiring.

        Description

        ForwardMetadata.Validate constrains receiver, port, and channel but does not constrain the maximum positive timeout or total retry lifetime. The string decoder accepts representable Go durations such as 2562047h, and OnRecvPacket only replaces durations less than or equal to zero with its default. ForwardTransferPacket uses the resulting duration to create a timestamp hundreds of years ahead, sets the timeout height to zero, and saves both the original packet data and the duration after a successful transfer. Successful receipt returns no acknowledgement for the original packet, and retries reuse the same duration, with up to 255 retries expressible by the remote memo. There is no deadline cap or independent expiry/reconciliation path in the reviewed receive, send, acknowledgement, and timeout consumers.

      • Missing prefix for RefundPacketKey celestia-pfm-2 Medium
    • Chainlocker Solidity Self-custody escrow for buyer/seller deals. Tasks 6 V12 6/6 Codex Sec 3/6 Pashov Opus 4/6 Pashov GPT-6 3/6 Devin 3/6 Devin (Deep) 4/6 Claude Sec 4/6 Claude Opus 3/6 Vercel 3/6

      Self-custody escrow for buyer/seller deals.

      Read the audit report
      • Potential funds loss for buyers upon approval chainlocker-1 · 9 writeups Critical

        V12

        Unrelated callers force deposits from approved owners

        src/TokenLocker.sol:417 Predicted severity: High

        Root cause

        The deposit flow treats allowance to the contract as authorization for any external caller to choose when and how much the owner deposits. It provides no caller-to-owner binding or explicit operator authorization for the escrow action.

        Impact

        An external caller can force an approved owner's tokens into an escrow and trigger non-refundable forfeiture to the seller on expiry. This is conditional on an outstanding allowance to the locker; the attacker does not obtain authority over wallets that have not approved it.

        Description

        depositTokens() accepts a caller-selected _depositor and checks that address's allowance, but never checks whether the caller is that depositor or an authorized operator. In an identified-buyer locker, the only identity check is _depositor == buyer, which anyone can satisfy by supplying the buyer's address. An unrelated caller can therefore pull tokens from a buyer who has approved the locker but has not submitted a deposit action. In a non-refundable locker, crossing the deposit threshold commits those tokens to the seller's expiry payout even if the buyer never approves execution. The permit path also has no separate action authorization, although it additionally requires a valid token permit.

        Codex Security (GPT-6 Sol)

        Any caller can commit a victim's approved tokens to escrow

        src/TokenLocker.sol:417 Predicted severity: Medium

        Root cause

        The deposit API takes _depositor from an arbitrary caller, checks only a token allowance or permit and the chosen depositor address, then calls transferFrom for that account. Token spending approval is not tied to a particular escrow action, caller, or time.

        Impact

        Exploitation requires a prior locker-specific approval or an unused permit, but can then commit real tokens and pay a nonrefundable deposit to an attacker-controlled seller.

        Description

        depositTokens accepts any caller's _depositor address and uses that account's locker allowance, allowing a malicious seller to force a victim's tokens into a nonrefundable escrow.

        Exploit scenario

        Victim grants locker-specific allowance or signs a permit; malicious seller or third party submits the deposit first; expiry routes the nonrefundable deposit to seller.

        Recommendation

        Require the depositor to submit the ordinary deposit transaction, or verify a separate depositor authorization that binds the locker, amount, escrow terms and deadline before third-party submission.

        Pashov (Claude Opus 5.5 high)

        depositTokens lets anyone pull tokens from any address that has approved the locker

        src/TokenLocker.sol:417 Predicted severity: Medium

        Root cause

        There is no check that the caller is, or is authorised by, _depositor.

        Impact

        A victim who approved the locker, for example in the approve step of a two-transaction flow or with an infinite approval, can have tokens moved without consent. The tokens are bound to a non-refundable deposit, or credited to a pool that the current buyer (possibly the attacker) receives at expiry. Combined with the expiry settlement in F-001, this is direct theft.

        Description

        depositTokens(_depositor, _amount) takes an arbitrary _depositor and calls transferFrom(_depositor, this, _amount) without checking msg.sender == _depositor. Any third party can therefore choose when, and how much of, an approver's allowance is moved into the locker. In an open offer they can also make the victim the buyer, or move the victim's tokens in while someone else is already buyer.

        Exploit scenario

        Open offer, non-refundable. Attacker B becomes buyer by depositing deposit. Victim V approves the locker for totalAmount - deposit, planning to join or to deposit after B is rejected. B front-runs V's deposit with depositTokens(V, allowance). V's tokens enter the locker, but buyer is B, so at expiry all non-deposit funds go to B. Alternatively the seller forces an approver into a non-refundable deposit and collects it at expiry.

        Recommendation

        Require _depositor == msg.sender (or use msg.sender directly) for depositTokens.

        Pashov (Codex GPT-6 Sol high)

        Any caller can force a token allowance into a nonrefundable escrow

        src/TokenLocker.sol:417 Predicted severity: High

        Root cause

        The allowance-based deposit path lacks a msg.sender==_depositor check or signed instruction binding the depositor to this call and escrow cycle.

        Impact

        A seller can force a buyers tokens into escrow and claim the configured nonrefundable deposit at expiry, including by spending a standing allowance after an earlier cycle. High severity: a seller can force a full allowance-backed payment and collect it as a nonrefundable deposit.

        Description

        depositTokens accepts any depositor address and only checks that it has granted the locker an ERC20 allowance. Any caller can initiate transferFrom on that allowance without the token owners per-call authorization, including when the resulting deposit is nonrefundable.

        Exploit scenario

        The buyer grants the locker a standing 100-token allowance while planning to fund later. The seller calls depositTokens(buyer,100) without the buyers participation, refuses to approve execution, and after expiry receives the 100-token nonrefundable deposit.

        Recommendation

        Require msg.sender to equal _depositor for allowance-based deposits or verify a signature authorizing this deposit and cycle; revoke further funding after successful execution.

        Devin Security

        depositTokens lets anyone pull tokens from any address that approved the locker

        src/TokenLocker.sol:417 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can move tokens out of the wallet of any user who has approved a TokenLocker. In a non-refundable locker, the seller can force a would-be buyer into the deal and keep that buyer's deposit at expiry.

        ##### What's wrong

        This is a missing authorization check. depositTokens() takes a _depositor address from the caller and runs transferFrom(_depositor, ...), but it never checks that msg.sender == _depositor. The only checks are that _depositor has enough allowance and, for closed offers, that _depositor == buyer.

        ##### Who can do it

        Mallory deploys a non-refundable open-offer TokenLocker and names herself as seller. Alice, a prospective buyer at Globex, approves the locker for the full amount while she reviews the deal, or gives it an unlimited approval. Before Alice decides, Mallory calls depositTokens(Alice, deposit). Alice's tokens move into the locker and Alice becomes buyer. Mallory never approves execution. At expiry, checkIfExpired() pays the deposit to Mallory as seller.

        - The victim has an outstanding ERC-20 allowance to this specific TokenLocker.

        - For an open offer, no buyer is fixed yet, so any approver can be targeted. For a closed offer, only the named buyer can be targeted, and the harm is a deposit forced on them at a time they did not choose.

        - The caller needs nothing else. depositTokens() has no caller check.

        ##### What they get

        Mallory can force Alice into an escrow she did not agree to, and in a non-refundable locker she can take Alice's deposit tokens. Anyone else can also lock up Alice's approved tokens until the seller rejects her or the locker expires. Every user who has approved the locker is exposed, up to their allowance.

        ##### How it works

        1. depositTokens() at TokenLocker.sol:417-420 accepts any _depositor from any caller.

        2. TokenLocker.sol:424-426 only checks the closed-offer buyer match and the size of _depositor's allowance. It never compares _depositor with msg.sender.

        3. TokenLocker.sol:431-433 makes _depositor the buyer in an open offer.

        4. TokenLocker.sol:442 pulls _amount from _depositor with safeTransferFrom.

        5. At expiry, checkIfExpired() at TokenLocker.sol:585-587 sends deposit to the seller when the locker is non-refundable.

        depositTokensWithPermit() at TokenLocker.sol:378-408 also takes _depositor from the caller. Anyone who copies a broadcast permit signature can submit it first. That makes the victim's own transaction revert. This is only a nuisance, because the permit still grants the allowance.

        Exploit scenario

        Not specified.

        Recommendation

        In depositTokens(), pull tokens from msg.sender instead of a caller-supplied _depositor, or require msg.sender == _depositor. In depositTokensWithPermit(), wrap the permit call in try/catch so a front-run permit does not block the deposit. To check the fix, write a test. Alice approves the locker. Then a different address calls depositTokens(Alice, x), and the call must revert.

        Devin Security (Deep)

        depositTokens() pulls tokens from any caller-chosen address that holds an allowance

        src/TokenLocker.sol:417 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can force an address that has approved the locker into the escrow before that address chooses to deposit, and in a non-refundable escrow this hands the deposit to the seller at expiry.

        ##### What's wrong

        This is a transferFrom with an arbitrary from: the caller picks _depositor, and the contract pulls that address's tokens based only on an existing allowance, with no check that msg.sender is the depositor or the buyer.

        ##### Who can do it

        Alice approves a non-refundable open-offer locker for 1,000 tokens while negotiating with the seller Mallory, then decides not to go through with it but does not revoke the approval. Mallory calls depositTokens(alice, 1000).

        - Alice has a live allowance to the specific locker.

        - For a non-open offer, Alice must be the configured buyer; for an open offer, anyone with an allowance qualifies.

        - The escrow has not expired.

        ##### What they get

        Alice's tokens are moved into the escrow against her will. She cannot withdraw them; only the seller can release them before expiry. In a non-refundable escrow, deposit goes to Mallory at expiry whether or not she delivers anything, and in an open offer Alice is also recorded as the buyer. The harm is limited to the amount Alice approved for that locker.

        ##### How it works

        1. Mallory calls depositTokens(alice, amount) (TokenLocker.sol:417-420); there is no msg.sender check.

        2. Line 425 only confirms allowance(alice, locker) >= amount.

        3. Line 442 calls safeTransferFrom(token, alice, locker, amount), moving Alice's tokens.

        4. At expiry, checkIfExpired() (TokenLocker.sol:585-591) pays deposit to the seller in a non-refundable escrow.

        Exploit scenario

        Not specified.

        Recommendation

        Require msg.sender == _depositor in depositTokens() (the permit variant already needs the depositor's signature), or drop the _depositor parameter and use msg.sender. Test: approve the locker from wallet A, call depositTokens(A, amount) from wallet B, and assert it reverts.

        Claude Security (Sonnet 5.5)

        depositTokens trusts caller-supplied _depositor as the transferFrom source without binding it to msg.sender

        src/TokenLocker.sol:442 Predicted severity: Low

        Root cause

        Vulnerable symbol: TokenLocker.depositTokens

        Preconditions: The victim has an outstanding ERC20 allowance to the TokenLocker, for example unlimited approvals or an allowance larger than the amount actually deposited; For the theft variant: the locker is non-refundable and its expiry is still in the future (after execute() or while deposits are open); For open offers: the attacker can name any approving address as buyer

        Offending code:

        safeTransferFrom(tokenContract, _depositor, address(this), _amount);

        Impact

        A third party, and in practice the seller, can move any approver's tokens into escrow without that approver's action. With a non-refundable locker this becomes a theft of up to deposit from the leftover allowance, collected at expiry. In any locker it forces premature deposits and, for open offers, an attacker-chosen buyer assignment.

        Description

        The untrusted _depositor argument of the external depositTokens is never compared to msg.sender. It flows straight into the from argument of the assembly safeTransferFrom, so any caller can pull tokens from any address that has an allowance to the locker. Also CWE-862: The attacker-chosen _depositor argument is the from of a transferFrom, and the only gate is erc20.allowance(_depositor, address(this)) >= _amount (line 425); msg.sender is never compared to _depositor, so a standing approval meant for the depositor's own deposit can be spent by anyone.

        Exploit scenario

        1) Seller S deploys a non-refundable TokenLocker (refundable=false, deposit D, totalAmount T, expiry well in the future) for buyer B. 2) B grants the locker a large or unlimited allowance, deposits T and the deal executes: execute() pays T to S, deletes deposited, and leaves buyer and the expiry untouched. There is no terminal state. 3) S calls depositTokens(B, D). All checks pass: _depositor == buyer, allowance(B, locker) >= D, not expired. D of B's tokens are pulled into the locker and deposited is set again. 4) At expiry, checkIfExpired() sees !refundable && _isDeposited and sends D to S. S has taken D (up to T if deposit == totalAmount) a second time from B's leftover allowance. In an open offer, anyone can also choose the buyer: they call depositTokens(victim, x) for any address with an allowance, which sets buyer = victim and forces the victim's tokens into escrow at a time the attacker picks.

        Recommendation

        Require msg.sender == _depositor, or drop the parameter and use msg.sender, in depositTokens. Keep third-party relaying only for depositTokensWithPermit, where the signature authorises it. Add a terminal 'executed' state so no deposits are accepted after execute(). Advise users to approve exact amounts. Also CWE-862: Require msg.sender == _depositor in depositTokens, or drop the _depositor parameter and use msg.sender. Keep the permit variant's signature-based flow, which is already authorized by the owner's signature.

        Claude Security (Opus 5.5)

        depositTokens pulls tokens from any caller-chosen _depositor's allowance, which lets an attacker take over the buyer role and drain a victim's approved tokens

        src/TokenLocker.sol:442 Predicted severity: High

        Root cause

        Vulnerable symbol: depositTokens

        Preconditions: Locker is an open offer (for non-open offers _depositor must equal buyer, which limits the attacker to moving the buyer's own allowance into escrow early); Victim has an outstanding allowance to the locker, either from the normal approve-then-deposit flow or from a public permit signature the attacker can replay to token.permit; deposit >= 2, so a sub-threshold pull from the victim is possible; The seller does not call rejectDepositor for the victim before expiry, or the seller is the attacker

        Offending code:

        safeTransferFrom(tokenContract, _depositor, address(this), _amount);

        Impact

        Theft of a victim's ERC20 tokens up to the lesser of their allowance to the locker and totalAmount-1. Victims can also be pushed into non-refundable escrows they never chose to join. The EthLocker equivalent ties the depositor to msg.sender, and the TokenLocker NatSpec says the same ('updates buyer to msg.sender', 'records amount deposited by msg.sender'), so this is a divergence from the intended design.

        Description

        _depositor is taken straight from the caller and becomes the from of transferFrom with no msg.sender == _depositor check, so any caller can spend another address's allowance to this locker. Because only crossing the deposit threshold assigns buyer (lines 429-433), and the whole balance goes to buyer at expiry (line 599), the attacker can deposit a victim's tokens as an 'other depositor' and still collect them as buyer. Also CWE-863: _depositor is a caller-supplied parameter and is never compared to msg.sender, so any caller can spend another address's ERC20 allowance to this locker. In an open offer, the caller can also make that address the buyer.

        Exploit scenario

        Take an open-offer, refundable TokenLocker with deposit D >= 2. Victim V calls token.approve(locker, X) with X >= D-1, as the two-step approve-then-deposit UI expects, or approves the maximum. The attacker watches for that approve, or grabs V's EIP-2612 signature from the mempool and submits it to token.permit directly, then: (1) calls depositTokens(V, D-1). The balance is below deposit, so V's tokens move into the locker but V is not made buyer. (2) Calls depositTokens(attacker, 1). The balance reaches D, so buyer = attacker and deposited = true. (3) Optionally calls depositTokens(V, totalAmount-D) to pull more of V's allowance. V's own deposit call now reverts for lack of allowance. After expiry anyone calls checkIfExpired(), and line 599 sends the whole balance to the attacker. The attacker spent 1 token and takes everything pulled from V. If the seller is the attacker, which works for both refundable and non-refundable lockers, the seller controls the attacker-buyer address, both call readyToExecute, and execute() pays V's tokens to the seller while V was never the buyer.

        Recommendation

        Bind deposits to the caller. Use msg.sender as the from and as the recorded depositor and buyer in depositTokens, and in depositTokensWithPermit either require _depositor == msg.sender or drop the parameter. If deposits on behalf of others are needed, pull from msg.sender and credit a separate beneficiary field, never another address's allowance. Also CWE-863: Require _depositor == msg.sender in depositTokens(). In depositTokensWithPermit(), either require the same or bind the permit to msg.sender.

        Vercel Security Review

        Open-offer refunds let a frontrunner collect another buyer's deposit

        src/EthLocker.sol:269 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. A frontrunner funds the required deposit first and captures the buyer slot** - src/EthLocker.sol:269-272

        ```solidity title="src/EthLocker.sol:269-272"

        if (address(this).balance >= deposit && !deposited) {

        // if this EthLocker is an open offer and was not yet accepted (thus '!deposited'), make depositing address the 'buyer' and update 'deposited' to true

        if (openOffer) {

        buyer = payable(msg.sender);

        ```

        **2. The victim's pending deposit remains accepted** - src/EthLocker.sol:264-267

        ```solidity title="src/EthLocker.sol:264-267"

        receive() external payable {

        if (address(this).balance > totalAmount)

        revert EthLocker_BalanceExceedsTotalAmount();

        if (expirationTime <= block.timestamp) revert EthLocker_IsExpired();

        ```

        When twice the deposit fits within totalAmount, no buyer check prevents the victim's funds joining the attacker's escrow. The new token paths likewise accept nonbuyers (src/TokenLocker.sol:386-407,421-442), including allowance-backed third-party pulls.

        **3. Expiry refunds both parties' funds to the attacker** - src/EthLocker.sol:431-434

        ```solidity title="src/EthLocker.sol:431-434"

        } else {

        safeTransferETH(buyer, address(this).balance);

        emit EthLocker_DepositedAmountTransferred(

        buyer,

        ```

        For refundable offers, no execution approval is needed. src/TokenLocker.sol:598-599 repeats this pooled refund; an honest seller's intervention is optional.

        Exploit scenario

        Not specified.

        Recommendation

        Refund each contributor's funds to that contributor instead of assigning the entire balance to the selected buyer. Bind acceptance transactions to the expected buyer/offer state, and reject funding from unrelated parties after a buyer is selected unless that contributor explicitly authorizes funding that buyer. In TokenLocker, do not allow arbitrary callers to consume another depositor's allowance for an already claimed offer.

      • updateBuyer does not update amountDeposited mapping chainlocker-2 · 1 writeup Critical

        V12

        Consumed contribution credits drain later escrow deposits

        src/EthLocker.sol:264 Predicted severity: Critical

        Root cause

        Settlement consumes the aggregate ETH balance but invalidates only the current buyer's contribution record. Party replacement and offer reuse leave other already-consumed amountDeposited entries redeemable through rejectDepositor().

        Impact

        A seller can withdraw a later buyer's escrow balance by recycling a contribution that was already paid out during an earlier execution. This path does not depend on surviving approval flags: the stale per-address refund credit remains independently actionable after execution.

        Description

        receive() credits each actual sender in amountDeposited, but updateBuyer() changes the refund identity without migrating or settling the former buyer's credit. Both execute() and expiry settlement clear only amountDeposited[buyer], even when funds credited to other addresses are included in the outgoing payment. A seller can fund its own open offer, replace itself as buyer with another controlled address, obtain the necessary approvals, and execute, recovering the initial funding while its original contribution remains recorded. A subsequent deposit reopens the same offer, and rejectDepositor() still treats that already-spent contribution as a payable refund. The seller can therefore reimburse its stale entry using the new buyer's funds without executing the new escrow or obtaining that buyer's approval.

      • Buyers can prevent themselves from being rejected chainlocker-3 · 1 writeup High

        V12

        Rejecting buyers permanently block non-refundable deposit payouts

        src/EthLocker.sol:38 Predicted severity: Critical

        Root cause

        Mandatory inline payouts couple every settlement and rejection transition to recipient acceptance. Address changes themselves depend on expiry settlement, leaving no recipient-independent recovery once an unpayable buyer blocks the deadline distribution.

        Impact

        A buyer can permanently prevent the seller from receiving its non-refundable deposit by rejecting the remainder, while also leaving the buyer's own contribution locked. For this sole-contributor open-offer state, rejection, execution, expiry retries, and post-deadline address replacement cannot complete settlement, so the seller's entitlement cannot be withdrawn without cooperation that the fixed rejecting recipient does not provide.

        Description

        Refunds in rejectDepositor() and expiry payouts use synchronous ETH calls that revert the enclosing transition when a recipient rejects payment. For a non-refundable open offer with deposit = 5 and totalAmount = 10, a contract buyer can contribute 10 and deliberately reject all incoming ETH. Rejecting that buyer fails and rolls back the buyer/deposit/ledger cleanup. At expiry the seller's payment of 5 is followed by the buyer's refund of 5; the rejecting buyer makes the entire transaction revert, including the seller's completed call. updateBuyer() cannot repair the recipient after the deadline because it first executes the same failing expiry settlement. No recipient-independent payout or recovery path exists in the reviewed implementation.

      • Irrevertible loss of tokens chainlocker-4 · 6 writeups High

        V12

        Unassigned open-offer refunds burn remaining contributions

        src/EthLocker.sol:206 Predicted severity: Critical

        Root cause

        checkIfExpired() distributes aggregate balances to buyer even when open-offer initialization or rejection has left that address unset. It has neither a valid-recipient guard nor an alternative per-contributor withdrawal path for that state.

        Impact

        Unassigned open-offer contributions are permanently lost when permissionless expiry transfers them to the zero address. The seller's ability to refund individual contributors before settlement does not protect them against a deadline caller executing the zero-recipient payout, and no recovery mechanism can retrieve ETH after that transfer.

        Description

        An open offer can hold ETH while buyer is zero, both before its threshold has been reached and after the seller rejects the current buyer but other contributions remain. checkIfExpired() deletes deposit state and then sends the remaining balance to buyer without checking that a recipient has been established. For a refundable offer, A can contribute 4 and B contribute 1 with deposit = 5; rejecting B leaves A's 4 in escrow and clears buyer to zero. If no replacement buyer is established before the deadline, any caller can settle and transfer those 4 to address(0). A low-level ETH call to the zero address succeeds, so the transaction does not roll back and the remaining contribution is irrecoverable. The payable constructor also permits an open offer to start with unrecorded ETH and no buyer, creating the same zero-recipient expiry path if buyer selection never occurs.

        Pashov (Claude Opus 5.5 high)

        Expiry refund goes to buyer == address(0) when no buyer exists, burning or freezing depositors' funds

        src/EthLocker.sol:229 Predicted severity: Medium

        Root cause

        Expiry settlement pays a single buyer address and never checks that it is set. Per-depositor balances (amountDeposited) are ignored.

        Impact

        Depositors who contributed but never met the deposit threshold (or whose buyer was rejected) permanently lose their funds once the locker expires.

        Description

        In an EthLocker open offer, buyer starts as address(0) and is reset to address(0) by rejectDepositor(buyer). Contributions below the deposit threshold do not set a buyer. At expiry, checkIfExpired() runs safeTransferETH(buyer, address(this).balance) without checking for a zero buyer, so the ETH is sent to the zero address. In TokenLocker the same transfer either burns tokens or reverts. Revert-on-zero tokens such as OpenZeppelin ERC20 then freeze the tokens permanently.

        Exploit scenario

        Open-offer EthLocker, deposit = 5 ETH. Alice sends 2 ETH and plans to send the rest later, then does not (or the seller rejects the previous buyer while Alice's funds sit there). After expiry anyone calls checkIfExpired() and 2 ETH is sent to address(0).

        Recommendation

        If buyer == address(0) at expiry, do not push funds. Let each depositor withdraw their own amountDeposited instead (pull-based refunds).

        Devin Security

        Tokens from other depositors go to the buyer, or get stuck, when the locker expires

        src/TokenLocker.sol:417 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        In an open offer, anyone who deposits less than the deposit amount can lose those tokens to whoever crosses the threshold, or have them locked in the contract.

        ##### What's wrong

        Settlement ignores each depositor's amountDeposited record. Buyer status is decided from the total token balance plus the new amount, so a small deposit can make someone buyer by using other people's tokens. At expiry, checkIfExpired() sends the whole balance to buyer. If buyer is address(0), most ERC-20 tokens refuse the transfer, so checkIfExpired() reverts and the tokens stay locked.

        ##### Who can do it

        Bob deposits 600 tokens into an open-offer locker that has a 1,000-token refundable deposit. Mallory, anyone on chain, deposits 400 and becomes buyer. After expiry, anyone calls checkIfExpired(), and all 1,000 tokens go to Mallory.

        - The locker is an open offer.

        - Another user has a partial deposit that the seller has not refunded before expiry.

        ##### What they get

        Mallory takes Bob's tokens. In the zero-buyer case, every call to checkIfExpired() reverts, so Bob's tokens stay locked unless the seller chooses to refund him. For non-refundable lockers, a refunded non-buyer depositor can push the balance below deposit. _balance - deposit at line 586 then underflows and blocks settlement.

        ##### How it works

        1. depositTokens() makes _depositor buyer once balanceOf(this) + _amount >= deposit at TokenLocker.sol:421-435.

        2. checkIfExpired() deletes only amountDeposited[buyer] at TokenLocker.sol:582.

        3. checkIfExpired() sends the full balance, or the remainder, to buyer at TokenLocker.sol:593 and 599.

        4. If buyer is address(0) after rejectDepositor() at TokenLocker.sol:555, the transfer reverts for most tokens and the funds stay locked.

        Exploit scenario

        Not specified.

        Recommendation

        Refund each depositor from amountDeposited at expiry, or add a pull-based withdrawal. Base buyer status on the depositor's own recorded amount. Skip or reject transfers to address(0). To check the fix, write tests where multiple partial depositors and an expiry each get back exactly what they deposited.

        Devin Security (Deep)

        Expiry sends the whole balance to address(0) when an open offer has no buyer, burning depositors' ETH

        src/EthLocker.sol:431 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        ETH sent to an open-offer escrow that never reached the deposit threshold, or that remains after the seller rejects the buyer, is burned to the zero address at expiry instead of being refunded.

        ##### What's wrong

        This is a missing zero-address check on a payout. In an open offer the buyer is address(0) until someone crosses the deposit threshold, and rejectDepositor() resets it to address(0); checkIfExpired() then sends the entire balance to buyer without checking it.

        ##### Who can do it

        Alice sees an open offer with a 10 ETH deposit and sends 6 ETH, meaning to send the rest later, but the seller stops responding and she gives up. Nobody calls rejectDepositor(). At expiry, Bob, a keeper bot, calls checkIfExpired(). In a second version, Alice is the buyer with 10 ETH and Carol, Alice's second wallet, adds 5 ETH; the seller Mallory rejects Alice and ignores Carol, so Carol's 5 ETH sit with buyer == address(0) until expiry.

        - openOffer == true.

        - buyer == address(0) at expiry: the deposit threshold was never crossed, or the seller rejected the buyer.

        - The contract balance is above zero.

        - The seller did not call rejectDepositor() for the remaining depositors before expiry.

        ##### What they get

        No one profits; the depositor's ETH is destroyed. A seller can also cause this on purpose by rejecting the buyer and ignoring other depositors, as a way to punish them. The loss is limited to the balance of that one escrow, and there is no way to recover it after the call.

        ##### How it works

        1. The constructor leaves buyer at address(0) for open offers (EthLocker.sol:229), and rejectDepositor() resets it to address(0) (EthLocker.sol:390-393).

        2. Alice's partial payment is accepted by receive() (EthLocker.sol:264-282) but does not reach deposit, so buyer stays address(0).

        3. After expiry, checkIfExpired() (EthLocker.sol:431-436) calls safeTransferETH(buyer, address(this).balance) with buyer == address(0).

        4. The low-level call to address(0) succeeds, so the ETH is burned.

        Exploit scenario

        Not specified.

        Recommendation

        In checkIfExpired(), if buyer == address(0), do not push funds; instead leave them claimable per depositor using amountDeposited (a pull-based withdraw() after expiry), or at least revert so the seller can still refund via rejectDepositor(). Test: open-offer locker, send less than deposit, warp past expiry, call checkIfExpired(), and assert the depositor can reclaim the ETH and that the contract never transfers to address(0).

        Claude Security (Sonnet 5.5)

        Open-offer refund at expiry is sent to an unvalidated, unset buyer (address(0)), burning partial depositors' ETH

        src/EthLocker.sol:432 Predicted severity: Low

        Root cause

        Vulnerable symbol: checkIfExpired

        Preconditions: openOffer == true; Balance is greater than zero at expiry while buyer is address(0); The seller does not call rejectDepositor for those depositors before expiry

        Offending code:

        safeTransferETH(buyer, address(this).balance);

        Impact

        Permanent loss of ETH for depositors in open offers whose balance never reached deposit, or whose buyer was rejected. The only rescue is a seller action taken before checkIfExpired() is first called after expiry, and depositors cannot withdraw on their own.

        Description

        For open offers the constructor leaves buyer as address(0), and rejectDepositor resets it to address(0). checkIfExpired() sends the whole balance to buyer with no non-zero check, so ETH from depositors who never reached deposit is sent to address(0). Also CWE-863: receive() accepts ETH from any sender. The first sender whose arrival makes balance >= deposit becomes buyer in an open offer (:269-274), regardless of how much of the balance came from others. checkIfExpired() then sends the entire address(this).balance to buyer and ignores the per-depositor amountDeposited mapping, so other depositors' ETH is paid to whoever holds the buyer role. Also CWE-754: In an open offer, buyer is address(0) until some depositor reaches deposit (and again after rejectDepositor). checkIfExpired() sends the entire balance to buyer without checking for zero. Any address, including a third party, can trigger this after expiry.

        Exploit scenario

        An open-offer EthLocker has deposit = 10 ETH. A user sends 4 ETH, so deposited stays false and buyer stays address(0), and the 4 ETH is recorded only in amountDeposited[user]. The seller does not call rejectDepositor before expiry. After expiry anyone calls checkIfExpired() (or execute/updateSeller/updateBuyer, which call it). The else-branch executes safeTransferETH(address(0), balance) and the 4 ETH is burned. The same happens to other depositors' remaining ETH after the seller calls rejectDepositor(buyer) and buyer is reset to address(0).

        Recommendation

        Never use buyer as the refund target when it is address(0). Refund each depositor from amountDeposited[] (pull-based, or iterate depositors) and let depositors withdraw their own balance after expiry. At minimum, skip or revert-safe the transfer when buyer == address(0) and keep the funds claimable. Also CWE-863: Track and pay refunds per depositor via amountDeposited (a pull-based withdrawal after expiry). Alternatively, restrict deposits in an open offer to a single address until the offer is accepted, or require msg.sender == buyer for all deposits once buyer is set. Never treat all escrowed ETH as belonging to the buyer role. Also CWE-754: At expiry, refund each depositor from amountDeposited (pull-based per-address refunds), or revert/skip when buyer == address(0) and let depositors withdraw their own amountDeposited. Never push to an unset buyer.

        Claude Security (Opus 5.5)

        Open-offer EthLocker burns all escrowed ETH to address(0) at expiry when no depositor qualified as buyer

        src/EthLocker.sol:432 Predicted severity: Medium

        Root cause

        Vulnerable symbol: checkIfExpired

        Preconditions: openOffer == true; Non-zero balance held at expiry with no current buyer (partial deposits, or buyer rejected)

        Offending code:

        safeTransferETH(buyer, address(this).balance);

        Impact

        Depositors permanently lose their ETH, and any third party can trigger the loss at expiry.

        Description

        In an open offer, buyer stays address(0) until someone pushes the balance past deposit, and it is reset to address(0) by rejectDepositor(). checkIfExpired() is public and callable by anyone. It sends the whole balance to buyer without checking for the zero address, so partial deposits recorded in amountDeposited are destroyed.

        Exploit scenario

        1. Prospective buyers send partial amounts (each below deposit) to an open-offer EthLocker, a flow the contract explicitly supports. Alternatively, the seller rejects the buyer while other partial deposits remain.

        2. At expirationTime, any address calls checkIfExpired(). deposited is false and buyer == address(0), so the else branch sends the entire balance to address(0).

        3. amountDeposited[victim] stays non-zero, but the balance is gone and rejectDepositor() can no longer refund it.

        Recommendation

        When buyer == address(0), do not push the balance. Let each depositor withdraw their amountDeposited (pull pattern), or refund recorded depositors instead of sending to buyer.

      • buyerApproved not cleared when buyer is rejected chainlocker-5 · 9 writeups Medium

        V12

        Replacement buyer inherits rejected buyer's approval

        src/EthLocker.sol:310 Predicted severity: High

        Root cause

        buyerApproved and sellerApproved are not invalidated when their associated party identities change. In particular, rejectDepositor() resets an open-offer relationship without clearing its buyer authorization.

        Impact

        A seller can reject an approved buyer and then release a replacement buyer's funding without obtaining that buyer's approval. This bypasses the escrow's separate buyer-consent gate and permits conditional loss of the replacement buyer's funds.

        Description

        readyToExecute() stores buyer consent in the unkeyed buyerApproved flag. In an open offer, rejectDepositor() removes the current buyer and resets deposited, but does not clear that flag. A subsequent deposit assigns a different buyer while retaining the rejected buyer's approval. With full funding and seller approval, execute() therefore pays the seller even though the replacement buyer never called readyToExecute(). Party-address updates likewise leave the corresponding approval flags unchanged.

        Codex Security (GPT-6 Sol)

        Seller can execute against a new buyer using a former buyer's approval

        src/EthLocker.sol:315 Predicted severity: High

        Root cause

        readyToExecute records global booleans. Neither rejectDepositor, updateBuyer, nor updateSeller invalidates them. execute checks only the flags and balance, so approvals from former parties authorize a later state.

        Impact

        A malicious seller can prepare stale approval before a new buyer deposits, then take the new buyer's entire escrow once fully funded.

        Description

        Approval flags survive buyer or seller replacement and open-offer rejection, so execution can use consent from a former role holder.

        Exploit scenario

        Seller-controlled initial buyer deposits and approves; seller rejects them; new buyer deposits; anyone calls execute, which pays seller without a new buyer approval.

        Recommendation

        Clear both approval flags whenever either role changes or an accepted buyer is rejected; bind approvals to the current role addresses and offer generation.

        Pashov (Claude Opus 5.5 high)

        Buyer approval survives buyer replacement (rejectDepositor), and TokenLocker presets buyer in open offers, so funds can be released without the real buyer's consent

        src/EthLocker.sol:310 Predicted severity: High

        Root cause

        Approvals are never cleared when the buyer identity changes, and TokenLocker does not ignore _buyer for open offers as EthLocker does.

        Impact

        The seller can release the escrow to themselves without the actual buyer's approval. This defeats the core escrow guarantee (the buyer releases only once satisfied), so the seller can take the full totalAmount before delivering anything.

        Description

        buyerApproved is a single global flag. It is not tied to the address that set it. rejectDepositor() clears buyer and deposited but leaves buyerApproved set. When a new open-offer participant later deposits and becomes buyer, the stale approval already counts as their consent. Separately, the TokenLocker constructor always runs buyer = _buyer, even when _openOffer is true (docs say the parameter is ignored). The deployer/seller can therefore name an address they control as the initial buyer and call readyToExecute() before any real buyer exists.

        Exploit scenario

        TokenLocker: the seller deploys an open offer with _buyer = sellerAlt. sellerAlt calls readyToExecute(), so buyerApproved = true. Victim calls depositTokens(victim, totalAmount) and becomes buyer. The seller calls readyToExecute() then execute(), and totalAmount goes to the seller with no approval from the victim. EthLocker: buyer A deposits and approves, the seller calls rejectDepositor(A), B deposits totalAmount and becomes buyer, then the seller approves and executes. B never approved.

        Recommendation

        Reset buyerApproved (and sellerApproved) whenever buyer or seller changes: in rejectDepositor, updateBuyer/updateSeller, and when a new open-offer buyer is set. In TokenLocker, do not assign buyer = _buyer when _openOffer is true. Consider storing the approving address and checking it equals the current buyer in execute().

        Pashov (Codex GPT-6 Sol high)

        Buyer approval survives buyer replacement or rejection

        src/EthLocker.sol:297 Predicted severity: High

        Root cause

        The buyer identity and buyerApproved flag are updated independently; execute checks the flag but does not prove the current buyer set it.

        Impact

        An escrow can execute and transfer its entire balance to the seller without the current buyer's consent. High severity: the seller can take the entire new buyer payment without that buyer approving execution.

        Description

        The approval booleans are tied only to the locker, not to the addresses that granted them. updateBuyer and rejectDepositor change or clear buyer without clearing buyerApproved, so a later buyer inherits a prior buyer's approval.

        Exploit scenario

        A malicious seller funds their own open offer, calls readyToExecute as both seller and buyer, then rejects their own deposit. rejectDepositor clears buyer but leaves both approvals true. A victim deposits the full amount and becomes the new buyer. The seller calls execute immediately and receives the victim funds without the victim approving.

        Recommendation

        Clear buyerApproved whenever buyer changes or is cleared, and clear sellerApproved whenever seller changes. Optionally store approving addresses and verify that both still match the current parties.

        Devin Security

        Buyer approval survives buyer replacement, and open offers keep a preset buyer, so a seller can release a new buyer's tokens without consent

        src/TokenLocker.sol:340 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A dishonest seller who runs an open-offer TokenLocker can take a real buyer's full token payment as soon as it arrives, without the buyer approving the release.

        ##### What's wrong

        This is a stale authorization flag. buyerApproved is never cleared when buyer changes. The constructor also sets buyer = _buyer even for open offers, though the documentation says this value is ignored. So the person who deploys the locker can pick a buyer address they control, approve from it, and let the approval pass to whoever deposits next.

        ##### Who can do it

        Mallory deploys an open-offer TokenLocker through the public factory. She names herself seller and passes her second wallet as _buyer. Her second wallet calls readyToExecute(). Bob, an honest buyer, deposits the full totalAmount with depositTokens() and becomes buyer. Mallory calls readyToExecute() as seller and then execute(). The same trick works with rejectDepositor(), as in EthLocker.

        - Anyone can deploy through the factory and choose _seller and _buyer.

        - The locker is an open offer.

        - The victim's deposits bring the token balance to totalAmount before expiry.

        ##### What they get

        Mallory receives Bob's whole token payment right away and does not need Bob's consent. Bob cannot recover it. This works against every buyer in every locker Mallory sets up.

        ##### How it works

        1. The constructor sets buyer = _buyer without checking _openOffer at TokenLocker.sol:342.

        2. Mallory's preset buyer wallet calls readyToExecute(), which sets buyerApproved at TokenLocker.sol:476-479.

        3. Bob deposits, and depositTokens() sets buyer = _depositor without resetting approval at TokenLocker.sol:431-435.

        4. Mallory approves as seller, and execute() passes its check at TokenLocker.sol:487-491 and sends totalAmount to her at TokenLocker.sol:524.

        Exploit scenario

        Not specified.

        Recommendation

        Only set buyer in the constructor when !_openOffer. Clear buyerApproved whenever buyer changes: in both deposit functions, in rejectDepositor(), and in updateBuyer(). To check the fix, write a Foundry test where a preset or rejected buyer approves, then a new buyer deposits the full amount. execute() must revert until the new buyer calls readyToExecute().

        Devin Security (Deep)

        Rejected buyer's approval survives rejectDepositor(), letting the seller release the next buyer's ETH without consent

        src/EthLocker.sol:386 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who sets up an open-offer ETH escrow as the seller can take the next buyer's full payment the moment it lands, without that buyer ever agreeing to release it.

        ##### What's wrong

        This is a stale authorization flag: a consent check that is set once and never reset when the party it belongs to changes. readyToExecute() sets buyerApproved for whoever is the current buyer, and rejectDepositor() removes that buyer but leaves buyerApproved set, so the approval carries over to the next buyer who never gave it.

        ##### Who can do it

        Mallory deploys an open-offer EthLocker as the seller and advertises goods for 10 ETH. From a second wallet she controls, she sends the deposit, calls readyToExecute(), and then as seller calls rejectDepositor() on that wallet to get the ETH back. The escrow now has no buyer but still records the buyer as approved. Alice, a shopper, sees the open offer and sends 10 ETH to accept it. Mallory calls readyToExecute() as seller and then execute().

        - The escrow was deployed with openOffer == true (needed for rejectDepositor()).

        - An earlier buyer (any wallet, including one the seller controls) called readyToExecute() and was then rejected by the seller.

        - The escrow has not expired and any value condition is met.

        - The victim's deposit brings the balance to totalAmount.

        ##### What they get

        Mallory receives Alice's entire totalAmount immediately, with no delivery and no approval from Alice. Alice has no way to reclaim the funds; there is no withdraw function and the expiry refund no longer applies because the balance is gone. Mallory can repeat this on every open-offer escrow she sets up. She can only reach buyers who accept her own offers.

        ##### How it works

        1. Mallory's second wallet sends deposit wei; receive() (EthLocker.sol:269-276) makes it the buyer.

        2. That wallet calls readyToExecute() (EthLocker.sol:315-318), setting buyerApproved = true.

        3. Mallory, as seller, calls rejectDepositor(secondWallet) (EthLocker.sol:390-399); deposited and buyer are cleared and the wallet is refunded, but buyerApproved is untouched.

        4. Alice sends ETH; receive() makes her the buyer and the balance reaches totalAmount.

        5. Mallory calls readyToExecute() to set sellerApproved, then execute() (EthLocker.sol:325-361) passes the approval check and sends totalAmount to the seller.

        Exploit scenario

        Not specified.

        Recommendation

        Reset buyerApproved whenever the buyer changes: in rejectDepositor() when _depositor == buyer, in updateBuyer(), and when receive() assigns a new buyer in an open offer. For symmetry, reset sellerApproved in updateSeller(). Verify with a Foundry test: deposit from wallet A, call readyToExecute() from A, reject A as seller, deposit from wallet B, call readyToExecute() as seller, and assert that execute() reverts with EthLocker_NotReadyToExecute and that B's balance is still in the contract.

        Claude Security (Sonnet 5.5)

        rejectDepositor removes the open-offer buyer but leaves buyerApproved set, so a stale approval carries over to the next buyer

        src/TokenLocker.sol:555 Predicted severity: High

        Root cause

        Vulnerable symbol: rejectDepositor

        Preconditions: openOffer == true; victim deposits the full totalAmount while buyerApproved() is already true

        Offending code:

        delete buyer;

        Impact

        Loss of the new buyer's entire deposit to the seller without the buyer's approval. This defeats the escrow's dual-consent guarantee.

        Description

        The seller can reject the current buyer, which clears deposited and buyer, but buyerApproved is not cleared. The next depositor becomes buyer at line 432 or 396 and inherits the previous buyer's approval, so execute() no longer requires the new buyer's own readyToExecute(). Also CWE-841: rejectDepositor() and the open-offer buyer assignment in depositTokens()/depositTokensWithPermit() never reset buyerApproved. execute() (487-491, 524) checks only the stale flag and the global token balance, then transfers totalAmount to the seller.

        Exploit scenario

        Seller-controlled address S' deposits the (possibly zero or tiny) deposit, becomes buyer and calls readyToExecute(). The seller calls rejectDepositor(S'), which refunds S', deletes buyer and resets deposited, but buyerApproved remains true. The seller also calls readyToExecute(). The offer looks fresh and open. A victim deposits totalAmount and becomes buyer, and anyone calls execute(), which pays the seller. The same happens unintentionally if an honest buyer approved before being rejected.

        Recommendation

        Delete buyerApproved in rejectDepositor when the buyer is deleted, and in every place where buyer is reassigned (open-offer takeover, updateBuyer). Consider resetting sellerApproved on updateSeller. Also CWE-841: Clear buyerApproved when buyer changes (rejectDepositor, open-offer assignment, updateBuyer) and sellerApproved when seller changes. Gate execute() on the current buyer's own deposit rather than the global balance.

        Claude Security (Opus 5.5)

        Open-offer TokenLocker keeps the deployer-chosen _buyer and its readyToExecute approval, so funds are released to the seller without the real buyer's approval

        src/TokenLocker.sol:342 Predicted severity: High

        Root cause

        Vulnerable symbol: constructor

        Preconditions: The attacker deploys, or is the seller of, an open-offer TokenLocker created through the factory with a non-zero _buyer they control; A victim accepts the open offer by depositing tokens until the balance reaches totalAmount

        Offending code:

        buyer = _buyer;

        Impact

        The escrow's main authorization rule, that the buyer must approve before totalAmount goes to the seller, is bypassed. The seller can take a buyer's full escrowed deposit the moment it is funded, with no delivery or approval. The buyer loses the escrow protection and therefore the funds.

        Description

        ChainLockerFactory.deployChainLocker forwards the caller's _buyer to new TokenLocker(...) at ChainLockerFactory.sol:213 even when _openOffer is true. Its own NatSpec at line 130 says the value is ignored in that case. The TokenLocker constructor stores it unconditionally. That placeholder buyer can call readyToExecute() and set buyerApproved = true. When a real depositor later takes over the buyer role (depositTokens/depositTokensWithPermit lines 395-397), buyerApproved is never cleared, so execute() accepts an approval the actual buyer never gave. Also CWE-266: The constructor docs and the factory docs both say _buyer is 'Ignored if openOffer', and EthLocker follows that (if (!_openOffer) buyer = _buyer;). TokenLocker instead sets buyer = _buyer unconditionally. An address chosen by the deployer therefore holds buyer privileges in an open offer before anyone has accepted it.

        Exploit scenario

        1) The attacker calls ChainLockerFactory.deployChainLocker with _openOffer = true, _seller = attacker, _buyer = attacker (or an address the attacker controls), and an ERC20 _tokenContract. 2) The attacker calls readyToExecute() on the new TokenLocker. Because msg.sender is both seller and buyer, sellerApproved and buyerApproved are both set to true. 3) A real buyer V accepts the open offer by calling depositTokens(V, totalAmount), or deposits in several steps. V becomes buyer, but buyerApproved stays true. 4) Once the balance reaches totalAmount, the attacker calls execute() in the same or the next block. All checks pass and the full totalAmount goes to the attacker-seller, although V never called readyToExecute. V has no function to revoke the stale approval. The same stale-approval flaw appears without the factory parameter in both lockers through rejectDepositor (EthLocker.sol:390-393, TokenLocker.sol:553-556): the seller deposits deposit from an alt address, calls readyToExecute as buyer, rejects that alt address to get the funds back, and buyerApproved stays true for the next real buyer.

        Recommendation

        In ChainLockerFactory.deployChainLocker, pass address(0) for _buyer when _openOffer is true, and in the TokenLocker constructor set buyer only when !_openOffer, as EthLocker does. More generally, clear buyerApproved wherever the buyer identity changes: open-offer buyer assignment in the deposit functions and receive(), rejectDepositor, and updateBuyer, in both EthLocker and TokenLocker. Alternatively, record the approving address and check it against the current buyer in execute(). Also CWE-266: Match EthLocker: assign buyer only when !_openOffer, so an open offer starts with buyer == address(0).

        Vercel Security Review

        Rejected buyers leave execution approval active for their replacements

        src/EthLocker.sol:390 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. A seller's cooperating buyer primes the execution approval** - src/EthLocker.sol:315-318

        ```solidity title="src/EthLocker.sol:315-318"

        if (msg.sender == buyer) {

        buyerApproved = true;

        emit EthLocker_BuyerReady();

        }

        ```

        **2. Rejecting that buyer reopens the offer without revoking approval** - src/EthLocker.sol:390-393

        ```solidity title="src/EthLocker.sol:390-393"

        if (_depositor == buyer) {

        delete deposited;

        delete buyer;

        emit EthLocker_BuyerUpdated(address(0));

        ```

        The seller refunds this buyer, then a replacement's deposit assigns the new buyer at lines 269-275. Neither transition clears buyerApproved. TokenLocker repeats this at src/TokenLocker.sol:553-562,429-435.

        **3. The seller executes against the replacement's funds without their consent** - src/EthLocker.sol:326-329

        ```solidity title="src/EthLocker.sol:326-329"

        if (

        !sellerApproved ||

        !buyerApproved ||

        address(this).balance < totalAmount

        ```

        Once the replacement fully funds escrow, seller approval satisfies this gate and releases funds at line 361 using the old buyer's approval. The equivalent token gate/payment is src/TokenLocker.sol:487-491,524.

        Exploit scenario

        Not specified.

        Recommendation

        Invalidate execution approvals whenever an offer is reopened or its buyer changes, including rejectDepositor and automatic open-offer buyer assignment. Bind approval to the current buyer and offer generation so an earlier participant's approval cannot authorize spending a replacement's funds. Apply the fix to both locker contracts.

      • Griefing in checkIfExpired chainlocker-6 · 7 writeups Medium

        V12

        Rejecting recipients permanently block expiry refunds

        src/EthLocker.sol:38 Predicted severity: Critical

        Root cause

        Expiry finalization and recipient updates depend on successful push payments to untrusted recipients. There is no independent withdrawal credit or post-expiry recipient-repair path.

        Impact

        A seller using an ETH-rejecting contract can permanently freeze the buyer's remaining escrow funds after expiry in an identified offer. A refundable identified offer is similarly frozen if its buyer cannot accept ETH; there is no alternate recipient or withdrawal path in this file.

        Description

        checkIfExpired() performs expiry settlement through synchronous ETH calls that revert on recipient failure. In a non-refundable, identified-buyer locker with deposited == true and a positive deposit, a seller contract that rejects ETH causes settlement to revert before the buyer receives the remainder. The revert also rolls back isExpired and the accounting deletions, so every retry encounters the same payout. After the deadline, both party-address setters call this failing settlement before they can change a recipient. rejectDepositor() cannot recover the funds in this configuration because it requires an open offer.

        Codex Security (GPT-6 Sol)

        Seller can block buyer's ETH refund with a reverting payout address

        src/EthLocker.sol:286 Predicted severity: Medium

        Root cause

        updateSeller accepts an arbitrary payable receiver before expiry. checkIfExpired performs a push payment to seller before refunding buyer, and the transfer helper reverts on receiver failure. Because address updates call checkIfExpired, the seller cannot simply change the address after expiry to unblock settlement.

        Impact

        A malicious seller must use a nonrefundable locker with a positive buyer remainder and a rejecting contract, but can otherwise indefinitely block the buyer refund.

        Description

        A seller may set its address to a contract that rejects ETH. On nonrefundable expiry, the seller transfer reverts before the buyer's remainder is paid, and post-expiry address changes enter the same failing path.

        Exploit scenario

        Seller selects rejecting receiver; buyer funds nonrefundable escrow; expiry attempts seller payment before buyer remainder and reverts.

        Recommendation

        Accrue seller and buyer claimable balances independently at expiry and let each withdraw to a chosen address.

        Pashov (Claude Opus 5.5 high)

        Push-based settlement in checkIfExpired lets a reverting or blacklisted party freeze all funds

        src/EthLocker.sol:420 Predicted severity: Low

        Root cause

        Several outbound transfers are bundled into one all-or-nothing call, with no pull/claim fallback.

        Impact

        Either party can grief the other, or be accidentally frozen, so the non-refundable deposit or the refund cannot be paid out. Funds stay locked permanently.

        Description

        After expiry, checkIfExpired() pushes funds to seller and then buyer in one transaction. If either transfer reverts, the whole call reverts. Causes include an ETH-rejecting contract, a USDC/USDT blacklisted address, a zero-address seller set via updateSeller on revert-on-zero tokens, or a remainder recipient that reverts. updateSeller/updateBuyer call checkIfExpired() first, so after expiry the parties cannot even switch to a working address.

        Exploit scenario

        Non-refundable EthLocker. The buyer is a contract that reverts on receiving ETH and leaves a remainder > 0. At expiry safeTransferETH(buyer, _remainder) reverts, so the seller never receives the non-refundable deposit either.

        Recommendation

        Use pull payments: record the amounts owed to seller and buyer and let each claim them separately. Allow address updates after expiry, before claiming.

        Pashov (Codex GPT-6 Sol high)

        A rejecting ETH recipient can block all expiry payouts

        src/EthLocker.sol:286 Predicted severity: Medium

        Root cause

        The refund and seller payment are coupled as mandatory external calls, and updateSeller/updateBuyer invoke checkIfExpired before changing the recipient.

        Impact

        A malicious seller can permanently freeze the buyers refund by choosing a reverting seller recipient; a rejecting buyer can likewise freeze the sellers nonrefundable payment. Medium severity: one counterparty can block the other counterparty’s payout indefinitely through a rejecting recipient.

        Description

        Expiry settlement pushes ETH to seller and buyer in one transaction. If either recipient rejects ETH, the whole settlement reverts; after expiry, the recipient update functions first call the same failing settlement, so the address cannot be repaired through the locker.

        Exploit scenario

        In a nonrefundable 10 ETH escrow with a 1 ETH deposit, the buyer funds all 10 ETH. Before expiry, the seller updates seller to a contract whose receive function reverts. After expiry, checkIfExpired reverts on the first 1 ETH payment. updateSeller also reverts because it calls checkIfExpired before replacing the address.

        Recommendation

        Use pull payments with independently claimable credits for each recipient, or permit an authorized recipient update after expiry without first executing the failing payout.

        Devin Security (Deep)

        Non-refundable expiry pays the seller by push first, so a seller address that rejects ETH locks the buyer's remaining funds forever

        src/EthLocker.sol:420 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A seller in a non-refundable ETH escrow can make the buyer's leftover funds unrecoverable forever by pointing the seller address at a contract that rejects ETH, and this costs the seller nothing when the deposit is zero.

        ##### What's wrong

        This is a push-payment denial of service: one failing transfer blocks everyone else's payout. checkIfExpired() sends deposit to seller with a reverting transfer before it pays the buyer, and updateSeller() lets the seller switch to any address with no check.

        ##### Who can do it

        Mallory (seller) and Alice (buyer) agree to a non-refundable escrow with a 0 ETH deposit and a 50 ETH total. Alice sends 50 ETH. Mallory never delivers. Shortly before expiry Mallory calls updateSeller() with the address of a contract that has no payable fallback (or she deployed with such a seller address from the start).

        - refundable == false.

        - deposited == true, which happens on the first receive() call when deposit == 0, or after a normal deposit otherwise.

        - The seller address rejects ETH at expiry time.

        - The escrow did not execute before expiry.

        ##### What they get

        Alice's 50 ETH stay in the contract forever. After expiry every call to checkIfExpired(), updateSeller(), updateBuyer(), and execute() reverts, and receive() rejects new deposits, so no code path can move the ETH. Mallory loses only deposit, which is zero in this setup. Before expiry she can use the threat to extort Alice, since only Mallory can switch the seller address back. The damage is limited to the funds in that one escrow. A buyer can do the mirror image to block the seller's deposit by making the buyer address reject ETH, at the cost of their own remainder.

        ##### How it works

        1. Alice sends 50 ETH; receive() (EthLocker.sol:269-275) sets deposited = true because the balance is at least deposit.

        2. Mallory calls updateSeller(revertingContract) (EthLocker.sol:286-293) before expiry; the new address is not validated.

        3. After expiry, checkIfExpired() (EthLocker.sol:422-424) enters the non-refundable branch and calls safeTransferETH(seller, deposit).

        4. The call to the reverting contract fails and safeTransferETH (EthLocker.sol:38-49) reverts the whole transaction, so the buyer transfer on line 425 never runs.

        5. Every function that settles expiry goes through checkIfExpired() and now reverts, so the ETH is stuck permanently.

        Exploit scenario

        Not specified.

        Recommendation

        Move to pull payments for expiry: in checkIfExpired(), record the amounts owed to seller and buyer in a mapping and add a withdraw() that each party calls. At minimum, do not let a failed seller transfer block the buyer; for example, record the seller's share as claimable on failure instead of reverting. Also reject address(0) in the constructor, updateSeller(), and updateBuyer(). Test: set the seller to a contract with no receive(), fund as buyer, warp past expiry, and assert the buyer can still recover their remainder.

        Claude Security (Sonnet 5.5)

        Expiry settlement pushes funds to both seller and buyer in one transaction; a reverting or blacklisted recipient permanently freezes the escrow

        src/TokenLocker.sol:587 Predicted severity: Low

        Root cause

        Vulnerable symbol: checkIfExpired

        Preconditions: refundable == false; A reverting, blacklisted or otherwise failing seller or buyer address

        Offending code:

        safeTransfer(tokenContract, seller, deposit);

        Impact

        Permanent loss of availability of escrowed funds for the counterparty. This is a hostage or griefing vector, not direct theft.

        Description

        In the non-refundable branch the seller payout and the buyer refund share one transaction (EthLocker 424-425 has the same shape). seller and buyer are party-controlled via updateSeller()/updateBuyer(), and a token's blacklist can also make either transfer revert. A single failing transfer reverts checkIfExpired(). That function gates execute(), updateSeller() and updateBuyer(), so nothing can run after expiry.

        Exploit scenario

        In a non-refundable locker, the seller calls updateSeller() to a contract that reverts on receive, or a blacklisted address. The buyer has funded the escrow. At expiry every checkIfExpired() call reverts, so the buyer's refundable remainder is stuck. The seller can restore a working address before expiry, which enables extortion. A buyer who moves to a reverting address symmetrically blocks the seller's deposit payout. With USDC-style blacklisting, a sanctioned counterparty freezes the escrow without any malicious action.

        Recommendation

        Use pull payments: record seller and buyer entitlements at expiry and let each party withdraw separately, so one failing recipient cannot block the other.

        Vercel Security Review

        A reverting seller can block the buyer's expiry refund

        src/EthLocker.sol:422 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. The seller can switch its recipient to a contract that rejects ETH** - src/EthLocker.sol:289-292

        ```solidity title="src/EthLocker.sol:289-292"

        if (!checkIfExpired()) {

        seller = _seller;

        emit EthLocker_SellerUpdated(_seller);

        }

        ```

        This can occur after the buyer funds the new escrow but before expiry.

        **2. Expiry requires paying the seller before refunding the buyer** - src/EthLocker.sol:422-425

        ```solidity title="src/EthLocker.sol:422-425"

        if (!refundable && _isDeposited) {

        uint256 _remainder = address(this).balance - deposit;

        safeTransferETH(seller, deposit);

        if (_remainder > 0) safeTransferETH(buyer, _remainder);

        ```

        For a nonrefundable deposit smaller than the funded balance, the malicious seller blocks the buyer's otherwise refundable surplus.

        **3. Rejected payment reverts the entire settlement** - src/EthLocker.sol:43-46

        ```solidity title="src/EthLocker.sol:43-46"

        // Store the function selector of ETHTransferFailed().

        mstore(0x00, 0xb12d13eb)

        // Revert with (offset, size).

        revert(0x1c, 0x04)

        ```

        The failed call at line 42 triggers this revert. There is no independent buyer withdrawal; changing recipients after expiry also attempts settlement first. The seller can indefinitely lock the buyer's surplus.

        Exploit scenario

        Not specified.

        Recommendation

        Record independent claimable balances for the seller's deposit and buyer's surplus at expiry, then let each party withdraw separately. A failed payment to either recipient must not revert or prevent the other party's withdrawal. Permit claim owners to redirect their own withdrawals without first requiring settlement payments to succeed.

    • Chateau Solidity Yield-bearing real-asset vault. Tasks 4 V12 4/4 Codex Sec 2/4 Pashov Opus 3/4 Pashov GPT-6 2/4 Devin 2/4 Devin (Deep) 3/4 Claude Sec 2/4 Claude Opus 1/4 Vercel 2/4

      Yield-bearing real-asset vault.

      Read the audit report
      • Potential DOS during swap chateau-1 · 8 writeups Critical

        V12

        Permanent histories can exhaust settlement gas

        contracts/StakingPool.sol:49 Predicted severity: High

        Root cause

        Inactive issue records and per-user indexes remain in grow-only histories that mandatory settlement paths scan without pagination or early termination. Work is tied to lifetime activity rather than the live claims being processed.

        Impact

        Accumulated inactive records can make every swap exceed the execution gas limit even when only a small live deposit needs settlement. A heavily used account can also lose its usable direct withdrawal path because unstake must process its entire history; owner withdrawal bounds the global scan only by withdrawing all issue tokens and invalidating the old eligibility range.

        Description

        Every successful positive stake appends a global issue and a permanent entry in the caller's history. Unstaking clears only the active flag, while both user withdrawal and the position getter continue copying and scanning the full lifetime history. The swap loop additionally scans every global index above indexStar, including inactive entries, and does not stop when the requested allocation is complete. An admitted caller can repeatedly stake a minimal amount and unstake it, or spread such cycles over multiple accounts, leaving a long inactive global range while recovering the deposited principal. No user-controlled pruning or bounded settlement interface exists.

        Codex Security (GPT-6 Sol)

        Accumulated stake history can make every swap run out of gas

        contracts/StakingPool.sol:49 Predicted severity: Medium

        Root cause

        The user-controlled count of stake records grows indexEnd permanently. Unstake only flips a flag, while swap scans the entire index range and does not stop once the amount has been assigned. Gas cost grows with history rather than work needed for the swap.

        Impact

        A public eligible user can disable the global swap function after accumulating enough entries; reversing it requires an owner withdrawal that clears claims.

        Description

        Every swap scans all historical stake slots, including inactive slots and entries after the requested amount is allocated. An eligible staker can grow that history until swaps exceed transaction gas limits.

        Exploit scenario

        repeated stake -> indexEnd growth -> inactive records retained -> swap global loop -> out-of-gas revert

        Recommendation

        Track active positions and settle in bounded batches; stop processing once the requested amount is allocated.

        Pashov (Claude Opus 5.5 high)

        Unbounded iteration over the whole stake history in swap() allows permanent DoS of swaps

        contracts/StakingPool.sol:128 Predicted severity: Medium

        Root cause

        The loop has no upper bound and no early exit, over an array that anyone can grow cheaply.

        Impact

        An attacker who passes the KYC check once can stake 1 wei thousands of times, or stake and unstake repeatedly, until swap() exceeds the block gas limit. Shareholders then cannot sell shares for staked USDT until the owner calls withdraw(), which seizes all stakes. Even without an attacker, normal use slowly makes swap more expensive and eventually unusable.

        Description

        swap() loops from indexEnd down to indexStar over every Issue ever created since the last withdraw, including ones already unstaked or fully consumed. It keeps looping after amountB reaches 0, so every call costs a cold SLOAD for each historical entry. Entries are never removed, and stake() accepts any amount above 0, including 1 wei.

        Exploit scenario

        On Arbitrum, where gas is cheap, the attacker calls stake(1) about 15,000 times (each costs around 100k gas). Every later swap() then needs more than 15,000 × ~2,100 gas just for SLOADs, which exceeds the block gas limit. All swaps revert.

        Recommendation

        Break out of the loop once amountB == 0. Keep a FIFO/LIFO queue pointer that moves past consumed or unstaked entries. Enforce a minimum stake size, or allow at most one active position per user.

        Pashov (Codex GPT-6 Sol high)

        Historical stake scans can exhaust gas for swaps and unstaking

        contracts/StakingPool.sol:128 Predicted severity: Medium

        Root cause

        The loop has no bounded batch size, cursor, or early exit when amountB reaches zero.

        Impact

        An attacker can block swaps for all users by extending global history; a staker with a long personal history can also lose access to an active stake because unstake exceeds the block gas limit.

        Description

        Swap traverses every global historical stake index, including inactive records and records after the requested amount is filled. Unstake copies and traverses a caller’s entire stake history. Both histories grow without bound.

        Exploit scenario

        An attacker repeatedly stakes the minimum permitted issue-token unit and optionally unstakes; all records remain in the scanned index range. Later swaps must scan every historical index and eventually become unexecutable.

        Recommendation

        Use bounded settlement batches with a persistent cursor and an indexed unstake path. Stop swap allocation once the requested amount is filled.

        Devin Security

        swap() loops over every stake ever made and can run out of gas

        contracts/StakingPool.sol:128 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A user who passes the KYC check can make swap() too expensive to call by creating many tiny stakes, which blocks liquidations until the owner resets the window.

        ##### What's wrong

        This is an unbounded loop. swap() walks every index from indexEnd down to indexStar. It does not stop once amountB reaches zero, and it also visits stakes that were already unstaked. Since stake() takes any amount above zero, the loop length grows with every stake.

        ##### Who can do it

        Mallory passes the non-US check and calls stake(1) followed by unstake() thousands of times. Bob, a share holder, then calls swap(), and his call runs out of gas.

        - Mallory passes the Quadrata non-US check.

        - Mallory pays gas for many small stakes.

        ##### What they get

        No one can call swap() until the owner calls withdraw(), which moves indexStar forward. No funds are stolen. The only harm is lost availability.

        ##### How it works

        1. stake() at StakingPool.sol:49-58 accepts any amount above zero and increases indexEnd each time.

        2. The swap() loop at StakingPool.sol:128 visits every index in the window and never breaks early.

        3. Once there are enough entries, swap() uses more than the block gas limit and reverts.

        Exploit scenario

        Not specified.

        Recommendation

        Break out of the loop once amountB == 0. Set a minimum stake amount, or keep a list of only active stakes so the loop skips stakes that were already unstaked. To check the fix, write a test that creates many dust stakes and confirms that a small swap() uses roughly constant gas.

        Devin Security (Deep)

        swap() iterates every stake index since the last withdraw, so cheap dust stakes can make swaps impossible

        contracts/StakingPool.sol:128 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A verified user can spend a few dollars of gas on roughly a thousand 1-wei stakes and make every swap() run out of gas until the fund manager calls withdraw().

        ##### What's wrong

        This is an unbounded loop over attacker-controlled state. swap() walks every index from indexEnd down to indexStar, including entries that are already unstaked, and never breaks early even once the requested amount is fully matched.

        ##### Who can do it

        Mallory, a non-US user with a Quadrata passport, calls stake(1) about a thousand times. Because matching is newest-first, every later swap() by Alice, a Share holder at Acme Capital, must first process all of Mallory's entries, each of which costs a Share transfer, and the transaction exceeds the block gas limit. Even after Mallory unstakes, the dead entries still cost a storage read on every swap.

        Conditions:

        - The attacker passes the NOT_AMERICAN check to call stake().

        - The attacker funds roughly a thousand tiny stakes (the exact count depends on the chain's gas limit).

        - The owner has not yet called withdraw() to reset indexStar.

        ##### What they get

        Share holders lose the ability to exit through swap() until the manager resets the pool with withdraw(), and the attacker can repeat the attack after each reset. No funds are lost or taken. The same shape exists in unstake(), which loops over the caller's own never-pruned index list, but that only affects the caller.

        ##### How it works

        1. stake() appends an entry at indexEnd with no minimum amount beyond > 0 (StakingPool.sol:50-54).

        2. swap() loops from indexEnd down to indexStar + 1 with no break once amountB reaches zero (StakingPool.sol:128-145).

        3. Each live entry triggers a Share transfer (StakingPool.sol:135, 139) and each dead entry still costs a storage read (StakingPool.sol:129-130).

        4. Only withdraw() moves indexStar forward (StakingPool.sol:154).

        Exploit scenario

        Not specified.

        Recommendation

        Add break once amountB == 0, keep a cursor to the newest live stake, skip or compact unstaked entries, and require a minimum stake amount. Check: a test that creates a few thousand 1-wei stakes and then calls swap() should still succeed within the block gas limit.

        Claude Security (Sonnet 5.5)

        swap() iterates over every issue since the last withdraw() with no early exit, so spam stakes can make swap() run out of gas

        contracts/StakingPool.sol:128 Predicted severity: Low

        Root cause

        Vulnerable symbol: swap

        Offending code:

        for (uint i = indexEnd; i > indexStar; i--) {

        Impact

        Each iteration costs at least one cold SLOAD (about 2.1k gas), and the cost grows with the total number of stakes since the last owner withdraw(). Once the range exceeds roughly the block gas limit divided by that per-entry cost, swap() always reverts. Stakers can no longer be converted to shares and share holders cannot sell into the pool. Only the owner's withdraw() resets indexStar, and it does so by sweeping all staked funds. The same degradation happens organically as history accumulates.

        Description

        Any KYC-passing account can append unbounded entries to the global issues range through stake(), which has no minimum amount. swap() walks the whole range from indexEnd down to indexStar, including already-filled entries, and keeps looping after amountB reaches 0.

        Exploit scenario

        An attacker with a passing Quadrata country attribute calls stake(1) repeatedly from the cheap L2 deployments the contract targets (Optimism, Arbitrum). They can call unstake() afterwards to reclaim the dust. The filled or unstaked entries remain in the range and are still read by swap(). After a few thousand to tens of thousands of entries, every swap() call runs out of gas.

        Recommendation

        Break out of the loop as soon as amountB == 0. Enforce a minimum stake amount. Use a bounded or linked-list structure, or a batch parameter for the swap loop (for example, a maxIterations argument with a persisted cursor), instead of a full scan from the newest entry to indexStar.

        Vercel Security Review

        Tiny stake spam can exhaust gas for every swap

        contracts/StakingPool.sol:128 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. The new staking flow lets any country-approved depositor grow a pool-wide history with repeated tiny stakes.** - contracts/StakingPool.sol:51-54

        ```solidity title="contracts/StakingPool.sol:51-54"

        issueToken.safeTransferFrom(msg.sender, address(this), amount);

        issues[indexEnd] = Issue(msg.sender, amount, block.timestamp, true);

        userIssueIndex[msg.sender].push(indexEnd);

        indexEnd++;

        ```

        **2. Cancelling stakes only marks their records inactive; their indices remain in that history.** - contracts/StakingPool.sol:67-70

        ```solidity title="contracts/StakingPool.sol:67-70"

        Issue storage issueInfo = issues[index];

        if (issueInfo.isStaking) {

        unstakeAmount += issueInfo.issueAmount;

        issueInfo.isStaking = false;

        ```

        **3. Every swap traverses the entire interval, including inactive records, even after satisfying its amount. Enough spam therefore makes other holders' swaps exceed transaction gas limits until the owner withdraws and resets the interval.** - contracts/StakingPool.sol:128-131

        ```solidity title="contracts/StakingPool.sol:128-131"

        for (uint i = indexEnd; i > indexStar; i--) {

        Issue storage issueInfo = issues[i];

        if (issueInfo.isStaking) {

        if (amountB > 0) {

        ```

        Exploit scenario

        Not specified.

        Recommendation

        Maintain an efficiently removable active-order queue instead of traversing all historical indices. Bound work per swap, support partial fills or pagination, and stop once the requested amount is satisfied. Cancelled and settled records must not remain mandatory traversal work.

      • Transparent pool ordering allows for preferential swaps chateau-2 · 1 writeup Critical

        V12

        Newest-first insertion captures redemption spreads

        contracts/StakingPool.sol:49 Predicted severity: Informational

        Root cause

        Immediate stake activation combined with descending-index allocation permits transaction-order priority capture. swap does not bind that allocation to stake age or the independent redemption value used by the vault.

        Impact

        Newest-first insertion lets a transient depositor capture a favorable redemption spread instead of an earlier depositor whenever the vault payout exceeds the issue-token claim consumed by the swap. Security relevance remains unresolved: the missing fact is the intended relationship between configured rate, vault redemption value and any protected allocation priority; the searched boundary comprises all project Solidity sources, the requested tests, deployment script, configuration and README, which supply no such economic constraint.

        Description

        Every admitted stake immediately appends an active issue, and swap allocates incoming shares to active issues in descending index order without an age or commitment requirement. An observer can therefore place a stake immediately before a pending swap and receive the shares ahead of previously active depositors. Those received shares can be passed to VaultPool.reedem, whose payout depends on the vault's live backing and share supply rather than the staking rate. As a conditional arithmetic example, with rate 10000, 20000 outstanding shares and 40004 backing units, a front-running 10000-unit stake can receive 10000 shares from a pending swap and redeem them for 20000 units, yielding 10000 units above the consumed stake before transaction costs. This establishes a redemption-spread capture path, but the source does not establish whether this is intended arbitrage or violates an economic protection promised to existing depositors or vault holders.

      • Withdraw leads to loss of stake chateau-3 · 9 writeups Critical

        V12

        Withdrawal boundary excludes the next deposit

        contracts/StakingPool.sol:34 Predicted severity: High

        Root cause

        withdraw stores the next unused index as an exclusive lower bound, while stake immediately reuses that index for a valid new claim. The swap payout additionally trusts pendingLiquidation without requiring the allocation loop to consume the full converted amount.

        Impact

        A user making the first deposit after an owner withdrawal loses access to that deposit through all user settlement paths, although the owner can recover and return the issue tokens separately. The excluded deposit also inflates the aggregate used to authorize swaps, allowing a share holder to receive issue tokens for an amount the allocation loop cannot fully match to eligible issues.

        Description

        indexEnd denotes the next unused issue index, but owner withdrawal saves that value directly into indexStar. The next successful stake writes an active issue at exactly that saved boundary and adds its amount to pendingLiquidation. Both unstake and getStakingInfo require an index strictly greater than indexStar, and the swap scan uses the same exclusive boundary. Consequently the first deposit after every owner withdrawal is recorded and funded but is never eligible for withdrawal or allocation. Owner withdrawal can create this condition even in an initially empty pool.

        Codex Security (GPT-6 Sol)

        A share swap can take the first post-withdraw stake without paying its owner

        contracts/StakingPool.sol:154 Predicted severity: High

        Root cause

        The owner stores the next unused index in indexStar. The next stake writes at that exact index and increments pendingLiquidation, but unstake and swap use strict greater-than comparisons. The record is invisible to both claim paths while swap can spend the aggregate backing.

        Impact

        The full affected deposit can be taken by a public Share holder after a normal owner withdrawal, with no recovery path for that stake.

        Description

        After an owner withdrawal, the first new stake is accepted and counted as liquidity but excluded from unstaking and share distribution. A Share holder can swap against its backing and receive the issue tokens while the staker receives no Shares.

        Exploit scenario

        owner withdraw -> indexStar=indexEnd -> first new stake at indexStar -> pendingLiquidation grows -> swap omits record -> issue-token payout

        Recommendation

        Set the boundary to the last used index or consistently include the next new stake in all claim and settlement paths.

        Pashov (Claude Opus 5.5 high)

        Off-by-one after owner withdraw: first stake after withdraw is frozen and its funds can be taken by swappers without compensation

        contracts/StakingPool.sol:151 Predicted severity: High

        Root cause

        withdraw() should mark every index up to indexEnd-1 as settled. It sets indexStar = indexEnd instead. Combined with the strict index > indexStar checks, this skips the next slot to be allocated.

        Impact

        After every owner withdraw, the first staker cannot unstake. The stake never appears in getStakingInfo. Because the amount still counts in pendingLiquidation, a swapper can take that USDT through swap() while the loop gives the staker no share tokens. The undistributed share tokens stay stuck in the pool. The staker loses all of the deposit.

        Description

        indexEnd always points to the next free slot. withdraw() sets indexStar = indexEnd. The next stake() is written to issues[indexEnd], which now equals indexStar. unstake(), getStakingInfo() and swap() only look at indices strictly greater than indexStar, so this stake can never be seen. Its amount is still added to pendingLiquidation.

        Exploit scenario

        1) Users stake at indices 1..3 and the owner calls withdraw(), so indexStar = 4. 2) Alice stakes 1000 USDT. It goes to issues[4], indexEnd = 5, pendingLiquidation = 1000. 3) Alice calls unstake(): 4 > 4 is false, so she gets nothing. 4) Bob, a shareholder, calls swap() for 1000 USDT worth of shares. The check pendingLiquidation >= amountB passes. The loop only visits i = 5 (empty), so no shares reach Alice. Bob still receives Alice's 1000 USDT, and his shares remain in the contract.

        Recommendation

        In withdraw(), set indexStar = indexEnd - 1. Alternatively, keep inclusive semantics with index >= indexStar consistently and start indexStar at 1. Also have swap() pay out only what the loop actually matched, and revert if amountB is left over.

        Pashov (Codex GPT-6 Sol high)

        First stake after owner withdrawal becomes permanently inaccessible

        contracts/StakingPool.sol:151 Predicted severity: High

        Root cause

        The cutoff stores indexEnd instead of the last used index, creating an off-by-one exclusion on the next stake.

        Impact

        The first post-withdraw staker can lose their full deposited amount: unstake excludes the record, and a share seller can receive the collateral without allocating shares to that staker. The owner can also sweep it.

        Description

        The owner withdrawal advances indexStar to the current next-free index. The next stake is stored at that same index, while unstake and swap process only indices strictly greater than indexStar. That stake is counted as pending liquidation but can never be selected for return or settlement.

        Exploit scenario

        The owner performs a normal withdrawal when indexEnd is 1. Alice then stakes 100 issue units at index 1, so pendingLiquidation is 100. A seller swaps 100 shares at rate 10000; the loop skips index 1 but sends the seller 100 issue units. Alice receives no shares and cannot unstake.

        Recommendation

        Set the cutoff to the last used index (indexEnd - 1), or change the record numbering and comparisons consistently.

        Devin Security

        First stake after an owner withdraw is locked and can be paid out to swappers

        contracts/StakingPool.sol:151 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        After every owner withdraw(), the next user to call stake() permanently loses their deposit: they can never unstake it, and any swapper can take their tokens without the staker getting share tokens back.

        ##### What's wrong

        This is an off-by-one error in the active-stake window. withdraw() sets indexStar = indexEnd. The next stake() stores the new stake at issues[indexEnd], which equals indexStar. But unstake(), getStakingInfo(), and the swap() loop all only look at indexes strictly greater than indexStar. So that one stake falls outside the window. It still counts in pendingLiquidation, though.

        ##### Who can do it

        Alice, a non-US user, stakes 1,000 issue tokens right after the fund manager calls withdraw(). Her stake sits at index indexStar. When she calls unstake(), nothing is returned. Mallory, who holds share tokens, then calls swap(). The pendingLiquidation check passes because it still includes Alice's 1,000 tokens. The swap loop skips Alice's stake, so Alice gets no share tokens, but Mallory still receives the full issue token amount.

        - The owner has called withdraw() at least once (this is the normal liquidation flow).

        - A user stakes after that withdraw, as the first staker.

        - For the theft path, any holder of share tokens calls swap() with an amount that the other active stakes cannot fully cover.

        ##### What they get

        Alice loses her whole stake. She cannot unstake it, and it never shows in getStakingInfo(). A swapper can drain her tokens for share tokens that go to nobody. Otherwise the tokens stay stuck until the next owner withdraw() sweeps them to the owner. This happens to one staker after every withdraw cycle.

        ##### How it works

        1. withdraw() sets indexStar = indexEnd at StakingPool.sol:154.

        2. stake() writes the new stake to issues[indexEnd] (now equal to indexStar) and adds it to pendingLiquidation at StakingPool.sol:52-56.

        3. unstake() skips the stake because of the index > indexStar check at StakingPool.sol:66, so Alice cannot get it back.

        4. swap() passes the pendingLiquidation >= amountB check at StakingPool.sol:121-124, but its loop at StakingPool.sol:128 stops before indexStar, so Alice's stake is never debited and she is never paid.

        5. swap() still sends the full amountBTotal of issue tokens to the swapper at StakingPool.sol:148, and those tokens come from Alice's deposit.

        Exploit scenario

        Not specified.

        Recommendation

        Keep the window boundaries consistent. One option is to set indexStar = indexEnd - 1 in withdraw(). Another is to treat indexStar as inclusive (index >= indexStar) in unstake, getStakingInfo, and the swap loop, and start the swap loop at indexEnd - 1. Also make swap() revert if amountB is still non-zero after the loop. To check the fix, write a test that calls withdraw, then stake, then unstake, and assert the staker gets the full amount back. Then repeat with a swap in place of unstake and assert the staker receives share tokens.

        Devin Security (Deep)

        First stake after owner withdraw() is unreachable: staker can never unstake and swaps take its funds

        contracts/StakingPool.sol:151 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        After the fund manager collects a raise, the next person who stakes loses control of that money: they can never unstake it, and any Share holder who swaps can take it while the staker receives nothing in return.

        ##### What's wrong

        This is an off-by-one error in the stake index bookkeeping. withdraw() sets indexStar equal to indexEnd, but the next stake() writes its entry at issues[indexEnd], which is the same slot as indexStar. Every reader (unstake, swap, getStakingInfo) only looks at entries with index > indexStar, so that entry becomes invisible, while pendingLiquidation still counts its amount.

        ##### Who can do it

        Alice, an investor at Acme Capital, stakes 20,000 USDT into the pool right after the fund manager has called withdraw() to collect the previous raise. Alice's entry is stored at the index that equals indexStar. Mallory, any holder of the fund's Share token, calls swap() for an amount worth 20,000 USDT. The matching loop never visits Alice's entry, but the liquidity check counts her 20,000 USDT, so Mallory receives it. Alice gets no Share tokens, and unstake() returns nothing to her.

        Conditions:

        - The owner has called withdraw() at least once; this is the normal flow for collecting a raise.

        - A user stakes after that call. The first stake after every withdraw() is affected.

        - For the swap path, any address holding Share tokens calls swap(); no KYC gate applies to swap().

        ##### What they get

        Alice's whole stake leaves her control. She cannot unstake it, it does not appear in getStakingInfo, and it never gets matched with Share tokens. If someone swaps, the swapper receives Alice's USDT and the Share tokens they paid are stuck in the pool forever, so nobody can make Alice whole from the pool. If nobody swaps, the manager's next withdraw() sweeps Alice's USDT along with the rest, and because the entry is hidden from getStakingInfo the manager's off-chain accounting can miss her. This repeats for the first staker after every raise cycle. Other stakers are not affected.

        ##### How it works

        1. The constructor sets indexEnd to 1 and leaves indexStar at 0, so the first entry (index 1) is readable (StakingPool.sol:41).

        2. withdraw() sets indexStar = indexEnd but does not advance indexEnd (StakingPool.sol:154).

        3. The next stake() writes issues[indexEnd], which now equals indexStar, and adds the amount to pendingLiquidation (StakingPool.sol:52-56).

        4. unstake() only processes entries where index > indexStar, so the entry is skipped and nothing is returned (StakingPool.sol:66).

        5. swap() checks pendingLiquidation >= amountB, which includes the hidden amount (StakingPool.sol:121-124), then loops from indexEnd down to indexStar + 1 and never visits the entry (StakingPool.sol:128).

        6. Any unmatched amountB is silently dropped and the swapper still receives the full amountBTotal in USDT (StakingPool.sol:147-148).

        7. getStakingInfo() applies the same index > indexStar filter and hides the entry (StakingPool.sol:91, 101).

        Exploit scenario

        Not specified.

        Recommendation

        In withdraw(), advance indexEnd after moving indexStar (indexStar = indexEnd; indexEnd++;) so the next stake lands above indexStar, matching what the constructor does. Alternatively set indexStar = indexEnd - 1 and keep the > comparisons. Also add require(amountB == 0, "unmatched liquidity") after the loop in swap() so a swap can never pay out USDT that was not matched to a live stake. Check: in a test, call withdraw(), then stake() from a user, and confirm getStakingInfo lists the stake, unstake() returns the full amount, and a swap() sends Share tokens to that user.

        Claude Security (Sonnet 5.5)

        Off-by-one in indexStar after owner withdraw() makes the next staker's position permanently unreachable (cannot unstake, never settled by swap)

        contracts/StakingPool.sol:154 Predicted severity: Medium

        Root cause

        Vulnerable symbol: withdraw

        Preconditions: The owner has called withdraw() at least once, so indexStar equals the current indexEnd; A user calls stake() as the next staker after that withdraw()

        Offending code:

        indexStar = indexEnd;

        Impact

        The first depositor after every owner withdraw() loses the ability to unstake and to be settled via swap, so their principal is stranded. The pendingLiquidation accounting also diverges from the amount that is actually reachable. swap() can then pay out issue tokens that back unreachable positions without distributing any shares to a staker. This is a loss or lock of user funds caused by an index boundary error.

        Description

        withdraw() sets indexStar = indexEnd, but indexEnd is the next free slot that the following stake() writes to, while unstake() and swap() only consider indices strictly greater than indexStar (index > indexStar, i > indexStar). The first stake after every withdraw() therefore lands on index == indexStar and is excluded from both loops.

        Exploit scenario

        The owner calls withdraw() when indexEnd == N, so indexStar becomes N. Alice then calls stake(1000): the issue is stored at issues[N], indexEnd becomes N+1, and pendingLiquidation grows by 1000. Alice's unstake() skips N because N > N is false, so she cannot recover her tokens. swap() iterates i from N+1 down to N+1 and never reaches N, so she is never paid redeem shares. Because pendingLiquidation still counts her 1000, a swapper's pendingLiquidation >= amountB check passes. The loop then settles nobody, and swap still transfers amountBTotal issue tokens out of the pool balance (the unchecked tail at lines 147-148), which can consume Alice's deposit. The swapper's shares stay in the pool and are never distributed. Alice's funds stay locked until the owner's next withdraw() sweeps them.

        Recommendation

        Set indexStar = indexEnd - 1 in withdraw(), since the constructor starts with indexEnd = 1 and indexStar = 0 to keep the first valid index strictly greater than indexStar. Alternatively, make the comparisons inclusive (>=) or advance indexEnd before the next stake. Also add a require(amountB == 0) after the settlement loop in swap(), and derive the payout from the amount actually settled so unreachable positions cannot be paid out from pool balance.

        Claude Security (Opus 5.5)

        Off-by-one in the indexStar check permanently denies the first staker after an owner withdraw, and swap() hands that stake's principal to the swapper

        contracts/StakingPool.sol:154 Predicted severity: Medium

        Root cause

        Vulnerable symbol: withdraw

        Preconditions: The owner has called StakingPool.withdraw() at least once, which is a normal admin action; A user stakes as the first depositor after that withdraw

        Offending code:

        indexStar = indexEnd;

        Impact

        The first staker after every owner withdraw loses their whole principal. They cannot unstake it, they get no shares for it, and any third party can take it through swap(). pendingLiquidation also no longer matches the stakes that can actually be filled.

        Description

        withdraw() sets indexStar = indexEnd, but indexEnd is the next free slot. Every later check asks whether a stake is still valid with a strict index > indexStar (unstake line 66, getStakingInfo lines 91/101, swap loop line 128). So the very next stake, at index == indexStar, is treated as invalid: its owner can never unstake it. Its amount is still counted in pendingLiquidation, so an unrestricted swap() caller can draw it out.

        Exploit scenario

        The owner calls withdraw() once, leaving indexStar = indexEnd = N. Victim stakes 10,000 USDT, which is stored at issues[N], with pendingLiquidation = 10,000. Victim's unstake() skips index N because N > N is false, so they get 0 back. Any share holder then calls swap(amount) with amount*rate/10000 <= 10,000. The loop runs i = N+1 (an empty slot) and stops before reaching N, so no staker gets shares. pendingLiquidation passes its check, and the swapper receives the victim's USDT. The swapper's shares stay stuck in the pool and the victim is never paid.

        Recommendation

        Set indexStar = indexEnd - 1 in withdraw(), or change every validity check to index >= indexStar with a matching loop bound. Also make swap() require that the amount actually distributed to stakers equals amountBTotal, and revert otherwise.

        Vercel Security Review

        Withdrawal cutoff excludes the first subsequent deposit

        contracts/StakingPool.sol:154 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. The new withdrawal routine marks indexEnd as already consumed.** - contracts/StakingPool.sol:151-154

        ```solidity title="contracts/StakingPool.sol:151-154"

        function withdraw() public onlyOwner {

        uint balance = issueToken.balanceOf(address(this));

        issueToken.safeTransfer(msg.sender, balance);

        indexStar = indexEnd;

        ```

        **2. However, indexEnd is the next unused index: the next eligible depositor transfers funds and receives exactly that index.** - contracts/StakingPool.sol:51-54

        ```solidity title="contracts/StakingPool.sol:51-54"

        issueToken.safeTransferFrom(msg.sender, address(this), amount);

        issues[indexEnd] = Issue(msg.sender, amount, block.timestamp, true);

        userIssueIndex[msg.sender].push(indexEnd);

        indexEnd++;

        ```

        **3. Unstaking excludes equal indices, making this deposit nonwithdrawable without owner intervention. swap applies the same exclusion at line 128, preventing share allocation too.** - contracts/StakingPool.sol:66-69

        ```solidity title="contracts/StakingPool.sol:66-69"

        if (index > indexStar) {

        Issue storage issueInfo = issues[index];

        if (issueInfo.isStaking) {

        unstakeAmount += issueInfo.issueAmount;

        ```

        Exploit scenario

        Not specified.

        Recommendation

        Keep the consumed cutoff at the last assigned index, e.g. set indexStar to indexEnd - 1, or consistently redesign the interval boundaries across all consumers. Add regression coverage for withdrawing, staking again, and then unstaking or matching that first new deposit.

      • Centralization risks chateau-4 · 3 writeups High

        V12

        Administrative withdrawals extinguish existing depositor claims

        contracts/StakingPool.sol:49 Predicted severity: Low

        Root cause

        The administrative custody transfer also expires all existing staking claims and resets their aggregate without migrating them into a recoverable per-user liability. Active issue records are left behind but excluded from every user settlement path.

        Impact

        A permitted administrative action removes both depositor backing and every direct user settlement route for pre-withdrawal issues. Users depend on the owner returning funds outside the implemented claim system; the code does not preserve a later on-chain entitlement, and no unauthorized caller can invoke this path.

        Description

        Owner withdrawal transfers the entire issue-token balance to the owner, including tokens backing active user issues. It then advances indexStar past those issues and resets pendingLiquidation to zero without creating any replacement claim or payout record for the depositors. Existing issue structs may still say isStaking = true, but user withdrawal and the getter exclude them by index. The test suite explicitly exercises an owner withdrawal immediately after another account's stake, so this is a reachable administrative lifecycle rather than an unused branch. The supplied trust model authorizes owner withdrawals, making this a privileged custodial risk rather than an access-control bypass.

        Pashov (Claude Opus 5.5 high)

        swap() has no slippage protection and is exposed to owner rate changes and front-running of setRate

        contracts/StakingPool.sol:110 Predicted severity: Low

        Root cause

        A mutable admin price is used without a minOut/maxPrice parameter or a delay.

        Impact

        Value moves between stakers and swappers. Stakers are forced to buy shares at a stale price, and swappers can receive fewer tokens than expected.

        Description

        swap() converts shares to USDT at the current owner-set rate. The caller cannot give a minimum output, and stakers cannot cap the price they pay for shares. When a rate cut is pending, shareholders can front-run setRate and dump shares on stakers at the old, higher price. If setRate lands just before a swap, the swapper gets a different amount than expected. The rate can be any value, including extreme ones.

        Exploit scenario

        The vault's NAV drops and the owner submits setRate(5000). A shareholder sees it and calls swap() first at rate 10000. Stakers get shares worth half of the USDT taken from them.

        Recommendation

        Add a minAmountOut / deadline parameter to swap(), use a timelock for rate changes, and consider limits on the rate.

        Devin Security (Deep)

        Owner can sweep the whole redemption pot and mint unlimited Share to drain it, with no timelock

        contracts/VaultPool.sol:43 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Whoever holds the fund manager's key can take every USDT waiting for Share holders in one call, or mint themselves enough Share to redeem almost all of it, so a stolen key means Share holders get nothing.

        ##### What's wrong

        This is a centralization risk with no safeguards. VaultPool.withdraw() transfers the entire issueToken balance to the owner and pauses redemptions, and the same owner controls Share.mint (no supply cap) and Share.burn(from, amount) (any holder's balance, no allowance), so the pro-rata payout in reedem() can be diluted or voided at will.

        ##### Who can do it

        Alice and Bob hold Share tokens of an Acme Capital fund. The manager deposits 1,000,000 USDT into the VaultPool for redemptions. Mallory, who has stolen the manager's key, calls withdraw() and receives the full 1,000,000 USDT, and the vault is paused. Alternatively, Mallory calls Share.mint([mallory], [hugeAmount]) and then reedem(hugeAmount) so her share of the pot approaches 100%.

        Conditions:

        - The attacker controls the owner address (the Factory owner's EOA, set in Factory.newFund).

        - USDT has been deposited into the vault for redemptions.

        ##### What they get

        Every Share holder's redemption value, instantly. Minting and burning also let the attacker dilute or wipe out specific holders. This affects all holders of every fund managed by the same key. The design does require the manager to fund and manage redemptions, so this is a trust assumption, but the code places no limit or delay on it.

        ##### How it works

        1. Factory.newFund makes one EOA the owner of the VaultPool and of the Share token (Factory.sol:28, 32).

        2. withdraw() sends the full balance to the owner and pauses the vault (VaultPool.sol:43-48).

        3. reedem() pays amount * issueTotal / (totalSupply + 1), so minting raises totalSupply and dilutes every other holder (VaultPool.sol:31-33).

        4. Share.mint has no supply cap and Share.burn(from, amount) needs no allowance (Share.sol:16-30).

        Exploit scenario

        Not specified.

        Recommendation

        Move ownership to a multisig behind a timelock, cap or schedule Share.mint, and consider freezing minting once a fund enters the redemption phase. Check: verify on-chain that owner() of the VaultPool and Share is the timelock, and that withdraw() from the manager EOA reverts.

    • Cove Solidity Yearn Cove basket manager. Tasks 7 V12 4/7 Codex Sec 1/7 Pashov Opus 4/7 Pashov GPT-6 2/7 Devin 3/7 Devin (Deep) 4/7 Claude Sec 2/7 Claude Opus 2/7 Vercel 2/7

      Yearn Cove basket manager.

      Read the audit report
      • Lack of access control in requestDeposit cove-1 · 9 writeups Critical

        V12

        Unauthenticated deposit requests steal approved assets

        src/BasketToken.sol:231 Predicted severity: Critical

        Root cause

        requestDeposit treats underlying-token approval to the vault as authorization for arbitrary callers to spend an owner's assets and assign their entitlement to any controller.

        Impact

        Any external caller can steal underlying assets from users with sufficient balances and outstanding allowances to the basket vault. The attack requires no operator approval, privileged role, or cooperation from the rebalance manager.

        Description

        requestDeposit accepts independent owner and controller addresses without authenticating the caller against owner. It credits the supplied controller and pulls the underlying asset from the owner using the owner's allowance to the vault. Consequently, an unrelated caller can select an owner who has approved the vault and select themselves as controller. The caller can immediately recover the pulled assets through cancelDepositRequest, without waiting for a rebalance or share fulfillment. Neither the outstanding-request checks nor the asset-pause check binds the caller to the asset owner.

        Codex Security (GPT-6 Sol)

        Any caller can withdraw an owner's approved base tokens through requestDeposit

        src/BasketToken.sol:231 Predicted severity: High

        Root cause

        requestDeposit treats ERC20 allowance to the basket as sufficient to debit any owner. It credits controller before safeTransferFrom and never binds msg.sender to owner or checks an owner-granted operator approval. The controller-only cancellation path then pays the caller.

        Impact

        An unprivileged caller can immediately drain base tokens up to an existing basket allowance; the required victim allowance is common for vault use.

        Description

        requestDeposit accepts an arbitrary owner and credits a caller-selected controller without checking owner authorization. Anyone can use a victim's allowance to the basket, then cancel the new request and receive those tokens immediately.

        Exploit scenario

        Attacker-selected owner and controller flow into a claim mapping and transferFrom; the same controller receives the cancellation transfer.

        Recommendation

        Require msg.sender == owner or an explicit owner-granted operator approval before using the owner's assets; retain an owner-authorized binding for the credited controller.

        Pashov (Claude Opus 5.5 high)

        BasketToken.requestDeposit lacks owner authorization: anyone can pull approved assets of any user into a deposit they control

        src/BasketToken.sol:231 Predicted severity: High

        Root cause

        Missing _onlySelfOrOperator(owner) (or an equivalent msg.sender == owner || isOperator[owner][msg.sender] check) before pulling funds from owner.

        Impact

        Every user with an outstanding ERC20 allowance to a BasketToken can have the full allowance stolen. Infinite approvals are common, and so are approvals left over after the user's own deposit. The attacker becomes the controller of the stolen deposit, receives the basket shares after the next rebalance, and can redeem them or cancel the pending deposit, since cancelDepositRequest refunds the controller (msg.sender). This is a direct theft of user funds.

        Description

        requestDeposit(assets, controller, owner) transfers assets of the base asset from the arbitrary owner argument via safeTransferFrom and credits the deposit to the arbitrary controller argument. Nothing checks that msg.sender == owner or that msg.sender is an approved operator of owner, as ERC-7540 requires. requestRedeem has the equivalent check, and the test suite exercises the operator path.

        Exploit scenario

        1) Alice approves the basket token for type(uint256).max USDC and deposits 100 USDC. 2) The attacker monitors Alice's USDC balance and allowance, then calls basket.requestDeposit(aliceBalance, attacker, alice). 3) The basket pulls Alice's USDC and records depositAssets[attacker]. 4) The attacker immediately calls cancelDepositRequest() and receives Alice's USDC, or waits for fulfillment and claims the shares.

        Recommendation

        At the start of requestDeposit, require msg.sender == owner or isOperator[owner][msg.sender]; otherwise revert with NotAuthorizedOperator.

        Pashov (Codex GPT-6 Sol high)

        Anyone can turn an approved user’s assets into attacker controlled basket shares

        src/BasketToken.sol:231 Predicted severity: Critical

        Root cause

        The function does not require msg.sender to be the asset owner or an authorized operator before transferFrom(owner), and it does not bind controller to owner.

        Impact

        Any base assets covered by an existing allowance to a basket token can be stolen immediately by an arbitrary caller.

        Description

        requestDeposit accepts any owner and attacker-controlled controller, and immediately pulls tokens through the owner’s existing ERC20 allowance. The attacker becomes the controller and can cancel the still-pending request to receive the victim’s base assets directly, without a rebalance.

        Exploit scenario

        A victim has approved the basket token for 100 base tokens. An attacker calls requestDeposit(100, attacker, victim), then calls cancelDepositRequest() as the attacker. The basket token transfers the victim’s 100 tokens to the attacker.

        Recommendation

        Require the caller to be the owner or an explicitly approved operator before pulling tokens from owner; bind delegated deposit authority and controller assignment to the owner’s consent.

        Devin Security

        requestDeposit pulls assets from any owner without checking the caller is the owner or an operator

        src/BasketToken.sol:232 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can take the deposit tokens of any user who has approved a basket token, and turn them into basket shares the attacker controls.

        ##### What's wrong

        This is a missing authorization check on a token pull. requestDeposit takes owner and controller from the caller and calls safeTransferFrom(owner, ...), but it never checks that msg.sender is owner or an approved operator of owner. The deposit is credited to the caller-chosen controller. ERC-7540 requires this check, and the sibling requestRedeem in the same file does perform it.

        ##### Who can do it

        Alice, a user of Acme's Cove basket, approves the basket token to spend her WETH. She often grants a large or unlimited allowance so she can deposit over time. Mallory, any address on the chain, calls requestDeposit(aliceBalance, mallory, alice).

        - Alice has a non-zero ERC20 allowance on the basket's base asset to the basket token contract.

        - The basket has no paused assets.

        - Mallory has no pending or claimable deposit for her own controller address.

        ##### What they get

        Alice's WETH, up to her allowance or balance, moves into the basket under Mallory's deposit request. After the next rebalance, Mallory claims the minted shares with deposit, or simply cancels the request with cancelDepositRequest and gets Alice's WETH sent straight to her. Mallory can do this to every user with a standing allowance on every basket.

        ##### How it works

        1. Mallory calls requestDeposit(assets, mallory, alice) at src/BasketToken.sol:232.

        2. The function only checks Mallory's own pending and claimable state (lines 238-249) and never compares msg.sender with owner.

        3. It credits depositAssets[mallory] with the amount (line 254) and sets lastDepositRequestId[mallory] (line 258).

        4. It pulls the tokens from Alice with safeTransferFrom(owner, address(this), assets) (line 263).

        5. Mallory calls cancelDepositRequest (line 503), which refunds the pending amount to msg.sender, Mallory.

        Exploit scenario

        Not specified.

        Recommendation

        At the start of requestDeposit, add if (owner != msg.sender && !isOperator[owner][msg.sender]) revert NotAuthorizedOperator();, the same as the ERC-7540 reference. To check the fix, add a Foundry test where Alice approves the basket token and a different address calls requestDeposit(amount, attacker, alice). The call must revert, and it must still succeed when Alice has called setOperator(attacker, true).

        Devin Security (Deep)

        requestDeposit pulls tokens from any owner without an operator or allowance check

        src/BasketToken.sol:231 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can pull the full base-asset allowance that any user has granted to a basket token and walk away with it in the same transaction.

        ##### What's wrong

        This is a missing authorization check on a path that pulls funds from a third party. requestDeposit(assets, controller, owner) never checks that the caller is owner or an operator approved by owner before it calls safeTransferFrom(owner, ...), and it credits the deposit to a caller-chosen controller. The sibling requestRedeem does perform this check, so the omission is a bug, not a design choice.

        ##### Who can do it

        Alice, a depositor at Acme Fund, approves the basket token to spend her WETH (most wallets grant an unlimited allowance) and deposits. Mallory, anyone with an Ethereum account, calls requestDeposit(remainingAllowance, mallory, alice) and then cancelDepositRequest().

        - The victim has a non-zero allowance for the basket's base asset granted to the BasketToken contract (left over after a deposit, or sitting in the mempool before a deposit transaction).

        - The basket's assets are not paused in the AssetRegistry.

        - The attacker's chosen controller has no outstanding deposit request (a fresh address always works).

        ##### What they get

        Mallory receives Alice's WETH directly, because cancelDepositRequest pays msg.sender. If she prefers, she waits for the next rebalance and claims the minted shares through deposit() as the controller. She can repeat this against every user who has any allowance left on any basket token. This is direct theft of depositor funds across all baskets.

        ##### How it works

        1. Mallory calls requestDeposit(assets, mallory, alice) on the BasketToken (src/BasketToken.sol:231). No owner or operator check runs; compare requestRedeem at src/BasketToken.sol:319-323.

        2. The contract records depositAssets[mallory] += assets (src/BasketToken.sol:255) and pulls the tokens with safeTransferFrom(alice, address(this), assets) (src/BasketToken.sol:264).

        3. Mallory calls cancelDepositRequest() (src/BasketToken.sol:503). pendingDepositRequest(nextDepositRequestId, mallory) returns the stolen amount and the contract transfers it to her (src/BasketToken.sol:515).

        4. If she waits instead, deposit(assets, mallory, mallory) (src/BasketToken.sol:678) hands her the shares minted for Alice's assets.

        Exploit scenario

        Not specified.

        Recommendation

        Add an owner/operator check at the top of requestDeposit, mirroring requestRedeem and ERC-7540: if (msg.sender != owner && !isOperator[owner][msg.sender]) revert NotAuthorizedOperator();. Verify with a test where victim approves the basket token and a non-operator calls requestDeposit(amount, attacker, victim); it must revert with NotAuthorizedOperator. The existing test that sets an operator before calling on behalf of another account (test/unit/BasketToken.t.sol:236-240) should still pass.

        Claude Security (Sonnet 5.5)

        requestDeposit pulls tokens from an arbitrary owner with no check that the caller is that owner or its operator, so any ERC-20 or permit approval to the basket can be spent by anyone

        src/BasketToken.sol:231 Predicted severity: High

        Root cause

        Vulnerable symbol: requestDeposit

        Preconditions: The victim has a non-zero allowance of the basket asset to the BasketToken. This can be a standing approval, or one granted in the same transaction through selfPermit or a permit signature visible in the mempool.; The victim holds the asset balance.; The basket's assets are not paused.

        Offending code:

        function requestDeposit(uint256 assets, address controller, address owner) public returns (uint256 requestId) {

        Impact

        Any account can take any user's approved asset balance, up to min(balance, allowance) of the basket's asset, and credit it to a controller of the attacker's choosing. After the next rebalance the attacker claims the shares via deposit or mint and redeems them, so the victim loses funds. Users who gave the basket an infinite approval are fully exposed. Users of the selfPermit plus requestDeposit multicall flow are exposed to the value they sign for.

        Description

        The untrusted owner argument is passed straight into IERC20(asset()).safeTransferFrom(owner, address(this), assets) at line 264. The function never checks msg.sender == owner or isOperator[owner][msg.sender]. Every other owner-scoped entry point does this check (_onlySelfOrOperator at 683, 711, 760, 782, and the allowance or operator check in requestRedeem at 319-323). The inherited SelfPermit mixin makes the approval trivially obtainable from a public signature.

        Exploit scenario

        1. Alice holds the basket asset (for example USDC) and has approved the BasketToken, either with a standing approval or in a multicall of [selfPermit(asset, value, deadline, v, r, s), requestDeposit(value, alice, alice)]. 2. Mallory calls basket.requestDeposit(aliceBalance, mallory, alice) directly, or in the permit flow first calls asset.permit(alice, basket, value, deadline, v, r, s) with the signature copied from the mempool and then requestDeposit(value, mallory, alice). 3. Line 264 pulls Alice's tokens into the basket, and depositRequest.depositAssets[mallory] is credited. 4. Alice's own multicall reverts because the permit nonce is already spent. 5. After the rebalance, Mallory calls deposit(assets, mallory, mallory) to receive the shares and then redeems them, taking Alice's assets.

        Recommendation

        At the top of requestDeposit, require msg.sender == owner or isOperator[owner][msg.sender]. The simplest fix is _onlySelfOrOperator(owner), which reverts with NotAuthorizedOperator. Do this before any state change or transfer. This matches the ERC-7540 requirement quoted in IERC7540.sol, that approval of ERC-20 tokens from owner to sender is NOT enough. Add a regression test where a non-operator calls requestDeposit(x, attacker, victim) and must revert.

        Claude Security (Opus 5.5)

        requestDeposit never checks that the caller is the owner or the owner's operator, so anyone can pull a victim's approved assets and cancel the request to take them

        src/BasketToken.sol:231 Predicted severity: High

        Root cause

        Vulnerable symbol: requestDeposit

        Preconditions: The victim has a non-zero ERC-20 allowance for the basket's base asset granted to the BasketToken, or a permit signature for it is visible; None of the basket's assets is paused in AssetRegistry (the check at line 249)

        Offending code:

        function requestDeposit(uint256 assets, address controller, address owner) public returns (uint256 requestId) {

        Impact

        Any unprivileged account can steal the full approved balance of the basket's base asset from every user with a non-zero allowance to any BasketToken. Funds are lost directly and the theft is atomic.

        Description

        owner and controller are both chosen by the caller. requestDeposit never requires msg.sender == owner or isOperator[owner][msg.sender], yet at line 264 it calls safeTransferFrom(owner, address(this), assets) using the allowance the victim gave to the BasketToken. The assets are credited to the controller the attacker picked (line 255). requestRedeem (lines 319-323) and the claim functions do check authorization. IERC7540.sol lines 42-43 says owner MUST be msg.sender unless explicit approval was given, and that an ERC-20 approval alone is not enough.

        Exploit scenario

        Alice approves the BasketToken for USDC so she can deposit. A max approval is common, and the approve and requestDeposit transactions are usually sent separately. In one transaction the attacker calls basket.requestDeposit(min(allowance, balance of Alice), attacker, alice). The USDC moves from Alice into the basket and is recorded as the attacker's pending deposit in the current epoch. The attacker then calls basket.cancelDepositRequest(). It reads pendingDepositRequest(nextDepositRequestId, msg.sender = attacker), sets the attacker's entry to zero and transfers the USDC to the attacker. Alice's funds are gone before any rebalance happens. A user who relies on an EIP-2612 permit is exposed too: the attacker can submit the signature seen in the mempool directly to token.permit(alice, basket, ...) and then run the same steps. Instead of cancelling, the attacker could also leave the request in place and later claim the basket shares minted for Alice's assets.

        Recommendation

        Add an operator check on owner at the start of requestDeposit, for example _onlySelfOrOperator(owner);, which reverts with NotAuthorizedOperator unless msg.sender == owner or isOperator[owner][msg.sender]. This matches ERC-7540 and the existing NotAuthorizedOperator error. Do not accept an ERC-20 allowance as authorization.

        Vercel Security Review

        Anyone can steal assets approved to a basket through requestDeposit

        src/BasketToken.sol:231 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. An unprivileged caller credits themselves using another owner's allowance** - src/BasketToken.sol:231-275

        ```solidity title="src/BasketToken.sol:263-265"

        DepositRequestStruct storage depositRequest = _depositRequests[requestId];

        // update controllers balance of assets pending deposit

        depositRequest.depositAssets[controller] += assets;

        ```

        The new public request flow never authenticates owner or checks their operators before transferring their approved assets. An attacker supplies the victim as owner and themselves as controller.

        **2. The attacker cancels and receives the victim's assets immediately** - src/BasketToken.sol:512-517

        ```solidity title="src/BasketToken.sol:513-517"

        depositRequest.depositAssets[msg.sender] = 0;

        depositRequest.totalDepositAssets -= pendingDeposit;

        // Interactions

        IERC20(asset()).safeTransfer(msg.sender, pendingDeposit);

        ```

        No rebalance or privileged participation is needed; theft is limited by the victim's balance and basket allowance.

        Exploit scenario

        Not specified.

        Recommendation

        Before recording or transferring a deposit, require msg.sender == owner or isOperator[owner][msg.sender]. Do not treat an ERC20 allowance to the basket as authorization for an arbitrary caller to choose the controller.

      • Underflow when calculating basket balances cove-2 · 3 writeups Critical

        V12

        Net-amount guard permits gross-amount underflow

        src/libraries/BasketManagerUtils.sol:793 Predicted severity: Informational

        Root cause

        The balance guard validates netBuyAmount although the settlement subtraction uses initialBuyAmount. The unchecked arithmetic relies on a bound that the guard does not enforce.

        Impact

        Security relevance remains unresolved: can the wrapped write survive the later target-weight check, or be consumed by subsequent trades in a proposal that ultimately succeeds? The missing fact is a guard-compatible complete proposal under supported oracle and strategy inputs; the searched boundary includes proposeTokenSwap, _validateExternalTrades, _isTargetWeightMet, manager role gates, and the available unit-trade tests, so durable corruption or fund loss is not established.

        Description

        The buy-side sufficiency check in _processInternalTrades compares the counterparty's balance with netBuyAmount, but settlement deducts the larger initialBuyAmount. When the buy-side fee is nonzero and the balance lies between those amounts, the check passes and the subsequent unchecked subtraction wraps. For example, gross buy amount 100, fee 2, net amount 98, and counterparty balance 99 pass validation but produce a wrapped balance when 100 is deducted. The wrapped amount is assigned both to memory and to basketBalanceOf before the subsequent proposal-wide weight check. This establishes a local arithmetic-defense failure, but ordinary positive-price weight checks may revert the proposal and roll back the corrupted write.

        Pashov (Claude Opus 5.5 high)

        Internal trade validates toBasket balance against netBuyAmount but subtracts initialBuyAmount in an unchecked block (underflow)

        src/libraries/BasketManagerUtils.sol:798 Predicted severity: Medium

        Root cause

        The check uses the wrong variable: netBuyAmount instead of initialBuyAmount. The unchecked comment assumes the check covers the subtraction.

        Impact

        basketBalanceOf for the buying basket becomes astronomically large, which corrupts totalAssets, share pricing, proRataRedeem (it can withdraw everyone's tokens of that asset held by the BasketManager), and rebalance math. Also, the fee is charged on tokens the basket does not have. A malformed or edge-case proposal can do this; the proposer bot may size trades to exactly the available balance.

        Description

        With a non-zero swapFee, initialBuyAmount = netBuyAmount + feeOnBuy. The sufficiency check is info.netBuyAmount > basketBalances[toBasketIndex][toBasketBuyTokenIndex], but inside unchecked the code subtracts initialBuyAmount from the same balance and writes the result to storage. If netBuyAmount <= balance < initialBuyAmount, the subtraction wraps to ~2^256 and gets stored as the toBasket's balance of buyToken.

        Exploit scenario

        swapFee = 50 bps. The toBasket holds 1000 WETH. The proposer submits an internal trade whose netBuyAmount is 999.9 WETH and whose initialBuyAmount is 1000.15 WETH. The check passes, and basketBalanceOf[toBasket][WETH] becomes 1000 - 1000.15 wrapped. A holder of the toBasket can then proRataRedeem and drain WETH belonging to other baskets.

        Recommendation

        Check initialBuyAmount > basketBalances[toBasketIndex][toBasketBuyTokenIndex] before subtracting, or remove the unchecked block.

        Devin Security (Deep)

        Internal trade balance check uses the after-fee amount but subtracts the pre-fee amount in unchecked math

        src/libraries/BasketManagerUtils.sol:800 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        The buyer basket's balance check and its balance subtraction use different amounts, so an unchecked underflow is possible, though today a later weight check makes the transaction revert before the wrapped value can persist.

        ##### What's wrong

        This is a check-versus-use mismatch inside an unchecked block. The guard compares info.netBuyAmount (after the swap fee) to the buyer basket's balance, but the unchecked subtraction removes initialBuyAmount (before the fee).

        ##### Who can do it

        Bob, who holds the TOKENSWAP_PROPOSER role at Acme, proposes an internal trade while swapFee is non-zero, choosing amounts so that netBuyAmount <= balance < initialBuyAmount.

        - The caller has the TOKENSWAP_PROPOSER role and swapFee > 0.

        - Today _isTargetWeightMet runs afterwards and either reverts inside the oracle or returns false for the wrapped balance, so the corrupted value does not survive the transaction. Any change to that check, or a stale asset index (see the updateBitFlag finding), would remove this accidental protection.

        ##### What they get

        If the wrapped value ever persisted, the buyer basket would own roughly 2^256 units of the buy token on paper and could drain the manager's pooled holdings of that token through proRataRedeem.

        ##### How it works

        1. _processInternalTrades computes initialBuyAmount and netBuyAmount = initialBuyAmount - feeOnBuy (src/libraries/BasketManagerUtils.sol:786-798).

        2. It checks netBuyAmount > basketBalances[to][buy] (src/libraries/BasketManagerUtils.sol:806), then executes basketBalances[to][buy] -= initialBuyAmount inside unchecked and writes the result to storage (src/libraries/BasketManagerUtils.sol:816-825).

        3. For a balance between netBuyAmount and initialBuyAmount the subtraction wraps to a value near 2^256.

        Exploit scenario

        Not specified.

        Recommendation

        Compare initialBuyAmount (the amount actually subtracted) against the buyer basket's balance, or subtract netBuyAmount and account for the fee separately. Verify with a fuzz test that sets swapFee > 0 and a buyer balance strictly between netBuyAmount and initialBuyAmount, asserting IncorrectTradeTokenAmount.

      • Missing rebalance-status check in updateBitFlag() leads to incorrect rebalancing cove-3 · 4 writeups High

        V12

        Mid-rebalance expansion invalidates committed asset identities

        src/BasketManager.sol:460 Predicted severity: Low

        Root cause

        updateBitFlag neither requires a safe rebalance boundary nor migrates the active commitment. The commitment binds positional weights without binding the composition that defines their asset identities.

        Impact

        An authorized composition update can cause the current rebalance to validate against unintended assets or repeatedly fail target checks, delaying settlement of staged redemptions. Completion may eventually bypass target checks after the retry limit, so this evidence supports misvalidated settlement and delay rather than an unconditional permanent freeze.

        Description

        updateBitFlag permits changing a basket's asset set while that basket is included in an active rebalance. The rebalance commitment hashes basket addresses and positional target weights, but not the asset set to which those weights apply. Proposal and completion subsequently load the current basketAssets rather than a committed composition snapshot. Adding an asset earlier in registry order therefore makes the previously committed weights refer to different assets, while appending an asset leaves it outside the old weight array. This failure is distinct from stale index mappings: even with correctly rebuilt indices, the active rebalance would still consume weights committed for the previous composition.

        Pashov (Claude Opus 5.5 high)

        updateBitFlag leaves basketAssetToIndexPlusOne and base-asset index stale (and is allowed mid-rebalance), corrupting basket accounting

        src/BasketManager.sol:460 Predicted severity: High

        Root cause

        Incomplete update of the derived index mappings when a basket's asset list changes, and no rebalance-status check.

        Impact

        (a) Any internal or external trade that touches a new asset reverts with AssetNotFoundInBasket, so the new targets can never be reached. (b) After an index shift, the internal-trade code writes basketBalances[i][wrongIndex] -/+ amount into the storage slot of a different token, which corrupts balances. (c) _processPendingDeposits reads balances[baseAssetIndex] and writes basketBalanceOf[basket][basketAssets[baseAssetIndex]], which is now a different token. The real base-asset deposit is never credited, and the other token's balance is inflated, making the basket insolvent and mispricing shares. (d) _finalizeRebalance approves assets[baseAssetIndex] (the wrong token) and then BasketToken.fulfillRedeem pulls the real base asset with transferFrom, which reverts. completeRebalance is then bricked. Changing basketAssets mid-rebalance also breaks _isTargetWeightMet, because the weights and asset arrays no longer line up.

        Description

        updateBitFlag replaces basketAssets[basket] with AssetRegistry.getAssets(newBitFlag), which is ordered by registry index. It does not rebuild basketAssetToIndexPlusOne or basketTokenToBaseAssetIndexPlusOne, and it does not check that the basket is outside an in-progress rebalance. Newly added assets have no index mapping. If a new asset has a lower registry index than existing assets, every existing asset's array position shifts while the stored indices still point to the old positions.

        Exploit scenario

        The asset registry holds [USDC(0), WETH(1), WBTC(2)] and a basket uses bitFlag 0b110 (WETH, WBTC) with base asset WETH (index 0). The timelock adds USDC by calling updateBitFlag(basket, 0b111). basketAssets becomes [USDC, WETH, WBTC], but the base index still points at 0, now USDC. On the next rebalance, deposited WETH is booked as USDC (basketBalanceOf[USDC] = USDCbal... += WETH amount), and redemptions approve USDC while BasketToken pulls WETH, so the call reverts.

        Recommendation

        In updateBitFlag, require rebalanceStatus.status == NOT_STARTED, or that the basket is not in basketMask. Clear the old basketAssetToIndexPlusOne entries, rebuild them for the new list, and recompute basketTokenToBaseAssetIndexPlusOne.

        Devin Security

        updateBitFlag does not refresh asset index mapping and skips the rebalance-in-progress check

        src/BasketManager.sol:460 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        When the timelock adds assets to a basket, the basket cannot trade the new assets, and the change can land in the middle of a running rebalance. This harms only availability and needs a timelock action.

        ##### What's wrong

        This is a state synchronization bug. updateBitFlag replaces basketAssets[basket] with the new asset list. It does not write basketAssetToIndexPlusOne for the new assets, and it does not refresh the old entries if the asset order changes. Trade code looks up asset positions through that mapping. The function also does not check whether the basket is in the current rebalance basketMask, while setManagementFee and proRataRedeem do check this.

        ##### Who can do it

        Alice's team at Acme uses the timelock to add a new asset to a live basket. The bug needs no attacker. It follows from a normal admin action.

        - Caller holds TIMELOCK_ROLE.

        - The new bitFlag adds at least one asset.

        ##### What they get

        Any internal or external trade that touches a new asset reverts with AssetNotFoundInBasket. The basket can then never reach its new target weights. Rebalances that include it keep failing until the retry limit forces them through without meeting the weights. If the order of existing assets shifts, the stale positions can point at the wrong slot in the balance arrays during trade checks. No funds can be stolen through this path.

        ##### How it works

        1. The timelock calls updateBitFlag (src/BasketManager.sol:460).

        2. The function overwrites basketAssets[basket] (src/BasketManager.sol:487) and leaves basketAssetToIndexPlusOne alone. createNewBasket sets that mapping (src/libraries/BasketManagerUtils.sol:210-217).

        3. Trade processing calls basketTokenToRebalanceAssetToIndex, which reverts for the missing entries or returns stale ones (src/libraries/BasketManagerUtils.sol:492-509).

        Exploit scenario

        Not specified.

        Recommendation

        In updateBitFlag, loop over the new asset list and set basketAssetToIndexPlusOne[basket][assets[i]] = i + 1. Also update basketTokenToBaseAssetIndexPlusOne if the base asset moves. Revert if the basket's bit is set in rebalanceStatus.basketMask. To check the fix, write a test that adds an asset with updateBitFlag and then proposes an internal trade into the new asset. The trade must succeed, and updateBitFlag must revert during an active rebalance.

        Devin Security (Deep)

        updateBitFlag replaces the asset list without refreshing stored asset and base-asset indices

        src/BasketManager.sol:460 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        After an admin adds an asset to a basket, the manager's stored per-asset indices, including the base-asset index, can point at the wrong assets, so later rebalances misprice deposits and read and write the wrong balances.

        ##### What's wrong

        Two parallel structures fall out of sync. updateBitFlag overwrites basketAssets[basket] with the new list (ordered by registry index) but leaves basketAssetToIndexPlusOne and basketTokenToBaseAssetIndexPlusOne untouched. Newly added assets have index 0 (not found), and every existing asset whose position shifted keeps a stale index. The function also runs without any rebalance-status guard.

        ##### Who can do it

        Tina operates Acme's timelock. A basket holds WETH (registry index 0) and rETH (index 5). She calls updateBitFlag to add weETH (index 2). basketAssets becomes [WETH, weETH, rETH], but rETH's stored index still says position 1, which now belongs to weETH.

        - The TIMELOCK_ROLE calls updateBitFlag with a new bit whose registry index is lower than an existing asset's index (or lower than the base asset's index).

        ##### What they get

        No attacker gain, but silent fund misaccounting for every holder of the basket. Internal and external trades on rETH check and update weETH's balance slot, producing phantom or lost balances that feed proRataRedeem from the shared token pool. New assets cannot be traded at all because the index lookup reverts. If the base asset's position shifts, deposits are valued and credited as the wrong token, and _finalizeRebalance approves the wrong token before fulfillRedeem pulls the real one, so completeRebalance reverts permanently for a basket with pending redeems.

        ##### How it works

        1. updateBitFlag writes basketAssets[basket] = getAssets(bitFlag) (src/BasketManager.sol:487) and nothing else; indices are only set in createNewBasket (src/libraries/BasketManagerUtils.sol:203, 210-217).

        2. basketTokenToRebalanceAssetToIndex returns the stale position (src/libraries/BasketManagerUtils.sol:492-509); _processInternalTrades and _validateExternalTrades use it to index basketBalances and to write storage (src/libraries/BasketManagerUtils.sol:767-770, 818-828, 864-883).

        3. _processPendingDeposits and _finalizeRebalance use basketTokenToBaseAssetIndexPlusOne to select basketAssets[basket][baseAssetIndex] (src/libraries/BasketManagerUtils.sol:277-283, 1009, 1017, 614-628); if that slot now holds a different token, deposits are credited to it and forceApprove pairs the wrong token with asset(), reverting at src/BasketToken.sol:487.

        4. updateBitFlag has no basketMask or status check (src/BasketManager.sol:460-491), so it can also run mid-rebalance and misalign the hashed target weights with basketAssets.

        Exploit scenario

        Not specified.

        Recommendation

        In updateBitFlag, require rebalanceStatus.status == NOT_STARTED (or that the basket's bit is clear in basketMask), clear the old basketAssetToIndexPlusOne entries, rebuild them for the new asset list, and recompute basketTokenToBaseAssetIndexPlusOne. Verify with a test that creates a basket with assets at registry indices {0, 5}, adds index 2, then runs an internal trade on the index-5 asset and a pending redeem, asserting balances move on the correct asset and that completeRebalance succeeds.

      • Incorrect swap-fee calculation on feeOnBuy cove-4 High
      • Management-fee calculation results in lower effective rate cove-5 High
      • Missing mapping update in BasketToken.updateBitFlag() causes rebalancing failure cove-6 · 8 writeups Medium

        V12

        Composition expansion leaves custody accounting indices stale

        src/BasketManager.sol:483 Predicted severity: High

        Root cause

        updateBitFlag mutates the canonical ordered asset set without migrating basketAssetToIndexPlusOne and basketTokenToBaseAssetIndexPlusOne. Downstream accounting assumes those creation-time positions still identify the same assets.

        Impact

        Following an authorized composition expansion, subsequent user deposits can create an accounting balance for an asset that was never received, and redemption fulfillment can approve the wrong token and revert. This supports conditional fund loss through incorrect share valuation or cross-basket custody accounting, and disruption of rebalancing when newly added assets cannot be resolved.

        Description

        updateBitFlag replaces basketAssets[basket] and changes the token's bitFlag, but does not rebuild either asset-position lookup or the stored base-asset position. Both lookups are populated only during basket creation. AssetRegistry.getAssets returns assets in registry order, so adding an earlier registered asset can shift existing positions even though the new flag includes every old asset. Subsequent deposit processing values and credits the deposit using the asset at the stale base position, although BasketToken.fulfillDeposit actually transfers the token's unchanged root asset. Trade validation also uses stale positions, and newly added assets have no lookup entry at all.

        Pashov (Claude Opus 5.5 high)

        updateBitFlag leaves basketAssetToIndexPlusOne and base-asset index stale (and is allowed mid-rebalance), corrupting basket accounting

        src/BasketManager.sol:460 Predicted severity: High

        Root cause

        Incomplete update of the derived index mappings when a basket's asset list changes, and no rebalance-status check.

        Impact

        (a) Any internal or external trade that touches a new asset reverts with AssetNotFoundInBasket, so the new targets can never be reached. (b) After an index shift, the internal-trade code writes basketBalances[i][wrongIndex] -/+ amount into the storage slot of a different token, which corrupts balances. (c) _processPendingDeposits reads balances[baseAssetIndex] and writes basketBalanceOf[basket][basketAssets[baseAssetIndex]], which is now a different token. The real base-asset deposit is never credited, and the other token's balance is inflated, making the basket insolvent and mispricing shares. (d) _finalizeRebalance approves assets[baseAssetIndex] (the wrong token) and then BasketToken.fulfillRedeem pulls the real base asset with transferFrom, which reverts. completeRebalance is then bricked. Changing basketAssets mid-rebalance also breaks _isTargetWeightMet, because the weights and asset arrays no longer line up.

        Description

        updateBitFlag replaces basketAssets[basket] with AssetRegistry.getAssets(newBitFlag), which is ordered by registry index. It does not rebuild basketAssetToIndexPlusOne or basketTokenToBaseAssetIndexPlusOne, and it does not check that the basket is outside an in-progress rebalance. Newly added assets have no index mapping. If a new asset has a lower registry index than existing assets, every existing asset's array position shifts while the stored indices still point to the old positions.

        Exploit scenario

        The asset registry holds [USDC(0), WETH(1), WBTC(2)] and a basket uses bitFlag 0b110 (WETH, WBTC) with base asset WETH (index 0). The timelock adds USDC by calling updateBitFlag(basket, 0b111). basketAssets becomes [USDC, WETH, WBTC], but the base index still points at 0, now USDC. On the next rebalance, deposited WETH is booked as USDC (basketBalanceOf[USDC] = USDCbal... += WETH amount), and redemptions approve USDC while BasketToken pulls WETH, so the call reverts.

        Recommendation

        In updateBitFlag, require rebalanceStatus.status == NOT_STARTED, or that the basket is not in basketMask. Clear the old basketAssetToIndexPlusOne entries, rebuild them for the new list, and recompute basketTokenToBaseAssetIndexPlusOne.

        Pashov (Codex GPT-6 Sol high)

        Expanding a basket leaves trade asset indices missing or stale

        src/BasketManager.sol:483 Predicted severity: Medium

        Root cause

        updateBitFlag updates basketAssets without rebuilding its per-asset index mapping.

        Impact

        A configured basket can become unable to trade newly added assets or reach its new target weights, blocking normal rebalance settlement.

        Description

        The bit flag update replaces the ordered basket asset list, but does not rebuild basketAssetToIndexPlusOne. New assets have a zero lookup index, while existing assets shifted by the insertion retain their former indices. Internal and external trade validation then reverts for new assets or reads the wrong balance column for shifted assets.

        Exploit scenario

        A timelock expands a basket to include an asset. The proposer prepares a trade for that asset, but basketTokenToRebalanceAssetToIndex returns zero and reverts.

        Recommendation

        Rebuild basketAssetToIndexPlusOne for every asset in the new ordered list whenever the bit flag changes.

        Devin Security

        updateBitFlag leaves asset index maps stale, so balances are booked to the wrong asset

        src/BasketManager.sol:483 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        After the timelock adds an asset to an existing basket, the basket's internal books point at the wrong assets, which can misbook deposits and trades and let the basket's redeemers withdraw tokens that belong to other baskets.

        ##### What's wrong

        This is a stale index bug. updateBitFlag in src/BasketManager.sol rewrites basketAssets[basket] from the new bit flag. It does not rebuild basketAssetToIndexPlusOne or basketTokenToBaseAssetIndexPlusOne, which createNewBasket sets at basket creation. The asset registry returns assets in registry order. If the new asset sorts before existing ones, every later asset moves to a new position, but the index maps still hold the old positions. The new asset has no index entry at all.

        ##### Who can do it

        Acme's timelock calls updateBitFlag to add rETH to a basket that holds WETH and USDC, a normal admin action. Bob, a user, then deposits WETH into that basket. Nobody acts maliciously, but the next rebalance runs on corrupted indexes.

        - The timelock calls updateBitFlag with a bit flag that adds an asset whose registry position is before an existing asset in the basket.

        - A rebalance then runs on that basket.

        ##### What they get

        In _processPendingDeposits, the stale base asset index selects a different asset. Bob's WETH deposit is then booked as a balance of that other asset. The basket's books then show more of that asset than it holds, and pro-rata redeemers of that basket can withdraw tokens that really belong to other baskets in the shared manager. Internal and external trade settlement and weight checks also read and write the wrong slots. Trades that involve the new asset revert with AssetNotFoundInBasket, which can stall rebalances. The harm reaches every basket held by the same BasketManager. It needs the trusted timelock to trigger it.

        ##### How it works

        1. BasketManager.updateBitFlag (src/BasketManager.sol:487) sets basketAssets[basket] to the new asset list and nothing else.

        2. basketAssetToIndexPlusOne was only set in createNewBasket (src/libraries/BasketManagerUtils.sol:209-216), and basketTokenToBaseAssetIndexPlusOne only in _setBaseAssetIndex (line 1145).

        3. basketTokenToRebalanceAssetToIndex (line 492) returns the old index, or reverts for the new asset.

        4. _processInternalTrades (line 752) and _validateExternalTrades (line 843) use those indexes into balance arrays built from the new basketAssets order, so they read and write the wrong asset's balance.

        5. _processPendingDeposits (lines 1009-1017) adds the deposit to basketBalanceOf[basket][basketAssets[basket][baseAssetIndex]], which is now a different asset.

        Exploit scenario

        Not specified.

        Recommendation

        In updateBitFlag, after setting the new basketAssets, clear and rewrite basketAssetToIndexPlusOne for every asset in the new list. Also recompute basketTokenToBaseAssetIndexPlusOne with _setBaseAssetIndex. Block updateBitFlag while the basket is in an active rebalance. To check the fix, add a test that creates a basket with assets at registry positions 0 and 2, updates the bit flag to add position 1, and asserts that basketTokenToRebalanceAssetToIndex and the base asset index match the new order. A following rebalance with a deposit should credit the base asset.

        Devin Security (Deep)

        updateBitFlag replaces the asset list without refreshing stored asset and base-asset indices

        src/BasketManager.sol:460 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        After an admin adds an asset to a basket, the manager's stored per-asset indices, including the base-asset index, can point at the wrong assets, so later rebalances misprice deposits and read and write the wrong balances.

        ##### What's wrong

        Two parallel structures fall out of sync. updateBitFlag overwrites basketAssets[basket] with the new list (ordered by registry index) but leaves basketAssetToIndexPlusOne and basketTokenToBaseAssetIndexPlusOne untouched. Newly added assets have index 0 (not found), and every existing asset whose position shifted keeps a stale index. The function also runs without any rebalance-status guard.

        ##### Who can do it

        Tina operates Acme's timelock. A basket holds WETH (registry index 0) and rETH (index 5). She calls updateBitFlag to add weETH (index 2). basketAssets becomes [WETH, weETH, rETH], but rETH's stored index still says position 1, which now belongs to weETH.

        - The TIMELOCK_ROLE calls updateBitFlag with a new bit whose registry index is lower than an existing asset's index (or lower than the base asset's index).

        ##### What they get

        No attacker gain, but silent fund misaccounting for every holder of the basket. Internal and external trades on rETH check and update weETH's balance slot, producing phantom or lost balances that feed proRataRedeem from the shared token pool. New assets cannot be traded at all because the index lookup reverts. If the base asset's position shifts, deposits are valued and credited as the wrong token, and _finalizeRebalance approves the wrong token before fulfillRedeem pulls the real one, so completeRebalance reverts permanently for a basket with pending redeems.

        ##### How it works

        1. updateBitFlag writes basketAssets[basket] = getAssets(bitFlag) (src/BasketManager.sol:487) and nothing else; indices are only set in createNewBasket (src/libraries/BasketManagerUtils.sol:203, 210-217).

        2. basketTokenToRebalanceAssetToIndex returns the stale position (src/libraries/BasketManagerUtils.sol:492-509); _processInternalTrades and _validateExternalTrades use it to index basketBalances and to write storage (src/libraries/BasketManagerUtils.sol:767-770, 818-828, 864-883).

        3. _processPendingDeposits and _finalizeRebalance use basketTokenToBaseAssetIndexPlusOne to select basketAssets[basket][baseAssetIndex] (src/libraries/BasketManagerUtils.sol:277-283, 1009, 1017, 614-628); if that slot now holds a different token, deposits are credited to it and forceApprove pairs the wrong token with asset(), reverting at src/BasketToken.sol:487.

        4. updateBitFlag has no basketMask or status check (src/BasketManager.sol:460-491), so it can also run mid-rebalance and misalign the hashed target weights with basketAssets.

        Exploit scenario

        Not specified.

        Recommendation

        In updateBitFlag, require rebalanceStatus.status == NOT_STARTED (or that the basket's bit is clear in basketMask), clear the old basketAssetToIndexPlusOne entries, rebuild them for the new asset list, and recompute basketTokenToBaseAssetIndexPlusOne. Verify with a test that creates a basket with assets at registry indices {0, 5}, adds index 2, then runs an internal trade on the index-5 asset and a pending redeem, asserting balances move on the correct asset and that completeRebalance succeeds.

        Claude Security (Sonnet 5.5)

        updateBitFlag rewrites basketAssets but leaves basketAssetToIndexPlusOne and basketTokenToBaseAssetIndexPlusOne stale, corrupting rebalance accounting

        src/BasketManager.sol:487 Predicted severity: Medium

        Root cause

        Vulnerable symbol: updateBitFlag

        Preconditions: TIMELOCK_ROLE calls updateBitFlag to add an asset to an existing basket; For the base-asset corruption: a newly added asset has a lower registry bit than the base asset (or other assets shift position)

        Offending code:

        _bmStorage.basketAssets[basket] = AssetRegistry(_bmStorage.assetRegistry).getAssets(bitFlag);

        Impact

        After any bitFlag update that inserts an asset before the base asset, or after any update at all for trading the new assets, deposit share pricing and per-asset accounting are wrong. This can mean phantom balances that drain other baskets' tokens, trades blocked for new assets, or a permanently reverting completeRebalance that freezes every basket in the stuck batch. Triggering requires the timelock performing its intended operation.

        Description

        updateBitFlag replaces the basket's asset array with the new registry list, but BasketManagerUtils continues to resolve asset positions through index mappings that are only ever written in createNewBasket. Those stale or missing indexes are then used to address the positional balances arrays and to pick the base asset.

        Exploit scenario

        A basket was created with assets [A (bit 0), C (bit 2)] and base asset C (stored base index 2). The timelock widens the bitFlag to add B (bit 1), the only operation updateBitFlag permits, so basketAssets becomes [A, B, C]. (1) B has no basketAssetToIndexPlusOne entry, so any internal or external trade involving B reverts with AssetNotFoundInBasket and B can never be bought. (2) C keeps its old index while its array position changed, so balances written through the index land on the wrong element: basketBalanceOf[from][sellToken] is set to another asset's balance minus sellAmount. (3) The stored base index 2 now points at B. At the next proposeRebalance, pending deposits (in C) are valued with B's oracle price, so shares are minted at the wrong price, and basketBalanceOf[B] is credited with C that was actually received. B becomes phantom-backed and can be redeemed pro-rata from other baskets' B. In _finalizeRebalance, forceApprove is granted on B while BasketToken.fulfillRedeem pulls C, so completeRebalance reverts and the global rebalance state stays stuck.

        Recommendation

        In updateBitFlag, rebuild basketAssetToIndexPlusOne for all assets in the new list (clearing stale entries) and recompute basketTokenToBaseAssetIndexPlusOne from BasketToken.asset(). Refuse the update while the basket is part of an in-progress rebalance.

        Claude Security (Opus 5.5)

        updateBitFlag rebuilds basketAssets but leaves the cached asset indexes stale, so later lookups read the wrong asset

        src/BasketManager.sol:487 Predicted severity: High

        Root cause

        Vulnerable symbol: updateBitFlag

        Preconditions: TIMELOCK_ROLE calls updateBitFlag with a superset bitFlag that adds an asset whose registry index is lower than the base asset or another existing asset (a normal, supported operation); Strategy has target weights set for the new bitFlag; The rebalance proposer runs proposeRebalance as usual (no attacker privileges needed)

        Offending code:

        _bmStorage.basketAssets[basket] = AssetRegistry(_bmStorage.assetRegistry).getAssets(bitFlag);

        Impact

        Share-minting and basket accounting break across tokens. An attacker can claim balances that do not exist and withdraw them from assets pooled across all baskets, which is theft from other baskets. Honest depositors can also be underpaid. Separately, finalization can revert permanently, freezing all future rebalances and pro-rata redemptions for the affected baskets. New assets also have no index entry, so every trade involving them reverts with AssetNotFoundInBasket.

        Description

        updateBitFlag replaces basketAssets[basket] with a new list sorted by registry index. It does not update basketTokenToBaseAssetIndexPlusOne or basketAssetToIndexPlusOne, which only createNewBasket writes (BasketManagerUtils.sol:212, :1156). If the timelock adds an asset whose registry index is lower than an existing asset's, every later index-based access in proposeRebalance, _processPendingDeposits, _finalizeRebalance, _processInternalTrades and _validateExternalTrades lands on a different token's slot. An unprivileged depositor can then have deposits credited and priced as the wrong token. Also CWE-1285: updateBitFlag swaps in a new, reordered basketAssets array. It never recomputes basketAssetToIndexPlusOne or basketTokenToBaseAssetIndexPlusOne, which are only written once, in createNewBasket (BasketManagerUtils.sol:212, :1156). Every later rebalance indexes the new array with these old indices. Deposit amounts, redeem approvals and internal-trade balance writes then land on a different token than intended. Also CWE-129: AssetRegistry.getAssets(bitFlag) returns assets in registry-index order. When updateBitFlag adds a bit below an existing one, every later asset moves to a new position in basketAssets. The index maps basketTokenToBaseAssetIndexPlusOne and basketAssetToIndexPlusOne are only written in createNewBasket (BasketManagerUtils.sol:212 and :1156), so after the update they still hold the old positions. BasketManagerUtils then uses those stale indices to read and write per-asset balances, and the slot they point to now holds a different token.

        Exploit scenario

        Registry is [USDC(0), WETH(1), WBTC(2)]. Basket B was created with bitFlag 0b110 and base asset WETH, so its assets are [WETH, WBTC] and its base index is 0. The timelock legitimately calls updateBitFlag(B, 0b111). basketAssets[B] becomes [USDC, WETH, WBTC], but the base index is still 0, which now points to USDC. The attacker calls B.requestDeposit(1e18 WETH). When the rebalance bot calls proposeRebalance, _processPendingDeposits prices 1e18 units as USDC (about $1e12) and mints about 1e6 times the existing supply to the depositor. It also sets basketBalanceOf[B][USDC] += 1e18, while the real WETH it received is never credited. The attacker claims the shares. completeRebalance has no role check, so the attacker calls it 4 times, 15 minutes apart, to exhaust the retries and finalize. Then B.proRataRedeem is called in chunks sized so the USDC payout matches BasketManager's real USDC balance. This drains USDC that belongs to every other basket, plus collected fees, for the cost of 1 WETH. In the other direction (base token worth more per unit than the token now at the stale index), honest depositors lose value with no attacker involved. If B has pending redeems at finalize, forceApprove approves the wrong token and fulfillRedeem's transferFrom of the real base asset reverts. In that case completeRebalance reverts every time it reaches finalize. The global rebalance status cannot return to NOT_STARTED, and proRataRedeem stays blocked for every basket in the mask.

        Recommendation

        In updateBitFlag, rebuild basketAssetToIndexPlusOne for every asset in the new list, clear the entries for old positions, and recompute basketTokenToBaseAssetIndexPlusOne from BasketToken(basket).asset(), for example by calling _setBaseAssetIndex. Also revert if the basket is part of an active rebalance (basketMask bit set or status != NOT_STARTED). Alternatively, only allow new assets that are appended after all existing ones. Also CWE-1285: In updateBitFlag, after rewriting basketAssets, clear and recompute basketAssetToIndexPlusOne for every asset and recompute basketTokenToBaseAssetIndexPlusOne, e.g. by calling _setBaseAssetIndex with BasketToken(basket).asset(). Also block updateBitFlag while the basket is in rebalanceStatus.basketMask or any rebalance is active. Alternatively, require that new bits are strictly above the highest current bit so existing indices cannot shift, and still register the new assets' indices. Also CWE-129: In updateBitFlag, rebuild basketAssetToIndexPlusOne for every asset in the new array. Clear entries for the old layout and recompute basketTokenToBaseAssetIndexPlusOne by calling _setBaseAssetIndex with the basket's asset(). Alternatively, make basket asset arrays append-only so existing positions never move. Also reject updateBitFlag while the basket is part of an in-progress rebalance (rebalanceStatus.basketMask), and run the hasPausedAssets check there as createNewBasket does.

        Vercel Security Review

        Expanding a basket leaves stale asset indexes and corrupts deposit accounting

        src/BasketManager.sol:487 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Valid basket expansion changes ordering without rebuilding indexes** - src/BasketManager.sol:487-490

        ```solidity title="src/BasketManager.sol:487-490"

        _bmStorage.basketAssets[basket] = AssetRegistry(_bmStorage.assetRegistry).getAssets(bitFlag);

        emit BasketBitFlagUpdated(basket, currentBitFlag, bitFlag, oldId, newId);

        // Update the bitFlag in the BasketToken contract

        BasketToken(basket).setBitFlag(bitFlag);

        ```

        Adding an earlier-registered asset shifts existing positions, but base-asset and per-asset indexes retain their previous values.

        **2. Subsequent deposits are valued using the wrong asset** - src/libraries/BasketManagerUtils.sol:1008-1009

        ```solidity title="src/libraries/BasketManagerUtils.sol:1008-1009"

        pendingDepositValue =

        self.eulerRouter.getQuote(pendingDeposit, self.basketAssets[basket][baseAssetIndex], _USD_ISO_4217_CODE);

        ```

        The stale base index also selects the credited holding at line 1017, mispricing shares and creating unbacked asset balances.

        **3. Fulfillment actually transfers the unchanged underlying token** - src/BasketToken.sol:395-397

        ```solidity title="src/BasketToken.sol:395-397"

        // Interactions

        // transfer the assets to the basket manager

        IERC20(asset()).safeTransfer(msg.sender, assets);

        ```

        Ordinary depositors can subsequently redeem fictitious holdings against other baskets' pooled inventory when token prices or decimals differ.

        Exploit scenario

        Not specified.

        Recommendation

        On every bitflag update, rebuild basketAssetToIndexPlusOne for the new ordered array and recompute basketTokenToBaseAssetIndexPlusOne from BasketToken(basket).asset(). Prevent updates during an active rebalance so its hashed weights and arrays remain consistent. Test insertion before existing assets with different decimals and prices.

      • Potential price manipulation via read-only reentrancy in BasketToken.proRataRedeem() cove-7 Medium
    • Dojoswap Rust CosmWasm DEX (Injective). Tasks 2 V12 2/2 Codex Sec 2/2 Pashov Opus — Pashov GPT-6 — Devin 2/2 Devin (Deep) 2/2 Claude Sec 1/2 Claude Opus 0/2 Vercel 1/2

      CosmWasm DEX (Injective).

      Read the audit report
      • Deposit amount is not validated against message funds dojoswap-1 · 6 writeups Critical

        V12

        Declared deposits need not match received coins

        contracts/launchpad/src/msg.rs:23 Predicted severity: High

        Root cause

        The custody check validates info.funds[0].denom but ignores info.funds[0].amount. Participant accounting and payout calculations trust the caller's separate amount argument instead of the actual received coins.

        Impact

        For storage containing the necessary participant records and sufficient shared payout balances, understated attached funds can purchase offering tokens without payment and extract native coins contributed by others. Overstated attached funds are also accepted without equivalent participation credit or a reconciliation refund, leaving the surplus outside participant accounting.

        Description

        deposit checks the number and denomination of attached coins but never compares their amount with the independently supplied ExecuteMsg::Deposit.amount. It adds the declared amount to both user.amount and state.total_amount, and harvest subsequently treats these numbers as paid participation when calculating offering tokens and native refunds. Conditional on a preexisting participant key, a sender can attach one raising coin while declaring a substantially larger deposit. With an honest recorded deposit of 100, a zero-amount attacker record, targets of 100 raising and 100 offering, and an attacker declaration of 100 backed by one coin, the resulting total is 200 and the attacker is assigned 50 offering tokens and a 50-coin refund. Fresh deployments are blocked by missing participant initialization; no legacy deployment or record-creation route is established by the searched repository.

        Codex Security (GPT-6 Sol)

        CreatePair can mint caller-owned LP tokens using factory-held native coins

        contracts/dojoswap_factory/src/contract.rs:151 Predicted severity: Medium

        Root cause

        CreatePair persists caller-declared native amounts without binding them to the native coins in info.funds. Its reply later builds the pair's funds from those amounts using the factory balance and designates the caller as LP receiver.

        Impact

        The path can transfer factory-held coins to a caller-controlled LP position. It requires an available new pair and enough factory balance for minimum initial liquidity; deployed balances are unknown.

        Description

        Any caller can create a new pair with native liquidity amounts that exceed the coins attached to CreatePair. The factory then pays the declared native amount from its own balance and asks the pair to mint the caller LP tokens.

        Exploit scenario

        Caller assets -> TMP_PAIR_INFO -> native funds in reply -> pair ProvideLiquidity -> LP mint to caller

        Recommendation

        In CreatePair, require each requested native amount to equal the matching attached coin amount, reject extra denominations, and carry only verified amounts into the reply.

        Devin Security

        Launchpad deposit credits the declared amount without checking the coins sent (currently masked by a load error)

        contracts/launchpad/src/contract.rs:174 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Right now no one can deposit, because a separate bug rejects every new user, but the obvious fix for that bug would let anyone claim a share of the sale they never paid for.

        ##### What's wrong

        This is a missing funds check. deposit adds the caller's amount argument to their balance and to total_amount. It only checks that one coin of raising_denom was attached. It never checks that info.funds[0].amount equals amount. Today USER_INFO.load at line 180 fails for any address with no stored record. Nothing else creates those records, so every deposit fails before it reaches the credit.

        ##### Who can do it

        Alice, a project owner, runs a token sale through the launchpad. If the load bug is fixed (for example by switching to may_load with a default), Mallory, anyone with a wallet, calls Deposit { amount: 1_000_000_000_000 } and attaches 1 unit of the raising denom.

        - USER_INFO.load in deposit is changed so that it succeeds for new users.

        - The sale is inside its start_time..end_time window.

        - Mallory attaches one coin of raising_denom of any size.

        ##### What they get

        Once that change is made, Mallory's fake balance dominates total_amount. At harvest she receives almost all of the offering tokens. She also receives a refund in the raising denom that is paid from honest buyers' deposits. In the current code the deposit always errors, so the only effect is that the launchpad cannot take deposits.

        ##### How it works

        1. deposit at contracts/launchpad/src/contract.rs:175 checks only info.funds.len() and info.funds[0].denom.

        2. USER_INFO.load at contracts/launchpad/src/contract.rs:180 currently errors for any address with no stored record, which blocks every deposit.

        3. If that load succeeds, contracts/launchpad/src/contract.rs:186-190 credits the caller-chosen amount to the user and to total_amount.

        4. harvest at contracts/launchpad/src/contract.rs:228-266 pays offering tokens and refunds in proportion to the credited amount.

        Exploit scenario

        Not specified.

        Recommendation

        Drop the amount parameter, or require info.funds[0].amount == amount, and credit only the coins actually received. At the same time, replace USER_INFO.load with may_load(...)?.unwrap_or(User { amount: 0, claimed: false }) so deposits work. To check the fix, add a test where a new user deposits with matching funds and succeeds. Add a second test where the declared amount is larger than the attached coins, and assert that it fails.

        Devin Security (Deep)

        Launchpad deposit credits the caller-chosen amount without checking the coins actually sent

        contracts/launchpad/src/contract.rs:174 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Any wallet that has a depositor record can attach one base unit of the raising coin, name any deposit amount it likes, and then collect most of the sale's tokens plus other depositors' real money as a refund; on a fresh deployment nobody can get a depositor record yet (separate finding), so this is live on an instance migrated with existing depositors or as soon as that bug is fixed.

        ##### What's wrong

        This is an unverified deposit amount. The deposit handler trusts the amount field inside the message instead of the coins attached to the transaction. It checks that exactly one coin of the right denom is attached, but it never compares that coin's amount with amount. It then credits amount to the user record and adds it to total_amount, and those two numbers drive every payout in harvest.

        ##### Who can do it

        Alice and Bob each deposit 500 INJ into a launchpad run by Acme Labs. The sale raises 1,000 INJ for 1,000,000 ACME tokens. Mallory, an attacker with an ordinary wallet, sends a Deposit message with amount set to 1,600 INJ but attaches only 1 base unit of INJ. The contract records her as a 1,600 INJ depositor and total_amount becomes 2,600 INJ.

        Conditions:

        - The sale window is open (block time between start_time and end_time).

        - Mallory's address already has an entry in the user_info map. The current deposit code cannot create one for a new address (see the separate NotFound finding), so this needs an instance that was migrated with existing depositor records, or the fix of that bug.

        - Mallory harvests after the admin enables claims and before the other depositors.

        ##### What they get

        When claims open, Mallory harvests first. The contract computes her share as 1,600 of 2,600 and sends her about 615,000 ACME tokens plus a refund of about 985 INJ. That refund is paid from the 1,000 INJ that Alice and Bob really deposited. Alice and Bob's harvests then fail because the contract no longer holds enough INJ for their refunds, so they get neither tokens nor their money back. Acme Labs loses most of its tokens and the raise. In an under-subscribed sale Mallory can instead name an amount that fills the remaining allocation and take those tokens for one base unit. Even if the admin notices the inflated total and never opens claims, the sale is ruined for every depositor.

        ##### How it works

        1. Mallory sends ExecuteMsg::Deposit { amount: 1600 INJ } with funds of 1 base unit of the raising denom (contract.rs:59).

        2. deposit() checks only that one coin with the right denom is attached, never its amount (contract.rs:175).

        3. deposit() adds the claimed amount to her user record and to total_amount (contract.rs:186, 190).

        4. After the admin flips allow_claim, harvest() computes user_allocation from the inflated user.amount and total_amount (contract.rs:228-232).

        5. get_offering_amount() and get_refunding_amount() turn that allocation into a cw20 transfer of offering tokens and a bank send of the raising denom to Mallory (contract.rs:233-267, 430-468).

        6. The refund is paid from the real coins other depositors sent, which the contract never tracks separately.

        Exploit scenario

        Not specified.

        Recommendation

        Credit the coins that were actually attached. Either remove the amount field from ExecuteMsg::Deposit and use info.funds[0].amount, or reject the call when info.funds[0].amount != amount. Fix the first-deposit NotFound bug in the same change so the corrected check is in place before deposits can work. To verify, add unit tests: a Deposit with amount 1000 and attached funds of 1 must fail; a Deposit with matching funds must record exactly the attached amount in both the user record and total_amount.

        Claude Security (Sonnet 5.5)

        create_pair never checks user-supplied native asset amounts against attached funds, so the factory's own native balance funds the initial liquidity

        contracts/dojoswap_factory/src/contract.rs:324 Predicted severity: Low

        Root cause

        Vulnerable symbol: reply

        Preconditions: At least one native denom is allowlisted and the factory holds a nonzero balance of it. This is guaranteed by add_native_token_decimals.; The attacker controls a cw20 contract, or uses any token for which no pair with that denom exists yet.

        Offending code:

        funds.push(coin(asset.amount.u128(), denom.to_string()));

        Impact

        Anyone can drain native tokens held by the factory: the verification dust for each allowlisted denom, plus any native funds stranded there by users who attach funds to CreatePair. The cost to the attacker is nothing. The loss is limited to the factory's balances. Users who attach funds to CreatePair without matching assets amounts also have those funds locked permanently.

        Description

        The permissionless execute_create_pair stores caller-supplied assets[].amount in TMP_PAIR_INFO without calling Asset::assert_sent_native_token_balance(&info), and info.funds is never read. reply then forwards coin(asset.amount, denom) from the factory's own bank balance as funds to the pair's ProvideLiquidity, with receiver set to the caller, so the LP tokens go to the attacker. Also CWE-862: The untrusted caller of the permissionless execute_create_pair supplies assets[].amount. It is saved to TMP_PAIR_INFO without comparing it to info.funds. The reply handler then attaches that amount in native coins to the pair's ProvideLiquidity from the factory's own balance, and the LP tokens are minted to the caller. Also CWE-1284: The caller supplies assets[i].amount in execute_create_pair, which never inspects info.funds. The factory's reply then forwards those unverified amounts as funds on a ProvideLiquidity call to the new pair, so the bank transfer comes out of the factory's own native balance. The pair's assert_sent_native_token_balance only compares the declared amount with what the factory attached, so the check passes whatever the creator paid.

        Exploit scenario

        1) The owner allowlists native denom X, which by design requires the factory to hold a nonzero balance of X (contract.rs:241-248). 2) The attacker deploys a cw20 token T that returns plausible decimals to TokenInfo and whose TransferFrom and IncreaseAllowance succeed without moving anything. 3) The attacker calls CreatePair with assets = [{NativeToken X, amount = factory's X balance}, {Token T, amount = any}], attaching no funds. 4) execute_create_pair passes because X is allowlisted and T answers TokenInfo. 5) reply sends coin(factory_balance, X) from the factory to the new pair's ProvideLiquidity, and the pair's assert_sent_native_token_balance passes because the funds really are attached. 6) LP tokens are minted to the attacker. 7) The attacker withdraws liquidity and receives nearly all of the factory's X, minus the locked MINIMUM_LIQUIDITY share. The attacker repeats this with a new T for each pair. Native funds that honest users attach to CreatePair stay in the factory with no withdrawal path, and an attacker can claim them the same way.

        Recommendation

        In execute_create_pair, call asset.assert_sent_native_token_balance(&info) for each asset. Also reject any info.funds coin that is not matched by an asset. Alternatively, record the funds actually received and cap the native amounts used in reply at that value. Refuse zero-amount native funds entries, since they make the ProvideLiquidity message invalid. The factory should never pay out of its own balance. Also CWE-862: In execute_create_pair, require that the native funds in info.funds exactly match the declared native asset amounts, for example with Asset::assert_sent_native_token_balance(&info) for both assets. Reject any extra denoms. Store the verified amounts in TMP_PAIR_INFO. Alternatively, spend only what this call attached, and refund or reject any surplus. Consider clearing TMP_PAIR_INFO after the reply. Also CWE-1284: In execute_create_pair, call assert_sent_native_token_balance(&info) on both assets and reject any extra funds, so that only the caller's own funds are forwarded. Alternatively, forward info.funds itself rather than the factory's balance. Also consider a rescue path for stranded funds.

        Vercel Security Review

        CreatePair lets callers convert the factory's native balances into their own LP tokens

        contracts/dojoswap_factory/src/contract.rs:323 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Caller-declared amounts spend factory funds** - contracts/dojoswap_factory/src/contract.rs:322-324

        ```rust title="contracts/dojoswap_factory/src/contract.rs:322-324"

        for asset in tmp_pair_info.assets.iter() {

        if let AssetInfoRaw::NativeToken { denom, .. } = &asset.info {

        funds.push(coin(asset.amount.u128(), denom.to_string()));

        ```

        New permissionless CreatePair never matches native amounts to info.funds. If the factory holds sufficient registered-denomination funds, anyone can contribute their own CW20 and spend that native balance without supplying it.

        **2. The caller receives the resulting liquidity ownership** - contracts/dojoswap_factory/src/contract.rs:351-354

        ```rust title="contracts/dojoswap_factory/src/contract.rs:351-354"

        msg: to_json_binary(&PairExecuteMsg::ProvideLiquidity {

        assets,

        receiver: Some(tmp_pair_info.sender.to_string()),

        deadline: None,

        ```

        The factory-funded contribution earns LP tokens for the attacker.

        **3. LP redemption transfers the assets to the attacker** - contracts/dojoswap_pair/src/contract.rs:470-473

        ```rust title="contracts/dojoswap_pair/src/contract.rs:470-473"

        Ok(Response::new()

        .add_messages(vec![

        refund_assets[0].clone().into_msg(sender.clone())?,

        refund_assets[1].clone().into_msg(sender.clone())?,

        ```

        Redeeming those LP tokens extracts the native funds, subject to minimum locked liquidity.

        Exploit scenario

        Not specified.

        Recommendation

        In execute_create_pair, validate that every declared native contribution exactly matches the corresponding coin in info.funds before saving temporary state or instantiating the pair. Reject unmatched or excess attached funds, and never satisfy a caller's contribution from pre-existing factory balances.

      • FEE_COLLECTOR address can reconfigure pair assets and enable drains dojoswap-2 · 4 writeups High

        V12

        Self-backed LP reserves enable disproportionate swaps

        contracts/dojoswap_pair/src/contract.rs:159 Predicted severity: High

        Root cause

        The configuration path permits the LP liability token to become a reserve asset of the same pair. Swap accounting then treats the pair's locked LP holdings as independent collateral and bypasses total-supply-based redemption accounting.

        Impact

        After this authorized self-referential configuration, an LP holder can exchange a small fraction of total shares for a large fraction of the independent reserve, depleting backing for other holders. The path uses the legitimately created LP token and its actual transfer hook; it does not require a malicious token deployment or forged caller.

        Description

        admin_configure can select the pair's own retained LP token as one of its reserve assets. The pair already holds 1,000 locked LP units from initial liquidity issuance, so that selection creates an apparently funded reserve without adding independent collateral. The CW20 swap hook then accepts the LP token as a configured offer token and prices it against the other reserve using those 1,000 units rather than total LP supply. For an original one-million-unit liquidity issuance and a one-million-unit native reserve, replacing the other asset with the LP token permits a 1,000-LP swap to return 498,500 native units after commission. This requires the fixed fee collector to configure the self-referential reserve, but the subsequent exchange is a normal LP-token Send hook and does not burn the offered LP tokens.

        Codex Security (GPT-6 Sol)

        Fee collector can turn one pair reserve into two withdrawal claims

        contracts/dojoswap_pair/src/contract.rs:147 Predicted severity: Low

        Root cause

        The pair grants AdminConfigure to the hard-coded fee collector and accepts any two asset identities, including duplicates, after liquidity exists. The withdrawal path treats the two slots as independent reserves even when they point to one balance.

        Impact

        Other LP providers' assets can be lost, but the attacker must control the designated fee collector account and hold LP tokens. The factory owner has separate migration authority; no public caller can invoke AdminConfigure.

        Description

        AdminConfigure lets the hard-coded fee collector replace a pair's assets with the same asset twice. WithdrawLiquidity then reads that reserve twice and emits two refunds for a single LP burn, allowing a fee-collector-controlled LP position to overdraw other providers' reserve.

        Exploit scenario

        Collector AdminConfigure -> duplicate PAIR_INFO assets -> duplicated reserve query -> two refunds on one LP burn

        Recommendation

        Use the intended pair-administration authority, reject duplicate assets, and prohibit reserve-identity changes while liquidity exists unless migration explicitly accounts for balances.

        Devin Security

        Hard-coded fee collector address can rewrite any live pool's assets and drain it

        contracts/dojoswap_pair/src/contract.rs:40 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Whoever holds the single hard-coded fee collector key can swap out the asset list of any live pool and empty every liquidity provider's deposits from every pair.

        ##### What's wrong

        This is an over-privileged backdoor admin. admin_configure lets the fixed address FEE_COLLECTOR replace asset_infos and asset_decimals of a pool that already holds funds. Nothing checks that the pool is empty or that the new assets match the old ones. The address is compiled into the code, so it cannot be changed or revoked, and it is not the factory owner.

        ##### Who can do it

        Alice and other liquidity providers deposit tokens into a DojoSwap pair. Mallory gets control of the fee collector key, either as an insider or by stealing the key. She calls AdminConfigure on Alice's pair and replaces one of the pool assets with a cw20 token she created.

        - Mallory controls the private key for the hard-coded FEE_COLLECTOR address.

        - The target pair holds liquidity.

        ##### What they get

        After the change, the pair prices swaps using the pair's balance of Mallory's worthless token. She sends that token in through the Swap hook and takes out the real asset. She can also point both entries at assets that hide the real balances, which leaves the LP tokens unredeemable. She can do this to every pair created from this code. Every liquidity provider in every pool can lose their deposit.

        ##### How it works

        1. Mallory calls ExecuteMsg::AdminConfigure on a pair; the only check is info.sender == FEE_COLLECTOR at contracts/dojoswap_pair/src/contract.rs:155.

        2. The handler overwrites PAIR_INFO.asset_infos and asset_decimals with her values at contracts/dojoswap_pair/src/contract.rs:161-168.

        3. swap and withdraw_liquidity read pool balances from the new asset_infos via query_pools, so her fake token becomes one side of the pool.

        4. She swaps her fake token for the remaining real asset, and the pair sends it to her at contracts/dojoswap_pair/src/contract.rs:569.

        Exploit scenario

        Not specified.

        Recommendation

        Remove AdminConfigure from the pair, or limit it to fixing asset_decimals. If you keep it, gate it on the factory or a governance address stored in state. Also refuse to change asset_infos while the LP token's total supply is non-zero. To check the fix, add a test that provides liquidity and then calls AdminConfigure with a different asset. Assert that the call fails and that PAIR_INFO is unchanged.

        Devin Security (Deep)

        Hard-coded fee collector key can re-point a live pair's assets and drain its reserves

        contracts/dojoswap_pair/src/contract.rs:40 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Whoever holds the single hard-coded fee collector key can swap out the assets of any live pool and take all of the liquidity providers' deposits in every pair, and the key can never be rotated.

        ##### What's wrong

        This is an unrestricted privileged configuration path. AdminConfigure lets one fixed external account overwrite asset_infos and asset_decimals of a pair that already holds funds, and every later balance, authorization and swap calculation trusts the new values.

        ##### Who can do it

        Alice and many other users at Acme Capital provide liquidity to the INJ/USDT pair. Mallory controls the private key for the address stored in FEE_COLLECTOR (either as a malicious insider or because she stole the key). She deploys a worthless cw20 token, calls AdminConfigure on the pair with assets: [her_token, USDT], then swaps a large amount of her token into the pair.

        Conditions that must hold:

        - Mallory can sign with the private key for the hard-coded FEE_COLLECTOR address at contracts/dojoswap_pair/src/contract.rs:40.

        - The target pair holds reserves (any live pair).

        ##### What they get

        Mallory receives nearly all of the pair's USDT in exchange for her worthless token, then repeats the trick with assets: [her_token, INJ] to take the INJ side. She can do this to every pair deployed from this code, so every liquidity provider on the exchange loses their deposits. She can also set asset_decimals to values that differ by more than 19, which makes every swap on the pair abort, freezing trading until she changes it back. Because the address is a compile-time constant with no update path, Acme cannot revoke the key without redeploying and migrating every pair.

        ##### How it works

        1. admin_configure at contract.rs:147-171 accepts the call when info.sender equals the constant FEE_COLLECTOR and overwrites PAIR_INFO.asset_infos and asset_decimals while keeping the same LP token.

        2. receive_cw20 at contract.rs:189-203 authorizes a cw20 swap if the sending token contract matches any entry in the current asset_infos, so Mallory's token is now accepted as an offer asset.

        3. swap at contract.rs:512-547 reads the pair's balances of the new asset list. The offer pool of Mallory's token is tiny and the ask pool is the real USDT reserve, so compute_swap returns almost the entire ask pool.

        4. The return asset is sent to Mallory at contract.rs:565-570.

        5. Separately, assert_max_spread at contract.rs:808 and contract.rs:822 computes 10u64.pow(diff) from the stored decimals on every swap, so a decimals gap above 19 overflows and aborts all swaps.

        Exploit scenario

        Not specified.

        Recommendation

        Remove AdminConfigure from the pair, or restrict it so it cannot change asset_infos once the pair holds liquidity (for example, only allow it while both pool balances and the LP total supply are zero) and cap asset_decimals at 18. Move the fee collector address into contract state that the factory owner can update, instead of a hard-coded constant. To check the fix, add tests that AdminConfigure is rejected on a pair with non-zero reserves and that the fee recipient can be rotated through the new update path.

    • Ebridge Solidity aelf bridge to Ethereum. Tasks 3 V12 3/3 Codex Sec 0/3 Pashov Opus 2/3 Pashov GPT-6 1/3 Devin 0/3 Devin (Deep) 0/3 Claude Sec 0/3 Claude Opus 0/3 Vercel 0/3

      aelf bridge to Ethereum.

      Read the audit report
      • MerkleTree usage complexity ebridge-1 · 2 writeups High

        V12

        Permitted tree depths make receipt processing unexecutable

        contracts/MerkleTreeImplementation.sol:80 Predicted severity: High

        Root cause

        _leavesToTree sizes memory from maximum configured capacity rather than actual nodes, and both recording and proof generation rebuild all stored leaves. Configuration validation enforces mathematical depth bounds without an execution-budget bound or an incremental tree algorithm.

        Impact

        For a swap configured with an unexecutable depth, hash-only receipt transmission cannot complete, preventing the corresponding proof-based payouts despite available deposited liquidity. Changing the global default affects only future spaces, not that swap's stored space; this is conditional claim-path unavailability, with an alternative signed direct-payment branch and owner-authorized upgrades still present.

        Description

        createSpace accepts depth 20, but _generateMerkleTree passes twice the configured leaf capacity to _leavesToTree, which allocates that entire array even for a single leaf. At depth 20 this is 2,097,152 words, or 64 MiB, with an EVM memory-expansion lower bound of 8,596,226,048 gas before copying or hashing. The same allocation occurs when getMerklePath rebuilds a tree during claim verification. BridgeOut's wallet setter permits depth 20, and createSwap permanently assigns the newly created space to that swap, so successful swap creation does not establish that recording or proof generation is executable. Independently of the upfront allocation, each append and path request copies the entire current leaf set and rebuilds its tree, so work also grows with occupancy. This is a source-derived gas failure for permitted large depths on chains with transaction/block budgets below that lower bound, not evidence that the depth-10 test configuration or a particular deployed swap has failed.

        Pashov (Claude Opus 5.5 high)

        MerkleTree space depth can be set up to 20, which makes recordMerkleTree exceed the block gas limit and permanently freezes the swap

        contracts/BridgeOutImplementationV1.sol:119 Predicted severity: Low

        Root cause

        O(n) work and O(maxLeafCount) memory allocation per insertion, with an upper bound on depth that is far above what fits in a block.

        Impact

        Short reports for a swap created with a large depth can never be recorded and no Merkle-path redemption works. Users' cross-chain transfers for that token become unredeemable, and the token key cannot be re-registered with a fresh swap.

        Description

        Every recordMerkleTree call rebuilds the whole tree. It allocates new bytes32[](maxLeafCount*2) in memory, reads every stored leaf with EnumerableSet.values(), and rehashes every node. setDefaultMerkleTreeDepth accepts depths up to 20 (2^21-word memory arrays). From about depth 16, quadratic memory expansion alone costs more than the block gas limit, even for the first leaf. Smaller depths also become unusable as the tree fills up. A space's pathLength cannot be changed after createSpace, and a token key can only be bound to one swap.

        Exploit scenario

        Governance sets defaultMerkleTreeDepth = 20 to get capacity, then creates a swap. Every transmit() with a short report reverts out of gas, so receipts for that token cannot be settled through the Merkle path.

        Recommendation

        Cap the depth at a value whose worst case fits comfortably in a block (for example 10 or lower), or use an incremental Merkle tree that updates O(depth) nodes per insertion.

      • Front-running gas attack can cancel transaction ebridge-2 · 3 writeups Medium

        V12

        Failed calls consume approved proposals

        contracts/MultiSigWallet.sol:211 Predicted severity: Low

        Root cause

        The success-independent executed marker consumes a proposal's authorization even when the external call fails. The decodable failure branch records the error but provides neither rollback nor retry state.

        Impact

        A failed administrative operation can lose its existing approvals and require another submission and quorum round before it can take effect. Inference: where an executable proposal encounters a transient failure, permissionless execution permits timing-based invalidation of that proposal; permanent wallet-fund lockup is not supported.

        Description

        Execution sets transaction.executed = true before calling the destination and does not reset it when the destination returns a decodable Error(string) failure. The failure event therefore commits alongside an executed flag even though the approved operation did not occur. The tests explicitly exercise this behavior and assert that failed membership calls remain marked executed. An arbitrary execution caller can consume an already executable proposal during a transient destination failure; for example, BridgeIn.restart rejects execution while the bridge is not paused. This affects the existing proposal's authorization and retry lifecycle, not all wallet funds, because members can submit and approve a replacement.

        Pashov (Claude Opus 5.5 high)

        MultiSigWallet failure handling: failed calls are permanently marked executed, and non-string revert data makes confirmation revert

        contracts/MultiSigWallet.sol:211 Predicted severity: Low

        Root cause

        Not resetting executed on failure, plus fragile parsing of revert reasons.

        Impact

        Governance transactions can be burned or griefed. An attacker can trigger a confirmed transaction when it will revert with a string reason (for example while the bridge is paused or a limit check fails), forcing members to re-submit and re-collect signatures. Transactions whose target reverts with custom errors cannot have their last confirmation recorded. This delays emergency actions such as restart or pause-controller changes.

        Description

        executeTransaction sets transaction.executed = true before the external call and never resets it on failure, unlike the reference Gnosis implementation. A transaction that fails once, for example because it is executed at an unfavourable moment, can never be retried. It is also publicly callable, so once a transaction is confirmed (including when a requirement change or member removal makes a pending transaction confirmed), anyone can choose when it runs. In the failure branch, the code does new bytes(returnData.length-4) and abi.decode(..., (string)). This underflows for empty revert data (out of gas, bare revert) and fails for custom errors such as Limiter's DailyLimitExceeded or Panic. The whole call reverts, so the final confirmTransaction cannot be recorded.

        Exploit scenario

        After removeMember lowers required, a pending transaction (BridgeIn.restart) becomes confirmed. While the bridge is not paused, an attacker calls executeTransaction(id). The inner call reverts with 'not paused', the transaction is marked executed with ExecutionFailure, and governance must redo it.

        Recommendation

        On failure, set transaction.executed = false (or revert). Decode revert data defensively: check the length and the Error(string) selector before decoding.

        Pashov (Codex GPT-6 Sol high)

        Failed multisig calls are marked executed and cannot be retried

        audit/contracts/MultiSigWallet.sol:216 Predicted severity: Medium

        Root cause

        The failure branch does not reset executed after an unsuccessful external call.

        Impact

        Approved governance, upgrade, or asset-transfer actions cannot be retried after temporary failure; members must create and reconfirm a new transaction.

        Description

        The wallet sets transaction.executed before calling the destination. If the call fails with a standard Error(string), the function emits ExecutionFailure but leaves executed true. A transient destination failure therefore permanently consumes the approved transaction.

        Exploit scenario

        A confirmed transfer call fails while the target is paused. The wallet records it executed; after the target restarts, executeTransaction rejects the same transaction as already executed.

        Recommendation

        Set executed back to false on failed calls or revert the entire wallet execution so the transaction remains retryable.

      • Special considerations for seed liquidity ebridge-3 · 1 writeup Medium

        V12

        Claims leave stale separate inventory withdrawal credits

        contracts/BridgeInImplementation.sol:301 Predicted severity: Informational

        Root cause

        depositAmount tracks historical separate deposits minus owner withdrawals, while tokenDepositAmount tracks pooled inventory minus both withdrawals and claims. No shared consumption or reconciliation rule connects the counters.

        Impact

        The local counter is not a reliable measure of remaining separate reserves: it can authorize an owner-only withdrawal against later receipt-funded inventory or allow an amount that the downstream balance cannot satisfy. Whether this constitutes withdrawal beyond the owner's authorized reserve entitlement is unresolved; the missing fact is the reserve-consumption and ownership rule after claims spend contributed liquidity. The searched boundary was both bridge implementations, the BridgeOut interface, inventory and claim tests, and deployment examples; none defines such a rule or provides reconciliation.

        Description

        depositAmount is increased when BridgeIn forwards separate inventory and decreased only when its owner withdraws. BridgeOut places that inventory in the same tokenDepositAmount used by receipts, direct deposits, and claim settlement. A claim can therefore spend a separate inventory contribution without reducing the corresponding BridgeIn counter. For example, after a contribution of 100 and claims totaling 100, BridgeIn still reports 100 while downstream inventory is zero; after another receipt contributes 100, the old local credit again permits an owner withdrawal of 100. Removal and re-addition preserve this stale credit rather than starting a new accounting epoch.

    • Etherfi Solidity EtherFi liquid restaking. Tasks 9 V12 9/9 Codex Sec 1/9 Pashov Opus 5/9 Pashov GPT-6 3/9 Devin 3/9 Devin (Deep) 5/9 Claude Sec 4/9 Claude Opus 5/9 Vercel 3/9

      EtherFi liquid restaking.

      Read the audit report
      • Repeated validator IDs could be passed in batchRevertExitRequest etherfi-1 · 5 writeups Critical

        V12

        Exit request counters diverge from validator requests

        src/EtherFiNodesManager.sol:129 Predicted severity: High

        Root cause

        The manager updates a safe-wide exit-request counter without enforcing per-validator pending-to-cleared transitions. A single timestamp cannot represent multiple increments, and an absent timestamp does not prevent a decrement.

        Impact

        An excess counter blocks reward withdrawals for other validators sharing the safe through PENDING_EXIT_REQUEST, including after the requested validator has been fully withdrawn. An unmatched reversal can instead bypass the pending-request reward restriction and make later unregistering the genuinely requested validator revert on counter underflow, obstructing its principal withdrawal.

        Description

        batchSendExitRequest increments the safe-wide numExitRequestsByTnft every time a LIVE validator is supplied, without checking its existing exitRequestTimestamp. Its phase remains LIVE, so the T-NFT owner can submit the same ID twice, either in one batch or in separate transactions, while only one timestamp is stored. batchRevertExitRequest decrements the same counter without requiring an outstanding request for the supplied validator. EtherFiNode.unRegisterValidator subtracts only once for a nonzero timestamp, leaving excess requests after that validator is fully withdrawn. Conversely, on a shared safe, reverting a validator that never requested exit can clear another validator's aggregate request count without clearing its timestamp.

        Pashov (Claude Opus 5.5 high)

        Missing exit-request state checks let T-NFT holders desync numExitRequestsByTnft and permanently block partial withdrawals of recycled or shared safes

        src/EtherFiNodesManager.sol:129 Predicted severity: Medium

        Root cause

        Send and revert are not idempotent: the !isExitRequested / isExitRequested guards are missing, while the counter lives at safe level and survives recycling.

        Impact

        Liveness and asset freeze. Staking rewards in the affected safe cannot be distributed via partialWithdraw for any future validator using it. The LiquidityPool, as T-NFT holder of most validators, has no function to revert exit requests, so its validators placed in such a safe stay stuck until they exit. Shared safes can also be pushed into an inconsistent state that makes fullWithdraw revert on counter underflow.

        Description

        batchSendExitRequest does not check that the validator has no pending exit request, and batchRevertExitRequest does not check that one exists (nor that the validator is LIVE). Each call adjusts the per-safe counter numExitRequestsByTnft by +/-1 and overwrites exitRequestTimestamp. A T-NFT holder can therefore send the request N times, which raises the counter N times for a single validator. When the validator is fully withdrawn, EtherFiNode.unRegisterValidator decrements the counter only once (if (_info.exitRequestTimestamp != 0)). The safe goes back to unusedWithdrawalSafes with a non-zero numExitRequestsByTnft, because nothing resets it on recycling. Every later validator allocated that safe fails _getTotalRewardsPayoutsFromSafe with PENDING_EXIT_REQUEST, so partialWithdraw and batchPartialWithdrawOptimized revert, and so does the view getRewardsPayouts. Other combinations also corrupt the state: revert without a request (wipes the timestamp while decrementing a counter that belongs to sibling validators), or send then revert after EXITED.

        Exploit scenario

        1. The attacker (a delegated staker, or anyone who buys a transferable T-NFT) calls batchSendExitRequest([id, id, id]). The safe's counter becomes 3.

        2. The validator exits and fullWithdraw runs. The counter drops to 2, the validator count reaches 0, and the safe is pushed to unusedWithdrawalSafes.

        3. With recycling enabled, the LP's next validator is allocated this safe. Every partialWithdraw for it reverts with PENDING_EXIT_REQUEST. Rewards build up until the safe reaches 16 ETH, and the validator then has to exit.

        Recommendation

        In batchSendExitRequest add require(!isExitRequested(_validatorId), "ASKED"). In batchRevertExitRequest add require(isExitRequested(_validatorId), "NOT_ASKED") (and preferably a LIVE phase check). Reset numExitRequestsByTnft and numExitedValidators (or assert they are zero) when a safe is recycled.

        Devin Security

        Repeated exit requests leave a stale exit-request counter on a safe that is later recycled

        src/EtherFiNodesManager.sol:129 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A T-NFT holder can permanently block reward payouts for the next validator that gets the recycled safe, delaying (but not stealing) another party's rewards until that validator exits.

        ##### What's wrong

        This is a counter-desync bug. batchSendExitRequest adds 1 to the safe's numExitRequestsByTnft on every call, even when the validator already has a pending request. Unregistering subtracts only 1. The leftover count stays on the safe when it goes back into the reuse pool. batchRevertExitRequest also never checks that a request exists before it subtracts.

        ##### Who can do it

        Mallory stakes 32 ETH through the public solo StakingManager.batchDepositWithBidIds and gets her own T-NFT. She can also buy a single-validator T-NFT on the open market. She calls batchSendExitRequest([id]) twice, exits, and lets fullWithdraw run. Her safe goes into unusedWithdrawalSafes with numExitRequestsByTnft == 1. Later Bob, a B-NFT holder, spins up a pool-funded validator, and node recycling hands him that safe.

        - Mallory owns the T-NFT of a LIVE validator.

        - An admin has enabled enableNodeRecycling.

        ##### What they get

        Every partialWithdraw, batchPartialWithdrawOptimized, and admin forcePartialWithdraw on Bob's validator reverts with PENDING_EXIT_REQUEST. Rewards for Bob, the node operator, the treasury, and the pool's eETH holders build up in the safe and cannot be skimmed. They are paid out only after Bob's validator exits and is fully withdrawn. No funds are stolen.

        ##### How it works

        1. batchSendExitRequest checks only T-NFT ownership and the LIVE phase, then calls updateNumExitRequests(1, 0) each time (EtherFiNodesManager.sol:129-144).

        2. EtherFiNode.unRegisterValidator subtracts 1 only if exitRequestTimestamp != 0 (EtherFiNode.sol:133). It does not reset the counter when the safe becomes empty (EtherFiNode.sol:148-152).

        3. _unRegisterValidator pushes the empty safe into unusedWithdrawalSafes (EtherFiNodesManager.sol:497-499). allocateEtherFiNode reuses it for a new validator (EtherFiNodesManager.sol:326-329).

        4. _getTotalRewardsPayoutsFromSafe requires numExitRequestsByTnft() == 0 and reverts for the new validator (EtherFiNodesManager.sol:513).

        Exploit scenario

        Not specified.

        Recommendation

        In batchSendExitRequest, add 1 only when validatorInfos[id].exitRequestTimestamp == 0. In batchRevertExitRequest, require a pending request (exitRequestTimestamp != 0) and the LIVE phase. Reset numExitRequestsByTnft and numExitedValidators to 0 when unRegisterValidator empties a safe. To check the fix, add a test that sends two exit requests, fully withdraws, re-allocates the recycled safe to a new validator, and asserts that partialWithdraw succeeds.

        Devin Security (Deep)

        Exit request counter on a shared withdrawal safe can be driven out of sync, blocking withdrawals

        src/EtherFiNodesManager.sol:129 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A T-NFT holder can repeat or revert exit requests on validators in a shared withdrawal safe to leave the safe's exit counter wrong, which can permanently block the bond holder's and node operator's withdrawals for validators in that safe, but the attacker locks their own principal as well.

        ##### What's wrong

        This is a state desynchronization bug. batchSendExitRequest increments a per-safe counter every time it is called for the same validator, and batchRevertExitRequest decrements it even when that validator has no open request, while unRegisterValidator only decrements once per validator based on a stored timestamp.

        ##### Who can do it

        Bob is a solo staker whose two validators share one withdrawal safe. Bob sold the T-NFT for validator A to Mallory, who also holds the T-NFT for validator B in the same safe. Mallory calls batchSendExitRequest([A]) and then batchRevertExitRequest([B]), which has no open request.

        - The attacker holds the T-NFT for at least one validator in a shared safe.

        - The validators are in the LIVE phase and the contract is not paused.

        ##### What they get

        After the revert call, the counter is 0 while validator A still has an exit timestamp. When A later exits and anyone calls fullWithdraw(A), unRegisterValidator tries to subtract 1 from a zero uint16 and reverts, so A's full withdrawal is stuck until another LIVE validator in the same safe gets an exit request. This locks Bob's 2 ETH bond and the operator's share for A, and also Mallory's own 30 ETH. In the repeated-send variant, after A is fully withdrawn the counter stays above zero and partialWithdraw for the remaining validators reverts with PENDING_EXIT_REQUEST until the T-NFT holder reverts it. This is availability harm only, confined to one safe.

        ##### How it works

        1. batchSendExitRequest (src/EtherFiNodesManager.sol:129-144) checks ownership and LIVE phase but never checks whether exitRequestTimestamp is already set, then calls updateNumExitRequests(1, 0).

        2. batchRevertExitRequest (src/EtherFiNodesManager.sol:148-161) checks ownership but never checks that a request exists, then calls updateNumExitRequests(0, 1) and zeroes the timestamp.

        3. EtherFiNode.updateNumExitRequests (src/EtherFiNode.sol:160-163) applies the raw add and subtract to the shared numExitRequestsByTnft.

        4. EtherFiNode.unRegisterValidator (src/EtherFiNode.sol:119-154) decrements the counter only once if the validator's stored timestamp is nonzero, so a mismatch causes a uint16 underflow revert inside fullWithdraw, or a stuck nonzero counter that blocks _getTotalRewardsPayoutsFromSafe (src/EtherFiNodesManager.sol:513).

        Exploit scenario

        Not specified.

        Recommendation

        In batchSendExitRequest, require validatorInfos[id].exitRequestTimestamp == 0 before incrementing. In batchRevertExitRequest, require validatorInfos[id].exitRequestTimestamp != 0 before decrementing. Add tests that send the same exit request twice and revert a request that does not exist, and assert both revert.

        Claude Security (Opus 5.5)

        Repeated or duplicate validator IDs in batchSendExitRequest inflate numExitRequestsByTnft, which permanently blocks reward withdrawals for the safe and for any validator later given the recycled safe

        src/EtherFiNodesManager.sol:139 Predicted severity: Medium

        Root cause

        Vulnerable symbol: batchSendExitRequest

        Preconditions: Attacker holds the T-NFT of a LIVE validator (anyone can mint one through delegated staking or buy one, since T-NFTs are transferable when the safe has exactly one validator); Reaching other users' validators also needs enableNodeRecycling == true (an admin setting that the test setup turns on) and the attacker's validator to exit and be fully withdrawn

        Offending code:

        IEtherFiNode(etherfiNode).updateNumExitRequests(1, 0);

        Impact

        Permanent denial of service on reward skimming (partialWithdraw, batchPartialWithdraw, batchPartialWithdrawOptimized, forcePartialWithdraw) for the affected safe. Rewards owed to T-NFT holders (including eETH holders through the LP), B-NFT stakers, node operators and the treasury stay frozen until every validator in the safe exits and is fully withdrawn, or the contract is upgraded. The bad state follows the safe through recycling and reaches unrelated users. Principal is not stolen.

        Description

        The T-NFT holder supplies the _validatorIds array. batchSendExitRequest never checks that the validator does not already have a pending exit request (validatorInfos[id].exitRequestTimestamp == 0), so passing the same ID twice, or calling twice, increments the safe's numExitRequestsByTnft counter once per entry. The counter is only ever decremented once per validator: once in batchRevertExitRequest at :157, which also has no isExitRequested check, and once in EtherFiNode.unRegisterValidator at :133, which runs only if the timestamp is non-zero. Also CWE-459: A T-NFT holder can call batchSendExitRequest repeatedly, or pass the same validatorId many times, because there is no exitRequestTimestamp == 0 check. Each call increments the safe-wide counter, but unRegisterValidator decrements it only once (EtherFiNode.sol:133). When the safe's last validator leaves, it is pushed to unusedWithdrawalSafes (line 498) without resetting the counter. allocateEtherFiNode (lines 326-336) later hands it, still dirty, to a new validator. Also CWE-841: batchSendExitRequest never checks whether the validator already has an exit request, so the T-NFT holder can raise the safe-wide counter several times for one validator. unRegisterValidator decrements it at most once, and the safe is then pushed to unusedWithdrawalSafes without resetting the counter. The next validator allocated that safe always fails the PENDING_EXIT_REQUEST check.

        Exploit scenario

        Alice holds the T-NFT of validator V, which sits alone in safe S (a delegated-staking T-NFT, or one bought on the secondary market). She calls batchSendExitRequest([V, V]), so S.numExitRequestsByTnft becomes 2. (Path a) She calls batchRevertExitRequest([V]) once: the counter drops to 1 and the timestamp is cleared, so no non-exit penalty applies to the B-NFT holder. partialWithdraw(V) and the admin's forcePartialWithdraw(V) now revert with PENDING_EXIT_REQUEST, so the B-NFT holder, the operator and the treasury cannot collect rewards. (Path b) After V exits and anyone calls fullWithdraw(V), unRegisterValidator decrements the counter only once, leaving 1, and S goes back into unusedWithdrawalSafes. With enableNodeRecycling on, the next validator allocated to S inherits numExitRequestsByTnft == 1. This could be a LiquidityPool (eETH) validator, plus any validators the LP later adds to S through _validatorIdToShareWithdrawalSafe. Their partialWithdraw and forcePartialWithdraw revert permanently. The LP has no path to batchRevertExitRequest, so only a contract upgrade can clear the counter, and every later fullWithdraw recycles S with the bad counter still set.

        Recommendation

        In batchSendExitRequest, add require(validatorInfos[_validatorId].exitRequestTimestamp == 0, "ASKED"). In batchRevertExitRequest, add require(validatorInfos[_validatorId].exitRequestTimestamp != 0, "NOT_ASKED"). As defense in depth, reset numExitRequestsByTnft and numExitedValidators when a safe is recycled (in unRegisterValidator when the last validator is removed, or in registerValidator when numAssociatedValidators() == 0). Also CWE-459: In batchSendExitRequest, reject validators whose exitRequestTimestamp is already non-zero. In batchRevertExitRequest, require a pending request. When a safe is recycled (numAssociatedValidators()==0 in unRegisterValidator), reset numExitRequestsByTnft and numExitedValidators to 0. Also CWE-841: Add require(!isExitRequested(id)) to batchSendExitRequest and require(isExitRequested(id)) to batchRevertExitRequest. Reset numExitRequestsByTnft (and numExitedValidators) when a safe's associated-validator count reaches zero.

      • Repeated validator IDs could be passed in batchSendExitRequest etherfi-2 · 7 writeups Critical

        V12

        Surplus exit requests poison recycled withdrawal safes

        src/EtherFiNode.sol:129 Predicted severity: High

        Root cause

        The request counter is incremented per call while deregistration decrements per validator, and the safe's terminal reset does not clear surplus request counts. The manager's timestamp overwrite permits those two counting models to diverge.

        Impact

        A T-NFT owner can leave a reusable safe poisoned for a subsequent validator, preventing its normal reward withdrawals. The same imbalance can block reward withdrawals for other validators currently sharing the safe; recycling additionally carries the block across distinct validator lifetimes.

        Description

        updateNumExitRequests adds a caller-supplied increment to a safe-wide counter without associating it with a validator request. The manager allows the T-NFT owner to send another exit request while the validator remains live, overwriting its single timestamp but incrementing this counter again. unRegisterValidator removes only one request count when that validator is withdrawn. When the last validator leaves, the node resets its restaking flags but does not reset the leftover request count, and the manager places the node in the reusable-safe stack. Reallocating that safe therefore gives an unrelated new validator a nonzero pending-request counter that blocks reward withdrawals despite having no exit request of its own.

        Pashov (Claude Opus 5.5 high)

        Missing exit-request state checks let T-NFT holders desync numExitRequestsByTnft and permanently block partial withdrawals of recycled or shared safes

        src/EtherFiNodesManager.sol:129 Predicted severity: Medium

        Root cause

        Send and revert are not idempotent: the !isExitRequested / isExitRequested guards are missing, while the counter lives at safe level and survives recycling.

        Impact

        Liveness and asset freeze. Staking rewards in the affected safe cannot be distributed via partialWithdraw for any future validator using it. The LiquidityPool, as T-NFT holder of most validators, has no function to revert exit requests, so its validators placed in such a safe stay stuck until they exit. Shared safes can also be pushed into an inconsistent state that makes fullWithdraw revert on counter underflow.

        Description

        batchSendExitRequest does not check that the validator has no pending exit request, and batchRevertExitRequest does not check that one exists (nor that the validator is LIVE). Each call adjusts the per-safe counter numExitRequestsByTnft by +/-1 and overwrites exitRequestTimestamp. A T-NFT holder can therefore send the request N times, which raises the counter N times for a single validator. When the validator is fully withdrawn, EtherFiNode.unRegisterValidator decrements the counter only once (if (_info.exitRequestTimestamp != 0)). The safe goes back to unusedWithdrawalSafes with a non-zero numExitRequestsByTnft, because nothing resets it on recycling. Every later validator allocated that safe fails _getTotalRewardsPayoutsFromSafe with PENDING_EXIT_REQUEST, so partialWithdraw and batchPartialWithdrawOptimized revert, and so does the view getRewardsPayouts. Other combinations also corrupt the state: revert without a request (wipes the timestamp while decrementing a counter that belongs to sibling validators), or send then revert after EXITED.

        Exploit scenario

        1. The attacker (a delegated staker, or anyone who buys a transferable T-NFT) calls batchSendExitRequest([id, id, id]). The safe's counter becomes 3.

        2. The validator exits and fullWithdraw runs. The counter drops to 2, the validator count reaches 0, and the safe is pushed to unusedWithdrawalSafes.

        3. With recycling enabled, the LP's next validator is allocated this safe. Every partialWithdraw for it reverts with PENDING_EXIT_REQUEST. Rewards build up until the safe reaches 16 ETH, and the validator then has to exit.

        Recommendation

        In batchSendExitRequest add require(!isExitRequested(_validatorId), "ASKED"). In batchRevertExitRequest add require(isExitRequested(_validatorId), "NOT_ASKED") (and preferably a LIVE phase check). Reset numExitRequestsByTnft and numExitedValidators (or assert they are zero) when a safe is recycled.

        Pashov (Codex GPT-6 Sol high)

        Duplicate exit requests leave a stale counter that blocks recycled safes

        audit/src/EtherFiNodesManager.sol:129 Predicted severity: Medium

        Root cause

        batchSendExitRequest has no check that exitRequestTimestamp is zero; unRegisterValidator decrements at most once for the single stored timestamp.

        Impact

        A later validator assigned the recycled safe cannot withdraw rewards while the stale counter remains; repeat requests can also shorten a BNFT non-exit penalty owed to operator and treasury.

        Description

        A TNFT holder can request the same validator exit repeatedly, incrementing a safe-wide counter more than once and overwriting the single timestamp that starts the non-exit penalty clock.

        Exploit scenario

        A holder submits [id,id] to batchSendExitRequest. On full withdrawal, the node decrements the counter once and enters the unused-safe pool with count one. A new validator assigned that safe hits PENDING_EXIT_REQUEST on reward payout. The holder can also repeat a request days later to reset the penalty start time.

        Recommendation

        Reject duplicate exit requests and enforce symmetry between each validator request timestamp and the safe-wide counter; verify the counter is zero before recycling.

        Devin Security

        Repeated exit requests leave a stale exit-request counter on a safe that is later recycled

        src/EtherFiNodesManager.sol:129 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A T-NFT holder can permanently block reward payouts for the next validator that gets the recycled safe, delaying (but not stealing) another party's rewards until that validator exits.

        ##### What's wrong

        This is a counter-desync bug. batchSendExitRequest adds 1 to the safe's numExitRequestsByTnft on every call, even when the validator already has a pending request. Unregistering subtracts only 1. The leftover count stays on the safe when it goes back into the reuse pool. batchRevertExitRequest also never checks that a request exists before it subtracts.

        ##### Who can do it

        Mallory stakes 32 ETH through the public solo StakingManager.batchDepositWithBidIds and gets her own T-NFT. She can also buy a single-validator T-NFT on the open market. She calls batchSendExitRequest([id]) twice, exits, and lets fullWithdraw run. Her safe goes into unusedWithdrawalSafes with numExitRequestsByTnft == 1. Later Bob, a B-NFT holder, spins up a pool-funded validator, and node recycling hands him that safe.

        - Mallory owns the T-NFT of a LIVE validator.

        - An admin has enabled enableNodeRecycling.

        ##### What they get

        Every partialWithdraw, batchPartialWithdrawOptimized, and admin forcePartialWithdraw on Bob's validator reverts with PENDING_EXIT_REQUEST. Rewards for Bob, the node operator, the treasury, and the pool's eETH holders build up in the safe and cannot be skimmed. They are paid out only after Bob's validator exits and is fully withdrawn. No funds are stolen.

        ##### How it works

        1. batchSendExitRequest checks only T-NFT ownership and the LIVE phase, then calls updateNumExitRequests(1, 0) each time (EtherFiNodesManager.sol:129-144).

        2. EtherFiNode.unRegisterValidator subtracts 1 only if exitRequestTimestamp != 0 (EtherFiNode.sol:133). It does not reset the counter when the safe becomes empty (EtherFiNode.sol:148-152).

        3. _unRegisterValidator pushes the empty safe into unusedWithdrawalSafes (EtherFiNodesManager.sol:497-499). allocateEtherFiNode reuses it for a new validator (EtherFiNodesManager.sol:326-329).

        4. _getTotalRewardsPayoutsFromSafe requires numExitRequestsByTnft() == 0 and reverts for the new validator (EtherFiNodesManager.sol:513).

        Exploit scenario

        Not specified.

        Recommendation

        In batchSendExitRequest, add 1 only when validatorInfos[id].exitRequestTimestamp == 0. In batchRevertExitRequest, require a pending request (exitRequestTimestamp != 0) and the LIVE phase. Reset numExitRequestsByTnft and numExitedValidators to 0 when unRegisterValidator empties a safe. To check the fix, add a test that sends two exit requests, fully withdraws, re-allocates the recycled safe to a new validator, and asserts that partialWithdraw succeeds.

        Devin Security (Deep)

        Duplicate exit requests leave a stale counter that blocks reward skimming on recycled withdrawal safes

        src/EtherFiNodesManager.sol:129 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A solo staker can leave a stale exit-request count on a withdrawal safe so that, after the safe is recycled, the next validators placed in it can never have their rewards skimmed and only get paid when they fully exit.

        ##### What's wrong

        This is a missing idempotency check. batchSendExitRequest increments the safe's numExitRequestsByTnft every time it is called for the same validator, but EtherFiNode.unRegisterValidator only decrements once and never resets the counter when the safe empties and is put back in the reuse pool.

        ##### Who can do it

        Mallory is a solo staker who put up 32 ETH, so she owns both the T-NFT and B-NFT of validator V, which sits alone in safe S. She calls batchSendExitRequest([V, V, V]), exits V on the beacon chain, the ether.fi oracle processes the exit, and anyone calls fullWithdraw(V). S now has numExitRequestsByTnft == 2 and is pushed onto unusedWithdrawalSafes. Later the pool's next validator is allocated S.

        - enableNodeRecycling is true (admin flag).

        - Mallory owns the T-NFT, which every solo staker does.

        ##### What they get

        This is griefing with no profit. Every validator later placed in S hits "PENDING_EXIT_REQUEST" in partialWithdraw, batchPartialWithdrawOptimized, and even the admin's forcePartialWithdraw, so staking rewards pile up in the safe until that validator exits. The pool has no function to call batchRevertExitRequest, so it cannot clear the counter for its own validators. Funds are delayed, not lost.

        ##### How it works

        1. batchSendExitRequest (src/EtherFiNodesManager.sol:129-144) only requires LIVE and T-NFT ownership and calls updateNumExitRequests(1, 0) on every call, including repeats for the same id (src/EtherFiNode.sol:160-163).

        2. On full withdrawal EtherFiNode.unRegisterValidator decrements the counter once when exitRequestTimestamp != 0 (src/EtherFiNode.sol:133) and, when the safe is empty, resets only the restaking fields (lines 148-152).

        3. _unRegisterValidator pushes the empty safe onto unusedWithdrawalSafes (src/EtherFiNodesManager.sol:497-499) and allocateEtherFiNode hands it to the next validator (lines 326-329).

        4. _getTotalRewardsPayoutsFromSafe requires numExitRequestsByTnft == 0 (line 513) and is used by every partial-withdrawal path.

        Exploit scenario

        Not specified.

        Recommendation

        In batchSendExitRequest, revert when validatorInfos[_validatorId].exitRequestTimestamp != 0, and in EtherFiNode.unRegisterValidator reset numExitRequestsByTnft (and numExitedValidators) to zero when the last validator leaves the safe. Add a test that sends two exit requests for one validator and asserts the second call reverts, and one that recycles a safe and asserts partialWithdraw works for the new validator.

        Claude Security (Sonnet 5.5)

        Non-idempotent exit-request counter can permanently block partialWithdraw and forcePartialWithdraw on a (recycled) safe

        src/EtherFiNodesManager.sol:139 Predicted severity: Low

        Root cause

        Vulnerable symbol: batchSendExitRequest

        Preconditions: Attacker holds a T-NFT (for example by staking via the delegated flow) or the admin repeats exit requests; enableNodeRecycling is on, or the safe is shared among LP-flow validators

        Offending code:

        IEtherFiNode(etherfiNode).updateNumExitRequests(1, 0);

        Impact

        Rewards of validators on the poisoned safe cannot be skimmed until the validator exits. Once the balance reaches 16 ETH, even the admin's forcePartialWithdraw is blocked, so the validator is forced to exit. This is a denial of service on reward payouts with cross-user reach, but only via recycled or shared safes.

        Description

        batchSendExitRequest increments the safe-level numExitRequestsByTnft on every call, even when the validator already has a pending request. unRegisterValidator decrements it only once if exitRequestTimestamp != 0, and _getTotalRewardsPayoutsFromSafe (used by partialWithdraw and forcePartialWithdraw) reverts while the counter is non-zero.

        Exploit scenario

        A T-NFT holder (for example a delegated staker, or LiquidityPool via repeated oracle exit lists) calls batchSendExitRequest twice for the same validator, then the validator exits and fullWithdraw runs. The counter stays at 1, and the safe goes to unusedWithdrawalSafes. With enableNodeRecycling on, the next validator allocated to this safe can never partialWithdraw or forcePartialWithdraw. If its T-NFT holder is the LiquidityPool, nothing can decrement the counter, since LP exposes no revert function. The same desync occurs on a shared safe when a co-resident validator is double-requested and then withdrawn. Reasoned from code; not executed.

        Recommendation

        Make exit-request accounting per validator: only increment when exitRequestTimestamp == 0, and only decrement in batchRevertExitRequest when a request is outstanding. Reset numExitRequestsByTnft (and numExitedValidators) when the last validator is unregistered and the safe is recycled.

        Claude Security (Opus 5.5)

        Repeated or duplicate validator IDs in batchSendExitRequest inflate numExitRequestsByTnft, which permanently blocks reward withdrawals for the safe and for any validator later given the recycled safe

        src/EtherFiNodesManager.sol:139 Predicted severity: Medium

        Root cause

        Vulnerable symbol: batchSendExitRequest

        Preconditions: Attacker holds the T-NFT of a LIVE validator (anyone can mint one through delegated staking or buy one, since T-NFTs are transferable when the safe has exactly one validator); Reaching other users' validators also needs enableNodeRecycling == true (an admin setting that the test setup turns on) and the attacker's validator to exit and be fully withdrawn

        Offending code:

        IEtherFiNode(etherfiNode).updateNumExitRequests(1, 0);

        Impact

        Permanent denial of service on reward skimming (partialWithdraw, batchPartialWithdraw, batchPartialWithdrawOptimized, forcePartialWithdraw) for the affected safe. Rewards owed to T-NFT holders (including eETH holders through the LP), B-NFT stakers, node operators and the treasury stay frozen until every validator in the safe exits and is fully withdrawn, or the contract is upgraded. The bad state follows the safe through recycling and reaches unrelated users. Principal is not stolen.

        Description

        The T-NFT holder supplies the _validatorIds array. batchSendExitRequest never checks that the validator does not already have a pending exit request (validatorInfos[id].exitRequestTimestamp == 0), so passing the same ID twice, or calling twice, increments the safe's numExitRequestsByTnft counter once per entry. The counter is only ever decremented once per validator: once in batchRevertExitRequest at :157, which also has no isExitRequested check, and once in EtherFiNode.unRegisterValidator at :133, which runs only if the timestamp is non-zero. Also CWE-459: A T-NFT holder can call batchSendExitRequest repeatedly, or pass the same validatorId many times, because there is no exitRequestTimestamp == 0 check. Each call increments the safe-wide counter, but unRegisterValidator decrements it only once (EtherFiNode.sol:133). When the safe's last validator leaves, it is pushed to unusedWithdrawalSafes (line 498) without resetting the counter. allocateEtherFiNode (lines 326-336) later hands it, still dirty, to a new validator. Also CWE-841: batchSendExitRequest never checks whether the validator already has an exit request, so the T-NFT holder can raise the safe-wide counter several times for one validator. unRegisterValidator decrements it at most once, and the safe is then pushed to unusedWithdrawalSafes without resetting the counter. The next validator allocated that safe always fails the PENDING_EXIT_REQUEST check.

        Exploit scenario

        Alice holds the T-NFT of validator V, which sits alone in safe S (a delegated-staking T-NFT, or one bought on the secondary market). She calls batchSendExitRequest([V, V]), so S.numExitRequestsByTnft becomes 2. (Path a) She calls batchRevertExitRequest([V]) once: the counter drops to 1 and the timestamp is cleared, so no non-exit penalty applies to the B-NFT holder. partialWithdraw(V) and the admin's forcePartialWithdraw(V) now revert with PENDING_EXIT_REQUEST, so the B-NFT holder, the operator and the treasury cannot collect rewards. (Path b) After V exits and anyone calls fullWithdraw(V), unRegisterValidator decrements the counter only once, leaving 1, and S goes back into unusedWithdrawalSafes. With enableNodeRecycling on, the next validator allocated to S inherits numExitRequestsByTnft == 1. This could be a LiquidityPool (eETH) validator, plus any validators the LP later adds to S through _validatorIdToShareWithdrawalSafe. Their partialWithdraw and forcePartialWithdraw revert permanently. The LP has no path to batchRevertExitRequest, so only a contract upgrade can clear the counter, and every later fullWithdraw recycles S with the bad counter still set.

        Recommendation

        In batchSendExitRequest, add require(validatorInfos[_validatorId].exitRequestTimestamp == 0, "ASKED"). In batchRevertExitRequest, add require(validatorInfos[_validatorId].exitRequestTimestamp != 0, "NOT_ASKED"). As defense in depth, reset numExitRequestsByTnft and numExitedValidators when a safe is recycled (in unRegisterValidator when the last validator is removed, or in registerValidator when numAssociatedValidators() == 0). Also CWE-459: In batchSendExitRequest, reject validators whose exitRequestTimestamp is already non-zero. In batchRevertExitRequest, require a pending request. When a safe is recycled (numAssociatedValidators()==0 in unRegisterValidator), reset numExitRequestsByTnft and numExitedValidators to 0. Also CWE-841: Add require(!isExitRequested(id)) to batchSendExitRequest and require(isExitRequested(id)) to batchRevertExitRequest. Reset numExitRequestsByTnft (and numExitedValidators) when a safe's associated-validator count reaches zero.

      • BNFT holder could cancel the deposit after processNodeExit is called etherfi-3 · 6 writeups Critical

        V12

        Exited cancellation bypasses principal withdrawal settlement

        src/LiquidityPool.sol:389 Predicted severity: High

        Root cause

        Cancellation relies on a generic node teardown routine rather than enforcing pre-live status itself. That routine intentionally supports exited full-withdrawal cleanup, so the cancellation caller can invoke terminal cleanup without its required payout and NFT burns.

        Impact

        A recorded BNFT staker can destroy normal principal recovery for an exited validator and corrupt the pool pending-deposit count while receiving an extra 2 ETH cancellation payment. The withdrawal safe retains its funds but loses the validator association used by fullWithdraw; recovery requires privileged intervention, and recycling can expose the retained balance to later safe users.

        Description

        Cancellation does not explicitly restrict the validator to the two pre-live phases. LIVE cancellation is rejected by the node transition rules, but EXITED takes a different teardown branch that is intended for full withdrawal and allows transition to FULLY_WITHDRAWN. If any pending pool deposit exists, _batchCancelDeposit can decrement that unrelated pending count and refund 2 ETH for an exited validator owned by the supplied staker. The staking manager then clears the staker, unregisters the exited validator, and reactivates its auction bid without distributing principal or burning its NFTs. This consumes the full-withdrawal teardown state through a cancellation path and removes the safe association required for the actual withdrawal.

        Pashov (Claude Opus 5.5 high)

        _cancelDeposit has no phase check: EXITED validators can be 'cancelled', refunding the stake and stranding the exited principal

        src/StakingManager.sol:448 Predicted severity: High

        Root cause

        The phase check (validatorPhase == STAKE_DEPOSITED || validatorPhase == WAITING_FOR_APPROVAL) is missing from _cancelDeposit. _unRegisterValidator's EXITED->FULLY_WITHDRAWN branch then lets the cancellation succeed.

        Impact

        Delegated flow: the attacker gets a 32 ETH refund paid out of other users' escrowed deposits, while their exited 32 ETH principal stays in the safe. That safe is recycled to the next validator, and the next owner (who may be the attacker) can later collect it as 'rewards'. BNFT flow: the LP pays 2 ETH it does not owe, the LP's 30 ETH principal is stranded in a recycled safe and can no longer be withdrawn through fullWithdraw (the node address is deleted and the T-NFT is never burned), and numPendingDeposits becomes corrupted. A recycled safe holding 32+ ETH also blocks partialWithdraw for its next validator (MUST_EXIT).

        Description

        _cancelDeposit reads validatorPhase = nodesManager.phase(_validatorId) but never uses it. It never requires the validator to be in STAKE_DEPOSITED or WAITING_FOR_APPROVAL. It calls nodesManager.unregisterValidator, whose _unRegisterValidator contains a branch for EXITED validators: it moves them to FULLY_WITHDRAWN (a valid transition), unregisters them from the safe, deletes etherfiNodeAddress, and pushes the safe (still holding the exited principal) to unusedWithdrawalSafes once it has no validators left. The phase-transition guard only blocks LIVE and BEING_SLASHED validators. So a staker whose validator has EXITED can still cancel the deposit. In the delegated flow StakingManager then refunds stakeAmount (32 ETH) from its balance. In the BNFT flow, LiquidityPool._batchCancelDeposit treats any non-WAITING_FOR_APPROVAL phase as a fresh deposit: it pays the staker 2 ETH and decrements numPendingDeposits.

        Exploit scenario

        1. The attacker stakes 32 ETH via the delegated batchDepositWithBidIds and registers the validator.

        2. The attacker exits the validator. The admin calls processNodeExit, so the phase is EXITED and the safe holds about 32 ETH.

        3. Before anyone calls fullWithdraw, the attacker calls StakingManager.batchCancelDeposit([id]). Source is DELEGATED_STAKING and staker == attacker. _unRegisterValidator sets FULLY_WITHDRAWN, the safe goes back to the pool with 32 ETH, the bid re-enters the auction, and _refundDeposit(attacker, 32 ether) pays from other stakers' pending deposits.

        4. With node recycling enabled, the attacker immediately deposits again and receives the recycled safe. On the later exit, the extra 32 ETH is counted as staking rewards and mostly paid to the attacker's T-NFT and B-NFT. Net: about 32 ETH stolen.

        Recommendation

        Restore the check in _cancelDeposit: require(validatorPhase == IEtherFiNode.VALIDATOR_PHASE.STAKE_DEPOSITED || validatorPhase == IEtherFiNode.VALIDATOR_PHASE.WAITING_FOR_APPROVAL, "INVALID_PHASE");. Also make unregisterValidator (the StakingManager entry point) reject EXITED validators.

        Pashov (Codex GPT-6 Sol high)

        Cancelling an exited validator can steal another depositor’s pending stake

        audit/src/StakingManager.sol:212 Predicted severity: High

        Root cause

        The cancellation path checks the recorded staker but not validator phase; EtherFiNodesManager treats EXITED unregister as fully withdrawn even though no payout occurred.

        Impact

        The cancelling staker can collect a second 32 ETH stake from StakingManager’s balance while another depositor’s funds become unavailable, and the original validator’s principal is stranded in an unlinked safe.

        Description

        A delegated staker can cancel a validator after it has exited, causing the manager to discard its withdrawal-safe link and refund 32 ETH from other users’ pending deposits.

        Exploit scenario

        A delegated staker registers and exits a validator. Another user deposits 32 ETH for a pending validator. Before fullWithdraw, the first staker calls batchCancelDeposit for its EXITED ID. _cancelDeposit unlinks the exited safe, reopens its bid, and refunds 32 ETH from the manager’s current balance; the first validator NFTs remain without a redeemable manager path.

        Recommendation

        Permit cancellation only in pre-registration phases and make EXITED validators settle exclusively through fullWithdraw; track and reserve each pending staker deposit separately.

        Claude Security (Sonnet 5.5)

        Cancel-deposit path accepts EXITED validators: refunds 32 ETH from StakingManager (or 2 ETH from LiquidityPool) and orphans the withdrawal safe

        src/StakingManager.sol:454 Predicted severity: Medium

        Root cause

        Vulnerable symbol: _cancelDeposit

        Preconditions: A validator the attacker is recorded as staker for is in phase EXITED and fullWithdraw has not been called yet; For the theft variant, StakingManager holds at least 32 ETH of other users' unregistered deposits; For the LP variant, the attacker is a registered BNFT holder and numPendingDeposits is at least 1

        Offending code:

        nodesManager.unregisterValidator(_validatorId);

        Impact

        Theft of other stakers' pending deposits from StakingManager (up to its whole balance), after which their batchRegisterValidators or cancel calls fail for lack of ETH. In the LP flow, the principal of the exited validator (about 30 ETH per validator) is stranded in an orphaned safe while LP accounting still counts it as out-of-LP assets, and LiquidityPool.numPendingDeposits is wrongly decremented, which can make other holders' register or cancel calls underflow-revert. The T-NFT and B-NFT stay unburned, and validatorInfos keeps FULLY_WITHDRAWN plus a non-zero exitTimestamp, so the re-entered bid reverts with INVALID_PHASE_TRANSITION whenever any batch includes it.

        Description

        StakingManager._cancelDeposit never checks the validator phase (the validatorPhase local at line 451 is dead code) and relies on EtherFiNodesManager._unRegisterValidator to reject non-cancellable phases, but that function was extended for fullWithdraw and now accepts EXITED (EXITED -> FULLY_WITHDRAWN). A staker can therefore 'cancel' an exited validator through StakingManager.batchCancelDeposit or LiquidityPool.batchCancelDeposit and be refunded. Also CWE-863: _cancelDeposit authorizes only on the staker's identity. It reads validatorPhase at line 451 but never uses it, relying on the phase-transition table to block cancellation of LIVE validators. EtherFiNodesManager._unRegisterValidator maps phase EXITED to FULLY_WITHDRAWN (lines 484-486), and that transition is valid. A staker can therefore call cancel on an EXITED validator and have it accepted as a cancellation.

        Exploit scenario

        Delegated-staking variant: attacker stakes 32 ETH via StakingManager.batchDepositWithBidIds (source DELEGATED_STAKING) and registers; the validator exits and the oracle runs EtherFiNodesManager.processNodeExit (phase EXITED). Before anyone calls fullWithdraw, attacker calls StakingManager.batchCancelDeposit([id]). The source check (line 214) and staker check (line 449) pass, unregisterValidator moves EXITED -> FULLY_WITHDRAWN and deletes etherfiNodeAddress, reEnterAuction succeeds, and _refundDeposit pays 32 ETH out of StakingManager's balance, which holds other users' deposits that are not yet registered. A slashed validator exiting with 16-31 ETH makes this directly profitable. LP variant: a registered BNFT holder watches NodeExitProcessed and calls LiquidityPool.batchCancelDeposit([id]) before fullWithdraw; LP pays 2 ETH and the 30 ETH T-NFT principal stays in the safe, unreachable because the validator is already unregistered. Reasoned from code; not executed.

        Recommendation

        Enforce the allowed phases in the cancel entry point: _cancelDeposit must require STAKE_DEPOSITED, or WAITING_FOR_APPROVAL for the BNFT flow. Split the cancel (-> NOT_INITIALIZED) and full-withdraw (-> FULLY_WITHDRAWN) transitions into separate manager functions so unregisterValidator can never take the EXITED branch. Delete or reset validatorInfos on unregister, and add a regression test for cancelling an EXITED validator. Also CWE-863: In _cancelDeposit, explicitly require the validator phase to be STAKE_DEPOSITED or WAITING_FOR_APPROVAL, and revert otherwise. Make EtherFiNodesManager.unregisterValidator, which is the StakingManager entry point, reject EXITED instead of treating it as a full withdrawal. Reserve that EXITED to FULLY_WITHDRAWN path for fullWithdraw.

        Claude Security (Opus 5.5)

        Staker can cancel an EXITED validator and take a full 32 ETH refund from StakingManager, stranding the validator principal

        src/StakingManager.sol:461 Predicted severity: High

        Root cause

        Vulnerable symbol: _cancelDeposit

        Preconditions: Attacker is the staker of a validator that has been marked EXITED and not yet fully withdrawn; For the DELEGATED path, StakingManager holds at least 32 ETH of other users' pending deposits; for the BNFT path, numPendingDeposits >= 1

        Offending code:

        _refundDeposit(msg.sender, stakeAmount);

        Impact

        Theft of up to 32 ETH per exited validator from StakingManager-held user deposits, plus theft of already-spent bid fees from AuctionManager. On the BNFT path, LiquidityPool / eETH holders lose 2 ETH plus 30 ETH of stranded principal per validator.

        Description

        _cancelDeposit authorizes cancellation and refund only on bidIdToStakerInfo.staker == caller. It has no phase check and never clears the staker after registration. EtherFiNodesManager._unRegisterValidator turns an EXITED validator into FULLY_WITHDRAWN (a transition meant for fullWithdraw). So a staker whose validator has exited (32 ETH already sent to the beacon chain) can still cancel, and line 461 pays them stakeAmount out of other users' pending deposits.

        Exploit scenario

        An attacker stakes 32 ETH via batchDepositWithBidIds, registers (32 ETH to the beacon chain, phase LIVE), then exits the validator. If they are also the operator they control the exit; otherwise they request it as TNFT holder. The admin or oracle marks it EXITED via processNodeExit. Before anyone calls fullWithdraw, the attacker calls StakingManager.batchCancelDeposit([id]). The EXITED->FULLY_WITHDRAWN transition passes, the safe mapping is deleted, and StakingManager refunds 32 ETH from the pending deposits of other DELEGATED stakers. If the attacker is also the operator, the bid re-enters the auction and cancelBid refunds the bid amount from other operators' escrow, even though it was already paid out at registration. A slashed validator holding 16-31 ETH is turned into a full 32 ETH refund. With node recycling enabled, the attacker can grab the recycled safe that still holds the old principal. The same missing check exists on the BNFT path: LiquidityPool._batchCancelDeposit pays the holder 2 ETH, and the LP's 30 ETH TNFT principal is left in an unmapped safe that fullWithdraw can no longer reach.

        Recommendation

        In _cancelDeposit, require the phase to be STAKE_DEPOSITED or WAITING_FOR_APPROVAL. Make the cancel path call a dedicated unregister that reverts unless the phase is pre-LIVE, instead of sharing _unRegisterValidator's EXITED branch. Clear bidIdToStakerInfo (or mark the stake consumed) once the 32 ETH reaches the beacon chain. Do not re-enter a bid whose fee has already been transferred.

        Vercel Security Review

        Exited delegated validators can be cancelled for another 32 ETH refund

        src/StakingManager.sol:451 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Cancellation authenticates the original staker but does not restrict the validator to a pending deposit** - src/StakingManager.sol:447-454

        ```solidity title="src/StakingManager.sol:451-454"

        IEtherFiNode.VALIDATOR_PHASE validatorPhase = nodesManager.phase(_validatorId);

        bidIdToStakerInfo[_validatorId].staker = address(0);

        nodesManager.unregisterValidator(_validatorId);

        ```

        **2. Unregistration accepts EXITED validators as completed withdrawals** - src/EtherFiNodesManager.sol:484-486

        ```solidity title="src/EtherFiNodesManager.sol:484-486"

        if (phase(_validatorId) == IEtherFiNode.VALIDATOR_PHASE.EXITED) {

        // Called by EtherFiNodesManager.fullWithdraw

        _setValidatorPhase(safeAddress, _validatorId, IEtherFiNode.VALIDATOR_PHASE.FULLY_WITHDRAWN);

        ```

        **3. The cancellation caller receives the full stake from pending deposit custody** - src/StakingManager.sol:459-462

        ```solidity title="src/StakingManager.sol:459-462"

        bool isFullStake = (msg.sender != liquidityPoolContract);

        if (isFullStake) {

        _refundDeposit(msg.sender, stakeAmount);

        }

        ```

        After selling the transferable TNFT and waiting for the oracle-observed exit, the original delegated staker can take 32 ETH belonging to pending stakers. Deleting the node association also prevents the TNFT buyer's withdrawal.

        Exploit scenario

        Not specified.

        Recommendation

        Require delegated cancellations to be in STAKE_DEPOSITED before changing any state or refunding custody funds. Restrict LP cancellations to their explicitly supported pending phases as well. Separate cancellation unregistration from full-withdrawal unregistration so cancellation cannot reach EXITED-to-FULLY_WITHDRAWN processing.

      • Malicious users could use the ETH of legitimate users and mint themselves NFTs etherfi-4 · 6 writeups Critical

        V12

        Cross-flow registration spends other stakers' escrow

        src/StakingManager.sol:145 Predicted severity: Critical

        Root cause

        The public 32 ETH registration path does not require bidIdToStakerInfo[_validatorId].sourceOfFund == DELEGATED_STAKING. Staker identity is incorrectly treated as sufficient authority to spend the contract's delegated-deposit escrow and select both NFT beneficiaries.

        Impact

        When StakingManager holds at least 32 ETH of pending delegated deposits, an admitted BNFT depositor can redirect that escrow into a validator whose TNFT and BNFT are both minted to the depositor. The affected delegated depositors lose the backing required for their own registrations or cancellation refunds.

        Description

        The public registration overload always calls _registerValidator with a 32 ETH deposit and both NFT recipients set to msg.sender. Its authorization checks only that the caller equals the recorded staker, without checking sourceOfFund. A BNFT depositor admitted through LiquidityPool._batchDeposit is recorded as that same user with source EETH, but the pool sends no ETH to StakingManager at this stage. While this validator is still STAKE_DEPOSITED, the user can invoke the public registration overload and spend ETH held for pending delegated deposits. The phase transition and initial NFT mints permit this path, giving the caller both validator entitlements despite contributing only the BNFT-side deposit.

        Pashov (Claude Opus 5.5 high)

        Delegated-staking batchRegisterValidators does not check the source of funds, so BNFT-flow stakers can register a 32 ETH validator using other users' pending deposits

        src/StakingManager.sol:145 Predicted severity: High

        Root cause

        The source-of-funds check (sourceOfFund == DELEGATED_STAKING) is missing from the delegated-flow batchRegisterValidators. The function trusts that any bid whose staker equals msg.sender was funded by msg.sender with 32 ETH held in StakingManager.

        Impact

        Theft of up to 32 ETH per call from delegated stakers' escrowed deposits. The attacker ends up owning a fully funded 32 ETH validator (T-NFT and B-NFT) after paying only 2 ETH in normal BNFT mode, or 0 ETH when isLpBnftHolder is enabled. The victims' later batchRegisterValidators or batchCancelDeposit calls revert for lack of balance, so their funds are effectively stolen and frozen. The LP's numPendingDeposits also drifts.

        Description

        The public, permissionless batchRegisterValidators(bytes32,uint256[],DepositData[]) is meant for the delegated (solo, 32 ETH) staking flow. Its only authorization check is in _registerValidator: bidIdToStakerInfo[id].staker == msg.sender. It never checks that bidIdToStakerInfo[id].sourceOfFund == DELEGATED_STAKING. For bids deposited through the LiquidityPool BNFT flow (batchDepositAsBnftHolder / batchDepositWithLiquidityPoolAsBnftHolder), staker is set to the BNFT player. So that player can call the delegated register function directly. StakingManager then deposits 32 ETH from its own balance into the beacon chain, mints both the T-NFT and the B-NFT to the BNFT player, and sets the validator LIVE. The only ETH StakingManager holds is the 32 ETH per validator escrowed by delegated stakers whose deposits are still in STAKE_DEPOSITED. The cancel path does enforce the flow split (require(sourceOfFund == DELEGATED_STAKING, "Wrong flow") in batchCancelDeposit), but the register path does not.

        Exploit scenario

        1. Victims call StakingManager.batchDepositWithBidIds{value: 32 ether * k} (delegated flow). StakingManager now holds 32k ETH.

        2. The attacker is a registered BNFT holder and calls LiquidityPool.batchDepositAsBnftHolder{value: 2 ether}(bids, 1), or the 0-ETH LP-mode variant. bidIdToStakerInfo[id] = (attacker, EETH).

        3. The attacker calls StakingManager.batchRegisterValidators(0x0, [id], [depositData for 32 ETH with withdrawal credentials of the safe]). _registerValidator passes the staker check, sets phase LIVE (STAKE_DEPOSITED->LIVE is valid), deposits 32 ETH from the victims' escrow, and mints the T-NFT and B-NFT to the attacker.

        4. Later the attacker exits the validator (as T-NFT owner) and fullWithdraw pays about 32 ETH plus rewards to the attacker. The victims can no longer register or cancel.

        Recommendation

        In the delegated batchRegisterValidators, add require(bidIdToStakerInfo[_validatorId[x]].sourceOfFund == ILiquidityPool.SourceOfFunds.DELEGATED_STAKING, "Wrong flow") for each id. Symmetrically, the LP-only batchRegisterValidators should require sourceOfFund != DELEGATED_STAKING. Otherwise a delegated staker can register through the LP (the LP pays 1 ETH and decrements numPendingDeposits) and then cancel through the delegated path to recover their full 32 ETH, leaving the LP's 1 ETH stranded in the beacon chain.

        Devin Security (Deep)

        Solo-staker registration path accepts pool-flow validators and pays the 32 ETH deposit from StakingManager's balance

        src/StakingManager.sol:145 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        An admin-registered bond holder can turn a validator reserved through the pool into a fully funded validator they own outright, with the 32 ETH taken from other users' deposits waiting inside StakingManager.

        ##### What's wrong

        This is a missing flow check. The three-argument batchRegisterValidators is meant for solo stakers who already sent 32 ETH into StakingManager, but it only checks that the caller is the recorded staker. Validators reserved through the pool record the bond holder as staker, so a bond holder can use this path, and StakingManager then pays 32 ETH from its own balance and mints both NFTs to the caller.

        ##### Who can do it

        Bob is a solo staker who sends 32 ETH to StakingManager.batchDepositWithBidIds and plans to register his key a little later. Mallory controls an address the ether.fi admin registered as a bond holder. She reserves a validator through LiquidityPool.batchDepositAsBnftHolder (posting a 2 ETH bond, or 0 ETH if the pool is in pool-as-bond-holder mode), then calls StakingManager.batchRegisterValidators(0x0, [id], [depositData]) with a 32 ETH deposit message signed by her own validator key.

        - Mallory is the recorded staker of a pool-flow validator, which today means an admin-registered bond holder.

        - StakingManager holds at least 32 ETH of other users' pending solo deposits at that moment; it keeps solo deposits between deposit and registration.

        - The validator is still in the STAKE_DEPOSITED phase.

        ##### What they get

        Mallory ends up with a live 32 ETH validator paid for with Bob's deposit, and both the T-NFT and B-NFT are minted to her, so on exit the full 32 ETH principal and all rewards go to her. Bob's later registration or cancellation fails because StakingManager no longer holds his ETH. She nets about 30 ETH per validator after her 2 ETH bond (32 ETH in pool-as-bond-holder mode), limited only by how much pending solo-staker ETH StakingManager holds.

        ##### How it works

        1. LiquidityPool._batchDeposit calls StakingManager.batchDepositWithBidIds, whose _processDeposit sets bidIdToStakerInfo[bidId].staker to the bond holder (src/StakingManager.sol:426).

        2. The bond holder calls the three-argument StakingManager.batchRegisterValidators (src/StakingManager.sol:145-156), which has no sourceOfFund check and calls _registerValidator(id, msg.sender, msg.sender, data, msg.sender, 32 ether).

        3. _registerValidator passes the staker check (line 391), moves the phase to LIVE (line 399), and sends 32 ETH from StakingManager's own balance to the beacon deposit contract (line 403).

        4. The T-NFT and B-NFT are minted to the caller (lines 410-411), so EtherFiNodesManager.fullWithdraw later pays the principal to the caller.

        5. batchCancelDeposit does check sourceOfFund == DELEGATED_STAKING (line 214), which shows the flow check exists elsewhere but was left out of registration.

        Exploit scenario

        Not specified.

        Recommendation

        In the three-argument batchRegisterValidators, require bidIdToStakerInfo[id].sourceOfFund == ILiquidityPool.SourceOfFunds.DELEGATED_STAKING for every id; in the six-argument version require the source to be EETH or ETHER_FAN. Add a test that deposits through the pool as a bond holder, funds StakingManager with a separate solo deposit, and asserts the solo batchRegisterValidators call for the pool-flow id reverts.

        Claude Security (Sonnet 5.5)

        Public batchRegisterValidators has no source-of-funds check, so an LP-flow BNFT holder can register with 32 ETH taken from other stakers' pending deposits

        src/StakingManager.sol:154 Predicted severity: Medium

        Root cause

        Vulnerable symbol: batchRegisterValidators

        Preconditions: Attacker is an LP BNFT holder registered by an admin; StakingManager holds at least 32 ETH of pending DELEGATED_STAKING deposits at the time of the call; Attacker's bid is in STAKE_DEPOSITED phase, so the LP 1 ETH register step has not yet been done

        Offending code:

        _registerValidator(_validatorId[x], msg.sender, msg.sender, _depositData[x], msg.sender, 32 ether);

        Impact

        Theft of other users' pending 32 ETH stake deposits held in StakingManager, about 30 ETH net per validator for the attacker. It also bypasses the LP's 1 ETH then oracle-approved 31 ETH flow and leaves the LP's numPendingDeposits and 2 ETH accounting inconsistent.

        Description

        The only authorization in the public batchRegisterValidators path is bidIdToStakerInfo[id].staker == msg.sender (line 391). It never checks sourceOfFund == DELEGATED_STAKING, unlike batchCancelDeposit (line 214, "Wrong flow"). A BNFT holder whose bid was matched through the LP flow (staker = holder, source EETH) can therefore call this non-payable function. It deposits 32 ETH from StakingManager's own balance at line 403, which holds other users' pending DELEGATED_STAKING deposits.

        Exploit scenario

        1) An admin-registered BNFT holder calls LiquidityPool.batchDepositAsBnftHolder with 2 ETH per validator. StakingManager records staker = holder, source = EETH, phase = STAKE_DEPOSITED. 2) While StakingManager holds at least 32 ETH of other users' pending deposits from the public payable batchDepositWithBidIds, the holder calls StakingManager.batchRegisterValidators(0x0, [bidId], [depositData]) directly instead of going through the LP. 3) _registerValidator passes the staker check. _tNftRecipient is not the LP, so the phase goes to LIVE with no oracle credential confirmation. deposit{value: 32 ether} spends the pooled ETH, and both the T-NFT and B-NFT are minted to the holder. 4) The holder controls a 32 ETH validator funded by other stakers. Those stakers' later batchRegisterValidators or batchCancelDeposit calls revert or underpay because the contract balance is gone.

        Recommendation

        In the public batchRegisterValidators, require bidIdToStakerInfo[id].sourceOfFund == ILiquidityPool.SourceOfFunds.DELEGATED_STAKING for every id, as batchCancelDeposit already does. Also make the 32 ETH funding explicit by tracking per-staker deposited ETH, or make the function payable and require msg.value == 32 ether * n.

        Claude Security (Opus 5.5)

        Public 32-ETH batchRegisterValidators accepts EETH (BNFT-flow) validator IDs and pays for them out of other delegated stakers' escrowed ETH

        src/StakingManager.sol:154 Predicted severity: High

        Root cause

        Vulnerable symbol: batchRegisterValidators(bytes32,uint256[],DepositData[])

        Preconditions: Attacker has been registered as a BNFT holder by the LiquidityPool admin; StakingManager holds at least 32 ETH from DELEGATED_STAKING deposits that have not been registered yet; Attacker can choose an EETH-approved operator's bid (any approved operator's active bid)

        Offending code:

        _registerValidator(_validatorId[x], msg.sender, msg.sender, _depositData[x], msg.sender, 32 ether);

        Impact

        The StakingManager balance holds only the escrowed 32 ETH stakes of DELEGATED_STAKING users who have not registered yet. The attacker spends one of those stakes on a validator whose keys they control and receives both NFTs, so they own the whole principal and rewards. The victim's later registration or cancel fails because the balance is short (the cancel refund at line 473 reverts), so the victim's 32 ETH is effectively stolen. In LP-bnft mode the attacker paid 0 ETH (batchDepositWithLiquidityPoolAsBnftHolder). Otherwise they paid 2 ETH, a net gain of about 30 ETH per validator, and they can repeat this up to maxBatchDepositSize per call while funds remain.

        Description

        The validator IDs passed to the public solo-staker register function are user-supplied. The only check on them is bidIdToStakerInfo[id].staker == msg.sender (line 391). Nothing confirms sourceOfFund == DELEGATED_STAKING, although batchCancelDeposit (line 214) does check this. A BNFT holder is recorded as the staker of EETH-sourced IDs (LiquidityPool.sol:320 passes msg.sender as _staker). That holder can call this function, which sends 32 ETH from the StakingManager balance to the beacon deposit contract (line 403) and mints both the TNFT and the BNFT to the caller (lines 410-411). Also CWE-863: This is outside the injection lens but is a confirmed path, so it is reported anyway. The public batchRegisterValidators takes caller-chosen validator IDs and only checks bidIdToStakerInfo[id].staker == msg.sender (line 391). It never checks sourceOfFund == DELEGATED_STAKING, unlike batchCancelDeposit at line 214. A BNFT holder is recorded as staker for its EETH-sourced IDs (LiquidityPool.sol:320), so it can push 32 ETH of the StakingManager balance, which belongs to other users' pending delegated deposits, to the beacon chain and have TNFT and BNFT minted to itself. Also CWE-843: Each StakerInfo record carries a sourceOfFund tag. A DELEGATED_STAKING record means 32 ETH is held in StakingManager, while an EETH or ETHER_FAN record from LiquidityPool._batchDeposit has nothing held there. The public batchRegisterValidators only checks bidIdToStakerInfo.staker == msg.sender and never checks the tag. It then calls depositContractEth2.deposit{value: 32 ether} (line 403) with the contract's pooled ETH and mints both T-NFT and B-NFT to the caller. The two cancel paths do check the tag (lines 214 and 232), but this path does not.

        Exploit scenario

        1) The attacker is a registered BNFT holder. They call LiquidityPool.batchDepositWithLiquidityPoolAsBnftHolder([bidId],1), which costs 0 ETH in LP mode, or batchDepositAsBnftHolder with 2 ETH. StakingManager records bidIdToStakerInfo[bidId] = (attacker, EETH) and the phase becomes STAKE_DEPOSITED. 2) A victim calls StakingManager.batchDepositWithBidIds with 32 ETH, which stays in StakingManager until they register. 3) The attacker calls StakingManager.batchRegisterValidators(0x0,[bidId],[depositData]) directly. The depositData is built for 32 ETH using the safe's withdrawal credentials and the attacker's own validator key. The staker check passes and the phase moves STAKE_DEPOSITED->LIVE. 32 ETH of the victim's escrow goes to the beacon chain, and the TNFT and BNFT are minted to the attacker. 4) Later the attacker exits the validator and collects the full payout as holder of both the TNFT and the BNFT. The victim's cancel or register reverts for lack of balance.

        Recommendation

        In the public batchRegisterValidators, require bidIdToStakerInfo[_validatorId[x]].sourceOfFund == ILiquidityPool.SourceOfFunds.DELEGATED_STAKING for every ID, the same check batchCancelDeposit uses. A better fix is to track escrowed ETH per validator so a registration can only spend the stake deposited for that validator ID. Also CWE-863: In the public batchRegisterValidators, require bidIdToStakerInfo[_validatorId[x]].sourceOfFund == ILiquidityPool.SourceOfFunds.DELEGATED_STAKING, mirroring batchCancelDeposit. In the LP-only overload, require the source to be EETH or ETHER_FAN. Better still, track the ETH escrowed per validator ID so a registration can only spend the ETH deposited for that ID. Also CWE-843: In the public batchRegisterValidators, require bidIdToStakerInfo[_validatorId[x]].sourceOfFund == ILiquidityPool.SourceOfFunds.DELEGATED_STAKING, the same check batchCancelDeposit uses. Better still, track escrowed ETH per bid and only deposit what that bid funded.

        Vercel Security Review

        bNFT reservations can consume other stakers' 32 ETH through full-stake registration

        src/StakingManager.sol:153 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. A registered bNFT staker reserves a validator for only 2 ETH** - src/LiquidityPool.sol:268-270

        ```solidity title="src/LiquidityPool.sol:268-270"

        function batchDepositAsBnftHolder(uint256[] calldata _candidateBidIds, uint256 _numberOfValidators, uint256 _validatorIdToShareSafeWith) public payable whenNotPaused returns (uint256[] memory) {

        require(!isLpBnftHolder, "IncorrectBnftMode");

        return _batchDeposit(_candidateBidIds, _numberOfValidators, 2 ether, _validatorIdToShareSafeWith);

        ```

        **2. The public full-stake entrypoint accepts the same reservation** - src/StakingManager.sol:153-155

        ```solidity title="src/StakingManager.sol:153-155"

        for (uint256 x; x < _validatorId.length; ++x) {

        _registerValidator(_validatorId[x], msg.sender, msg.sender, _depositData[x], msg.sender, 32 ether);

        }

        ```

        The helper checks staker identity at line 391, not sourceOfFund, and assigns both NFTs to the caller.

        **3. Registration spends pooled custody funds** - src/StakingManager.sol:403-406

        ```solidity title="src/StakingManager.sol:403-406"

        depositContractEth2.deposit{value: _depositAmount}(_depositData.publicKey, withdrawalCredentials, _depositData.signature, depositDataRoot);

        nodesManager.incrementNumberOfValidators(1);

        auctionManager.processAuctionFeeTransfer(_validatorId);

        ```

        When other delegated stakes are pending, their 32 ETH backs the attacker's validator and withdrawal rights, leaving victims' registrations or refunds insolvent.

        Exploit scenario

        Not specified.

        Recommendation

        Require DELEGATED_STAKING source for the public full-stake registration overload. Enforce source-specific registration amounts, callers, and NFT recipients inside _registerValidator so LP reservations can only follow the LP-controlled 1 ETH/31 ETH approval flow.

      • ETH sent to wrong address on cancellation etherfi-5 · 9 writeups Critical

        V12

        Zero-bond cancellations drain pooled ETH

        src/LiquidityPool.sol:294 Predicted severity: Critical

        Root cause

        Cancellation assumes every pool-backed validator has a refundable external 2 ETH bond, but pool BNFT mode funds the entire validator from pool assets. No per-ID bond or funding-mode record constrains the refund.

        Impact

        An untrusted registered holder can directly drain liquid staking assets while pool BNFT mode is enabled. The pool's totalValueInLp is not reduced by these payments, so the same sequence also leaves depositor balances backed by nonexistent liquidity.

        Description

        In liquidity-pool BNFT mode, a registered holder can allocate a validator through batchDepositWithLiquidityPoolAsBnftHolder without providing any ETH. The allocation still records that external holder as the validator's staker. LiquidityPool._batchCancelDeposit calculates refunds solely from phase, assigning 2 ETH to an unregistered validator and 1 ETH to a validator waiting for approval, regardless of which mode funded it. The staking cancellation path accepts the recorded holder, unregisters the validator, and reactivates the bid. Consequently the holder can repeatedly allocate and cancel the same bid, collecting a 2 ETH payment from pool assets each time without depositing a bond.

        Codex Security (GPT-6 Sol)

        A registered holder can drain pool ETH by cancelling zero-funded validators

        src/LiquidityPool.sol:294 Predicted severity: High

        Root cause

        The deposit path stores the caller as staker but does not store how much that caller paid. Cancellation assumes every BNFT staker paid 2 ETH, so it pays that amount even when the LP-funded mode collected zero.

        Impact

        Repeatable transfer of LP ETH to a lower-privilege registered holder can undercollateralize eETH. Exploitation requires an admin to enable LP-funded mode and register the holder.

        Description

        In LP-funded BNFT mode, a registered holder creates a validator without paying ETH, then cancels it before registration to receive a fixed 2 ETH refund. The bid is reactivated, so the holder can repeat the transfer while the pool has liquidity.

        Exploit scenario

        Zero-value holder deposit -> staker record -> fixed cancellation refund -> LP ETH transfer and bid reset

        Recommendation

        Record each validator's actual holder contribution and refund no more than that stored amount. A zero-funded LP validator must refund zero to the holder.

        Pashov (Claude Opus 5.5 high)

        In LP-as-BNFT-holder mode, cancelling a deposit refunds 1-2 ETH of LiquidityPool funds to a staker who deposited nothing

        src/LiquidityPool.sol:389 Predicted severity: High

        Root cause

        The refund logic assumes the staker always deposited 2 ETH (normal BNFT mode). It does not account for LP-as-BNFT-holder mode, where the staker contributes nothing and the 1 ETH registration deposit is paid by the LP itself.

        Impact

        A registered BNFT player can drain the LiquidityPool (eETH holders' ETH) 2 ETH per validator per round. The cancelled bids re-enter the auction (reEnterAuction), so deposit then cancel can be repeated until the pool is empty. totalValueInLp keeps reporting ETH that is gone, which breaks withdrawals and share pricing.

        Description

        When isLpBnftHolder is true, batchDepositWithLiquidityPoolAsBnftHolder calls _batchDeposit with _stakerDepositAmountPerValidator = 0, so the BNFT player sends no ETH. _batchCancelDeposit does not check the mode. It always computes returnAmount as 2 ETH per STAKE_DEPOSITED validator (1 ETH if WAITING_FOR_APPROVAL) and sends it to _bnftStaker from the LiquidityPool's balance. That balance backs eETH (totalValueInLp). totalValueInLp is not decreased, so the pool's books also become insolvent.

        Exploit scenario

        1. The admin enables updateBnftMode(true). The attacker is a registered BNFT holder.

        2. The attacker calls batchDepositWithLiquidityPoolAsBnftHolder(bids, 25) with 0 ETH. This only needs totalValueInLp >= 32 ether * 25.

        3. The attacker calls batchCancelDeposit(validatorIds). Every validator is STAKE_DEPOSITED, so returnAmount = 50 ETH. StakingManager cancels the deposits and the LP _sendFunds 50 ETH to the attacker.

        4. The attacker repeats with the re-entered bids.

        Recommendation

        When isLpBnftHolder is true, do not send any refund to the staker (the ETH belongs to the LP). Properly account for any ETH that does return. Better: record the per-validator staker deposit amount at deposit time and refund exactly that.

        Pashov (Codex GPT-6 Sol high)

        LP-funded BNFT deposits can be cancelled for unearned ETH refunds

        audit/src/LiquidityPool.sol:294 Predicted severity: Critical

        Root cause

        The LP-funded deposit variant passes zero as the staker deposit amount while _batchCancelDeposit applies fixed 2 ETH or 1 ETH refund amounts without recording what the holder paid.

        Impact

        A registered BNFT holder can repeatedly extract 2 ETH from pooled funds without contributing ETH, potentially draining all available pool liquidity and leaving eETH liabilities underbacked.

        Description

        In LP-funded BNFT mode, a registered BNFT holder starts validators without paying the 2 ETH BNFT contribution, yet cancellation refunds that contribution from pooled ETH.

        Exploit scenario

        When isLpBnftHolder is true, a registered holder calls batchDepositWithLiquidityPoolAsBnftHolder with active bids and zero msg.value, then batchCancelDeposit before registration. Each cancellation sends 2 ETH to that holder despite no contribution.

        Recommendation

        Record each validator’s actual holder-funded contribution and refund only that amount; in LP-funded mode return the reserved ETH to pool accounting without sending it to the caller.

        Devin Security

        B-NFT holder can drain liquidity pool ETH by depositing 0 ETH and cancelling for a 2 ETH refund

        src/LiquidityPool.sol:298 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Any approved B-NFT holder can take 2 ETH of pooled user funds per validator slot, over and over, while the pool runs in LP-funded B-NFT mode.

        ##### What's wrong

        This is a refund-without-deposit bug. In LP-funded B-NFT mode the B-NFT holder deposits 0 ETH, but _batchCancelDeposit refunds 2 ETH per cancelled validator (1 ETH after registration) based only on the validator phase. It never checks how much the caller actually paid.

        ##### Who can do it

        Alice and many other users hold eETH backed by ETH in the LiquidityPool. Mallory is a B-NFT holder that the ether.fi admin registered. The admin has switched the pool to LP-funded B-NFT mode. Mallory calls batchDepositWithLiquidityPoolAsBnftHolder with 0 ETH and then calls batchCancelDeposit on the new validator IDs. She repeats this.

        - Mallory is registered through registerAsBnftHolder, which only an admin can do.

        - isLpBnftHolder is true (set by an admin through updateBnftMode).

        - Active bids exist from node operators approved for the EETH source.

        - totalValueInLp >= 32 ether * n for the batch size.

        ##### What they get

        Mallory receives 2 ETH of pool ETH for each cancelled validator and pays nothing but gas. The bid goes back into the auction on cancel, so she can reuse the same bids and repeat until the pool's ETH is gone. The stolen ETH belongs to every eETH holder. The pool's totalValueInLp is never reduced, so eETH keeps claiming ETH the pool no longer holds. Withdrawals then fail or are paid out of other users' funds.

        ##### How it works

        1. Mallory calls batchDepositWithLiquidityPoolAsBnftHolder (LiquidityPool.sol:298-301). This requires msg.value == 0 because _stakerDepositAmountPerValidator is 0 (LiquidityPool.sol:317).

        2. StakingManager records Mallory as the staker and sets each validator to STAKE_DEPOSITED (StakingManager.sol:425-441).

        3. Mallory calls batchCancelDeposit (LiquidityPool.sol:381-383). _batchCancelDeposit adds 2 ETH per validator that is not WAITING_FOR_APPROVAL (LiquidityPool.sol:391-398).

        4. StakingManager.batchCancelDepositAsBnftHolder checks that Mallory is the staker, unregisters the validator, and re-activates the bid (StakingManager.sol:448-457). It refunds nothing itself because the caller is the pool.

        5. The pool sends returnAmount to Mallory out of pooled ETH and leaves totalValueInLp unchanged (LiquidityPool.sol:403).

        Exploit scenario

        Not specified.

        Recommendation

        Record the amount each B-NFT holder actually deposited per validator, for example in a mapping set inside _batchDeposit. Refund only that amount, minus the 1 ETH already sent to the beacon deposit contract after registration. Alternatively, refund 0 ETH when the validator was created in isLpBnftHolder mode. Also update totalValueInLp for any ETH that leaves the pool. To check the fix, add a test that enables updateBnftMode(true), deposits with batchDepositWithLiquidityPoolAsBnftHolder, cancels, and asserts that the pool's ETH balance and the B-NFT holder's balance are unchanged.

        Devin Security (Deep)

        Pool-as-bond-holder mode refunds 2 ETH of pooled funds for deposits that cost 0 ETH

        src/LiquidityPool.sol:298 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        When the pool is switched into the mode where it holds the bond itself, any address the admin registered as a bond holder can reserve validators for free, cancel them, and collect 2 ETH of other depositors' ETH per validator, again and again until the pool is empty.

        ##### What's wrong

        This is a refund that does not match what was paid. In isLpBnftHolder mode _batchDeposit takes 0 ETH from the caller, but batchCancelDeposit has no mode check and always pays back a fixed 2 ETH (1 ETH after registration) per validator out of the pool's own balance.

        ##### Who can do it

        Alice deposits ETH into the ether.fi pool and holds eETH. Acme Staking is an address the ether.fi admin registered as a bond holder with registerAsBnftHolder, and the admin has switched the pool into "pool holds the bond" mode with updateBnftMode(true). Mallory controls the Acme Staking address. She calls batchDepositWithLiquidityPoolAsBnftHolder with 25 open bids, then batchCancelDeposit with the returned validator ids, in the same block, and repeats.

        - isLpBnftHolder is true (admin toggle; the mode is implemented and exercised by test_bnftFlowWithLiquidityPoolAsBnftHolder).

        - The attacker address is registered in bnftHoldersIndexes (an admin action).

        - Active auction bids from operators approved for the EETH source exist; cancelled bids go back into the auction, so the same bids can be reused.

        - The pool has at least 32 ETH per validator in totalValueInLp and 2 ETH per validator of real balance.

        ##### What they get

        Mallory receives 2 ETH per validator per cycle, up to 50 ETH per transaction, and can repeat until the pool's ETH balance is gone. The refund does not reduce totalValueInLp, so Alice and every other eETH holder still see their balance but the pool can no longer honor withdrawals. The loss falls on all eETH holders; nothing outside the pool is touched.

        ##### How it works

        1. LiquidityPool.batchDepositWithLiquidityPoolAsBnftHolder (src/LiquidityPool.sol:298-301) calls _batchDeposit with a per-validator deposit of 0, so the msg.value check at line 317 passes with no ETH sent.

        2. StakingManager.batchDepositWithBidIds records the caller as the staker of each new validator (src/StakingManager.sol:426) and the phase becomes STAKE_DEPOSITED.

        3. The caller calls LiquidityPool.batchCancelDeposit (src/LiquidityPool.sol:381-383), which does not check the mode and adds 2 ether per validator to returnAmount (line 396).

        4. StakingManager.batchCancelDepositAsBnftHolder accepts because the caller is the recorded staker (src/StakingManager.sol:449) and returns the bids to the auction (line 457).

        5. _sendFund(_bnftStaker, returnAmount) (src/LiquidityPool.sol:403) pays 2 ETH per validator from the pool's balance without changing totalValueInLp.

        Exploit scenario

        Not specified.

        Recommendation

        Store the amount each staker actually paid per validator (or the bond mode in effect) at deposit time and refund only that amount; in pool-as-bond-holder mode the refund for unregistered and registered validators should be 0. Any refund that does come out of pooled ETH should also reduce totalValueInLp. Verify with a test that enables updateBnftMode(true), deposits as a registered holder, cancels, and asserts both the holder's and the pool's ETH balances are unchanged.

        Claude Security (Sonnet 5.5)

        Cancelling an LP-as-BNFT-holder deposit refunds 1 or 2 ETH to a holder who deposited nothing

        src/LiquidityPool.sol:403 Predicted severity: Medium

        Root cause

        Vulnerable symbol: _batchCancelDeposit

        Preconditions: LP-BNFT mode is enabled (isLpBnftHolder = true), which is non-default; Attacker is an admin-registered BNFT holder and has an active bid from an EETH-approved operator

        Offending code:

        _sendFund(_bnftStaker, returnAmount);

        Impact

        Drains LP's liquid ETH, which belongs to eETH holders and pending withdrawal claimants, while totalValueInLp stays unchanged. This leaves the pool insolvent and makes withdrawals revert in _sendFund.

        Description

        In LP-BNFT mode, batchDepositWithLiquidityPoolAsBnftHolder takes 0 ETH from the holder (_stakerDepositAmountPerValidator = 0), but _batchCancelDeposit refunds fixed constants (2 ETH before register, 1 ETH after register) without consulting the mode or any recorded contribution, paying them out of LP's pooled ETH.

        Exploit scenario

        Admin enables updateBnftMode(true). A registered BNFT holder (also an operator approved for EETH, holding an active bid) calls batchDepositWithLiquidityPoolAsBnftHolder with 0 ETH and then LiquidityPool.batchCancelDeposit for the same ids. Each cancel pays 2 ETH from LP. The bid re-enters the auction, so the loop can be repeated in one transaction or one block. The totalValueInLp + msg.value >= 32 ether * n guard in _batchDeposit only reads accounting, which the drain never reduces, so it keeps passing until the real balance is exhausted. Toggling the mode between deposit and cancel gives the same result. Reasoned from code; not executed.

        Recommendation

        Record each validator's holder contribution at deposit time (or the mode) and refund only what was contributed. In LP mode refund 0 to the holder; for the 1 ETH forfeited in a post-register cancel, charge the LP's own pool accounting. Also make updateBnftMode revert while numPendingDeposits > 0 or any validator is in WAITING_FOR_APPROVAL.

        Claude Security (Opus 5.5)

        In LP-as-BNFT-holder mode, cancelling refunds 2 ETH (or 1 ETH) per validator that the caller never paid, letting a BNFT holder drain the pool

        src/LiquidityPool.sol:403 Predicted severity: High

        Root cause

        Vulnerable symbol: _batchCancelDeposit

        Preconditions: Attacker is a registered BNFT holder (admin registerAsBnftHolder); Admin has enabled LP-as-BNFT-holder mode via updateBnftMode(true); Active auction bids from operators eligible for the EETH source exist; LiquidityPool not paused

        Offending code:

        _sendFund(_bnftStaker, returnAmount);

        Impact

        A non-admin role (registered BNFT holder) can steal all ETH held by the LiquidityPool, which belongs to eETH holders. totalValueInLp is not reduced, so eETH stays overvalued, and later withdrawals and validator spin-ups fail for lack of balance.

        Description

        When isLpBnftHolder is true, batchDepositWithLiquidityPoolAsBnftHolder lets a registered BNFT holder start validators with 0 ETH. batchCancelDeposit (open to any staker) still always pays the caller 2 ETH per STAKE_DEPOSITED validator, or 1 ETH per WAITING_FOR_APPROVAL validator, out of the LP's ETH. The refund is authorized only by 'caller is the staker', not by what the caller actually deposited. Also CWE-372: batchDepositWithLiquidityPoolAsBnftHolder is non-payable and calls _batchDeposit with a 0 ETH per-validator stake. _batchCancelDeposit still refunds a fixed 2 ETH (STAKE_DEPOSITED) or 1 ETH (WAITING_FOR_APPROVAL) per validator to the caller. Nothing records how much the BNFT player actually deposited, so the refund comes out of eETH holders' liquidity.

        Exploit scenario

        With LP mode on, a registered BNFT holder calls batchDepositWithLiquidityPoolAsBnftHolder(bids, 25) and sends no ETH. In the same or the next transaction they call batchCancelDeposit on the 25 new IDs. All are STAKE_DEPOSITED, so the LP sends them 50 ETH, and StakingManager puts the bids back into the auction. The deposit check totalValueInLp >= 32 ether * n keeps passing because the refunds never reduce totalValueInLp. Repeating the loop drains the LP's ETH balance. Cancelling after registration adds another 1 ETH loss per validator, since the LP already funded the 1 ETH beacon deposit.

        Recommendation

        Base the refund on what the staker actually escrowed. Record per validator whether the deposit was made in LP mode (0 ETH) and, if so, refund nothing to the caller. If the LP funded the 1 ETH registration deposit, account for that loss to the pool rather than paying the caller. Alternatively, block batchCancelDeposit for LP-mode validators and allow only admin cancellation without any payout. Also CWE-372: Store each validator's actual BNFT-player contribution, or the mode it was deposited under, and refund only that amount. Refund nothing for validators whose bond was funded by the LP.

        Vercel Security Review

        Zero-bond LP-funded reservations receive a 2 ETH cancellation refund

        src/LiquidityPool.sol:395 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. LP-funded mode lets registered bNFT holders reserve without paying ETH** - src/LiquidityPool.sol:298-300

        ```solidity title="src/LiquidityPool.sol:298-300"

        function batchDepositWithLiquidityPoolAsBnftHolder(uint256[] calldata _candidateBidIds, uint256 _numberOfValidators, uint256 _validatorIdToShareSafeWith) public whenNotPaused returns (uint256[] memory) {

        require(isLpBnftHolder, "IncorrectBnftMode");

        return _batchDeposit(_candidateBidIds, _numberOfValidators, 0 ether, _validatorIdToShareSafeWith);

        ```

        **2. Cancelling an unregistered reservation still credits the legacy bond refund** - src/LiquidityPool.sol:395-398

        ```solidity title="src/LiquidityPool.sol:395-398"

        } else {

        returnAmount += 2 ether;

        numPendingDeposits -= 1;

        }

        ```

        **3. The pool pays the caller despite their zero contribution** - src/LiquidityPool.sol:401-403

        ```solidity title="src/LiquidityPool.sol:401-403"

        stakingManager.batchCancelDepositAsBnftHolder(_validatorIds, _bnftStaker);

        _sendFund(_bnftStaker, returnAmount);

        ```

        The identity check accepts the reservation's legitimate staker. Cancellation reactivates its bid (StakingManager.sol:457), allowing repeated reserve/cancel cycles to drain depositor liquidity without validator registration or oracle approval.

        Exploit scenario

        Not specified.

        Recommendation

        Persist each reservation's actual user-funded bond and refund only its unspent portion. LP-funded reservations must never pay bond refunds to the initiating operator. Apply this to both pre-registration and WAITING_FOR_APPROVAL cancellations without relying on the current global mode.

      • Wrong rewards calculation due to numAssociatedValidators etherfi-6 · 1 writeup High

        V12

        Pending shared allocations recycle another validator's accrued yield

        src/StakingManager.sol:425 Predicted severity: High

        Root cause

        Safe recycling checks only the association count, not outstanding ETH or entitlement obligations. Pending allocations count as associated validators in the withdrawal branch, allowing the last real validator's rewards to survive teardown and change beneficiaries.

        Impact

        Accrued yield belonging to the original pool-backed validator can move to unrelated beneficiaries when a pending shared allocation outlives that validator and is then canceled. A holder that also controls the operator can position a new allocation to capture a recycled safe's residual rewards, including a portion previously attributable to pool depositors.

        Description

        A holder can allocate a second, still-pending validator sharing the safe of its existing pool-backed validator, provided the TNFT, BNFT and operator checks match. If the existing validator subsequently exits, getFullWithdrawalPayouts sees more than one associated validator and pays only principal, leaving accrued rewards in the safe. After that full withdrawal removes the exited validator, canceling the remaining STAKE_DEPOSITED allocation removes the last association. NodesManager puts the resulting nonempty safe on the reusable stack without distributing its residual rewards. When recycling is enabled, a subsequent allocation assigns those rewards to a new validator's owners and operator.

      • The BNFT holder is compared with an incorrect address etherfi-7 · 2 writeups Medium

        V12

        Pool-owned bonds cannot satisfy shared-safe ownership checks

        src/LiquidityPool.sol:298 Predicted severity: Informational

        Root cause

        The shared-safe ownership check assumes the external staker is always the BNFT owner. Pool BNFT mode deliberately separates the external allocation actor from that entitlement owner.

        Impact

        The specific unresolved security question is whether deploying separate safes and EigenPods instead of the selected shared safe changes delegation, proof coverage, or operational custody assumptions for pool-funded validators. The missing fact is the operational requirement for shared custody/delegation in pool BNFT mode; the searched boundary includes pool and staking entrypoints, node allocation/restaking logic, NFT ownership rules, tests and scripts, which demonstrate the failed owner comparison but do not establish that security requirement.

        Description

        The shared-safe allocation branch requires the existing BNFT owner to equal _staker, which is always the external registered holder passed by the pool. In pool BNFT mode, however, successful registration mints that existing BNFT to address(this), the liquidity pool, rather than the external holder. Subsequent pool-mode deposits selecting an existing pool-owned validator as their shared-safe target therefore always fail WRONG_BNFT_OWNER, even when the pool owns both NFTs and the operator matches. Passing zero avoids the branch but forces allocation of another safe. The intended same-owner sharing path is thus locally unreachable for externally initiated pool-mode allocations; its effect on restaking security configuration is not established.

        Devin Security (Deep)

        Shared-safe join does not check who will receive the new validator's B-NFT, letting a B-NFT player skim rewards from pool-funded validators

        src/StakingManager.sol:431 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        After ether.fi switches the pool to act as the B-NFT holder, a previously approved B-NFT player can attach any number of pool-funded validators to their old withdrawal safe and collect the B-NFT share of all of their staking rewards.

        ##### What's wrong

        This is an incomplete invariant check. The protocol pays the whole safe's rewards to the owners of whichever validator id is passed to partialWithdraw, and relies on every validator in a shared safe having the same T-NFT owner, B-NFT owner and operator. _processDeposit enforces this only by checking the ownership of the *existing* validator against msg.sender and _staker. It does not know who the *new* validator's B-NFT will go to; that is decided later by the pool's isLpBnftHolder mode at registration time. The two can differ.

        ##### Who can do it

        Mallory is a B-NFT player that the admin registered. In the original mode she deposited validator A (2 ETH) and holds its B-NFT; the pool holds its T-NFT. The admin later calls updateBnftMode(true) so the pool becomes the B-NFT holder for new validators. Mallory now calls batchDepositWithLiquidityPoolAsBnftHolder(bids, n, A) with 0 ETH, choosing bids from A's operator, then registers them with batchRegisterWithLiquidityPoolAsBnftHolder.

        - Mallory is a registered B-NFT holder in the pool (admin-gated).

        - Mallory owns the B-NFT of at least one existing pool validator (from the earlier mode).

        - The pool has been switched to isLpBnftHolder == true, which the tests show is an intended mode.

        - The pool's restakeBnftDeposits flag matches the old safe's restaking setting.

        ##### What they get

        Safe S now holds validator A (B-NFT: Mallory) and validators B1..Bn (B-NFT: the pool), all funded 32 ETH each by the pool. Mallory calls the permissionless partialWithdraw(A) whenever rewards accrue. The payout is computed from the whole safe balance and sent to the owners of A, so Mallory receives the B-NFT share (about 8.4% with the default split) of the rewards of every pool-funded validator in the safe, which should have gone to the pool's depositors. She paid nothing for those validators. She can keep adding validators (25 per call) to grow the skim, and she also makes batchPartialWithdrawOptimized fail for the mixed set.

        ##### How it works

        1. In pool-as-B-NFT-holder mode, Mallory deposits new validators with _validatorIdToShareSafeWith = A and 0 ETH (src/LiquidityPool.sol:298-301, 314-320).

        2. _processDeposit (src/StakingManager.sol:434-436) checks only that the pool owns A's T-NFT, Mallory owns A's B-NFT, and the operators match, then registers the new id into A's safe (src/StakingManager.sol:437-440).

        3. Mallory registers via the pool path; _registerValidator mints the new B-NFT to the pool, not to Mallory (src/LiquidityPool.sol:311, src/StakingManager.sol:411).

        4. EtherFiNodesManager.partialWithdraw(A) computes payouts from the entire safe balance (src/EtherFiNodesManager.sol:504-531, src/EtherFiNode.sol:219-225) and pays them to A's owners (src/EtherFiNodesManager.sol:533-540), so Mallory receives the B-NFT share of all validators' rewards.

        Exploit scenario

        Not specified.

        Recommendation

        Enforce the invariant at registration rather than only at deposit: in _registerValidator, when the safe already has validators, require that _bNftRecipient and _tNftRecipient equal the B-NFT and T-NFT owners of an existing validator in that safe (or store the intended B-NFT recipient at deposit time and compare). Alternatively, in _processDeposit, reject sharing when the pool is in isLpBnftHolder mode and the shared validator's B-NFT is not owned by the pool. Test: create a validator in player mode, switch to updateBnftMode(true), attempt a shared-safe deposit against it and assert it reverts.

      • Queued withdrawals are not claimed by forcePartialWithdraw etherfi-8 · 1 writeup Medium

        V12

        Unclaimed router assets inflate immediate reward payouts

        src/EtherFiNode.sol:282 Predicted severity: Medium

        Root cause

        The node conflates claimable assets with locally available ETH when quoting immediate payouts. The caller's bounded or omitted claim step does not guarantee that every asset included in that quote has been transferred into the safe.

        Impact

        Mature queues larger than the manager's claim limit can block reward withdrawal transactions despite ample claimable assets, and retries do not reduce the queue because the transaction rolls back. A separate successful claim transaction or increased claim limit can recover the path; this is a reversible reward-withdrawal failure rather than demonstrated loss of principal.

        Description

        withdrawableBalanceInExecutionLayer includes all claimable router withdrawals, although those amounts are not yet held by the safe. getRewardsPayouts splits that entire sum for immediate payment through withdrawFunds. The manager's ordinary partial withdrawal claims only maxEigenlayerWithdrawals entries first, so additional matured entries remain included in the payout quote but unavailable to the ETH calls. Its forced partial-withdrawal path does not claim router entries at all. When the calculated payouts exceed the safe's actual balance, failed holder payments are redirected to the treasury and the final treasury payment reverts, rolling back even the bounded claims made earlier.

      • Deposit cancellation may fail if the etherFiNode version is not updated etherfi-9 · 1 writeup Medium

        V12

        Legacy pending deposits cannot complete migration-dependent lifecycle

        src/EtherFiNode.sol:120 Predicted severity: High

        Root cause

        ensureLatestVersion is enforced at node deregistration, but its cancellation caller does not perform the required migration. Registration also fails to establish a single authoritative lifecycle representation before changing the manager's phase.

        Impact

        Pending deposits associated with legacy safes can be blocked from refund, and registration can leave an already-funded validator represented as still pending. The condition requires a version-0 pending deposit at upgrade; the reviewed paths contain no successful ordinary staker-accessible migration for that state.

        Description

        unRegisterValidator requires version 1, but the manager's cancellation path calls it without first migrating a legacy version-0 safe. Pending legacy deposits therefore revert with NEED_TO_MIGRATE when their staker attempts cancellation. The registration path can update the manager's phase and fund the beacon without migrating the node, while EtherFiNodesManager.phase continues reading the legacy node phase for version-0 safes. When a later withdrawal helper attempts migration, the manager copies that old phase back over the newer manager record. Thus the version guard and legacy-phase fallback together leave upgrade-era pending validators without a coherent cancellation or registration-to-withdrawal path.

    • Euler FEE Flow Solidity Periodic fee-revenue auction system. Tasks 1 V12 1/1 Codex Sec 0/1 Pashov Opus 1/1 Pashov GPT-6 0/1 Devin 1/1 Devin (Deep) 1/1 Claude Sec 0/1 Claude Opus 0/1 Vercel 1/1

      Periodic fee-revenue auction system.

      Read the audit report
      • Front-running of the buy function euler-fee-flow-1 · 5 writeups Medium

        V12

        Unbound inventory permits payment after asset depletion

        src/FeeFlowController.sol:91 Predicted severity: High

        Root cause

        buy() has a price-side ceiling but no epoch binding or asset-delivery lower bounds. It treats a nonempty list of token addresses as sufficient even after another purchase depleted their balances.

        Impact

        An ordering adversary can acquire the inventory first while a pending buyer subsequently loses payment tokens for no assets. This is conditional on the buyer's price ceiling accepting the new epoch price and the selected tokens accepting zero transfers; an exact ceiling of p normally blocks the same-block 2p example.

        Description

        buy() bounds only the current payment price and deadline; it does not bind the transaction to an epoch or expected asset amounts. An earlier purchase can sweep the victim's selected assets and reset the auction before the victim's transaction executes. If the victim's maxPaymentTokenAmount also admits the reset price, the victim still pays even though the subsequent balance reads return zero. For example, with the tested multiplier of two and without hitting either price bound, a preceding purchase at price p makes a same-block victim pay 2p when its ceiling is at least 2p. The nonempty-array check does not prevent this because the original asset addresses remain in the victim's calldata.

        Pashov (Claude Opus 5.5 high)

        buy() is not bound to a specific auction epoch: front-run or reordered buyers pay the next epoch's (reset, higher) price for an already-drained contract

        src/FeeFlowController.sol:91 Predicted severity: High

        Root cause

        The auction state (Slot1) has no epoch identifier, and buy() does not let the caller commit to the epoch or price curve they observed. maxPaymentTokenAmount is an absolute price cap, not a binding to the auction instance. Because each epoch resets the price upward (to at least priceMultiplier x the last price, and at least minInitPrice), a transaction aimed at the old epoch can still pass the cap in the new one.

        Impact

        Buyers can lose payment tokens and get nothing (or dust) back. This is most likely near the end of an epoch, when the price is close to 0 and the next epoch starts at minInitPrice, or whenever a buyer sets a loose maxPaymentTokenAmount. A mempool observer or block builder can always reorder two competing buys so the loser pays the full new initPrice for an empty contract. They can also deliberately front-run a buyer, take the assets, and leave the victim paying the reset price; that payment goes to paymentReceiver. The whitepaper's promised MEV resistance does not hold for honest bidders.

        Description

        FeeFlowController runs back-to-back Dutch auctions. Each successful buy() sends the whole current asset balance to the buyer and immediately starts a new epoch whose initPrice is max(paymentAmount * priceMultiplier, minInitPrice) and whose startTime is block.timestamp. buy() takes no argument naming which epoch the caller means to settle. Its only protections are deadline and maxPaymentTokenAmount. A buy transaction signed against epoch N can therefore run in epoch N+1, after another buyer has already settled epoch N, taken every asset, and reset the price. The late transaction still passes all checks as long as the new price is <= maxPaymentTokenAmount. It then pulls payment from the caller and transfers the remaining balances, which are zero or near zero.

        Exploit scenario

        1) Epoch N nears its end: the price has decayed to roughly 0.3 PAY and the contract holds fee tokens worth 50 PAY. minInitPrice = 1 PAY. 2) Victim submits buy([FEE], victim, deadline, maxPaymentTokenAmount = 2 PAY), allowing headroom for gas/price variance. 3) Attacker sees it in the mempool and front-runs with buy([FEE], attacker, ...), paying ~0.3 PAY and receiving all 50 PAY of fees. The new epoch starts at initPrice = max(0.6, 1) = 1 PAY with startTime = now. 4) The victim's transaction runs in the same block: getPrice() = 1 PAY <= 2 PAY, so the victim pays 1 PAY to paymentReceiver and gets a zero balance of FEE. Epoch N+1 is now settled at 1 PAY and the next initPrice becomes 2 PAY. The same thing happens without any attacker whenever two bidders race and the builder orders them.

        Recommendation

        Bind each purchase to an auction instance. Add a monotonically increasing epochId to Slot1 (it fits in the spare bits next to initPrice/startTime). Make buy() take epochId and revert with EpochIdMismatch if it differs from the stored value. Increment epochId each time an auction settles. Optionally also let callers require minimum asset amounts received.

        Devin Security

        buy() is not tied to an auction epoch, so a front-run or same-block buy makes a later buyer pay for an empty auction

        src/FeeFlowController.sol:91 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who front-runs a buyer can make that buyer pay up to their own price cap and receive nothing, because a buy is not bound to the auction it was meant for.

        ##### What's wrong

        This is a missing replay or ordering guard. buy() takes assets, deadline and maxPaymentTokenAmount, but no epoch identifier. When an earlier buy in the same epoch drains the assets and resets the auction, a later pending buy still runs. It pays the new auction price and receives zero balances.

        ##### Who can do it

        Alice, a searcher, sends buy() near the end of an epoch. The price has decayed to near zero, so she sets maxPaymentTokenAmount to cover minInitPrice as slippage room. Mallory, any address on the network, sees Alice's transaction in the mempool. Mallory submits her own buy() first with a higher gas price.

        - Mallory only needs to send a normal buy() transaction ordered before Alice's.

        - Alice's maxPaymentTokenAmount must be at least the reset price. The reset price is paymentAmount * priceMultiplier / 1e18, or minInitPrice at minimum.

        - The same thing happens without malice when two buyers land in the same block.

        ##### What they get

        Mallory gets all the accumulated fee assets. Alice's transaction then pays the fresh auction price (the full initPrice, since no time has passed) to paymentReceiver and gets zero tokens back. Alice loses up to her maxPaymentTokenAmount. The loss is capped by her own slippage setting, and the lost funds go to the protocol's receiver, not to Mallory.

        ##### How it works

        1. Mallory's buy() runs first. It moves every asset balance out of the contract (FeeFlowController.sol:106-110) and resets slot1 with a new initPrice and startTime = block.timestamp (lines 113-125).

        2. Alice's buy() runs next. The only checks are the deadline, a non-empty assets array, and paymentAmount <= maxPaymentTokenAmount (lines 92-100).

        3. getPriceFromCache returns the full new initPrice, because timePassed is 0 (lines 139-145).

        4. If that price fits under Alice's cap, she pays it (line 103). The asset loop then transfers balances of 0 (lines 108-109), and the auction resets again at an even higher price.

        Exploit scenario

        Not specified.

        Recommendation

        Add an epoch counter to Slot1, for example a uint16 epochId next to initPrice and startTime. Make buy() take an epochId argument and revert when it does not match the stored value. Increment the counter on every buy. You could also let buyers pass a minimum amount they expect to receive for each asset. To check the fix, write a Foundry test that sends two buy() calls with the same epochId in one block. The second call must revert.

        Devin Security (Deep)

        buy() is not tied to a specific auction epoch, so a pending bid can pay the next epoch's price for an already-emptied controller

        src/FeeFlowController.sol:91 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone watching the mempool can front-run a bidder's buy() so that the bidder's transaction settles the *next* auction instead, paying up to their slippage cap to the protocol for a controller that no longer holds any assets.

        ##### What's wrong

        This is a missing epoch (auction round) binding on a settlement call. buy() only checks a wall-clock deadline and a price cap maxPaymentTokenAmount; nothing in the call says *which* auction the bidder meant to settle. As soon as one buy lands, the contract immediately starts a new auction at paymentAmount * priceMultiplier, and any still-pending buy() whose cap is at least that high will execute against the new auction and pull payment even though the assets were just swept.

        ##### Who can do it

        Alice runs a bidding bot for Acme DAO and submits buy(assets, alice, now + 10 min, 300 USDC) when the auction price is 250 USDC and the controller holds about 300 USDC of fees. Mallory, any searcher with a funded account, sees Alice's transaction in the public mempool and submits her own buy() at 250 USDC with higher gas. Mallory's buy lands first, takes the fees, and resets the auction to 250 * 1.1 = 275 USDC (or higher with a larger multiplier). Alice's transaction then executes: 275 USDC is below her 300 USDC cap, so the contract pulls 275 USDC from Alice and transfers her the controller's now-empty balances.

        - The victim's maxPaymentTokenAmount must be at least priceMultiplier times the price they expected (at least 1.1x; the repo's own tests pass caps far above the price).

        - The victim's deadline has not passed when their transaction is mined.

        - The attacker only needs a funded paymentToken balance and allowance; no special role.

        - The same loss happens without a deliberate attacker whenever two honest bids land in the same block or Alice's transaction is delayed past another buy.

        ##### What they get

        Mallory gets the auctioned fees at the normal price, which she could also get by honest competition, so she does not profit from Alice's loss directly. Alice loses up to her full maxPaymentTokenAmount in payment tokens to paymentReceiver and receives nothing in return. The loss is capped by the cap the victim chose and is limited to the single bidder whose transaction was overtaken; it does not touch other users' funds or the protocol's accrued fees.

        ##### How it works

        1. Alice submits buy() with a deadline and maxPaymentTokenAmount while the auction price is P (src/FeeFlowController.sol:91).

        2. Mallory front-runs with her own buy() at price P; the loop at src/FeeFlowController.sol:106-110 moves every listed asset out of the controller.

        3. Mallory's call writes a fresh auction with initPrice = P * priceMultiplier / 1e18 and startTime = now (src/FeeFlowController.sol:113-125).

        4. Alice's transaction executes next: the deadline check at line 92 passes, getPriceFromCache at line 98 now returns about P * priceMultiplier, and the cap check at line 100 passes because her cap was set above that.

        5. Line 103 pulls that amount from Alice to paymentReceiver; the loop at lines 106-110 transfers zero balances; Alice has paid for an empty auction. No parameter lets her say "only settle the auction that started at startTime S" and have the call revert otherwise.

        Exploit scenario

        Not specified.

        Recommendation

        Bind each bid to the auction it targets. Add an epochId (or the expected startTime) to Slot1 and to the buy() parameters, increment it on every successful buy, and revert with an EpochIdMismatch error when the caller's value does not match the stored one. Check it before any token transfer. To verify: write a Foundry test where buyer A and buyer B both prepare buy() with a generous maxPaymentTokenAmount; execute A's call first, then assert B's call reverts with the mismatch error and that B's payment token balance is unchanged.

        Vercel Security Review

        Front-run purchases can make pending buyers pay for empty auctions

        src/FeeFlowController.sol:91 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Purchases are not bound to an auction** - src/FeeFlowController.sol:91-93

        ```solidity title="src/FeeFlowController.sol:91-93"

        function buy(address[] calldata assets, address assetsReceiver, uint256 deadline, uint256 maxPaymentTokenAmount) external nonReentrant returns(uint256 paymentAmount) {

        if(block.timestamp > deadline) revert DeadlinePassed();

        if(assets.length == 0) revert EmptyAssets();

        ```

        An unprivileged bidder can front-run a pending purchase, take its requested inventory, and reset the auction (lines 113–125).

        **2. The stale purchase still pays** - src/FeeFlowController.sol:100-103

        ```solidity title="src/FeeFlowController.sol:100-103"

        if(paymentAmount > maxPaymentTokenAmount) revert MaxPaymentTokenAmountExceeded();

        if(paymentAmount > 0) {

        paymentToken.safeTransferFrom(sender, paymentReceiver, paymentAmount);

        ```

        If the victim's deadline remains valid and its cap covers the reset price—for example, 2P with a 2× multiplier—the next transaction transfers payment again.

        **3. Empty inventory does not revert** - src/FeeFlowController.sol:108-110

        ```solidity title="src/FeeFlowController.sol:108-110"

        uint256 balance = ERC20(assets[i]).balanceOf(address(this));

        ERC20(assets[i]).safeTransfer(assetsReceiver, balance);

        }

        ```

        For ERC20s accepting zero transfers, execution succeeds while the victim receives nothing and irreversibly loses its payment.

        Exploit scenario

        Not specified.

        Recommendation

        Add a monotonically increasing auction identifier, require buyers to supply the expected identifier, and reject mismatches before transferring payment. Increment it on every successful purchase. Consider per-asset minimum received amounts to protect buyers against inventory changes as well.

    • Gammaswap Staking Solidity Gammaswap staking and rewards. Tasks 2 V12 2/2 Codex Sec 1/2 Pashov Opus 1/2 Pashov GPT-6 1/2 Devin 1/2 Devin (Deep) 1/2 Claude Sec 1/2 Claude Opus 1/2 Vercel 1/2

      Gammaswap staking and rewards.

      Read the audit report
      • Vester incorrect burn gammaswap-staking-1 · 9 writeups High

        V12

        Vesting burns liquid tokens instead of escrow

        contracts/VesterNoReserve.sol:240 Predicted severity: High

        Root cause

        VesterNoReserve._updateVesting confuses the owner of vesting receipts with the custodian of the underlying escrow. It burns esGSb from _account even though _deposit moved that esGSb to address(this).

        Impact

        A fully deposited esGSb position cannot be claimed or withdrawn once positive vesting has accrued, because both operations first attempt the wrong-account burn. Maintaining additional liquid esGSb permits progress only by destroying assets outside the deposit, imposing an additional token loss on the vesting user.

        Description

        VesterNoReserve uses account-specific cumulative rewards from a reward tracker to admit vesting deposits, then transfers the deposited escrow tokens into the vester and mints nontransferable vesting receipts. On subsequent vesting progress, it burns those receipts and credits cumulativeClaimAmounts, but calls esToken.burn(_account, amount) rather than burning the escrow held by the vester. The configured RestrictedToken burns the exact supplied account's balance, and the router grants the loan vester permission to perform that burn. An account that deposited all its available esGSb therefore cannot advance a positive vesting amount without acquiring additional esGSb. If the account does hold additional tokens, the operation destroys those additional tokens while leaving the originally deposited vested escrow in the contract.

        Codex Security (GPT-6 Sol)

        Vesting esGSb can block claims and burn extra wallet tokens

        contracts/VesterNoReserve.sol:324 Predicted severity: High

        Root cause

        _deposit transfers esGSb into VesterNoReserve, but _updateVesting later passes _account to esToken.burn. The restricted token burns that account's real ERC20 balance. Both claim and withdrawal call this update, so the accounting transition requires a second wallet balance while the deposited tokens remain in escrow.

        Impact

        Normal vesting can block recovery of escrow and GS claims; spare esGSb is consumed. The path needs only a user deposit and passage of time, though impact depends on token balances.

        Description

        After VesterNoReserve escrows esGSb, its vesting update burns the user's wallet balance. A depositor who used their full balance cannot claim or withdraw after vesting accrues; one with spare esGSb loses those additional tokens.

        Exploit scenario

        user esGSb -> vester escrow -> vesting update -> burn(_account, amount) -> user wallet balance

        Recommendation

        Burn esGSb from address(this) in VesterNoReserve._updateVesting, matching the deposit custody address.

        Pashov (Claude Opus 5.5 high)

        VesterNoReserve burns vested esGSb from the user's wallet instead of the vester's escrow

        contracts/VesterNoReserve.sol:312 Predicted severity: High

        Root cause

        The wrong burn target in _updateVesting: burn(_account, amount) should be burn(address(this), amount). The vester is a handler on esGSb, so it can burn from any address.

        Impact

        (1) A user with no spare esGSb in their wallet hits an ERC20 burn underflow in every call that runs _updateVesting once some time has passed: claim, deposit and withdraw. Their escrowed esGSb and the GS already vested are frozen in the vester. Because StakingRouter.claim() also calls loanVester.claimForAccount, the router's main claim path reverts for that user too, which blocks claiming fee, esGS and other rewards through it. (2) A user who does hold extra esGSb loses it: the wallet balance is burned a second time while the escrowed copy stays in the vester forever. The vester's esGSb balance also grows without bound, so the esGSb supply is accounted wrongly.

        Description

        When esGSb is deposited for vesting, _deposit moves the tokens from the user into the VesterNoReserve contract (safeTransferFrom(_account, address(this), _amount)). As the escrowed amount vests, _updateVesting should burn the vested esGSb that the vester holds. Instead it calls IRestrictedToken(esToken).burn(_account, amount), which burns from the user's own wallet. The sibling Vester contract correctly burns address(this) (Vester.sol line 387).

        Exploit scenario

        Alice earns 100 esGSb and vests all of it through StakingRouter.vestEsGsb(100e18). Her wallet esGSb balance is now 0. One month later she calls StakingRouter.claim(). This reaches VesterNoReserve._claim, then _updateVesting, which computes about 8.2e18 vested and calls esGsb.burn(alice, 8.2e18). That reverts with 'burn amount exceeds balance'. Every later claim, deposit or withdraw also reverts, so her esGSb and the GS she is owed are locked permanently. If Bob instead keeps 50 unvested esGSb in his wallet, each claim silently destroys part of those 50 tokens.

        Recommendation

        Burn from the vester's own balance, matching Vester: IRestrictedToken(esToken).burn(address(this), amount);. Add tests that vest, warp time, then claim and withdraw on VesterNoReserve.

        Pashov (Codex GPT-6 Sol high)

        Vesting burns the user's wallet tokens instead of escrowed esGSb

        contracts/VesterNoReserve.sol:324 Predicted severity: High

        Root cause

        _updateVesting passes _account to IRestrictedToken.burn, while _deposit escrows esToken in address(this).

        Impact

        High severity because the ordinary vesting path can freeze both the claim and escrowed principal and can burn extra wallet tokens. Vested GS is frozen for ordinary users, and users who hold extra esGSb lose tokens beyond the amount they deposited. Escrowed tokens remain unburned, breaking the intended supply conversion.

        Description

        When vesting advances, the contract burns esGSb from the beneficiary's wallet even though deposit transferred the vesting principal into the vester. A beneficiary with no additional wallet esGSb cannot claim or withdraw after any amount has vested. If the beneficiary has wallet esGSb, the claim destroys those extra tokens while leaving the escrowed principal unburned.

        Exploit scenario

        A user deposits their entire esGSb balance and waits for vesting. On claim, _updateVesting computes a positive amount, then burn(user, amount) reverts because the wallet balance is zero; withdrawal also calls _claim and reverts.

        Recommendation

        Burn esToken from address(this), the escrow holder, when vesting advances.

        Devin Security

        Loan vester burns vested esGSb from the user's wallet instead of its own escrow, locking deposits

        contracts/VesterNoReserve.sol:313 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Every user who vests esGSb through the loan vester either loses esGSb from their wallet or gets their vested esGSb and GS rewards stuck, because each claim, deposit, or withdraw reverts once their wallet holds less esGSb than the newly vested amount.

        ##### What's wrong

        This is an accounting bug: the contract burns the wrong holder's tokens. When vesting progresses, _updateVesting should burn the esGSb that the vester itself holds in escrow. Instead it burns the same amount from the user's own wallet. The Vester contract it was copied from burns from address(this).

        ##### Who can do it

        Alice, a borrower on Acme's GammaSwap deployment, earns esGSb and calls vestEsGsb on the StakingRouter to deposit all of it into the loan vester. Her wallet now holds 0 esGSb. A week later she calls claim() to collect her vested GS. The call reverts, and so do later claims and withdrawEsGsb(). No attacker is needed. The flaw triggers during normal use.

        - The loan vester (coreTracker.loanVester) is deployed by setupGsStakingForLoan.

        - The user has deposited esGSb and some time has passed.

        - The user's wallet esGSb balance is below the amount vested since the last update. If it is not, the wallet tokens are burned.

        ##### What they get

        Alice cannot claim her vested GS, and she cannot withdraw her escrowed esGSb, because _withdraw first calls _claim, which calls _updateVesting. Her tokens stay locked in the vester for good. If Alice does hold extra esGSb in her wallet, it is silently burned, while the escrowed copy stays in the vester and is never burned. This affects every user of the loan vester. The GS-side Vester and the pool vesters are not affected.

        ##### How it works

        1. StakingRouter.vestEsGsb calls depositForAccount on the loan vester, and _deposit moves the user's esGSb into the vester (VesterNoReserve.sol:245).

        2. On a later claim, deposit, or withdraw, _updateVesting computes the vested amount and reduces the user's vester balance (VesterNoReserve.sol:313-322).

        3. It then calls IRestrictedToken(esToken).burn(_account, amount), which burns from the user's wallet instead of the vester's escrow (VesterNoReserve.sol:324).

        4. RestrictedToken.burn calls ERC20 _burn, which reverts when the wallet balance is too low, so the whole transaction reverts (RestrictedToken.sol:39-43).

        5. _withdraw calls _claim first, so the user also cannot get the escrowed esGSb back (VesterNoReserve.sol:291-302).

        Exploit scenario

        Not specified.

        Recommendation

        Change line 324 to IRestrictedToken(esToken).burn(address(this), amount); to match Vester.sol. To check the fix, add a test that deposits a user's entire esGSb balance into the loan vester and advances time. Then confirm that claim() and withdraw() succeed and the user receives GS. Also confirm that the vester's esGSb balance drops by the vested amount and the user's wallet balance does not change.

        Devin Security (Deep)

        VesterNoReserve burns vested esGSb from the user's wallet instead of from the vester, which bricks claims and withdrawals

        contracts/VesterNoReserve.sol:312 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Any user who vests esGSb in the loan vester either loses extra esGSb from their wallet or, if their wallet is empty, can never claim their GS or withdraw their deposit again.

        ##### What's wrong

        This is a wrong-account burn. On deposit the vester pulls esGSb from the user into itself. When tokens vest, _updateVesting calls esToken.burn(_account, amount), burning from the user's wallet, while the matching line in Vester burns from address(this). The deposited esGSb stays locked in the vester and the user is charged a second time.

        ##### Who can do it

        Alice, a borrower at Acme Capital, earns esGSb and calls StakingRouter.vestEsGsb to vest all of it. A day later she calls StakingRouter.claim. Nobody attacks her; the contract burns from the wrong balance.

        - Alice has deposited esGSb into the loan vester (coreTracker.loanVester).

        - Some vesting time has passed so _getNextClaimableAmount is non-zero.

        - Reaching the vester in the current wiring requires the owner to have enabled a path that gives users cumulativeRewards in the core loan reward tracker (for example setInPrivateStakingMode(false) on it through execute) or to have set bonusRewards or turned off hasMaxVestableAmount; with the default wiring StakingRouter.stakeEsGsb targets the main reward tracker, where esGSb is not a deposit token, so the vest cap starts at zero.

        ##### What they get

        If Alice holds no spare esGSb, every claim, withdraw, and further deposit on the loan vester reverts inside _updateVesting, so her deposited esGSb and the GS it should turn into are stuck forever. Because StakingRouter.claim calls the loan vester for every user, her router-level claim also reverts and she must claim each tracker directly. If Alice does hold spare esGSb, the vester burns it from her wallet while keeping her deposit, so she pays twice for the GS she receives. This affects every Acme user who uses the loan vester; it does not cross into other users' balances.

        ##### How it works

        1. Alice deposits; _deposit transfers her esGSb into the vester and mints her a vester balance (contracts/VesterNoReserve.sol:245-247).

        2. Later she claims; _claim calls _updateVesting (contracts/VesterNoReserve.sol:278-279).

        3. _updateVesting computes the vested amount, reduces her vester balance, and then calls IRestrictedToken(esToken).burn(_account, amount) against her wallet, not the vester (contracts/VesterNoReserve.sol:321-324).

        4. RestrictedToken.burn reverts if her wallet balance is below amount, which makes claim, withdraw, and deposit all fail from then on; if it succeeds, the tokens the vester holds are never burned (contracts/tokens/RestrictedToken.sol:39-43).

        5. The reserve-based Vester burns from address(this) on the same step, showing the intended behavior (contracts/Vester.sol:387).

        Exploit scenario

        Not specified.

        Recommendation

        Change line 324 to IRestrictedToken(esToken).burn(address(this), amount); to match Vester. Verify with a test that deposits a user's entire esGSb balance into VesterNoReserve, advances time, and confirms claim and withdraw succeed and that the vester's esGSb balance decreases by the vested amount while the user's wallet balance is unchanged.

        Claude Security (Sonnet 5.5)

        VesterNoReserve burns vested esGSb from the account's wallet using its handler privilege instead of from the vester's own escrow

        contracts/VesterNoReserve.sol:324 Predicted severity: Medium

        Root cause

        Vulnerable symbol: _updateVesting

        Preconditions: The loan vester (VesterNoReserve) is deployed via StakingAdmin.setupGsStakingForLoan and set as a handler of the esGSb RestrictedToken; The user has deposited esGSb and the vesting clock has advanced (or a handler acts on the account)

        Offending code:

        IRestrictedToken(esToken).burn(_account, amount);

        Impact

        Every vesting user of the loan vester is charged an extra esGSb burn from their wallet equal to the amount vested. The escrowed esGSb accumulates unburned and unrecoverable in the vester. Claims and withdrawals revert, locking the user's escrowed esGSb and vested GS, whenever the wallet balance is below the amount being vested. Handlers can also burn arbitrary accounts' esGSb through the vester.

        Description

        _updateVesting calls IRestrictedToken(esToken).burn(_account, amount), where _account is the vesting user (or any account named by a handler on claimForAccount/withdrawForAccount/depositForAccount). The vester holds the deposited tokens and is an esGSb handler (StakingAdmin.setupGsStakingForLoan:143), so RestrictedToken.burn (_validateHandler only) burns the third-party wallet balance with no allowance or consent. Vester.sol:387 burns address(this) instead. Also CWE-682: On deposit, VesterNoReserve pulls the user's esGSb into the vester (line 245) and credits balances[_account]. When vesting accrues, _updateVesting calls esToken.burn(_account, amount), which targets the user's wallet, not the vester's custody balance. Vester.sol correctly burns address(this). Also CWE-669: In VesterNoReserve._updateVesting (reached from deposit, claim, claimForAccount, withdraw and withdrawForAccount), the Vester uses its RestrictedToken handler privilege to call esToken.burn(_account, amount). That destroys the user's free wallet balance rather than the esGSb the Vester escrowed in _deposit, which the user never authorized. Vester.sol correctly burns address(this). Also CWE-863: VesterNoReserve._updateVesting calls the handler-only RestrictedToken.burn (which burns any account's balance without allowance) with the vesting user as target, although the esToken being consumed is held by the vester itself (deposited via safeTransferFrom(_account, address(this))). Vester.sol burns address(this) in the same spot. Also CWE-670: The vester is an esGsb handler, so RestrictedToken.burn lets it burn any address's balance with no allowance. _deposit moves the user's esGsb into the vester, but _updateVesting then burns the vested amount from the user's wallet (_account) instead of address(this). The sibling Vester.sol:387 correctly uses burn(address(this), amount).

        Exploit scenario

        A user vests esGSb through StakingRouter.vestEsGsb, which calls depositForAccount(msg.sender, D). The router is a handler of the vester, and RestrictedToken.transferFrom is handler-gated and ignores allowances, so D moves from the user's wallet to the vester. After time passes, the user (or the router on their behalf) calls claim, withdraw or claimForAccount. _updateVesting moves v from balances to cumulativeClaimAmounts and calls burn(_account, v). This burns v esGSb from the user's wallet while the D tokens in the vester are untouched. If the wallet holds less than v, which is the usual case after vesting the whole balance or staking the rest, the burn reverts. claim and withdraw then both revert, because _withdraw calls _claim first. The escrowed esGSb and the vested GS are frozen until the user receives fresh esGSb from elsewhere. If the wallet does hold enough, the user loses v esGSb from the wallet. withdraw then returns only the unvested D-v, and the vested v esGSb stays in the vester and is never burned. The user effectively pays twice for each vested token. Any handler can also point claimForAccount, withdrawForAccount or depositForAccount at an arbitrary victim and have that victim's esGSb wallet balance burned without consent.

        Recommendation

        Burn the escrowed tokens held by the vester, as Vester.sol does: IRestrictedToken(esToken).burn(address(this), amount). Never pass a user address to a privileged burn or transferFrom that skips allowance checks. Add tests covering claim and withdraw on VesterNoReserve, including a user whose wallet esGSb balance is zero. Also CWE-682: Burn the escrow tokens the vester actually holds: replace the call with IRestrictedToken(esToken).burn(address(this), amount), as Vester.sol does. Add test coverage for VesterNoReserve claim and withdraw. None exists in test/ today. Also CWE-863: Burn from the vester's own balance, as Vester.sol does: IRestrictedToken(esToken).burn(address(this), amount). Add tests for the loan vester's claim, withdraw and deposit flows. Also CWE-670: Change the call to IRestrictedToken(esToken).burn(address(this), amount), as Vester.sol does. Add a test that checks the vester's esGsb balance and total supply after vesting.

        Claude Security (Opus 5.5)

        VesterNoReserve uses its RestrictedToken handler burn right on the user's wallet instead of its own escrow, destroying unescrowed esGSb or freezing vesting

        contracts/VesterNoReserve.sol:324 Predicted severity: High

        Root cause

        Vulnerable symbol: _updateVesting

        Preconditions: setupGsStakingForLoan has run, which makes the loan vester an esGSb handler; The user has deposited esGSb into the loan vester (StakingRouter.vestEsGsb or VesterNoReserve.deposit) and some vesting time has passed

        Offending code:

        IRestrictedToken(esToken).burn(_account, amount);

        Impact

        Every loan-vester user loses esGSb they never put into vesting, or has their vesting position and GS claims frozen. The vester keeps escrowed esGSb that can never be recovered. No attacker is needed; normal use triggers it.

        Description

        RestrictedToken.burn (contracts/tokens/RestrictedToken.sol:39-42) lets any handler burn any account's balance with no allowance or consent, so it relies on each handler to name the right account. The loan vester is made an esGSb handler at StakingAdmin.sol:143. When it vests, it burns the vested amount from the user's own wallet (_account) instead of from its own escrow, where _deposit (line 245) put those tokens. Vester.sol:387 burns from address(this), which is correct. So the token's blanket handler permission is used on a balance the user never handed to the vester. Also CWE-669: _deposit moves the user's esGSb into the vester with safeTransferFrom(_account, address(this), _amount). _updateVesting then burns the vested portion from _account instead of address(this), unlike Vester.sol line 387. The vester is an esGSb handler, so RestrictedToken.burn lets it burn from any address. Also CWE-628: At line 324 the vester uses its esGsb RestrictedToken handler role to call burn(_account, amount). That role can burn from any address, needs no allowance and has no consent check (RestrictedToken.sol:39-42). The user only handed over the esGsb they deposited, which line 245 moved into address(this). Vester.sol:387 correctly burns from address(this), but here the vester destroys esGsb the user never deposited and leaves the deposited tokens stranded in the contract. Also CWE-441: At setup the loan vester is made an esGsb handler (StakingAdmin.sol:143). A handler can burn tokens from any address, with no allowance needed (RestrictedToken.sol:39-43). _updateVesting uses that power to burn amount from _account, meaning the user's free wallet balance, when it should burn the esGsb the vester already holds in escrow. Vester.sol:387 burns from address(this) correctly. The user never put those wallet tokens up for vesting, and the escrowed tokens are never burned.

        Exploit scenario

        A user deposits 100 esGSb into the loan vester, which leaves them with no esGSb in their wallet. Six months later they call claim, withdraw, deposit, or StakingRouter.claim(). Each of these calls _updateVesting, which tries to burn 50 esGSb from the user's wallet. The wallet is empty, so the ERC20 burn reverts. The user cannot claim GS or withdraw their escrowed esGSb. StakingRouter.claim() also calls loanVester.claimForAccount, so it reverts for this user and blocks the other reward claims bundled in it. A user who does hold esGSb in their wallet (for example, freshly claimed loan rewards) has that unescrowed balance burned instead. Either way, the matching escrowed esGSb stays stuck in the vester for good.

        Recommendation

        Burn the vester's own escrowed tokens: IRestrictedToken(esToken).burn(address(this), amount); as Vester.sol does. Also consider narrowing RestrictedToken.burn so non-manager handlers can burn only their own balance (_account == msg.sender) or must spend an allowance. That way a mistaken account argument in one handler cannot destroy third-party balances. Also CWE-669: Burn from the contract's escrow, as Vester does: IRestrictedToken(esToken).burn(address(this), amount). Also CWE-628: Burn from the vester's own escrow, matching Vester.sol: IRestrictedToken(esToken).burn(address(this), amount). More generally, the vester should never use its handler privileges on an account balance other than its own escrow. Also CWE-441: Burn the escrowed tokens held by the vester rather than the user's wallet: IRestrictedToken(esToken).burn(address(this), amount);. This matches Vester.sol:387.

        Vercel Security Review

        VesterNoReserve burns users' wallet tokens instead of deposited escrow

        contracts/VesterNoReserve.sol:324 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Deposits remove escrow from the user's wallet** - contracts/VesterNoReserve.sol:245-247

        ```solidity title="contracts/VesterNoReserve.sol:245-247"

        IERC20(esToken).safeTransferFrom(_account, address(this), _amount);

        _mint(_account, _amount);

        ```

        **2. Vesting burns an additional payment from that user** - contracts/VesterNoReserve.sol:321-324

        ```solidity title="contracts/VesterNoReserve.sol:321-324"

        _burn(_account, amount);

        cumulativeClaimAmounts[_account] = cumulativeClaimAmounts[_account] + amount;

        IRestrictedToken(esToken).burn(_account, amount);

        ```

        RestrictedToken.burn burns the specified account's balance, not the caller's (contracts/tokens/RestrictedToken.sol:39-42).

        **3. Cancellation cannot bypass the incorrect burn** - contracts/VesterNoReserve.sol:292-293

        ```solidity title="contracts/VesterNoReserve.sol:292-293"

        function _withdraw(address _account) private {

        _claim(_account, _account);

        ```

        _claim first updates vesting (278-279). Once vesting accrues, users without spare esGSb cannot claim or withdraw deposited escrow. Users with spare tokens lose those additional tokens while the corresponding deposited escrow remains stranded.

        Exploit scenario

        Not specified.

        Recommendation

        Burn vested esToken from address(this), where deposits are held, rather than from _account. Keep the user's vesting-receipt burn separate from the underlying escrow-token burn.

      • Cancellation of isDepositToken still allows rewards to be claimed gammaswap-staking-2 · 1 writeup Medium

        V12

        Disabling deposits also freezes existing principal

        contracts/RewardTracker.sol:73 Predicted severity: Low

        Root cause

        Deposit admission and withdrawal eligibility share isDepositToken, so disabling future deposits also disables exit from existing balances.

        Impact

        An owner configuration change can temporarily freeze principal already deposited in an asset that is no longer intended to admit new stakes. There is no unprivileged escalation: the demonstrated security consequence is confined to a privileged asset-disable operation and remains recoverable by that owner.

        Description

        RewardTracker.setDepositToken() can disable an asset even while its recorded deposits remain positive. The same eligibility flag gates both new staking and removal of existing deposits, so a disabled asset cannot be withdrawn despite a valid account-specific deposit balance. Reward settlement and claims do not require that flag and can continue, but no alternate principal-withdrawal function bypasses it. The child fee tracker inherits this setter and withdrawal check. Re-enabling the asset through the owner setter restores the path.

    • Hyperliquid Solidity Hyperliquid DEX bridge contracts. Tasks 2 V12 2/2 Codex Sec 1/2 Pashov Opus 2/2 Pashov GPT-6 2/2 Devin 2/2 Devin (Deep) 2/2 Claude Sec 2/2 Claude Opus 1/2 Vercel 1/2

      Hyperliquid DEX bridge contracts.

      Read the audit report
      • Withdrawal finalization does not work hyperliquid-1 · 9 writeups High

        V12

        Nested reentrancy guards permanently block custody withdrawals

        Bridge2.sol:60 Predicted severity: Critical

        Root cause

        The external batch and its private worker both use the same single-entry nonReentrant guard. There is no alternative reachable token-release or recovery entrypoint.

        Impact

        Custodied tokens cannot leave through the bridge's withdrawal mechanism, including fully authorized withdrawals whose dispute periods have elapsed. Neither validator rotation nor cold-authorized emergency unlocking removes the nested guard, making the custody freeze permanent within this implementation.

        Description

        batchedFinalizeWithdrawals() enters the inherited nonReentrant guard and calls finalizeWithdrawal() without leaving that guarded execution. The private finalizer applies the same guard again, so OpenZeppelin's single-entry guard rejects the first iteration of every nonempty batch. This rejection occurs before checking the withdrawal record, dispute period, completion flag, or token transfer. finalizeWithdrawal() is private and the batch loop is its only caller; the complete contract contains no alternate payout, cancellation, rescue, or custody-token replacement path. Deposits and valid withdrawal requests can therefore succeed while withdrawal settlement cannot.

        Codex Security (GPT-6 Sol)

        Finalizing any withdrawal batch reverts and traps bridge tokens

        Bridge2.sol:302 Predicted severity: Critical

        Root cause

        A caller supplies a withdrawal message to the only public finalizer. That function activates nonReentrant and calls the private helper without leaving the guarded call. The helper applies the same modifier, so OpenZeppelin's reentrancy guard rejects the nested entry before the stored withdrawal can reach the transfer. The private helper has no other public caller.

        Impact

        Every valid withdrawal is blocked, so all tokens held by this deployed contract remain inaccessible through its withdrawal interface. The failure is unconditional for nonempty batches.

        Description

        batchedFinalizeWithdrawals() enters the reentrancy guard and calls finalizeWithdrawal(), which enters the same guard again. Every nonempty batch reverts before the token transfer, leaving requested withdrawals unclaimable through the only public finalization path.

        Exploit scenario

        Caller-controlled message array -> public guarded batch -> private guarded finalizer -> revert before usdcToken.transfer.

        Recommendation

        Remove nonReentrant from the private finalizeWithdrawal() helper and keep it on the external batch entry; verify all token release paths share a single effective guard.

        Pashov (Claude Opus 5.5 high)

        Nested nonReentrant on private finalizeWithdrawal makes batchedFinalizeWithdrawals always revert, permanently freezing all withdrawals

        audit/Bridge2.sol:284 Predicted severity: High

        Root cause

        The nonReentrant modifier is applied to a private helper that is only reachable from another nonReentrant function. The guard is not reentrant-safe for internal nested calls.

        Impact

        No withdrawal can ever be finalized. All USDC deposited into the bridge, and every requested withdrawal, is permanently locked in the contract. The contract has no upgrade or rescue path.

        Description

        batchedFinalizeWithdrawals is the only external way to finalize a withdrawal. It has the nonReentrant modifier and calls the private finalizeWithdrawal, which also has nonReentrant. In OpenZeppelin's ReentrancyGuard, the outer call sets the status to _ENTERED. The inner modifier then sees _ENTERED and reverts with 'ReentrancyGuard: reentrant call'. Every call that passes at least one message therefore reverts.

        Exploit scenario

        A user calls requestWithdrawal with valid validator signatures and waits out the dispute period. They then call batchedFinalizeWithdrawals([message]). The outer nonReentrant sets _status = _ENTERED. finalizeWithdrawal's nonReentrant then reverts, so the user can never get their USDC. This happens on every attempt for every user, with no attacker needed.

        Recommendation

        Remove nonReentrant (and the redundant whenNotPaused) from the private finalizeWithdrawal and keep the guard only on the external batchedFinalizeWithdrawals entry point.

        Pashov (Codex GPT-6 Sol high)

        Every nonempty withdrawal finalization batch reverts, freezing bridged funds

        Bridge2.sol:284 Predicted severity: Critical

        Root cause

        A private function and its calling external entry point both use the same contract-wide nonReentrant guard.

        Impact

        No requested withdrawal can be finalized, so all assets deposited into the bridge are frozen on Arbitrum through the intended withdrawal path.

        Description

        The only externally reachable withdrawal finalizer calls finalizeWithdrawal from batchedFinalizeWithdrawals. Both functions carry OpenZeppelin's nonReentrant modifier. The outer call enters the guard, and the first inner invocation re-enters the same guard and reverts. There is no other public path to finalizeWithdrawal.

        Exploit scenario

        A user submits a valid signed withdrawal, waits past the dispute period, and calls batchedFinalizeWithdrawals with that message. The transaction reverts at the nested guard before marking the withdrawal finalized or transferring USDC.

        Recommendation

        Keep nonReentrant on the external batch entry point and remove it from the private helper; route any future external single-item finalizer through a guarded entry point.

        Devin Security

        Nested nonReentrant guard makes every withdrawal finalization revert, freezing all bridged USDC

        Bridge2.sol:284 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        No user can ever finalize a withdrawal, so all USDC deposited into the bridge is permanently stuck in the contract.

        ##### What's wrong

        This is a self-reentrancy lockout. batchedFinalizeWithdrawals holds the OpenZeppelin nonReentrant lock and then calls finalizeWithdrawal, which also has nonReentrant. OpenZeppelin's guard reverts with "ReentrancyGuard: reentrant call" whenever a guarded function runs while the lock is already held. finalizeWithdrawal is private, so batchedFinalizeWithdrawals is the only way to release funds, and it always reverts once the batch is non-empty.

        ##### Who can do it

        No attacker is needed. Alice, a trader at Acme Corp, deposits 100,000 USDC, trades on the L1, and requests a withdrawal with valid validator signatures. After the dispute period she calls batchedFinalizeWithdrawals([message]). The call reverts every time.

        - Any withdrawal request exists (or none; the bug affects all of them).

        - The contract is deployed as written with the OpenZeppelin ReentrancyGuard.

        ##### What they get

        Every user's withdrawal fails. Deposits keep working, so the contract keeps taking in USDC that can never leave. The contract has no admin transfer, upgrade, or rescue function, so validators cannot recover the funds either. All USDC held by the bridge is frozen for every user.

        ##### How it works

        1. A user calls batchedFinalizeWithdrawals at Bridge2.sol:302, which enters nonReentrant and sets the lock.

        2. The loop at Bridge2.sol:306-308 calls finalizeWithdrawal.

        3. finalizeWithdrawal at Bridge2.sol:284 is also nonReentrant, sees the lock is held, and reverts.

        4. The revert undoes the whole transaction, so the USDC transfer at Bridge2.sol:291 never happens.

        Exploit scenario

        Not specified.

        Recommendation

        Remove nonReentrant (and the duplicate whenNotPaused) from the private finalizeWithdrawal, and keep the guard only on batchedFinalizeWithdrawals. To check the fix, add a test that requests a withdrawal, waits past the dispute period, calls batchedFinalizeWithdrawals, and asserts that the user's USDC balance increases and FinalizedWithdrawal is emitted.

        Devin Security (Deep)

        Nested nonReentrant on finalizeWithdrawal makes every withdrawal finalization revert, locking all bridged USDC forever

        Bridge2.sol:284 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Every USDC deposit into this bridge is stuck forever, because the only function that can release a withdrawal always reverts.

        ##### What's wrong

        This is a nested re-entrancy guard. OpenZeppelin's nonReentrant modifier reverts when a function marked nonReentrant is called while another nonReentrant function on the same contract is already running. batchedFinalizeWithdrawals is marked nonReentrant and it calls the private finalizeWithdrawal, which is also marked nonReentrant. The inner guard sees the outer guard's "entered" flag and reverts with "ReentrancyGuard: reentrant call". batchedFinalizeWithdrawals is the only caller of finalizeWithdrawal, and finalizeWithdrawal holds the only usdcToken.transfer in the contract. So no USDC can ever leave the contract.

        ##### Who can do it

        Alice, a trader at Acme Capital, deposits 1,000,000 USDC into the bridge with deposit. The L1 credits her and later she asks to withdraw. The validators sign the withdrawal, she calls requestWithdrawal, and the dispute period passes. Then she (or the bridge watcher bot) calls batchedFinalizeWithdrawals with her message. The call reverts every time. No attacker is needed; this happens to every user by default.

        - The contract is deployed as written, with finalizeWithdrawal marked nonReentrant.

        - The OpenZeppelin ReentrancyGuard in use is any released version; all of them reject nested nonReentrant calls.

        ##### What they get

        Nobody gains, but every depositor loses. All USDC sent to the bridge is locked permanently. The contract has no admin withdraw, no rescue function and no upgrade path, and the cold validator keys cannot move tokens either. The L1 side already debited the user's balance when the withdrawal was requested, so the money is gone on both sides. This affects every user of the bridge and the full bridge balance.

        ##### How it works

        1. A user deposits USDC through deposit (Bridge2.sol:241), which moves tokens into the contract.

        2. The user later calls requestWithdrawal (Bridge2.sol:249) with a validator-signed voucher, and the request is recorded.

        3. After the dispute period, anyone calls batchedFinalizeWithdrawals (Bridge2.sol:302). Its nonReentrant modifier sets the guard status to "entered".

        4. The loop calls finalizeWithdrawal (Bridge2.sol:284). That function's own nonReentrant modifier checks the status, finds "entered", and reverts.

        5. The whole transaction reverts before usdcToken.transfer (Bridge2.sol:291) runs. Since this is the only transfer out of the contract, the tokens can never leave.

        Exploit scenario

        Not specified.

        Recommendation

        Remove nonReentrant (and the redundant whenNotPaused) from the private finalizeWithdrawal, keeping both modifiers on the external batchedFinalizeWithdrawals. Verify with a test that deposits, calls requestWithdrawal with a valid voucher, advances time and blocks past the dispute period, and then calls batchedFinalizeWithdrawals with that one message; assert the user's USDC balance increases and FinalizedWithdrawal is emitted. This is the test that tests/example.rs:139 marks as still missing.

        Claude Security (Sonnet 5.5)

        Nested nonReentrant makes batchedFinalizeWithdrawals always revert, permanently locking all deposited USDC

        Bridge2.sol:284 Predicted severity: Critical

        Root cause

        Vulnerable symbol: finalizeWithdrawal / batchedFinalizeWithdrawals

        Preconditions: OpenZeppelin ReentrancyGuard semantics, where a nested nonReentrant call reverts (the import path security/ReentrancyGuard.sol indicates OZ 4.x). The OZ source is not in the staged files, so this is based on known library behaviour.

        Offending code:

        function finalizeWithdrawal(bytes32 message) private nonReentrant whenNotPaused {

        Impact

        No withdrawal can ever be finalized, because finalizeWithdrawal is private and batchedFinalizeWithdrawals is the only path to it. Every USDC deposit is permanently locked in the bridge. Nothing in the contract fixes this, because there is no upgrade path and no other transfer-out function.

        Description

        batchedFinalizeWithdrawals is external nonReentrant and is the only caller of the private finalizeWithdrawal, which is also marked nonReentrant. OpenZeppelin's ReentrancyGuard reverts when a nonReentrant function is entered while _status is already ENTERED, so any non-empty batch reverts. This is outside the memory/overflow lens but is a complete, deterministic path to permanent loss of funds. Also CWE-862: finalizeWithdrawal is reachable by anyone through batchedFinalizeWithdrawals with an arbitrary bytes32. It never checks requestedWithdrawals[message].requestedTime != 0, so a message that was never authorised by a validator quorum passes the dispute-period check with a zero-valued Withdrawal and is flagged finalized.

        Exploit scenario

        A user deposits USDC and later obtains validator signatures, then calls requestWithdrawal, which succeeds and records the pending withdrawal. After the dispute period the user calls batchedFinalizeWithdrawals([message]). The outer nonReentrant sets _status to ENTERED. The inner call to finalizeWithdrawal runs the nonReentrant modifier again, which sees _status == ENTERED and reverts with 'ReentrancyGuard: reentrant call'. Every attempt reverts the same way, so the funds are stuck. Only an empty array succeeds.

        Recommendation

        Remove nonReentrant and whenNotPaused from the private finalizeWithdrawal and keep them on the external batchedFinalizeWithdrawals. Alternatively remove nonReentrant from the external wrapper and keep it on the inner function. Add a test that finalizes a withdrawal. Also CWE-862: Add require(withdrawal.requestedTime != 0, "Withdrawal not requested") at the start of finalizeWithdrawal, and consider SafeERC20 for transfers.

        Claude Security (Opus 5.5)

        Nested nonReentrant guard makes batchedFinalizeWithdrawals always revert, so withdrawals can never be paid out

        Bridge2.sol:284 Predicted severity: High

        Root cause

        Vulnerable symbol: finalizeWithdrawal

        Preconditions: Any non-empty messages array (always the case for a real withdrawal)

        Offending code:

        function finalizeWithdrawal(bytes32 message) private nonReentrant whenNotPaused {

        Impact

        No requested withdrawal can ever be finalized and the transfer at line 291 can never run. All USDC deposited into the bridge is frozen for good: the contract has no admin sweep, upgrade path, or other function that moves funds out.

        Description

        The only external way to finalize a withdrawal is batchedFinalizeWithdrawals, which takes OpenZeppelin's ReentrancyGuard lock and then calls the private finalizeWithdrawal, which tries to take the same lock again. ReentrancyGuard reverts when the lock is already held ('ReentrancyGuard: reentrant call'), so every call with a non-empty array reverts.

        Exploit scenario

        A user deposits USDC, gets a valid validator-signed withdrawal, calls requestWithdrawal, waits out the dispute period, and calls batchedFinalizeWithdrawals([message]). The outer nonReentrant sets _status=ENTERED. The inner nonReentrant on finalizeWithdrawal sees _status==ENTERED and reverts. Every withdrawal fails the same way, so all deposits are stuck.

        Recommendation

        Remove nonReentrant (and the duplicate whenNotPaused) from the private finalizeWithdrawal and keep the guard only on the external batchedFinalizeWithdrawals entry point. Alternatively, expose a single external finalizeWithdrawal and build batching on top of an unguarded internal helper.

        Vercel Security Review

        Nested nonReentrant guards prevent every withdrawal payout

        Bridge2.sol:284 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. The new batch entrypoint takes the guard before calling the finalizer** - Bridge2.sol:304-307

        ```solidity title="Bridge2.sol:304-307"

        ) external nonReentrant whenNotPaused {

        uint64 end = uint64(messages.length);

        for (uint64 idx; idx < end; idx++) {

        finalizeWithdrawal(messages[idx]);

        ```

        **2. The private finalizer attempts to acquire the same guard again** - Bridge2.sol:284-286

        ```solidity title="Bridge2.sol:284-286"

        function finalizeWithdrawal(bytes32 message) private nonReentrant whenNotPaused {

        require(!finalizedWithdrawals[message], "Withdrawal already finalized");

        Withdrawal memory withdrawal = requestedWithdrawals[message];

        ```

        OpenZeppelin's shared reentrancy guard rejects this nested entry before the USDC transfer at line 291. This is the sole payout path: every nonempty batch reverts, even with valid requests and elapsed dispute periods. Deposits remain enabled, but users cannot redeem their funds.

        Exploit scenario

        Not specified.

        Recommendation

        Keep nonReentrant on the external batchedFinalizeWithdrawals entrypoint, but remove the redundant modifier from its private finalizeWithdrawal helper. Add coverage for successful nonempty withdrawal batches after the dispute period and rejection of repeated finalization.

      • Disputed actions are not blocked by validator rotation hyperliquid-2 · 6 writeups High

        V12

        Recovery preserves disputed withdrawal authorizations

        Bridge2.sol:39 Predicted severity: High

        Root cause

        Emergency replacement changes validator authority without invalidating deferred withdrawals accepted under the disputed authority. Settlement trusts stored requests independently of the recovered validator generation, so pause-and-replace is not a withdrawal rejection mechanism.

        Impact

        If a locker pauses to dispute a hot-signed withdrawal, cold recovery cannot selectively reject or invalidate that already recorded withdrawal; once the settlement guard defect is corrected, resuming permits the old request to transfer escrow despite replacement of its authorizing set. Conditional fund loss arises if the recorded withdrawal is unauthorized on the L1, the exact circumstance the documented locker dispute mechanism is intended to address; the present nested-guard bug prevents an immediate transfer exploit in this implementation.

        Description

        Cold-authorized emergency recovery replaces the pending validator proposal and active validator metadata, but does not invalidate previously requested withdrawals. A request authenticated under the hot set being disputed remains stored with its original recipient, amount, and clocks after that set is replaced. The withdrawal helper checks only its finalized flag and the dispute gate before transferring tokens; it does not bind the request to an authority generation or require reauthorization after recovery. Thus pausing during a withdrawal's dispute period does not itself cancel that disputed request when the bridge resumes. The separately reported nested reentrancy guards currently block the transfer path, but they do not repair this independent recovery-state defect.

        Pashov (Claude Opus 5.5 high)

        Emergency lock cannot invalidate fraudulent pending withdrawals; they still finalize after unlock

        audit/Bridge2.sol:249 Predicted severity: High

        Root cause

        No function lets the cold-wallet quorum (or anyone else) invalidate or delete requestedWithdrawals entries. A withdrawal's validity is fixed when it is requested and is never re-checked against the validator set at finalization.

        Impact

        If 2/3 of hot-wallet power is compromised, the attacker can request withdrawals for the whole bridge balance. Lockers can only delay the theft. Once the cold quorum unlocks to rotate keys, the attacker finalizes the fraudulent withdrawals and drains the bridge. The cold-wallet dispute mechanism gives no protection against fraudulent withdrawals.

        Description

        The security model depends on a dispute period during which lockers can lock the bridge if a hot-key quorum signs something that does not match the L1. Locking only pauses the contract. Nothing can remove or invalidate an entry in requestedWithdrawals. emergencyUnlock replaces and finalizes the validator set and unpauses, but every withdrawal requested earlier stays valid. It can be finalized as soon as the contract is unpaused, because its dispute period is measured from the original request time.

        Exploit scenario

        1) An attacker steals enough hot keys to reach 2/3 power and calls requestWithdrawal(bridgeBalance, nonce, ...) from their address. 2) A locker notices and calls emergencyLock. 3) The validators call emergencyUnlock with new keys using cold signatures. 4) The contract is unpaused and the attacker's requestedWithdrawals entry is unchanged. Its dispute period has already elapsed, so the attacker finalizes it and receives the funds.

        Recommendation

        Add a cold-quorum-authorized (or locker-callable while paused) invalidateWithdrawals(bytes32[] messages) that marks entries as invalid and is checked in finalizeWithdrawal. Alternatively, record the validator-set epoch on each withdrawal and reject finalization when an emergency unlock happened after the request.

        Pashov (Codex GPT-6 Sol high)

        Emergency recovery leaves disputed withdrawals payable

        Bridge2.sol:269 Predicted severity: High

        Root cause

        Emergency unlock does not invalidate or cancel pending withdrawals created under the disputed validator set, and finalization does not recheck the current set.

        Impact

        A compromised hot quorum can still extract bridge USDC after a locker detects the fraud and a cold quorum performs emergency recovery.

        Description

        A locker can pause a forged pending withdrawal, but cold-wallet recovery only replaces validators and unpauses. The pending withdrawal remains payable after the dispute period without a fresh signature check.

        Exploit scenario

        A compromised hot quorum signs a fraudulent withdrawal. A locker pauses the bridge during the dispute period. Cold validators rotate the set and unpause it; the forged request remains in requestedWithdrawals and pays when finalized after the separate reentrancy defect is fixed.

        Recommendation

        Record the validator-set generation for each withdrawal and invalidate disputed pending withdrawals on recovery, or add a cold-quorum cancellation mechanism before unpausing.

        Devin Security

        Locking the bridge does not cancel disputed withdrawals, so fraudulent withdrawals still pay out after unlock

        Bridge2.sol:591 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        If attackers steal a quorum of validator hot keys, the locker and cold-wallet dispute process cannot stop their already-requested withdrawals, so they can still drain the bridge's USDC after the bridge is unlocked.

        ##### What's wrong

        This is a broken dispute mechanism. The header comment says lockers dispute bad withdrawals during the dispute period. But emergencyLock only pauses the contract. emergencyUnlock replaces the validator set and unpauses. Nothing deletes or invalidates entries in requestedWithdrawals. A withdrawal signed by the compromised hot set stays valid, and finalizeWithdrawal only checks that its time has passed.

        ##### Who can do it

        Mallory steals the hot keys of enough Hyperliquid validators to reach two thirds of the power. She signs a withdrawal of the bridge's USDC to her address and calls requestWithdrawal. Bob, a locker, notices and calls emergencyLock. The cold-wallet holders sign emergencyUnlock with a fresh validator set. As soon as the bridge unpauses, Mallory calls batchedFinalizeWithdrawals and gets paid, because her dispute period has already passed.

        - Mallory controls hot-wallet signatures with at least two thirds of the active validator power.

        - Her requestWithdrawal succeeds before a locker pauses the bridge.

        - The cold quorum unlocks the bridge without some separate off-chain way to block her.

        ##### What they get

        Mallory takes up to the bridge's entire USDC balance, which belongs to all depositors. The lock delays her but does not stop her. The only workaround is to never unlock the bridge, which freezes everyone's funds.

        ##### How it works

        1. Mallory's request passes the hot-set signature check and is stored in requestedWithdrawals at Bridge2.sol:269-272.

        2. A locker calls emergencyLock at Bridge2.sol:591, which only calls _pause().

        3. The cold quorum calls emergencyUnlock at Bridge2.sol:596-628, which swaps the validator set and calls _unpause() but never touches requestedWithdrawals.

        4. finalizeWithdrawal at Bridge2.sol:284-291 only checks finalizedWithdrawals and the dispute period, then transfers the USDC to Mallory.

        Exploit scenario

        Not specified.

        Recommendation

        Give the cold quorum a way to invalidate pending withdrawals. For example, add a cold-signed invalidateWithdrawals(bytes32[] messages, nonce) that marks them finalized without paying out. Or record the validator epoch on each request and require at finalization that the request's epoch equals the current epoch or was explicitly re-approved. To check the fix, add a test that requests a withdrawal, locks, unlocks with a new set, and asserts that finalization reverts.

        Devin Security (Deep)

        Disputed withdrawals survive emergencyLock/emergencyUnlock and can be finalized afterwards; the lock cannot cancel a fraudulent withdrawal

        Bridge2.sol:269 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        If a thief ever gets a quorum of validator hot keys, the emergency lock cannot stop them from draining the bridge; it only delays the theft until the cold keys unlock the contract.

        ##### What's wrong

        This is a missing invalidation step. The contract's safety design is that a locker pauses the bridge when a bad withdrawal is requested and the cold keys then unlock with a new validator set. But emergencyUnlock only replaces the validator set. The record in requestedWithdrawals for the bad withdrawal is never removed or marked invalid, and finalizeWithdrawal only checks the dispute clock, which keeps running while the contract is paused. A pending validator set update is replaced on unlock; a pending withdrawal is not.

        ##### Who can do it

        Mallory breaks into enough validator servers to collect hot-key signatures worth two thirds of the validator power. She calls requestWithdrawal from her own wallet for the whole bridge balance. Bob, a locker at Hyperliquid, spots the fake withdrawal and calls emergencyLock. The validators rotate to new hot keys and the cold keys call emergencyUnlock. Mallory then calls batchedFinalizeWithdrawals with her message and receives the tokens.

        - Mallory holds signatures over her withdrawal message from hot keys worth at least two thirds of totalValidatorPower (compromised or colluding validators).

        - At least disputePeriodSeconds and the matching number of blocks have passed since her request, counting time spent paused.

        - The cold keys unlock the bridge at some point; if they never do, every user's funds stay frozen instead.

        - The nested nonReentrant bug in finalizeWithdrawal (separate finding) has been fixed, since today it blocks every finalization.

        ##### What they get

        Mallory takes the full USDC balance of the bridge, which is every user's deposited money. Hyperliquid's only alternative is to leave the bridge locked forever, which also loses every user's funds because there is no other way to move tokens out. The locker and cold-key mechanism therefore gives no real protection against the exact threat it was built for.

        ##### How it works

        1. Mallory calls requestWithdrawal (Bridge2.sol:249) with valid hot-key signatures. checkValidatorSignatures (Bridge2.sol:270) passes and the withdrawal is stored at Bridge2.sol:272.

        2. A locker calls emergencyLock (Bridge2.sol:591) and the contract pauses. requestedWithdrawals[message] stays in storage.

        3. The cold keys call emergencyUnlock (Bridge2.sol:596). It replaces and finalizes the validator set (Bridge2.sol:618-626) and unpauses, but touches nothing in requestedWithdrawals or finalizedWithdrawals.

        4. Mallory calls batchedFinalizeWithdrawals (Bridge2.sol:302). finalizeWithdrawal (Bridge2.sol:284) checks only finalizedWithdrawals and checkDisputePeriod (Bridge2.sol:288, 311-317), which compares against wall-clock time and block numbers that kept advancing during the pause.

        5. usdcToken.transfer (Bridge2.sol:291) sends the tokens to Mallory.

        Exploit scenario

        Not specified.

        Recommendation

        Give pending withdrawals a way to be cancelled. For example, store the validator set epoch (or a withdrawalGeneration counter) inside each Withdrawal, bump that counter in emergencyUnlock, and have finalizeWithdrawal require the stored value to match the current one. Alternatively, let emergencyUnlock take a list of withdrawal messages to delete from requestedWithdrawals. Verify with a test that requests a withdrawal, calls emergencyLock, calls emergencyUnlock with a new set, advances past the dispute period, and asserts that batchedFinalizeWithdrawals for that message reverts.

        Claude Security (Sonnet 5.5)

        Disputed withdrawals cannot be cancelled; lock then emergencyUnlock leaves fraudulent pending withdrawals finalizable

        Bridge2.sol:291 Predicted severity: High

        Root cause

        Vulnerable symbol: finalizeWithdrawal

        Preconditions: Hot validator quorum compromised, or a bad L1 withdrawal signature produced; Finalization is currently blocked by the F-001 bug; this issue becomes live once that is fixed

        Offending code:

        usdcToken.transfer(withdrawal.user, withdrawal.usdc);

        Impact

        The dispute and lock mechanism described in the header comments cannot neutralize a bad or compromised withdrawal. Once a hot-key quorum has requested a withdrawal, the cold wallets can only delay it, so the funds can still be stolen. Reaching this requires a hot-key compromise or a faulty L1 signature, which is the scenario the lock is meant to defend against.

        Description

        requestWithdrawal stores a pending withdrawal signed by the hot validator quorum. The only gates in finalizeWithdrawal are 'not already finalized' and the wall-clock dispute period. No function can invalidate a pending withdrawal, and emergencyUnlock replaces the validator sets without touching requestedWithdrawals. Also CWE-863: A withdrawal authorized by the hot-validator quorum is stored permanently in requestedWithdrawals. finalizeWithdrawal checks only that the message is not yet finalized and that the dispute period has elapsed. It never rechecks that the authorizing validator set is still trusted, and there is no function to cancel or invalidate a requested withdrawal. The design relies on lockers and the cold quorum to stop a malicious withdrawal, but locking only pauses finalization. emergencyUnlock replaces the validator set and unpauses without touching requestedWithdrawals. Also CWE-285: A withdrawal authorized by the hot validator quorum in requestWithdrawal is stored in requestedWithdrawals. finalizeWithdrawal only checks the finalized flag and checkDisputePeriod. It does not check that the authorizing validator set is still active or that the bridge was not locked. emergencyUnlock replaces the validator sets but never touches requestedWithdrawals, and no function lets the cold quorum invalidate pending withdrawals.

        Exploit scenario

        An attacker who controls a 2/3 quorum of hot keys signs a withdrawal to themselves and calls requestWithdrawal. A locker notices and calls emergencyLock. The cold quorum later calls emergencyUnlock with a clean validator set. The dispute timer kept running while the bridge was paused, so the malicious withdrawal is already past its dispute period. The attacker calls batchedFinalizeWithdrawals immediately after the unpause and drains the funds. The lock and unlock cycle gives the cold validators no step at which to cancel the entry.

        Recommendation

        Add a cold-quorum-signed, replay-protected invalidateWithdrawals(bytes32[] messages, ...) callable while paused, and have finalizeWithdrawal reject invalidated messages. Alternatively, extend or restart the dispute window on unlock for withdrawals requested before the lock. Also require requestedTime != 0 in finalizeWithdrawal. Also CWE-863: Add a cold-quorum-signed, whenPaused invalidateWithdrawals(bytes32[] messages, nonce, coldSet, signers, signatures) function that records invalidated messages. Require !invalidatedWithdrawals[message] in finalizeWithdrawal. Also require requestedWithdrawals[message].requestedTime != 0 there. Consider re-basing the dispute period on unlock time so that pending withdrawals are not instantly final after an unlock. Also CWE-285: Add a cold-quorum-signed invalidateWithdrawals(bytes32[] messages, ...) that marks pending withdrawals as finalized or cancelled. Alternatively, bind each pending withdrawal to the validator-set epoch that authorized it and reject finalization if the hot set has been replaced via emergencyUnlock. Alternatively, restart the dispute clock for all pending withdrawals on unlock.

    • Maia Solidity Maia Ulysses omnichain liquidity. Tasks 13 V12 13/13 Codex Sec 5/13 Pashov Opus 10/13 Pashov GPT-6 10/13 Devin 9/13 Devin (Deep) 11/13 Claude Sec 8/13 Claude Opus 9/13 Vercel 5/13

      Maia Ulysses omnichain liquidity.

      Read the audit report
      • Lack of the RootBridgeAgent contract verification maia-1 · 9 writeups Critical

        V12

        Permissionless deployment grants unrestricted custody withdrawal authority

        src/2-audit/ulysses-omnichain/factories/ArbitrumBranchBridgeAgentFactory.sol:46 Predicted severity: Critical

        Root cause

        Factory deployment automatically grants port authority without authenticating the requested root/controller relationship. The Arbitrum executor check then delegates message authority directly to that untrusted constructor input.

        Impact

        An arbitrary user can release tokens held by the Arbitrum branch port to their own recipient without depositing or burning corresponding claims. Permissionless factory deployment becomes direct custody authority and can drain available user backing.

        Description

        Both branch bridge-agent factories expose createBridgeAgent without authorization and accept a caller-selected root bridge-agent address. Creation immediately registers the new agent in the custody port, making it an authorized caller of withdrawal and mint functions. In the Arbitrum specialization, _requiresExecutor accepts any direct caller equal to that supplied root address. A user can therefore create an agent naming their own account as its root and directly deliver a single-asset settlement withdrawing an existing port asset. The receiving single-asset branch has no additional gas withdrawal or registered-root check that would block this path.

        Codex Security (GPT-6 Sol)

        Anyone can register an Arbitrum bridge agent and withdraw port reserves

        src/2-audit/ulysses-omnichain/factories/ArbitrumBranchBridgeAgentFactory.sol:46 Predicted severity: Critical

        Root cause

        The factory has no caller or trusted-root check. It registers an agent whose executor is controlled by the creator; port authorization trusts that registration, and the agent accepts forged settlement bytes from that executor.

        Impact

        An unprivileged caller can directly withdraw pooled underlying tokens without a deposit or cross-chain message.

        Description

        A public factory lets a caller choose a new agent's trusted root address, registers that agent with the port, and the caller can submit a forged settlement to withdraw the port's ERC20 reserves.

        Exploit scenario

        factory input -> agent root address -> agent executor check -> settlement decode -> port withdrawal

        Recommendation

        Restrict agent creation and bind the root agent address to a root-approved registry before registering the new agent with the port.

        Pashov (Claude Opus 5.5 high)

        Unprotected BranchBridgeAgentFactory.createBridgeAgent lets anyone register a malicious Bridge Agent on a Branch Port and drain it

        src/2-audit/ulysses-omnichain/factories/BranchBridgeAgentFactory.sol:70 Predicted severity: Critical

        Root cause

        Missing msg.sender == localCoreBranchRouterAddress (requiresCoreRouter) check on createBridgeAgent. Any agent the factory creates is automatically whitelisted in the port.

        Impact

        Total loss of every underlying token held by any Branch Port, including ArbitrumBranchPort, plus unlimited minting of branch hTokens (or global hTokens through ArbitrumBranchPort.bridgeIn -> RootPort.mintToLocalBranch).

        Description

        Both BranchBridgeAgentFactory.createBridgeAgent and its Arbitrum override are external with no access control. Each deploys a new bridge agent whose router address and root bridge agent address come from the caller, then calls BranchPort.addBridgeAgent. That makes the new agent a trusted isBridgeAgent of the port, so it can call withdraw/bridgeIn/bridgeInMultiple. localCoreBranchRouterAddress is stored in the factory but never checked.

        Exploit scenario

        Arbitrum: the attacker calls ArbitrumBranchBridgeAgentFactory.createBridgeAgent(attackerRouter, attackerEOA). The new ArbitrumBranchBridgeAgent's _requiresExecutor only checks msg.sender == rootBridgeAgentAddress, which is the attacker's EOA. The attacker calls anyExecute(0x01 | recipient | nonce | hToken | token=USDC | amount | deposit=portBalance | gas) directly. _clearToken -> ArbitrumBranchPort.withdraw(attacker, USDC, portBalance) empties the port. Other branches: the agent is created with rootBridgeAgentAddress = an attacker contract on the root chain. That contract calls AnycallProxy.anyCall to the new branch agent with a crafted settlement. The executor context from matches, so the same _clearToken withdraws all of the port's tokens.

        Recommendation

        Restrict createBridgeAgent to localCoreBranchRouterAddress (requiresCoreRouter), as the rest of the system assumes. Consider also having the root side approve new branch agents before the port whitelists them.

        Pashov (Codex GPT-6 Sol high)

        Permissionless Arbitrum agent registration lets attacker drain BranchPort

        audit/src/2-audit/ulysses-omnichain/factories/ArbitrumBranchBridgeAgentFactory.sol:46 Predicted severity: Critical

        Root cause

        Agent registration does not establish that the caller or remote endpoint is approved by the protocol.

        Impact

        A forged trusted agent may instruct the port to release other users assets.

        Description

        Once the Arbitrum factory is authorized by BranchPort, anyone can call it with an arbitrary rootBridgeAgentAddress and it immediately registers the new agent in the shared port. The Arbitrum agent trusts direct calls from that chosen address, so an attacker can make a port-authorized agent execute a forged settlement.

        Exploit scenario

        Choose the attacker EOA as _rootBridgeAgentAddress in createBridgeAgent. From that EOA call newAgent.anyExecute(abi.encodePacked(bytes1(0x01), attacker, uint32(0), address(0), tokenHeldByPort, uint256(N), uint256(N), uint128(0))). The agent calls BranchPort.withdraw(attacker,tokenHeldByPort,N).

        Recommendation

        Require protocol authorization and verified root pairing before registering an agent in BranchPort; never trust an arbitrary caller-selected root endpoint.

        Devin Security

        Anyone can deploy a registered branch bridge agent that trusts an attacker-chosen root agent and drain the branch port

        src/2-audit/ulysses-omnichain/factories/BranchBridgeAgentFactory.sol:70 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Any anonymous user can register their own bridge agent on a branch chain and use it to withdraw every underlying token held by that chain's BranchPort.

        ##### What's wrong

        This is missing access control on a privileged factory. createBridgeAgent has no caller check, takes the trusted root agent address from the caller, and then registers the new agent in the BranchPort with addBridgeAgent. A registered agent can call BranchPort.withdraw and BranchPort.bridgeIn for any token and amount.

        ##### Who can do it

        Alice and many other users have bridged USDC from a branch chain, so the BranchPort holds their USDC. Mallory has only a wallet. She calls createBridgeAgent(anyRouter, mallorysContract) on the branch factory. She then makes mallorysContract, on any chain AnyCall supports, send an AnyCall message to her new agent with flag 0x01 and a settlement that names USDC as the token and the port's full balance as the deposit.

        - The branch factory is deployed and is a registered factory in the BranchPort.

        - Mallory can pay the AnyCall source fee from a contract she controls.

        - The same flaw exists in ArbitrumBranchBridgeAgentFactory.createBridgeAgent.

        ##### What they get

        Mallory receives all of the port's USDC, and the same for every other underlying token the port holds. She can also mint unlimited branch hTokens to herself. Every user who bridged through that branch loses their funds. The damage covers every branch chain where the factory is deployed.

        ##### How it works

        1. Mallory calls BranchBridgeAgentFactory.createBridgeAgent (line 70), which accepts any _rootBridgeAgentAddress and has no access check.

        2. The factory calls BranchPort.addBridgeAgent (line 87), and the port sets isBridgeAgent[newAgent] = true.

        3. The new agent's _requiresExecutor in BranchBridgeAgent.sol (lines 121-125) only checks that the AnyCall from equals Mallory's chosen root agent address. It does not check the source chain.

        4. Mallory's contract sends a flag 0x01 message. anyExecute decodes token and deposit from the message and calls _clearToken (BranchBridgeAgent.sol lines 744-756).

        5. _clearToken calls BranchPort.withdraw(recipient, token, deposit) (BranchBridgeAgent.sol line 563), and the port transfers the tokens because the caller is a registered agent.

        Exploit scenario

        Not specified.

        Recommendation

        Restrict createBridgeAgent in both the branch and Arbitrum factories to the local core branch router, for example if (msg.sender != localCoreBranchRouterAddress) revert UnrecognizedCoreBranchRouter();. Also require the root agent to come from a known root bridge agent factory. To check the fix, add a test where an unrelated address calls createBridgeAgent and expect a revert. Add a second test that confirms the port never registers that agent.

        Devin Security (Deep)

        Branch bridge agents trust a constructor-supplied root address; anyone can deploy one through the open factory and forge settlements that drain the branch port

        src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:121 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can deploy a branch bridge agent through the open factory with a root address they control, and the agent then accepts their forged settlement messages and tells the branch port to hand over any token to them.

        ##### What's wrong

        This is trust in a caller-supplied address combined with an open registration path. BranchBridgeAgent._requiresExecutor (and the Arbitrum override) treats whoever matches rootBridgeAgentAddress as the root chain, but that address is an unchecked constructor argument that BranchBridgeAgentFactory.createBridgeAgent lets anyone choose, and the factory immediately registers the new agent as a trusted bridge agent in BranchPort.

        ##### Who can do it

        Alice has USDC in the Arbitrum port. Mallory, an attacker with a wallet, calls ArbitrumBranchBridgeAgentFactory.createBridgeAgent(anyRouter, mallory) where mallory is her own address. She then calls anyExecute on the new agent directly with a flag 0x01 settlement that names herself as recipient, USDC as the token and the port's whole balance as the deposit. On other branch chains she does the same, but sends the message through anycall from a contract she deployed on the root chain at the address she registered.

        - A wallet with gas on the target branch chain. For non-Arbitrum chains she also needs to call anycall from the root chain, which is open to any contract that pays the fee.

        - createBridgeAgent on the branch factory is callable by anyone and BranchPort.addBridgeAgent grants bridge agent rights at once.

        - No root-side state is needed. Flag 0x01 settlements do not touch gas accounting, so no fee assumptions apply.

        ##### What they get

        _clearToken calls BranchPort.withdraw, which pays Mallory any token the port holds, and BranchPort.bridgeIn, which mints any branch hToken to her. She empties every branch port, taking every user's deposits on every chain.

        ##### How it works

        1. Mallory calls createBridgeAgent(router, rootAddress) with rootAddress under her control (BranchBridgeAgentFactory.sol:70-88, ArbitrumBranchBridgeAgentFactory.sol:46-63); the constructor stores it (BranchBridgeAgent.sol:76-95) and BranchPort.addBridgeAgent sets isBridgeAgent (BranchPort.sol:272-276).

        2. She calls anyExecute on the agent. On Arbitrum she calls it directly, since the override only checks msg.sender == rootBridgeAgentAddress (ArbitrumBranchBridgeAgent.sol:122-124). Elsewhere she sends it through anycall, since _requiresExecutor only checks that the anycall from equals rootBridgeAgentAddress and never checks the source chain (BranchBridgeAgent.sol:121-125).

        3. Flag 0x01 decodes recipient, token and amounts from her payload and calls _clearToken (BranchBridgeAgent.sol:731-761).

        4. _clearToken calls BranchPort.withdraw and BranchPort.bridgeIn, which pass requiresBridgeAgent and transfer or mint the requested tokens to her (BranchBridgeAgent.sol:555-565, BranchPort.sol:185-211).

        Exploit scenario

        Not specified.

        Recommendation

        Restrict createBridgeAgent on the branch factories to the owner, or require that the root bridge agent address was pre-approved by the core branch router after a root-side confirmation, and have BranchPort grant bridge agent rights only after that confirmation. In _requiresExecutor, also require fromChainId == rootChainId. Verify with tests: call createBridgeAgent from a random account and assert it reverts; deploy an agent with a fake root address and assert anyExecute from that address reverts and the port balance is unchanged.

        Claude Security (Sonnet 5.5)

        Unauthenticated BranchBridgeAgentFactory.createBridgeAgent registers attacker-controlled bridge agents in the BranchPort

        src/2-audit/ulysses-omnichain/factories/BranchBridgeAgentFactory.sol:70 Predicted severity: Critical

        Root cause

        Vulnerable symbol: createBridgeAgent

        Preconditions: Factory is registered in BranchPort.isBridgeAgentFactory, which is its normal deployment.; Attacker can originate an Anycall message from an address they control on the root chain (permissionless in Anycall V7 with prepaid fees).

        Offending code:

        function createBridgeAgent(

        Impact

        Complete theft of all underlying tokens held by the BranchPort on every branch chain where the factory is registered, plus unbacked hToken minting. This breaks the bridge's solvency.

        Description

        Any caller can deploy a BranchBridgeAgent with an arbitrary rootBridgeAgentAddress, and the factory immediately registers it as a trusted bridge agent in the BranchPort (IPort.addBridgeAgent). The agent trusts any Anycall message whose context().from equals that attacker-chosen address, and its anyExecute then calls BranchPort.withdraw/bridgeIn with payload-supplied recipient, token and amount.

        Exploit scenario

        1) Attacker calls createBridgeAgent(anyRouter, attackerContractOnRootChain). The new agent is added to BranchPort.isBridgeAgent. 2) The attacker contract on the root chain calls Anycall anyCall(newAgent, payload, branchChainId, ...), where payload is flag 0x01 + recipient=attacker + hToken + token=USDC + amount=deposit=Port balance (data[65:129]). 3) The Anycall executor calls newAgent.anyExecute. Context.from equals the attacker address, so _requiresExecutor passes. 4) _clearToken runs IPort.withdraw(attacker, USDC, deposit), which transfers all USDC held by the Port to the attacker. The same works for every token held by the Port, and bridgeIn mints unbacked hTokens.

        Recommendation

        Restrict createBridgeAgent to the local core branch router, i.e. require msg.sender == localCoreBranchRouterAddress, or to the owner. Also bind the root bridge agent to an allowlist or to the official root factory. Make BranchBridgeAgent._requiresExecutor also check fromChainId == rootChainId.

        Claude Security (Opus 5.5)

        Anyone can register a bridge agent in BranchPort with a root agent and router they choose, then drain every token in the port

        src/2-audit/ulysses-omnichain/factories/BranchBridgeAgentFactory.sol:70 Predicted severity: Critical

        Root cause

        Vulnerable symbol: createBridgeAgent

        Preconditions: The factory is registered as a bridge agent factory in BranchPort, which is done at initialize; The attacker can send one anycall message from a contract they control (normal anycall usage, no privileges)

        Offending code:

        function createBridgeAgent(

        Impact

        Total loss of all underlying assets held by the BranchPort on every non-Arbitrum branch, and unlimited minting of local hTokens that can be bridged to the root for real value.

        Description

        createBridgeAgent has no caller check. The stored localCoreBranchRouterAddress is never used. It deploys a BranchBridgeAgent whose rootBridgeAgentAddress and localRouterAddress come from the caller, then whitelists it with BranchPort.addBridgeAgent. Every whitelisted agent may call BranchPort.withdraw and bridgeIn for any token. The new agent's _requiresExecutor only checks that the anycall context from equals the attacker-chosen rootBridgeAgentAddress.

        Exploit scenario

        1. The attacker deploys contract X on any chain that anycall supports. 2. On the branch, the attacker calls BranchBridgeAgentFactory.createBridgeAgent(router=attacker, rootBridgeAgent=X). The port marks the new agent as a bridge agent. 3. X sends an anyCall to the new agent with the payload 0x01 | attacker(20) | nonce(4) | anyAddr(20) | USDC(20) | amount=N(32) | deposit=N(32) | gas(16). 4. The branch executor calls newAgent.anyExecute. The context from is X, so the check passes. _clearToken skips bridgeIn because amount equals deposit, then calls BranchPort.withdraw(attacker, USDC, N). 5. The attacker repeats this for every token the port holds. Setting amount greater than deposit instead calls bridgeIn, which mints unbacked hTokens. As the agent's router, the attacker can also call performCallOutAndBridge(depositor=victim, ...) to pull tokens that victims approved to the port.

        Recommendation

        Only let the core branch router call createBridgeAgent, through a governance path that starts on the root chain (require msg.sender == localCoreBranchRouterAddress). In BranchBridgeAgent._requiresExecutor, also check fromChainId == rootChainId. Consider tracking port balances per bridge agent so one agent cannot withdraw assets deposited through another.

        Vercel Security Review

        Permissionless Arbitrum agent creation gives attackers authority to withdraw port reserves

        src/2-audit/ulysses-omnichain/factories/ArbitrumBranchBridgeAgentFactory.sol:46 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Anyone chooses a trusted root** - src/2-audit/ulysses-omnichain/factories/ArbitrumBranchBridgeAgentFactory.sol:46-49

        ```solidity title="src/2-audit/ulysses-omnichain/factories/ArbitrumBranchBridgeAgentFactory.sol:46-49"

        function createBridgeAgent(

        address _newBranchRouterAddress,

        address _rootBridgeAgentAddress

        ) external override returns (address newBridgeAgent) {

        ```

        The newly added factory registers this agent with the shared port at line 62 without authorizing the caller or validating the root.

        **2. The attacker becomes the executor** - src/2-audit/ulysses-omnichain/ArbitrumBranchBridgeAgent.sol:122-124

        ```solidity title="src/2-audit/ulysses-omnichain/ArbitrumBranchBridgeAgent.sol:122-124"

        function _requiresExecutor() internal view override {

        if (msg.sender != rootBridgeAgentAddress) revert AnycallUnauthorizedCaller();

        }

        ```

        **3. Forged settlements drain shared collateral** - src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:562-564

        ```solidity title="src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:562-564"

        if (_deposit > 0) {

        IPort(localPortAddress).withdraw(_recipient, _token, _deposit);

        }

        ```

        The attacker submits single-asset settlements to anyExecute, selecting their recipient and reserve token. Port authorization succeeds because the factory registered the agent; no corresponding deposit or burn is required.

        Exploit scenario

        Not specified.

        Recommendation

        Authorize bridge-agent creation through governance or an authenticated core-router flow, validate the configured root agent, and do not grant port privileges before that validation. Apply equivalent registration restrictions to the base branch factory.

      • Missing access control for Multicall maia-2 · 8 writeups Critical

        V12

        Unauthenticated callback enables account and residual theft

        src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412 Predicted severity: Critical

        Root cause

        The multiple-deposit callback omits bridge-agent admission and trusts a caller-selected account implementation to supply custody and authorization checks. The downstream requiresRouter gate authenticates the confused-deputy router, while its unused lock leaves the real-account approval window exploitable.

        Impact

        An external caller can steal residual hTokens held by the shared router by substituting a fake account and selecting its own settlement recipient. During a legitimate signed call into an attacker-controlled target, that target can also cause the approved real account to transfer its assets directly to the attacker through the no-output branch, without encountering outbound gas or settlement checks.

        Description

        anyExecuteSignedDepositMultiple lacks requiresAgent and accepts an arbitrary userAccount, unlike the single-deposit callback. For funcId == 0x02, an attacker-controlled account can return a valid empty result from call and make withdrawERC20 a no-op; the router then approves and bridges its own existing token balance to the attacker-selected recipient. The downstream agent's requiresRouter check accepts this request because the router itself makes the call, and no deposit metadata or balance-increase check binds that balance to the supplied account. A concrete same-chain exit uses depositOut == amountOut to burn residual hTokens and release the corresponding underlying through the local branch port, provided destination backing and the agent's retained fallback-gas threshold are sufficient. The same missing admission check permits an untrusted target invoked during either signed callback to reenter the multiple-deposit callback and issue arbitrary calls through the temporarily approved real account.

        Codex Security (GPT-6 Sol)

        A called contract can reenter the router and spend a virtual account's assets

        src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412 Predicted severity: Medium

        Root cause

        The signed multiple-deposit router entry omits the agent guard. During bridge execution, the router already has temporary authority over the user's virtual account, and the public entry lets a called contract reuse that authority before it is revoked.

        Impact

        The path can steal account-held assets, but requires a user-signed operation that calls a malicious contract during a brief approval window.

        Description

        During a signed multiple-deposit call, the bridge temporarily approves the router for the user's virtual account; a called contract can reenter an unguarded router entry and make that account transfer unrelated assets.

        Exploit scenario

        temporary router approval -> target callback -> public router entry -> approved virtual-account call

        Recommendation

        Apply requiresAgent to anyExecuteSignedDepositMultiple and use explicit approval setting and clearing around every signed execution.

        Pashov (Claude Opus 5.5 high)

        MulticallRootRouter.anyExecuteSignedDepositMultiple is missing the requiresAgent modifier

        src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412 Predicted severity: Low

        Root cause

        Missing requiresAgent modifier.

        Impact

        Any tokens or ETH sitting in the router can be bridged out to an attacker-chosen recipient through _approveAndCallOut/_approveMultipleAndCallOut. The router's privileges with the bridge agent are exposed to everyone.

        Description

        Every other entry point of MulticallRootRouter is restricted to the bridge agent, but anyExecuteSignedDepositMultiple has no access control. Anyone can call it with an arbitrary userAccount (for example an attacker contract that implements call/withdrawERC20 as no-ops) and arbitrary OutputParams.

        Exploit scenario

        Router holds stray hTokens. The attacker calls anyExecuteSignedDepositMultiple(0x02, rlp(calls=[], OutputParams{attacker, hToken, X, X}, toChain), params, attackerContract, 0). The router burns its own hTokens through the bridge agent and the settlement pays underlying to the attacker.

        Recommendation

        Add requiresAgent to anyExecuteSignedDepositMultiple.

        Pashov (Codex GPT-6 Sol high)

        Signed multiple-deposit router handler lacks agent authentication

        audit/src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412 Predicted severity: High

        Root cause

        Missing requiresAgent modifier on this override.

        Impact

        An external target reached during a signed deposit can make the approved router transfer all tokens held by that user VirtualAccount to the attacker.

        Description

        This callback lacks requiresAgent. RootBridgeAgent temporarily approves the router to execute a user VirtualAccount during signed deposits, and the router then makes attacker-influenced external calls. A reentrant target can call the unguarded callback with that VirtualAccount and arbitrary Call[], which the router executes as the approved caller.

        Exploit scenario

        A victim signed single deposit invokes a target controlled by the attacker through VirtualAccount.call. The target reenters anyExecuteSignedDepositMultiple with funcId 0x01, the victim userAccount, and a Call[] that calls ERC20.transfer(attacker,N) on a token held by the VirtualAccount.

        Recommendation

        Add requiresAgent to the callback and a shared reentrancy guard around every handler that operates on an approved VirtualAccount.

        Devin Security

        anyExecuteSignedDepositMultiple has no caller check, so it can act on a victim's virtual account

        src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        When a user's signed cross-chain call touches a contract an attacker controls, that contract can call back into the router and empty the user's virtual account.

        ##### What's wrong

        This is a missing authorization check. Every other handler uses requiresAgent, but anyExecuteSignedDepositMultiple does not. It runs IVirtualAccount(userAccount).call(calls) for any userAccount and any calls the caller passes. The root agent approves the router on a user's virtual account for the whole signed execution, so a call back into the router during that time passes the account's approval check.

        ##### Who can do it

        Alice, an Acme user, sends a signed multicall that swaps through a token or pool that Mallory deployed. During the swap, Mallory's contract calls anyExecuteSignedDepositMultiple(0x01, calls, ..., aliceAccount, ...), where calls transfers every token in Alice's virtual account to Mallory.

        - Alice's signed execution must make an external call into a contract Mallory controls, such as a malicious token, pool, or hook.

        ##### What they get

        Mallory takes every token and NFT held in Alice's virtual account. She can do this only to accounts whose owner is running a signed call at that moment.

        ##### How it works

        1. The root agent sets isRouterApproved[aliceAccount][router] before signed execution (RootBridgeAgent.sol:947, 975, 1004).

        2. Alice's calls reach Mallory's contract.

        3. Mallory's contract calls anyExecuteSignedDepositMultiple, which has no caller check (MulticallRootRouter.sol:412-424).

        4. The router calls aliceAccount.call(calls), and requiresApprovedCaller passes (VirtualAccount.sol:55-58).

        Exploit scenario

        Not specified.

        Recommendation

        Add requiresAgent to anyExecuteSignedDepositMultiple, and also to the same function in CoreRootRouter. Consider a reentrancy lock on all router entry points. Add a test that a direct call from an outside address reverts.

        Devin Security (Deep)

        anyExecuteSignedDepositMultiple has no caller check, exposing virtual account calls and bridge-agent outputs to anyone

        src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can call a router entry point that drives a user's virtual account and the bridge agent, which lets an attacker who gets code execution during another user's cross-chain action empty that user's virtual account.

        ##### What's wrong

        This is missing authentication. Every other anyExecute* function on MulticallRootRouter carries requiresAgent, but anyExecuteSignedDepositMultiple does not (and is missing override). It accepts an arbitrary userAccount address and calls IVirtualAccount(userAccount).call(calls) and withdrawERC20 on it, then calls RootBridgeAgent.callOutAndBridge as the router.

        ##### Who can do it

        Alice, an Acme Bridge user, runs a signed multicall that swaps tokens through her virtual account. Mallory, an attacker, controls a contract that Alice's swap touches (for example a token with transfer hooks that Alice trades). During Alice's execution the root bridge agent has toggled the router as approved on Alice's virtual account. Mallory's contract reenters MulticallRootRouter.anyExecuteSignedDepositMultiple(0x01, rlpCalls, dummy, aliceVA, chain) with calls that transfer every token out of Alice's virtual account.

        - Mallory must execute code while isRouterApproved[aliceVA][router] is true, which only happens inside Alice's own anyExecuteSigned* window; this requires Alice's calls to reach attacker-controlled code.

        - Outside such a window the virtual account rejects the router, and the bridge-agent output path only moves tokens the router itself holds.

        ##### What they get

        Mallory drains Alice's virtual account of every token it holds at that moment. Each victim must be attacked individually during their own transaction.

        ##### How it works

        1. RootBridgeAgent.anyExecute flag 0x04 toggles the router approved on Alice's virtual account and calls anyExecuteSigned (RootBridgeAgent.sol:942-953).

        2. Alice's virtual account executes her calls, one of which reaches Mallory's contract (VirtualAccount.sol:42-48).

        3. Mallory calls anyExecuteSignedDepositMultiple directly; nothing checks msg.sender (MulticallRootRouter.sol:412-418).

        4. The router calls IVirtualAccount(aliceVA).call(mallorysCalls); the approval check passes because the window is open (MulticallRootRouter.sol:421-424, VirtualAccount.sol:55-59).

        Exploit scenario

        Not specified.

        Recommendation

        Add requiresAgent (and override) to anyExecuteSignedDepositMultiple, matching the other handlers, and add a lock modifier on the router's anyExecute* functions. Add a test asserting a direct call from a non-agent reverts.

        Claude Security (Opus 5.5)

        MulticallRootRouter.anyExecuteSignedDepositMultiple has no requiresAgent check, so anyone can run router-privileged Virtual Account calls and bridge-outs

        src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:412 Predicted severity: Medium

        Root cause

        Vulnerable symbol: anyExecuteSignedDepositMultiple

        Preconditions: MulticallRootRouter is deployed as the localRouterAddress of a RootBridgeAgent; To drain a Virtual Account, attacker code must run while the router is approved for the victim's account (inside a signed execution); to steal router-held hTokens, the router must hold a balance

        Offending code:

        function anyExecuteSignedDepositMultiple(

        Impact

        An attacker can steal assets from users' Virtual Accounts during any signed execution window where it gains control flow. Without any precondition, it can steal hTokens held by the router and act as the router against the RootBridgeAgent's router-only functions. The bridge agent's authentication of the message source is bypassed.

        Description

        Every other anyExecute* handler in MulticallRootRouter has the requiresAgent modifier (msg.sender == bridgeAgentAddress). anyExecuteSignedDepositMultiple (line 412-418) does not. So any external caller can pass its own rlpEncodedData, which RLPDecoder.decodeCallData turns into Call[] and output params, plus any userAccount. The router then runs IVirtualAccount(userAccount).call(calls), withdrawERC20, approves the port for any token, and calls the root bridge agent's router-only callOutAndBridge/callOutAndBridgeMultiple.

        Exploit scenario

        (1) Reentrancy drain of a victim's Virtual Account. RootBridgeAgent approves the router for a user's VirtualAccount only while it runs that user's signed message (toggle on, router call, toggle off). If attacker code gets control flow during that window, for example through a token transfer hook or an attacker contract the victim's calls touch, it calls MulticallRootRouter.anyExecuteSignedDepositMultiple(0x01, RLP([token.transfer(attacker, balance)...]), anyParams, victimVA, 0). isRouterApproved[victimVA][router] is true at that point, so VirtualAccount.call runs the attacker's calls and moves the victim's tokens to the attacker. (2) Direct, with no precondition. The attacker passes its own contract as userAccount, so its call/withdrawERC20 do nothing. The router then approves localPortAddress and calls the bridge agent's router-only callOutAndBridge(Multiple) with recipient, token, amount, deposit and toChain chosen by the attacker. Any hToken balance the router holds is burned or bridged to the attacker's recipient on a branch chain.

        Recommendation

        Add the requiresAgent modifier, and override to match IRootRouter, to anyExecuteSignedDepositMultiple, as the sibling handlers have. Also consider adding a lock reentrancy guard to all anyExecute* handlers, and have VirtualAccount check that the call came through the active bridge-agent execution, not only a toggled router approval.

        Vercel Security Review

        Unguarded multicall handler lets external targets hijack an active virtual account

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:975 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Signed execution temporarily authorizes the router** - src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:975-978

        ```solidity title="src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:975-978"

        IPort(localPortAddress).toggleVirtualAccountApproved(userAccount, localRouterAddress);

        IRouter(localRouterAddress).anyExecuteSignedDepositSingle(

        data[132], data[133:length - PARAMS_GAS_IN], dParams, address(userAccount), fromChainId

        ```

        If the user's calls reach an attacker-controlled target, that target can reenter while approval remains active.

        **2. The new multiple-deposit handler accepts unauthenticated calls** - src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:418-421

        ```solidity title="src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:418-421"

        ) external payable returns (bool success, bytes memory result) {

        /// FUNC ID: 1 (multicallNoOutput)

        if (funcId == 0x01) {

        Call[] memory calls = abi.decode(RLPDecoder.decodeCallData(rlpEncodedData, MAX_LENGTH), (Call[]));

        ```

        Unlike adjacent handlers, it lacks requiresAgent. The target supplies the victim's account and token-transfer calls.

        **3. Attacker instructions execute as the approved router** - src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:423-424

        ```solidity title="src/2-audit/ulysses-omnichain/MulticallRootRouter.sol:423-424"

        //Call desired functions

        IVirtualAccount(userAccount).call(calls);

        ```

        The account's router check succeeds, enabling theft of unrelated balances without the user's signed authorization.

        Exploit scenario

        Not specified.

        Recommendation

        Add requiresAgent to anyExecuteSignedDepositMultiple and consistently authenticate every execution handler. Add appropriate reentrancy protection around signed execution and virtual-account approval lifetimes.

      • Multitoken lacks validations maia-3 · 9 writeups Critical

        V12

        Mismatched constructor arrays commit unusable basket state

        src/2-audit/ulysses-amm/factories/UlyssesFactory.sol:123 Predicted severity: High

        Root cause

        Neither createToken nor ERC4626MultiToken enforces equality between asset and weight array lengths. Constructor validation uses the weight count rather than validating every stored asset and its coupled reverse index.

        Impact

        The malformed basket can accept LP tokens and mint shares while later reconciliation fails, creating a configuration-dependent custody and recovery failure. The supplied owner can attempt repair with a correctly sized setWeights call, but repair requires any newly required LP-token backing; the independent redemption and payout defects reported separately also remain.

        Description

        createToken forwards poolIds and weights without checking that their lengths match, and the base constructor stores both arrays while iterating only over weights.length. Consequently, [P, Q] with weights [1] successfully deploys a registered basket with two assets but only one weight and no reverse-index entry for Q. A user can deposit a one-element amount array containing P tokens because both pricing and transfers iterate over that caller-supplied prefix. Subsequent full-basket operations and owner reconciliation index the absent second weight, so the successful deployment can accept custody that its stored configuration cannot consistently service. Longer weight arrays instead fail during constructor indexing and revert the transaction; this is an asymmetric validation defect, not a counter-rollback failure.

        Codex Security (GPT-6 Sol)

        An empty vault deposit can mint the maximum share supply for free

        src/2-audit/erc-4626/ERC4626MultiToken.sol:182 Predicted severity: Medium

        Root cause

        convertToShares uses a maximum-value sentinel but does not require the amount array to match the configured basket length. For an empty array it returns that sentinel as a legitimate mint amount.

        Impact

        An unprivileged caller can corrupt a newly created vault's supply and block later positive deposits at zero asset cost; current redemption defects limit direct asset extraction.

        Description

        An empty amount array skips the asset transfers and leaves the share calculation at uint256.max, which deposit mints on a fresh vault.

        Exploit scenario

        empty array -> sentinel share calculation -> no transfers -> maximum share mint

        Recommendation

        Require assetsAmounts.length to equal the configured nonzero basket length and reject zero received assets before minting.

        Pashov (Claude Opus 5.5 high)

        ERC4626MultiToken.deposit trusts the caller-supplied array length, so shares can be minted for partial or zero deposits

        src/2-audit/erc-4626/ERC4626MultiToken.sol:54 Predicted severity: High

        Root cause

        Missing assetsAmounts.length == assets.length validation in deposit/withdraw and their preview helpers.

        Impact

        An attacker mints UlyssesToken shares without supplying the full basket (or anything at all with an empty array, if totalSupply is 0). They can then redeem those shares for other depositors' assets. Combined with redeem, this drains the vault.

        Description

        convertToShares iterates over assetsAmounts.length, not assets.length, and takes the minimum share value. receiveAssets also only pulls the entries supplied. With an empty array, shares = type(uint256).max and nothing is transferred. With an array containing only the first asset, shares are computed from that asset alone, and none of the other basket assets are deposited. previewWithdraw has the same problem: passing a short array makes the burned share amount depend only on the listed assets.

        Exploit scenario

        The attacker calls deposit([1e18], attacker) on a 3-asset UlyssesToken with weights [1,1,1]. shares = 1e18*3/1 = 3e18, but only 1e18 of asset0 is transferred. Redeeming 3e18 shares (once redeem pays the receiver) yields 1e18 of each asset, a 2e18 profit taken from other users.

        Recommendation

        Require assetsAmounts.length == assets.length in deposit, withdraw, convertToShares and previewWithdraw.

        Pashov (Codex GPT-6 Sol high)

        Incomplete basket deposits mint unbacked shares

        audit/src/2-audit/erc-4626/ERC4626MultiToken.sol:182 Predicted severity: High

        Root cause

        No equality check against the configured asset count.

        Impact

        Unbacked and transferable shares dilute existing holders; an empty first deposit can corrupt total supply and block subsequent deposits.

        Description

        The share conversion loop uses caller-supplied array length rather than the configured basket length. A short array prices only the supplied components, while receiveAssets transfers only those components. An empty array leaves shares at uint256.max.

        Exploit scenario

        For two equal-weight assets, deposit only the first asset. The vault mints shares as if the basket contribution were complete while taking no second asset; deposit([]) on an empty vault mints the maximum share amount for zero payment.

        Recommendation

        Require assetsAmounts.length == assets.length in all deposit and withdrawal entry points and reject empty baskets before conversion.

        Devin Security

        Deposit with an empty or short amounts array mints shares without paying for every asset

        src/2-audit/erc-4626/ERC4626MultiToken.sol:182 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can mint Ulysses token shares for free, or while paying for only one asset of the basket, which dilutes every honest holder.

        ##### What's wrong

        This is missing input validation. convertToShares and receiveAssets loop over the length of the caller's assetsAmounts array, not over assets.length. An empty array leaves shares at type(uint256).max and transfers nothing. A one-element array prices shares from asset 0 alone and collects only asset 0.

        ##### Who can do it

        Alice deposits a full basket of three tokens into a UlyssesToken vault. Mallory, with any wallet, calls deposit([], mallory).

        - The vault is a deployed UlyssesToken (anyone can create one with UlyssesFactory.createToken, and existing ones are public).

        - No approval or prior balance is needed for the empty-array case.

        ##### What they get

        Mallory receives 2^256-1 shares for nothing. She holds nearly all of the supply, so Alice's shares become worthless anywhere the token is traded or used. Further deposits then overflow totalSupply and revert, so the vault is also unusable. With a one-element array she instead gets full-basket shares while paying for one asset.

        ##### How it works

        1. deposit calls previewDeposit, which calls convertToShares (ERC4626MultiToken.sol:88, 210-212).

        2. convertToShares starts shares at the max value and loops only over the caller's array (ERC4626MultiToken.sol:182-194).

        3. receiveAssets also loops only over the caller's array, so it transfers nothing or only some assets (ERC4626MultiToken.sol:54-63).

        4. _mint credits the computed shares to Mallory (ERC4626MultiToken.sol:93).

        Exploit scenario

        Not specified.

        Recommendation

        Require assetsAmounts.length == assets.length in deposit, withdraw, convertToShares and previewWithdraw, and loop over assets.length. Add tests that deposit([]) and a short array both revert.

        Devin Security (Deep)

        UlyssesToken deposit accepts a short or empty amounts array and mints shares that are not backed by all assets

        src/2-audit/erc-4626/ERC4626MultiToken.sol:81 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can call deposit on a Ulysses multi-asset token with a one-element or empty amounts array and receive a huge number of shares while paying for only one asset, or for nothing at all, which dilutes every existing holder and locks the owner out of the admin functions.

        ##### What's wrong

        This is a missing input length check that turns into unbacked minting. ERC4626MultiToken.deposit takes a user-supplied assetsAmounts array, computes shares as the minimum over only the entries the user supplied, and pulls only those entries from the user. It never checks that the array covers every asset in the vault.

        ##### Who can do it

        Alice, an LP at Acme Capital, deposits equal value of three Ulysses pool tokens into a Ulysses Token (ULT) and holds ULT shares. Mallory, an attacker with a funded wallet and no special role, calls deposit([x], mallory) with a one-element array holding only the cheapest of the three assets. If totalSupply is still zero she can even call deposit([], mallory) and receive type(uint256).max shares for free.

        - The target is any UlyssesToken created through UlyssesFactory.createToken, which anyone can call, or an official one.

        - Mallory needs only enough of one underlying asset to pass the non-zero share check (or none if supply is zero).

        ##### What they get

        Mallory mints shares as if she had deposited every asset, so the vault now has far more shares than backing. Alice's shares lose their claim on the other assets. The inflated totalSupply also makes updateAssetBalances try to pull totalSupply * weight / totalWeights of every asset from the owner, so addAsset, removeAsset and setWeights revert or drain the owner's approved balance. If ULT is traded or accepted anywhere else, Mallory can sell the unbacked shares for real value. She can do this to every ULT vault on the chain.

        ##### How it works

        1. Mallory calls ERC4626MultiToken.deposit(assetsAmounts, receiver) at ERC4626MultiToken.sol:81 with assetsAmounts.length smaller than assets.length.

        2. previewDeposit calls convertToShares at ERC4626MultiToken.sol:182, which loops only over assetsAmounts.length entries and takes the minimum, so with one entry shares equal amount * totalWeights / weights[0]; with zero entries shares stay at type(uint256).max.

        3. receiveAssets at ERC4626MultiToken.sol:54 also loops only over assetsAmounts.length, so only the supplied assets are pulled from Mallory.

        4. _mint(receiver, shares) at ERC4626MultiToken.sol:93 credits the full share amount.

        5. Later, UlyssesToken.updateAssetBalances at UlyssesToken.sol:105 computes the required balance for every asset from the inflated totalSupply and tries to pull the shortfall from the owner.

        Exploit scenario

        Not specified.

        Recommendation

        In deposit, withdraw, previewDeposit, previewWithdraw and convertToShares, require assetsAmounts.length == assets.length and revert otherwise. In convertToShares, also revert when the computed minimum is still type(uint256).max. Add a unit test that calls deposit with a shorter array and with an empty array and asserts both revert, and a test that a full-length deposit still mints the expected shares.

        Claude Security (Sonnet 5.5)

        deposit() with an empty assetsAmounts array mints type(uint256).max shares for zero assets

        src/2-audit/erc-4626/ERC4626MultiToken.sol:186 Predicted severity: Medium

        Root cause

        Vulnerable symbol: convertToShares

        Preconditions: Vault totalSupply is 0 (freshly created token), because a non-zero supply makes totalSupply += type(uint256).max overflow and revert; No privileges are required

        Offending code:

        shares = type(uint256).max;

        Impact

        Free minting of an effectively unlimited share supply. Permanent denial of service for deposits into the affected vault and for all owner rebalancing and asset management. Total loss of share-accounting integrity. An attacker can front-run the first honest depositor of any fresh vault.

        Description

        The caller-supplied assetsAmounts array is never checked to be non-empty or to match assets.length. convertToShares starts from type(uint256).max and only lowers it inside a loop over the caller's array length. An empty array skips the loop, so previewDeposit returns type(uint256).max, which passes the != 0 check in deposit. receiveAssets then transfers nothing and _mint credits the receiver the full amount. Also CWE-130: The untrusted assetsAmounts array sets the loop bound in convertToShares (line 184) and in receiveAssets (line 55). Neither compares it to assets.length or weights.length. Shares are priced from only the supplied prefix, while the assets pulled are only that same prefix. An empty array leaves shares at type(uint256).max.

        Exploit scenario

        UlyssesFactory.createToken is permissionless and does not override deposit/previewDeposit, so every UlyssesToken inherits this behaviour. Right after a token is created, totalSupply is 0. An attacker calls deposit(new uint256[](0), attacker). convertToShares returns 2^256-1, no tokens are pulled, and the attacker receives 2^256-1 shares for free. Because totalSupply is now at the uint256 ceiling, every later deposit fails when _mint does totalSupply += shares (checked arithmetic in Solidity 0.8, per upstream solmate ERC20). The owner's addAsset, removeAsset and setWeights call updateAssetBalances, which tries to pull about totalSupply * weight / totalWeights of each asset from the owner, and that reverts. The vault is permanently bricked and the attacker holds 100% of the share supply.

        Recommendation

        In deposit, withdraw and convertToShares, require assetsAmounts.length == assets.length. Revert on empty input. Initialise the running minimum from the first element, not from type(uint256).max. Also validate that _assets.length == _weights.length, that weights are non-zero, and that assets are unique in the constructor. Also CWE-130: At the top of deposit, withdraw, previewDeposit and previewWithdraw, require assetsAmounts.length == assets.length. Also reject a zero-length assets array. Initialise shares from the first element instead of type(uint256).max. In the constructor, require _assets.length == _weights.length, nonzero weights and no duplicate assets.

        Claude Security (Opus 5.5)

        Unvalidated assetsAmounts length in multi-token deposit lets anyone mint unbacked shares, or type(uint256).max shares for free

        src/2-audit/erc-4626/ERC4626MultiToken.sol:88 Predicted severity: Medium

        Root cause

        Vulnerable symbol: deposit

        Preconditions: A UlyssesToken (ERC4626MultiToken) is deployed with more than one asset for the short-array variant, or totalSupply == 0 for the empty-array variant; Attacker holds some of at least one underlying asset for the short-array variant; nothing is needed for the empty-array variant

        Offending code:

        require((shares = previewDeposit(assetsAmounts)) != 0, "ZERO_SHARES");

        Impact

        Any unprivileged caller can mint vault shares without supplying the matching underlying. This breaks share accounting, dilutes other holders and forces owner-funded top-ups through updateAssetBalances. With an empty array on a fresh token, the attacker takes the maximum supply and permanently blocks deposits and admin rebalancing. Direct asset withdrawal is currently limited by separate bugs in redeem/withdraw (convertToAssets writes to an unallocated array and sendAssets transfers to address(this)). Once those are fixed, the unbacked shares can be redeemed for other depositors' assets.

        Description

        deposit() takes the caller's assetsAmounts array and never checks it against assets.length. The array length bounds the share calculation in convertToShares (min over supplied entries only, starting from type(uint256).max) and the token pull in receiveAssets. A short array mints shares that represent the full basket while only some assets are paid in, and an empty array mints type(uint256).max shares while paying nothing.

        Exploit scenario

        (1) Empty array: right after a UlyssesToken is created (totalSupply == 0), an attacker calls deposit([], attacker). convertToShares skips its loop and returns type(uint256).max. That passes the != 0 check, receiveAssets transfers nothing, and _mint credits the attacker with 2^256-1 shares. After that, every honest deposit()/mint() overflows totalSupply and reverts, so the token is permanently unusable. The owner's addAsset/setWeights then call updateAssetBalances, which tries to pull totalSupply-proportional balances from the owner and reverts. (2) Short array: with assets = [A,B,C] and equal weights, the attacker calls deposit([X], attacker) and pays only X of asset A. convertToShares returns X*totalWeights/weights[0] = 3X shares, the amount that would normally require X of each of A, B and C. The attacker's shares dilute honest depositors' claim on B and C. When the owner later calls setWeights/addAsset, updateAssetBalances pulls the missing B and C from the owner to back the inflated supply.

        Recommendation

        In deposit(), withdraw(), convertToShares() and previewWithdraw(), require assetsAmounts.length == assets.length (revert otherwise). Iterate over assets.length rather than the caller-supplied length, and reject an empty array explicitly. Also validate in the constructor that _assets.length == _weights.length and that every weight is non-zero.

        Vercel Security Review

        Empty deposits can saturate a new UlyssesToken's supply for free

        src/2-audit/erc-4626/ERC4626MultiToken.sol:184 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Empty input produces the maximum share amount** - src/2-audit/erc-4626/ERC4626MultiToken.sol:184-187

        ```solidity title="src/2-audit/erc-4626/ERC4626MultiToken.sol:184-187"

        uint256 length = assetsAmounts.length;

        shares = type(uint256).max;

        for (uint256 i = 0; i < length;) {

        ```

        An attacker can front-run a new UlyssesToken's first deposit with an empty array; no basket-length validation exists.

        **2. Empty input also skips all collateral transfers** - src/2-audit/erc-4626/ERC4626MultiToken.sol:54-57

        ```solidity title="src/2-audit/erc-4626/ERC4626MultiToken.sol:54-57"

        function receiveAssets(uint256[] memory assetsAmounts) private {

        uint256 length = assetsAmounts.length;

        for (uint256 i = 0; i < length;) {

        assets[i].safeTransferFrom(msg.sender, address(this), assetsAmounts[i]);

        ```

        **3. The new deposit path mints these unbacked shares** - src/2-audit/erc-4626/ERC4626MultiToken.sol:91-93

        ```solidity title="src/2-audit/erc-4626/ERC4626MultiToken.sol:91-93"

        receiveAssets(assetsAmounts);

        _mint(receiver, shares);

        ```

        With zero existing supply this saturates totalSupply, causing subsequent positive deposits to overflow rather than mint shares.

        Exploit scenario

        Not specified.

        Recommendation

        Require a nonempty configured basket and exact input length before calculating shares or transferring assets.

      • Multiple redeems of the same deposit are possible maia-4 · 9 writeups Critical

        V12

        Failed deposits can be refunded repeatedly

        src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:237 Predicted severity: Critical

        Root cause

        Refunding a failed deposit does not consume its lifecycle status or refundable balances in _redeemDeposit().

        Impact

        A failed-request owner can drain the branch port's wrapped-native reserves by repeatedly withdrawing the same refundable gas balance. Failed token-bearing deposits can likewise repeat their token refunds, although the management-request gas path alone supports direct unauthorized withdrawal beyond the original deposit.

        Description

        Failed management requests can enter BranchBridgeAgent.anyFallback(), which marks their stored deposit Failed and deducts fallback costs from its gas balance. redeemDeposit() checks this status but _redeemDeposit() never changes it or clears the stored refundable amounts. Every subsequent call repeats the same port withdrawals, including the remaining wrapped-native gas deposit for no-token requests. The function is public, and withdrawals are sent to the stored deposit owner, so that owner can repeatedly redeem their own failed request. The branch port authorizes the bridge agent but maintains no per-deposit consumed flag to stop the repeated withdrawals.

        Codex Security (GPT-6 Sol)

        A failed bridge deposit can be redeemed repeatedly

        src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:237 Predicted severity: Critical

        Root cause

        The redemption state machine has no terminal transition. The lock prevents nested calls but leaves subsequent transactions able to reuse the same failed deposit record.

        Impact

        A depositor with one failed message can repeatedly mint hTokens and withdraw shared branch reserves.

        Description

        The refund entry checks that a deposit failed but leaves it failed after refunding hTokens, underlying, and gas, so its owner can claim the same refund again.

        Exploit scenario

        failed nonce -> unchanged status check -> repeated port mint/withdraw

        Recommendation

        Set a terminal redeemed state before external refund calls and reject any later redemption of that nonce.

        Pashov (Claude Opus 5.5 high)

        BranchBridgeAgent.redeemDeposit never clears the deposit, so a failed deposit can be redeemed repeatedly

        src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:237 Predicted severity: Critical

        Root cause

        Missing state update (delete getDeposit[_depositNonce] or setting the status to a redeemed state) before the token transfers in _redeemDeposit.

        Impact

        Anyone can drain all underlying tokens and gas WETH held by the Branch Port and mint unlimited branch hTokens. Every user's deposit is at risk.

        Description

        redeemDeposit only checks getDeposit[nonce].status == Failed and then calls _redeemDeposit. That function mints the hTokens back, withdraws the underlying, and withdraws the deposited gas WETH to the owner. It never deletes the deposit or changes its status. The deposit stays Failed, so redeemDeposit can be called any number of times.

        Exploit scenario

        The attacker deposits 100 USDC through callOutAndBridge with params that make root execution revert (for example an unknown funcId or a bad hToken). Anycall calls anyFallback, which sets the deposit to Failed. The attacker then calls redeemDeposit(nonce) N times. Each call withdraws 100 USDC plus the deposited gas from the port, until the port is empty.

        Recommendation

        Delete the deposit (or mark it as redeemed) before transferring tokens, and restrict redemption to the deposit owner.

        Pashov (Codex GPT-6 Sol high)

        Failed branch deposit can be redeemed repeatedly

        audit/src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:237 Predicted severity: Critical

        Root cause

        No terminal Redeemed status or deletion after refund.

        Impact

        Repeated minting and withdrawal can drain branch reserves.

        Description

        redeemDeposit checks Failed status but _redeemDeposit does not consume the record.

        Exploit scenario

        Cause a deposit fallback, then call redeemDeposit on the same nonce repeatedly.

        Recommendation

        Mark or delete the deposit before external refund calls; reject consumed nonces.

        Devin Security

        Failed deposits can be redeemed over and over, draining the branch port

        src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:237 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Any user can make one deposit fail on purpose and then redeem it again and again, pulling every token the branch port holds.

        ##### What's wrong

        This is a double-spend (missing state update). redeemDeposit only checks that the deposit status is Failed, and _redeemDeposit pays out the tokens but never changes the status or deletes the entry, so the same failed deposit stays redeemable forever.

        ##### Who can do it

        Mallory has a wallet and some USDC on a branch chain. She calls callOutAndBridge with 100 USDC and a payload that the root router rejects. MulticallRootRouter.anyExecuteDepositSingle always reverts, and the root agent's multi-asset path always reverts on its slice length, so this is easy. The message layer calls anyFallback on the branch, which marks her deposit Failed. She then calls redeemDeposit(nonce) in a loop.

        - Mallory needs only a normal wallet and one small deposit.

        - The root side must revert her message so that the fallback fires. Many inputs do this.

        - The branch port must hold tokens from other users.

        ##### What they get

        Each call sends Mallory her full underlying deposit again, mints her hToken amount again, and returns her deposited gas in wrapped native token. She can repeat this until the port is empty. That takes the locked funds of every user who bridged through this branch chain, plus the gas budget.

        ##### How it works

        1. Mallory deposits through callOutAndBridge, and the port pulls her tokens (BranchBridgeAgent.sol:482-497).

        2. The root execution reverts, and the message layer calls anyFallback, which sets the status to Failed through _clearDeposit (BranchBridgeAgent.sol:828-831, 541-544).

        3. redeemDeposit checks for Failed and calls _redeemDeposit (BranchBridgeAgent.sol:237-243).

        4. _redeemDeposit calls bridgeIn and withdraw for every token and withdraws depositedGas, but it never writes a new status (BranchBridgeAgent.sol:504-522).

        5. Mallory calls redeemDeposit again with the same nonce, and the check passes again.

        Exploit scenario

        Not specified.

        Recommendation

        In redeemDeposit, require that msg.sender is the deposit owner. Delete the deposit, or set it to a terminal Redeemed status, before you make any port calls. Add a test that makes one deposit fail, redeems it once, and checks that a second redeemDeposit call reverts.

        Devin Security (Deep)

        redeemDeposit never clears the deposit, so a failed deposit can be redeemed an unlimited number of times

        src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:237 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone whose branch deposit fails can call redeemDeposit as many times as they like and get paid in full every time, draining the branch port of every other user's tokens.

        ##### What's wrong

        This is a missing state update that enables a replay. _redeemDeposit pays out the deposit's hTokens, underlying tokens and gas, but never marks the deposit as redeemed or deletes it, so the Failed status check passes again on the next call.

        ##### Who can do it

        Alice holds USDC in the Fantom port. Mallory, an attacker with a wallet, deposits 10,000 USDC on Fantom with callOutAndBridge and a payload the root router rejects; the multicall root router reverts on every deposit-with-call, so this is easy. The anycall fallback marks her deposit Failed. She then calls redeemDeposit repeatedly.

        - A deposit in Failed status owned by Mallory. She can produce one at will on any remote branch chain by sending a deposit the root reverts on.

        - The anycall fallback must be delivered to the branch so _clearDeposit runs.

        ##### What they get

        Every call returns her 10,000 USDC plus her gas deposit. She repeats until the Fantom port has no USDC left and does the same for every token and every remote branch chain. All depositors lose their funds. Because bridgeIn also mints branch hTokens on each call, she can also inflate hToken supply without limit.

        ##### How it works

        1. Mallory calls callOutAndBridge with a real deposit (BranchBridgeAgent.sol:147-154, 324-346); _createDepositMultiple stores the deposit with status Success (471-497).

        2. The root reverts, for example because MulticallRootRouter.anyExecuteDepositSingle always reverts (MulticallRootRouter.sol:236-244), and anycall calls anyFallback on the branch.

        3. anyFallback calls _clearDeposit, setting the status to Failed (BranchBridgeAgent.sol:826-837, 541-544).

        4. Mallory calls redeemDeposit; it checks status == Failed and calls _redeemDeposit (BranchBridgeAgent.sol:237-243).

        5. _redeemDeposit transfers everything out through BranchPort.bridgeIn and BranchPort.withdraw and leaves the stored deposit untouched (BranchBridgeAgent.sol:504-522).

        6. Mallory calls redeemDeposit again with the same nonce; step 4 passes again.

        Exploit scenario

        Not specified.

        Recommendation

        In _redeemDeposit, delete getDeposit[_depositNonce] (or set a distinct Redeemed status) before transferring funds, and restrict redeemDeposit to deposit.owner. Verify with a test that fails a deposit, redeems it once, and asserts the second redeemDeposit reverts and the port balance decreased exactly once.

        Claude Security (Sonnet 5.5)

        Failed deposit can be redeemed an unlimited number of times because redeemDeposit never closes the deposit state

        src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:515 Predicted severity: Critical

        Root cause

        Vulnerable symbol: _redeemDeposit

        Preconditions: Non-Arbitrum branch chain, where Anycall fallback marks deposits as Failed.; Attacker can cause a root-side revert for their own deposit, which is trivial with an unregistered hToken.

        Offending code:

        IPort(localPortAddress).withdraw(deposit.owner, deposit.tokens[i], deposit.deposits[i]);

        Impact

        Any user can drain every token (and wrapped-native gas) held by a branch Port, with repeated minting of local hTokens. This is wholesale theft of bridged liquidity.

        Description

        redeemDeposit is gated only by getDeposit[n].status == Failed. _redeemDeposit pays out underlying, remints hTokens and returns gas WETH, but never changes status or deletes the entry, so the gate stays open. The owner (or anyone, since there is no caller check) can repeat the payout, each time taking assets that belong to other depositors from the Port. Also CWE-837: The deposit nonce is a one-time redemption token, but _redeemDeposit pays out the Port's tokens and wrapped gas without changing status or clearing the entry. redeemDeposit only checks status == Failed, so every call pays out again. An attacker can force a deposit into Failed state by sending a bogus hToken that Root rejects.

        Exploit scenario

        1) Attacker approves the BranchPort and calls callOutAndBridge with DepositInput{hToken: an unregistered address, token: USDC, amount: D, deposit: D}, plus enough gas. 2) The branch pulls D USDC into the Port. At the root, CheckParamsLib.checkParams returns false (hToken is not a local token), so InvalidInputParams reverts. 3) Anycall delivers anyFallback to the branch. _clearDeposit sets status = Failed. 4) Attacker calls redeemDeposit(nonce) repeatedly. Each call withdraws D USDC and the leftover gas WETH from the Port to the attacker, so the first call refunds their own deposit and every later call takes other users' funds. A deposit with amount>deposit also remints hTokens on each call.

        Recommendation

        Set the deposit status to a terminal state (for example delete getDeposit[_depositNonce] or mark it Redeemed) before making external calls. Also require msg.sender == deposit.owner. Also CWE-837: Consume the deposit when redeeming. Before any external calls, set the status to a terminal value (for example a new Redeemed state) or delete getDeposit[_depositNonce], and require that state in redeemDeposit. Also validate dParams.hToken and dParams.token against the Port registries on the Branch side so bogus deposits cannot be created.

        Claude Security (Opus 5.5)

        A failed deposit can be redeemed any number of times: the refund check (status == Failed) is never cleared, so the port can be drained

        src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:515 Predicted severity: Critical

        Root cause

        Vulnerable symbol: _redeemDeposit

        Preconditions: Non-Arbitrum branch, where deposits reach Failed through the anycall fallback; The attacker funds one deposit and makes the root execution fail, which their own params can do

        Offending code:

        IPort(localPortAddress).withdraw(deposit.owner, deposit.tokens[i], deposit.deposits[i]);

        Impact

        Theft of all underlying tokens and WETH gas reserves held by the branch port, which belong to all users, and unbounded minting of branch hTokens that can be bridged to the root.

        Description

        redeemDeposit is public and has no owner check. Its only gate is getDeposit[nonce].status == Failed. _redeemDeposit refunds tokens, mints hTokens and returns gas from the port, but never deletes the deposit or changes its status. Every later call passes the same gate and pays the refund again out of the shared port. Also CWE-841: The only gate on redeemDeposit is getDeposit[nonce].status == Failed, and anyone can call it. _redeemDeposit pays out the deposit's tokens, hToken mints and depositedGas WETH from the shared port, but never deletes the entry or changes its status. The one-time refund can therefore be repeated until the port is empty.

        Exploit scenario

        1. On a non-Arbitrum branch, the attacker calls callOutAndBridge with a real registered token, e.g. deposit = 1,000 USDC, and enough gas. The root call is built to fail; for example, CoreRootRouter.anyExecuteDepositSingle always reverts. 2. Anycall delivers the fallback. anyFallback calls _clearDeposit, which sets status to Failed. 3. The attacker calls redeemDeposit(nonce) repeatedly. Each call transfers 1,000 USDC plus depositedGas WETH from the BranchPort to the attacker. If amount > deposit, each call also mints unbacked hTokens. 4. The attacker continues until the port is empty.

        Recommendation

        In _redeemDeposit, delete getDeposit[_depositNonce] (or move it to a terminal Redeemed state) before transferring anything. In redeemDeposit, require msg.sender == getDeposit[_depositNonce].owner. Also CWE-841: In redeemDeposit, require msg.sender == deposit.owner (or route funds only to the owner) and either delete getDeposit[_depositNonce] or set a terminal status before paying out (checks-effects-interactions).

        Vercel Security Review

        Failed bridge deposits can be refunded repeatedly

        src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:504 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. A failed request enables refunds** - src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:541-544

        ```solidity title="src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:541-544"

        function _clearDeposit(uint32 _depositNonce) internal {

        //Update and return Deposit

        getDeposit[_depositNonce].status = DepositStatus.Failed;

        }

        ```

        An attacker needs one deposit whose remote execution fails and completes fallback.

        **2. Redemption checks only the unchanged failure flag** - src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:239-242

        ```solidity title="src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:239-242"

        if (getDeposit[_depositNonce].status != DepositStatus.Failed) {

        revert DepositRedeemUnavailable();

        }

        _redeemDeposit(_depositNonce);

        ```

        **3. Each invocation pays the same stored balances again** - src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:515

        ```solidity title="src/2-audit/ulysses-omnichain/BranchBridgeAgent.sol:515"

        IPort(localPortAddress).withdraw(deposit.owner, deposit.tokens[i], deposit.deposits[i]);

        ```

        The newly added _redeemDeposit never consumes the entry or changes its status. The deposit owner can repeatedly reclaim collateral and remaining gas, or remint burned hTokens, draining reserves belonging to other users.

        Exploit scenario

        Not specified.

        Recommendation

        Mark the deposit as redeemed and clear its refundable balances before making external calls. Reject subsequent redemption attempts for that nonce.

      • Broken fee sweep maia-5 · 6 writeups High

        V12

        Fee sweeping erases its payout before transfer

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:797 Predicted severity: Medium

        Root cause

        Fee cleanup zeroes the transfer amount before reading it and uses the wrong asset form for the retained surplus. The payout cannot reconcile the accumulator with the WETH balance.

        Impact

        Gas-fee surplus from management execution cannot be collected through the designated cleanup path, and the call erases the accounting claim without paying its beneficiary. This strands protocol fee value under the available implementation; it does not demonstrate theft of user principal.

        Description

        Successful root execution records unused gas as accumulatedFees while retaining the corresponding balance as wrapped native tokens. RootBridgeAgent.sweep sets the fee accumulator to zero before using it as the amount in safeTransferETH. Every authorized sweep therefore transfers zero and destroys the tracked fee amount. The function also attempts a native transfer without unwrapping the WETH retained by fee accounting. The reviewed gas lifecycle exposes no other fee withdrawal method that pays this accumulated balance to the DAO.

        Pashov (Claude Opus 5.5 high)

        RootBridgeAgent.sweep zeroes accumulatedFees before transferring, so the DAO always receives 0

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:1111 Predicted severity: Medium

        Root cause

        Wrong statement order; the value is not cached before being reset.

        Impact

        Execution-gas fees collected by the Root Bridge Agent can never be withdrawn and stay locked in the contract permanently.

        Description

        sweep sets accumulatedFees = 0 and then transfers accumulatedFees (now 0) to the DAO.

        Exploit scenario

        After 10 ETH of fees accumulate, the DAO calls sweep(). It receives 0 ETH, and accumulatedFees is reset, so the ETH is stranded.

        Recommendation

        Cache the amount: uint256 fees = accumulatedFees; accumulatedFees = 0; safeTransferETH(daoAddress, fees);.

        Pashov (Codex GPT-6 Sol high)

        DAO fee sweep transfers zero ether

        audit/src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:1111 Predicted severity: Medium

        Root cause

        The payable amount is read after clearing storage.

        Impact

        Collected execution fees remain stranded in the agent.

        Description

        sweep clears accumulatedFees before reading it as the transfer amount, so the DAO receives zero. Excess bridge gas fees are accumulated from WETH-denominated gas proceeds and are not unwrapped for an ETH transfer either.

        Exploit scenario

        Accrue fees then invoke sweep from the DAO address.

        Recommendation

        Cache accumulatedFees, clear storage, unwrap that amount of WETH (or transfer WETH directly), then pay the DAO the cached amount.

        Devin Security

        sweep sets accumulatedFees to zero before it transfers the fees, so the DAO always receives 0

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:1111 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        The DAO can never collect the bridge fees, so they stay locked in the contract.

        ##### What's wrong

        This is a statement-ordering bug. sweep sets accumulatedFees = 0 and then transfers accumulatedFees to the DAO. The transfer always sends 0.

        ##### Who can do it

        No attacker is needed. When the DAO operator at Acme Corp calls sweep, it receives nothing.

        - The DAO address calls sweep.

        ##### What they get

        All fees that build up in accumulatedFees are locked in the agent forever. This harms the protocol's own revenue, not user funds.

        ##### How it works

        1. sweep zeroes the counter (RootBridgeAgent.sol:1113).

        2. sweep then transfers the counter, which is now zero (RootBridgeAgent.sol:1114).

        Exploit scenario

        Not specified.

        Recommendation

        Store the amount in a local variable, set accumulatedFees = 0, and then transfer the local variable. To check the fix, add a test that builds up fees, calls sweep, and asserts that the DAO balance increases by that amount.

        Devin Security (Deep)

        sweep() zeroes accumulatedFees before transferring it, locking protocol fees forever

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:1111 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        The DAO can never collect the execution fees the bridge agent accumulates because the withdrawal function sends zero.

        ##### What's wrong

        This is an ordering bug. sweep sets accumulatedFees = 0 and then transfers accumulatedFees, which is now zero.

        ##### Who can do it

        No attacker is needed. When the Acme DAO treasurer calls sweep, the counter is reset and nothing is sent.

        - Caller must be daoAddress.

        ##### What they get

        Nothing is stolen, but all accumulated fees stay stuck in the bridge agent contract with no way to withdraw them.

        ##### How it works

        1. sweep sets accumulatedFees = 0 (RootBridgeAgent.sol:1113).

        2. It then calls safeTransferETH(daoAddress, accumulatedFees) with the zeroed value (RootBridgeAgent.sol:1114).

        Exploit scenario

        Not specified.

        Recommendation

        Cache the value first: uint256 fees = accumulatedFees; accumulatedFees = 0; safeTransferETH(daoAddress, fees);. Add a test that accumulates fees and asserts the DAO balance increases after sweep.

        Claude Security (Sonnet 5.5)

        DAO-only sweep() zeroes accumulatedFees before sending, so it always transfers 0 and fees are locked

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:1114 Predicted severity: Low

        Root cause

        Vulnerable symbol: sweep

        Preconditions: None beyond fees having accumulated.

        Offending code:

        SafeTransferLib.safeTransferETH(daoAddress, accumulatedFees);

        Impact

        Permanent loss of access to protocol fee accounting and funds (DoS of the DAO's withdrawal authority).

        Description

        The authorized DAO call sets accumulatedFees = 0 on the previous line and then transfers the (now zero) variable, so the privileged withdrawal path never pays out anything. Also CWE-670: accumulatedFees is set to 0 on the previous line, so the transfer always sends 0; additionally fees are kept as WETH while the function sends ETH.

        Exploit scenario

        The DAO calls sweep() to collect accumulated gas surplus. The call succeeds but sends 0 wei and also resets the accounting, so the recorded fees are lost and cannot be withdrawn later.

        Recommendation

        Cache the amount, zero the storage variable, then transfer the cached amount. Ensure the contract actually holds native ETH (accumulated surplus is currently kept as WETH). Also CWE-670: Cache the amount, zero the state, unwrap WETH if needed, and send the cached amount.

      • Asset removal is broken maia-6 · 7 writeups High

        V12

        Asset removal always crosses the array boundary

        src/2-audit/ulysses-amm/UlyssesToken.sol:57 Predicted severity: Medium

        Root cause

        The shift loop's bound includes the final element even though its body reads the next element. It must stop before the last index, but the current implementation always crosses the storage array boundary.

        Impact

        An owner cannot remove a problematic constituent or use the intended removal-and-rebalance recovery path for a basket holding user LP tokens. The demonstrated impact is loss of the composition-recovery operation; removal does not itself steal funds because its transaction always reverts before the final transfer.

        Description

        For every existing constituent of a basket with at least two assets, removeAsset iterates while i < assets.length but reads assets[i + 1]. The last iteration therefore reads exactly assets[assets.length], which is outside the array and reverts the entire transaction. The same error applies to removing the last constituent from a multi-asset basket, where the invalid read occurs immediately. This makes asset removal unavailable after successful factory deployment and prevents this recovery mechanism from resolving duplicate or malformed initial compositions. The subtraction of the shifted weight and missing reverse-index updates are also visible in the intended mutation sequence, but those later state-corruption mechanisms are unreachable because this panic rolls all writes back.

        Pashov (Claude Opus 5.5 high)

        UlyssesToken.removeAsset is broken: out-of-bounds loop, wrong weight subtracted, and stale assetId indexes

        src/2-audit/ulysses-amm/UlyssesToken.sol:57 Predicted severity: Medium

        Root cause

        Incorrect array-removal implementation and wrong ordering of the weight update.

        Impact

        The owner can never remove an asset. If the bound were fixed, totalWeights would be corrupted (share/asset conversion mispriced) and assetId lookups would be wrong, causing mis-accounting for depositors.

        Description

        The shifting loop runs for (i = assetIndex; i < assets.length; i++) assets[i] = assets[i+1]. On the last iteration it reads assets[assets.length], so every call reverts. Even with the bound fixed, totalWeights -= weights[assetIndex] runs after the shift and subtracts the next asset's weight rather than the removed one. The assetId of every shifted asset is also never updated, so it points at the wrong index.

        Exploit scenario

        The owner calls removeAsset(asset0) on a 2-asset token. The loop reads assets[2] and reverts.

        Recommendation

        Read the removed weight first. Swap the removed element with the last one and pop, updating assetId for the moved asset (stored as index+1).

        Pashov (Codex GPT-6 Sol high)

        Basket asset removal always reverts

        audit/src/2-audit/ulysses-amm/UlyssesToken.sol:57 Predicted severity: Medium

        Root cause

        The shift loop runs through assets.length rather than ending at length minus one.

        Impact

        Owner cannot remove a failed or compromised component; portfolio configuration is frozen.

        Description

        removeAsset copies assets[i+1] until i reaches the final index, which reads past array end.

        Exploit scenario

        Call removeAsset for any registered asset in a basket with more than one component.

        Recommendation

        Stop the shift loop before the final index and subtract the removed weight before shifting.

        Devin Security

        removeAsset reads past the end of the array and always reverts

        src/2-audit/ulysses-amm/UlyssesToken.sol:57 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        The token owner can never remove an asset from a Ulysses token, but no user funds are at risk.

        ##### What's wrong

        This is an off-by-one bug. The shift loop runs to i < assets.length and reads assets[i + 1], which is out of bounds on the last pass. The code also subtracts the weight after the shift, so it would subtract the wrong weight even if the loop were fixed.

        ##### Who can do it

        Alice, the token owner, calls removeAsset. The call always reverts. No attacker is involved.

        - The caller is the token owner.

        ##### What they get

        Nobody gains anything. The owner cannot change the basket by removing an asset.

        ##### How it works

        1. The loop reads assets[i + 1] when i equals the last index (UlyssesToken.sol:64-67).

        2. totalWeights -= weights[assetIndex] runs after the shift and uses the neighbour's weight (UlyssesToken.sol:69).

        Exploit scenario

        Not specified.

        Recommendation

        Subtract weights[assetIndex] before shifting, loop to assets.length - 1, and update assetId for the moved assets. Add a test that removes a middle asset.

        Devin Security (Deep)

        UlyssesToken withdraw sends the assets to the vault itself, and mint/redeem/removeAsset always revert, so deposits cannot be recovered

        src/2-audit/erc-4626/ERC4626MultiToken.sol:65 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Any holder who withdraws from a Ulysses multi-asset token burns their shares and receives nothing, and no other exit path works, so every deposit into these vaults is permanently lost.

        ##### What's wrong

        This is a wrong transfer recipient combined with uninitialized memory arrays. sendAssets transfers each asset to address(this) instead of the receiver, and convertToAssets and previewMint write into a zero-length memory array, so mint, redeem and maxWithdraw always revert with an out-of-bounds panic. The owner's removeAsset also always reverts because its shift loop reads one past the end of the array.

        ##### Who can do it

        Alice, an LP at Acme Capital, deposits three Ulysses pool tokens into a Ulysses Token vault and later calls withdraw to get them back. Her shares are burned and the tokens move from the vault to the vault. She then tries redeem, which reverts. Bob, the vault owner at Acme, tries removeAsset to rescue the funds, and that reverts too.

        - Any UlyssesToken with at least one asset is affected.

        - No attacker is needed; normal use triggers the loss.

        ##### What they get

        Alice loses every token she deposited. Nothing Alice or Bob can call moves the tokens out of the vault, so the loss is permanent for every depositor of every Ulysses Token vault.

        ##### How it works

        1. Alice calls withdraw(assetsAmounts, alice, alice) at ERC4626MultiToken.sol:120; previewWithdraw computes the shares and _burn removes them at ERC4626MultiToken.sol:136.

        2. sendAssets at ERC4626MultiToken.sol:65 calls assets[i].safeTransfer(address(this), amount) at line 68, so the tokens stay in the vault and the receiver argument is never used.

        3. redeem at ERC4626MultiToken.sol:144 calls previewRedeem, which calls convertToAssets at line 197; that function writes to assetsAmounts[i] on an unallocated return array at line 202 and reverts. mint fails the same way through previewMint at line 220.

        4. UlyssesToken.removeAsset at UlyssesToken.sol:57 loops i up to assets.length - 1 and reads assets[i + 1] at line 65, which is out of bounds, so the owner cannot sweep the stranded tokens either.

        Exploit scenario

        Not specified.

        Recommendation

        Change sendAssets to take a receiver parameter and transfer to it; pass receiver from withdraw and redeem. In convertToAssets and previewMint, allocate assetsAmounts = new uint256[](length) before the loop. In UlyssesToken.removeAsset, bound the shift loop at assets.length - 1 and read the removed weight before shifting. Add tests that deposit, then withdraw and redeem, and assert the receiver's balances increase by the expected amounts and mint succeeds.

        Claude Security (Sonnet 5.5)

        UlyssesToken.removeAsset always reverts: off-by-one out-of-bounds read in the array shift loop

        src/2-audit/ulysses-amm/UlyssesToken.sol:65 Predicted severity: Medium

        Root cause

        Vulnerable symbol: removeAsset

        Preconditions: Caller is the UlyssesToken owner (the function is onlyOwner); The basket contains at least two assets, since a single asset reverts with CannotRemoveLastAsset

        Offending code:

        assets[i] = assets[i + 1];

        Impact

        The owner cannot remove any asset from a UlyssesToken basket (for example a depegged or compromised one). Setting its weight to zero is no workaround, because convertToShares and previewWithdraw then divide by weights[i] == 0 and deposits and withdrawals revert. If the loop bound were fixed naively, assetId of the shifted assets would stay stale, and totalWeights would subtract the already-overwritten weights[assetIndex] (the next asset's weight) instead of the removed asset's weight. That would corrupt the accounting.

        Description

        The shift loop runs i up to assets.length - 1 but reads assets[i + 1] and weights[i + 1]. On the final iteration this indexes one past the end of the storage array and hits the Solidity bounds check (Panic 0x32), so the owner-only call can never succeed for any existing asset. Also CWE-125: The loop condition is i < assets.length but the body indexes i + 1. On the final iteration (i == assets.length - 1) it reads assets[assets.length], which fails the bounds check with Panic(0x32). The loop cannot complete for any asset, because the last iteration is always reached. Also CWE-129: The loop for (i = assetIndex; i < assets.length; i++) reads index i + 1 on every iteration. On the last iteration (i == assets.length - 1) that index is out of bounds, so every call panics regardless of the asset passed.

        Exploit scenario

        The owner calls removeAsset(X) for any registered asset X. The loop reaches i == assets.length - 1, evaluates assets[assets.length], and the transaction reverts with Panic(0x32). The same happens for every asset and for every basket size above one.

        Recommendation

        Rewrite the removal as swap-and-pop, or loop i + 1 < assets.length. Read the removed asset's weight into a local variable before shifting and subtract that from totalWeights. Update assetId for every moved element. Also CWE-125: Iterate i < assets.length - 1, or use swap-and-pop. Subtract the removed asset's weight before shifting, and update assetId for the moved element. Also CWE-129: Bound the loop at i < assets.length - 1. Read the removed weight before shifting. Update assetId for every shifted element, or use swap-and-pop with an assetId update.

        Claude Security (Opus 5.5)

        Off-by-one loop bound in removeAsset reads assets[assets.length], so removeAsset always reverts

        src/2-audit/ulysses-amm/UlyssesToken.sol:65 Predicted severity: Medium

        Root cause

        Vulnerable symbol: removeAsset

        Preconditions: Caller is the UlyssesToken owner (onlyOwner); Token has two or more assets

        Offending code:

        assets[i] = assets[i + 1];

        Impact

        The token owner can never remove an underlying asset from a UlyssesToken, for example a compromised or depegged pool LP. Setting that asset's weight to 0 through setWeights does not work as a substitute: convertToShares divides by weights[i], so a zero weight makes deposits revert. The token's asset composition is effectively frozen. The logic after the loop is also wrong. totalWeights -= weights[assetIndex] subtracts the weight of the shifted-in neighbour, not the removed asset. assetId is never updated for the shifted assets. So simply fixing the loop bound would still corrupt accounting.

        Description

        The shift loop runs while i < assets.length and reads assets[i + 1] and weights[i + 1]. On the last pass it reads index assets.length, which is out of bounds. Solidity's storage bounds check then panics (0x32) on every call, for any asset.

        Exploit scenario

        The owner of a UlyssesToken holding pools A, B and C calls removeAsset(B). assetIndex is 1 and the loop runs i=1 then i=2. At i=2 it evaluates assets[3] while assets.length is 3, and the transaction reverts with Panic(0x32). The same happens for every asset, so no asset can ever be removed.

        Recommendation

        Use swap-and-pop. Read weights[assetIndex] before any mutation and subtract it from totalWeights. Move the last element into assetIndex, set assetId[lastAsset] = assetIndex + 1, then pop both arrays. If order must be kept, bound the loop with i < assets.length - 1 and update assetId for every shifted asset.

      • Unsupported function codes maia-7 · 4 writeups High

        V12

        Management messages reach the wrong dispatcher

        src/2-audit/ulysses-omnichain/CoreRootRouter.sol:162 Predicted severity: Medium

        Root cause

        Management producers use the system-response action flag for selectors implemented only in the request dispatcher. The bridge agent also discards the router's failure return, allowing the failed management operation to be acknowledged as successful.

        Impact

        The supported consequence is failure of the standard branch-agent onboarding/synchronization and global-token expansion paths, with unsuccessful management requests acknowledged as successful by the bridge agent. Alternative user-originated flag-0x01 delivery exists, so the evidence does not establish an unavoidable system-wide outage, unauthorized registry changes, or permanent loss of funds.

        Description

        The root router divides management selectors between anyExecuteResponse (0x02/0x03) and anyExecute (0x01/0x04), but the actual branch management producers send all of them as system messages. CoreBranchRouter.addGlobalToken and syncBridgeAgent invoke performSystemCallOut, which prefixes the outer action flag 0x00. RootBridgeAgent.anyExecute routes that flag exclusively to anyExecuteResponse, so legitimate global-addition and branch-synchronization requests reach its unknown-selector return instead of their management handlers. The bridge agent ignores that false return and ultimately returns success, so these operations can finish without adding the token or synchronizing the branch. This is a source-backed dispatcher/lifecycle failure independent of whether the router's deployment configuration is correct.

        Pashov (Claude Opus 5.5 high)

        CoreRootRouter accepts _syncBranchBridgeAgent (funcId 0x04) from any user, so anyone can register an arbitrary EOA as a branch bridge agent and mint unlimited hTokens

        src/2-audit/ulysses-omnichain/CoreRootRouter.sol:185 Predicted severity: Critical

        Root cause

        System-level sync request is exposed through the user-callable anyExecute path instead of the system-only anyExecuteResponse path.

        Impact

        The attacker's EOA can call its Root Bridge Agent's anyExecute directly (requiresExecutor passes because msg.sender == getBranchBridgeAgent[localChainId]). It can supply forged deposits (flags 0x02/0x03/0x05/0x06). RootPort.bridgeToRoot then mints arbitrary global hTokens, which can be redeemed for real underlying on any branch. The attacker can also use flag 0x04 to approve their own router on any victim's VirtualAccount and steal its balance.

        Description

        _syncBranchBridgeAgent is dispatched from CoreRootRouter.anyExecute (flag 0x01, which any user reaches through BranchBridgeAgent.callOut). It is not in anyExecuteResponse, which only the CoreBranchRouter can reach through performSystemCallOut. The CoreBranchRouter.syncBridgeAgent check that the new agent is a real BranchBridgeAgent registered in the branch port is therefore skipped. Root bridge agents can be created permissionlessly, and the creator becomes manager and can approve any address. An attacker can thus make any address the getBranchBridgeAgent[chain] of their own Root Bridge Agent. That agent is a trusted isBridgeAgent in RootPort.

        Exploit scenario

        1) RootBridgeAgentFactory.createBridgeAgent(attackerRouter); the attacker is now manager. 2) attackerAgent.approveBranchBridgeAgent(attackerEOA, rootChainId). 3) ArbitrumBranchBridgeAgent(core).callOut{value: 1e6}(abi.encodePacked(bytes1(0x04), abi.encode(attackerEOA, attackerAgent)), 0). Root CoreRootRouter.anyExecute calls RootPort.syncBranchBridgeAgentWithRoot, which sets getBranchBridgeAgent[root] = attackerEOA. 4) attackerEOA calls attackerAgent.anyExecute(0x02|nonce|hUSDC|USDC|1e30|1e30|toChain|funcId|gas). _bridgeIn mints 1e30 global hUSDC to attackerRouter. 5) The attacker withdraws the underlying through ArbitrumBranchBridgeAgent.withdrawFromPort or bridges it to other branches.

        Recommendation

        Handle funcId 0x04 only in anyExecuteResponse (system requests from the CoreBranchRouter, which checks that the agent is registered in the branch port). Consider also requiring governance approval for new branch bridge agents.

        Pashov (Codex GPT-6 Sol high)

        Global-token onboarding messages use incompatible dispatch and payloads

        audit/src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:46 Predicted severity: Medium

        Root cause

        Request/response dispatch, payload schemas, and response-gas funding disagree across the root and branch routers.

        Impact

        A registered global token cannot be onboarded to another branch through the advertised flow.

        Description

        The branch sends an add-global-token request as system flag 0x00 with inner ID 0x01, but RootBridgeAgent forwards system messages to CoreRootRouter.anyExecuteResponse, which does not handle ID 0x01. The root return payload also omits the bytes1 selector required by the branch handler. That handler attempts to pay response gas from its own unfunded ETH balance.

        Exploit scenario

        Call CoreBranchRouter.addGlobalToken for a registered global hToken; root ignores inner 0x01 as an unknown response. If root dispatch is corrected, the returned ABI address begins with zero and branch ignores it as an unknown selector.

        Recommendation

        Route the branch request to CoreRootRouter.anyExecute, prefix the root return data with the agreed selector, fund the branch response from escrowed gas, and verify the full round trip.

        Devin Security (Deep)

        Branch agent sync is handled on the user call path; with the open root factory anyone registers their own sender for a port-privileged bridge agent and can mint any hToken or take over any virtual account

        src/2-audit/ulysses-omnichain/CoreRootRouter.sol:186 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can create their own root bridge agent, register an address they control as its trusted branch sender through a system command that is reachable from an ordinary user call, and then forge deposit messages that mint unlimited hTokens and take control of every user's virtual account.

        ##### What's wrong

        This is an authorization bypass. CoreRootRouter handles the system commands add global token (funcId 0x01) and sync branch bridge agent (funcId 0x04) in anyExecute, which receives payloads from any user's callOut, instead of in anyExecuteResponse, which only receives payloads the branch core router sends through performSystemCallOut. The sync command accepts any new branch agent address and only checks the target root bridge agent's own allow list. Because RootBridgeAgentFactory.createBridgeAgent is open to everyone and registers the new agent as a trusted bridge agent in RootPort, the attacker is the manager of that allow list.

        ##### Who can do it

        Alice keeps hTokens in her virtual account on the root chain and USDC in the Arbitrum port. Mallory, an attacker with a wallet on Arbitrum, calls RootBridgeAgentFactory.createBridgeAgent with a router contract she wrote. She calls approveBranchBridgeAgent on her new agent to allow a contract she controls. She then calls the public callOut on the core branch bridge agent on Arbitrum with a payload that starts with 0x04 and names her contract and her agent. The root core router registers her contract as the agent's trusted sender. Her contract now calls anyExecute on her agent with any message it likes.

        - A wallet with gas on Arbitrum. The same works from any branch chain through anycall.

        - RootBridgeAgentFactory.createBridgeAgent is callable by anyone and grants isBridgeAgent in RootPort.

        - The core branch bridge agent's callOut is callable by anyone and its payload reaches CoreRootRouter.anyExecute, which handles funcId 0x04.

        ##### What they get

        With a forged flag 0x02 message, _bridgeIn and RootPort.bridgeToRoot mint any amount of any hToken to Mallory, which she cashes out of every branch port. With a forged flag 0x04 message that names Alice's address, RootPort approves Mallory's router on Alice's virtual account and Mallory's router calls withdrawERC20 and arbitrary call on it, taking everything Alice holds there. This reaches every user and every chain.

        ##### How it works

        1. RootBridgeAgentFactory.createBridgeAgent(attackerRouter) deploys a RootBridgeAgent and RootPort.addBridgeAgent marks it isBridgeAgent with Mallory as manager (RootBridgeAgentFactory.sol:68-85, RootPort.sol:388-393).

        2. Mallory calls approveBranchBridgeAgent(attackerContract, chainId) as manager (RootBridgeAgent.sol:1097-1100).

        3. Mallory calls callOut on the core branch bridge agent with params = 0x04 || abi.encode(attackerContract, attackerAgent) (BranchBridgeAgent.sol:142-144, 307-314).

        4. The core root bridge agent passes the payload to CoreRootRouter.anyExecute, which handles funcId 0x04 and calls RootPort.syncBranchBridgeAgentWithRoot (RootBridgeAgent.sol:902-904, CoreRootRouter.sol:203-208, 66-70).

        5. RootPort only checks the attacker agent's own allow list and calls syncBranchBridgeAgent, so getBranchBridgeAgent[chainId] = attackerContract (RootPort.sol:396-408, RootBridgeAgent.sol:1107-1109).

        6. attackerContract calls anyExecute on the attacker agent and _requiresExecutor accepts it (RootBridgeAgent.sol:183-189).

        7. Flag 0x02 mints arbitrary hTokens through _bridgeIn and bridgeToRoot (RootBridgeAgent.sol:907-921, RootPort.sol:324-330). Flag 0x04 approves the attacker router on any user's virtual account and hands it control (RootBridgeAgent.sol:942-953, RootPort.sol:364-381, VirtualAccount.sol:32-48, 55-58).

        Exploit scenario

        Not specified.

        Recommendation

        Move funcIds 0x01 and 0x04 from anyExecute to anyExecuteResponse so only the branch core router's performSystemCallOut can trigger them, and make anyExecute reject them. In RootPort.syncBranchBridgeAgentWithRoot, additionally require that the message came from the branch's core bridge agent (which has verified isBridgeAgent on the branch port). Restrict RootBridgeAgentFactory.createBridgeAgent to the owner or an allow list, or stop granting isBridgeAgent automatically on creation. Verify with tests: send a 0x04 payload through a user callOut and assert the root rejects it; call createBridgeAgent from a random account and assert it reverts.

      • Missing access control on anyExecuteNoSettlement maia-8 · 7 writeups High

        V12

        Unauthenticated receiver can overwrite cross-chain token mappings

        src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149 Predicted severity: High

        Root cause

        The derived no-settlement receiver omits the base caller guard, while the root registry treats every resulting system response as authorized to overwrite token mappings.

        Impact

        A caller can replace an existing global token's destination mapping with a newly deployed hToken, redirecting future bridge settlements away from the previously registered token. The path requires the branch router to hold enough native currency to fund gasToBridgeOut and successful response transport; without that balance the attempted mutation reverts, but no caller authorization prevents it when funded.

        Description

        CoreBranchRouter.anyExecuteNoSettlement() overrides the base receiver without retaining requiresBridgeAgent. An arbitrary local caller can therefore submit abi.encode(bytes1(0x01), globalAddress, name, symbol, gasToBridgeOut) and execute _receiveAddGlobalToken() without a root message. The router creates a port-owned hToken and sends a 0x03 system response claiming that the caller-selected global address maps to that token on this chain. The authenticated root bridge forwards this response to _setLocalToken(), and RootPort.setLocalAddress() overwrites both registry directions without checking prior registration or global-token recognition. This is a local-to-cross-chain authority escalation: transport authentication authenticates a response generated from an unauthenticated local invocation.

        Pashov (Claude Opus 5.5 high)

        CoreBranchRouter.anyExecuteNoSettlement lacks the bridge-agent check, so anyone can remap global tokens to fresh local hTokens

        src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149 Predicted severity: High

        Root cause

        Missing requiresBridgeAgent modifier on CoreBranchRouter.anyExecuteNoSettlement.

        Impact

        An attacker can repoint any global token's local representation on a branch to a freshly deployed hToken with no underlying mapping. Settlements to that chain then use the wrong token and underlying withdrawals revert (UnrecognizedUnderlyingAddress), freezing bridging for that asset. The old hTokens held by users lose their global->local round-trip. The call also spends the router's ETH balance on gas.

        Description

        anyExecuteNoSettlement overrides the BaseBranchRouter version but drops the requiresBridgeAgent modifier. Anyone can call it with funcId 0x01. _receiveAddGlobalToken then deploys a new hToken and sends a system request (performSystemCallOut, flag 0x00, funcId 0x03) through the core bridge agent. Root trusts that request as coming from the CoreBranchRouter and calls RootPort.setLocalAddress(global, newToken, chain), overwriting the existing global->local mapping for any token the attacker names.

        Exploit scenario

        The attacker force-sends a little ETH to the CoreBranchRouter (for example via selfdestruct) so performSystemCallOut{value:_rootExecutionGas} has value. They call CoreBranchRouter.anyExecuteNoSettlement(abi.encode(bytes1(0x01), hUSDC_global, "x", "x", uint128(200000))). Root executes _setLocalToken(hUSDC_global, newFakeLocal, branchChain), and all later settlements of hUSDC to that branch use the new, unbacked token.

        Recommendation

        Add requiresBridgeAgent to CoreBranchRouter.anyExecuteNoSettlement. On root, refuse to overwrite an existing local mapping in _setLocalToken.

        Pashov (Codex GPT-6 Sol high)

        Public core branch callback can execute without bridge agent authentication

        audit/src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149 Predicted severity: High

        Root cause

        The override omits requiresBridgeAgent.

        Impact

        An untrusted EOA can remap an active global token on a branch, disrupting or redirecting future bridging and stranding old local-token holders.

        Description

        anyExecuteNoSettlement overrides the authenticated base callback without the bridge-agent restriction.

        Exploit scenario

        Force-fund the router with enough ETH for the system response, then call anyExecuteNoSettlement with abi.encode(bytes1(0x01), an existing global hToken, chosen name, chosen symbol, gas). The router deploys a new local token and sends an authenticated response that overwrites the global/local mapping.

        Recommendation

        Apply requiresBridgeAgent and verify source chain and payload constraints.

        Devin Security

        anyExecuteNoSettlement override has no caller check

        src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can call the branch core router's cross-chain handler directly and push a token-mapping update to the root chain, but only if the router holds ETH, which it normally does not.

        ##### What's wrong

        This is a missing authorization check. The override of anyExecuteNoSettlement drops the requiresBridgeAgent modifier that the base router uses. The 0x01 branch then creates a new hToken and sends a system message that tells the root to map any globalAddress to that token on this chain. The second branch also tests 0x01, so the add-bridge-agent-factory handler can never run.

        ##### Who can do it

        Mallory, who has no special access, calls CoreBranchRouter.anyExecuteNoSettlement with a payload that names Acme's popular global token. The call works only if the router holds at least 150,001 wei. The router has no payable entry point, but someone can force ETH into it, for example through selfdestruct.

        - The router must hold enough ETH. Mallory can force it in.

        ##### What they get

        The root's _setLocalToken overwrites getLocalAddressFromGlobal for that global token on this chain with no checks. Later bridge-outs to this chain then go to the new hToken instead of the existing one. That breaks token accounting for the asset on this chain. She cannot directly steal funds this way.

        ##### How it works

        1. Mallory calls anyExecuteNoSettlement, which has no caller check (CoreBranchRouter.sol:149-159).

        2. _receiveAddGlobalToken creates a token and calls performSystemCallOut with the router's ETH (CoreBranchRouter.sol:111-130).

        3. The root agent passes flag 0x00 with function 0x03 to CoreRootRouter._setLocalToken (CoreRootRouter.sol:171-174).

        4. RootPort.setLocalAddress overwrites the mapping.

        Exploit scenario

        Not specified.

        Recommendation

        Add requiresBridgeAgent to the override. Change the second selector to 0x02. On the root side, check that the global token exists and is not already mapped before _setLocalToken. Add a test that a direct call from an outside address reverts.

        Devin Security (Deep)

        anyExecuteNoSettlement has no caller check, letting anyone rewrite a token's branch mapping on the root chain

        src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can make the root chain point a real bridged token at a freshly created empty token on a branch chain, which breaks withdrawals of that token on that chain and sends later bridgers the wrong token.

        ##### What's wrong

        This is missing authentication. BaseBranchRouter.anyExecuteNoSettlement is guarded by requiresBridgeAgent, but CoreBranchRouter overrides it without the modifier. The function mints a new local hToken and sends a system message that the root CoreRootRouter turns into RootPort.setLocalAddress with no validation that the global token exists or that the mapping is still empty.

        ##### Who can do it

        Alice and other Acme Bridge users bridge USDC to chain B. Mallory, an attacker with an ordinary wallet on chain B, force-sends a little ETH to the CoreBranchRouter (for example via selfdestruct) and then calls anyExecuteNoSettlement(abi.encode(bytes1(0x01), hUSDC_global, name, symbol, gas)).

        - Mallory needs a wallet on a branch chain that uses CoreBranchRouter (the Arbitrum variant reverts in this function).

        - The router must hold at least MIN_FALLBACK_OVERHEAD wei, which Mallory can force-send herself.

        ##### What they get

        The root port now maps global hUSDC on chain B to a new, empty token T. Any user bridging hUSDC with an underlying withdrawal to chain B reverts with UnrecognizedUnderlyingAddress, and users bridging without withdrawal receive T instead of the real local hUSDC. Mallory can do this for every token on every such chain and repeat it after an operator fixes it. No funds are taken, but bridging to the chain is disrupted until an owner repairs the registry.

        ##### How it works

        1. Mallory calls CoreBranchRouter.anyExecuteNoSettlement directly; there is no requiresBridgeAgent (CoreBranchRouter.sol:149-154 versus BaseBranchRouter.sol:90-92).

        2. _receiveAddGlobalToken creates a new hToken T via the factory (the router is the authorized caller) and calls performSystemCallOut with the router's ETH (CoreBranchRouter.sol:111-130).

        3. The core branch bridge agent sends flag 0x00 with funcId 0x03 to the root (BranchBridgeAgent.sol:250-263).

        4. CoreRootRouter.anyExecuteResponse decodes (globalAddress, T) and calls _setLocalToken with no checks (CoreRootRouter.sol:171-176, 146-148).

        5. RootPort.setLocalAddress overwrites getLocalAddressFromGlobal[B][hUSDC_global] = T (RootPort.sol:296-302).

        6. RootBridgeAgent.callOutAndBridge now resolves hUSDC to T on chain B and an underlying of address(0) (RootBridgeAgent.sol:249-252).

        Exploit scenario

        Not specified.

        Recommendation

        Add requiresBridgeAgent to CoreBranchRouter.anyExecuteNoSettlement. On the root, make _setLocalToken require isGlobalAddress(_globalAddress) and that getLocalAddressFromGlobal[_toChain][_globalAddress] == address(0). Add a test asserting a direct call to anyExecuteNoSettlement from a non-agent reverts.

        Claude Security (Sonnet 5.5)

        CoreBranchRouter.anyExecuteNoSettlement is callable by anyone, letting any caller drive the router's system call-outs to the root chain

        src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149 Predicted severity: Medium

        Root cause

        Vulnerable symbol: CoreBranchRouter.anyExecuteNoSettlement

        Preconditions: The deployment is a non-Arbitrum branch chain using CoreBranchRouter. ArbitrumCoreBranchRouter overrides the function with revert().; The attacker must put roughly 0.0001 to 0.01 native token of gas funds into the router, for example by selfdestruct force-send, because the router holds no ETH by default and performSystemCallOut requires msg.value > 150000 wei.; The root side must accept the message: the deposited gas must cover _payExecutionGas, which depends on gas price and the root gas pool.

        Offending code:

        function anyExecuteNoSettlement(bytes memory _data)

        Impact

        An unauthenticated caller can corrupt the root port's global-to-local token registry for any global token on any non-Arbitrum branch chain. This permanently breaks underlying-token withdrawals and settlements for the targeted token and chain, which freezes the underlying funds held in the BranchPort, and it misdirects hToken settlements to an unintended local token. The caller can also spam-deploy hToken contracts with arbitrary names and symbols through the factory.

        Description

        BaseBranchRouter declares anyExecuteNoSettlement with the requiresBridgeAgent modifier, but the CoreBranchRouter override drops the modifier, so any address can call it with attacker-chosen _data. The data reaches _receiveAddGlobalToken, which creates an hToken through the factory and sends a trusted system message (0x03 setLocalToken) to the root chain in the router's own name.

        Exploit scenario

        1) The attacker force-sends a small amount of native token to the CoreBranchRouter (for example via selfdestruct), since the router has no payable fallback. The amount must exceed MIN_FALLBACK_OVERHEAD (150000 wei) and cover root-side execution gas. 2) The attacker calls CoreBranchRouter.anyExecuteNoSettlement(abi.encode(bytes1(0x01), victimGlobalToken, 'x', 'x', gas)), with gas set to the donated amount. 3) The router calls factory.createToken(...), which passes because the router is the factory's core router. It then calls performSystemCallOut{value: gas}(address(this), 0x03 || abi.encode(victimGlobalToken, newToken), 0). The call passes requiresRouter because msg.sender is the router, and the message is delivered through the genuine Core branch bridge agent. 4) On the root chain, the Core bridge agent passes the flag-0x00 message to CoreRootRouter.anyExecuteResponse, which calls RootPort.setLocalAddress(victimGlobalToken, newToken, branchChainId). That overwrites getLocalAddressFromGlobal[branchChain][victimGlobalToken] and adds getGlobalAddressFromLocal[branchChain][newToken], with no check that the global token is valid or that a mapping already exists. 5) Root-to-branch settlements for that token now resolve the local token to newToken, and getUnderlyingTokenFromLocal(newToken) is address(0). Any settlement with deposit > 0 reverts with UnrecognizedUnderlyingAddress, so underlying funds for that token on that chain can no longer be withdrawn.

        Recommendation

        Add the requiresBridgeAgent modifier to CoreBranchRouter.anyExecuteNoSettlement (and to the base implementation's override chain). Fix the duplicated selector check: the second branch tests _data[0] == 0x01 again, so _receiveAddBridgeAgentFactory is dead code. If that branch is corrected to 0x02 without the access check, anyone could register an arbitrary bridge agent factory on the BranchPort. Add validation on the root side so setLocalAddress requires an existing global address and refuses to overwrite an already-mapped (global, chain) pair.

        Claude Security (Opus 5.5)

        CoreBranchRouter.anyExecuteNoSettlement has no bridge-agent check, so anyone can send the privileged setLocalToken (0x03) system message to the root and overwrite the global-to-local token mapping

        src/2-audit/ulysses-omnichain/CoreBranchRouter.sol:149 Predicted severity: Medium

        Root cause

        Vulnerable symbol: anyExecuteNoSettlement

        Preconditions: Non-Arbitrum branch (ArbitrumCoreBranchRouter overrides this function to revert); The attacker force-feeds more than 150000 wei plus root execution gas into CoreBranchRouter, which has no receive function, for example via selfdestruct

        Offending code:

        function anyExecuteNoSettlement(bytes memory _data)

        Impact

        Unauthenticated corruption of the root token registry for any global token on the branch. Withdrawals of that token's underlying from the branch are frozen until the RootPort owner repairs the mapping, and the attack can be repeated after each repair.

        Description

        The override drops the requiresBridgeAgent modifier that BaseBranchRouter puts on this function. Any caller can reach _receiveAddGlobalToken. That creates a factory hToken and has the core bridge agent send a trusted system message (flag 0x00, funcId 0x03) to the root. CoreRootRouter._setLocalToken and RootPort.setLocalAddress then overwrite getLocalAddressFromGlobal[chain][G] for any G with no validation. This skips the isGlobalAddress and already-added checks that only the root-originated addGlobalToken flow performs.

        Exploit scenario

        1. The attacker force-sends a small amount of ETH to CoreBranchRouter (for example via selfdestruct), enough to exceed MIN_FALLBACK_OVERHEAD and cover root execution gas. 2. The attacker calls CoreBranchRouter.anyExecuteNoSettlement(abi.encode(bytes1(0x01), G, "x", "x", uint128(gas))). G is an existing global token, e.g. hUSDC, that already has local token L and underlying USDC on this branch. 3. The router creates a fresh hToken L' and the core bridge agent sends 0x00|nonce|0x03|abi.encode(G, L') to the root. The root trusts the message because it comes from the core branch agent, and sets getLocalAddressFromGlobal[branch][G] = L'. 4. Root settlements of G to this branch now resolve to L', which has no underlying mapping. Any settlement with deposit > 0 reverts with UnrecognizedUnderlyingAddress, so users can no longer withdraw USDC from that branch port, and hToken settlements mint L' instead of L. The attacker can repeat this after any admin repair.

        Recommendation

        Add the requiresBridgeAgent modifier to CoreBranchRouter.anyExecuteNoSettlement. On the root, make _setLocalToken check that the global token is registered and does not already have a local token on that chain (or only accept 0x03 as a reply to a pending addGlobalToken request).

      • The protocol fee from pools will be claimed to zero address maia-9 · 4 writeups High

        V12

        Factory omits security-critical ownership bootstrap

        src/2-audit/ulysses-amm/factories/UlyssesFactory.sol:38 Predicted severity: Informational

        Root cause

        The factory delegates owner bootstrap entirely to an unavailable Ownable dependency and supplies no explicit initialization, even though its owner is security-critical to every registered pool's fee handling.

        Impact

        If the linked Ownable implementation leaves ownership unset until _initializeOwner and requires an existing owner for recovery, registered pools cannot change protocol fees and fee claims target the zero address, causing failed collection or irrecoverable transfers depending on the asset. The exact missing fact is the linked Solady version's bootstrap and ownership-recovery behavior; searches of lib/solady, repository-wide Ownable filenames and initialization references, remappings, submodule declarations, and package metadata did not recover that implementation or a version pin.

        Description

        UlyssesFactory inherits Solady Ownable but has no constructor or initializer that establishes the factory owner. By contrast, the pool constructor explicitly calls _initializeOwner(_owner) for the separate pool authority. Every registered pool stores this factory and subsequently uses factory.owner() both as its protocol-fee administrator and as the recipient of claimed fees. The configured Solady dependency directory is empty, so the actual inherited constructor, ownership-transfer restrictions, and recovery APIs cannot be verified in this workspace. The source-backed omission therefore warrants an unresolved ownership-lifecycle candidate, rather than an unconditional claim that ownership or fees are permanently lost.

        Devin Security (Deep)

        UlyssesFactory never initializes its Ownable owner, so every pool's protocol fees are sent to the zero address and setProtocolFee can never be called

        src/2-audit/ulysses-amm/factories/UlyssesFactory.sol:38 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Every pool created by the factory sends its protocol fees to the zero address and nobody can ever change the protocol fee, because the factory's owner is permanently unset.

        ##### What's wrong

        This is an uninitialized owner. UlyssesFactory inherits Solady's Ownable but has no constructor and never calls _initializeOwner, so factory.owner() returns address(0) forever. Solady's Ownable has no public initializer, and transferOwnership and completeOwnershipHandover are owner-only, so the state cannot be repaired after deployment. UlyssesPool uses factory.owner() as the fee recipient and as the authority for setProtocolFee.

        ##### Who can do it

        Acme deploys UlyssesFactory and creates pools through it. Alice, the pool owner at Acme, calls claimProtocolFees() after a month of swaps. The pool transfers the accumulated fees to address(0). If the underlying token rejects transfers to the zero address, the call reverts instead and the fees stay stuck in the pool, excluded from totalAssets so no LP can ever withdraw them. Alice later tries setProtocolFee and gets Unauthorized because only address(0) may call it.

        - The factory is deployed as written, with no owner initialization.

        - Any pool created through _createPool.

        ##### What they get

        No attacker is needed. Acme loses 100% of protocol fee revenue from every pool, either burned to the zero address or frozen in the pool forever, and cannot adjust the protocol fee on any pool. The damage covers every pool the factory creates; user deposits are not at risk.

        ##### How it works

        1. UlyssesFactory at UlyssesFactory.sol:38 inherits Ownable but has no constructor, so _initializeOwner is never called and owner() reads an empty slot.

        2. _createPool at UlyssesFactory.sol:70 passes address(this) as the pool's factory.

        3. UlyssesPool.claimProtocolFees at UlyssesPool.sol:152 transfers the fees to factory.owner(), which is address(0).

        4. UlyssesPool.setProtocolFee at UlyssesPool.sol:322 requires msg.sender == factory.owner(), which no account can satisfy.

        Exploit scenario

        Not specified.

        Recommendation

        Add a constructor to UlyssesFactory that calls _initializeOwner(_owner) with a non-zero address, and have UlyssesPool.claimProtocolFees revert if the recipient is address(0). Verify with a test that deploys the factory, asserts factory.owner() != address(0), and checks that claimProtocolFees moves fees to that owner.

        Claude Security (Sonnet 5.5)

        UlyssesFactory never initializes its Ownable owner, so factory.owner() is address(0) forever

        src/2-audit/ulysses-amm/factories/UlyssesFactory.sol:38 Predicted severity: Medium

        Root cause

        Vulnerable symbol: UlyssesFactory

        Preconditions: The factory is deployed as written, with no constructor or initializer that calls _initializeOwner; Solady Ownable does not auto-initialize the owner (as documented upstream)

        Offending code:

        contract UlyssesFactory is Ownable, IUlyssesFactory {

        Impact

        The protocol-level admin role is permanently unreachable. Protocol fees accrued in every pool (the swapIn base fee plus any surplus over bandwidth) can never reach a real recipient: they are burned or stuck. The protocol fee parameter cannot be adjusted. LP principal is not directly affected.

        Description

        UlyssesFactory inherits Solady Ownable, which does not auto-set the owner and requires an explicit _initializeOwner call. The factory has no constructor and no other path that calls it (the other Ownable contracts in the repo all call _initializeOwner). The owner is therefore address(0), and nobody can pass onlyOwner, including transferOwnership. The pools use factory.owner() as the sole protocol authority and as the fee recipient. I could not read lib/solady (submodule empty) and relied on its documented behavior.

        Exploit scenario

        1) The factory is deployed and no owner is ever set. 2) Any call to UlyssesPool.setProtocolFee fails the check msg.sender != factory.owner(), because msg.sender can never be address(0). The protocol fee stays at the 1e14 default and the 1% cap can never be used. 3) When a pool owner calls claimProtocolFees, asset.safeTransfer(factory.owner(), claimed) sends the accrued protocol fees to address(0). That burns them for solmate-style tokens and reverts, leaving the fees locked, for OpenZeppelin-style tokens. 4) Ownership cannot be recovered, because transferOwnership and completeOwnershipHandover are onlyOwner and the owner is zero.

        Recommendation

        Add a constructor, for example constructor(address _owner) { _initializeOwner(_owner); }, and reject address(0). Also guard claimProtocolFees against a zero recipient.

        Claude Security (Opus 5.5)

        UlyssesFactory never sets its owner, so protocol fees go to address(0) and the factory-owner-only setProtocolFee can never be called

        src/2-audit/ulysses-amm/UlyssesPool.sol:152 Predicted severity: Medium

        Root cause

        Vulnerable symbol: claimProtocolFees

        Preconditions: Pools are deployed through UlyssesFactory (the only supported path); At least one swap has accrued protocol fees; The pool owner, an arbitrary address chosen in createPool, calls claimProtocolFees

        Offending code:

        asset.safeTransfer(factory.owner(), claimed);

        Impact

        All protocol fee revenue from every pool the factory creates is lost (burned to address(0)) or permanently stuck. The protocol-fee admin function cannot be used by anyone. LP principal is not directly affected.

        Description

        UlyssesFactory inherits Solady Ownable but has no constructor and never calls _initializeOwner, so factory.owner() is always address(0). claimProtocolFees uses that address as the protocol-fee recipient, and setProtocolFee uses it as its only authorization check, so the protocol-admin role belongs to nobody.

        Exploit scenario

        Anyone calls UlyssesFactory.createPool(asset, attacker) and becomes owner of a production pool. Users swap through it and pay protocolFee, which builds up as balance above bandwidths plus the rebalancing reserve (getProtocolFees). The pool owner, who need not be the protocol, calls claimProtocolFees(). The pool sends all accrued protocol fees to address(0). For tokens that allow transfers to zero (solmate-style), the fees are burned. For tokens that reject them (OpenZeppelin-style), the call reverts and the fees stay locked in the pool forever. Meanwhile setProtocolFee always reverts for every caller, because msg.sender can never equal address(0), so the protocol cannot change or turn off the 0.01% swap fee on any pool.

        Recommendation

        Add a constructor to UlyssesFactory that takes the owner address, requires it to be non-zero, and calls _initializeOwner(_owner). In claimProtocolFees, also revert when factory.owner() == address(0) as a defensive check.

      • Unlimited cross-chain asset transfer without deposit requirement maia-10 · 7 writeups High

        V12

        Successful settlement retries remain endlessly replayable

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:215 Predicted severity: Critical

        Root cause

        The retry status transition is applied to a memory copy rather than getSettlement[_settlementNonce].status. Destination settlement execution is also non-idempotent, turning the persistent Pending state into repeated payouts.

        Impact

        After inducing or encountering one fallback on a root-to-branch settlement, a user can repeatedly release the same underlying or hToken amount from branch custody. Repetition can drain shared port balances beyond the single root-side debit.

        Description

        _clearSettlement loads a pending settlement into memory and sets only the memory copy's status to Success. It writes the modified call data back but never persists the status transition, so the stored settlement remains Pending after a successful retry. Any caller can invoke clearSettlement again with more gas and retransmit the same settlement; the destination branch has no settlement-consumption check and releases the encoded assets each time. The original root-side transfer/burn is not repeated during retries, so every extra destination payout is unbacked. This path does not depend on external transport accidentally replaying a message because the public retry entrypoint deliberately sends it again.

        Pashov (Claude Opus 5.5 high)

        RootBridgeAgent._clearSettlement updates only a memory copy of the status, so settlements can be retried and paid out indefinitely

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:601 Predicted severity: High

        Root cause

        State change applied to a memory struct instead of storage. anyFallback reopens settlements without checking that they exist or belong to the message.

        Impact

        Settled hTokens and underlying are released multiple times on the destination branch. Branch ports can be drained and unbacked hTokens minted.

        Description

        _clearSettlement loads the settlement into memory, requires status == Pending, and sets settlement.status = Success on that memory copy only. Only callData is written back to storage, so the stored status stays Pending and the settlement can be re-sent again and again. anyFallback also reopens settlementNonce for flag 0x00 callOut messages, which never created a settlement. A callOut fallback can therefore reopen someone else's settlement (the one later created with that nonce). The branch side keeps no execution history, so each retried message clears the tokens again.

        Exploit scenario

        The attacker gets one settlement into Pending, either by making its first branch execution fail or by having a flag-0x00 callOut fall back onto a nonce that is later used by a real settlement. They then call BranchBridgeAgent.retrySettlement(nonce) (flag 0x07) or RootBridgeAgent.clearSettlement repeatedly. Each call re-sends the same settlement payload, and the branch agent mints/withdraws the settlement amount to the recipient each time.

        Recommendation

        Write the status to storage (getSettlement[nonce].status = Success). Only reopen settlements that exist and match the failed message. Add execution-nonce replay protection on the branch agent.

        Pashov (Codex GPT-6 Sol high)

        Root settlement clearing never persists Success status

        audit/src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:601 Predicted severity: Critical

        Root cause

        The status assignment targets memory, and only callData is written to storage.

        Impact

        Anyone can resend the same settlement and repeat token releases.

        Description

        _clearSettlement updates a memory copy of Settlement while persistent status stays Pending.

        Exploit scenario

        After a settlement is reopened, repeatedly call permissionless clearSettlement with execution gas.

        Recommendation

        Write Success to the storage settlement before external calls and enforce destination replay protection.

        Devin Security

        Settlement retry never marks the settlement done, so anyone can replay a payout

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:601 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can get a settlement reopened and then retry it as many times as they like, and each retry pays the recipient's tokens out of the branch port again.

        ##### What's wrong

        This is a replay bug caused by a lost state update. _clearSettlement loads the settlement into a memory copy and sets status = Success on that copy. Only callData is written back to storage. The stored status stays Pending, so the same settlement passes the Pending check every time. Nothing checks that the caller owns the settlement. The branch agent also keeps no record of which settlement nonces it already executed.

        A settlement can also reach Pending without failing itself. callOut sends the current settlementNonce but does not create or increment a settlement. When that message falls back, anyFallback reopens whatever settlement later took that nonce.

        ##### Who can do it

        Mallory has a normal wallet on a branch chain. She calls the public CoreBranchRouter.addGlobalToken. The root sends back a callOut message with the current settlement nonce N. That message reverts on the branch because the branch core router holds no ETH for performSystemCallOut. Before the fallback arrives, Mallory takes settlement N herself with a normal bridge-out to her own address. The fallback then reopens N. Mallory then calls BranchBridgeAgent.retrySettlement(N) over and over, paying only a little gas each time. Any settlement that fails on its own also works, including one that belongs to another user.

        - Mallory needs only a normal wallet and small gas payments.

        - A settlement must be in Pending. She can force this as described above, or she can use any settlement that failed.

        ##### What they get

        Each retry sends the settlement message again. The branch agent mints the hTokens again and withdraws the underlying tokens again from the branch port to the recipient. When Mallory is the recipient, she can drain the port's locked tokens, which belong to every user of that chain.

        ##### How it works

        1. callOut encodes settlementNonce without creating a settlement (RootBridgeAgent.sol:231-237).

        2. On fallback, anyFallback reopens the settlement at that nonce, even when a later settlement took it (RootBridgeAgent.sol:1074-1076, 638-641).

        3. The branch retrySettlement call, which anyone can make, sends flag 0x07, and the root agent calls _clearSettlement (BranchBridgeAgent.sol:228-234, RootBridgeAgent.sol:1020-1021).

        4. _clearSettlement sets Success only on the memory copy and stores just callData, so the stored status stays Pending (RootBridgeAgent.sol:603-627).

        5. The branch agent executes flag 0x01 with no replay check and pays out again through _clearToken (BranchBridgeAgent.sol:712-731).

        Exploit scenario

        Not specified.

        Recommendation

        Write the status to storage (getSettlement[_settlementNonce].status = SettlementStatus.Success) before you resend. Require that the caller, or the branch-signed sender, is the settlement owner. Do not reopen settlements for flag 0x00 messages, which never create a settlement. Add an executionHistory[nonce] check on the branch anyExecute. Add a test that retries one pending settlement twice and checks that the second retry reverts.

        Devin Security (Deep)

        Settlement retry never stores the Success status, so a failed settlement can be replayed and paid out repeatedly

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:601 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can resend a failed settlement over and over because the retry code never marks it as done, so the destination branch port pays the same tokens out again on every retry until it is empty.

        ##### What's wrong

        This is a missing state update that enables a replay. _clearSettlement loads the settlement into memory, sets the status to Success on the memory copy, and writes back only the callData field. The stored status stays Pending, so the same settlement passes the Pending check forever. The branch side keeps no record of executed settlement nonces, so each resend pays out again.

        ##### Who can do it

        Alice and other users hold USDC in the Fantom branch port. Mallory, an attacker with a wallet and some capital, creates a settlement to Fantom that fails there, for example a withdrawal a little larger than what the port holds while a port strategy has borrowed part of the reserves, or by first inflating the recorded per-chain balance with one of the accounting bugs reported separately. The anycall fallback reopens her settlement as Pending on the root. Mallory then calls clearSettlement on the root bridge agent in a loop; once the Fantom port has enough balance again, every call sends the same payout to her.

        - A settlement with status Pending where Mallory is the recipient. Any settlement becomes Pending when its branch-side execution fails.

        - clearSettlement is callable by anyone with any nonce and has no ownership check or reentrancy lock.

        - The retry works whenever the root bridge agent's initialGas is non-zero. anyFallback sets it and never clears it, so it is non-zero right after the failure that reopened the settlement.

        - The root bridge agent must hold a little wrapped native token to pay for the gas swap; it keeps the excess from every user's fees, so this is normally true.

        ##### What they get

        Mallory receives the settlement amount on every retry. She drains the destination branch port of the settled token, taking all other users' deposits on that chain, and can do the same on every branch chain she targets.

        ##### How it works

        1. A settlement to a branch fails and anycall calls anyFallback on the root; _reopenSettlemment sets the stored status to Pending and initialGas is left non-zero (RootBridgeAgent.sol:1063-1065, 1078-1079, 638-641).

        2. Mallory calls clearSettlement(nonce, 0) (RootBridgeAgent.sol:215-224); because initialGas is non-zero the stale fee info is reused and _manageGasOut swaps the agent's own wrapped native token for destination gas (RootBridgeAgent.sol:745-758).

        3. _clearSettlement reads the settlement into memory, checks Pending, flips only the memory copy to Success, and writes back only callData (RootBridgeAgent.sol:601-631).

        4. _performCall resends the original settlement payload to the branch (RootBridgeAgent.sol:765-775).

        5. The branch bridge agent executes flag 0x01 and _clearToken mints hTokens and withdraws underlying tokens to the recipient with no replay protection (BranchBridgeAgent.sol:744-761, 555-565).

        6. Mallory repeats step 2. The stored status is still Pending, so every call pays out again.

        Exploit scenario

        Not specified.

        Recommendation

        Persist the status before resending: write getSettlement[_settlementNonce].status = SettlementStatus.Success (or operate on a storage reference) in _clearSettlement. Restrict clearSettlement to the settlement owner and add the lock modifier. On the branch, record executed settlement nonces and reject duplicates. Reset initialGas to zero at the end of anyFallback. Verify by reopening a settlement in a test, calling clearSettlement twice, and asserting the second call reverts and the branch port balance changed only once.

        Claude Security (Sonnet 5.5)

        Settlement 'Success' status is written only to a memory copy, so a Pending settlement can be retried and paid out repeatedly

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:609 Predicted severity: High

        Root cause

        Vulnerable symbol: _clearSettlement

        Preconditions: A settlement must have been reopened as Pending by a branch-side fallback.

        Offending code:

        settlement.status = SettlementStatus.Success;

        Impact

        Repeated payout of a single settlement drains the destination BranchPort, which is theft of other users' funds. It is limited by the need for a settlement to reach Pending and for the recipient to benefit.

        Description

        _clearSettlement copies the settlement into memory and sets status = Success there. Only callData is written back to storage, so getSettlement[n].status stays Pending after a successful retry. The only gate (require status == Pending) therefore never closes. Because clearSettlement is public, each repeat re-sends the same clearTokens message to the branch, which re-releases the settled assets from the Port. Also CWE-837: settlement is a memory copy of the storage entry; only callData is written back (line 627), so storage status stays Pending after a retry. clearSettlement (public, no owner check) and flag 0x07 can then re-send the same settlement message any number of times; the branch agent has no per-settlement replay protection and delivers tokens each time.

        Exploit scenario

        A bridge-out settlement to chain X fails at the branch (for example the Port's real balance is below the root-tracked amount) and anyFallback reopens it as Pending. The recipient, or anyone acting for them, calls clearSettlement(nonce, gas) once the branch can execute. The branch pays the recipient. Status is still Pending, so they call clearSettlement again and again, and each execution withdraws or mints the same amount on the branch while the root burned or escrowed it only once.

        Recommendation

        Write the new status to storage before the external call (getSettlement[_settlementNonce].status = SettlementStatus.Success), or take a storage reference instead of a memory copy. Also CWE-837: Use a storage pointer or write the whole struct back after setting status to Success (before the external call), and add an owner/recipient check plus a settlement-executed guard on the branch side.

        Claude Security (Opus 5.5)

        Settlement status is set on a memory copy and never saved, so a reopened settlement can be replayed without limit

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:609 Predicted severity: High

        Root cause

        Vulnerable symbol: _clearSettlement

        Preconditions: A settlement reaches Pending status through anyFallback; A working retry path: same-chain destination, or the gas-swap conversion bugs fixed for remote chains

        Offending code:

        settlement.status = SettlementStatus.Success;

        Impact

        An attacker can release the same settlement many times and drain the underlying tokens held in branch ports, and over-mint branch hTokens.

        Description

        _clearSettlement copies the stored Settlement into memory, sets status = Success on that copy, and writes back only callData. The stored status stays Pending. Anyone can call clearSettlement (no owner check) and resend the same settlement callData to the branch over and over.

        Exploit scenario

        1) The attacker gets a settlement into Pending. Either one of their own root-to-branch settlements fails on the branch (for example the branch port lacks the underlying for withdraw) and anyFallback reopens it, or a callOut fails and its fallback reopens the current settlementNonce after the attacker has created a settlement at that nonce. 2) The attacker calls clearSettlement(nonce, >50000) again and again. For a local-chain (Arbitrum) destination, _manageGasOut returns 0 and _performCall runs ArbitrumBranchBridgeAgent.anyExecute synchronously. For remote chains, the retry runs from inside an anyExecute multicall. 3) Each call resends the original flag-0x01/0x02 payload, and the branch runs _clearToken again, minting hTokens or withdrawing underlying to the recipient every time.

        Recommendation

        Update status through a storage reference (Settlement storage s = getSettlement[nonce]; s.status = SettlementStatus.Success;) before making the external call. Restrict retries to the settlement owner. Make callOut either create a settlement or carry no settlement nonce, so a fallback cannot reopen an unrelated settlement.

      • ChainId type confusion maia-11 · 1 writeup High

        V12

        Outbound root domains exceed supported identity width

        src/2-audit/ulysses-omnichain/factories/BranchBridgeAgentFactory.sol:41 Predicted severity: Informational

        Root cause

        The standard factory admits a root-domain width that the repository's root implementations cannot instantiate and does not validate representability before agents use that domain for message dispatch.

        Impact

        Inference: an accepted request with an unrepresentable root domain could leave deposited assets awaiting execution or fallback on the wrong destination, whereas synchronous rejection rolls the source transaction back. The exact missing fact is Anycall's behavior for such destination IDs and its fallback delivery semantics; the searched boundary includes both factories, both agent constructors, outbound routing/fee consumers, and every repository Anycall source, which contains no proxy implementation.

        Description

        The standard branch factory accepts a uint256 rootChainId although the root factory and root bridge agent construct their root-chain identity from uint24 values. Values above type(uint24).max are stored without validation and forwarded unchanged into standard branch agents. Those agents use the full value as the Anycall destination domain and as the fee-calculation domain, while the corresponding root implementation cannot represent that same root identity. Unlike localChainId, which is only stored/exposed by the standard agent, this configuration reaches a messaging sink after custody and gas deposits are recorded. Whether the messaging dependency rejects the request synchronously or accepts an undeliverable/wrong-domain request is not established by its interface.

      • Incorrect accounting of total and strategies debt maia-12 · 8 writeups Medium

        V12

        Reserve repayment debits the wrong strategy

        src/2-audit/ulysses-omnichain/BranchPort.sol:139 Predicted severity: High

        Root cause

        replenishReserves mixes the authenticated target _strategy with msg.sender when updating per-strategy debt. The storage key differs from the strategy whose assets were requested.

        Impact

        Permissionless positive reserve replenishment by a debt-free keeper cannot succeed, preventing that recovery path from returning managed assets when reserves are short. A debt-bearing caller can also misattribute repayment across strategies, corrupting per-strategy debt without demonstrating a direct drain in the available strategy implementations.

        Description

        BranchPort.replenishReserves takes a target _strategy and authorizes that strategy-token pair, but later debits getPortStrategyTokenDebt[msg.sender][_token]. manage records borrowing under the managing strategy's own address, so an ordinary keeper has no debt to debit. A keeper's positive repayment therefore underflows after the strategy withdrawal and reverts the entire operation, including the returned reserves. If the caller is another strategy with its own outstanding debt, the call instead reduces that caller's debt while requesting funds from the target strategy. No caller-to-target equality requirement or target-keyed debit reconciles these paths.

        Codex Security (GPT-6 Sol)

        A port strategy can erase debt without repaying reserves

        src/2-audit/ulysses-omnichain/BranchPort.sol:139 Predicted severity: Medium

        Root cause

        replenishReserves couples a capped withdrawal request with an uncapped debt reduction. The debt ledger no longer tracks assets retained by the strategy.

        Impact

        A whitelisted but compromised strategy can hide outstanding borrowing and repeatedly draw excess reserves; the attack requires a preapproved strategy.

        Description

        The branch port requests at most the current reserve shortfall from a strategy but subtracts the strategy's full requested amount from its debt, even when zero assets return.

        Exploit scenario

        manage transfer and debt -> capped zero repayment -> full debt reduction

        Recommendation

        Measure the port's received token balance and reduce the indebted strategy's debt only by that amount; bind the ledger update to _strategy.

        Pashov (Claude Opus 5.5 high)

        BranchPort.replenishReserves is permissionless and debits the caller's debt by the requested amount, not the amount actually withdrawn

        src/2-audit/ulysses-omnichain/BranchPort.sol:153 Predicted severity: Medium

        Root cause

        Uses msg.sender instead of _strategy for per-strategy debt and accounts the requested amount rather than the amount withdrawn.

        Impact

        Debt accounting diverges from reality. A strategy can call with a large _amount while only a small amount (or nothing) is returned, erasing its recorded debt and the global debt. Funds lent to strategies then become unrecoverable, and reserve-ratio calculations (_minimumReserves uses getStrategyTokenDebt) are understated, letting strategies take more than allowed. Third-party callers have their own (zero) debt underflow, which blocks legitimate replenishment by keepers.

        Description

        replenishReserves pulls min(_amount, reservesLacking) from the strategy. It then subtracts the full _amount from getPortStrategyTokenDebt[msg.sender][_token] (the caller, not _strategy) and from getStrategyTokenDebt[_token].

        Exploit scenario

        A strategy with 1,000 debt calls replenishReserves(self, token, 1,000) when reservesLacking is 0. Nothing is withdrawn, but getPortStrategyTokenDebt[strategy] and getStrategyTokenDebt drop to 0. The strategy keeps the 1,000 tokens and can call manage again.

        Recommendation

        Compute amount = min(_amount, reservesLacking), withdraw it, and decrease getPortStrategyTokenDebt[_strategy][_token] and getStrategyTokenDebt by amount.

        Pashov (Codex GPT-6 Sol high)

        Reserve replenishment can erase debt without repayment

        audit/src/2-audit/ulysses-omnichain/BranchPort.sol:153 Predicted severity: High

        Root cause

        Debt lookup and decrement do not use the same strategy/actual amount as the withdrawal.

        Impact

        Strategy debt and reserve constraints can be bypassed, enabling repeated borrowing without repayment; third-party replenishment also fails when the caller has no debt.

        Description

        replenishReserves requests only min(_amount,reservesLacking) from the selected strategy, but subtracts full _amount from both total debt and the debt keyed by msg.sender. If reservesLacking is zero, no assets are returned but debt can be fully erased by a debtor strategy.

        Exploit scenario

        An approved strategy borrows 70 from a 100-token port with 30-token minimum reserve. It calls replenishReserves(self,token,70) while reservesLacking is zero; withdraw receives 0 but recorded debt falls by 70.

        Recommendation

        Debit the selected strategy by the actual amount received.

        Devin Security

        replenishReserves clears more strategy debt than it withdraws

        src/2-audit/ulysses-omnichain/BranchPort.sol:153 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        An approved port strategy can erase its debt while keeping most of the borrowed tokens, which lowers the port's reserves.

        ##### What's wrong

        This is an accounting bug. replenishReserves withdraws only min(_amount, reservesLacking) from the strategy. It then subtracts the full _amount from the debt. It also subtracts from getPortStrategyTokenDebt[msg.sender] instead of _strategy.

        ##### Who can do it

        A port strategy that the owner approved, and that holds debt, calls replenishReserves(self, token, fullDebt) when the port lacks few reserves. Outside callers have no debt, so their calls underflow and revert.

        - The caller must be an approved strategy with outstanding debt.

        ##### What they get

        The strategy keeps tokens that the port no longer counts as owed. That reduces the backing for users' deposits.

        ##### How it works

        1. replenishReserves withdraws the smaller of _amount and reservesLacking (BranchPort.sol:159).

        2. It subtracts the full _amount from the caller's debt and the total debt (BranchPort.sol:161-162).

        Exploit scenario

        Not specified.

        Recommendation

        Compute amountToWithdraw = min(_amount, reservesLacking). Withdraw that amount, and subtract it from getPortStrategyTokenDebt[_strategy][_token] and getStrategyTokenDebt[_token]. Add a test that the debt drops by exactly the amount the port received.

        Devin Security (Deep)

        replenishReserves lowers a strategy's recorded debt by more than it actually returns

        src/2-audit/ulysses-omnichain/BranchPort.sol:153 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        An approved Port Strategy can erase its recorded debt without returning the tokens, which lets it later borrow more of users' deposits than the reserve limits allow.

        ##### What's wrong

        Inconsistent accounting. replenishReserves pulls back only min(_amount, reservesLacking) from the strategy but subtracts the full _amount from both debt counters, and it debits getPortStrategyTokenDebt[msg.sender] instead of [_strategy].

        ##### Who can do it

        Alice's USDC sits in the Avalanche Branch Port. Sam runs a Port Strategy that the owner approved for USDC with a daily limit. After borrowing through manage, Sam's strategy calls replenishReserves(strategy, USDC, fullDebt) at a moment when the Port's reserves are not lacking. The Port withdraws 0 tokens but records the debt as repaid.

        - Caller is an owner-approved Port Strategy, so only an insider or a compromised strategy.

        - _reservesLacking(token) is smaller than _amount at the time of the call.

        ##### What they get

        The strategy keeps the borrowed USDC while the Port believes it was repaid. Because minimum reserves are computed from balance + debt, the lower debt lowers the reserve floor and lets the strategy call manage again for more. A compromised strategy can repeatedly take users' deposits beyond the intended limits. Only tokens whitelisted for that strategy are at risk.

        ##### How it works

        1. The strategy calls replenishReserves(_strategy, _token, _amount) (BranchPort.sol:153).

        2. The Port withdraws only _amount < reservesLacking ? _amount : reservesLacking from the strategy (BranchPort.sol:157-159).

        3. It then subtracts the full _amount from getPortStrategyTokenDebt[msg.sender] and getStrategyTokenDebt[_token] (BranchPort.sol:161-162).

        4. _minimumReserves uses the reduced debt (BranchPort.sol:130-132), so manage allows a larger withdrawal next time (BranchPort.sol:139-150).

        Exploit scenario

        Not specified.

        Recommendation

        Compute the actual amount withdrawn once, reduce both debt mappings by exactly that amount, and index the per-strategy mapping by _strategy. Test: borrow via manage, call replenishReserves while reserves are not lacking, and assert the debt is unchanged.

        Claude Security (Opus 5.5)

        replenishReserves pulls funds from the caller-chosen _strategy but reduces the caller's debt, by the full requested amount

        src/2-audit/ulysses-omnichain/BranchPort.sol:161 Predicted severity: Low

        Root cause

        Vulnerable symbol: replenishReserves

        Preconditions: The caller is an owner-whitelisted port strategy with outstanding debt

        Offending code:

        getPortStrategyTokenDebt[msg.sender][_token] -= _amount;

        Impact

        A registered strategy can keep port funds with its debt erased, or shift its debt onto another strategy. This corrupts strategy accounting and the minimum-reserve calculation that protects users.

        Description

        The function pulls funds from any whitelisted _strategy the caller names. It then reduces the debt of msg.sender rather than _strategy, and by the full _amount even though only min(_amount, reservesLacking) was withdrawn. Nothing requires msg.sender == _strategy. A registered strategy with debt can make another strategy repay for it, or erase its own debt without repaying anything when reserves are not lacking.

        Exploit scenario

        Strategy A has borrowed X through manage(). When reserves are lacking, A calls replenishReserves(B, token, X). Strategy B returns the funds to the port while B's recorded debt stays the same, and A's debt is cleared. When reserves are not lacking, A calls replenishReserves(A, token, X). Nothing is withdrawn, but A's debt and the global debt drop by X, which also lowers _minimumReserves and lets more be pulled out through manage().

        Recommendation

        Reduce getPortStrategyTokenDebt[_strategy][_token] (not msg.sender's) by the amount actually withdrawn, and reduce getStrategyTokenDebt by the same amount.

        Vercel Security Review

        Strategy repayment erases unpaid debt and weakens the reserve floor

        src/2-audit/ulysses-omnichain/BranchPort.sol:159 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. An approved strategy borrows against tracked debt** - src/2-audit/ulysses-omnichain/BranchPort.sol:144-147

        ```solidity title="src/2-audit/ulysses-omnichain/BranchPort.sol:144-147"

        getStrategyTokenDebt[_token] += _amount;

        getPortStrategyTokenDebt[msg.sender][_token] += _amount;

        _token.safeTransfer(msg.sender, _amount);

        ```

        **2. Repayment deducts more debt than it retrieves** - src/2-audit/ulysses-omnichain/BranchPort.sol:159-162

        ```solidity title="src/2-audit/ulysses-omnichain/BranchPort.sol:159-162"

        IPortStrategy(_strategy).withdraw(address(this), _token, _amount < reservesLacking ? _amount : reservesLacking);

        getPortStrategyTokenDebt[msg.sender][_token] -= _amount;

        getStrategyTokenDebt[_token] -= _amount;

        ```

        In this new function, a borrowing strategy can select itself and its full debt while reserves lack nothing: zero tokens return, but the debt disappears.

        **3. The reserve requirement falls with fictitious repayment** - src/2-audit/ulysses-omnichain/BranchPort.sol:130-132

        ```solidity title="src/2-audit/ulysses-omnichain/BranchPort.sol:130-132"

        function _minimumReserves(uint256 _currBalance, address _token) internal view returns (uint256) {

        return ((_currBalance + getStrategyTokenDebt[_token]) * getMinimumTokenReserveRatio[_token]) / DIVISIONER;

        }

        ```

        An abusive approved strategy can borrow the newly exposed reserves across daily-limit resets, retaining unpaid assets and breaching the intended reserve floor.

        Exploit scenario

        Not specified.

        Recommendation

        Compute the repayment once and reduce both debt mappings by the actual tokens received, credited to _strategy rather than msg.sender. Bound repayment by that strategy's debt and protect the external withdrawal against reentrancy.

      • Bridging assets erroneously mints new assets maia-13 · 1 writeup Medium

        V12

        Local escrow delivery duplicates root token supply

        src/2-audit/ulysses-omnichain/RootBridgeAgent.sol:458 Predicted severity: High

        Root cause

        The Arbitrum local delivery/refund implementation copies a remote mint-on-delivery behavior despite the local producer escrowed the same root token rather than burning a separate branch representation. Existing-token settlement should release the escrowed units instead of minting root supply again.

        Impact

        This duplicates root hToken supply and overstates local underlying attribution whenever an escrowed existing-token portion is delivered or refunded locally. Inference from withdrawFromPort: the new local counter and fungible claims can authorize withdrawals from local underlying custody that the escrow-only operation never replenished, conditional on owner admission and available reserves.

        Description

        Root outbound settlement transfers the existing-token portion into RootPort custody and burns only the requested underlying portion. On the same-chain destination, _clearToken routes the existing-token portion through ArbitrumBranchPort.bridgeIn, which calls mintToLocalBranch rather than returning those escrowed root tokens. After the explicit owner workaround for the separate mint authorization failure, this creates additional root supply and increments the local chain counter without an underlying deposit. Failed local source deposits use the same minting path for refunds even though ArbitrumBranchPort.bridgeOutMultiple escrowed their existing root tokens instead of burning them. A pure-hToken settlement or refund therefore leaves the original units in RootPort while issuing new units to the recipient.

    • Metavest Solidity On-chain vesting + token-grant tooling. Tasks 12 V12 12/12 Codex Sec 6/12 Pashov Opus 11/12 Pashov GPT-6 11/12 Devin 8/12 Devin (Deep) 10/12 Claude Sec 9/12 Claude Opus 10/12 Vercel 8/12

      On-chain vesting + token-grant tooling.

      Read the audit report
      • Reward tokens corresponding to removed milestones are locked metavest-1 · 8 writeups Critical

        V12

        Milestone deletion strands funded awards

        src/MetaVesTController.sol:430 Predicted severity: Medium

        Root cause

        The controller treats milestone deletion as cancellation of a funded award, but the allocation implementation deletes the record without returning the backing tokens or retaining recoverable accounting.

        Impact

        Removing an unconfirmed milestone can strand its funded tokens in vesting allocations rather than returning them to authority as documented. The same lost-accounting problem affects restricted awards; options have a separate post-termination surplus-recovery path, so permanent inaccessibility is not asserted for options.

        Description

        removeMetavestMilestone resets consent and delegates deletion to the allocation, but performs no refund or accounting reconciliation for the funded award. The concrete removeMilestone implementation merely deletes the milestone entry. For an unconfirmed milestone, that removes the award from future confirmation and from the milestone sums used to calculate termination recovery. In a vesting allocation with no withdrawals, termination recovers the remaining stream and milestones but leaves the deleted award in the contract. The common allocation implementation has no token-sweep path to retrieve that residual.

        Codex Security (GPT-6 Sol)

        Removing a funded milestone permanently strands its award tokens

        src/BaseAllocation.sol:246 Predicted severity: Medium

        Root cause

        The controller funds a milestone award, but BaseAllocation.removeMilestone deletes its value without returning tokens or retaining recovery accounting. Later entitlement and vesting termination formulas use current milestone records, so the removed award is omitted.

        Impact

        The supported amendment can permanently lock valuable ERC20 balances, though it requires authority execution and grantee or set consent.

        Description

        An approved milestone removal deletes the award record without transferring or preserving its prefunded token amount, leaving those tokens inaccessible in vesting and restricted allocations.

        Exploit scenario

        Milestone funding → milestone delete → accounting omits award → inaccessible token balance

        Recommendation

        Before deletion, reject completed milestones and refund or record the uncompleted award in a recoverable balance used by termination.

        Pashov (Claude Opus 5.5 high)

        Removing a milestone permanently locks its tokens and corrupts termination accounting

        src/BaseAllocation.sol:243 Predicted severity: Medium

        Root cause

        Deletion without refunding the award or adjusting totals, and no check that the milestone is incomplete.

        Impact

        Milestone tokens are frozen forever in the allocation contract. Removing completed milestones can make terminate() or getAmountRepurchasable() revert, blocking termination and repurchase.

        Description

        removeMilestone just deletes the array element. The milestoneAward tokens transferred in for it are not returned, and every later accounting loop sums milestones[i].milestoneAward, which is now 0. No path returns them: terminate() recovers only total + current milestone awards - vested, and VestingAllocation/RTA have no sweep. Removing an already completed milestone is also allowed (despite the doc saying 'if not yet confirmed'). Its award stays in milestoneAwardTotal but is gone from milestonesAllocation, so terminate/getAmountRepurchasable can underflow and revert. The deleted slot also stays confirmable by anyone (no conditions).

        Exploit scenario

        Authority (with consent) removes an unconfirmed milestone worth 500 tokens. Later termination returns only the stream remainder, and the 500 tokens remain stuck in the VestingAllocation forever.

        Recommendation

        On removal of an incomplete milestone, transfer its award back to authority. Disallow removing completed milestones.

        Pashov (Codex GPT-6 Sol high)

        Removing an uncompleted milestone strands its funded award

        src/BaseAllocation.sol:240 Predicted severity: Medium

        Root cause

        The deletion loses the award amount used by subsequent termination accounting.

        Impact

        The removed award can remain permanently stranded in the allocation.

        Description

        removeMilestone deletes the record but does not return or track the tokens already funded for that award.

        Exploit scenario

        Fund a milestone, remove it before completion, then terminate the grant.

        Recommendation

        For an uncompleted milestone, return its award to the funder or track it for recovery; reject deletion after completion or reconcile all credited award totals.

        Devin Security (Deep)

        Tokens funding a removed milestone stay locked in the allocation with no way to recover them

        src/BaseAllocation.sol:240 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        When the authority removes an unconfirmed milestone, the tokens that funded it stay in the allocation contract where neither the grantee nor the authority can ever withdraw them.

        ##### What's wrong

        This is missing accounting on removal. The controller's docstring says removal makes the award withdrawable by the controller, but removeMilestone only zeroes the struct; no transfer happens, and terminate() only recovers tokenStreamTotal plus the awards still listed in milestones[].

        ##### Who can do it

        Acme Corp funds a 500 token milestone for Alice, an engineer, and later removes it with her consent. Nobody acts maliciously; the protocol simply loses track of the tokens.

        - A milestone removal executes before the milestone is confirmed.

        - The allocation is a VestingAllocation or RestrictedTokenAward (TokenOptionAllocation.recoverForfeitTokens would sweep the surplus after termination).

        ##### What they get

        No one gains. Acme loses the 500 tokens permanently; the amount locked equals the award of every removed milestone. As a side effect the stranded tokens partly mask the termination over-recovery bug reported in TokenOptionAllocation.sol, because the grantee's withdraw balance check keeps passing.

        ##### How it works

        1. The authority calls removeMetavestMilestone (MetaVesTController.sol:433-439); the docstring at line 430 promises the award becomes withdrawable by the controller.

        2. BaseAllocation.removeMilestone (BaseAllocation.sol:243-248) deletes the struct and emits an event; no tokens move.

        3. VestingAllocation.terminate (VestingAllocation.sol:82-88) sums only the milestones still present, so the removed award is never part of tokensToRecover, and withdraw (BaseAllocation.sol:273-279) is capped by getAmountWithdrawable, which never includes it.

        Exploit scenario

        Not specified.

        Recommendation

        When removing an unconfirmed milestone, transfer milestoneAward back to the authority in the same call (or track a recoverable amount and add an authority-only sweep). Verify with a test that adds then removes a milestone and asserts the authority's token balance is restored.

        Claude Security (Sonnet 5.5)

        removeMilestone zeroes the milestone but leaves its funded tokens stranded and breaks terminate/repurchase accounting

        src/BaseAllocation.sol:246 Predicted severity: Medium

        Root cause

        Vulnerable symbol: removeMilestone

        Preconditions: A funded milestone is removed through the controller

        Offending code:

        delete milestones[_milestoneIndex];

        Impact

        Permanent loss of the tokens funded for removed milestones in Vesting and RTA allocations, and possible bricking of terminate or repurchase for grants whose confirmed milestone was removed.

        Description

        The controller funds every milestone at creation (milestoneAward is part of _total) and documents that removing a milestone makes its tokens recoverable. The allocation only deletes the array entry. VestingAllocation.terminate and RestrictedTokenAward.getAmountRepurchasable sum milestones[i].milestoneAward, which now excludes the deleted award, so the funded tokens are not part of any recoverable amount. If the milestone was already confirmed, milestoneAwardTotal still includes the award while the sum does not, which skews or underflows the same expressions.

        Exploit scenario

        Authority and grantee agree to remove a 500-token milestone. After removeMetavestMilestone the 500 tokens stay in the VestingAllocation, and terminate() recovers only the remainder, so they are locked forever. If the removed milestone had been confirmed, terminate()/getAmountRepurchasable() can underflow and revert because vested includes an award that the sum no longer does.

        Recommendation

        Track funded and removed milestone awards explicitly (for example keep the award in a removedMilestoneTotal that terminate and repurchase include), refuse to remove completed milestones, and send the removed award back to the authority at removal time.

        Claude Security (Opus 5.5)

        Tokens for a removed milestone are permanently stuck, and the completed-milestone check exists on neither side

        src/BaseAllocation.sol:246 Predicted severity: Medium

        Root cause

        Vulnerable symbol: removeMilestone

        Preconditions: Authority removes a milestone via removeMetavestMilestone (consent-gated, documented feature)

        Offending code:

        delete milestones[_milestoneIndex];

        Impact

        The authority permanently loses every removed milestone award in Vesting and RestrictedToken allocations. Removing a completed milestone can permanently block termination and majority proposals for the set.

        Description

        The controller's removeMetavestMilestone says only unconfirmed milestones are removed and that their award becomes withdrawable by the controller. The controller never checks the milestone (its MilestoneIndexCompletedOrDoesNotExist error is unused), and BaseAllocation.removeMilestone only checks the index before zeroing the award. Neither layer returns the award tokens, and terminate() recomputes the amount to recover from the zeroed array, so those tokens never come out.

        Exploit scenario

        Authority funds a VestingAllocation with tokenStreamTotal 1000 and a milestone worth 500, all 1500 tokens transferred. With the grantee's consent it calls removeMetavestMilestone(grant, 0), expecting the 500 back as the docs promise. No function sends them back. A later terminate() recovers T + 0 - vested (+withdrawn), and the grantee can only withdraw vested tokens, so the 500 stay in the contract forever. VestingAllocation has no sweep, and RestrictedTokenAward only lets the authority 'repurchase' them by paying the grantee. If a completed milestone is removed instead, milestoneAwardTotal still counts it while the summed awards drop. terminate() then underflows and reverts once the stream is fully vested. getGoverningPower(all) also underflows after withdrawals, which blocks proposeMajorityMetavestAmendment for the whole set.

        Recommendation

        In removeMilestone, revert if milestone.complete is true. Transfer milestoneAward to getAuthority() (or the controller) before deleting it, or track removed awards so terminate() recovers them.

        Vercel Security Review

        Removing an uncompleted milestone strands its funded award

        src/BaseAllocation.sol:243 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Milestone awards are funded into the allocation** - src/MetaVesTController.sol:453-455

        ```solidity title="src/MetaVesTController.sol:453-455"

        // send the new milestoneAward to 'metavest'

        safeTransferFrom(_tokenContract, msg.sender, _grant, _milestone.milestoneAward);

        BaseAllocation(_grant).addMilestone(_milestone);

        ```

        **2. Consented removal deletes the liability without returning funds** - src/BaseAllocation.sol:243-246

        ```solidity title="src/BaseAllocation.sol:243-246"

        function removeMilestone(uint256 _milestoneIndex) external onlyController {

        if(terminated) revert MetaVesT_AlreadyTerminated();

        if (_milestoneIndex >= milestones.length) revert MetaVesT_ZeroAmount();

        delete milestones[_milestoneIndex];

        ```

        For an uncompleted milestone, its award never enters vested or unlocked totals, so the grantee cannot withdraw it.

        **3. Vesting termination also excludes the deleted award** - src/VestingAllocation.sol:83-86

        ```solidity title="src/VestingAllocation.sol:83-86"

        for (uint256 i; i < milestones.length; ++i) {

        milestonesAllocation += milestones[i].milestoneAward;

        }

        tokensToRecover = allocation.tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() + tokensWithdrawn;

        ```

        With no prior withdrawals, termination returns only the remaining recorded allocation. Cancelled milestone funding stays stranded; VestingAllocation has no surplus recovery entrypoint.

        Exploit scenario

        Not specified.

        Recommendation

        Before deleting an uncompleted milestone, preserve its award amount and safely return it to the authority or credit a separately tracked recoverable balance. Reject removal of completed milestones or explicitly reconcile their cumulative accounting. Ensure every funded token remains assigned to a payout or recovery liability.

      • Anyone can vote on any majority amendment proposal with arbitrary voting power metavest-2 · 9 writeups High

        V12

        Arbitrary contracts can fabricate majority votes

        src/MetaVesTController.sol:589 Predicted severity: Medium

        Root cause

        Voting authenticates ownership through caller-selected self-reported metadata but never authenticates the allocation's membership in the proposal's electorate. Arbitrary external voting weight is consequently trusted.

        Impact

        An external account can fabricate sufficient voting power to pass any pending set proposal without consent from the affected set members. Execution remains authority-only, but the authority's majority-consent restriction no longer protects grantees against economic changes such as freezes or option-price increases.

        Description

        voteOnMetavestAmendment accepts a caller-selected _grant and checks its self-reported grantee, but does not check membership in _setName or registration with this controller. It then adds that address's self-reported getGoverningPower() to the named proposal. An ordinary allocation outside the set can therefore vote in its election, and an external account can instead supply a purpose-built contract returning that account as grantee and a chosen voting weight. Duplicate prevention only limits each supplied address to one affirmative vote. consentCheck trusts the resulting accumulated weight when authorizing amendments to actual set members.

        Codex Security (GPT-6 Sol)

        A grantee outside a set can approve amendments for that set

        src/MetaVesTController.sol:591 Predicted severity: Medium

        Root cause

        The proposal denominator is computed from set members, but voteOnMetavestAmendment credits power from any grant address whose reported grantee is msg.sender. No set-membership or controller-provenance check binds that grant to the proposal.

        Impact

        An outside grantee can forge set majority, but execution still requires an authority call against a pending proposal and may be constrained by DAO conditions.

        Description

        An outsider can add their grant's governing power to another set's majority proposal, allowing an amendment without the affected set's majority.

        Exploit scenario

        Caller-selected outside _grant → getGoverningPower → currentVotingPower for named set → consentCheck

        Recommendation

        Require _grant to be a registered member of _setName and bind eligibility and voting power to the proposal snapshot.

        Pashov (Claude Opus 5.5 high)

        Majority amendment votes accept any metavest, not just members of the set

        src/MetaVesTController.sol:589 Predicted severity: High

        Root cause

        Missing membership check: the set membership of _grant is never validated.

        Impact

        The majority-consent protection for set members can be bypassed. Authority (the party the consent mechanism constrains) can create an allocation with itself or a sybil as grantee, or deploy any contract returning grantee()=attacker and a huge getGoverningPower(), and vote. This pushes currentVotingPower*2 past totalVotingPower and lets authority unilaterally change rates, prices, transferability, or milestones for every member of the set.

        Description

        voteOnMetavestAmendment only checks that msg.sender is the grantee of _grant. It never checks that _grant is in sets[_setName]. Any grantee of any allocation created by this controller (or by any contract exposing grantee()/getGoverningPower()) can add its governing power to another set's proposal. totalVotingPower is snapshotted from set members only.

        Exploit scenario

        Set 'employees' has total power 1,000,000. Authority deploys a fake contract whose grantee() returns authority and getGoverningPower() returns 1e30, then calls voteOnMetavestAmendment(fake, 'employees', updateMetavestVestingRate.selector, true). Next it calls updateMetavestVestingRate(member, 0) for each member, freezing everyone's vesting.

        Recommendation

        Require _grant to be in sets[_setName], and snapshot each voter's power at proposal time, or cap total votes at the snapshot.

        Pashov (Codex GPT-6 Sol high)

        Out-of-set grants can vote on majority amendments

        src/MetaVesTController.sol:589 Predicted severity: High

        Root cause

        No set-membership check precedes the vote accounting.

        Impact

        An outsider can fabricate approval for amendments to real grantees. A forged vote of 2**255 also makes the majority multiplication overflow and blocks the proposal from execution.

        Description

        Voting checks ownership of _grant but never its membership in _setName; its governing power is added to that set's proposal.

        Exploit scenario

        Deploy a fake grant that reports attacker ownership and 51 governing-power units, then vote on a real set with total power 100; no member needs to vote. A value of 2**255 instead causes execution to revert on overflow.

        Recommendation

        Verify _grant belongs to sets[_setName] before counting its vote.

        Devin Security

        Majority amendment votes accept any contract as a voter, so the authority can fake grantee consent

        src/MetaVesTController.sol:589 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        The authority, or anyone helping it, can manufacture a fake majority vote and then change vesting rates, unlock rates, prices, or milestones for every grantee in a set without their real consent.

        ##### What's wrong

        This is a broken consent check. voteOnMetavestAmendment trusts whatever address the caller passes as _grant. It only asks that contract who its grantee is and how much voting power it has. It never checks that _grant is a real MetaVesT made by this controller or that it belongs to the set being voted on.

        ##### Who can do it

        Alice is a grantee at Acme Corp. Her vesting contract sits in the set "engineering" with other grantees. Mallory controls the Acme authority address and wants to cut Alice's unlock rate to zero. Mallory proposes a majority amendment for the set. She then deploys a tiny contract whose grantee() returns her own address and whose getGoverningPower() returns a huge number. She calls voteOnMetavestAmendment with that contract as _grant. The vote passes, and she calls updateMetavestUnlockRate for Alice.

        - Mallory holds the authority role on the controller, which is needed to propose and to execute the amendment.

        - The target MetaVesT is in a set. The authority can put any MetaVesT into a set at any time with addMetaVestToSet, which needs no grantee consent.

        - Anyone can cast the fake vote. Only the final execution needs the authority.

        ##### What they get

        Mallory skips the grantee consent that the contract is built to require. She can freeze Alice's vested tokens forever by setting the unlock rate to zero. She can raise the exercise price on Alice's vested options or lower the repurchase price on her restricted tokens. She can remove milestones. Termination alone cannot do these things, because termination keeps the vested tokens for the grantee. The damage reaches every grantee whose MetaVesT is in, or is added to, a set on this controller.

        ##### How it works

        1. The authority calls proposeMajorityMetavestAmendment, which stores the total voting power of the real set members (MetaVesTController.sol:571-582).

        2. The attacker calls voteOnMetavestAmendment with a fake _grant. The only identity check is BaseAllocation(_grant).grantee() != msg.sender, which the fake contract passes (MetaVesTController.sol:591).

        3. The function adds the fake contract's self-reported getGoverningPower() to currentVotingPower without checking set membership (MetaVesTController.sol:595-606).

        4. The authority calls a consent-gated function. consentCheck sees currentVotingPower*2 >= totalVotingPower and lets the call through (MetaVesTController.sol:146).

        Exploit scenario

        Not specified.

        Recommendation

        In voteOnMetavestAmendment, require that _grant is listed in sets[_setName] and that the controller deployed it (for example, keep a isMetavest mapping that the create functions fill). Do not let a single vote come from an address outside the set. Consider snapshotting each member's power when the proposal is made. Add a test that votes with a mock contract outside the set and confirm the vote reverts and the amendment call still fails consentCheck.

        Devin Security (Deep)

        Majority amendment votes accept any caller-supplied grant contract, so anyone can pass a set-wide proposal

        src/MetaVesTController.sol:589 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can push a pending set-wide amendment past its voting threshold by voting with a grant contract they deployed themselves, which lets the authority apply changes to every grant in the set without any real grantee consent.

        ##### What's wrong

        This is a missing resource ownership check. voteOnMetavestAmendment trusts the caller-supplied _grant address: it only checks that the contract's grantee() returns the caller and then adds whatever that contract's getGoverningPower() returns to the proposal. It never checks that _grant is a member of _setName, or that this controller created it.

        ##### Who can do it

        Acme Corp runs a controller; Alice, Bob and Carol hold grants in the set "eng". The authority proposes a set-wide amendment for "eng". Mallory, who controls Acme's authority multisig or simply wants to help it, deploys her own VestingAllocation through the public VestingAllocationFactory, naming herself grantee with an enormous vesting cliff, and votes with it. The proposal passes at once no matter how Alice, Bob and Carol vote.

        - A set-wide proposal is pending for the (function, set) pair, created by the authority.

        - The voter can deploy a contract, or holds any grant from any set or any other controller; no token balance is needed.

        - Applying the passed amendment still requires the authority role, so in practice the attacker is the authority or someone colluding with it.

        ##### What they get

        The authority can apply any amendable change to every grant in the set with zero genuine consent: vesting rate, unlock rate, exercise or repurchase price, stop times, milestone removal, transferability and governing power type. Because rates apply retroactively, setting the vesting rate to zero and then terminating lets Acme recover tokens that had already vested but were not withdrawn, and setting the repurchase price to 1 wei and terminating lets Acme buy back all unvested restricted tokens for nothing. Grantees in other sets, or of other controllers, can also vote on "eng" proposals.

        ##### How it works

        1. The authority calls proposeMajorityMetavestAmendment("eng", sig, data) (MetaVesTController.sol:562-584) and the total power of the real members is snapshotted.

        2. Mallory calls VestingAllocationFactory.createAllocation (VestingAllocationFactory.sol:9-24) with grantee = Mallory, any controller address, tokenStreamTotal and vestingCliffCredit near 2^128, and vestingStartTime 0; the VestingAllocation constructor (VestingAllocation.sol:23-26) only caps vestingRate, so getGoverningPower (VestingAllocation.sol:51-67) returns about 3.4e38. Any hand-written contract exposing grantee() and getGoverningPower() works too.

        3. Mallory calls voteOnMetavestAmendment(fake, "eng", sig, true) (MetaVesTController.sol:589-608). Line 591 passes because grantee() is Mallory, lines 592-594 pass because the proposal is pending and fresh, line 595 reads the huge power, and lines 604-606 add it to currentVotingPower.

        4. The authority calls the amending function; consentCheck (MetaVesTController.sol:146) sees totalVotingPower far below currentVotingPower*2 and allows it for every grant in "eng".

        Exploit scenario

        Not specified.

        Recommendation

        In voteOnMetavestAmendment require that _grant is an element of sets[_setName] (loop or maintain a membership mapping), and keep a mapping of allocations created by this controller so foreign contracts are rejected everywhere a _grant is accepted. Prefer snapshotting each member's power at proposal time rather than reading live power from a caller-supplied address. Verify with a test that deploys an allocation through the factory, votes with it on a set it does not belong to, and asserts the vote reverts.

        Claude Security (Sonnet 5.5)

        Majority-consent check hashes only the last 32 bytes of raw calldata, so authority can append trailing bytes to execute a different value than the one voters approved

        src/MetaVesTController.sol:146 Predicted severity: High

        Root cause

        Vulnerable symbol: consentCheck

        Preconditions: The attacker is the authority; The target grant is in a set, so the majority path is used; At least one majority proposal for that function signature and set has been approved, which can be for any benign value

        Offending code:

        if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {

        Impact

        Grantee/majority consent is not bound to the executed parameters. A malicious authority can apply arbitrary price, unlock-rate, vesting-rate or stop-time values to every grant in a set after obtaining approval for a harmless value. Retroactive rate rewrites reduce vested or unlocked balances, which can then be recovered with terminateMetavestVesting.

        Description

        For grants in a set, consentCheck is called with msg.data and binds the approval only to keccak256 of the final 32 bytes of the raw calldata. The Solidity ABI decoder accepts extra trailing calldata, so the authority (the only caller of the guarded functions) controls those last 32 bytes independently of the real function argument. Also CWE-863: The authority controls set membership (addMetaVestToSet) and the proposal. The majority predicate only reverts when totalVotingPower is strictly greater than twice currentVotingPower, so a proposal with zero total power, or exactly 50%, passes with no grantee vote. The authority can also inflate its own votes with unfunded shell allocations that the public allocation factories let anyone create. This replaces the per-grantee consent that the README says is required for these amendments. Also CWE-20: msg.data is attacker-influenced because ABI decoding ignores calldata beyond the declared arguments. consentCheck compares keccak256(_data[_data.length - 32:]) with the stored hash. authority can append a 32-byte word equal to the approved value to a call whose real arguments differ, and the check still passes. Also CWE-130: For grants in a set, consentCheck is passed msg.data and assumes its last 32 bytes are the function's last argument. The authority controls the raw calldata. The Solidity ABI decoder ignores bytes beyond the expected arguments, so the authority can append a 32-byte word equal to the approved value and put a different value in the real argument slot. Also CWE-697: The majority test totalVotingPower > currentVotingPower*2 evaluates to false when both values are 0. proposeMajorityMetavestAmendment snapshots totalVotingPower from getGoverningPower(), which is 0 for token-option grants nobody has exercised and for vesting grants before vestingStartTime (default govType is vested). A proposal made in that state counts as majority-approved with no votes. Also CWE-354: In the set (majority) path of consentCheck, the commitment is keccak256(_data[_data.length - 32:]) of msg.data, not of the decoded arguments. Solidity ignores extra trailing calldata, so the authority can append the approved 32-byte word to a call whose real arguments differ and still pass the check. Also CWE-190: A fake _grant can contribute an arbitrary _callerPower, for example 2^255, which proposal.currentVotingPower += _callerPower accepts. The unchecked-magnitude value is then doubled in consentCheck, where Solidity 0.8 checked arithmetic panics on overflow, so every consentCheck for that function and set reverts.

        Exploit scenario

        1) Authority calls proposeMajorityMetavestAmendment("S", updateExerciseOrRepurchasePrice.selector, abi.encode(P_benign)); the stored dataHash is keccak256(abi.encode(P_benign)). 2) Grantees in S vote in favor of the benign value and the quorum is met. 3) Authority sends a raw call to updateExerciseOrRepurchasePrice(grantX, P_evil) with abi.encode(P_benign) appended to the calldata. The modifier hashes the trailing 32 bytes, which equal P_benign, so the check passes while the decoded _newPrice is P_evil. The same trick applies to updateMetavestUnlockRate, updateMetavestVestingRate, updateMetavestStopTimes, removeMetavestMilestone and setMetaVestGovVariables, and it applies to every grant in the set.

        Recommendation

        Bind the approval to the full decoded call. Hash abi.encode of the actual typed arguments inside the function, or require msg.data.length to equal the exact expected length. Include the function selector and every argument that matters in the proposal hash. Do not hash a calldata suffix. Also CWE-863: Require a strict majority (currentVotingPower*2 > totalVotingPower, and totalVotingPower > 0). Enforce expiry of the set proposal at execution time. Consume or reset the set proposal after use. Require grantee consent, or a validated and controller-registered allocation, before a grant can be added to a set. Verify set members against a registry of allocations the controller itself created, not just a controller() match, because the public factories can forge that. Also CWE-20: Bind the approval to the exact parameters. Enforce the expected calldata length (_data.length == 4 + 32*nArgs) and hash all arguments after _grant, for example keccak256(_data[36:]). Alternatively decode the amendment value explicitly per function and compare it. Also check proposal expiry in consentCheck and reset the majority proposal after use. Also CWE-130: Bind the approval to the decoded arguments instead of a calldata tail. For example, require msg.data.length to equal the canonical length for the selector, or recompute the hash from the decoded value (keccak256(abi.encode(<last param>))) inside each function. Record the full approved parameters, not a hash of the last word. Reject calldata with trailing bytes. Also clear the proposal after use or after it expires. Also CWE-697: Require totalVotingPower > 0 when proposing, and require currentVotingPower*2 > totalVotingPower, or >= with explicit semantics, with a non-zero current power. Do not let the authority place grants into a set without grantee consent. Also expire and reset proposals after execution. Also CWE-354: Bind consent to the decoded arguments, not raw calldata tails. Hash abi.encode of the specific parameters (excluding the per-grant address if set-wide application is intended), or require msg.data.length to equal the exact expected length and hash the full argument region. Do the same in proposeMajorityMetavestAmendment, and have the proposer pass structured parameters instead of a raw bytes blob. Also CWE-190: Validate _grant as a real set member, so power is bounded by real balances, and compute the majority test without multiplication (for example current > total - current, or compare against total/2). Allow replacing an expired or consumed proposal by fixing the inverted pending check at line 568.

        Claude Security (Opus 5.5)

        Majority consent passes with zero votes when the snapshot voting power is 0, and is not tied to current set membership

        src/MetaVesTController.sol:146 Predicted severity: High

        Root cause

        Vulnerable symbol: consentCheck

        Preconditions: Attacker is the authority (proposals and set management are onlyAuthority); The target set's governing power is 0 at proposal time, or the authority can move the victim into such a set

        Offending code:

        if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {

        Impact

        The authority can impose any consent-gated amendment on any grantee without a single vote, for example freezing vested tokens with an unlock rate of 0, raising option or repurchase prices, or removing milestones.

        Description

        Consent counts as given whenever totalVotingPower <= currentVotingPower*2. totalVotingPower is a snapshot of the set's members taken when the proposal was made (lines 572-574). If that snapshot is 0, the check passes with no votes at all. The check is never re-run against who is in the set when the amendment executes, and exactly 50% also passes despite the documented '>50%' rule. Also CWE-20: For grants in a set, consentCheck compares the voted dataHash with keccak256 of only the last 32 bytes of the raw msg.data. The function itself reads its arguments through the ABI decoder, which ignores extra trailing calldata. The authority can therefore pass any _grant and parameter value and append the approved 32-byte word at the end, and the privileged onlyController call on the allocation then runs with values that were never voted on. Also CWE-436: The authority supplies msg.data, which is untrusted with respect to grantee consent. The consent check hashes only the trailing 32-byte word of msg.data (line 146; proposals store the same slice at line 580). The ABI decoder reads the amendment value at fixed offset 0x24 and ignores any extra trailing calldata. So the authority can put an arbitrary value in the decoded slot and append the majority-approved word at the end, and the check still passes. Also CWE-190: voteOnMetavestAmendment (lines 589-607) accepts any _grant contract. It only checks that grantee() == msg.sender and never checks that the contract is an allocation in _setName, so the attacker sets the getGoverningPower() value. That value is added to proposal.currentVotingPower at line 606, and line 146 then computes currentVotingPower*2 with checked arithmetic. If the total is 2^255 or more, every call that goes through consentCheck panics and reverts. Also CWE-1023: For grants in a set, consentCheck compares only the last 32-byte word of msg.data (_data[_data.length - 32:]) against the proposal hash, which is also built from only the last word (line 580). Solidity's ABI decoder ignores extra calldata after the arguments. So the bytes the consent check reads are not the bytes that become the function arguments. Also CWE-345: Line 580 commits the majority proposal to keccak256 of only the last 32 raw bytes of the proposed calldata, and line 146 checks the live msg.data the same way. The real arguments are ABI-decoded from fixed offsets (bytes 4..68), and Solidity ignores extra trailing calldata. The hash therefore does not bind the values that actually execute, and the authority can supply any argument while appending the approved word as trailing bytes.

        Exploit scenario

        The authority calls createSet("evil") and then proposeMajorityMetavestAmendment("evil", updateMetavestUnlockRate.selector, abi.encodeWithSelector(sel, victim, 0)). The set is empty, so totalVotingPower is 0. It removes the victim's grant from its current set, if any, and calls addMetaVestToSet("evil", victim). It then calls updateMetavestUnlockRate(victim, 0). consentCheck finds the victim in "evil", sees isPending, evaluates 0 > 0 as false, matches the last-32-byte hash, and runs the amendment. The same happens without any set manipulation for a set of new token-option grants: the default govType is vested and they have 0 governing power until exercise, so any majority proposal for them passes as soon as it is made.

        Recommendation

        Reject proposals with totalVotingPower == 0 and require a strict majority (currentVotingPower*2 > totalVotingPower). Bind each proposal to a frozen member list or snapshot so grants added after the proposal cannot be amended under it, and do not let the authority change a grant's set membership while proposals that affect it are pending. Also CWE-20: Do not authorize by hashing a slice of raw msg.data. Store the full keccak256 of the exact intended calldata (or of abi.encode of the decoded parameters) in the proposal. In consentCheck, recompute the hash from the decoded arguments and also bind the msg.sig and the set. At minimum, require msg.data.length to equal the canonical ABI length for the function, compare against the full calldata, delete the majority proposal after it is executed, and enforce AMENDMENT_TIME_LIMIT at execution time. Also CWE-436: Bind consent to the decoded parameters rather than raw calldata. For example, store keccak256(abi.encode(selector, value)) in the proposal and recompute it inside each function from the decoded argument. Alternatively, require msg.data.length to equal the exact ABI length (4 + 64) before hashing. Also check in proposeMajorityMetavestAmendment that _callData[0:4] == _msgSig. Also CWE-190: In voteOnMetavestAmendment, only accept a _grant that is a member of sets[_setName] and was deployed by this controller's factories. Take voting power from that verified allocation, and cap the total so that currentVotingPower can never exceed totalVotingPower. Compare votes without the possibly overflowing multiplication, for example proposal.currentVotingPower <= proposal.totalVotingPower - proposal.currentVotingPower. Also fix the inverted re-proposal guard at line 568 so that expired or poisoned proposals can be replaced. Also CWE-1023: Bind the full calldata. Store keccak256(_callData) at proposal time and compare it against keccak256(msg.data). Better, store the decoded new value and require it to equal the executed argument. Also reject msg.data whose length differs from the expected ABI-encoded length. Clear the majority proposal after execution and check its expiry. Also CWE-345: Bind the commitment to the full decoded intent, not to raw trailing bytes. For example, store keccak256(abi.encode(<decoded argument(s)>)) at proposal time and recompute it inside each amending function from its decoded parameters. Alternatively, require msg.data.length to equal the exact expected ABI length and hash msg.data[36:] (everything after the selector and grant). Reject proposals whose _callData length differs from the canonical encoding.

        Vercel Security Review

        Arbitrary contracts can supply voting power for any set's amendments

        src/MetaVesTController.sol:591 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Untrusted grant supplies voter identity and weight** - src/MetaVesTController.sol:591-595

        ```solidity title="src/MetaVesTController.sol:591-594"

        if(BaseAllocation(_grant).grantee() != msg.sender) revert MetaVesTController_OnlyGrantee();

        if (!functionToSetMajorityProposal[_msgSig][_setName].isPending) revert MetaVesTController_NoPendingAmendment(_msgSig, _grant);

        if (!_checkFunctionToTokenToAmendmentTime(_msgSig, _setName))

        revert MetaVesTController_ProposedAmendmentExpired();

        ```

        Any outsider can supply a contract reporting themselves as grantee and fabricated governing power; neither set membership nor controller provenance is checked.

        **2. Fabricated weight becomes affirmative votes** - src/MetaVesTController.sol:604-607

        ```solidity title="src/MetaVesTController.sol:604-607"

        if (_inFavor) {

        proposal.voters.push(_grant);

        proposal.currentVotingPower += _callerPower;

        }

        ```

        **3. Forged majority authorizes amendments** - src/MetaVesTController.sol:146-148

        ```solidity title="src/MetaVesTController.sol:146-148"

        if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {

        revert MetaVesTController_AmendmentNeitherMutualNorMajorityConsented();

        }

        ```

        For an authority-proposed amendment, outsiders can satisfy the consent gate without affected grantees' votes. Authority execution remains required, but the majority protection is defeated.

        Exploit scenario

        Not specified.

        Recommendation

        Before reading voting power, require that the grant is a registered allocation controlled by this controller and belongs to the proposal's set. Derive eligible voters and their voting weights from a proposal snapshot rather than caller-selected contracts.

      • Possibility for users to buy tokens from MetaVesT for free metavest-3 · 9 writeups High

        V12

        Unequal token decimals undercharge option exercises

        src/TokenOptionAllocation.sol:55 Predicted severity: High

        Root cause

        getPaymentAmount() applies a second decimal conversion when the payment token has fewer decimals, despite exercisePrice already being expressed in payment-token units per whole allocation token.

        Impact

        A grantee can acquire authority-funded option tokens for substantially less than the configured consideration, including zero consideration when the extra division rounds the payment to zero. This crosses the normal controller-funded asset boundary and requires neither a malicious token nor direct self-deployment.

        Description

        The constructor stores exercisePrice in the payment-token denomination and accepts allocation and payment tokens with different decimals. In getPaymentAmount(), the amount is first converted with _amount * exercisePrice / 10**exerciseTokenDecimals, which already produces payment-token base units. When the payment token has fewer decimals, the function divides that result again by 10**(exerciseTokenDecimals - paymentDecimals). For an 18-decimal allocation token and a 6-decimal payment token priced at 1e6, exercising one whole allocation token consequently costs zero instead of 1e6 payment units. The controller validates nonzero addresses and price but does not prevent this supported token configuration, and exerciseTokenOption() credits the entire exercised quantity after the resulting payment transfer.

        Codex Security (GPT-6 Sol)

        Lower-decimal payment token lets a grantee exercise options below the quoted price

        src/TokenOptionAllocation.sol:125 Predicted severity: High

        Root cause

        The option payment getter divides the grant quantity by its token scale and then applies an extra division when the payment token has fewer decimals. exerciseTokenOption uses the reduced amount while increasing tokensExercised.

        Impact

        The grantee can acquire funded option tokens without paying the authority for a realistic 18/6 decimal combination.

        Description

        An option grantee can exercise a funded award for zero payment when the payment token has fewer decimals than the grant token.

        Exploit scenario

        Exercise amount → extra division in getPaymentAmount → zero payment transfer → tokensExercised increment

        Recommendation

        Define price in payment-token base units and calculate amount × price ÷ 10^grantTokenDecimals once, using full-precision arithmetic and a clear rounding rule.

        Pashov (Claude Opus 5.5 high)

        getPaymentAmount scales twice when payment token has fewer decimals, making option exercises / repurchases nearly free

        src/TokenOptionAllocation.sol:116 Predicted severity: High

        Root cause

        An extra decimal normalization in the else branch of getPaymentAmount, duplicated in both TokenOptionAllocation and RestrictedTokenAward.

        Impact

        With an 18-decimal vesting token and a 6-decimal payment token (e.g. USDC), the payment is 1e12 times too small. Grantees exercise options for close to nothing, so authority/the DAO lose the strike price. In RTAs, authority repurchases restricted tokens for close to nothing, so grantees lose. Rounding to zero also allows free exercises of small amounts.

        Description

        The price is documented as 'in decimals of the payment token' per whole vesting token. The correct payment is amount * price / 10**tokenDecimals, which is what the first branch computes. The else branch (paymentDecimals < tokenDecimals) computes that same value and then divides again by 10**(tokenDecimals - paymentDecimals).

        Exploit scenario

        TokenOption with an 18-decimal token, USDC payment, exercisePrice = 1e6 (1 USDC). Grantee exercises 1e18 * 1000 tokens: payment = 1000e18*1e6/1e18 = 1000e6, then /1e12 = 0. The grantee pays 0 USDC for 1000 tokens.

        Recommendation

        Remove the second division, i.e. always paymentAmount = _amount * price / 10**tokenDecimals, and round up for exercises.

        Pashov (Codex GPT-6 Sol high)

        Payment calculation double-scales lower-decimal tokens

        src/TokenOptionAllocation.sol:116 Predicted severity: High

        Root cause

        A second decimal adjustment is applied after price has already been expressed in payment-token units.

        Impact

        Option grantees can exercise for too little payment and authorities can underpay repurchases.

        Description

        When payment decimals are lower than grant-token decimals, paymentAmount is divided by 10**grantDecimals and again by 10**the difference.

        Exploit scenario

        With 18-decimal grant tokens, 6-decimal payment tokens and a 1e6 price, one grant token costs zero instead of 1e6.

        Recommendation

        Divide grant amount by 10**grantTokenDecimals only.

        Devin Security

        Repurchase payment is divided twice when the payment token has fewer decimals, so grantees are paid almost nothing

        src/RestrictedTokenAllocation.sol:116 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        When the payment token has fewer decimals than the award token (for example a 6-decimal stablecoin against an 18-decimal token), the authority repurchases a grantee's restricted tokens for about one trillionth of the agreed price.

        ##### What's wrong

        This is a unit conversion bug. The price is documented as payment token units per whole award token. _amount * repurchasePrice / 10**tokenDecimals already gives the payment amount in payment token units. The else branch then divides again by 10**(tokenDecimals - paymentDecimals).

        ##### Who can do it

        Alice, a grantee at Acme Corp, has a restricted award of an 18-decimal token. The agreed repurchase price is 1 USDC per token, stored as 1e6. Acme terminates her. Mallory, who controls the authority, repurchases 1000 of Alice's unvested tokens. Alice should receive 1000 USDC. The contract computes 0.000000001 USDC, which rounds to zero.

        - Mallory holds the authority role and the award is terminated.

        - The payment token has fewer decimals than the award token, which is common with USDC or USDT.

        ##### What they get

        Mallory takes back Alice's unvested tokens without paying the agreed price. Alice loses the money her contract promised her. Combined with the repeated repurchase bug, Mallory can also take vested tokens almost for free. This affects every restricted award on the controller that uses such a token pair. TokenOptionAllocation.getPaymentAmount has the same formula, so grantees there exercise options for almost nothing.

        ##### How it works

        1. getPaymentAmount reads both token decimals (RestrictedTokenAllocation.sol:117-118).

        2. When the payment token has fewer decimals, it computes the correct amount and then divides by the decimal gap again (RestrictedTokenAllocation.sol:125-126).

        3. repurchaseTokens pulls this reduced amount from the authority and still sends the full _amount of tokens to the authority (RestrictedTokenAllocation.sol:140-144).

        Exploit scenario

        Not specified.

        Recommendation

        Use one formula, _amount * repurchasePrice / 10**tokenDecimals, and remove the extra division. If the price is meant to be in some other unit, document it and scale in both directions. Fix TokenOptionAllocation.getPaymentAmount the same way. Add a test with an 18-decimal award token and a 6-decimal payment token at price 1e6. Confirm that repurchasing 1e18 costs exactly 1e6.

        Devin Security (Deep)

        Repurchase payment is divided by the decimals gap twice, under-paying the grantee when the payment token has fewer decimals

        src/RestrictedTokenAllocation.sol:113 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        When the payment token has fewer decimals than the grant token and the price is set in payment token units as the documentation says, the authority repurchases the grantee's tokens for a tiny fraction of the agreed price, usually rounding to zero.

        ##### What's wrong

        This is a unit mix-up. getPaymentAmount first computes amount * price / 10^tokenDecimals, which already yields payment token units when the price is in payment token units, and then divides again by 10^(tokenDecimals - paymentDecimals). The two branches implicitly expect the price in different units, while the NatSpec says payment token decimals.

        ##### Who can do it

        Acme Corp sets up a restricted token award for Alice paid in a 6 decimal stablecoin, with repurchasePrice = 1,000,000, meaning one stablecoin per token as the docs describe. After termination Acme repurchases 1,000 unvested tokens.

        - The payment token has fewer decimals than the grant token (for example USDC against an 18 decimal token).

        - The price was configured in payment token units as documented. The repository tests avoid the bug only by passing 1e18 as the price with a 6 decimal payment token.

        ##### What they get

        The payment computes as 1000e18 * 1e6 / 1e18 = 1e9, which is the correct 1,000 stablecoins, and is then divided by 1e12 to 0. Acme takes 1,000 tokens and pays nothing. Any repurchase below one million tokens pays zero and larger ones pay one millionth of the agreed price. Combined with the repurchase limit bug in this file, this extends to Alice's vested tokens. The identical function in TokenOptionAllocation lets a grantee exercise options for free (reported there).

        ##### How it works

        1. The controller docstring (MetaVesTController.sol:418) and updatePrice NatSpec (RestrictedTokenAllocation.sol:106) say the price is in payment token units.

        2. getPaymentAmount (RestrictedTokenAllocation.sol:116-129) takes the branch at lines 124-126 when paymentDecimals < repurchaseTokenDecimals and divides twice.

        3. repurchaseTokens (RestrictedTokenAllocation.sol:140-142) pulls that under-scaled amount from the authority.

        Exploit scenario

        Not specified.

        Recommendation

        Define the price unit once (payment token units per whole grant token) and compute amount * price / 10**grantTokenDecimals in every case; revert when the computed payment is zero. Verify with a test using a 6 decimal payment token, an 18 decimal grant token and price 1e6, asserting that one whole token costs 1e6.

        Claude Security (Sonnet 5.5)

        getPaymentAmount applies an extra 10^(tokenDecimals - paymentDecimals) division when payment token has fewer decimals, understating the exercise cost by orders of magnitude (rounding to zero)

        src/TokenOptionAllocation.sol:126 Predicted severity: Medium

        Root cause

        Vulnerable symbol: TokenOptionAllocation.getPaymentAmount

        Preconditions: Payment token has fewer decimals than the vesting token; Price is configured per the documented payment-token-decimals convention

        Offending code:

        paymentAmount = paymentAmount / (10**(exerciseTokenDecimals - paymentDecimals));

        Impact

        Option exercise payments can be undercharged by a factor of 10^(tokenDecimals - paymentDecimals), up to a complete bypass of the exercise price. The authority is deprived of the agreed payment.

        Description

        The two branches are mutually inconsistent. For paymentDecimals >= tokenDecimals the cost is amount*price/10^tokenDecimals. For paymentDecimals < tokenDecimals the same value is divided again by 10^(tokenDecimals - paymentDecimals). The natspec (updatePrice, controller docs) defines price as payment-token units per token, so the first expression is already in payment decimals. The extra division is applied to the grantee-controlled exercise amount.

        Exploit scenario

        Vesting token has 18 decimals and the payment token is USDC (6 decimals), the most common pairing. The authority follows the documented convention and sets exercisePrice = 2_000_000 (2 USDC per token). Exercising 1e24 tokens (1,000,000 tokens) gives 1e24*2e6/1e18 = 2e12, then /1e12 = 2 units, i.e. 0.000002 USDC. Any exercise under ~500,000 tokens costs 0 (floor). The grantee exercises the whole grant for effectively nothing. If operators instead treat price as an 18-decimal fixed-point value (as the test fixtures do), the pay > token case lacks the matching scale-up, so the same bug appears with the roles reversed.

        Recommendation

        Define one price convention and implement it consistently: e.g. cost = _amount * exercisePrice / 10^tokenDecimals when price is in payment decimals, with no second division. Alternatively use a fixed-point price and scale by 10^paymentDecimals / 10^tokenDecimals in both directions. Round up (mulDivUp) so tiny exercises cannot be free. Add tests covering unequal-decimals pairs.

        Claude Security (Opus 5.5)

        Double decimal scaling lets the authority repurchase restricted tokens for about 10^-(decimal difference) of the agreed price

        src/RestrictedTokenAllocation.sol:126 Predicted severity: Medium

        Root cause

        Vulnerable symbol: getPaymentAmount

        Preconditions: paymentToken has fewer decimals than the vesting token; Authority repurchases after termination

        Offending code:

        paymentAmount = paymentAmount / (10**(repurchaseTokenDecimals - paymentDecimals));

        Impact

        The grantee is underpaid by a factor of 10^(decimal difference) for repurchased restricted tokens.

        Description

        repurchasePrice is payment-token units per whole token. When payment decimals are lower than the token's, the else branch scales a second time, so repurchaseTokens (line 140/142) pulls a truncated, often zero, payment from the authority and still sends the grantee's tokens to the authority (line 144).

        Exploit scenario

        With an 18-decimal token and a 6-decimal payment token, the authority terminates the grant and calls repurchaseTokens(unvested). The repurchase payment is 1e12 times too small (0 for typical amounts), so the grantee's claimRepurchasedTokens yields almost nothing for the tokens taken.

        Recommendation

        Use a single normalization, _amount * repurchasePrice / 10**tokenDecimals, and round up in the grantee's favour.

        Vercel Security Review

        Extra decimal scaling can make option exercises and repurchases free

        src/TokenOptionAllocation.sol:125 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Exercise prices are specified in payment-token units** - src/TokenOptionAllocation.sol:106-109

        ```solidity title="src/TokenOptionAllocation.sol:106-109"

        /// @param _newPrice - the new exercise price in decimals of the payment token

        function updatePrice(uint256 _newPrice) external onlyController {

        if(terminated) revert MetaVesT_AlreadyTerminated();

        exercisePrice = _newPrice;

        ```

        **2. Lower-decimal payment tokens trigger an extra division** - src/TokenOptionAllocation.sol:125-126

        ```solidity title="src/TokenOptionAllocation.sol:125-126"

        paymentAmount = _amount * exercisePrice / (10**exerciseTokenDecimals);

        paymentAmount = paymentAmount / (10**(exerciseTokenDecimals - paymentDecimals));

        ```

        For 18-decimal allocation tokens, a 6-decimal payment token, and price 1e6, exercising one whole token computes zero rather than 1e6. RestrictedTokenAllocation.sol:125-126 duplicates this error for repurchases.

        **3. Zero payment still credits exercised tokens** - src/TokenOptionAllocation.sol:141-143

        ```solidity title="src/TokenOptionAllocation.sol:141-143"

        if (IERC20M(paymentToken).balanceOf(msg.sender) < paymentAmount) revert MetaVesT_InsufficientPaymentTokenBalance();

        safeTransferFrom(paymentToken, msg.sender, getAuthority(), paymentAmount);

        tokensExercised += _tokensToExercise;

        ```

        Grantees can obtain vested options without the stipulated payment; authorities can similarly underpay restricted-token repurchases.

        Exploit scenario

        Not specified.

        Recommendation

        Define and consistently enforce price units in both allocation types. For prices denominated in payment-token base units per whole allocation token, calculate amount times price divided by 10^allocationDecimals without a second decimal conversion. Use appropriate rounding to prevent positive purchases rounding to zero.

      • Incorrect calculation in terminate function metavest-4 · 8 writeups High

        V12

        Prior withdrawals inflate termination collateral recovery

        src/BaseAllocation.sol:153 Predicted severity: High

        Root cause

        The termination recovery formula adds tokensWithdrawn even though withdrawals already reduced the actual balance and do not increase unvested entitlement. This double-counts previously delivered tokens as additional recoverable collateral.

        Impact

        Ordinary pre-termination withdrawals can cause authority recovery to remove collateral backing the grantee's remaining paid option rights. Larger prior withdrawals can instead make termination unavailable because the inflated recovery exceeds the escrow balance; both outcomes arise under normally funded grants without malformed constructor parameters.

        Description

        The constructor initializes withdrawal and exercise counters at zero, but normal exercise followed by withdrawal makes tokensWithdrawn positive before termination. terminate() computes recovery as total configured funding minus remaining exercisable rights minus exercised quantity, then adds tokensWithdrawn. The exercisable quantity already subtracts exercised tokens, so the first two deductions reduce to the vested amount; adding withdrawals incorrectly increases the unvested recovery rather than preserving the outstanding funded rights. With 100 fully vested and exercised tokens and 40 already withdrawn, the function attempts to transfer another 40 to authority even though no tokens are unvested. If the remaining balance is sufficient, termination succeeds with too little collateral for the other 60 paid tokens; otherwise it reverts and blocks termination.

        Pashov (Claude Opus 5.5 high)

        VestingAllocation.terminate adds tokensWithdrawn instead of ignoring it, seizing vested tokens or making termination revert

        src/VestingAllocation.sol:79 Predicted severity: High

        Root cause

        Wrong sign/term in the recovery formula: tokensWithdrawn is added even though withdrawn tokens have already left the contract and are part of the vested amount.

        Impact

        After termination the contract holds vested - 2*tokensWithdrawn instead of vested - tokensWithdrawn. Authority takes tokensWithdrawn worth of the grantee's vested-but-unwithdrawn tokens, so the grantee's later withdraw() fails the balance check. If the grantee has withdrawn more than half of the vested amount, the transfer exceeds the balance and terminate() reverts. Authority then cannot terminate at all and vesting keeps running.

        Description

        terminate() computes the amount returned to authority as tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() + tokensWithdrawn. The contract balance before termination is tokenStreamTotal + milestonesAllocation - tokensWithdrawn, and the unvested remainder authority should get back is tokenStreamTotal + milestonesAllocation - vested. Adding tokensWithdrawn counts tokens the grantee already withdrew a second time.

        Exploit scenario

        Grantee has vested 600 of 1000 tokens and withdrawn 400. Authority calls terminateMetavestVesting. tokensToRecover = 1000 - 600 + 400 = 800, but only 600 are held. The call reverts and the grant cannot be terminated. With 200 withdrawn instead: authority gets 600 (400 unvested + 200 of the grantee's vested tokens), leaving 200 of the grantee's 400 still owed.

        Recommendation

        Use tokensToRecover = tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() (no + tokensWithdrawn), and use a consistent definition of the milestone totals (see the removed-milestone finding).

        Pashov (Codex GPT-6 Sol high)

        Termination over-recovers tokens after prior withdrawals

        src/VestingAllocation.sol:79 Predicted severity: High

        Root cause

        The recovery formulas include + tokensWithdrawn.

        Impact

        The authority can receive tokens reserved for the grantee; termination can also revert when the computed recovery exceeds the actual balance.

        Description

        Termination adds prior withdrawals to the authority recovery even though those tokens have already left the allocation.

        Exploit scenario

        Fund 100, vest 40, withdraw 10, then terminate; vesting sends 70 to authority, leaving 20 against the grantee’s remaining 30-token claim.

        Recommendation

        Remove + tokensWithdrawn from both recovery formulas and reconcile against remaining balance.

        Devin Security

        Termination adds withdrawn tokens to the recovery amount, so a grantee can block termination or lose vested tokens

        src/VestingAllocation.sol:79 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A grantee who has withdrawn their vested tokens can make termination revert forever and keep vesting the whole grant. A grantee who withdrew less loses part of their vested tokens to the company when it terminates.

        ##### What's wrong

        This is an accounting bug. terminate computes the tokens to send back as unvested tokens plus tokensWithdrawn. Withdrawn tokens have already left the contract, so the amount should not grow with them. The math asks for more tokens than the contract holds or should return.

        ##### Who can do it

        Alice, an engineer at Acme Corp, has a vesting grant. Mallory is a grantee at Acme who expects to be fired. Mallory withdraws everything she can each time it unlocks. When Acme's authority calls terminateMetavestVesting on her grant, the transfer asks for more tokens than the contract holds and reverts. In the other direction, when Acme terminates Alice after she withdrew a small amount, Alice loses that amount again from her remaining vested tokens.

        - Mallory is the grantee of a VestingAllocation.

        - Her unlock schedule keeps pace with her vesting, so she can withdraw at least half of her vested tokens.

        - The authority cannot cut her vesting or unlock rate without her consent.

        ##### What they get

        Mallory blocks her own termination. She keeps vesting and later withdraws the unvested part of the grant that Acme meant to take back. She can do this until the whole grant has vested. In the other case, Acme takes vested tokens that belong to Alice. The amount equals what Alice had already withdrawn. The damage stays within one grant at a time.

        ##### How it works

        1. The contract balance before termination is the grant total minus tokensWithdrawn.

        2. terminate sets tokensToRecover to the total minus the vested amount plus tokensWithdrawn (VestingAllocation.sol:86).

        3. The transfer to the authority needs more tokens than the balance whenever tokensWithdrawn is more than half of the vested amount, so it reverts (VestingAllocation.sol:88).

        4. When it does not revert, the contract keeps only the vested amount minus twice tokensWithdrawn, which is less than the grantee can still withdraw.

        Exploit scenario

        Not specified.

        Recommendation

        Compute the recovery amount as tokenStreamTotal + milestonesAllocation - getVestedTokenAmount(), without adding tokensWithdrawn. Apply the same fix to TokenOptionAllocation.terminate, which has the same pattern. Add a test where the grantee withdraws all vested tokens and the authority then terminates. Confirm termination succeeds and the grantee can still withdraw the rest of their vested tokens.

        Devin Security (Deep)

        Termination adds tokensWithdrawn to the recovered amount, shorting the grantee or reverting

        src/TokenOptionAllocation.sol:149 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Terminating a grant takes back the grantee's already withdrawn amount a second time out of their remaining balance, and if the grantee has withdrawn more than half of what vested the termination reverts, so a grantee can block termination for good simply by withdrawing as they vest.

        ##### What's wrong

        This is an arithmetic error in the recovery formula. The contract holds total minus withdrawn, and the grantee is owed vested minus withdrawn, so the correct recovery is total minus vested. terminate() instead computes total minus vested plus withdrawn.

        ##### Who can do it

        Alice holds a token option grant from Acme Corp. She exercises and withdraws tokens as they vest. Acme later decides to terminate her grant.

        - Loss case: 2 * tokensWithdrawn <= vested, and Alice loses tokensWithdrawn tokens to the authority.

        - Block case: 2 * tokensWithdrawn > vested, which any grantee can arrange by withdrawing promptly; termination then reverts.

        ##### What they get

        In the block case Acme's terminateMetavestVesting reverts every time, so Alice's grant keeps vesting the whole remaining stream and Acme cannot stop it (updateMetavestVestingRate to zero needs consent, absent the consent bypasses reported in MetaVesTController.sol). In the loss case Acme receives tokensWithdrawn more than it should and Alice can later withdraw only vested - 2 * withdrawn, losing the difference. Example with total 1000, vested 500, exercised 500: withdrawn 400 gives a balance of 600 and a formula result of 900, so terminate reverts; withdrawn 200 gives a balance of 800 and a formula result of 700, so Acme takes 700 while Alice is owed 300 and only 100 remain. VestingAllocation.terminate has the same formula.

        ##### How it works

        1. terminate (TokenOptionAllocation.sol:149-162) line 156 computes tokensToRecover = total + sum(milestones) - getAmountExercisable() - tokensExercised + tokensWithdrawn.

        2. getAmountExercisable (TokenOptionAllocation.sol:174-188) is linearVested + milestoneAwardTotal - tokensExercised, so the expression equals total + sum(milestones) - linearVested - milestoneAwardTotal + tokensWithdrawn.

        3. The contract holds total + sum(milestones) - tokensWithdrawn, so the safeTransfer at line 159 reverts whenever 2 * tokensWithdrawn exceeds linearVested + milestoneAwardTotal, and otherwise sends tokensWithdrawn too many tokens to the authority.

        4. Alice's later withdraw (BaseAllocation.sol:275) is capped by the depleted balance.

        Exploit scenario

        Not specified.

        Recommendation

        Remove the + tokensWithdrawn term: recover total + sum(milestones) - linearVested - milestoneAwardTotal (equivalently balanceOf(this) minus what the grantee is still owed), in both TokenOptionAllocation.sol:156 and VestingAllocation.sol:86. Verify with a test where the grantee exercises and withdraws more than half of the vested amount, then terminate, asserting success and that the grantee can still withdraw exactly vested - withdrawn.

        Claude Security (Sonnet 5.5)

        VestingAllocation.terminate() adds tokensWithdrawn to the recovery amount, so termination takes the grantee's vested tokens or reverts

        src/VestingAllocation.sol:86 Predicted severity: High

        Root cause

        Vulnerable symbol: terminate

        Preconditions: Grantee has withdrawn a nonzero amount before terminate() is called; Controller authority calls terminateMetavestVesting (loss path), or the grantee pre-emptively withdraws at least half of their vested amount (blocking path)

        Offending code:

        tokensToRecover = allocation.tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() + tokensWithdrawn;

        Impact

        When vested amount is at least twice tokensWithdrawn, an ordinary authority termination sweeps tokensWithdrawn worth of the grantee's vested, unwithdrawn tokens to the authority. The grantee cannot withdraw them afterwards because withdraw() also checks the contract balance. Otherwise terminate() reverts permanently until enough has vested. A grantee who has withdrawn at least half of their vested tokens can therefore prevent the authority from recovering the unvested remainder.

        Description

        getVestedTokenAmount() is cumulative and already includes tokens the grantee has withdrawn. The contract balance is total+milestones-tokensWithdrawn, so the correct recovery is total+milestones-vested. The extra '+ tokensWithdrawn' over-recovers by exactly tokensWithdrawn, and the following safeTransfer to the authority is sized from that wrong number. Also CWE-682: The contract is funded with T = tokenStreamTotal + milestones and holds T - tokensWithdrawn after withdrawals, while the unvested remainder to return is T - vested. The extra + tokensWithdrawn double-counts withdrawals, so the amount sent to the authority at line 88 exceeds the unvested remainder by exactly tokensWithdrawn.

        Exploit scenario

        Take tokenStreamTotal=1000, no milestones, vested=300, and the grantee has withdrawn 150. The contract balance is 850 and the grantee is still owed 150 vested tokens. The controller's terminateMetavestVesting (authority only, no grantee consent) computes 1000-300+150=850 and transfers the whole balance to the authority, leaving the grantee with 0. If instead the grantee has withdrawn 200 of 300 vested, the computed amount is 900 against a balance of 800. The token transfer then fails with TransferFailed, so the authority can no longer terminate. A grantee who sees termination coming can withdraw more than half of their vested amount to block it. Existing tests only terminate when tokensWithdrawn is 0, so this path is untested.

        Recommendation

        Remove '+ tokensWithdrawn'. Use tokensToRecover = tokenStreamTotal + milestonesAllocation - getVestedTokenAmount(). Cap it by the contract balance minus (vested - tokensWithdrawn), and add tests that terminate after partial withdrawals. Also CWE-682: Use tokensToRecover = tokenStreamTotal + milestonesAllocation - getVestedTokenAmount(), without adding tokensWithdrawn. Cap it by the contract's token balance minus the grantee's remaining entitlement (vested - tokensWithdrawn) so the transfer cannot revert or over-recover.

        Claude Security (Opus 5.5)

        terminate() adds tokensWithdrawn to the recovery amount, so termination either takes the grantee's vested tokens or reverts

        src/VestingAllocation.sol:86 Predicted severity: High

        Root cause

        Vulnerable symbol: terminate

        Preconditions: Grantee has withdrawn a nonzero amount before termination; Authority calls terminateMetavestVesting

        Offending code:

        tokensToRecover = allocation.tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() + tokensWithdrawn;

        Impact

        After any prior withdrawal, a routine termination confiscates vested tokens owed to the grantee, equal to the amount already withdrawn. Alternatively, a grantee can make their own grant impossible to terminate and keep vesting the unvested allocation.

        Description

        The contract balance is tokenStreamTotal + milestones - tokensWithdrawn, but the recovery amount is computed as total - vested + tokensWithdrawn. The unvested remainder should be total - vested. The withdrawn amount is effectively counted twice, and the result is sent to the authority by safeTransfer at line 88. Also CWE-191: removeMilestone (BaseAllocation.sol:246) deletes a milestone without checking complete. milestonesAllocation, the sum of current awards, drops, while milestoneAwardTotal, which is included in getVestedTokenAmount, keeps the deleted award. Once linear vesting is near full, T + milestonesAllocation - vested underflows and terminate reverts. The same applies to TokenOptionAllocation.sol:156.

        Exploit scenario

        Take T=1000 and vested=unlocked=600, after the grantee has withdrawn W=200, leaving a balance of 800. terminate() sends 1000-600+200=600 to the authority and leaves 200, while the grantee is still owed 600-200=400. The grantee loses 200 vested tokens. In general the leftover balance is V-2W, so the grantee always loses W. Conversely, once W > V/2 (for example, the grantee withdraws everything available, or front-runs terminateMetavestVesting with a withdraw), the transfer exceeds the balance and terminate reverts. The grantee keeps vesting, and the authority cannot pause vesting without the grantee's consent.

        Recommendation

        Recover exactly the unvested amount, tokensStreamTotal + milestonesAllocation - getVestedTokenAmount(), with no tokensWithdrawn term. Equivalently, recover balanceOf(this) - (vested - tokensWithdrawn). Also CWE-191: In removeMilestone, revert if milestones[_milestoneIndex].complete is true. Base recovery calculations on the actual balance rather than on recomputed totals.

        Vercel Security Review

        Termination adds prior withdrawals to recoverable funds and consumes vested backing

        src/VestingAllocation.sol:86 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Withdrawals already reduce the escrow balance** - src/BaseAllocation.sol:275-277

        ```solidity title="src/BaseAllocation.sol:275-277"

        if (_amount > getAmountWithdrawable() || _amount > IERC20M(allocation.tokenContract).balanceOf(address(this))) revert MetaVesT_MoreThanAvailable();

        tokensWithdrawn += _amount;

        safeTransfer(allocation.tokenContract, msg.sender, _amount);

        ```

        **2. Vesting termination adds those withdrawals to recovery** - src/VestingAllocation.sol:86-88

        ```solidity title="src/VestingAllocation.sol:86-88"

        tokensToRecover = allocation.tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() + tokensWithdrawn;

        terminationTime = block.timestamp;

        safeTransfer(allocation.tokenContract, getAuthority(), tokensToRecover);

        ```

        With 100 allocated, 60 vested, and 20 withdrawn, termination recovers 60 instead of 40, leaving only 20 backing the remaining 40 vested entitlement.

        **3. Options repeat the same over-recovery** - src/TokenOptionAllocation.sol:156-159

        ```solidity title="src/TokenOptionAllocation.sol:156-159"

        uint256 tokensToRecover = allocation.tokenStreamTotal + milestonesAllocation - getAmountExercisable() - tokensExercised + tokensWithdrawn;

        terminationTime = block.timestamp;

        shortStopTime = block.timestamp + shortStopDuration;

        safeTransfer(allocation.tokenContract, getAuthority(), tokensToRecover);

        ```

        Normal authority termination either takes vested backing or reverts when the inflated recovery exceeds the remaining balance, preventing termination.

        Exploit scenario

        Not specified.

        Recommendation

        Compute recovery from actual escrow balance minus all outstanding protected entitlements. For standard fully funded grants, prior withdrawals must not increase the original unvested recovery amount. Correct both VestingAllocation and TokenOptionAllocation and cover partial withdrawal before termination.

      • Unable to unlock milestone metavest-5 · 2 writeups High

        V12

        Deferred milestone awards never unlock after payment

        src/TokenOptionAllocation.sol:45 Predicted severity: High

        Root cause

        unlockOnCompletion=false milestones are excluded from immediate unlock accounting without being incorporated into any deferred unlocking calculation. The stream-only cap makes the omission persist after the schedule completes.

        Impact

        Grantees can pay for option rights that never unlock, leaving the corresponding allocation tokens unavailable under the initialized schedule. Post-termination recovery can transfer these paid-but-locked tokens to authority, producing conditional loss of paid entitlement rather than merely a displayed balance discrepancy.

        Description

        A milestone initialized with unlockOnCompletion=false is accepted and funded through normal option creation. When its conditions are satisfied, confirmMilestone() credits milestoneAwardTotal but never credits milestoneUnlockedTotal for that milestone. The grantee can therefore exercise the milestone and pay its configured consideration. However, the linear unlock calculation is permanently capped at allocation.tokenStreamTotal, and the only extra unlock credit comes from milestones whose unlockOnCompletion flag was true. After exercising and withdrawing the entire stream, the false-flag milestone cannot become withdrawable even when the unlocking schedule has fully elapsed.

        Vercel Security Review

        Deferred milestone awards never unlock

        src/VestingAllocation.sol:117 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Completing a milestone only unlocks it immediately when configured true.** - src/BaseAllocation.sol:232-235

        ```solidity title="src/BaseAllocation.sol:232-235"

        milestone.complete = true;

        milestoneAwardTotal += milestone.milestoneAward;

        if(milestone.unlockOnCompletion)

        milestoneUnlockedTotal += milestone.milestoneAward;

        ```

        **2. Linear unlocking caps at tokenStreamTotal, which excludes milestone awards. With unlockOnCompletion=false, even a completed award never unlocks. Withdrawal takes the minimum of vested and unlocked amounts, stranding that award after both schedules finish. RestrictedTokenAllocation.sol:213-216 and TokenOptionAllocation.sol:198-201 repeat this cap; option grantees can pay for tokens they cannot withdraw.** - src/VestingAllocation.sol:117-120

        ```solidity title="src/VestingAllocation.sol:117-120"

        if(_tokensUnlocked>allocation.tokenStreamTotal)

        _tokensUnlocked = allocation.tokenStreamTotal;

        return _tokensUnlocked += milestoneUnlockedTotal;

        ```

        Exploit scenario

        Not specified.

        Recommendation

        Include completed, deferred-unlock milestone awards in scheduled unlock entitlements and the final unlock cap, without double-counting immediately unlocked awards.

      • The authority can execute majority-consented proposals with arbitrary data metavest-6 · 7 writeups High

        V12

        Trailing calldata substitutes approved amendment values

        src/MetaVesTController.sol:140 Predicted severity: Medium

        Root cause

        The majority authorization hash covers a position relative to total calldata length rather than the canonical decoded mutation payload. Appended calldata can decouple the authorized word from the executed argument.

        Impact

        An authority can replace the economic parameters approved by a set with unapproved parameters, including a zero unlock rate or a different exercise price. This defeats majority consent even when every vote came from a legitimate member and the proposal passed legitimately; configured selector conditions remain a separate requirement.

        Description

        The majority consent path hashes only the last 32 bytes of execution calldata rather than the decoded amendment argument. For the two-argument update functions, ordinary ABI calldata places the amendment value in the second argument word, but trailing bytes can be appended without changing those decoded arguments. An authority can therefore encode a different value in the argument word and append the originally approved word at the end. consentCheck sees the approved trailing hash while the function body forwards the different decoded value. The selector and set checks do not prevent this value substitution.

        Pashov (Claude Opus 5.5 high)

        Approved majority amendments never expire or reset and can be replayed indefinitely

        src/MetaVesTController.sol:140 Predicted severity: Medium

        Root cause

        No expiry or consumption of majority proposals at execution time; consent is bound only to the final 32 bytes of calldata.

        Impact

        Once a majority approved a change at any point (even years earlier), authority can re-apply it whenever it likes, including to members added to the set later or after their parameters changed (e.g. re-setting a vesting rate the grantees later negotiated up, or removing milestones by index again after new milestones were added).

        Description

        For metavests in a set, consentCheck only checks isPending, the vote ratio, and the hash of the last 32 bytes of calldata. It does not check proposal.time + AMENDMENT_TIME_LIMIT, and _resetAmendmentParams only clears the individual-consent mapping, not functionToSetMajorityProposal. Votes are also counted with live power at vote time against a stale totalVotingPower snapshot, and metavests added to the set later are bound by a proposal they never voted on.

        Exploit scenario

        Set approves removeMetavestMilestone with index 0. Months later authority adds a new milestone at index 0 for a new member's grant and immediately calls removeMetavestMilestone(newMember, 0) using the old approval.

        Recommendation

        Check expiry in consentCheck, delete the majority proposal after execution, and snapshot both membership and power at proposal time.

        Pashov (Codex GPT-6 Sol high)

        Trailing calldata bypasses the value approved by a majority

        src/MetaVesTController.sol:140 Predicted severity: High

        Root cause

        consentCheck binds the final calldata word rather than the decoded amendment parameter or exact full calldata.

        Impact

        The authority can execute a different price, rate, transferability, or stop value from the one approved by voters.

        Description

        Majority approval hashes the final 32 calldata bytes, while Solidity decodes a setter parameter from its fixed ABI position and accepts trailing bytes.

        Exploit scenario

        Voters approve updateMetavestUnlockRate(grant,1). Authority calls the selector with grant, decoded rate 0, and an extra trailing ABI word 1. The suffix hash matches while the setter applies 0.

        Recommendation

        Decode and compare the approved parameter explicitly or hash canonical calldata with an exact-length check.

        Devin Security

        Passed majority amendments never expire or reset and bind only the last 32 bytes of calldata

        src/MetaVesTController.sol:140 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        After one majority amendment passes, the authority can reuse it forever, on any grant in the set, with any value in the other arguments, so grantees lose control over later changes to their grants.

        ##### What's wrong

        This is a consent replay bug. The majority proposal stores a hash of only the last 32 bytes of the calldata. consentCheck compares against that hash but does not check the one-week expiry. _resetAmendmentParams clears only the individual-consent mapping, never functionToSetMajorityProposal. A passed proposal stays valid with no time limit.

        ##### Who can do it

        The Acme authority gets the "engineering" set to approve a single cut of the vesting rate to X. Months later, the authority calls updateMetavestVestingRate again on every grant in the set, without a new vote. The authority can also call any function whose last argument encodes as the same 32 bytes, for example removeMetavestMilestone with an index that equals X.

        - The caller is the controller authority.

        - One majority proposal for that function and set has passed at some point.

        ##### What they get

        The authority can apply the amendment again whenever it wants, including after grantees have been added to the set who never voted. Because the grant address is not part of the hash, one approval covers every grant in the set. This lets the authority impose term changes without the consent grantees bargained for. The impact is limited to grants in sets under this controller.

        ##### How it works

        1. proposeMajorityMetavestAmendment stores keccak256(_callData[_callData.length - 32:]) (MetaVesTController.sol:580).

        2. consentCheck checks pending status, the vote ratio, and the 32-byte hash, but not the proposal time (MetaVesTController.sol:146).

        3. After the call, _resetAmendmentParams deletes only the individual proposal (MetaVesTController.sol:611-613), so the majority proposal remains pending and passed.

        4. The authority calls the same function again on any grant in the set, and it succeeds.

        Exploit scenario

        Not specified.

        Recommendation

        Hash the full calldata, minus the grant address if the amendment is meant to cover the whole set, and include the function selector. Check _checkFunctionToTokenToAmendmentTime inside consentCheck. Clear or mark the majority proposal as used once it has been applied to every grant in the set. Add a test that a second call after execution reverts.

        Claude Security (Sonnet 5.5)

        Majority-consent check hashes only the last 32 bytes of raw calldata, so authority can append trailing bytes to execute a different value than the one voters approved

        src/MetaVesTController.sol:146 Predicted severity: High

        Root cause

        Vulnerable symbol: consentCheck

        Preconditions: The attacker is the authority; The target grant is in a set, so the majority path is used; At least one majority proposal for that function signature and set has been approved, which can be for any benign value

        Offending code:

        if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {

        Impact

        Grantee/majority consent is not bound to the executed parameters. A malicious authority can apply arbitrary price, unlock-rate, vesting-rate or stop-time values to every grant in a set after obtaining approval for a harmless value. Retroactive rate rewrites reduce vested or unlocked balances, which can then be recovered with terminateMetavestVesting.

        Description

        For grants in a set, consentCheck is called with msg.data and binds the approval only to keccak256 of the final 32 bytes of the raw calldata. The Solidity ABI decoder accepts extra trailing calldata, so the authority (the only caller of the guarded functions) controls those last 32 bytes independently of the real function argument. Also CWE-863: The authority controls set membership (addMetaVestToSet) and the proposal. The majority predicate only reverts when totalVotingPower is strictly greater than twice currentVotingPower, so a proposal with zero total power, or exactly 50%, passes with no grantee vote. The authority can also inflate its own votes with unfunded shell allocations that the public allocation factories let anyone create. This replaces the per-grantee consent that the README says is required for these amendments. Also CWE-20: msg.data is attacker-influenced because ABI decoding ignores calldata beyond the declared arguments. consentCheck compares keccak256(_data[_data.length - 32:]) with the stored hash. authority can append a 32-byte word equal to the approved value to a call whose real arguments differ, and the check still passes. Also CWE-130: For grants in a set, consentCheck is passed msg.data and assumes its last 32 bytes are the function's last argument. The authority controls the raw calldata. The Solidity ABI decoder ignores bytes beyond the expected arguments, so the authority can append a 32-byte word equal to the approved value and put a different value in the real argument slot. Also CWE-697: The majority test totalVotingPower > currentVotingPower*2 evaluates to false when both values are 0. proposeMajorityMetavestAmendment snapshots totalVotingPower from getGoverningPower(), which is 0 for token-option grants nobody has exercised and for vesting grants before vestingStartTime (default govType is vested). A proposal made in that state counts as majority-approved with no votes. Also CWE-354: In the set (majority) path of consentCheck, the commitment is keccak256(_data[_data.length - 32:]) of msg.data, not of the decoded arguments. Solidity ignores extra trailing calldata, so the authority can append the approved 32-byte word to a call whose real arguments differ and still pass the check. Also CWE-190: A fake _grant can contribute an arbitrary _callerPower, for example 2^255, which proposal.currentVotingPower += _callerPower accepts. The unchecked-magnitude value is then doubled in consentCheck, where Solidity 0.8 checked arithmetic panics on overflow, so every consentCheck for that function and set reverts.

        Exploit scenario

        1) Authority calls proposeMajorityMetavestAmendment("S", updateExerciseOrRepurchasePrice.selector, abi.encode(P_benign)); the stored dataHash is keccak256(abi.encode(P_benign)). 2) Grantees in S vote in favor of the benign value and the quorum is met. 3) Authority sends a raw call to updateExerciseOrRepurchasePrice(grantX, P_evil) with abi.encode(P_benign) appended to the calldata. The modifier hashes the trailing 32 bytes, which equal P_benign, so the check passes while the decoded _newPrice is P_evil. The same trick applies to updateMetavestUnlockRate, updateMetavestVestingRate, updateMetavestStopTimes, removeMetavestMilestone and setMetaVestGovVariables, and it applies to every grant in the set.

        Recommendation

        Bind the approval to the full decoded call. Hash abi.encode of the actual typed arguments inside the function, or require msg.data.length to equal the exact expected length. Include the function selector and every argument that matters in the proposal hash. Do not hash a calldata suffix. Also CWE-863: Require a strict majority (currentVotingPower*2 > totalVotingPower, and totalVotingPower > 0). Enforce expiry of the set proposal at execution time. Consume or reset the set proposal after use. Require grantee consent, or a validated and controller-registered allocation, before a grant can be added to a set. Verify set members against a registry of allocations the controller itself created, not just a controller() match, because the public factories can forge that. Also CWE-20: Bind the approval to the exact parameters. Enforce the expected calldata length (_data.length == 4 + 32*nArgs) and hash all arguments after _grant, for example keccak256(_data[36:]). Alternatively decode the amendment value explicitly per function and compare it. Also check proposal expiry in consentCheck and reset the majority proposal after use. Also CWE-130: Bind the approval to the decoded arguments instead of a calldata tail. For example, require msg.data.length to equal the canonical length for the selector, or recompute the hash from the decoded value (keccak256(abi.encode(<last param>))) inside each function. Record the full approved parameters, not a hash of the last word. Reject calldata with trailing bytes. Also clear the proposal after use or after it expires. Also CWE-697: Require totalVotingPower > 0 when proposing, and require currentVotingPower*2 > totalVotingPower, or >= with explicit semantics, with a non-zero current power. Do not let the authority place grants into a set without grantee consent. Also expire and reset proposals after execution. Also CWE-354: Bind consent to the decoded arguments, not raw calldata tails. Hash abi.encode of the specific parameters (excluding the per-grant address if set-wide application is intended), or require msg.data.length to equal the exact expected length and hash the full argument region. Do the same in proposeMajorityMetavestAmendment, and have the proposer pass structured parameters instead of a raw bytes blob. Also CWE-190: Validate _grant as a real set member, so power is bounded by real balances, and compute the majority test without multiplication (for example current > total - current, or compare against total/2). Allow replacing an expired or consumed proposal by fixing the inverted pending check at line 568.

        Claude Security (Opus 5.5)

        Majority consent passes with zero votes when the snapshot voting power is 0, and is not tied to current set membership

        src/MetaVesTController.sol:146 Predicted severity: High

        Root cause

        Vulnerable symbol: consentCheck

        Preconditions: Attacker is the authority (proposals and set management are onlyAuthority); The target set's governing power is 0 at proposal time, or the authority can move the victim into such a set

        Offending code:

        if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {

        Impact

        The authority can impose any consent-gated amendment on any grantee without a single vote, for example freezing vested tokens with an unlock rate of 0, raising option or repurchase prices, or removing milestones.

        Description

        Consent counts as given whenever totalVotingPower <= currentVotingPower*2. totalVotingPower is a snapshot of the set's members taken when the proposal was made (lines 572-574). If that snapshot is 0, the check passes with no votes at all. The check is never re-run against who is in the set when the amendment executes, and exactly 50% also passes despite the documented '>50%' rule. Also CWE-20: For grants in a set, consentCheck compares the voted dataHash with keccak256 of only the last 32 bytes of the raw msg.data. The function itself reads its arguments through the ABI decoder, which ignores extra trailing calldata. The authority can therefore pass any _grant and parameter value and append the approved 32-byte word at the end, and the privileged onlyController call on the allocation then runs with values that were never voted on. Also CWE-436: The authority supplies msg.data, which is untrusted with respect to grantee consent. The consent check hashes only the trailing 32-byte word of msg.data (line 146; proposals store the same slice at line 580). The ABI decoder reads the amendment value at fixed offset 0x24 and ignores any extra trailing calldata. So the authority can put an arbitrary value in the decoded slot and append the majority-approved word at the end, and the check still passes. Also CWE-190: voteOnMetavestAmendment (lines 589-607) accepts any _grant contract. It only checks that grantee() == msg.sender and never checks that the contract is an allocation in _setName, so the attacker sets the getGoverningPower() value. That value is added to proposal.currentVotingPower at line 606, and line 146 then computes currentVotingPower*2 with checked arithmetic. If the total is 2^255 or more, every call that goes through consentCheck panics and reverts. Also CWE-1023: For grants in a set, consentCheck compares only the last 32-byte word of msg.data (_data[_data.length - 32:]) against the proposal hash, which is also built from only the last word (line 580). Solidity's ABI decoder ignores extra calldata after the arguments. So the bytes the consent check reads are not the bytes that become the function arguments. Also CWE-345: Line 580 commits the majority proposal to keccak256 of only the last 32 raw bytes of the proposed calldata, and line 146 checks the live msg.data the same way. The real arguments are ABI-decoded from fixed offsets (bytes 4..68), and Solidity ignores extra trailing calldata. The hash therefore does not bind the values that actually execute, and the authority can supply any argument while appending the approved word as trailing bytes.

        Exploit scenario

        The authority calls createSet("evil") and then proposeMajorityMetavestAmendment("evil", updateMetavestUnlockRate.selector, abi.encodeWithSelector(sel, victim, 0)). The set is empty, so totalVotingPower is 0. It removes the victim's grant from its current set, if any, and calls addMetaVestToSet("evil", victim). It then calls updateMetavestUnlockRate(victim, 0). consentCheck finds the victim in "evil", sees isPending, evaluates 0 > 0 as false, matches the last-32-byte hash, and runs the amendment. The same happens without any set manipulation for a set of new token-option grants: the default govType is vested and they have 0 governing power until exercise, so any majority proposal for them passes as soon as it is made.

        Recommendation

        Reject proposals with totalVotingPower == 0 and require a strict majority (currentVotingPower*2 > totalVotingPower). Bind each proposal to a frozen member list or snapshot so grants added after the proposal cannot be amended under it, and do not let the authority change a grant's set membership while proposals that affect it are pending. Also CWE-20: Do not authorize by hashing a slice of raw msg.data. Store the full keccak256 of the exact intended calldata (or of abi.encode of the decoded parameters) in the proposal. In consentCheck, recompute the hash from the decoded arguments and also bind the msg.sig and the set. At minimum, require msg.data.length to equal the canonical ABI length for the function, compare against the full calldata, delete the majority proposal after it is executed, and enforce AMENDMENT_TIME_LIMIT at execution time. Also CWE-436: Bind consent to the decoded parameters rather than raw calldata. For example, store keccak256(abi.encode(selector, value)) in the proposal and recompute it inside each function from the decoded argument. Alternatively, require msg.data.length to equal the exact ABI length (4 + 64) before hashing. Also check in proposeMajorityMetavestAmendment that _callData[0:4] == _msgSig. Also CWE-190: In voteOnMetavestAmendment, only accept a _grant that is a member of sets[_setName] and was deployed by this controller's factories. Take voting power from that verified allocation, and cap the total so that currentVotingPower can never exceed totalVotingPower. Compare votes without the possibly overflowing multiplication, for example proposal.currentVotingPower <= proposal.totalVotingPower - proposal.currentVotingPower. Also fix the inverted re-proposal guard at line 568 so that expired or poisoned proposals can be replaced. Also CWE-1023: Bind the full calldata. Store keccak256(_callData) at proposal time and compare it against keccak256(msg.data). Better, store the decoded new value and require it to equal the executed argument. Also reject msg.data whose length differs from the expected ABI-encoded length. Clear the majority proposal after execution and check its expiry. Also CWE-345: Bind the commitment to the full decoded intent, not to raw trailing bytes. For example, store keccak256(abi.encode(<decoded argument(s)>)) at proposal time and recompute it inside each amending function from its decoded parameters. Alternatively, require msg.data.length to equal the exact expected ABI length and hash msg.data[36:] (everything after the selector and grant). Reject proposals whose _callData length differs from the canonical encoding.

        Vercel Security Review

        Trailing calldata bypasses majority approval of amendment parameters

        src/MetaVesTController.sol:146 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Majority consent authenticates only the calldata suffix.** - src/MetaVesTController.sol:146-148

        ```solidity title="src/MetaVesTController.sol:146-148"

        if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {

        revert MetaVesTController_AmendmentNeitherMutualNorMajorityConsented();

        }

        ```

        **2. Setters apply decoded arguments, not that suffix. Solidity permits trailing calldata: after a legitimate majority approval, malicious authority can change the actual unlock rate to zero while appending the approved word. The hash matches, but unlocking is frozen without consent. Other majority-protected setters share this bypass.** - src/MetaVesTController.sol:465-467

        ```solidity title="src/MetaVesTController.sol:465-467"

        ) external onlyAuthority conditionCheck consentCheck(_grant, msg.data) {

        _resetAmendmentParams(_grant, msg.sig);

        BaseAllocation(_grant).updateUnlockRate(_unlockRate);

        ```

        Exploit scenario

        Not specified.

        Recommendation

        Hash canonical decoded parameters rather than the caller-controlled suffix. Reject trailing calldata and bind approval to the actual parameter used by each setter.

      • Removing confirmed milestones is possible metavest-7 · 6 writeups High

        V12

        Completed milestone deletion corrupts lifecycle accounting

        src/MetaVesTController.sol:430 Predicted severity: Medium

        Root cause

        Neither the controller cancellation wrapper nor the concrete deletion implementation enforces the uncompleted-milestone precondition. Deleting a completed entry desynchronizes array-based award sums from cumulative vested/unlocked accounting.

        Impact

        Deleting a completed award can make termination or governing-power calculations revert through checked-arithmetic underflow. A consented cancellation can therefore become an accounting/liveness failure if a publicly confirmable milestone completes before execution; this is distinct from stranding an unconfirmed award's backing tokens.

        Description

        removeMetavestMilestone does not recheck whether the milestone has completed before forwarding deletion. The concrete allocation deletion function also checks only termination and index bounds, so it can delete a completed milestone. Completion has already credited the award to milestoneAwardTotal and possibly milestoneUnlockedTotal, but deletion leaves those credited totals unchanged while removing the award from the milestone array. Termination and governing-power calculations later combine the reduced array sum with the unchanged credited totals. This can arise when a milestone completes after a cancellation amendment was proposed and consented, before authority executes it.

        Pashov (Claude Opus 5.5 high)

        Removing a milestone permanently locks its tokens and corrupts termination accounting

        src/BaseAllocation.sol:243 Predicted severity: Medium

        Root cause

        Deletion without refunding the award or adjusting totals, and no check that the milestone is incomplete.

        Impact

        Milestone tokens are frozen forever in the allocation contract. Removing completed milestones can make terminate() or getAmountRepurchasable() revert, blocking termination and repurchase.

        Description

        removeMilestone just deletes the array element. The milestoneAward tokens transferred in for it are not returned, and every later accounting loop sums milestones[i].milestoneAward, which is now 0. No path returns them: terminate() recovers only total + current milestone awards - vested, and VestingAllocation/RTA have no sweep. Removing an already completed milestone is also allowed (despite the doc saying 'if not yet confirmed'). Its award stays in milestoneAwardTotal but is gone from milestonesAllocation, so terminate/getAmountRepurchasable can underflow and revert. The deleted slot also stays confirmable by anyone (no conditions).

        Exploit scenario

        Authority (with consent) removes an unconfirmed milestone worth 500 tokens. Later termination returns only the stream remainder, and the 500 tokens remain stuck in the VestingAllocation forever.

        Recommendation

        On removal of an incomplete milestone, transfer its award back to authority. Disallow removing completed milestones.

        Pashov (Codex GPT-6 Sol high)

        Removing a completed milestone corrupts recovery accounting

        src/BaseAllocation.sol:218 Predicted severity: Medium

        Root cause

        There is no completed-milestone guard or counter reconciliation before deletion.

        Impact

        Termination can underflow and revert permanently, while governing-power and funding totals disagree.

        Description

        removeMilestone deletes a completed award from the milestone array but leaves its credited milestoneAwardTotal and milestoneUnlockedTotal unchanged.

        Exploit scenario

        Fund a 100-token stream and a 100-token milestone, complete the milestone, vest 50 stream tokens, remove the milestone, and call VestingAllocation.terminate; it computes 100 - 150 and reverts.

        Recommendation

        Reject removal of completed milestones, or consistently settle the credited amounts and funded tokens before deletion.

        Devin Security (Deep)

        removeMilestone can delete a completed milestone, corrupting totals so termination and repurchase revert forever

        src/BaseAllocation.sol:243 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A grantee who front-runs a consented milestone removal by confirming the milestone first both keeps the award and makes the grant impossible to terminate, so the rest of the grant keeps vesting to them for good.

        ##### What's wrong

        This is a missing state check. removeMilestone zeroes the milestone struct without checking the complete flag. After a completed milestone is removed, milestoneAwardTotal still counts its award but the sum over milestones[] does not, and every function that subtracts one from the other underflows and reverts.

        ##### Who can do it

        Alice holds a grant from Acme Corp with a 1,000 token milestone whose condition list is empty or already satisfiable. Acme proposes removing that milestone and Alice consents, perhaps as part of a renegotiation. When Acme's removeMetavestMilestone transaction appears in the mempool, Alice sends confirmMilestone first (anyone may call it). The removal then lands on a completed milestone. The same state also arises by accident if any third party confirms the milestone between proposal and execution.

        - The authority has proposed removal and consent exists (or the set-wide consent bypasses reported in MetaVesTController.sol are used).

        - The milestone's conditions can be satisfied at that moment; empty conditionContracts, as used throughout the tests, always can.

        - For the termination revert, the removed award must be at least as large as the still unvested part of the stream, which holds for the test fixtures where milestoneAward equals tokenStreamTotal.

        ##### What they get

        Alice keeps the 1,000 token award, since milestoneAwardTotal already includes it, and Acme can never call terminate() on the grant because the recovery arithmetic underflows, so the remaining stream keeps vesting and unlocking to Alice. On a RestrictedTokenAward, getAmountRepurchasable reverts, so Acme can never repurchase. If the grant's govType is all, getGoverningPower reverts too, which makes proposeMajorityMetavestAmendment revert for every set containing the grant.

        ##### How it works

        1. The authority proposes and Alice consents to removeMetavestMilestone(grant, i) (MetaVesTController.sol:433-439).

        2. Alice calls confirmMilestone(i) (BaseAllocation.sol:218-238); lines 232-235 set complete and add the award to milestoneAwardTotal.

        3. The authority's removeMetavestMilestone executes; removeMilestone (BaseAllocation.sol:243-248) only checks the index and deletes the struct at line 246.

        4. VestingAllocation.terminate computes tokenStreamTotal + sum(milestones) - (linear vested + milestoneAwardTotal) + tokensWithdrawn (VestingAllocation.sol:86 via getVestedTokenAmount at 95-107); TokenOptionAllocation.terminate does the equivalent at TokenOptionAllocation.sol:156; RestrictedTokenAward.getAmountRepurchasable at RestrictedTokenAllocation.sol:184. With the removed award missing from the sum but present in milestoneAwardTotal, each underflows and reverts.

        Exploit scenario

        Not specified.

        Recommendation

        In removeMilestone revert when milestones[_milestoneIndex].complete is true or the award is already zero, or alternatively subtract the award from milestoneAwardTotal and milestoneUnlockedTotal when removing a completed milestone. Verify with a test that confirms a milestone, removes it, and asserts terminate() and getAmountRepurchasable() still work with correct amounts.

        Claude Security (Sonnet 5.5)

        removeMilestone zeroes the milestone but leaves its funded tokens stranded and breaks terminate/repurchase accounting

        src/BaseAllocation.sol:246 Predicted severity: Medium

        Root cause

        Vulnerable symbol: removeMilestone

        Preconditions: A funded milestone is removed through the controller

        Offending code:

        delete milestones[_milestoneIndex];

        Impact

        Permanent loss of the tokens funded for removed milestones in Vesting and RTA allocations, and possible bricking of terminate or repurchase for grants whose confirmed milestone was removed.

        Description

        The controller funds every milestone at creation (milestoneAward is part of _total) and documents that removing a milestone makes its tokens recoverable. The allocation only deletes the array entry. VestingAllocation.terminate and RestrictedTokenAward.getAmountRepurchasable sum milestones[i].milestoneAward, which now excludes the deleted award, so the funded tokens are not part of any recoverable amount. If the milestone was already confirmed, milestoneAwardTotal still includes the award while the sum does not, which skews or underflows the same expressions.

        Exploit scenario

        Authority and grantee agree to remove a 500-token milestone. After removeMetavestMilestone the 500 tokens stay in the VestingAllocation, and terminate() recovers only the remainder, so they are locked forever. If the removed milestone had been confirmed, terminate()/getAmountRepurchasable() can underflow and revert because vested includes an award that the sum no longer does.

        Recommendation

        Track funded and removed milestone awards explicitly (for example keep the award in a removedMilestoneTotal that terminate and repurchase include), refuse to remove completed milestones, and send the removed award back to the authority at removal time.

        Claude Security (Opus 5.5)

        terminate() adds tokensWithdrawn to the recovery amount, so termination either takes the grantee's vested tokens or reverts

        src/VestingAllocation.sol:86 Predicted severity: High

        Root cause

        Vulnerable symbol: terminate

        Preconditions: Grantee has withdrawn a nonzero amount before termination; Authority calls terminateMetavestVesting

        Offending code:

        tokensToRecover = allocation.tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() + tokensWithdrawn;

        Impact

        After any prior withdrawal, a routine termination confiscates vested tokens owed to the grantee, equal to the amount already withdrawn. Alternatively, a grantee can make their own grant impossible to terminate and keep vesting the unvested allocation.

        Description

        The contract balance is tokenStreamTotal + milestones - tokensWithdrawn, but the recovery amount is computed as total - vested + tokensWithdrawn. The unvested remainder should be total - vested. The withdrawn amount is effectively counted twice, and the result is sent to the authority by safeTransfer at line 88. Also CWE-191: removeMilestone (BaseAllocation.sol:246) deletes a milestone without checking complete. milestonesAllocation, the sum of current awards, drops, while milestoneAwardTotal, which is included in getVestedTokenAmount, keeps the deleted award. Once linear vesting is near full, T + milestonesAllocation - vested underflows and terminate reverts. The same applies to TokenOptionAllocation.sol:156.

        Exploit scenario

        Take T=1000 and vested=unlocked=600, after the grantee has withdrawn W=200, leaving a balance of 800. terminate() sends 1000-600+200=600 to the authority and leaves 200, while the grantee is still owed 600-200=400. The grantee loses 200 vested tokens. In general the leftover balance is V-2W, so the grantee always loses W. Conversely, once W > V/2 (for example, the grantee withdraws everything available, or front-runs terminateMetavestVesting with a withdraw), the transfer exceeds the balance and terminate reverts. The grantee keeps vesting, and the authority cannot pause vesting without the grantee's consent.

        Recommendation

        Recover exactly the unvested amount, tokensStreamTotal + milestonesAllocation - getVestedTokenAmount(), with no tokensWithdrawn term. Equivalently, recover balanceOf(this) - (vested - tokensWithdrawn). Also CWE-191: In removeMilestone, revert if milestones[_milestoneIndex].complete is true. Base recovery calculations on the actual balance rather than on recomputed totals.

      • The function proposeMajorityMetavestAmendment cannot identify expired proposals metavest-8 · 7 writeups High

        V12

        First majority proposal blocks all replacements

        src/MetaVesTController.sol:562 Predicted severity: Medium

        Root cause

        The replacement guard compares against creation time instead of expiration time, and the majority proposal state machine has no completion or cancellation transition that clears isPending.

        Impact

        A failed or expired first proposal can indefinitely disable subsequent majority-authorized amendments for that selector and set, including amendments needed to restore unlocking rates. Authority can restructure the set or move allocations to another consent track, so this is an amendment-path denial of service rather than an established permanent fund freeze.

        Description

        proposeMajorityMetavestAmendment rejects an existing pending proposal whenever the current timestamp is greater than the proposal's creation timestamp. This comparison does not use AMENDMENT_TIME_LIMIT, so rejected, unvoted, and expired proposals all block replacements at later timestamps. There is also no transition that clears a majority proposal after execution: _resetAmendmentParams deletes only the individual amendment mapping. As a result, the first proposal reserves its selector/set slot indefinitely. Changing its proposed parameters through a later majority proposal is impossible while the same slot remains in use.

        Pashov (Claude Opus 5.5 high)

        proposeMajorityMetavestAmendment pending check is inverted, permanently blocking new proposals and allowing live ones to be overwritten

        src/MetaVesTController.sol:562 Predicted severity: Medium

        Root cause

        Inverted/incorrect comparison, and pending state is never reset after execution or expiry.

        Impact

        Each function selector can receive only one majority amendment per set for the lifetime of the controller. If that proposal fails or expires, no new majority amendment can be proposed, which permanently disables the governance path for that set. Combined with the lack of reset after execution, the one approved proposal stays usable forever.

        Description

        The guard is if (isPending && block.timestamp > time) revert. time is the proposal timestamp and isPending is never cleared, so after the block where a proposal was made, every later proposal for that (msgSig, set) reverts forever. Within the same block, a pending proposal can be overwritten. The intended check was presumably 'pending and not expired' (block.timestamp < time + AMENDMENT_TIME_LIMIT).

        Exploit scenario

        Authority proposes updateMetavestVestingRate for set 'team'. It doesn't reach majority within the week. Any later proposeMajorityMetavestAmendment for that selector/set reverts with AmendmentAlreadyPending, so no rate amendment for the set is ever possible again.

        Recommendation

        Revert only if isPending && block.timestamp < time + AMENDMENT_TIME_LIMIT, and clear the proposal after successful execution.

        Pashov (Codex GPT-6 Sol high)

        A pending majority proposal blocks new proposals indefinitely

        src/MetaVesTController.sol:562 Predicted severity: Medium

        Root cause

        The already-pending guard compares block.timestamp > proposal.time rather than the expiration time or pending lifetime.

        Impact

        The authority cannot replace a rejected, stale, or already executed proposal for the same set and function in later blocks.

        Description

        Once a majority proposal exists, the proposal function reverts whenever current time is later than its creation timestamp, even after the intended expiration.

        Exploit scenario

        Propose once, wait one block, then try to propose a corrected rate amendment for the same set and selector; the call always reverts.

        Recommendation

        Permit replacement after expiry or consume the proposal on execution, and compare against time + AMENDMENT_TIME_LIMIT.

        Devin Security

        Inverted pending check blocks every new majority proposal after the first

        src/MetaVesTController.sol:567 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Once a majority proposal exists for a function and set, the authority can never propose a new one, which permanently freezes majority amendments for that function and set.

        ##### What's wrong

        This is an inverted condition. The comment says to revert if a proposal is pending and not expired. The code reverts when block.timestamp > time, which means "already started". Majority proposals are never cleared, so isPending stays true and every later proposal reverts. A new proposal is only accepted in the same block, where it silently overwrites the live one and erases its votes.

        ##### Who can do it

        The Acme authority proposes a majority amendment for the "engineering" set. It fails or expires. When the authority tries to propose a corrected version, the call reverts forever. No outside attacker is needed. This is a stuck state under normal use.

        - A prior majority proposal exists for that function selector and set name.

        ##### What they get

        The authority can no longer use majority consent for that function on that set. It would have to remove grants from the set and get individual consent instead. This affects availability only.

        ##### How it works

        1. The first proposal sets isPending = true and time = block.timestamp (MetaVesTController.sol:575-582).

        2. In any later block, isPending && block.timestamp > time is true, so the call reverts (MetaVesTController.sol:568-569).

        3. Nothing ever clears isPending.

        Exploit scenario

        Not specified.

        Recommendation

        Revert only when isPending && block.timestamp < time + AMENDMENT_TIME_LIMIT. Clear the majority proposal after it is executed. Add a test that a new proposal succeeds after the old one expires and fails while it is live.

        Devin Security (Deep)

        Majority consent can be forged with a fake grant, so authority can amend any grant without grantee consent

        src/MetaVesTController.sol:589 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        The authority, or anyone willing to help it, can pass any set-wide amendment vote with a throwaway contract that claims huge voting power, so the authority can change vesting rates, prices, milestones and stop times on any grant without the grantee ever agreeing.

        ##### What's wrong

        This is an authorization bypass in the consent system. voteOnMetavestAmendment accepts any _grant address, never checks that it belongs to the set being voted on or that this controller created it, and adds whatever voting power that address reports. addMetaVestToSet also accepts any address and moves a grant from one-to-one consent to set voting without the grantee's agreement. A passed set proposal is never cleared or expired in consentCheck, so it keeps authorizing the same change for any grant added to the set later.

        ##### Who can do it

        Alice, an engineer at Acme Corp, holds a vesting grant issued by Acme's multisig, which is the authority for this controller. Mallory controls the authority keys, or is any outsider who wants to help the authority. Mallory deploys a ten-line contract whose grantee() returns her address and whose getGoverningPower() returns 2^127. She can get the same effect with no custom code by calling the public VestingAllocationFactory.createAllocation with a huge cliff credit, which needs no tokens. The authority creates a set, adds Alice's grant to it, proposes a set amendment such as "set vesting rate to 0", and Mallory votes once with the fake grant.

        Conditions that must hold:

        - The voter controls an address whose grantee() returns the voter's address; no tokens and no real grant are needed.

        - A set proposal is pending for the target function selector and set name (the authority can create one at will, and only the authority benefits because only it can call the amending function).

        - The target grant is in a set (the authority can add any grant with addMetaVestToSet; no consent is required).

        ##### What they get

        The authority gains every power the consent system was meant to withhold. It can freeze Alice's vesting and unlocking by setting both rates to 0 and then terminate to claw back her unvested tokens, raise her option exercise price so the options are worthless, cut her restricted-token repurchase price to 1 wei before repurchasing, remove her milestones, or move her stop times. It can do this to every grant in this framework, one set at a time. It cannot touch grants under a different controller.

        ##### How it works

        1. The authority calls addMetaVestToSet("S", aliceGrant) (MetaVesTController.sol:667-671); nothing asks Alice.

        2. The authority calls proposeMajorityMetavestAmendment("S", updateMetavestVestingRate.selector, callData) (MetaVesTController.sol:562-584); totalVotingPower is the sum of the real members' power.

        3. Mallory calls voteOnMetavestAmendment(fakeGrant, "S", selector, true) (MetaVesTController.sol:589-608). Line 591 only checks fakeGrant.grantee() == msg.sender; line 595 reads fakeGrant.getGoverningPower() (2^127) and line 606 adds it to currentVotingPower. Nothing checks that fakeGrant is in set "S" or was created by this controller.

        4. The authority calls updateMetavestVestingRate(aliceGrant, 0). consentCheck (MetaVesTController.sol:141-150) sees Alice's grant in "S", finds totalVotingPower <= currentVotingPower * 2, matches the last 32 bytes of calldata to the proposal hash, and lets the call through.

        5. _resetAmendmentParams (MetaVesTController.sol:611-613) only clears the one-to-one proposal, and consentCheck never checks the proposal's age, so the same passed proposal keeps authorizing the same change for any grant the authority adds to "S" afterwards. The re-proposal guard at line 568 (block.timestamp > time) also means the proposal can never be replaced.

        Exploit scenario

        Not specified.

        Recommendation

        In voteOnMetavestAmendment, require that _grant is a member of sets[_setName] and, better, a grant this controller created (record created allocations in a mapping inside createMetavest and check it everywhere a _grant is accepted). Restrict addMetaVestToSet to controller-created grants and require the grantee's consent, or make set membership part of the grant terms at creation. In consentCheck, enforce time + AMENDMENT_TIME_LIMIT, snapshot the member list at proposal time so later additions cannot inherit a vote, and clear or mark the set proposal consumed once an amendment executes. Fix the re-proposal check at line 568 to compare against the expiry. Verify with a test where a non-member contract reporting huge getGoverningPower votes and the amending call still reverts with MetaVesTController_AmendmentNeitherMutualNorMajorityConsented, and a test where a grant added to the set after the vote cannot be amended.

        Claude Security (Sonnet 5.5)

        Amendment approvals never expire and are never consumed, and the proposal overwrite check is inverted

        src/MetaVesTController.sol:143 Predicted severity: Medium

        Root cause

        Vulnerable symbol: consentCheck

        Offending code:

        MajorityAmendmentProposal memory proposal = functionToSetMajorityProposal[msg.sig][set];

        Impact

        Stale consent is honored long after the voting window, and for grants that joined the set later. A one-time approval gives the authority a standing, reusable right to amend. The authority can add a victim's grant to the set (addMetaVestToSet) and reuse the old approval on it. Governance for that function and set is also permanently locked to the first proposal's hash.

        Description

        The README states that amendment proposals have a one-week expiry. In the set path consentCheck never checks the proposal time. _checkFunctionToTokenToAmendmentTime is used only in voteOnMetavestAmendment. _resetAmendmentParams clears only the individual-path mapping, so a set approval persists indefinitely. Also CWE-613: The majority path of consentCheck reads the proposal and checks only isPending, the vote counts and the hash. It never checks the AMENDMENT_TIME_LIMIT, which is enforced only inside voteOnMetavestAmendment. _resetAmendmentParams (line 612) deletes only functionToGranteeToAmendmentPending, never functionToSetMajorityProposal. The guard at line 568 (pending && block.timestamp > time) also makes a pending set proposal impossible to replace after its creation block. Also CWE-294: The majority branch of consentCheck loads the stored proposal and checks only isPending, voting power and the hash. It never compares proposal.time with AMENDMENT_TIME_LIMIT, and nothing clears the proposal after execution, because _resetAmendmentParams deletes only the per-grantee mapping. A single approval therefore acts as a permanent, reusable authorization token.

        Exploit scenario

        A set proposal is approved once. After the one-week window, and after governing power has shifted or new grants have been added to the set via addMetaVestToSet, the authority keeps calling the guarded functions for any member. Each call passes because isPending stays true and the stored votes and hash never change. The authority can repeat the call and apply it to grantees who never voted and were not in the original electorate. The same is true of individual consents, which carry no timestamp, despite the README's stated one-week expiry.

        Recommendation

        In consentCheck, require block.timestamp < proposal.time + AMENDMENT_TIME_LIMIT. Delete or consume the set proposal after use, or bind it to the set membership snapshot. Store a timestamp in AmendmentProposal for the individual path. Fix the guard in proposeMajorityMetavestAmendment to revert only while block.timestamp < time + AMENDMENT_TIME_LIMIT. Also CWE-613: Store and check an expiry in consentCheck. Delete or invalidate the set proposal after execution. Fix the replacement guard to compare against time + AMENDMENT_TIME_LIMIT, and clear isPending on expiry. Add an expiry timestamp to individual AmendmentProposals. Also CWE-294: Enforce block.timestamp < proposal.time + AMENDMENT_TIME_LIMIT in consentCheck for both the majority and per-grantee paths. Consume or clear the majority proposal (or track per-grant execution) after use. Fix the supersede condition in proposeMajorityMetavestAmendment so it reverts only while the proposal has not expired. Bind each approval to a proposal id or nonce.

        Claude Security (Opus 5.5)

        Majority consent passes with zero votes when the snapshot voting power is 0, and is not tied to current set membership

        src/MetaVesTController.sol:146 Predicted severity: High

        Root cause

        Vulnerable symbol: consentCheck

        Preconditions: Attacker is the authority (proposals and set management are onlyAuthority); The target set's governing power is 0 at proposal time, or the authority can move the victim into such a set

        Offending code:

        if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {

        Impact

        The authority can impose any consent-gated amendment on any grantee without a single vote, for example freezing vested tokens with an unlock rate of 0, raising option or repurchase prices, or removing milestones.

        Description

        Consent counts as given whenever totalVotingPower <= currentVotingPower*2. totalVotingPower is a snapshot of the set's members taken when the proposal was made (lines 572-574). If that snapshot is 0, the check passes with no votes at all. The check is never re-run against who is in the set when the amendment executes, and exactly 50% also passes despite the documented '>50%' rule. Also CWE-20: For grants in a set, consentCheck compares the voted dataHash with keccak256 of only the last 32 bytes of the raw msg.data. The function itself reads its arguments through the ABI decoder, which ignores extra trailing calldata. The authority can therefore pass any _grant and parameter value and append the approved 32-byte word at the end, and the privileged onlyController call on the allocation then runs with values that were never voted on. Also CWE-436: The authority supplies msg.data, which is untrusted with respect to grantee consent. The consent check hashes only the trailing 32-byte word of msg.data (line 146; proposals store the same slice at line 580). The ABI decoder reads the amendment value at fixed offset 0x24 and ignores any extra trailing calldata. So the authority can put an arbitrary value in the decoded slot and append the majority-approved word at the end, and the check still passes. Also CWE-190: voteOnMetavestAmendment (lines 589-607) accepts any _grant contract. It only checks that grantee() == msg.sender and never checks that the contract is an allocation in _setName, so the attacker sets the getGoverningPower() value. That value is added to proposal.currentVotingPower at line 606, and line 146 then computes currentVotingPower*2 with checked arithmetic. If the total is 2^255 or more, every call that goes through consentCheck panics and reverts. Also CWE-1023: For grants in a set, consentCheck compares only the last 32-byte word of msg.data (_data[_data.length - 32:]) against the proposal hash, which is also built from only the last word (line 580). Solidity's ABI decoder ignores extra calldata after the arguments. So the bytes the consent check reads are not the bytes that become the function arguments. Also CWE-345: Line 580 commits the majority proposal to keccak256 of only the last 32 raw bytes of the proposed calldata, and line 146 checks the live msg.data the same way. The real arguments are ABI-decoded from fixed offsets (bytes 4..68), and Solidity ignores extra trailing calldata. The hash therefore does not bind the values that actually execute, and the authority can supply any argument while appending the approved word as trailing bytes.

        Exploit scenario

        The authority calls createSet("evil") and then proposeMajorityMetavestAmendment("evil", updateMetavestUnlockRate.selector, abi.encodeWithSelector(sel, victim, 0)). The set is empty, so totalVotingPower is 0. It removes the victim's grant from its current set, if any, and calls addMetaVestToSet("evil", victim). It then calls updateMetavestUnlockRate(victim, 0). consentCheck finds the victim in "evil", sees isPending, evaluates 0 > 0 as false, matches the last-32-byte hash, and runs the amendment. The same happens without any set manipulation for a set of new token-option grants: the default govType is vested and they have 0 governing power until exercise, so any majority proposal for them passes as soon as it is made.

        Recommendation

        Reject proposals with totalVotingPower == 0 and require a strict majority (currentVotingPower*2 > totalVotingPower). Bind each proposal to a frozen member list or snapshot so grants added after the proposal cannot be amended under it, and do not let the authority change a grant's set membership while proposals that affect it are pending. Also CWE-20: Do not authorize by hashing a slice of raw msg.data. Store the full keccak256 of the exact intended calldata (or of abi.encode of the decoded parameters) in the proposal. In consentCheck, recompute the hash from the decoded arguments and also bind the msg.sig and the set. At minimum, require msg.data.length to equal the canonical ABI length for the function, compare against the full calldata, delete the majority proposal after it is executed, and enforce AMENDMENT_TIME_LIMIT at execution time. Also CWE-436: Bind consent to the decoded parameters rather than raw calldata. For example, store keccak256(abi.encode(selector, value)) in the proposal and recompute it inside each function from the decoded argument. Alternatively, require msg.data.length to equal the exact ABI length (4 + 64) before hashing. Also check in proposeMajorityMetavestAmendment that _callData[0:4] == _msgSig. Also CWE-190: In voteOnMetavestAmendment, only accept a _grant that is a member of sets[_setName] and was deployed by this controller's factories. Take voting power from that verified allocation, and cap the total so that currentVotingPower can never exceed totalVotingPower. Compare votes without the possibly overflowing multiplication, for example proposal.currentVotingPower <= proposal.totalVotingPower - proposal.currentVotingPower. Also fix the inverted re-proposal guard at line 568 so that expired or poisoned proposals can be replaced. Also CWE-1023: Bind the full calldata. Store keccak256(_callData) at proposal time and compare it against keccak256(msg.data). Better, store the decoded new value and require it to equal the executed argument. Also reject msg.data whose length differs from the expected ABI-encoded length. Clear the majority proposal after execution and check its expiry. Also CWE-345: Bind the commitment to the full decoded intent, not to raw trailing bytes. For example, store keccak256(abi.encode(<decoded argument(s)>)) at proposal time and recompute it inside each amending function from its decoded parameters. Alternatively, require msg.data.length to equal the exact expected ABI length and hash msg.data[36:] (everything after the selector and grant). Reject proposals whose _callData length differs from the canonical encoding.

      • The grantee cannot revoke consent to the amendment metavest-9 · 9 writeups Medium

        V12

        Rejecting amendments grants consent instead

        src/MetaVesTController.sol:185 Predicted severity: Medium

        Root cause

        consentToMetavestAmendment hardcodes the consent flag to true instead of storing _inFavor, conflating rejection and approval.

        Impact

        An authority can execute economic or transferability changes that the grantee explicitly rejected or attempted to revoke. For example, a proposed zero unlock rate can pass the consent gate after a false response and prevent further scheduled unlocking; execution still requires the authority role.

        Description

        consentToMetavestAmendment verifies that an amendment is pending and the caller is the allocation's current grantee, but always stores inFavor = true. The supplied _inFavor value is used only in the event and never controls the stored consent. Consequently, an initial rejection with _inFavor = false authorizes the amendment, and a later revocation leaves an existing authorization intact. The individual branch of consentCheck then accepts the proposed calldata because it reads that stored inFavor value. This permits an authority to apply a rejected amendment, subject to any separately configured conditions.

        Codex Security (GPT-6 Sol)

        Rejecting an amendment records approval and lets the authority execute it

        src/MetaVesTController.sol:191 Predicted severity: High

        Root cause

        The consent endpoint accepts a boolean response but writes inFavor=true unconditionally. Later amendment execution reads that stored value as approval, so a false response or attempted revocation has the opposite effect.

        Impact

        The authority can change price, vesting rate, unlock rate, transferability, milestone and governance terms over an affected grantee's express rejection.

        Description

        A grantee who rejects or revokes a proposed amendment inadvertently authorizes it because consentToMetavestAmendment stores true regardless of _inFavor.

        Exploit scenario

        Grantee _inFavor=false → unconditional inFavor=true → consentCheck → authority amendment

        Recommendation

        Store _inFavor exactly as supplied and test rejection and revocation before every individual-consent amendment.

        Pashov (Claude Opus 5.5 high)

        Individual consent can be redirected by front-running: consentToMetavestAmendment doesn't bind to the proposal content and ignores _inFavor

        src/MetaVesTController.sol:185 Predicted severity: Medium

        Root cause

        Consent is bound to (msgSig, grant) only, not to the proposal hash, and the _inFavor parameter is ignored.

        Impact

        Grantees end up consenting to amendments they never saw (e.g. vesting rate 0, a much higher exercise price, removal of milestones), and they cannot withdraw consent if authority delays or breaches.

        Description

        consentToMetavestAmendment sets inFavor = true whatever the _inFavor argument, so a grantee can never revoke consent, which contradicts the documented intent. It also doesn't take the dataHash being consented to. proposeMetavestAmendment silently overwrites any pending proposal. Authority can watch the mempool and replace a benign proposal with a malicious one just before the grantee's consent transaction is mined.

        Exploit scenario

        Authority proposes updateMetavestVestingRate(grant, sameRate*2). The grantee submits consentToMetavestAmendment. Authority front-runs with proposeMetavestAmendment(grant, sel, calldata for rate 0); the consent is applied to the new hash and authority executes it.

        Recommendation

        Store inFavor = _inFavor and require the grantee to pass the expected dataHash, verifying it matches the pending proposal.

        Pashov (Codex GPT-6 Sol high)

        Consent revocation is ignored

        src/MetaVesTController.sol:185 Predicted severity: Medium

        Root cause

        The function always assigns inFavor=true instead of _inFavor.

        Impact

        An unwanted authority amendment remains executable after the grantee revokes consent.

        Description

        A grantee calling consentToMetavestAmendment with false remains recorded as consenting.

        Exploit scenario

        Propose an amendment, obtain consent, have the grantee call false to revoke, then execute the same amendment.

        Recommendation

        Assign the supplied _inFavor value.

        Devin Security

        Grantee consent cannot be withdrawn because _inFavor is ignored

        src/MetaVesTController.sol:185 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A grantee who agreed to an amendment cannot take that consent back, so the authority can still carry out the change after the grantee tries to revoke it.

        ##### What's wrong

        This is a logic bug. consentToMetavestAmendment always writes inFavor = true no matter what _inFavor is. The emitted event still reports the value the grantee passed, so the logs look like the consent was revoked.

        ##### Who can do it

        Alice, a grantee at Acme, consents to a vesting-rate change. Acme then breaks a side agreement, so Alice calls consentToMetavestAmendment(grant, sig, false). The event shows false, but the stored value stays true. The Acme authority then executes the change.

        - The grant is not in any set, so it uses individual consent.

        - The grantee consented once before.

        ##### What they get

        The authority can apply the amendment that Alice tried to block. This defeats the documented purpose of the parameter. It affects only grants that have already given consent once.

        ##### How it works

        1. Alice calls consentToMetavestAmendment with _inFavor = false (MetaVesTController.sol:185).

        2. The function stores inFavor = true (MetaVesTController.sol:191).

        3. consentCheck sees inFavor == true and lets the authority's call through (MetaVesTController.sol:152-155).

        Exploit scenario

        Not specified.

        Recommendation

        Store _inFavor instead of true. Add a test where consent is given and then revoked, and the amendment call reverts.

        Devin Security (Deep)

        Grantee consent to an amendment cannot be revoked and never expires

        src/MetaVesTController.sol:182 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Once a grantee has consented to an amendment the authority can apply it at any later time, even after the grantee has tried to revoke, so a grantee cannot back out of a deal the authority is delaying or has broken.

        ##### What's wrong

        This is a logic bug in the consent flow. consentToMetavestAmendment ignores its _inFavor argument and always writes inFavor = true, and the mutual consent proposal has no timestamp, so consentCheck never applies the one week limit that the README and the function's own comment promise.

        ##### Who can do it

        Alice holds a grant from Acme Corp. Acme's authority proposes lowering her vesting rate as part of a deal, for example in exchange for a bonus milestone. Alice consents. Acme does not deliver the bonus, so Alice calls consentToMetavestAmendment again with _inFavor = false, sees the event report inFavor = false, and believes she has revoked. Months later Mallory, who controls the authority multisig, executes the rate cut.

        - Alice consented once to a specific proposal (function selector plus exact calldata).

        - The authority has not called proposeMetavestAmendment again for that selector and grant, which would reset the record.

        ##### What they get

        The authority can apply the consented change at any moment of its choosing. Because vesting and unlock amounts are recomputed from the current rate, a rate reduction executed long after consent also claws back tokens that vested in the meantime and were not withdrawn. The grantee's revocation is silently discarded and the emitted event misreports the stored state. The damage is limited to amendments the grantee consented to at some point.

        ##### How it works

        1. The authority calls proposeMetavestAmendment(grant, sig, callData) (MetaVesTController.sol:544-556); the AmendmentProposal struct (MetaVesTController.sol:46-50) has no time field.

        2. Alice calls consentToMetavestAmendment(grant, sig, true) (MetaVesTController.sol:185-193); line 191 sets inFavor = true.

        3. Alice calls it again with false; line 191 still writes true while line 192 emits inFavor = false.

        4. At any later time the authority calls the amending function; consentCheck (MetaVesTController.sol:152-155) checks only inFavor and dataHash, with no time check.

        Exploit scenario

        Not specified.

        Recommendation

        Store _inFavor as given (functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = _inFavor), add a proposal timestamp to AmendmentProposal and reject execution in consentCheck once block.timestamp exceeds time + AMENDMENT_TIME_LIMIT. Verify with tests: consent then revoke and assert the amending call reverts; consent, warp eight days, and assert the amending call reverts.

        Claude Security (Sonnet 5.5)

        consentToMetavestAmendment ignores the _inFavor argument, so consent can never be withheld or revoked while the event reports the opposite

        src/MetaVesTController.sol:191 Predicted severity: Medium

        Root cause

        Vulnerable symbol: consentToMetavestAmendment

        Preconditions: A pending amendment proposal exists for the grantee; The grantee calls with _inFavor=false

        Offending code:

        functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = true;

        Impact

        The documented ability for a grantee to revoke consent "should authority delay or breach agreement elsewhere" does not work. A grantee who calls it with false leaves or sets the consent flag to true while the AmendmentConsentUpdated(..., false) event tells grantees and off-chain monitors that consent was withdrawn. authority can then execute the amendment (vesting rate, unlock rate, price, stop times and so on) against the grantee's wishes.

        Description

        The user-supplied _inFavor is used only in the emitted event. The state write hard-codes true, so a grantee who calls with false to revoke or deny consent actually sets consent to true. Also CWE-20: The grantee-supplied boolean _inFavor is never used to set state. The function writes inFavor = true unconditionally and only echoes _inFavor in the event. A grantee who passes false to reject or revoke actually grants consent, and the event shows the opposite of the state. Also CWE-863: The grantee-supplied _inFavor flag is used only in the event. The stored authorization state is unconditionally set to true. Also CWE-345: consentToMetavestAmendment takes only (_grant, _msgSig, _inFavor) and sets inFavor on whatever AmendmentProposal is currently stored. proposeMetavestAmendment lets authority overwrite the stored dataHash at any time, so the consent commits to no particular content. Also CWE-367: consentToMetavestAmendment takes only (_grant, _msgSig, _inFavor) and sets inFavor on whatever proposal is currently stored. It does not take or verify the dataHash the grantee reviewed. proposeMetavestAmendment lets the authority overwrite the pending proposal at any time and stores only keccak256(_callData) without emitting the data.

        Exploit scenario

        The grantee consents, then authority breaches the off-chain agreement. The grantee calls consentToMetavestAmendment(grant, sig, false) to revoke. State remains inFavor = true, and the event shows false. authority calls the amendment function and consentCheck passes.

        Recommendation

        Write the parameter: functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = _inFavor;. Also CWE-20: Store the supplied value: functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = _inFavor;. Emit the grant or grantee consistently. Consider adding an expiry for single-grantee amendments. Also CWE-863: Set .inFavor = _inFavor. Add an expiry for individual proposals, and ideally bind the consent to the proposal hash. Also CWE-345: Make the consent commit to the content: consentToMetavestAmendment(_grant, _msgSig, bytes32 expectedDataHash, bool _inFavor) must require expectedDataHash == stored dataHash. Store the _inFavor argument (not constant true). Consider invalidating or adding a delay before an overwritten proposal can be consented to. Also CWE-367: Make consentToMetavestAmendment take the expected dataHash (or a proposal nonce) and revert if it differs from the stored value. Emit the full callData in the proposal event, and consider rejecting overwrites of a proposal that has already been consented.

        Claude Security (Opus 5.5)

        Grantee's _inFavor input is ignored; a rejection or revocation is recorded as consent

        src/MetaVesTController.sol:191 Predicted severity: Medium

        Root cause

        Vulnerable symbol: consentToMetavestAmendment

        Preconditions: The authority has a pending individual amendment proposal for the grant; The grantee calls the function with _inFavor = false to reject or revoke

        Offending code:

        functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = true;

        Impact

        Amendments the grantee explicitly rejected can be executed, and consent can never be revoked. Grantees cannot protect their vesting terms through the consent mechanism, and the misleading event hides this.

        Description

        The grantee's _inFavor argument is documented as letting the grantee revoke or refuse consent. The function never uses it and always writes inFavor = true, while the event still emits the caller's false value. A grantee who explicitly rejects an amendment therefore enables it. Also CWE-863: The grantee-supplied _inFavor flag is documented as letting a grantee refuse or later revoke consent. It is ignored, and inFavor is always set to true. consentCheck (line 153) then lets the authority run the amendment.

        Exploit scenario

        The authority proposes an unfavorable individual amendment, for example updateMetavestUnlockRate(grant, 0). The grantee calls consentToMetavestAmendment(grant, sel, false) to reject it, or to withdraw earlier consent. The contract stores inFavor = true, and the emitted event says false, so off-chain monitoring shows a rejection. The authority then calls updateMetavestUnlockRate(grant, 0), passes consentCheck at line 153, and freezes the grantee's unlocks.

        Recommendation

        Store the supplied value (functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = _inFavor). Also consider having the grantee pass the expected dataHash, so consent cannot be applied to a proposal that was swapped in front of their transaction. Also CWE-863: Store _inFavor as given: functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = _inFavor;.

        Vercel Security Review

        Rejecting or revoking an amendment records affirmative consent

        src/MetaVesTController.sol:191 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. A grantee's false decision is stored as true** - src/MetaVesTController.sol:191-192

        ```solidity title="src/MetaVesTController.sol:191-192"

        functionToGranteeToAmendmentPending[_msgSig][_grant].inFavor = true;

        emit MetaVesTController_AmendmentConsentUpdated(_msgSig, msg.sender, _inFavor);

        ```

        For a pending individual amendment, calling with _inFavor=false to reject or revoke consent still authorizes it, while emitting an event claiming the opposite.

        **2. Authority can execute the rejected amendment** - src/MetaVesTController.sol:152-155

        ```solidity title="src/MetaVesTController.sol:152-155"

        AmendmentProposal memory proposal = functionToGranteeToAmendmentPending[msg.sig][_grant];

        if (!proposal.inFavor || proposal.dataHash != keccak256(_data)) {

        revert MetaVesTController_AmendmentNeitherMutualNorMajorityConsented();

        }

        ```

        For grants outside sets, matching calldata now passes consentCheck despite explicit rejection. The authority can change prices, schedules, or transferability without the affected grantee's actual approval.

        Exploit scenario

        Not specified.

        Recommendation

        Assign proposal.inFavor = _inFavor and ensure emitted events reflect the stored decision. Cover initial rejection and true-to-false revocation before authority execution.

      • Incorrect calculation about voting power metavest-10 · 8 writeups Medium

        V12

        Arbitrary contracts can fabricate majority votes

        src/MetaVesTController.sol:589 Predicted severity: Medium

        Root cause

        Voting authenticates ownership through caller-selected self-reported metadata but never authenticates the allocation's membership in the proposal's electorate. Arbitrary external voting weight is consequently trusted.

        Impact

        An external account can fabricate sufficient voting power to pass any pending set proposal without consent from the affected set members. Execution remains authority-only, but the authority's majority-consent restriction no longer protects grantees against economic changes such as freezes or option-price increases.

        Description

        voteOnMetavestAmendment accepts a caller-selected _grant and checks its self-reported grantee, but does not check membership in _setName or registration with this controller. It then adds that address's self-reported getGoverningPower() to the named proposal. An ordinary allocation outside the set can therefore vote in its election, and an external account can instead supply a purpose-built contract returning that account as grantee and a chosen voting weight. Duplicate prevention only limits each supplied address to one affirmative vote. consentCheck trusts the resulting accumulated weight when authorizing amendments to actual set members.

        Codex Security (GPT-6 Sol)

        A grantee outside a set can approve amendments for that set

        src/MetaVesTController.sol:591 Predicted severity: Medium

        Root cause

        The proposal denominator is computed from set members, but voteOnMetavestAmendment credits power from any grant address whose reported grantee is msg.sender. No set-membership or controller-provenance check binds that grant to the proposal.

        Impact

        An outside grantee can forge set majority, but execution still requires an authority call against a pending proposal and may be constrained by DAO conditions.

        Description

        An outsider can add their grant's governing power to another set's majority proposal, allowing an amendment without the affected set's majority.

        Exploit scenario

        Caller-selected outside _grant → getGoverningPower → currentVotingPower for named set → consentCheck

        Recommendation

        Require _grant to be a registered member of _setName and bind eligibility and voting power to the proposal snapshot.

        Pashov (Claude Opus 5.5 high)

        Majority amendment votes accept any metavest, not just members of the set

        src/MetaVesTController.sol:589 Predicted severity: High

        Root cause

        Missing membership check: the set membership of _grant is never validated.

        Impact

        The majority-consent protection for set members can be bypassed. Authority (the party the consent mechanism constrains) can create an allocation with itself or a sybil as grantee, or deploy any contract returning grantee()=attacker and a huge getGoverningPower(), and vote. This pushes currentVotingPower*2 past totalVotingPower and lets authority unilaterally change rates, prices, transferability, or milestones for every member of the set.

        Description

        voteOnMetavestAmendment only checks that msg.sender is the grantee of _grant. It never checks that _grant is in sets[_setName]. Any grantee of any allocation created by this controller (or by any contract exposing grantee()/getGoverningPower()) can add its governing power to another set's proposal. totalVotingPower is snapshotted from set members only.

        Exploit scenario

        Set 'employees' has total power 1,000,000. Authority deploys a fake contract whose grantee() returns authority and getGoverningPower() returns 1e30, then calls voteOnMetavestAmendment(fake, 'employees', updateMetavestVestingRate.selector, true). Next it calls updateMetavestVestingRate(member, 0) for each member, freezing everyone's vesting.

        Recommendation

        Require _grant to be in sets[_setName], and snapshot each voter's power at proposal time, or cap total votes at the snapshot.

        Pashov (Codex GPT-6 Sol high)

        Out-of-set grants can vote on majority amendments

        src/MetaVesTController.sol:589 Predicted severity: High

        Root cause

        No set-membership check precedes the vote accounting.

        Impact

        An outsider can fabricate approval for amendments to real grantees. A forged vote of 2**255 also makes the majority multiplication overflow and blocks the proposal from execution.

        Description

        Voting checks ownership of _grant but never its membership in _setName; its governing power is added to that set's proposal.

        Exploit scenario

        Deploy a fake grant that reports attacker ownership and 51 governing-power units, then vote on a real set with total power 100; no member needs to vote. A value of 2**255 instead causes execution to revert on overflow.

        Recommendation

        Verify _grant belongs to sets[_setName] before counting its vote.

        Devin Security

        Majority amendment votes accept any contract as a voter, so the authority can fake grantee consent

        src/MetaVesTController.sol:589 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        The authority, or anyone helping it, can manufacture a fake majority vote and then change vesting rates, unlock rates, prices, or milestones for every grantee in a set without their real consent.

        ##### What's wrong

        This is a broken consent check. voteOnMetavestAmendment trusts whatever address the caller passes as _grant. It only asks that contract who its grantee is and how much voting power it has. It never checks that _grant is a real MetaVesT made by this controller or that it belongs to the set being voted on.

        ##### Who can do it

        Alice is a grantee at Acme Corp. Her vesting contract sits in the set "engineering" with other grantees. Mallory controls the Acme authority address and wants to cut Alice's unlock rate to zero. Mallory proposes a majority amendment for the set. She then deploys a tiny contract whose grantee() returns her own address and whose getGoverningPower() returns a huge number. She calls voteOnMetavestAmendment with that contract as _grant. The vote passes, and she calls updateMetavestUnlockRate for Alice.

        - Mallory holds the authority role on the controller, which is needed to propose and to execute the amendment.

        - The target MetaVesT is in a set. The authority can put any MetaVesT into a set at any time with addMetaVestToSet, which needs no grantee consent.

        - Anyone can cast the fake vote. Only the final execution needs the authority.

        ##### What they get

        Mallory skips the grantee consent that the contract is built to require. She can freeze Alice's vested tokens forever by setting the unlock rate to zero. She can raise the exercise price on Alice's vested options or lower the repurchase price on her restricted tokens. She can remove milestones. Termination alone cannot do these things, because termination keeps the vested tokens for the grantee. The damage reaches every grantee whose MetaVesT is in, or is added to, a set on this controller.

        ##### How it works

        1. The authority calls proposeMajorityMetavestAmendment, which stores the total voting power of the real set members (MetaVesTController.sol:571-582).

        2. The attacker calls voteOnMetavestAmendment with a fake _grant. The only identity check is BaseAllocation(_grant).grantee() != msg.sender, which the fake contract passes (MetaVesTController.sol:591).

        3. The function adds the fake contract's self-reported getGoverningPower() to currentVotingPower without checking set membership (MetaVesTController.sol:595-606).

        4. The authority calls a consent-gated function. consentCheck sees currentVotingPower*2 >= totalVotingPower and lets the call through (MetaVesTController.sol:146).

        Exploit scenario

        Not specified.

        Recommendation

        In voteOnMetavestAmendment, require that _grant is listed in sets[_setName] and that the controller deployed it (for example, keep a isMetavest mapping that the create functions fill). Do not let a single vote come from an address outside the set. Consider snapshotting each member's power when the proposal is made. Add a test that votes with a mock contract outside the set and confirm the vote reverts and the amendment call still fails consentCheck.

        Devin Security (Deep)

        Majority amendment votes accept any caller-supplied grant contract, so anyone can pass a set-wide proposal

        src/MetaVesTController.sol:589 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can push a pending set-wide amendment past its voting threshold by voting with a grant contract they deployed themselves, which lets the authority apply changes to every grant in the set without any real grantee consent.

        ##### What's wrong

        This is a missing resource ownership check. voteOnMetavestAmendment trusts the caller-supplied _grant address: it only checks that the contract's grantee() returns the caller and then adds whatever that contract's getGoverningPower() returns to the proposal. It never checks that _grant is a member of _setName, or that this controller created it.

        ##### Who can do it

        Acme Corp runs a controller; Alice, Bob and Carol hold grants in the set "eng". The authority proposes a set-wide amendment for "eng". Mallory, who controls Acme's authority multisig or simply wants to help it, deploys her own VestingAllocation through the public VestingAllocationFactory, naming herself grantee with an enormous vesting cliff, and votes with it. The proposal passes at once no matter how Alice, Bob and Carol vote.

        - A set-wide proposal is pending for the (function, set) pair, created by the authority.

        - The voter can deploy a contract, or holds any grant from any set or any other controller; no token balance is needed.

        - Applying the passed amendment still requires the authority role, so in practice the attacker is the authority or someone colluding with it.

        ##### What they get

        The authority can apply any amendable change to every grant in the set with zero genuine consent: vesting rate, unlock rate, exercise or repurchase price, stop times, milestone removal, transferability and governing power type. Because rates apply retroactively, setting the vesting rate to zero and then terminating lets Acme recover tokens that had already vested but were not withdrawn, and setting the repurchase price to 1 wei and terminating lets Acme buy back all unvested restricted tokens for nothing. Grantees in other sets, or of other controllers, can also vote on "eng" proposals.

        ##### How it works

        1. The authority calls proposeMajorityMetavestAmendment("eng", sig, data) (MetaVesTController.sol:562-584) and the total power of the real members is snapshotted.

        2. Mallory calls VestingAllocationFactory.createAllocation (VestingAllocationFactory.sol:9-24) with grantee = Mallory, any controller address, tokenStreamTotal and vestingCliffCredit near 2^128, and vestingStartTime 0; the VestingAllocation constructor (VestingAllocation.sol:23-26) only caps vestingRate, so getGoverningPower (VestingAllocation.sol:51-67) returns about 3.4e38. Any hand-written contract exposing grantee() and getGoverningPower() works too.

        3. Mallory calls voteOnMetavestAmendment(fake, "eng", sig, true) (MetaVesTController.sol:589-608). Line 591 passes because grantee() is Mallory, lines 592-594 pass because the proposal is pending and fresh, line 595 reads the huge power, and lines 604-606 add it to currentVotingPower.

        4. The authority calls the amending function; consentCheck (MetaVesTController.sol:146) sees totalVotingPower far below currentVotingPower*2 and allows it for every grant in "eng".

        Exploit scenario

        Not specified.

        Recommendation

        In voteOnMetavestAmendment require that _grant is an element of sets[_setName] (loop or maintain a membership mapping), and keep a mapping of allocations created by this controller so foreign contracts are rejected everywhere a _grant is accepted. Prefer snapshotting each member's power at proposal time rather than reading live power from a caller-supplied address. Verify with a test that deploys an allocation through the factory, votes with it on a set it does not belong to, and asserts the vote reverts.

        Claude Security (Opus 5.5)

        Majority consent passes with zero votes when the snapshot voting power is 0, and is not tied to current set membership

        src/MetaVesTController.sol:146 Predicted severity: High

        Root cause

        Vulnerable symbol: consentCheck

        Preconditions: Attacker is the authority (proposals and set management are onlyAuthority); The target set's governing power is 0 at proposal time, or the authority can move the victim into such a set

        Offending code:

        if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {

        Impact

        The authority can impose any consent-gated amendment on any grantee without a single vote, for example freezing vested tokens with an unlock rate of 0, raising option or repurchase prices, or removing milestones.

        Description

        Consent counts as given whenever totalVotingPower <= currentVotingPower*2. totalVotingPower is a snapshot of the set's members taken when the proposal was made (lines 572-574). If that snapshot is 0, the check passes with no votes at all. The check is never re-run against who is in the set when the amendment executes, and exactly 50% also passes despite the documented '>50%' rule. Also CWE-20: For grants in a set, consentCheck compares the voted dataHash with keccak256 of only the last 32 bytes of the raw msg.data. The function itself reads its arguments through the ABI decoder, which ignores extra trailing calldata. The authority can therefore pass any _grant and parameter value and append the approved 32-byte word at the end, and the privileged onlyController call on the allocation then runs with values that were never voted on. Also CWE-436: The authority supplies msg.data, which is untrusted with respect to grantee consent. The consent check hashes only the trailing 32-byte word of msg.data (line 146; proposals store the same slice at line 580). The ABI decoder reads the amendment value at fixed offset 0x24 and ignores any extra trailing calldata. So the authority can put an arbitrary value in the decoded slot and append the majority-approved word at the end, and the check still passes. Also CWE-190: voteOnMetavestAmendment (lines 589-607) accepts any _grant contract. It only checks that grantee() == msg.sender and never checks that the contract is an allocation in _setName, so the attacker sets the getGoverningPower() value. That value is added to proposal.currentVotingPower at line 606, and line 146 then computes currentVotingPower*2 with checked arithmetic. If the total is 2^255 or more, every call that goes through consentCheck panics and reverts. Also CWE-1023: For grants in a set, consentCheck compares only the last 32-byte word of msg.data (_data[_data.length - 32:]) against the proposal hash, which is also built from only the last word (line 580). Solidity's ABI decoder ignores extra calldata after the arguments. So the bytes the consent check reads are not the bytes that become the function arguments. Also CWE-345: Line 580 commits the majority proposal to keccak256 of only the last 32 raw bytes of the proposed calldata, and line 146 checks the live msg.data the same way. The real arguments are ABI-decoded from fixed offsets (bytes 4..68), and Solidity ignores extra trailing calldata. The hash therefore does not bind the values that actually execute, and the authority can supply any argument while appending the approved word as trailing bytes.

        Exploit scenario

        The authority calls createSet("evil") and then proposeMajorityMetavestAmendment("evil", updateMetavestUnlockRate.selector, abi.encodeWithSelector(sel, victim, 0)). The set is empty, so totalVotingPower is 0. It removes the victim's grant from its current set, if any, and calls addMetaVestToSet("evil", victim). It then calls updateMetavestUnlockRate(victim, 0). consentCheck finds the victim in "evil", sees isPending, evaluates 0 > 0 as false, matches the last-32-byte hash, and runs the amendment. The same happens without any set manipulation for a set of new token-option grants: the default govType is vested and they have 0 governing power until exercise, so any majority proposal for them passes as soon as it is made.

        Recommendation

        Reject proposals with totalVotingPower == 0 and require a strict majority (currentVotingPower*2 > totalVotingPower). Bind each proposal to a frozen member list or snapshot so grants added after the proposal cannot be amended under it, and do not let the authority change a grant's set membership while proposals that affect it are pending. Also CWE-20: Do not authorize by hashing a slice of raw msg.data. Store the full keccak256 of the exact intended calldata (or of abi.encode of the decoded parameters) in the proposal. In consentCheck, recompute the hash from the decoded arguments and also bind the msg.sig and the set. At minimum, require msg.data.length to equal the canonical ABI length for the function, compare against the full calldata, delete the majority proposal after it is executed, and enforce AMENDMENT_TIME_LIMIT at execution time. Also CWE-436: Bind consent to the decoded parameters rather than raw calldata. For example, store keccak256(abi.encode(selector, value)) in the proposal and recompute it inside each function from the decoded argument. Alternatively, require msg.data.length to equal the exact ABI length (4 + 64) before hashing. Also check in proposeMajorityMetavestAmendment that _callData[0:4] == _msgSig. Also CWE-190: In voteOnMetavestAmendment, only accept a _grant that is a member of sets[_setName] and was deployed by this controller's factories. Take voting power from that verified allocation, and cap the total so that currentVotingPower can never exceed totalVotingPower. Compare votes without the possibly overflowing multiplication, for example proposal.currentVotingPower <= proposal.totalVotingPower - proposal.currentVotingPower. Also fix the inverted re-proposal guard at line 568 so that expired or poisoned proposals can be replaced. Also CWE-1023: Bind the full calldata. Store keccak256(_callData) at proposal time and compare it against keccak256(msg.data). Better, store the decoded new value and require it to equal the executed argument. Also reject msg.data whose length differs from the expected ABI-encoded length. Clear the majority proposal after execution and check its expiry. Also CWE-345: Bind the commitment to the full decoded intent, not to raw trailing bytes. For example, store keccak256(abi.encode(<decoded argument(s)>)) at proposal time and recompute it inside each amending function from its decoded parameters. Alternatively, require msg.data.length to equal the exact expected ABI length and hash msg.data[36:] (everything after the selector and grant). Reject proposals whose _callData length differs from the canonical encoding.

        Vercel Security Review

        Arbitrary contracts can supply voting power for any set's amendments

        src/MetaVesTController.sol:591 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Untrusted grant supplies voter identity and weight** - src/MetaVesTController.sol:591-595

        ```solidity title="src/MetaVesTController.sol:591-594"

        if(BaseAllocation(_grant).grantee() != msg.sender) revert MetaVesTController_OnlyGrantee();

        if (!functionToSetMajorityProposal[_msgSig][_setName].isPending) revert MetaVesTController_NoPendingAmendment(_msgSig, _grant);

        if (!_checkFunctionToTokenToAmendmentTime(_msgSig, _setName))

        revert MetaVesTController_ProposedAmendmentExpired();

        ```

        Any outsider can supply a contract reporting themselves as grantee and fabricated governing power; neither set membership nor controller provenance is checked.

        **2. Fabricated weight becomes affirmative votes** - src/MetaVesTController.sol:604-607

        ```solidity title="src/MetaVesTController.sol:604-607"

        if (_inFavor) {

        proposal.voters.push(_grant);

        proposal.currentVotingPower += _callerPower;

        }

        ```

        **3. Forged majority authorizes amendments** - src/MetaVesTController.sol:146-148

        ```solidity title="src/MetaVesTController.sol:146-148"

        if (!proposal.isPending || proposal.totalVotingPower>proposal.currentVotingPower*2 || keccak256(_data[_data.length - 32:]) != proposal.dataHash ) {

        revert MetaVesTController_AmendmentNeitherMutualNorMajorityConsented();

        }

        ```

        For an authority-proposed amendment, outsiders can satisfy the consent gate without affected grantees' votes. Authority execution remains required, but the majority protection is defeated.

        Exploit scenario

        Not specified.

        Recommendation

        Before reading voting power, require that the grant is a registered allocation controlled by this controller and belongs to the proposal's set. Derive eligible voters and their voting weights from a proposal snapshot rather than caller-selected contracts.

      • RestrictedTokenAllocation lacks repurchase deadline check metavest-11 · 8 writeups Medium

        V12

        Repurchase rights never expire

        src/RestrictedTokenAllocation.sol:131 Predicted severity: Low

        Root cause

        shortStopDate is written by terminate() but never enforced by repurchaseTokens().

        Impact

        The authority retains a restricted-token purchase right beyond its configured deadline and can transfer assets after that right was supposed to expire. This is a bounded privileged lifecycle bypass, not evidence that an arbitrary external caller can repurchase.

        Description

        The constructor records shortStopDuration, and termination computes shortStopDate from that duration. Nevertheless, repurchaseTokens() checks only termination, nonzero amount, and the computed repurchasable amount. Neither this entrypoint nor its calculation reads the deadline. A terminated, funded award therefore accepts purchases arbitrarily later than its configured short-stop date. The checked expiry test never terminates its award, so its rejection exercises the pre-termination guard rather than the missing deadline defense.

        Codex Security (GPT-6 Sol)

        Authority can repurchase restricted tokens after the deadline

        src/RestrictedTokenAllocation.sol:134 Predicted severity: Medium

        Root cause

        Termination stores shortStopDate, but neither repurchaseTokens nor its eligibility getter reads that date. The authority's repurchase capability therefore persists indefinitely.

        Impact

        The deadline is a real time limit on an authority's economic power, but exploitation requires that privileged role and tokens still held by the allocation.

        Description

        An authority can exercise a restricted-award repurchase right after its configured short-stop period because repurchaseTokens never checks shortStopDate.

        Exploit scenario

        Termination records deadline → time passes → repurchaseTokens checks no time limit → authority receives grant tokens

        Recommendation

        Reject repurchases after shortStopDate and return zero eligible amount after expiry.

        Pashov (Claude Opus 5.5 high)

        RTA repurchase is not limited to the short-stop window

        src/RestrictedTokenAllocation.sol:134 Predicted severity: Low

        Root cause

        Missing block.timestamp <= shortStopDate check.

        Impact

        Authority can repurchase at any time after the agreed window, e.g. waiting for the token price to appreciate before paying the fixed repurchase price, contrary to the grant terms.

        Description

        shortStopDate is set in terminate() and documented as the deadline for repurchases (the controller even defines MetaVesTController_RepurchaseExpired), but repurchaseTokens never checks it.

        Exploit scenario

        Short stop is 90 days. Authority waits 2 years until the token is worth 50x the repurchase price, then repurchases.

        Recommendation

        Revert in repurchaseTokens if block.timestamp > shortStopDate.

        Pashov (Codex GPT-6 Sol high)

        Restricted-token repurchases ignore the deadline

        src/RestrictedTokenAllocation.sol:134 Predicted severity: High

        Root cause

        The repurchase guard checks termination and amount only.

        Impact

        Authority retains an indefinite repurchase right over restricted tokens.

        Description

        Termination stores shortStopDate, but repurchaseTokens does not check it.

        Exploit scenario

        Terminate, wait beyond shortStopDate, then repurchase a positive remaining amount.

        Recommendation

        Require block.timestamp <= shortStopDate.

        Devin Security

        The authority can repurchase restricted tokens more than once and with no deadline, taking the grantee's vested tokens

        src/RestrictedTokenAllocation.sol:134 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        After termination, the authority can call repurchase again and again to force-buy the grantee's vested tokens, not just the unvested ones, at any time.

        ##### What's wrong

        This is a missing state update. getAmountRepurchasable returns unvested tokens without subtracting tokensRepurchased. The cap therefore never shrinks after a repurchase. repurchaseTokens also never checks shortStopDate, so the repurchase window never closes.

        ##### Who can do it

        Alice, a grantee at Acme Corp, holds a restricted token award. Acme terminates her and 600 of her 1000 tokens have vested. Mallory, who controls the Acme authority, calls repurchaseTokens(400) once. She then calls it again for another 400. The cap is still 400, so the call passes and takes 400 of Alice's vested tokens.

        - Mallory holds the authority role.

        - The award is terminated.

        - Mallory pays the repurchase price for each call, and Alice has not yet withdrawn her vested tokens.

        ##### What they get

        Mallory force-buys Alice's vested tokens, which Alice owns outright. She pays the repurchase price instead of the market value. With the payment rounding bug in getPaymentAmount, the price can be close to zero. Alice's later withdraw call fails because the contract is empty. The damage reaches every restricted token grantee on the controller.

        ##### How it works

        1. terminate sets shortStopDate, but no function reads it (RestrictedTokenAllocation.sol:170).

        2. repurchaseTokens checks _amount against getAmountRepurchasable() (RestrictedTokenAllocation.sol:137).

        3. getAmountRepurchasable returns tokenStreamTotal + milestones - vested and ignores tokensRepurchased (RestrictedTokenAllocation.sol:184).

        4. Each call sends _amount tokens to the authority until the balance runs out (RestrictedTokenAllocation.sol:144).

        Exploit scenario

        Not specified.

        Recommendation

        Subtract tokensRepurchased in getAmountRepurchasable. Make repurchaseTokens revert when block.timestamp > shortStopDate. Add tests that call repurchaseTokens twice for the full unvested amount and once after the short stop date. Confirm both calls revert and the grantee can still withdraw all vested tokens.

        Devin Security (Deep)

        Repurchase deadline is stored but never checked

        src/RestrictedTokenAllocation.sol:168 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        The authority's right to repurchase tokens after termination never expires, even though the contract computes and stores a deadline and the controller documents one.

        ##### What's wrong

        This is dead state. terminate() sets shortStopDate, but repurchaseTokens and getAmountRepurchasable never read it.

        ##### Who can do it

        Acme Corp terminates Alice's restricted token award with a 30 day repurchase window. Two years later Mallory, controlling the authority multisig, repurchases at the old fixed price after the token's market price has risen.

        - The award is terminated.

        - The authority holds payment tokens.

        ##### What they get

        The authority keeps a perpetual option to buy the unvested tokens (and, through the repurchase limit bug in this file, the vested ones) at the fixed price, picking the moment the market is most favorable. The grantee's direct loss is limited because unvested tokens were never theirs to withdraw, but the documented window does not exist, and the test testFailRepurchaseTokensAfterExpiry passes only because the award in it was never terminated.

        ##### How it works

        1. terminate (RestrictedTokenAllocation.sol:161-173) stores shortStopDate at line 170.

        2. repurchaseTokens (RestrictedTokenAllocation.sol:134-147) checks only terminated, a non-zero amount and getAmountRepurchasable.

        3. No other function reads shortStopDate (declared at line 12).

        Exploit scenario

        Not specified.

        Recommendation

        Revert in repurchaseTokens when block.timestamp > shortStopDate, and define what happens to unrepurchased tokens after the window (release to grantee or recover to authority). Verify with a test that terminates, warps past the window, and asserts repurchase reverts.

        Claude Security (Sonnet 5.5)

        Repurchase deadline (shortStopDate) is never enforced, so the authority's repurchase right does not expire

        src/RestrictedTokenAllocation.sol:134 Predicted severity: Low

        Root cause

        Vulnerable symbol: repurchaseTokens

        Preconditions: Caller is the current authority; The award has been terminated

        Offending code:

        function repurchaseTokens(uint256 _amount) external onlyAuthority nonReentrant {

        Impact

        The authority keeps a permanent repurchase option at the fixed price after the agreed repurchase window ends. The grantee's counterparty can claw back restricted tokens long after the deadline, contrary to the documented term ("duration after termination during which restricted tokens can be repurchased"). The controller declares an unused MetaVesTController_RepurchaseExpired error and the test testFailRepurchaseTokensAfterExpiry shows the intended expiry.

        Description

        terminate() records shortStopDate = block.timestamp + shortStopDuration, but repurchaseTokens (onlyAuthority) never compares block.timestamp to it, and no other function reads it. The time-window authorization on the authority's repurchase power is missing.

        Exploit scenario

        The controller terminates the award with shortStopDuration = 30 days. The authority waits a year, approves the payment token, and calls repurchaseTokens(getAmountRepurchasable()). It succeeds because only the terminated flag is checked, so the authority repurchases at the original price after the window has closed.

        Recommendation

        In repurchaseTokens, revert when block.timestamp > shortStopDate. Make getAmountRepurchasable() return 0 after shortStopDate. Define what happens to unrepurchased tokens after expiry.

        Claude Security (Opus 5.5)

        Authority can repurchase without limit and after the deadline, taking the grantee's vested tokens

        src/RestrictedTokenAllocation.sol:137 Predicted severity: Medium

        Root cause

        Vulnerable symbol: repurchaseTokens

        Preconditions: Caller is the controller's authority; The authority terminates the RTA, which it can do on its own; Vested tokens remain in the contract because of the unlock schedule or because the grantee has not withdrawn

        Offending code:

        if (_amount > getAmountRepurchasable()) revert MetaVesT_MoreThanAvailable();

        Impact

        The grantee is forced to sell tokens that have already vested (lapsed) back to the authority at the repurchase price, which may be nominal. They permanently lose the vested allocation. The protocol says only unvested tokens are repurchasable and only within the short-stop window. This also gets around the grantee-consent model that protects other amendments.

        Description

        The only check on how much the authority may repurchase is _amount > getAmountRepurchasable(). getAmountRepurchasable() (line 184) returns tokenStreamTotal + milestones - vested, which stays fixed after termination. It never subtracts tokensRepurchased, and repurchaseTokens never compares against shortStopDate. The authority can therefore keep calling it to take tokens beyond the unvested remainder, at any time after termination.

        Exploit scenario

        An RTA has tokenStreamTotal 1000 and unlocks slowly. At termination 400 tokens are vested but still locked, so 600 can be repurchased. The authority calls terminateMetavestVesting, which needs no grantee consent. It then calls repurchaseTokens(600) to take the unvested tokens. It calls repurchaseTokens(400) next: the check still compares against 600, so this passes and takes the grantee's vested tokens at repurchasePrice. It can do this months after shortStopDate. The grantee's later withdraw() calls revert on the balance check at BaseAllocation.sol:275.

        Recommendation

        Return tokenStreamTotal + milestonesAllocation - getVestedTokenAmount() - tokensRepurchased from getAmountRepurchasable. In repurchaseTokens, revert with a RepurchaseExpired error when block.timestamp > shortStopDate.

      • Accumulation of vested or unlocked tokens metavest-12 · 4 writeups Medium

        V12

        Rate amendments retroactively invalidate accrued balances

        src/MetaVesTController.sol:458 Predicted severity: Medium

        Root cause

        Controller amendments integrate with rate setters that overwrite historical schedule inputs without preserving accrued accounting. Consumers then apply the replacement rate retrospectively to the original start time.

        Impact

        Ordinary consented rate reductions, including the advertised temporary zero-rate freeze, can make withdrawal and governance-power reads revert until a sufficiently compensating rate is restored. Vesting-rate reductions also erase accrued but unwithdrawn entitlement from subsequent termination accounting, so their effects exceed a prospective schedule change.

        Description

        The rate-update wrappers forward replacement rates without checkpointing accrued vesting or unlocking. The concrete setters simply overwrite the stored rate, and the allocation views multiply that rate by the entire elapsed interval since the original start time. Thus reducing a rate retroactively removes previously accrued entitlement rather than merely pausing or slowing future accrual. When grantee has already withdrawn tokens, a consented reduction can lower calculated vested or unlocked totals below tokensWithdrawn. The downstream withdrawable and governing-power calculations then revert on subtraction instead of preserving the accrued position.

        Pashov (Claude Opus 5.5 high)

        Vesting/unlock rate updates are applied retroactively from start time

        src/BaseAllocation.sol:193 Predicted severity: Medium

        Root cause

        No checkpointing of accrued vested/unlocked amounts when rates change.

        Impact

        Rate changes approved via the majority process can strip set members of tokens already vested. If amounts drop below tokensWithdrawn, withdraw/getGoverningPower revert on underflow, which also DoSes set governance loops. A 'temporary freeze' to 0 lets terminate() recover tokens that had already vested.

        Description

        The vested and unlocked amounts are computed as (now - startTime) * currentRate. Changing the rate via updateVestingRate/updateUnlockRate rewrites history: lowering the rate claws back already-vested tokens, and raising it instantly vests past periods. The controller docs describe a rate of 0 as a 'temporary freeze', but it actually zeroes all streamed vesting to date.

        Exploit scenario

        Grantee has 400 tokens vested by rate. Authority sets vestingRate to 0 ('temporary freeze') via majority consent, then terminates: vested becomes just the cliff/milestones and authority recovers the 400 tokens.

        Recommendation

        Checkpoint accrued amounts and reset the start time when updating rates.

        Pashov (Codex GPT-6 Sol high)

        Rate amendments retroactively erase vested or unlocked balances

        src/BaseAllocation.sol:190 Predicted severity: High

        Root cause

        Rate setters store only the new rate, while getters recompute all historical accrual from the original start time.

        Impact

        Previously earned rights can disappear; subtraction underflow blocks withdrawals, option exercise, and termination.

        Description

        Updating a rate replaces the lifetime rate applied from the original start time, so a reduction can make previously vested or unlocked amounts smaller than prior exercises or withdrawals.

        Exploit scenario

        After 100 tokens vest and 20 are exercised or withdrawn, amend vestingRate to zero; getAmountExercisable or getAmountWithdrawable reverts on 0 minus prior activity.

        Recommendation

        Checkpoint accrued vested and unlocked amounts at amendment time, then apply the new rate only prospectively.

        Devin Security (Deep)

        Vesting and unlock rate updates rewrite already accrued amounts and can make views revert

        src/BaseAllocation.sol:193 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Lowering a grant's vesting or unlock rate retroactively shrinks what has already vested or unlocked, which can claw back tokens the grantee had earned and can make withdraw and governing power reads revert for the grant and for its set.

        ##### What's wrong

        Rate changes are not checkpointed. updateVestingRate and updateUnlockRate overwrite the rate, and the amount functions recompute (now - start) * rate from scratch, so the new rate is applied to the whole past.

        ##### Who can do it

        Acme Corp's authority, with Alice's consent or without it via the consent bypasses reported in MetaVesTController.sol, sets Alice's vesting rate from 10 to 1 tokens per second a year into her grant.

        - A rate change executes (consent gated unless the bypasses are used).

        - For the revert case, Alice has already withdrawn more than the recomputed vested or unlocked amount.

        ##### What they get

        Acme can then terminate and recover tokens that had vested under the old rate but were not withdrawn. If Alice had already withdrawn more than the recomputed amount, getAmountWithdrawable and getGoverningPower underflow, so she cannot withdraw and any set-wide proposal over a set containing her grant reverts until the rate is raised again. The controller docstring calls a zero unlock rate a temporary freeze, but the code makes it a rollback.

        ##### How it works

        1. updateVestingRate (BaseAllocation.sol:193-197) or updateUnlockRate (BaseAllocation.sol:202-206) overwrites the stored rate.

        2. getVestedTokenAmount (VestingAllocation.sol:98-106, RestrictedTokenAllocation.sol:192-201) and getAmountExercisable (TokenOptionAllocation.sol:178-187) recompute elapsed * rate.

        3. getAmountWithdrawable (VestingAllocation.sol:128) subtracts tokensWithdrawn and underflows when the recomputed amount is smaller.

        4. proposeMajorityMetavestAmendment (MetaVesTController.sol:572-574) calls getGoverningPower on every member and reverts if any member underflows.

        Exploit scenario

        Not specified.

        Recommendation

        When a rate changes, checkpoint the amount accrued so far (store accrued and move the start time to now) so the new rate applies only going forward, and clamp subtractions of tokensWithdrawn to zero. Verify with a test that withdraws, lowers the rate, and asserts getAmountWithdrawable does not revert and previously accrued tokens are preserved.

    • Nibiru Go Nibiru Chain Cosmos modules. Tasks 10 V12 10/10 Codex Sec 7/10 Pashov Opus — Pashov GPT-6 — Devin 7/10 Devin (Deep) 8/10 Claude Sec 7/10 Claude Opus 7/10 Vercel 7/10

      Nibiru Chain Cosmos modules.

      Read the audit report
      • EVM base fee is set to 1 wei instead of 1e12 wei nibiru-1 · 3 writeups Critical

        V12

        Execution and debit use different base-fee scales

        x/evm/keeper/vm_config.go:30 Predicted severity: Informational

        Root cause

        A native-denomination base-fee getter is used directly at wei-denominated EVM pricing boundaries, while the ante debit path converts it. There is no shared, consistently scaled base-fee value for effective-fee calculation and message construction.

        Impact

        The source establishes inconsistent financial pricing across ante and execution, but the exact delivered dynamic-transaction settlement is unresolved because the configured geth fork's Transaction.AsMessage implementation is absent. The specific missing fact is the effective price that this fork returns for a signed dynamic transaction with these inputs; repository-wide caller searches, the local JSON producer, and dependency-cache searches were inspected, but no fork implementation or runtime execution was available.

        Description

        GetEVMConfig copies GetBaseFee(ctx) directly into the EVM configuration, although that getter returns the native-denomination value 1. In contrast, VerifyFee converts the same value to 10^12 wei before computing the effective fee. ApplyEvmTx supplies the unconverted configuration value to AsMessage, and NewEVM also supplies it as the VM block base fee. The local JSON-message producer demonstrates the same pricing discrepancy explicitly: with fee cap 10^12 and tip 1, its effective message price is 2, whereas DynamicFeeTx.EffectiveGasPriceWei(10^12) returns 10^12. Consequently the debit calculation and the execution/refund price are derived from different base-fee scales, independently of the missing conversion of the final refund amount.

        Codex Security (GPT-6 Sol)

        EVM BASEFEE and RPC block base fee expose native units as wei

        x/evm/keeper/vm_config.go:30 Predicted severity: Medium

        Root cause

        GetBaseFee returns a native micronibi amount, but EVM BlockContext and Ethereum RPC publish it in wei-denominated base-fee fields without conversion.

        Impact

        Public EVM fee values understate the actual chain base fee by 10^12, affecting contract and client fee decisions; direct loss depends on their use of those values.

        Description

        EVM block context and Ethereum RPC expose a 1-micronibi base fee as 1 wei instead of 10^12 wei, misleading contract fee logic and clients.

        Exploit scenario

        GetBaseFee returns a native micronibi amount, but EVM BlockContext and Ethereum RPC publish it in wei-denominated base-fee fields without conversion.

        Recommendation

        Convert native base fee to wei before passing it to EVM BlockContext and Ethereum RPC responses.

        Devin Security (Deep)

        EVM gas refund multiplies leftover gas by the wei gas price but pays it out in unibi, letting any EVM sender drain the fee collector

        x/evm/keeper/gas_fees.go:41 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who can send an Ethereum style transaction on the chain can get paid up to a trillion times more than the fee they paid, taking every coin held by the fee collector account, which holds all transaction fees of the block and, once a day, the whole day's staking rewards.

        ##### What's wrong

        This is a unit mismatch bug in the EVM gas refund. The ante handler charges the sender in unibi after converting the wei fee with WeiToNative (dividing by 10^12), but RefundGas multiplies the leftover gas by the raw wei gas price and hands that number out as unibi coins from the fee collector, with no conversion and no cap at what the sender actually paid.

        ##### Who can do it

        Alice runs a validator for the Acme chain and Bob delegates to her. Mallory holds an ordinary Ethereum style key with about one NIBI on the chain. She signs one plain EVM transfer to herself with a gas limit of 200,000 and a gas price of 1,000,000 wei, wraps it in the normal ExtensionOptionsEthereumTx envelope, and broadcasts it.

        - Mallory needs any funded account that can sign an Ethereum transaction; no registration or approval is involved.

        - The fee collector module account must hold coins at the time the transaction runs, which it does during every block that contains fee paying transactions and during the daily inflation block.

        - Mallory picks a gas price so the refund matches the fee collector balance, which she can read from the public bank balance query.

        ##### What they get

        Mallory pays 0.2 NIBI in fees and receives 100,000 NIBI from the fee collector in the same transaction, because the 100,000 units of leftover gas are multiplied by 1,000,000 wei and paid as 10^11 unibi. She can repeat this every block to take all fees paid by every other user before the distribution module hands them to validators and delegators. Once a day, the inflation module mints the entire daily staking reward into the fee collector in the epoch block, and that full amount is exposed to her in that block. Alice and Bob lose the staking income they were owed, and so does every other validator and delegator on the chain. A legitimate user who sets a sane gas price of 10^12 wei is also hurt: the oversized refund fails for lack of fee collector funds and the transaction errors, so correct transactions with leftover gas are rejected.

        ##### How it works

        1. Mallory's transaction enters the EVM ante chain selected in app/ante.go and passes CanTransferDecorator in app/evmante/evmante_can_transfer.go:47-63, whose base fee check compares a wei gas fee cap against a micronibi base fee of 1, so any gas price of at least 1 wei passes.

        2. AnteDecEthGasConsume in app/evmante/evmante_gas_consume.go:103-110 calls VerifyFee in x/evm/keeper/gas_fees.go:188-195, which computes the charge as WeiToNative(gas * max(gasPrice, 10^12)), so Mallory pays 200,000 unibi.

        3. EthereumTx in x/evm/keeper/msg_server.go:31-45 runs ApplyEvmTx, which builds the core message with the raw wei gas price at line 58 and executes the transfer; ApplyEvmMsg reports gas used as 50% of the limit (100,000) because of the minimum gas multiplier, leaving 100,000 gas to refund at lines 110-113.

        4. RefundGas in x/evm/keeper/gas_fees.go:48-60 computes 100,000 * 1,000,000 and sends that many unibi from FeeCollectorName to Mallory's address with SendCoinsFromModuleToAccount, never converting from wei and never comparing against the 200,000 unibi she paid.

        5. The fee collector holds all fees of the block until the next BeginBlock of the distribution module, and AllocatePolynomialInflation in x/inflation/keeper/inflation.go:81-88 also deposits the daily staking inflation there, so this balance is what Mallory drains.

        Exploit scenario

        Not specified.

        Recommendation

        Make the refund use the same units and the same price as the charge. In RefundGas, compute the leftover amount in wei using the effective gas price that VerifyFee charged (max(gasPrice, baseFeeWei) for legacy and access list transactions, the EIP-1559 effective price for dynamic fee transactions), then convert with evm.WeiToNative before building the sdk.Coin. Also pass the amount deducted in the ante handler (or recompute it with VerifyFee) into ApplyEvmTx and cap the refund at that amount so the fee collector can never pay out more than the sender paid in for that transaction. Pass a wei base fee (evm.NativeToWei(baseFee)) into tx.AsMessage so msg.GasPrice() is computed in one consistent unit. To check the fix: write a keeper test that funds the fee collector with 1,000,000 unibi, sends a plain transfer with a 200,000 gas limit and a 1,000,000 wei gas price, and asserts the sender's balance after the transaction is strictly lower than before and the fee collector balance did not decrease by more than the fee charged. Add a second test with a 10^12 wei gas price asserting the refund equals leftover gas in unibi and the transaction succeeds.

      • Remaining EVM gas refund is created in wei instead of unibi, causing excessive refunds nibiru-2 · 7 writeups Critical

        V12

        Wei refunds spend native fee-collector balances

        x/evm/keeper/gas_fees.go:41 Predicted severity: Critical

        Root cause

        RefundGas treats the wei-priced refund product as a native-denomination amount, whereas VerifyFee explicitly converts the debit. Low declared legacy prices remain reachable because effective-fee and mempool validation apply a base-fee floor while the declared-cap check uses the unscaled native base fee.

        Impact

        The source-derived small-price path permits a sender to withdraw more native coins from the shared fee collector than its own ante deduction, conditional on existing collector funds. At conventional wei prices, the same mismatch instead requests enormously inflated refunds and returns an insufficient-funds error when the collector cannot cover them; it must not be described as a successful withdrawal in that case.

        Description

        VerifyFee converts the effective full gas-limit fee from wei to native coins, but RefundGas constructs native coins directly from leftoverGas * msg.GasPrice() without WeiToNative. The legacy transaction adapter passes its wei-denominated price into the Ethereum transaction, and ApplyEvmTx obtains the refund message with AsMessage; repository execution tests use price 1 and separately pre-fund native fee-collector coins to support these refunds. A particularly important reachable case is a small positive legacy price: fee verification and the mempool check raise the effective price to the native base-fee equivalent, while the transfer precheck only compares the declared fee cap against the unconverted base-fee value 1. For a zero-value, empty-data call with gas limit 50,000 and legacy price 3, the shown execution accounting yields gas used 25,000, an ante deduction of 50,000 native units, and a requested refund of 75,000 native units. This is a source-derived reproduction calculation, not an executed test; it succeeds only when the fee collector has sufficient additional coins and the remaining transaction checks succeed.

        Codex Security (GPT-6 Sol)

        EVM gas refund uses wei amount as native coin units

        x/evm/keeper/gas_fees.go:47 Predicted severity: High

        Root cause

        RefundGas multiplies leftover gas by wei GasPrice and pays it as native denomination, while VerifyFee deducts converted native amount.

        Impact

        An EVM sender can request a leftover-gas refund in wei that is paid as native units, potentially draining the fee collector when it has sufficient funds. Fee collector balance gates the excess refund; dependency AsMessage price semantics need verification.

        Description

        An EVM sender can request a leftover-gas refund in wei that is paid as native units, potentially draining the fee collector when it has sufficient funds.

        Exploit scenario

        RefundGas multiplies leftover gas by wei GasPrice and pays it as native denomination, while VerifyFee deducts converted native amount.

        Recommendation

        Convert the wei refund amount to the native denomination before sending coins from the fee collector.

        Devin Security

        EVM gas refund pays wei-denominated amounts in micronibi, over-refunding by 10^12 and draining the fee collector

        x/evm/keeper/gas_fees.go:41 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who can send an Ethereum transaction can receive a gas refund about one trillion times larger than the fee they paid, and so take the gas fees other users paid earlier in the same block.

        ##### What's wrong

        This is a unit-mismatch bug in fee accounting. The ante handler charges the fee in micronibi (wei divided by 10^12). RefundGas multiplies leftover gas by the transaction gas price in wei and pays that number out as micronibi, with no conversion.

        ##### Who can do it

        Alice and many other users send transactions in block N, and their fees collect in the fee collector account. Mallory has a normal funded account. She sends one EVM transaction with a gas limit of a few million, a gas price of 10^12 wei (1 micronibi per gas, the base fee), and a simple transfer that uses 21,000 gas. She pays about her gas limit in micronibi. She is refunded the leftover gas times 10^12 micronibi, capped only by what the fee collector holds. She can lower the gas price or gas limit so the refund fits the current balance exactly.

        - Mallory has any funded account and can submit an Ethereum transaction.

        - The fee collector holds fees from earlier transactions in the same block.

        - The deployed code predates the upstream fix that converts the refund with WeiToNative (Nibiru PR #2076).

        ##### What they get

        Mallory takes the NIBI fees that other users paid in the block. That money was meant for validators and stakers. After the fee collector is empty, later EVM transactions in the block fail when their refund cannot be paid, so honest users lose their fee and their transaction. She can repeat this in every block.

        ##### How it works

        1. The ante handler charges WeiToNative(EffectiveFeeWei) micronibi through VerifyFee and DeductTxCostsFromUserBalance in x/evm/keeper/gas_fees.go:188-195.

        2. ApplyEvmTx computes refundGas = msg.Gas() - evmResp.GasUsed and calls RefundGas(ctx, msg, refundGas, evm.EVMBankDenom) in x/evm/keeper/msg_server.go:110-114.

        3. RefundGas computes remaining = leftoverGas * msg.GasPrice(), where msg.GasPrice() is in wei, in x/evm/keeper/gas_fees.go:48.

        4. RefundGas builds coins of remaining in the micronibi denom and sends them from the fee collector to the sender in x/evm/keeper/gas_fees.go:56-60.

        Exploit scenario

        Not specified.

        Recommendation

        Compute the refund in wei with the effective gas price, then convert it with evm.WeiToNative before building micronibi coins, as upstream Nibiru did in PR #2076. Add a unit test that sends a transaction with gas price 10^12 wei and a large unused gas limit. The test should assert that the sender's balance after the transaction is never higher than before minus the value sent, and that the refund equals WeiToNative(leftoverGas * effectiveGasPriceWei).

        Devin Security (Deep)

        RefundGas computes the gas refund in wei but pays it in micronibi, overpaying by 10^12

        x/evm/keeper/gas_fees.go:47 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Unused-gas refunds are paid out of the fee collector at a trillion times the correct amount, which lets a sender who gets a low-gas-price transaction included take the block's staking rewards, and otherwise makes every EVM transaction with leftover gas fail.

        ##### What's wrong

        This is a unit-conversion error. The EVM ante handler charges the sender WeiToNative(gasPrice_wei * gasLimit) micronibi. ApplyEvmTx later refunds leftoverGas * msg.GasPrice() where the gas price is in wei, but the result is used directly as a micronibi coin amount without dividing by 10^12.

        ##### Who can do it

        Mallory, a user whose Ethereum transaction gets into a block. On a node whose minimum-gas-prices is zero, or when Mallory is herself a validator proposing the block, a gas price of a few thousand wei is accepted.

        - Mallory signs an Ethereum tx with gas limit 1,000,000, gas price P wei, and a cheap call that uses ~21,000 gas.

        - The tx must pass CheckTx on the proposing validator; MempoolGasPriceDecorator skips the gas-price check when the node's min gas price is zero and is never applied in DeliverTx.

        - If every proposer enforces a min gas price of 1 micronibi per gas, the refund becomes astronomically large, the bank transfer fails, and the transaction fails instead (see What they get).

        ##### What they get

        Mallory pays WeiToNative(P * 1,000,000) micronibi, which rounds to zero for P below 10^6 wei. She is refunded 979,000 * P micronibi from the fee collector. With P tuned to the fee collector's balance (the current block's staking inflation plus fees), she takes all of it, every block, at no cost. This steals rewards from all validators and delegators. If proposers do enforce a minimum gas price (P ≥ 10^12 wei), the computed refund is at least 10^12 micronibi per leftover gas unit, the fee collector cannot pay it, and ApplyEvmTx returns an error, so every EVM transaction that does not use its exact gas limit fails. This is critical if any proposer accepts gas prices below one micronibi per gas.

        ##### How it works

        1. AnteDecEthGasConsume calls VerifyFee, which charges WeiToNative(EffectiveFeeWei) micronibi (app/evmante/evmante_gas_consume.go:103-110, x/evm/keeper/gas_fees.go:188-195).

        2. ApplyEvmTx computes refundGas = msg.Gas() - gasUsed and calls RefundGas (x/evm/keeper/msg_server.go:109-116).

        3. RefundGas multiplies leftoverGas by msg.GasPrice() (wei per gas) and builds sdk.NewCoin(denom, remaining) in the EVM denom without converting wei to micronibi (x/evm/keeper/gas_fees.go:47-56).

        4. The coin is sent from the fee collector to the sender (x/evm/keeper/gas_fees.go:60); the amount is 10^12 times what the sender was charged per gas.

        5. The existing tests fund the fee collector with 1,000,000 micronibi to make a 1-wei gas price transaction pass, which shows the mismatch (x/evm/keeper/msg_ethereum_tx_test.go:35-43).

        Exploit scenario

        Not specified.

        Recommendation

        Convert the refund to the native unit: compute leftoverWei = leftoverGas * weiPerGas and refund evm.WeiToNative(leftoverWei) micronibi (matching VerifyFee). Also cap the refund at the fee actually collected for the message. Verify with a test using a realistic gas price of 10^12 wei per gas: the sender's balance after the tx must equal start minus gasUsed micronibi, and the fee collector must not be drained.

        Claude Security (Sonnet 5.5)

        RefundGas credits leftover gas at the raw wei gas price as unibi (10^12x unit error) from the fee collector

        x/evm/keeper/gas_fees.go:48 Predicted severity: High

        Root cause

        Vulnerable symbol: Keeper.RefundGas

        Preconditions: Any account able to send an EVM tx; For large payouts, tx inclusion in the epoch-end block (epoch start times are deterministic)

        Offending code:

        remaining := new(big.Int).Mul(new(big.Int).SetUint64(leftoverGas), msg.GasPrice())

        Impact

        Theft of fee-collector funds (all fees accumulated earlier in the block, and the daily staking inflation at epoch boundaries) from stakers and validators. Honest users who set a gas price above 1 wei (for example 1 gwei) see their txs with leftover gas fail with a refund error after fees are already paid.

        Description

        The ante handler charges max(gasPrice, 1e12 wei) per gas converted to unibi (VerifyFee/WeiToNative), but RefundGas multiplies leftover gas by msg.GasPrice() in wei and pays that number directly as unibi from the fee collector module account. The two paths use different units and different effective prices.

        Exploit scenario

        Attacker sends a DynamicFeeTx (or legacy tx) with gasLimit 100000, feeCap >= tip+1e12, and tip = P wei where P is chosen so that 50000*P unibi is just below the fee collector balance. The ante charges about 100000 unibi (gas*1 unibi) but RefundGas pays 50000*P unibi. At the daily epoch-end block the x/inflation hook has just moved the staking-reward allocation into the fee collector (distribution BeginBlocker already ran earlier in that block, see app/keepers.go orderedModuleNames), so the whole allocation is available. A ladder of txs with decreasing P in that block captures most of it; in ordinary blocks the attacker takes all fees collected before their tx.

        Recommendation

        Convert the refund to native units and use the same effective price as the ante charge: refund = leftoverGas * WeiToNative(max(msg.GasPrice(), NativeToWei(baseFee))) (or better, record the charged amount and refund pro rata). Add a test that charge minus refund equals gasUsed*price for prices other than 1 wei.

        Claude Security (Opus 5.5)

        Gas refund pays leftoverGas x gasPrice(wei) as unibi while the ante handler charges in unibi via wei->native conversion: free txs and fee-collector theft

        x/evm/keeper/gas_fees.go:48 Predicted severity: High

        Root cause

        Vulnerable symbol: Keeper.RefundGas

        Preconditions: Fee collector holds fees from earlier txs in the block

        Offending code:

        remaining := new(big.Int).Mul(new(big.Int).SetUint64(leftoverGas), msg.GasPrice())

        Impact

        Any user can steal the per-block transaction fees owed to validators and delegators and pay nothing for EVM execution. Honest txs priced in real wei fail.

        Description

        The EVM ante handler charges WeiToNative(gasLimit * max(P_wei, 1e12)) unibi. That is gasLimit unibi for any P below 1e12. ApplyEvmTx then refunds leftoverGas * msg.GasPrice() from the fee collector, where msg.GasPrice() is the user-chosen wei price P, but the product is paid out as unibi with no unit conversion.

        Exploit scenario

        The attacker sends a legacy EVM tx with gasLimit 1,000,000 and gasPrice P = 1000 wei. P passes the ante check P >= 1. The ante charges 1,000,000 unibi. Execution uses 21k gas, and the 50% min-gas multiplier sets gasUsed to 500k, so leftover is 500k. RefundGas sends 500k*1000 = 5e8 unibi from the fee collector, for a net profit of about 499 NIBI. P is tuned so the refund stays below the fee collector's balance (all fees collected earlier in the block). With P = 2 every transaction is free. Honest wallets that sign with realistic wei prices (for example 1 gwei) hit refunds the fee collector cannot cover, so their txs fail after paying fees.

        Recommendation

        Compute the refund in the same units and with the same effective price as the fee deduction: refund = WeiToNative(leftoverGas * effectiveGasPriceWei), where effectiveGasPriceWei = max(msg.GasPrice(), NativeToWei(baseFee)). Also pass the base fee to AsMessage and CanTransfer in wei.

        Vercel Security Review

        Wei-denominated gas refunds are paid as unibi from pooled fees

        x/evm/keeper/gas_fees.go:188 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. The new fee path charges native units** - x/evm/keeper/gas_fees.go:188-189

        ```go title="x/evm/keeper/gas_fees.go:188-189"

        baseFeeWei := evm.NativeToWei(baseFeeMicronibi)

        feeAmtMicronibi := evm.WeiToNative(txData.EffectiveFeeWei(baseFeeWei))

        ```

        **2. Unused gas produces a wei-denominated refund instead** - x/evm/keeper/gas_fees.go:48

        ```go title="x/evm/keeper/gas_fees.go:48"

        remaining := new(big.Int).Mul(new(big.Int).SetUint64(leftoverGas), msg.GasPrice())

        ```

        **3. The sender receives that amount from pooled native fees** - x/evm/keeper/gas_fees.go:60

        ```go title="x/evm/keeper/gas_fees.go:60"

        err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, authtypes.FeeCollectorName, msg.From().Bytes(), refundedCoins)

        ```

        Line 56 wraps remaining directly as native coins, without dividing by 10^12 or bounding it by the debit. A funded signer can select gas limits and prices yielding an affordable refund exceeding their payment, stealing other users' collected fees. Refunds exceeding the pool instead fail otherwise-valid transactions.

        Exploit scenario

        Not specified.

        Recommendation

        Calculate debits and refunds using the same effective gas price and denomination. Convert the total wei refund to native units with consistent rounding, and ensure no refund can exceed the native fee actually debited for that message. Add end-to-end legacy and EIP-1559 fee/refund conservation tests.

      • Dirty EVM journal entries are not applied to Cosmos state in precompiles, enabling infinite unibi minting nibiru-3 · 7 writeups Critical

        V12

        Stale cross-VM balances restore spent native funds

        x/evm/precompile/wasm.go:155 Predicted severity: High

        Root cause

        The SDK bank and EVM account cache are treated as independently mutable balances during the same execution. SetAccBalance() uses mint/burn reconciliation against stale cached balances after native keeper calls.

        Impact

        Inference: a funded caller can repeatedly supply native coins to a Wasm recipient while having its debit restored by native minting at EVM commit, creating unbacked spendable value. Conversely, native receipts into a dirty EVM account can be burned when the stale lower balance is committed; the exact end-to-end transfer behavior must be verified against the unavailable Wasmd keeper implementation.

        Description

        The Wasm gateways mutate bank state using the SDK context but do not reconcile those changes with cached EVM account balances. StateDB.getStateObject() retains an account once loaded, and Commit() later writes each dirty account's cached balance back through SetAccount(). That setter calls SetAccBalance(), which mints or burns native coins to force the bank balance to the cached amount. A caller can combine EVM value movement, which dirties its EVM balance, with a successful Wasm invocation that spends native-denom funds from the same account. Inference: the commit then restores the spent funds from the stale EVM balance rather than preserving the bank-side debit. This affects u2 and u4 execution and u3 instantiation independently of whether any call reverts.

        Codex Security (GPT-6 Sol)

        Wasm precompile can duplicate native coins through stale EVM balance reconciliation

        x/evm/precompile/wasm.go:160 Predicted severity: High

        Root cause

        Wasm keeper spends native funds, then stale EVM StateDB account balance is committed via SetAccBalance, potentially minting the delta.

        Impact

        A successful EVM call that spends native coins through Wasm can restore the caller's spent balance when the stale EVM account is committed, minting replacement coins. Transaction-level cache discards failed outer transactions; issue requires successful outer transaction and dirty EVM account.

        Description

        A successful EVM call that spends native coins through Wasm can restore the caller's spent balance when the stale EVM account is committed, minting replacement coins.

        Exploit scenario

        Wasm keeper spends native funds, then stale EVM StateDB account balance is committed via SetAccBalance, potentially minting the delta.

        Recommendation

        Reconcile native balances with EVM account changes in one transactional state layer; never overwrite bank balance from a stale cached EVM balance.

        Devin Security

        Wasm precompile funds are paid from bank state, then the EVM commit restores the caller's cached NIBI balance

        x/evm/precompile/wasm.go:92 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone with an EVM account can send NIBI into Wasm contracts through the precompile and have the same NIBI put back in their account at the end of the transaction, which creates unlimited NIBI.

        ##### What's wrong

        This is a state desynchronization double spend. The Wasm precompile moves funds with the bank module on the raw context, but the EVM StateDB has already cached the caller's NIBI balance. When the transaction commits, the StateDB sets the bank balance back to that cached value by minting the difference.

        ##### Who can do it

        Mallory has a funded EVM account. She sends an Ethereum transaction that calls the Wasm precompile's execute, instantiate, or executeMulti, with funds in unibi sent to a Wasm contract she controls.

        - Mallory can send an Ethereum transaction.

        - The funds include the EVM base denom (unibi).

        ##### What they get

        The bank module moves Mallory's NIBI into her Wasm contract. At commit, the EVM writes her old balance back by minting new NIBI. She withdraws the contract balance and repeats. She can mint unlimited NIBI, which dilutes every holder and lets her drain pools and markets on the chain.

        ##### How it works

        1. Run takes the raw context from the StateDB (wasm.go:97).

        2. execute, instantiate, and executeMulti pass caller funds to the Wasm keeper (wasm.go:161, 252-253, 307-314), which uses bank transfers on that context.

        3. The caller's account object is already loaded in the StateDB and marked dirty, because ApplyEvmMsg sets the nonce (x/evm/keeper/msg_server.go:356).

        4. StateDB.Commit calls SetAccount, and SetAccount calls SetAccBalance with the cached balance (x/evm/keeper/statedb.go:104-131).

        5. SetAccBalance mints the difference between the cached balance and the real bank balance (x/evm/keeper/statedb.go:69-85). This undoes the payment and creates new NIBI.

        Exploit scenario

        Not specified.

        Recommendation

        Before a precompile that touches bank or Wasm state runs, commit the StateDB's dirty state to a cached context. After the call, reload the cached balances of every account the precompile touched, or journal the precompile's changes so the StateDB stays consistent. To check the fix, add a test where an EOA calls Wasm.execute with 1000 unibi in funds. After the transaction, the EOA's balance must be lower by 1000 plus gas, and the total unibi supply must not change.

        Devin Security (Deep)

        FunToken precompile runs a nested EVM call that commits beneath the live StateDB, letting the outer commit undo the ERC20 debit (token duplication / escrow drain)

        x/evm/keeper/msg_server.go:279 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who can send an EVM transaction on the chain can duplicate any ERC20 token that has a FunToken mapping and drain the native coins other users escrowed in the EVM module.

        ##### What's wrong

        This is a state-consistency bug between nested EVM executions. ApplyEvmMsg builds a fresh StateDB straight from the SDK context and, when commit is true, writes its result directly into that context. The FunToken precompile (bankSend) calls this from inside a running transaction, so the inner call reads the on-disk store (not the outer transaction's pending changes) and writes to the store underneath the outer StateDB. When the outer transaction later commits, it writes its own cached storage slots back and silently overwrites what the inner call wrote.

        ##### Who can do it

        Alice, a Nibiru user at Acme, converted 10,000 TOKEN (an ERC20 that has a FunToken mapping) into bank coins, so the EVM module account now holds 10,000 TOKEN in escrow. Mallory, an attacker with a funded EVM account, deploys a small contract and calls it once.

        - Mallory needs an EVM account with gas and a balance of the target ERC20 (any amount).

        - The ERC20 needs a FunToken mapping. Anyone can create one with MsgCreateFunToken by paying the fee, so this is not a barrier.

        - No special permissions, roles, or governance actions are needed.

        ##### What they get

        Mallory's contract first transfers 1 TOKEN to a second address she controls. This marks her TOKEN balance slot as dirty in the outer StateDB. It then calls the FunToken precompile bankSend(TOKEN, 99, mallory_nibi_addr). The precompile performs the ERC20 transfer in a separate inner EVM run that reads the store (where Mallory still has 100) and commits her balance as 1 and the module's as 99, then mints 99 bank coins to her. When the outer transaction commits, it writes Mallory's cached slot (99) back over the inner result. Mallory ends with 99 TOKEN and 99 bank coins, and the module holds 99 escrowed TOKEN. She redeems the bank coins with MsgConvertCoinToEvm and now has 198 TOKEN from 100. Repeating this doubles her holdings every transaction. If the FunToken was created from a bank coin (for example the native gas coin), bankSend pays her from the module's escrow of coins other users deposited, so she drains Alice's and everyone else's escrowed funds directly. This works for every ERC20 on the chain, including bridged stablecoins.

        ##### How it works

        1. Mallory's contract calls TOKEN.transfer(addr2, 1) inside the outer EVM run; stateObject.SetState records her balance slot as dirty in the outer StateDB (x/evm/statedb/state_object.go:276-294).

        2. Her contract calls the FunToken precompile; bankSend pulls the SDK context from the outer StateDB and calls ERC20().Transfer(TOKEN, caller, module, 99, ctx) (x/evm/precompile/funtoken.go:73, 160-165).

        3. CallContractWithInput runs ApplyEvmMsg(ctx, ..., commit=true), which builds a new StateDB from the same context and reads her balance as 100 from the store, ignoring the outer pending change (x/evm/keeper/erc20.go:167-229, x/evm/keeper/msg_server.go:291).

        4. The inner stateDB.Commit() writes her slot as 1 and the module's slot as 99 into the context store (x/evm/keeper/msg_server.go:389-393, x/evm/statedb/statedb.go:452-479).

        5. bankSend mints 99 bank coins (or burns module ERC20 and pays escrowed coins) and sends them to Mallory's Nibiru address (x/evm/precompile/funtoken.go:167-195).

        6. The outer run finishes and ApplyEvmTx commits the outer StateDB, which writes the cached dirty slot (99) over the inner value and leaves the module's 99 in place (x/evm/keeper/msg_server.go:66, 389-393; x/evm/statedb/statedb.go:468-475).

        7. Mallory redeems the bank coins through ConvertCoinToEvm → convertCoinNativeERC20, which transfers 99 TOKEN from the module escrow to her (x/evm/keeper/msg_server.go:584-671).

        Exploit scenario

        Not specified.

        Recommendation

        Do not run a second, independent StateDB for precompile side effects. Either execute precompile ERC20 interactions through the live outer StateDB (for example by exposing a way to run a sub-call with the same vm.EVM/StateDB and journaling bank changes), or make the outer StateDB aware of nested commits: after a nested committing call, flush the outer StateDB's dirty objects first (commit-before-call) and reload affected state objects, or journal precompile actions and apply them only at the outer commit. At minimum, reject bankSend when the outer StateDB has dirty state for the ERC20 contract. Verify with a test that: a contract transfers 1 token, then calls bankSend for the rest in the same tx, and assert the caller's final ERC20 balance plus bank coins never exceeds the starting balance and that ERC20 total supply equals the sum of balances.

        Claude Security (Sonnet 5.5)

        Wasm precompile moves bank funds out-of-band from the EVM StateDB; StateDB.Commit then restores the stale balance by minting, duplicating native coins

        x/evm/precompile/wasm.go:161 Predicted severity: Critical

        Root cause

        Vulnerable symbol: precompileWasm.execute

        Preconditions: Attacker can obtain a wasm contract from which funds are recoverable (default wasmd permissions allow anyone to upload and instantiate; otherwise an existing generic forwarding contract); Caller account must be dirty in the StateDB (trivially achieved by attaching >=1 unibi of value, or by any storage write in a calling contract)

        Offending code:

        data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)

        Impact

        Unbounded inflation of the native token supply by any user, so total loss of the chain's economic integrity; also silent burning of funds that wasm contracts send back to EVM accounts during the same tx.

        Description

        The precompile mutates bank state directly on stateDB.GetContext() with caller-supplied funds, while the running StateDB keeps its own cached account balances. When the EVM call ends, StateDB.Commit calls SetAccount -> SetAccBalance, which mints or burns so the bank balance equals the stale cached value, undoing the bank debit.

        Exploit scenario

        1) Attacker has account A with B unibi and a wasm contract W they can later withdraw from (instantiated from any permitted code id, for example through the instantiate precompile or a normal MsgInstantiateContract). 2) A sends an Ethereum tx to the Wasm precompile 0x...0802 with value = 1e12 wei (1 unibi; this journals a balanceChange so A becomes a dirty StateDB account with cached balance B-fee-1) and calldata execute(W, msg, [{denom:"unibi", amount:X}]) with X <= B. 3) wasm Execute calls bank TransferCoins(A -> W, X), so the bank balance of A drops to B-fee-X. 4) At the end of ApplyEvmMsg, StateDB.Commit sets A's balance to the cached B-fee-1, minting X-1 unibi to A through the evm module account. 5) A keeps its balance and W holds X new unibi. Repeating roughly doubles A's holdings per tx. The mirror case (coins received by a dirty account via the precompile) is burned/lost instead.

        Recommendation

        Before invoking any state-mutating precompile, flush the StateDB journal into the ctx (or run the precompile on a cache ctx and commit/sync it to the StateDB), and after it returns drop/reload cached stateObjects so later reads see bank changes. Alternatively make StateDB.Commit write only deltas it actually made instead of forcing absolute balances, and add invariant checks on total supply in tests.

        Claude Security (Opus 5.5)

        FunToken precompile runs a nested EVM on stale KV state that the outer StateDB later overwrites, so ERC20 tokens can be double-spent and escrow drained

        x/evm/precompile/funtoken.go:162 Predicted severity: Critical

        Root cause

        Vulnerable symbol: precompileFunToken.bankSend

        Preconditions: A FunToken mapping exists for the ERC20 (normal protocol state); Attacker holds some of the token and can deploy a contract

        Offending code:

        _, err = p.evmKeeper.ERC20().Transfer(erc20, caller, transferTo, amount, ctx)

        Impact

        Any user can mint ERC20 balances out of nothing and drain the bank-coin or ERC20 escrow behind every FunToken mapping. Bridged assets become insolvent.

        Description

        bankSend takes the outer StateDB's raw sdk.Context and calls ERC20().Transfer/Burn. That goes through CallContractWithInput -> ApplyEvmMsg, which builds a fresh StateDB on the same ctx and commits straight to KV. The nested call cannot see the outer StateDB's uncommitted dirty storage. When the outer tx commits, its cached slots overwrite whatever the nested call wrote. Also CWE-290: bankSend takes contract.CallerAddress, which can be any contract, and passes it as from to ERC20().Transfer. That function builds a new top-level geth Message from that address (erc20.go:192) and runs it with ApplyEvmMsg/NewEVM, which sets TxContext.Origin = msg.From() (msg_server.go:172). The nested execution therefore runs with tx.origin set to a contract address, which normal Ethereum semantics never allow. Also CWE-252: The ConvertCoinToEvm path rejects !res and verifies the exact balance delta. The precompile path to the same escrow discards Transfer's bool and mints amount coins whatever the EVM module actually received.

        Exploit scenario

        The attacker deploys contract C holding 100 units of a FunToken-mapped ERC20 T. In one tx C first calls T.transfer(X, 100) in the EVM, so the outer StateDB caches bal(C)=0 and bal(X)=100 as dirty while KV still says bal(C)=100. C then calls bankSend(T, 100, attackerNibiAddr) on precompile 0x...800. The nested EVM reads bal(C)=100 from KV and moves it to the EVM module. For a coin-backed mapping it then burns those tokens and sends 100 escrowed bank coins to the attacker. For an ERC20-backed mapping it mints 100 coins, which ConvertCoinToEvm later redeems against the module's escrow. At the end of the tx the outer StateDB writes bal(C)=0 and bal(X)=100. X keeps 100 T and the attacker also holds 100 bank coins. Repeating the loop drains the escrow of every mapping. The same staleness can be reached through wasm.execute when the wasm contract dispatches MsgConvertCoinToEvm, which also runs nested EVM calls on the shared ctx.

        Recommendation

        Do not run nested EVM executions against the outer StateDB's context. Run precompile side effects on a cache context that is journaled in the StateDB, flush or commit the outer StateDB's dirty state before the nested call, or do the ERC20 movement inside the outer EVM (for example via the outer StateDB or a sub-call of the current EVM) instead of a separate ApplyEvmMsg. Also CWE-290: Do not start a new top-level EVM message from an arbitrary caller. Either perform the token debit inside the current EVM frame using the existing StateDB and EVM, keeping the outer tx.origin, or have the module account move the tokens (for example with transferFrom and an allowance). If a nested message is unavoidable, reject callers that have code, or set Origin to the outer transaction's origin. Also CWE-252: Require Transfer to return true, and mint or send coins only for the measured increase in the EVM module's ERC20 balance (balance after minus balance before), mirroring convertCoinNativeERC20.

        Vercel Security Review

        Wasm spending is overwritten by stale EVM balances, minting native tokens

        x/evm/precompile/wasm.go:160 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. The new precompile spends bank funds outside the EVM balance cache** - x/evm/precompile/wasm.go:160-161

        ```go title="x/evm/precompile/wasm.go:160-161"

        callerBech32 := eth.EthAddrToNibiruAddr(caller)

        data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)

        ```

        An attacker funds their EVM contract, dirties its storage, then supplies unibi to their Wasm contract. The bank debit never updates its cached EVM balance.

        **2. Successful execution writes the stale account balance back** - x/evm/statedb/statedb.go:465-467

        ```go title="x/evm/statedb/statedb.go:465-467"

        if err := s.keeper.SetAccount(s.ctx, obj.Address(), obj.account.ToNative()); err != nil {

        return errorf("failed to set account: %w")

        }

        ```

        **3. Restoring that balance mints replacement unibi** - x/evm/keeper/statedb.go:78-81

        ```go title="x/evm/keeper/statedb.go:78-81"

        case 1:

        // mint

        coins := sdk.NewCoins(sdk.NewCoin(params.EvmDenom, sdkmath.NewIntFromBigInt(delta)))

        if err := k.bankKeeper.MintCoins(ctx, evm.ModuleName, coins); err != nil {

        ```

        SetAccount calls SetAccBalance at line 129; its positive delta restores the spent funds while the Wasm recipient retains them. Repetition creates unbacked native currency.

        Exploit scenario

        Not specified.

        Recommendation

        Synchronize native bank balance changes with the active EVM StateDB. Before Wasm execution, make pending EVM balances visible consistently; journal and reconcile all native balance changes afterward so commit cannot restore stale balances. Do not fix this by merely suppressing balance writes, which would lose legitimate EVM transfers. Test SSTORE plus Wasm spending and subsequent EVM balance operations for supply conservation.

      • Precompile bankSend modifies Cosmos state which can be overwritten by outdated EVM state nibiru-4 · 7 writeups Critical

        V12

        Stale cross-VM balances restore spent native funds

        x/evm/precompile/wasm.go:155 Predicted severity: High

        Root cause

        The SDK bank and EVM account cache are treated as independently mutable balances during the same execution. SetAccBalance() uses mint/burn reconciliation against stale cached balances after native keeper calls.

        Impact

        Inference: a funded caller can repeatedly supply native coins to a Wasm recipient while having its debit restored by native minting at EVM commit, creating unbacked spendable value. Conversely, native receipts into a dirty EVM account can be burned when the stale lower balance is committed; the exact end-to-end transfer behavior must be verified against the unavailable Wasmd keeper implementation.

        Description

        The Wasm gateways mutate bank state using the SDK context but do not reconcile those changes with cached EVM account balances. StateDB.getStateObject() retains an account once loaded, and Commit() later writes each dirty account's cached balance back through SetAccount(). That setter calls SetAccBalance(), which mints or burns native coins to force the bank balance to the cached amount. A caller can combine EVM value movement, which dirties its EVM balance, with a successful Wasm invocation that spends native-denom funds from the same account. Inference: the commit then restores the spent funds from the stale EVM balance rather than preserving the bank-side debit. This affects u2 and u4 execution and u3 instantiation independently of whether any call reverts.

        Codex Security (GPT-6 Sol)

        Wasm precompile can duplicate native coins through stale EVM balance reconciliation

        x/evm/precompile/wasm.go:160 Predicted severity: High

        Root cause

        Wasm keeper spends native funds, then stale EVM StateDB account balance is committed via SetAccBalance, potentially minting the delta.

        Impact

        A successful EVM call that spends native coins through Wasm can restore the caller's spent balance when the stale EVM account is committed, minting replacement coins. Transaction-level cache discards failed outer transactions; issue requires successful outer transaction and dirty EVM account.

        Description

        A successful EVM call that spends native coins through Wasm can restore the caller's spent balance when the stale EVM account is committed, minting replacement coins.

        Exploit scenario

        Wasm keeper spends native funds, then stale EVM StateDB account balance is committed via SetAccBalance, potentially minting the delta.

        Recommendation

        Reconcile native balances with EVM account changes in one transactional state layer; never overwrite bank balance from a stale cached EVM balance.

        Devin Security

        FunToken bankSend writes outside the EVM state cache, so a stale ERC20 balance is written back and tokens are spent twice

        x/evm/precompile/funtoken.go:67 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone with an EVM account can turn their ERC20 tokens into bank coins and still keep the tokens, then convert the duplicate coins back to drain other users' escrowed tokens.

        ##### What's wrong

        This is a state desynchronization double spend. The FunToken precompile moves ERC20 tokens through a separate inner EVM call that commits straight to the Cosmos context, but the outer EVM transaction keeps its own cached copy of the same ERC20 storage and writes that stale copy back at the end.

        ##### Who can do it

        Alice and many other users have converted their bank coins or ERC20 tokens through a FunToken mapping, so the EVM module holds their escrow. Mallory, who has any funded EVM account, deploys a small contract and holds 100 units of a mapped ERC20 token.

        - Mallory can send an Ethereum transaction (no special permissions).

        - The ERC20 token has a FunToken mapping (any token can get one by paying the creation fee).

        - The outer EVM call reads the ERC20 balance slot before calling bankSend, so it is cached.

        ##### What they get

        Mallory's contract calls balanceOf on the token, then bankSend for 100 units, then transfer of 100 units to a second address. The bank side gives her 100 coins, and the outer EVM still believes she has 100 tokens, so the transfer succeeds and overwrites the inner deduction. She repeats this and uses ConvertCoinToEvm to pull real tokens out of the EVM module escrow. For coin-backed mappings, bankSend pays her out of escrowed native coins directly. She can drain every user's escrow for every mapped token.

        ##### How it works

        1. Run takes the raw transaction context from the StateDB with stateDB.GetContext() (funtoken.go:73) and passes it to bankSend.

        2. bankSend calls ERC20().Transfer (funtoken.go:162), which runs CallContractWithInput with commit=true and builds a new StateDB on the same context (x/evm/keeper/erc20.go:167-224), so the balance change is written to the store immediately.

        3. bankSend then mints or releases bank coins and sends them to the recipient on that same context (funtoken.go:168-195). None of this is recorded in the outer StateDB journal.

        4. The outer StateDB already cached the ERC20 balance slot in originStorage (x/evm/statedb/state_object.go:258-266). A later transfer in the same transaction reads the stale value.

        5. At the end, StateDB.Commit writes the dirty slot with the stale-based value (x/evm/statedb/statedb.go:454-480), which undoes the inner deduction while the bank coins stay minted.

        6. If an inner call frame that invoked bankSend reverts while the outer transaction succeeds, the bank and ERC20 changes also persist because they were never journaled.

        Exploit scenario

        Not specified.

        Recommendation

        Make precompile side effects part of the StateDB. Before a precompile runs, flush the outer StateDB's dirty state to a cached context. Run the precompile on that cached context, record a journal entry so a revert discards it, and then reload or invalidate the affected cached state objects (ERC20 contract storage and account balances) after the call. Upstream Nibiru later added a precompile journal entry and a CacheCtx inside the StateDB for this reason. To check the fix, write an end-to-end test where one contract calls balanceOf, then bankSend, then transfer in a single transaction. The transfer must fail with insufficient balance. Add a second test where bankSend runs in a call frame that reverts inside try/catch. Both the bank balance and the ERC20 balance must be unchanged.

        Devin Security (Deep)

        StateDB commit mints unibi to cover bank balance changes made by precompiles, enabling unlimited native token minting

        x/evm/keeper/statedb.go:68 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone with a small EVM balance can mint unlimited unibi out of nothing by moving coins through the Wasm precompile inside one Ethereum transaction, because the EVM state commit restores the sender's cached balance by minting the difference.

        ##### What's wrong

        This is a state desynchronization between the EVM's in-memory account cache and the bank module. SetAccBalance reconciles an account by comparing the cached EVM balance to the live bank balance and minting or burning the difference. Precompiles run with the raw SDK context and move bank coins outside the EVM cache. When the transaction commits, the cache is stale, so SetAccBalance mints coins to put the balance back where the cache says it should be.

        ##### Who can do it

        Mallory has 1,000 NIBI in an EVM account on the public chain. She sends one Ethereum transaction to the Wasm precompile at 0x...0802, attaching 1 unibi of value and calling execute on any Wasm contract that accepts deposits (her own contract, or an existing exchange or escrow contract) with funds set to 999 NIBI. Alice, Bob, and every other holder of NIBI at Acme Exchange and Globex Staking see their tokens diluted by the coins Mallory prints.

        - Mallory needs an EVM account with any unibi balance.

        - A Wasm contract that can receive funds and later release value to Mallory must exist. She can deploy or instantiate one herself, or use any existing deposit or swap contract.

        - No grant, permission, or privileged role is required.

        ##### What they get

        After the transaction, the Wasm contract holds 999 NIBI and Mallory's EVM account has been topped back up to about 999 NIBI by newly minted coins. She withdraws or swaps the deposit and repeats, doubling her holdings each round with no upper bound. This inflates the native token supply without limit, lets her drain any pool or exchange priced in NIBI, and breaks the economic security of staking for the whole chain. The same stale-cache problem also affects the FunToken precompile, whose nested EVM call writes ERC20 storage directly to the store while the outer transaction may later overwrite those slots with cached values, allowing an ERC20 balance to be spent and kept at the same time.

        ##### How it works

        1. ApplyEvmMsg creates a StateDB over the transaction context and hands the same context to the EVM (x/evm/keeper/msg_server.go:291-292).

        2. The sender's call to the precompile carries a non-zero value, so the EVM calls SubBalance on the sender, which loads the sender's current bank balance into the StateDB cache and marks it dirty (x/evm/statedb/state_object.go:163-169).

        3. The Wasm precompile fetches the raw SDK context from the StateDB and calls Wasm.Execute(ctx, contract, caller, msg, funds), which transfers funds from the sender's bank account to the Wasm contract immediately in the store (x/evm/precompile/wasm.go:92-101, 155-161).

        4. When the EVM finishes, StateDB.Commit writes each dirty account through keeper.SetAccount with the cached balance (x/evm/statedb/statedb.go:454-467).

        5. SetAccount calls SetAccBalance, which reads the live bank balance (now lower by funds), computes a positive delta, and mints that delta to the sender (x/evm/keeper/statedb.go:69-86, 129-131).

        6. ApplyEvmTx commits the cached context, so both the Wasm contract's deposit and the newly minted coins persist (x/evm/keeper/msg_server.go:104-107).

        7. A second variant: the FunToken precompile's bankSend runs a nested ApplyEvmMsg with commit=true on the same context (x/evm/precompile/funtoken.go:160-165, x/evm/keeper/erc20.go:216-219), writing ERC20 storage to the store while the outer StateDB still holds dirty copies of those slots, which Commit later writes back via SetState (x/evm/statedb/statedb.go:468-475, x/evm/keeper/statedb.go:139-143).

        Exploit scenario

        Not specified.

        Recommendation

        Make precompile side effects part of the StateDB journal. Give precompiles a cache-wrapped context created by the StateDB (for example stateDB.CacheCtxForPrecompile()), record a journal entry whose revert discards that cache, and only write the cache to the real store at Commit. Before writing cached balances in Commit, re-read live bank balances and apply only the EVM-originated delta (or have the precompile cache ctx be the one the StateDB reads from), so bank changes made by precompiles are never undone by SetAccBalance. Apply the same treatment to nested ApplyEvmMsg calls made from precompiles so they execute against the outer StateDB rather than a fresh one. Verify with a test that calls the Wasm precompile execute with non-zero value and funds equal to most of the sender's balance, then asserts the total supply of unibi is unchanged and the sender's balance decreased by the funds plus value.

        Claude Security (Sonnet 5.5)

        Wasm precompile moves bank funds out-of-band from the EVM StateDB; StateDB.Commit then restores the stale balance by minting, duplicating native coins

        x/evm/precompile/wasm.go:161 Predicted severity: Critical

        Root cause

        Vulnerable symbol: precompileWasm.execute

        Preconditions: Attacker can obtain a wasm contract from which funds are recoverable (default wasmd permissions allow anyone to upload and instantiate; otherwise an existing generic forwarding contract); Caller account must be dirty in the StateDB (trivially achieved by attaching >=1 unibi of value, or by any storage write in a calling contract)

        Offending code:

        data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)

        Impact

        Unbounded inflation of the native token supply by any user, so total loss of the chain's economic integrity; also silent burning of funds that wasm contracts send back to EVM accounts during the same tx.

        Description

        The precompile mutates bank state directly on stateDB.GetContext() with caller-supplied funds, while the running StateDB keeps its own cached account balances. When the EVM call ends, StateDB.Commit calls SetAccount -> SetAccBalance, which mints or burns so the bank balance equals the stale cached value, undoing the bank debit.

        Exploit scenario

        1) Attacker has account A with B unibi and a wasm contract W they can later withdraw from (instantiated from any permitted code id, for example through the instantiate precompile or a normal MsgInstantiateContract). 2) A sends an Ethereum tx to the Wasm precompile 0x...0802 with value = 1e12 wei (1 unibi; this journals a balanceChange so A becomes a dirty StateDB account with cached balance B-fee-1) and calldata execute(W, msg, [{denom:"unibi", amount:X}]) with X <= B. 3) wasm Execute calls bank TransferCoins(A -> W, X), so the bank balance of A drops to B-fee-X. 4) At the end of ApplyEvmMsg, StateDB.Commit sets A's balance to the cached B-fee-1, minting X-1 unibi to A through the evm module account. 5) A keeps its balance and W holds X new unibi. Repeating roughly doubles A's holdings per tx. The mirror case (coins received by a dirty account via the precompile) is burned/lost instead.

        Recommendation

        Before invoking any state-mutating precompile, flush the StateDB journal into the ctx (or run the precompile on a cache ctx and commit/sync it to the StateDB), and after it returns drop/reload cached stateObjects so later reads see bank changes. Alternatively make StateDB.Commit write only deltas it actually made instead of forcing absolute balances, and add invariant checks on total supply in tests.

        Claude Security (Opus 5.5)

        Wasm precompile moves unibi underneath the StateDB; Commit's SetAccBalance re-mints the spent funds (infinite NIBI mint)

        x/evm/precompile/wasm.go:161 Predicted severity: Critical

        Root cause

        Vulnerable symbol: precompileWasm.execute

        Preconditions: Attacker can send an EVM tx with nonzero value, or call from a contract whose balance is dirty in the StateDB; Any wasm contract that accepts funds (the attacker can deploy one)

        Offending code:

        data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)

        Impact

        Unbounded minting of the native gas and staking token NIBI by any user. This breaks total supply, staking security and every market denominated in NIBI.

        Description

        execute, executeMulti and instantiate send attacker-chosen bank funds from the EVM caller's account directly on ctx. If the outer StateDB has a dirty cached balance for that caller, StateDB.Commit calls SetAccount -> SetAccBalance with the stale balance. SetAccBalance mints the difference against the now-lower bank balance.

        Exploit scenario

        An EOA holding B unibi sends a tx to 0x...802 with msg.value = 1 micronibi. core.Transfer calls SubBalance, which marks the caller's stateObject dirty with cached balance B-1. The calldata is execute(W, msg, [{unibi, B-2}]), where W is an attacker-controlled CosmWasm contract (for example a forwarder or vault). Bank moves B-2 unibi to W. At commit, SetAccBalance sees target B-1 against an actual balance of 1 and mints B-2 unibi back to the caller. W holds B-2, the caller holds about B, and every iteration doubles the attacker's NIBI. The opposite direction burns funds: a wasm contract that pays into a dirty EVM account has the payment erased at commit.

        Recommendation

        Make precompiles StateDB-aware. Before calling into Cosmos modules, commit the StateDB's dirty accounts to ctx, or run on a cache ctx and afterwards reload or mark affected accounts so Commit does not overwrite bank balances. Alternatively, express bank transfers through StateDB.SubBalance/AddBalance. Never let SetAccBalance mint against an independently changed bank balance.

        Vercel Security Review

        Wasm spending is overwritten by stale EVM balances, minting native tokens

        x/evm/precompile/wasm.go:160 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. The new precompile spends bank funds outside the EVM balance cache** - x/evm/precompile/wasm.go:160-161

        ```go title="x/evm/precompile/wasm.go:160-161"

        callerBech32 := eth.EthAddrToNibiruAddr(caller)

        data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)

        ```

        An attacker funds their EVM contract, dirties its storage, then supplies unibi to their Wasm contract. The bank debit never updates its cached EVM balance.

        **2. Successful execution writes the stale account balance back** - x/evm/statedb/statedb.go:465-467

        ```go title="x/evm/statedb/statedb.go:465-467"

        if err := s.keeper.SetAccount(s.ctx, obj.Address(), obj.account.ToNative()); err != nil {

        return errorf("failed to set account: %w")

        }

        ```

        **3. Restoring that balance mints replacement unibi** - x/evm/keeper/statedb.go:78-81

        ```go title="x/evm/keeper/statedb.go:78-81"

        case 1:

        // mint

        coins := sdk.NewCoins(sdk.NewCoin(params.EvmDenom, sdkmath.NewIntFromBigInt(delta)))

        if err := k.bankKeeper.MintCoins(ctx, evm.ModuleName, coins); err != nil {

        ```

        SetAccount calls SetAccBalance at line 129; its positive delta restores the spent funds while the Wasm recipient retains them. Repetition creates unbacked native currency.

        Exploit scenario

        Not specified.

        Recommendation

        Synchronize native bank balance changes with the active EVM StateDB. Before Wasm execution, make pending EVM balances visible consistently; journal and reconcile all native balance changes afterward so commit cannot restore stale balances. Do not fix this by merely suppressing balance writes, which would lose legitimate EVM transfers. Test SSTORE plus Wasm spending and subsequent EVM balance operations for supply conservation.

      • On-chain gas limit estimation for internal EVM calls can be abused for DoS nibiru-5 · 6 writeups High

        V12

        Nested contract execution bypasses enclosing gas accounting

        x/evm/keeper/erc20.go:181 Predicted severity: Medium

        Root cause

        The adapter fails to bridge independent EVM execution gas back into the enclosing SDK/EVM budget. Fixed precompile gas pricing excludes the adapter's user-controlled execution and binary-search work.

        Impact

        Inference: a mapped token with a computation-heavy transfer lets an external caller force validators to perform substantial nested EVM work for the precompile's much smaller fixed charge. Repeated precompile invocations and their estimation probes amplify validator CPU consumption without corresponding transaction or block gas accounting, threatening processing availability.

        Description

        Keeper-driven contract calls obtain their own EVM gas limit and return a GasUsed value, but the adapter never charges that value to the enclosing SDK gas meter. The FunToken precompile similarly charges a fixed 42,000 EVM gas while invoking the ERC20 adapter, which runs its own independent EVM and gas-estimation loop. An arbitrary mapped ERC20 can therefore execute expensive computational work during its transfer without reducing the outer EVM's remaining gas by that work. The normal Ethereum transaction path meters its outer response, but that response excludes gas consumed in these independent executions. The default inner limit of 25,000,000 bounds each execution, not the accumulated work authorized by an outer transaction.

        Devin Security

        Module-initiated EVM calls into user-supplied ERC20 contracts do not charge EVM gas to the Cosmos transaction

        x/evm/keeper/erc20.go:167 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A user can make every validator run up to tens of millions of EVM gas worth of work per message while paying only a small Cosmos fee, which can slow block production.

        ##### What's wrong

        This is unmetered computation. CallContractWithInput runs an EVM message with a 25,000,000 gas limit, plus a binary-search gas estimate when it commits. The EVM gas it uses is never consumed on the Cosmos transaction's gas meter. Only key-value store reads and writes are charged.

        ##### Who can do it

        Mallory deploys an ERC20 whose balanceOf, transfer, name, symbol and decimals functions spin in loops until they nearly run out of gas. She pays the creation fee once and creates a FunToken mapping for it with MsgCreateFunToken. She then sends many cheap MsgConvertCoinToEvm messages for the matching erc20/... bank coin.

        - Mallory has a funded account and pays the FunToken creation fee once.

        - Mallory holds a small amount of the erc20/<her contract> bank coin.

        ##### What they get

        Each conversion runs three balanceOf calls at up to 25M gas each. It also runs a transfer whose gas estimate repeats the call about 25 times. Validators do this work for almost no fee, so block times can grow. This affects availability only. No funds are lost.

        ##### How it works

        1. convertCoinNativeERC20 calls BalanceOf and Transfer on the mapped contract in x/evm/keeper/msg_server.go:593-644.

        2. CallContractWithInput sets the gas limit to DefaultEthCallGasLimit (25,000,000) in x/evm/keeper/erc20.go:183.

        3. For commits, computeCommitGasLimit runs EstimateGasForEvmCallType, which binary-searches by executing the call repeatedly, in x/evm/keeper/erc20.go:241-276.

        4. ApplyEvmMsg returns GasUsed, but CallContractWithInput never consumes it on ctx.GasMeter() in x/evm/keeper/erc20.go:217-228.

        Exploit scenario

        Not specified.

        Recommendation

        Consume evmResp.GasUsed on ctx.GasMeter() after each module-initiated call, including the estimation runs, as upstream did in PR #2180. Bound the gas limit by the remaining Cosmos gas. Add a test that a conversion against a gas-burning ERC20 fails with out-of-gas when the Cosmos gas limit is low.

        Devin Security (Deep)

        bankSend charges a flat 42,000 gas but triggers dozens of full nested EVM executions, letting one transaction consume far more compute than it pays for

        x/evm/precompile/funtoken.go:35 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can make every node in the network do hundreds of times more work than the gas they pay for, slowing or stalling block production, without gaining funds or data.

        ##### What's wrong

        This is underpriced computation. RequiredGas for bankSend is a flat 2 * TxGas. The call then performs a nested ERC20().Transfer (and for coin-backed FunTokens a Burn), each of which runs computeCommitGasLimit's binary-search gas estimation (about 25 full EVM executions up to the 25M cap) plus the real execution, none of which is charged to the outer transaction's gas.

        ##### Who can do it

        Mallory, any EVM user, deploys an ERC20 whose transfer burns close to 25M gas of computation, creates a FunToken for it, and sends one transaction that loops over bankSend hundreds of times.

        - She needs enough gas for the outer loop only (about 42,000 gas per call plus call overhead).

        ##### What they get

        Each bankSend costs her ~42k gas but makes every node execute roughly 26 × 25M gas of EVM work. A single block-gas-limit transaction can translate into hours of CPU time per node, causing missed blocks or a stalled chain. No funds are stolen.

        ##### How it works

        1. RequiredGas returns a constant 2 * TxGas regardless of what the nested calls will do (x/evm/precompile/funtoken.go:36-46).

        2. bankSend calls ERC20().Transfer, which goes through CallContractWithInput with commit=true (x/evm/precompile/funtoken.go:162; x/evm/keeper/erc20.go:73-93).

        3. computeCommitGasLimit runs EstimateGasForEvmCallType, binary-searching with up to DefaultEthCallGasLimit (25M) gas per iteration; none of this gas is deducted from the outer EVM call (x/evm/keeper/erc20.go:183-189, 241-277).

        Exploit scenario

        Not specified.

        Recommendation

        Bound nested calls by the outer call's remaining gas: pass contract.Gas (minus a margin) as the gas limit for the inner ApplyEvmMsg instead of estimating, and deduct the inner GasUsed from the precompile's returned gas. Drop the binary-search estimation for in-transaction calls. Verify with a test that a bankSend against an ERC20 whose transfer loops until out of gas fails when the outer call's gas is small and consumes gas proportional to the inner work.

        Claude Security (Sonnet 5.5)

        Module-initiated ERC20 calls run unmetered EVM code and a ~25-probe gas-estimation binary search, giving a cheap chain-halting amplifier via attacker-controlled ERC20s

        x/evm/keeper/erc20.go:264 Predicted severity: High

        Root cause

        Vulnerable symbol: computeCommitGasLimit

        Preconditions: Attacker can pay the FunToken creation fee (default 10,000 NIBI) and deploy an ERC20; Estimated CPU cost of the EVM interpreter on all validators is similar (about 5-15 s per estimation sequence is an estimate, not measured)

        Offending code:

        gasRes, err := k.EstimateGasForEvmCallType(

        Impact

        Chain-wide liveness failure/halt for the price of the FunToken creation fee plus negligible gas; also underpricing of EVM compute relative to block gas limits.

        Description

        Any user can register an attacker-written ERC20 as a FunToken. State-transition paths (the bankSend precompile, MsgConvertCoinToEvm, FunToken creation) then call that contract with a 25M gas cap and first estimate gas by binary search, executing the contract about 25 times, but charge only a flat 42000 EVM gas (precompile) or ordinary Cosmos store gas (message path).

        Exploit scenario

        Attacker pays the FunToken creation fee (default 10,000 NIBI, burned) to map a malicious ERC20 M whose transfer/balanceOf burn all supplied gas. (a) A contract loops bankSend(M, ...) in try/catch inside one EVM tx; each iteration costs 42000 EVM gas but forces roughly 25 estimation probes of up to 25M gas plus the final run (hundreds of millions of EVM gas of CPU). (b) Or the attacker submits many ordinary MsgConvertCoinToEvm txs for erc20/M; each costs about one cheap Cosmos tx of gas but triggers the same work in DeliverTx. Blocks then take minutes to hours to execute on every validator.

        Recommendation

        Do not estimate gas inside state transitions; call module-initiated ERC20 methods with a small fixed gas cap and charge the consumed EVM gas to the outer gas meter (EVM or Cosmos). Bound nested precompile calls by the caller's remaining gas and price the precompile by actual work. Consider restricting FunToken creation to audited tokens or require ERC20s to pass checks.

        Claude Security (Opus 5.5)

        Nested EVM executions from native code (precompile bankSend, ConvertCoinToEvm, CreateFunToken) get a 25M gas cap plus a binary-search estimate and are never charged

        x/evm/keeper/erc20.go:217 Predicted severity: High

        Root cause

        Vulnerable symbol: Keeper.CallContractWithInput

        Preconditions: Attacker controls an ERC20 and either pays the CreateFunToken fee once or holds 10k NIBI for the failing-creation path

        Offending code:

        evmResp, err = k.ApplyEvmMsg(

        Impact

        Large compute amplification that lets an unprivileged user slow or halt block production (chain liveness).

        Description

        CallContractWithInput hard-codes DefaultEthCallGasLimit (25M). For commit calls it runs a full EstimateGas binary search (about 25 executions) and then executes again, but evmResp.GasUsed is never consumed from ctx.GasMeter(). The FunToken precompile charges a flat 42,000 gas for all of it.

        Exploit scenario

        The attacker deploys an ERC20 whose transfer() burns about 24M gas before returning true, and maps it with CreateFunToken. In a 30M-gas EVM tx, a contract calls bankSend about 700 times at roughly 42k gas each. Each call triggers about 25 binary-search runs plus a commit run of up to 24M gas, roughly 6e8 gas of unpaid compute per call and about 4e11 per tx, which stalls block execution. Without paying the mapping fee: CreateFunToken only needs the 10k NIBI fee balance, which is refunded when the msg fails. With name() and symbol() each burning about 24M gas and decimals() reverting, every cheap failing Cosmos tx forces about 48M gas of unmetered EVM work.

        Recommendation

        Consume evmResp.GasUsed, and the estimation cost, from ctx.GasMeter() in CallContractWithInput. Derive the nested gas limit from the caller's remaining gas instead of a fixed 25M. Make the precompile's RequiredGas or the EVM's gas accounting reflect nested execution, and drop the per-call binary search.

        Vercel Security Review

        FunToken charges fixed gas for independently metered ERC20 execution

        x/evm/precompile/funtoken.go:45 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. bankSend is charged a constant 42,000 gas** - x/evm/precompile/funtoken.go:45

        ```go title="x/evm/precompile/funtoken.go:45"

        return gethparams.TxGas * 2

        ```

        **2. Its ERC20 transfer receives an independent execution allowance** - x/evm/keeper/erc20.go:183-186

        ```go title="x/evm/keeper/erc20.go:183-186"

        gasLimit := serverconfig.DefaultEthCallGasLimit

        gasLimit, err = computeCommitGasLimit(

        commit, gasLimit, &fromAcc, contract, contractInput, k, ctx,

        )

        ```

        This allows up to 25 million gas plus binary-search estimation work, irrespective of the outer precompile's remaining gas.

        **3. Runtime gas usage is discarded** - x/evm/keeper/erc20.go:92

        ```go title="x/evm/keeper/erc20.go:92"

        return erc20Bool.Value, nil

        ```

        Only the transfer's boolean reaches bankSend; its EVM GasUsed never reduces the calling contract's gas. An attacker can register an ERC20 with computationally expensive successful transfers and repeatedly call bankSend, imposing validator work far exceeding transaction/block gas accounting.

        Exploit scenario

        Not specified.

        Recommendation

        Execute ERC20 calls inside the active EVM with gas drawn from the caller's remaining gas, and return unused gas normally. Avoid binary-search gas estimation during consensus execution. If keeper calls remain, enforce a caller-derived finite budget and charge all nested execution work before returning.

      • Gas spent in internal EVM calls is not charged to the user for MsgCreateFunToken and MsgConvertCoinToEvm nibiru-6 · 4 writeups High

        V12

        Token accessor execution bypasses transaction gas accounting

        app/server/config/server_config.go:61 Predicted severity: High

        Root cause

        Keeper-internal EVM simulations use a fixed execution allowance and discard MsgEthereumTxResponse.GasUsed rather than debiting the enclosing SDK gas meter. The SDK-facing registration and conversion entrypoints therefore omit the EVM execution work from their gas accounting.

        Impact

        Inference: user-selected token implementations can amplify validator CPU and memory work relative to transaction and block gas accounting, degrading block processing availability through repeated registration attempts or conversions. The per-call EVM limit bounds each execution, but does not bound cumulative accessor work by the enclosing SDK transaction's purchased gas; no permanent chain halt is claimed.

        Description

        Noncommitting ERC20 accessor calls always receive the fixed DefaultEthCallGasLimit of 25,000,000, independently of the surrounding Cosmos transaction's remaining gas. ApplyEvmMsg computes EVM gas usage and returns it in MsgEthereumTxResponse, but CallContractWithInput and the balance and metadata loaders never charge that usage to the SDK gas meter. Registration calls three accessors, and ERC20-origin redemption calls three balance accessors in addition to its transfer operation. A token can spend nearly the entire per-call allowance in arithmetic or memory operations and still return valid ABI data without proportionate SDK store work. Consequently, the on-chain caller's charged gas does not account for the execution work performed by these reads.

        Devin Security

        Module-initiated EVM calls into user-supplied ERC20 contracts do not charge EVM gas to the Cosmos transaction

        x/evm/keeper/erc20.go:167 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A user can make every validator run up to tens of millions of EVM gas worth of work per message while paying only a small Cosmos fee, which can slow block production.

        ##### What's wrong

        This is unmetered computation. CallContractWithInput runs an EVM message with a 25,000,000 gas limit, plus a binary-search gas estimate when it commits. The EVM gas it uses is never consumed on the Cosmos transaction's gas meter. Only key-value store reads and writes are charged.

        ##### Who can do it

        Mallory deploys an ERC20 whose balanceOf, transfer, name, symbol and decimals functions spin in loops until they nearly run out of gas. She pays the creation fee once and creates a FunToken mapping for it with MsgCreateFunToken. She then sends many cheap MsgConvertCoinToEvm messages for the matching erc20/... bank coin.

        - Mallory has a funded account and pays the FunToken creation fee once.

        - Mallory holds a small amount of the erc20/<her contract> bank coin.

        ##### What they get

        Each conversion runs three balanceOf calls at up to 25M gas each. It also runs a transfer whose gas estimate repeats the call about 25 times. Validators do this work for almost no fee, so block times can grow. This affects availability only. No funds are lost.

        ##### How it works

        1. convertCoinNativeERC20 calls BalanceOf and Transfer on the mapped contract in x/evm/keeper/msg_server.go:593-644.

        2. CallContractWithInput sets the gas limit to DefaultEthCallGasLimit (25,000,000) in x/evm/keeper/erc20.go:183.

        3. For commits, computeCommitGasLimit runs EstimateGasForEvmCallType, which binary-searches by executing the call repeatedly, in x/evm/keeper/erc20.go:241-276.

        4. ApplyEvmMsg returns GasUsed, but CallContractWithInput never consumes it on ctx.GasMeter() in x/evm/keeper/erc20.go:217-228.

        Exploit scenario

        Not specified.

        Recommendation

        Consume evmResp.GasUsed on ctx.GasMeter() after each module-initiated call, including the estimation runs, as upstream did in PR #2180. Bound the gas limit by the remaining Cosmos gas. Add a test that a conversion against a gas-burning ERC20 fails with out-of-gas when the Cosmos gas limit is low.

        Claude Security (Sonnet 5.5)

        Module-initiated ERC20 calls run unmetered EVM code and a ~25-probe gas-estimation binary search, giving a cheap chain-halting amplifier via attacker-controlled ERC20s

        x/evm/keeper/erc20.go:264 Predicted severity: High

        Root cause

        Vulnerable symbol: computeCommitGasLimit

        Preconditions: Attacker can pay the FunToken creation fee (default 10,000 NIBI) and deploy an ERC20; Estimated CPU cost of the EVM interpreter on all validators is similar (about 5-15 s per estimation sequence is an estimate, not measured)

        Offending code:

        gasRes, err := k.EstimateGasForEvmCallType(

        Impact

        Chain-wide liveness failure/halt for the price of the FunToken creation fee plus negligible gas; also underpricing of EVM compute relative to block gas limits.

        Description

        Any user can register an attacker-written ERC20 as a FunToken. State-transition paths (the bankSend precompile, MsgConvertCoinToEvm, FunToken creation) then call that contract with a 25M gas cap and first estimate gas by binary search, executing the contract about 25 times, but charge only a flat 42000 EVM gas (precompile) or ordinary Cosmos store gas (message path).

        Exploit scenario

        Attacker pays the FunToken creation fee (default 10,000 NIBI, burned) to map a malicious ERC20 M whose transfer/balanceOf burn all supplied gas. (a) A contract loops bankSend(M, ...) in try/catch inside one EVM tx; each iteration costs 42000 EVM gas but forces roughly 25 estimation probes of up to 25M gas plus the final run (hundreds of millions of EVM gas of CPU). (b) Or the attacker submits many ordinary MsgConvertCoinToEvm txs for erc20/M; each costs about one cheap Cosmos tx of gas but triggers the same work in DeliverTx. Blocks then take minutes to hours to execute on every validator.

        Recommendation

        Do not estimate gas inside state transitions; call module-initiated ERC20 methods with a small fixed gas cap and charge the consumed EVM gas to the outer gas meter (EVM or Cosmos). Bound nested precompile calls by the caller's remaining gas and price the precompile by actual work. Consider restricting FunToken creation to audited tokens or require ERC20s to pass checks.

        Claude Security (Opus 5.5)

        Nested EVM executions from native code (precompile bankSend, ConvertCoinToEvm, CreateFunToken) get a 25M gas cap plus a binary-search estimate and are never charged

        x/evm/keeper/erc20.go:217 Predicted severity: High

        Root cause

        Vulnerable symbol: Keeper.CallContractWithInput

        Preconditions: Attacker controls an ERC20 and either pays the CreateFunToken fee once or holds 10k NIBI for the failing-creation path

        Offending code:

        evmResp, err = k.ApplyEvmMsg(

        Impact

        Large compute amplification that lets an unprivileged user slow or halt block production (chain liveness).

        Description

        CallContractWithInput hard-codes DefaultEthCallGasLimit (25M). For commit calls it runs a full EstimateGas binary search (about 25 executions) and then executes again, but evmResp.GasUsed is never consumed from ctx.GasMeter(). The FunToken precompile charges a flat 42,000 gas for all of it.

        Exploit scenario

        The attacker deploys an ERC20 whose transfer() burns about 24M gas before returning true, and maps it with CreateFunToken. In a 30M-gas EVM tx, a contract calls bankSend about 700 times at roughly 42k gas each. Each call triggers about 25 binary-search runs plus a commit run of up to 24M gas, roughly 6e8 gas of unpaid compute per call and about 4e11 per tx, which stalls block execution. Without paying the mapping fee: CreateFunToken only needs the 10k NIBI fee balance, which is refunded when the msg fails. With name() and symbol() each burning about 24M gas and decimals() reverting, every cheap failing Cosmos tx forces about 48M gas of unmetered EVM work.

        Recommendation

        Consume evmResp.GasUsed, and the estimation cost, from ctx.GasMeter() in CallContractWithInput. Derive the nested gas limit from the caller's remaining gas instead of a fixed 25M. Make the precompile's RequiredGas or the EVM's gas accounting reflect nested execution, and drop the per-call binary search.

      • Precompiles use the global Cosmos gas meter instead of a local meter, allowing gas-limit evasion nibiru-7 · 6 writeups High

        V12

        Wasm precompiles inherit an unenforced execution budget

        app/evmante/evmante_gas_consume.go:150 Predicted severity: Informational

        Root cause

        The custom Wasm precompile inherits an SDK meter whose configured limit is informational only. The cross-VM call does not bind native execution work to the remaining EVM gas budget in the repository-local code.

        Impact

        An externally invoked Wasm contract can plausibly perform work beyond the gas purchased for its EVM precompile call, degrading transaction or node availability. Whether this permits unbounded execution rather than bounded undercharging depends on the absent wasmd/wasmvm execution-budget implementation; the searched boundary includes Ethereum ante metering, EVM construction, StateDB context access and all repository-local precompile gas handling.

        Description

        The Ethereum ante path installs InfiniteGasMeter on the SDK context before execution, and NewEVM exposes that execution context to custom precompiles through StateDB. The meter tracks gas consumption but never enforces its nominal limit, always reports that it is not out of gas, and returns MaxUint64 as remaining gas. The Wasm precompile passes this context directly into Wasm.Execute without replacing the meter or deriving a budget from the EVM call's remaining gas. Its advertised EVM cost is based on input length and flat storage pricing rather than the executed Wasm work. This establishes an unenforced host-side execution budget at the cross-VM boundary, while the external Wasm keeper's independent limits remain unverified.

        Codex Security (GPT-6 Sol)

        EVM gas accounting does not bound Wasm precompile work

        x/evm/precompile/wasm.go:69 Predicted severity: High

        Root cause

        Calldata-based RequiredGas charges EVM gas while executeMulti runs Wasm in loop under InfiniteGasMeter.

        Impact

        An EVM caller can trigger Wasm and nested ERC20 execution that consumes validator resources beyond the gas charged to the transaction or block. EVM gas and calldata limit count calls/input but may not account for downstream Wasm work.

        Description

        An EVM caller can trigger Wasm and nested ERC20 execution that consumes validator resources beyond the gas charged to the transaction or block.

        Exploit scenario

        Calldata-based RequiredGas charges EVM gas while executeMulti runs Wasm in loop under InfiniteGasMeter.

        Recommendation

        Charge actual Wasm and nested EVM work to the outer EVM gas budget and enforce the native gas meter.

        Devin Security (Deep)

        Wasm precompile runs Wasm contracts on the infinite EVM gas meter for a flat EVM gas price

        x/evm/precompile/wasm.go:69 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who can send an Ethereum transaction can make every validator run large amounts of Wasm computation while paying only a few thousand EVM gas per call, which lets them underpay for execution by orders of magnitude and slow block production for the whole network.

        ##### What's wrong

        This is missing gas accounting for nested execution. The Wasm precompile charges a flat EVM gas price based only on input length, then runs the Wasm contract on the SDK context taken from the StateDB. That context carries the infinite gas meter that the EVM ante chain installed, so the Wasm VM is handed gasWanted - consumed SDK gas (up to the whole block gas limit), its real gas use is never deducted from the EVM call's gas, and the meter never panics.

        ##### Who can do it

        Alice runs a validator for the Nibiru network. Mallory is anyone with a funded Ethereum wallet. She deploys a Wasm contract that loops for as long as its gas allows and an EVM contract that calls the Wasm precompile execute on it in a loop. She then sends one Ethereum transaction to her EVM contract.

        Conditions that must hold:

        - Mallory can deploy or find a Wasm contract that does heavy computation (Wasm code upload permissions allow it, or any existing compute heavy contract works).

        - Her Ethereum transaction has a gas limit near the block gas limit so the inner Wasm call receives a large SDK gas budget.

        ##### What they get

        Mallory makes Alice's node, and every other validator, spend roughly the full block gas budget of Wasm CPU time per precompile call while she pays only the flat precompile cost in EVM gas. Each block can hold many such transactions because their reported EVM gas use is tiny, so block execution time grows far beyond what the block gas limit is meant to allow, slowing or stalling the chain. She also gets large amounts of Wasm execution for a fraction of the fee that a normal Cosmos transaction would pay, which is lost fee income for Alice and the other validators.

        ##### How it works

        1. EthSetupContextDecorator installs an infinite SDK gas meter and zero KV gas configs for every EVM transaction (app/evmante/evmante_setup_ctx.go:40-42), and AnteDecEthGasConsume replaces it with NewInfiniteGasMeterWithLimit(gasWanted) whose ConsumeGas never panics and whose IsOutOfGas is always false (app/evmante/evmante_gas_consume.go:151, eth/gas_limit.go:45-50, 102-109, 135-137).

        2. Mallory's EVM contract calls the Wasm precompile; geth deducts only RequiredGas, which is a flat write cost plus a per byte cost on the input (x/evm/precompile/precompile.go:109-132, x/evm/precompile/wasm.go:70-72).

        3. Run takes the SDK context from the StateDB and calls p.Wasm.Execute with it (x/evm/precompile/wasm.go:97-101, 161).

        4. The wasmd keeper sizes the Wasm VM gas budget from that context's meter limit minus consumed gas, so the contract receives up to the EVM transaction's full gas limit in SDK gas, and when it finishes the keeper consumes that gas on the infinite meter without any effect on the EVM call's remaining gas.

        5. The EVM call returns having spent a few thousand EVM gas; the transaction's reported gas use and the block gas meter do not reflect the Wasm work, so Mallory repeats the call in a loop and across many transactions in one block.

        Exploit scenario

        Not specified.

        Recommendation

        In every precompile that calls into Cosmos keepers (wasm.go, funtoken.go, oracle.go), wrap the StateDB context with a fresh bounded gas meter before calling the keeper (ctx.WithGasMeter(sdk.NewGasMeter(contract.Gas)) with normal KV gas configs), then after the call charge the SDK gas consumed to the EVM call with contract.UseGas(ctx.GasMeter().GasConsumed()) and fail the call if it cannot pay. Keep RequiredGas as the floor. Verify with a test that calls execute on a Wasm contract that burns a known amount of gas and asserts that the EVM call's gas used grows by at least that amount, and that an EVM call with too little remaining gas fails with out of gas instead of completing.

        Claude Security (Sonnet 5.5)

        Wasm precompile query runs the CosmWasm VM on the eth_call ctx, which has an infinite gas meter, so wasm gas is unbounded

        x/evm/precompile/wasm.go:199 Predicted severity: Medium

        Root cause

        Vulnerable symbol: precompileWasm.query

        Preconditions: JSON-RPC or gRPC enabled on the target node; Attacker can upload or instantiate a looping wasm contract (default wasmd params allow everybody; governance may restrict this); wasmd treats an infinite gas meter as MaxUint64 runtime gas (believed, not verified offline)

        Offending code:

        respBz, err := p.Wasm.QuerySmart(ctx, wasmContract, req)

        Impact

        Unauthenticated denial of service of RPC/gRPC nodes (resource exhaustion); consensus is not affected because the unlimited ctx is only used in query paths.

        Description

        EthCall executes ApplyEvmMsg on the raw gRPC query ctx, whose gas meter is infinite and is never replaced. The Wasm precompile passes that ctx straight to the wasm keeper, which (by wasmd's runtimeGasForContract) hands the VM an effectively unlimited gas budget, bypassing the smart_query_gas_limit that normal wasm queries get.

        Exploit scenario

        Attacker uploads a CosmWasm contract whose query handler loops forever, then repeatedly sends eth_call (or gRPC EthCall) to the Wasm precompile query(contract, req) on a public JSON-RPC/gRPC node. Each request pins a CPU core indefinitely.

        Recommendation

        Wrap the ctx passed to wasm in the precompile with a bounded gas meter derived from the remaining EVM gas (or the wasm smart-query gas limit), and add an overall cancellation/timeout for eth_call execution.

        Claude Security (Opus 5.5)

        Wasm precompile execution gas is consumed on an infinite gas meter that ApplyEvmTx resets, so CosmWasm compute from the EVM is unpaid and not counted toward the block limit

        x/evm/precompile/wasm.go:71 Predicted severity: Medium

        Root cause

        Vulnerable symbol: precompileWasm.RequiredGas

        Preconditions: Attacker can send EVM txs and point them at any wasm contract (or deploy one)

        Offending code:

        return RequiredGas(input, embeds.SmartContract_Wasm.ABI)

        Impact

        Unpaid compute and a block-gas-limit bypass that unprivileged users can use to degrade or halt block production.

        Description

        The precompile charges only a byte-based KV cost (about 2000 + 30*len). Wasm then runs on ctx, whose gas meter is the EVM ante's InfiniteGasMeterWithLimit(gasWanted), so wasm gets the whole tx gas limit as budget. ApplyEvmTx then overwrites the meter with the EVM gasUsed only, so fees, refunds and block gas ignore the wasm work.

        Exploit scenario

        The attacker sends EVM txs with gasLimit near the block max that call wasm.execute or query on a CPU-heavy wasm contract. Each tx is charged about 50k EVM gas, with the rest refunded, and adds only 50k to the block gas meter. Yet it runs up to gasLimit worth of wasm gas. Hundreds of these fit in one block, multiplying validator work far beyond the block gas limit.

        Recommendation

        After each wasm call, measure the SDK gas consumed and deduct it from the EVM contract's gas (or include it in evmResp.GasUsed). Alternatively run wasm with a gas meter bounded by the precompile's remaining EVM gas.

        Vercel Security Review

        Wasm precompile execution bypasses transaction and block gas accounting

        x/evm/precompile/precompile.go:130 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. The new Wasm precompile prices input bytes, not execution** - x/evm/precompile/precompile.go:130-131

        ```go title="x/evm/precompile/precompile.go:130-131"

        argsBzLen := uint64(len(input[4:]))

        return (costPerByte * argsBzLen) + costFlat

        ```

        **2. Arbitrary Wasm runs without charging its work to EVM gas** - x/evm/precompile/wasm.go:160-161

        ```go title="x/evm/precompile/wasm.go:160-161"

        callerBech32 := eth.EthAddrToNibiruAddr(caller)

        data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)

        ```

        The inherited SDK meter is unenforced (app/evmante/evmante_gas_consume.go:150-152; eth/gas_limit.go:106-112). No contract.UseGas accounts for Wasm consumption.

        **3. Accrued SDK consumption is discarded afterward** - x/evm/keeper/gas_fees.go:76-77

        ```go title="x/evm/keeper/gas_fees.go:76-77"

        ctx.GasMeter().RefundGas(ctx.GasMeter().GasConsumed(), "reset the gas count")

        ctx.GasMeter().ConsumeGas(gasUsed, "apply evm transaction")

        ```

        A signer able to invoke expensive Wasm code can repeatedly purchase small EVM calls while imposing disproportionately large validator work outside transaction/block gas limits, stalling block processing.

        Exploit scenario

        Not specified.

        Recommendation

        Execute each native precompile with an enforced SDK gas meter bounded by the EVM call's remaining gas, convert gas units consistently, and deduct actual native consumption from the active vm.Contract. Preserve that consumption on failure and out-of-gas paths; include it in block gas accounting. Apply this to instantiate, execute, executeMulti, and query paths.

      • Cosmos SDK state changes made by precompiles are not reverted when the EVM call reverts nibiru-8 · 5 writeups High

        V12

        Caught reverts retain cross-VM custody mutations

        x/evm/precompile/funtoken.go:67 Predicted severity: High

        Root cause

        Stateful precompile effects and nested keeper EVM commits bypass the enclosing StateDB's rollback journal; the only SDK cache boundary is the full transaction, not each EVM call frame.

        Impact

        Inference: a contract can revert a subcall's internal withdrawal debit while retaining its bank payout, then catch the revert in a successful outer transaction; repeated withdrawals can exhaust collateral managed by that contract. A transfer committed before an ABI-decoding or later bank-send error can also remain escrowed despite a caught failed conversion, leaving the depositor without the promised bank payout.

        Description

        The FunToken precompile writes bank state directly through the SDK context and executes transfer and burn through independently created, committed EVM StateDB instances. Those mutations are not appended to the enclosing EVM's journal. Snapshot and RevertToSnapshot only record and replay that enclosing journal, so they cannot undo the precompile's SDK writes or its nested keeper commits. ApplyEvmTx discards its transaction cache when the entire EVM transaction fails, but commits it when an enclosing contract catches a reverted subcall and ultimately succeeds. Thus transaction-level caching does not provide call-frame atomicity for either a completed conversion followed by a nested revert or an adapter error after a transfer has already committed.

        Codex Security (GPT-6 Sol)

        EVM snapshot reverts leave native precompile writes intact

        x/evm/precompile/wasm.go:161 Predicted severity: High

        Root cause

        Wasm/FunToken mutate SDK context; StateDB RevertToSnapshot undoes only EVM journal; successful outer tx commits SDK cache.

        Impact

        A contract can catch a reverted nested EVM call after a native precompile has changed Wasm or bank state, allowing native writes to survive the EVM revert. Top-level failed EVM tx discards SDK cache; issue requires caught nested revert and outer success.

        Description

        A contract can catch a reverted nested EVM call after a native precompile has changed Wasm or bank state, allowing native writes to survive the EVM revert.

        Exploit scenario

        Wasm/FunToken mutate SDK context; StateDB RevertToSnapshot undoes only EVM journal; successful outer tx commits SDK cache.

        Recommendation

        Include native keeper writes in EVM snapshot rollback, or execute precompile mutations in a matching cache context that is discarded on nested revert.

        Devin Security

        FunToken bankSend writes outside the EVM state cache, so a stale ERC20 balance is written back and tokens are spent twice

        x/evm/precompile/funtoken.go:67 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone with an EVM account can turn their ERC20 tokens into bank coins and still keep the tokens, then convert the duplicate coins back to drain other users' escrowed tokens.

        ##### What's wrong

        This is a state desynchronization double spend. The FunToken precompile moves ERC20 tokens through a separate inner EVM call that commits straight to the Cosmos context, but the outer EVM transaction keeps its own cached copy of the same ERC20 storage and writes that stale copy back at the end.

        ##### Who can do it

        Alice and many other users have converted their bank coins or ERC20 tokens through a FunToken mapping, so the EVM module holds their escrow. Mallory, who has any funded EVM account, deploys a small contract and holds 100 units of a mapped ERC20 token.

        - Mallory can send an Ethereum transaction (no special permissions).

        - The ERC20 token has a FunToken mapping (any token can get one by paying the creation fee).

        - The outer EVM call reads the ERC20 balance slot before calling bankSend, so it is cached.

        ##### What they get

        Mallory's contract calls balanceOf on the token, then bankSend for 100 units, then transfer of 100 units to a second address. The bank side gives her 100 coins, and the outer EVM still believes she has 100 tokens, so the transfer succeeds and overwrites the inner deduction. She repeats this and uses ConvertCoinToEvm to pull real tokens out of the EVM module escrow. For coin-backed mappings, bankSend pays her out of escrowed native coins directly. She can drain every user's escrow for every mapped token.

        ##### How it works

        1. Run takes the raw transaction context from the StateDB with stateDB.GetContext() (funtoken.go:73) and passes it to bankSend.

        2. bankSend calls ERC20().Transfer (funtoken.go:162), which runs CallContractWithInput with commit=true and builds a new StateDB on the same context (x/evm/keeper/erc20.go:167-224), so the balance change is written to the store immediately.

        3. bankSend then mints or releases bank coins and sends them to the recipient on that same context (funtoken.go:168-195). None of this is recorded in the outer StateDB journal.

        4. The outer StateDB already cached the ERC20 balance slot in originStorage (x/evm/statedb/state_object.go:258-266). A later transfer in the same transaction reads the stale value.

        5. At the end, StateDB.Commit writes the dirty slot with the stale-based value (x/evm/statedb/statedb.go:454-480), which undoes the inner deduction while the bank coins stay minted.

        6. If an inner call frame that invoked bankSend reverts while the outer transaction succeeds, the bank and ERC20 changes also persist because they were never journaled.

        Exploit scenario

        Not specified.

        Recommendation

        Make precompile side effects part of the StateDB. Before a precompile runs, flush the outer StateDB's dirty state to a cached context. Run the precompile on that cached context, record a journal entry so a revert discards it, and then reload or invalidate the affected cached state objects (ERC20 contract storage and account balances) after the call. Upstream Nibiru later added a precompile journal entry and a CacheCtx inside the StateDB for this reason. To check the fix, write an end-to-end test where one contract calls balanceOf, then bankSend, then transfer in a single transaction. The transfer must fail with insufficient balance. Add a second test where bankSend runs in a call frame that reverts inside try/catch. Both the bank balance and the ERC20 balance must be unchanged.

        Devin Security (Deep)

        Wasm precompile fund transfers are minted back to the caller when the EVM state is committed (infinite NIBI mint)

        x/evm/precompile/wasm.go:92 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who can send an Ethereum transaction on the chain can create NIBI out of nothing by paying funds through the Wasm precompile, because the EVM commit step mints the spent amount straight back to the payer.

        ##### What's wrong

        This is a stale balance cache being used as the source of truth. The EVM state database caches each account's NIBI balance when it first touches the account, and on commit it forces the bank balance to equal that cached number by minting or burning the difference. The Wasm precompile moves NIBI through the bank module directly, outside that cache, so the cache never learns about the spend and the commit mints it back.

        ##### Who can do it

        Alice runs a validator on Acme Chain. Mallory holds a small amount of NIBI in an ordinary account. Mallory deploys a tiny Solidity contract and instantiates (or picks) any Wasm contract that will hand funds back to her. She sends one Ethereum transaction that calls her contract, which stores one value and then calls the Wasm precompile execute with funds set to all of its NIBI.

        - Mallory needs an account with NIBI for gas and for the first funds payment.

        - Mallory needs any Wasm contract address that accepts coins (she can create one through the precompile instantiate method if a permissionless code ID exists, or use any existing contract that returns funds).

        - Nothing else is required. The Wasm precompile is registered unconditionally in InitPrecompiles and wired into the app in app/app.go:192.

        ##### What they get

        Mallory's contract pays F NIBI to the Wasm contract, and at the end of the same transaction the chain mints F NIBI back to Mallory's contract. The Wasm contract still holds the F it received, so each call creates F new NIBI. She can repeat this inside one transaction with executeMulti and across transactions without limit, inflating the native token supply and draining value from every NIBI holder on the chain. Because instantiate also moves funds, the same trick works there.

        The same root cause means that when an inner EVM call reverts after calling this precompile, the Wasm and bank side effects stay in place while the EVM side is rolled back, so dApps cannot rely on atomicity around these calls either.

        ##### How it works

        1. Mallory's contract A is called by her transaction; the EVM loads A's account into the state database with its current bank balance B (x/evm/statedb/statedb.go:209-224, x/evm/keeper/statedb.go:27-35).

        2. A writes one storage slot, which marks A as dirty in the journal (x/evm/statedb/state_object.go:277-290).

        3. A calls the Wasm precompile execute with funds = F unibi; the precompile takes the raw transaction context from the state database and calls the Wasm keeper with A's address as the payer (x/evm/precompile/wasm.go:97, 160-161).

        4. The Wasm keeper moves F unibi from A's bank account to the Wasm contract in that context. The EVM state database's cached balance for A is still B.

        5. The transaction finishes and StateDB.Commit writes every dirty account with its cached balance (x/evm/statedb/statedb.go:454-467).

        6. SetAccount calls SetAccBalance, which compares the cached B against the real bank balance B minus F and mints F to A to make them match (x/evm/keeper/statedb.go:68-100, 129).

        7. ApplyEvmTx commits the cached context because the EVM call did not fail (x/evm/keeper/msg_server.go:104-107). A has B again and the Wasm contract has F.

        Exploit scenario

        Not specified.

        Recommendation

        Make precompile side effects part of the EVM state database's transactional model. Two common approaches: (a) have the precompile run its bank and Wasm calls against a cached context (ctx.CacheContext()), append a journal entry to the StateDB that commits that cache only on Commit and discards it on revert, and after the call refresh the cached BalanceWei of any EVM account whose bank balance changed (or invalidate the state objects for the caller); or (b) stop using the cached balance as the source of truth in Commit: track balance deltas in the journal and apply AddBalance/SubBalance style changes to the bank module instead of forcing the bank balance to equal the cached value. In either case, reject funds in the EVM denom from precompiles until the sync is fixed. To verify: write a test where a contract stores a value, calls execute with funds of N unibi to a Wasm contract, and assert after the transaction that the caller's bank balance decreased by N and total supply of unibi is unchanged.

        Vercel Security Review

        Native precompile writes survive reverted EVM call frames

        x/evm/precompile/wasm.go:160 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. New Wasm calls mutate the transaction's SDK context directly** - x/evm/precompile/wasm.go:160-161

        ```go title="x/evm/precompile/wasm.go:160-161"

        callerBech32 := eth.EthAddrToNibiruAddr(caller)

        data, err := p.Wasm.Execute(ctx, wasmContract, callerBech32, msgArgs, funds)

        ```

        **2. EVM rollback restores only its in-memory journal** - x/evm/statedb/statedb.go:440-444

        ```go title="x/evm/statedb/statedb.go:441-444"

        // Replay the journal to undo changes and remove invalidated snapshots

        s.journal.Revert(s, snapshot)

        s.validRevisions = s.validRevisions[:idx]

        ```

        No journal entry restores SDK stores. An attacker can execute a precompile inside an inner frame, revert that frame, and catch the failure externally. Wasm storage and native transfers persist while EVM accounting rolls back.

        **3. A successful outer transaction persists those effects** - x/evm/keeper/msg_server.go:104-107

        ```go title="x/evm/keeper/msg_server.go:104-107"

        if !evmResp.Failed() {

        receipt.Status = gethcore.ReceiptStatusSuccessful

        commit()

        }

        ```

        Top-level failure discards the cache, but caught failures do not, breaking contract atomicity across the VM boundary.

        Exploit scenario

        Not specified.

        Recommendation

        Extend EVM snapshots and rollback to cover the SDK multistore, events, and nested keeper calls. Native writes must be journaled at the same call-frame scope as EVM changes, not merely cached once per top-level transaction. Test successful precompiles followed by inner reverts, caught precompile errors, and partially failing executeMulti calls.

      • RequiredGas() in funtoken and oracle precompiles does not account for dynamic-type gas usage nibiru-9 · 1 writeup Medium

        V12

        Malformed oracle pairs incur size-independent gas charges

        x/evm/precompile/oracle.go:29 Predicted severity: Informational

        Root cause

        A fixed oracle gas charge is combined with unbounded separator splitting and full-input error formatting before pair validation. The failure-path parser work is not bounded or priced by the pair's size in the visible implementation.

        Impact

        The supported resource-risk inference is repeated CPU and allocation pressure from malformed oracle queries whose per-call work grows with input size while their visible gateway gas charge stays constant. The precise exploit budget remains unresolved because the geth replacement's precompile runner is not available in the repository; the searched boundary includes ABI dispatch, pair validation, intrinsic transaction gas, EVM accounting, and RPC gas-cap construction, none of which adds pair-size pricing to this handler.

        Description

        Oracle calls always cost TxGas, regardless of the encoded pair string's length. After ABI decoding, queryExchangeRate passes that caller-controlled string to TryNewPair, which calls strings.Split on every colon before checking that exactly two assets were supplied. For an oversized, colon-heavy string, this allocates a slice proportional to the separator count and then formats the entire invalid string into the error. Denomination validation occurs only after these operations, so it cannot bound their work. Reusing such input across EVM calls can repeat the allocation and formatting at the same gateway price; actual denial-of-service magnitude and any additional dependency-level charging remain unverified.

      • Funtoken precompile does not verify ERC-20 transfer boolean return nibiru-10 · 7 writeups Medium

        V12

        False token transfers mint unbacked redeemable coins

        x/evm/keeper/erc20.go:73 Predicted severity: Critical

        Root cause

        bankSend treats a nil Go error as proof of ERC20 payment while discarding the authoritative boolean returned by erc20Calls.Transfer. Bank minting is consequently not conditional on a successful inbound transfer.

        Impact

        Inference: for a mapped ERC20 that returns false on insufficient balance and permits valid outbound transfers, a caller can mint unbacked bank coins and redeem them against ERC20 reserves deposited by other holders. The existing outbound escrow-balance check limits withdrawals to the available reserves rather than preventing their unauthorized depletion.

        Description

        The Transfer wrapper decodes and returns the ERC20 transfer boolean independently of its Go error. In the inbound FunToken precompile, bankSend discards that boolean and proceeds whenever the Go error is nil. For an ERC20-origin mapping, it then mints amount bank coins and sends them to the requested recipient without verifying that any ERC20 entered escrow. An ERC20 that returns false rather than reverting on insufficient balance therefore allows the conversion to succeed without payment. The outbound conversion checks its transfer boolean and escrow balance, but those checks do not establish that the previously minted bank coins were backed.

        Codex Security (GPT-6 Sol)

        FunToken bankSend mints coins when ERC20 transfer returns false

        x/evm/keeper/erc20.go:86 Predicted severity: High

        Root cause

        ERC20.Transfer returns false,nil; bankSend discards bool and mints/sends corresponding bank coins.

        Impact

        A registered ERC20 that returns false from transfer can cause FunToken to mint and send unbacked native coins. Mapping and positive amount checks do not prove ERC20 transfer success.

        Description

        A registered ERC20 that returns false from transfer can cause FunToken to mint and send unbacked native coins.

        Exploit scenario

        ERC20.Transfer returns false,nil; bankSend discards bool and mints/sends corresponding bank coins.

        Recommendation

        Require ERC20 transfer to return true before minting or sending the mapped bank coin.

        Devin Security

        bankSend ignores the ERC20 transfer result and mints the requested amount instead of the amount received

        x/evm/precompile/funtoken.go:160 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        If a mapped ERC20 returns false instead of reverting, or charges a fee on transfer, a user can get more bank coins than the tokens they put in and use them to drain other holders' escrow.

        ##### What's wrong

        This is a missing return-value and balance check. bankSend throws away the boolean that transfer returns. It also mints amount bank coins without measuring how many tokens the EVM module actually received.

        ##### Who can do it

        Mallory has any EVM account. Acme's token, which returns false on a failed transfer (USDT-style) or takes a transfer fee, has a FunToken mapping, and Alice and others have bridged it.

        - The mapped ERC20 returns false on failure or delivers less than amount.

        - The EVM module holds escrowed tokens from other users.

        ##### What they get

        Mallory calls bankSend with an amount larger than her balance. The token returns false, the precompile ignores it, and it mints her the full amount as bank coins. She then calls ConvertCoinToEvm to take real tokens out of the module escrow that belongs to Alice and the other users. With a fee-on-transfer token, each round trip leaks the fee out of the escrow in the same way.

        ##### How it works

        1. bankSend calls ERC20().Transfer and discards the boolean result (funtoken.go:162).

        2. It builds coins from the requested amount (funtoken.go:168-169) and mints them for non-coin mappings (funtoken.go:181).

        3. It sends those coins to the recipient (funtoken.go:190) without checking the EVM module's balance change.

        4. convertCoinNativeERC20 later releases up to the escrowed balance for those coins (x/evm/keeper/msg_server.go:613-641).

        Exploit scenario

        Not specified.

        Recommendation

        Fail when Transfer returns false. Measure the EVM module's ERC20 balance before and after the transfer, and mint or send only the difference. The reverse path already checks balances this way. To check the fix, add a test with a mock ERC20 whose transfer returns false and a second mock that charges a 1% fee. bankSend must fail for the first and mint 99% for the second.

        Devin Security (Deep)

        bankSend ignores the ERC20 transfer return value and performs no balance check before minting bank coins

        x/evm/precompile/funtoken.go:160 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        For any FunToken whose ERC20 returns false instead of reverting on a failed transfer, anyone can mint bank coins without giving up tokens and then redeem them against other users' escrowed tokens.

        ##### What's wrong

        This is a missing success check on an external token transfer. bankSend calls ERC20().Transfer and discards its boolean result, then mints or pays out bank coins for the full amount. The sibling path convertCoinNativeERC20 in the keeper checks both the boolean and the recipient's balance delta; this path does neither.

        ##### Who can do it

        Mallory, any EVM user, targets an ERC20 that has a FunToken mapping and follows the older ERC20 convention of returning false on insufficient balance rather than reverting.

        - The ERC20 must not revert on a failed transfer (true for a number of legacy tokens; not true for the module-deployed ERC20Minter).

        - Other users must have converted that token to bank coins, so the module holds escrow.

        ##### What they get

        Mallory calls bankSend(TOKEN, N, her_nibi_addr) with no TOKEN balance. The transfer returns false, nothing moves, and the precompile mints N erc20/TOKEN bank coins to her. She converts them back with MsgConvertCoinToEvm, which pays N real TOKEN from the module's escrow deposited by other users. She can repeat until the escrow is empty.

        ##### How it works

        1. bankSend calls p.evmKeeper.ERC20().Transfer(erc20, caller, module, amount, ctx) and keeps only err (x/evm/precompile/funtoken.go:160-165).

        2. Transfer returns (false, nil) when the token returns false without reverting (x/evm/keeper/erc20.go:73-93).

        3. bankSend proceeds to MintCoins and SendCoinsFromModuleToAccount for the full amount (x/evm/precompile/funtoken.go:167-195).

        4. convertCoinNativeERC20 later pays escrowed ERC20 to whoever holds those bank coins (x/evm/keeper/msg_server.go:584-671).

        Exploit scenario

        Not specified.

        Recommendation

        Check the boolean returned by Transfer and fail if false. Also read the module's ERC20 balance before and after the transfer and require the delta to equal amount (as convertCoinNativeERC20 does). Verify with a test using a mock ERC20 whose transfer returns false; bankSend must fail and no bank coins may be minted.

        Claude Security (Sonnet 5.5)

        FunToken bankSend runs ERC20 transfer/burn through a separate StateDB on the shared ctx, so the outer EVM's stale dirty storage overwrites it and ERC20 supply and bank escrow diverge

        x/evm/precompile/funtoken.go:162 Predicted severity: High

        Root cause

        Vulnerable symbol: precompileFunToken.bankSend

        Preconditions: A FunToken mapping exists for a token the attacker can hold (creation is permissionless for a fee); Attacker calls bankSend from a contract that has touched the same token slots earlier in the same tx

        Offending code:

        _, err = p.evmKeeper.ERC20().Transfer(erc20, caller, transferTo, amount, ctx)

        Impact

        Theft of escrowed native coins backing coin-origin FunTokens, and inflation of ERC20-origin tokens (bank coins minted without matching burn, tokens duplicated), both exploitable by any user able to deploy a contract.

        Description

        A contract caller's earlier ERC20 writes are only in the outer StateDB journal, not in the store. bankSend's nested CallContractWithInput creates a fresh StateDB, reads committed (older) balances, commits straight to ctx, and mints or releases bank coins; the outer StateDB later commits its older dirty slot values over the nested writes. Also CWE-252: ERC20().Transfer returns the token's boolean result, but bankSend discards it and then mints (or releases from escrow) the full amount of bank coin. The reverse path convertCoinNativeERC20 checks both res and the receiver's balance delta, so the two paths into the same escrow accounting have inconsistent checks.

        Exploit scenario

        Attacker contract C holds B0 of an ERC20 T that has a FunToken mapping. In one tx: (1) C calls T.transfer(attacker2, B0), which makes C's balance slot dirty in the outer StateDB; (2) C calls bankSend(T, B0, nibi1...). The nested Transfer reads C's committed balance B0, moves B0 to the EVM module, and the precompile mints (or releases from escrow) B0 bank coins to the recipient; (3) at tx end the outer StateDB commits attacker2's B0 and C's dirty slot, and the nested decrement of C is lost or overwritten. Result: attacker2 holds B0 tokens and the recipient holds B0 coins. For a mapping created from a bank coin, the nested Burn lowers totalSupply while the outer balances sum is unchanged and native coins are released from escrow, so the ERC20 mirror becomes under-collateralized and later redeemers lose funds. Repeating doubles the position each tx.

        Recommendation

        Flush the outer StateDB into the ctx before running the precompile and resync (or clear) its cached objects afterward, or perform the ERC20 interaction inside the same StateDB/EVM instance (a normal nested call) rather than via a new StateDB on the shared ctx. Also CWE-252: Require the returned bool to be true and verify the EVM module's ERC20 balance increased by exactly amount before minting or releasing coins, mirroring convertCoinNativeERC20. Consider rejecting fee-on-transfer tokens at mapping creation.

        Claude Security (Opus 5.5)

        FunToken precompile runs a nested EVM on stale KV state that the outer StateDB later overwrites, so ERC20 tokens can be double-spent and escrow drained

        x/evm/precompile/funtoken.go:162 Predicted severity: Critical

        Root cause

        Vulnerable symbol: precompileFunToken.bankSend

        Preconditions: A FunToken mapping exists for the ERC20 (normal protocol state); Attacker holds some of the token and can deploy a contract

        Offending code:

        _, err = p.evmKeeper.ERC20().Transfer(erc20, caller, transferTo, amount, ctx)

        Impact

        Any user can mint ERC20 balances out of nothing and drain the bank-coin or ERC20 escrow behind every FunToken mapping. Bridged assets become insolvent.

        Description

        bankSend takes the outer StateDB's raw sdk.Context and calls ERC20().Transfer/Burn. That goes through CallContractWithInput -> ApplyEvmMsg, which builds a fresh StateDB on the same ctx and commits straight to KV. The nested call cannot see the outer StateDB's uncommitted dirty storage. When the outer tx commits, its cached slots overwrite whatever the nested call wrote. Also CWE-290: bankSend takes contract.CallerAddress, which can be any contract, and passes it as from to ERC20().Transfer. That function builds a new top-level geth Message from that address (erc20.go:192) and runs it with ApplyEvmMsg/NewEVM, which sets TxContext.Origin = msg.From() (msg_server.go:172). The nested execution therefore runs with tx.origin set to a contract address, which normal Ethereum semantics never allow. Also CWE-252: The ConvertCoinToEvm path rejects !res and verifies the exact balance delta. The precompile path to the same escrow discards Transfer's bool and mints amount coins whatever the EVM module actually received.

        Exploit scenario

        The attacker deploys contract C holding 100 units of a FunToken-mapped ERC20 T. In one tx C first calls T.transfer(X, 100) in the EVM, so the outer StateDB caches bal(C)=0 and bal(X)=100 as dirty while KV still says bal(C)=100. C then calls bankSend(T, 100, attackerNibiAddr) on precompile 0x...800. The nested EVM reads bal(C)=100 from KV and moves it to the EVM module. For a coin-backed mapping it then burns those tokens and sends 100 escrowed bank coins to the attacker. For an ERC20-backed mapping it mints 100 coins, which ConvertCoinToEvm later redeems against the module's escrow. At the end of the tx the outer StateDB writes bal(C)=0 and bal(X)=100. X keeps 100 T and the attacker also holds 100 bank coins. Repeating the loop drains the escrow of every mapping. The same staleness can be reached through wasm.execute when the wasm contract dispatches MsgConvertCoinToEvm, which also runs nested EVM calls on the shared ctx.

        Recommendation

        Do not run nested EVM executions against the outer StateDB's context. Run precompile side effects on a cache context that is journaled in the StateDB, flush or commit the outer StateDB's dirty state before the nested call, or do the ERC20 movement inside the outer EVM (for example via the outer StateDB or a sub-call of the current EVM) instead of a separate ApplyEvmMsg. Also CWE-290: Do not start a new top-level EVM message from an arbitrary caller. Either perform the token debit inside the current EVM frame using the existing StateDB and EVM, keeping the outer tx.origin, or have the module account move the tokens (for example with transferFrom and an allowance). If a nested message is unavoidable, reject callers that have code, or set Origin to the outer transaction's origin. Also CWE-252: Require Transfer to return true, and mint or send coins only for the measured increase in the EVM module's ERC20 balance (balance after minus balance before), mirroring convertCoinNativeERC20.

        Vercel Security Review

        Ignored ERC20 transfer failures mint unbacked FunToken coins

        x/evm/keeper/erc20.go:92 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. ERC20 transfer failure can be a successful EVM call** - x/evm/keeper/erc20.go:92

        ```go title="x/evm/keeper/erc20.go:92"

        return erc20Bool.Value, nil

        ```

        A registered ERC20 may legitimately signal insufficient balance by returning false instead of reverting.

        **2. The new deposit path discards that failure flag** - x/evm/precompile/funtoken.go:162-165

        ```go title="x/evm/precompile/funtoken.go:162-165"

        _, err = p.evmKeeper.ERC20().Transfer(erc20, caller, transferTo, amount, ctx)

        if err != nil {

        return nil, fmt.Errorf("failed to send from caller to the EVM account: %w", err)

        }

        ```

        An ordinary caller can request an amount they do not own; false, nil passes this check.

        **3. Native claims are minted without receiving collateral** - x/evm/precompile/funtoken.go:180-182

        ```go title="x/evm/precompile/funtoken.go:180-182"

        } else {

        err = p.bankKeeper.MintCoins(ctx, evm.ModuleName, coins)

        if err != nil {

        ```

        Line 190 pays the requested coins to the caller's recipient. These unbacked claims can redeem other users' escrowed ERC20 through convertCoinNativeERC20.

        Exploit scenario

        Not specified.

        Recommendation

        Require both a nil error and a true transfer result before minting. Also verify the EVM module's ERC20 balance increased by the amount being credited, rejecting unsupported fee-on-transfer or other nonconserving token behavior. Keep failed deposits atomic and test false-returning ERC20 contracts.

    • PDT Staking Solidity ParagonsDAO staking program. Tasks 2 V12 2/2 Codex Sec 1/2 Pashov Opus 1/2 Pashov GPT-6 2/2 Devin 0/2 Devin (Deep) 1/2 Claude Sec 0/2 Claude Opus 0/2 Vercel 0/2

      ParagonsDAO staking program.

      Read the audit report
      • Reward-token registration is irreversible pdt-staking-1 · 2 writeups Critical

        V12

        One broken reward token blocks principal exits

        src/contracts/StakedPDT.sol:221 Predicted severity: High

        Root cause

        distribute() assumes every registered reward balance remains at least its reserve and every balance query succeeds. The append-only token registry provides no failure isolation or retirement path.

        Impact

        A deficient or nonresponsive registered reward token can freeze all principal exits and epoch settlement, not merely claims of that token. Replenishment or repair of the dependency may restore operation, and a manager may extend the epoch, but the contract cannot retire a permanently broken reward token.

        Description

        Every registered reward token is queried and its balance is subtracted from its recorded reserve during distribute(). If one token's balance falls below its reserve, such as a balance of 99 against a reserve of 100, checked subtraction reverts even when another token has ample new rewards. A reverting or invalid balanceOf() implementation similarly aborts the whole rollover. Registration requires only a nonzero, nonduplicate address, and the implementation has no removal or skip mechanism for a failed token. Because users cannot unstake after the deadline, failure of one reward dependency also blocks redemption of the independent PDT principal.

        Pashov (Codex GPT-6 Sol high)

        A malformed reward token can freeze epoch progression

        src/contracts/StakedPDT.sol:221 Predicted severity: Medium

        Root cause

        Registration accepts any nonzero address without checking its token behavior, and distribute loops over every registered token unconditionally.

        Impact

        An invalid reward-token entry can permanently block epoch progression and leave staked PDT locked after the deadline.

        Description

        The token manager can register an address whose balanceOf call fails; every later distribute call reverts and no function can remove the address.

        Exploit scenario

        A token manager registers an EOA or failing token. After the epoch ends, distribute fails on its balanceOf call and unstake rejects all users as out of epoch.

        Recommendation

        Validate balanceOf at registration and provide a controlled removal or skip mechanism for failed tokens.

      • PDT can be set as a reward token and withdrawn by admin pdt-staking-2 · 5 writeups Medium

        V12

        Staking principal can also become reward backing

        src/contracts/StakedPDT.sol:221 Predicted severity: Low

        Root cause

        distribute() partitions rewards only by unclaimedRewards and omits principal liabilities when the reward asset equals pdt. Registration does not prohibit that conflicting asset identity.

        Impact

        Registering PDT as a reward asset makes the same tokens back both principal redemption and reward claims. Reward payouts or manager withdrawals can therefore leave receipts unbacked and cause subsequent unstaking to fail; the scenario depends on a manager-selected reward configuration, not permissionless registration.

        Description

        Reward-token registration permits the immutable PDT address, and distribute() counts the resulting token balance without subtracting receipt principal liabilities. For example, if users have deposited 100 PDT and PDT is registered as a reward token, a rollover reserves those same 100 units as a reward allocation. When the allocated epoch settles, claim() pays those units as rewards while the receipts still represent redeemable PDT. A token-manager withdrawal can likewise remove the registered PDT balance without a principal-liability check. Neither the constructor, registration function, nor distribution distinguishes staking custody from reward surplus.

        Codex Security (GPT-6 Sol)

        Reward manager can withdraw users' staked PDT

        src/contracts/StakedPDT.sol:221 Predicted severity: Medium

        Root cause

        registerNewRewardToken accepts any nonzero address, including the immutable pdt address. withdrawRewardTokens treats membership in that list as sufficient authority to transfer any amount to TOKEN_MANAGER. Principal backing receipts therefore enters the reward-manager withdrawal path.

        Impact

        Complete principal loss is possible, but exploitation requires a token-manager role holder; that role normally has reward custody but is not meant to control staking principal.

        Description

        A TOKEN_MANAGER can register the immutable PDT principal token as a reward token and then withdraw the deposited principal, leaving stPDT receipts unbacked.

        Exploit scenario

        Manager-chosen token address -> rewardTokenList -> withdrawal registration check -> safeTransfer(msg.sender, amount) -> missing principal for unstake

        Recommendation

        Reject the immutable pdt address in reward registration and withdrawal, and enforce separate custody accounting for deposited principal.

        Pashov (Claude Opus 5.5 high)

        PDT can be registered as a reward token, letting staked principal be distributed or withdrawn

        src/contracts/StakedPDT.sol:221 Predicted severity: Low

        Root cause

        The contract does not separate the staking token's principal from reward-token balances.

        Impact

        Stakers' principal gets paid out as rewards or withdrawn by TOKEN_MANAGER, leaving the contract unable to honour unstake (insolvency).

        Description

        registerNewRewardToken does not reject the staking token pdt. Once PDT is registered, distribute treats balanceOf(this) - unclaimedRewards[pdt], which includes every staker's principal, as new rewards. withdrawRewardTokens(pdt, amount) also lets TOKEN_MANAGER take staked principal directly.

        Exploit scenario

        TOKEN_MANAGER (malicious or mistaken) registers PDT to distribute PDT incentives. At the next distribute, all staked PDT is counted as rewards and early claimers withdraw it. Later unstake calls revert for lack of balance. Alternatively, TOKEN_MANAGER calls withdrawRewardTokens(pdt, totalSupply()).

        Recommendation

        Reject newRewardToken == pdt in registerNewRewardToken. If PDT rewards are needed, track principal (totalSupply()) separately and exclude it from reward balances and withdrawals.

        Pashov (Codex GPT-6 Sol high)

        Reward token registration exposes staked PDT principal

        src/contracts/StakedPDT.sol:221 Predicted severity: High

        Root cause

        registerNewRewardToken does not reject newRewardToken == pdt.

        Impact

        A claimant can receive staked principal as a reward and still hold redeemable stPDT, making later withdrawals insolvent.

        Description

        The token manager can register PDT itself as a reward token; distribution then counts deposited principal as free reward inventory while receipt liabilities remain.

        Exploit scenario

        The token manager registers PDT as a reward token. Two users each stake 100 PDT; distribute allocates the held 200 PDT as rewards. A claimant receives PDT while retaining stPDT, leaving insufficient principal for later exits.

        Recommendation

        Reject PDT as a reward token and keep staking principal segregated from reward accounting.

        Devin Security (Deep)

        TOKEN_MANAGER can register PDT as a reward token and withdraw all staked principal; reward withdrawals ignore owed balances

        src/contracts/StakedPDT.sol:221 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        An account holding only the TOKEN_MANAGER role, or an attacker who steals that key, can take every staker's PDT and every unpaid reward in one or two transactions, because the role's functions never check the token or the amount against what the contract owes.

        ##### What's wrong

        This is a missing-restriction bug in privileged functions. registerNewRewardToken accepts any address, including the staking token pdt, and withdrawRewardTokens transfers any amount of any registered token to the caller without checking unclaimedRewards or the staked supply. The role meant to manage reward tokens therefore has unrestricted access to user principal and to rewards already allocated to users.

        ##### Who can do it

        Acme DAO grants TOKEN_MANAGER to a reward-operations wallet so a contractor, Bob, can add new reward tokens. Mallory phishes Bob's key. She calls registerNewRewardToken(pdt) and then withdrawRewardTokens(pdt, totalSupply()), sending every staker's PDT to herself. She can also call withdrawRewardTokens(PRIME, balanceOf(this)) to take the PRIME that stakers earned but have not yet claimed.

        Conditions that must hold:

        - The caller holds TOKEN_MANAGER (granted to initialOwner in the constructor; may be delegated).

        - For the principal drain, pdt is not yet in rewardTokenList (there is no check preventing it).

        ##### What they get

        Mallory gets all PDT ever staked by all users, plus all reward tokens sitting in the contract including those already owed to users. Even an honest but careless TOKEN_MANAGER causes damage: withdrawing more than balance - unclaimedRewards makes distribute underflow at line 272 and revert, which freezes stake and unstake for everyone until the tokens are returned, and makes claim fail for users whose rewards were taken. If PDT is registered, distribute would also pay out staked PDT as rewards, leaving the contract unable to honour unstakes.

        ##### How it works

        1. Mallory, holding TOKEN_MANAGER, calls registerNewRewardToken(pdt) at StakedPDT.sol:221; lines 222 to 237 only reject the zero address and duplicates.

        2. She calls withdrawRewardTokens(pdt, amount) at StakedPDT.sol:312; lines 327 to 340 confirm the token is registered and line 342 transfers amount to msg.sender with no comparison to totalSupply() or unclaimedRewards.

        3. For reward tokens, the same call at line 342 can take tokens counted in unclaimedRewards, and the next distribute computes _rewardBalance - unclaimedRewards[_token] at line 272, which underflows and reverts, locking epoch rollover.

        Exploit scenario

        Not specified.

        Recommendation

        In registerNewRewardToken add require(newRewardToken != pdt). In withdrawRewardTokens cap amount at IERC20(rewardToken).balanceOf(address(this)) - unclaimedRewards[rewardToken] (the idle, not-yet-allocated amount) and revert otherwise. Consider sending withdrawals to a fixed treasury address rather than msg.sender. Test: assert registerNewRewardToken(pdt) reverts, and that withdrawRewardTokens reverts when amount exceeds the idle balance while distribute still succeeds afterwards.

    • Perennial Solidity Perennial perpetuals vault + market. Tasks 3 V12 2/3 Codex Sec 0/3 Pashov Opus 1/3 Pashov GPT-6 1/3 Devin 0/3 Devin (Deep) 1/3 Claude Sec 0/3 Claude Opus 0/3 Vercel 0/3

      Perennial perpetuals vault + market.

      Read the audit report
      • ERC-4626 inflation attack on Vault perennial-1 · 4 writeups Critical

        V12

        Donations can absorb deposits into existing shares

        packages/perennial-vault/contracts/Vault.sol:221 Predicted severity: High

        Root cause

        Share pricing accepts unaccounted direct token transfers through asset.balanceOf() without virtual shares or an equivalent inflation defense. Deposits have no minimum realized-share check at the delayed conversion boundary.

        Impact

        In a low-supply vault, a holder can use a direct donation to make another user's deposit mint zero or disproportionately few shares and then recover the contributed assets through redemption. This is a conditional deposit-loss path; market fees, available maker liquidity, and the configured deposit cap constrain the profitable sizes but do not enforce a minimum realized share amount.

        Description

        _checkpoint includes the vault's raw token balance in the assets snapshot used to price subsequent deposits. An existing holder can transfer assets directly to the vault without receiving additional shares, raising the assets-to-shares ratio while keeping supply small. Neither _update nor checkpoint settlement checks that a deposit ultimately produces nonzero shares or meets a depositor-specified minimum. CheckpointLib._toShares converts at this ratio, permitting a deposit to round down to zero before the account's pending deposit is cleared. The existing holder can subsequently redeem against assets that include both the donation and the absorbed deposit.

        Pashov (Claude Opus 5.5 high)

        Vault is susceptible to share-price inflation by first depositor / donation

        packages/perennial-vault/contracts/types/Checkpoint.sol:55 Predicted severity: Low

        Root cause

        Share pricing uses the donation-manipulable balance, with no virtual shares or minimum liquidity.

        Impact

        Depositors in a freshly launched or nearly empty vault can lose most of their deposit to the attacker.

        Description

        Checkpoint assets are taken from the vault's raw token balance (asset.balanceOf()) plus market collateral, and shares are minted with assets.muldiv(shares, selfAssets), rounding down. An attacker holding a tiny share supply can donate tokens directly to the vault and inflate the price per share, so that later deposits round down to (near) zero shares.

        Exploit scenario

        The attacker deposits the minimum into a new vault, redeems all but a dust amount of shares, then transfers a large amount of DSU directly to the vault. A victim's deposit in the next checkpoint mints 0 shares, and the attacker later redeems the dust shares for the victim's funds.

        Recommendation

        Seed vaults with protocol-owned initial liquidity or burn initial shares, use virtual shares/assets, or track assets internally instead of using balanceOf.

        Pashov (Codex GPT-6 Sol high)

        Direct asset donation can make a later vault depositor mint zero shares

        audit/packages/perennial-vault/contracts/types/Checkpoint.sol:55 Predicted severity: High

        Root cause

        Checkpoint.initialize includes unsolicited asset balance, while _toShares rounds down and Vault.update has no minimum shares output check.

        Impact

        A depositor can transfer assets without receiving shares; incumbent shareholders can recover those assets by redemption.

        Description

        An existing shareholder can donate assets directly to the vault before a new checkpoint, raising the share price until a later deposit rounds to zero shares. The shareholder then captures the deposit.

        Exploit scenario

        An attacker holds all existing shares, donates enough DSU to make assets per share larger than the victim deposit, and the victim deposits into the next checkpoint. The conversion mints zero shares to the victim.

        Recommendation

        Enforce a caller-supplied minimum share output or reject deposits that convert to zero shares.

        Devin Security (Deep)

        First-depositor share price inflation: a holder of a tiny share balance can donate assets to the vault and absorb later deposits that round to zero shares

        packages/perennial-vault/contracts/Vault.sol:221 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can take over a new or nearly empty vault by leaving themselves one share and then donating tokens, after which the next depositors receive zero shares and their deposits become the attacker's money.

        ##### What's wrong

        This is the classic ERC4626 inflation attack. The vault prices shares from the raw token balance in Checkpoint.initialize (asset.balanceOf()), mints shares with floor division in Checkpoint._toShares, and has no minimum share count, no virtual shares, and no check that a deposit mints at least one share.

        ##### Who can do it

        Acme launches a new vault. Mallory, anyone with a wallet, deposits a small amount, waits one settlement, then redeems all but one share unit. She then transfers a large amount of the asset directly to the vault contract. Alice, the next real depositor, sends her deposit through update.

        - The vault's total shares are tiny (a fresh vault or one Mallory has drained to a few share units).

        - Mallory's donation is at least as large as the victim's deposit (times the share count she keeps).

        - The markets have enough outside maker liquidity that _maxRedeem lets Mallory redeem her remaining share later.

        ##### What they get

        Alice's deposit converts to floor(deposit * 1 / (donation + 1)), which is zero shares when her deposit is smaller than the donation. Her assets are now owned by the vault's one share, which Mallory holds. Mallory redeems and walks away with her donation plus Alice's full deposit. This repeats for every depositor who sends less than the donation until someone notices. It affects only this vault, but every depositor of this vault is exposed.

        ##### How it works

        1. Mallory deposits 2*settlementFee + 1 via Vault.update (Vault.sol:204-217); as the first depositor she receives shares at par in toSharesGlobal (Checkpoint.sol:88).

        2. After settlement she redeems 2*settlementFee shares (passes the minimum check at Vault.sol:260 because the proceeds exceed the fee) and claims, leaving global.shares == 1.

        3. She transfers a large donation directly to the vault; Checkpoint.initialize (Checkpoint.sol:55-60, called from Vault.sol:225) and _collateral (Vault.sol:486-490) count it as vault assets, so the checkpoint has 1 share backing donation+1 assets.

        4. Alice deposits; at settlement toSharesGlobal(deposit) runs _toShares (Checkpoint.sol:148-151), which computes deposit.muldiv(1, donation+1) and floors to 0.

        5. Alice's processLocal (Account.sol:82-85) credits 0 shares; her tokens remain vault collateral.

        6. Mallory redeems her single share and receives the whole vault balance, including Alice's deposit.

        Exploit scenario

        Not specified.

        Recommendation

        Add protection against inflation: either mint virtual shares/assets (a decimals offset) in Checkpoint._toShares/_toAssets, or enforce a minimum total share supply (for example lock a small amount of shares at vault initialization) and revert deposits that would mint zero shares. Verify with a test where one user is left with 1 share unit, a large donation is sent to the vault, and a second user deposits; the second user must receive a proportional non-zero share amount (or the deposit must revert).

      • High-volatility ticks can cause bank run due to negative liquidations perennial-2 · 1 writeup High

        V12

        Self-liquidation pays bonuses from other users' collateral

        packages/perennial/contracts/Market.sol:475 Predicted severity: High

        Root cause

        Protected liquidation permits a payout exceeding the account's available collateral and uses pooled token reserves as its cap. Maintenance can rise on a maker position with zero economic loss, allowing a coordinated liquidator to monetize the resulting eligibility.

        Impact

        Under allowed liquidation-rate and maximum-fee settings, self-liquidation can transfer collateral belonging to other accounts to the position controller. Repeating across positions creates account shortfalls funded by the shared market balance rather than a loss imposed on the controller.

        Description

        Liquidation eligibility depends on position maintenance at the latest price, but the liquidation payout is capped by the entire market token balance rather than the account's positive collateral. A maker with no matching taker exposure can become liquidatable after a price rise without incurring offsetting P&L. The account controller can then liquidate that position through its own or another controlled address and withdraw more than the position's deposited collateral. Protected updates bypass the ordinary negative-collateral withdrawal check, leaving the excess payout as debt on the emptied account. This is distinct from price-movement bad debt because the payout itself can create the shortfall on an otherwise zero-P&L position.

      • Markets missing slippage protection perennial-3 Medium
    • Pyth Lazer Solana Rust Pyth Lazer oracle Solana program. Tasks 1 V12 1/1 Codex Sec 1/1 Pashov Opus — Pashov GPT-6 — Devin 1/1 Devin (Deep) 1/1 Claude Sec 1/1 Claude Opus 1/1 Vercel 1/1

      Pyth Lazer oracle Solana program.

      Read the audit report
      • Signature bypass pyth-lazer-solana-1 · 7 writeups Critical

        V12

        Signed Bytes Diverge From Returned Payload

        lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/lib.rs:192 Predicted severity: High

        Root cause

        The verifier treats caller-provided message_offset as proof that raw current-instruction bytes and the separately deserialized message_data are identical. It validates only offset metadata, then consumes message_data without comparing it to the byte range actually checked by the ed25519 program.

        Impact

        A caller can obtain a successful verification result for oracle payload bytes that no trusted Lazer signer signed. Any on-chain CPI consumer that relies on the returned VerifiedMessage for price-dependent state transitions can consequently act on attacker-selected prices or metadata; the exact downstream asset loss depends on the external consumer, which is outside the searched component boundary.

        Description

        verify_message binds the ed25519 offset table to the transaction's current top-level instruction index, but it extracts the allegedly verified key and payload from the separately supplied message_data vector. During CPI, the instructions sysvar still identifies the caller's top-level instruction, so an attacker-controlled caller program can place a genuine trusted-signer envelope in its own instruction data while passing a different envelope of the same declared payload length as message_data. The offset checks establish only that the genuine bytes occupy the expected absolute positions in the caller instruction; they never load those raw bytes or compare them with the vector later consumed. The counterfeit vector can contain the correct magic and a configured signer key but an arbitrary same-length payload, and the function returns that arbitrary payload as VerifiedMessage. The same mismatch is also reachable by a direct instruction if Anchor accepts trailing serialized bytes, but CPI is sufficient and does not depend on that deserialization detail.

        Codex Security (GPT-6 Sol)

        A caller can present forged oracle payload as a verified message

        lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:208 Predicted severity: High

        Root cause

        The verifier assumes the caller-provided message_offset marks the start of message_data. It checks Ed25519 offsets using that absolute value, then subtracts the same value to parse bytes from the start of message_data. It never loads the current instruction bytes or checks that the authenticated region equals the parsed region.

        Impact

        An unprivileged caller can bypass oracle signature authenticity and supply arbitrary price data to consumers; a transaction with a genuine signed envelope and a forged envelope suffices.

        Description

        verify_message accepts caller-chosen message_data and message_offset; the Ed25519 instruction verifies bytes at the chosen absolute offset, while the contract returns key and payload bytes parsed from the beginning of message_data without comparing the two regions.

        Exploit scenario

        Caller message_data and offset -> Ed25519 metadata check -> relative parse of different message_data bytes -> VerifiedMessage

        Recommendation

        Require message_offset to identify the serialized start of message_data and compare the authenticated instruction bytes with the parsed envelope; reject any mismatch before returning VerifiedMessage.

        Devin Security

        verify_message checks a signature over one set of bytes but returns a different, unsigned public key and payload

        lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:208 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone with a Solana wallet can make the Lazer program report an attacker-written price message as verified and signed by a trusted Pyth signer, so every program that relies on verify_message can be fed fake prices.

        ##### What's wrong

        This is a signature-verification bypass caused by a mismatch between the checked bytes and the used bytes. The program checks that the ed25519 instruction points at offsets derived from the caller-supplied message_offset in the current instruction data. It never checks that those offsets are where message_data actually sits. It then reads the public key and payload out of message_data, which the ed25519 program never verified.

        ##### Who can do it

        Alice runs a lending protocol at Acme Corp that calls the Lazer verify_message instruction through CPI and trusts the returned payload as a Pyth price. Mallory has an ordinary Solana wallet. Mallory builds one transaction with an ed25519 instruction and a call into the Lazer program (or into Alice's program). The message_data she passes holds a forged message with the trusted Pyth signer's public key and her chosen price. Somewhere else in the same instruction data she places a second message that she signed with her own keypair, and she sets message_offset to point at that second copy.

        - Mallory only needs to send a transaction and pay the 1 lamport fee.

        - She needs to know a currently trusted signer public key, which is public in the storage account.

        - Her forged payload must have the same length as the payload she signed herself, which she controls.

        ##### What they get

        The program returns VerifiedMessage { public_key: <trusted Pyth signer>, payload: <Mallory's bytes> }. Mallory can set any price, timestamp, or feed in that payload. Any protocol that consumes Lazer prices through this program can be drained, for example by borrowing against an inflated collateral price or by triggering liquidations with a crashed price. This affects every integrator of the program, not one customer.

        ##### How it works

        1. Mallory puts an ed25519 instruction earlier in the transaction whose offsets point at message_offset+4, message_offset+68 and message_offset+102 in the Lazer instruction, where she placed a message signed by her own key. The ed25519 program verifies it successfully.

        2. verify_message in signature.rs:208-259 only compares the ed25519 offsets to values computed from message_offset and checks they reference the current instruction. It never checks that message_offset is the real position of message_data (12 bytes after the start for a direct call).

        3. At signature.rs:215 and 249, the magic and size are read from message_data, the forged copy, which Mallory fills to match.

        4. At signature.rs:261-281, the public key used for the trusted-signer check is read from the forged message_data, so the trusted Pyth key passes.

        5. At signature.rs:283-298, the returned payload is also read from the forged message_data, so the caller receives Mallory's unsigned bytes as a verified message.

        Exploit scenario

        Not specified.

        Recommendation

        Bind the verified bytes to the returned bytes. Load the current instruction from the instructions sysvar and check that instruction.data[message_offset .. message_offset + message_data.len()] == message_data (with bounds checks) before trusting any field. Also check that offsets.message_data_size plus header fits inside message_data. A simpler alternative is to read the public key and payload directly from the current instruction data at the verified offsets instead of from message_data. Add a test that places a self-signed message after a forged message_data that names a trusted key, sets message_offset to the self-signed copy, and asserts the call fails.

        Devin Security (Deep)

        verify_message never checks that message_offset points at message_data, so an attacker can get a trusted-signer attestation for an unsigned payload

        lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:160 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who can send a Solana transaction can make the Pyth Lazer receiver return a "verified" price message that carries a trusted Pyth signer key but a payload the attacker wrote, and any program that forwards the caller-supplied message_offset to this contract will accept forged prices.

        ##### What's wrong

        This is a signature verification bypass caused by a missing binding check. The contract proves that the ed25519 precompile verified some bytes at message_offset inside the current top-level instruction, but it reads the public key and payload from message_data, a separate argument, and it never checks that message_data is actually the bytes that sit at message_offset.

        ##### Who can do it

        Alice runs Acme Lending, a Solana protocol that prices collateral with Pyth Lazer. Acme's program copies the pattern of the Lazer verify_message instruction and lets the transaction specify message_offset, then forwards it in the CPI call. Mallory, an attacker with nothing but a funded Solana wallet, builds one transaction with an ed25519 precompile instruction and a call into Acme. She sets message_offset to point at a region she signed with her own key, and places a real Pyth signer key plus a fake price in the message_data argument. The Lazer contract returns a VerifiedMessage with the Pyth key and her fake price.

        Conditions that must hold:

        - The attacker can submit a transaction to the cluster where the Lazer receiver is deployed (no account or signer status needed beyond paying fees).

        - The attacker knows a current trusted signer public key. This is public data in the storage account.

        - For on-chain impact, an integrating program must pass message_offset through from its own instruction arguments, or otherwise pass a value that does not equal the real position of message_data in its instruction data. A direct call to the Lazer verify_message instruction is forgeable with no further condition, but its result is only visible as return data.

        This is CRITICAL if any deployed integrator forwards message_offset from untrusted input. The repository does not contain integrator code, so this cannot be confirmed here.

        ##### What they get

        Mallory can make a Lazer-integrated protocol believe any price she wants for any feed, as if Pyth had signed it. Against a lending protocol she can borrow against worthless collateral or liquidate healthy positions and take the users' deposits. She can repeat this against every protocol that forwards message_offset. She cannot change the trusted signer list or the Lazer storage account itself, and she cannot fool an integrator that hard-codes the correct offset.

        ##### How it works

        1. Mallory builds instruction 0 as an ed25519 precompile call whose offsets table entry says: signature at mo+4, public key at mo+68, message at mo+102 with size S, all in instruction 1 (signature.rs:26-43 describes this table).

        2. She builds instruction 1 as a call to verify_message (lib.rs:192-198) with message_data laid out as: Pyth magic at bytes 0..4, a real trusted Pyth signer key at bytes 68..100, size S at bytes 100..102, her fake payload at bytes 102..102+S, and after that her own signature, her own public key, and a message she signed with her own key.

        3. She sets message_offset to 12 plus the distance to her own region, so the precompile offsets mo+4, mo+68, mo+102 land on her signature, her key, and her message. The precompile verifies that signature successfully before the transaction runs.

        4. The contract checks only that the precompile offsets equal message_offset plus fixed constants (signature.rs:208-236) and that the offsets refer to the current top-level instruction (signature.rs:254-259). It never loads the current instruction and compares its bytes at message_offset with message_data.

        5. The contract reads the public key from message_data[68..100] (signature.rs:261-271) and finds the trusted Pyth key, then reads the payload from message_data[102..] (signature.rs:283-293) and returns it as verified (signature.rs:295-298).

        6. The test file shows the intended but unenforced invariant: message_offset is hard-coded to 12 because that is where message_data really starts in the Anchor-encoded instruction (tests/test1.rs:109-110).

        Exploit scenario

        Not specified.

        Recommendation

        Inside signature::verify_message, load the current top-level instruction with sysvar::instructions::load_instruction_at_checked(self_instruction_index, instructions_sysvar) and require that self_instruction.data[message_offset .. message_offset + message_data.len()] equals message_data (return a new MessageDataMismatch error otherwise, and return InvalidMessageOffset if the range is out of bounds). Alternatively, drop the message_offset argument entirely and derive the public key and payload directly from the current instruction's bytes at the offsets the precompile verified. Also update the doc comments on lib.rs:190 and signature.rs:158 to make the binding explicit.

        To check the fix, add a test that builds the transaction from test1.rs::verify_message but passes message_offset = 12 + 200 with the attacker's own signature, key and message placed 200 bytes into message_data and a trusted key at message_data[68..100]; the instruction must fail. The existing test_basic with message_offset = 12 must still pass.

        Claude Security (Sonnet 5.5)

        verify_message trusts caller-supplied message_data instead of the bytes the ed25519 program actually verified, allowing forged Lazer messages

        lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:270 Predicted severity: Critical

        Root cause

        Vulnerable symbol: verify_message

        Preconditions: At least one trusted signer is configured and not expired in Storage, which is the normal operating state.; The attacker can submit a transaction containing an ed25519 instruction followed by verify_message, or can drive a consumer program that forwards user-supplied message_data and message_offset in its CPI to verify_message.

        Offending code:

        &message_data[start..end]

        Impact

        Anyone can make verify_message return a VerifiedMessage with a trusted Pyth Lazer signer's public key and an arbitrary payload, such as fabricated prices, without holding any trusted key. They pay only the 1 lamport fee. Any on-chain consumer that relies on the returned VerifiedMessage can then be fed attacker-chosen price data. That enables oracle manipulation, theft from lending and perps protocols, and forced liquidations.

        Description

        The untrusted message_data instruction argument is the sole source of the public key (line 270), the trusted-signer check (line 275-279) and the returned payload (line 292). The code only compares the offsets in the ed25519 instruction against message_offset. It never checks that message_data equals the bytes of the current instruction data at message_offset, which are the bytes the ed25519 program verified.

        Exploit scenario

        1. Read the trusted signer pubkey T from the public Storage PDA account.

        2. Generate an attacker ed25519 keypair K and sign an arbitrary S-byte message with it.

        3. Build a transaction with instruction 0 = ed25519 program, carrying one Ed25519SignatureOffsets entry whose three instruction indices all point to the verify_message instruction (index 1). Signature, pubkey, size and message offsets are O+4, O+68, O+100/O+102 and S, where O is a chosen message_offset (for example just past the Borsh args, or inside the tail of a longer message_data Vec). Those bytes are placed in instruction 1's data and hold K's real signature, K's pubkey and the S-byte message.

        4. Instruction 1 = verify_message with message_offset = O. message_data is a forged buffer laid out as the code indexes it relative to message_offset: SOLANA magic (LE 0x821a01b9), 64 arbitrary signature bytes, the trusted pubkey T, the 2-byte LE size S, then S bytes of attacker-chosen payload.

        5. The ed25519 program accepts the transaction, because it validates K's signature at the absolute offsets. verify_message passes every offset and size comparison, reads magic, size and pubkey T from the forged message_data, finds T in the trusted list, and returns the forged payload.

        Anchor 0.30.1 deserializes instruction args with deserialize, which ignores trailing bytes. A Vec tail would work in any case.

        Recommendation

        Bind message_data to the verified bytes. Load the current instruction with load_instruction_at_checked(self_instruction_index). Require that current.data[message_offset .. message_offset + message_data.len()] equals message_data, or derive public key, size and payload directly from the current instruction data at the verified offsets instead of from the separate argument. Also compare the public key at offsets.public_key_offset in the current instruction data with the trusted signer. Add explicit length checks on message_data (at least 4 + 64 + 32 + 2 + size) to return clean errors instead of panicking on slice indexing at lines 215, 249, 270 and 292.

        Claude Security (Opus 5.5)

        verify_message reads the signer pubkey and payload from the caller's message_data, not from the bytes ed25519 checked, so anyone can forge trusted messages

        lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:270 Predicted severity: Critical

        Root cause

        Vulnerable symbol: verify_message

        Preconditions: At least one trusted signer is configured and not expired (normal operating state); The attacker pays the 1-lamport fee and a transaction fee

        Offending code:

        &message_data[start..end]

        Impact

        The signature check is bypassed completely. Any unprivileged user can make the contract certify any Pyth Lazer payload (prices, timestamps) as signed by the trusted Pyth signer. Programs that CPI into verify_message and trust the returned VerifiedMessage can be fed forged oracle prices. That enables price manipulation and theft of funds from any integrating DeFi protocol (lending liquidations, swaps, perps).

        Description

        message_data is an Anchor argument fully chosen by the caller. The program only checks that the ed25519 instruction's offsets equal message_offset + const and that the instruction indexes match the current one. It never checks that message_data equals the bytes of the current instruction at message_offset, which are the only bytes the ed25519 precompile verified. The trusted-signer pubkey (line 270) and the payload (line 292) that come back as VerifiedMessage are therefore never covered by any signature check.

        Exploit scenario

        The attacker builds a transaction with two instructions. ix0 is ed25519_program with one offsets struct: sig=M+4, pk=M+68, msg=M+102, size=S, all instruction indexes = 1. ix1 is lazer verify_message with message_data = FAKE || REAL. FAKE = magic || 64 junk bytes || TRUSTED_PUBKEY || u16 S || attacker-chosen price payload (S bytes). REAL = magic || attacker_sig || attacker_pubkey || u16 S || S bytes signed with the attacker's own key. The attacker sets message_offset = M = 12 + len(FAKE), and ed25519_instruction_index=0, signature_index=0. The ed25519 precompile checks REAL, which is a valid signature by the attacker's key. The program checks offsets against M, reads magic, size, pubkey and payload from FAKE, finds TRUSTED_PUBKEY in storage, and returns VerifiedMessage{public_key: TRUSTED_PUBKEY, payload: forged}. Trailing instruction bytes, which Anchor ignores, work too. Under CPI it is even simpler: self_instruction_index is the outer top-level instruction, so the attacker signs bytes in that outer instruction's data and passes any message_data through the consumer.

        Recommendation

        Bind the verified bytes to the returned data. Load the current instruction (load_instruction_at_checked(self_instruction_index)) and require instruction.data[message_offset..message_offset+message_data.len()] == message_data, or better, read magic, pubkey, size and payload directly from the instruction data at the offsets the ed25519 instruction used, and drop the separate message_data argument. Also check that instruction.program_id == crate::ID, and handle or reject CPI calls, where the current index refers to the outer instruction. Add bounds checks on message_data length so short input returns an error instead of panicking.

        Vercel Security Review

        Caller-controlled message offset separates verified bytes from returned payload

        lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/lib.rs:194 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Caller controls both data and its alleged location** - lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/lib.rs:194-197

        ```rust title="lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/lib.rs:194-197"

        message_data: Vec<u8>,

        ed25519_instruction_index: u16,

        signature_index: u8,

        message_offset: u16,

        ```

        An unprivileged caller can concatenate a forged frame and a genuine signed frame with matching key and payload length, pointing message_offset at the latter.

        **2. Offsets are checked against that assertion** - lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:208-211

        ```rust title="lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:208-211"

        let expected_signature_offset = message_offset

        .checked_add(MAGIC_LEN)

        .ok_or(SignatureVerificationError::MessageOffsetOverflow)?;

        if offsets.signature_offset != expected_signature_offset {

        ```

        The new verifier never binds this offset to the parsed vector's start. Ed25519 validates the genuine frame.

        **3. Different bytes become authenticated output** - lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:289-292

        ```rust title="lazer/contracts/solana/programs/pyth-lazer-solana-contract/src/signature.rs:289-292"

        let end = start

        .checked_add(expected_message_size.into())

        .ok_or(SignatureVerificationError::MessageOffsetOverflow)?;

        &message_data[start..end]

        ```

        Subtracting message_offset makes start always 102 within the first frame. Its forged payload is returned as VerifiedMessage, bypassing oracle authenticity without a signing key.

        Exploit scenario

        Not specified.

        Recommendation

        Bind the exact parsed message bytes to the bytes verified by Ed25519. For direct calls enforce the actual serialized vector offset; for CPI-supported flows load the referenced top-level instruction and compare the referenced key, signature and payload bytes to message_data. Reject any mismatch instead of trusting a caller-supplied location.

    • SPL Token Rust SPL-Token program — Solana token standard. Tasks 3 V12 3/3 Codex Sec 0/3 Pashov Opus — Pashov GPT-6 — Devin 2/3 Devin (Deep) 1/3 Claude Sec 1/3 Claude Opus 3/3 Vercel 1/3

      SPL-Token program — Solana token standard.

      Read the audit report
      • Missing check in process_transfer leading to inflationary bug spl-token-1 · 5 writeups Critical

        V12

        Transfer proofs are not bound to live balances

        token/program-2022/src/extension/confidential_transfer/processor.rs:129 Predicted severity: High

        Root cause

        process_source_for_transfer authenticates the configured encryption key but does not authenticate the live source balance against the transfer proof's balance statement. Both transfer branches discard the proof balance context before mutating account balances.

        Impact

        The source-backed path permits repeated recipient credits without an accompanying check that the live source balance supports each debit; encrypted subtraction alone does not enforce nonnegative token accounting. Inference: a holder can reuse a valid transfer proof to accumulate redeemable recipient balances beyond their original holdings, causing token inflation and losses to holders or systems accepting those tokens; the external SDK proof implementation and a runtime reproduction were not available in the searched repository, so this is a raw candidate rather than a completed exploit.

        Description

        The confidential-transfer source helper checks the account owner, mint, approval, and configured encryption public key, but never binds the verified transfer proof's balance statement to the source account's current available_balance. process_transfer extracts the transfer amount ciphertexts from TransferData and the helper subtracts them from whatever balance is currently stored. The client constructs those proofs using an explicit source balance and source balance ciphertext, so the proof and the live balance are distinct inputs that require reconciliation. Reusing an otherwise-valid proof after spending, or using it against another account configured with the same encryption public key, therefore passes the visible source checks even when the live source balance differs. This downstream consumer makes encryption-key reuse across configured accounts a value-accounting boundary rather than merely an account-configuration choice.

        Devin Security (Deep)

        Confidential Transfer never checks the proven new source balance, so anyone can send tokens they do not have

        token/program-2022/src/extension/confidential_transfer/processor.rs:663 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone holding two confidential token accounts on a mint can create up to about 281 trillion base units of that token out of nothing per transaction, repeatedly, and then withdraw them as ordinary spendable tokens.

        ##### What's wrong

        This is a missing proof-binding check. The zero-knowledge transfer proof only proves that a ciphertext the sender supplies (new_source_ciphertext) holds a non-negative balance. The program is supposed to confirm that this ciphertext equals the balance it computes on chain (current balance minus the transfer amount). process_source_for_transfer computes the new balance and stores it, but never compares it to proof_data.new_source_ciphertext, and no code in the program reads that field at all. The on-chain balance can therefore go negative without the proof ever covering it.

        ##### Who can do it

        Alice at Acme Corp issues a token on Token-2022 with the confidential transfer extension turned on. Mallory, an ordinary user with a wallet, opens two token accounts for that mint, configures both for confidential transfers, and gets them approved (automatic on most mints). She builds a transfer proof using a made-up starting balance of 2^48 - 1 and a freshly encrypted ciphertext for that number instead of her real on-chain balance of zero, then submits the proof instruction followed by a Transfer from her first account to her second account.

        - Mallory owns two token accounts for the target mint that have the confidential transfer extension and are approved.

        - The ZK token proof program is active on the cluster, which is required for any confidential transfer to work at all.

        - The mint is not marked non-transferable.

        ##### What they get

        Mallory's second account is credited with a pending balance of 2^48 - 1 tokens that were never minted. She runs ApplyPendingBalance, then Withdraw with a correct proof (she knows the true value of her balance) and now holds 2^48 - 1 freely spendable public tokens of Acme's mint. She can repeat this in every transaction. She can sell the tokens, drain any liquidity pool, or send them to anyone. Every holder of Acme's token loses value, and Acme's mint supply number no longer reflects the tokens in circulation. The same attack works on every Token-2022 mint that has confidential transfers enabled.

        ##### How it works

        1. Mallory calls TransferData::new (or TransferWithFeeData::new) with her real ElGamal keypair, a fabricated (spendable_balance, spendable_ciphertext) pair, and amount 2^48 - 1; the proof program accepts it because all values are self-consistent.

        2. process_transfer in token/program-2022/src/extension/confidential_transfer/processor.rs:568-598 decodes the proof and checks only the auditor pubkey, then passes the source pubkey and the amount ciphertexts to process_source_for_transfer; new_source_ciphertext is never read.

        3. process_source_for_transfer at lines 663-672 subtracts the amount ciphertexts from the account's real available balance (zero) and stores the result, which now encrypts a negative number, with no comparison to the proven ciphertext.

        4. process_destination_for_transfer at lines 714-744 adds the full amount to the second account's pending balance.

        5. process_apply_pending_balance at lines 808-813 moves the pending amount into the available balance.

        6. process_withdraw at lines 422-436 accepts Mallory's valid withdraw proof for the real value and adds 2^48 - 1 to token_account.base.amount, creating spendable tokens from nothing.

        Exploit scenario

        Not specified.

        Recommendation

        Pass &proof_data.new_source_ciphertext into process_source_for_transfer on both the fee and non-fee paths, and return TokenError::ConfidentialTransferBalanceMismatch when new_source_available_balance != *new_source_ciphertext before storing the new balance. To verify: write a program test that builds a TransferData from a fabricated balance/ciphertext pair that differs from the on-chain ciphertext (for example, a transfer amount greater than the real balance) and assert the Transfer instruction fails with ConfidentialTransferBalanceMismatch, while a transfer built from the real on-chain ciphertext still succeeds.

        Claude Security (Sonnet 5.5)

        Confidential Transfer / TransferWithFee never binds the ZK proof's new source ciphertext to the on-chain available balance, allowing transfers beyond balance (token inflation)

        token/program-2022/src/extension/confidential_transfer/processor.rs:672 Predicted severity: Critical

        Root cause

        Vulnerable symbol: process_source_for_transfer

        Preconditions: Mint has the ConfidentialTransferMint extension (default zk-ops feature enabled); Attacker owns a source and a destination token account configured for confidential transfers and approved (auto-approve or by authority)

        Offending code:

        confidential_transfer_account.available_balance = new_source_available_balance;

        Impact

        Unbounded creation of spendable tokens for any mint that enables confidential transfers: total supply invariants break, holders and liquidity pools are diluted or drained, and the confidentiality soundness guarantee (no spending more than balance) is void. Loss of funds for all users of the affected mint.

        Description

        The attacker-supplied VerifyTransfer / VerifyTransferWithFee proof instruction (decoded in process_transfer) is only checked for pubkeys and fee parameters; the on-chain available_balance minus the transfer ciphertexts is committed to account state without being compared to the source ciphertext the proof's equality and range proofs were built against, so the range proof proves nothing about the real balance. Also CWE-20: The attacker-supplied proof context (read from the instructions sysvar in process_transfer) is only used for its lo/hi transfer ciphertexts. The proof's post-transfer source ciphertext is never compared with the program-computed available_balance - amount, and no function parameter carries it. The program then stores the self-computed ciphertext as the source's new available balance, so the 'remaining balance >= 0' range proof is never tied to the real account state. Also CWE-863: The proof instruction content (TransferData / TransferWithFeeData, generated client-side from a caller-supplied balance ciphertext, see token/client TransferData::new(amount, (balance, balance_ciphertext), ...)) is the only evidence that the source can afford the transfer, yet process_source_for_transfer computes ops::subtract_with_lo_hi(available_balance, lo, hi) and stores it without comparing the result to the source ciphertext certified by the proof; only the pubkey, auditor and fee-parameter fields of the proof are checked, so a proof built over a fabricated balance is accepted for any real account.

        Exploit scenario

        The attacker owns confidential account A (available balance 0) and account B. They build TransferData::new(amount, (fake_balance, fake_ciphertext), keypair_A, (pubkey_B, auditor)) where fake_ciphertext is an ElGamal encryption of a large balance under A's own key. The proof is internally consistent (new source ciphertext = fake ciphertext - amount, equality proof and 64-bit range proof over the fake remainder) so the zk-token-proof program accepts VerifyTransfer. process_transfer only compares source/destination/auditor pubkeys (lines 573-577, 659, 709), subtracts the transfer ciphertexts from A's real zero balance (wrapping the encrypted balance negative) and credits B's pending balance with up to 2^48-1 units. The attacker runs ApplyPendingBalance on B, then Withdraw on B (whose proof is bound to B's real balance), which does token_account.base.amount += amount without any matching supply or backing. Repeating this mints unbacked tokens that can be moved to the public balance and sold or drained from pools. The same missing binding also permits replaying one proof instruction across several Transfer instructions in a transaction.

        Recommendation

        Make process_source_for_transfer take the proof's new source ciphertext (TransferData::new_source_ciphertext / TransferWithFeeData equivalent) as a parameter from both branches of process_transfer. After computing new_source_available_balance, reject with TokenError::ConfidentialTransferBalanceMismatch unless it equals that ciphertext, before writing it to account state. Add a negative test that spends more than the on-chain balance with a forged spendable ciphertext. Also CWE-20: Pass the proof's post-transfer source ciphertext (new_source_ciphertext in TransferData / TransferWithFeeData) into process_source_for_transfer. After computing new_source_available_balance, require new_source_available_balance == *new_source_ciphertext and return TokenError::ConfidentialTransferBalanceMismatch otherwise. Do this before storing the new balance, in both the fee and non-fee branches. Add regression tests that supply a proof built against a mismatched balance. Also CWE-863: Pass the proof's resulting source ciphertext (new_source_ciphertext) into process_source_for_transfer for both the TransferData and TransferWithFeeData branches and return TokenError::ConfidentialTransferBalanceMismatch unless the on-chain subtract_with_lo_hi result equals it, before writing available_balance.

        Claude Security (Opus 5.5)

        Confidential Transfer debits the source without binding the ZK proof's new source balance to the on-chain balance

        token/program-2022/src/extension/confidential_transfer/processor.rs:672 Predicted severity: Critical

        Root cause

        Vulnerable symbol: process_source_for_transfer

        Preconditions: zk-ops feature enabled (it is the default in Cargo.toml); Attacker owns an approved confidential account (automatic on auto-approve mints, or obtainable through the ApproveAccount mint-mismatch bug)

        Offending code:

        confidential_transfer_account.available_balance = new_source_available_balance;

        Impact

        An unprivileged attacker can mint unlimited unbacked tokens of any confidential-transfer mint and convert them to public balances. The mint's supply is never increased, so this enables theft from AMMs and lending pools and destroys the token's value.

        Description

        The VerifyTransfer and VerifyTransferWithFee proofs are stateless: the client builds them from a source balance and ciphertext it chooses (client/src/token.rs:1562-1570), and the proof program never reads the account. The token program subtracts the proof's lo/hi ciphertexts from available_balance (664-672) but never checks that the result equals the proof's range-proven new source ciphertext. Nothing therefore enforces that the sender holds enough funds before the destination is credited (714-744).

        Exploit scenario

        The attacker configures two token accounts A and B on a confidential-transfer mint. A has a zero confidential balance. The attacker calls TransferData::new(amount = 2^40-1, (fake_balance = 2^40, Enc(2^40) under A's key), A's keypair, ...), which yields a valid VerifyTransfer proof. They submit it together with ConfidentialTransfer::Transfer(A -> B). The proof verifies, the program checks only the pubkeys and subtracts the amount from A's real zero balance (the ciphertext wraps to a 'negative' value), and B's pending balance is credited. The attacker then runs ApplyPendingBalance and Withdraw on B (B's withdraw proof is legitimate against its now-credited balance) to get public tokens. Repeating this mints unlimited tokens. The TransferWithFee path has the same gap.

        Recommendation

        Pass the proof context's new source ciphertext (TransferData/TransferWithFeeData new_source_ciphertext) into process_source_for_transfer and reject the instruction unless ops::subtract_with_lo_hi(available_balance, lo, hi) == proof_data.new_source_ciphertext, as Withdraw already does with final_ciphertext.

        Vercel Security Review

        Confidential transfer proofs are not bound to the source account balance

        token/program-2022/src/extension/confidential_transfer/processor.rs:568 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. A holder can resubmit a previously valid transfer proof** - token/program-2022/src/extension/confidential_transfer/processor.rs:568-571

        ```rust title="token/program-2022/src/extension/confidential_transfer/processor.rs:568-571"

        let proof_data = decode_proof_instruction::<TransferData>(

        ProofInstruction::VerifyTransfer,

        &previous_instruction,

        )?;

        ```

        **2. The new source handler never compares its resulting ciphertext with the proof's proven remaining balance** - token/program-2022/src/extension/confidential_transfer/processor.rs:672-676

        ```rust title="token/program-2022/src/extension/confidential_transfer/processor.rs:672-674"

        confidential_transfer_account.available_balance = new_source_available_balance;

        confidential_transfer_account.decryptable_available_balance =

        new_source_decryptable_available_balance;

        ```

        Homomorphic subtraction can therefore drive the actual source balance negative, even though the standalone proof verifies. Both transfer variants use this handler.

        **3. The recipient still receives spendable tokens** - token/program-2022/src/extension/confidential_transfer/processor.rs:714-717

        ```rust title="token/program-2022/src/extension/confidential_transfer/processor.rs:714-717"

        let new_destination_pending_balance_lo = ops::add(

        &destination_confidential_transfer_account.pending_balance_lo,

        destination_ciphertext_lo,

        )

        ```

        Repeated transfers followed by recipient application/withdrawal create unbacked public tokens without mint authority, violating supply conservation.

        Exploit scenario

        Not specified.

        Recommendation

        For both TransferData and TransferWithFeeData, compare the source account's post-subtraction ciphertext with the remaining-balance ciphertext authenticated by the verified proof before committing either account update. Reject mismatches. Pass the proven ciphertext into the shared source handler and add negative tests for replaying a proof after the source balance changes.

      • Missing check in process_withdraw potentially leading to inflationary bug spl-token-2 · 3 writeups Critical

        V12

        Withdrawal proof lacks account encryption key binding

        token/program-2022/src/extension/confidential_transfer/processor.rs:388 Predicted severity: Informational

        Root cause

        The encrypted-to-public withdrawal path treats equality of ciphertext bytes as sufficient proof binding without also binding the verification key to the account's configured encryption_pubkey. Unlike confidential transfer, it has no explicit key-instance guard.

        Impact

        The specific security question is whether a valid withdrawal proof under a different ElGamal key can certify a different remaining plaintext for a reachable account ciphertext and thereby release more public tokens than the account holds. The missing facts are the exact WithdrawData public-key binding and verification equations, together with the constructibility of such a reachable ciphertext under solana-zk-token-sdk 1.11.6. Repository-wide Rust searches, the confidential-transfer SDK consumers, and the repository's encryption/proof documentation were inspected; the external SDK implementation was not available, so unauthorized balance creation is not asserted as demonstrated.

        Description

        process_withdraw decodes a VerifyWithdraw instruction and compares only its final ciphertext with the result of subtracting the requested public amount from the live available ciphertext. It never compares the proof's encryption key with ConfidentialTransferAccount.encryption_pubkey. This differs from the transfer path, which explicitly binds the proof's source key to the stored account key. Because configuration accepts caller-selected encryption-key bytes and later transfers credit ciphertexts under that stored key, ciphertext equality alone leaves the key under which the remaining balance was proved unbound. The missing check is verified, but acceptance of a concrete cross-key over-withdrawal remains unresolved because the external proof verifier implementation is not present in the searched workspace.

        Devin Security

        Withdraw and EmptyAccount do not check that the proof's ElGamal public key matches the account's key

        token/program-2022/src/extension/confidential_transfer/processor.rs:416 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A token account owner can submit a withdraw or close proof made for a different encryption key, and the program accepts it without checking the key; current proof math appears to stop this from creating or destroying tokens, so this is a missing safety check, not a known theft path.

        ##### What's wrong

        This is a missing binding check. The Withdraw and EmptyAccount handlers read the zero-knowledge proof from the previous instruction. They compare only the ciphertext in the proof with the account's ciphertext. They never compare the public key in the proof (proof_data.pubkey) with the account's encryption_pubkey. Every other proof-consuming handler in this file (Transfer, TransferWithFee, WithdrawWithheldTokens*) does check the public key.

        ##### Who can do it

        Mallory owns a confidential token account for a mint run by Acme Corp. She builds a VerifyWithdraw or VerifyCloseAccount proof that uses an ElGamal public key she picks, not the key stored on her account. She puts it in front of a Withdraw or EmptyAccount instruction. The program accepts the proof as long as the ciphertext bytes match.

        - Mallory must own (sign for) the token account being withdrawn from or emptied.

        - The zk-ops feature must be enabled for Withdraw.

        - A real exploit also needs Mallory to make a proof under another key that verifies against her account's ciphertext. Under the standard ElGamal equality proof, this looks infeasible unless she can solve discrete logs. I could not confirm this against the exact solana-zk-token-sdk 1.11 verifier source.

        ##### What they get

        If a proof can be made to verify under a substitute key, Mallory could withdraw more public tokens than her confidential balance holds. That would mint value out of nothing for Acme's token. She could also close an account that still holds a non-zero confidential balance. My analysis of the proof equations shows the substitute key gives her no extra freedom today. So the practical impact is the loss of a check that the upstream design relies on. It affects only accounts Mallory owns.

        ##### How it works

        1. process_withdraw decodes WithdrawData from the previous instruction at processor.rs:388-391.

        2. It subtracts amount from available_balance and compares the result only with proof_data.final_ciphertext at processor.rs:420-426. It never compares proof_data.pubkey with encryption_pubkey.

        3. It then credits amount to the public balance at processor.rs:430-434.

        4. process_empty_account decodes CloseAccountData at processor.rs:233-237 and compares only proof_data.ciphertext with available_balance at processor.rs:249-252. It never checks the key before it zeroes the balance.

        Exploit scenario

        Not specified.

        Recommendation

        In process_withdraw and process_empty_account, return TokenError::ConfidentialTransferElGamalPubkeyMismatch when proof_data.pubkey != confidential_transfer_account.encryption_pubkey. Run this check before you use the ciphertext. To confirm the fix, add program tests that send a valid proof made for a different ElGamal keypair with matching ciphertext bytes. Both instructions should fail with the mismatch error.

        Claude Security (Opus 5.5)

        Withdraw does not check that the proof's ElGamal pubkey is the account's key; with an arbitrary key accepted at ConfigureAccount, the owner can withdraw more than the encrypted balance

        token/program-2022/src/extension/confidential_transfer/processor.rs:426 Predicted severity: High

        Root cause

        Vulnerable symbol: process_withdraw

        Preconditions: Mint has ConfidentialTransferMint and the attacker's account is approved; Attacker builds custom proof data (chosen openings and a malformed encryption key); no other privileges needed; Relies on solana-zk-token-sdk 1.11 equality-proof semantics (not vendored; reasoned from the protocol)

        Offending code:

        if confidential_transfer_account.available_balance != proof_data.final_ciphertext {

        Impact

        An account owner can withdraw more public tokens than their confidential balance holds, which inflates the token supply without limit.

        Description

        WithdrawData includes the ElGamal pubkey that the equality and range proof were checked against. process_withdraw only compares final_ciphertext with the on-chain balance minus amount (line 426) and never checks proof_data.pubkey against the account's encryption_pubkey. ConfigureAccount (line 132) stores any 32-byte point as encryption_pubkey with no proof that the owner knows a secret key, so the decrypt handle of an account can carry a G component with a coefficient the attacker knows.

        Exploit scenario

        1) The attacker configures account B with encryption_pubkey P = G + H, a valid Ristretto point whose discrete log relative to H is unknown and which has a G component. 2) From an honest account A the attacker transfers x (x can be 0) to B. The attacker writes their own proof code and chooses the Pedersen openings so the total randomness is R = -E mod l. The validity proof works for any destination point, and B's on-chain pubkey matches. 3) B runs ApplyPendingBalance, so available = (xG + RH, R(G+H)). 4) The attacker calls Withdraw with amount = x + E. On-chain the final ciphertext becomes (-EG - EH, -EG - EH). The attacker submits a WithdrawData proof under pubkey P' = H (secret s' = 1): C_f - s'·D_f = 0·G, so the equality proof and the range proof on 0 both verify. The program checks only that final_ciphertext matches, then credits x + E public tokens. 5) This mints E tokens, for any E up to the u64 limit, and can be repeated. I derived this from the equality-proof algebra in solana-zk-token-sdk 1.11. The SDK source is not staged, so I could not confirm it in code.

        Recommendation

        In process_withdraw, and likewise in process_empty_account against CloseAccountData.pubkey, return ConfidentialTransferElGamalPubkeyMismatch unless proof_data.pubkey == confidential_transfer_account.encryption_pubkey. In ConfigureAccount, also require a VerifyPubkeyValidity proof so that only keys of the form s^-1·H with a known secret can be registered.

      • Missing public key check in EmptyAccount leading to deflationary bug spl-token-3 · 3 writeups High

        V12

        Close proof omits live encryption key binding

        token/program-2022/src/extension/confidential_transfer/processor.rs:232 Predicted severity: Informational

        Root cause

        process_empty_account binds the close proof to ciphertext bytes but does not bind its key context to the account's encryption_pubkey. Correctness therefore depends on an unverified implication of the external proof implementation rather than a local live-state key check.

        Impact

        The specific security question is whether a close proof valid for the same ciphertext under another encryption key can clear a nonzero balance under the account's configured key and thereby permit closure without redeeming the tokens. The missing facts are the CloseAccountData key inputs, verification equations, and ability to construct such a ciphertext through accepted account transitions in solana-zk-token-sdk 1.11.6; repository-wide Rust searches and the available client/tests did not expose that dependency implementation. Owner authorization remains enforced, so this candidate does not establish unauthorized access to another owner's account.

        Description

        process_empty_account authenticates the token account owner and loads a VerifyCloseAccount instruction through the shared proof decoder. Its only equality check between proof data and live confidential state compares proof_data.ciphertext with available_balance. It never binds the proof's encryption-key context to ConfidentialTransferAccount.encryption_pubkey before replacing the available ciphertext with canonical zero. The pending and withheld checks prevent clearing those balances, but do not establish that the available ciphertext represents zero under the account's stored key. This is a source-backed missing public-input binding; whether the pinned SDK makes that omission exploitable remains unresolved because its proof implementation is not included in the workspace.

        Devin Security

        Withdraw and EmptyAccount do not check that the proof's ElGamal public key matches the account's key

        token/program-2022/src/extension/confidential_transfer/processor.rs:416 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A token account owner can submit a withdraw or close proof made for a different encryption key, and the program accepts it without checking the key; current proof math appears to stop this from creating or destroying tokens, so this is a missing safety check, not a known theft path.

        ##### What's wrong

        This is a missing binding check. The Withdraw and EmptyAccount handlers read the zero-knowledge proof from the previous instruction. They compare only the ciphertext in the proof with the account's ciphertext. They never compare the public key in the proof (proof_data.pubkey) with the account's encryption_pubkey. Every other proof-consuming handler in this file (Transfer, TransferWithFee, WithdrawWithheldTokens*) does check the public key.

        ##### Who can do it

        Mallory owns a confidential token account for a mint run by Acme Corp. She builds a VerifyWithdraw or VerifyCloseAccount proof that uses an ElGamal public key she picks, not the key stored on her account. She puts it in front of a Withdraw or EmptyAccount instruction. The program accepts the proof as long as the ciphertext bytes match.

        - Mallory must own (sign for) the token account being withdrawn from or emptied.

        - The zk-ops feature must be enabled for Withdraw.

        - A real exploit also needs Mallory to make a proof under another key that verifies against her account's ciphertext. Under the standard ElGamal equality proof, this looks infeasible unless she can solve discrete logs. I could not confirm this against the exact solana-zk-token-sdk 1.11 verifier source.

        ##### What they get

        If a proof can be made to verify under a substitute key, Mallory could withdraw more public tokens than her confidential balance holds. That would mint value out of nothing for Acme's token. She could also close an account that still holds a non-zero confidential balance. My analysis of the proof equations shows the substitute key gives her no extra freedom today. So the practical impact is the loss of a check that the upstream design relies on. It affects only accounts Mallory owns.

        ##### How it works

        1. process_withdraw decodes WithdrawData from the previous instruction at processor.rs:388-391.

        2. It subtracts amount from available_balance and compares the result only with proof_data.final_ciphertext at processor.rs:420-426. It never compares proof_data.pubkey with encryption_pubkey.

        3. It then credits amount to the public balance at processor.rs:430-434.

        4. process_empty_account decodes CloseAccountData at processor.rs:233-237 and compares only proof_data.ciphertext with available_balance at processor.rs:249-252. It never checks the key before it zeroes the balance.

        Exploit scenario

        Not specified.

        Recommendation

        In process_withdraw and process_empty_account, return TokenError::ConfidentialTransferElGamalPubkeyMismatch when proof_data.pubkey != confidential_transfer_account.encryption_pubkey. Run this check before you use the ciphertext. To confirm the fix, add program tests that send a valid proof made for a different ElGamal keypair with matching ciphertext bytes. Both instructions should fail with the mismatch error.

        Claude Security (Opus 5.5)

        Withdraw does not check that the proof's ElGamal pubkey is the account's key; with an arbitrary key accepted at ConfigureAccount, the owner can withdraw more than the encrypted balance

        token/program-2022/src/extension/confidential_transfer/processor.rs:426 Predicted severity: High

        Root cause

        Vulnerable symbol: process_withdraw

        Preconditions: Mint has ConfidentialTransferMint and the attacker's account is approved; Attacker builds custom proof data (chosen openings and a malformed encryption key); no other privileges needed; Relies on solana-zk-token-sdk 1.11 equality-proof semantics (not vendored; reasoned from the protocol)

        Offending code:

        if confidential_transfer_account.available_balance != proof_data.final_ciphertext {

        Impact

        An account owner can withdraw more public tokens than their confidential balance holds, which inflates the token supply without limit.

        Description

        WithdrawData includes the ElGamal pubkey that the equality and range proof were checked against. process_withdraw only compares final_ciphertext with the on-chain balance minus amount (line 426) and never checks proof_data.pubkey against the account's encryption_pubkey. ConfigureAccount (line 132) stores any 32-byte point as encryption_pubkey with no proof that the owner knows a secret key, so the decrypt handle of an account can carry a G component with a coefficient the attacker knows.

        Exploit scenario

        1) The attacker configures account B with encryption_pubkey P = G + H, a valid Ristretto point whose discrete log relative to H is unknown and which has a G component. 2) From an honest account A the attacker transfers x (x can be 0) to B. The attacker writes their own proof code and chooses the Pedersen openings so the total randomness is R = -E mod l. The validity proof works for any destination point, and B's on-chain pubkey matches. 3) B runs ApplyPendingBalance, so available = (xG + RH, R(G+H)). 4) The attacker calls Withdraw with amount = x + E. On-chain the final ciphertext becomes (-EG - EH, -EG - EH). The attacker submits a WithdrawData proof under pubkey P' = H (secret s' = 1): C_f - s'·D_f = 0·G, so the equality proof and the range proof on 0 both verify. The program checks only that final_ciphertext matches, then credits x + E public tokens. 5) This mints E tokens, for any E up to the u64 limit, and can be repeated. I derived this from the equality-proof algebra in solana-zk-token-sdk 1.11. The SDK source is not staged, so I could not confirm it in code.

        Recommendation

        In process_withdraw, and likewise in process_empty_account against CloseAccountData.pubkey, return ConfidentialTransferElGamalPubkeyMismatch unless proof_data.pubkey == confidential_transfer_account.encryption_pubkey. In ConfigureAccount, also require a VerifyPubkeyValidity proof so that only keys of the form s^-1·H with a known secret can be registered.

    • Trufin Rust CosmWasm liquid staking on Injective. Tasks 1 V12 1/1 Codex Sec 0/1 Pashov Opus — Pashov GPT-6 — Devin 0/1 Devin (Deep) 0/1 Claude Sec 0/1 Claude Opus 0/1 Vercel 1/1

      CosmWasm liquid staking on Injective.

      Read the audit report
      • Unstake could be blocked for certain users trufin-1 · 2 writeups Medium

        V12

        Liquid-only exits emit zero undelegations

        contracts/injective-staker/src/contract.rs:1650 Predicted severity: Informational

        Root cause

        The reward-funded withdrawal calculation can reduce actual_amount_to_unstake to zero, but message construction assumes every funded withdrawal requires a nonzero staking-module undelegation.

        Impact

        If Injective rejects zero-amount undelegations, holders whose backing is entirely liquid cannot redeem through this otherwise-funded path, and claim creation and share burning roll back with the rejected message. The missing fact is the deployed staking module's acceptance rule for MsgUndelegate with amount zero; the reviewed contract, message definitions, constants, unstake/claim tests, and repository-wide unbonding searches provide no chain implementation or integration test resolving it.

        Description

        internal_unstake permits an entitlement to be covered entirely by CONTRACT_REWARDS, but always emits StakingMsg::Undelegate, including when the selected validator's delegated principal is zero. The delegation query explicitly defaults to (0, 0), and the resource guard can still pass using contract-held rewards. This state can arise after the last ordinary holder withdraws all principal plus net rewards while fee minting leaves treasury shares backed solely by liquid rewards. There is no zero-amount branch that creates and funds the delayed claim without undelegating. The searched repository does not contain the deployed staking module's zero-undelegation validation, so transaction rejection and resulting withdrawal blockage remain a specific unresolved dependency question.

        Vercel Security Review

        Zero-amount undelegation blocks withdrawals backed only by liquid rewards

        contracts/injective-staker/src/contract.rs:1724 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. A final depositor exit can exhaust delegated principal while leaving treasury fees liquid: 100 INJ principal, 10 rewards and a 10% fee leave 1 INJ. Subsequent treasury unstaking caps delegated withdrawal at zero.** - contracts/injective-staker/src/contract.rs:1673-1676

        ```rust title="contracts/injective-staker/src/contract.rs:1673-1676"

        if actual_amount_to_unstake > validator_total_staked {

        excess_unstaked_amount = actual_amount_to_unstake - validator_total_staked;

        actual_amount_to_unstake = validator_total_staked;

        }

        ```

        **2. The unconditional Undelegate message uses that zero amount. The staking module rejects it, reverting the burn and claim despite sufficient liquid backing.** - contracts/injective-staker/src/contract.rs:1726-1729

        ```rust title="contracts/injective-staker/src/contract.rs:1726-1729"

        amount: Coin {

        denom: INJ.to_string(),

        amount: actual_amount_to_unstake.into(),

        },

        ```

        **3. With all delegations exhausted, compounding returns before sweeping retained rewards. The remaining holder cannot redeem until somebody supplies another stake.** - contracts/injective-staker/src/contract.rs:939-941

        ```rust title="contracts/injective-staker/src/contract.rs:939-941"

        if total_rewards == 0 {

        return Ok(Response::new());

        }

        ```

        Exploit scenario

        Not specified.

        Recommendation

        Emit StakingMsg::Undelegate only when actual_amount_to_unstake is positive. Allow rewards-only withdrawals to burn shares and create claims against the already-liquid CONTRACT_REWARDS balance without an undelegation. Also allow compounding to sweep stored rewards when no validator rewards or existing delegations remain.

    • Valorem Solidity On-chain options clearinghouse. Tasks 3 V12 3/3 Codex Sec 1/3 Pashov Opus 2/3 Pashov GPT-6 3/3 Devin 1/3 Devin (Deep) 3/3 Claude Sec 1/3 Claude Opus 1/3 Vercel 2/3

      On-chain options clearinghouse.

      Read the audit report
      • Un-encoded claimID can be used in write() valorem-1 · 4 writeups High

        V12

        Option IDs accepted as irredeemable claim records

        src/OptionSettlementEngine.sol:302 Predicted severity: High

        Root cause

        write treats a balance of one as sufficient proof of claim ownership without validating the supplied token's claim-number discriminator. This allows an option token ID to become an inaccessible claim-accounting key.

        Impact

        A validly shaped call can accept collateral while recording its redemption entitlement under an ID that redemption always rejects. Unexercised collateral from that contribution becomes inaccessible after expiry, while ordinary claim owners cannot redeem on the writer's behalf because the contribution is recorded under the option ID.

        Description

        The existing-claim branch of write verifies the parent option key and requires a caller balance of one, but never verifies that claimId has a nonzero claim number. A caller holding exactly one fungible option can therefore pass that option's own ID as the existing claimId. The branch updates _claim[optionId] and _claimIdToClaimIndexArray[optionId], mints additional option tokens, and collects collateral without minting a claim token for that contribution. redeem explicitly rejects the same ID because its claim number is zero. If those new options remain unexercised at expiry, the added collateral has no claim token through which its writer can recover it.

        Pashov (Claude Opus 5.5 high)

        write() accepts the fungible option ID as claimId, permanently locking the writer's collateral claim

        src/OptionSettlementEngine.sol:302 Predicted severity: Low

        Root cause

        Missing claimNum != 0 validation on the supplied claimId. The 'owns claim' check uses balance == 1, which an ordinary option balance can also satisfy.

        Impact

        The deposited collateral, and any exercise proceeds assigned to that lot, are recorded under a token ID that redeem() refuses (claimNum == 0 reverts). At expiry, the unexercised underlying and the exercise asset attributed to that lot stay in the contract forever. This affects users and integrating contracts (vaults, routers) that hold one option and pass the wrong ID.

        Description

        When claimId != 0, write() only checks that the upper 160 bits match the option and that the caller's balance of claimId is exactly 1. It does not check that the lower 96 bits (claimNum) are non-zero. If a caller holds exactly one option token and passes claimId = optionId, the check passes. _claim[optionId] and _claimIdToClaimIndexArray[optionId] are then updated, collateral is pulled in, and only fungible options are minted.

        Exploit scenario

        A router holds 1 option of type X and calls write(optionId, 1000, optionId) intending to top up a lot. The call succeeds and mints 1000 options, but there is no claim NFT. After expiry, any of the 1000*underlyingAmount collateral that was not exercised cannot be redeemed.

        Recommendation

        In write(), revert if claimId != 0 && uint96(claimId) == 0. Also require claimNum < optionRecord.nextClaimNum and that the claim has not been redeemed.

        Pashov (Codex GPT-6 Sol high)

        An option token can be used as its own claim ID and locks new collateral

        src/OptionSettlementEngine.sol:302 Predicted severity: Low

        Root cause

        The existing-claim branch validates ownership and the high 160 bits but omits the low 96-bit claim-number check required for a redeemable claim token.

        Impact

        A caller who supplies the option ID as the claim ID permanently loses the collateral deposited through that call. The path requires an invalid argument and exactly one option token, which limits its severity.

        Description

        The overloaded write function checks that an existing claim ID has the same option key and that the caller owns one token with that ID, but never checks that the ID encodes a nonzero claim number. A caller who owns exactly one option token can pass optionId as claimId. The function deposits collateral and mints more options, but records the collateral under a token ID that redeem explicitly rejects.

        Exploit scenario

        A user holds one option token and calls write(optionId, 1, optionId). The upper-bit comparison succeeds and balanceOf[user][optionId] equals one. The function updates _claim[optionId], credits the bucket, mints one more option, and transfers collateral. At expiry, redeem(optionId) reverts InvalidClaim because its claim number is zero.

        Recommendation

        For nonzero claimId, require that decodeTokenId(claimId).claimNum is nonzero and that the ID identifies an existing unclaimed claim NFT before accepting additional collateral.

        Devin Security (Deep)

        write() accepts an option ID as the claimId and creates an unredeemable phantom claim that locks the writer's collateral

        src/OptionSettlementEngine.sol:303 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A writer who passes the option ID itself as the claim ID while holding exactly one option token mints new options against collateral that can never be redeemed, so a simple integration mistake permanently loses the deposit.

        ##### What's wrong

        This is a missing input validation bug. write(optionId, amount, claimId) only checks that the top 160 bits of claimId match the option and that the caller's ERC-1155 balance of claimId is exactly 1. It never checks that the low 96 bits are non-zero, so claimId == optionId passes when the caller holds one option token, and the engine records the claim under the option's own ID, which redeem rejects.

        ##### Who can do it

        Alice uses a front end or script at Acme Markets that mistakenly reuses the option ID in the claim field. She holds exactly one option token of that type from an earlier trade. Her call to write 50 more options succeeds and pulls 50 x underlyingAmount plus fee from her wallet.

        - Caller holds exactly 1 option token of the option type.

        - Caller passes claimId equal to the option ID (low 96 bits zero).

        ##### What they get

        No attacker gains anything; the harm is loss. Alice receives 50 option tokens, but the matching collateral is tracked under a claim ID with claim number zero, and redeem reverts with InvalidClaim for any ID with a zero claim number. Her collateral, and any exercise asset later assigned to it, is stuck in the contract forever. Other writers' payouts stay correct because the phantom claim is accounted for in the bucket totals.

        ##### How it works

        1. Alice calls write(optionId, 50, optionId); the check at src/OptionSettlementEngine.sol:303-305 passes because the upper bits match.

        2. The ownership check at src/OptionSettlementEngine.sol:337-340 reads balanceOf[msg.sender][optionId], which is her option token balance of 1, and passes.

        3. Lines 343-350 update _claim[optionId] and the claim index under the option ID, and line 365 mints 50 options to her; line 369 pulls the collateral.

        4. redeem(optionId) reverts at src/OptionSettlementEngine.sol:438-440 because the claim number is zero, so the collateral is unrecoverable.

        Exploit scenario

        Not specified.

        Recommendation

        In write, decode claimId and revert with InvalidClaim when claimId != 0 and its claim number is zero (or when it is >= nextClaimNum). Verify with a test that write(optionId, 1, optionId) reverts while a caller holds exactly one option token.

      • Rounding error in the redeem mechanism valorem-2 · 7 writeups High

        V12

        Whole-contract rounding strands substantial claim payouts

        src/OptionSettlementEngine.sol:585 Predicted severity: High

        Root cause

        _getAmountExercised rounds proportional entitlements in whole-contract units before _getPositionsForClaim converts them to asset units. Independently rounding both categories destroys conservation of a claim's collateral entitlement.

        Impact

        Writers can lose entire claim payouts during partial exercise of a shared bucket, even when the per-option asset amounts are large. After the claim tokens are burned, neither redemption nor fee sweeping provides a path to recover these unallocated principal balances.

        Description

        _getAmountExercised independently rounds a claim's exercised and unexercised allocations down to whole option contracts. _getPositionsForClaim only multiplies those rounded counts by the per-option asset amounts afterward, so the lost fraction can represent substantial collateral rather than token-unit dust. For example, two claims each writing one contract in the same day bucket, followed by one exercise, give each claim floor(1 * 1 / 2) = 0 contracts in both payout categories. At expiry, redeem consequently pays neither asset to either writer and still burns both claim tokens. This source-level example leaves one contract's underlying collateral and one contract's exercise payment without a redeemable entitlement; it is not a runtime-tested reproduction because the workspace lacks the imported math dependency.

        Codex Security (GPT-6 Sol)

        Partial exercise can permanently strand writers’ collateral and exercise proceeds

        src/OptionSettlementEngine.sol:592 Predicted severity: High

        Root cause

        The engine aggregates exercised options by day, then independently floors each claim's proportional exercised and unexercised counts. Those two rounded values need not sum to the claim's written count, and no remainder is allocated before claim destruction.

        Impact

        An ordinary holder can trigger complete loss for small claims in a shared bucket; no privileged access or unusual token behavior is required.

        Description

        When multiple one-option claims share a day bucket, exercising one option makes each claim's exercised and unexercised share round down to zero. Redemption burns the claims with no payout, leaving the remaining collateral and paid exercise asset inaccessible.

        Exploit scenario

        Public writes -> shared day bucket -> public partial exercise -> per-claim floored ratios -> zero payout and claim burn.

        Recommendation

        Allocate integer exercised counts to claims with a conservation-preserving remainder rule; derive each claim's unexercised count from its written count minus the allocated exercised count before redemption.

        Pashov (Codex GPT-6 Sol high)

        Independent claim rounding permanently locks both settlement assets

        src/OptionSettlementEngine.sol:590 Predicted severity: High

        Root cause

        Both pro rata divisions round down independently, and no claim or residual account receives the remainders.

        Impact

        Writers can permanently lose the underlying collateral and exercise proceeds attributable to their claims. An attacker can cause large aggregate losses by splitting writing into many small claims in the same bucket and exercising a subset of the options.

        Description

        The engine calculates each claim's exercised and unexercised shares with separate downward rounding. Small claims can receive zero of both assets even though their options were fully collateralized and some were exercised. Redemption then burns the claim NFT, leaving the unpaid assets in the engine without a withdrawal path.

        Exploit scenario

        Two writers each write one option in the same day bucket. One option is exercised. Each claim computes floor(1*1/2) = 0 exercised and floor(1*1/2) = 0 unexercised. Both claim holders redeem for zero, while one underlying unit and one exercise payment remain trapped.

        Recommendation

        Allocate integer exercised units to individual claims with a conservation-preserving remainder rule, and derive each claim's unexercised units from its written units. Verify that the sums of all claim payouts equal the bucket's remaining underlying and collected exercise proceeds.

        Devin Security (Deep)

        Claim payouts round down to whole options, permanently locking up to one option's underlying and exercise asset per claim per day

        src/OptionSettlementEngine.sol:592 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Writers who share a day bucket with other writers can lose up to a full option's worth of collateral per bucket on redeem, and the lost tokens are stuck in the contract forever with no way for anyone to recover them.

        ##### What's wrong

        This is a precision loss bug. The engine computes each claim's exercised and unexercised share as whole option counts with mulDivDown, then multiplies by the per-option asset amounts. The fractional option that is rounded away in each of the two divisions is not paid to anyone and cannot be swept.

        ##### Who can do it

        Alice writes 1 WETH/USDC call option (1 WETH underlying, 2000 USDC exercise). Bob writes 2 of the same option type the same day, so all 3 are in one bucket. Carol, any holder, exercises 1 option. Nobody needs to be malicious; this happens in normal use. A griefer can also trigger it deliberately by exercising an amount that does not divide evenly across the bucket.

        - Two or more claims share a day bucket (any two writers writing the same option type on the same day).

        - The bucket is partially exercised at expiry.

        ##### What they get

        At redeem Alice's exercised share is floor(1 x 1 / 3) = 0 and her unexercised share is floor(2 x 1 / 3) = 0, so she receives nothing; her 1 WETH is lost. Bob receives floor(4 / 3) = 1 WETH and 0 USDC, losing one WETH of value as well. The contract keeps 1 WETH and 2000 USDC that no function, including the admin's sweepFees, can ever release. In a bucket of two writers with 10 options each and one exercise, each writer loses half an option of underlying and half an option of exercise asset. For option types sized at one WETH or one WBTC per contract this is thousands of dollars per incident, and it recurs for every claim in every partially exercised bucket.

        ##### How it works

        1. After expiry, Alice calls redeem (src/OptionSettlementEngine.sol:435-478), which calls _getPositionsForClaim.

        2. _getAmountExercised (src/OptionSettlementEngine.sol:592-602) computes mulDivDown(amountExercised, claim.amountWritten, bucket.amountWritten) and the same for the unexercised count, both floored to whole options.

        3. _getPositionsForClaim (src/OptionSettlementEngine.sol:616-617) multiplies those truncated counts by exerciseAmount and underlyingAmount, so the fractional option is dropped from both payouts.

        4. redeem burns the claim NFT at line 459 and transfers only the truncated amounts; the remainder stays in the contract with no path out.

        Exploit scenario

        Not specified.

        Recommendation

        Do the pro-rata math in asset units instead of option counts: exerciseAmount += mulDivDown(bucket.amountExercised * optionRecord.exerciseAmount, claim.amountWritten, bucket.amountWritten) and likewise for the underlying with (bucket.amountWritten - bucket.amountExercised) * optionRecord.underlyingAmount. The rounding loss then drops to at most 1 wei per claim per bucket. Verify with a test where Alice writes 1, Bob writes 2, Carol exercises 1, warp past expiry, and assert Alice receives 2/3 of underlyingAmount and 1/3 of exerciseAmount (within 1 wei) and the contract balance after all redeems is only the fee balance plus dust.

        Claude Security (Sonnet 5.5)

        Both exercised and unexercised shares round down, so partially exercised buckets strand funds and can zero out small claims

        src/OptionSettlementEngine.sol:592 Predicted severity: Low

        Root cause

        Vulnerable symbol: _getAmountExercised

        Preconditions: A bucket is partially exercised; Claim lots are small relative to the bucket total, or option unit sizes are large

        Offending code:

        _exercised = FixedPointMathLib.mulDivDown(

        Impact

        Writers lose up to one option unit (underlyingAmount or exerciseAmount, which can be large, e.g. 7 WETH per option in the tests) per claim index, and small lots can be wiped out. The stranded underlying and exercise assets are unrecoverable. A griefer can deliberately bring a victim's small claim into the zero-payout case.

        Description

        _getAmountExercised floors the exercised share and the unexercised share independently, in whole option units. For any claim with amountWritten = 1 in a bucket where 0 < amountExercised < amountWritten, both floors are 0, so redeem() pays nothing for that unit. More generally each claim index loses up to 1 option unit across the two assets. The remainder is never redistributed and stays in the engine permanently.

        Exploit scenario

        Alice writes 1 option and Carol writes 2 options on the same day (W=3). A holder exercises 1 option (E=1). At expiry Alice's claim gets floor(1*1/3)=0 exercise units and floor(2*1/3)=0 unexercised units, so she redeems nothing. Carol gets 0 exercise units and 1 of her 2 unexercised units. One unit each of exercise asset and underlying remains locked in the engine.

        Recommendation

        Compute the unexercised share as amountWritten - exercisedShare so the two shares sum exactly to the claim's stake. Use a largest-remainder or cumulative approach so that all dust is distributed, and consider tracking the remainder in the bucket.

        Claude Security (Opus 5.5)

        Redemption rounds whole option contracts down for each claim, so collateral is stranded in the engine for good

        src/OptionSettlementEngine.sol:592 Predicted severity: Medium

        Root cause

        Vulnerable symbol: _getAmountExercised

        Preconditions: Two or more claims written into the same day bucket; The bucket is partly exercised at expiry; Per-contract amounts large enough for one contract to matter

        Offending code:

        _exercised = FixedPointMathLib.mulDivDown(

        Impact

        Writers permanently lose up to one contract's worth of underlying and exercise asset for each claim and day bucket, and up to 100% for small lots. This happens in normal use whenever a bucket holds several claims and is partly exercised. The loss is large when contracts are large (underlyingAmount can be as big as a uint96).

        Description

        exercise() records assignment per day bucket (OptionsDayBucket.amountExercised), and redeem() works out each claim's share in whole option contracts. It rounds the exercised and unexercised counts down separately (lines 592-602) before multiplying by the per-contract exerciseAmount and underlyingAmount (lines 616-617). Each claim index can lose up to one full contract's value. Nothing can ever withdraw that value, because sweepFees only moves feeBalance.

        Exploit scenario

        Two writers each write 1 contract of a 1 WETH / 2000 USDC option on the same day, so the bucket shows written=2. One contract is exercised and lands in that bucket (exercised=1). On redeem, each writer gets exercised = 1*1/2 = 0 and unexercised = 1*1/2 = 0. Both claims are burned and pay nothing, and 1 WETH plus 2000 USDC stay in the contract with no way out. A griefer can also force this on purpose: write 1 contract into a victim's day bucket and exercise 1.

        Recommendation

        Work out redemption in asset units, not contract counts. For example, exerciseAmount = mulDivDown(bucket.amountExercised * optionRecord.exerciseAmount, claimIndex.amountWritten, bucket.amountWritten), and do the same for the underlying. Or track per-claim assignment exactly so no whole contract is lost to rounding.

        Vercel Security Review

        Whole-contract rounding can erase claimants' entire redemption

        src/OptionSettlementEngine.sol:592 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Partial exercise rounds away claim ownership** - src/OptionSettlementEngine.sol:592-594

        ```solidity title="src/OptionSettlementEngine.sol:592-594"

        _exercised = FixedPointMathLib.mulDivDown(

        claimBucketInfo.amountExercised, claimIndex.amountWritten, claimBucketInfo.amountWritten

        );

        ```

        Two one-contract claims sharing a bucket with one exercise each receive an exercised count of zero.

        **2. Remaining collateral ownership also rounds away** - src/OptionSettlementEngine.sol:598-601

        ```solidity title="src/OptionSettlementEngine.sol:598-601"

        _unexercised = FixedPointMathLib.mulDivDown(

        claimBucketInfo.amountWritten - claimBucketInfo.amountExercised,

        claimIndex.amountWritten,

        claimBucketInfo.amountWritten

        ```

        Both unexercised counts likewise become zero, before conversion into asset units at lines 615-617.

        **3. Redemption irreversibly burns the claims** - src/OptionSettlementEngine.sol:457-459

        ```solidity title="src/OptionSettlementEngine.sol:457-459"

        claimRecord.claimed = true;

        _burn(msg.sender, claimId, 1);

        ```

        Neither claimant receives either asset; remaining collateral and strike payments become permanently stranded.

        Exploit scenario

        Not specified.

        Recommendation

        Calculate proportional payouts in ERC20 base units before rounding, using overflow-safe arithmetic. Test partial exercise across multiple claims.

      • Writing during the exercise period may lead to arbitrage opportunities valorem-3 · 6 writeups Medium

        V12

        Late writes dilute historical exercise entitlements

        src/OptionSettlementEngine.sol:313 Predicted severity: High

        Root cause

        Current-day bucket contributions remain mutable after exercise assignment, but claim settlement uses only final cumulative ratios. No per-write checkpoint separates pre-existing exercise allocations from claims created afterward.

        Impact

        A late writer can retrospectively purchase a share of already-collected exercise assets rather than only assume exposure to future exercises. Inference: if those exercise assets have become worth more than the collateral deposited later that day, the writer can extract the difference from existing claim holders by diluting their prior assignment.

        Description

        write remains available throughout the exercise window and adds same-day contributions to the current bucket even after that bucket has already absorbed exercises. _getAmountExercised later apportions the bucket's cumulative historical exercises using its final amountWritten denominator and each claim's final contribution. Consequently a new claim can receive exercise payments made before the claim existed, while earlier claims lose part of their previously assigned exercise entitlement. For example, an original 100-contract claim that has been fully exercised is reopened by a later same-day 100-contract write; with no further exercises, both claims settle as 50 exercised and 50 unexercised. The new writer's option tokens need not be exercised for that writer to receive half of the earlier exercise payments.

        Pashov (Claude Opus 5.5 high)

        Same-day bucket pooling lets late writers capture exercise proceeds already assigned to earlier writers

        src/OptionSettlementEngine.sol:622 Predicted severity: Medium

        Root cause

        Assignment is recorded per day-bucket, not per claim, and buckets stay open to new writes after exercises have already been assigned to them. Exercises assigned before a write are spread over writers who were not exposed when the exercise happened.

        Impact

        Value moves between writers. After an exercise, an attacker can watch the price and, if the exercise asset is now worth more than the underlying (the price moved down after exercise), write into the same bucket. They redeem part of the earlier writer's exercise proceeds and leave that writer with underlying that has lost value. Honest writers lose funds and assignment no longer matches what each writer was exposed to.

        Description

        All writes made on the same UTC day are added to one OptionsDayBucket, and a claim's redemption is computed as bucket.amountExercised * claim.amountWritten / bucket.amountWritten. Writes that happen after an exercise was already assigned to the bucket increase amountWritten without changing amountExercised, so the new writer retroactively receives a pro-rata share of exercises that happened before they wrote. A fully exercised bucket is even put back into the unexercised list when someone writes again that day.

        Exploit scenario

        Day D: Alice writes 10 WETH calls (strike 1300 DAI). A holder exercises 10, so the bucket is fully assigned and Alice is owed 13,000 DAI. Later that day WETH falls to 1000 DAI. Mallory writes 10 options into the same bucket (written=20, exercised=10). At expiry, both Alice and Mallory redeem 5 exercised (6,500 DAI) plus 5 WETH. Mallory deposited 10 WETH worth 10,000 DAI and leaves with 6,500 DAI + 5 WETH (11,500 DAI). Alice loses the 1,500 DAI Mallory gained. Mallory's own 10 options are out of the money and not worth exercising.

        Recommendation

        Snapshot exercise state per write. Examples: start a new bucket after any exercise has been assigned to the current bucket, or track per-claim 'exercised-before-write' offsets (similar to reward-per-share accounting) so later writes cannot share earlier assignments.

        Pashov (Codex GPT-6 Sol high)

        Later same-day writes capture earlier exercise proceeds

        src/OptionSettlementEngine.sol:636 Predicted severity: High

        Root cause

        The daily bucket stores only aggregate written and exercised amounts and retroactively dilutes the exercise ratio when a later write increments amountWritten.

        Impact

        A strategic writer can transfer exercise proceeds from earlier writers to itself, exchanging newly deposited underlying for already collected exercise assets and extracting value when market prices have moved.

        Description

        The engine adds new same-day options to a bucket after previous options in that bucket were exercised. The new claim receives a share of those earlier exercise payments because redemption calculates the final bucket ratio against all writes, regardless of when each claim was created. Existing claims consequently lose settlement proceeds to later writers.

        Exploit scenario

        Writer A writes 100 options in a bucket and all 100 are exercised. Before the day changes, writer B writes 100 options of the same type. The bucket changes from written=100, exercised=100 to written=200, exercised=100. Each 100-option claim now redeems 50 underlying units and 50 exercise payments, so B receives 50 payments collected before B wrote any option while A loses them.

        Recommendation

        Freeze or segment the settlement cohort once an exercise occurs. Place subsequent writes into a new bucket or track per-claim exercise assignment so earlier exercise amounts cannot be reallocated to later claims.

        Devin Security

        Writing into a same-day bucket after it was exercised moves earlier exercises onto the new writer

        src/OptionSettlementEngine.sol:636 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        An honest writer who writes later on the same day can be charged for exercises that happened before they wrote, which moves value between writers of the same option.

        ##### What's wrong

        This is an accounting logic bug. Exercise is tracked per day bucket, not per claim. Redemption splits the bucket's exercised amount pro rata across every claim in the bucket. That includes claims written after the exercise. When a fully exercised bucket gets new writes, it is re-added to the unexercised list, and its old exercises are spread across old and new writers.

        ##### Who can do it

        Mallory writes 100 options on day D after the exercise window opens. She exercises all 100 herself the same day, which fully exercises the day-D bucket. Bob writes 100 options later that day. Now the bucket shows 200 written and 100 exercised. Mallory's claim is treated as 50 exercised and 50 unexercised, and Bob's is the same.

        - The attacker has any Ethereum account.

        - The exercise window is open, so writing and exercise can happen on the same day.

        - Another user writes into the same day bucket afterward.

        ##### What they get

        Bob takes on half of an exercise that happened before his options existed. If his own options are not exercised later, Bob redeems less underlying than he should and Mallory redeems more. The total collateral stays consistent. The loss is limited to writers in that day bucket of that option type.

        ##### How it works

        1. _addOrUpdateClaimBucket adds new writes to today's bucket and re-adds it to the unexercised list if it was fully exercised (src/OptionSettlementEngine.sol:641-650).

        2. _getAmountExercised computes each claim's exercised share as bucket.amountExercised * claim.amountWritten / bucket.amountWritten (lines 592-602).

        3. The bucket ratio includes exercises that happened before the later claim was written, so the later writer absorbs part of them at redeem (line 455).

        Exploit scenario

        Not specified.

        Recommendation

        Start a new bucket when writing into a bucket that already has exercises, or track exercises at claim granularity. To check the fix, add a test where writer A is fully exercised, writer B writes the same day, and both redeem: A should get all exercise asset and B all underlying.

        Devin Security (Deep)

        Writing into a day bucket that already has exercises retroactively assigns those exercises to the new writer

        src/OptionSettlementEngine.sol:636 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can write options late in the day into a bucket where other writers were already assigned, and at expiry collect part of those earlier writers' settlement value with no downside of their own.

        ##### What's wrong

        This is a retroactive assignment bug. The engine groups every option written on the same day into one shared bucket and splits that bucket's exercised count pro-rata among its writers at redeem time. When a bucket already has exercises and a new writer adds options to it later the same day, the new options take a share of exercises that happened before they existed, and the earlier writers are silently un-assigned.

        ##### Who can do it

        Alice, a market maker, writes 100 WETH/USDC call options in the morning. Bob holds them and exercises all 100 while the option is in the money, so Alice's claim is now fully assigned and will pay her 100 x the exercise amount in USDC. In the afternoon the price of WETH drops and the option is out of the money. Mallory, an attacker with any funded wallet, writes 900 options of the same type. Because it is still the same day, her options land in Alice's bucket.

        - The option type's exercise window is open (exerciseTimestamp has passed) and it has not expired.

        - At least one exercise was assigned to today's bucket before Mallory's write.

        - Mallory writes before the UTC day rolls over.

        - Some options in the bucket stay unexercised through expiry (true whenever the option ends out of the money).

        ##### What they get

        At expiry the bucket shows 1000 written and 100 exercised. Alice's claim is now only 10% assigned: she receives 10 x the USDC exercise amount and 90 WETH back, instead of the 100 x USDC she had earned when Bob exercised. Mallory's claim is 10% assigned too: she deposited 900 WETH and receives 90 x the USDC exercise amount plus 810 WETH, pocketing the price difference on 90 options that she never had real exposure to. If the option instead moves back into the money, Mallory exercises her own 900 options and ends at least even, so the position has no downside for her. Mallory can repeat this on every option type and every day where exercises happen, and the losses fall on whichever writers wrote earlier that day.

        ##### How it works

        1. Bob exercises, and _assignExercise (src/OptionSettlementEngine.sol:547-567) increments amountExercised on today's bucket until it is fully exercised and removes it from the unexercised list.

        2. Mallory calls write later the same day; _addOrUpdateClaimBucket (src/OptionSettlementEngine.sol:636-649) sees daysAfterEpoch is unchanged and adds her amount to the same bucket's amountWritten, re-adding the bucket to the unexercised list.

        3. At redeem, _getAmountExercised (src/OptionSettlementEngine.sol:592-602) splits the bucket's amountExercised pro-rata by each claim's amountWritten, so Mallory's claim is credited with exercises that happened before she wrote and Alice's claim loses them.

        4. _getPositionsForClaim (src/OptionSettlementEngine.sol:612-618) converts those counts into exercise and underlying asset payouts, moving the settlement value from Alice to Mallory.

        Exploit scenario

        Not specified.

        Recommendation

        Never add new writes to a bucket that has already been exercised. In _addOrUpdateClaimBucket, when the current bucket has amountExercised != 0, push a new OptionsDayBucket for today instead of incrementing amountWritten on the existing one (a bucket should be identified by day plus an 'unexercised' state, not day alone). Verify with a test: Alice writes 100, Bob exercises 100, Mallory writes 900 in the same day, warp past expiry, and assert Alice's redeem pays exactly 100 x exerciseAmount and 0 underlying while Mallory's pays 0 exerciseAmount and 900 x underlyingAmount.

        Vercel Security Review

        Late same-day writes capture previously paid exercise proceeds

        src/OptionSettlementEngine.sol:642 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. New writes reopen an already exercised bucket** - src/OptionSettlementEngine.sol:640-643

        ```solidity title="src/OptionSettlementEngine.sol:640-643"

        } else {

        // Update claim bucket for today

        currentBucket.amountWritten += amount;

        bucketIndex -= 1;

        ```

        Before expiry, anyone can add collateral to today's bucket even after its earlier claims were fully exercised.

        **2. Historical payments become the new writer's entitlement** - src/OptionSettlementEngine.sol:592-594

        ```solidity title="src/OptionSettlementEngine.sol:592-594"

        _exercised = FixedPointMathLib.mulDivDown(

        claimBucketInfo.amountExercised, claimIndex.amountWritten, claimBucketInfo.amountWritten

        );

        ```

        If an earlier two-contract lot was fully exercised, adding another two-contract lot gives each lot one exercised and one unexercised contract.

        **3. Redemption transfers earlier writers' proceeds** - src/OptionSettlementEngine.sol:461-463

        ```solidity title="src/OptionSettlementEngine.sol:461-463"

        if (exerciseAmount > 0) {

        SafeTransferLib.safeTransfer(ERC20(optionRecord.exerciseAsset), msg.sender, exerciseAmount);

        }

        ```

        After a same-day price fall below strike, the attacker leaves new options unexercised and redeems collateral plus historical strike proceeds, profiting at earlier writers' expense.

        Exploit scenario

        Not specified.

        Recommendation

        Exclude new writes from prior exercise allocations. Seal exercised buckets and create fresh buckets for subsequent collateral, or track assignment baselines per claim.

    • Voyage Solidity NFT lending diamond. Tasks 16 V12 16/16 Codex Sec 9/16 Pashov Opus 13/16 Pashov GPT-6 9/16 Devin 7/16 Devin (Deep) 14/16 Claude Sec 8/16 Claude Opus 8/16 Vercel 7/16

      NFT lending diamond.

      Read the audit report
      • Public pullToken function allows stealing ERC20 tokens for which Voyage has approval voyage-1 · 9 writeups Critical

        V12

        Public payment helper steals approved provider tokens

        contracts/voyage/facets/LiquidityFacet.sol:128 Predicted severity: Critical

        Root cause

        The payment helper used by deposit exposes the diamond's spender authority through a public function with caller-selected source and destination. ERC20 allowances intended for deposit or withdrawal flows are not bound to the account invoking those flows.

        Impact

        Any account can transfer a provider's approved underlying directly to an attacker-selected recipient without minting shares. The same helper also exposes tranche shares approved to the diamond for withdrawals, so granting the normal protocol allowance creates an unauthorized-transfer path.

        Description

        deposit requires providers to approve the Voyage diamond so its payment helper can pull underlying from them. The same diamond exposes the inherited public pullToken function without restricting its caller, from, or recipient arguments. An external caller can therefore invoke that helper directly with a provider as from and the caller's address as recipient. The ERC20 sees the diamond as the spender and honors the provider's existing allowance, despite the transfer not being a deposit. The deployment script installs PaymentsFacet alongside LiquidityFacet, and the test setup grants the diamond an unlimited underlying allowance.

        Codex Security (GPT-6 Sol)

        Any caller can transfer tokens approved to Voyage

        contracts/shared/util/PeripheryPayments.sol:14 Predicted severity: Critical

        Root cause

        PaymentsFacet inherits externally callable PeripheryPayments.pullToken. It forwards caller-chosen from and recipient to safeTransferFrom with no caller binding; ERC20 allowance to the diamond is the only check.

        Impact

        An unprivileged caller can take approved user tokens up to the allowance without initiating a legitimate deposit. Likelihood is high under the stated prerequisites.

        Description

        The public pullToken method lets any caller spend a user's ERC20 allowance to the Voyage diamond and choose the recipient, so approved funds can be sent to the caller.

        Exploit scenario

        contracts/shared/util/PeripheryPayments.sol:14 to contracts/voyage/facets/LiquidityFacet.sol:129

        Recommendation

        Make token pulling internal to authenticated protocol flows, or require the token owner to be the authenticated caller and bind the recipient.

        Pashov (Claude Opus 5.5 high)

        PeripheryPayments.pullToken lets anyone transfer tokens from any address that approved the Voyage diamond

        contracts/shared/util/PeripheryPayments.sol:14 Predicted severity: Critical

        Root cause

        No access control and no from == msg.sender restriction on a function that spends allowances granted to the diamond.

        Impact

        Theft of every token balance that any user has approved to the Voyage diamond (typically unlimited WETH approvals). Complete loss of user funds.

        Description

        PaymentsFacet (inheriting PeripheryPayments) is cut into the Voyage diamond and exposes pullToken(token, amount, from, recipient) as a public, unauthenticated function that executes token.safeTransferFrom(from, recipient, amount) with the diamond as msg.sender. Users must approve the diamond for the reserve currency (WETH) to deposit (LiquidityFacet.deposit uses pullToken), to pay the down-payment and protocol fee in buyNow, to repay and to liquidate. Any third party can therefore call pullToken naming a victim as from and themselves as recipient.

        Exploit scenario

        Alice approves Voyage for type(uint256).max WETH and deposits. Attacker calls Voyage.pullToken(WETH, WETH.balanceOf(alice), alice, attacker); the diamond calls WETH.transferFrom(alice, attacker, ...) using Alice's allowance and the attacker receives all her WETH.

        Recommendation

        Make pullToken internal (or restrict from to _msgSender()), and similarly restrict the other PaymentsFacet helpers. Internal facets should use an internal library function rather than an external self-call.

        Pashov (Codex GPT-6 Sol high)

        Permissionless pullToken can take any approved user funds

        audit/contracts/shared/util/PeripheryPayments.sol:14 Predicted severity: Critical

        Root cause

        pullToken is public with no caller or recipient constraint.

        Impact

        All users who approve the diamond for an ERC20 can lose up to their allowance.

        Description

        Any caller can choose from and recipient in pullToken, causing the diamond to spend another user’s token allowance.

        Exploit scenario

        After a victim approves Voyage, an attacker calls pullToken(token,amount,victim,attacker).

        Recommendation

        Restrict pullToken to trusted internal call paths or require from to equal the effective sender and recipient to be protocol-controlled.

        Devin Security

        Public pullToken lets anyone move tokens from any user who approved the Voyage diamond

        contracts/shared/util/PeripheryPayments.sol:14 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone on the internet can take every token that any Voyage user has approved to the Voyage contract, which covers lenders and borrowers who granted standing allowances.

        ##### What's wrong

        This is a missing access check on an arbitrary transferFrom. pullToken(token, amount, from, recipient) is a public function that runs token.safeTransferFrom(from, recipient, amount) with a caller-chosen from and recipient. PaymentsFacet inherits it, and the deploy script adds PaymentsFacet to the diamond, so the function is callable on the main Voyage contract by anyone.

        ##### Who can do it

        Alice, a lender, approves the Voyage diamond to spend her WETH so she can call LiquidityFacet.deposit. Bob, a borrower, approves an unlimited WETH allowance so that buyNow, repay and interest payments can pull funds. Mallory, who has no account and no relationship with Voyage, calls pullToken(WETH, amount, Alice, Mallory) on the diamond.

        - The victim has a non-zero allowance to the Voyage diamond for some token.

        - The victim holds a balance of that token.

        - PaymentsFacet is cut into the diamond (it is, in deploy/001_voyager.ts).

        ##### What they get

        Mallory receives Alice's and Bob's WETH directly in her own wallet. She can repeat this for every address with an allowance, and bots can watch Approval events to drain new approvals in the same block. The loss covers every Voyage user's approved balance.

        ##### How it works

        1. LiquidityFacet.deposit and LoanFacet.buyNow/repay require users to approve the diamond, because they pull funds with transferFrom from the user.

        2. PeripheryPayments.pullToken at contracts/shared/util/PeripheryPayments.sol:14-21 has no modifier and takes from and recipient as arguments.

        3. The diamond fallback delegatecalls PaymentsFacet, so safeTransferFrom runs with the diamond as the spender and uses the victim's allowance.

        4. The tokens go to the attacker-chosen recipient.

        Exploit scenario

        Not specified.

        Recommendation

        Remove from from the external API. Either make pullToken internal and call it with from = msg.sender from LiquidityFacet, or restrict it with require(msg.sender == address(this)) and pass the real user from the calling facet. Do the same for approve. Add a test where a third party calls pullToken(token, amt, victim, attacker) on the diamond and expect a revert.

        Devin Security (Deep)

        Anyone can call pullToken on the Voyage diamond to move tokens out of any wallet that approved it

        deployments/rinkeby/solcInputs/12dd858cd3471725424835f3a0db1659.json:152 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone on the internet can call pullToken on the Voyage diamond and move WETH (and deposit-token shares) out of any wallet that has approved the diamond, which is every depositor and borrower.

        ##### What's wrong

        This is a missing access control on a token-moving helper. PeripheryPayments.pullToken(token, amount, from, recipient) is a public function of PaymentsFacet, which is installed on the Voyage diamond. It calls token.safeTransferFrom(from, recipient, amount) with the diamond as the spender, and the caller chooses both from and recipient. The sibling helpers approve, sweepToken, unwrapWETH9(amountMinimum, recipient) and refundETH are also public and let anyone move whatever tokens or ETH the diamond itself holds.

        ##### Who can do it

        Alice deposits WETH into the Crab pool through LiquidityFacet.deposit, which requires her to approve the Voyage diamond to spend her WETH (most wallets set an unlimited approval). Bob borrows through buyNow and also approved the diamond. Mallory, an attacker with no account at all, calls pullToken(WETH, amount, alice, mallory) on the diamond.

        - The victim has a live WETH (or deposit-token share) allowance to the Voyage diamond. Every deposit, buyNow, repay and liquidate call requires one, and LiquidityFacet.withdraw requires a share allowance.

        - The PaymentsFacet selectors are installed on the diamond. deployments/rinkeby/Voyage.json lists pullToken (0xd26aaa3e), approve (0xe1f21c67), sweepToken (0xdf2ab5bb), unwrapWETH9 (0x49404b7c) and refundETH (0x12210e8a) on the deployed diamond.

        ##### What they get

        Mallory drains every protocol user's WETH wallet balance up to their allowance straight into her own address. She can also take any ETH or WETH sitting on the diamond (for example the first-instalment interest that buyNow strands there) with refundETH or unwrapWETH9(0, mallory), and the deposit-token shares of any user who approved the diamond for withdraw. Nothing limits the amount and she can repeat it for every user and every token.

        ##### How it works

        1. A user approves the Voyage diamond for WETH so that LiquidityFacet.deposit or LoanFacet.buyNow can pull funds; LiquidityFacet.deposit itself uses PaymentsFacet(address(this)).pullToken(..., msg.sender, ...) (contracts/voyage/facets/LiquidityFacet.sol:129-134).

        2. Mallory calls pullToken(WETH, amount, victim, mallory) directly on the diamond (contracts/shared/util/PeripheryPayments.sol:14-21, exposed by contracts/shared/facets/PaymentsFacet.sol:12).

        3. The diamond executes WETH.transferFrom(victim, mallory, amount); WETH checks the victim's allowance to the diamond, which exists, and transfers.

        4. Mallory can also call refundETH() or unwrapWETH9(0, mallory) (contracts/shared/facets/PaymentsFacet.sol:15-28 and 48-52) to take any ETH or WETH the diamond holds.

        Exploit scenario

        Not specified.

        Recommendation

        Remove pullToken and approve from the externally callable surface, or hard-code from = msg.sender and restrict approve, sweepToken, unwrapWETH9 and refundETH to msg.sender == address(this) (as MarketplaceAdapterFacet.purchase does) or make them internal library calls. Replace the external self-call in LiquidityFacet.deposit with a direct safeTransferFrom(msg.sender, ...). Verify with a test: after account A approves the diamond for WETH, account B calling pullToken(WETH, 1, A, B) must revert, and facetFunctionSelectors(PaymentsFacet) must no longer contain 0xd26aaa3e, 0xe1f21c67, 0xdf2ab5bb, 0x49404b7c or 0x12210e8a.

        Claude Security (Sonnet 5.5)

        PaymentsFacet.pullToken is callable by anyone and pulls tokens from an arbitrary from address

        contracts/shared/util/PeripheryPayments.sol:14 Predicted severity: Critical

        Root cause

        Vulnerable symbol: PeripheryPayments.pullToken

        Preconditions: Victim has a non-zero ERC20 allowance to the Voyage diamond, which the protocol requires for normal use

        Offending code:

        function pullToken(

        Impact

        Unauthenticated theft of the token balance of every address that has approved the diamond, up to its allowance. Typical approvals are unlimited, so this covers LP and borrower wallets.

        Description

        The diamond exposes pullToken(token, amount, from, recipient) with no authorization check. The caller picks from and recipient, and the diamond executes token.safeTransferFrom(from, recipient, amount) as spender. Any user who has approved the Voyage diamond can be drained.

        Exploit scenario

        A depositor, borrower or liquidator approves the diamond for WETH. LiquidityFacet.deposit, LoanFacet.buyNow, LoanFacet.repay and LoanFacet.liquidate all require that approval. An attacker calls voyage.pullToken(WETH, victimAllowanceOrBalance, victim, attacker). The diamond is the spender, so the transfer succeeds and the victim's tokens go straight to the attacker. This repeats for every approver.

        Recommendation

        Remove pullToken from the externally reachable surface, or make it internal or restricted to calls from the diamond itself (msg.sender == address(this)). Never accept a caller-supplied from; use the authenticated sender. Apply the same restriction to approve.

        Claude Security (Opus 5.5)

        Public pullToken lets anyone transferFrom any address that has approved the Voyage diamond, so depositor funds and vToken shares can be stolen

        contracts/shared/util/PeripheryPayments.sol:14 Predicted severity: Critical

        Root cause

        Vulnerable symbol: pullToken

        Preconditions: Victim has a non-zero ERC20 allowance to the Voyage diamond. The deposit flow requires this, and the project's own scripts grant MAX_UINT256.; PaymentsFacet selectors are registered on the diamond (they are, per deploy/001_voyager.ts)

        Offending code:

        function pullToken(

        Impact

        Anyone can steal, with no privileges, the full token balance (up to the allowance) of every user who approved the diamond for deposits, and the junior/senior tranche shares of every user who approved the diamond for withdrawals. Allowances granted through SelfPermit.selfPermit are exposed the same way.

        Description

        PaymentsFacet (a registered diamond facet; see deploy/001_voyager.ts:133) inherits the public payable pullToken(token, amount, from, recipient). It passes the caller-chosen from and recipient straight to token.safeTransferFrom (line 20) and never checks that from == msg.sender or that the caller is the diamond itself. LiquidityFacet.deposit (LiquidityFacet.sol:129-134) works by pulling the depositor's tokens through this function, so every depositor has to approve the diamond, and any caller can then spend that allowance.

        Exploit scenario

        Alice follows the documented flow: she approves the Voyage diamond for WETH (max, as in scripts/0003_deposit_reserve.ts) and calls deposit(). Later, or by front-running a deposit that follows an exact-amount approval, the attacker calls voyage.pullToken(WETH, WETH.balanceOf(alice), alice, attacker) and receives Alice's WETH. The same works on tranche shares. LiquidityFacet.withdraw calls vToken.withdraw(_amount, msg.sender, msg.sender) with the diamond as msg.sender, so a user who wants to withdraw must approve the diamond for their vToken shares. The attacker then calls pullToken(vToken, shares, victim, attacker), takes the shares, and redeems them.

        Recommendation

        Remove the arbitrary from parameter and always pull from msg.sender. Or restrict pullToken to internal use (require(msg.sender == address(this))) and change LiquidityFacet.deposit to transfer directly with IERC20(asset).safeTransferFrom(msg.sender, address(this), _amount), or let the vToken pull from the user directly. Also change LiquidityFacet.withdraw so it does not depend on users granting share allowances to the diamond.

        Vercel Security Review

        Public pullToken can steal any user's allowance to Voyage

        contracts/shared/util/PeripheryPayments.sol:17 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. The new payment facet exposes the inherited helper** - contracts/shared/facets/PaymentsFacet.sol:12

        ```solidity title="contracts/shared/facets/PaymentsFacet.sol:12"

        contract PaymentsFacet is PeripheryPayments, Multicall, SelfPermit {

        ```

        Normal depositors authorize Voyage to spend their underlying tokens (LiquidityFacet.sol:129-135).

        **2. Any caller can spend that authorization for an arbitrary recipient** - contracts/shared/util/PeripheryPayments.sol:17-20

        ```solidity title="contracts/shared/util/PeripheryPayments.sol:17-20"

        address from,

        address recipient

        ) public payable {

        token.safeTransferFrom(from, recipient, amount);

        ```

        No caller-to-from check or self-call restriction exists. An unrelated account can transfer a victim's tokens to itself, limited only by the victim's balance and allowance, without making a deposit.

        Exploit scenario

        Not specified.

        Recommendation

        Restrict this helper to calls from the diamond itself, preserving the deposit self-call flow. For any public pulling interface, bind the payer to the authenticated sender and constrain the destination; never let arbitrary callers spend another user's allowance.

      • Signature clash allows calls to transferReserve to steal NFT collateral voyage-2 · 6 writeups Critical

        V12

        Reserve transfers bypass NFT collateral restrictions

        contracts/voyage/facets/VaultFacet.sol:78 Predicted severity: Critical

        Root cause

        transferReserve does not restrict the target to approved fungible reserve assets, creating an alternate NFT-transfer path that bypasses the lien guard.

        Impact

        A borrower can transfer a correctly pledged NFT to any address without repaying the loan, removing the lender's collateral. Later liquidation cannot retrieve that NFT, exposing senior liquidity to unrecoverable borrower default.

        Description

        transferReserve accepts a caller-selected _currency and invokes its transferFrom(address,address,uint256) selector through the owner's vault. That selector is shared by ERC20 and ERC721. Passing an NFT collection as _currency and a pledged token ID as _amount therefore causes an ERC721 transfer rather than a reserve-token transfer. Unlike withdrawNFT, this entrypoint never checks nftIndex.isCollateral. The vault authorizes the Voyage call and executes the NFT transfer as its current owner.

        Pashov (Claude Opus 5.5 high)

        transferReserve can move collateralised NFTs out of the vault, bypassing the lien

        contracts/voyage/facets/VaultFacet.sol:97 Predicted severity: Critical

        Root cause

        The function treats _currency as an arbitrary ERC20 and does not check that it is not a collection / collateral NFT; selector collision between ERC20 and ERC721 transferFrom.

        Impact

        Borrowers can withdraw NFTs that secure outstanding loans immediately after buyNow and then default; liquidation will fail (NFT not in vault) and senior/junior depositors lose the full outstanding principal.

        Description

        transferReserve(vault, currency, to, amount) makes the vault call currency.transferFrom(vault, to, amount) without any check on currency. ERC721 transferFrom(address,address,uint256) has exactly the same selector as ERC20 transferFrom. A borrower can pass the collateral NFT collection as _currency and the collateral tokenId as _amount. Unlike withdrawNFT, there is no nftIndex[..].isCollateral check.

        Exploit scenario

        Attacker buys an NFT with buyNow paying only the first instalment, then calls transferReserve(myVault, collection, attacker, tokenId). The vault executes collection.transferFrom(vault, attacker, tokenId) (vault is the owner so it succeeds). The attacker sells the NFT and never repays.

        Recommendation

        Disallow _currency values that are registered collections/NFTs (or only allow the reserve currency), and check that the asset is not collateral; better, use typed functions for ERC20 vs ERC721 withdrawals.

        Devin Security (Deep)

        transferReserve lets a vault owner move collateral NFTs out of the vault while the loan is unpaid

        deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json:53 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Any borrower can take the NFT that secures their loan out of the vault after paying only the first instalment, leaving lenders with no collateral to liquidate.

        ##### What's wrong

        This is a collateral-lock bypass. VaultFacet.transferReserve(_vault, _currency, _to, _amount) has the vault call _currency.transferFrom(_vault, _to, _amount) without validating _currency. The ERC20 and ERC721 transferFrom(address,address,uint256) selectors are identical, so an NFT collection and token id move the NFT, skipping the isCollateral check that only withdrawNFT applies. The source is identical to the deployed artifact 12dd858c....

        ##### Who can do it

        Bob, a customer with an operator-created vault, buys a 9 ETH NFT via buyNow with a 3 ETH down payment and 6 ETH from the senior pool, then calls transferReserve(bobVault, crabCollection, bob, tokenId).

        - The attacker owns a vault (created through the authorised createVault).

        - The attacker has an open loan whose collateral sits in the vault.

        ##### What they get

        Bob keeps the NFT and never pays the remaining 6 ETH plus interest. liquidate later reverts because the vault no longer owns the NFT, so lenders recover nothing. Every borrower can repeat this on every loan.

        ##### How it works

        1. buyNow records the NFT as collateral in Bob's vault (contracts/voyage/libraries/LibLoan.sol:184-204).

        2. Bob calls transferReserve(vault, collection, bob, tokenId); only vault ownership is checked (contracts/voyage/facets/VaultFacet.sol:97-111).

        3. The encoded transferFrom(vault, bob, tokenId) is executed by Vault.execute, which the diamond is authorised to call (contracts/voyage/facets/VaultFacet.sol:60-67, contracts/vault/Vault.sol:113-123).

        4. liquidate reverts on the NFT transfer (contracts/voyage/facets/LoanFacet.sol:437-445).

        Exploit scenario

        Not specified.

        Recommendation

        Restrict _currency in transferReserve to initialised reserve currencies and reject registered collections, or route all vault asset movements through functions that check isCollateral. Verify: transferReserve(vault, crab, user, tokenId) after buyNow must revert.

        Claude Security (Sonnet 5.5)

        transferReserve lets a vault owner move collateralised NFTs out of the vault, bypassing the isCollateral lock in withdrawNFT

        contracts/voyage/facets/VaultFacet.sol:110 Predicted severity: High

        Root cause

        Vulnerable symbol: VaultFacet.transferReserve

        Preconditions: Attacker owns a vault (created by the admin); Attacker has an open loan whose NFT is held in the vault

        Offending code:

        IVault(_vault).execute(encodedData);

        Impact

        Borrowers can keep the NFT and default on the senior tranche's principal. The loan becomes unliquidatable, leaving permanent bad debt for LPs.

        Description

        withdrawNFT refuses to move an NFT whose nftIndex.isCollateral flag is set. transferReserve takes a caller-chosen _currency and builds transferFrom(_vault, _to, _amount) for it, with no check against the reserve currency. IERC20.transferFrom and IERC721.transferFrom share selector 0x23b872dd. An owner can therefore pass the collection as _currency and the tokenId as _amount, and Vault.execute will transfer the NFT out of the vault. Also CWE-20: The caller-supplied _currency is never checked to be an ERC20 or a reserve currency. It becomes the target of a transferFrom(vault, _to, _amount) call executed by the vault via Vault.execute. Passing an NFT collection as _currency and a tokenId as _amount moves a collateralised NFT out of the vault, skipping the isCollateral check that only withdrawNFT performs. Also CWE-843: transferReserve builds an ERC20 transferFrom(_vault, _to, _amount) call against a caller-chosen _currency and runs it through Vault.execute with Voyage's blanket permission. ERC20 and ERC721 share the transferFrom(address,address,uint256) selector. Passing a collateral collection as _currency and the tokenId as _amount makes the vault, as token owner, transfer the NFT. This bypasses the isCollateral check enforced in withdrawNFT. Also CWE-863: transferReserve lets the vault owner make the vault call transferFrom(vault, _to, _amount) on any _currency address, and the ERC-20 and ERC-721 transferFrom selectors are identical, so passing a collection address with _amount = tokenId transfers the NFT without the nftIndex.isCollateral check that withdrawNFT applies.

        Exploit scenario

        A borrower calls buyNow to buy an NFT with 2/3 of the price funded by the senior tranche, then calls transferReserve(vault, collection, attacker, tokenId). The NFT leaves the vault although the loan is open. The borrower stops repaying. LoanFacet.liquidate later calls IVault.execute(transferFrom(vault, liquidator, id)), which reverts because the vault no longer owns the token, so the position cannot be liquidated.

        Recommendation

        Restrict transferReserve to the reserve currency (WETH or the configured currencies) and reject any _currency that is a registered collection or has nftIndex entries. Alternatively, verify post-call that no collateral-flagged NFT has left the vault. Do not construct arbitrary token calls from user-chosen addresses. Also CWE-20: Restrict _currency in transferReserve to an allowlist of reserve currencies and WETH. Reject any address that is a registered reserve collection or that implements ERC721 (ERC165). Apply the same collateral check on every vault-originated transfer, not only in withdrawNFT. Validate _collection in withdrawNFT in the same way, since it also lets the vault call arbitrary contracts with the transferFrom selector. Also CWE-843: Restrict _currency to a whitelist of registered reserve currencies, or at least reject any address that is a registered collection. Do not build generic transferFrom calls for caller-supplied tokens. Apply the isCollateral check to every path that can move an NFT. Also CWE-863: Restrict transferReserve to the reserve currency (WETH) or to tokens that are not registered collections, and check nftIndex.isCollateral for any collection. Alternatively use a distinct function selector or an explicit ERC-20 transfer, and verify the vault still owns every collateral NFT before releasing funds.

        Claude Security (Opus 5.5)

        transferReserve accepts any address as _currency, so a borrower can pull collateral NFTs out of their vault

        contracts/voyage/facets/VaultFacet.sol:110 Predicted severity: High

        Root cause

        Vulnerable symbol: transferReserve

        Preconditions: Attacker owns a Voyage vault, which the admin creates through createVault as part of normal onboarding; Attacker has an active loan whose collateral NFT is held by the vault, i.e. buyNow was paid with only the downpayment

        Offending code:

        IVault(_vault).execute(encodedData);

        Impact

        A borrower can withdraw collateral NFTs that are still pledged. They keep an asset mostly paid for with pool liquidity and leave senior and junior depositors with unrecoverable debt. Liquidation of that loan also reverts permanently, so the debt cannot be resolved. This undermines the protocol's core collateral guarantee.

        Description

        transferReserve takes _currency, _to and _amount from the caller and never checks that _currency is a reserve ERC20. It then has the vault run _currency.call(transferFrom(_vault,_to,_amount)). ERC20 and ERC721 transferFrom(address,address,uint256) share the selector 0x23b872dd, so passing an NFT collection as _currency and a token ID as _amount moves that NFT. This bypasses the nftIndex[...].isCollateral check that withdrawNFT (VaultFacet.sol:86) enforces. Also CWE-843: The vault owner fully controls _currency, _to and _amount in transferReserve. The function builds IERC20.transferFrom(_vault,_to,_amount) (selector 0x23b872dd), which is byte-for-byte the same call as ERC721 transferFrom(from,to,tokenId). When _currency is an NFT collection, the vault executes an ERC721 transfer of token _amount. Nothing checks the nftIndex[...].isCollateral lock that withdrawNFT enforces. Also CWE-863: withdrawNFT and transferReserve both make the vault call target.transferFrom(vault, X, uint256). Only withdrawNFT checks nftIndex[..].isCollateral. transferReserve accepts any _currency target and any _amount. ERC721.transferFrom has the same selector as ERC20.transferFrom (0x23b872dd), so a vault owner can pass the NFT collection as _currency and the tokenId as _amount.

        Exploit scenario

        1) The admin creates a vault for the attacker, which is the normal onboarding step. 2) The attacker calls LoanFacet.buyNow(collection, tokenId, vault, marketplace, data) and pays only the downpayment. The senior tranche funds the rest, and the NFT ends up in the vault marked isCollateral = true. 3) The attacker calls VaultFacet.transferReserve(vault, collection, attackerEOA, tokenId). The diamond holds the ACL permission for vault.execute, so the vault calls collection.transferFrom(vault, attackerEOA, tokenId). The vault owns the token, so the transfer succeeds. 4) The attacker stops repaying. LoanFacet.liquidate reaches the same transferFrom from a vault that no longer owns the NFT, so it reverts and the bad debt can never be liquidated. Lenders lose the principal.

        Recommendation

        Restrict _currency to configured reserve currencies, for example by requiring it to be the currency of an initialized reserve, and reject any address that is a reserve collection or has nftIndex entries. Use transfer rather than transferFrom for ERC20 moves out of the vault. Also check that the move does not cut into funds backing outstanding debt. More broadly, have the vault and diamond tell ERC20 and ERC721 operations apart explicitly instead of relying on a shared selector with caller-chosen targets. Also CWE-843: Allow transferReserve only for whitelisted reserve currencies, for example require _currency to be a configured reserve currency and never an initialized collection. Better still, use separate, typed code paths for ERC20 and ERC721 and enforce the isCollateral lock in both. Also check the vault's outstanding debt and margin before allowing any ERC20 withdrawal. Also CWE-863: Restrict transferReserve to the reserve currency/approved ERC20s, or run the same nftIndex collateral check (and an ERC721 interface check) before executing. Better, use a dedicated vault-side function that refuses to move locked collateral.

        Vercel Security Review

        transferReserve can transfer NFT collateral out of indebted vaults

        contracts/voyage/facets/VaultFacet.sol:106 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. The new reserve withdrawal accepts an arbitrary token contract** - contracts/voyage/facets/VaultFacet.sol:103-106

        ```solidity title="contracts/voyage/facets/VaultFacet.sol:103-106"

        if (LibVault.getVaultAddress(_msgSender()) != _vault) {

        revert InvalidVaultCall();

        }

        bytes4 selector = IERC20(_currency).transferFrom.selector;

        ```

        A borrower supplies their NFT collection as _currency and a collateral token ID as _amount. ERC20 and ERC721 share the transferFrom(address,address,uint256) selector.

        **2. The vault transfers the collateral without checking its lien** - contracts/voyage/facets/VaultFacet.sol:107-110

        ```solidity title="contracts/voyage/facets/VaultFacet.sol:107-110"

        bytes memory param = abi.encode(_vault, _to, _amount);

        bytes memory data = abi.encodePacked(selector, param);

        bytes memory encodedData = abi.encode(_currency, data);

        IVault(_vault).execute(encodedData);

        ```

        Unlike withdrawNFT, this path never checks isCollateral. Voyage's vault-execution permission lets borrowers remove financed NFTs while leaving lenders with unsecured debt.

        Exploit scenario

        Not specified.

        Recommendation

        Restrict reserve transfers to configured currencies and use ERC20 transfer, not the ERC721-compatible transferFrom selector.

      • Missing calldata validation in buyNow results in stolen NFT voyage-3 · 6 writeups Critical

        V12

        Marketplace orders are not bound to pledged collateral

        contracts/voyage/facets/LoanFacet.sol:122 Predicted severity: High

        Root cause

        The loan collateral identifiers and encoded marketplace order describe the same intended purchase but are validated independently. buyNow trusts successful dispatch without validating acquisition and custody of the precise pledged NFT.

        Impact

        A borrower can withdraw an acquired NFT that was not indexed as collateral and leave the loan without a realizable pledged asset. Liquidation then attempts to transfer the declared token instead, allowing conditional loss of senior liquidity or liquidation failure; actual funded-marketplace execution is also constrained by the separately identified missing value forwarding.

        Description

        buyNow records collateral using the caller's _collection and _tokenId, but submits _data independently to the marketplace adapter without binding its order asset to those identifiers. Neither MarketplaceAdapterFacet.purchase nor the supplied adapters receives the expected collateral identifiers to enforce that relationship. The LooksRare adapter checks only the function selector, while the Seaport adapter checks the route, amount, and consideration token rather than matching the offered NFT to the loan. No post-purchase ownerOf check verifies that the recorded collateral arrived in the canonical vault. Consequently a successful order for a different NFT can leave the acquired asset unencumbered while the loan points at nonexistent or unrelated collateral.

        Codex Security (GPT-6 Sol)

        A funded purchase can leave the recorded NFT absent from the vault

        contracts/voyage/facets/LoanFacet.sol:115 Predicted severity: Medium

        Root cause

        LibLoan.initDebt records the caller's token ID before purchase. The adapters validate selectors and some order shape but not the expected collection/token ID; MarketplaceAdapterFacet.purchase executes the order via the vault and does not confirm ownerOf afterward.

        Impact

        Under a configured marketplace that returns success for mismatched order data, senior funds can finance a different or absent NFT and liquidation of the recorded collateral fails. Likelihood is unknown under the stated prerequisites.

        Description

        buyNow records caller-supplied collection and token ID as collateral without binding them to marketplace order fields or checking post-purchase ownership.

        Exploit scenario

        contracts/voyage/facets/LoanFacet.sol:115 to contracts/voyage/facets/LoanFacet.sol:263

        Recommendation

        Validate the order's collection, token ID, recipient and consideration against loan parameters, then require the expected NFT in the vault after execution.

        Pashov (Claude Opus 5.5 high)

        buyNow does not verify that the purchased NFT is the recorded collateral (collection/tokenId) or that the order price is the amount actually paid

        contracts/voyage/facets/LoanFacet.sol:150 Predicted severity: High

        Root cause

        Trusting user-supplied order data without binding it to the loan's collateral and without post-purchase ownership verification.

        Impact

        A borrower can sell a worthless NFT from any collection to his own vault at the floor price of a supported collection, receiving the pool's principal as seller proceeds; the loan is recorded against an NFT the vault never owns, so liquidation reverts or yields nothing and the senior/junior tranches lose the full outstanding principal.

        Description

        The collateral recorded by initDebt is the user-supplied _collection/_tokenId, while the asset actually bought is whatever the user-supplied marketplace order _data specifies. Neither the adapters (_validate only checks selector, route, offerAmount and considerationToken; LooksRare only checks the selector) nor buyNow check that the order's collection/offerToken equals _collection, that the tokenId equals _tokenId, or that the vault actually received the NFT afterwards. The price is taken from takerOrder.price / considerationAmount and compared to the floor of _collection.

        Exploit scenario

        Attacker lists a junk ERC721 on Seaport (ETH_TO_ERC721) for 10 ETH, where 10 ETH is the floor of collection C. He calls buyNow(C, tokenId X, vault, seaport, data-for-junk-order). Checks pass (price <= floor); the vault pays 10 ETH (6.7 from senior) to the attacker as seller; collateral recorded is C#X which the vault does not hold. Attacker defaults.

        Recommendation

        Decode and enforce collection == offerToken, tokenId == offerIdentifier, price including all additional recipients, and verify IERC721(collection).ownerOf(tokenId) == vault after the purchase.

        Devin Security

        buyNow never checks that the marketplace order buys the collateral NFT it records

        contracts/voyage/facets/LoanFacet.sol:145 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A borrower with a vault can take a loan that records one NFT as collateral while the marketplace order buys a different, worthless NFT that the borrower sells to themselves, which pulls lender funds out with no real collateral.

        ##### What's wrong

        This is a missing validation bug. buyNow takes _collection and _tokenId from the caller and records them as collateral. It takes the price and the actual order from separate, caller-supplied _data. Neither the facet nor the LooksRare or Seaport adapter checks that the order's collection and token ID match _collection and _tokenId. Neither checks that the vault receives that NFT.

        ##### Who can do it

        Bob is a borrower whose vault the operator has created. He lists a worthless NFT that he owns from a second address, priced at the floor price of a supported collection. He calls buyNow with that collection and any token ID, and passes his own listing as _data.

        - The borrower owns a vault created by the operator.

        - A marketplace adapter is registered for the _marketplace argument.

        - The vault can pay the order. The vault calls the marketplace with no ETH value, so this depends on how the marketplace pulls payment from the vault. This part is not fully verified.

        ##### What they get

        Bob's second address is paid about the floor price, and most of that money comes from the senior tranche. The recorded collateral is not in the vault, so liquidation cannot recover anything. The senior and junior lenders absorb the full loss, and Bob can repeat this up to his credit limit.

        ##### How it works

        1. buyNow stores the caller's _collection and _tokenId as collateral (LoanFacet.sol:123-124, and LibLoan.sol:193-196).

        2. The price comes from extractAssetPrice(_marketplace, _data), which returns the taker price or considerationAmount from _data (LoanFacet.sol:151-152).

        3. The only price check is fv >= totalPrincipal (LoanFacet.sol:161-163).

        4. MarketplaceAdapterFacet.purchase makes the vault call the marketplace with the caller's order as-is (MarketplaceAdapterFacet.sol:22-28).

        5. The adapters check only the function selector, the route and the amount. They never compare offerToken/offerIdentifier or makerOrder.collection/tokenId with the recorded collateral (adapter/SeaportAdapter.sol:240-279 and adapter/LooksRareAdapter.sol:143-163).

        Exploit scenario

        Not specified.

        Recommendation

        Have each adapter decode and return the collection and token ID of the order. In buyNow, require them to equal _collection and _tokenId. After purchase, require IERC721(_collection).ownerOf(_tokenId) == _vault. For Seaport, include the additional recipient amounts in the price. To check the fix, write a test that calls buyNow with an order for a different collection or token ID. It should revert.

        Devin Security (Deep)

        buyNow never checks that the vault received the named NFT, so pool funds are lent against collateral the vault does not hold

        deployments/rinkeby/solcInputs/12dd858cd3471725424835f3a0db1659.json:245 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A borrower can call buyNow with order data that does not deliver the named NFT and still receive two-thirds of the price from the senior pool, leaving lenders with a loan that can never be liquidated.

        ##### What's wrong

        This is a missing post-condition check. buyNow takes _collection and _tokenId as plain parameters and takes the purchase price from caller-supplied marketplace _data. Nothing verifies that _data refers to that collection and token, or that IERC721(_collection).ownerOf(_tokenId) == _vault after purchase. The loan and the collateral record are written against (_collection, _tokenId) regardless.

        ##### Who can do it

        Bob has an operator-created vault. On the deployed Rinkeby/Goerli system the registered marketplace is MockMarketPlace, whose matchAskWithTakerBidUsingETHAndWETH does nothing, so Bob calls buyNow(crab, 1, bobVault, mockMarketplace, data) with data naming a 9 ETH price while the Crab floor is 10 ETH. On a real marketplace, Bob would list a worthless NFT from a second wallet at 9 ETH and point _data at that listing.

        - The attacker has a vault; the reserve has liquidity and a non-zero oracle price.

        - The marketplace call completes without delivering (_collection, _tokenId) to the vault, which is true for the deployed mock marketplaces and for any self-listed item on a real marketplace.

        ##### What they get

        6 ETH of lenders' money, plus Bob's 3 ETH down payment, is sent to Bob's vault as ETH and no collateral exists. When Bob stops paying, liquidate reverts on the NFT transfer, so lenders cannot recover the 6 ETH. In the self-listing variant the 9 ETH lands in Bob's selling wallet, so he directly pockets lenders' funds. Repeating this drains the pool up to its available liquidity.

        ##### How it works

        1. buyNow extracts the price from _data via the adapter and only checks that it is at or below the oracle floor of _collection (contracts/voyage/facets/LoanFacet.sol:148-158).

        2. It moves outstandingPrincipal from the senior token and sends totalPrincipal ETH to the vault (contracts/voyage/facets/LoanFacet.sol:250-261).

        3. MarketplaceAdapterFacet.purchase has the vault call the marketplace with the adapter output; the vault forwards no ETH and nothing checks what, if anything, was received (contracts/voyage/facets/MarketplaceAdapterFacet.sol:14-29, contracts/vault/Vault.sol:113-123).

        4. The loan and nftIndex[_collection][_tokenId] are recorded as if the NFT were in the vault (contracts/voyage/libraries/LibLoan.sol:184-204).

        5. liquidate later tries collection.transferFrom(vault, liquidator, tokenId) and reverts (contracts/voyage/facets/LoanFacet.sol:437-445).

        Exploit scenario

        Not specified.

        Recommendation

        After purchase, require IERC721(_collection).ownerOf(_tokenId) == _vault, and have each adapter return the order's collection and token id so buyNow can require they equal _collection and _tokenId before any funds move. Verify with a test where the mock marketplace does not transfer the NFT: buyNow must revert and the senior token balance must be unchanged.

        Claude Security (Opus 5.5)

        buyNow locks a caller-chosen tokenId, not the NFT it bought, so borrowers can withdraw financed NFTs and lock other users' NFTs

        contracts/voyage/libraries/LibLoan.sol:194 Predicted severity: High

        Root cause

        Vulnerable symbol: initDebt

        Preconditions: Attacker holds a Voyage vault (created by the admin through createVault); buyNow completes a purchase through a registered marketplace adapter; The reserve has liquidity and a non-zero oracle floor price

        Offending code:

        LibAppStorage.ds().nftIndex[param.collection][

        Impact

        Each loan lets the borrower take the outstanding principal (about two-thirds of the NFT price with the default 30/90-day setup) from the senior pool, and the loan cannot be liquidated. The attacker can also lock other users' NFTs indefinitely, or unlock collateral backing someone else's loan, through the global nftIndex.

        Description

        The caller passes _tokenId to LoanFacet.buyNow (L117/L124). It is written straight into the loan's collateral list and into the global nftIndex[collection][tokenId] lock (LibLoan L193-196). Nothing ties it to the NFT that _data buys at L270. VaultFacet.withdrawNFT decides whether a withdrawal is allowed only from that nftIndex entry, so the caller controls which NFT gets locked.

        Exploit scenario

        1) A borrower with a registered vault calls buyNow(collection, tokenId=B, vault, marketplace, data). data is an order for the real NFT A; B is an id the vault does not hold, or an NFT in a victim's vault. The pool provides outstandingPrincipal, which is about (nper-1)/nper of the price, and the vault buys A. 2) nftIndex[collection][A] was never set, so the borrower calls VaultFacet.withdrawNFT(vault, collection, A) and receives A after paying only the downpayment, fee and interest. 3) The borrower stops paying. liquidate() tries transferFrom(vault, liquidator, B) through the vault. That reverts because the vault does not own B, so the loan can never be liquidated or written down, and the senior pool loses the principal. 4) If B is an uncollateralised NFT in another user's vault, its isCollateral flag is now true and that user can no longer withdraw it. Only clearing the attacker's loan resets the flag, and the attacker controls that. If B is someone else's collateral, clearing the attacker's own small loan sets isCollateral=false (LibLoan L319-321) and unlocks the other borrower's collateral early.

        Recommendation

        Take the collection and tokenId from the order the adapter executes, such as Seaport offerToken/offerIdentifier or LooksRare makerAsk.collection/tokenId, and require them to match _collection/_tokenId. After purchase, check that IERC721(_collection).ownerOf(_tokenId) == _vault. Revert if nftIndex[collection][tokenId].isCollateral is already true. Key the collateral lock per vault so one user cannot write another user's entry.

      • Missing timelocks can result in stolen NFTs voyage-4 · 9 writeups Critical

        V12

        Withdrawal caps are inflated after share burns

        contracts/voyage/tokenization/VToken.sol:41 Predicted severity: High

        Root cause

        pushWithdraw() values already-burned shares against a post-burn denominator while underlying has not left the tranche. The unbonding cap is not bound to the actual assets requested or a pre-burn share valuation.

        Impact

        A provider can withdraw a partial position and claim more underlying than the position relinquished, reducing the backing of remaining shares. This directly depletes junior assets available to cover liquidation shortfalls, and the same inherited implementation affects senior tokens.

        Description

        VToken.withdraw() burns shares before computing the unbonding position's maxUnderlying. pushWithdraw() then converts those burned shares using the reduced live supply while the withdrawn underlying remains in the token contract. With an initially balanced tranche holding 100 assets and 100 shares, withdrawing 20 assets burns 20 shares but records a cap of 25 assets, not 20. claim() can immediately pay that cap and does not enforce the declared cooldown. This path lets a junior provider overclaim before or between liquidation losses, leaving less underlying for the remaining providers and the liquidation backstop.

        Codex Security (GPT-6 Sol)

        A withdrawing depositor can claim other depositors' assets

        contracts/voyage/tokenization/VToken.sol:41 Predicted severity: Critical

        Root cause

        The withdrawal calculates shares before burning, but pushWithdraw calls convertToAssets after _burn. That conversion divides by the smaller remaining supply. claim transfers the recorded maxUnderlying if liquidity is available.

        Impact

        For 100 assets and 100 shares, withdrawing 49 shares can record a 96-asset claim, leaving four assets for other holders after claim. Likelihood is high under the stated prerequisites.

        Description

        VToken.withdraw burns shares before computing the pending asset entitlement. The reduced supply inflates maxUnderlying, and claim pays that inflated amount from the shared reserve.

        Exploit scenario

        contracts/voyage/tokenization/VToken.sol:41 to contracts/shared/tokenization/ERC4626.sol:128

        Recommendation

        Record the requested asset entitlement before burning shares and settle at most the remaining recorded asset amount.

        Pashov (Claude Opus 5.5 high)

        VToken.withdraw computes unbonding maxUnderlying after burning shares, letting withdrawers claim far more than their share

        contracts/voyage/tokenization/VToken.sol:41 Predicted severity: Critical

        Root cause

        Order of operations: _burn before convertToAssets in pushWithdraw (and totalUnbonding updated after the conversion).

        Impact

        A depositor can claim assets belonging to other depositors; with a large share, a single withdrawal can drain the whole tranche.

        Description

        VToken.withdraw burns the owner's shares first and only then calls pushWithdraw, which records maxUnderlying += convertToAssets(_shares). At that moment totalSupply has already decreased while totalAssets() has not (totalUnbonding is only incremented afterwards), so the share price used is inflated. claim() later pays out maxUnderlying (capped by the contract balance).

        Exploit scenario

        Pool has 200 assets/200 shares split 100/100 between Alice and attacker. Attacker withdraws 100 assets: shares=100 are burned (supply 100, totalAssets 200) then convertToAssets(100)=200 is recorded as maxUnderlying. Attacker calls claim(): availableLiquidity=200 is not > 200, so else-branch transfers all 200 tokens. Alice's deposit is gone.

        Recommendation

        Compute the asset amount before burning (use the _amount/previewRedeem value computed before state changes), and account totalUnbonding in assets consistently.

        Pashov (Codex GPT-6 Sol high)

        Withdrawal claim is valued after share burn and can drain other depositors

        audit/contracts/voyage/tokenization/VToken.sol:51 Predicted severity: Critical

        Root cause

        withdraw burns shares at line 53 and pushWithdraw calls convertToAssets on those same shares at line 72 using the post-burn supply.

        Impact

        A withdrawing depositor can claim more underlying than their shares represented before withdrawal, causing direct loss to other depositors and possible complete reserve depletion.

        Description

        VToken burns withdrawal shares before it computes the user's queued asset entitlement. The smaller total supply raises convertToAssets(shares), so the queued claim can exceed the requested withdrawal and consume assets belonging to remaining holders.

        Exploit scenario

        In a pool with 200 assets and 200 shares, an attacker owning 100 shares withdraws 99 assets. The burn leaves 101 shares, so pushWithdraw records floor(99*200/101)=196 assets. claim immediately pays 196 because cash 200 exceeds that cap, leaving only 4 assets for other holders.

        Recommendation

        Calculate and record the asset entitlement before burning shares, or pass the requested asset amount into pushWithdraw, and keep pending claims in asset units consistently.

        Devin Security

        Withdraw records an inflated claimable amount, so any depositor can drain the tranche

        contracts/voyage/tokenization/VToken.sol:41 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can deposit into a senior or junior tranche, withdraw, and claim almost all of the other depositors' money in the same block.

        ##### What's wrong

        This is a share accounting bug. VToken.withdraw burns the caller's shares first and only then calls pushWithdraw, which prices those already-burned shares with convertToAssets. Burning shrinks the total supply but leaves totalAssets unchanged, so the recorded maxUnderlying is far larger than what the shares were worth. claim then pays out maxUnderlying directly and has no cooldown check.

        ##### Who can do it

        Alice, a lender, has deposited 100 WETH into a tranche. Mallory, any Ethereum address, deposits 99 WETH and gets 99 shares. She calls withdraw(99, ...) on the tranche token and then claim() in the same transaction.

        - The tranche token is deployed and holds other depositors' funds.

        - Mallory holds enough of the underlying token to make a deposit somewhat smaller than the existing pool.

        - No account, role or vault is needed. deposit, withdraw and claim are public.

        ##### What they get

        In the example, withdraw records maxUnderlying as 99 × 199 / 100 = 197.01 WETH. claim sends Mallory 197.01 WETH, so she takes about 98 WETH of Alice's 100 WETH. She can repeat this to empty both the senior and junior tranche of every reserve. Lenders lose their deposits.

        ##### How it works

        1. Mallory deposits into the tranche through the public ERC4626 deposit (shared/tokenization/ERC4626.sol:35) and gets shares at the normal price.

        2. VToken.withdraw computes shares and then calls _burn before pushWithdraw (VToken.sol:46-54).

        3. pushWithdraw sets maxUnderlying += convertToAssets(_shares) (VToken.sol:72). The supply has already dropped, and totalUnbonding has not grown yet, so the price per share is inflated.

        4. claim checks only that the contract balance exceeds maxUnderlying and transfers that amount. It never checks cooldown or the share value (VToken.sol:91-107).

        5. The balance that pays Mallory belongs to the other depositors.

        Exploit scenario

        Not specified.

        Recommendation

        Compute the asset value of the shares before burning them, for example uint256 assets = convertToAssets(shares) before _burn, or simply record _amount. Add totalUnbonding to the accounting before or atomically with the burn. In claim, cap the payout at convertToAssets(unbondings[user].shares) (as maximumClaimable already does) and enforce cooldown. Fix the == typo in reduceUnbondingPosition. To check the fix, write a test with two depositors where one withdraws and claims. That depositor should receive no more than they deposited.

        Devin Security (Deep)

        Deposit tokens allow instant exit via redeem and claim, bypassing the unbonding queue and cooldown

        deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json:215 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A depositor who sees a loss coming can exit instantly through redeem, taking liquidity that was reserved for users already waiting in the withdrawal queue.

        ##### What's wrong

        VToken overrides withdraw to queue shares but inherits ERC4626.redeem, which pays out immediately and ignores totalUnbonding; claim() never checks the declared cooldown. Same source as the deployed artifact.

        ##### Who can do it

        Alice has a queued withdrawal; Mallory, another depositor, calls redeem(shares, mallory, mallory) on the token ahead of a write-down.

        - The attacker holds deposit-token shares and the token has WETH balance.

        ##### What they get

        Mallory exits at full pre-loss value with the WETH Alice's claim depended on; the loss falls on remaining depositors.

        ##### How it works

        1. VToken overrides withdraw only (contracts/voyage/tokenization/VToken.sol:41-57).

        2. ERC4626.redeem pays out instantly (contracts/shared/tokenization/ERC4626.sol:90-109).

        3. claim() has no cooldown check; cooldown is unused (contracts/voyage/tokenization/VToken.sol:24, 91-108).

        Exploit scenario

        Not specified.

        Recommendation

        Override redeem to use the unbonding logic (or revert) and enforce the cooldown in claim. Verify: redeem must revert or queue; claim before cooldown must revert.

        Claude Security (Sonnet 5.5)

        Unbonding position priced after the share burn, so claim() pays out far more than the shares are worth (drains a whole tranche)

        contracts/voyage/tokenization/VToken.sol:72 Predicted severity: Critical

        Root cause

        Vulnerable symbol: pushWithdraw

        Preconditions: Tranche token holds liquidity that has not been lent out; Attacker can deposit an amount X below the existing liquidity H (flash loan is enough)

        Offending code:

        unbondings[_user].maxUnderlying += convertToAssets(_shares);

        Impact

        Any unprivileged address can steal close to the entire liquidity of the junior or senior deposit token in one transaction (flash-loanable), leaving the other depositors with near-zero value.

        Description

        VToken.withdraw burns the caller's shares and only then calls pushWithdraw, which records maxUnderlying = convertToAssets(_shares) against the already-reduced supply; claim() then pays that inflated maxUnderlying out of the pool, and any address can deposit into and withdraw from the tranche token directly.

        Exploit scenario

        Junior (or senior) tranche holds H = 100 WETH for 100 shares. Attacker (own funds or a flash loan) calls tranche.deposit(99 WETH, attacker) and gets 99 shares (balance 199, supply 199). Attacker calls tranche.withdraw(99 WETH, attacker, attacker): previewWithdraw gives 99 shares, _burn drops supply to 100, then pushWithdraw records maxUnderlying = 99 * totalAssets(199) / supply(100) = 197.01 WETH. Attacker calls claim(): availableLiquidity (199) > maxClaimable (197.01), so 197.01 WETH is transferred. Net +98.01 WETH, taken from the honest depositor, who is left with about 1.99 WETH backing 100 shares. The attacker needs no privileges and never goes through the diamond. Any attacker deposit X < H works; the payout is roughly X*(X+H)/H. Static reasoning only; nothing was executed.

        Recommendation

        Compute the asset value of the shares before burning them and before the unbonding accounting changes (convertToAssets/previewRedeem at the pre-burn supply), or set maxUnderlying = the _amount argument already priced by previewWithdraw. Cap claims at min(maxUnderlying, current value). Add invariant tests on unbonding accounting.

        Claude Security (Opus 5.5)

        VToken withdraw values unbonding shares after burning them, so a withdrawer is credited with most or all of the pool

        contracts/voyage/tokenization/VToken.sol:72 Predicted severity: Critical

        Root cause

        Vulnerable symbol: pushWithdraw

        Preconditions: Pool has other depositors' funds

        Offending code:

        unbondings[_user].maxUnderlying += convertToAssets(_shares);

        Impact

        Any depositor can take almost the whole balance of either tranche, stealing the other LPs' funds.

        Description

        VToken.withdraw burns the owner's shares and only then calls pushWithdraw, which prices them with ERC4626.convertToAssets. At that point totalSupply has already dropped, but Junior/Senior totalAssets (balance - totalUnbonding) has not changed yet because totalUnbonding is updated afterwards. claim() then pays out the inflated maxUnderlying from the shared pool balance.

        Exploit scenario

        The junior (or senior) pool holds 100 WETH from Bob, backed by 100 shares. The attacker deposits 99 WETH and receives 99 shares (pool now 199 WETH / 199 shares). The attacker calls VToken.withdraw(99, attacker, attacker). The 99 shares are burned, leaving supply at 100, and convertToAssets(99) = 99*199/100 = 197. claim() sees a balance of 199 > 197 and sends 197 WETH to the attacker. Bob's 100 shares are now backed by about 2 WETH.

        Recommendation

        Compute the asset value (or record it from previewWithdraw/_amount) before _burn, and update totalUnbonding in the same step. Keep totalUnbonding in asset units, or convert consistently when subtracting it in totalAssets.

        Vercel Security Review

        Post-burn withdrawal valuation lets depositors claim other holders' assets

        contracts/voyage/tokenization/VToken.sol:53 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Withdrawal destroys shares before valuing the queued claim** - contracts/voyage/tokenization/VToken.sol:53-54

        ```solidity title="contracts/voyage/tokenization/VToken.sol:53-54"

        _burn(_owner, shares);

        pushWithdraw(_owner, shares);

        ```

        The new withdrawal flow reduces supply while leaving underlying assets unchanged.

        **2. The burned shares receive an inflated asset valuation** - contracts/voyage/tokenization/VToken.sol:71-73

        ```solidity title="contracts/voyage/tokenization/VToken.sol:71-73"

        unbondings[_user].shares += _shares;

        unbondings[_user].maxUnderlying += convertToAssets(_shares);

        totalUnbonding += _shares;

        ```

        For a junior pool with 100 assets and 100 shares, withdrawing 49 shares records approximately 96 assets, since conversion now divides by 51 shares.

        **3. Claim honors the inflated amount** - contracts/voyage/tokenization/VToken.sol:96-99

        ```solidity title="contracts/voyage/tokenization/VToken.sol:96-99"

        if (availableLiquidity > maxClaimable) {

        transferredAsset = maxClaimable;

        transferredShares = unbondings[msg.sender].shares;

        resetUnbondingPosition(msg.sender);

        ```

        Line 107 transfers that amount to the caller. A depositor can withdraw and immediately claim nearly twice their stake at the expense of remaining holders.

        Exploit scenario

        Not specified.

        Recommendation

        Compute the queued underlying entitlement before burning, using the original requested asset amount and pre-withdrawal exchange rate. Track pending liabilities in consistent asset units and subtract those liabilities from totalAssets. Claim must never pay more than the correctly valued entitlement.

      • Junior depositor funds mistakenly sent to senior depositors voyage-5 · 5 writeups Critical

        V12

        Covered liquidations still consume junior liquidity

        contracts/voyage/facets/LoanFacet.sol:409 Predicted severity: High

        Root cause

        The covered-debt branch in liquidate fails to clear param.remaningDebt. The junior backstop treats an already-funded installment as an outstanding shortfall.

        Impact

        Liquidation needlessly consumes junior liquidity and transfers it to the senior tranche even for fully covered installments. Repeating qualifying liquidations can exhaust junior backing and reduce the value or availability of junior depositors' claims.

        Description

        liquidate initializes param.remaningDebt to the installment principal before comparing the collateral proceeds against that debt. When discounted collateral proceeds cover the installment, the else branch refunds their excess to the vault but never sets param.remaningDebt to zero. The subsequent junior-tranche branch therefore still transfers up to an entire installment of junior assets into the diamond and adds it to receivedAmount. Both the collateral-funded installment and this unnecessary junior contribution are sent to the senior deposit token. This occurs even when collateral proceeds exactly equal the installment and no actual shortfall exists.

        Pashov (Codex GPT-6 Sol high)

        Liquidation charges junior tranche after NFT sale already covers debt

        audit/contracts/voyage/facets/LoanFacet.sol:454 Predicted severity: High

        Root cause

        The full-coverage branch at lines 456-461 omits setting param.remaningDebt to zero before the junior-tranche shortfall branch.

        Impact

        Junior depositors lose principal to the senior tranche even though the liquidation sale fully covered the loan.

        Description

        When discounted NFT proceeds exceed principal, liquidate refunds the excess but leaves remainingDebt at its initial full-debt value, then charges the junior tranche for that same debt.

        Exploit scenario

        For an 80-unit debt and 90-unit discounted sale, the code refunds 10 units but retains remaningDebt=80, then transfers up to 80 more units from junior reserves.

        Recommendation

        Set remaningDebt to zero when sale proceeds cover totalDebt and derive junior write-down only from the actual unpaid principal.

        Devin Security (Deep)

        Liquidation recovers only one installment, refunds the rest of the collateral value to the defaulting borrower and always charges the junior tranche

        contracts/voyage/facets/LoanFacet.sol:407 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A borrower who deliberately defaults and liquidates their own loan keeps the NFT for roughly two installments, while lenders in the senior and junior tranches absorb the rest of the principal as a loss.

        ##### What's wrong

        This is a loan accounting error in LoanFacet.liquidate. It treats the debt to recover as loan.pmt.principal (one installment) instead of the loan's outstanding principal. LibLoan.releaseLien deletes the whole loan and hands every collateral NFT to the liquidator, any excess the liquidator paid over that single installment is refunded to the borrower's vault, remaningDebt is never zeroed in the refund branch so the junior tranche is debited one installment anyway, and because the loan was already deleted the later LibLoan.repay subtracts zero from borrowState.totalDebt, so the written-off principal stays on the books.

        ##### Who can do it

        Mallory has a Voyage vault (vaults are created for users by an authorised protocol account, so she only needs to be onboarded like any customer). She calls buyNow for an NFT priced near the floor F with nper installments, paying one installment of principal and interest. She skips the next payment and waits out the grace period. From a second wallet she calls liquidate on her own loan, paying F - discount, and receives the NFT. Her vault receives F - discount - pmt.principal in WETH, which she withdraws with VaultFacet.transferReserve.

        Conditions:

        - Mallory has a vault and a marketplace adapter that completes the purchase. In this snapshot Vault.execute forwards no ETH, so real Seaport/LooksRare orders cannot settle; the registered marketplace on the testnets is MockMarketPlace. The theft requires the purchase path to deliver the NFT, which is the intended production design.

        - nper is at least 3 (the testnet config is term 90 / epoch 30, so nper = 3).

        ##### What they get

        Mallory ends up owning the NFT worth F after spending about 2F/nper plus fees; the senior tranche, which lent F - F/nper, gets back only one installment from the liquidator plus one installment taken from the junior tranche. Every lender in both tranches loses, and the senior token's totalDebt still counts the dead loan, so later depositors and withdrawers price shares against money that no longer exists. She can repeat this for every loan she can open.

        ##### How it works

        1. liquidate sets param.totalDebt = param.principal, one installment, and remaningDebt = totalDebt (contracts/voyage/facets/LoanFacet.sol:407-416).

        2. LibLoan.releaseLien deletes the loan and returns all collateral; the liquidator pays discountedFloorPrice * n and receives every NFT (LoanFacet.sol:421-445; contracts/voyage/libraries/LibLoan.sol:105-125).

        3. Because the payment exceeds one installment, the else branch transfers discountedFloorPriceInTotal - totalDebt to the borrower's vault and leaves remaningDebt unchanged (LoanFacet.sol:454-461).

        4. Since remaningDebt > 0, one installment is pulled from the junior token with transferUnderlyingTo (LoanFacet.sol:464-486).

        5. LibLoan.repay runs on the already-deleted loan, so borrowState.totalDebt and debtData.totalPrincipal are reduced by zero and the senior tranche's outstanding principal is never written down (LoanFacet.sol:489-494; LibLoan.sol:228-292).

        6. The borrower withdraws the WETH refund from the vault via transferReserve (contracts/voyage/facets/VaultFacet.sol:97-111).

        Exploit scenario

        Not specified.

        Recommendation

        Compute the amount to recover as the loan's remaining principal and interest (loan.principal - loan.totalPrincipalPaid plus unpaid interest), only refund the borrower what exceeds that full amount, set remaningDebt to zero when the liquidator covers the debt, and update borrowState/debtData with the written-off principal before deleting the loan. To verify, add a test where a borrower with nper = 3 defaults and self-liquidates, and assert the senior tranche's totalAssets and principalBalance return to their pre-loan values and the junior tranche balance is unchanged.

        Claude Security (Sonnet 5.5)

        liquidate() never clears remaningDebt when proceeds already cover the debt, so the junior tranche is charged a second time on every liquidation

        contracts/voyage/facets/LoanFacet.sol:464 Predicted severity: Medium

        Root cause

        Vulnerable symbol: liquidate

        Preconditions: An overdue loan whose discounted collateral value exceeds the single-instalment debt; Junior tranche holds liquidity

        Offending code:

        if (param.remaningDebt > 0) {

        Impact

        Every fully covered liquidation transfers an extra pmt.principal from junior depositors to the senior tranche; junior LPs lose funds even though no loss occurred.

        Description

        remaningDebt is initialised to totalDebt and is only reduced in the 'debt greater than proceeds' branch; in the 'proceeds cover debt' branch it stays at totalDebt, so the later 'if (remaningDebt > 0)' block still pulls that amount from the junior deposit token.

        Exploit scenario

        Floor 100, discounted 95, totalDebt 3.33. Liquidator pays 95, vault is refunded 91.67 and receivedAmount = 3.33. Because remaningDebt is still 3.33, the junior tranche also sends 3.33 to the diamond, and 6.67 reaches the senior token. A senior LP who is also a borrower or liquidator can trigger it on any overdue loan to move junior funds to the senior tranche. Static reasoning only.

        Recommendation

        Set param.remaningDebt = 0 in the branch where proceeds cover the debt, and compute remaining debt from the real total debt.

        Vercel Security Review

        Fully covered liquidations still debit the junior insurance tranche

        contracts/voyage/facets/LoanFacet.sol:457 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Liquidation initializes the shortfall to the entire debt** - contracts/voyage/facets/LoanFacet.sol:415-416

        ```solidity title="contracts/voyage/facets/LoanFacet.sol:415-416"

        param.totalDebt = param.principal;

        param.remaningDebt = param.totalDebt;

        ```

        **2. Sufficient collateral proceeds do not clear that shortfall** - contracts/voyage/facets/LoanFacet.sol:457-460

        ```solidity title="contracts/voyage/facets/LoanFacet.sol:457-460"

        uint256 refundAmount = discountedFloorPriceInTotal -

        param.totalDebt;

        IERC20(param.currency).transfer(param.vault, refundAmount);

        param.receivedAmount -= refundAmount;

        ```

        When proceeds cover the debt, this branch refunds excess but leaves remaningDebt positive.

        **3. Junior depositors pay the already-covered debt again** - contracts/voyage/facets/LoanFacet.sol:469-472

        ```solidity title="contracts/voyage/facets/LoanFacet.sol:469-472"

        if (param.totalAssetFromJuniorTranche >= param.remaningDebt) {

        IVToken(reserveData.juniorDepositTokenAddress)

        .transferUnderlyingTo(address(this), param.remaningDebt);

        param.juniorTrancheAmount = param.remaningDebt;

        ```

        Any liquidation of an eligible default can unnecessarily consume junior funds. Borrowers aligned with senior depositors can deliberately trigger covered defaults to shift junior backing into the senior tranche.

        Exploit scenario

        Not specified.

        Recommendation

        Set remaining debt to zero when collateral proceeds cover it; debit junior funds only for a genuine uncovered balance.

      • Inconsistent usage of totalUnbonding leads to lost or under- utilized lender assets voyage-6 · 9 writeups Critical

        V12

        Pending shares are deducted as underlying assets

        contracts/shared/tokenization/ERC4626.sol:128 Predicted severity: High

        Root cause

        The child totalAssets() implementations subtract share-denominated totalUnbonding from asset-denominated balances. ERC4626 then treats that mixed-unit result as the backing for mint, deposit, and immediate redeem pricing.

        Impact

        Remaining shareholders can redeem against understated withdrawal liabilities, leaving queued claimants without sufficient backing. Below a one-to-one exchange rate, subtracting share counts can instead underflow or zero the asset balance used by deposit and withdrawal pricing, blocking these operations.

        Description

        The conversion functions assume totalAssets() is an asset-denominated net balance, but both deployed tranche implementations subtract totalUnbonding, which VToken records in shares. Once assets per share differ from one, pending withdrawals are therefore reserved at the wrong amount. The inherited redeem uses this incorrect net balance to price immediate asset transfers for remaining holders. With an exchange rate above one, it can pay out underlying already needed to satisfy queued withdrawal caps. This defect remains even if the separate burn-before-pricing problem in VToken.withdraw is corrected.

        Codex Security (GPT-6 Sol)

        Junior liquidation can strand funded withdrawal claims

        contracts/voyage/tokenization/VToken.sol:70 Predicted severity: Medium

        Root cause

        totalUnbonding accumulates shares, but JuniorDepositToken.totalAssets subtracts that integer from token assets. Liquidation may transfer that reported totalAssets, leaving only pending-claim assets. The partial claim branch calls convertToShares, which divides by zero when totalAssets is zero.

        Impact

        A pending withdrawal remains locked until unrelated new assets arrive, despite the token still holding funds. Likelihood is medium under the stated prerequisites.

        Description

        The junior token subtracts pending share count from asset balance as if it were an asset amount. A liquidation can consume reported available assets and leave a funded claim that cannot be converted because totalAssets becomes zero.

        Exploit scenario

        contracts/voyage/tokenization/VToken.sol:70 to contracts/voyage/tokenization/VToken.sol:91

        Recommendation

        Track pending withdrawal liabilities in asset units and settle claims without converting them through current live-share price.

        Pashov (Claude Opus 5.5 high)

        VToken.totalUnbonding is denominated in shares but subtracted from asset balances

        contracts/voyage/tokenization/JuniorDepositToken.sol:7 Predicted severity: High

        Root cause

        Mixing share and asset units in the same quantity.

        Impact

        Incorrect share pricing; depositors can withdraw more/less than entitled; borrowers can borrow funds reserved for withdrawals; reverts (underflow) once totalUnbonding (shares) exceeds balance.

        Description

        totalUnbonding is incremented with share amounts (totalUnbonding += _shares) yet it is subtracted from token balances in Junior/SeniorDepositToken.totalAssets, in buyNow's available-liquidity check and in utilizationRate. Once share price differs from 1:1 (interest accrual, losses), totalAssets, share prices, available liquidity and the interest rate all become wrong. The withdrawn assets of unbonding users remain partly counted in totalAssets, so remaining holders' shares are mispriced and can be redeemed for assets reserved for unbonding users (or vice-versa).

        Exploit scenario

        Junior tranche earns interest so 1 share = 2 assets. A user unbonds 100 shares (200 assets recorded as maxUnderlying) but totalAssets only deducts 100, so 100 assets are double counted: remaining holders' share price is inflated and they can withdraw part of the unbonding user's claim, leaving the latter unpaid.

        Recommendation

        Track unbonding in assets (sum of maxUnderlying) and subtract that from balances.

        Pashov (Codex GPT-6 Sol high)

        Pending withdrawal shares are subtracted as asset units

        audit/contracts/voyage/tokenization/JuniorDepositToken.sol:7 Predicted severity: High

        Root cause

        The same storage counter is used as shares by VToken and as assets by accounting consumers.

        Impact

        Share prices and available lending cash diverge from actual pending asset obligations; claims can become underfunded.

        Description

        The tranche token totalAssets calculations and loan liquidity check subtract totalUnbonding as if it counted assets, although VToken updates it with share quantities.

        Exploit scenario

        When share price exceeds one asset, 50 queued shares can represent more than 50 assets but the reserve withholds only 50 assets.

        Recommendation

        Store pending asset liabilities separately or convert queued shares to assets at the appropriate snapshot price before each asset calculation.

        Devin Security

        Senior tranche value ignores outstanding loans, so late depositors take earlier lenders' repayments

        contracts/voyage/tokenization/SeniorDepositToken.sol:8 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can deposit into the senior tranche while loans are outstanding at a heavily discounted share price, then take a large share of the repayments that belong to earlier lenders.

        ##### What's wrong

        This is a share price miscalculation. SeniorDepositToken.totalAssets adds principalBalance(address(asset)), but principalBalance expects an NFT collection address, not the currency. The lookup reads an unused storage slot and returns 0. Lent-out principal therefore vanishes from the tranche value. In addition, totalUnbonding counts shares but is subtracted as if it were assets.

        ##### Who can do it

        Alice deposits 100 WETH into the senior tranche. Bob, a borrower, takes loans that move 90 WETH out to buy NFTs. The tranche now reports 10 WETH of assets for 100 shares. Mallory, any Ethereum address, deposits 10 WETH and receives 100 shares. When Bob repays 90 WETH, Mallory withdraws half of the pool.

        - At least one loan is outstanding in the reserve. This is normal operation.

        - Mallory holds some of the reserve currency. No account or role is needed.

        ##### What they get

        In the example, Mallory turns 10 WETH into about 55 WETH. Alice loses about 45 WETH of her deposit. Lenders who withdraw while loans are outstanding are also underpaid, and their loss stays with the remaining shareholders. This affects every senior tranche.

        ##### How it works

        1. SeniorDepositToken.totalAssets calls LoanFacet.principalBalance(address(asset)) (SeniorDepositToken.sol:10-12).

        2. principalBalance uses its argument as a collection and reads _reserveData[currency].currency and _borrowState[currency][...]. These are empty, so it returns 0 (LoanFacet.sol:539-551).

        3. When buyNow moves principal out with transferUnderlyingTo (LoanFacet.sol:250), the balance drops and the share price drops with it.

        4. The public ERC4626 deposit mints shares at this low price (shared/tokenization/ERC4626.sol:35-46, 117-126).

        5. Repayments go straight to the senior token (LoanFacet.sol:341-345), so the share price recovers and Mallory's shares gain value.

        Exploit scenario

        Not specified.

        Recommendation

        Store the collection address in the senior token at initialization and pass it to principalBalance. Alternatively, have the diamond expose the outstanding principal by currency. Subtract convertToAssets(totalUnbonding), or keep unbonding in asset units, instead of a raw share count. To check the fix, write a test that opens a loan, deposits as a second user, repays the loan, and confirms the second user can only withdraw about what they deposited.

        Devin Security (Deep)

        Senior deposit token prices shares without the principal on loan, letting anyone buy in cheap and exit after repayments

        deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json:197 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can deposit into the senior pool right after a loan is funded, when the share price is artificially low, and withdraw after repayments arrive, taking money that belongs to earlier depositors.

        ##### What's wrong

        This is a wrong-key lookup that breaks share pricing. SeniorDepositToken.totalAssets calls LoanFacet.principalBalance(address(asset)), passing the WETH address where a collection address is expected, so the outstanding principal always reads 0 and the token's assets fall by the full loan amount whenever money is lent out. The source is identical to the deployed artifact 12dd858c....

        ##### Who can do it

        Alice deposits 100 WETH and holds 100 shares. Bob borrows 66 WETH via buyNow, so totalAssets falls to 34. Mallory, with no account, deposits 34 WETH and receives 100 shares.

        - At least one loan is outstanding in the pool.

        - Mallory can call LiquidityFacet.deposit (no access control) and exit via redeem or withdraw plus claim (no cooldown enforced).

        ##### What they get

        When Bob repays 33 WETH, Mallory's shares are worth 50 WETH; she redeems and keeps 16 WETH of Alice's money. Repeating this around loans and repayments skims repaid principal from every passive depositor. Depositors who exit while loans are outstanding are underpaid, and if totalUnbonding exceeds the token balance totalAssets underflows and the token stops working.

        ##### How it works

        1. buyNow moves outstandingPrincipal WETH out of the senior token (contracts/voyage/facets/LoanFacet.sol:250-253).

        2. SeniorDepositToken.totalAssets adds principalBalance(address(asset)) (contracts/voyage/tokenization/SeniorDepositToken.sol:8-14).

        3. principalBalance resolves the reserve by collection; the WETH key is empty and returns 0 (contracts/voyage/facets/LoanFacet.sol:539-552).

        4. ERC4626.convertToShares mints against the understated totalAssets (contracts/shared/tokenization/ERC4626.sol:117-126).

        5. Repayments return principal to the token (contracts/voyage/facets/LoanFacet.sol:341-345) and redeem pays out instantly (contracts/shared/tokenization/ERC4626.sol:90-109).

        Exploit scenario

        Not specified.

        Recommendation

        Store the collection in the deposit token and call principalBalance(collection), express totalUnbonding in assets, and fix the phantom-debt accounting first. Verify: seniorToken.totalAssets() and convertToShares(1e18) must be unchanged immediately after buyNow.

        Claude Security (Sonnet 5.5)

        totalUnbonding (shares) is subtracted from asset balances, mispricing shares and allowing underflow reverts

        contracts/voyage/tokenization/JuniorDepositToken.sol:8 Predicted severity: Medium

        Root cause

        Vulnerable symbol: totalAssets

        Preconditions: Share price different from 1 (accrued interest or a junior write-down); At least one pending withdrawal

        Offending code:

        return asset.balanceOf(address(this)) - totalUnbonding;

        Impact

        When the share price is above 1, a withdrawal reserves fewer assets than it owes. Remaining holders' shares are overvalued, and they can call the inherited ERC4626.redeem (no queue) to take funds reserved for unbonding users. When the share price is below 1 (after a junior write-down), totalUnbonding can exceed the balance and totalAssets reverts with an underflow panic. That bricks deposit, mint, redeem and the conversion functions. It also bricks LoanFacet.liquidate, which calls juniorToken.totalAssets(), and buyNow's rate calculation, which does the same subtraction.

        Description

        totalUnbonding is accumulated in share units (pushWithdraw adds _shares). totalAssets subtracts it from the underlying token balance, which is in asset units. The same mismatch exists in SeniorDepositToken.totalAssets (line 13), LibLiquidity.utilizationRate and DefaultReserveInterestRateStrategy.calculateBorrowRate. The units only agree when the share price is exactly 1.

        Exploit scenario

        Share price 2: supply 100, balance 200, holders V and A each have 50 shares. A queues withdraw(100 assets), which burns 50 shares and adds 50 to totalUnbonding. totalAssets is now 200-50=150 instead of 100, so V redeems 50 shares for 150 (entitled to 100). Only 50 remains for A's 100 claim. For the DoS case, after a junior write-down leaves supply 100 and balance 50 (share price 0.5), the sole LP queues withdraw(50) and totalUnbonding becomes 100. totalAssets() then reverts, liquidations of bad debt revert, and no new junior deposits are possible.

        Recommendation

        Track the unbonding reserve in asset units (the sum of maxUnderlying) and subtract that from the balance. Guard the subtraction against underflow. Update the strategy and utilization code to use the asset-denominated figure.

        Claude Security (Opus 5.5)

        Senior tranche totalAssets underflows once loans are out, so the senior tranche's deposits and withdrawals revert

        contracts/voyage/tokenization/SeniorDepositToken.sol:13 Predicted severity: Medium

        Root cause

        Vulnerable symbol: SeniorDepositToken.totalAssets

        Preconditions: Senior liquidity has been lent out through buyNow, the normal operating state; A senior LP withdraws more shares than balance - totalUnbonding (easy because the share price is understated)

        Offending code:

        return underlyingBalance + outstandingPrincipal - totalUnbonding;

        Impact

        All senior LP funds are frozen: deposits, withdrawals and partial claims revert. No new loans can be made either, because buyNow sees no available liquidity. The freeze can last as long as the outstanding loans, and any LP can trigger it, deliberately or by accident, in normal operation.

        Description

        Line 13 subtracts totalUnbonding from an asset amount, but totalUnbonding counts shares (VToken.pushWithdraw:73 adds burned shares). The outstanding principal term is always 0 because the token's address is passed where a collection key is expected (SeniorDepositToken:10-11 -> LoanFacet.principalBalance:539-551). Once loans have taken out the senior balance, any LP withdrawal pushes more shares than assets into totalUnbonding. Checked arithmetic then underflows and reverts every call to totalAssets().

        Exploit scenario

        Start with 100 WETH deposited 1:1 in the senior tranche. A borrower calls buyNow, which moves 90 WETH out (LoanFacet:250), leaving balance 10. principalBalance returns 0, so totalAssets is 10 for 100 shares, a price of 0.1. An LP with 50 shares calls withdraw(5) directly on the vToken or through LiquidityFacet.withdraw. previewWithdraw rounds up to 50 shares, which are burned and added to totalUnbonding (now 50). totalAssets() becomes 10 + 0 - 50 and reverts. From then on, deposit/mint (previewDeposit/previewMint), withdraw (previewWithdraw), maxWithdraw (also called by LiquidityFacet.withdraw:159), the partial-claim branch of claim() (convertToShares at VToken:102), and DataProviderFacet.getPoolData all revert. This lasts until repayments push the balance above totalUnbonding. Because totalUnbonding is in inflated share units, that can take most of the outstanding loan book. Separately, a borrower who draws exactly balance - totalUnbonding leaves totalAssets == 0 with supply > 0, so mulDivDown divides by zero and deposits revert.

        Recommendation

        Keep totalUnbonding in asset units, or convert it with convertToAssets before subtracting. Pass the collection, not the currency, to principalBalance so outstanding principal is counted. Bound the subtraction (return 0 when the liabilities exceed the balance) so it cannot revert, and guard the share math against totalAssets()==0.

        Vercel Security Review

        Post-burn withdrawal valuation lets depositors claim other holders' assets

        contracts/voyage/tokenization/VToken.sol:53 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Withdrawal destroys shares before valuing the queued claim** - contracts/voyage/tokenization/VToken.sol:53-54

        ```solidity title="contracts/voyage/tokenization/VToken.sol:53-54"

        _burn(_owner, shares);

        pushWithdraw(_owner, shares);

        ```

        The new withdrawal flow reduces supply while leaving underlying assets unchanged.

        **2. The burned shares receive an inflated asset valuation** - contracts/voyage/tokenization/VToken.sol:71-73

        ```solidity title="contracts/voyage/tokenization/VToken.sol:71-73"

        unbondings[_user].shares += _shares;

        unbondings[_user].maxUnderlying += convertToAssets(_shares);

        totalUnbonding += _shares;

        ```

        For a junior pool with 100 assets and 100 shares, withdrawing 49 shares records approximately 96 assets, since conversion now divides by 51 shares.

        **3. Claim honors the inflated amount** - contracts/voyage/tokenization/VToken.sol:96-99

        ```solidity title="contracts/voyage/tokenization/VToken.sol:96-99"

        if (availableLiquidity > maxClaimable) {

        transferredAsset = maxClaimable;

        transferredShares = unbondings[msg.sender].shares;

        resetUnbondingPosition(msg.sender);

        ```

        Line 107 transfers that amount to the caller. A depositor can withdraw and immediately claim nearly twice their stake at the expense of remaining holders.

        Exploit scenario

        Not specified.

        Recommendation

        Compute the queued underlying entitlement before burning, using the original requested asset amount and pre-withdrawal exchange rate. Track pending liabilities in consistent asset units and subtract those liabilities from totalAssets. Claim must never pay more than the correctly valued entitlement.

      • Share burn timing in Vtoken can lead to complete loss of funds voyage-7 · 9 writeups Critical

        V12

        Post-burn pricing inflates queued withdrawal payouts

        contracts/shared/tokenization/ERC4626.sol:128 Predicted severity: High

        Root cause

        VToken.withdraw mutates supply before calling the live ERC4626.convertToAssets pricing function. The withdrawal entitlement is not computed from the same pre-burn snapshot used to determine shares to burn.

        Impact

        A withdrawing shareholder can receive more underlying than their shares represented before the withdrawal, taking value from other shareholders. The sequence is reachable with a standard ERC20, a one-to-one initial exchange rate, and no donation or administrative action.

        Description

        convertToAssets values a share amount against the live totalSupply() rather than a saved exchange-rate snapshot. VToken.withdraw burns the requested shares before pushWithdraw calls that conversion to set the pending asset cap. During that conversion, underlying assets have not been transferred or reserved, but the supply denominator has already decreased. Partial withdrawals therefore obtain a cap larger than the pre-withdrawal value of their burned shares. claim uses this inflated cap directly whenever sufficient underlying remains.

        Codex Security (GPT-6 Sol)

        A withdrawing depositor can claim other depositors' assets

        contracts/voyage/tokenization/VToken.sol:41 Predicted severity: Critical

        Root cause

        The withdrawal calculates shares before burning, but pushWithdraw calls convertToAssets after _burn. That conversion divides by the smaller remaining supply. claim transfers the recorded maxUnderlying if liquidity is available.

        Impact

        For 100 assets and 100 shares, withdrawing 49 shares can record a 96-asset claim, leaving four assets for other holders after claim. Likelihood is high under the stated prerequisites.

        Description

        VToken.withdraw burns shares before computing the pending asset entitlement. The reduced supply inflates maxUnderlying, and claim pays that inflated amount from the shared reserve.

        Exploit scenario

        contracts/voyage/tokenization/VToken.sol:41 to contracts/shared/tokenization/ERC4626.sol:128

        Recommendation

        Record the requested asset entitlement before burning shares and settle at most the remaining recorded asset amount.

        Pashov (Claude Opus 5.5 high)

        VToken.withdraw computes unbonding maxUnderlying after burning shares, letting withdrawers claim far more than their share

        contracts/voyage/tokenization/VToken.sol:41 Predicted severity: Critical

        Root cause

        Order of operations: _burn before convertToAssets in pushWithdraw (and totalUnbonding updated after the conversion).

        Impact

        A depositor can claim assets belonging to other depositors; with a large share, a single withdrawal can drain the whole tranche.

        Description

        VToken.withdraw burns the owner's shares first and only then calls pushWithdraw, which records maxUnderlying += convertToAssets(_shares). At that moment totalSupply has already decreased while totalAssets() has not (totalUnbonding is only incremented afterwards), so the share price used is inflated. claim() later pays out maxUnderlying (capped by the contract balance).

        Exploit scenario

        Pool has 200 assets/200 shares split 100/100 between Alice and attacker. Attacker withdraws 100 assets: shares=100 are burned (supply 100, totalAssets 200) then convertToAssets(100)=200 is recorded as maxUnderlying. Attacker calls claim(): availableLiquidity=200 is not > 200, so else-branch transfers all 200 tokens. Alice's deposit is gone.

        Recommendation

        Compute the asset amount before burning (use the _amount/previewRedeem value computed before state changes), and account totalUnbonding in assets consistently.

        Pashov (Codex GPT-6 Sol high)

        Withdrawal claim is valued after share burn and can drain other depositors

        audit/contracts/voyage/tokenization/VToken.sol:51 Predicted severity: Critical

        Root cause

        withdraw burns shares at line 53 and pushWithdraw calls convertToAssets on those same shares at line 72 using the post-burn supply.

        Impact

        A withdrawing depositor can claim more underlying than their shares represented before withdrawal, causing direct loss to other depositors and possible complete reserve depletion.

        Description

        VToken burns withdrawal shares before it computes the user's queued asset entitlement. The smaller total supply raises convertToAssets(shares), so the queued claim can exceed the requested withdrawal and consume assets belonging to remaining holders.

        Exploit scenario

        In a pool with 200 assets and 200 shares, an attacker owning 100 shares withdraws 99 assets. The burn leaves 101 shares, so pushWithdraw records floor(99*200/101)=196 assets. claim immediately pays 196 because cash 200 exceeds that cap, leaving only 4 assets for other holders.

        Recommendation

        Calculate and record the asset entitlement before burning shares, or pass the requested asset amount into pushWithdraw, and keep pending claims in asset units consistently.

        Devin Security

        Withdraw records an inflated claimable amount, so any depositor can drain the tranche

        contracts/voyage/tokenization/VToken.sol:41 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can deposit into a senior or junior tranche, withdraw, and claim almost all of the other depositors' money in the same block.

        ##### What's wrong

        This is a share accounting bug. VToken.withdraw burns the caller's shares first and only then calls pushWithdraw, which prices those already-burned shares with convertToAssets. Burning shrinks the total supply but leaves totalAssets unchanged, so the recorded maxUnderlying is far larger than what the shares were worth. claim then pays out maxUnderlying directly and has no cooldown check.

        ##### Who can do it

        Alice, a lender, has deposited 100 WETH into a tranche. Mallory, any Ethereum address, deposits 99 WETH and gets 99 shares. She calls withdraw(99, ...) on the tranche token and then claim() in the same transaction.

        - The tranche token is deployed and holds other depositors' funds.

        - Mallory holds enough of the underlying token to make a deposit somewhat smaller than the existing pool.

        - No account, role or vault is needed. deposit, withdraw and claim are public.

        ##### What they get

        In the example, withdraw records maxUnderlying as 99 × 199 / 100 = 197.01 WETH. claim sends Mallory 197.01 WETH, so she takes about 98 WETH of Alice's 100 WETH. She can repeat this to empty both the senior and junior tranche of every reserve. Lenders lose their deposits.

        ##### How it works

        1. Mallory deposits into the tranche through the public ERC4626 deposit (shared/tokenization/ERC4626.sol:35) and gets shares at the normal price.

        2. VToken.withdraw computes shares and then calls _burn before pushWithdraw (VToken.sol:46-54).

        3. pushWithdraw sets maxUnderlying += convertToAssets(_shares) (VToken.sol:72). The supply has already dropped, and totalUnbonding has not grown yet, so the price per share is inflated.

        4. claim checks only that the contract balance exceeds maxUnderlying and transfers that amount. It never checks cooldown or the share value (VToken.sol:91-107).

        5. The balance that pays Mallory belongs to the other depositors.

        Exploit scenario

        Not specified.

        Recommendation

        Compute the asset value of the shares before burning them, for example uint256 assets = convertToAssets(shares) before _burn, or simply record _amount. Add totalUnbonding to the accounting before or atomically with the burn. In claim, cap the payout at convertToAssets(unbondings[user].shares) (as maximumClaimable already does) and enforce cooldown. Fix the == typo in reduceUnbondingPosition. To check the fix, write a test with two depositors where one withdraws and claims. That depositor should receive no more than they deposited.

        Devin Security (Deep)

        VToken.withdraw values the unbonding position after burning shares, letting a depositor claim far more than their share

        contracts/voyage/tokenization/VToken.sol:41 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Any depositor into a senior or junior tranche can withdraw almost the whole tranche in a single transaction, taking every other lender's money.

        ##### What's wrong

        This is a share-accounting error in an ERC4626-style vault. VToken.withdraw burns the caller's shares first and only then converts those shares to an asset amount, so the conversion uses the reduced total supply against the unchanged asset balance. The resulting maxUnderlying is inflated by totalSupply / (totalSupply - shares), and claim pays it out immediately because the declared cooldown is never checked.

        ##### Who can do it

        Alice and other lenders at Acme Capital hold 51 WETH worth of senior tranche shares. Mallory, anyone with a wallet, deposits 49 WETH into the same tranche directly on the vToken contract, then calls withdraw(49 WETH) and claim() in the same block.

        - The tranche has at least one other depositor.

        - Mallory holds less than half of the tranche shares (she can repeat with smaller fractions if needed).

        - No cooldown exists in claim, so no waiting is required.

        ##### What they get

        In the example Mallory receives about 96 of the 100 WETH in the tranche for her 49 WETH deposit, leaving Alice and the other lenders with about 4 WETH. She can repeat the deposit and withdraw cycle to drain whatever is left. This applies to both tranches of every reserve.

        ##### How it works

        1. Mallory calls VToken.withdraw(assets, mallory, mallory) (contracts/voyage/tokenization/VToken.sol:41-57); previewWithdraw computes the honest share count s.

        2. _burn(_owner, shares) at line 53 lowers totalSupply to S - s while asset.balanceOf and totalUnbonding are unchanged.

        3. pushWithdraw (lines 70-74) sets maxUnderlying += convertToAssets(s), which is s * totalAssets / (S - s) (ERC4626.sol:128-137), so with s = 49 and S = 100 she is credited 96 percent of the pool.

        4. claim() (lines 91-108) has no time check; because maxUnderlying is below the balance it transfers the full inflated amount to Mallory.

        The same code is embedded in the deployment artifact deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json.

        Exploit scenario

        Not specified.

        Recommendation

        Compute the asset amount before burning: in withdraw, record assets = previewRedeem(shares) (or simply use the _amount argument) before _burn, and pass that value to pushWithdraw instead of recomputing with convertToAssets. Track totalUnbonding in asset units, or convert consistently, so totalAssets subtracts a like-for-like value. Enforce the cooldown in claim. Also override redeem so it goes through the same unbonding path. Verify with a test where two users deposit 51 and 49, the second withdraws 49 and claims, and assert the payout is at most 49.

        Claude Security (Sonnet 5.5)

        Unbonding position priced after the share burn, so claim() pays out far more than the shares are worth (drains a whole tranche)

        contracts/voyage/tokenization/VToken.sol:72 Predicted severity: Critical

        Root cause

        Vulnerable symbol: pushWithdraw

        Preconditions: Tranche token holds liquidity that has not been lent out; Attacker can deposit an amount X below the existing liquidity H (flash loan is enough)

        Offending code:

        unbondings[_user].maxUnderlying += convertToAssets(_shares);

        Impact

        Any unprivileged address can steal close to the entire liquidity of the junior or senior deposit token in one transaction (flash-loanable), leaving the other depositors with near-zero value.

        Description

        VToken.withdraw burns the caller's shares and only then calls pushWithdraw, which records maxUnderlying = convertToAssets(_shares) against the already-reduced supply; claim() then pays that inflated maxUnderlying out of the pool, and any address can deposit into and withdraw from the tranche token directly.

        Exploit scenario

        Junior (or senior) tranche holds H = 100 WETH for 100 shares. Attacker (own funds or a flash loan) calls tranche.deposit(99 WETH, attacker) and gets 99 shares (balance 199, supply 199). Attacker calls tranche.withdraw(99 WETH, attacker, attacker): previewWithdraw gives 99 shares, _burn drops supply to 100, then pushWithdraw records maxUnderlying = 99 * totalAssets(199) / supply(100) = 197.01 WETH. Attacker calls claim(): availableLiquidity (199) > maxClaimable (197.01), so 197.01 WETH is transferred. Net +98.01 WETH, taken from the honest depositor, who is left with about 1.99 WETH backing 100 shares. The attacker needs no privileges and never goes through the diamond. Any attacker deposit X < H works; the payout is roughly X*(X+H)/H. Static reasoning only; nothing was executed.

        Recommendation

        Compute the asset value of the shares before burning them and before the unbonding accounting changes (convertToAssets/previewRedeem at the pre-burn supply), or set maxUnderlying = the _amount argument already priced by previewWithdraw. Cap claims at min(maxUnderlying, current value). Add invariant tests on unbonding accounting.

        Claude Security (Opus 5.5)

        VToken withdraw values unbonding shares after burning them, so a withdrawer is credited with most or all of the pool

        contracts/voyage/tokenization/VToken.sol:72 Predicted severity: Critical

        Root cause

        Vulnerable symbol: pushWithdraw

        Preconditions: Pool has other depositors' funds

        Offending code:

        unbondings[_user].maxUnderlying += convertToAssets(_shares);

        Impact

        Any depositor can take almost the whole balance of either tranche, stealing the other LPs' funds.

        Description

        VToken.withdraw burns the owner's shares and only then calls pushWithdraw, which prices them with ERC4626.convertToAssets. At that point totalSupply has already dropped, but Junior/Senior totalAssets (balance - totalUnbonding) has not changed yet because totalUnbonding is updated afterwards. claim() then pays out the inflated maxUnderlying from the shared pool balance.

        Exploit scenario

        The junior (or senior) pool holds 100 WETH from Bob, backed by 100 shares. The attacker deposits 99 WETH and receives 99 shares (pool now 199 WETH / 199 shares). The attacker calls VToken.withdraw(99, attacker, attacker). The 99 shares are burned, leaving supply at 100, and convertToAssets(99) = 99*199/100 = 197. claim() sees a balance of 199 > 197 and sends 197 WETH to the attacker. Bob's 100 shares are now backed by about 2 WETH.

        Recommendation

        Compute the asset value (or record it from previewWithdraw/_amount) before _burn, and update totalUnbonding in the same step. Keep totalUnbonding in asset units, or convert consistently when subtracting it in totalAssets.

        Vercel Security Review

        Post-burn withdrawal valuation lets depositors claim other holders' assets

        contracts/voyage/tokenization/VToken.sol:53 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Withdrawal destroys shares before valuing the queued claim** - contracts/voyage/tokenization/VToken.sol:53-54

        ```solidity title="contracts/voyage/tokenization/VToken.sol:53-54"

        _burn(_owner, shares);

        pushWithdraw(_owner, shares);

        ```

        The new withdrawal flow reduces supply while leaving underlying assets unchanged.

        **2. The burned shares receive an inflated asset valuation** - contracts/voyage/tokenization/VToken.sol:71-73

        ```solidity title="contracts/voyage/tokenization/VToken.sol:71-73"

        unbondings[_user].shares += _shares;

        unbondings[_user].maxUnderlying += convertToAssets(_shares);

        totalUnbonding += _shares;

        ```

        For a junior pool with 100 assets and 100 shares, withdrawing 49 shares records approximately 96 assets, since conversion now divides by 51 shares.

        **3. Claim honors the inflated amount** - contracts/voyage/tokenization/VToken.sol:96-99

        ```solidity title="contracts/voyage/tokenization/VToken.sol:96-99"

        if (availableLiquidity > maxClaimable) {

        transferredAsset = maxClaimable;

        transferredShares = unbondings[msg.sender].shares;

        resetUnbondingPosition(msg.sender);

        ```

        Line 107 transfers that amount to the caller. A depositor can withdraw and immediately claim nearly twice their stake at the expense of remaining holders.

        Exploit scenario

        Not specified.

        Recommendation

        Compute the queued underlying entitlement before burning, using the original requested asset amount and pre-withdrawal exchange rate. Track pending liabilities in consistent asset units and subtract those liabilities from totalAssets. Claim must never pay more than the correctly valued entitlement.

      • Buyers make first interest payment twice voyage-8 · 3 writeups High

        V12

        First installment interest is charged twice

        contracts/voyage/facets/LoanFacet.sol:208 Predicted severity: High

        Root cause

        buyNow includes interest in its collected downpayment but also funds interest distribution with another borrower transfer instead of the already-collected funds. The excess remains in a shared diamond balance exposed to permissionless refunds.

        Impact

        A successful borrowing transaction charges the borrower an extra first-installment interest amount that is not credited against debt. Any external caller can collect the residual ETH from the diamond, creating conditional borrower fund loss whenever installment interest is nonzero.

        Description

        buyNow sets params.downpayment to the complete first installment, including both principal and interest. It collects that amount through msg.value and/or a currency transfer into the diamond, then unwraps the diamond's entire WETH balance and sends only the purchase principal to the vault. After recording the first repayment, it calls LibLoan.distributeInterest, which separately pulls the same installment interest from the borrower into the tranche tokens. For a WETH reserve with no preexisting diamond balance, the purchase funding therefore leaves exactly the first installment's interest as residual ETH while additionally charging that interest in WETH. The residual is not assigned to the borrower and can be taken through the public refundETH helper.

        Pashov (Claude Opus 5.5 high)

        buyNow charges the first instalment's interest twice and leaves the surplus ETH in the diamond

        contracts/voyage/facets/LoanFacet.sol:208 Predicted severity: Medium

        Root cause

        Interest is collected both as part of the down-payment and separately in distributeInterest.

        Impact

        Every borrower overpays one instalment of interest; the excess accumulates in the diamond where anyone can take it via refundETH/sweepToken, or it is used to subsidise other calls (see multicall msg.value reuse).

        Description

        The down-payment collected is params.pmt.pmt = pmt.principal + pmt.interest. The diamond then receives outstandingPrincipal from the senior tranche and forwards totalPrincipal = outstandingPrincipal + pmt.principal ETH to the vault, so pmt.interest remains in the diamond. Step 11 then calls distributeInterest, which pulls pmt.interest again from _msgSender() via transferFrom.

        Exploit scenario

        Borrower buys an NFT with pmt.interest = 0.5 ETH: sends downpayment incl. 0.5 ETH interest and additionally has 0.5 WETH transferred to tranches. Attacker then calls refundETH() and receives the 0.5 ETH.

        Recommendation

        Collect only the principal part as down-payment (or don't pull interest again), and never leave residual funds in the diamond.

        Devin Security (Deep)

        buyNow charges the first instalment's interest twice and leaves one copy on the diamond where anyone can take it

        deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json:245 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Every borrower overpays the first interest instalment, and the extra ETH sits on the Voyage diamond where anyone can sweep it with refundETH.

        ##### What's wrong

        This is an accounting mistake in the payment flow. The down payment pulled from the borrower is pmt.pmt (principal plus interest), the diamond unwraps all its WETH and forwards only totalPrincipal to the vault, leaving pmt.interest as ETH on the diamond, and distributeInterest then pulls pmt.interest from the borrower again. This artifact's buyNow matches the current contracts/ tree.

        ##### Who can do it

        Bob borrows 9 ETH over 3 instalments; buyNow takes 3.15 ETH down and another 0.15 ETH as interest, leaving 0.15 ETH on the diamond. Mallory calls refundETH() on the diamond right after.

        - Any buyNow has happened and the diamond has not been swept.

        - PaymentsFacet.refundETH/unwrapWETH9 are public.

        ##### What they get

        Mallory collects one instalment of interest from every loan, paid by borrowers; any WETH on the diamond at the time is also unwrapped and exposed.

        ##### How it works

        1. downpayment = pmt.pmt is pulled (contracts/voyage/facets/LoanFacet.sol:209, 227-237).

        2. unwrapWETH9 unwraps the whole WETH balance (contracts/voyage/facets/LoanFacet.sol:250-259, contracts/shared/facets/PaymentsFacet.sol:15-28).

        3. Only totalPrincipal ETH is sent to the vault (contracts/voyage/facets/LoanFacet.sol:261).

        4. distributeInterest pulls pmt.interest again (contracts/voyage/facets/LoanFacet.sol:285-289).

        5. Anyone calls refundETH() (contracts/shared/facets/PaymentsFacet.sol:48-52).

        Exploit scenario

        Not specified.

        Recommendation

        Pull only pmt.principal as the down payment (or drop the second interest pull), unwrap exactly outstandingPrincipal, and assert the diamond's ETH balance is unchanged at the end of buyNow. Verify: diamond ETH/WETH balances are zero after buyNow.

      • Missing stale price oracle check results in outsized NFT price risk voyage-9 · 4 writeups High

        V12

        Stale floor prices govern borrowing and collateral seizure

        contracts/voyage/facets/LoanFacet.sol:150 Predicted severity: High

        Root cause

        Oracle timestamps are fetched but never enforced at either borrowing or liquidation. The underlying oracle also permits indefinite reads of its last nonzero value.

        Impact

        An outdated high floor can admit financing above current collateral value and make liquidation recovery unrealistic. An outdated low floor can permit collateral seizure at an obsolete discount, causing conditional borrower loss and unnecessary junior-tranche consumption.

        Description

        buyNow and liquidate retrieve oracle timestamps alongside floor prices but validate only that the prices are nonzero. PriceOracle.getTwap returns the last stored update indefinitely and has no freshness enforcement of its own. Borrowing therefore accepts a historical floor as both a purchase-price ceiling and an input to the credit limit. Liquidation likewise uses an arbitrarily old floor to calculate the amount paid for seized collateral. A missed operator update does not make either entrypoint reject obsolete valuation data.

        Codex Security (GPT-6 Sol)

        Borrowing and liquidation can use expired floor prices

        contracts/voyage/infra/PriceOracle.sol:27 Predicted severity: Medium

        Root cause

        PriceOracle records block.timestamp on update and returns it with price. Both loan paths assign that timestamp but only test the price for zero, so an old value remains accepted indefinitely.

        Impact

        If floor prices move after the last update, a borrower may receive excessive credit or a liquidator may acquire collateral at an outdated discount. Likelihood is medium under the stated prerequisites.

        Description

        buyNow and liquidate read oracle timestamps but never enforce a maximum age, allowing transactions against an old nonzero floor price.

        Exploit scenario

        contracts/voyage/infra/PriceOracle.sol:27 to contracts/voyage/facets/LoanFacet.sol:396

        Recommendation

        Enforce a configured maximum oracle age in borrowing and liquidation, with a safe pause or alternate path when the price expires.

        Pashov (Claude Opus 5.5 high)

        Oracle TWAP timestamp is ignored: stale floor prices are used for borrowing and liquidation

        contracts/voyage/facets/LoanFacet.sol:153 Predicted severity: Medium

        Root cause

        Missing staleness check on an operator-pushed oracle.

        Impact

        If the operator stops updating (outage, key loss) or the market moves sharply, borrowers can borrow against outdated, inflated floor prices (fv >= price check passes) and liquidators settle at outdated prices, causing bad debt or unfair liquidations.

        Description

        buyNow and liquidate read (price, timestamp) from the PriceOracle but only check price != 0; the update time is never validated.

        Exploit scenario

        Collection floor drops 50% but the oracle was last updated a day earlier; an attacker buys NFTs at the current (halved) market price but the principal check and credit limit are evaluated against the stale floor, so the loan is sized on a value the collateral no longer has; on default, the liquidation recovery (also priced from the stale floor, then from the real market) leaves bad debt.

        Recommendation

        Require block.timestamp - timestamp <= maxAge (configurable per reserve) in both buyNow and liquidate.

        Devin Security (Deep)

        buyNow and liquidate ignore the oracle timestamp, so a stale floor price is used for loan sizing and liquidation pricing

        home/ubuntu/extracted/goerli_solc/contracts/voyage/facets/LoanFacet.sol:194 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        If the price operator stops updating a collection's floor price, borrowers can keep taking loans against the old, higher price and liquidators are charged the old price, so lenders can be left under-collateralized after a market drop.

        ##### What's wrong

        This is a missing freshness check on oracle data. PriceOracle.getTwap returns both a price and the time it was written, and LoanFacet.buyNow and liquidate read the timestamp into params.timestamp / param.floorPriceTime but never compare it to block.timestamp.

        ##### Who can do it

        Acme's price operator posts a floor of 10 WETH for a collection and then goes offline for a week while the floor falls to 2 WETH. Mallory, a user with a Vault, calls buyNow with an order priced at 10 WETH for an NFT from that collection (which she can list herself) and borrows against it.

        - The operator-run oracle must be stale for the collection (no on-chain guarantee of updates exists).

        - Mallory needs a Vault and the downpayment for one instalment.

        ##### What they get

        Mallory borrows up to the stale floor against an NFT now worth far less, defaults, and the lenders recover only the discounted stale floor from a liquidator (if any liquidator is willing to overpay) or nothing. The senior and junior depositors of that reserve carry the loss; other reserves are unaffected.

        ##### How it works

        1. buyNow reads (params.fv, params.timestamp) from the oracle (contracts/voyage/facets/LoanFacet.sol:196-204) and only checks fv == 0 and fv < totalPrincipal.

        2. The credit limit and the loan amount are derived from fv with no age check.

        3. liquidate reads (floorPrice, floorPriceTime) (:444-452) and again uses the price without checking the time.

        4. PriceOracle.updateTwap (contracts/voyage/infra/PriceOracle.sol:38-44) is the only write path and is manual, so staleness is realistic.

        Exploit scenario

        Not specified.

        Recommendation

        Add a per-reserve maxTwapStaleness and revert in buyNow and liquidate when block.timestamp - timestamp > maxTwapStaleness. Verify with a test that buyNow reverts once the oracle entry is older than the configured limit.

      • Calls to redeem(...) can result in lost depositor funds voyage-10 · 5 writeups High

        V12

        Immediate redemption drains queued exit reserves

        contracts/voyage/tokenization/VToken.sol:41 Predicted severity: High

        Root cause

        The implementation overrides only withdraw() while leaving inherited immediate redeem() exposed, and it reserves pending exits by subtracting share units from asset units. At share prices above one, immediate redemption can consume the unreserved portion of pending claims.

        Impact

        A shareholder can front-run or follow a queued withdrawal with direct redemption and take assets reserved for the queued claimant. The claimant suffers direct principal loss while the redeemer receives more than their fair unreserved share.

        Description

        VToken queues only withdraw(); it inherits redeem() unchanged, so remaining holders can immediately transfer underlying while another user's exit is pending. The tranche reserves pending shares by subtracting their numeric value directly from asset-denominated totalAssets(), which under-reserves a claim whenever the share price exceeds one. With 200 assets and 100 shares, a request for 20 assets burns 10 shares and adds 10 to totalUnbonding; the other 90 shares then see 190 assets and can redeem all 90 for 190 underlying. Only 10 remains for the queued user despite that user having requested and burned shares for 20 assets. Yield or interest transfers naturally create a price above one, so this does not require a donation-only setup.

        Codex Security (GPT-6 Sol)

        Share holders can redeem immediately around the withdrawal queue

        contracts/voyage/tokenization/VToken.sol:41 Predicted severity: Medium

        Root cause

        The override of withdraw removes the immediate asset transfer and records a claim. No matching redeem override exists, so the inherited method uses _burn followed by asset.safeTransfer directly.

        Impact

        A holder can exit before queued claimants and take liquid assets that would otherwise satisfy pending withdrawals. Likelihood is high under the stated prerequisites.

        Description

        VToken queues withdraw into an unbonding claim but inherits ERC4626.redeem, which burns shares and immediately transfers liquid underlying to the caller.

        Exploit scenario

        contracts/voyage/tokenization/VToken.sol:41 to contracts/shared/tokenization/ERC4626.sol:90

        Recommendation

        Override redeem to use the same pending-claim accounting as withdraw, or disable redemption if unsupported.

        Pashov (Claude Opus 5.5 high)

        ERC4626 redeem/mint are not overridden in VToken, letting holders bypass the unbonding queue and take liquidity owed to unbonding users

        contracts/shared/tokenization/ERC4626.sol:90 Predicted severity: Medium

        Root cause

        Inconsistent exit paths: only one of the two ERC4626 exit functions applies the unbonding logic.

        Impact

        Users can skip the queue/cooldown and withdraw instantly, draining the liquid balance needed to pay claimants who unbonded earlier; claimants receive partial or no payment. It also amplifies the totalUnbonding share/asset mismatch.

        Description

        VToken only overrides withdraw to route exits through the unbonding queue, but inherits the public ERC4626 redeem, which burns shares and immediately transfers previewRedeem(shares) assets from the contract balance. That balance includes assets already promised to users in the unbonding queue (whose maxUnderlying is still sitting in the contract).

        Exploit scenario

        Senior pool has 100 liquid WETH, 80 of which are owed to Alice who called withdraw. Bob calls seniorToken.redeem(shares, bob, bob) directly and receives 60 WETH, leaving Alice unable to claim her full amount.

        Recommendation

        Override redeem (and mint/deposit as appropriate) to use the same unbonding logic, or disable them.

        Pashov (Codex GPT-6 Sol high)

        Withdrawal cooldown and queue can be bypassed through redeem

        audit/contracts/shared/tokenization/ERC4626.sol:90 Predicted severity: Medium

        Root cause

        Neither the claim path nor the inherited redeem path enforces the cooldown or queue policy.

        Impact

        Depositors can exit before the intended waiting period and avoid sharing subsequent loan or liquidation losses.

        Description

        VToken declares a seven-day cooldown and overrides withdraw to queue claims, but claim checks no time and inherited redeem burns shares for immediate asset transfer.

        Exploit scenario

        A tranche holder calls inherited redeem(shares,receiver,owner) and receives assets immediately; alternatively the holder withdraws then calls claim in the same transaction when cash exceeds the recorded cap.

        Recommendation

        Override redeem to use the same queued exit, record a withdrawal timestamp, and enforce cooldown in claim.

        Devin Security (Deep)

        Deposit tokens allow instant exit via redeem and claim, bypassing the unbonding queue and cooldown

        deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json:215 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A depositor who sees a loss coming can exit instantly through redeem, taking liquidity that was reserved for users already waiting in the withdrawal queue.

        ##### What's wrong

        VToken overrides withdraw to queue shares but inherits ERC4626.redeem, which pays out immediately and ignores totalUnbonding; claim() never checks the declared cooldown. Same source as the deployed artifact.

        ##### Who can do it

        Alice has a queued withdrawal; Mallory, another depositor, calls redeem(shares, mallory, mallory) on the token ahead of a write-down.

        - The attacker holds deposit-token shares and the token has WETH balance.

        ##### What they get

        Mallory exits at full pre-loss value with the WETH Alice's claim depended on; the loss falls on remaining depositors.

        ##### How it works

        1. VToken overrides withdraw only (contracts/voyage/tokenization/VToken.sol:41-57).

        2. ERC4626.redeem pays out instantly (contracts/shared/tokenization/ERC4626.sol:90-109).

        3. claim() has no cooldown check; cooldown is unused (contracts/voyage/tokenization/VToken.sol:24, 91-108).

        Exploit scenario

        Not specified.

        Recommendation

        Override redeem to use the unbonding logic (or revert) and enforce the cooldown in claim. Verify: redeem must revert or queue; claim before cooldown must revert.

      • Incorrect calculation in refundGas voyage-11 · 4 writeups Medium

        V12

        Partial gas refunds underflow despite available funds

        contracts/vault/Vault.sol:125 Predicted severity: Medium

        Root cause

        The deficient-balance branch subtracts balanceWETH9 from the initial ETH remainder instead of adding the WETH just unwrapped. amountRefundable therefore does not reflect the vault's available native funding.

        Impact

        Settlement can revert while a vault still has spendable ETH/WETH, preventing its gas refund from completing. This matters when funds become insufficient between the paymaster's initial funding check and settlement, or on direct settlement requests permitted by the current paymaster; the exact relay-hub recovery behavior after such a revert is outside the supplied source.

        Description

        refundGas attempts to refund whatever funding is available when the requested WETH shortfall exceeds the vault's WETH balance. After unwrapping that balance, it computes amountRefundable - toUnwrap - balanceWETH9. Since toUnwrap is the requested amount minus the original ETH balance, this evaluates to original ETH minus WETH rather than the available ETH plus WETH. If the WETH balance exceeds the original ETH balance, checked arithmetic reverts and even the unwrap rolls back. If the arithmetic succeeds, it under-refunds by twice the WETH balance despite having unwrapped those funds.

        Pashov (Claude Opus 5.5 high)

        Vault.refundGas miscomputes the refundable amount when WETH is insufficient (underflow / short refund)

        contracts/vault/Vault.sol:125 Predicted severity: Low

        Root cause

        Incorrect arithmetic (sign error in subtraction).

        Impact

        If the vault's WETH balance exceeds its ETH balance the function underflows and reverts, so the paymaster cannot recover gas costs (adding to paymaster losses); otherwise it refunds far less than what is available (unwrapped WETH stays in the vault as ETH).

        Description

        When toUnwrap > balanceWETH9, the code sets amountRefundable = amountRefundable - toUnwrap - balanceWETH9, which equals ethBal - balanceWETH9. The intended value is _amount - (toUnwrap - balanceWETH9) = ethBal + balanceWETH9.

        Exploit scenario

        Vault has 0.01 ETH and 0.02 WETH; paymaster requests 0.05. toUnwrap=0.04 > 0.02 so amountRefundable = 0.05-0.04-0.02 -> underflow revert.

        Recommendation

        Use amountRefundable = ethBal + balanceWETH9 in the shortfall branch.

        Pashov (Codex GPT-6 Sol high)

        Refund gas arithmetic underflows when vault has insufficient funds

        audit/contracts/vault/Vault.sol:125 Predicted severity: Medium

        Root cause

        The fallback ETH/WETH payment calculation uses inconsistent remaining-amount arithmetic.

        Impact

        Relayed calls to low-balance vaults revert instead of paying the available amount.

        Description

        The gas refund path subtracts the WETH balance from an already reduced amount even when that balance is insufficient to cover the requested refund.

        Exploit scenario

        For a 100-unit refund with 10 ETH and 20 WETH, the computed subtraction underflows.

        Recommendation

        Calculate the unpaid remainder once, cap WETH withdrawal by balance, and transfer only available funds.

        Devin Security (Deep)

        Vault.refundGas double-subtracts the unwrapped WETH, causing refund reverts or wrong amounts

        contracts/vault/Vault.sol:125 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        When a Vault has to unwrap WETH to pay a gas refund and does not have quite enough, the arithmetic underflows and the whole relayed transaction fails, so this only causes failed gas-sponsored calls, not fund loss.

        ##### What's wrong

        This is an arithmetic bug. In the branch where the Vault's WETH is less than what is still needed, amountRefundable has toUnwrap subtracted (which already equals the remaining shortfall) and then balanceWETH9 subtracted again, so the value underflows and reverts instead of settling for what is available, which is the opposite of the comment above it.

        ##### Who can do it

        Alice, a Voyage user, sends a gasless transaction while her Vault holds a little ETH and a little WETH. The paymaster calls refundGas; the branch is entered and the call reverts. Nobody gains; the relayed action simply fails.

        - Only the configured paymaster can call refundGas.

        - The Vault must have ETH + WETH below the requested refund.

        ##### What they get

        No attacker gain. Gas-sponsored transactions for under-funded Vaults fail, and in GSN the paymaster deposit is charged for the failed attempt.

        ##### How it works

        1. refundGas (contracts/vault/Vault.sol:125-146) computes toUnwrap = amountRefundable - balance.

        2. If balanceWETH9 < toUnwrap, it unwraps balanceWETH9 and sets amountRefundable = amountRefundable - toUnwrap - balanceWETH9.

        3. Since amountRefundable - toUnwrap == balance, subtracting balanceWETH9 again underflows whenever balanceWETH9 > balance, reverting the call.

        Exploit scenario

        Not specified.

        Recommendation

        Set amountRefundable = address(this).balance after unwrapping (that is, balance + balanceWETH9). Verify with a unit test where the Vault has 0.01 ETH and 0.02 WETH and a 0.05 ETH refund is requested; it should transfer 0.03 ETH instead of reverting.

      • Missing access control on postRelayedCall leading to ETH transfer from Vault voyage-12 · 7 writeups High

        V12

        Public settlement callback enables unauthorized vault depletion

        contracts/shared/gsn/VoyagePaymaster.sol:89 Predicted severity: High

        Root cause

        The state-changing postRelayedCall override omits hub-only authorization and trusts externally supplied settlement context and gas parameters. The vault's onlyPaymaster authenticates the intermediary contract, not the caller or relay that caused it to request a refund.

        Impact

        Anyone can force transfers of a victim vault's ETH and WETH to the configured treasury without the vault owner's authorization or an actual relayed transaction. The attacker cannot select the treasury through this path, but can repeat fabricated refunds to deplete user funds; no hub deployment is required.

        Description

        postRelayedCall is an unrestricted external override that accepts caller-supplied context, gasUseWithoutPost, and relayData without a hub-only modifier or an in-body caller check. An arbitrary caller can supply abi.encode(victimVault) and fabricated gas parameters, bypassing preRelayedCall, any relay signature validation, and the sender-to-vault registry lookup. The paymaster then calls the selected vault's refundGas, where onlyPaymaster succeeds because the immediate caller is the configured paymaster contract. For requests covered by the vault's ETH or combined ETH/WETH balance, the vault transfers the fabricated charge to the immutable treasury. The tests directly invoke this override with manually encoded vault addresses, independently of the broken context produced by the pre-relay callback.

        Codex Security (GPT-6 Sol)

        Any caller can debit a user's vault through paymaster settlement

        contracts/shared/gsn/VoyagePaymaster.sol:89 Predicted severity: High

        Root cause

        The external callback has no RelayHub caller check. It decodes caller-controlled context as a vault and computes a refund from caller-controlled gas fields. Vault.refundGas trusts the immediate paymaster caller, so it cannot distinguish a forged settlement.

        Impact

        An unprivileged caller can deplete a funded victim vault into the fixed treasury; the attacker cannot choose the recipient. Likelihood is high under the stated prerequisites.

        Description

        postRelayedCall accepts unauthenticated callers and caller-supplied settlement context, then instructs a victim vault to transfer ETH or WETH to the paymaster treasury.

        Exploit scenario

        contracts/shared/gsn/VoyagePaymaster.sol:89 to contracts/vault/Vault.sol:125

        Recommendation

        Require the trusted RelayHub on both callbacks and bind the context, vault, and refund to a verified relay.

        Pashov (Codex GPT-6 Sol high)

        Anyone can invoke paymaster settlement against a user vault

        audit/contracts/shared/gsn/VoyagePaymaster.sol:89 Predicted severity: High

        Root cause

        The paymaster settlement hook is externally callable without authenticating the relay hub.

        Impact

        An attacker can force an unrelated vault to transfer available ETH or WETH to the treasury without a relay transaction.

        Description

        postRelayedCall lacks a relay-hub caller restriction and trusts supplied context to identify the vault charged for gas.

        Exploit scenario

        The attacker calls postRelayedCall with abi.encode(victimVault) and arbitrary gas usage; paymaster then calls victimVault.refundGas, which trusts the paymaster address.

        Recommendation

        Restrict postRelayedCall to the configured relay hub and bind context to a validated preRelayedCall.

        Devin Security (Deep)

        Anyone can call VoyagePaymaster.postRelayedCall to drain any user's vault ETH and WETH to the treasury

        deployments/rinkeby/solcInputs/12dd858cd3471725424835f3a0db1659.json:320 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone on the internet can empty every user's vault of ETH and WETH by calling the paymaster's post-relay hook directly, sending the funds to the protocol treasury.

        ##### What's wrong

        This is a missing access check on a privileged callback. GSN's IPaymaster requires postRelayedCall to be guarded with relayHubOnly; VoyagePaymaster.postRelayedCall has no modifier. It decodes a vault address from caller-supplied context, computes a refund from caller-supplied gasUseWithoutPost and relayData.gasPrice, and calls IVault(vault).refundGas(refund, treasury). The vault trusts the paymaster unconditionally through onlyPaymaster.

        ##### Who can do it

        Alice's vault holds 5 ETH and 20 WETH (a liquidation refund). Mallory, with no account, calls paymaster.postRelayedCall(abi.encode(aliceVault), true, N, relayData), choosing N and relayData.gasPrice so that the computed fee equals 25 ETH.

        - The target vault holds any ETH or WETH.

        - The paymaster address stored in the vault at Vault.initialize is the deployed VoyagePaymaster.

        ##### What they get

        Alice's vault unwraps its WETH and sends all 25 ETH to the treasury address. Mallory gains nothing directly, but she can wipe out the ETH and WETH of every vault in the protocol at any time, including liquidation refunds and gas deposits, and users then depend on the treasury owner to hand funds back. Because vault ETH is also what pays for gasless transactions, every victim also loses gasless usage.

        ##### How it works

        1. Mallory calls VoyagePaymaster.postRelayedCall(context, success, gasUseWithoutPost, relayData); there is no relayHubOnly or other sender check (contracts/shared/gsn/VoyagePaymaster.sol:89-107).

        2. vault = abi.decode(context, (address)) is Alice's vault, and minimumFees = (gasUseWithoutPost + 21000 + msg.data.length * 8 + 35000) * relayData.gasPrice is fully attacker-controlled (contracts/shared/gsn/VoyagePaymaster.sol:95-105).

        3. The paymaster calls IVault(vault).refundGas(refund, treasury); Vault.onlyPaymaster passes because msg.sender is the paymaster (contracts/vault/Vault.sol:87-90 and 125-155).

        4. refundGas unwraps WETH as needed and sends the amount as ETH to the treasury.

        Exploit scenario

        Not specified.

        Recommendation

        Add relayHubOnly to postRelayedCall (and preRelayedCall). In Vault.refundGas, also cap the refund to a bound recorded in the pre-call context (for example maxPossibleGas * gasPrice) so even the hub cannot over-charge. Verify: calling postRelayedCall from a non-hub account must revert with the RelayHub-only error, and a hub-originated call must not be able to refund more than the pre-call bound.

        Claude Security (Sonnet 5.5)

        VoyagePaymaster.postRelayedCall has no relayHubOnly check and lets anyone force any vault to refund arbitrary ETH/WETH to the treasury

        contracts/shared/gsn/VoyagePaymaster.sol:89 Predicted severity: High

        Root cause

        Vulnerable symbol: VoyagePaymaster.postRelayedCall

        Offending code:

        function postRelayedCall(

        Impact

        Any user's vault ETH and WETH can be drained to the treasury by any caller, with no authentication. This is user fund loss and an easy griefing or DoS vector against the protocol's users.

        Description

        postRelayedCall is external with no relayHubOnly guard. It decodes a vault address from caller-supplied context and computes refund from caller-supplied gasUseWithoutPost and relayData.gasPrice. It then calls IVault(vault).refundGas(refund, treasury). The vault only checks msg.sender == paymaster, which this contract satisfies for any caller.

        Exploit scenario

        An attacker calls paymaster.postRelayedCall(abi.encode(victimVault), true, X, {gasPrice: 1, ...}), choosing X so that refund equals the vault's ETH balance. For WETH-only vaults the attacker picks refund within ETH+WETH, so the vault unwraps WETH and sends it. The vault pays ETH to treasury, and the attacker repeats this for every vault.

        Recommendation

        Guard preRelayedCall and postRelayedCall with the relayHubOnly or _verifyRelayHubOnly() check from BasePaymaster. Also bind the context to the vault computed in preRelayedCall rather than decoding a caller-supplied address, and note that preRelayedCall currently puts request.from (the EOA) in the context.

        Claude Security (Opus 5.5)

        Anyone can call VoyagePaymaster.postRelayedCall to drain any user's vault ETH/WETH through Vault.refundGas

        contracts/shared/gsn/VoyagePaymaster.sol:89 Predicted severity: High

        Root cause

        Vulnerable symbol: postRelayedCall

        Preconditions: The victim vault holds ETH or WETH

        Offending code:

        function postRelayedCall(

        Impact

        Anyone, without authentication, can empty the ETH and WETH of every user vault. That includes gas deposits, liquidation refunds credited to the vault, and principal ETH sitting in the vault. The funds go to the protocol treasury, so users lose them and gasless relaying stops working for everyone.

        Description

        postRelayedCall has no relayHubOnly check (GSN 2.2.x BasePaymaster leaves that check to the subclass). It takes context (the vault address) and gasUseWithoutPost/relayData.gasPrice (the refund amount) from the caller and calls IVault(vault).refundGas(refund, treasury). Vault.refundGas checks only that msg.sender == paymaster, so any external caller who goes through the paymaster gets past the vault's only access check.

        Exploit scenario

        The attacker reads victimVault = voyage.getVaultAddr(victim). They call paymaster.postRelayedCall(abi.encode(victimVault), true, G, relayData{gasPrice: 1, ...}) with G chosen so that (G + 21000 + calldata*8 + 35000) equals ETH(vault) + WETH(vault). refundGas unwraps all of the vault's WETH and sends the vault's entire ETH and WETH balance to the treasury. The attacker can repeat this for every vault in s.vaults.

        Recommendation

        Add the relayHubOnly modifier (or an equivalent require(msg.sender == getHubAddr())) to postRelayedCall and preRelayedCall. Also bind the refunded vault to the relayed request: derive it from request.from in preRelayedCall and encode it consistently (abi.encode, not encodePacked of the user address) so postRelayedCall cannot be pointed at an arbitrary vault.

        Vercel Security Review

        Unauthenticated paymaster callback can force arbitrary vault gas refunds

        contracts/shared/gsn/VoyagePaymaster.sol:94 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. The new post-relay callback trusts externally supplied context** - contracts/shared/gsn/VoyagePaymaster.sol:92-95

        ```solidity title="contracts/shared/gsn/VoyagePaymaster.sol:92-95"

        uint256 gasUseWithoutPost,

        GsnTypes.RelayData calldata relayData

        ) external virtual override {

        address vault = abi.decode(context, (address));

        ```

        Anyone, not just RelayHub, can select a victim vault and invent gas usage and price without a relayed transaction.

        **2. Those inputs trigger a privileged refund** - contracts/shared/gsn/VoyagePaymaster.sol:103-106

        ```solidity title="contracts/shared/gsn/VoyagePaymaster.sol:103-106"

        uint256 refund = vault.balance >= minimumFees

        ? minimumFees

        : minimumFees + 21000 * relayData.gasPrice; // cover cost of unwrapping WETH

        IVault(vault).refundGas(refund, treasury);

        ```

        **3. The vault pays because the immediate caller is its trusted paymaster** - contracts/vault/Vault.sol:142-144

        ```solidity title="contracts/vault/Vault.sol:142-144"

        (bool success, bytes memory result) = _dst.call{

        value: amountRefundable

        }(EMPTY_BYTES);

        ```

        onlyPaymaster at line 125 does not authenticate the originating caller. Attackers can deplete other users' ETH/WETH into the fixed treasury; they cannot choose the destination.

        Exploit scenario

        Not specified.

        Recommendation

        Authenticate RelayHub explicitly at both relay callbacks before processing inputs. Encode validated vault context consistently using abi.encode, and accept refund accounting only from authenticated relay execution.

      • Functions cannot be removed during upgrades voyage-13 · 2 writeups Medium

        V12

        Removed selectors are omitted from upgrade differences

        contracts/voyage/facets/DiamondVersionFacet.sol:49 Predicted severity: Informational

        Root cause

        getUpgrade never populates existingSelectors, although the Remove loop enumerates that array. Current-inventory selectors are recorded in the wrong key registry, making removal classification unreachable from default workspace state.

        Impact

        The returned comparison can leave a retired selector callable if its cuts are used to reconcile a diamond against the registered snapshot. That security consequence remains unresolved because no returned-cut application path was found in contracts, deploy, tests, scripts, or helpers; the exact missing fact is whether security-sensitive selector revocation relies on this result rather than independently prepared cuts.

        Description

        The current loupe inventory is appended to newSelectors, not to existingSelectors. Consequently, existingSelectors remains empty under every writer found in the repository, and the entire Remove-classification loop is skipped. A supplied inventory containing an extra selector alongside unchanged snapshot selectors therefore returns an empty cut list instead of a removal. The same result occurs for a nonempty vault inventory with no registered snapshot at version zero, or with an explicitly empty snapshot. This failure occurs on a successful transaction and is independent of the out-of-bounds writes in the Add and Replace branches.

        Pashov (Claude Opus 5.5 high)

        DiamondVersionFacet.getUpgrade is broken: writes past array bounds, never records existing selectors, leaves stale state

        contracts/voyage/facets/DiamondVersionFacet.sol:30 Predicted severity: Low

        Root cause

        Wrong array used and indexed assignment instead of push on storage arrays.

        Impact

        The upgrade helper always reverts or returns incorrect cuts (never removing deprecated/vulnerable selectors), and leftover per-sender state corrupts subsequent computations.

        Description

        getUpgrade (public, unauthenticated, state-mutating) pushes the current facets' selectors into newSelectors instead of existingSelectors, so selectors to remove are never computed and existingSelectorFacetMap entries are never cleaned (cleanUpgradeParam iterates the empty existingSelectors). It writes facetCuts[facetCutSize] = facetCut on a storage array without push, which reverts with an out-of-bounds panic whenever any cut is needed. newSelectorSet entries for snapshot selectors are never cleared.

        Exploit scenario

        Calling getUpgrade(vault) with a snapshot that adds any selector reverts with panic 0x32.

        Recommendation

        Push to existingSelectors, use push() for facetCuts, and clean all helper mappings.

      • Missing access control on multiple PaymentsFacet functions voyage-14 · 8 writeups High

        V12

        First installment interest is charged twice

        contracts/voyage/facets/LoanFacet.sol:208 Predicted severity: High

        Root cause

        buyNow includes interest in its collected downpayment but also funds interest distribution with another borrower transfer instead of the already-collected funds. The excess remains in a shared diamond balance exposed to permissionless refunds.

        Impact

        A successful borrowing transaction charges the borrower an extra first-installment interest amount that is not credited against debt. Any external caller can collect the residual ETH from the diamond, creating conditional borrower fund loss whenever installment interest is nonzero.

        Description

        buyNow sets params.downpayment to the complete first installment, including both principal and interest. It collects that amount through msg.value and/or a currency transfer into the diamond, then unwraps the diamond's entire WETH balance and sends only the purchase principal to the vault. After recording the first repayment, it calls LibLoan.distributeInterest, which separately pulls the same installment interest from the borrower into the tranche tokens. For a WETH reserve with no preexisting diamond balance, the purchase funding therefore leaves exactly the first installment's interest as residual ETH while additionally charging that interest in WETH. The residual is not assigned to the borrower and can be taken through the public refundETH helper.

        Codex Security (GPT-6 Sol)

        Any caller can sweep assets from the Voyage diamond

        contracts/shared/facets/PaymentsFacet.sol:35 Predicted severity: High

        Root cause

        PaymentsFacet exposes sweepToken, unwrapWETH9, and refundETH without authorization; inherited approve likewise grants a caller-selected spender an allowance. The deployed diamond includes this facet.

        Impact

        Any balance retained or present during a reachable callback can be stolen or made spendable by an attacker. Likelihood is medium under the stated prerequisites.

        Description

        Public payment helpers let an arbitrary caller move the diamond's ERC20, WETH, or ETH balance and grant an arbitrary ERC20 spender allowance.

        Exploit scenario

        contracts/shared/facets/PaymentsFacet.sol:35 to deploy/001_voyager.ts:132

        Recommendation

        Restrict sweeping and approval to authorized recovery flows; make internal payment helpers non-public or bind recipients and amounts to an operation.

        Pashov (Claude Opus 5.5 high)

        PaymentsFacet sweepToken / refundETH / unwrapWETH9 / approve allow anyone to drain or misuse assets held by the diamond

        contracts/shared/facets/PaymentsFacet.sol:15 Predicted severity: High

        Root cause

        Unauthenticated payment helpers in a contract that persistently custodies funds.

        Impact

        Any ETH/ERC20 left in the diamond (e.g. the surplus interest from every buyNow) can be stolen by anyone; anyone can set arbitrary allowances from the diamond (also able to reset the vToken approvals to 0, breaking deposits).

        Description

        PaymentsFacet exposes sweepToken, refundETH, unwrapWETH9, wrapWETH9 and PeripheryPayments.approve publicly on the diamond with no authorisation. These are Uniswap-periphery style helpers that assume the contract never holds funds between transactions, but the Voyage diamond does hold funds: in buyNow the down-payment includes the first instalment's interest which is pulled again by distributeInterest, leaving ETH in the diamond; liquidation proceeds, rounding remainders, mistakenly sent tokens, etc. approve additionally lets anyone make the diamond approve an arbitrary spender for any token it holds.

        Exploit scenario

        After a borrower calls buyNow, the diamond retains pmt.interest worth of ETH (down-payment includes interest which is also separately transferred to the tranches). Attacker calls refundETH() and receives the diamond's entire ETH balance, or sweepToken(WETH,0,attacker) for WETH; or approve(WETH, attacker, max) then transferFrom.

        Recommendation

        Restrict these helpers to internal use or to authorised callers; never leave value in the diamond between transactions.

        Pashov (Codex GPT-6 Sol high)

        Permissionless payment functions can sweep diamond assets

        audit/contracts/shared/facets/PaymentsFacet.sol:15 Predicted severity: High

        Root cause

        Payment functions have no caller authorization and use the diamond as the asset source.

        Impact

        Any assets temporarily or persistently held by the Voyage diamond can be stolen.

        Description

        The diamond exposes unrestricted functions that transfer its entire ETH, WETH, or ERC20 balance to a caller-selected recipient. The inherited public approve function also lets callers grant themselves a spend allowance over those balances.

        Exploit scenario

        An attacker calls sweepToken(token,0,attacker) or unwrapWETH9(0,attacker) while the diamond holds user funds.

        Recommendation

        Restrict sweep and unwrap to an authorized role or remove them from the public diamond interface.

        Devin Security

        Unauthenticated sweepToken, unwrapWETH9, refundETH and approve let anyone take funds held by the diamond

        contracts/shared/facets/PaymentsFacet.sol:15 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can take any ETH or tokens that sit in the Voyage diamond, but the normal flows move funds out within the same transaction, so this mostly exposes stray or stuck balances.

        ##### What's wrong

        These are missing access checks. sweepToken, unwrapWETH9 and refundETH send the diamond's whole token or ETH balance to a caller-chosen recipient (or to the caller). The inherited approve lets any caller make the diamond approve any spender for any token. None of them has a modifier. They are Uniswap router helpers, but the Voyage diamond is not a stateless router: LoanFacet uses unwrapWETH9 internally and liquidation and buyNow route funds through the diamond's balance.

        ##### Who can do it

        Alice, a user, sends WETH to the diamond by mistake, or a liquidation refund leaves dust behind. Mallory, an anonymous caller, calls sweepToken(WETH, 0, Mallory) or approve(WETH, Mallory, max) and then transferFrom.

        - The diamond holds a token or ETH balance at the moment Mallory calls.

        ##### What they get

        Mallory takes the diamond's full balance of any token or ETH. In the current code the main flows (buyNow, liquidate) spend what they pull in the same transaction, so the exposed amount is usually limited to stray or leftover funds. Because multicall delegatecalls the diamond, a payable call inside it also sees the same msg.value on every subcall, which makes any ETH the diamond holds usable as a free downpayment in a batched buyNow.

        ##### How it works

        1. PaymentsFacet.sweepToken at contracts/shared/facets/PaymentsFacet.sol:35-46 transfers the full balance to recipient with no auth.

        2. unwrapWETH9 at lines 15-28 unwraps all WETH and sends the ETH to recipient.

        3. refundETH at lines 48-52 sends all ETH to msg.sender.

        4. PeripheryPayments.approve lets the caller set any allowance from the diamond.

        Exploit scenario

        Not specified.

        Recommendation

        Restrict these helpers to internal callers with require(msg.sender == address(this)) or the existing authorised modifier, and keep LoanFacet's internal use working. Add tests that an external caller cannot sweep, unwrap, refund or approve from the diamond.

        Devin Security (Deep)

        buyNow charges the first instalment's interest twice and leaves one copy on the diamond where anyone can take it

        deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json:245 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Every borrower overpays the first interest instalment, and the extra ETH sits on the Voyage diamond where anyone can sweep it with refundETH.

        ##### What's wrong

        This is an accounting mistake in the payment flow. The down payment pulled from the borrower is pmt.pmt (principal plus interest), the diamond unwraps all its WETH and forwards only totalPrincipal to the vault, leaving pmt.interest as ETH on the diamond, and distributeInterest then pulls pmt.interest from the borrower again. This artifact's buyNow matches the current contracts/ tree.

        ##### Who can do it

        Bob borrows 9 ETH over 3 instalments; buyNow takes 3.15 ETH down and another 0.15 ETH as interest, leaving 0.15 ETH on the diamond. Mallory calls refundETH() on the diamond right after.

        - Any buyNow has happened and the diamond has not been swept.

        - PaymentsFacet.refundETH/unwrapWETH9 are public.

        ##### What they get

        Mallory collects one instalment of interest from every loan, paid by borrowers; any WETH on the diamond at the time is also unwrapped and exposed.

        ##### How it works

        1. downpayment = pmt.pmt is pulled (contracts/voyage/facets/LoanFacet.sol:209, 227-237).

        2. unwrapWETH9 unwraps the whole WETH balance (contracts/voyage/facets/LoanFacet.sol:250-259, contracts/shared/facets/PaymentsFacet.sol:15-28).

        3. Only totalPrincipal ETH is sent to the vault (contracts/voyage/facets/LoanFacet.sol:261).

        4. distributeInterest pulls pmt.interest again (contracts/voyage/facets/LoanFacet.sol:285-289).

        5. Anyone calls refundETH() (contracts/shared/facets/PaymentsFacet.sol:48-52).

        Exploit scenario

        Not specified.

        Recommendation

        Pull only pmt.principal as the down payment (or drop the second interest pull), unwrap exactly outstandingPrincipal, and assert the diamond's ETH balance is unchanged at the end of buyNow. Verify: diamond ETH/WETH balances are zero after buyNow.

        Claude Security (Sonnet 5.5)

        PaymentsFacet sweep, refund and unwrap functions, and PeripheryPayments.approve, are unauthenticated and let anyone take or approve anything the diamond holds

        contracts/shared/facets/PaymentsFacet.sol:48 Predicted severity: Medium

        Root cause

        Vulnerable symbol: PaymentsFacet.refundETH

        Preconditions: The diamond holds a non-zero ETH or token balance (accumulates through buyNow as described above)

        Offending code:

        function refundETH() external payable {

        Impact

        Loss of any funds that rest in the diamond (leftover ETH, tokens, WETH residue) to arbitrary callers. The amounts are bounded by what the diamond holds at the moment of the call.

        Description

        refundETH, sweepToken, unwrapWETH9 and PeripheryPayments.approve have no access control. refundETH sends the diamond's whole ETH balance to msg.sender. sweepToken sends any token balance to a caller-chosen recipient. unwrapWETH9 unwraps all WETH to an arbitrary recipient. approve(token, to, amount) makes the diamond approve any spender for any token.

        Exploit scenario

        After buyNow calls, the diamond keeps the leftover ETH from the interest share of each downpayment. An attacker calls refundETH() and collects the balance. The attacker can also call approve(token, attacker, max) followed by transferFrom, or call sweepToken, to take any other token or WETH residue the diamond holds, such as liquidation proceeds in flight or rounding dust.

        Recommendation

        Make these helpers internal or restrict them to msg.sender == address(this) or authorised. Remove approve. Fix buyNow so the interest share of the downpayment is routed to the tranches rather than left in the diamond.

        Claude Security (Opus 5.5)

        refundETH, unwrapWETH9 and sweepToken let anyone take the diamond's accumulated ETH, WETH and token balances

        contracts/shared/facets/PaymentsFacet.sol:48 Predicted severity: Medium

        Root cause

        Vulnerable symbol: refundETH

        Preconditions: The diamond holds a non-zero ETH, WETH or token balance. ETH accrues from every buyNow.

        Offending code:

        function refundETH() external payable {

        Impact

        Theft of all ETH, WETH and ERC20 balances held by the Voyage diamond, including the interest portion of every buyNow downpayment.

        Description

        refundETH sends the diamond's entire ETH balance to msg.sender, with no check that the caller deposited it. unwrapWETH9(0, attacker) and sweepToken(token, 0, attacker) send the entire WETH or token balance to a caller-chosen recipient. LoanFacet.buyNow leaves ETH in the diamond on every loan, and these functions let anyone collect it.

        Exploit scenario

        After users take loans with buyNow, the diamond holds one installment of interest per loan as ETH. Any address calls diamond.refundETH() and receives the full balance. Any WETH or ERC20 sent to the diamond can likewise be taken with unwrapWETH9(0, attacker) or sweepToken(token, 0, attacker).

        Recommendation

        Restrict these helpers to internal use or to authorised callers, and let msg.sender recover only the msg.value it sent within the same call. Also fix buyNow so that the leftover downpayment is forwarded to the tranches instead of staying in the diamond.

      • Multicall can be used to call buyNow with untrusted msg.value voyage-15 · 4 writeups High

        V12

        Multicall reuses native downpayment across purchases

        contracts/voyage/facets/LoanFacet.sol:226 Predicted severity: Medium

        Root cause

        buyNow treats transaction-level msg.value as a fresh payment per delegatecalled invocation. Payable multicall provides no per-subcall value accounting, and shared residual ETH can mask the resulting funding deficit.

        Impact

        A borrower can avoid one purchase's principal downpayment when repeated subcalls reuse msg.value and the first purchase's residual covers the second purchase's ETH shortfall. This is conditional on sufficient residual interest or other existing diamond ETH, and results in value leakage through falsely credited first payments.

        Description

        buyNow accepts msg.value as the downpayment for each invocation without consuming or tracking it, while the payments facet exposes a payable delegatecall multicall. Each subcall consequently observes the same outer msg.value even though ETH entered the diamond only once. Multiple purchases ordinarily revert on insufficient remaining ETH, but the first purchase leaves its included installment interest in the diamond, which can fund a later subcall's principal contribution. Accepted long-term schedules can produce installment interest at least as large as installment principal, making two such purchases complete using one ETH downpayment. Each purchase still receives the full principal and is recorded as having made its first payment.

        Pashov (Claude Opus 5.5 high)

        msg.value reuse through payable multicall lets borrowers fund multiple buyNow down-payments with one payment

        contracts/shared/util/Multicall.sol:12 Predicted severity: High

        Root cause

        msg.value-based accounting inside a function reachable through a delegatecall-based payable multicall.

        Impact

        Borrowers obtain loans without paying the down-payment, draining ETH held by the diamond and leaving the protocol under-collateralised.

        Description

        PaymentsFacet exposes Multicall, whose multicall is payable and delegatecalls address(this) for each sub-call. Every delegatecall observes the same msg.value. buyNow is payable and accepts the down-payment as msg.value (if downpayment <= msg.value require(downpayment == msg.value)). Batching N buyNow calls with msg.value = downpayment satisfies the check N times while ETH is only sent once; the remaining ETH sent to vaults (safeTransferETH(vault, totalPrincipal)) is taken from the diamond's ETH balance (e.g. the interest surplus left by previous buyNows or any other ETH held).

        Exploit scenario

        Diamond holds 5 ETH of accumulated surplus. Attacker calls multicall([buyNow(A,...), buyNow(B,...)]) with value = downpayment of each (equal). Both calls accept msg.value; the second loan's down-payment principal is paid using the diamond's 5 ETH.

        Recommendation

        Make multicall non-payable or track consumed ETH explicitly; do not rely on msg.value inside multicall-able functions.

        Devin Security

        Unauthenticated sweepToken, unwrapWETH9, refundETH and approve let anyone take funds held by the diamond

        contracts/shared/facets/PaymentsFacet.sol:15 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can take any ETH or tokens that sit in the Voyage diamond, but the normal flows move funds out within the same transaction, so this mostly exposes stray or stuck balances.

        ##### What's wrong

        These are missing access checks. sweepToken, unwrapWETH9 and refundETH send the diamond's whole token or ETH balance to a caller-chosen recipient (or to the caller). The inherited approve lets any caller make the diamond approve any spender for any token. None of them has a modifier. They are Uniswap router helpers, but the Voyage diamond is not a stateless router: LoanFacet uses unwrapWETH9 internally and liquidation and buyNow route funds through the diamond's balance.

        ##### Who can do it

        Alice, a user, sends WETH to the diamond by mistake, or a liquidation refund leaves dust behind. Mallory, an anonymous caller, calls sweepToken(WETH, 0, Mallory) or approve(WETH, Mallory, max) and then transferFrom.

        - The diamond holds a token or ETH balance at the moment Mallory calls.

        ##### What they get

        Mallory takes the diamond's full balance of any token or ETH. In the current code the main flows (buyNow, liquidate) spend what they pull in the same transaction, so the exposed amount is usually limited to stray or leftover funds. Because multicall delegatecalls the diamond, a payable call inside it also sees the same msg.value on every subcall, which makes any ETH the diamond holds usable as a free downpayment in a batched buyNow.

        ##### How it works

        1. PaymentsFacet.sweepToken at contracts/shared/facets/PaymentsFacet.sol:35-46 transfers the full balance to recipient with no auth.

        2. unwrapWETH9 at lines 15-28 unwraps all WETH and sends the ETH to recipient.

        3. refundETH at lines 48-52 sends all ETH to msg.sender.

        4. PeripheryPayments.approve lets the caller set any allowance from the diamond.

        Exploit scenario

        Not specified.

        Recommendation

        Restrict these helpers to internal callers with require(msg.sender == address(this)) or the existing authorised modifier, and keep LoanFacet's internal use working. Add tests that an external caller cannot sweep, unwrap, refund or approve from the diamond.

        Devin Security (Deep)

        Anyone can sweep ETH and tokens held by the Voyage diamond, which accumulates double-charged borrower interest

        contracts/shared/facets/PaymentsFacet.sol:15 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can take whatever ETH or tokens sit in the Voyage contract, and the contract steadily collects borrowers' overpaid interest, so that money is lost to the first person who grabs it.

        ##### What's wrong

        This is a set of unauthenticated treasury functions combined with a double charge. refundETH, sweepToken, unwrapWETH9 and approve in PaymentsFacet have no access control and operate on the diamond's own balances. Separately, buyNow collects the first installment's interest inside the down payment and then charges the same interest again in distributeInterest, leaving the first copy as ETH inside the diamond.

        ##### Who can do it

        Alice, a borrower at Acme, calls buyNow; the diamond keeps her first-period interest as ETH after forwarding the purchase price to her vault. Mallory, anyone watching the chain, calls refundETH() on the diamond and receives that ETH. multicall also lets a caller reuse one msg.value across several payable calls, so any ETH the diamond holds can also be spent as someone else's down payment.

        - The diamond holds any ETH or ERC20 balance, which happens after every buyNow or when funds are sent to it by mistake.

        ##### What they get

        Mallory takes the diamond's whole ETH balance (and, via sweepToken, any token balance) to her own wallet. The amount per purchase is one installment of interest per borrower, and it grows with protocol volume. Borrowers have already lost this money because they were charged twice. With approve(WETH, vToken, 0) she can also reset the diamond's allowance to a tranche token and break deposit until someone re-approves.

        ##### How it works

        1. buyNow sets downpayment = pmt.pmt (principal plus interest for one installment) and pulls it from the borrower (contracts/voyage/facets/LoanFacet.sol:209, 227-237).

        2. It unwraps all diamond WETH and sends only totalPrincipal to the vault (lines 256-261), leaving pmt.interest worth of ETH in the diamond.

        3. distributeInterest then pulls pmt.interest from the borrower a second time (lines 285-289; LibLoan.sol:427-447).

        4. Mallory calls refundETH() (contracts/shared/facets/PaymentsFacet.sol:48-52), which sends the diamond's full ETH balance to msg.sender; sweepToken (lines 35-46), unwrapWETH9 (lines 15-28) and approve (PeripheryPayments.sol:23-29) are equally open.

        5. Multicall.multicall (Multicall.sol:12-35) delegatecalls payable functions in a loop with the same msg.value, so diamond-held ETH can also cover repeated buyNow down payments.

        The same code is embedded in the deployment artifact deployments/rinkeby/solcInputs/8683a2c35133ff397846d93c3e914ec7.json.

        Exploit scenario

        Not specified.

        Recommendation

        Restrict refundETH, sweepToken, unwrapWETH9 and approve to msg.sender == address(this) or an authorised role, and make unwrapWETH9 unwrap only the requested amount. In buyNow, either stop collecting interest in the down payment or forward the collected interest to the tranches instead of calling distributeInterest from the borrower a second time. Remove multicall or make the payable paths check msg.value only once. Verify with a test that the diamond's ETH and WETH balances are zero after buyNow and that refundETH from a stranger reverts.

      • Lack of reentrancy guards voyage-16 · 1 writeup Medium

        V12

        Callbacks can consume loans during purchase initialization

        contracts/voyage/facets/LoanFacet.sol:201 Predicted severity: Informational

        Root cause

        Creation and repayment share mutable loan storage without a shared lock or lifecycle marker protecting the interval between debt insertion and the outer first repayment.

        Impact

        Conditional on an admitted callback-capable currency and enough native/WETH funding to complete the hardwired payment step, nested repayment can release the collateral lien before the outer purchase finishes and corrupt debt mirrors. The exact net extraction depends on the token's transfer hooks, funding balances, and marketplace settlement; the source-backed deletion/reuse race is distinct from the absence of a lock alone.

        Description

        buyNow registers its loan before collecting user funds or drawing senior liquidity, and performs firstRepay only after marketplace execution. Token transfers during that interval can invoke an ERC777 sender hook, while the loan facet has no reentrancy lock. A contract borrower can call ordinary repay from its downpayment sender hook twice on a three-installment loan. The second nested repayment clears and deletes the loan, but the outer buyNow continues funding and executing the purchase. It then reads a zero PMT and performs firstRepay against the deleted record instead of verifying that its original loan still exists.

    • Zetachain Go ZetaChain cross-chain modules. Tasks 12 V12 11/12 Codex Sec 4/12 Pashov Opus — Pashov GPT-6 — Devin 5/12 Devin (Deep) 8/12 Claude Sec 10/12 Claude Opus 8/12 Vercel 3/12

      ZetaChain cross-chain modules.

      Read the audit report
      • Any ZetaSent events are processed regardless of what contract emits them zetachain-1 · 7 writeups Critical

        V12

        Forged connector events authorize external treasury payments

        x/crosschain/keeper/evm_hooks.go:38 Predicted severity: High

        Root cause

        Event decoding is mistaken for emitter authentication. The Go hook grants connector-level payment authority to any contract capable of emitting the same event shape.

        Impact

        When the fungible module holds sufficient ZETA, a forged event can conditionally spend that module balance to authorize an external ZETA payment chosen by the caller. This is a producer-side authorization failure reaching u4; its amount is bounded by the module balance accepted by BurnCoins, not by a demonstrated caller-funded connector deposit.

        Description

        The ZEVM post-processing hook parses every receipt log as a possible ZetaSent event without checking its emitter against the deployed connector. ParseZetaSentEvent constructs a filterer using the log's own address, so the parser does not supply a trusted-emitter boundary. A caller-deployed contract can emit the same event signature and fields, causing ProcessZetaSentEvent to burn the specified value from the fungible module and create a PendingOutbound ZETA CCTX. The signer treats that CCTX as ZetaChain-origin and signs an external connector payment to the emitted destination. Unlike the genuine connector, the emitting contract need not have transferred wrapped ZETA into the module before creating that event.

        Codex Security (GPT-6 Sol)

        Forged ZetaSent logs can authorize an unfunded outbound

        x/crosschain/keeper/evm_hooks.go:47 Predicted severity: Medium

        Root cause

        The hook iterates every receipt log and parses ZetaSent using the log's own address. It never compares that address with the registered connector. Event amount and destination then drive a module burn and outbound CCTX.

        Impact

        The unauthorized event path is reachable to any zEVM contract caller, but a positive payout requires an existing fungible module balance, which is not established as routine.

        Description

        Any successful zEVM contract can emit a ZetaSent-shaped log; the receipt hook accepts it without checking the registered connector and can burn existing fungible module balance to create an outbound CCTX.

        Exploit scenario

        The hook iterates every receipt log and parses ZetaSent using the log's own address. It never compares that address with the registered connector. Event amount and destination then drive a module burn and outbound CCTX.

        Recommendation

        Compare the log emitter with the trusted connector address held in module state and bind the event to the connector's funded transfer.

        Devin Security

        ZetaSent events are accepted from any ZEVM contract, letting anyone spend the fungible module's ZETA on outbound transfers

        x/crosschain/keeper/evm_hooks.go:47 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who can send a ZEVM transaction can make the chain burn ZETA held by the fungible module and send that ZETA to an address they choose on an external chain, up to whatever balance the module holds.

        ##### What's wrong

        This is event spoofing. The post-transaction hook trusts a ZetaSent log based only on its event signature. It never checks that the log came from the system ZetaConnectorZEVM contract. The ZRC20 withdrawal path does check the emitter against the foreign coin list. The ZETA path does not.

        ##### Who can do it

        Alice runs a ZetaChain validator. Mallory has an ordinary ZEVM account with enough gas. Mallory deploys a contract that declares the same ZetaSent event as the connector. She calls it to emit ZetaSent with zetaValueAndGas equal to the fungible module's native ZETA balance. She sets the destination to her own address on a supported external chain. She does not transfer any ZETA to the module.

        - Mallory can send any ZEVM transaction. Deploying a contract is permissionless.

        - The fungible module account (0x735b14BB79463307AAcBED86DAf3322B1e6226aB) holds a native ZETA balance at the end of her transaction. Examples are a donation, a mistaken transfer, or leftover funds.

        - The destination chain is supported and has a gas price and chain nonce set.

        ##### What they get

        The chain burns the module's ZETA and creates a pending outbound transfer. The TSS signers then release the same amount of ZETA to Mallory on the external chain. She takes funds that belong to the protocol, or to whoever sent them to the module. The loss is limited to the module's balance when her transaction ends. Each legitimate connector send is burned in its own transaction, so it does not leave funds behind. ZETA in other accounts is not exposed.

        ##### How it works

        1. Ethermint calls PostTxProcessing for every ZEVM transaction because the crosschain keeper is registered as the EVM hook in app/app.go:445.

        2. PostTxProcessing passes every log in the receipt to ParseZetaSentEvent (x/crosschain/keeper/evm_hooks.go:54).

        3. ParseZetaSentEvent builds a filterer around log.Address, whatever contract that is. abigen's UnpackLog checks only the event signature topic (evm_hooks.go:177-188).

        4. ProcessZetaSentEvent burns event.ZetaValueAndGas from the fungible module account. It never checks that the log came from the connector or that ZETA arrived in this transaction (evm_hooks.go:120).

        5. It then builds a cross-chain transaction to the destination chain and address from the event and stores it as pending outbound (evm_hooks.go:124-137). The TSS signers then send the funds.

        Exploit scenario

        Not specified.

        Recommendation

        Process ZetaSent only when log.Address equals the stored system ZetaConnectorZEVM address, and ignore it otherwise. Track how much native ZETA the module receives in each transaction, and never burn more than that. Add a unit test where a contract that is not the connector emits a well-formed ZetaSent log. The test should check that no coins are burned and no cross-chain transaction is created.

        Devin Security (Deep)

        EVM hook accepts ZetaSent events from any contract, letting an attacker burn the fungible module's ZETA and withdraw it to a foreign chain

        x/crosschain/keeper/evm_hooks.go:47 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone who can deploy a contract on ZetaChain's EVM can emit a fake ZetaSent event and make the protocol pay out whatever ZETA the fungible module account holds at that moment, without depositing anything.

        ##### What's wrong

        This is a missing event authenticity check. The hook parses every log in every EVM receipt as a ZetaSent event and never checks that the log came from the system ZetaConnectorZEVM contract. The parallel ZRC20 withdrawal path does check the emitting address against registered coins, but the ZETA path does not.

        ##### Who can do it

        Mallory deploys a contract on the ZetaChain EVM. Her contract reads the fungible module address balance, then emits an event with the exact ZetaSent signature carrying that amount, her Ethereum address, and chain id 1. She never calls the real connector and never transfers any WZETA.

        - Mallory needs a ZetaChain account with enough ZETA for EVM gas.

        - The fungible module account must hold some ZETA; it accumulates dust from pool setup on low decimal chains and anything sent to its address, and the attacker can read the balance on chain to size the claim exactly.

        - Gas price and nonce records must exist for the destination chain, which is true for every supported chain in normal operation.

        ##### What they get

        The chain burns the claimed amount from the fungible module account and creates a pending outbound transfer, so the TSS signers send Mallory that much ZETA on Ethereum. Mallory receives protocol owned ZETA she never paid for, and the protocol also pays Ethereum gas for the outbound. The amount per attack is limited to the module account balance at the time, so the theft is capped at what the protocol lets accumulate there, but Mallory can repeat it whenever the balance is non zero. She cannot take other users' balances directly because legitimate sends are burned in the same transaction they arrive.

        ##### How it works

        1. Mallory's contract emits a log whose first topic is the ZetaSent event id and whose data encodes zetaValueAndGas equal to the fungible module balance.

        2. PostTxProcessing at x/crosschain/keeper/evm_hooks.go:47-60 iterates all receipt logs and calls ParseZetaSentEvent on each one.

        3. ParseZetaSentEvent at lines 177-188 binds a filterer to log.Address, whatever it is, and only checks the event signature, so the fake log parses successfully.

        4. ProcessZetaSentEvent at line 120 burns event.ZetaValueAndGas from the fungible module account with no check that the funds came from the connector.

        5. Lines 124-137 create a CrossChainTx for the full amount to Mallory's address on the destination chain and ProcessCCTX assigns a nonce, so zetaclient signers pay it out.

        Exploit scenario

        Not specified.

        Recommendation

        Record the system ZetaConnectorZEVM address when it is deployed (alongside the system contract address in the fungible module state) and in PostTxProcessing only call ProcessZetaSentEvent when log.Address equals that stored address. Verify by deploying a test contract that emits a ZetaSent shaped event and asserting the hook ignores it (no burn, no CCTX), while a real ZetaConnectorZEVM.send still produces a CCTX.

        Claude Security (Sonnet 5.5)

        ZetaSent event from any contract triggers a burn of fungible-module ZETA and a cross-chain transfer (emitter address not validated)

        x/crosschain/keeper/evm_hooks.go:120 Predicted severity: Low

        Root cause

        Vulnerable symbol: Keeper.ProcessZetaSentEvent

        Preconditions: The fungible module account holds a non-zero native balance at the time of the attacker's tx; The attacker can deploy a contract on ZetaChain's EVM

        Offending code:

        if err := k.bankKeeper.BurnCoins(ctx, "fungible", sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewIntFromBigInt(event.ZetaValueAndGas)))); err != nil {

        Impact

        Anyone can convert whatever native ZETA sits on the fungible module account into a cross-chain release to an address of their choice, and can burn it. Because a legitimate send burns its own funds in the same tx, the exposed amount is limited to pre-existing module balance, which I could not determine. The weakness also lets an arbitrary contract create cctxs whose recorded sender is the tx target rather than an authenticated connector call.

        Description

        PostTxProcessing runs ParseZetaSentEvent on every log of every EVM tx. The generated parser only matches the topic and ABI shape, so a log emitted by any contract is accepted, with no check that the emitter is the deployed ZetaConnectorZEVM. ProcessZetaSentEvent then burns the attacker-chosen ZetaValueAndGas from the fungible module account and creates a PendingOutbound cctx to the attacker-chosen destination. By contrast, ProcessZRC20WithdrawalEvent does check event.Raw.Address against the registered ZRC20 list.

        Exploit scenario

        The attacker deploys a contract on ZetaChain that declares and emits ZetaSent(sourceTxOrigin, sender, destChainId, destAddress, N, gasLimit, message, params) with destAddress set to their own address on a supported chain. If the fungible module account (0x735b14BB...) holds at least N azeta, the hook burns N and creates a pending outbound that the TSS fulfils on the destination chain. The attacker needs no WZETA and never calls the real connector. The module balance may come from ZETA sent directly to that address, leftover liquidity refunds or genesis balances. The hook errors, and the attacker's tx reverts, if the balance is less than N.

        Recommendation

        In PostTxProcessing and ProcessZetaSentEvent, require log.Address to equal the registered ZetaConnectorZEVM address and reject other emitters. Do this before BurnCoins and before any CCTX creation. Apply the same emitter allow-list to ProcessWithdrawalLogs.

        Claude Security (Opus 5.5)

        ZetaSent events are accepted from any contract, so anyone can burn and claim the fungible module's native ZETA as a cross-chain transfer

        x/crosschain/keeper/evm_hooks.go:54 Predicted severity: Medium

        Root cause

        Vulnerable symbol: (Keeper).PostTxProcessing

        Preconditions: The fungible module holds native ZETA, e.g. stranded by deposit-and-call flows

        Offending code:

        eZeta, err := ParseZetaSentEvent(*log)

        Impact

        Other users' stranded ZETA in the fungible module can be stolen.

        Description

        PostTxProcessing parses ZetaSent by topic only and never checks that log.Address is the system ZetaConnectorZEVM. The ZRC20 path, by contrast, checks the emitter against registered ZRC20s. Any contract can emit ZetaSent with an arbitrary value. ProcessZetaSentEvent burns that amount from the fungible module and creates an outbound CCTX to the attacker.

        Exploit scenario

        Native ZETA builds up in the fungible module, for example when a deposit-and-call target calls ZetaConnectorZEVM.send (its ZetaSent log is ignored by HandleEVMDeposit) or when ZETA is sent there directly. The attacker deploys a contract that emits ZetaSent(zetaValueAndGas = fungible balance, destinationChainId = Ethereum, destinationAddress = attacker). The hook burns the stranded ZETA and the TSS releases that amount to the attacker on Ethereum.

        Recommendation

        Only process ZetaSent logs whose Address equals the registered ZetaConnectorZEVM. Also process ZetaSent logs in the HandleEVMDeposit path, or reject them there.

        Vercel Security Review

        Forged ZetaSent logs authorize withdrawals funded by the fungible module

        x/crosschain/keeper/evm_hooks.go:54 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Arbitrary contract logs enter the trusted withdrawal hook** - x/crosschain/keeper/evm_hooks.go:54-57

        ```go title="x/crosschain/keeper/evm_hooks.go:54-57"

        eZeta, err := ParseZetaSentEvent(*log)

        if err == nil {

        if err := k.ProcessZetaSentEvent(ctx, eZeta, target, ""); err != nil {

        return err

        ```

        Any ZEVM caller can emit an ABI-compatible ZetaSent from its own contract. The emitter is never compared with the deployed connector.

        **2. The forged amount burns shared funds instead of charging the emitter** - x/crosschain/keeper/evm_hooks.go:120-123

        ```go title="x/crosschain/keeper/evm_hooks.go:120-123"

        if err := k.bankKeeper.BurnCoins(ctx, "fungible", sdk.NewCoins(sdk.NewCoin(config.BaseDenom, sdk.NewIntFromBigInt(event.ZetaValueAndGas)))); err != nil {

        fmt.Printf("burn coins failed: %s\n", err.Error())

        return fmt.Errorf("ProcessWithdrawalEvent: failed to burn coins from fungible: %s", err.Error())

        }

        ```

        Whenever fungible holds ZETA, including residual pool-setup funds, this succeeds without a connector transfer.

        **3. Attacker-selected parameters become a payable outbound command** - x/crosschain/keeper/evm_hooks.go:133-135

        ```go title="x/crosschain/keeper/evm_hooks.go:133-135"

        msg := zetacoretypes.NewMsgSendVoter("", contract.Hex(), senderChain.ChainId, txOrigin, toAddr, receiverChain.ChainId, amount, "", event.Raw.TxHash.String(), event.Raw.BlockNumber, 90000, common.CoinType_Zeta, "")

        sendHash := msg.Digest()

        cctx := k.CreateNewCCTX(ctx, msg, sendHash, zetacoretypes.CctxStatus_PendingOutbound, &senderChain, receiverChain)

        ```

        Normal signing pays the attacker's destination, stealing up to the module's available ZETA.

        Exploit scenario

        Not specified.

        Recommendation

        Reject ZetaSent logs unless event.Raw.Address equals the canonical deployed ZEVM connector. Preserve the connector's transfer-and-burn accounting and ensure no untrusted caller can choose a substitute emitter merely by supplying an ABI-compatible event.

      • Bonded validators can trigger reverts for successful transactions zetachain-2 · 7 writeups Critical

        V12

        Single validators can erase live outbound evidence

        x/crosschain/keeper/keeper_out_tx_tracker.go:200 Predicted severity: High

        Root cause

        The single-validator cleanup entrypoint permits destruction of live shared confirmation evidence without any lifecycle guard. Global role admission is treated as sufficient authority to delete outstanding candidates belonging to the entire observer set.

        Impact

        Inference under adversarial transaction ordering: repeated deletion of an outstanding tracker can deny honest observers the transaction evidence needed for confirmation and temporarily freeze withdrawal completion. Deletion after observers have already cached the transaction does not establish this effect, so the supported attack window is before their polling loop consumes each published candidate.

        Description

        RemoveFromOutTxTracker grants every bonded validator deletion authority over the entire tracker named by the supplied chain and nonce. It does not require outbound-ballot finalization, a completed CCTX, or a relationship between the caller and the stored candidates. RemoveOutTxTracker then deletes the exact record, including candidates submitted by other validators. Both external-chain observers discover outbound transactions through these records, while outbound signing publishes transaction hashes back into the same store. A validator acting alone can repeatedly remove newly published evidence before observers consume it, independently of the quorum-protected ordinary finalization path.

        Codex Security (GPT-6 Sol)

        Validator tracker entry can falsely fail a pending outbound

        x/crosschain/keeper/keeper_out_tx_tracker.go:158 Predicted severity: High

        Root cause

        AddToOutTxTracker checks validator bond status and supported chain but does not prove a hash belongs to a pending CCTX. The EVM client retrieves each tracker hash and stores its receipt by the tracker-provided nonce without checking the transaction sender or actual nonce. A failed receipt prompts a failure vote for the CCTX at that nonce, and the keeper finalizes/reverts it.

        Impact

        A single bonded validator can induce honest quorum votes and a false revert of funds; double payout requires the genuine outbound to execute as well.

        Description

        A bonded validator can attach an unrelated failed EVM transaction hash to a pending CCTX nonce; honest observers cache it under that nonce and vote failure, which can start a revert despite the genuine outbound.

        Exploit scenario

        AddToOutTxTracker checks validator bond status and supported chain but does not prove a hash belongs to a pending CCTX. The EVM client retrieves each tracker hash and stores its receipt by the tracker-provided nonce without checking the transaction sender or actual nonce. A failed receipt prompts a failure vote for the CCTX at that nonce, and the keeper finalizes/reverts it.

        Recommendation

        Bind tracker entries to a pending CCTX and verify external transaction sender, actual nonce, destination and expected payload before caching or voting; recheck chain and nonce in the keeper.

        Devin Security

        Out-tx trackers can be removed by any bonded validator or a hardcoded admin address

        x/crosschain/keeper/keeper_out_tx_tracker.go:200 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        One bonded validator, or whoever holds a hardcoded admin key, can delete or pollute the outbound transaction trackers for any chain and nonce, which delays outbound confirmations.

        ##### What's wrong

        The authorization is too broad. AddToOutTxTracker and RemoveFromOutTxTracker accept any bonded validator. They also accept a fixed address compiled into the binary (types.AdminKey). Removal needs no vote and does not check whether the transaction finished.

        ##### Who can do it

        Mallory runs one bonded validator, or she has the private key for the hardcoded admin address. She sends MsgRemoveFromOutTxTracker for pending nonces on a chain.

        - Mallory controls a bonded validator operator account, or the key for types.AdminKey (x/crosschain/types/keys.go:84).

        ##### What they get

        Observers use the trackers to find signed outbound transactions. Deleting them, or flooding them with fake hashes, slows or blocks confirmation of pending withdrawals until the trackers are added again. No funds move.

        ##### How it works

        1. Both handlers accept a bonded validator or the hardcoded admin address (keeper_out_tx_tracker.go:162, :204).

        2. RemoveFromOutTxTracker deletes the tracker for the chain ID and nonce in the message (keeper_out_tx_tracker.go:208).

        Exploit scenario

        Not specified.

        Recommendation

        Remove the hardcoded AdminKey bypass and use the observer admin policy account. Allow tracker removal only through the outbound vote finalization path or the admin policy account. Add tests that a bonded validator that is not an observer cannot remove a tracker.

        Devin Security (Deep)

        Any bonded validator can inject arbitrary tx hashes into the outbound tracker and make every observer forge an outbound success or failure vote

        x/crosschain/keeper/keeper_out_tx_tracker.go:158 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A single bonded validator (or whoever holds the hardcoded admin key) can plant a foreign transaction hash in the outbound tracker and make every honest observer vote that a cross-chain transfer failed or succeeded, which lets the validator get paid twice for a transfer or make other users' transfers never arrive and stall all outbound traffic on that chain.

        ##### What's wrong

        This is a trust-boundary bug: the chain accepts unverified outbound transaction hashes from any bonded validator, and the observer client treats whatever hash is in the tracker as the real outbound transaction. AddToOutTxTracker only checks that the sender is a bonded validator or equals the hardcoded AdminKey; it never checks that the hash belongs to the transaction the TSS signed for that chain and nonce. The observer client (zetaclient/evm_client.go observeOutTx and queryTxByHash) fetches the receipt for each tracker hash and records it for that nonce without checking that the transaction was sent by the TSS address or carries that nonce. IsSendOutTxProcessed then votes on the cross-chain transaction using that receipt. RemoveFromOutTxTracker has the same weak gate and lets the same caller delete any tracker.

        ##### Who can do it

        Alice uses the ZetaChain bridge at Acme Corp to send ZETA from chain A to chain B. Mallory runs a bonded validator on ZetaChain (she staked enough to enter the active set; the staking module does not restrict who can create a validator). Mallory also sends her own transfers through the bridge. When a cross-chain transaction for chain B with TSS nonce N becomes pending, Mallory submits MsgAddToOutTxTracker for (chain B, N) with the hash of any already confirmed transaction on chain B that she chooses, for example an old reverted transaction or a transfer she made with a specific value.

        Conditions:

        - Mallory controls an account that is a bonded validator operator (IsBondedValidator) or the private key for the hardcoded AdminKey address.

        - A cross-chain transaction is pending outbound on an EVM or Bitcoin chain, so a tracker (chain, nonce) is relevant.

        - The planted hash is confirmed on the target chain before the real TSS transaction reaches the confirmation depth, or is the first hash in the tracker list.

        ##### What they get

        Mallory can get paid twice. She sends ZETA from chain A to herself on chain B. The TSS broadcasts the real outbound and she receives the ZETA on chain B. Before that transaction is confirmed by the observers, she plants the hash of a failed transaction for that nonce. Every honest observer records the failed receipt for nonce N, votes "failed", the ballot finalizes, and the chain creates a revert that pays her original amount back on chain A. She repeats this for every transfer she makes and drains value that belongs to all bridge users. If she plants the hash early enough that observers record it before they sign, the real outbound is never signed: Alice's funds never arrive on chain B even though the transaction is marked mined, and the TSS nonce N is skipped so every later outbound on chain B is stuck behind the gap. With RemoveFromOutTxTracker she can also keep deleting trackers so observers never find real outbound receipts and transfers never finalize.

        ##### How it works

        1. Mallory, a bonded validator, sends MsgAddToOutTxTracker with an arbitrary TxHash for (chain, nonce); AddToOutTxTracker in x/crosschain/keeper/keeper_out_tx_tracker.go:158-198 only checks IsBondedValidator or AdminKey and appends the hash.

        2. Each honest observer's observeOutTx in zetaclient/evm_client.go:377-424 reads the tracker, calls queryTxByHash (evm_client.go:430-458), and stores the receipt and transaction for that nonce once it is confirmed, with no check that transaction.From is the TSS address or that transaction.Nonce equals the tracker nonce.

        3. queryTxByHash returns early once a receipt is recorded for the nonce (evm_client.go:432), so the planted receipt is never replaced by the real one.

        4. IsSendOutTxProcessed in evm_client.go:210-373 posts MsgVoteOnObservedOutboundTx using the planted receipt: status 0 becomes a "failed" vote, status 1 becomes a "success" vote with the planted transaction's value.

        5. VoteOnObservedOutboundTx in x/crosschain/keeper/keeper_cross_chain_tx_vote_outbound_tx.go:15-83 finalizes the ballot once enough observers submit the identical vote; a failed vote runs FinalizeOutbound which creates a revert payout to the original sender (keeper_cross_chain_tx_vote_outbound_tx.go:121-141).

        6. The send scheduler in zetaclient/zetacore_observer.go:203-211 skips signing whenever IsSendOutTxProcessed reports the nonce as included, so a planted receipt also suppresses the real outbound and leaves a nonce gap.

        7. RemoveFromOutTxTracker at keeper_out_tx_tracker.go:200-210 lets the same caller delete any tracker by (chainId, nonce) with no ownership or status check.

        Exploit scenario

        Not specified.

        Recommendation

        Treat tracker hashes as hints, never as proof. In the observer client, after fetching the transaction for a tracker hash, require transaction.From == TSS address (recover the sender with the chain signer) and transaction.Nonce == tracker.Nonce before recording the receipt, and do the same check for Bitcoin (verify the spent UTXO belongs to the TSS address). On the chain side, restrict AddToOutTxTracker and RemoveFromOutTxTracker to observers of that chain (reuse IsAuthorized), require the (chain, nonce) to match a pending cross-chain transaction, remove the hardcoded AdminKey in favor of the admin policy parameters, and cap the length of HashList. Verify the fix by adding a confirmed non-TSS transaction hash to a tracker in a localnet and checking that observers ignore it and still confirm the real TSS transaction.

        Claude Security (Sonnet 5.5)

        Out-tx tracker add/remove is authorized for any bonded validator instead of the chain's observers, with no binding to the TSS tx

        x/crosschain/keeper/keeper_out_tx_tracker.go:162 Predicted severity: Medium

        Root cause

        Vulnerable symbol: msgServer.AddToOutTxTracker

        Preconditions: Attacker operates a bonded validator

        Offending code:

        if !IsBondedValidator(msg.Creator, validators) && msg.Creator != types.AdminKey {

        Impact

        One validator can inject arbitrary hashes for arbitrary nonces (feeding the forged-confirmation issue in zetaclient), spam the store with unlimited tracker entries, or delete the entries zetaclients need to confirm real outbounds (a deleted entry is not re-added once the broadcast returns 'nonce too low'), leaving cctxs pending forever.

        Description

        AddToOutTxTracker and RemoveFromOutTxTracker only require the signer to be a bonded validator (or the hard-coded AdminKey); they do not require observer membership for the chain, do not validate chain/nonce against a pending cctx or the tx hash format, and let one validator delete any other entry. Zetaclients treat these entries as authoritative.

        Exploit scenario

        A bonded validator broadcasts MsgRemoveFromOutTxTracker for (chain, nonce) right after the TSS broadcast; observers never learn the tx hash, the cctx stays PendingOutbound and is repeatedly re-signed.

        Recommendation

        Authorize with IsAuthorized for the chain's observer set (or only TSS signers), require the nonce to correspond to a pending cctx on that chain, bound hash-list length, and drop AdminKey backdoor writes or gate them behind governance.

        Claude Security (Opus 5.5)

        Outbound tracker can be written by any bonded validator or a hard-coded AdminKey, and observers trust it

        x/crosschain/keeper/keeper_out_tx_tracker.go:162 Predicted severity: High

        Root cause

        Vulnerable symbol: AddToOutTxTracker

        Preconditions: Attacker is a bonded validator (not necessarily an observer) or holds the AdminKey private key; zetaclient observers consume tracker hashes as shown in zetaclient/evm_client.go and bitcoin_client.go

        Offending code:

        if !IsBondedValidator(msg.Creator, validators) && msg.Creator != types.AdminKey {

        Impact

        Holders of a broadly available role (bonded validator) or a baked-in admin key can make the honest observer quorum vote false outbound outcomes. The result is fund loss through double payouts or cancelled transfers, and stuck nonces.

        Description

        MsgAddToOutTxTracker (chain, nonce, arbitrary TxHash) is accepted from any bonded validator, whether or not it is an observer or TSS signer for that chain, and from a hard-coded address (types.AdminKey, x/crosschain/types/keys.go:84). Nothing ties the hash to the TSS sender or to the nonce. zetaclient observers take tracker hashes as the authoritative outbound transaction for that nonce and vote on its receipt.

        Exploit scenario

        An attacker gets a bonded validator seat by staking enough to enter the active set; this does not make them an observer. They read the next TSS nonce N for an EVM chain from ChainNonces. Before the TSS signer reports its own hash, they call AddToOutTxTracker(chain, N, H), where H is any confirmed reverted transaction on that chain. Every honest observer records H as the outbound for nonce N and votes Failure, the ballot finalizes, and the cctx moves to revert and is refunded. The real TSS transaction for nonce N can still be mined, so the funds are paid out twice. If H is instead a successful transfer of exactly the cctx amount, the victim's cctx is marked OutboundMined without ever being sent. The holder of the hard-coded AdminKey can do the same on any deployment.

        Recommendation

        Allow only observers authorized for msg.ChainId (IsAuthorized against the chain's observer mapper) to write the tracker, and remove the hard-coded AdminKey bypass, or replace it with a governance- or policy-controlled account. Also have clients check that a tracker transaction is signed by the TSS address with the expected nonce before using it.

        Vercel Security Review

        Unverified tracker hashes let one validator forge outbound confirmations

        x/crosschain/keeper/keeper_out_tx_tracker.go:179 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. A validator can nominate an unrelated transaction for any nonce** - x/crosschain/keeper/keeper_out_tx_tracker.go:179-182

        ```go title="x/crosschain/keeper/keeper_out_tx_tracker.go:179-182"

        ChainId: chain.ChainId,

        Nonce: msg.Nonce,

        HashList: []*types.TxHashList{&hash},

        })

        ```

        One bonded validator can prepopulate a future withdrawal's tracker with a confirmed self-transfer.

        **2. Honest observers accept its claimed identity** - zetaclient/evm_client.go:400-403

        ```go title="zetaclient/evm_client.go:400-403"

        if err == nil && receipt != nil { // confirmed

        ob.mu.Lock()

        ob.outTXConfirmedReceipts[int(nonceInt)] = receipt

        ob.outTXConfirmedTransaction[int(nonceInt)] = transaction

        ```

        queryTxByHash checks maturity, not TSS sender, transaction nonce, or recipient (evm_client.go:438-457). The cache uses the tracker's nonce.

        **3. The unrelated payment produces success votes** - zetaclient/evm_client.go:227-230

        ```go title="zetaclient/evm_client.go:227-230"

        transaction.Value(),

        common.ReceiveStatus_Success,

        ob.chain,

        nonce,

        ```

        For native withdrawals, matching the victim's amount suffices. The keeper finalizes the unpaid CCTX using honest observers' votes, leaving the victim's burned ZRC20 without payment.

        Exploit scenario

        Not specified.

        Recommendation

        Treat tracker hashes as untrusted hints. Before caching or confirming, recover and verify the expected TSS sender, chain ID, actual transaction nonce, recipient, value, and operation against the pending CCTX. Validate authoritative contract addresses and event parameters for token withdrawals as well.

      • Sending ZETA to a Bitcoin network results in BTC being sent instead zetachain-3 · 3 writeups Critical

        V12

        ZETA sends spend native Bitcoin custody

        x/crosschain/keeper/evm_hooks.go:117 Predicted severity: Critical

        Root cause

        Bitcoin dispatch and signing lack a native-gas-coin eligibility check. TryProcessOutTx assumes all Bitcoin-targeted CCTX amounts are BTC satoshis although the producer also creates ZETA-denominated CCTXs for that destination.

        Impact

        A user can request a Bitcoin-targeted ZETA send and receive native BTC from TSS custody without burning the corresponding BTC-backed ZRC20. The supported failure path is direct custody-value substitution; availability of sufficient Bitcoin reserves and a functioning TSS signing quorum are the execution preconditions.

        Description

        The Bitcoin outbound handler treats every scheduled CCTX amount as satoshis and passes CoinType_Gas to its processed-state check, without checking the CCTX's actual coin type or origin. ProcessZetaSentEvent can create a Bitcoin-targeted PendingOutbound CCTX with CoinType_Zeta and an amount denominated in base ZETA units. ProcessCCTX copies that amount unchanged into the outbound parameters, and the scheduler dispatches by receiver chain rather than coin type. The Bitcoin signer therefore constructs a native BTC payment for the numerical ZETA amount. For example, an amount of 100000000 base ZETA units is interpreted as one BTC when sufficient custody inputs exist.

        Claude Security (Sonnet 5.5)

        BTC signer pays out CCTX.Amount as satoshis without checking CoinType, so ZETA-denominated (18-decimal) CCTXs drain the BTC reserve

        zetaclient/btc_signer.go:227 Predicted severity: High

        Root cause

        Vulnerable symbol: BTCSigner.TryProcessOutTx

        Preconditions: A Bitcoin chain is enabled in the observer params and the zetaclient; The BTC gas price and chain nonce are registered, which happens in normal operation; The TSS BTC address holds UTXOs

        Offending code:

        tx, err := signer.SignWithdrawTx(to, float64(send.GetCurrentOutTxParam().Amount.Uint64())/1e8, float64(gasprice.Int64())/1e8*1024, btcClient.utxos, btcClient.pendingUtxos)

        Impact

        Theft of BTC custody funds, up to the TSS UTXO balance, for a negligible ZETA cost. The result is a cross-chain accounting break and loss of the BTC reserve.

        Description

        TryProcessOutTx never checks send.GetCurrentOutTxParam().CoinType or the origin of the CCTX. It divides Amount by 1e8 and TSS-signs a BTC payment to the receiver. The Receiver, which is the destination address bytes chosen by the user, goes straight into btcutil.DecodeAddress. Zetacore builds CCTXs for any supported destination from user-controlled ZetaSent events, with CoinType_Zeta and Amount in wei (18 decimals). The BTC signer therefore treats 1 wei of ZETA as 1 satoshi.

        Exploit scenario

        On a deployment where a Bitcoin chain is supported and has a gas price and nonce registered, a zEVM user calls ZetaConnectorZEVM.send() with destinationChainId set to the BTC chain ID and destinationAddress set to the ASCII bytes of their own bech32 P2WPKH address. zetaValueAndGas is 1e9 wei, which is 1e-9 ZETA. ConnectorZEVM.sol has no destination check. evm_hooks.go ProcessZetaSentEvent and ProcessCCTX create a PendingOutbound CCTX for BTC with CoinType_Zeta and Amount=1e9 and apply no fee, coin-type or chain checks. Every BTC zetaclient then signs and broadcasts a 10 BTC payment from the TSS UTXO pool to the attacker.

        Recommendation

        In BTC TryProcessOutTx, accept only CoinType_Gas CCTXs whose receiver chain is a Bitcoin chain, and reject everything else. Also reject Zeta-to-BTC routes in zetacore (ProcessZetaSentEvent and the inbound vote handler). Validate receiver format and amount bounds before signing.

        Claude Security (Opus 5.5)

        BTC signer ignores CCTX CoinType and pays out ZETA-denominated (azeta) amounts as BTC satoshis

        zetaclient/btc_signer.go:227 Predicted severity: Critical

        Root cause

        Vulnerable symbol: BTCSigner.TryProcessOutTx

        Preconditions: Bitcoin chain is enabled in zetaclient and supported in observer params (normal for a BTC deployment); ZetaConnectorZEVM is deployed on zEVM and the BTC gas price and nonce are posted (normal operation)

        Offending code:

        tx, err := signer.SignWithdrawTx(to, float64(send.GetCurrentOutTxParam().Amount.Uint64())/1e8, float64(gasprice.Int64())/1e8*1024, btcClient.utxos, btcClient.pendingUtxos)

        Impact

        Anyone can steal the whole BTC reserve held by the TSS address. Each satoshi costs one azeta (1e-18 ZETA).

        Description

        Any user can create a CoinType_Zeta CCTX to the BTC chain by calling ZetaConnectorZEVM.send; its Amount is in azeta (18 decimals). BTCSigner.TryProcessOutTx never checks CoinType or status and treats that Amount as satoshis, so the TSS signs a real BTC payment of that many satoshis. Also CWE-1287: BTCSigner.TryProcessOutTx never checks the CCTX's CoinType. It treats GetCurrentOutTxParam().Amount as satoshis for every CCTX routed to the BTC chain. A CoinType_Zeta CCTX whose amount is in azeta (1e-18 ZETA), created by anyone through ZetaConnectorZEVM.send with a BTC destinationChainId, therefore makes the TSS sign a native BTC payment of amount/1e8 BTC to an address the attacker chooses.

        Exploit scenario

        On zEVM the attacker wraps 1e8 azeta (1e-10 ZETA) into WZETA, approves ZetaConnectorZEVM, and calls send({destinationChainId: <BTC chain id>, destinationAddress: bytes("tb1q<attacker p2wpkh>"), zetaValueAndGas: 1e8, ...}). The PostTxProcessing hook burns the 1e8 azeta and creates a PendingOutbound CCTX to BTC with CoinType_Zeta and Amount=1e8. Every zetaclient schedules it on the BTC signer, which reads Amount=1e8 as 1e8 sats (1 BTC). It selects TSS UTXOs, TSS-signs a 1 BTC payment to the attacker, broadcasts it, and records it in the tracker. Repeating this drains the TSS BTC reserve for almost no ZETA.

        Recommendation

        In BTCSigner.TryProcessOutTx, refuse any CCTX unless CoinType == CoinType_Gas, the sender chain is ZetaChain or the status is a valid revert, and the amount is denominated in sats. Also make zetacore's ProcessZetaSentEvent reject Zeta transfers to chains that have no ZETA connector, such as Bitcoin. Also CWE-1287: In BTCSigner.TryProcessOutTx, reject any CCTX whose outbound CoinType is not CoinType_Gas, and check that the receiver chain matches the asset. In zetacore, reject ZetaSent or ZRC20 withdrawals to non-EVM chains that cannot carry that coin type. Bound-check and convert amounts by coin type before signing.

      • Race condition in Bitcoin client leads to double spend zetachain-4 · 1 writeup Critical

        V12

        Bitcoin retries can pay withdrawals repeatedly

        zetaclient/btc_signer.go:44 Predicted severity: High

        Root cause

        Bitcoin outbound idempotency depends entirely on post-broadcast tracker publication. The signer has no durable CCTX-to-signed-transaction mapping and treats absence from the tracker-derived cache as permission to create another payment.

        Impact

        A funded Bitcoin withdrawal can pay its recipient more than once when the first payment succeeds but tracker publication fails or remains invisible before a retry. Each separately funded Bitcoin transaction can consume additional TSS reserves, so this is a conditional reserve-loss path, not just redundant signing.

        Description

        A Bitcoin attempt creates and signs a new transaction from currently available UTXOs, broadcasts it, and only then submits its hash to the core tracker. If that tracker submission fails, the attempt merely logs the error and ends, releasing its active ID. BitcoinChainClient.IsSendOutTxProcessed recognizes an attempt only through submittedTx, which is populated from core tracker hashes, not from the signer's successful broadcast. On the next scheduling pass the same pending CCTX can therefore select different UTXOs and broadcast another payment. Neither the CCTX nonce nor its hash is included as an enforceable Bitcoin replay constraint, and the signer does not retain and rebroadcast the original transaction for that CCTX.

      • Not waiting for minimum number of block confirmations results in double spend zetachain-5 · 4 writeups Critical

        V12

        Unsettled Bitcoin deposits can retain unbacked credits

        zetaclient/bitcoin_client.go:69 Predicted severity: High

        Root cause

        Inbound observation equates inclusion at the current Bitcoin tip with settlement and stores only a height. No confirmation policy or reorganization reconciliation guards financial credit.

        Impact

        A short Bitcoin reorganization can leave minted BTC-backed ZRC20 without the underlying TSS payment, creating conditional fund loss if that credit is spent or withdrawn. Exploiting this requires a replaced deposit block and enough observer votes before replacement; the code does not require an individual observer to bypass the ballot threshold.

        Description

        The Bitcoin inbound scanner processes every height through the current RPC tip without enforcing a confirmation depth or checking block continuity. NewBitcoinClient sets confCount to zero, and observeInTx does not use even that field or the fetched block's confirmation count. Once it submits a payment, it advances past that height without retaining the block hash for reorganization detection. Finalized core votes call HandleEVMDeposit, which credits the reported amount through the fungible module. A payment observed on a block that is later replaced can consequently retain its ZEVM credit despite disappearing from Bitcoin's canonical chain.

        Codex Security (GPT-6 Sol)

        Bitcoin deposits are credited at the current tip before reorg safety

        zetaclient/bitcoin_client.go:205 Predicted severity: Medium

        Root cause

        The Bitcoin inbound loop advances one block whenever count exceeds the cursor, including the current tip. It immediately posts each matching transaction and advances the cursor without waiting for depth or reconciling a later replacement block.

        Impact

        A shallow Bitcoin reorganization could leave credited assets unbacked, but attacker ability to induce such a reorg and a non-regtest deployment are unproven.

        Description

        The Bitcoin observer reports a deposit as soon as it appears in the next tip block, allowing an observer quorum to credit or route assets before the deposit survives confirmations.

        Exploit scenario

        The Bitcoin inbound loop advances one block whenever count exceeds the cursor, including the current tip. It immediately posts each matching transaction and advances the cursor without waiting for depth or reconciling a later replacement block.

        Recommendation

        Wait for a configured Bitcoin confirmation depth before voting, persist observed block hashes, and reconcile votes and cursor state after reorganization.

        Devin Security

        Bitcoin deposits are reported after a single confirmation, so a block reorg can mint unbacked BTC on ZetaChain

        zetaclient/bitcoin_client.go:205 Predicted severity: Medium

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        An attacker who can get a deposit block orphaned can be credited BTC on ZetaChain for a deposit that no longer exists on Bitcoin, which drains the pooled BTC reserve.

        ##### What's wrong

        This is a missing confirmation depth check. The Bitcoin inbound watcher processes block lastBN+1 as soon as the chain tip reaches it. That includes the tip block itself, which has only one confirmation, and there is no configured confirmation depth.

        ##### Who can do it

        Mallory sends BTC to the TSS address (the shared signing key of the observers) with a memo, and every observer reports it right away. She then broadcasts a conflicting spend of the same coins. If the deposit's block is orphaned, through a natural one-block reorg race or with hash power she rents, her deposit disappears from Bitcoin. Her ZRC20 BTC on ZetaChain stays.

        - Mallory needs a BTC wallet.

        - The block holding her deposit must be reorganized out. This happens naturally at the tip from time to time, or she can pay for hash power. That cost is the main barrier.

        ##### What they get

        Mallory keeps ZRC20 BTC that has no BTC behind it. She can withdraw it to drain BTC that other users deposited into the TSS address. The loss is limited by how often she can win a reorg.

        ##### How it works

        1. observeInTx processes block lastBN+1 whenever GetBlockCount() > lastBN, without subtracting any confirmation depth (zetaclient/bitcoin_client.go:205-239).

        2. FilterAndParseIncomingTx accepts any transaction in that block that pays the TSS address and carries an OP_RETURN memo (zetaclient/bitcoin_client.go:387-470).

        3. PostSend votes the deposit to zetacore right away (zetaclient/bitcoin_client.go:247-261), and progress moves past the block without any later reorg check (line 269).

        Exploit scenario

        Not specified.

        Recommendation

        Process block bn only when cnt - bn + 1 >= confirmations, with the confirmation count set per network (for example 6 on mainnet), as the EVM observer does with confCount. Apply the same rule to outbound confirmation, where Confirmations > 0 is marked FIXME. To verify, write a unit test showing that a block at the tip is not processed until enough blocks are on top of it.

        Devin Security (Deep)

        Bitcoin deposits are credited after a single confirmation with no reorg handling, allowing unbacked BTC ZRC20 mints

        zetaclient/bitcoin_client.go:205 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can get BTC ZRC20 minted on ZetaChain for a Bitcoin deposit that later disappears in a one-block reorg, and then withdraw real BTC that belongs to other depositors; this needs a stale Bitcoin block to occur, which is rare on mainnet but common on testnet.

        ##### What's wrong

        This is a missing confirmation depth check. The Bitcoin observer scans and votes on a block as soon as it becomes the chain tip (one confirmation), ignores its own confCount field, and only ever moves forward by block number, so a deposit in a block that is later orphaned is still credited and is never re-checked.

        ##### Who can do it

        Mallory, anyone with a Bitcoin wallet, sends a replace-by-fee enabled deposit to the TSS address with a valid memo naming her zEVM address. Every observer sees the tx in the newest block, immediately calls PostSend, and the inbound vote finalizes and mints BTC ZRC20 to her. Mallory watches the Bitcoin network; if the block containing her deposit becomes stale (a natural one-block reorg, or one she encourages by broadcasting the deposit to only part of the network), she immediately broadcasts a conflicting higher-fee spend of the same inputs so the deposit is never re-mined. She can repeat this at the cost of Bitcoin fees until a reorg lands.

        - Bitcoin must be an enabled inbound chain (it is in the default mainnet and testnet chain lists).

        - A reorg must orphan the block that contained the deposit. On Bitcoin mainnet this happens a few times per year; on testnet it happens frequently.

        - The attacker must prevent the deposit from being re-included (RBF or a conflicting spend).

        ##### What they get

        Mallory ends up holding BTC ZRC20 on ZetaChain with no BTC behind it. She calls withdraw on the BTC ZRC20, and the TSS signer pays her real BTC out of the pooled UTXOs that other users deposited. Every repeat drains more of the shared BTC reserve, so honest depositors like Alice eventually cannot withdraw. On testnet this is nearly free to pull off; on mainnet it is a low-probability but repeatable lottery with a payout equal to the deposit size.

        ##### How it works

        1. observeInTx in zetaclient/bitcoin_client.go:205-222 fetches block lastBN+1 as soon as GetBlockCount() exceeds lastBN, so the tip block (one confirmation) is processed; ob.confCount (set to 0 at line 73) is never consulted.

        2. FilterAndParseIncomingTx at line 239 extracts deposits to the TSS address from that block.

        3. Lines 241-267 call PostSend for each deposit, which becomes a MsgVoteOnObservedInboundTx; once the observer threshold is reached, HandleEVMDeposit in x/crosschain/keeper/evm_deposit.go:25-29 mints BTC ZRC20 to the memo address.

        4. Line 269 sets lastBlock = bn by height only; if block bn is later orphaned the observer fetches the new block at bn+1 and never revisits bn, so the credit is never reversed.

        5. The attacker burns the unbacked ZRC20 via ZRC20.withdraw, and BTCSigner.SignWithdrawTx in zetaclient/btc_signer.go:44-111 spends pooled TSS UTXOs to pay her.

        Exploit scenario

        Not specified.

        Recommendation

        Require a configurable confirmation depth for Bitcoin inbound observation: only process block bn when GetBlockCount() - bn >= confCount with a sensible default (for example 6 on mainnet), and remove the hardcoded confCount = 0. Additionally track the processed block hash and, when the hash at lastBlock no longer matches the node's hash for that height, roll lastBlock back and re-scan. To verify: in regtest, mine a block containing a deposit, invalidate it with invalidateblock, mine a competing chain without the deposit, and confirm no MsgVoteOnObservedInboundTx is posted until the deposit reaches the configured depth on the canonical chain.

      • Multiple events in the same transaction causes loss of funds and chain halting zetachain-6 · 4 writeups Critical

        V12

        Identical withdrawal events overwrite allocated outbound commands

        x/crosschain/keeper/evm_hooks.go:47 Predicted severity: High

        Root cause

        Withdrawal identity omits the event position although nonce allocation happens per event. Store writes overwrite a previous pending command without detecting the duplicate or reconciling its allocated nonce and burned amount.

        Impact

        A funded contract can issue identical withdrawals within one ZEVM transaction and create a missing TSS nonce, blocking subsequent EVM withdrawals on that destination. The same overwrite also collapses multiple burned withdrawal amounts into one pending payment command; automatic recovery or reconciliation for the lost command was not found in the examined producer, scheduler, scrubber, and finalizer paths.

        Description

        Withdrawal CCTX identity is derived from MsgVoteOnObservedInboundTx.Digest, which contains the transaction hash but no event log index. Both withdrawal hook paths iterate all receipt logs, and identical withdrawal events within one transaction produce identical message fields and therefore the same CCTX index. Each event nevertheless calls UpdateNonce and stores a new pending CCTX under that index. The later event overwrites the earlier record while consuming another outbound nonce. On an EVM destination, the surviving higher-nonce transfer cannot execute before the lower nonce for which the pending command has been lost.

        Claude Security (Sonnet 5.5)

        ZEVM withdrawal CCTX index is a content hash; identical withdrawals overwrite each other, orphan a TSS nonce and deadlock the chain's outbound queue

        x/crosschain/keeper/evm_hooks.go:159 Predicted severity: High

        Root cause

        Vulnerable symbol: Keeper.ProcessCCTX

        Preconditions: Attacker holds a small amount of a ZRC20 plus the gas ZRC20 on ZEVM (obtainable through any normal deposit or a swap); Target chain is an EVM chain whose TSS account requires sequential nonces

        Offending code:

        k.SetCrossChainTx(ctx, cctx)

        Impact

        A single transaction by any user creates a permanent nonce hole for the destination chain: the cctx with nonce N+1 is signed and broadcast but never mined because the TSS account nonce is stuck at N, and every later outbound on that chain queues behind it. Outbound processing for the chain (ZETA, ERC20 and gas withdrawals of all users) is frozen until governance/manual intervention. The overwritten withdrawal's ZRC20 is also burned without any outbound (loss for the sender). The same collision happens across different inbound deposit-and-call transactions because logs produced by CallEVMWithData carry an all-zero TxHash, so identical withdrawals triggered by different deposits also collide.

        Description

        ProcessZRC20WithdrawalEvent/ProcessZetaSentEvent derive the cctx Index from msg.Digest() (a hash of sender, receiver, amount, coin, in_tx_hash with Creator and height zeroed) and ProcessCCTX allocates a fresh nonce via UpdateNonce before writing the cctx under that Index. Two identical events in the same tx (same TxHash) produce the same Index, so the second SetCrossChainTx overwrites the first while both consumed a nonce.

        Exploit scenario

        1) Deploy helper H on ZEVM with function twice(zrc20,to,amt){ zrc20.withdraw(to,amt); zrc20.withdraw(to,amt); }. 2) Fund H with 2*(amt+gasFee) of ZRC20/gas ZRC20 and call twice(). 3) PostTxProcessing sees two identical Withdrawal logs, creating two cctxs with equal Index and nonces N and N+1; the store keeps only the N+1 one. 4) The signer broadcasts nonce N+1 on the external chain; it never confirms because nonce N is never filled, blocking all later nonces.

        Recommendation

        Make the cctx index unique (include log index/event sequence and a per-chain counter) and refuse to overwrite an existing cctx; allocate the nonce only after confirming the index is new. Add a recovery path for orphaned nonces.

        Claude Security (Opus 5.5)

        Identical zEVM withdrawal events produce the same CCTX index, so one overwrites the other and leaves a permanent TSS nonce gap

        x/crosschain/keeper/evm_hooks.go:111 Predicted severity: High

        Root cause

        Vulnerable symbol: ProcessZRC20WithdrawalEvent

        Preconditions: The attacker can pay ZRC20 withdraw gas fees on zEVM

        Offending code:

        sendHash := msg.Digest()

        Impact

        Any zEVM user can permanently halt all outbound transfers to a chosen EVM chain at very low cost. The overwritten withdrawal's funds are also lost.

        Description

        The CCTX index is msg.Digest() over (contract=msg.To, receiver, amount, chain, coin, InTxHash). It excludes the log index, the event sender and the block height. Two identical ZRC20 Withdrawal or ZetaSent events in one zEVM tx therefore get the same index. ProcessCCTX gives each a fresh nonce and SetCrossChainTx overwrites the first, so the first nonce never has a CCTX and is never signed.

        Exploit scenario

        The attacker deploys a zEVM contract that calls ETH-ZRC20.withdraw(to, 1) twice in one tx after paying the two small gas fees. PostTxProcessing builds two identical messages. The first CCTX gets nonce N and is then overwritten by the second, which gets nonce N+1. No zetaclient ever signs nonce N on Ethereum, so every later outbound tx (N+1, N+2, ...) sits unmineable and all outbound to that chain halts until manual intervention. Logs from module-originated ApplyMessage calls (the HandleEVMDeposit deposit-and-call path) carry a zero TxHash, so repeated identical deposit-and-call withdrawals collide across different blocks too.

        Recommendation

        Derive the CCTX index from a unique tuple such as tx hash, log index and block height, and refuse to create a CCTX whose index already exists. Also make module-originated EVM calls carry a unique tx hash.

        Vercel Security Review

        Identical withdrawals overwrite a CCTX and leave an unfillable TSS nonce

        x/crosschain/keeper/evm_hooks.go:109 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        **1. Distinct withdrawal logs collapse to one identifier** - x/crosschain/keeper/evm_hooks.go:109-112

        ```go title="x/crosschain/keeper/evm_hooks.go:109-112"

        msg := zetacoretypes.NewMsgSendVoter("", contract.Hex(), senderChain.ChainId, txOrigin, toAddr, receiverChainID, math.NewUintFromBigInt(event.Value),

        "", event.Raw.TxHash.String(), event.Raw.BlockNumber, 90000, coinType, asset)

        sendHash := msg.Digest()

        cctx := k.CreateNewCCTX(ctx, msg, sendHash, zetacoretypes.CctxStatus_PendingOutbound, &senderChain, recvChain)

        ```

        An unprivileged contract can call a registered ZRC20's withdrawal twice with identical parameters in one transaction. Neither identifier includes the log index.

        **2. Each log nevertheless consumes a nonce** - x/crosschain/keeper/keeper_utils.go:146-148

        ```go title="x/crosschain/keeper/keeper_utils.go:146-148"

        cctx.GetCurrentOutTxParam().OutboundTxTssNonce = nonce.Nonce

        nonce.Nonce++

        k.SetChainNonces(ctx, nonce)

        ```

        The two commands receive N and N+1.

        **3. The second command destroys the first** - x/crosschain/keeper/keeper_cross_chain_tx.go:28-31

        ```go title="x/crosschain/keeper/keeper_cross_chain_tx.go:28-31"

        p := types.KeyPrefix(fmt.Sprintf("%s-%d", types.SendKey, send.CctxStatus.Status))

        store := prefix.NewStore(ctx.KVStore(k.storeKey), p)

        b := k.cdc.MustMarshal(&send)

        store.Set(types.KeyPrefix(send.Index), b)

        ```

        Only N+1 survives. No command can fill N, so subsequent EVM outbounds for all users on that chain stall pending operator repair.

        Exploit scenario

        Not specified.

        Recommendation

        Include the withdrawal log index in CCTX identity and preserve a separate CCTX for every withdrawal. Allocate and persist each nonce atomically with its unique command; reject any unexpected existing identifier before incrementing the nonce.

      • Missing authentication when adding node keys zetachain-7 · 4 writeups Critical

        V12

        Permissionless registrations enter the keygen participant roster

        x/crosschain/types/message_set_node_keys.go:30 Predicted severity: Informational

        Root cause

        The startup keygen path treats the permissionlessly populated NodeAccount registry as an authorized TSS participant roster. NodeStatus_Unknown and the bonded-validator filter used by a separate, disabled initializer do not constrain that consumer.

        Impact

        An inference supported by the request construction is that a nonparticipating registered account can disrupt configured startup key generation, or that registering many controlled accounts can distort the participant set. Whether this also changes signing authority is unresolved: the exact missing facts are the participant admission and quorum rules inside go-tss v1.5.7, whose implementation was not available after searching the repository and attempting to read dependency sources; no theft or fund freeze is established.

        Description

        SetNodeKeys admits any creator with a matching account public key and stores the registration with NodeStatus_Unknown; neither registration nor the startup keygen consumer requires validator membership. When KeygenBlock is positive, genNewKeysAtBlock obtains node accounts through GetAllNodeAccounts and copies every returned secp256k1 key into a TSS keygen request without checking status, staking membership, or an approved participant set. Thus an external account can register its own valid key before that fetch and become a requested participant in other nodes' key generation. This differs from InitializeGenesisKeygen, which applies IsBondedValidator, but that helper's EndBlock invocation is commented out and does not protect the startup path. The source establishes untrusted participant selection, not a demonstrated compromise of the external TSS implementation.

        Devin Security (Deep)

        Anyone can register a node account, and the operator keygen flow uses every node account as a TSS key share holder

        x/crosschain/keeper/keeper_node_account.go:103 Predicted severity: High

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone with a funded ZetaChain account can register a node key before a key generation ceremony and either break the ceremony or, by registering enough keys and running their own TSS nodes, take a controlling share of the key that holds all bridged funds.

        ##### What's wrong

        This is a missing authorization check. SetNodeKeys lets any signer create a node account with an arbitrary public key set; it never checks that the signer is a validator or observer. The operator key generation flow in the observer client (zetaclientd start with --keygen-block) builds the TSS participant list from every node account on chain without filtering, so the registered key becomes a keygen party.

        ##### Who can do it

        Acme Corp runs the ZetaChain validators and schedules a TSS key generation at block H using zetaclientd init --keygen-block H. Mallory, an outsider with a funded ZetaChain account (testnet faucet tokens are enough), submits MsgSetNodeKeys with her own TSS public key before block H. If she wants control rather than disruption, she submits several such messages from several accounts and runs matching go-tss nodes connected to the same p2p rendezvous.

        Conditions:

        - Operators run key generation through the --keygen-block path in cmd/zetaclientd/start.go (the in-chain genesis keygen at block 80 filters by bonded validator and is not affected).

        - Mallory submits MsgSetNodeKeys before the keygen block.

        - For takeover, Mallory's TSS nodes must reach the honest nodes' p2p network and she must register at least two thirds of the total party count.

        ##### What they get

        At minimum, Mallory stops the ceremony: go-tss requires every listed party to participate, so a key that no online node holds makes keygen fail and the bridge cannot start signing. At worst, with enough registered keys and running nodes, Mallory holds a threshold share of the TSS key and can sign withdrawals from the TSS address on every connected chain, draining all funds users deposited into the bridge.

        ##### How it works

        1. Mallory sends MsgSetNodeKeys with her PubkeySet; SetNodeKeys in x/crosschain/keeper/keeper_node_account.go:103-124 only parses the address and stores the node account.

        2. Each operator's zetaclientd start calls genNewKeysAtBlock in cmd/zetaclientd/start.go:231-291, which queries NodeAccountAll and puts every account's PubkeySet.Secp256k1 into the keygen request (start.go:243-251).

        3. go-tss runs the ceremony with that party list (start.go:266-267); a missing party fails keygen, and a party Mallory operates receives a key share.

        4. The resulting TSS public key is set on chain via SetTSS (start.go:119) and becomes the custody address for all connected chains.

        Exploit scenario

        Not specified.

        Recommendation

        Require msg.Creator to be a bonded validator (or an authorized observer) in SetNodeKeys, and make the client keygen path in cmd/zetaclientd/start.go use the on-chain Keygen.Pubkeys list (or filter node accounts by bonded validator) instead of every node account. Verify by submitting MsgSetNodeKeys from a non-validator account on a localnet and checking that it is rejected and that a keygen run does not include its key.

        Claude Security (Sonnet 5.5)

        SetNodeKeys lets any account register a node account; zetaclient then uses every node account as a TSS keygen participant

        x/crosschain/keeper/keeper_node_account.go:103 Predicted severity: High

        Root cause

        Vulnerable symbol: msgServer.SetNodeKeys

        Preconditions: Keygen is performed through the zetaclientd --keygen-block path, which uses all node accounts without filtering; The attacker registers before the keygen block and, to gain signing power rather than just DoS, runs TSS peers; Attacker has tiny funds for gas

        Offending code:

        func (k msgServer) SetNodeKeys(goCtx context.Context, msg *types.MsgSetNodeKeys) (*types.MsgSetNodeKeysResponse, error) {

        Impact

        An unprivileged attacker can add many Sybil parties to a TSS keygen. Registering unresponsive parties makes keygen fail, which blocks bootstrap or rotation. If the attacker runs the extra parties, they can accumulate enough key shares to reach the signing threshold and take over the TSS key that custodies the bridged assets. The index is the raw bech32 string, so an upper-case variant of the same creator address bypasses the 'already has a node account' check and creates a duplicate record for one key.

        Description

        The handler only checks that the creator has no node account yet. It never checks that the creator is a bonded validator or an observer. The only gate is ValidateBasic, which requires the pubkey to match the creator, so an attacker simply generates fresh keys. zetaclientd genNewKeysAtBlock (cmd/zetaclientd/start.go:243-266) queries all node accounts and passes every Secp256k1 pubkey, unfiltered, to go-tss Keygen. The chain-side keygen path in end_block_server_keygen.go does filter with IsBondedValidator, which shows the intended invariant is missing here.

        Exploit scenario

        1) Before operators run zetaclientd start --keygen-block N (contrib/localnet/scripts/keygen.sh), the attacker generates k secp256k1 keys. 2) For each key they submit MsgSetNodeKeys signed by that key, paying only gas. 3) Honest zetaclients fetch GetAllNodeAccounts and call tss.Server.Keygen with the honest plus attacker pubkeys. 4) Either the attacker nodes stay offline, so keygen fails and is blamed on the honest nodes, or the attacker nodes join and hold shares, with k large enough to meet the 2/3 signing threshold.

        Recommendation

        Restrict SetNodeKeys to bonded validators or observers, for example IsBondedValidator or an observer-list check, and normalise the creator address before using it as a store key. Filter the zetaclient keygen participant list to bonded validators, or take it only from the on-chain Keygen object.

        Claude Security (Opus 5.5)

        TSS keygen party list is built from every self-registered node account, so an attacker can join or break vault key generation

        cmd/zetaclientd/start.go:250 Predicted severity: High

        Root cause

        Vulnerable symbol: genNewKeysAtBlock

        Preconditions: Operators have configured a keygen block (KeygenBlock > 0), which is how vault keys are created and rotated; The attacker holds a funded zeta account to pay gas for MsgSetNodeKeys, and registers before honest clients fetch node accounts at start.go:243; For theft (not needed for DoS): the attacker can reach honest TSS nodes over libp2p (go-tss v1.5.7 is configured with no peer allowlist) and registers enough Sybil node accounts to meet the keysign threshold. This relies on go-tss library behavior that was not verified by running it

        Offending code:

        pubkeys = append(pubkeys, na.PubkeySet.Secp256k1.String())

        Impact

        Unauthorized control over the cross-chain TSS vault key, which allows theft of all funds sent to the TSS addresses. At minimum, anyone can cheaply cause a permanent failure of TSS key generation and key rotation.

        Description

        genNewKeysAtBlock asks zetacore for every node account (GetAllNodeAccounts, start.go:243) and adds each pubkey to the TSS keygen request (start.go:250, used at start.go:266). It never checks that the account belongs to a bonded validator or an authorized observer, and it ignores NodeStatus. Anyone can create these node accounts: the MsgSetNodeKeys handler (x/crosschain/keeper/keeper_node_account.go:103-118) has no authorization check, and ValidateBasic only requires the pubkey to match the sender's own address. So any funded account can make itself a TSS keygen party.

        Exploit scenario

        Before the configured keygen block, an attacker sends cheap MsgSetNodeKeys transactions from many fresh accounts, each with a pubkey derived from that account's own key. (a) DoS: if even one registered party never joins, or if honest clients fetch the account list at different times and so build different party lists, go-tss keygen fails for every honest node and no vault key is created. (b) Theft: the attacker runs go-tss nodes on the hard-coded rendezvous string 'MetaMetaOpenTheDoor' (port 6668), using p2p identities derived from those account keys, and takes part in keygen. If the attacker registers more parties than the honest set (e.g. 9 attacker parties against 4 honest ones, so 9 of 13 meet the keysign threshold), the attacker holds enough shares to sign alone. Honest zetaclients then report the resulting TSS address through SetTSS/CreateTSSVoter (start.go:119), and every bonded validator votes for it. The attacker can then sign withdrawals from the BTC and EVM vaults at will.

        Recommendation

        Build the keygen party list only from authorized signers. Intersect the node accounts with the bonded validator set or the observer set (the same rule as CreateTSSVoter/IsAuthorized), or have the chain store an authoritative, governance-approved keygen party list that every client reads. Separately, add an authorization check to MsgSetNodeKeys (bonded validator or observer only) so that node accounts cannot be self-registered.

      • Missing nil check when parsing client event zetachain-8 · 5 writeups High

        V12

        Unsupported destination events crash the client daemon

        zetaclient/evm_client.go:544 Predicted severity: Medium

        Root cause

        The connector event path assumes a decoded uint256 destination always resolves to a locally known, configured chain before dereferencing the lookup results.

        Impact

        An unsupported destination in external RPC event data can terminate the client daemon and interrupt observations and signing across its chains. Whether an ordinary connector caller can cause the deployed contract to emit such an event remains unresolved: the reviewed Go bindings expose the destination argument, but the deployed external connector's executable validation was not available in the searched repository Solidity sources.

        Description

        For every decoded connector event, observeInTX converts DestinationChainId with Int64() and looks up the resulting chain. common.GetChainFromChainID returns nil for unknown identifiers. The caller immediately dereferences destChain.ChainName and then the corresponding ChainConfigs entry without checking either lookup. A correctly ABI-encoded RPC event carrying an unsupported destination therefore panics before the observer can reject or skip it. The watcher runs in a goroutine without a recovery handler, and its normal error-return handling cannot intercept that panic.

        Devin Security

        Nil pointer panic on a ZetaSent event with an unknown destination chain crashes every zetaclient

        zetaclient/evm_client.go:560 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can emit one ZetaSent event with an unsupported destination chain ID and crash every observer, which stops the bridge until the code is patched.

        ##### What's wrong

        This is a nil pointer dereference. The inbound watcher turns the event's destination chain ID into a chain object and uses it without checking for nil. It also uses a config map entry without checking that it exists.

        ##### Who can do it

        Mallory, an anonymous user with a wallet on Goerli, calls the public connector send function with destinationChainId set to 999999. Every zetaclient sees the event and crashes. When an operator restarts a node, it reads the same saved block height, sees the same event again, and crashes again.

        - Mallory can call the connector's send on a connected EVM chain. The chain ID is not validated on-chain.

        - destinationChainId is not in DefaultChainsList, or the chain is missing from the node's ChainConfigs.

        ##### What they get

        All observers stop processing deposits and outbound transfers on every chain, because the panic kills the whole process. No funds are stolen. The outage lasts until a code fix ships.

        ##### How it works

        1. observeInTX reads ZetaSent logs from the connector (zetaclient/evm_client.go:544-560).

        2. common.GetChainFromChainID returns nil for an unknown ID (common/chain.go:104-112), and the code does not check the result (zetaclient/evm_client.go:563).

        3. destChain.ChainName dereferences nil, and config.ChainConfigs[...] can also return a nil entry (zetaclient/evm_client.go:566).

        4. The ExternalChainWatcher goroutine has no recover, so the process exits before SetLastBlockHeight saves progress (zetaclient/evm_client.go:481-497, 731-734).

        Exploit scenario

        Not specified.

        Recommendation

        If destChain is nil or config.ChainConfigs has no entry for it, log the event and skip it with continue. Also add a recover to the watcher goroutines. To verify, add a test that feeds a ZetaSent event with chain ID 999999 and confirm the loop moves past it.

        Devin Security (Deep)

        ZetaSent event with an unknown destination chain id crashes every zetaclient observer in a restart loop

        zetaclient/evm_client.go:560 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can send one cheap transaction to the ZetaChain connector on Ethereum and crash every observer and signer node, and because the crash happens before the scanned block is recorded, the nodes keep crashing after every restart until the code is patched, so the bridge stops; no funds or data are exposed.

        ##### What's wrong

        This is an unchecked nil pointer from untrusted input. GetChainFromChainID returns nil for chain ids outside the built in list, and the observer dereferences the result without checking it, using a chain id copied straight from an on chain event anyone can emit.

        ##### Who can do it

        Mallory has an Ethereum account. She calls send on the ZetaChain connector contract on Ethereum with destinationChainId set to 424242 and zetaValueAndGas set to zero.

        - Mallory needs an Ethereum account with gas; no ZETA tokens are required for a zero value send.

        - The zetaclient observer for that chain must scan the block containing her event, which it does for every block.

        ##### What they get

        Every zetaclient process panics while scanning that block. The last scanned height is only persisted after the scan completes, so each restart rescans the same block and panics again. All inbound observation and outbound signing for every connected chain stops, because one process hosts all chain clients and the TSS signer. Pending user withdrawals and deposits are frozen until operators patch the binary. Mallory cannot take funds; this is a full outage of the bridge.

        ##### How it works

        1. Mallory emits a ZetaSent event on Ethereum with destinationChainId = 424242.

        2. observeInTX at zetaclient/evm_client.go:544-548 fetches ZetaSent logs from the connector for the new block range.

        3. Line 563 calls common.GetChainFromChainID(event.DestinationChainId.Int64()), which returns nil at common/chain.go:104-112 because 424242 is not in DefaultChainsList.

        4. Line 566 reads destChain.ChainName, which dereferences nil and panics inside the ExternalChainWatcher goroutine started at line 190 with no recover, terminating the process.

        5. The height is only saved at lines 731-734 after the loop, so the next start rescans the same block and hits the same panic.

        Exploit scenario

        Not specified.

        Recommendation

        Check the result of GetChainFromChainID for nil at evm_client.go:563 and skip the event with a warning log when the destination chain is unknown; apply the same check at evm_signer.go:217-221 and zetacore_observer.go:278. Also wrap the observer goroutines with a recover that logs and continues. Verify by emitting a ZetaSent event with an unsupported chain id on a local Ethereum node and confirming the zetaclient logs a warning, keeps running, and advances its scanned height.

        Claude Security (Sonnet 5.5)

        Unvalidated destinationChainId in observed ZetaSent event causes nil-pointer panic and persistent crash loop of the whole zetaclient

        zetaclient/evm_client.go:566 Predicted severity: High

        Root cause

        Vulnerable symbol: EVMChainClient.observeInTX

        Preconditions: The attacker can submit a transaction to the Zeta connector on any chain observed by zetaclient (public function); Connector send() does not reject unknown destination chain IDs (upstream behaviour; contract source not in repo)

        Offending code:

        if strings.EqualFold(destAddr, config.ChainConfigs[destChain.ChainName.String()].ZETATokenContractAddress) {

        Impact

        A permissionless attacker can crash every observer/signer node at the same time and keep them in a crash loop. This halts inbound observation, outbound TSS signing and gas-price posting for all chains handled by the process, until operators intervene manually. No funds are directly stolen, but the bridge is down.

        Description

        The destinationChainId field of ZetaSent logs from the public Zeta connector contract is attacker-chosen, and the code passes it to common.GetChainFromChainID, which returns nil for unknown IDs. The result is dereferenced unchecked at destChain.ChainName and at config.ChainConfigs[...].ZETATokenContractAddress, where the map entry is also nil for chains such as BTC that have no ChainETHish entry. The panic is unrecovered, so the process dies.

        Exploit scenario

        1. The attacker calls ZetaConnector.send on a monitored EVM chain with a destinationChainId that is not in DefaultChainsList (for example 0xdeadbeef). They could also use a known non-EVM chain ID such as the BTC chain ID, which has no ChainConfigs entry in the testnet/privnet builds. zetaValueAndGas can be zero or minimal, so the only cost is gas. This relies on the connector's send() not validating the destination chain, as in the upstream ZetaConnector; the Solidity source is not in this repo, only the ABI and bytecode bindings.

        2. Within one scan window (MaxBlocksPerPeriod=100 blocks) every validator's zetaclient runs observeInTX over the block holding the log.

        3. FilterZetaSent yields the event and the code dereferences a nil *Chain (or nil *ChainETHish). The panic occurs in the ExternalChainWatcher goroutine, there is no recover() anywhere in zetaclient or cmd, and the whole process exits.

        4. lastBlock and PosKey are only advanced at the end of observeInTX (lines 731-734), so on restart the same block range is rescanned and the process crashes again, until an operator manually sets <CHAIN>_SCAN_FROM or patches the code.

        Recommendation

        Check for nil from GetChainFromChainID and for a missing config.ChainConfigs entry before dereferencing, and skip or log the event. Also check that DestinationChainId fits in int64. Wrap the per-event processing in a recover so one malformed external event cannot kill the process, and advance the scan cursor past unprocessable logs.

        Claude Security (Opus 5.5)

        Attacker-chosen DestinationChainId in a ZetaSent event dereferences nil and crash-loops every zetaclient

        zetaclient/evm_client.go:566 Predicted severity: High

        Root cause

        Vulnerable symbol: observeInTX

        Preconditions: Inbound is enabled in zetacore permission flags (the default); The EVM ZetaConnector send() accepts any destinationChainId (true of the public connector contract; its source is not in this repository)

        Offending code:

        if strings.EqualFold(destAddr, config.ChainConfigs[destChain.ChainName.String()].ZETATokenContractAddress) {

        Impact

        Anyone who can pay gas on a supported EVM chain can halt the whole cross-chain bridge. Every observer and TSS signer goes into a crash loop, so deposits and withdrawals on all chains freeze. This is a liveness failure across the network.

        Description

        Any EVM user sets event.DestinationChainId by calling the connector's send. That value goes to common.GetChainFromChainID, which returns nil for an unknown id (common/chain.go:104-112). Line 566 then reads destChain.ChainName with no nil check. A chain id that is known but has no ETH-style config (for example btc_testnet) also panics, because config.ChainConfigs[...] is a nil *ChainETHish.

        Exploit scenario

        1. The attacker calls ZetaConnector.send on an observed EVM chain (Goerli, BSC testnet, Mumbai, and so on) with destinationChainId = 999999 and zetaValueAndGas = 0 or 1 wei.

        2. After the confirmation depth, every observer's ExternalChainWatcher goroutine reaches line 566 and panics with a nil pointer dereference.

        3. Nothing recovers the panic, so the whole zetaclientd process exits on every validator.

        4. On restart, BuildBlockIndex reads the old PosKey from leveldb, scans the same block again and panics again.

        5. Inbound observation, outbound TSS signing and gas-price voting stop on all chains until operators manually set <chain>_SCAN_FROM past the block (also skipping legitimate deposits) or patch the code.

        Recommendation

        Check that GetChainFromChainID returned a non-nil chain and that config.ChainConfigs[...] exists before using either. If the chain is unsupported, log it and skip the event (continue) instead of dereferencing. Add a recover() at the top of each observer goroutine so a single bad event cannot kill the process. Store the scanned-block position in a way that cannot get stuck on one block that always fails.

      • Case-sensitive address check allows for double signing zetachain-9 · 2 writeups High

        V12

        Noncanonical identities can occupy multiple consensus slots

        x/crosschain/keeper/utils.go:10 Predicted severity: Informational

        Root cause

        Authorization and duplicate detection use different identity equivalence relations: decoded address bytes versus raw Creator strings. Signer-count consensus relies on the latter without canonicalization.

        Impact

        The security question is whether accepted Bech32 aliases let one validator meet the TSS consensus gate with fewer independent identities than required. The exact missing fact is alias acceptance and normalization in Cosmos SDK v0.46.8's AccAddressFromBech32/Bech32 decoder; repository-wide decoder/alias searches and the local validation, signer extraction, ante wiring, and tally paths were examined, but dependency code and runtime execution were unavailable. Custody theft is not established because the retrieved client signs with independently selected local keys.

        Description

        IsBondedValidator authorizes by decoded account/operator bytes, whereas isDuplicateSigner compares the original Creator strings verbatim. CreateTSSVoter persists those original strings and counts their number as independent validators. ValidateBasic also only delegates Creator validation to sdk.AccAddressFromBech32, without requiring a canonical re-encoding. If the pinned Bech32 decoder accepts uppercase and lowercase spellings of the same account, one bonded validator can submit both spellings for the same payload and session and occupy two signer slots. The decoder implementation was unavailable in the workspace, so acceptance of that concrete alias pair is an unresolved precondition rather than a verified exploit.

        Claude Security (Sonnet 5.5)

        CreateTSSVoter duplicate-signer check is case-sensitive, so a validator can vote twice and the 'full consensus' TSS requirement is weakened

        x/crosschain/keeper/keeper_tss_voter.go:118 Predicted severity: Low

        Root cause

        Vulnerable symbol: msgServer.CreateTSSVoter

        Preconditions: Colluding bonded validators, at least about half of the set; Cosmos SDK AccAddressFromBech32 accepting all-uppercase bech32. I believe it does but could not confirm in the vendored module source.

        Offending code:

        if isDuplicateSigner(msg.Creator, tssVoter.Signers) {

        Impact

        The code says TSS finalisation needs full consensus: len(Signers) == len(validators). With double voting, roughly half the validators acting twice reach N entries and call SetTSS. A minority can therefore overwrite the on-chain TSS pubkey and address that observers and signers consult.

        Description

        Eligibility is checked by decoding the creator to bytes (IsBondedValidator, utils.go:10-26), which accepts both the all-lowercase and all-uppercase bech32 forms of one address. The double-vote check compares raw strings (isDuplicateSigner, keeper_chain_nonces.go:136-143). The same validator can therefore sign the identical message once with zeta1... and once with ZETA1.... Each form is appended to Signers.

        Exploit scenario

        With N bonded validators, ceil(N/2) colluding validators each submit MsgCreateTSSVoter with a lowercase Creator and again with an uppercase Creator. The message digest zeroes Creator, so both land in the same tssVoter record. After exactly N entries the handler stores the attacker-chosen TSS record.

        Recommendation

        Normalise to canonical sdk.AccAddress bytes or the canonical bech32 string before storing or comparing signers. Apply the same normalisation wherever signer strings are used as keys. Compare against validators that are actually bonded, not GetAllValidators, when computing the consensus size.

      • No panic handler in Zetaclient may halt cross-chain communication zetachain-10 · 5 writeups High

        V12

        Empty keygen reply crashes the observer process

        zetaclient/zetacore_observer.go:66 Predicted severity: Medium

        Root cause

        The coordinator trusts successful transport status to imply the presence of an optional protobuf record and has no containment for the resulting goroutine panic.

        Impact

        A successful RPC response omitting Keygen can terminate the entire observer process, interrupting all of its chain observation and signing work. This requires the configured RPC boundary to deliver such a response; ordinary missing-record replies from the inspected keeper return an error and do not trigger the panic.

        Description

        GetKeyGen returns the optional Keygen pointer from a successful gRPC response without checking that the field is present. keygenObserve checks only the returned error before directly accessing kg.BlockNumber. The generated query client allocates a response object, but the response's nested Keygen field remains nullable, so an empty successful response reaches a nil dereference. This operation runs in a goroutine launched by MonitorCore without panic recovery. The repository's own keeper returns a non-nil keygen on success, so this candidate specifically concerns malformed or version-skewed responses at the external RPC boundary rather than a missing record from that keeper.

        Devin Security

        Nil pointer panic on a ZetaSent event with an unknown destination chain crashes every zetaclient

        zetaclient/evm_client.go:560 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can emit one ZetaSent event with an unsupported destination chain ID and crash every observer, which stops the bridge until the code is patched.

        ##### What's wrong

        This is a nil pointer dereference. The inbound watcher turns the event's destination chain ID into a chain object and uses it without checking for nil. It also uses a config map entry without checking that it exists.

        ##### Who can do it

        Mallory, an anonymous user with a wallet on Goerli, calls the public connector send function with destinationChainId set to 999999. Every zetaclient sees the event and crashes. When an operator restarts a node, it reads the same saved block height, sees the same event again, and crashes again.

        - Mallory can call the connector's send on a connected EVM chain. The chain ID is not validated on-chain.

        - destinationChainId is not in DefaultChainsList, or the chain is missing from the node's ChainConfigs.

        ##### What they get

        All observers stop processing deposits and outbound transfers on every chain, because the panic kills the whole process. No funds are stolen. The outage lasts until a code fix ships.

        ##### How it works

        1. observeInTX reads ZetaSent logs from the connector (zetaclient/evm_client.go:544-560).

        2. common.GetChainFromChainID returns nil for an unknown ID (common/chain.go:104-112), and the code does not check the result (zetaclient/evm_client.go:563).

        3. destChain.ChainName dereferences nil, and config.ChainConfigs[...] can also return a nil entry (zetaclient/evm_client.go:566).

        4. The ExternalChainWatcher goroutine has no recover, so the process exits before SetLastBlockHeight saves progress (zetaclient/evm_client.go:481-497, 731-734).

        Exploit scenario

        Not specified.

        Recommendation

        If destChain is nil or config.ChainConfigs has no entry for it, log the event and skip it with continue. Also add a recover to the watcher goroutines. To verify, add a test that feeds a ZetaSent event with chain ID 999999 and confirm the loop moves past it.

        Devin Security (Deep)

        ZetaSent event with an unknown destination chain id crashes every zetaclient observer in a restart loop

        zetaclient/evm_client.go:560 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone can send one cheap transaction to the ZetaChain connector on Ethereum and crash every observer and signer node, and because the crash happens before the scanned block is recorded, the nodes keep crashing after every restart until the code is patched, so the bridge stops; no funds or data are exposed.

        ##### What's wrong

        This is an unchecked nil pointer from untrusted input. GetChainFromChainID returns nil for chain ids outside the built in list, and the observer dereferences the result without checking it, using a chain id copied straight from an on chain event anyone can emit.

        ##### Who can do it

        Mallory has an Ethereum account. She calls send on the ZetaChain connector contract on Ethereum with destinationChainId set to 424242 and zetaValueAndGas set to zero.

        - Mallory needs an Ethereum account with gas; no ZETA tokens are required for a zero value send.

        - The zetaclient observer for that chain must scan the block containing her event, which it does for every block.

        ##### What they get

        Every zetaclient process panics while scanning that block. The last scanned height is only persisted after the scan completes, so each restart rescans the same block and panics again. All inbound observation and outbound signing for every connected chain stops, because one process hosts all chain clients and the TSS signer. Pending user withdrawals and deposits are frozen until operators patch the binary. Mallory cannot take funds; this is a full outage of the bridge.

        ##### How it works

        1. Mallory emits a ZetaSent event on Ethereum with destinationChainId = 424242.

        2. observeInTX at zetaclient/evm_client.go:544-548 fetches ZetaSent logs from the connector for the new block range.

        3. Line 563 calls common.GetChainFromChainID(event.DestinationChainId.Int64()), which returns nil at common/chain.go:104-112 because 424242 is not in DefaultChainsList.

        4. Line 566 reads destChain.ChainName, which dereferences nil and panics inside the ExternalChainWatcher goroutine started at line 190 with no recover, terminating the process.

        5. The height is only saved at lines 731-734 after the loop, so the next start rescans the same block and hits the same panic.

        Exploit scenario

        Not specified.

        Recommendation

        Check the result of GetChainFromChainID for nil at evm_client.go:563 and skip the event with a warning log when the destination chain is unknown; apply the same check at evm_signer.go:217-221 and zetacore_observer.go:278. Also wrap the observer goroutines with a recover that logs and continues. Verify by emitting a ZetaSent event with an unsupported chain id on a local Ethereum node and confirming the zetaclient logs a warning, keeps running, and advances its scanned height.

        Claude Security (Sonnet 5.5)

        Unvalidated destinationChainId in observed ZetaSent event causes nil-pointer panic and persistent crash loop of the whole zetaclient

        zetaclient/evm_client.go:566 Predicted severity: High

        Root cause

        Vulnerable symbol: EVMChainClient.observeInTX

        Preconditions: The attacker can submit a transaction to the Zeta connector on any chain observed by zetaclient (public function); Connector send() does not reject unknown destination chain IDs (upstream behaviour; contract source not in repo)

        Offending code:

        if strings.EqualFold(destAddr, config.ChainConfigs[destChain.ChainName.String()].ZETATokenContractAddress) {

        Impact

        A permissionless attacker can crash every observer/signer node at the same time and keep them in a crash loop. This halts inbound observation, outbound TSS signing and gas-price posting for all chains handled by the process, until operators intervene manually. No funds are directly stolen, but the bridge is down.

        Description

        The destinationChainId field of ZetaSent logs from the public Zeta connector contract is attacker-chosen, and the code passes it to common.GetChainFromChainID, which returns nil for unknown IDs. The result is dereferenced unchecked at destChain.ChainName and at config.ChainConfigs[...].ZETATokenContractAddress, where the map entry is also nil for chains such as BTC that have no ChainETHish entry. The panic is unrecovered, so the process dies.

        Exploit scenario

        1. The attacker calls ZetaConnector.send on a monitored EVM chain with a destinationChainId that is not in DefaultChainsList (for example 0xdeadbeef). They could also use a known non-EVM chain ID such as the BTC chain ID, which has no ChainConfigs entry in the testnet/privnet builds. zetaValueAndGas can be zero or minimal, so the only cost is gas. This relies on the connector's send() not validating the destination chain, as in the upstream ZetaConnector; the Solidity source is not in this repo, only the ABI and bytecode bindings.

        2. Within one scan window (MaxBlocksPerPeriod=100 blocks) every validator's zetaclient runs observeInTX over the block holding the log.

        3. FilterZetaSent yields the event and the code dereferences a nil *Chain (or nil *ChainETHish). The panic occurs in the ExternalChainWatcher goroutine, there is no recover() anywhere in zetaclient or cmd, and the whole process exits.

        4. lastBlock and PosKey are only advanced at the end of observeInTX (lines 731-734), so on restart the same block range is rescanned and the process crashes again, until an operator manually sets <CHAIN>_SCAN_FROM or patches the code.

        Recommendation

        Check for nil from GetChainFromChainID and for a missing config.ChainConfigs entry before dereferencing, and skip or log the event. Also check that DestinationChainId fits in int64. Wrap the per-event processing in a recover so one malformed external event cannot kill the process, and advance the scan cursor past unprocessable logs.

        Claude Security (Opus 5.5)

        Attacker-chosen DestinationChainId in a ZetaSent event dereferences nil and crash-loops every zetaclient

        zetaclient/evm_client.go:566 Predicted severity: High

        Root cause

        Vulnerable symbol: observeInTX

        Preconditions: Inbound is enabled in zetacore permission flags (the default); The EVM ZetaConnector send() accepts any destinationChainId (true of the public connector contract; its source is not in this repository)

        Offending code:

        if strings.EqualFold(destAddr, config.ChainConfigs[destChain.ChainName.String()].ZETATokenContractAddress) {

        Impact

        Anyone who can pay gas on a supported EVM chain can halt the whole cross-chain bridge. Every observer and TSS signer goes into a crash loop, so deposits and withdrawals on all chains freeze. This is a liveness failure across the network.

        Description

        Any EVM user sets event.DestinationChainId by calling the connector's send. That value goes to common.GetChainFromChainID, which returns nil for an unknown id (common/chain.go:104-112). Line 566 then reads destChain.ChainName with no nil check. A chain id that is known but has no ETH-style config (for example btc_testnet) also panics, because config.ChainConfigs[...] is a nil *ChainETHish.

        Exploit scenario

        1. The attacker calls ZetaConnector.send on an observed EVM chain (Goerli, BSC testnet, Mumbai, and so on) with destinationChainId = 999999 and zetaValueAndGas = 0 or 1 wei.

        2. After the confirmation depth, every observer's ExternalChainWatcher goroutine reaches line 566 and panics with a nil pointer dereference.

        3. Nothing recovers the panic, so the whole zetaclientd process exits on every validator.

        4. On restart, BuildBlockIndex reads the old PosKey from leveldb, scans the same block again and panics again.

        5. Inbound observation, outbound TSS signing and gas-price voting stop on all chains until operators manually set <chain>_SCAN_FROM past the block (also skipping legitimate deposits) or patch the code.

        Recommendation

        Check that GetChainFromChainID returned a non-nil chain and that config.ChainConfigs[...] exists before using either. If the chain is unsupported, log it and skip the event (continue) instead of dereferencing. Add a recover() at the top of each observer goroutine so a single bad event cannot kill the process. Store the scanned-block position in a way that cannot get stuck on one block that always fails.

      • Ethermint Ante handler bypass zetachain-11 · 3 writeups High

        Devin Security (Deep)

        EVM transactions wrapped in authz MsgExec skip the Ethereum ante handler, allowing fee collector theft and unbounded EVM execution

        app/ante/handler_options.go:45 Predicted severity: Critical

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        Anyone with a funded ZetaChain account can run Ethereum style transactions without paying their gas, get a refund from the fee collector for gas they never paid, and make every validator execute an EVM call with an effectively unlimited gas budget.

        ##### What's wrong

        This is an authentication and fee bypass through message wrapping. The Cosmos ante chains in this file only reject a MsgEthereumTx when it sits at the top level of a transaction. The x/authz module is enabled and its MsgExec carries nested messages, so a MsgEthereumTx placed inside MsgExec passes RejectMessagesDecorator and runs through the Cosmos ante chain instead of newEthAnteHandler. None of the Ethereum checks run: no gas fee is deducted, no nonce is checked, no base fee or gas cap is enforced.

        ##### Who can do it

        Mallory holds a normal ZetaChain account with a little ZETA for fees. She signs an Ethereum transaction with her own key, giving it a gas limit of several million and a very high gas price. She puts that transaction inside an authz.MsgExec where she is both granter and grantee, wraps it in a normal Cosmos transaction, and broadcasts it.

        - Mallory needs a ZetaChain account with enough ZETA to pay the small Cosmos fee at the fee market minimum gas price.

        - The x/authz module is registered in app/app.go, so MsgExec is routable.

        - No decorator in newCosmosAnteHandler or newCosmosAnteHandlerNoGasLimit inspects nested messages.

        ##### What they get

        The EVM keeper refunds (gasLimit - gasUsed) * gasPrice to the sender from the fee collector account after every EVM transaction, assuming the ante handler already took that money. Mallory never paid it, so every refund is pure profit taken from the fee collector. At execution time the fee collector holds the current block's validator emission rewards (the emissions BeginBlocker sends them there after distribution runs) plus all fees paid earlier in the block. Mallory can size her gas price so the refund equals that balance and repeat it every block, stealing the validator and delegator reward stream from everyone on the network. Separately, because the Ethereum gas cap and gas fee checks are skipped, she can submit an EVM call with a gas limit near the int64 maximum that loops forever; validators run it to completion in DeliverTx before any Cosmos gas accounting fires, which stalls block production for the whole chain.

        ##### How it works

        1. Mallory builds a signed MsgEthereumTx and nests it in authz.MsgExec with herself as grantee; authz skips the grant lookup when granter equals grantee.

        2. The transaction has no Ethereum extension option, so NewAnteHandler in app/ante/ante.go:92-116 routes it to newCosmosAnteHandler (or newCosmosAnteHandlerNoGasLimit).

        3. ethante.RejectMessagesDecorator{} at app/ante/handler_options.go:47 and :69 loops over tx.GetMsgs() only, sees a MsgExec, and lets it through; no decorator unwraps nested messages.

        4. The Cosmos chain deducts only the small Cosmos fee and verifies only Mallory's Cosmos signature; the Ethereum fee deduction, nonce check, base fee check and MaxTxGasWanted cap in newEthAnteHandler (lines 29-42) never run.

        5. authz.MsgExec dispatches the nested message to the EVM EthereumTx handler, which calls ApplyTransaction, executes the EVM with the full attacker chosen gas limit, and then calls RefundGas, which sends (gasLimit - gasUsed) * gasPrice from the fee collector module account to Mallory.

        6. Mallory repeats this each block to drain the fee collector, or uses a huge gas limit with a looping contract to stall validators.

        Exploit scenario

        Not specified.

        Recommendation

        Add an authz limiting decorator to both Cosmos ante chains, placed right after RejectMessagesDecorator, that recursively walks authz.MsgExec messages and rejects any transaction that nests MsgEthereumTx (and other messages that depend on ante handler side effects, such as vesting account creation). Ethermint v0.22.0 ships AuthzLimiterDecorator for exactly this purpose; upgrading Ethermint or copying that decorator both work. Verify the fix by building a transaction containing MsgExec{MsgEthereumTx} with granter equal to grantee and confirming it is rejected in CheckTx with an invalid type error, and by adding a unit test that asserts nested MsgEthereumTx at depth 1 and depth 2 are rejected.

        Claude Security (Sonnet 5.5)

        authz MsgExec can wrap MsgEthereumTx and bypass the Ethereum ante handler (no fee, nonce or gas-cap enforcement)

        app/ante/handler_options.go:47 Predicted severity: High

        Root cause

        Vulnerable symbol: newCosmosAnteHandler

        Preconditions: A funded account whose key can sign both an Ethereum tx and a Cosmos tx (eth_secp256k1 is the default key type); Ethermint v0.21.0 EthereumTx msg server refunds leftover gas from the fee collector and does not itself enforce the ante-only invariants (from memory; the dependency is not in the audit tree, so not verified)

        Offending code:

        ethante.RejectMessagesDecorator{}, // reject MsgEthereumTxs

        Impact

        An attacker holding any funded eth_secp256k1 account can run EVM transactions without paying gas, without nonce consumption, and with an attacker-chosen EVM gas limit. Per Ethermint's msg-server design (not readable here, so this part is unverified), leftover gas is refunded from the fee collector at the attacker-chosen gas price. That would let the attacker drain the fee collector, which here also holds the validator emission share sent by x/emissions at BeginBlock (x/emissions/abci.go:23-26). A huge EVM gas limit with a pure-compute loop could stall block execution on all validators.

        Description

        The app registers the SDK authz module (app/app.go:358, 480), but the only guard against MsgEthereumTx in the Cosmos ante chain is RejectMessagesDecorator. It checks only the top-level tx.GetMsgs(), so a MsgEthereumTx nested in an authz MsgExec reaches the EVM msg server without any of the Ethereum ante decorators (sig/nonce/balance/fee deduction/gas-limit). No AuthzLimiter/DisabledAuthzMsgs decorator exists anywhere in the repo.

        Exploit scenario

        1) Attacker signs a legacy Ethereum tx with their own key: gas limit about 20M, gas price chosen to fit the fee collector balance, a trivial transfer to self. 2) Attacker wraps it in authz MsgExec with grantee equal to their own address. For MsgEthereumTx the signer is recovered from the eth signature, so the grantee equals the signer and no grant is needed. 3) The attacker signs the outer Cosmos tx with the same key. 4) The Cosmos ante chain (newCosmosAnteHandler or the NoGasLimit variant) only inspects the top-level MsgExec, so RejectMessagesDecorator passes. 5) authz dispatches the inner MsgEthereumTx to the EVM msg server. The Ethereum ante decorators (EthGasConsume, EthIncrementSenderSequence and the others) never run. The EVM then executes and the leftover-gas refund is paid from the fee collector, or the attacker uses an unbounded gas limit with a compute loop.

        Recommendation

        Add an AuthzLimiter-style ante decorator that walks nested MsgExec messages recursively. It should reject MsgEthereumTx and MsgCreateVestingAccount (and any other message that depends on ante-time checks) inside authz. Put it first in newCosmosAnteHandler, newCosmosAnteHandlerNoGasLimit, and the legacy EIP-712 handler. Make RejectMessagesDecorator recurse into MsgExec as well.

        Claude Security (Opus 5.5)

        MsgEthereumTx wrapped in authz MsgExec skips the Ethereum ante checks, letting a user drain the fee collector through gas refunds

        app/ante/handler_options.go:47 Predicted severity: High

        Root cause

        Vulnerable symbol: newCosmosAnteHandler

        Preconditions: Attacker has an eth_secp256k1 account with enough balance to pay a small Cosmos fee; Fee collector holds a balance during the block (emissions rewards / EVM prepaid fees); Behaviour of ethermint v0.21.0 EthereumTx/RefundGas taken from the dependency, which is not vendored in the repo

        Offending code:

        ethante.RejectMessagesDecorator{}, // reject MsgEthereumTxs

        Impact

        Theft of every block's validator emission rewards and of other users' prepaid EVM gas fees held in the fee collector. Honest EVM txs that need a refund fail, and EVM execution becomes free of fees and nonce checks.

        Description

        The authz module is wired to the app MsgServiceRouter (app.go:358-362). The Cosmos ante chains only reject MsgEthereumTx at the top level through RejectMessagesDecorator, and neither those chains nor the HandlerOptions in app.go:568-576 add an authz limiter. So a MsgEthereumTx nested in MsgExec reaches the EVM msg server without fee deduction, nonce, balance or gas checks. The EVM keeper then pays leftoverGas*gasPrice from the fee collector to the sender.

        Exploit scenario

        The attacker uses an eth_secp256k1 key, so the same address controls both its Cosmos account and its Ethereum account. It signs an Ethereum dynamic-fee tx (for example a plain transfer) with gas limit G and a huge gasFeeCap/gasTipCap P. It wraps this tx as a MsgEthereumTx inside an authz MsgExec where the grantee is the attacker's own Cosmos account. The eth tx signer is the same address, so authz needs no grant. The outer Cosmos tx passes newCosmosAnteHandler because RejectMessagesDecorator only looks at the top-level MsgExec. The EVM ante checks (fee deduction, nonce, balance, max gas) never run. In the msg server, ApplyTransaction executes the tx and RefundGas sends (G - gasUsed)*P azeta from the fee_collector module account to the attacker, even though no fee was prepaid. The attacker sizes P so the refund equals the fee collector's balance. That balance includes the validator emission rewards that x/emissions moves into it every BeginBlock after distribution, plus the prepaid fees of other EVM txs in the block. The attack can be repeated every block. Other users' EVM refunds in the same block then fail.

        Recommendation

        Add an authz limiter decorator to every Cosmos ante chain (newCosmosAnteHandler, newCosmosAnteHandlerNoGasLimit and the legacy EIP-712 chain). It must recursively reject MsgEthereumTx (and other sensitive types) nested inside authz.MsgExec and authz.MsgGrant authorizations. Set DisabledAuthzMsgs in HandlerOptions accordingly.

      • Unbonded validators prevent the TSS vote from passing zetachain-12 · 4 writeups Medium

        V12

        Ineligible validator records inflate the consensus denominator

        x/crosschain/keeper/keeper_tss_voter.go:104 Predicted severity: Informational

        Root cause

        CreateTSSVoter assumes the population returned by GetAllValidators is identical to the bonded population accepted by IsBondedValidator. That assumption is not enforced at the tally site.

        Impact

        The specific unresolved security question is whether an external account can obstruct TSS registration by creating a nonbonded record counted by GetAllValidators. Missing facts are the pinned dependency's enumeration predicate and validator-creation/admission rules; repository-wide dependency-file searches, the expected-keeper interface, application wiring, and observer hooks were checked, but the Cosmos staking source was unavailable. The retrieved signing client uses local key material, so no custody-fund freeze is established by a failed on-chain registration alone.

        Description

        CreateTSSVoter obtains its promotion denominator from GetAllValidators, but admits votes only through IsBondedValidator, which requires v.IsBonded(). The handler neither filters the denominator nor records an eligible-voter snapshot. If the wired staking keeper returns an unbonded or unbonding validator along with the bonded validators, unanimous votes from the currently eligible identities cannot reach the required count. Adding a validator record without obtaining bonded status would consequently obstruct new TSS registration rather than merely add an eligible voter. The application wires the Cosmos staking keeper directly, but its dependency implementation is not present in the retrieved workspace, so the record-enumeration and creation preconditions remain unverified.

        Codex Security (GPT-6 Sol)

        Unbonded validator records can block TSS finalization

        x/crosschain/keeper/keeper_tss_voter.go:104 Predicted severity: Medium

        Root cause

        CreateTSSVoter obtains GetAllValidators and permits only bonded validators to sign, then compares distinct signer count with the length of the unfiltered list. Ineligible records remain in the denominator.

        Impact

        TSS setup or rotation can stall when the staking store includes an unbonded validator; the condition can arise during normal validator churn.

        Description

        The TSS voter accepts only bonded validators but requires votes equal to every stored validator, so a single unbonded record makes the threshold unreachable.

        Exploit scenario

        CreateTSSVoter obtains GetAllValidators and permits only bonded validators to sign, then compares distinct signer count with the length of the unfiltered list. Ineligible records remain in the denominator.

        Recommendation

        Compute a stable eligible bonded-validator set and use the same set for vote authorization and finalization threshold.

        Devin Security (Deep)

        TSS vote finalization compares bonded signers against all validators, so one unbonded or unbonding validator blocks every TSS key update

        x/crosschain/keeper/keeper_tss_voter.go:104 Predicted severity: Low

        Root cause

        Not specified.

        Impact

        Not specified.

        Description

        ##### TL;DR

        A TSS key update can never finalize while any validator is unbonded or unbonding, so a single stale or departing validator freezes key rotation, which matters most when operators need to rotate away from a compromised key.

        ##### What's wrong

        This is a mismatched-set logic bug. Only bonded validators may vote (IsBondedValidator), but the finalization rule requires the signer count to equal the size of GetAllValidators, which includes unbonding and unbonded validators. The two sets differ whenever any validator is not bonded, so the equality can never be met.

        ##### Who can do it

        Acme Corp runs the ZetaChain validator set. Mallory operates one validator and starts unbonding it, or simply never votes. From then on every MsgCreateTSSVoter round collects at most the bonded validators' votes and never reaches len(validators).

        Conditions:

        - At least one validator in GetAllValidators is not bonded, or one bonded validator withholds its vote.

        ##### What they get

        Mallory prevents the network from recording a new TSS key. Acme cannot rotate the key that holds bridged funds, including after a suspected key compromise, until the staking set is cleaned up.

        ##### How it works

        1. CreateTSSVoter in x/crosschain/keeper/keeper_tss_voter.go:107-110 rejects any signer that is not a bonded validator.

        2. Finalization at keeper_tss_voter.go:139 requires len(tssVoter.Signers) == len(validators) where validators is GetAllValidators, including non-bonded entries.

        3. With any non-bonded validator present, the signer count stays below the validator count and SetTSS never runs.

        Exploit scenario

        Not specified.

        Recommendation

        Count only bonded validators when deciding finalization (for example use GetBondedValidatorsByPower or filter validators with IsBonded), and consider a supermajority threshold instead of unanimity. Verify by unbonding one validator on a localnet and confirming that the remaining bonded validators can still finalize a TSS vote.

        Claude Security (Sonnet 5.5)

        TSS finalization quorum compares bonded signers against all validators (including unbonded/jailed), letting a dust validator block TSS creation

        x/crosschain/keeper/keeper_tss_voter.go:139 Predicted severity: Low

        Root cause

        Vulnerable symbol: msgServer.CreateTSSVoter

        Preconditions: Attacker can create a validator with a minimal self-delegation, or an honest validator is jailed or unbonded; TSS key not yet set or in need of rotation

        Offending code:

        if len(tssVoter.Signers) == len(validators) {

        Impact

        Anyone can create a minimal-stake validator that never enters the active set (or a validator can be jailed). From then on MsgCreateTSSVoter can never finalize SetTSS, so TSS keygen or rotation is blocked and cross-chain outbounds that depend on a TSS key cannot start. The strict '==' also stalls if the validator set shrinks after votes were cast.

        Description

        Only bonded validators may sign (IsBondedValidator, line 108), but the 'full consensus' denominator is len(StakingKeeper.GetAllValidators), which counts Unbonded, Unbonding and Jailed validators too. Equality can therefore never be reached while any non-bonded validator exists.

        Exploit scenario

        Before keygen, an attacker submits MsgCreateValidator with a dust self-delegation that stays Unbonded. All bonded validators send identical MsgCreateTSSVoter. len(Signers) tops out at the number of bonded validators, which is below len(validators), so the TSS record is never written.

        Recommendation

        Compute the quorum over the same set that is allowed to sign (bonded, non-jailed validators at the time of finalization). Use >= and verify every bonded validator has signed, instead of comparing against the total validator count.

    • Private Fixture #1 Rust Tasks 15 V12 14/15 Codex Sec 7/15 Pashov Opus — Pashov GPT-6 — Devin 5/15 Devin (Deep) 10/15 Claude Sec 10/15 Claude Opus 8/15 Vercel 7/15

      Source redacted (private engagement)

      • [redacted finding] private-1-001 Critical
      • [redacted finding] private-1-002 Critical
      • [redacted finding] private-1-003 Critical
      • [redacted finding] private-1-004 Critical
      • [redacted finding] private-1-005 Critical
      • [redacted finding] private-1-006 High
      • [redacted finding] private-1-007 High
      • [redacted finding] private-1-008 High
      • [redacted finding] private-1-009 High
      • [redacted finding] private-1-010 High
      • [redacted finding] private-1-011 Medium
      • [redacted finding] private-1-012 Medium
      • [redacted finding] private-1-013 Medium
      • [redacted finding] private-1-014 Medium
      • [redacted finding] private-1-015 Medium
    • Private Fixture #2 Rust Tasks 24 V12 18/24 Codex Sec 7/24 Pashov Opus — Pashov GPT-6 — Devin 8/24 Devin (Deep) 7/24 Claude Sec 6/24 Claude Opus 6/24 Vercel 4/24

      Source redacted (private engagement)

      • [redacted finding] private-2-001 Critical
      • [redacted finding] private-2-002 Critical
      • [redacted finding] private-2-003 Critical
      • [redacted finding] private-2-004 Critical
      • [redacted finding] private-2-005 Critical
      • [redacted finding] private-2-006 Critical
      • [redacted finding] private-2-007 Critical
      • [redacted finding] private-2-008 High
      • [redacted finding] private-2-009 High
      • [redacted finding] private-2-010 High
      • [redacted finding] private-2-011 High
      • [redacted finding] private-2-012 High
      • [redacted finding] private-2-013 High
      • [redacted finding] private-2-014 High
      • [redacted finding] private-2-015 High
      • [redacted finding] private-2-016 High
      • [redacted finding] private-2-017 Medium
      • [redacted finding] private-2-018 Medium
      • [redacted finding] private-2-019 Medium
      • [redacted finding] private-2-020 Medium
      • [redacted finding] private-2-021 Medium
      • [redacted finding] private-2-022 Medium
      • [redacted finding] private-2-023 Medium
      • [redacted finding] private-2-024 Medium
    • Private Fixture #3 Rust Tasks 70 V12 55/70 Codex Sec 19/70 Pashov Opus — Pashov GPT-6 — Devin 0/70 Devin (Deep) 17/70 Claude Sec 10/70 Claude Opus 9/70 Vercel 3/70

      Source redacted (private engagement)

      • [redacted finding] private-3-001 Critical
      • [redacted finding] private-3-002 Critical
      • [redacted finding] private-3-003 Critical
      • [redacted finding] private-3-004 High
      • [redacted finding] private-3-005 High
      • [redacted finding] private-3-006 High
      • [redacted finding] private-3-007 High
      • [redacted finding] private-3-008 High
      • [redacted finding] private-3-009 High
      • [redacted finding] private-3-010 High
      • [redacted finding] private-3-011 High
      • [redacted finding] private-3-012 High
      • [redacted finding] private-3-013 High
      • [redacted finding] private-3-014 High
      • [redacted finding] private-3-015 High
      • [redacted finding] private-3-016 High
      • [redacted finding] private-3-017 High
      • [redacted finding] private-3-018 High
      • [redacted finding] private-3-019 High
      • [redacted finding] private-3-020 High
      • [redacted finding] private-3-021 High
      • [redacted finding] private-3-022 High
      • [redacted finding] private-3-023 High
      • [redacted finding] private-3-024 High
      • [redacted finding] private-3-025 High
      • [redacted finding] private-3-026 High
      • [redacted finding] private-3-027 High
      • [redacted finding] private-3-028 High
      • [redacted finding] private-3-029 Medium
      • [redacted finding] private-3-030 Medium
      • [redacted finding] private-3-031 Medium
      • [redacted finding] private-3-032 Medium
      • [redacted finding] private-3-033 Medium
      • [redacted finding] private-3-034 Medium
      • [redacted finding] private-3-035 Medium
      • [redacted finding] private-3-036 Medium
      • [redacted finding] private-3-037 Medium
      • [redacted finding] private-3-038 Medium
      • [redacted finding] private-3-039 Medium
      • [redacted finding] private-3-040 Medium
      • [redacted finding] private-3-041 Medium
      • [redacted finding] private-3-042 Medium
      • [redacted finding] private-3-043 Medium
      • [redacted finding] private-3-044 Medium
      • [redacted finding] private-3-045 Medium
      • [redacted finding] private-3-046 Medium
      • [redacted finding] private-3-047 Medium
      • [redacted finding] private-3-048 Medium
      • [redacted finding] private-3-049 Medium
      • [redacted finding] private-3-050 Medium
      • [redacted finding] private-3-051 Medium
      • [redacted finding] private-3-052 Medium
      • [redacted finding] private-3-053 Medium
      • [redacted finding] private-3-054 Medium
      • [redacted finding] private-3-055 Medium
      • [redacted finding] private-3-056 Medium
      • [redacted finding] private-3-057 Medium
      • [redacted finding] private-3-058 Medium
      • [redacted finding] private-3-059 Medium
      • [redacted finding] private-3-060 Medium
      • [redacted finding] private-3-061 Medium
      • [redacted finding] private-3-062 Medium
      • [redacted finding] private-3-063 Medium
      • [redacted finding] private-3-064 Medium
      • [redacted finding] private-3-065 Medium
      • [redacted finding] private-3-066 Medium
      • [redacted finding] private-3-067 Medium
      • [redacted finding] private-3-068 Medium
      • [redacted finding] private-3-069 Medium
      • [redacted finding] private-3-070 Medium
    • Private Fixture #4 Rust Tasks 27 V12 22/27 Codex Sec 5/27 Pashov Opus — Pashov GPT-6 — Devin 6/27 Devin (Deep) 11/27 Claude Sec 5/27 Claude Opus 5/27 Vercel 2/27

      Source redacted (private engagement)

      • [redacted finding] private-4-001 Critical
      • [redacted finding] private-4-002 Critical
      • [redacted finding] private-4-003 Critical
      • [redacted finding] private-4-004 Critical
      • [redacted finding] private-4-005 Critical
      • [redacted finding] private-4-006 High
      • [redacted finding] private-4-007 High
      • [redacted finding] private-4-008 High
      • [redacted finding] private-4-009 Medium
      • [redacted finding] private-4-010 Medium
      • [redacted finding] private-4-011 Medium
      • [redacted finding] private-4-012 Medium
      • [redacted finding] private-4-013 Medium
      • [redacted finding] private-4-014 Medium
      • [redacted finding] private-4-015 Medium
      • [redacted finding] private-4-016 Medium
      • [redacted finding] private-4-017 Medium
      • [redacted finding] private-4-018 Medium
      • [redacted finding] private-4-019 Medium
      • [redacted finding] private-4-020 Medium
      • [redacted finding] private-4-021 Medium
      • [redacted finding] private-4-022 Medium
      • [redacted finding] private-4-023 Medium
      • [redacted finding] private-4-024 Medium
      • [redacted finding] private-4-025 Medium
      • [redacted finding] private-4-026 Medium
      • [redacted finding] private-4-027 Medium
    • Private Fixture #5 C++ Tasks 28 V12 21/28 Codex Sec 6/28 Pashov Opus — Pashov GPT-6 — Devin 6/28 Devin (Deep) 10/28 Claude Sec 14/28 Claude Opus 13/28 Vercel 3/28

      Source redacted (private engagement)

      • [redacted finding] private-5-001 Critical
      • [redacted finding] private-5-002 Critical
      • [redacted finding] private-5-003 Critical
      • [redacted finding] private-5-004 Critical
      • [redacted finding] private-5-005 Critical
      • [redacted finding] private-5-006 Critical
      • [redacted finding] private-5-007 Critical
      • [redacted finding] private-5-008 Critical
      • [redacted finding] private-5-009 High
      • [redacted finding] private-5-010 Critical
      • [redacted finding] private-5-011 High
      • [redacted finding] private-5-012 Medium
      • [redacted finding] private-5-013 Medium
      • [redacted finding] private-5-014 Critical
      • [redacted finding] private-5-015 Critical
      • [redacted finding] private-5-016 Critical
      • [redacted finding] private-5-017 Critical
      • [redacted finding] private-5-018 Critical
      • [redacted finding] private-5-019 Critical
      • [redacted finding] private-5-020 Critical
      • [redacted finding] private-5-021 Critical
      • [redacted finding] private-5-022 Critical
      • [redacted finding] private-5-023 Critical
      • [redacted finding] private-5-024 Critical
      • [redacted finding] private-5-025 Critical
      • [redacted finding] private-5-026 Critical
      • [redacted finding] private-5-027 Critical
      • [redacted finding] private-5-028 High

    Methodology and FAQ

    What determines the ‘ground truth’ for what vulnerabilities exist in a codebase?

    Each public fixture is derived from a published audit report. Ground truth is the set of vulnerabilities those audits surfaced and the project team accepted.

    What about precision?

    Precision is difficult to compare across systems because it depends on how a “bug” is defined and judged. Our ground truth is per-task — each task is a single auditor-confirmed vulnerability — so we can score “did the system find this bug?” objectively. On the other hand, we can’t fairly score “was every other finding it emitted a real bug,” because that depends on “what counts as a bug?”, which is subjective.

    In practice, V12 is tuned to surface fewer, higher-signal findings. Our internal experience in real world settings flags that precision is greater than 35%, but we don’t lead with that number publicly as it’s difficult to falsify.

    How were the other systems run and judged?

    Codex Security, Pashov Skills, Devin Security, Devin Security (Deep), Claude Security, and Vercel Security Review each ran through its own harness. Devin Security (Deep) is Devin Security with its deep scan. We ran Claude Security twice, once on Claude Sonnet 5.5 and once on Claude Opus 5.5. Vercel Security Review reviewed one push of each project to a private GitHub repository. We ran Pashov Skills twice, once on Claude Opus 5.5 and once on Codex GPT-6 Sol. We adapted each harness’s findings to one common finding format.

    All systems are judged by the same judge model. V12 is scored inside its own detect run. The harness systems, Codex Security, Pashov Skills, Devin Security, Devin Security (Deep), Claude Security, and Vercel Security Review, are scored by a separate judgment of their adapted findings.

    Why are some fixtures redacted?

    Some Crypto Security Bench fixtures are from audits we performed under NDA. They are included in aggregate (so the totals are honest), but project names, descriptions, and per-finding titles are redacted. General Security Bench has no redacted fixtures.

    How are language groups assigned?

    Fixtures are assigned by the primary language of the project codebase: Rust, C++, Solidity, and Go in Crypto Security Bench, and Rust, C++, Go, C, Java, Python, Ruby, and Haskell in General Security Bench. Private fixtures keep project names and finding details redacted, but their languages are included so the aggregate results are accurate.

    Where do the public fixtures come from?

    Every public Crypto Security Bench fixture is derived from a published human audit report. The link on each fixture row points to the report PDF. General Security Bench fixtures come from published security audits of open-source projects. Ground truth is the set of vulnerabilities those auditors surfaced and the project team accepted.

    How is detection scored?

    A finding is “detected” when the LLM judge matches the system’s emitted finding to the ground-truth vulnerability based on root cause, affected component, and impact. The judge has no access to the run that produced the finding; it sees only the finding text and the ground truth.

    A subsequent human review of the judge’s decisions on a sampled subset of Crypto Security Bench found no false positives and no false negatives (with a small number of borderline cases that still identified the correct mechanism). Borderlines are treated as detections here.