Skip to content

Compile all 261 Solidity declarations through SolidCore source lowering - #1784

Draft
KillariDev wants to merge 332 commits into
mainfrom
t3/solidcore-contract-compilation
Draft

KillariDev wants to merge 332 commits into
mainfrom
t3/solidcore-contract-compilation

Conversation

@KillariDev

@KillariDev KillariDev commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Source-level compilation

SolidCore checks all 261 Solidity declarations in Zoltar’s two compiler profiles. The inventory includes 128 concrete contracts, 20 abstract contracts, 33 libraries and 80 interfaces. Each concrete contract also produces a checked deployment constructor.

The driver takes the repository compiler’s source maps, flattens each source with Forge, and parses and analyzes it with the pinned native solc. It imports the complete target declaration and the dependencies it uses into SolidCore’s Solidity frontend. Lean checks each resulting module with TypeCheck.CheckedInput.contract. The coverage report comes from this source path. Anvil provides an independent execution comparison for the regression probes.

The importer, interpreter extensions, arithmetic proof and replay probes now live in DarkFlorist/solidity-lean PR #1. The main replay pins 9af8f8d. It covers the inline-assembly patterns exercised by this repository, including word arithmetic, calldata and memory operations, storage references, calls, creation, logging and exceptional exits. The source projection also handles inherited calls, library dependencies, ABI conversions, and evaluation of effectful operands.

INV-02 REP grid per lot

For positive per-lot commitment and REP aligned to M / gcd(M, 10000), the generated commitment index returns the same protocol-floor price for one lot and every positive representable multiple. Inv02.gridPrice covers every initial state and full-width products, with explicit word bounds on the multiplied inputs, the first quotient and the final price. Inv02.cappedGridPrice derives both quotient bounds from the REP supply cap. Both theorems establish successful public returns.

The proof checks the getter body and both library functions in the commitment index’s own function table. A separate generated requiredRep example shows the extra rounding at a voluntary 11,000 bps health target. One and two lots require 3 and 5 units, respectively, versus 2 and 4 at the protocol floor. The replay checks all three theorems’ transitive axioms.

INV-03 maximum removable fee units

Inv03.maximumRemoval proves the return value of the generated public InvariantMathHarness.feeBudget call through the production settlement library. For every funded question in the book domain and every candidate removal up to its unit balance, the rounded raw-cash value stays above or equal to the minimum exactly when the removal is within the returned budget. An underfunded question returns zero.

The theorem assumes positive net cash and total units, a question weight at most the book’s total, total units below the book’s 128-bit cap, and a minimum exchange rate at most 10^18. It derives the word bounds for both ceiling conversions and the intervening floor conversion. The replay checks the theorem’s transitive axioms.

INV-05 incumbent value on issuance

For every successful public mintUnits call on a funded, nonempty book, Lean proves that incumbent net cash per unit weakly increases. With raw deposit C, scale S = 10^9, pre-mint units U, pre-mint net scaled cash N and returned units a, the residual C × S × U − a × N is nonnegative and strictly less than N. The theorem covers every initial state and deposits below the production book’s 128-bit cash cap.

Inv05.publicMint follows the generated settlement library through the zero-deposit return, full-width quotient, overflow rejection and precision guard. Inv05.incumbentValue uses the returned amount from that public call. Both theorems have transitive axiom checks in the permanent replay.

INV-06 immediate redemption

Lean proves that immediately burning every newly minted unit returns the deposit or one raw cash unit less. The proof follows the public mintUnits and cashForUnits calls on the generated harness with the fee carry held fixed. It covers the first mint into a newly created cash-funded book, which redeems the full deposit, and subsequent successful mints on a nonempty book with positive net cash. Post-mint cash and units must fit the production book caps. Both the zero-deposit boundary and the full-burn branch are included. See Inv06.immediateRedemption and Inv06.firstRedemption.

INV-07 remaining backing after redemption

Inv07.remainingBacking proves the public payout for every burn size on a nonempty settlement book, including zero. For a partial burn of b units, net scaled cash N, U original units and settlement scale S, the payout p is exactly floor(b × N / (U × S)). The cross-multiplied difference (N − p × S) × U − N × (U − b) is nonnegative and strictly less than U × S. Burning all units returns all remaining raw cash, including any cash held against the fee carry.

INV-08 checkpoint frequency and full vesting

Lean proves that any two authorized public checkpoint schedules with the same start, end and eligibility cutoff return identical ETH and REP and leave the same deferred balances. At the last expiry, prior vesting, newly returned amounts and new deferrals account for every original deposit. The proof starts at the generated public initializer on fresh clone storage and covers interleaved funding, releases, checkpoints and deferred withdrawals, including deposits merged at the same timestamp. It uses the documented mapping storage non-collision assumption only for the locations used in each history.

The permanent replay checks both Inv08.checkpointFrequency and Inv08.fullVesting against the source-generated SecurityPoolCapitalFeeStreams and audits their transitive Lean axioms.

INV-32

Whenever quoteExactOutput successfully quotes a gross input, an arbitrary uint256 gross input reaches the target via quoteExactInput if and only if it is at least the quoted amount. This includes fee rounding, output overshoot and the wide-denominator path.

Lean proves Inv32Source.forwardRefines and Inv32Source.inverseSound from the two public functions of the freshly lowered TwoWayConstantProductMathHarness. The harness calls the production TwoWayConstantProductMath library. The final theorem, Inv32Source.minimumGrossInput, takes uint256 bounds and a successful inverse return. It requires neither refinement as a hypothesis. Model execution uses SolidCore's checked call with fuel 50,000 and empty initial state for these pure functions.

The proof entry point is formal/solidcore/inv32/Inv32Proved.lean. The replay checks the transitive axioms of both refinements and the final theorem. The allowlist consists of propext, Classical.choice, Quot.sound, Lean.ofReduceBool, and Lean.trustCompiler. The last two support native reduction of closed terms, including checks against the generated function bodies.

INV-33

For two successful same-direction exact-input quotes with a fixed fee rate, the single quote for the combined gross input succeeds and returns at least their combined output. The second leg starts with the full first gross input added to the input reserve and the first output removed from the output reserve. The result holds across representable uint256 quote arguments, including fee and output rounding. Equality is allowed.

Inv33Source.splitExactInput in formal/solidcore/inv33/Inv33Proved.lean applies the verified execution of the generated Solidity harness to all three calls. The theorem covers the fixed-pool pricing comparison. Token transfers, callbacks and transaction execution are outside its scope. The replay checks its transitive axioms against the same allowlist as INV-32.

INV-34

For two successful exact-input quotes on the same pool, immediately trading the entire first output in the opposite direction recovers at most the original gross input. The reverse quote uses the post-trade reserves, including the retained fee. Both legs use the same fee rate, with no intervening reserve changes. The proof also verifies a tight example: at reserves (2, 2) and zero fee, 2 units buy 1 and that unit buys back 2.

Inv34Source.roundTripExactInput and Inv34Source.equalityExample in formal/solidcore/inv34/Inv34Proved.lean use the generated public Solidity quote harness. The replay enforces the existing Lean axiom allowlist for both the general theorem and the example. The theorem covers quote arithmetic; the pair-level round-trip regression separately exercises transfers and reserve updates.

INV-35

For uint256 reserves with positive sum, the two directional prices returned by the generated public conditionalYesBps method total 9,999 or 10,000 basis points. They total 10,000 exactly when the reserve sum divides 10,000 times the no reserve. Multiplying both reserves by any positive integer preserves both returned prices whenever the scaled reserves fit. The sum itself may need 257 bits.

The test harness exposes the production library method. Inv35Source.mirroredPrices and Inv35Source.scaledPrices in formal/solidcore/inv35/Inv35Proved.lean start at the checked public call. The proof follows library dispatch and the generated ratio routine, including its wide-denominator branch. Both theorems use the existing axiom allowlist.

INV-36

For every successful public initialLiquidityAmounts quote with requested Yes probability p in basis points, the quote at 10000 - p succeeds and exchanges the Yes and No reserves exactly. The displayed Yes price from the original reserves is at most the request below 50%, at least the request above 50%, and exactly 5,000 basis points at the midpoint.

Inv36Source.initializationSymmetry in formal/solidcore/inv36/Inv36Proved.lean evaluates both initializer quotes and the public price call against the checked Solidity model. The proof replay enforces the existing axiom allowlist.

INV-37 backing per LP token

Lean proves the reserve-product inequality for both generated public swap quote functions with the full gross input retained in reserves. For deposits, minting the smaller of the two pro-rata floors preserves backing on each side; for withdrawals, each pro-rata floor preserves backing even when one payout rounds to zero. An ordinary donation preserves the product at fixed supply.

The replay also lowers the production pair, locates the require statement after its effective-reserve read inside _checkReserves, and evaluates the actual guard for arbitrary uint256 local values. The swap, deposit and withdrawal theorems use a passing guard at their respective expected minima and allow the observed balances to exceed those minima. The transitive axiom checks use the existing allowlist.

Full INV-37 remains open. The proofs still need to connect complete public transactions to the guard observations, token balance reads and post-transaction LP supply. The present theorems establish the arithmetic and the local guard semantics.

INV-40 threshold steps

The generated Zoltar getters return the ceilings of S / D and S / (2D) after the theoretical-supply read returns S and the immutable divisor is D > 0. Lean follows the non-decision getter into the generated internal fork-threshold function. The proof preserves the supply provider’s interaction transcript. For either denominator d and positive S, reducing supply by 1 + ((S − 1) mod d) lowers its threshold by one. Every smaller reduction leaves it unchanged. The arithmetic includes a reduction to zero and divisors for which 2D exceeds uint256.

The production getter bodies are checked by the replay. Four frozen-genesis snapshots also run through the public Solidity model with D = 5. Supplies 11, 10, 1 and 0 give threshold pairs (3, 2), (2, 1), (1, 1) and (0, 0).

INV-44 deployment mask

Lean proves that the public status oracle returns a bit for each constructor-supplied address, set exactly when that address has runtime code at the time of the read. Duplicate addresses have identical bits, every unused high bit is zero, and a 256-address configuration uses bit 255. Deployment and reading may have different account-code environments.

The generated constructor stores ABI addresses in their original order, emits the configuration event, and rejects a representable input array longer than 256 with its original state. The proof checks the physical array header and all element slots, including their separation for the supported length. The public getter proof assumes EVM-representable runtime code lengths. The entry point is Inv44.constructedMask in formal/solidcore/inv44/Inv44Proved.lean; the replay audits the theorem's transitive axioms.

INV-45 scalar question labels

Inv45.Public.scalarLabels proves the result of the generated ZoltarQuestionData.getAnswerOptionName selector for every valid tick of a stored scalar question. For fixed bounds, tick count and unit, the public call returns distinct byte strings for distinct ticks, even when the numeric components coincide. The numeric component is nondecreasing and both endpoint values are exact.

The theorem starts from the packed question storage and canonical answer encoding. It follows the public input checks, generated internal calls, formatting, and public return-value decoding. Its transitive axiom check permits only Lean's existing logical and native-evaluation axioms. The replay regenerates the contract from Solidity before checking the proof.

INV-27 revised oracle bounds

Inv27.publicQuote proves both production OraclePriceMath helpers through the source-generated harness for every initial state, uint256 raw price and uint256 uncertainty. For uncertainty below the percentage precision, liquidation returns the exact floor. The conservative helper returns the exact ceiling up to the maximum representable price and returns the specified error above it. Both helpers return the invalid-uncertainty error at or above the precision.

Inv27.outward proves that increasing uncertainty widens the representable interval. Inv27.noUncertainty recovers the raw price up to the maximum uint256. Inv27.funded proves both results for the price derived from a uint128 REP amount and positive collateral. The replay checks the transitive axioms and retains the concrete regression witnesses for the domain correction in #1793.

INV-01 upper-price boundary

Issue #1796 tracks the unrestricted pure-helper domain. With commitment 1, multiplier 20,000 and target health 10,000, backing of 2 × (floor(MAX_UINT256 / 10^18) + 1) covers even the largest uint256 price. Asking for the maximum healthy price with that backing panics with 0x11. With one less unit of backing the inverse succeeds. Both the generated production contract and compiled Solidity on Anvil confirm these outcomes. The witness exceeds the protocol REP cap. Lean separately proves the inverse fits when backing is at or below that cap.

INV-04 minimum required cash

Lean proves that the mathematical minimum m = ceil((ceil(u*n/d) + r)/10^9) satisfies m <= c exactly when u*n + r*d <= c*10^9*d, for every positive denominator. The cross-multiplied form accounts for signed subtraction even when cash is zero. The rounded scaled amount plus the carry fits a word exactly when u*n + r*d <= (2^256-1)*d. It always fits when the raw minimum is below the settlement book’s 2^128 cash cap.

Separate checked public Solidity calls verify that a carry of one raises the raw minimum from 1 to 2 for u=10^9, n=d=1. For unrestricted helper inputs u=2^256-1, n=d=1, the carry-free call succeeds. A carry of one causes panic 0x11 although the mathematical final minimum fits uint256. The witness exceeds the production book’s unit cap. Main incorporated #1797, which specifies the positive denominator and the representable scaled intermediate for INV-04 and addresses #1794. These boundary calls also run on Anvil. On the revised domain, Lean now proves that the generated public Solidity call succeeds from every initial state and returns the least qualifying raw cash amount. The theorem follows the production rounded mulDiv, checked carry addition, and final ceilDiv, including a zero numerator, and audits transitive axioms (Inv04.leastRequiredCash).

Replay

Install the repository’s locked Bun dependencies. Use Python 3.10+, Lean/Lake 4.28.0, Forge/Anvil 1.5.1 and the two native solc versions below. From the repository root run

SOLC_035=/path/to/solc-0.8.35 \
SOLC_028=/path/to/solc-0.8.28 \
FORGE=/path/to/forge ANVIL=/path/to/anvil \
bash formal/solidcore/replay.sh /tmp/zoltar-solidcore

The command applies the diff, builds SolidCore, runs the probes, and writes one row per declaration to /tmp/zoltar-solidcore/contracts.tsv. Passing Lean modules are in /tmp/zoltar-solidcore/models-*/contracts/. The final stages rebuild the proof modules against the models emitted by the same run, including the trading harness, production pair, commitment index, settlement math harness and Zoltar getters. A rejected declaration or failed proof makes the replay fail. Set SOLIDCORE_JOBS to adjust inventory concurrency for the available memory.

Validation and proof scope

  • 261 unique declarations produced 261 checked Lean modules. All 128 concrete constructors lowered.
  • 44 source-lowering regression tests passed. They include deployment and subsequent reads of a public immutable variable that implements an inherited getter.
  • 400 full-width multiplication input pairs and 505 mulDiv calls matched the reference results, including rounding and exact revert data. Lean also checked the mul512 limb identity for arbitrary inputs.
  • Differential execution covered both solc profiles for the OpenOracle hashes, packed event data and topics, typed and raw calldata, nested mapping accesses and scalar modular exponentiation.
  • Compilation establishes that every declaration in this source inventory has a checked SolidCore representation. General semantic equivalence between the SolidCore interpreter and solc bytecode remains outside this proof.

INV-42 zero timestamp

A timestamp of zero is reserved in the maturity map. The replay creates two nonzero-key entries with inclusive totals (130, 87), submits an update of (12, 34) at timestamp zero, and queries the new snapshot. Its value at zero is still (0, 0) and its inclusive totals are still (130, 87). Applying deltas at every uint48 timestamp would instead give (12, 34) at zero and totals of (142, 121). The generated Solidity interpreter and compiled Solidity on Anvil agree. Main incorporated #1797, which addresses #1792 by specifying addition at positive timestamps and an identity update at zero. A universal proof of the revised positive-key, permutation, cancellation and historical-root clauses remains open.

INV-62 revised specification

Issue #1788 was addressed by #1789, now included from main. The revised text distinguishes the recipient-directed mint from the recipient’s net balance increase when the recipient is the lock. The merged direct and router regressions include separate and coincident recipients. A full generated-model proof of the revised constructor and initializer property remains open.

INV-39 unused child mint capacity

The generated ReputationToken constructor starts a freshly deployed child with zero supply and empty balances. After successful initialization, its theoretical supply minus its circulating supply equals its initial theoretical supply minus the sum of all successful mint amounts in the admitted call history. Child burns decrease both supplies equally. Transfers preserve both. The generated public history includes signed transfers, getters, reverts and attempted repeat initialization.

The theorem uses the 50,000-fuel source interpreter, typed public calls, the deployed token layout, and physical storage-key separation under the documented cryptographic assumptions. The constructor is checked directly for arbitrary deployers and nonzero owners. The factory's external CREATE2 response is an environment boundary.

The entry points are Inv39.TraceEmbedding.childHeadroom and the recursive audit in Inv39Proved.lean. The replay command is python3 formal/solidcore/replay_inv39.py --models "$MODELS" --solidcore "$SOLIDCORE" with freshly lowered models.

Source lowering corrections in da8c80a

The importer uses solc-resolved parameter widths for numeric literals in external calls, including the reporting-clock uint48 argument. The pinned compiler resolves library constants in their declaring scope. Replay includes regressions for both cases.

All 261 named declarations passed checked source lowering. Pinned generation reproduced 234 byte-identical checked models and 27 models passed fresh Lean checks. All 128 concrete contracts passed constructor translation. The INV-39 replay freshly compiled all 437 registered modules on the corrected checker and passed the recursive axiom audit. INV-15 and INV-50 remain open.

@KillariDev
KillariDev changed the base branch from main to t3/invariant-tests-and-catalogue December 4, 2026 08:32
Base automatically changed from t3/invariant-tests-and-catalogue to main December 4, 2026 08:52

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant