@aztec/simulator 3.0.0-nightly.20251214 → 3.0.0-nightly.20251217

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 (37) hide show
  1. package/dest/public/avm/avm_memory_types.d.ts +3 -1
  2. package/dest/public/avm/avm_memory_types.d.ts.map +1 -1
  3. package/dest/public/avm/avm_memory_types.js +2 -2
  4. package/dest/public/debug_fn_name.d.ts +1 -1
  5. package/dest/public/debug_fn_name.d.ts.map +1 -1
  6. package/dest/public/debug_fn_name.js +10 -3
  7. package/dest/public/fixtures/custom_bytecode_tester.d.ts +28 -6
  8. package/dest/public/fixtures/custom_bytecode_tester.d.ts.map +1 -1
  9. package/dest/public/fixtures/custom_bytecode_tester.js +36 -12
  10. package/dest/public/fixtures/custom_bytecode_tests.js +9 -9
  11. package/dest/public/fixtures/index.d.ts +3 -1
  12. package/dest/public/fixtures/index.d.ts.map +1 -1
  13. package/dest/public/fixtures/index.js +2 -0
  14. package/dest/public/fixtures/minimal_public_tx.js +2 -2
  15. package/dest/public/fixtures/opcode_spammer.d.ts +90 -0
  16. package/dest/public/fixtures/opcode_spammer.d.ts.map +1 -0
  17. package/dest/public/fixtures/opcode_spammer.js +1262 -0
  18. package/dest/public/fixtures/public_tx_simulation_tester.d.ts +2 -2
  19. package/dest/public/fixtures/public_tx_simulation_tester.d.ts.map +1 -1
  20. package/dest/public/fixtures/public_tx_simulation_tester.js +19 -7
  21. package/dest/public/public_tx_simulator/contract_provider_for_cpp.d.ts +1 -1
  22. package/dest/public/public_tx_simulator/contract_provider_for_cpp.d.ts.map +1 -1
  23. package/dest/public/public_tx_simulator/contract_provider_for_cpp.js +5 -1
  24. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.d.ts +1 -1
  25. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.d.ts.map +1 -1
  26. package/dest/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.js +2 -1
  27. package/package.json +16 -16
  28. package/src/public/avm/avm_memory_types.ts +2 -2
  29. package/src/public/debug_fn_name.ts +10 -3
  30. package/src/public/fixtures/custom_bytecode_tester.ts +53 -19
  31. package/src/public/fixtures/custom_bytecode_tests.ts +9 -9
  32. package/src/public/fixtures/index.ts +6 -0
  33. package/src/public/fixtures/minimal_public_tx.ts +2 -2
  34. package/src/public/fixtures/opcode_spammer.ts +1235 -0
  35. package/src/public/fixtures/public_tx_simulation_tester.ts +19 -5
  36. package/src/public/public_tx_simulator/contract_provider_for_cpp.ts +6 -1
  37. package/src/public/public_tx_simulator/cpp_vs_ts_public_tx_simulator.ts +2 -1
@@ -0,0 +1,1235 @@
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
+ */
151
+ import {
152
+ FLAT_PUBLIC_LOGS_PAYLOAD_LENGTH,
153
+ MAX_L2_TO_L1_MSGS_PER_TX,
154
+ MAX_NOTE_HASHES_PER_TX,
155
+ MAX_NULLIFIERS_PER_TX,
156
+ MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS,
157
+ MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
158
+ MAX_PUBLIC_LOG_SIZE_IN_FIELDS,
159
+ PUBLIC_LOG_HEADER_LENGTH,
160
+ } from '@aztec/constants';
161
+ import { Grumpkin } from '@aztec/foundation/crypto/grumpkin';
162
+ import { Fr } from '@aztec/foundation/curves/bn254';
163
+ import type { Bufferable } from '@aztec/foundation/serialize';
164
+ import type { CallStackMetadata, PublicTxResult } from '@aztec/stdlib/avm';
165
+
166
+ import assert from 'assert';
167
+
168
+ import {
169
+ Field,
170
+ INTEGRAL_TAGS,
171
+ type MemoryValue,
172
+ TaggedMemory,
173
+ TypeTag,
174
+ Uint1,
175
+ Uint32,
176
+ Uint64,
177
+ VALID_TAGS,
178
+ } from '../avm/avm_memory_types.js';
179
+ import {
180
+ Add,
181
+ And,
182
+ Call,
183
+ CalldataCopy,
184
+ Cast,
185
+ DebugLog,
186
+ Div,
187
+ EcAdd,
188
+ EmitNoteHash,
189
+ EmitNullifier,
190
+ EmitUnencryptedLog,
191
+ Eq,
192
+ FieldDiv,
193
+ GetContractInstance,
194
+ GetEnvVar,
195
+ Jump,
196
+ JumpI,
197
+ KeccakF1600,
198
+ L1ToL2MessageExists,
199
+ Lt,
200
+ Lte,
201
+ Mov,
202
+ Mul,
203
+ Not,
204
+ NoteHashExists,
205
+ NullifierExists,
206
+ Or,
207
+ Poseidon2,
208
+ ReturndataCopy,
209
+ ReturndataSize,
210
+ Revert,
211
+ SLoad,
212
+ SStore,
213
+ SendL2ToL1Message,
214
+ Set,
215
+ Sha256Compression,
216
+ Shl,
217
+ Shr,
218
+ Sub,
219
+ SuccessCopy,
220
+ ToRadixBE,
221
+ Xor,
222
+ } from '../avm/opcodes/index.js';
223
+ import { encodeToBytecode } from '../avm/serialization/bytecode_serialization.js';
224
+ import { Opcode } from '../avm/serialization/instruction_serialization.js';
225
+ import { deployCustomBytecode, executeCustomBytecode } from './custom_bytecode_tester.js';
226
+ import { deployAndExecuteCustomBytecode } from './index.js';
227
+ import type { PublicTxSimulationTester } from './public_tx_simulation_tester.js';
228
+
229
+ // ============================================================================
230
+ // Types
231
+ // ============================================================================
232
+
233
+ /**
234
+ * Memory cell to initialize before spamming.
235
+ */
236
+ interface MemSetup {
237
+ offset: number;
238
+ value: MemoryValue;
239
+ }
240
+
241
+ /**
242
+ * Some setup action to take before spamming.
243
+ * Either a memory cell to initialize, or some instruction generator.
244
+ */
245
+ type SetupItem = MemSetup | (() => Bufferable[]);
246
+
247
+ /**
248
+ * Everything needed to spam an opcode.
249
+ */
250
+ export interface SpamConfig {
251
+ /** Memory cells to initialize */
252
+ setup: SetupItem[];
253
+
254
+ /** Factory to create target instruction(s) to spam */
255
+ targetInstructions: () => Bufferable[];
256
+
257
+ /** Instructions to run after target spam (e.g., REVERT) */
258
+ cleanupInstructions?: () => Bufferable[];
259
+
260
+ /**
261
+ * Per-TX limit for the target opcode (for side-effect-limited opcodes)
262
+ * If set:
263
+ * 1. makes nested CALL
264
+ * 2. executes target opcode #limit times in a nested call
265
+ * 3. REVERT
266
+ * 4. CALL again to repeat
267
+ */
268
+ limit?: number;
269
+
270
+ /** Optional label for this config variant (e.g., UINT8 or MAXSIZE) */
271
+ label?: string;
272
+ }
273
+
274
+ /**
275
+ * An object containing opcode name and its SpamConfigs
276
+ * Useful when ready to iterate over all opcodes and test them.
277
+ */
278
+ export interface SpamConfigsForOpcode {
279
+ /** Opcode name (e.g., "ADD_8") */
280
+ opcode: string;
281
+
282
+ /** All spam configs for this opcode (one or more) */
283
+ configs: SpamConfig[];
284
+ }
285
+
286
+ // ============================================================================
287
+ // Constants
288
+ // ============================================================================
289
+
290
+ /**
291
+ * Maximum bytecode size in bytes.
292
+ *
293
+ * Bytecode is encoded as fields using bufferAsFields():
294
+ * - 1 field for the byte length
295
+ * - ceil(byteLength / 31) fields for the data (31 bytes per field)
296
+ *
297
+ * So: 1 + ceil(byteLength / 31) <= MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS
298
+ * ceil(byteLength / 31) <= MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS - 1
299
+ * byteLength <= (MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS - 1) * 31
300
+ */
301
+ const BYTES_PER_FIELD = Fr.SIZE_IN_BYTES - 1; // 31 bytes of data per field
302
+ const MAX_BYTECODE_BYTES = (MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS - 1) * BYTES_PER_FIELD;
303
+
304
+ const JUMP_SIZE = encodeToBytecode([new Jump(0)]).length; // JUMP_32
305
+
306
+ // ============================================================================
307
+ // Type Variant Helpers (for generating multiple configs per opcode)
308
+ // ============================================================================
309
+
310
+ const ALL_TAGS = Array.from(VALID_TAGS);
311
+ const INT_TAGS = Array.from(INTEGRAL_TAGS);
312
+
313
+ /** Build from tag truncating - shorter name */
314
+ function withTag(v: bigint, tag: TypeTag): MemoryValue {
315
+ return TaggedMemory.buildFromTagTruncating(v, tag);
316
+ }
317
+
318
+ // ============================================================================
319
+ // Configuration Map
320
+ // ============================================================================
321
+
322
+ /**
323
+ * Opcode spammer configs for ~all opcodes.
324
+ * Each opcode maps to an array of configs (usually one, but can be multiple for type variants, etc.)
325
+ * Uses smallest wire format (_8) for maximum instruction density.
326
+ */
327
+ export const SPAM_CONFIGS: Partial<Record<Opcode, SpamConfig[]>> = {
328
+ // ═══════════════════════════════════════════════════════════════════════════
329
+ // ARITHMETIC - Test with all type variants
330
+ // ═══════════════════════════════════════════════════════════════════════════
331
+ [Opcode.ADD_8]: ALL_TAGS.map(tag => ({
332
+ label: TypeTag[tag],
333
+ setup: [
334
+ { offset: 0, value: withTag(1n, tag) }, // accumulator
335
+ { offset: 1, value: withTag(1n, tag) }, // constant addend
336
+ ],
337
+ targetInstructions: () => [
338
+ new Add(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.ADD_8, Add.wireFormat8),
339
+ ],
340
+ })),
341
+
342
+ [Opcode.SUB_8]: ALL_TAGS.map(tag => ({
343
+ label: TypeTag[tag],
344
+ setup: [
345
+ { offset: 0, value: withTag(1000000n, tag) }, // start high
346
+ { offset: 1, value: withTag(1n, tag) }, // subtract 1
347
+ ],
348
+ targetInstructions: () => [
349
+ new Sub(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.SUB_8, Sub.wireFormat8),
350
+ ],
351
+ })),
352
+
353
+ [Opcode.MUL_8]: ALL_TAGS.map(tag => ({
354
+ label: TypeTag[tag],
355
+ setup: [
356
+ { offset: 0, value: withTag(2n, tag) }, // accumulator
357
+ { offset: 1, value: withTag(2n, tag) }, // multiply by 2
358
+ ],
359
+ targetInstructions: () => [
360
+ new Mul(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.MUL_8, Mul.wireFormat8),
361
+ ],
362
+ })),
363
+
364
+ // DIV doesn't support FIELD type
365
+ [Opcode.DIV_8]: INT_TAGS.map(tag => ({
366
+ label: TypeTag[tag],
367
+ setup: [
368
+ { offset: 0, value: withTag(111111111111111111n, tag) },
369
+ { offset: 1, value: withTag(1n, tag) }, // divide by 2 (identity)
370
+ ],
371
+ targetInstructions: () => [
372
+ new Div(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.DIV_8, Div.wireFormat8),
373
+ ],
374
+ })),
375
+
376
+ // Field-only
377
+ [Opcode.FDIV_8]: [
378
+ {
379
+ setup: [
380
+ { offset: 0, value: new Field(1000000n) },
381
+ { offset: 1, value: new Field(1n) }, // divide by 1 (identity)
382
+ ],
383
+ targetInstructions: () => [
384
+ new FieldDiv(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(
385
+ Opcode.FDIV_8,
386
+ FieldDiv.wireFormat8,
387
+ ),
388
+ ],
389
+ },
390
+ ],
391
+
392
+ // ═══════════════════════════════════════════════════════════════════════════
393
+ // COMPARATORS - Test with all type variants
394
+ // ═══════════════════════════════════════════════════════════════════════════
395
+ [Opcode.EQ_8]: ALL_TAGS.map(tag => ({
396
+ label: TypeTag[tag],
397
+ setup: [
398
+ { offset: 0, value: withTag(42n, tag) },
399
+ { offset: 1, value: withTag(42n, tag) },
400
+ ],
401
+ targetInstructions: () => [
402
+ new Eq(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 2).as(Opcode.EQ_8, Eq.wireFormat8),
403
+ ],
404
+ })),
405
+
406
+ [Opcode.LT_8]: ALL_TAGS.map(tag => ({
407
+ label: TypeTag[tag],
408
+ setup: [
409
+ { offset: 0, value: withTag(1n, tag) },
410
+ { offset: 1, value: withTag(1000000n, tag) },
411
+ ],
412
+ targetInstructions: () => [
413
+ new Lt(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 2).as(Opcode.LT_8, Lt.wireFormat8),
414
+ ],
415
+ })),
416
+
417
+ [Opcode.LTE_8]: ALL_TAGS.map(tag => ({
418
+ label: TypeTag[tag],
419
+ setup: [
420
+ { offset: 0, value: withTag(1n, tag) },
421
+ { offset: 1, value: withTag(1000000n, tag) },
422
+ ],
423
+ targetInstructions: () => [
424
+ new Lte(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 2).as(Opcode.LTE_8, Lte.wireFormat8),
425
+ ],
426
+ })),
427
+
428
+ // ═══════════════════════════════════════════════════════════════════════════
429
+ // BITWISE - Integer types only (no FIELD)
430
+ // ═══════════════════════════════════════════════════════════════════════════
431
+ [Opcode.AND_8]: INT_TAGS.map(tag => ({
432
+ label: TypeTag[tag],
433
+ setup: [
434
+ { offset: 0, value: withTag(0xffffffffffffffffffffffffffffffffn, tag) },
435
+ { offset: 1, value: withTag(0xffffffffffffffffffffffffffffffffn, tag) },
436
+ ],
437
+ targetInstructions: () => [
438
+ new And(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.AND_8, And.wireFormat8),
439
+ ],
440
+ })),
441
+
442
+ [Opcode.OR_8]: INT_TAGS.map(tag => ({
443
+ label: TypeTag[tag],
444
+ setup: [
445
+ { offset: 0, value: withTag(0xffffffffffffffffffffffffffffffffn, tag) },
446
+ { offset: 1, value: withTag(0n, tag) },
447
+ ],
448
+ targetInstructions: () => [
449
+ new Or(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.OR_8, Or.wireFormat8),
450
+ ],
451
+ })),
452
+
453
+ [Opcode.XOR_8]: INT_TAGS.map(tag => ({
454
+ label: TypeTag[tag],
455
+ setup: [
456
+ { offset: 0, value: withTag(0xdeadbeefcafebaben, tag) },
457
+ { offset: 1, value: withTag(0x1234567890abcdefn, tag) },
458
+ ],
459
+ targetInstructions: () => [
460
+ new Xor(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.XOR_8, Xor.wireFormat8),
461
+ ],
462
+ })),
463
+
464
+ [Opcode.NOT_8]: INT_TAGS.map(tag => ({
465
+ label: TypeTag[tag],
466
+ setup: [{ offset: 0, value: withTag(0xffffffffffffffffn, tag) }],
467
+ targetInstructions: () => [
468
+ new Not(/*indirect=*/ 0, /*srcOffset=*/ 0, /*dstOffset=*/ 0).as(Opcode.NOT_8, Not.wireFormat8),
469
+ ],
470
+ })),
471
+
472
+ [Opcode.SHL_8]: INT_TAGS.map(tag => ({
473
+ label: TypeTag[tag],
474
+ setup: [
475
+ { offset: 0, value: withTag(1n, tag) },
476
+ { offset: 1, value: withTag(1n, tag) },
477
+ ],
478
+ targetInstructions: () => [
479
+ new Shl(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.SHL_8, Shl.wireFormat8),
480
+ ],
481
+ })),
482
+
483
+ [Opcode.SHR_8]: INT_TAGS.map(tag => ({
484
+ label: TypeTag[tag],
485
+ setup: [
486
+ { offset: 0, value: withTag(0xffffffffffffffffn, tag) },
487
+ { offset: 1, value: withTag(1n, tag) },
488
+ ],
489
+ targetInstructions: () => [
490
+ new Shr(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.SHR_8, Shr.wireFormat8),
491
+ ],
492
+ })),
493
+
494
+ // ═══════════════════════════════════════════════════════════════════════════
495
+ // CAST / MOV - Test with all type variants
496
+ // ═══════════════════════════════════════════════════════════════════════════
497
+ [Opcode.CAST_8]: ALL_TAGS.map(tag => ({
498
+ label: TypeTag[tag],
499
+ setup: [{ offset: 0, value: withTag(42n, tag) }],
500
+ targetInstructions: () => [
501
+ new Cast(/*indirect=*/ 0, /*srcOffset=*/ 0, /*dstOffset=*/ 1, /*dstTag=*/ TypeTag.UINT32).as(
502
+ Opcode.CAST_8,
503
+ Cast.wireFormat8,
504
+ ),
505
+ ],
506
+ })),
507
+
508
+ [Opcode.MOV_8]: ALL_TAGS.map(tag => ({
509
+ label: TypeTag[tag],
510
+ setup: [{ offset: 0, value: withTag(42n, tag) }],
511
+ targetInstructions: () => [
512
+ new Mov(/*indirect=*/ 0, /*srcOffset=*/ 0, /*dstOffset=*/ 1).as(Opcode.MOV_8, Mov.wireFormat8),
513
+ ],
514
+ })),
515
+
516
+ // ═══════════════════════════════════════════════════════════════════════════
517
+ // MEMORY - SET
518
+ // ═══════════════════════════════════════════════════════════════════════════
519
+ // Not testing all wire formats as they should be roughly the same in terms of simulation
520
+ // and proving time
521
+ //[Opcode.SET_8]: [
522
+ // {
523
+ // setup: [],
524
+ // targetInstructions: () => [new Set(0, 0, TypeTag.UINT8, 42).as(Opcode.SET_8, Set.wireFormat8)],
525
+ // },
526
+ //],
527
+
528
+ //[Opcode.SET_16]: [
529
+ // {
530
+ // setup: [],
531
+ // targetInstructions: () => [new Set(0, 0, TypeTag.UINT16, 4242).as(Opcode.SET_16, Set.wireFormat16)],
532
+ // },
533
+ //],
534
+
535
+ //[Opcode.SET_32]: [
536
+ // {
537
+ // setup: [],
538
+ // targetInstructions: () => [new Set(0, 0, TypeTag.UINT32, 424242).as(Opcode.SET_32, Set.wireFormat32)],
539
+ // },
540
+ //],
541
+
542
+ //[Opcode.SET_64]: [
543
+ // {
544
+ // setup: [],
545
+ // targetInstructions: () => [new Set(0, 0, TypeTag.UINT64, 42424242n).as(Opcode.SET_64, Set.wireFormat64)],
546
+ // },
547
+ //],
548
+
549
+ [Opcode.SET_128]: [
550
+ {
551
+ setup: [],
552
+ targetInstructions: () => [
553
+ new Set(/*indirect=*/ 0, /*dstOffset=*/ 0, /*inTag=*/ TypeTag.UINT128, /*value=*/ 4242424242424242n).as(
554
+ Opcode.SET_128,
555
+ Set.wireFormat128,
556
+ ),
557
+ ],
558
+ },
559
+ ],
560
+
561
+ //[Opcode.SET_FF]: [
562
+ // {
563
+ // setup: [],
564
+ // targetInstructions: () => [new Set(0, 0, TypeTag.FIELD, 42n).as(Opcode.SET_FF, Set.wireFormatFF)],
565
+ // },
566
+ //],
567
+
568
+ // ═══════════════════════════════════════════════════════════════════════════
569
+ // CONTROL FLOW
570
+ // ═══════════════════════════════════════════════════════════════════════════
571
+ [Opcode.JUMP_32]: [
572
+ {
573
+ setup: [],
574
+ // Target will be overwritten by loop builder
575
+ targetInstructions: () => [new Jump(/*jumpOffset=*/ 0)],
576
+ },
577
+ ],
578
+
579
+ [Opcode.JUMPI_32]: [
580
+ {
581
+ setup: [{ offset: 0, value: new Uint1(0n) }], // Always false
582
+ targetInstructions: () => [new JumpI(/*indirect=*/ 0, /*condOffset=*/ 0, /*loc=*/ 0)],
583
+ },
584
+ ],
585
+
586
+ // ═══════════════════════════════════════════════════════════════════════════
587
+ // ENVIRONMENT
588
+ // ═══════════════════════════════════════════════════════════════════════════
589
+ [Opcode.GETENVVAR_16]: [
590
+ {
591
+ setup: [],
592
+ targetInstructions: () => [
593
+ new GetEnvVar(/*indirect=*/ 0, /*dstOffset=*/ 0, /*varEnum=*/ 0).as(
594
+ Opcode.GETENVVAR_16,
595
+ GetEnvVar.wireFormat16,
596
+ ),
597
+ ],
598
+ },
599
+ ],
600
+
601
+ [Opcode.CALLDATACOPY]: [
602
+ {
603
+ // CalldataCopy(indirect=0, copySizeOffset=0, cdStartOffset=1, dstOffset=2)
604
+ // Copies M[0]=1 elements starting from CD[M[1]]=CD[0] into M[2].
605
+ // In other words: M[2] = CD[0]
606
+ setup: [
607
+ { offset: 0, value: new Uint32(1n) }, // copySize = 1
608
+ { offset: 1, value: new Uint32(0n) }, // cdStart = 0 (start copying from calldata[0])
609
+ ],
610
+ targetInstructions: () => [
611
+ new CalldataCopy(/*indirect=*/ 0, /*copySizeOffset=*/ 0, /*cdStartOffset=*/ 1, /*dstOffset=*/ 2),
612
+ ],
613
+ },
614
+ ],
615
+
616
+ [Opcode.SUCCESSCOPY]: [
617
+ {
618
+ setup: [],
619
+ targetInstructions: () => [new SuccessCopy(/*indirect=*/ 0, /*dstOffset=*/ 0)],
620
+ },
621
+ ],
622
+
623
+ [Opcode.RETURNDATASIZE]: [
624
+ {
625
+ setup: [],
626
+ targetInstructions: () => [new ReturndataSize(/*indirect=*/ 0, /*dstOffset=*/ 0)],
627
+ },
628
+ ],
629
+
630
+ [Opcode.RETURNDATACOPY]: [
631
+ {
632
+ setup: [
633
+ { offset: 0, value: new Uint32(0n) }, // copySize = 0
634
+ { offset: 1, value: new Uint32(0n) }, // rdOffset
635
+ ],
636
+ targetInstructions: () => [
637
+ new ReturndataCopy(/*indirect=*/ 0, /*copySizeOffset=*/ 0, /*rdStartOffset=*/ 1, /*dstOffset=*/ 2),
638
+ ],
639
+ },
640
+ ],
641
+
642
+ // ═══════════════════════════════════════════════════════════════════════════
643
+ // WORLD STATE READS
644
+ // ═══════════════════════════════════════════════════════════════════════════
645
+ [Opcode.SLOAD]: [
646
+ {
647
+ setup: [{ offset: 0, value: new Field(0n) }], // slot
648
+ targetInstructions: () => [new SLoad(/*indirect=*/ 0, /*slotOffset=*/ 0, /*dstOffset=*/ 1)],
649
+ },
650
+ ],
651
+
652
+ [Opcode.NOTEHASHEXISTS]: [
653
+ {
654
+ setup: [
655
+ { offset: 0, value: new Field(0n) }, // noteHash
656
+ { offset: 1, value: new Uint64(0n) }, // leafIndex
657
+ ],
658
+ targetInstructions: () => [
659
+ new NoteHashExists(/*indirect=*/ 0, /*noteHashOffset=*/ 0, /*leafIndexOffset=*/ 1, /*existsOffset=*/ 2),
660
+ ],
661
+ },
662
+ ],
663
+
664
+ [Opcode.NULLIFIEREXISTS]: [
665
+ {
666
+ setup: [
667
+ { offset: 0, value: new Field(0n) }, // nullifier
668
+ { offset: 1, value: new Field(0n) }, // address
669
+ ],
670
+ targetInstructions: () => [
671
+ new NullifierExists(/*indirect=*/ 0, /*nullifierOffset=*/ 0, /*addressOffset=*/ 1, /*existsOffset=*/ 2),
672
+ ],
673
+ },
674
+ ],
675
+
676
+ [Opcode.L1TOL2MSGEXISTS]: [
677
+ {
678
+ setup: [
679
+ { offset: 0, value: new Field(0n) }, // msgHash
680
+ { offset: 1, value: new Uint64(0n) }, // msgLeafIndex
681
+ ],
682
+ targetInstructions: () => [
683
+ new L1ToL2MessageExists(/*indirect=*/ 0, /*msgHashOffset=*/ 0, /*msgLeafIndexOffset=*/ 1, /*existsOffset=*/ 2),
684
+ ],
685
+ },
686
+ ],
687
+
688
+ [Opcode.GETCONTRACTINSTANCE]: [
689
+ {
690
+ setup: [{ offset: 0, value: new Field(0n) }], // address
691
+ // memberEnum 0 = DEPLOYER
692
+ targetInstructions: () => [
693
+ new GetContractInstance(/*indirect=*/ 0, /*addressOffset=*/ 0, /*dstOffset=*/ 1, /*memberEnum=*/ 0),
694
+ ],
695
+ },
696
+ ],
697
+
698
+ // ═══════════════════════════════════════════════════════════════════════════
699
+ // SIDE-EFFECT LIMITED (have per-TX limit, use nested call pattern)
700
+ // ═══════════════════════════════════════════════════════════════════════════
701
+ [Opcode.EMITNOTEHASH]: [
702
+ {
703
+ setup: [
704
+ { offset: 0, value: new Field(0x1000n) },
705
+ { offset: 1, value: new Uint32(0n) }, // revertSize
706
+ ],
707
+ targetInstructions: () => [new EmitNoteHash(/*indirect=*/ 0, /*noteHashOffset=*/ 0)],
708
+ cleanupInstructions: () => [
709
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 1, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8),
710
+ ], // revert with empty
711
+ limit: MAX_NOTE_HASHES_PER_TX,
712
+ },
713
+ ],
714
+
715
+ [Opcode.EMITNULLIFIER]: [
716
+ {
717
+ // Nullifiers must be unique - increment value after each emit
718
+ // Memory layout: offset 0 = nullifier value, offset 1 = constant 1 for incrementing
719
+ setup: [
720
+ { offset: 0, value: new Field(0x2000n) }, // nullifier (will be incremented)
721
+ { offset: 1, value: new Field(1n) }, // constant 1 for ADD
722
+ { offset: 2, value: new Uint32(0n) }, // revertSize
723
+ ],
724
+ targetInstructions: () => [
725
+ new EmitNullifier(/*indirect=*/ 0, /*nullifierOffset=*/ 0),
726
+ new Add(/*indirect=*/ 0, /*aOffset=*/ 0, /*bOffset=*/ 1, /*dstOffset=*/ 0).as(Opcode.ADD_8, Add.wireFormat8), // nullifier++
727
+ ],
728
+ cleanupInstructions: () => [
729
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 2, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8),
730
+ ], // revert with empty
731
+ limit: MAX_NULLIFIERS_PER_TX - 1, // minus 1 because a TX will always have 1 "TX nullifier" from private
732
+ },
733
+ ],
734
+
735
+ [Opcode.SENDL2TOL1MSG]: [
736
+ {
737
+ setup: [
738
+ { offset: 0, value: new Field(1n) }, // recipient
739
+ { offset: 1, value: new Field(0x3000n) }, // content
740
+ { offset: 2, value: new Uint32(0n) }, // revertSize
741
+ ],
742
+ targetInstructions: () => [new SendL2ToL1Message(/*indirect=*/ 0, /*recipientOffset=*/ 0, /*contentOffset=*/ 1)],
743
+ cleanupInstructions: () => [
744
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 2, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8),
745
+ ], // revert with empty
746
+ limit: MAX_L2_TO_L1_MSGS_PER_TX,
747
+ },
748
+ ],
749
+
750
+ // SSTORE has two modes:
751
+ // 1. Same slot: Writing to the same slot repeatedly has no per-TX limit - it just overwrites.
752
+ // 2. Unique slots: Writing to unique slots is limited by MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX.
753
+ [Opcode.SSTORE]: [
754
+ {
755
+ label: 'Same slot (no limit)',
756
+ setup: [
757
+ { offset: 0, value: new Field(42n) }, // value
758
+ { offset: 1, value: new Field(0x100n) }, // slot (same slot each iteration)
759
+ { offset: 2, value: new Uint32(0n) }, // revertSize
760
+ ],
761
+ targetInstructions: () => [new SStore(/*indirect=*/ 0, /*srcOffset=*/ 0, /*slotOffset=*/ 1)],
762
+ cleanupInstructions: () => [
763
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 2, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8),
764
+ ], // revert with empty
765
+ },
766
+ {
767
+ label: 'Unique slots (side-effect limited)',
768
+ setup: [
769
+ { offset: 0, value: new Field(42n) }, // value (constant)
770
+ { offset: 1, value: new Field(0x100n) }, // slot (will be incremented)
771
+ { offset: 2, value: new Field(1n) }, // constant 1 for ADD
772
+ { offset: 3, value: new Uint32(0n) }, // revertSize
773
+ ],
774
+ targetInstructions: () => [
775
+ new SStore(/*indirect=*/ 0, /*srcOffset=*/ 0, /*slotOffset=*/ 1),
776
+ new Add(/*indirect=*/ 0, /*aOffset=*/ 1, /*bOffset=*/ 2, /*dstOffset=*/ 1).as(Opcode.ADD_8, Add.wireFormat8), // slot++
777
+ ],
778
+ cleanupInstructions: () => [
779
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 3, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8),
780
+ ], // revert with empty
781
+ limit: MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
782
+ },
783
+ ],
784
+
785
+ // EMITUNENCRYPTEDLOG - two configs: minimal (many small logs) and max-size (one large log)
786
+ [Opcode.EMITUNENCRYPTEDLOG]: [
787
+ {
788
+ label: 'Many empty logs, revert, repeat',
789
+ setup: [
790
+ { offset: 0, value: new Uint32(0n) }, // logSize = 0 fields (minimal)
791
+ { offset: 1, value: new Uint32(0n) }, // revertSize
792
+ ],
793
+ targetInstructions: () => [new EmitUnencryptedLog(/*indirect=*/ 0, /*logSizeOffset=*/ 0, /*logOffset=*/ 1)], // logOffset doesn't matter when size is 0
794
+ cleanupInstructions: () => [
795
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 1, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8),
796
+ ], // revert with empty
797
+ // Max logs with 0-field content: floor(4096 / 2) = 2048
798
+ limit: Math.floor(FLAT_PUBLIC_LOGS_PAYLOAD_LENGTH / PUBLIC_LOG_HEADER_LENGTH),
799
+ },
800
+ {
801
+ label: 'One max size log, revert, repeat',
802
+ setup: [
803
+ // logSize = MAX_PUBLIC_LOG_SIZE_IN_FIELDS
804
+ { offset: 0, value: new Uint32(BigInt(MAX_PUBLIC_LOG_SIZE_IN_FIELDS)) },
805
+ { offset: 1, value: new Uint32(0n) }, // revertSize
806
+ // NOTE: We don't initialize the log contents and just let it use default values (Field(0n))
807
+ // so that we save more gas and bytecode space for the Emit.
808
+ //// Initialize all log content fields to zero (FIELD type)
809
+ //...Array.from({ length: MAX_PUBLIC_LOG_SIZE_IN_FIELDS }, (_, i) => ({
810
+ // offset: 2 + i,
811
+ // value: new Field(0n),
812
+ //})),
813
+ ],
814
+ targetInstructions: () => [new EmitUnencryptedLog(/*indirect=*/ 0, /*logSizeOffset=*/ 0, /*logOffset=*/ 2)], // uses logOffset 2 (uninitialized Field(0))
815
+ cleanupInstructions: () => [
816
+ new Revert(/*indirect=*/ 0, /*retSizeOffset=*/ 1, /*returnOffset=*/ 0).as(Opcode.REVERT_8, Revert.wireFormat8),
817
+ ], // revert with empty
818
+ limit: 1, // Only 1 max-size log fits
819
+ },
820
+ ],
821
+
822
+ // ═══════════════════════════════════════════════════════════════════════════
823
+ // GADGETS - Use non-trivial inputs to avoid special-case optimizations
824
+ // ═══════════════════════════════════════════════════════════════════════════
825
+ [Opcode.POSEIDON2]: [
826
+ {
827
+ // Poseidon2 takes 4 field elements as input
828
+ setup: Array.from({ length: 4 }, (_, i) => ({
829
+ offset: i,
830
+ value: new Field(BigInt(0xdeadbeef + i * 0x1111)),
831
+ })),
832
+ // Poseidon hash data at M[0..3], write result to M[0:3] (reuse results as next inputs)
833
+ targetInstructions: () => [new Poseidon2(/*indirect=*/ 0, /*inputStateOffset=*/ 0, /*outputStateOffset=*/ 0)],
834
+ },
835
+ ],
836
+
837
+ [Opcode.SHA256COMPRESSION]: [
838
+ {
839
+ setup: [
840
+ // State: 8 x UINT32 at offsets 0-7 (use SHA256 initial hash values)
841
+ { offset: 0, value: new Uint32(0x6a09e667n) },
842
+ { offset: 1, value: new Uint32(0xbb67ae85n) },
843
+ { offset: 2, value: new Uint32(0x3c6ef372n) },
844
+ { offset: 3, value: new Uint32(0xa54ff53an) },
845
+ { offset: 4, value: new Uint32(0x510e527fn) },
846
+ { offset: 5, value: new Uint32(0x9b05688cn) },
847
+ { offset: 6, value: new Uint32(0x1f83d9abn) },
848
+ { offset: 7, value: new Uint32(0x5be0cd19n) },
849
+ // Inputs: 16 x UINT32 at offsets 8-23 (non-trivial message block)
850
+ ...Array.from({ length: 16 }, (_, i) => ({
851
+ offset: 8 + i,
852
+ value: new Uint32((0xcafebaben + BigInt(i) * 0x01010101n) & 0xffffffffn),
853
+ })),
854
+ ],
855
+ targetInstructions: () => [
856
+ new Sha256Compression(/*indirect=*/ 0, /*outputOffset=*/ 0, /*stateOffset=*/ 0, /*inputsOffset=*/ 8),
857
+ ],
858
+ },
859
+ ],
860
+
861
+ [Opcode.KECCAKF1600]: [
862
+ {
863
+ // Keccak state: 25 x UINT64 (5x5 lane array)
864
+ setup: Array.from({ length: 25 }, (_, i) => ({
865
+ offset: i,
866
+ value: new Uint64((0xdeadbeefcafebaben + BigInt(i) * 0x0101010101010101n) & 0xffffffffffffffffn),
867
+ })),
868
+ targetInstructions: () => [new KeccakF1600(/*indirect=*/ 0, /*dstOffset=*/ 0, /*inputOffset=*/ 0)],
869
+ },
870
+ ],
871
+
872
+ [Opcode.ECADD]: [
873
+ {
874
+ // Use the Grumpkin generator point G for both points (valid curve point)
875
+ setup: [
876
+ { offset: 0, value: new Field(Grumpkin.generator.x) }, // p1X = G.x
877
+ { offset: 1, value: new Field(Grumpkin.generator.y) }, // p1Y = G.y
878
+ { offset: 2, value: new Uint1(0n) }, // p1IsInfinite = false
879
+ { offset: 3, value: new Field(Grumpkin.generator.x) }, // p2X = G.x
880
+ { offset: 4, value: new Field(Grumpkin.generator.y) }, // p2Y = G.y
881
+ { offset: 5, value: new Uint1(0n) }, // p2IsInfinite = false
882
+ ],
883
+ targetInstructions: () => [
884
+ new EcAdd(
885
+ /*indirect=*/ 0,
886
+ /*p1XOffset=*/ 0,
887
+ /*p1YOffset=*/ 1,
888
+ /*p1IsInfiniteOffset=*/ 2,
889
+ /*p2XOffset=*/ 3,
890
+ /*p2YOffset=*/ 4,
891
+ /*p2IsInfiniteOffset=*/ 5,
892
+ /*dstOffset=*/ 0,
893
+ ),
894
+ ],
895
+ },
896
+ ],
897
+
898
+ [Opcode.TORADIXBE]: [
899
+ {
900
+ setup: [
901
+ { offset: 0, value: new Field(0xdeadbeefcafebaben) }, // non-trivial src value
902
+ { offset: 1, value: new Uint32(16n) }, // radix = 16 (hex)
903
+ { offset: 2, value: new Uint32(16n) }, // numLimbs = 16
904
+ { offset: 3, value: new Uint1(0n) }, // outputBits = false
905
+ ],
906
+ targetInstructions: () => [
907
+ new ToRadixBE(
908
+ /*indirect=*/ 0,
909
+ /*srcOffset=*/ 0,
910
+ /*radixOffset=*/ 1,
911
+ /*numLimbsOffset=*/ 2,
912
+ /*outputBitsOffset=*/ 3,
913
+ /*dstOffset=*/ 4,
914
+ ),
915
+ ],
916
+ },
917
+ ],
918
+
919
+ // ═══════════════════════════════════════════════════════════════════════════
920
+ // MISC
921
+ // ═══════════════════════════════════════════════════════════════════════════
922
+ [Opcode.DEBUGLOG]: [
923
+ {
924
+ setup: [
925
+ { offset: 0, value: new Field(0n) }, // level (0 = trace)
926
+ { offset: 1, value: new Field(0n) }, // message
927
+ { offset: 2, value: new Field(0n) }, // fields
928
+ { offset: 3, value: new Uint32(0n) }, // fieldsSize = 0
929
+ ],
930
+ // messageSize = 0
931
+ targetInstructions: () => [
932
+ new DebugLog(
933
+ /*indirect=*/ 0,
934
+ /*levelOffset=*/ 0,
935
+ /*messageOffset=*/ 1,
936
+ /*fieldsOffset=*/ 2,
937
+ /*fieldsSizeOffset=*/ 3,
938
+ /*messageSize=*/ 0,
939
+ ),
940
+ ],
941
+ },
942
+ ],
943
+ };
944
+
945
+ /**
946
+ * Get all spam test cases grouped by opcode.
947
+ * This is the main entry point for tests - it handles all the complexity of
948
+ * type variants, multiple configs, etc.
949
+ *
950
+ * Returns hierarchical structure for nested describe blocks in tests.
951
+ *
952
+ * @param maxConfigsPerOpcode - Maximum number of configs to include per opcode.
953
+ * Defaults to Infinity (no limit). Useful for quick
954
+ * smoke tests where testing all type variants is too slow,
955
+ * or for proving tests that are inherently slower.
956
+ */
957
+ export function getSpamConfigsPerOpcode(maxConfigsPerOpcode: number = Infinity): SpamConfigsForOpcode[] {
958
+ const groups: SpamConfigsForOpcode[] = [];
959
+
960
+ for (const [opcodeKey, configs] of Object.entries(SPAM_CONFIGS)) {
961
+ const opcode = Opcode[Number(opcodeKey) as Opcode];
962
+ if (!configs) {
963
+ throw new Error(`Opcode ${opcode} listed in spam configs, but empty`);
964
+ }
965
+
966
+ // Apply the limit to the number of configs per opcode
967
+ const limitedConfigs = configs.slice(0, maxConfigsPerOpcode);
968
+
969
+ const cases: SpamConfig[] = limitedConfigs.map(config => ({
970
+ ...config,
971
+ // unlabeled configs just get opcode name
972
+ label: config.label ? `${opcode}/${config.label}` : opcode,
973
+ }));
974
+
975
+ groups.push({ opcode: opcode, configs: cases });
976
+ }
977
+
978
+ return groups;
979
+ }
980
+
981
+ // ============================================================================
982
+ // Helper Functions
983
+ // ============================================================================
984
+
985
+ /**
986
+ * Create a SET instruction from a MemoryValue.
987
+ * Chooses smallest SET variant based on offset and value magnitude for optimal bytecode density.
988
+ */
989
+ function createSetInstruction(offset: number, memValue: MemoryValue): Bufferable {
990
+ const tag = memValue.getTag();
991
+ const value = memValue.toBigInt();
992
+
993
+ // SET_8 only supports offset <= 255 and value <= 255
994
+ if (offset <= 0xff && value <= 0xffn) {
995
+ return new Set(0, offset, tag, Number(value)).as(Opcode.SET_8, Set.wireFormat8);
996
+ }
997
+ // SET_16+ support offset <= 65535
998
+ if (value <= 0xffffn) {
999
+ return new Set(0, offset, tag, Number(value)).as(Opcode.SET_16, Set.wireFormat16);
1000
+ }
1001
+ if (value <= 0xffffffffn) {
1002
+ return new Set(0, offset, tag, Number(value)).as(Opcode.SET_32, Set.wireFormat32);
1003
+ }
1004
+ if (value <= 0xffffffffffffffffn) {
1005
+ return new Set(0, offset, tag, value).as(Opcode.SET_64, Set.wireFormat64);
1006
+ }
1007
+ if (value <= 0xffffffffffffffffffffffffffffffffn) {
1008
+ return new Set(0, offset, tag, value).as(Opcode.SET_128, Set.wireFormat128);
1009
+ }
1010
+ return new Set(0, offset, tag, value).as(Opcode.SET_FF, Set.wireFormatFF);
1011
+ }
1012
+
1013
+ /**
1014
+ * Append (to the instructions array) the SET instructions for the setup.
1015
+ *
1016
+ * @param instructions - the instructions array to append the setup to
1017
+ * @param setup - the setup configuration specifying what SETs to do
1018
+ */
1019
+ function appendSetupInstructions(instructions: Bufferable[], setup: SetupItem[]): void {
1020
+ for (const item of setup) {
1021
+ if (typeof item === 'function') {
1022
+ // item is a function that creates setup instructions (like)
1023
+ instructions.push(...item());
1024
+ } else {
1025
+ // MemSetup
1026
+ instructions.push(createSetInstruction(item.offset, item.value));
1027
+ }
1028
+ }
1029
+ }
1030
+
1031
+ /**
1032
+ * Append (to the instructions array) the target instructions nTimes times.
1033
+ *
1034
+ * @param instructions - the instructions array to append the loop to
1035
+ * @param config - the spam config to use
1036
+ * @param nTimes - the number of times to append the target instructions
1037
+ * @returns the number of target instructions appended
1038
+ */
1039
+ function appendTargetNTimes(instructions: Bufferable[], config: SpamConfig, nTimes: number) {
1040
+ for (let i = 0; i < nTimes; i++) {
1041
+ instructions.push(...config.targetInstructions());
1042
+ }
1043
+ }
1044
+
1045
+ /**
1046
+ * Append (to the instructions array) an infinite loop that maximizes target instruction density.
1047
+ * Fills remaining bytecode space with unrolled target instructions.
1048
+ *
1049
+ * @param instructions - the instructions array to append the loop to
1050
+ * @param config - the spam config to use
1051
+ * @returns the number of target instructions in the loop body
1052
+ */
1053
+ function appendInfiniteLoop(instructions: Bufferable[], config: SpamConfig): number {
1054
+ const setupBytecode = encodeToBytecode(instructions);
1055
+ const setupSize = setupBytecode.length;
1056
+
1057
+ // Compute the size of the target instruction(s)
1058
+ const targetSize = encodeToBytecode(config.targetInstructions()).length;
1059
+
1060
+ // Fill remaining space (loop body) with target instructions
1061
+ const availableForLoopBody = MAX_BYTECODE_BYTES - setupSize - JUMP_SIZE;
1062
+ const numTargetsInLoopBody = Math.floor(availableForLoopBody / targetSize);
1063
+
1064
+ const loopStartPc = setupSize;
1065
+ appendTargetNTimes(instructions, config, numTargetsInLoopBody);
1066
+ instructions.push(new Jump(loopStartPc)); // JUMP_SIZE (JUMP_32)
1067
+
1068
+ return numTargetsInLoopBody;
1069
+ }
1070
+
1071
+ /**
1072
+ * Generate basic opcode spam bytecode from a SpamConfig.
1073
+ * Spams the target instruction(s) in an infinite loop until out-of-gas.
1074
+ */
1075
+ export function createOpcodeSpamBytecode(config: SpamConfig): Buffer {
1076
+ assert(
1077
+ config.limit === undefined,
1078
+ 'If config has `limit`, use createSideEffectLimitedSpamInRevertingNestedCall instead',
1079
+ );
1080
+
1081
+ const instructions: Bufferable[] = [];
1082
+
1083
+ // 1. Setup memory
1084
+ appendSetupInstructions(instructions, config.setup);
1085
+
1086
+ // 2. Infinite loop - maximize iterations until out-of-gas
1087
+ appendInfiniteLoop(instructions, config);
1088
+
1089
+ return encodeToBytecode(instructions);
1090
+ }
1091
+
1092
+ /**
1093
+ * Generate a bytecode that spams a side-effect limited opcode #limit times
1094
+ * NOT in a loop, but inline/unrolled. Then revert.
1095
+ *
1096
+ * @param config - the side-effect limited spam config to use
1097
+ * @returns the bytecode for the side-effect limited spam
1098
+ */
1099
+ export function createSideEffectSpamBytecode(config: SpamConfig): Buffer {
1100
+ assert(
1101
+ config.limit !== undefined,
1102
+ 'If config has `limit`, use createSideEffectLimitedSpamInRevertingNestedCall instead',
1103
+ );
1104
+ const instructions: Bufferable[] = [];
1105
+
1106
+ // 1. Setup
1107
+ appendSetupInstructions(instructions, config.setup);
1108
+
1109
+ // 2. Body - run target instruction(s) #limit times
1110
+ appendTargetNTimes(instructions, config, config.limit);
1111
+
1112
+ // 3. Cleanup (revert)
1113
+ if (config.cleanupInstructions) {
1114
+ instructions.push(...config.cleanupInstructions());
1115
+ }
1116
+
1117
+ return encodeToBytecode(instructions);
1118
+ }
1119
+
1120
+ /** Reserved memory offsets for outer call loop */
1121
+ const CONST_1_OFFSET = 0;
1122
+ const CALL_L2_GAS_OFFSET = 1;
1123
+ const CALL_DA_GAS_OFFSET = 2;
1124
+ const CALL_ADDR_OFFSET = 3;
1125
+ const CALL_ARGS_SIZE = 4;
1126
+ const CALL_ARGS_OFFSET = 5;
1127
+ const CALLDATA_INDEX_OFFSET = 6; // calldata index as in calldata[index]
1128
+
1129
+ /**
1130
+ * A SpamConfig for an external call loop.
1131
+ */
1132
+ const EXTERNAL_CALL_LOOP_CONFIG: SpamConfig = {
1133
+ setup: [
1134
+ // calldata will contain 1 item: the external call address
1135
+ { offset: CONST_1_OFFSET, value: new Uint32(1) }, // calldata size = 1
1136
+ { offset: CALLDATA_INDEX_OFFSET, value: new Uint32(0) }, // we want calldata[0]
1137
+ { offset: CALL_L2_GAS_OFFSET, value: new Uint32(0xffffffffn) }, // l2Gas = max uint32
1138
+ { offset: CALL_DA_GAS_OFFSET, value: new Uint32(0xffffffffn) }, // daGas = max uint32
1139
+ () => [
1140
+ new CalldataCopy(
1141
+ /*indirect=*/ 0,
1142
+ /*copySizeOffset=*/ CONST_1_OFFSET,
1143
+ /*cdStartOffset=*/ CALLDATA_INDEX_OFFSET,
1144
+ /*dstOffset=*/ CALL_ADDR_OFFSET,
1145
+ ),
1146
+ ], // address = calldata[0] of parent call
1147
+ { offset: CALL_ARGS_SIZE, value: new Uint32(0) }, // argsSize = max uint32
1148
+ { offset: CALL_ARGS_SIZE, value: new Uint32(0) }, // argsSize = max uint32
1149
+ ],
1150
+ targetInstructions: () => [
1151
+ new Call(
1152
+ /*indirect=*/ 0,
1153
+ /*l2GasOffset=*/ CALL_L2_GAS_OFFSET,
1154
+ /*daGasOffset=*/ CALL_DA_GAS_OFFSET,
1155
+ /*addrOffset=*/ CALL_ADDR_OFFSET,
1156
+ /*argsSizeOffset=*/ CALL_ARGS_SIZE,
1157
+ /*argsOffset=*/ CALL_ARGS_OFFSET,
1158
+ ),
1159
+ ],
1160
+ };
1161
+
1162
+ /**
1163
+ * Create bytecode that makes an external call in a loop.
1164
+ *
1165
+ * @returns the bytecode for the external call loop
1166
+ */
1167
+ export function createExternalCallLoopBytecode(): Buffer {
1168
+ const config = EXTERNAL_CALL_LOOP_CONFIG;
1169
+ const instructions: Bufferable[] = [];
1170
+
1171
+ // 1. Setup memory
1172
+ appendSetupInstructions(instructions, config.setup);
1173
+ // 2. Infinite loop of external calls - maximize iterations until out-of-gas
1174
+ appendInfiniteLoop(instructions, config);
1175
+ return encodeToBytecode(instructions);
1176
+ }
1177
+
1178
+ async function testStandardOpcodeSpam(
1179
+ tester: PublicTxSimulationTester,
1180
+ config: SpamConfig,
1181
+ expectToBeTrue: (x: boolean) => void,
1182
+ ): Promise<PublicTxResult> {
1183
+ const bytecode = createOpcodeSpamBytecode(config);
1184
+ const result = await deployAndExecuteCustomBytecode(bytecode, tester, config.label);
1185
+
1186
+ // should have halted with out of gas
1187
+ expectToBeTrue(!result.revertCode.isOK());
1188
+ const revertReason = result.findRevertReason()?.message.toLowerCase();
1189
+ const allowedReasons = ['out of gas', 'not enough l2gas'];
1190
+ // expect the reason to match ONE of the allowed reasons
1191
+ expectToBeTrue(allowedReasons.some(allowedReason => revertReason!.includes(allowedReason)));
1192
+ return result;
1193
+ }
1194
+
1195
+ async function testSideEffectOpcodeSpam(
1196
+ tester: PublicTxSimulationTester,
1197
+ config: SpamConfig,
1198
+ expectToBeTrue: (x: boolean) => void,
1199
+ ): Promise<PublicTxResult> {
1200
+ const innerBytecode = createSideEffectSpamBytecode(config);
1201
+ const outerBytecode = createExternalCallLoopBytecode();
1202
+ const innerContract = await deployCustomBytecode(innerBytecode, tester, `${config.label}_Inner`);
1203
+ const outerContract = await deployCustomBytecode(outerBytecode, tester, `${config.label}_Outer`);
1204
+ // Outer contract reads calldata[0] as inner contract address to CALL to
1205
+ const result = await executeCustomBytecode(outerContract, tester, config.label, [innerContract.address.toField()]);
1206
+
1207
+ // should have halted with out of gas or explicit REVERT (assertion failed)
1208
+ expectToBeTrue(!result.revertCode.isOK());
1209
+ const revertReason = result.findRevertReason()?.message.toLowerCase();
1210
+ const allowedReasons = ['assertion failed', 'out of gas', 'not enough l2gas'];
1211
+ // expect the reason to match ONE of the allowed reasons
1212
+ expectToBeTrue(allowedReasons.some(allowedReason => revertReason!.includes(allowedReason)));
1213
+
1214
+ // Top-level should _always_ run out of gas for these tests
1215
+ // Check top-level halting message
1216
+ // WARNING: only the C++ simulator (or TsVsCpp) will have haltingMessage
1217
+ const allowedOuterReasons = ['out of gas', 'not enough l2gas'];
1218
+ const outerCallMetadata = result.callStackMetadata[0] as CallStackMetadata;
1219
+ const outerReason = outerCallMetadata.haltingMessage?.toLowerCase();
1220
+ // expect the reason to match ONE of the allowed reasons
1221
+ expectToBeTrue(allowedOuterReasons.some(allowedReason => outerReason!.includes(allowedReason)));
1222
+
1223
+ return result;
1224
+ }
1225
+
1226
+ export async function testOpcodeSpamCase(
1227
+ tester: PublicTxSimulationTester,
1228
+ config: SpamConfig,
1229
+ expectToBeTrue: (x: boolean) => void = () => {}, // default no-op
1230
+ ): Promise<PublicTxResult> {
1231
+ if (config.limit) {
1232
+ return await testSideEffectOpcodeSpam(tester, config, expectToBeTrue);
1233
+ }
1234
+ return await testStandardOpcodeSpam(tester, config, expectToBeTrue);
1235
+ }