Are you an LLM? Read llms.txt for a summary of the docs, or llms-full.txt for the full context.
Skip to content

Cookbook: Building a browser trace viewer

Because Tevm's native ZEVM engine runs in Node.js, browser tools connect over HTTP or WebSocket to @tevm/server. This cookbook wires a tiny Node.js RPC server to a browser frontend that deploys sample bytecode, calls debug_traceCall, and renders each opcode step.

Serving One Native Engine Over Multiple Transports
Browser dApp (viem)http() / webSocket()Remote Node / CLIcreateHttpClient()Local Process / Foundry/tmp/tevm.sockExpress / Next.js Routemiddleware / handlercreateServer(client)HTTP POST · batches · notificationsWebSocket · eth_subscribenewHeads · logs · pendingTxscreateIpcServer(client)newline-delimited JSON streamcreateHttpHandler(client)Express & Next.js adaptersShared ClientZevmEngineOne chain stateNative filtersSerialized queue
Browser apps and external tools connect to @tevm/server over HTTP or WebSocket; local processes can also connect over Unix IPC.

1. Start a CORS-enabled local Tevm server

Save as server.mjs and run node server.mjs:

import { createMemoryClient } from 'tevm'
import { createServer } from 'tevm/server'
 
const client = createMemoryClient()
await client.tevmReady()
 
// Pre-load sample bytecode: PUSH1 0x2a; PUSH1 0x00; MSTORE; PUSH1 0x20; PUSH1 0x00; RETURN
const target = '0x0000000000000000000000000000000000000123'
await client.tevmSetAccount({
  address: target,
  deployedBytecode: '0x602a60005260206000f3',
})
 
const server = createServer(client, {}, { cors: true })
server.listen(8545, '127.0.0.1', () => {
  console.log('TEVM trace server listening on http://127.0.0.1:8545')
})
 
process.once('SIGINT', () => {
  server.close(() => {
    void client.tevmClose()
  })
})

2. Query debug_traceCall from the browser

Native Opcode Tracing with debug_traceCall
debug_traceCallcall object + blockTagenableMemory: trueenableReturnData: truedisableStack / StorageGuillotine Mini TracerSnapshots before each opcode:pc · op · gas · gasCost · depthstack[] · memory[] · returnDataCap: 100,000 stepsTrace Payloadgas: 21018failed: falsereturnValue: "0x...2a"truncated: falsestructLogs: [...]
Guillotine Mini records pre-opcode stack, memory, gas, and returnData inside native code and returns a bounded structLogs array.

Any browser framework (React, Svelte, Vue, or vanilla TypeScript) can call debug_traceCall directly over fetch or viem's http() transport:

type StructLog = {
  pc: number
  op: string
  gas: number
  gasCost: number
  depth: number
  stack: string[]
  memory?: string[]
  returnData?: string
}
 
type TraceResult = {
  gas: number
  failed: boolean
  returnValue: string
  truncated: boolean
  structLogs: StructLog[]
}
 
export async function traceCall(
  rpcUrl: string,
  to: `0x${string}`,
  data: `0x${string}` = '0x',
): Promise<TraceResult> {
  const response = await fetch(rpcUrl, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({
      jsonrpc: '2.0',
      id: 1,
      method: 'debug_traceCall',
      params: [
        { to, data },
        'latest',
        { enableMemory: true, enableReturnData: true },
      ],
    }),
  })
 
  const payload = (await response.json()) as {
    result?: TraceResult
    error?: { code: number; message: string }
  }
  if (payload.error) throw new Error(`${payload.error.code}: ${payload.error.message}`)
  return payload.result!
}

3. Render the step table

In your UI component (Svelte, React, or vanilla DOM):

<script lang="ts">
  import { traceCall, type TraceResult } from './trace'
 
  let trace: TraceResult | null = null
  let error = ''
  let loading = false
 
  async function runTrace() {
    loading = true
    error = ''
    try {
      trace = await traceCall(
        'http://127.0.0.1:8545',
        '0x0000000000000000000000000000000000000123',
      )
    } catch (cause) {
      error = cause instanceof Error ? cause.message : String(cause)
    } finally {
      loading = false
    }
  }
</script>
 
<main>
  <h1>Tevm Trace Viewer</h1>
  <button onclick={runTrace} disabled={loading}>
    {loading ? 'Tracing…' : 'Trace call'}
  </button>
 
  {#if error}<pre>{error}</pre>{/if}
 
  {#if trace}
    <p>
      Gas: {trace.gas} · Failed: {String(trace.failed)} · Return: <code>{trace.returnValue}</code>
      {#if trace.truncated} (truncated at 100,000 steps){/if}
    </p>
 
    <table>
      <thead>
        <tr><th>PC</th><th>Opcode</th><th>Gas</th><th>Cost</th><th>Stack (top last)</th></tr>
      </thead>
      <tbody>
        {#each trace.structLogs as step}
          <tr>
            <td>{step.pc}</td>
            <td>{step.op}</td>
            <td>{step.gas}</td>
            <td>{step.gasCost}</td>
            <td>{step.stack.join(', ') || '—'}</td>
          </tr>
        {/each}
      </tbody>
    </table>
  {/if}
</main>

Extending the viewer

  • Live block feed: open a WebSocket to ws://127.0.0.1:8545 and subscribe to newHeads (eth_subscribe) to refresh your UI whenever blocks are mined.
  • Revert inspection: debug_traceCall returns failed: true and the raw revert bytes in returnValue instead of throwing, so you can highlight the exact REVERT step and decode custom errors with viem's decodeErrorResult.
  • Step budget: check trace.truncated before assuming the trace ran to completion (the native cap is 100,000 steps).

Next: Tracing & engine events · HTTP, WebSocket & IPC server