Executive Summary & Direct Answer

A legacy Solidity bonding curve can quote a zero purchase price when intermediate multiplication or addition wraps modulo 2²⁵⁶. The Truebit incident analysis describes this failure in a price calculation involving token supply, purchase amount, and ETH reserves: two large terms fit individually, but their sum overflows before division. Reproduce the behavior with Solidity 0.7.6, compare it with checked arithmetic, and fuzz the exact expression. For production, reject unsafe inputs or use a rigorously verified full-precision calculation; changing compiler versions alone does not repair the formula.

What failed in the bonding-curve calculation

The Truebit incident analysis reports that a purchase quote returned zero for a large requested token amount. The reported calculation combined token supply, purchase amount, and cumulative ETH reserves. In the example, the terms v9 and v12 each fit in a uint256, but their sum exceeded 2²⁵⁶ - 1. Solidity versions before 0.8.0 silently wrapped that sum modulo 2²⁵⁶. The wrapped numerator was then divided, producing a small result that rounded down to zero.

The security failure was not merely “old Solidity has unchecked arithmetic.” It was a specific interaction between expression ordering, a large intermediate sum, integer division, and a quote that the minting function trusted. If a zero quote authorizes minting, an attacker can receive tokens without paying the intended ETH amount. This guide reproduces that arithmetic behavior and shows how to test and mitigate it.

Environment and baseline specifications

Use these versions to make the behavior reproducible:

  • Legacy reproduction: Solidity 0.7.6, compiled with the same EVM target and optimizer settings as the contract under investigation.
  • Checked comparison: Solidity 0.8.24 or later. Arithmetic reverts on overflow by default; an unchecked block restores wrapping behavior.
  • Testing: Foundry with forge-std; pin the Foundry version and compiler in CI.
  • Production arithmetic option: OpenZeppelin Contracts v5 Math.mulDiv for verified full-precision two-factor multiplication and division. It does not, by itself, solve arbitrary three-factor products or sums.

A minimal foundry.toml for a legacy harness:

[profile.legacy]
src = "src"
test = "test"
solc_version = "0.7.6"
optimizer = true
optimizer_runs = 200
evm_version = "istanbul"

For the checked comparison, use a separate profile with solc_version = "0.8.24" and the intended deployment EVM version. Do not assume a profile change reproduces the original deployment: optimizer settings, EVM version, source code, and proxy implementation all matter.

Reproduce the vulnerable expression first

The incident analysis describes these terms:

  • supply: token total supply
  • amount: requested token amount
  • reserve: cumulative ETH reserve
  • v9 = 200 supply amount * reserve
  • v12 = 100 amount amount * reserve
  • denominator = 25 supply supply

The reported calculation describes division by the denominator. Parentheses are security-critical: numerator / (25 supply supply) is not equivalent to (numerator / 25) supply supply.

Here is a focused Solidity 0.7.6 reproduction harness. The intermediate variables preserve the relevant multiplication and addition order:

// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;

contract LegacyCurve {
    function quote(
        uint256 supply,
        uint256 amount,
        uint256 reserve
    ) external pure returns (uint256) {
        uint256 v9 = 200 * supply * amount * reserve;
        uint256 v12 = 100 * amount * amount * reserve;
        uint256 denominator = 25 * supply * supply;

        return (v9 + v12) / denominator;
    }
}

All arithmetic in this compiler version wraps on overflow. The assignments to v9 and v12 can themselves overflow for other inputs; the reported example highlights a case where each term fits but v9 + v12 does not. The denominator can also overflow or become zero, creating separate failure modes. A faithful investigation must test each intermediate rather than treating “the final answer” as the only relevant value.

Using the incident analysis’s example values—supply = 161753242367424992669183203, amount = 240442509453545333947284131, and reserve = 8539408935947150350830—the reported v9 and v12 sum exceeds 2²⁵⁶ - 1. In 0.7.6, the addition wraps. The source reports that the resulting quote rounded down to zero, enabling the described mint-and-sell sequence. Confirm exact deployed bytecode and operation order before treating an article’s pseudocode as a byte-for-byte reproduction.

Compare against checked arithmetic

With Solidity 0.8.x, the same expression reverts when an intermediate operation overflows. That prevents a wrapped value from becoming a misleading quote, but it does not make the formula universally correct: legitimate large inputs may now revert, and arithmetic outside the checked expression may still be unsafe.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract CheckedCurve {
    error InvalidInput();
    error ArithmeticOverflow();

    function quote(
        uint256 supply,
        uint256 amount,
        uint256 reserve
    ) external pure returns (uint256) {
        if (supply == 0 || amount == 0 || reserve == 0) {
            revert InvalidInput();
        }

        // Checked multiplication and addition revert on overflow.
        uint256 v9 = 200 * supply * amount * reserve;
        uint256 v12 = 100 * amount * amount * reserve;
        uint256 denominator = 25 * supply * supply;

        if (denominator == 0) revert ArithmeticOverflow();
        return (v9 + v12) / denominator;
    }
}

The custom overflow error in this example is illustrative; Solidity’s default checked-arithmetic failure is a panic. If callers or monitoring systems depend on a particular error, define and test that API deliberately. More importantly, a checked calculation that unexpectedly reverts should not be “fixed” by putting the entire formula inside unchecked.

Production mitigation: bound, prove, and fail closed

For a legacy deployment, the safest immediate mitigation is to constrain inputs before the vulnerable calculation, if the protocol can establish safe bounds and the implementation can be changed safely. The bounds must guarantee that every multiplication, addition, and denominator calculation fits—not just the final mathematical result.

For a new implementation, retain checked arithmetic and reject values outside proven bounds. For example, a protocol can cap amount, supply, and reserve based on a mathematical proof that each intermediate fits within uint256. Document the proof beside the constants and test the exact boundary values. If the business requirement includes larger values, use a reviewed full-precision algorithm or reformulate the calculation with verified rounding semantics. Math.mulDiv(x, y, denominator) computes a full-precision two-factor product divided by a denominator, but the curve’s multi-factor sum must be decomposed carefully; replacing just one multiplication is not a complete fix.

Never convert an overflow into a zero quote, clamp an invalid result to zero, or allow minting to proceed when quote calculation fails. The mint path must require a valid quote and collect at least the required payment. Review the quote and mint functions together: a safe quote helper is ineffective if another entry point bypasses it. For related arithmetic and decode hazards at external boundaries, see Preventing Unsafe abi.decode Usage in Solidity. If a purchase or sale invokes token callbacks or other external code, also assess Preventing Cross-Function Reentrancy in Solidity.

Differential fuzzing: legacy wrap versus checked revert

Create a test that compares the legacy result to a uint256-bounded mathematical oracle. The oracle should use arbitrary-precision arithmetic off-chain or a test helper that explicitly models the intended full-precision result. Do not use the legacy contract as the oracle for correctness.

A compact Foundry test can first verify the key property: the reported inputs cause the legacy expression to differ from checked evaluation. For Solidity 0.8, make a dedicated harness that evaluates the legacy expression inside unchecked; this is useful for reproducing wraparound, not as production code.

function testReportedInputWrapsAtAddition() public {
    uint256 supply = 161753242367424992669183203;
    uint256 amount = 240442509453545333947284131;
    uint256 reserve = 8539408935947150350830;

    uint256 v9 = 200 * supply * amount * reserve;
    uint256 v12 = 100 * amount * amount * reserve;

    assert(v9 <= type(uint256).max);
    assert(v12 <= type(uint256).max);
    assert(v9 > type(uint256).max - v12);
}

Compile this particular test under Solidity 0.8 only if the products themselves are known to fit; otherwise, those checked test expressions revert before reaching the addition assertion. For a faithful 0.7.6 reproduction, run the harness with the pinned legacy profile and assert the observed wrapped output. For the checked profile, assert that the same input reverts. Also test nearby values, amount = 0, supply = 0, denominator boundaries, and the maximum permitted production inputs.

Run separate compiler profiles rather than mixing compiler pragmas and assuming the test runner selected the intended version:

forge test --profile legacy -vvv
forge test --profile default --match-test testReportedInput -vvv
forge test --profile default --fuzz-runs 10000

Add a differential script that evaluates the formula with arbitrary-precision integers and compares it with both EVM implementations. For source-level investigation, inspect compiler output and deployed runtime bytecode; optimizer transformations can change instruction sequences while preserving wraparound semantics. Pin the exact compiler and verify that the deployed proxy implementation corresponds to the source under test. This is particularly important when a proxy’s current implementation differs from its historical implementation.

Quantitative trade-offs

The figures below describe arithmetic behavior, not gas measurements; exact gas depends on compiler, optimizer, EVM target, and surrounding call path. The incident example’s values are reported by the source analysis.

ApproachOverflow behaviorKey quantitative propertySecurity trade-off
Solidity 0.7.6 expressionWraps modulo 2²⁵⁶Reported v9 + v12 exceeds 2²⁵⁶ - 1Can produce a misleading quote, including zero
Solidity 0.8.x checked expressionReverts on overflowRejects the overflowing additionFail-closed, but may reject otherwise valid large inputs
Solidity 0.8.x unchecked reproductionWraps modulo 2²⁵⁶Matches legacy arithmetic for the same operation orderSuitable for regression tests only
Bounded checked formulaReverts outside proven input limitsEvery intermediate must fit in 256 bitsSafe if bounds and rounding are formally reviewed
Full-precision verified formulaDepends on library and expression designTwo-factor mulDiv can retain a 512-bit product before divisionMulti-factor sums and rounding still need proof

Production pitfalls and verification checklist

  • Check deployed code, not just repository source. Resolve the proxy implementation at the relevant block and compare its runtime bytecode with the build artifact.
  • Preserve operation order in reproductions. Algebraically equivalent expressions can overflow at different points or round differently after integer division.
  • Test numerator and denominator independently. v9, v12, their sum, 25 supply supply, and the final division each have distinct edge cases.
  • Specify rounding. Solidity integer division truncates toward zero. A formula that returns zero for a positive fractional result may be mathematically expected or economically unsafe, depending on the protocol’s units and policy.
  • Enforce payment consistency. The mint path should reject a zero quote when a nonzero purchase is required and verify that supplied ETH meets the quote. Do not assume the quote function alone enforces payment.
  • Review upgrade and emergency paths. A patched implementation does not repair already-minted balances or prevent an unpatched alternate entry point from being used.
  • Compare compiler outputs. Build with pinned settings, inspect optimized IR or assembly, and test the actual deployment toolchain. A compiler upgrade may expose the bug as a revert, but only a corrected design establishes intended behavior.

Frequently Asked Questions (FAQ)

Why did the Truebit bonding-curve quote return zero?

The incident analysis reports that the price calculation added two large intermediate terms that each fit in uint256, but whose sum exceeded the 256-bit maximum. Solidity versions below 0.8.0 wrapped that addition modulo 2²⁵⁶; division then produced a result rounded down to zero.

Does upgrading from Solidity 0.7.6 to 0.8.24 fix the formula?

It prevents silent overflow in ordinary checked arithmetic by reverting when an intermediate overflows. That is a safer failure mode, but it can reject inputs the protocol intends to support and does not prove the formula’s units or rounding are correct. Review and test the arithmetic and payment flow as part of the upgrade.

Can OpenZeppelin Math.mulDiv safely replace the bonding-curve expression?

Math.mulDiv is designed for full-precision two-factor multiplication followed by division. The reported curve includes multiple factors and a sum, so replacing one multiplication does not automatically make the whole expression safe. Derive and test a decomposition that preserves the intended result and rounding, or enforce proven input bounds.

Learn more with useful resources