make it more extremely difficult # Gasworks: Adver...

Created on: December 5, 2026

Answered using GPT-6.2 Thinking by Chat01

Question

make it more extremely difficult

Gasworks: Adversarial Whole-System Bytecode Optimization

The current Gasworks is difficult, but a strong frontier model could potentially achieve a respectable score using peephole optimization, constant folding, dead-code elimination, and basic control-flow analysis.

To make it extremely difficult, turn it from a local bytecode optimization problem into a whole-system optimizing compiler problem, where meaningful gas savings require reasoning about dynamically dispatched execution, persistent state, memory aliasing, indirect jumps, and adversarial interactions between contracts.

The difficulty should come from genuine semantic complexity, rather than insufficient documentation, unrealistic time limits, or arbitrary requirements.

1. Increase the core technical difficulty

AreaCurrent GasworksExtreme Gasworks
Control flowJump tables and dispatchersComputed jumps, shared continuations, recursive internal subroutines
System sizeSmall contract combinationsInterdependent systems of 3–12 contracts
StorageBasic persistent stateSymbolic storage keys, dynamic mappings, packed fields and aliasing
MemoryOrdinary memory operationsOverlapping regions, dynamic offsets and conditional aliasing
External callsAdversarial responsesNested reentrancy, callbacks into different contracts and failures
BytecodeTwo compilation stylesMultiple independently generated compilation styles and mixed styles
OptimizationLocal gas savingsInterprocedural analysis and safe global transformations
TransactionsRandom sequencesStateful, adaptive and boundary-value sequences
Hidden systemsUnseen contract typesUnseen combinations of business logic, control flow and bytecode generation techniques

2. Introduce eight genuinely difficult optimization problems

1. Interprocedural control-flow reconstruction

Contracts contain dynamically computed jump destinations, shared subroutines, multiple return sites and code-embedded constants. Changing instruction offsets requires correctly relocating every affected reference.


2. Symbolic storage alias analysis

Repeated storage operations use keys calculated through different arithmetic expressions. The optimizer must determine whether two accesses are equivalent, independent or potentially overlapping.


3. Reentrancy-aware optimization

External calls can invalidate previously established facts about storage, balances and control flow by reentering any reachable contract in the system.


4. Memory alias analysis

Contracts repeatedly copy, overwrite and read partially overlapping memory regions. Removing an apparently redundant write can silently corrupt later return data, logs or call arguments.


5. Path-sensitive symbolic execution

An expression may be redundant on one execution path but essential on another. Useful optimizations require propagating constraints across branches and loop iterations.


6. Cross-contract specialization

Contracts repeatedly interact through predictable interfaces. The optimizer can exploit provable relationships between contracts, but cannot assume that initial state, caller identities or outside responses remain constant.


7. Bit-vector arithmetic simplification

Algebraic transformations must preserve the VM's exact word width, overflow, signedness, shifts and exceptional arithmetic behavior.


8. Optimization under a code-size budget

Inlining, loop unrolling and specialization can reduce execution costs while increasing bytecode size. The optimizer must select profitable transformations without exceeding the deployment limit.

3. Make aggressive optimizations dangerous

For example, consider this execution:

An apparently redundant storage read becomes essential after an adversarial callback.

A naive optimizer caches the first storage read and removes the second. A conservative optimizer preserves both. An advanced optimizer must establish when caching is actually safe.

Build similar situations into memory operations, arithmetic, indirect jumps and cross-contract interactions. Include both safe and unsafe variants so that simply disabling aggressive optimizations sacrifices meaningful gas savings.

4. Expand the hidden systems

Do not rely exclusively on token, vault, staking and auction contracts.

Hidden systemPrimary challenge
Automated market makerArithmetic invariants and storage dependencies
Lending protocolCross-contract state and callbacks
Governance systemDynamic dispatch and complex state transitions
Escrow networkFailure propagation and conditional transfers
Order-matching exchangeLoops, memory aliasing and dynamic data
Multisignature walletVariable-length inputs and indirect execution
Reward distribution systemNested mappings and arithmetic boundaries
Composable financial protocolCombined optimization hazards
Contract routerComputed jumps and runtime dispatch
Settlement systemPartial failures and complex inter-contract dependencies

Generate multiple equivalent bytecode variants of each system using deterministic transformations. Vary instruction layout, stack ordering, arithmetic expressions, dispatch mechanisms and subroutine sharing.

This makes recognizing a particular compiler pattern much less useful.

5. Make basic optimization insufficient

The intended progression should look something like this:

Proposed difficulty calibration — illustrative targets, not measured results

Design workloads where the largest savings come from reasoning across basic blocks, subroutines and contracts, rather than replacing short instruction sequences.

Calibrate those workloads against actual baseline optimizers and the reference implementation.

6. Verifier design that respects the authoring requirements

Avoid making the entire task all-or-nothing. Instead, independently score small systems and workloads.

FunctionalitySub-checksWeight
Control-flow and bytecode transformation420%
Stack, arithmetic and memory optimization420%
Persistent storage optimization420%
Cross-contract and adversarial optimization420%
Gas efficiency on mixed workloads420%
Total20100%

Each sub-check is worth at most 5%. A behavioral difference invalidates that system, not the entire submission. Correct optimizations receive granular credit according to their gas savings.

The unchanged optimizer must earn zero.

This allocation treats the first four groups as functional optimizer capabilities and the last group as non-functional efficiency. Confirm that interpretation against the authoring rules, because gas reduction is itself the primary functionality of Gasworks.

The private verifier should include deterministic transaction sequences, arithmetic boundary values, malformed inputs, deep callbacks, rollback scenarios, equivalent bytecode variants and adaptive outside behavior driven by observable contract interactions.

Also explicitly resolve gas observability, gas-limited execution and code introspection according to evm.py. Otherwise, some seemingly reasonable equivalence requirements could make optimization impossible.

7. Revised candidate-facing instruction

:::writing{variant="document" id="83921"}

Gasworks

Build an optimizing bytecode rewriter for interconnected smart-contract systems.

Existing contracts execute correctly but consume unnecessary gas. Your goal is to reduce their execution costs without changing their observable behavior.

Input

Each system contains deployed contract bytecode, initial persistent storage, addresses and initial balances.

The supplied virtual machine defines the execution semantics. Contracts may use indirect control flow, shared subroutines, dynamic storage addressing, overlapping memory regions and interactions with other contracts.

The supplied examples demonstrate several valid bytecode layouts. Your optimizer must not depend on a particular layout, contract implementation or transaction sequence.

Output

Implement the supplied optimizer command so that it produces replacement bytecode for every contract in the input system.

Your implementation must support previously unseen contracts and systems without manual configuration.

Behavioral requirements

For every valid transaction sequence under the supplied virtual machine, the rewritten system must preserve:

  • Transaction success and failure.
  • Returned data.
  • Emitted logs and their ordering.
  • Calls to outside addresses and their arguments.
  • Persistent storage.
  • Account balances.
  • The observable effects of nested calls and transaction rollback.

Outside addresses are not trusted. They may return arbitrary data, fail, or call back into any accessible contract.

The optimizer must not assume that initial storage values remain constant, that memory regions are independent, or that external interactions leave system state unchanged.

Gas consumption and unobservable intermediate execution state may differ.

Optimization objective

Reduce unnecessary gas consumption across the complete contract system.

The optimizer may restructure control flow, simplify calculations, eliminate redundant operations, specialize execution paths and perform other semantics-preserving transformations.

The implementation must operate using the supplied bytecode and system information alone.

Resource requirements

  • Maximum optimization time: 60 seconds per system.
  • Maximum available CPUs: 2.
  • Maximum replacement bytecode size: 24,576 bytes per contract.

The replacement system must remain executable by the supplied virtual machine without modifications.

The behavior implemented in evm.py is authoritative.
:::

8. Mutants to validate the extreme version

Use eight core functional mutants and two non-functional mutants.

MutantDeliberately broken behavior
M1Incorrect relocation of computed jump destinations
M2Unsound storage alias assumptions
M3Reuse of storage values after reentrant calls
M4Incorrect elimination of overlapping memory writes
M5Arithmetic simplification that ignores overflow
M6Invalid propagation of facts across conditional branches
M7Incorrect cross-contract specialization
M8Incorrect handling of failed calls and rollback
M9Exceeding the bytecode size constraint
M10Exceeding the optimization runtime budget

Each mutant should remain executable and fail for its intended reason. Verify that its score reduction matches its targeted weight within the permitted tolerance.

9. Why this version is substantially harder

The biggest improvement is that the model can no longer solve individual optimization opportunities independently.

One possible architecture for a high-performing solution, rather than a prescribed implementation.

A sophisticated solution may require substantial components of a production optimizing compiler, including abstract interpretation, symbolic execution, alias analysis, interprocedural effect analysis and bytecode generation.

That makes Gasworks substantially more open-ended than a conventional fully specified software engineering task.

Difficulty target: both qualifying frontier models below 30% at medium reasoning effort, while the reference solution consistently earns 100%.

This is a proposed redesign, not an experimentally validated difficulty result. I have retained the original runtime, CPU and bytecode limits rather than making the task harder through artificial resource restrictions. The repository, reference implementation and model proof runs were not supplied, so the proposed scoring distribution and difficulty still require empirical validation.L Gym Task Authoring and Self-Check
A basic pre-submission validation. It covers only what the task requirements state directly and helps candidates catch issues before submitting. It is not the final review, and the final review may identify additional issues. It reports what looks good, what is not passing yet, and what has no proof. It does not suggest redesigns.

Repository context
Use this guidance when authoring or reviewing a task. Run the self-check workflow below when validating a submission; its scratch-copy and no-edit rules apply to validation, not to an explicitly requested authoring change.

Read README.md for the index and the selected task's detailed guide: brownfield/README.md or greenfield/README.md.
Each task root contains task.toml, instruction.md, app/config.toml, environment/Dockerfile, reference-solution/, verifier/, and proof-of-work/.
Only app/ and instruction.md are candidate-visible. Keep reference solutions, verifiers, mutants, proof-of-work, and authoring guidance private.
Keep instructions, setup/run commands, reference behavior, and verification aligned. Keep verifier/scoring.yml synchronized with the verifier's TESTS declarations, which currently award points.
Brownfield has zero-point existing-feature gates in verifier/hidden-tests/. These must pass before scored tests run and are reported separately in reward.json.
Generate solutions using the latest qualifying frontier model versions available at generation time. Outdated models are not allowed. Use medium reasoning effort and include at least two proof-of-solution runs from different qualifying frontier models per task.
Store runs in proof-of-work/model-reasoning-timestamp/, omitting the provider prefix. Include solution/, generation metadata.json and trajectory.jsonl, and verifications/<run-number>/reward.json. Nondeterministic verification also requires metadata and trajectory files in each numbered verification folder.
Keep the root README short and task details in the task READMEs. Update this file when shared authoring guidance changes. Exclude generated dependencies, build output, local databases, and secrets from submissions.
How to run
Task Progress:

  • 1. Read the instruction and the scoring files
  • 2. Run the reference through the verifier twice
  • 3. Run each mutant and compare the score with its weight
  • 4. Read the proof-of-work run records
  • 5. Write the report
    For self-checks, work in a scratch copy of the repo. Do not edit the candidate's files. Run the workflow separately for each task being submitted.

From the selected task root (brownfield/ or greenfield/), read instruction.md, task.toml, verifier/tests/, verifier/scoring.yml, and any verifier/hidden-tests/.
Prepare a fresh scratch copy of reference-solution/ using its setup commands. For Taskboard, use the task's app/config.toml for setup/run commands; GoRedis's reference has its own config.toml. Use the task environment for installed dependencies. Run the verifier twice, using a fresh reference workspace and separate output directory for each run. Keep both scores and logs.
Run each patch in verifier/mutants/ independently against a fresh reference copy, after an unmutated control. Compare the score with the targeted weight and the mutant README's expected score. This repository does not define check:reference or check:mutants npm scripts.
Grade a fresh app/ copy and confirm 0/100. For brownfield, also confirm all existing-feature gates pass.
Open the reference and model run records. Note each run's score, model name/version, reasoning effort, and the instruction and verifier version it was generated against.
After running the workspace's configured setup, invoke the verifier from the task root with absolute paths:

WORKSPACE=/absolute/path/to/prepared-workspace
TASK_DIR="$PWD"
OUT_DIR=/absolute/path/to/results
python3 verifier/tests/run_tests.py
The verifier starts the configured app; leave its port free. Save each run's reward.json and verifier.log. GoRedis also uses OUT_DIR/setup.log to detect setup failure, so preserve setup output there. Scores in this repository use 0–100: the reference target of 1.0 below means 100/100.

What to check

  1. Instruction
    Check Passing looks like
    Realistic A genuine use case with a practical application. Not an arbitrary puzzle with many invented constraints.
    No verifier or test leakage It does not name test files, test cases, check names, weights or how the score is computed.
    No evaluation framing It does not say or imply the task is for RLVR, benchmarking, training or evaluating models.

  2. Verifier
    Check Passing looks like
    Deterministic The reference scores exactly 1.0, and gives the same score on a repeat run. A saved run record showing this exists. If there is no such proof, treat it as "not shown yet".
    Genuine (black-box) It checks behaviour and output, not how the solution is written. It does not require specific function names, attributes, internal values, file names or message text, unless the instruction states them. Many valid implementations should be able to pass.
    Real partial credit It does not rely on all-or-nothing components. A component worth 30% or 40% of the total that gives nothing on a single failure is flagged, because it cannot tell partly correct from fully wrong.
    Functionality weights No single functionality carries more than 25% of the total score. Each major functionality has several granular sub-checks.
    Sub-check weights No single sub-check carries more than 5% of the total score.
    Non-functional share Non-functional requirements (for example performance, limits, robustness) total no more than 20% of the score.
    If the weights break any of these limits, say so and ask the candidate to review the weight allocation.

  3. Mutants
    Check Passing looks like
    Count and mix 7 to 8 mutants on core functional behaviour, plus 1 to 2 on non-functional behaviour.
    Each mutant breaks only its own feature Take the weight of the feature a mutant targets (for example 7%). With that mutant applied, the reference should score about 100% minus that weight (93%). A difference of more than 2 percentage points either way is flagged.
    Caught for the right reason Mutants fail on behaviour, not because the build fails. Run an unmutated control first, and confirm it still scores 1.0.

  4. Reference solution
    Check Passing looks like
    Exists There is a reference solution that builds and runs.
    Scores 1.0 Run against the verifier, it scores exactly 1.0, with the same score on every run.
    Below 1.0 Flag it and ask the candidate to check it. The cause may be the verifier or the reference.
    Not hacky The reference does not hard-code expected values or detect the test inputs to reach 1.0. It solves the task the way the instruction describes.

  5. Proof-of-work
    Check Passing looks like
    Qualifying model runs At least two distinct qualifying models have completed single-pass runs, with records and scores. Use the model anchors and release-date rule below; do not require an exact name match. A missing or unverified run is "not shown yet".
    Difficulty target Each qualifying model must score below 30% in a single pass on the final version, using medium reasoning effort. A score of 30% or higher is flagged for review.
    Repeated zero scores If multiple independent qualifying model runs score 0%, gently ask the author to review whether the instruction and verifier are clear and aligned. Consistent zero scores may indicate a task or verifier issue, rather than only high difficulty.
    Latest version Every run was generated against the latest instruction and the latest verifier. If the instruction or verifier changed after a run was recorded, the proof is not valid until the solution is regenerated and the run completed again on the latest versions.
    Use these as provider and release-date anchors, not as a static exact-name allowlist: GPT-5 Sol / GPT-6 Astra, Claude Opus 5 / Claude Fable 5, Gemini Argon 4 / Gemini 3.8 Flash, Grok 4.7, Muse Wonder, Kimi K3, Qwen 3.8 Max, MiMo V2.6 Pro, Mistral Large 4, GLM 5.3, MiniMax M3, and Nemotron 3.5 Lightning. Normalize case, punctuation, separators, and common provider/model aliases before comparing names. Identify the publishing company for both the candidate model and the matching anchor; use an official model catalog or release announcement to confirm publisher and release chronology when needed. A candidate model qualifies when it is from the same company as an anchor and was released on or after that company's anchor model. Accept newer generations and naming variants, including GPT-6 Sol, GPT-6.1, and GPT-5.1-Sol as later OpenAI models than GPT-5 Sol; do not reject them because their names differ from an anchor. Do not compare version numbers across companies or infer release order from name alone. If the publisher or release chronology cannot be confirmed, treat the run as outside the qualifying set. Runs from companies not represented by these anchors do not count toward candidate-provided proof-of-work. Require at least two distinct qualifying models, each run with medium reasoning effort and scoring below 30% in a single pass on the final task version.

If multiple independent qualifying model runs score 0%, gently ask the author to review whether the task instruction and verifier are clear and aligned. Present this as a possible issue to investigate, not as a conclusion that either is defective.

If proof runs use other models, including free-tier models, acknowledge them as useful early evidence. Explain gently that they may not predict the final assessment: after submission, the task may be evaluated with two leading frontier models selected from examples such as GPT-6 Sol, Claude Opus 5.5, and GPT-6 Astra, using high reasoning effort. The expected score in that assessment is below 40%. Free-tier proof alone may not be sufficient if the task does not meet the final evaluation criteria. Use wording such as: "If your proof runs use other or free-tier models, they can still help you assess the task before submission. For a consistent final assessment, we may also run it after submission with two leading frontier models (for example, GPT-6 Sol, Claude Opus 5.5, or GPT-6 Astra) at high reasoning effort; the task is expected to score below 40%. Free-tier results may differ from that assessment, so final acceptance will depend on the task meeting the evaluation criteria."

To check the last row, compare the instruction and verifier version recorded in each run (a commit, hash or timestamp) with the current files. If the run record has no version, say that the freshness of the proof cannot be confirmed.

How to word the report
Report every miss as a check that is not passing yet. Do not say the work is bad or wrong, and do not accuse.
For checks that meet the stated criteria, use "Looks good" instead of "Passing".
Use plain, calm wording: "This check is not passing yet:", "This is not shown yet:", "Please review:".
Give the evidence: the score, the weight, the count, or the file. Say what you ran and what you read.
Do not propose designs or rewrites. State what failed and what would show it passing.
If a check could not be run, say so once and say why.
Report template

RL Gym Task Self-Check: <task name>

Instruction

  • Realistic: <Looks good / not passing yet, with a one-line reason>
  • No verifier or test leakage: <...>
  • No evaluation framing: <...>

Verifier

  • Deterministic (reference at 1.0, repeatable, proof saved): <...>
  • Genuine (behaviour-based, no unstated exact names or values): <...>
  • Partial credit (no large all-or-nothing component): <...>
  • Functionality weights (max 25%, multiple sub-checks): <...>
  • Sub-check weights (max 5%): <...>
  • Non-functional share (max 20%): <...>

Mutants

  • Count and mix (7-8 core, 1-2 non-functional): <...>
  • Score with each mutant applied matches its weight (within 2 points): <...>
  • Caught on behaviour, control run at 1.0: <...>

Reference solution

  • Exists and runs: <...>
  • Scores 1.0 on every run: <...>
  • Not hacky: <...>

Proof-of-work

  • At least two qualifying-model runs present and verified: <...>
  • Each qualifying model below 30% with medium reasoning on the final version: <...>
  • Repeated 0% scores reviewed for possible instruction/verifier misalignment: <...>
  • Generated against the latest instruction and verifier: <...>

Items to review

<Numbered list of every check that is not passing yet or not shown yet, in the order above. Include the gentle post-submission assessment note when the submitted runs do not meet the provider/release-date rule. Write "None" if everything passes.>

Always end the report with: This is a basic pre-submission validation, not the final review. The final review may identify additional issues.

If the list contains any items, put this reminder after that note so it is the final line: Please resolve the feedback above before you submit the task. Omit the reminder when the list is "None".
Self-check before sending
Every number in the report came from a run or a file read in this check.
Every miss is worded as "not passing yet" or "not shown yet", with the evidence.
No fixes or redesigns are proposed.
The scratch copy was used, and the candidate's repo was not changed.

Thought

Designing harder challenges

I’m reframing the task around adversarial compiler behavior: stateful execution, gas-sensitive paths, opaque dependencies, and semantic traps. I’ll keep the design self-contained, avoid relying on repository files, and make difficulty come from reasoning rather than tedious implementation.

Structuring challenge scoring

I’m separating correctness from efficiency: independent workload families each receive partial credit, while gas, bytecode size, and runtime are scored explicitly. Every mutant targets a distinct semantic weakness, avoiding all-or-nothing grading or accidental overlap.

Refining equivalence rules

I’m tightening the rubric around genuine observables: gas-sensitive branches, forwarded budgets, refunds, introspection, and out-of-gas behavior remain binding where reachable. Efficiency gains are measured only on valid traces, with deterministic caps and partial credit.

Designed harder challenges, scoring, and equivalence rules

Answer

I’ll make the difficulty come from interacting compiler analyses, while keeping the scoring granular and separating the candidate-facing task from the private verifier design.

Thought

Searched 3 websites

Worked for 36s

Answer

Text version

Gasworks: Adversarial Relational Whole-System Optimization

To make Gasworks significantly more difficult than the current extreme version, I would move beyond conventional whole-system optimization into relational program analysis, speculative specialization, recursive effect analysis, and semantics-preserving bytecode synthesis.

The fundamental change is that individual optimization techniques should no longer be sufficient. The most valuable transformations should require several analyses to succeed simultaneously.

A model implementing a respectable conventional optimizing compiler should still struggle to reach 30%.

The difficulty should come from semantic complexity, not obfuscation for its own sake, undocumented behavior, excessive implementation requirements, or artificial resource restrictions.


1. Increase the difficulty ceiling

DimensionPrevious Extreme GasworksNew Gasworks
Control flowComputed jumpsState-dependent dispatch and recursive continuations
Program analysisSymbolic executionRelational, context-sensitive symbolic analysis
StorageSymbolic alias analysisConditional, bit-level and cross-contract alias analysis
External callsNested reentrancyMutually recursive adversarial callbacks
MemoryOverlapping regionsSymbolic byte-level dependencies
ArithmeticBit-vector simplificationModular invariants and guarded equivalence
OptimizationInterprocedural transformationsMulti-stage transformations with interacting preconditions
StatePersistent storageHistory-dependent invariants
SpecializationPredictable interfacesRuntime-guarded specialization with general fallback
Code generationRelocationGlobal stack allocation and relocation-aware synthesis
Gas optimizationIndependent transformationsCompeting transformations under nonlinear costs
Hidden workloadsUnseen contract systemsUnseen combinations of semantic hazards
CorrectnessBehavioral preservationContextual equivalence under adaptive adversaries

2. Introduce 15 advanced optimization challenges

1. Recursive interprocedural control-flow reconstruction

Recover control flow where return destinations are passed through shared subroutines, transformed on the stack, and selected dynamically. Different callers may reach the same instruction with different stack layouts.


2. Relational abstract interpretation

Track relationships between symbolic values rather than independent constants and ranges. An expression may only be redundant because two unknown values satisfy a relationship established several branches earlier.


3. Bit-level persistent storage analysis

Multiple logical fields occupy the same storage word. The optimizer must distinguish modification of an entire word from modification of an individual field, including across external interactions.


4. Recursive reentrancy effect analysis

A contract calls another contract, which invokes an outside address, which calls back into a different contract that can eventually mutate the original contract. The optimizer must conservatively summarize the entire reachable interaction graph.


5. Guarded speculative optimization

Enable aggressive optimization when a runtime condition establishes its safety. Preserve a fully correct general execution path when that condition fails, without making the guard more expensive than the savings.


6. History-dependent state invariants

Some invariants hold only after particular state transitions. Initial storage alone cannot establish them; the optimizer must reason about all reachable mutations and entry points.


7. Byte-precise symbolic memory analysis

Use overlapping writes with dynamic lengths, partially overwritten words, reused call buffers, and conditionally initialized bytes. Eliminating a single write may alter a later hash, log, or return value.


8. Modular arithmetic equivalence

Require simplifications involving wrapping arithmetic, signed comparisons, bit masks, dynamic shifts, multiplication, division, and correlated operands. Include safe and unsafe forms of superficially identical expressions.


9. Path-sensitive loop optimization

Include nested loops whose bounds depend on calldata, persistent state, and previous call results. Loop-invariant computations may become invalid on only one branch of one iteration.


10. Transactional rollback analysis

Differentiate successful nested calls, reverted calls, caught failures, and outer transaction rollback. Facts established inside a failed execution context must not incorrectly survive.


11. Dynamic cross-contract specialization

Contract destinations and interfaces may depend on mutable storage. Specialization must preserve call context, failure behavior, balance effects, and all possible alternative destinations.


12. Global stack scheduling

Eliminate redundant stack manipulation across basic blocks while preserving stack heights, live values, computed destinations, and shared subroutine conventions.


13. Code-as-data relocation

Executable instructions and embedded data coexist in the same bytecode. Rewriting code must preserve reachable jump targets and any observable data extracted from the original layout.


14. Context-dependent gas profitability

Where supported by the VM, account for memory expansion, storage transitions, access costs, refunds, and execution frequencies. Removing instructions does not necessarily produce the most profitable program.


15. Joint transformation selection

Inlining, specialization, code duplication, stack scheduling, and storage elimination compete for the same code-size budget. An individually profitable transformation may prevent a substantially better global transformation.

3. Make the optimization problems dependent on one another

This is the most important difficulty increase.

Instead of constructing 15 separate workloads that independently reward 15 techniques, construct workloads where useful optimizations depend on a chain of discoveries.

Example optimization dependency chain

Reconstruct indirect control flow

Recover reachable functions and continuations

Symbolic key analysis

Resolve storage dependencies

Call graph analysis

Resolve possible callbacks

Recursive effect analysis

Establish which facts survive external calls

Path-sensitive specialization

Identify execution paths where elimination is safe

Profitability and code generation

Produce valid, smaller-cost replacement bytecode

A model that completes five of these stages but cannot perform the sixth may discover the optimization without being able to implement it safely.

Keep individual scoring workloads granular, however, so that failure on a complicated transformation does not invalidate unrelated work.


4. Introduce adversarially similar safe and unsafe programs

Construct pairs or families of contracts where the same optimization is correct in one variant and incorrect in another.

OptimizationSafe variantUnsafe variant
Storage cachingCallback modifies a provably distinct keyCallback modifies an aliased key
Packed-field cachingCallback preserves the relevant bitsCallback modifies overlapping bits
Loop hoistingExpression remains invariantRare iteration invalidates it
Memory write eliminationEvery relevant byte is overwrittenOne byte remains observable
Call specializationDestination is established by a valid guardDestination can change before use
Arithmetic rewritingEquivalence holds under branch constraintsOverflow violates equivalence
Jump relocationDestination expression is fully relocatedEmbedded offset remains unchanged
Write eliminationIntermediate state cannot be observedCallback observes intermediate state
Failure simplificationFailed call effects are rolled backCaller-side effects remain observable
Bounds-check eliminationEarlier conditions imply valid boundsAlternate entry bypasses those conditions

Simply applying aggressive transformations should introduce correctness failures. Simply refusing aggressive transformations should leave substantial gas savings unrealized.

Example: Conditional storage caching

Consider this conceptual program:

python
key = calculate_key(account, market) before = SLOAD(key) if condition: call_external_router(account) else: call_internal_settlement(account) after = SLOAD(key) return combine(before, after)

An advanced optimizer must determine:

  • Whether the storage key aliases any key modified by the reachable contracts.
  • Whether the selected branch can trigger a callback.
  • Whether callback effects modify the relevant storage field.
  • Whether a failed call rolls back those modifications.
  • Whether the second read can be eliminated only along certain execution paths.
  • Whether specializing those paths produces net gas savings.

Use variants in which each of these questions has a different answer.

Do not permit an optimizer to assume that arbitrary hash expressions are mathematically collision-free unless the supplied VM explicitly provides such a guarantee.

5. Expand the hidden systems into composable ecosystems

Rather than testing isolated applications, combine multiple applications into functioning contract ecosystems.

Hidden ecosystemContractsPrimary difficulty
Derivatives clearinghouse12Relational accounting invariants
Multi-market lending protocol10Recursive liquidation callbacks
Cross-pool exchange router9Mutable dispatch and arithmetic
Governance-controlled treasury8History-dependent state
Batch settlement exchange12Dynamic loops and partial failures
Composable yield aggregator11Cross-contract storage dependencies
Insurance claims network8Conditional execution and rollback
Permissioned execution wallet7Indirect control flow
Collateral management system10Packed storage and aliasing
Auction and escrow network9Adversarial interleaving
Dynamic reward distributor8Nested mappings and loop invariants
Multi-protocol settlement engine12Combined semantic hazards

These are proposed system sizes, not measured implementations.

Use deterministic program generation to independently vary:

  • Contract addresses and storage layouts.
  • Dispatch structures and continuation conventions.
  • Equivalent arithmetic expressions.
  • Stack allocation strategies.
  • Memory layouts.
  • Branch nesting and loop structures.
  • Function sharing and duplication.
  • Which semantic invariants hold.
  • Which interactions are safe to optimize.

Hidden systems should contain previously unseen compositions, not merely renamed versions of public examples.

6. Make the private workloads adaptive

Static randomized transactions are insufficient.

Instead, implement deterministic, stateful outside actors whose behavior depends on observable contract interactions.

A deterministic outside actor can initiate nested callbacks and react to observable execution history.

An actor could choose its next action based on call arguments, previous responses, invocation counts, or its own state.

Exercise repeated state transitions, successful and unsuccessful callbacks, unexpected return lengths, malformed calldata, arithmetic boundaries, and transactions that invalidate previously established invariants.

Run the original and optimized systems independently with identical initial conditions and deterministic actor logic.

The actor must not depend on information that the behavioral specification explicitly excludes from observation.

7. Resolve the semantic impossibility problem

The previous instruction contains a potential contradiction: it requires preservation for every transaction sequence while permitting gas consumption to change.

In an actual EVM, gas can influence call execution, and contract bytecode can be inspected directly. Storage access costs can also depend on transaction history. (ethereum.org eips.ethereum.org eips.ethereum.org)

These issues must be resolved according to the actual evm.py, not assumptions about Ethereum.

HazardRequired specification
Remaining gasDefine whether gas-derived observable values must be preserved
Out-of-gas behaviorDefine admissible execution budgets
Forwarded gasDistinguish explicit gas arguments from implicit budget changes
Code introspectionDefine whether replacement bytecode can be observed
Program countersPreserve values when they become observable
Memory expansionFollow the VM's exact observable semantics
Gas refunds and feesSeparate optimization measurements from application-level balances
Unknown opcodesPreserve unsupported regions conservatively
Nonterminating executionDefine the supported execution domain

I recommend comparing execution under documented, nonbinding incidental gas budgets, while retaining meaningful explicit call-budget behavior wherever supported. Arbitrary inspection of rewritten code by outside actors must either be excluded from the equivalence domain or accommodated by preserving the inspected contracts.

Otherwise, the task could unintentionally make valid optimization impossible.


8. Calibrate the difficulty against progressively stronger optimizers

The majority of available credit should come from transformations requiring deep analysis.

Proposed difficulty calibration

Illustrative design targets — not measured model results

If a simple optimizer earns 40%, the workloads are not sufficiently dependent on advanced analysis.

If every reasonable optimizer earns zero, investigate whether the task is too brittle or the verifier is misaligned.

The intended outcome is meaningful partial credit with a very high ceiling.

9. Scoring compliant with the authoring requirements

Use 20 independently scored sub-checks, each worth a maximum of 5%.

Major functionalitySub-checksWeight
Recursive control flow and bytecode synthesis420%
Relational arithmetic and memory transformations420%
Persistent storage and recursive effect analysis420%
Cross-contract specialization and transactional semantics420%
Resource-constrained optimization420%
Total20100%

The first four groups measure the optimizer's primary functional output: correct transformations that reduce execution costs. The final group measures non-functional requirements involving optimization runtime and replacement code size.

This classification should be confirmed against the task-specific authoring guidance.

Granular gas-based scoring

For an individual correctness-preserving workload:

S=w⋅clamp⁡(B−CB−T,0,1)S=w\cdot\operatorname{clamp} \left(\frac{B-C}{B-T},0,1\right)

Where:

  • ww is the workload's maximum score.
  • BB is original gas consumption.
  • CC is candidate gas consumption.
  • TT is the validated gas-consumption target, with T<BT<B.

An incorrect system receives zero for that system. Other independent systems retain their earned credit.

Interactive sub-check scoring example

Original gas

[Input value unavailable]

Gas target

[Input value unavailable]

Candidate gas

[Input value unavailable]

  • Behavioral equivalence checks pass (Current selection unavailable.)

Gas reduction

Sub-check score

/ 5

This ensures the unchanged implementation scores zero, marginal improvements receive partial credit, and correct substantial optimizations receive higher credit.

Resource-focused checks must also require meaningful optimization; otherwise, the unchanged optimizer could earn points simply for finishing quickly.

10. Use stronger, independently targeted mutants

Use eight functional mutants and two non-functional mutants.

MutantDeliberately broken behaviorTargeted weightExpected score
M1Incorrect recursive continuation relocation10%90
M2Incorrect stack scheduling across control-flow merges10%90
M3Unsound relational arithmetic simplification10%90
M4Incorrect symbolic byte-level memory analysis10%90
M5Unsound packed-storage alias analysis10%90
M6Incorrect recursive callback effect summaries10%90
M7Invalid guarded cross-contract specialization10%90
M8Incorrect transactional rollback reasoning10%90
M9Incorrect code-size budgeting10%90
M10Unbounded analysis causing runtime violations10%90

The expected scores are proposed targets. Each must be experimentally verified to fall within the permitted two-point tolerance.

Mutants should introduce genuine localized defects in a working optimizer. They must not detect verifier inputs, deliberately return incorrect test outputs, or fail during setup.

Resource violations must be isolated to affected workloads rather than invalidating the entire submission.

11. Intended reference architecture

A high-performing reference solution could resemble a specialized production optimizing compiler.

Contract system bytecode

Decoder and control-flow recovery

Code/data separation · computed jumps · continuations

Stack-aware intermediate representation

SSA values · memory effects · storage effects

Transformation engine

Elimination · guarded specialization · hoisting · inlining

Global profitability selection

Gas model · code-size budget · conflicting transformations

Stack scheduling and bytecode synthesis

Relocation · layout · conservative fallback

Semantic validation

Optimized contract system

This architecture is private design guidance, not a prescribed candidate implementation. The verifier must accept any implementation that achieves the required behavior and optimization results.

12. Revised candidate-facing instruction

The instruction should remain substantially simpler than the private technical design. It should specify the problem, supported behaviors, constraints, and deliverables without leaking optimization opportunities or scoring details.

:::writing{variant="document" id="83921"}

Gasworks

Implement a general-purpose optimizing bytecode rewriter for interconnected smart-contract systems.

The supplied contracts implement existing applications but incur unnecessary execution costs. Your goal is to produce equivalent replacement bytecode that reduces the gas consumed by these applications.

Input

Each input describes a deployed contract system, including contract addresses, executable bytecode, initial persistent storage, and account balances.

Systems may contain multiple independently compiled contracts with dynamic control flow, shared internal routines, persistent state, indirect calls, and interactions with outside addresses.

Contracts may use different compilation conventions within the same system.

The supplied examples illustrate the input format and supported execution environment. Your implementation must operate on previously unseen systems without manual configuration.

Required implementation

Implement the supplied optimizer command so that it produces replacement bytecode for every contract in an input system.

The optimizer must derive its transformations from the supplied system information.

Replacement contracts must remain executable by the supplied virtual machine without modifications, additional execution infrastructure, or changes to the initial application state.

Behavioral requirements

For every admissible transaction sequence and outside interaction under the supplied execution model, the replacement system must preserve:

  • Transaction success and failure.
  • Returned data.
  • Emitted logs and their ordering.
  • Calls to outside addresses and their observable arguments.
  • Persistent storage and account balances, subject to the documented gas-accounting conventions.
  • Observable effects of nested calls.
  • Call failure and transaction rollback behavior.
  • Observable execution context.

Outside addresses are not trusted. They may fail, return arbitrary data, maintain state, and invoke callbacks into accessible contracts.

Contract interactions may depend on previous transactions, mutable storage, runtime inputs, and earlier call results.

The optimizer must not rely on initial values remaining constant, assume that dynamic addresses are independent, or assume that external interactions preserve application state.

Gas consumption and unobservable intermediate execution state may differ within the supplied execution model.

Optimization objective

Reduce execution gas across the complete contract system.

Transformations may restructure executable code, simplify calculations, eliminate unnecessary work, specialize execution paths, and reorganize interactions where permitted by the execution semantics.

Transformations must remain valid for admissible inputs and interactions beyond the supplied examples.

The implementation may conservatively retain code for which a safe or profitable transformation cannot be established.

Resource requirements

  • Maximum optimization time: 60 seconds per system.
  • Maximum available CPUs: 2.
  • Maximum replacement bytecode size: 24,576 bytes per contract.

The supplied virtual machine and its documented execution model define the authoritative semantics.

Your implementation must not modify the virtual machine or depend on changes to its execution behavior. :::

The final repository must include the referenced execution-model documentation defining gas observability, code introspection, and admissible execution budgets before using this instruction.

13. Features that should not be added merely to increase difficulty

Avoid requiring mandatory SMT solvers, formal proof certificates, a particular intermediate representation, thousands of contracts, encrypted bytecode, intentionally incomplete VM documentation, or extremely short execution limits.

These requirements would increase implementation burden without necessarily creating a better optimization problem.

A reference solution must solve the same general problem as the candidate, rather than recognize generated systems or exploit private workload knowledge.

14. Target difficulty and submission readiness

Reference target

100/100

Two independent verifier runs

Unchanged implementation

0/100

Required baseline

Qualifying frontier models

Below 30%

Medium reasoning effort

Stronger assessment target

Below 40%

High reasoning effort

Independent sub-checks

20

Mutants

10

Pre-submission validation checklist

Validation progress

of

Final assessment

The defining difficulty of this redesign is that knowing how to optimize bytecode is no longer enough.

A strong solution must discover when optimizations are legal, establish relationships across execution paths, reason about mutable state and recursive interactions, select profitable transformations, and synthesize valid replacement code.

It turns Gasworks into a genuine advanced compiler-engineering problem rather than a collection of independent optimization puzzles.

Validation limitation: This is an authoring proposal, not an experimentally validated submission. I retained the original CPU, runtime, and bytecode-size limits. The repository, evm.py, reference implementation, verifier, mutant patches, and proof-of-work records were not supplied, so semantic compatibility, scoring compliance, mutant isolation, reference correctness, and the actual frontier-model difficulty remain unverified.

Share this Q&A