Repository navigation
Compile all 261 Solidity declarations through SolidCore source lowering - #1784
Draft
KillariDev wants to merge 332 commits into
Draft
KillariDev wants to merge 332 commits into
KillariDev wants to merge 332 commits into
Conversation
This was referenced Nov 26, 2026
…tract-compilation
KillariDev
changed the base branch from
main
to
t3/invariant-tests-and-catalogue
December 4, 2026 08:32
…' into t3/solidcore-contract-compilation
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.gridPricecovers every initial state and full-width products, with explicit word bounds on the multiplied inputs, the first quotient and the final price.Inv02.cappedGridPricederives 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
requiredRepexample 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.maximumRemovalproves the return value of the generated publicInvariantMathHarness.feeBudgetcall 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
mintUnitscall 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.publicMintfollows the generated settlement library through the zero-deposit return, full-width quotient, overflow rejection and precision guard.Inv05.incumbentValueuses 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
mintUnitsandcashForUnitscalls 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. SeeInv06.immediateRedemptionandInv06.firstRedemption.INV-07 remaining backing after redemption
Inv07.remainingBackingproves 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.checkpointFrequencyandInv08.fullVestingagainst the source-generatedSecurityPoolCapitalFeeStreamsand audits their transitive Lean axioms.INV-32
Whenever
quoteExactOutputsuccessfully quotes a gross input, an arbitrary uint256 gross input reaches the target viaquoteExactInputif and only if it is at least the quoted amount. This includes fee rounding, output overshoot and the wide-denominator path.Lean proves
Inv32Source.forwardRefinesandInv32Source.inverseSoundfrom the two public functions of the freshly loweredTwoWayConstantProductMathHarness. The harness calls the productionTwoWayConstantProductMathlibrary. 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 ofpropext,Classical.choice,Quot.sound,Lean.ofReduceBool, andLean.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.splitExactInputinformal/solidcore/inv33/Inv33Proved.leanapplies 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.roundTripExactInputandInv34Source.equalityExampleinformal/solidcore/inv34/Inv34Proved.leanuse 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
conditionalYesBpsmethod 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.mirroredPricesandInv35Source.scaledPricesinformal/solidcore/inv35/Inv35Proved.leanstart 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
initialLiquidityAmountsquote with requested Yes probabilitypin basis points, the quote at10000 - psucceeds 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.initializationSymmetryinformal/solidcore/inv36/Inv36Proved.leanevaluates 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.constructedMaskinformal/solidcore/inv44/Inv44Proved.lean; the replay audits the theorem's transitive axioms.INV-45 scalar question labels
Inv45.Public.scalarLabelsproves the result of the generatedZoltarQuestionData.getAnswerOptionNameselector 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.publicQuoteproves both productionOraclePriceMathhelpers 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.outwardproves that increasing uncertainty widens the representable interval.Inv27.noUncertaintyrecovers the raw price up to the maximum uint256.Inv27.fundedproves 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)satisfiesm <= cexactly whenu*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 whenu*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 inputsu=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
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. SetSOLIDCORE_JOBSto adjust inventory concurrency for the available memory.Validation and proof scope
mulDivcalls matched the reference results, including rounding and exact revert data. Lean also checked themul512limb identity for arbitrary inputs.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.childHeadroomand the recursive audit inInv39Proved.lean. The replay command ispython3 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.