Skip to main content

Try it Live

Run Opcode examples in the interactive playground

Opcode.pushBytes()

Get number of immediate bytes for PUSH opcode.
import { pushBytes, PUSH1, PUSH32 } from 'tevm/Opcode'

pushBytes(PUSH1)   // 1
pushBytes(PUSH32)  // 32

Parameters

  • opcode: BrandedOpcode - Opcode to check

Returns

number | undefined - Byte count (0-32) or undefined if not PUSH

PUSH Byte Counts

PUSH0:  0 bytes  (0x5F)
PUSH1:  1 byte   (0x60)
PUSH2:  2 bytes  (0x61)
PUSH3:  3 bytes  (0x62)
...
PUSH31: 31 bytes (0x7E)
PUSH32: 32 bytes (0x7F)

Use Cases

Skip PUSH Data During Parsing

function parseBytecode(bytecode: Uint8Array): void {
  let i = 0
  while (i < bytecode.length) {
    const opcode = bytecode[i]
    console.log(`Offset ${i}: ${Opcode.name(opcode)}`)

    const pushSize = Opcode.pushBytes(opcode)
    if (pushSize !== undefined) {
      i += pushSize  // Skip immediate data
    }
    i++  // Next opcode
  }
}

Validate PUSH Data

function validatePushData(inst: Instruction): boolean {
  const expected = Opcode.pushBytes(inst.opcode)
  if (expected === undefined) return true  // Not a PUSH

  if (expected === 0) {
    return inst.immediate === undefined  // PUSH0 has no data
  }

  return inst.immediate?.length === expected
}