Overview
This audit reviews Fermah Strata, a liquidity-sensitive LMSR market. A Strata market implements a liquidity-sensitive logarithmic market scoring rule (LS-LMSR) over N mutually exclusive outcomes. It operates on a buy-only basis: participants spend stablecoins to acquire shares in a particular outcome, with each outcome's price representing its marginal probability. Upon resolution, each winning share can be redeemed for one unit of collateral, less a volume-scaled settlement fee.
The audit was conducted over two weeks and involved a comprehensive review of the relevant smart contracts.
During the assessment, we identified one high-severity issue that allows an attacker to observe a market resolution transaction and front-run it by purchasing shares in the winning outcome to capture profits. In addition, we identified one medium-severity issue, three low-severity issues, and ten informational issues.
All identified issues were either remediated or acknowledged by the development team, and the corresponding fixes were subsequently verified by our auditors.
Following the remediation phase, we conclude that the audit has contributed to improving the protocol's overall security posture and code quality.
Scope
The analyzed resources are located on:
https://github.com/fermah-labs/strata/tree/989ef62e3db320d56d34f9538c455b5f480eee5d
The issues described in this report were fixed in the following commit:
https://git.fermah.xyz/fermah-labs/strata/tree/449fdaf596feaf4392101fe1ca5b0e6a38520822
Summary
Weaknesses
This section contains the list of discovered weaknesses.
FERM1-1 | RESOLVING A MARKET DURING THE BETTING WINDOW ALLOWS FRONT-RUNNING OF THE OUTCOME
Severity:
Status:
Fixed
Path:
contracts/src/MarketCore.sol#L1028-L1041
Description:
A market is resolved when its resolver calls one of resolve(), resolveScalar() or resolveJoint(). All of them end in _settle(), which marks the market resolved and fixes the winning inventory:
function resolve(
uint256 winner
) external nonReentrant {
if (msg.sender != resolver) {
revert OnlyResolver();
}
if (_hasScalarLeg()) {
revert InvalidResolutionKind();
}
_resolveCategorical(winner);
}
None of these functions check closeTime. Meanwhile, _credit() only stops a buy once the market is resolved or closeTime has passed:
if (resolved) {
revert AlreadyResolved();
}
if (block.timestamp >= closeTime) {
revert MarketClosed();
}
As a result, when a market is resolved before its closeTime, the resolving transaction is the first public disclosure of the outcome. Anyone who sees it can place a buy on the winning outcome ahead of it. The gasless reportWithAuthorization() path makes this easier: the relayer holds the signed outcome and can buy first, then submit the signature.
The front-runner buys the winning shares at the pre-resolution LMSR price and redeems them right after at close to 1 collateral per share.
Note that DisputeResolver._openProposal() already accounts for this and pulls closeTime in before publishing a proposal. However, that happens in the same transaction, so a buy ordered before the propose transaction is still possible, and the attackers can still benefit from it.
Remediation:
Consider requiring that betting has already closed before a non-void resolution is accepted, so that the resolver must stop betting in an earlier transaction (via setCloseTime()) before revealing the outcome:
function _settle(
uint256[] memory weights
) internal {
++ if (block.timestamp <= closeTime && _weightedShares(_q) != 0) {
++ revert MarketStillOpen();
++ }
resolved = true;
...
}
resolveVoid() can stay exempt, since a buy placed right before a void is refunded at par and gives no advantage. Closing betting and reporting in the same transaction does not prevent the issue, because the front-running buy executes earlier in the block while closeTime is still in the future.
FERM1-6 | SEED PROVIDER CAN MAKE RISK-FREE UNDERDOG BETS AT THE EXPENSE OF THE TREASURY
Severity:
Status:
Acknowledged
Path:
contracts/src/MarketCore.sol#L1390-L1396
Description:
The seed provider can make an underdog bet with no additional downside and use it to extract revenue that would otherwise go to the treasury and creator.
The seed provider is the sponsored funder that posted the seed, or the creator of a self-funded market (in which case it only gives up its own creatorBps share of the house take).
The issue is that the provider's losing bet is used to refill its own seed before the remaining funds are split between the treasury and creator. When the favourite's winners are owed more than the pot, the 95% floor in _setSeedScale() caps their haircut and the seed pays the remaining shortfall. _sweep() then refunds the seed from the recoverable balance, which includes losing stakes, before the house take is split:
uint256 seedRefund = Math.min(_pendingSeedRefund(), recoverable);
...
swept = recoverable - seedRefund;
uint256 creatorCut = Math.mulDiv(swept, creatorBps, BPS_DENOM);
uint256 treasuryCut = swept - creatorCut;
This could create the following outcome:
- If the favourite wins, the provider's losing bet fills the seed shortfall that the seed would have paid anyway, so the bet costs it nothing (up to the size of that shortfall).
- If the underdog wins, the provider receives its full seed back plus the betting payout, while the treasury and creator receive less house revenue. The provider therefore gets a free option on the underdog, funded by the house.
For example, consider a binary market with alphaBps = 300, bMin = 10,000 USDC (seed 10,000 USDC) and the default halfTaper, so b = bMin throughout:
- Bob bets 13,000 USDC on YES and receives 19,725.37 shares. Carol then bets 4,000 USDC on NO and receives 13,636.99 shares. The pot is 17,000 USDC and YES is priced at 60.40%.
- If YES wins, the winners are owed
19,725.37 * 0.9803 = 19,336.78(keepBps = 9,803from the fee curve at a 17,000 USDC volume with the defaulthalfTaper), which exceeds the pot.seedScaleBpsis floored at 9,500, so the winners receive 18,369.94 and the seed covers the 1,369.94 shortfall. - Just before the market closes, the seed provider bets 1,000 USDC on NO from another address and receives 2,402.90 shares. The resulting outcomes are:
| Without the provider's bet | With the 1,000 USDC NO bet | |
|---|---|---|
| YES wins: seed refund | 8,630.06 | 9,630.06 |
| YES wins: provider P&L | −1,369.94 | −1,369.94 (the 1,000 loss for NO bet is offset by a 1,000 higher seed refund) |
| NO wins: provider payout | 0 | 2,355.56 |
| NO wins: provider P&L | 0 | +1,355.56 |
| NO wins: house take | 3,631.66 | 2,276.09 |
If YES wins, the provider's 1,000 USDC NO bet loses and enters the pot. This reduces the seed's shortfall one-for-one, from 1,369.94 to 369.94, so the provider loses its 1,000 USDC bet but gets exactly 1,000 USDC more of its seed back.
If NO wins, the provider wins its bet. Because the seed is not needed to cover the NO winners, its 1,355.56 USDC profit comes out of funds that would otherwise contribute to the house take, which falls from 3,631.66 to 2,276.09 USDC.
A bet larger than the 1,369.94 shortfall is no longer free: at 2,000 USDC, the provider loses 2,000 instead of 1,369.94 if YES wins.
As a result, a seed provider can repeatedly extract house revenue from qualifying markets while taking no additional risk. It only needs to trade from another address and place the bet shortly before the market closes.
Remediation:
Consider charging a fee on every stake at buy time that accrues to the house in every outcome, so a hedge against the seed is never free.
Commentary from the client:
Partially fixed by incurring a cost for the hedge.
FERM1-7 | YIELD IS SHARED BY STAKE SIZE ONLY, SO A LATE STAKE CAN TAKE MOST OF THE ACCRUED YIELD RISK-FREE
Severity:
Status:
Acknowledged
Path:
contracts/src/MarketCore.sol#L1259-L1269
Description:
_yieldShare() splits the whole net yield pool by stake alone:
function _yieldShare(
uint256 stake
) private view returns (uint256) {
if (netYieldPool == 0 || totalVolume == 0) {
return 0;
}
return Math.mulDiv(netYieldPool, stake, totalVolume);
}
However, it ignores when the stake entered and how long it was in the vault. A stake placed one minute before settlement, possibly never deposited, receives the same share as one that was in the vault for the whole market. Since depositToYield() also deposits the seed, which is not part of totalVolume, the seed s yield further enlarges the pool that late stakes can claim.
As a result, anyone can enter shortly before settlement and take most of the yield accrued by earlier bettors.
For example, when a market is voided, every stake is refunded at par. A late bettor therefore gets their entire stake back plus a stake weighted share of the yield, even though their capital was never deposited into the vault, or was deposited only for a short time. This is especially easy on a conditional market: once its condition has publicly failed but betting is still open, the void is certain, so the late stake carries no risk at all.
Remediation:
Consider distributing yield based on time weighted deposited capital (e.g. tracking stake seconds since the last deposit), or only giving yield to stakes that were actually deposited into the vault.
Commentary from the client:
The yield split may incorrect when the vault loses value and then recovers but it's intended as joining later to a market should not have a different benefit in terms of vault losses. We don't want vault fluctuations to dictate good or bad timing to enter a market.
FERM1-11 | BASE'S TRANSACTION GAS CAP PREVENTS ORDINARY BUYS IN 32-OUTCOME MARKETS
Severity:
Status:
Fixed
Path:
contracts/src/MarketCore.sol:buy#L578-L596, contracts/src/MarketCore.sol:_credit#L659-L704, contracts/src/LsLmsr.sol:sharesBoughtImpl#L137-L167
Description:
The buy function lets a bettor purchase shares in one market outcome. It calls _credit, which uses LsLmsr.sharesBought to calculate the shares through repeated full-book cost calculations. This applies to every bettor, including users of the gasless buyWithAuthorization route.
All supported market configurations should be tradable on Base at normal stake sizes. In particular, MAX_OUTCOMES allows 32 outcomes so a five-leg binary parlay can be created, and the gas benchmark treats a 100 USDC buy in this configuration as supported.
However, the limit was chosen against Base's 100M block gas limit instead of its 16,777,216 per-transaction gas cap. The repository's own optimized benchmark shows that the 32-outcome, 100 USDC buy uses more than 25M gas. A user cannot raise the transaction gas limit to compensate: Base rejects a regular transaction above the cap, while a transaction at or below it runs out of gas. The authorized and basket-buy paths do at least the same pricing work and therefore do not provide a workaround.
An ordinary failure scenario is:
- A creator deploys a five-leg binary parlay with 32 outcomes, which passes the
MAX_OUTCOMEScheck. - A bettor submits a direct 100 USDC buy.
- The buy needs more than 25M gas, so it cannot execute under Base's 16,777,216 transaction cap and reverts.
- The market remains deployed, but its advertised trading flow is unavailable for this normal stake size.
Remediation:
Benchmark every advertised buy path against Base's per-transaction cap with enough safety margin, then lower MAX_OUTCOMES and constrain other gas-sensitive inputs as needed. The pricing implementation should also avoid repeating full-book calculations during bisection.
FERM1-9 | PROTOCOL RESOLVER FEE IGNORES COLLATERAL DECIMALS
Severity:
Status:
Fixed
Path:
contracts/src/MarketFactory.sol
Description:
The protocol resolver fee is calculated in raw token units without accounting for the collateral's decimals. Since ResolverFeeConfig uses one global baseFee and perSecondRate, the fee is only correctly priced for one decimal width.
For example, with baseFee = 250,000 and perSecondRate = 4, a 90-day market pays:
- USDC (6 decimals): ~$31.35
- DAI (18 decimals): ~$0.000000000031 Thus, an 18-decimal stablecoin can effectively bypass the resolver fee.
Root Cause
The fee is taken directly from the global configuration:
terms.baseFee = feeConfig.baseFee();
terms.perSecondRate = feeConfig.perSecondRate();
terms.amount = terms.baseFee + terms.perSecondRate * horizon;
Unlike minBMin and halfTaper, these values are never scaled using collateral.decimals().
Remediation:
Scale baseFee, perSecondRate according to the collateral's decimals, using the same approach as minBMin and halfTaper.
FERM1-16 | PARLAY BASKETS ADD TOO MUCH LIQUIDITY DEPTH: EACH SELECTED CELL IS COUNTED, THOUGH ONLY ONE CAN PAY
Severity:
Status:
Fixed
Path:
contracts/src/MarketCore.sol#L1390-L1396
Description:
Parlay baskets pay an additional spread for every selected outcome cell, even though only one cell normally determines the payout. At the default α = 300 bps, this can cause users to lose money even when their bets win.
For example:
the market covers four games (Chiefs, Eagles, 49ers, Cowboys), creating 16 possible outcomes.
Alice bets $100 that the Chiefs win, regardless of the other three games. This covers 8 of the 16 possible outcomes. The market displays an 81.71% probability, suggesting a payout of $119.95 if she wins.
However, the addition spread increases her actual cost per share to $1.526, even though each winning share pays only $1. Her $100 buys 65.28 shares per outcome.
All four teams win, so Alice is correct. After the 1.99% settlement fee, she receives just $63.98, losing $36.02 on a winning bet.
The other bettors' payouts remain unchanged at $2,501.06, while the house take increases by $36.02.
Root cause
Liquidity depth is calculated from the total shares across all outcome cells:
b = max(bMin, α * totalShares); // LsLmsr.sol:54-65
Once α, rather than the seed floor bMin, determines the depth, every share added to any cell increases the total shares used to calculate liquidity depth. This introduces an additional spread of α H(p) per share, where H(p) is the entropy of the outcome probabilities. However, the displayed prices (priceBps and marginalPriceBps) do not include this spread.
When buying a basket, it adds the same number of shares to every selected cell and recalculates the cost:
// LsLmsr.sol:212-231
for (uint256 i = 0; i < n; ++i) {
prev[i] = q[cells[i]];
q[cells[i]] = prev[i] + delta;
}
uint256 c = costImpl(q, alphaBps, bMin);
A basket covering |S| cells therefore increases totalShares by |S| · delta. When α determines the depth, this increases the liquidity depth used to price the purchase. However, only one selected cell normally determines the payout, so the basket receives at most one dollar per share when it wins.
The basket pays the additional spread for every selected cell, even though it can only receive one winning payout.
As the impact, users pay more than the displayed prices suggest and can lose money even when their bets win. The larger the basket, the more times the additional spread is charged. The excess accrues to the house rather than other bettors.
Remediation:
Calculate liquidity depth based on the shares that can actually be paid out, counting a basket's delta once rather than once per selected cell. Alternatively, scale and enforce alpha according to the number of outcome cells. Update displayed prices and documentation to disclose the actual basket cost.
FERM1-2 | PRICEBPS() IS DOCUMENTED AS THE MARGINAL PRICE BUT RETURNS THE SOFTMAX PROBABILITY
Severity:
Status:
Fixed
Path:
docs/src/mechanism.md, contracts/src/LsLmsr.sol#L111-L116
Description:
priceBps() and the priceBps in the Bought event return the market's displayed probability. However, the documentation defines the marginal price as the derivative of the cost function, i.e. the price a user pays for the next share:
The marginal price of outcome `i` is `∂C/∂qᵢ`, always a probability in `(0, 1)`,
and the `N` prices sum to one; ...
And the NatSpec describes priceBps() as exactly this marginal price:
/// @notice Marginal price of `outcome` in basis points:
/// `2^(q_i/b) / Sigma_j 2^(q_j/b)`, from the shifted exponentials so
/// it stays in range. Each price is a true probability and the N
/// prices sum to 10_000 (up to flooring dust). ...
function priceBpsImpl(
/// @notice Marginal price of `outcome` in basis points.
function priceBps(
When the market's liquidity grows beyond bMin, the actual cost of the next share becomes higher than the displayed probability.
The displayed value is the softmax probability p_i, which equals the marginal cost only while b is fixed. Once alphaBps * Σq > bMin, b = α * Σq also grows with every share bought, so the cost function C = b * log2(Σ_j 2^(q_j / b)) gives:
∂C/∂q_i = (∂b/∂q_i) * log2(Z) + b * ∂log2(Z)/∂q_i Z = Σ_j 2^(q_j / b)
= α * log2(Z) + (p_i − α * Σ_j p_j * q_j / b)
= p_i + α * H(p) H(p) = −Σ_j p_j * log2(p_j)
So the actual marginal cost is higher than priceBps() by α * H(p).
The trade itself is calculated correctly by buy() using sharesBought(). The issue is that an integrator relying on the NatSpec and documentation would use priceBps() as the marginal price to calculate the expected shares and minSharesOut.
Remediation:
Clarify that priceBps() represents the displayed probability, not the actual execution price. Integrators should use sharesBought() or a dedicated quote function to calculate the expected number of shares.
FERM1-3 | SEEDED PARLAYS REFUND LOSING BETS WHEN THE WINNING CELL IS EMPTY
Severity:
Status:
Fixed
Description:
On a seeded market, the seed acts as the counterparty of the bettors: when the winners are owed more than the pot, the seed pays the difference. So the seed loses whenever a bettor wins against a thin book.
However, when a market resolves to a cell that nobody bought, MarketCore treats it as void and refunds all stakes:
function _isVoid() internal view returns (bool) {
return _weightedShares(_q) == 0;
}
In that case every losing stake is returned, so the seed provider, which pays the bettor when the bettor wins, gains nothing when the bettor loses.
In a parlay with a lot of outcomes but thin liquidity (16 cells for 4 legs, 32 for 5 legs), many cells end up with no shares. Consider a bettor who buys a single cell. A single cell rarely wins, but at resolution there are three cases:
| Result | Bettor | Seed |
|---|---|---|
| The bettor's cell wins | paid out; on a thin book most of the payout comes from the seed | loses |
| Another cell held by someone else wins | loses the stake | - |
| An empty cell wins | refunded in full (void) | - |
The second case is the only one in which the bettor loses, and it requires someone else to hold the exact realized cell. When the bettor is alone, or when bets are concentrated on a few cells, it rarely or never happens. The bettor therefore keeps the upside of the bet, which the seed pays for, while its downside is mostly removed by the void.
As a result, a bettor can repeatedly take a positive expectation position against the seed in a thin liquidity market.
Remediation:
Consider charging a fee on each bet at execution time that accrues to the seed provider and is not refunded on a void, so the seed is compensated for the risk it takes as the counterparty regardless of how the market resolves.
FERM1-5 | SEED-COVER SCALING CAN REDUCE AN EARLIER WINNER'S PAYOUT AFTER A LATER BET
Severity:
Status:
Fixed
Path:
contracts/src/MarketCore.sol#L1067-L1068, docs/src/mechanism/evidence.md
Description:
Following the documentation, a later bettor should not be able to dilute an earlier bettor's position:
## No dilution: an early bet is untouchable
A separate scripted scenario isolates the core fairness promise. An early small
bettor's payout is measured twice: once in a quiet market, once with a late whale
piling in on the same side. Under LS-LMSR the early bettor's payout is
**byte-identical** in both runs — the whale cannot dilute shares already bought.
However, on a seeded market (bMin > 0), this does not hold when the amount owed to winners exceeds the pot. At resolution, _setSeedScale() compares the nominal winner redemption with totalVolume, and scales every winning claim down by up to 5% when the pot does not cover it:
function _setSeedScale() private {
seedScaleBps = BPS_DENOM;
uint256 nominal = Math.mulDiv(
unclaimedWinnerShares, FeeCurve.keepBps(totalVolume, halfTaper), BPS_DENOM
);
if (nominal <= totalVolume || requiredSeed() == 0) {
emit SeedScaleFixed(BPS_DENOM);
return;
}
uint256 tight = (totalVolume * BPS_DENOM + (BPS_DENOM - 1)) / nominal;
seedScaleBps = Math.max(tight, SEED_COVER_FLOOR_BPS);
emit SeedScaleFixed(seedScaleBps);
}
The resulting seedScaleBps is applied uniformly to every winning claim through _seedScaled(), and it is computed only from the final state of the market. Since a later bet on the winning outcome can increase unclaimedWinnerShares (and therefore nominal) by more than it increases totalVolume, pushing nominal above the pot or lowering tight.
As a result, a later bet on the same side can reduce the payout of an earlier winner by up to 5%, even though the earlier winner's shares were fixed at purchase. The final payout of a position therefore cannot be determined from its purchase-time price, which contradicts the documented "no dilution" guarantee.
Remediation:
Consider documenting that winner payouts on seeded markets are subject to a seed-cover scale of up to 5% that depends on the final market state, or limiting the scale so that it cannot reduce payouts of shares bought before the bet that caused the shortfall.
FERM1-8 | SEED IS DEPOSITED INTO THE YIELD VAULT, CONTRARY TO THE DOCUMENTATION
Severity:
Status:
Fixed
Path:
contracts/src/MarketCore.sol#L743, contracts/src/MarketCore.sol#L855, docs/src/mechanism/collateral.md
Description:
The documentation states that the seed is a static maker buffer and is not deposited into the yield vault:
The seed is a **static maker buffer**: it is not deployed to the yield rail, so
the [yield](#yield-on-idle-collateral) distribution and the seed refund are
independent — only pooled stakes are routed to a vault, and the seed is refunded
flat.
However, depositToYield() deposits the entire market balance, which includes the seed transferred by the factory at creation:
uint256 assets = collateral.balanceOf(address(this));
// Nothing idle to deploy (every buy may already be in the vault) — a
// benign no-op rather than a revert, so the operator can poll safely.
if (assets > 0) {
principalDeployed += assets;
collateral.forceApprove(address(yieldVault), assets);
uint256 mintedShares = yieldVault.deposit(assets, address(this));
...
}
The implementation itself also assumes the opposite of the documentation. _finalizeRecovery() counts the seed as part of the deposited principal:
// The seed is maker capital deposited into the vault alongside the
// stakes, so it backs the winner obligation exactly like the pot does.
...
uint256 backing = totalVolume + requiredSeed();
As a result, the documented guarantees that only pooled stakes are routed to the vault, that the yield distribution and the seed refund are independent, and that the seed is refunded flat do not hold:
- The seed is exposed to vault losses. For example, a funder supplies a $10,000 seed and nobody bets. The operator calls
depositToYield(), and the vault loses 10%. The funder receives only $9,000 back, despite no user ever betting. - The seed's yield is not credited in proportion to the seed. The gross yield is split into
yieldHandlingFee, which flows into the house take and reaches the creator only through itscreatorBpsshare, andnetYieldPool, which is distributed to bettors pro-rata to their stake. Bettors therefore receive most of the yield generated by the seed, and the seed provider's share does not scale with the capital it supplied.
Remediation:
Consider either excluding the seed from depositToYield() (e.g. depositing at most balance - requiredSeed()) so the implementation matches the documentation, or updating the documentation to state that the seed is deposited alongside the stakes, bears vault losses, and does not earn its share of the yield.
FERM1-10 | SUB-BASIS-POINT PRICES CAP FILLS WHILE CHARGING THE FULL STAKE
Severity:
Status:
Fixed
Path:
contracts/src/LsLmsr.sol:sharesBoughtImpl]#L117-166, L295-L317
Description:
sharesBoughtImpl converts a user's stake into shares by searching for the largest share amount whose LMSR cost is no greater than the stake. Regular and gasless buys reach it through MarketCore._credit, while parlay basket buys use the equivalent basketSharesImpl flow. These entry points are available to ordinary bettors.
The search should start with an upper bound that is known to be unaffordable. Bisection can then return the largest affordable amount, after which the market credits those shares and pulls the user's full stake.
However, priceBpsImpl rounds prices down to whole basis points. When an outcome's real price is positive but below one basis point, it returns zero. bracket then changes that zero to one basis point and derives the search limit from it:
uint256 priceBpsValue = Math.max(priceBpsImpl(outcome, q, alphaBps, bMin), 1);
uint256 hiBound = Math.mulDiv(target, BPS_DENOM, priceBpsValue) + 1;
Rounding the price up makes hiBound too small, so it is not necessarily an upper bound at all. sharesBoughtImpl never checks whether that bound is unaffordable and cannot find any larger fill. The basket path has the same issue when all selected cell prices round to zero. MarketCore.buy and MarketParlay.buyBasket still transfer and account for the full stake, with no refund for the underfill.
For example, consider a 6-decimal binary market with alphaBps = 300, bMin = 1,000,000, inventory [1,000,000,000,000, 0], and a 1,000,000 stake on the second outcome:
- The second outcome's real price is about
0.000000924basis points, butpriceBpsImplreturns zero. bracketsubstitutes one basis point and caps the search near10,000,000,000share units.- A fill of
250,000,000,000share units is still affordable and costs only about51,590units undercostImpl, but bisection cannot reach it. - With a permissive minSharesOut, the market credits the capped fill and pulls the full 1,000,000 stake. The bettor receives far less payout exposure if the outcome wins, while the excess collateral remains in the market.
function sharesBoughtImpl(
uint256 outcome,
uint256 stake,
uint256[] memory q,
uint256 alphaBps,
uint256 bMin
) internal pure returns (uint256) {
if (stake == 0 || outcome >= q.length) {
return 0;
}
uint256 base = costImpl(q, alphaBps, bMin);
(uint256 lo, uint256 hi) = bracket(outcome, stake, q, alphaBps, bMin);
for (uint256 i = 0; i < BISECT_STEPS; ++i) {
if (hi - lo <= 1) {
break;
}
uint256 mid = lo + (hi - lo) / 2;
if (costIncrement(outcome, mid, base, q, alphaBps, bMin) <= stake) {
lo = mid;
} else {
hi = mid;
}
}
return lo;
}
Remediation:
Build the bracket from costIncrement: grow the upper bound until it is unaffordable, then run bisection. Apply the same approach to basketBracket and test that the returned fill is affordable while the next share is not.
FERM1-12 | OUTSTANDING ALLOWLIST SIGNATURE CAN OVERRIDE THE OWNER'S LATER DIRECT UPDATE
Severity:
Status:
Fixed
Path:
contracts/src/Allowlist.sol#L90
Description:
The Allowlist owner can update bettors directly through setAllowed(), or gaslessly by signing a SetAllowed message that anyone can submit through setAllowedWithSig():
function setAllowed(
address[] calldata bettors,
bool ok
) external onlyOwner {
_setAllowed(bettors, ok);
}
function setAllowedWithSig(
address[] calldata bettors,
bool ok,
uint256 nonce_,
uint8 v,
bytes32 r,
bytes32 s
) external {
if (nonce_ != nonce) {
revert InvalidNonce();
}
...
nonce = nonce_ + 1;
_setAllowed(bettors, ok);
}
However, the signed message has no deadline, and the direct setAllowed() does not advance nonce. As a result, a signed update that has not been submitted yet stays valid indefinitely, and the owner cannot invalidate it with a direct call.
For example:
- The owner signs
SetAllowed([Alice], true, nonce = 1)and hands it to the relayer. - Before it is submitted, the owner decides Alice must not bet anymore and calls
setAllowed([Alice], false)directly.nonceis still 1. - The relayer (or anyone holding the signature) submits the signed message. The nonce still matches, so Alice is allowed again and the owner's latest decision is silently reverted.
Note that the codebase already handles this case elsewhere:
CreatorResolverandMarketCore.sweep()both consume the current nonce on the direct path, so an older outstanding signature is invalidated.
Remediation:
Consider advancing nonce in setAllowed() as well, and adding a deadline to the SetAllowed message:
function setAllowed(
address[] calldata bettors,
bool ok
) external onlyOwner {
++ nonce += 1;
_setAllowed(bettors, ok);
}
FERM1-13 | UNUSED _ISSCALAR() FUNCTION
Severity:
Status:
Fixed
Path:
contracts/src/MarketCore.sol#L480-L482, contracts/src/MarketScalar.sol#L56-L58
Description:
MarketCore declares the internal virtual function _isScalar(), which MarketScalar overrides:
// MarketCore
function _isScalar() internal view virtual returns (bool) {
return false;
}
// MarketScalar
function _isScalar() internal view override returns (bool) {
return scalarHi > scalarLo;
}
However, the function is never called anywhere in the codebase. Its NatSpec states that it is "consumed by the shared settlement tail", but _settle() and the other settlement functions never reference it; each resolve*() entry point builds its own payout weights instead.
Remediation:
Consider removing _isScalar() from MarketCore and MarketScalar, or updating its NatSpec if it is meant for future use.
FERM1-14 | DISPUTE INCENTIVES WEAKEN AS THE MARKET GROWS
Severity:
Status:
Acknowledged
Path:
contracts/src/DisputeResolver.sol#L680
Description:
A proposal in the DisputeResolver can only be challenged by posting a bond, which scales linearly with the market's totalVolume:
function disputeBond(
address market
) public view returns (uint256 bond) {
...
uint256 pot = IMarketCore(market).totalVolume();
return Math.max(
cfg.minBond,
Math.mulDiv(pot, cfg.bondBps, BPS_DENOM)
);
}
The bond has no upper cap. With bondBps = 100, disputing a 10M USDC market requires a 100,000 USDC bond (which is a significant amount of money for a person).
However, the disputer has little reason to post it, even when the proposal is wrong:
- A correct dispute only gets its bond back. In
arbitrate(), an overturned proposal calls_refundBond()and nothing more, so there is no reward for the disputer. - A correct dispute can still lose the bond. If the arbiters do not rule within
arbiterTimeout,_closeWindow()finalizes the original proposal and calls_forfeitBond()regardless of whether the dispute was right:
else if (st.status == Status.Disputed) {
if (block.timestamp < st.disputedAt + cfg.arbiterTimeout) {
revert NotArbiterTimedOut();
}
uint256 forfeited = st.bond;
st.bond = 0;
_finalize(market, st.proposed);
_forfeitBond(market, forfeited);
}
- One disputer posts the whole bond, while the benefit of overturning a wrong outcome is shared by every holder of the correct outcome. Only a holder whose own position is worth more than the bond has a reason to dispute. As a result, the larger the market, the more a wrong (or compromised) proposal is worth, and the less likely it is to be challenged.
Remediation:
Consider one or more of the following:
- Capping the bond, e.g.
min(max(minBond, bondBps * pot), maxBond). - Rewarding a successful disputer, for example from a proposer bond or a share of the house take.
- Refunding the bond instead of forfeiting it when the arbiters time out.
Commentary from the client:
The risk will be documented internally.
FERM1-15 | MISPLACED NATSPEC FOR _CREDIT()
Severity:
Status:
Fixed
Path:
contracts/src/MarketCore.sol#L639-L657
Description:
The NatSpec from line 639 - 644 describing _credit() is placed above _requireBettorAllowed() instead of above _credit() itself:
/// @dev The shared body of a buy, run before collateral is pulled: validates
/// the market is open and the outcome is in range, prices the stake,
/// enforces the slippage guard, records `shares` of `outcome` against
/// `buyer`'s position, advances the book and volume, and emits
/// {Bought}. The caller performs the collateral transfer last (CEI), so
/// a failed transfer reverts these writes.
/// @dev Enforces the optional betting allowlist. A zero `allowlist` is
/// permissionless and short-circuits before any external call ...
function _requireBettorAllowed(
address buyer
) internal view {
...
}
function _credit(
address buyer,
uint256 outcome,
uint256 stake,
uint256 minSharesOut,
address sponsor
) internal returns (uint256 shares) {
As a result, both @dev blocks are attached to _requireBettorAllowed(), which wrongly describes it as pricing the stake and recording shares, while _credit() has no documentation.
Remediation:
Consider moving the first @dev block directly above _credit().