@aztec/simulator 3.0.0-rc.5 → 4.0.0-nightly.20260107

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dest/private/circuit_recording/circuit_recorder.d.ts +1 -1
  2. package/dest/private/circuit_recording/circuit_recorder.d.ts.map +1 -1
  3. package/dest/private/circuit_recording/circuit_recorder.js +15 -14
  4. package/dest/public/avm/opcodes/accrued_substate.js +1 -1
  5. package/dest/public/avm/opcodes/external_calls.d.ts +1 -1
  6. package/dest/public/avm/opcodes/external_calls.d.ts.map +1 -1
  7. package/dest/public/avm/opcodes/external_calls.js +1 -0
  8. package/dest/public/avm/opcodes/hashing.d.ts +1 -1
  9. package/dest/public/avm/opcodes/hashing.d.ts.map +1 -1
  10. package/dest/public/avm/opcodes/hashing.js +6 -3
  11. package/dest/public/debug_fn_name.d.ts +1 -1
  12. package/dest/public/debug_fn_name.d.ts.map +1 -1
  13. package/dest/public/debug_fn_name.js +10 -3
  14. package/dest/public/fixtures/bulk_test.js +3 -51
  15. package/dest/public/fixtures/custom_bytecode_tester.d.ts +28 -6
  16. package/dest/public/fixtures/custom_bytecode_tester.d.ts.map +1 -1
  17. package/dest/public/fixtures/custom_bytecode_tester.js +36 -12
  18. package/dest/public/fixtures/custom_bytecode_tests.d.ts +3 -1
  19. package/dest/public/fixtures/custom_bytecode_tests.d.ts.map +1 -1
  20. package/dest/public/fixtures/custom_bytecode_tests.js +54 -10
  21. package/dest/public/fixtures/index.d.ts +4 -2
  22. package/dest/public/fixtures/index.d.ts.map +1 -1
  23. package/dest/public/fixtures/index.js +3 -1
  24. package/dest/public/fixtures/minimal_public_tx.d.ts +2 -7
  25. package/dest/public/fixtures/minimal_public_tx.d.ts.map +1 -1
  26. package/dest/public/fixtures/minimal_public_tx.js +2 -12
  27. package/dest/public/fixtures/opcode_spammer.d.ts +123 -0
  28. package/dest/public/fixtures/opcode_spammer.d.ts.map +1 -0
  29. package/dest/public/fixtures/opcode_spammer.js +1681 -0
  30. package/dest/public/fixtures/public_tx_simulation_tester.d.ts +15 -2
  31. package/dest/public/fixtures/public_tx_simulation_tester.d.ts.map +1 -1
  32. package/dest/public/fixtures/public_tx_simulation_tester.js +34 -7
  33. package/dest/public/fixtures/utils.d.ts +1 -1
  34. package/dest/public/fixtures/utils.d.ts.map +1 -1
  35. package/dest/public/fixtures/utils.js +3 -2
  36. package/dest/public/fuzzing/avm_fuzzer_simulator.d.ts +1 -1
  37. package/dest/public/fuzzing/avm_fuzzer_simulator.d.ts.map +1 -1
  38. package/dest/public/fuzzing/avm_fuzzer_simulator.js +4 -1
  39. package/dest/public/fuzzing/avm_simulator_bin.js +18 -2
  40. package/dest/public/hinting_db_sources.d.ts +2 -1
  41. package/dest/public/hinting_db_sources.d.ts.map +1 -1
  42. package/dest/public/hinting_db_sources.js +5 -0
  43. package/dest/public/public_processor/guarded_merkle_tree.d.ts +2 -1
  44. package/dest/public/public_processor/guarded_merkle_tree.d.ts.map +1 -1
  45. package/dest/public/public_processor/guarded_merkle_tree.js +5 -0
  46. package/dest/public/public_processor/public_processor.d.ts +2 -2
  47. package/dest/public/public_processor/public_processor.d.ts.map +1 -1
  48. package/dest/public/public_processor/public_processor.js +417 -28
  49. package/dest/public/public_tx_simulator/contract_provider_for_cpp.d.ts +1 -1
  50. package/dest/public/public_tx_simulator/contract_provider_for_cpp.d.ts.map +1 -1
  51. package/dest/public/public_tx_simulator/contract_provider_for_cpp.js +15 -11
  52. package/dest/public/public_tx_simulator/cpp_public_tx_simulator.d.ts +16 -1
  53. package/dest/public/public_tx_simulator/cpp_public_tx_simulator.d.ts.map +1 -1
  54. package/dest/public/public_tx_simulator/cpp_public_tx_simulator.js +41 -3
  55. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.d.ts +1 -1
  56. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.d.ts.map +1 -1
  57. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.js +3 -2
  58. package/dest/public/public_tx_simulator/public_tx_simulator_interface.d.ts +24 -1
  59. package/dest/public/public_tx_simulator/public_tx_simulator_interface.d.ts.map +1 -1
  60. package/dest/public/public_tx_simulator/telemetry_public_tx_simulator.js +395 -19
  61. package/package.json +16 -16
  62. package/src/private/circuit_recording/circuit_recorder.ts +16 -15
  63. package/src/public/avm/opcodes/accrued_substate.ts +1 -1
  64. package/src/public/avm/opcodes/external_calls.ts +1 -0
  65. package/src/public/avm/opcodes/hashing.ts +7 -3
  66. package/src/public/debug_fn_name.ts +10 -3
  67. package/src/public/fixtures/bulk_test.ts +6 -6
  68. package/src/public/fixtures/custom_bytecode_tester.ts +53 -19
  69. package/src/public/fixtures/custom_bytecode_tests.ts +70 -10
  70. package/src/public/fixtures/index.ts +7 -1
  71. package/src/public/fixtures/minimal_public_tx.ts +3 -12
  72. package/src/public/fixtures/opcode_spammer.ts +1638 -0
  73. package/src/public/fixtures/public_tx_simulation_tester.ts +38 -5
  74. package/src/public/fixtures/utils.ts +1 -2
  75. package/src/public/fuzzing/avm_fuzzer_simulator.ts +8 -1
  76. package/src/public/fuzzing/avm_simulator_bin.ts +21 -2
  77. package/src/public/hinting_db_sources.ts +4 -0
  78. package/src/public/public_processor/guarded_merkle_tree.ts +4 -0
  79. package/src/public/public_processor/public_processor.ts +20 -9
  80. package/src/public/public_tx_simulator/contract_provider_for_cpp.ts +16 -11
  81. package/src/public/public_tx_simulator/cpp_public_tx_simulator.ts +48 -3
  82. package/src/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.ts +3 -2
  83. package/src/public/public_tx_simulator/public_tx_simulator_interface.ts +23 -0
@@ -0,0 +1,1681 @@
1
+ /**
2
+ * Opcode Spammer - A minimal, data-driven opcode spammer for AVM gas benchmarking.
3
+ *
4
+ * Design principles:
5
+ * 1. Data over code: Opcode behavior is configuration, not control flow
6
+ * 2. Derive, don't declare: Categories and strategies follow from the data
7
+ * 3. Maximize coverage: Fill bytecode to the limit for accurate gas measurement
8
+ * 4. Smallest wire format: Use _8 variants over _16 to fit more instructions per loop
9
+ * 5. Single file: Everything in one module
10
+ *
11
+ * ## Architecture
12
+ *
13
+ * ```
14
+ * ┌─────────────────────────────────────────────────────────────────┐
15
+ * │ SPAM_CONFIGS │
16
+ * │ Record<Opcode, SpamConfig[]> │
17
+ * │ │
18
+ * │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
19
+ * │ │ ADD_8 │ │ POSEIDON2 │ │EMITNULLIFIER│ ... │
20
+ * │ │ [7 configs] │ │ [1 config] │ │ [1 config] │ │
21
+ * │ │ (per type) │ │ │ │ (limit=63) │ │
22
+ * │ └─────────────┘ └─────────────┘ └─────────────┘ │
23
+ * └─────────────────────────────────────────────────────────────────┘
24
+ * │
25
+ * ▼
26
+ * ┌─────────────────────────────────────────────────────────────────┐
27
+ * │ getSpamConfigsPerOpcode() │
28
+ * │ Returns { opcodes, config[] } for test iteration │
29
+ * └─────────────────────────────────────────────────────────────────┘
30
+ * │
31
+ * ▼
32
+ * ┌─────────────────────────────────────────────────────────────────┐
33
+ * │ testOpcodeSpamCase() │
34
+ * │ Routes to appropriate bytecode generator & executes test │
35
+ * │ │
36
+ * │ config.limit === undefined? │
37
+ * │ YES → testStandardOpcodeSpam() │
38
+ * │ NO → testSideEffectOpcodeSpam() │
39
+ * └─────────────────────────────────────────────────────────────────┘
40
+ * ```
41
+ *
42
+ * ## Two Execution Strategies
43
+ *
44
+ * ### Strategy 1: Standard Opcodes (Gas-Limited)
45
+ *
46
+ * For opcodes without per-TX limits (arithmetic, comparisons, memory ops, etc.), we create a single contract with an infinite loop:
47
+ *
48
+ * ```
49
+ * ┌────────────────────────────────────────────────────────────────┐
50
+ * │ SINGLE CONTRACT │
51
+ * │ │
52
+ * │ ┌──────────────────────────────────────────────────────────┐ │
53
+ * │ │ SETUP PHASE │ │
54
+ * │ │ SET mem[0] = initial_value │ │
55
+ * │ │ SET mem[1] = operand │ │
56
+ * │ │ ... │ │
57
+ * │ └──────────────────────────────────────────────────────────┘ │
58
+ * │ │ │
59
+ * │ ▼ │
60
+ * │ ┌──────────────────────────────────────────────────────────┐ │
61
+ * │ │ LOOP (fills remaining bytecode space) ◄─────┐ │ │
62
+ * │ │ TARGET_OPCODE ─┐ │ │ │
63
+ * │ │ TARGET_OPCODE │ unrolled N times │ │ │
64
+ * │ │ TARGET_OPCODE │ (N = available_bytes / instr_size)│ │ │
65
+ * │ │ ... ─┘ │ │ │
66
+ * │ │ JUMP back ──────────────────────────────────────────┘ │ │
67
+ * │ └──────────────────────────────────────────────────────────┘ │
68
+ * │ │
69
+ * │ Executes until: OUT OF GAS │
70
+ * └────────────────────────────────────────────────────────────────┘
71
+ * ```
72
+ *
73
+ * **Bytecode Layout:**
74
+ * ```
75
+ * ┌─────────────────────────────────────────────────────────────────┐
76
+ * │ 0x00: SET instructions (setup) │
77
+ * │ ... │
78
+ * │ 0xNN: ┌─── LOOP START ◄──────────────────────────────────────┐ │
79
+ * │ │ TARGET_OPCODE │ │
80
+ * │ │ TARGET_OPCODE (unrolled to fill max bytecode size) │ │
81
+ * │ │ TARGET_OPCODE │ │
82
+ * │ │ ... │ │
83
+ * │ └─► JUMP 0xNN ─────────────────────────────────────────┘ │
84
+ * │ MAX_BYTECODE_BYTES │
85
+ * └─────────────────────────────────────────────────────────────────┘
86
+ * ```
87
+ *
88
+ * ### Strategy 2: Side-Effect Limited Opcodes (Nested Call Pattern)
89
+ *
90
+ * For opcodes with per-TX limits (EMITNOTEHASH, EMITNULLIFIER, SENDL2TOL1MSG, etc.), we use a two-contract pattern where the inner contract executes side effects up to the limit, then REVERTs to discard them:
91
+ *
92
+ * ```
93
+ * ┌─────────────────────────────────────────────────────────────────┐
94
+ * │ OUTER CONTRACT │
95
+ * │ │
96
+ * │ ┌───────────────────────────────────────────────────────────┐ │
97
+ * │ │ SETUP │ │
98
+ * │ │ CALLDATACOPY inner_address from calldata[0] │ │
99
+ * │ │ SET l2Gas = MAX_UINT32 │ │
100
+ * │ │ SET daGas = MAX_UINT32 │ │
101
+ * │ └───────────────────────────────────────────────────────────┘ │
102
+ * │ │ │
103
+ * │ ▼ │
104
+ * │ ┌───────────────────────────────────────────────────────────┐ │
105
+ * │ │ LOOP ◄────┐ │ │
106
+ * │ │ CALL inner_contract ──────────────────────┐ │ │ │
107
+ * │ │ JUMP back ─────────────────────────────────────────────┘ │ │
108
+ * │ └───────────────────────────────────────────────────────────┘ │
109
+ * │ │ │
110
+ * │ Executes until: OUT OF GAS │ │
111
+ * └───────────────────────────────────────────────│─────────────────┘
112
+ * │
113
+ * ▼
114
+ * ┌─────────────────────────────────────────────────────────────────┐
115
+ * │ INNER CONTRACT │
116
+ * │ │
117
+ * │ ┌───────────────────────────────────────────────────────────┐ │
118
+ * │ │ SETUP │ │
119
+ * │ │ SET initial values for side-effect opcode │ │
120
+ * │ └───────────────────────────────────────────────────────────┘ │
121
+ * │ │ │
122
+ * │ ▼ │
123
+ * │ ┌───────────────────────────────────────────────────────────┐ │
124
+ * │ │ BODY (unrolled, NOT a loop) │ │
125
+ * │ │ SIDE_EFFECT_OPCODE ─┐ │ │
126
+ * │ │ SIDE_EFFECT_OPCODE │ repeated `limit` times │ │
127
+ * │ │ SIDE_EFFECT_OPCODE │ (e.g., 64 for EMITNOTEHASH) │ │
128
+ * │ │ ... ─┘ │ │
129
+ * │ └───────────────────────────────────────────────────────────┘ │
130
+ * │ │ │
131
+ * │ ▼ │
132
+ * │ ┌───────────────────────────────────────────────────────────┐ │
133
+ * │ │ CLEANUP │ │
134
+ * │ │ REVERT (discards all side effects from this call) │ │
135
+ * │ └───────────────────────────────────────────────────────────┘ │
136
+ * │ │
137
+ * └─────────────────────────────────────────────────────────────────┘
138
+ * ```
139
+ *
140
+ * **Why this pattern?**
141
+ *
142
+ * Side-effect opcodes have per-TX limits:
143
+ * - `EMITNOTEHASH`: max 64 per TX
144
+ * - `EMITNULLIFIER`: max 63 per TX (one reserved for TX nullifier)
145
+ * - `SENDL2TOL1MSG`: max 8 per TX
146
+ * - `EMITUNENCRYPTEDLOG`: limited by total log payload size
147
+ *
148
+ * By having the inner contract REVERT after emitting side effects, those effects are discarded, allowing the outer contract to call it again. This enables thousands of opcode executions per TX instead of just the limit.
149
+ *
150
+ */ import { FLAT_PUBLIC_LOGS_PAYLOAD_LENGTH, MAX_L2_TO_L1_MSGS_PER_TX, MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_PUBLIC_LOG_SIZE_IN_FIELDS, PUBLIC_LOG_HEADER_LENGTH } from '@aztec/constants';
151
+ import { Grumpkin } from '@aztec/foundation/crypto/grumpkin';
152
+ import { randomBigInt } from '@aztec/foundation/crypto/random';
153
+ import { Fr } from '@aztec/foundation/curves/bn254';
154
+ import { PublicDataWrite } from '@aztec/stdlib/avm';
155
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
156
+ import { computePublicDataTreeLeafSlot, siloNullifier } from '@aztec/stdlib/hash';
157
+ import { MerkleTreeId } from '@aztec/stdlib/trees';
158
+ import assert from 'assert';
159
+ import { Field, TaggedMemory, TypeTag, Uint1, Uint32, Uint64 } from '../avm/avm_memory_types.js';
160
+ import { Add, And, Call, CalldataCopy, Cast, DebugLog, Div, EcAdd, EmitNoteHash, EmitNullifier, EmitUnencryptedLog, Eq, FieldDiv, GetContractInstance, GetEnvVar, InternalCall, InternalReturn, Jump, JumpI, KeccakF1600, L1ToL2MessageExists, Lt, Lte, Mov, Mul, Not, NoteHashExists, NullifierExists, Or, Poseidon2, Return, ReturndataCopy, ReturndataSize, Revert, SLoad, SStore, SendL2ToL1Message, Set, Sha256Compression, Shl, Shr, StaticCall, Sub, SuccessCopy, ToRadixBE, Xor } from '../avm/opcodes/index.js';
161
+ import { encodeToBytecode } from '../avm/serialization/bytecode_serialization.js';
162
+ import { Opcode } from '../avm/serialization/instruction_serialization.js';
163
+ import { deployCustomBytecode, executeCustomBytecode } from './custom_bytecode_tester.js';
164
+ // ============================================================================
165
+ // Constants
166
+ // ============================================================================
167
+ /**
168
+ * Constants for "warm" tree reads - these values are inserted into the trees
169
+ * before running the spammer so that existence checks can find them.
170
+ */ export const WARM_NOTE_HASH = new Fr(0xdeadbeefn);
171
+ export const WARM_L1_TO_L2_MSG = new Fr(0xcafebabedeadbeefn);
172
+ /** Warm nullifier constants - uses a fixed address since NULLIFIEREXISTS takes address as parameter */ export const WARM_NULLIFIER = new Fr(0xdeadbeef0001n);
173
+ export const WARM_NULLIFIER_ADDRESS = AztecAddress.fromNumber(0xbeef);
174
+ /** Warm storage constants - storage is inserted for the deployed contract's address */ export const WARM_STORAGE_SLOT = new Fr(0xdeadbeef0002n);
175
+ export const WARM_STORAGE_VALUE = new Fr(0xcafebabe0003n);
176
+ /**
177
+ * Leaf indices inserted to by insertWarmTreeEntries().
178
+ * Ideally we'd getTreeInfo and set dynamically, but that doesn't
179
+ * work easily with static spam configs, so we assume intial index 0.
180
+ */ export const WARM_NOTE_HASH_LEAF_INDEX = 0n;
181
+ export const WARM_L1_TO_L2_MSG_LEAF_INDEX = 0n;
182
+ /**
183
+ * Insert entries into the trees so that "warm" configs can find them with existence checks.
184
+ * Call this before running the opcode spammer to enable warm tree reads.
185
+ *
186
+ * Inserts:
187
+ * - Note hash into NOTE_HASH_TREE
188
+ * - L1 to L2 message into L1_TO_L2_MESSAGE_TREE
189
+ * - Siloed nullifier into NULLIFIER_TREE (for NULLIFIEREXISTS warm check)
190
+ * - Storage value into PUBLIC_DATA_TREE (for SLOAD warm check)
191
+ */ export async function insertWarmTreeEntries(merkleTrees, contractAddress) {
192
+ // Insert into note hash tree
193
+ await merkleTrees.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, [
194
+ WARM_NOTE_HASH
195
+ ]);
196
+ // Insert into L1 to L2 message tree
197
+ await merkleTrees.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [
198
+ WARM_L1_TO_L2_MSG
199
+ ]);
200
+ // Insert siloed nullifier into nullifier tree
201
+ const siloedNullifier = await siloNullifier(WARM_NULLIFIER_ADDRESS, WARM_NULLIFIER);
202
+ await merkleTrees.sequentialInsert(MerkleTreeId.NULLIFIER_TREE, [
203
+ siloedNullifier.toBuffer()
204
+ ]);
205
+ // Insert storage value into public data tree
206
+ const leafSlot = await computePublicDataTreeLeafSlot(contractAddress, WARM_STORAGE_SLOT);
207
+ const publicDataWrite = new PublicDataWrite(leafSlot, WARM_STORAGE_VALUE);
208
+ await merkleTrees.sequentialInsert(MerkleTreeId.PUBLIC_DATA_TREE, [
209
+ publicDataWrite.toBuffer()
210
+ ]);
211
+ }
212
+ /**
213
+ * Maximum bytecode size in bytes.
214
+ *
215
+ * Bytecode is encoded as fields using bufferAsFields():
216
+ * - 1 field for the byte length
217
+ * - ceil(byteLength / 31) fields for the data (31 bytes per field)
218
+ *
219
+ * So: 1 + ceil(byteLength / 31) <= MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS
220
+ * ceil(byteLength / 31) <= MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS - 1
221
+ * byteLength <= (MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS - 1) * 31
222
+ */ const BYTES_PER_FIELD = Fr.SIZE_IN_BYTES - 1; // 31 bytes of data per field
223
+ const MAX_BYTECODE_BYTES = (MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS - 1) * BYTES_PER_FIELD;
224
+ const JUMP_SIZE = encodeToBytecode([
225
+ new Jump(0)
226
+ ]).length; // JUMP_32
227
+ const INTERNALCALL_SIZE = encodeToBytecode([
228
+ new InternalCall(0)
229
+ ]).length;
230
+ // ============================================================================
231
+ // Type Variant Helpers (for generating multiple configs per opcode)
232
+ // ============================================================================
233
+ // Not using these sets directly because we want to control order
234
+ //const ALL_TAGS = Array.from(VALID_TAGS);
235
+ //const INT_TAGS = Array.from(INTEGRAL_TAGS);
236
+ // Ordered so that limiting #configs per opcode still tests max size (Field)
237
+ const ALL_TAGS = [
238
+ TypeTag.FIELD,
239
+ TypeTag.UINT1,
240
+ TypeTag.UINT8,
241
+ TypeTag.UINT16,
242
+ TypeTag.UINT32,
243
+ TypeTag.UINT64,
244
+ TypeTag.UINT128
245
+ ];
246
+ // ordered so that limiting #configs per opcode still tests max size
247
+ const INT_TAGS = [
248
+ TypeTag.UINT128,
249
+ TypeTag.UINT1,
250
+ TypeTag.UINT8,
251
+ TypeTag.UINT16,
252
+ TypeTag.UINT32,
253
+ TypeTag.UINT64
254
+ ];
255
+ /** Build from tag truncating - shorter name */ function withTag(v, tag) {
256
+ return TaggedMemory.buildFromTagTruncating(v, tag);
257
+ }
258
+ // ============================================================================
259
+ // Random Value Helpers (seeded via SEED env var for reproducibility)
260
+ // ============================================================================
261
+ /** Modulus (really just max+1) for each integer type tag */ const TAG_MODULI = {
262
+ [TypeTag.UINT1]: 2n,
263
+ [TypeTag.UINT8]: 256n,
264
+ [TypeTag.UINT16]: 65536n,
265
+ [TypeTag.UINT32]: 0x1_0000_0000n,
266
+ [TypeTag.UINT64]: 0x1_0000_0000_0000_0000n,
267
+ [TypeTag.UINT128]: 0x1_0000_0000_0000_0000_0000_0000_0000_0000n,
268
+ [TypeTag.FIELD]: Fr.MODULUS
269
+ };
270
+ /** Generate a random value with the given type tag. Uses SEED env var if set. */ function randomWithTag(tag) {
271
+ const modulus = TAG_MODULI[tag];
272
+ if (modulus === undefined) {
273
+ throw new Error(`Unsupported tag for random generation: ${TypeTag[tag]}`);
274
+ }
275
+ const value = randomBigInt(modulus);
276
+ return TaggedMemory.buildFromTagTruncating(value, tag);
277
+ }
278
+ /** Generate a random non-zero value with the given type tag (for division). */ function randomNonZeroWithTag(tag) {
279
+ const modulus = TAG_MODULI[tag];
280
+ if (modulus === undefined) {
281
+ throw new Error(`Unsupported tag for random generation: ${TypeTag[tag]}`);
282
+ }
283
+ // Generate random in range [1, max) by generating [0, max-1) and adding 1
284
+ const value = randomBigInt(modulus - 1n) + 1n;
285
+ return TaggedMemory.buildFromTagTruncating(value, tag);
286
+ }
287
+ /** Generate a random non-zero Field value (for field division). */ function randomNonZeroField() {
288
+ return new Field(randomBigInt(Fr.MODULUS - 1n) + 1n);
289
+ }
290
+ /** Reserved memory offsets for external call loop (used by CALL spam and side-effect opcodes) */ const CONST_0_OFFSET = 0; // Uint32(0)
291
+ const CONST_1_OFFSET = 1; // Uint32(1)
292
+ const CONST_MAX_U32_OFFSET = 2; // Uint32(MAX_U32)
293
+ const CALL_ADDR_OFFSET = 3; // copy addr from calldata to here, and then use this addr for CALL
294
+ const CALL_ARGS_OFFSET = CALL_ADDR_OFFSET; // address is the arg to send to CALL
295
+ const CALL_COPY_SIZE_OFFSET = CONST_1_OFFSET; // copy size = 1 (forward calldata[0])
296
+ const CALL_CALLDATA_INDEX_OFFSET = CONST_0_OFFSET; // calldata[0]
297
+ const CALL_L2_GAS_OFFSET = CONST_MAX_U32_OFFSET; // MAX_U32 gets capped to remaining gas by AVM
298
+ const CALL_DA_GAS_OFFSET = CONST_MAX_U32_OFFSET; // MAX_U32 gets capped to remaining gas by AVM
299
+ const CALL_ARGS_SIZE_OFFSET = CONST_1_OFFSET; // argsSize = 1 (forward calldata[0] - might contain contract address)
300
+ const MAX_U32 = 0xffffffffn;
301
+ /**
302
+ * A SpamConfig for to make external CALLs to an address specified in calldata[0].
303
+ */ export const EXTERNAL_CALL_CONFIG = {
304
+ setup: [
305
+ // calldata will contain 1 item: the external call address
306
+ {
307
+ offset: CONST_0_OFFSET,
308
+ value: new Uint32(0)
309
+ },
310
+ {
311
+ offset: CONST_1_OFFSET,
312
+ value: new Uint32(1)
313
+ },
314
+ {
315
+ offset: CONST_MAX_U32_OFFSET,
316
+ value: new Uint32(MAX_U32)
317
+ },
318
+ ()=>[
319
+ new CalldataCopy(/*indirect=*/ 0, /*copySizeOffset=*/ CALL_COPY_SIZE_OFFSET, /*cdStartOffset=*/ CALL_CALLDATA_INDEX_OFFSET, /*dstOffset=*/ CALL_ADDR_OFFSET)
320
+ ]
321
+ ],
322
+ targetInstructions: ()=>[
323
+ new Call(/*indirect=*/ 0, /*l2GasOffset=*/ CALL_L2_GAS_OFFSET, /*daGasOffset=*/ CALL_DA_GAS_OFFSET, /*addrOffset=*/ CALL_ADDR_OFFSET, /*argsSizeOffset=*/ CALL_ARGS_SIZE_OFFSET, /*argsOffset=*/ CALL_ARGS_OFFSET)
324
+ ],
325
+ addressAsCalldata: true
326
+ };
327
+ const STATIC_CALL_CONFIG = {
328
+ setup: [
329
+ // calldata will contain 1 item: the external call address
330
+ {
331
+ offset: CONST_0_OFFSET,
332
+ value: new Uint32(0)
333
+ },
334
+ {
335
+ offset: CONST_1_OFFSET,
336
+ value: new Uint32(1)
337
+ },
338
+ {
339
+ offset: CONST_MAX_U32_OFFSET,
340
+ value: new Uint32(MAX_U32)
341
+ },
342
+ ()=>[
343
+ new CalldataCopy(/*indirect=*/ 0, /*copySizeOffset=*/ CALL_COPY_SIZE_OFFSET, /*cdStartOffset=*/ CALL_CALLDATA_INDEX_OFFSET, /*dstOffset=*/ CALL_ADDR_OFFSET)
344
+ ]
345
+ ],
346
+ targetInstructions: ()=>[
347
+ new StaticCall(/*indirect=*/ 0, /*l2GasOffset=*/ CALL_L2_GAS_OFFSET, /*daGasOffset=*/ CALL_DA_GAS_OFFSET, /*addrOffset=*/ CALL_ADDR_OFFSET, /*argsSizeOffset=*/ CALL_ARGS_SIZE_OFFSET, /*argsOffset=*/ CALL_ARGS_OFFSET)
348
+ ],
349
+ addressAsCalldata: true
350
+ };
351
+ // ============================================================================
352
+ // Configuration Map
353
+ // ============================================================================
354
+ /**
355
+ * Opcode spammer configs for ~all opcodes.
356
+ * Each opcode maps to an array of configs (usually one, but can be multiple for type variants, etc.)
357
+ * Uses smallest wire format (_8) for maximum instruction density.
358
+ */ export const SPAM_CONFIGS = {
359
+ // ═══════════════════════════════════════════════════════════════════════════
360
+ // ARITHMETIC - Test with all type variants (random values, seeded via SEED env var)
361
+ // ═══════════════════════════════════════════════════════════════════════════
362
+ [Opcode.ADD_8]: ALL_TAGS.map((tag)=>({
363
+ label: TypeTag[tag],
364
+ setup: [
365
+ {
366
+ offset: 0,
367
+ value: randomWithTag(tag)
368
+ },
369
+ {
370
+ offset: 1,
371
+ value: randomWithTag(tag)
372
+ }
373
+ ],
374
+ targetInstructions: ()=>[
375
+ new Add(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.ADD_8, Add.wireFormat8)
376
+ ]
377
+ })),
378
+ [Opcode.SUB_8]: ALL_TAGS.map((tag)=>({
379
+ label: TypeTag[tag],
380
+ setup: [
381
+ {
382
+ offset: 0,
383
+ value: randomWithTag(tag)
384
+ },
385
+ {
386
+ offset: 1,
387
+ value: randomWithTag(tag)
388
+ }
389
+ ],
390
+ targetInstructions: ()=>[
391
+ new Sub(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.SUB_8, Sub.wireFormat8)
392
+ ]
393
+ })),
394
+ [Opcode.MUL_8]: ALL_TAGS.map((tag)=>({
395
+ label: TypeTag[tag],
396
+ setup: [
397
+ {
398
+ offset: 0,
399
+ value: randomWithTag(tag)
400
+ },
401
+ {
402
+ offset: 1,
403
+ value: randomWithTag(tag)
404
+ }
405
+ ],
406
+ targetInstructions: ()=>[
407
+ new Mul(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.MUL_8, Mul.wireFormat8)
408
+ ]
409
+ })),
410
+ // DIV doesn't support FIELD type
411
+ [Opcode.DIV_8]: INT_TAGS.map((tag)=>({
412
+ label: TypeTag[tag],
413
+ setup: [
414
+ {
415
+ offset: 0,
416
+ value: randomWithTag(tag)
417
+ },
418
+ {
419
+ offset: 1,
420
+ value: randomNonZeroWithTag(tag)
421
+ }
422
+ ],
423
+ targetInstructions: ()=>[
424
+ new Div(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.DIV_8, Div.wireFormat8)
425
+ ]
426
+ })),
427
+ // Field-only
428
+ [Opcode.FDIV_8]: [
429
+ {
430
+ setup: [
431
+ {
432
+ offset: 0,
433
+ value: new Field(Fr.random())
434
+ },
435
+ {
436
+ offset: 1,
437
+ value: randomNonZeroField()
438
+ }
439
+ ],
440
+ targetInstructions: ()=>[
441
+ new FieldDiv(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.FDIV_8, FieldDiv.wireFormat8)
442
+ ]
443
+ }
444
+ ],
445
+ // ═══════════════════════════════════════════════════════════════════════════
446
+ // COMPARATORS - Test with all type variants (random values)
447
+ // ═══════════════════════════════════════════════════════════════════════════
448
+ [Opcode.EQ_8]: ALL_TAGS.map((tag)=>({
449
+ label: TypeTag[tag],
450
+ setup: [
451
+ {
452
+ offset: 0,
453
+ value: randomWithTag(tag)
454
+ },
455
+ {
456
+ offset: 1,
457
+ value: randomWithTag(tag)
458
+ }
459
+ ],
460
+ targetInstructions: ()=>[
461
+ new Eq(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 2).as(Opcode.EQ_8, Eq.wireFormat8)
462
+ ]
463
+ })),
464
+ [Opcode.LT_8]: ALL_TAGS.map((tag)=>({
465
+ label: TypeTag[tag],
466
+ setup: [
467
+ {
468
+ offset: 0,
469
+ value: randomWithTag(tag)
470
+ },
471
+ {
472
+ offset: 1,
473
+ value: randomWithTag(tag)
474
+ }
475
+ ],
476
+ targetInstructions: ()=>[
477
+ new Lt(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 2).as(Opcode.LT_8, Lt.wireFormat8)
478
+ ]
479
+ })),
480
+ [Opcode.LTE_8]: ALL_TAGS.map((tag)=>({
481
+ label: TypeTag[tag],
482
+ setup: [
483
+ {
484
+ offset: 0,
485
+ value: randomWithTag(tag)
486
+ },
487
+ {
488
+ offset: 1,
489
+ value: randomWithTag(tag)
490
+ }
491
+ ],
492
+ targetInstructions: ()=>[
493
+ new Lte(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 2).as(Opcode.LTE_8, Lte.wireFormat8)
494
+ ]
495
+ })),
496
+ // ═══════════════════════════════════════════════════════════════════════════
497
+ // BITWISE - Integer types only (no FIELD) (random values)
498
+ // ═══════════════════════════════════════════════════════════════════════════
499
+ [Opcode.AND_8]: INT_TAGS.map((tag)=>({
500
+ label: TypeTag[tag],
501
+ setup: [
502
+ {
503
+ offset: 0,
504
+ value: randomWithTag(tag)
505
+ },
506
+ {
507
+ offset: 1,
508
+ value: randomWithTag(tag)
509
+ }
510
+ ],
511
+ targetInstructions: ()=>[
512
+ new And(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.AND_8, And.wireFormat8)
513
+ ]
514
+ })),
515
+ [Opcode.OR_8]: INT_TAGS.map((tag)=>({
516
+ label: TypeTag[tag],
517
+ setup: [
518
+ {
519
+ offset: 0,
520
+ value: randomWithTag(tag)
521
+ },
522
+ {
523
+ offset: 1,
524
+ value: randomWithTag(tag)
525
+ }
526
+ ],
527
+ targetInstructions: ()=>[
528
+ new Or(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.OR_8, Or.wireFormat8)
529
+ ]
530
+ })),
531
+ [Opcode.XOR_8]: INT_TAGS.map((tag)=>({
532
+ label: TypeTag[tag],
533
+ setup: [
534
+ {
535
+ offset: 0,
536
+ value: randomWithTag(tag)
537
+ },
538
+ {
539
+ offset: 1,
540
+ value: randomWithTag(tag)
541
+ }
542
+ ],
543
+ targetInstructions: ()=>[
544
+ new Xor(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.XOR_8, Xor.wireFormat8)
545
+ ]
546
+ })),
547
+ [Opcode.NOT_8]: INT_TAGS.map((tag)=>({
548
+ label: TypeTag[tag],
549
+ setup: [
550
+ {
551
+ offset: 0,
552
+ value: randomWithTag(tag)
553
+ }
554
+ ],
555
+ targetInstructions: ()=>[
556
+ new Not(/*indirect=*/ 0, /*srcOffset=*/ 0, /*dstOffset=*/ 0).as(Opcode.NOT_8, Not.wireFormat8)
557
+ ]
558
+ })),
559
+ [Opcode.SHL_8]: INT_TAGS.map((tag)=>({
560
+ label: TypeTag[tag],
561
+ setup: [
562
+ {
563
+ offset: 0,
564
+ value: randomWithTag(tag)
565
+ },
566
+ {
567
+ offset: 1,
568
+ value: withTag(1n, tag)
569
+ }
570
+ ],
571
+ targetInstructions: ()=>[
572
+ new Shl(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.SHL_8, Shl.wireFormat8)
573
+ ]
574
+ })),
575
+ [Opcode.SHR_8]: INT_TAGS.map((tag)=>({
576
+ label: TypeTag[tag],
577
+ setup: [
578
+ {
579
+ offset: 0,
580
+ value: randomWithTag(tag)
581
+ },
582
+ {
583
+ offset: 1,
584
+ value: withTag(1n, tag)
585
+ }
586
+ ],
587
+ targetInstructions: ()=>[
588
+ new Shr(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.SHR_8, Shr.wireFormat8)
589
+ ]
590
+ })),
591
+ // ═══════════════════════════════════════════════════════════════════════════
592
+ // CAST / MOV - Test with all type variants (random values)
593
+ // ═══════════════════════════════════════════════════════════════════════════
594
+ [Opcode.CAST_8]: ALL_TAGS.map((tag)=>({
595
+ label: TypeTag[tag],
596
+ setup: [
597
+ {
598
+ offset: 0,
599
+ value: randomWithTag(tag)
600
+ }
601
+ ],
602
+ targetInstructions: ()=>[
603
+ new Cast(/*indirect=*/ 0, /*srcOffset=*/ 0, /*dstOffset=*/ 1, /*dstTag=*/ TypeTag.UINT32).as(Opcode.CAST_8, Cast.wireFormat8)
604
+ ]
605
+ })),
606
+ [Opcode.MOV_8]: ALL_TAGS.map((tag)=>({
607
+ label: TypeTag[tag],
608
+ setup: [
609
+ {
610
+ offset: 0,
611
+ value: randomWithTag(tag)
612
+ }
613
+ ],
614
+ targetInstructions: ()=>[
615
+ new Mov(/*indirect=*/ 0, /*srcOffset=*/ 0, /*dstOffset=*/ 1).as(Opcode.MOV_8, Mov.wireFormat8)
616
+ ]
617
+ })),
618
+ // ═══════════════════════════════════════════════════════════════════════════
619
+ // MEMORY - SET
620
+ // ═══════════════════════════════════════════════════════════════════════════
621
+ // Not testing all wire formats as they should be roughly the same in terms of simulation
622
+ // and proving time
623
+ //[Opcode.SET_8]: [
624
+ // {
625
+ // setup: [],
626
+ // targetInstructions: () => [new Set(0, 0, TypeTag.UINT8, 42).as(Opcode.SET_8, Set.wireFormat8)],
627
+ // },
628
+ //],
629
+ //[Opcode.SET_16]: [
630
+ // {
631
+ // setup: [],
632
+ // targetInstructions: () => [new Set(0, 0, TypeTag.UINT16, 4242).as(Opcode.SET_16, Set.wireFormat16)],
633
+ // },
634
+ //],
635
+ //[Opcode.SET_32]: [
636
+ // {
637
+ // setup: [],
638
+ // targetInstructions: () => [new Set(0, 0, TypeTag.UINT32, 424242).as(Opcode.SET_32, Set.wireFormat32)],
639
+ // },
640
+ //],
641
+ //[Opcode.SET_64]: [
642
+ // {
643
+ // setup: [],
644
+ // targetInstructions: () => [new Set(0, 0, TypeTag.UINT64, 42424242n).as(Opcode.SET_64, Set.wireFormat64)],
645
+ // },
646
+ //],
647
+ [Opcode.SET_128]: [
648
+ {
649
+ setup: [],
650
+ targetInstructions: ()=>[
651
+ new Set(/*indirect=*/ 0, /*dstOffset=*/ 0, /*inTag=*/ TypeTag.UINT128, /*value=*/ 4242424242424242n).as(Opcode.SET_128, Set.wireFormat128)
652
+ ]
653
+ }
654
+ ],
655
+ //[Opcode.SET_FF]: [
656
+ // {
657
+ // setup: [],
658
+ // targetInstructions: () => [new Set(0, 0, TypeTag.FIELD, 42n).as(Opcode.SET_FF, Set.wireFormatFF)],
659
+ // },
660
+ //],
661
+ // ═══════════════════════════════════════════════════════════════════════════
662
+ // CONTROL FLOW
663
+ // ═══════════════════════════════════════════════════════════════════════════
664
+ [Opcode.JUMP_32]: [
665
+ {
666
+ setup: [],
667
+ // Target will be overwritten by loop builder
668
+ targetInstructions: ()=>[
669
+ new Jump(/*jumpOffset=*/ 0)
670
+ ]
671
+ }
672
+ ],
673
+ [Opcode.JUMPI_32]: [
674
+ {
675
+ setup: [
676
+ {
677
+ offset: 0,
678
+ value: new Uint1(0n)
679
+ }
680
+ ],
681
+ targetInstructions: ()=>[
682
+ new JumpI(/*indirect=*/ 0, /*condOffset=*/ 0, /*loc=*/ 0)
683
+ ]
684
+ }
685
+ ],
686
+ // INTERNALCALL: calls itself infinitely by jumping to its own PC (PC 0, since no setup)
687
+ // Creates infinite recursion until OOG (internal call stack grows forever)
688
+ [Opcode.INTERNALCALL]: [
689
+ {
690
+ setup: [],
691
+ targetInstructions: ()=>[
692
+ new InternalCall(/*loc=*/ 0)
693
+ ]
694
+ }
695
+ ],
696
+ // INTERNALRETURN: needs INTERNALCALL to return without error
697
+ // Layout: INTERNALCALL(10) -> JUMP(0) -> INTERNALRETURN
698
+ // INTERNALCALL jumps to INTERNALRETURN, which returns to JUMP, which loops back
699
+ [Opcode.INTERNALRETURN]: [
700
+ {
701
+ setup: [],
702
+ targetInstructions: ()=>[
703
+ new InternalCall(/*loc=*/ INTERNALCALL_SIZE + JUMP_SIZE),
704
+ new Jump(/*jumpOffset=*/ 0),
705
+ new InternalReturn()
706
+ ]
707
+ }
708
+ ],
709
+ // CALL (EXTERNALCALL): calls the current contract address (self) in a loop
710
+ // Contract address is passed via calldata[0] and propagated to nested calls
711
+ [Opcode.CALL]: [
712
+ EXTERNAL_CALL_CONFIG
713
+ ],
714
+ [Opcode.STATICCALL]: [
715
+ STATIC_CALL_CONFIG
716
+ ],
717
+ // RETURN: terminates execution, so we need to use the two-contract pattern
718
+ // Outer contract CALLs inner contract in a loop, inner contract does RETURN
719
+ [Opcode.RETURN]: [
720
+ {
721
+ setup: [
722
+ {
723
+ offset: 0,
724
+ value: new Uint32(0)
725
+ }
726
+ ],
727
+ targetInstructions: ()=>[
728
+ new Return(/*indirect=*/ 0, /*returnSizeOffset=*/ 0, /*returnOffset=*/ 0)
729
+ ],
730
+ // Use the side-effect-limit pattern (even though it's not a side-effect) as it fits
731
+ // this case (we want to CALL, RETURN, then CALL again back in parent). We omit "cleanup"
732
+ // because we don't need to REVERT as we do for real side-effects.
733
+ limit: 1
734
+ }
735
+ ],
736
+ // REVERT: terminates execution, so we need to use the two-contract pattern
737
+ // Outer contract CALLs inner contract in a loop, inner contract does REVERT
738
+ [Opcode.REVERT_8]: [
739
+ {
740
+ setup: [
741
+ {
742
+ offset: 0,
743
+ value: new Uint32(0)
744
+ }
745
+ ],
746
+ targetInstructions: ()=>[
747
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 0, /*returnOffset=*/ 1).as(Opcode.REVERT_8, Revert.wireFormat8)
748
+ ],
749
+ limit: 1
750
+ }
751
+ ],
752
+ // ═══════════════════════════════════════════════════════════════════════════
753
+ // ENVIRONMENT
754
+ // ═══════════════════════════════════════════════════════════════════════════
755
+ [Opcode.GETENVVAR_16]: [
756
+ {
757
+ setup: [],
758
+ targetInstructions: ()=>[
759
+ new GetEnvVar(/*indirect=*/ 0, /*dstOffset=*/ 0, /*varEnum=*/ 0).as(Opcode.GETENVVAR_16, GetEnvVar.wireFormat16)
760
+ ]
761
+ }
762
+ ],
763
+ // CALLDATACOPY has dynamic gas scaling with copySize
764
+ [Opcode.CALLDATACOPY]: [
765
+ {
766
+ label: 'Min copy size',
767
+ // CalldataCopy with copySize=0 is a no-op but still executes the opcode
768
+ setup: [
769
+ {
770
+ offset: 0,
771
+ value: new Uint32(0n)
772
+ },
773
+ {
774
+ offset: 1,
775
+ value: new Uint32(0n)
776
+ }
777
+ ],
778
+ targetInstructions: ()=>[
779
+ new CalldataCopy(/*indirect=*/ 0, /*copySizeOffset=*/ 0, /*cdStartOffset=*/ 1, /*dstOffset=*/ 2)
780
+ ]
781
+ },
782
+ {
783
+ label: 'Large copy size',
784
+ // Large copySize with large dynamic gas - will OOG quickly
785
+ // NOTE: we don't want it so large that it exceeds memory bounds (MAX_MEMORY_SIZE = 2^32)
786
+ // and we really want it small enough that we run at least 1 successful target opcode.
787
+ setup: [
788
+ {
789
+ offset: 0,
790
+ value: new Uint32(1000n)
791
+ },
792
+ {
793
+ offset: 1,
794
+ value: new Uint32(0n)
795
+ }
796
+ ],
797
+ targetInstructions: ()=>[
798
+ new CalldataCopy(/*indirect=*/ 0, /*copySizeOffset=*/ 0, /*cdStartOffset=*/ 1, /*dstOffset=*/ 2)
799
+ ]
800
+ },
801
+ {
802
+ label: 'Near min copy size of 1',
803
+ // Near-min but actually copies data (more meaningful than size=0 no-op)
804
+ setup: [
805
+ {
806
+ offset: 0,
807
+ value: new Uint32(1n)
808
+ },
809
+ {
810
+ offset: 1,
811
+ value: new Uint32(0n)
812
+ }
813
+ ],
814
+ targetInstructions: ()=>[
815
+ new CalldataCopy(/*indirect=*/ 0, /*copySizeOffset=*/ 0, /*cdStartOffset=*/ 1, /*dstOffset=*/ 2)
816
+ ]
817
+ }
818
+ ],
819
+ [Opcode.SUCCESSCOPY]: [
820
+ {
821
+ setup: [],
822
+ targetInstructions: ()=>[
823
+ new SuccessCopy(/*indirect=*/ 0, /*dstOffset=*/ 0)
824
+ ]
825
+ }
826
+ ],
827
+ [Opcode.RETURNDATASIZE]: [
828
+ {
829
+ setup: [],
830
+ targetInstructions: ()=>[
831
+ new ReturndataSize(/*indirect=*/ 0, /*dstOffset=*/ 0)
832
+ ]
833
+ }
834
+ ],
835
+ // RETURNDATACOPY has dynamic gas scaling with copySize
836
+ [Opcode.RETURNDATACOPY]: [
837
+ {
838
+ label: 'Min copy size',
839
+ setup: [
840
+ {
841
+ offset: 0,
842
+ value: new Uint32(0n)
843
+ },
844
+ {
845
+ offset: 1,
846
+ value: new Uint32(0n)
847
+ }
848
+ ],
849
+ targetInstructions: ()=>[
850
+ new ReturndataCopy(/*indirect=*/ 0, /*copySizeOffset=*/ 0, /*rdStartOffset=*/ 1, /*dstOffset=*/ 2)
851
+ ]
852
+ },
853
+ {
854
+ label: 'Large copy size',
855
+ // Large copySize to maximize dynamic gas - will OOG quickly
856
+ // NOTE: we don't want it so large that it exceeds memory bounds (MAX_MEMORY_SIZE = 2^32)
857
+ // and we really want it small enough that we run at least 1 successful target opcode.
858
+ setup: [
859
+ {
860
+ offset: 0,
861
+ value: new Uint32(1000n)
862
+ },
863
+ {
864
+ offset: 1,
865
+ value: new Uint32(0n)
866
+ }
867
+ ],
868
+ targetInstructions: ()=>[
869
+ new ReturndataCopy(/*indirect=*/ 0, /*copySizeOffset=*/ 0, /*rdStartOffset=*/ 1, /*dstOffset=*/ 2)
870
+ ]
871
+ },
872
+ {
873
+ label: 'Near min copy size of 1',
874
+ // Near-min but actually copies data (more meaningful than size=0 no-op)
875
+ setup: [
876
+ {
877
+ offset: 0,
878
+ value: new Uint32(1n)
879
+ },
880
+ {
881
+ offset: 1,
882
+ value: new Uint32(0n)
883
+ }
884
+ ],
885
+ targetInstructions: ()=>[
886
+ new ReturndataCopy(/*indirect=*/ 0, /*copySizeOffset=*/ 0, /*rdStartOffset=*/ 1, /*dstOffset=*/ 2)
887
+ ]
888
+ }
889
+ ],
890
+ // ═══════════════════════════════════════════════════════════════════════════
891
+ // WORLD STATE READS
892
+ // ═══════════════════════════════════════════════════════════════════════════
893
+ [Opcode.SLOAD]: [
894
+ {
895
+ label: 'Cold read (slot not written)',
896
+ setup: [
897
+ {
898
+ offset: 0,
899
+ value: new Field(Fr.random())
900
+ }
901
+ ],
902
+ targetInstructions: ()=>[
903
+ new SLoad(/*indirect=*/ 0, /*slotOffset=*/ 0, /*dstOffset=*/ 1)
904
+ ]
905
+ },
906
+ {
907
+ label: 'Warm read (from tree)',
908
+ // Uses pre-inserted storage from insertWarmTreeEntries() which is called after contract deployment
909
+ setup: [
910
+ {
911
+ offset: 0,
912
+ value: new Field(WARM_STORAGE_SLOT)
913
+ }
914
+ ],
915
+ targetInstructions: ()=>[
916
+ new SLoad(/*indirect=*/ 0, /*slotOffset=*/ 0, /*dstOffset=*/ 1)
917
+ ]
918
+ },
919
+ {
920
+ label: 'Warm read (SSTORE first, unique slot per SLOAD)',
921
+ // Memory layout: slot (incremented), value, constant 1, revertSize, loaded value
922
+ setup: [
923
+ {
924
+ offset: 0,
925
+ value: new Field(Fr.random())
926
+ },
927
+ {
928
+ offset: 1,
929
+ value: new Field(Fr.random())
930
+ },
931
+ {
932
+ offset: 2,
933
+ value: new Field(1n)
934
+ },
935
+ {
936
+ offset: 3,
937
+ value: new Uint32(0n)
938
+ }
939
+ ],
940
+ targetInstructions: ()=>[
941
+ new SStore(/*indirect=*/ 0, /*srcOffset=*/ 1, /*slotOffset=*/ 0),
942
+ new SLoad(/*indirect=*/ 0, /*slotOffset=*/ 0, /*dstOffset=*/ 4),
943
+ new Add(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 2, /*dstOffset=*/ 0).as(Opcode.ADD_8, Add.wireFormat8)
944
+ ],
945
+ cleanupInstructions: ()=>[
946
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 3, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8)
947
+ ],
948
+ limit: MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX
949
+ }
950
+ ],
951
+ [Opcode.NOTEHASHEXISTS]: [
952
+ {
953
+ label: 'Cold (non-existent)',
954
+ // Note: Can't easily do "write first" version - would need to know the leaf index
955
+ // that EMITNOTEHASH will produce, which depends on tree state
956
+ setup: [
957
+ {
958
+ offset: 0,
959
+ value: new Field(Fr.random())
960
+ },
961
+ {
962
+ offset: 1,
963
+ value: randomWithTag(TypeTag.UINT64)
964
+ }
965
+ ],
966
+ targetInstructions: ()=>[
967
+ new NoteHashExists(/*indirect=*/ 0, /*noteHashOffset=*/ 0, /*leafIndexOffset=*/ 1, /*existsOffset=*/ 2)
968
+ ]
969
+ },
970
+ {
971
+ label: 'Warm (exists in tree)',
972
+ // Uses pre-inserted note hash from insertWarmTreeEntries()
973
+ setup: [
974
+ {
975
+ offset: 0,
976
+ value: new Field(WARM_NOTE_HASH)
977
+ },
978
+ {
979
+ offset: 1,
980
+ value: new Uint64(WARM_NOTE_HASH_LEAF_INDEX)
981
+ }
982
+ ],
983
+ targetInstructions: ()=>[
984
+ new NoteHashExists(/*indirect=*/ 0, /*noteHashOffset=*/ 0, /*leafIndexOffset=*/ 1, /*existsOffset=*/ 2)
985
+ ]
986
+ }
987
+ ],
988
+ [Opcode.NULLIFIEREXISTS]: [
989
+ {
990
+ label: 'Non-existent nullifier',
991
+ setup: [
992
+ {
993
+ offset: 0,
994
+ value: new Field(Fr.random())
995
+ },
996
+ {
997
+ offset: 1,
998
+ value: new Field(Fr.random())
999
+ }
1000
+ ],
1001
+ targetInstructions: ()=>[
1002
+ new NullifierExists(/*indirect=*/ 0, /*nullifierOffset=*/ 0, /*addressOffset=*/ 1, /*existsOffset=*/ 2)
1003
+ ]
1004
+ },
1005
+ {
1006
+ label: 'Existing nullifier (warm - from tree)',
1007
+ // Uses pre-inserted nullifier from insertWarmTreeEntries()
1008
+ setup: [
1009
+ {
1010
+ offset: 0,
1011
+ value: new Field(WARM_NULLIFIER)
1012
+ },
1013
+ {
1014
+ offset: 1,
1015
+ value: new Field(WARM_NULLIFIER_ADDRESS.toField())
1016
+ }
1017
+ ],
1018
+ targetInstructions: ()=>[
1019
+ new NullifierExists(/*indirect=*/ 0, /*nullifierOffset=*/ 0, /*addressOffset=*/ 1, /*existsOffset=*/ 2)
1020
+ ]
1021
+ },
1022
+ {
1023
+ label: 'Existing nullifier (warm - EMITNULLIFIER first)',
1024
+ // Memory layout: nullifier (incremented), constant 1, current address (from GETENVVAR), revertSize, exists result
1025
+ setup: [
1026
+ {
1027
+ offset: 0,
1028
+ value: new Field(Fr.random())
1029
+ },
1030
+ {
1031
+ offset: 1,
1032
+ value: new Field(1n)
1033
+ },
1034
+ ()=>[
1035
+ // Get current contract address into offset 2
1036
+ new GetEnvVar(/*indirect=*/ 0, /*dstOffset=*/ 2, /*varEnum=*/ 0).as(Opcode.GETENVVAR_16, GetEnvVar.wireFormat16)
1037
+ ],
1038
+ {
1039
+ offset: 3,
1040
+ value: new Uint32(0n)
1041
+ }
1042
+ ],
1043
+ targetInstructions: ()=>[
1044
+ new EmitNullifier(/*indirect=*/ 0, /*nullifierOffset=*/ 0),
1045
+ new NullifierExists(/*indirect=*/ 0, /*nullifierOffset=*/ 0, /*addressOffset=*/ 2, /*existsOffset=*/ 4),
1046
+ new Add(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.ADD_8, Add.wireFormat8)
1047
+ ],
1048
+ cleanupInstructions: ()=>[
1049
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 3, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8)
1050
+ ],
1051
+ limit: MAX_NULLIFIERS_PER_TX - 1
1052
+ }
1053
+ ],
1054
+ [Opcode.L1TOL2MSGEXISTS]: [
1055
+ {
1056
+ label: 'Cold (non-existent)',
1057
+ setup: [
1058
+ {
1059
+ offset: 0,
1060
+ value: new Field(Fr.random())
1061
+ },
1062
+ {
1063
+ offset: 1,
1064
+ value: randomWithTag(TypeTag.UINT64)
1065
+ }
1066
+ ],
1067
+ targetInstructions: ()=>[
1068
+ new L1ToL2MessageExists(/*indirect=*/ 0, /*msgHashOffset=*/ 0, /*msgLeafIndexOffset=*/ 1, /*existsOffset=*/ 2)
1069
+ ]
1070
+ },
1071
+ {
1072
+ label: 'Warm (exists in tree)',
1073
+ // Uses pre-inserted L1 to L2 message from insertWarmTreeEntries()
1074
+ setup: [
1075
+ {
1076
+ offset: 0,
1077
+ value: new Field(WARM_L1_TO_L2_MSG)
1078
+ },
1079
+ {
1080
+ offset: 1,
1081
+ value: new Uint64(WARM_L1_TO_L2_MSG_LEAF_INDEX)
1082
+ }
1083
+ ],
1084
+ targetInstructions: ()=>[
1085
+ new L1ToL2MessageExists(/*indirect=*/ 0, /*msgHashOffset=*/ 0, /*msgLeafIndexOffset=*/ 1, /*existsOffset=*/ 2)
1086
+ ]
1087
+ }
1088
+ ],
1089
+ [Opcode.GETCONTRACTINSTANCE]: [
1090
+ {
1091
+ // Use GETENVVAR to get current contract address (varEnum 0 = ADDRESS)
1092
+ // This ensures we're querying a valid deployed contract
1093
+ setup: [
1094
+ ()=>[
1095
+ new GetEnvVar(/*indirect=*/ 0, /*dstOffset=*/ 0, /*varEnum=*/ 0).as(Opcode.GETENVVAR_16, GetEnvVar.wireFormat16)
1096
+ ]
1097
+ ],
1098
+ // memberEnum 0 = DEPLOYER
1099
+ targetInstructions: ()=>[
1100
+ new GetContractInstance(/*indirect=*/ 0, /*addressOffset=*/ 0, /*dstOffset=*/ 1, /*memberEnum=*/ 0)
1101
+ ]
1102
+ }
1103
+ ],
1104
+ // ═══════════════════════════════════════════════════════════════════════════
1105
+ // SIDE-EFFECT LIMITED (have per-TX limit, use nested call pattern)
1106
+ // ═══════════════════════════════════════════════════════════════════════════
1107
+ [Opcode.EMITNOTEHASH]: [
1108
+ {
1109
+ setup: [
1110
+ {
1111
+ offset: 0,
1112
+ value: new Field(Fr.random())
1113
+ },
1114
+ {
1115
+ offset: 1,
1116
+ value: new Uint32(0n)
1117
+ }
1118
+ ],
1119
+ targetInstructions: ()=>[
1120
+ new EmitNoteHash(/*indirect=*/ 0, /*noteHashOffset=*/ 0)
1121
+ ],
1122
+ cleanupInstructions: ()=>[
1123
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 1, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8)
1124
+ ],
1125
+ limit: MAX_NOTE_HASHES_PER_TX
1126
+ }
1127
+ ],
1128
+ [Opcode.EMITNULLIFIER]: [
1129
+ {
1130
+ // Nullifiers must be unique - increment value after each emit
1131
+ // Memory layout: offset 0 = nullifier value, offset 1 = constant 1 for incrementing
1132
+ setup: [
1133
+ {
1134
+ offset: 0,
1135
+ value: new Field(Fr.random())
1136
+ },
1137
+ {
1138
+ offset: 1,
1139
+ value: new Field(1n)
1140
+ },
1141
+ {
1142
+ offset: 2,
1143
+ value: new Uint32(0n)
1144
+ }
1145
+ ],
1146
+ targetInstructions: ()=>[
1147
+ new EmitNullifier(/*indirect=*/ 0, /*nullifierOffset=*/ 0),
1148
+ new Add(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.ADD_8, Add.wireFormat8)
1149
+ ],
1150
+ cleanupInstructions: ()=>[
1151
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 2, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8)
1152
+ ],
1153
+ limit: MAX_NULLIFIERS_PER_TX - 1
1154
+ }
1155
+ ],
1156
+ [Opcode.SENDL2TOL1MSG]: [
1157
+ {
1158
+ setup: [
1159
+ {
1160
+ offset: 0,
1161
+ value: new Field(Fr.random())
1162
+ },
1163
+ {
1164
+ offset: 1,
1165
+ value: new Field(Fr.random())
1166
+ },
1167
+ {
1168
+ offset: 2,
1169
+ value: new Uint32(0n)
1170
+ }
1171
+ ],
1172
+ targetInstructions: ()=>[
1173
+ new SendL2ToL1Message(/*indirect=*/ 0, /*recipientOffset=*/ 0, /*contentOffset=*/ 1)
1174
+ ],
1175
+ cleanupInstructions: ()=>[
1176
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 2, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8)
1177
+ ],
1178
+ limit: MAX_L2_TO_L1_MSGS_PER_TX
1179
+ }
1180
+ ],
1181
+ // SSTORE has two modes:
1182
+ // 1. Same slot: Writing to the same slot repeatedly has no per-TX limit - it just overwrites.
1183
+ // 2. Unique slots: Writing to unique slots is limited by MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX.
1184
+ [Opcode.SSTORE]: [
1185
+ {
1186
+ label: 'Same slot (no limit)',
1187
+ setup: [
1188
+ {
1189
+ offset: 0,
1190
+ value: new Field(Fr.random())
1191
+ },
1192
+ {
1193
+ offset: 1,
1194
+ value: new Field(Fr.random())
1195
+ },
1196
+ {
1197
+ offset: 2,
1198
+ value: new Uint32(0n)
1199
+ }
1200
+ ],
1201
+ targetInstructions: ()=>[
1202
+ new SStore(/*indirect=*/ 0, /*srcOffset=*/ 0, /*slotOffset=*/ 1)
1203
+ ],
1204
+ cleanupInstructions: ()=>[
1205
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 2, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8)
1206
+ ]
1207
+ },
1208
+ {
1209
+ label: 'Unique slots (side-effect limited)',
1210
+ setup: [
1211
+ {
1212
+ offset: 0,
1213
+ value: new Field(Fr.random())
1214
+ },
1215
+ {
1216
+ offset: 1,
1217
+ value: new Field(Fr.random())
1218
+ },
1219
+ {
1220
+ offset: 2,
1221
+ value: new Field(1n)
1222
+ },
1223
+ {
1224
+ offset: 3,
1225
+ value: new Uint32(0n)
1226
+ }
1227
+ ],
1228
+ targetInstructions: ()=>[
1229
+ new SStore(/*indirect=*/ 0, /*srcOffset=*/ 0, /*slotOffset=*/ 1),
1230
+ new Add(/*indirect=*/ 0, /*aOffset=*/ 1, /*bOffset=*/ 2, /*dstOffset=*/ 1).as(Opcode.ADD_8, Add.wireFormat8)
1231
+ ],
1232
+ cleanupInstructions: ()=>[
1233
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 3, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8)
1234
+ ],
1235
+ limit: MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX
1236
+ }
1237
+ ],
1238
+ // EMITUNENCRYPTEDLOG - two configs: minimal (many small logs) and max-size (one large log)
1239
+ [Opcode.EMITUNENCRYPTEDLOG]: [
1240
+ {
1241
+ label: 'Many empty logs, revert, repeat',
1242
+ setup: [
1243
+ {
1244
+ offset: 0,
1245
+ value: new Uint32(0n)
1246
+ },
1247
+ {
1248
+ offset: 1,
1249
+ value: new Uint32(0n)
1250
+ }
1251
+ ],
1252
+ targetInstructions: ()=>[
1253
+ new EmitUnencryptedLog(/*indirect=*/ 0, /*logSizeOffset=*/ 0, /*logOffset=*/ 1)
1254
+ ],
1255
+ cleanupInstructions: ()=>[
1256
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 1, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8)
1257
+ ],
1258
+ // Max logs with 0-field content: floor(4096 / 2) = 2048
1259
+ limit: Math.floor(FLAT_PUBLIC_LOGS_PAYLOAD_LENGTH / PUBLIC_LOG_HEADER_LENGTH)
1260
+ },
1261
+ {
1262
+ label: 'One max size log, revert, repeat',
1263
+ setup: [
1264
+ // logSize = MAX_PUBLIC_LOG_SIZE_IN_FIELDS
1265
+ {
1266
+ offset: 0,
1267
+ value: new Uint32(BigInt(MAX_PUBLIC_LOG_SIZE_IN_FIELDS))
1268
+ },
1269
+ {
1270
+ offset: 1,
1271
+ value: new Uint32(0n)
1272
+ }
1273
+ ],
1274
+ targetInstructions: ()=>[
1275
+ new EmitUnencryptedLog(/*indirect=*/ 0, /*logSizeOffset=*/ 0, /*logOffset=*/ 2)
1276
+ ],
1277
+ cleanupInstructions: ()=>[
1278
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 1, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8)
1279
+ ],
1280
+ limit: 1
1281
+ }
1282
+ ],
1283
+ // ═══════════════════════════════════════════════════════════════════════════
1284
+ // GADGETS - Random inputs (seeded via SEED env var)
1285
+ // ═══════════════════════════════════════════════════════════════════════════
1286
+ [Opcode.POSEIDON2]: [
1287
+ {
1288
+ // Poseidon2 takes 4 field elements as input
1289
+ setup: Array.from({
1290
+ length: 4
1291
+ }, (_, i)=>({
1292
+ offset: i,
1293
+ value: new Field(Fr.random())
1294
+ })),
1295
+ // Poseidon hash data at M[0..3], write result to M[0:3] (reuse results as next inputs)
1296
+ targetInstructions: ()=>[
1297
+ new Poseidon2(/*indirect=*/ 0, /*inputStateOffset=*/ 0, /*outputStateOffset=*/ 0)
1298
+ ]
1299
+ }
1300
+ ],
1301
+ [Opcode.SHA256COMPRESSION]: [
1302
+ {
1303
+ setup: [
1304
+ // State: 8 x UINT32 at offsets 0-7 (random initial state)
1305
+ ...Array.from({
1306
+ length: 8
1307
+ }, (_, i)=>({
1308
+ offset: i,
1309
+ value: randomWithTag(TypeTag.UINT32)
1310
+ })),
1311
+ // Inputs: 16 x UINT32 at offsets 8-23 (random message block)
1312
+ ...Array.from({
1313
+ length: 16
1314
+ }, (_, i)=>({
1315
+ offset: 8 + i,
1316
+ value: randomWithTag(TypeTag.UINT32)
1317
+ }))
1318
+ ],
1319
+ targetInstructions: ()=>[
1320
+ new Sha256Compression(/*indirect=*/ 0, /*outputOffset=*/ 0, /*stateOffset=*/ 0, /*inputsOffset=*/ 8)
1321
+ ]
1322
+ }
1323
+ ],
1324
+ [Opcode.KECCAKF1600]: [
1325
+ {
1326
+ // Keccak state: 25 x UINT64 (5x5 lane array) with random values
1327
+ setup: Array.from({
1328
+ length: 25
1329
+ }, (_, i)=>({
1330
+ offset: i,
1331
+ value: randomWithTag(TypeTag.UINT64)
1332
+ })),
1333
+ targetInstructions: ()=>[
1334
+ new KeccakF1600(/*indirect=*/ 0, /*dstOffset=*/ 0, /*inputOffset=*/ 0)
1335
+ ]
1336
+ }
1337
+ ],
1338
+ [Opcode.ECADD]: [
1339
+ {
1340
+ // Use the Grumpkin generator point G for both points (valid curve point)
1341
+ setup: [
1342
+ {
1343
+ offset: 0,
1344
+ value: new Field(Grumpkin.generator.x)
1345
+ },
1346
+ {
1347
+ offset: 1,
1348
+ value: new Field(Grumpkin.generator.y)
1349
+ },
1350
+ {
1351
+ offset: 2,
1352
+ value: new Uint1(0n)
1353
+ },
1354
+ {
1355
+ offset: 3,
1356
+ value: new Field(Grumpkin.generator.x)
1357
+ },
1358
+ {
1359
+ offset: 4,
1360
+ value: new Field(Grumpkin.generator.y)
1361
+ },
1362
+ {
1363
+ offset: 5,
1364
+ value: new Uint1(0n)
1365
+ }
1366
+ ],
1367
+ targetInstructions: ()=>[
1368
+ new EcAdd(/*indirect=*/ 0, /*p1XOffset=*/ 0, /*p1YOffset=*/ 1, /*p1IsInfiniteOffset=*/ 2, /*p2XOffset=*/ 3, /*p2YOffset=*/ 4, /*p2IsInfiniteOffset=*/ 5, /*dstOffset=*/ 0)
1369
+ ]
1370
+ }
1371
+ ],
1372
+ // TORADIXBE has dynamic gas scaling with numLimbs
1373
+ [Opcode.TORADIXBE]: [
1374
+ {
1375
+ label: 'Min limbs',
1376
+ setup: [
1377
+ {
1378
+ offset: 0,
1379
+ value: new Field(1n)
1380
+ },
1381
+ {
1382
+ offset: 1,
1383
+ value: new Uint32(2n)
1384
+ },
1385
+ {
1386
+ offset: 2,
1387
+ value: new Uint32(1n)
1388
+ },
1389
+ {
1390
+ offset: 3,
1391
+ value: new Uint1(0n)
1392
+ }
1393
+ ],
1394
+ targetInstructions: ()=>[
1395
+ new ToRadixBE(/*indirect=*/ 0, /*srcOffset=*/ 0, /*radixOffset=*/ 1, /*numLimbsOffset=*/ 2, /*outputBitsOffset=*/ 3, /*dstOffset=*/ 4)
1396
+ ]
1397
+ },
1398
+ {
1399
+ label: 'Max limbs',
1400
+ setup: [
1401
+ {
1402
+ offset: 0,
1403
+ value: new Field(Fr.random())
1404
+ },
1405
+ {
1406
+ offset: 1,
1407
+ value: new Uint32(2n)
1408
+ },
1409
+ {
1410
+ offset: 2,
1411
+ value: new Uint32(256n)
1412
+ },
1413
+ {
1414
+ offset: 3,
1415
+ value: new Uint1(0n)
1416
+ }
1417
+ ],
1418
+ targetInstructions: ()=>[
1419
+ new ToRadixBE(/*indirect=*/ 0, /*srcOffset=*/ 0, /*radixOffset=*/ 1, /*numLimbsOffset=*/ 2, /*outputBitsOffset=*/ 3, /*dstOffset=*/ 4)
1420
+ ]
1421
+ },
1422
+ {
1423
+ label: 'Radix 3 (slow divmod path)',
1424
+ // Radix 3 bypasses the fast path for power-of-2 radixes (4, 8, 16, 32, 64, 128, 256)
1425
+ // and uses the slow divmod implementation instead
1426
+ setup: [
1427
+ {
1428
+ offset: 0,
1429
+ value: new Field(Fr.random())
1430
+ },
1431
+ {
1432
+ offset: 1,
1433
+ value: new Uint32(3n)
1434
+ },
1435
+ {
1436
+ offset: 2,
1437
+ value: new Uint32(161n)
1438
+ },
1439
+ {
1440
+ offset: 3,
1441
+ value: new Uint1(0n)
1442
+ }
1443
+ ],
1444
+ targetInstructions: ()=>[
1445
+ new ToRadixBE(/*indirect=*/ 0, /*srcOffset=*/ 0, /*radixOffset=*/ 1, /*numLimbsOffset=*/ 2, /*outputBitsOffset=*/ 3, /*dstOffset=*/ 4)
1446
+ ]
1447
+ }
1448
+ ],
1449
+ // ═══════════════════════════════════════════════════════════════════════════
1450
+ // MISC
1451
+ // ═══════════════════════════════════════════════════════════════════════════
1452
+ // DEBUGLOG only has base gas (no dynamic gas scaling) - memory reads only happen
1453
+ // when collectDebugLogs config is enabled
1454
+ [Opcode.DEBUGLOG]: [
1455
+ {
1456
+ setup: [
1457
+ {
1458
+ offset: 0,
1459
+ value: new Field(0n)
1460
+ },
1461
+ {
1462
+ offset: 1,
1463
+ value: new Field(0n)
1464
+ },
1465
+ {
1466
+ offset: 2,
1467
+ value: new Field(0n)
1468
+ },
1469
+ {
1470
+ offset: 3,
1471
+ value: new Uint32(0n)
1472
+ }
1473
+ ],
1474
+ // messageSize = 0
1475
+ targetInstructions: ()=>[
1476
+ new DebugLog(/*indirect=*/ 0, /*levelOffset=*/ 0, /*messageOffset=*/ 1, /*fieldsOffset=*/ 2, /*fieldsSizeOffset=*/ 3, /*messageSize=*/ 0)
1477
+ ]
1478
+ }
1479
+ ]
1480
+ };
1481
+ /**
1482
+ * Get all spam test cases grouped by opcode.
1483
+ * This is the main entry point for tests - it handles all the complexity of
1484
+ * type variants, multiple configs, etc.
1485
+ *
1486
+ * Returns hierarchical structure for nested describe blocks in tests.
1487
+ *
1488
+ * @param maxConfigsPerOpcode - Maximum number of configs to include per opcode.
1489
+ * Defaults to Infinity (no limit). Useful for quick
1490
+ * smoke tests where testing all type variants is too slow,
1491
+ * or for proving tests that are inherently slower.
1492
+ */ export function getSpamConfigsPerOpcode(maxConfigsPerOpcode = Infinity) {
1493
+ const groups = [];
1494
+ for (const [opcodeKey, configs] of Object.entries(SPAM_CONFIGS)){
1495
+ const opcode = Opcode[Number(opcodeKey)];
1496
+ if (!configs) {
1497
+ throw new Error(`Opcode ${opcode} listed in spam configs, but empty`);
1498
+ }
1499
+ // Apply the limit to the number of configs per opcode
1500
+ const limitedConfigs = configs.slice(0, maxConfigsPerOpcode);
1501
+ const cases = limitedConfigs.map((config)=>({
1502
+ ...config,
1503
+ // unlabeled configs just get opcode name
1504
+ label: config.label ? `${opcode}/${config.label}` : opcode
1505
+ }));
1506
+ groups.push({
1507
+ opcode: opcode,
1508
+ configs: cases
1509
+ });
1510
+ }
1511
+ return groups;
1512
+ }
1513
+ // ============================================================================
1514
+ // Helper Functions
1515
+ // ============================================================================
1516
+ /**
1517
+ * Create a SET instruction from a MemoryValue.
1518
+ * Chooses smallest SET variant based on offset and value magnitude for optimal bytecode density.
1519
+ */ function createSetInstruction(offset, memValue) {
1520
+ const tag = memValue.getTag();
1521
+ const value = memValue.toBigInt();
1522
+ // SET_8 only supports offset <= 255 and value <= 255
1523
+ if (offset <= 0xff && value <= 0xffn) {
1524
+ return new Set(0, offset, tag, Number(value)).as(Opcode.SET_8, Set.wireFormat8);
1525
+ }
1526
+ // SET_16+ support offset <= 65535
1527
+ if (value <= 0xffffn) {
1528
+ return new Set(0, offset, tag, Number(value)).as(Opcode.SET_16, Set.wireFormat16);
1529
+ }
1530
+ if (value <= 0xffffffffn) {
1531
+ return new Set(0, offset, tag, Number(value)).as(Opcode.SET_32, Set.wireFormat32);
1532
+ }
1533
+ if (value <= 0xffffffffffffffffn) {
1534
+ return new Set(0, offset, tag, value).as(Opcode.SET_64, Set.wireFormat64);
1535
+ }
1536
+ if (value <= 0xffffffffffffffffffffffffffffffffn) {
1537
+ return new Set(0, offset, tag, value).as(Opcode.SET_128, Set.wireFormat128);
1538
+ }
1539
+ return new Set(0, offset, tag, value).as(Opcode.SET_FF, Set.wireFormatFF);
1540
+ }
1541
+ /**
1542
+ * Append (to the instructions array) the SET instructions for the setup.
1543
+ *
1544
+ * @param instructions - the instructions array to append the setup to
1545
+ * @param setup - the setup configuration specifying what SETs to do
1546
+ */ function appendSetupInstructions(instructions, setup) {
1547
+ for (const item of setup){
1548
+ if (typeof item === 'function') {
1549
+ // item is a function that creates setup instructions (like)
1550
+ instructions.push(...item());
1551
+ } else {
1552
+ // MemSetup
1553
+ instructions.push(createSetInstruction(item.offset, item.value));
1554
+ }
1555
+ }
1556
+ }
1557
+ /**
1558
+ * Append (to the instructions array) the target instructions nTimes times.
1559
+ *
1560
+ * @param instructions - the instructions array to append the loop to
1561
+ * @param config - the spam config to use
1562
+ * @param nTimes - the number of times to append the target instructions
1563
+ * @returns the number of target instructions appended
1564
+ */ function appendTargetNTimes(instructions, config, nTimes) {
1565
+ for(let i = 0; i < nTimes; i++){
1566
+ instructions.push(...config.targetInstructions());
1567
+ }
1568
+ }
1569
+ /**
1570
+ * Append (to the instructions array) an infinite loop that maximizes target instruction density.
1571
+ * Fills remaining bytecode space with unrolled target instructions.
1572
+ *
1573
+ * @param instructions - the instructions array to append the loop to
1574
+ * @param config - the spam config to use
1575
+ * @returns the number of target instructions in the loop body
1576
+ */ function appendInfiniteLoop(instructions, config) {
1577
+ const setupBytecode = encodeToBytecode(instructions);
1578
+ const setupSize = setupBytecode.length;
1579
+ // Compute the size of the target instruction(s)
1580
+ const targetSize = encodeToBytecode(config.targetInstructions()).length;
1581
+ // Fill remaining space (loop body) with target instructions
1582
+ const availableForLoopBody = MAX_BYTECODE_BYTES - setupSize - JUMP_SIZE;
1583
+ const numTargetsInLoopBody = Math.floor(availableForLoopBody / targetSize);
1584
+ const loopStartPc = setupSize;
1585
+ appendTargetNTimes(instructions, config, numTargetsInLoopBody);
1586
+ instructions.push(new Jump(loopStartPc)); // JUMP_SIZE (JUMP_32)
1587
+ return numTargetsInLoopBody;
1588
+ }
1589
+ /**
1590
+ * Generate basic opcode spam bytecode from a SpamConfig.
1591
+ * Spams the target instruction(s) in an infinite loop until out-of-gas.
1592
+ */ export function createOpcodeSpamBytecode(config) {
1593
+ assert(config.limit === undefined, 'If config has `limit`, use createSideEffectLimitedSpamInRevertingNestedCall instead');
1594
+ const instructions = [];
1595
+ // 1. Setup memory
1596
+ appendSetupInstructions(instructions, config.setup);
1597
+ // 2. Infinite loop - maximize calls to target until out-of-gas
1598
+ appendInfiniteLoop(instructions, config);
1599
+ return encodeToBytecode(instructions);
1600
+ }
1601
+ /**
1602
+ * Generate a bytecode that spams a side-effect limited opcode #limit times
1603
+ * NOT in a loop, but inline/unrolled. Then revert.
1604
+ *
1605
+ * @param config - the side-effect limited spam config to use
1606
+ * @returns the bytecode for the side-effect limited spam
1607
+ */ export function createSideEffectSpamBytecode(config) {
1608
+ assert(config.limit !== undefined, 'If config has `limit`, use createSideEffectLimitedSpamInRevertingNestedCall instead');
1609
+ const instructions = [];
1610
+ // 1. Setup
1611
+ appendSetupInstructions(instructions, config.setup);
1612
+ // 2. Body - run target instruction(s) #limit times
1613
+ appendTargetNTimes(instructions, config, config.limit);
1614
+ // 3. Cleanup (revert)
1615
+ if (config.cleanupInstructions) {
1616
+ instructions.push(...config.cleanupInstructions());
1617
+ }
1618
+ return encodeToBytecode(instructions);
1619
+ }
1620
+ async function testStandardOpcodeSpam(tester, config, expectToBeTrue) {
1621
+ const bytecode = createOpcodeSpamBytecode(config);
1622
+ const contract = await deployCustomBytecode(bytecode, tester, config.label);
1623
+ await insertWarmTreeEntries(tester.merkleTrees, contract.address);
1624
+ // Should we pass the contract address as calldata?
1625
+ const calldata = config.addressAsCalldata ? [
1626
+ contract.address.toField()
1627
+ ] : [];
1628
+ const result = await executeCustomBytecode(contract, tester, config.label, calldata);
1629
+ // should have halted with out of gas
1630
+ expectToBeTrue(!result.revertCode.isOK());
1631
+ const revertReason = result.findRevertReason()?.message.toLowerCase();
1632
+ const allowedReasons = [
1633
+ 'out of gas',
1634
+ 'not enough l2gas'
1635
+ ];
1636
+ // expect the reason to match ONE of the allowed reasons
1637
+ expectToBeTrue(allowedReasons.some((allowedReason)=>revertReason?.includes(allowedReason)));
1638
+ return result;
1639
+ }
1640
+ async function testSideEffectOpcodeSpam(tester, config, expectToBeTrue) {
1641
+ // Inner contract will spam the side-effect limited opcode up to its limit, then REVERT
1642
+ const innerBytecode = createSideEffectSpamBytecode(config);
1643
+ // Outer contract will CALL to inner contract in a loop
1644
+ const outerBytecode = createOpcodeSpamBytecode(EXTERNAL_CALL_CONFIG);
1645
+ const innerContract = await deployCustomBytecode(innerBytecode, tester, `${config.label}_Inner`);
1646
+ const outerContract = await deployCustomBytecode(outerBytecode, tester, `${config.label}_Outer`);
1647
+ // Outer contract reads calldata[0] as inner contract address to CALL to
1648
+ const result = await executeCustomBytecode(outerContract, tester, config.label, [
1649
+ innerContract.address.toField()
1650
+ ]);
1651
+ // should have halted with out of gas or explicit REVERT (assertion failed)
1652
+ expectToBeTrue(!result.revertCode.isOK());
1653
+ const revertReason = result.findRevertReason()?.message.toLowerCase();
1654
+ const allowedReasons = [
1655
+ 'assertion failed',
1656
+ 'out of gas',
1657
+ 'not enough l2gas'
1658
+ ];
1659
+ // expect the reason to match ONE of the allowed reasons
1660
+ expectToBeTrue(allowedReasons.some((allowedReason)=>revertReason?.includes(allowedReason)));
1661
+ // Top-level should _always_ run out of gas for these tests
1662
+ // Check top-level halting message
1663
+ // WARNING: only the C++ simulator (or TsVsCpp) will have haltingMessage
1664
+ const allowedOuterReasons = [
1665
+ 'out of gas',
1666
+ 'not enough l2gas'
1667
+ ];
1668
+ if (result.callStackMetadata && result.callStackMetadata.length > 0) {
1669
+ const outerCallMetadata = result.callStackMetadata[0];
1670
+ const outerReason = outerCallMetadata.haltingMessage?.toLowerCase();
1671
+ // expect the reason to match ONE of the allowed reasons
1672
+ expectToBeTrue(allowedOuterReasons.some((allowedReason)=>outerReason?.includes(allowedReason)));
1673
+ }
1674
+ return result;
1675
+ }
1676
+ export async function testOpcodeSpamCase(tester, config, expectToBeTrue = ()=>{}) {
1677
+ if (config.limit) {
1678
+ return await testSideEffectOpcodeSpam(tester, config, expectToBeTrue);
1679
+ }
1680
+ return await testStandardOpcodeSpam(tester, config, expectToBeTrue);
1681
+ }