Skip to content
Business logic Audit finding Advanced

Capacity uses a period-start snapshot a payout cannot lower, so cover is sold against collateral already paid out

The allocator values the vault leg of collateral using a period-start checkpoint, but a payout records its reduced total at the current timestamp, so assets already paid out keep counting as collateral for the rest of the period. This lets cover be committed and settled against capital that has left the vault, overstating capacity by up to 5.5 times the amount paid out.

FaithfulLayney Follow

Originally disclosed on Immunefi

  • Disclosed after under an hour

88565 sc high capacity uses a period start snapshot a payout cannot lower so cover is sold against collateral already paid out

Submitted on Aug 13th 2026 at 20:34:18 UTC by @FaithfulLayney for Audit Comp | Firelight

Description

Brief/Intro

_computeAvailableCapacity values the vault leg of collateral at vault.totalAssetsAt(vault.currentPeriodStart()), while FirelightVault.payout records its post-payout total at Time.timestamp() and Checkpoints.upperLookupRecent returns the last checkpoint with key ≤ the search key. A payout executed at any moment after the period's first second is therefore excluded from the period-start lookup by construction. Assets already transferred out to pay a claim keep counting as collateral for the rest of the period, so commitAllocation accepts — and settleCoverOrder sells — cover the capital-adequacy floor was written to forbid. The contract's own constants bound the overstatement at 5.5× the amount paid out, persisting until the next period boundary: one day on the deployed vault. No attacker is involved; two individually-correct operator actions in their natural order are enough.

Vulnerability Details

Of the three collateral and price inputs to capacity, two are read live and only the vault leg is a snapshot:

Solidity
// contracts/core/CoverOrderAllocator.sol:696-725
        uint256 assetPriceUSD = $.priceFeedAdapter.getPrice($.maxPriceAge);          // :700  LIVE
            ...
        uint256 firstLossBufferUSDCanonical = Decimals.convert(
            config.firstLossBufferToken.balanceOf(config.firstLossBuffer),           // :705  LIVE
            ...
        uint256 totalAssetsCanonical = Decimals.convert(
            $.vault.totalAssetsAt($.vault.currentPeriodStart()),                     // :711  STALE
            ...
        uint256 strictCapacity = availableCollateralCanonical.mulDiv(config.effectiveLeverage, config.minCAR);

The two terms of availableCollateralCanonical are read as of two different times, and they are exactly the two pots the payout waterfall (IncidentManager._executePayout, :621-706; the buffer draw at :658, the vault draw at :684) draws from. The first-loss-buffer leg self-corrects after a payout; the vault leg cannot:

Solidity
// contracts/core/FirelightVault.sol:456-458
    function totalAssetsAt(uint48 timestamp) public view returns (uint256) {
        return _traceTotalAssets.upperLookupRecent(timestamp);
    }

// contracts/core/FirelightVault.sol:952  (inside payout)
            _traceTotalAssets.push(Time.timestamp(), currentActiveAssets - paidFromActive);

Checkpoints.upperLookupRecent (Checkpoints.sol:217-224) returns the last checkpoint with a key lower than or equal to the search key, and the payout's key is Time.timestamp(), greater than currentPeriodStart() for every payout except one mined in the exact first second of the period — which the PoC confirms from the other side, as a control: a payout landing on that exact second does lower the snapshot.

Nothing compensates. There is no per-period "already paid out" accumulator anywhere in the allocator, capacity is validated only at commit or recommit, and settlement never revalidates it: the committed figure is stored at :352 (or :381 on recommit) and thereafter read only at :507, as the base the per-protocol concentration cap is a percentage of. The stale number is consulted exactly once, at :401 (matchingCapacity <= maxCapacity), with :402 chaining totalAllocated <= matchingCapacity onto it — and :388-392 documents that this is deliberate ("A commitment stores the capacity THE MATCHER RAN AGAINST … not a capacity recomputed at transaction time"), which is precisely why the single commit-time check has to be correct.

A period-start valuation is defensible for exposure: withdrawal requests made during the period stay slashable, and payout handles that explicitly by adding withdrawAssets[capturePeriod+1]/[capturePeriod+2] back into activePayableAmount (:916-926). A payout is categorically different — those tokens are transferred out and can never back anything again. payout's own comment says as much, calling the period-start figure "an exposure cap, not a segregated asset bucket" (FirelightVault.sol:909-910): the vault treats it as exposure a payout consumes, while the allocator keeps selling against the same number as if untouched.

The period-start basis is documented, but in one direction only. The @dev at CoverOrderAllocator.sol:690-691 states it, and the sponsor's tests pin the intent on the deposit side: test/coverOrderAllocator/commitAllocation.js:230 asserts "mid-period deposits do NOT inflate capacity", and :248 asserts a commit reverts when it exceeds snapshot-based capacity even if live totalAssets would cover it. Both fix the snapshot below live, making it a conservative floor against an increase. The outflow direction is untested: across the four sponsor test files that call commitAllocation — testVectors.js, commitAllocation.js, capacityConfigCheckpoints.js, premiumTokenDecimals.js — the string payout does not appear once.

Both calls are role-gated and neither role misbehaves: a payout during period P — its window is exactly {capturePeriod, capturePeriod+1} (FirelightVault.sol:1130-1132) — followed by the designed one-commit-per-period allocation for P is the ordinary sequence. The interface's own documented recipe computes capacity from live vault.totalAssets() (ICoverOrderAllocator.sol:40-46), so even a matcher that reads correctly is unprotected: the on-chain check accepts anything up to the stale figure. The constraint that gets bypassed is one the contract asserts about itself three lines above the leverage constant: "Real backing behind sold cover is minCAR / (effectiveLeverage × (1 + tolerance)), so bounding the ratio floors it at 1 / (MAX_LEVERAGE_FACTOR × (1 + tolerance)) regardless of the configured minCAR" (CoverOrderAllocator.sol:79-81) — an absolute floor of 1/5.5 ≈ 18.18% real backing, enforced only by the check at :401, which reads the stale figure. PoC-030 part 2b drives that floor to 0%. This is the exception the scope page's "Privileged actors" rule carves out; that rule reads, in full: "Any bug report that requires a privileged role holder to act within the permissions explicitly granted to that role is out of scope, unless the report demonstrates that the role can exceed its intended permissions or bypass an intended protocol constraint." Neither role exceeds its permissions — acting strictly within them is what bypasses the constraint.

The fix is to value the vault leg at the live figure the sponsor's own recipe already specifies — $.vault.totalAssets() at :711 — or, if a period-start basis must be kept for exposure, to subtract a per-period paid-out accumulator from it before applying leverage.

Impact Details

Protocol insolvency: cover is issued against collateral that has already left the vault. The overstatement is

overstatement = paidFromActiveThisPeriod × assetPriceUSD / 10**priceFeedDecimals
              × (effectiveLeverage / minCAR) × (1 + divergenceToleranceBps / 10_000)

bounded by the contract's own constants — MAX_LEVERAGE_FACTOR = 5 (:82, enforced :665-666) and divergenceToleranceBps ≤ 1_000 (:78, enforced :668-669) — at 5.5× the amount paid out, and it persists to the next period boundary. Nobody gains: the victims are the LPs whose remaining stake now backs more cover than the capital-adequacy policy allows, and the buyers settled into the over-issued tranche who pay premium for cover the vault cannot pay.

Measured on the real FirelightVault wired to the real CoverOrderAllocator:

Run Config Deposited Paid out in-period totalAssets() after Capacity still granted Result
PoC-010 #1 minCAR=12000, effectiveLeverage=12000 (1.0×), tolerance 0 30,000 fXRP 15,000 15,000 30,000e18 15,000e18 canonical USD of cover with zero backing; real backing 0.5 against this configuration's floor of 1.0 — 2× over-issued
PoC-010 #2 (claim from P-1 paid during P) same 30,000 fXRP 20,000 10,000 30,000e18 3× the real collateral
PoC-030 part 2 minCAR=12000, effectiveLeverage=24000 (2.0×), tolerance 0 1,000,000 fXRP 500,000 500,000 2,000,000e18 2,000,000e18 of cover settled; real backing 2500 bps against a 5000 bps policy floor
PoC-030 part 2b same 1,000,000 fXRP 100% of the vault 0 2,000,000e18 1,200,000e18 of cover committed and settled against $0 of staked collateral

In the first two runs the bound is proved exactly rather than inferred: commitAllocation with matchingCapacity = staleFigure is accepted, and with staleFigure + 1 reverts MatchingCapacityOverflow(staleFigure+1, staleFigure). The on-chain maximum is the pre-payout snapshot.

No external precondition is involved — no price move, no depeg, no oracle misbehaviour, no third party; the PoC holds the price at $1.00 and the first-loss buffer at zero. The scope page's known-issues list discloses that a USD price decrease reduces capacity, and that severe collateral drawdowns "can reduce coverage capacity and may cause shortfalls or undercollateralization relative to outstanding cover obligations"; the price leg is read live at :700, so the price case behaves as disclosed, and both disclosures describe capacity that reduces. This is the opposite case: a collateral outflow at constant price against which capacity provably does not reduce — the allocator returns the identical maxCapacity before and after (2,000,000e18 both times, with totalAssets() halved between them).

The in-scope Phase-2 allocator is not deployed yet; the vault proxy it will be wired to, 0x4C18Ff3C89632c3Dd62E796c0aFA5c07c4c1B2b3 on Flare, currently runs the out-of-scope Phase-1 implementation. Read-only eth_call at block 67152319: totalAssets() = 58,333,517.103995 fXRP, periodConfigurations(0) = (epoch 1764682969, duration 86400, startingPeriod 0) — a one-day period. At that TVL a single 10% incident payout (≈ 5.83M fXRP) would license up to ≈ 32M fXRP-equivalent of cover with no collateral behind it before the next boundary; 5.5× is the enforced ceiling, not a configured live value.

References

Repository immunefi-team/audit-comp-firelight @ 42f9ea5e43d88b35197b901acc2a8c24b314fa62:

Proof of Concept

Step-by-step

Roles: CURATOR_ROLE (books the cover order, :198), PAYOUT_ROLE (executes an approved claim), ALLOCATOR_ROLE (commits the period's matching tree at :337 and settles at :446); the capacity config is set by CONFIG_ADMIN_ROLE at initialization. No attacker, and no user behaviour beyond the ordinary product flow — LPs deposit, the buyer approves premium: the capacity overstatement itself is produced by two individually-correct operator actions in their natural order.

  1. LPs stake. The vault's totalAssets() and its period-start checkpoint agree.
  2. Period P begins. currentPeriodStart() is fixed for the rest of the period, and _computeAvailableCapacity will read the vault leg at exactly that key (CoverOrderAllocator.sol:711).
  3. A claim is paid during P. FirelightVault.payout transfers assets out and pushes the reduced total at Time.timestamp() (:952) — a key strictly greater than currentPeriodStart(). totalAssets() drops; totalAssetsAt(currentPeriodStart()) does not, because upperLookupRecent only considers keys ≤ the search key.
  4. The allocator commits P's matching tree. commitAllocation validates matchingCapacity against the stale figure and accepts it. The bound is proved exactly: the stale figure is accepted and staleFigure + 1 reverts MatchingCapacityOverflow(staleFigure+1, staleFigure).
  5. Cover settles against it. settleCoverOrder consumes commit.totalAvailableCapacity with no revalidation (:507-509), so the over-issued cover becomes live cover.
  6. Control 1: with no in-period payout, the same commit is bounded by the real collateral. Control 2: a payout mined in the exact period-start second does lower the snapshot — which isolates the checkpoint key as the root cause.

Net result: cover in force 30,000e18 canonical USD against 15,000e18 of real collateral — real backing 0.5 against this configuration's floor of 1.0, i.e. twice the cover the policy permits, with no attacker and no external condition.

Runnable test A — the bound is exactly the stale snapshot

Reproduced from a clean checkout at the competition commit with this single file added. Local Hardhat only; no transaction was sent to any live or public network.

Bash
git clone https://github.com/immunefi-team/audit-comp-firelight.git
cd audit-comp-firelight
git checkout 42f9ea5e43d88b35197b901acc2a8c24b314fa62      # branch v1_audit_ready HEAD
npm install                                                # postinstall runs patch-package
mkdir -p test/poc && cp h010_capacity_stale_period_start_snapshot.js test/poc/
npx hardhat test test/poc/h010_capacity_stale_period_start_snapshot.js

test/poc/h010_capacity_stale_period_start_snapshot.js:

JavaScript
// PoC 010 — CoverOrderAllocator._computeAvailableCapacity values staked collateral from a
// period-START checkpoint (`totalAssetsAt(currentPeriodStart())`, CoverOrderAllocator.sol:710-715)
// while FirelightVault.payout writes its post-payout checkpoint at `Time.timestamp()`
// (FirelightVault.sol:952), i.e. strictly AFTER the period start.
//
// Consequence: assets that have already left the vault through an incident payout executed
// inside the current period are still counted as collateral when the period's cover capacity
// is computed. The first-loss-buffer term of the same sum IS read live
// (`firstLossBufferToken.balanceOf(...)`, :704-709) — the two terms of
// `availableCollateralCanonical` are read at different times.
//
// This test uses the REAL FirelightVault rather than MockCoverOrderAllocatorVault. The mock CAN
// return a period-start value distinct from the live one — `setTotalAssetsAtSnapshot` (:48-51) sets
// `_hasSnapshot`, after which `totalAssetsAt` (:198-199) returns
// `_hasSnapshot ? _totalAssetsAtSnapshot : _totalAssets` — and the sponsor's own suite uses exactly
// that setter at test/coverOrderAllocator/commitAllocation.js:237. But the mock's `payout` (:251) is
// `pure` and moves nothing, so a mock-based test could only restate a hand-set divergence. Only the
// real vault shows that a real `payout()` PRODUCES the divergence, via the checkpoint push at
// FirelightVault.sol:952 keyed on `Time.timestamp()`. That is the actual claim.
//
// Run:  npx hardhat test test/poc/h010_capacity_stale_period_start_snapshot.js

const { loadFixture, time } = require('@nomicfoundation/hardhat-network-helpers')
const { expect } = require('chai')
const { ethers, upgrades } = require('hardhat')
const { StandardMerkleTree } = require('@openzeppelin/merkle-tree')
const { deployVault, computeMarketId, computeProtocolConcentrationHash } = require('../setup/fixtures.js')

const abiCoder = ethers.AbiCoder.defaultAbiCoder()

const PROTOCOL = 'Morpho'
const MARKET = ethers.encodeBytes32String('market-A')

const randomSigner = async () => {
  const wallet = ethers.Wallet.createRandom().connect(ethers.provider)
  await ethers.provider.send('hardhat_setBalance', [wallet.address, '0x3635C9ADC5DEA00000'])
  return wallet
}

// Deploys the real vault plus a real CoverOrderAllocator wired to it.
async function setup () {
  const ctx = await loadFixture(
    deployVault.bind(null, {
      decimals: 6,                              // FXRP has 6 decimals on Flare
      initial_deposit_limit: '1000000000000',   // 1,000,000 FXRP
      period_configuration_duration: 604800     // 1 week
    })
  )

  const deployer = ctx.deployer
  const admin = await randomSigner()
  const curator = await randomSigner()
  const allocatorRole = await randomSigner()
  const configAdmin = await randomSigner()
  const adminRole = await randomSigner()
  const premiumCollector = await randomSigner()
  const flbWallet = await randomSigner()
  const buyer = await randomSigner()
  const payoutRecipient = await randomSigner()

  const MockERC20 = await ethers.getContractFactory('MockERC20')
  const usdc = await MockERC20.connect(deployer).deploy('MockUSDC', 'mUSDC', 6)   // premium + FLB token

  // $1.00 per FXRP with 18-dec feed => canonical USD == FXRP units * 1e12. Keeps the
  // arithmetic in the assertions exact and independent of any price move.
  const MockAggregator = await ethers.getContractFactory('MockAggregatorV3')
  const priceFeed = await MockAggregator.connect(deployer).deploy(18, 10n ** 18n)

  const CoverNFTFactory = await ethers.getContractFactory('CoverNFT')
  const coverNFT = await upgrades.deployProxy(
    CoverNFTFactory,
    ['Firelight Cover', 'FLCOVER', '', admin.address, deployer.address, ethers.ZeroAddress, ethers.ZeroAddress],
    { kind: 'transparent' }
  )

  const capacityConfig = {
    minCAR: 12000,               // MIN_CAR_BPS
    firstLossBufferToken: await usdc.getAddress(),
    firstLossBuffer: flbWallet.address,   // deliberately left at zero balance
    effectiveLeverage: 12000,    // lev/minCAR == 1.0 so capacity == collateral, exactly
    minOrderMarketCoverAmount: 1,
    divergenceToleranceBps: 0    // no tolerance: the bound is the raw formula
  }

  const initParams = {
    vault: ctx.firelight_vault.target,
    premiumCollector: premiumCollector.address,
    coverNFT: await coverNFT.getAddress(),
    priceFeedAdapter: await priceFeed.getAddress(),
    maxPriceAge: 7 * 24 * 3600,
    premiumTokens: [await usdc.getAddress()],
    admin: admin.address,
    adminRole: adminRole.address,
    curatorRole: curator.address,
    allocatorRole: allocatorRole.address,
    configAdminRole: configAdmin.address,
    initialProtocolConcentrations: [{ protocol: PROTOCOL, chainId: 1, maxProtocolConcentrationBps: 10000 }],
    newMarkets: [{ chainId: 1, protocol: PROTOCOL, market: MARKET }],
    capacityConfig
  }

  const Factory = await ethers.getContractFactory('CoverOrderAllocator')
  const allocator = await upgrades.deployProxy(Factory, [initParams], {
    kind: 'transparent',
    unsafeAllow: ['missing-initializer-call']
  })

  await coverNFT.connect(admin).grantRole(ethers.id('MINTER_ROLE'), await allocator.getAddress())

  return {
    ...ctx, allocator, coverNFT, usdc, priceFeed,
    admin, curator, allocatorRole, configAdmin, premiumCollector, flbWallet, buyer, payoutRecipient,
    marketId: computeMarketId(1, PROTOCOL, MARKET),
    concHash: computeProtocolConcentrationHash(1, PROTOCOL)
  }
}

describe('POC-010 capacity uses a stale period-start assets checkpoint', function () {
  it('sells a full period of cover against collateral that a payout already removed', async () => {
    const c = await setup()
    const vault = c.firelight_vault
    const DEPOSIT = 30_000_000_000n        // 30,000 FXRP (6 dec)
    const PAYOUT  = 15_000_000_000n        // 15,000 FXRP — exactly half
    const E12 = 10n ** 12n                 // FXRP(6) -> canonical USD(18) at $1.00

    // ---- period P0: LPs deposit -------------------------------------------------
    await c.utils.mintAndApprove(DEPOSIT, c.users[0])
    await vault.connect(c.users[0]).deposit(DEPOSIT, c.users[0].address)
    expect(await vault.totalAssets()).to.equal(DEPOSIT)

    // ---- a cover order is booked for the next period ----------------------------
    const p0 = await vault.currentPeriod()
    await c.allocator.connect(c.curator).createCoverOrder(
      c.buyer.address,
      c.payoutRecipient.address,
      'rXRPbeneficiary',
      await c.usdc.getAddress(),
      [{ marketId: c.marketId, coverRateAnnual: 500, coverAmount: DEPOSIT * E12 }], // 30,000 USD of cover
      0 // NEW
    )
    const orderId = 0n
    const order = await c.allocator.getCoverOrder(orderId)
    expect(order.period).to.equal(p0 + 1n)

    // ---- roll into period P1 ----------------------------------------------------
    await time.increase(604800)
    await c.priceFeed.setAnswer(10n ** 18n)   // refresh the feed after the time jump
    const p1 = await vault.currentPeriod()
    expect(p1).to.equal(p0 + 1n)

    const periodStart = await vault.currentPeriodStart()
    const snapshotAtPeriodStart = await vault.totalAssetsAt(periodStart)
    expect(snapshotAtPeriodStart).to.equal(DEPOSIT)

    // ---- an incident captured inside P1 is paid out, inside P1 ------------------
    // (this is the ordinary flow: IncidentManager.approveCurrentAssessment ->
    //  FirelightVault.payout, with capturePeriod == currentPeriod)
    const captureTimestamp = periodStart
    await vault.connect(c.payout_signer).payout(c.payout_receiver.address, PAYOUT, captureTimestamp)

    // Half the collateral is gone.
    expect(await vault.totalAssets()).to.equal(DEPOSIT - PAYOUT)
    expect(await c.token_contract.balanceOf(vault.target)).to.equal(DEPOSIT - PAYOUT)

    // ...but the period-start checkpoint the capacity formula reads is untouched,
    // because payout pushed its checkpoint at Time.timestamp() > currentPeriodStart().
    expect(await vault.totalAssetsAt(periodStart)).to.equal(DEPOSIT)

    // ---- the allocator still grants the FULL pre-payout capacity ----------------
    const staleCapacity  = DEPOSIT * E12                   // 30,000 USD (18 dec)
    const honestCapacity = (DEPOSIT - PAYOUT) * E12        // 15,000 USD (18 dec)

    // one wei above the stale figure is rejected -> proves maxCapacity == staleCapacity
    const leaves = [[orderId, [[c.marketId, DEPOSIT * E12]]]]
    const tree = StandardMerkleTree.of(leaves, ['uint256', '(bytes32,uint256)[]'])

    await expect(
      c.allocator.connect(c.allocatorRole).commitAllocation(p1, tree.root, staleCapacity, staleCapacity + 1n)
    ).to.be.revertedWithCustomError(c.allocator, 'MatchingCapacityOverflow')
      .withArgs(staleCapacity + 1n, staleCapacity)

    // exactly the stale figure is accepted
    await c.allocator.connect(c.allocatorRole).commitAllocation(p1, tree.root, staleCapacity, staleCapacity)

    const commit = await c.allocator.getAllocationCommitment(p1)
    expect(commit.totalAvailableCapacity).to.equal(staleCapacity)
    expect(commit.totalAvailableCapacity).to.equal(honestCapacity * 2n)  // 2x the real collateral

    // ---- and the cover actually settles at that size ---------------------------
    const premium18 = await (async () => {
      const o = await c.allocator.getCoverOrder(orderId)
      return o.totalPremiumAmount
    })()
    const premiumNative = (premium18 + 10n ** 12n - 1n) / 10n ** 12n   // ceil to 6 dec
    await c.usdc.mint(c.buyer.address, premiumNative)
    await c.usdc.connect(c.buyer).approve(await c.allocator.getAddress(), premiumNative)

    await c.allocator.connect(c.allocatorRole).settleCoverOrder(
      orderId,
      [{ marketId: c.marketId, allocatedCover: DEPOSIT * E12 }],
      tree.getProof(0)
    )

    const settled = await c.allocator.getCoverOrder(orderId)
    expect(settled.status).to.equal(1) // MATCHED
    expect(settled.allocatedCoverAmount).to.equal(DEPOSIT * E12)

    // ---- the invariant that is broken ------------------------------------------
    // cover in force for period P1, valued in USD
    const coverInForceUSD = settled.allocatedCoverAmount
    // collateral actually available to pay a P1 claim, valued in USD
    const flbUSD = (await c.usdc.balanceOf(c.flbWallet.address)) * E12
    const realCollateralUSD = (await vault.totalAssets()) * E12 + flbUSD

    console.log('    cover in force  (USD 18d):', coverInForceUSD.toString())
    console.log('    real collateral (USD 18d):', realCollateralUSD.toString())
    console.log('    unbacked cover  (USD 18d):', (coverInForceUSD - realCollateralUSD).toString())

    // The configured backing floor is effectiveLeverage/minCAR = 12000/12000 = 1.0, i.e. the
    // contract promised >= 1.00 USD of collateral per USD of cover. It has 0.50.
    expect(realCollateralUSD).to.equal(honestCapacity)
    expect(coverInForceUSD).to.equal(realCollateralUSD * 2n)
  })

  // The operationally natural variant: an incident captured late in period P-1 is assessed
  // and paid early in period P (payout window = {P-1, P}), and the matcher commits P's
  // allocation afterwards. No incident of period P has to exist at all.
  it('previous-period claim paid inside period P is invisible to period P capacity', async () => {
    const c = await setup()
    const vault = c.firelight_vault
    const DEPOSIT = 30_000_000_000n
    const PAYOUT  = 20_000_000_000n
    const E12 = 10n ** 12n

    await c.utils.mintAndApprove(DEPOSIT, c.users[0])
    await vault.connect(c.users[0]).deposit(DEPOSIT, c.users[0].address)

    // roll to period P-1, then to period P; both period-start snapshots read DEPOSIT
    await time.increase(604800)
    const pPrev = await vault.currentPeriod()
    const prevStart = await vault.currentPeriodStart()

    await time.increase(604800)
    await c.priceFeed.setAnswer(10n ** 18n)
    const p = await vault.currentPeriod()
    const pStart = await vault.currentPeriodStart()
    expect(p).to.equal(pPrev + 1n)
    expect(await vault.totalAssetsAt(pStart)).to.equal(DEPOSIT)

    // claim for the PREVIOUS period, executed now (allowed: current == capturePeriod + 1)
    await vault.connect(c.payout_signer).payout(c.payout_receiver.address, PAYOUT, prevStart)
    expect(await vault.totalAssets()).to.equal(DEPOSIT - PAYOUT)          // 10,000 FXRP left

    // period P capacity is still computed off the untouched period-start checkpoint
    expect(await vault.totalAssetsAt(pStart)).to.equal(DEPOSIT)

    await expect(
      c.allocator.connect(c.allocatorRole).commitAllocation(p, ethers.id('root'), 0, DEPOSIT * E12 + 1n)
    ).to.be.revertedWithCustomError(c.allocator, 'MatchingCapacityOverflow')
      .withArgs(DEPOSIT * E12 + 1n, DEPOSIT * E12)

    await c.allocator.connect(c.allocatorRole).commitAllocation(p, ethers.id('root'), DEPOSIT * E12, DEPOSIT * E12)
    const commit = await c.allocator.getAllocationCommitment(p)
    // 30,000 USD of capacity granted against 10,000 FXRP (= 10,000 USD) of real collateral
    expect(commit.totalAvailableCapacity).to.equal(DEPOSIT * E12)
    expect(commit.totalAvailableCapacity).to.equal((await vault.totalAssets()) * E12 * 3n)
  })

  it('control: with no in-period payout the same commit is bounded by the real collateral', async () => {
    const c = await setup()
    const vault = c.firelight_vault
    const DEPOSIT = 30_000_000_000n
    const E12 = 10n ** 12n

    await c.utils.mintAndApprove(DEPOSIT, c.users[0])
    await vault.connect(c.users[0]).deposit(DEPOSIT, c.users[0].address)

    await time.increase(604800)
    await c.priceFeed.setAnswer(10n ** 18n)
    const p1 = await vault.currentPeriod()

    // no payout this period -> the bound equals the live collateral
    await expect(
      c.allocator.connect(c.allocatorRole).commitAllocation(p1, ethers.id('root'), 0, DEPOSIT * E12 + 1n)
    ).to.be.revertedWithCustomError(c.allocator, 'MatchingCapacityOverflow')

    await c.allocator.connect(c.allocatorRole).commitAllocation(p1, ethers.id('root'),

The original report as published on Immunefi, by FaithfulLayney. Images and videos are our own copies; raw HTML is shown as text. View it on Immunefi.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

Likely the capacity calculation reads the vault's assets from a period-start checkpoint while payouts write their reduced total at the current timestamp, so the lookup never sees the reduction.

Impact

Cover could be issued against collateral that has already left the vault, overstating capacity by up to 5.5 times the amount paid out until the next period boundary, harming LPs and buyers of the over-issued cover.

What the attacker needed

No attacker needed; a payout occurs mid-period; allocator commits cover in same period

The fix

The vault leg should be valued at the live total assets figure, or a per-period paid-out accumulator should be subtracted before applying leverage.

How it was found

  1. Liquidity providers deposit into the vault so its live total and period-start checkpoint agree.
  2. A new period begins and the period-start timestamp is fixed for the rest of the period.
  3. A claim is paid out during the period, transferring assets out and recording the reduced total at the current timestamp.
  4. The allocator commits the period's matching tree, validating capacity against the unchanged period-start figure.
  5. Cover settles against the committed capacity without any revalidation.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

A vault holds the money that backs insurance-style cover. Capacity is how much cover the system thinks it can safely sell, and it is calculated from how much money the vault holds. The bug is that this calculation looks at how much money the vault held at the start of the day, not how much it holds now, so money paid out to a claim earlier in the day is still counted as if it were there.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by FaithfulLayney

View all

2 more disclosed reports, best first.

More from Firelight

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.