# Tracers

The tracers a `Debug.trace*` call can run. The options of the call select the tracer, and with
it the type of the result.

```ts
import { Debug } from "@ethect/core/rpc";
import type { Hash } from "@ethect/core";

const traces = (hash: Hash.Hash) => ({
  // no `tracer` key, the struct logger: Effect<StructLog.Trace, …>
  opcodes: Debug.traceTransaction(hash),
  // a `tracer` key changes the tracer and the type: Effect<CallFrame.CallFrame, …>
  calls: Debug.traceTransaction(hash, { tracer: "callTracer" }),
});
```

The same options go to [`Debug.traceTransaction`](https://ethect.dev/rpc/debug/trace-transaction/),
[`Debug.traceCall`](https://ethect.dev/rpc/debug/trace-call/) and the three methods that
[trace a block](https://ethect.dev/rpc/debug/trace-block/).

## How the options select a tracer

| Options | Tracer | Result type |
| --- | --- | --- |
| no `tracer` key | [struct logger](#struct-logger) | [`StructLog.Trace`](https://ethect.dev/rpc/types/struct-log/) |
| `tracer: "callTracer"` | [`callTracer`](#calltracer) | [`CallFrame.CallFrame`](https://ethect.dev/rpc/types/call-frame/) |
| `tracer: "prestateTracer"` | [`prestateTracer`](#prestatetracer) | [`Prestate.Prestate`](https://ethect.dev/rpc/types/prestate/) |
| `tracer: "prestateTracer"`, `tracerConfig: { diffMode: true }` | [`prestateTracer`, diff mode](#diff-mode) | [`Prestate.Diff`](https://ethect.dev/rpc/types/prestate/) |
| `tracer: "4byteTracer"` | [`4byteTracer`](#4bytetracer) | [`Trace.FourByte`](https://ethect.dev/rpc/types/trace/) |
| `tracer: "noopTracer"` | [`noopTracer`](#nooptracer) | an empty object |
| `tracer:` any other string | [custom tracer](#custom-tracers) | `unknown` |

- **A name the library knows gives a typed result.** The answer of the node is decoded with
  the schema of that tracer.
- **Any other name, or a JavaScript tracer, gives `unknown`.** The library cannot know what the
  tracer returns, so the answer is handed over as the node sent it.

Every tracer also takes two fields at the top level of the options:

| Field | Type | Description |
| --- | --- | --- |
| `timeout` | `string` (optional) | how long the trace may take, as a Go duration such as `"10s"` |
| `reexec` | `number` (optional) | how many blocks the node may run again to rebuild a state it no longer has |

The answers shown below are what anvil 1.9 sent for one transaction: a call to a contract that
stores the 32-byte word it is given, emits one log with it and returns it.

## Struct logger

The tracer that runs when the options name none. It logs every opcode executed.

- **Selected by:** options without a `tracer` key, or no options at all.
- **Config:** the fields of [`StructLog.Config`](https://ethect.dev/rpc/types/struct-log/), at the top level
  of the options: `enableMemory`, `disableStack`, `disableStorage`, `enableReturnData`,
  `debug`, `limit`.
- **Result:** [`StructLog.Trace`](https://ethect.dev/rpc/types/struct-log/).

```ts
import { Debug } from "@ethect/core/rpc";
import type { Hash } from "@ethect/core";

// Effect<StructLog.Trace, …>
const firstSteps = (hash: Hash.Hash) => Debug.traceTransaction(hash, { limit: 2 });
```

```json
{
  "failed": false,
  "gas": 44293,
  "returnValue": "0x0000000000000000000000000000000000000000000000000000000000000007",
  "structLogs": [
    {
      "pc": 0,
      "op": "CALLDATASIZE",
      "gas": 23153,
      "gasCost": 2,
      "depth": 1,
      "stack": [],
      "refund": 0
    },
    {
      "pc": 1,
      "op": "PUSH1",
      "gas": 23151,
      "gasCost": 3,
      "depth": 1,
      "stack": [
        "0x20"
      ],
      "refund": 0
    }
  ]
}
```

The stack values are decoded to `bigint`: `"0x20"` is read as `32n`. For a mined transaction,
anvil only has the logs when it is started with `anvil --steps-tracing`.

## callTracer

Returns the execution as the tree of the calls it made.

- **Selected by:** `tracer: "callTracer"`.
- **Config:** `tracerConfig` (optional), a [`CallFrame.Config`](https://ethect.dev/rpc/types/call-frame/):
  `onlyTopCall` leaves out the calls the top one made, `withLog` adds the logs each call
  emitted.
- **Result:** [`CallFrame.CallFrame`](https://ethect.dev/rpc/types/call-frame/).

```ts
import { Debug } from "@ethect/core/rpc";
import type { Hash } from "@ethect/core";

// Effect<CallFrame.CallFrame, …>
const calls = (hash: Hash.Hash) =>
  Debug.traceTransaction(hash, {
    tracer: "callTracer",
    tracerConfig: { withLog: true },
  });
```

```json
{
  "from": "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266",
  "gas": "0x5a71",
  "gasUsed": "0xad05",
  "to": "0x5fbdb2315678afecb367f032d93f642f64180aa3",
  "input": "0x0000000000000000000000000000000000000000000000000000000000000007",
  "output": "0x0000000000000000000000000000000000000000000000000000000000000007",
  "logs": [
    {
      "address": "0x5fbdb2315678afecb367f032d93f642f64180aa3",
      "topics": [
        "0xabababababababababababababababababababababababababababababababab"
      ],
      "data": "0x0000000000000000000000000000000000000000000000000000000000000007",
      "position": "0x0",
      "index": "0x0"
    }
  ],
  "value": "0x0",
  "type": "CALL"
}
```

The quantities are decoded: `gasUsed` is `44293n`, `value` is `0n`, and the `position` and
`index` of a log are `0`. This contract calls no other, so the frame has no `calls`.

## prestateTracer

Returns the accounts the execution touched, as they were before it.

- **Selected by:** `tracer: "prestateTracer"`.
- **Config:** `tracerConfig` (optional), a [`Prestate.Config`](https://ethect.dev/rpc/types/prestate/):
  `disableCode` and `disableStorage` leave the code and the storage out of every account.
- **Result:** [`Prestate.Prestate`](https://ethect.dev/rpc/types/prestate/), a record of addresses to
  account states.

```ts
import { Debug } from "@ethect/core/rpc";
import type { Hash } from "@ethect/core";

// Effect<Prestate.Prestate, …>
const before = (hash: Hash.Hash) =>
  Debug.traceTransaction(hash, { tracer: "prestateTracer" });
```

```json
{
  "0x0000000000000000000000000000000000000000": {
    "balance": "0x3d23cea3f000"
  },
  "0x5fbdb2315678afecb367f032d93f642f64180aa3": {
    "balance": "0x0",
    "code": "0x3660105763deadbeef5f526004601cfd5b5f35805f555f527fabababababababababababababababababababababababababababababababab60205fa160205ff3",
    "nonce": 1,
    "storage": {
      "0x0000000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000000"
    }
  },
  "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266": {
    "balance": "0x21e19e04f7314f82000",
    "nonce": 1
  }
}
```

The three accounts are the fee recipient, the contract and the sender. The contract's storage
holds the one slot the transaction touched, with the value it had before.

### Diff mode

With `diffMode: true` the tracer returns what the execution changed.

- **Selected by:** `tracer: "prestateTracer"` and `tracerConfig: { diffMode: true }`.
- **Config:** a [`Prestate.DiffConfig`](https://ethect.dev/rpc/types/prestate/): `diffMode: true`, with
  `disableCode` and `disableStorage` as above.
- **Result:** [`Prestate.Diff`](https://ethect.dev/rpc/types/prestate/): the accounts as they were in
  `pre`, and what became of them in `post`.

```ts
import { Debug } from "@ethect/core/rpc";
import type { Hash } from "@ethect/core";

// Effect<Prestate.Diff, …>
const changes = (hash: Hash.Hash) =>
  Debug.traceTransaction(hash, {
    tracer: "prestateTracer",
    tracerConfig: { diffMode: true },
  });
```

```json
{
  "post": {
    "0x0000000000000000000000000000000000000000": {
      "balance": "0x656c932be200"
    },
    "0x5fbdb2315678afecb367f032d93f642f64180aa3": {
      "storage": {
        "0x0000000000000000000000000000000000000000000000000000000000000000": "0x0000000000000000000000000000000000000000000000000000000000000007"
      }
    },
    "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266": {
      "balance": "0x21e19e003e4dd81d4d8",
      "nonce": 2
    }
  },
  "pre": {
    "0x0000000000000000000000000000000000000000": {
      "balance": "0x3d23cea3f000"
    },
    "0x5fbdb2315678afecb367f032d93f642f64180aa3": {
      "balance": "0x0",
      "code": "0x3660105763deadbeef5f526004601cfd5b5f35805f555f527fabababababababababababababababababababababababababababababababab60205fa160205ff3",
      "nonce": 1
    },
    "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266": {
      "balance": "0x21e19e04f7314f82000",
      "nonce": 1
    }
  }
}
```

`post` holds only the fields that changed: the slot the contract wrote, the nonce and the
balance of the sender.

## 4byteTracer

Counts the calls each function selector got.

- **Selected by:** `tracer: "4byteTracer"`.
- **Config:** none.
- **Result:** [`Trace.FourByte`](https://ethect.dev/rpc/types/trace/), a record of counts. A key is the
  selector, a dash, then the size of the calldata that followed it, in bytes.

```ts
import { Debug } from "@ethect/core/rpc";
import type { Hash } from "@ethect/core";

// Effect<Trace.FourByte, …>
const selectors = (hash: Hash.Hash) =>
  Debug.traceTransaction(hash, { tracer: "4byteTracer" });
```

```json
{
  "0x00000000-28": 1
}
```

The transaction called the contract once, with 32 bytes of calldata: 4 read as the selector and
28 after it. anvil 1.9 runs this tracer for a mined transaction and for a block, and refuses it
for [`Debug.traceCall`](https://ethect.dev/rpc/debug/trace-call/).

## noopTracer

Runs the execution and returns nothing about it.

- **Selected by:** `tracer: "noopTracer"`.
- **Config:** none.
- **Result:** an empty object, typed as a record without values.

```ts
import { Debug } from "@ethect/core/rpc";
import type { Hash } from "@ethect/core";

// Effect<{ readonly [name: string]: never }, …>
const nothing = (hash: Hash.Hash) =>
  Debug.traceTransaction(hash, { tracer: "noopTracer" });
```

```json
{}
```

## Custom tracers

Any other `tracer` string is sent to the node as it is: the name of a tracer the library has no
definition for, or the source of a JavaScript tracer.

- **Selected by:** a `tracer` that is none of the four names above.
- **Config:** `tracerConfig` (optional), any value.
- **Result:** `unknown`. Decode it with a schema of what your tracer returns.

```ts
import { Effect, Schema } from "effect";
import { Debug } from "@ethect/core/rpc";
import type { Hash } from "@ethect/core";

// a JavaScript tracer that collects the name of every opcode executed
const tracer = [
  "{ ops: [],",
  "step(log) { this.ops.push(log.op.toString()) },",
  "fault() {},",
  "result() { return this.ops } }",
].join(" ");

const opcodes = (hash: Hash.Hash) =>
  // Effect<unknown, …>
  Debug.traceTransaction(hash, { tracer }).pipe(
    // Effect<ReadonlyArray<string>, …>
    Effect.flatMap(Schema.decodeUnknownEffect(Schema.Array(Schema.String))),
  );
```

```json
[
  "CALLDATASIZE",
  "PUSH1",
  "JUMPI",
  "JUMPDEST",
  "PUSH0",
  "CALLDATALOAD",
  "DUP1",
  "PUSH0",
  "SSTORE",
  "PUSH0",
  "MSTORE",
  "PUSH32",
  "PUSH1",
  "PUSH0",
  "LOG1",
  "PUSH1",
  "PUSH0",
  "RETURN"
]
```

anvil 1.9 runs JavaScript tracers. It also reads a name it does not know as JavaScript, so a
misspelled name fails with an `RpcError` of reason `InternalError`.

geth's other tracers, such as `muxTracer` and `flatCallTracer`, have no definition in the
library: they are custom tracers here.

## Behavior

- **One definition per tracer.** Each tracing method is a
  [`Method.overload`](https://ethect.dev/rpc/method/overload/) over the tracers of
  [`Trace.tracers`](https://ethect.dev/rpc/types/trace/), in the order of the table above with diff mode
  before plain `prestateTracer`. TypeScript and the run-time match both take the first one
  that accepts the options. `Debug.Traces` is the type of that list of definitions, which is
  what `Debug.traceCall.variants` holds.
- **A typo in `tracerConfig` gives `unknown`, not a compile error.** With
  `tracerConfig: { onlyTopCal: true }` the options no longer fit `callTracer` for TypeScript,
  which falls back to the custom tracer and types the result `unknown`. At run time the
  misspelled key is dropped from the request and the tracer runs with its defaults. A result
  that is `unknown` where you expected a trace is the sign to check the config.
- **The same goes for a config the tracer does not take.** `4byteTracer` and `noopTracer` have
  no config: giving them a `tracerConfig` types the result `unknown`.
- **A typo at the top level does not compile.** A misspelled struct logger setting, or a
  misspelled `tracerConfig` key name, is refused by TypeScript.
- **Options built beforehand need `as const`.** In `const options = { tracer: "callTracer" }`
  the tracer is a `string`, which selects the custom tracer. Write
  `{ tracer: "callTracer" } as const` to keep the name.
- **`diffMode` has to be a literal.** A `diffMode` of type `boolean` fits neither mode and types
  the result `unknown`.
- **Struct logger settings do not mix with a tracer.** `enableMemory` and the others are only
  accepted without a `tracer` key.
