# Debug.traceTransaction

Runs a mined transaction again and traces it. The options name the tracer, and the tracer
decides the type of the result.

## Usage

```ts
import { Effect } from "effect";
import { FetchHttpClient } from "effect/http";
import { Transport } from "@ethect/core";
import { Debug, Eth } from "@ethect/core/rpc";

const program = Effect.gen(function* () {
  const [from, to] = yield* Eth.accounts();
  const receipt = yield* Eth.sendTransactionSync({ from, to, value: 1n });
  const trace = yield* Debug.traceTransaction(receipt.transactionHash);
  return { gas: trace.gas, failed: trace.failed, returnValue: trace.returnValue };
});

const traced = await program.pipe(
  Effect.provide(Transport.http("http://127.0.0.1:8545")),
  Effect.provide(FetchHttpClient.layer),
  Effect.runPromise,
);
// { gas: 21000, failed: false, returnValue: "0x" }
```

Without options the tracer is the struct logger, and the result is a
[`StructLog.Trace`](https://ethect.dev/rpc/types/struct-log/). The examples below leave the transport out
and take the hash of a transaction that called a contract.

### The calls it made

`callTracer` returns the transaction as a tree of calls.

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

const calls = (hash: Hash.Hash) =>
  Debug.traceTransaction(hash, {
    tracer: "callTracer",
    tracerConfig: { withLog: true },
  }).pipe(
    Effect.map((frame) => ({
      type: frame.type, // "CALL"
      to: frame.to, // the contract
      gasUsed: frame.gasUsed, // 44293n
      inner: frame.calls?.length ?? 0, // the calls the contract made itself
      logs: frame.logs?.length ?? 0, // 1
    })),
  );
```

The result is a [`CallFrame.CallFrame`](https://ethect.dev/rpc/types/call-frame/).

### The state it ran on

`prestateTracer` returns the accounts the transaction touched, as they were before it.

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

const touched = (hash: Hash.Hash) =>
  Debug.traceTransaction(hash, { tracer: "prestateTracer" }).pipe(
    Effect.map((accounts) => Object.keys(accounts)),
    // the fee recipient, the contract and the sender
  );
```

The result is a [`Prestate.Prestate`](https://ethect.dev/rpc/types/prestate/): a record of addresses to
account states.

### What it changed

In diff mode the same tracer returns the accounts the transaction changed, before and after.

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

const CONTRACT = Address.makeUnsafe("0x5FbDB2315678afecb367f032d93F642f64180aa3");

const written = (hash: Hash.Hash) =>
  Effect.gen(function* () {
    const { pre, post } = yield* Debug.traceTransaction(hash, {
      tracer: "prestateTracer",
      tracerConfig: { diffMode: true },
    });
    // `before` is undefined when the slots written were empty
    return { before: pre[CONTRACT]?.storage, after: post[CONTRACT]?.storage };
  });
```

The result is a [`Prestate.Diff`](https://ethect.dev/rpc/types/prestate/).

### Opcode by opcode

The struct logger takes its settings at the top level of the options, with no `tracer` key.

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

const opcodes = (hash: Hash.Hash) =>
  Debug.traceTransaction(hash, { enableMemory: true, limit: 100 }).pipe(
    Effect.map((trace) => trace.structLogs.map((log) => log.op)),
    // ["CALLDATASIZE", "PUSH1", "JUMPI", …]
  );
```

> **Caution**
>
> anvil keeps the struct logs of the transactions it mines only when it is started with
> `anvil --steps-tracing`. Without the flag, `structLogs` is an empty array for a mined
> transaction, while `gas`, `failed` and `returnValue` are still right. In a test, pass the flag
> in the `args` option of [`AnvilNode`](https://ethect.dev/reference/testing/anvil-node/).
> [`Debug.traceCall`](https://ethect.dev/rpc/debug/trace-call/) is not affected.

## Returns

[`Effect<StructLog.Trace, Method.Error, Transport>`](https://ethect.dev/rpc/method/#calling-a-method)

That is the type without options. The success type follows the tracer the options select:

| Options | Success type |
| --- | --- |
| none, or struct logger settings only | [`StructLog.Trace`](https://ethect.dev/rpc/types/struct-log/) |
| `tracer: "callTracer"` | [`CallFrame.CallFrame`](https://ethect.dev/rpc/types/call-frame/) |
| `tracer: "prestateTracer"` | [`Prestate.Prestate`](https://ethect.dev/rpc/types/prestate/) |
| `tracer: "prestateTracer"` and `tracerConfig: { diffMode: true }` | [`Prestate.Diff`](https://ethect.dev/rpc/types/prestate/) |
| `tracer: "4byteTracer"` | [`Trace.FourByte`](https://ethect.dev/rpc/types/trace/) |
| `tracer: "noopTracer"` | an empty object |
| any other `tracer` | `unknown` |

See [Tracers](https://ethect.dev/rpc/debug/tracers/) for what each one returns and how the options are
matched.

## Parameters

### hash

- **Type:** [`Hash`](https://ethect.dev/reference/primitives/hash/)

The hash of a mined transaction.

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

const trace = Debug.traceTransaction(
  "0xa219263389834d0af83a08dd013ddff84317a5ba432c60207e0be8d56f66980b",
  { tracer: "callTracer" },
);
```

### options (optional)

- **Type:** an object, whose fields depend on the tracer

Which tracer to run and how. Left out, the struct logger runs with its defaults.

| Field | Type | Description |
| --- | --- | --- |
| `tracer` | `string` (optional) | the tracer: `"callTracer"`, `"prestateTracer"`, `"4byteTracer"`, `"noopTracer"`, or any other name or JavaScript tracer |
| `tracerConfig` | an object (optional) | the settings of the tracer named: see [Tracers](https://ethect.dev/rpc/debug/tracers/) |
| `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 |
| `enableMemory`, `disableStack`, `disableStorage`, `enableReturnData`, `debug`, `limit` | | the settings of the struct logger, accepted only without `tracer`: see [`StructLog.Config`](https://ethect.dev/rpc/types/struct-log/) |

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

const top = (hash: Hash.Hash) =>
  Debug.traceTransaction(hash, {
    tracer: "callTracer",
    tracerConfig: { onlyTopCall: true },
    timeout: "5s",
    reexec: 128,
  });
```

## Behavior

- **The options choose the type.** The method is one definition per tracer, grouped with
  [`Method.overload`](https://ethect.dev/rpc/method/overload/). TypeScript picks the success type from the
  options, and at run time the same options pick the schema that decodes the answer.
- **A revert is a result, not a failure.** Tracing a transaction that reverted succeeds: the
  struct logger reports `failed: true`, and `callTracer` puts `error: "execution reverted"` on
  the frame.
- **A contract creation is a frame too.** For a transaction that deployed a contract,
  `callTracer` returns a frame of type `"CREATE"` whose `to` is the new contract and whose
  `output` is its code.
- **Mined transactions only.** The hash has to be that of a transaction in a block: for one
  still in the pool, anvil answers `transaction not found`. To trace something that was not
  sent, use [`Debug.traceCall`](https://ethect.dev/rpc/debug/trace-call/).

## Errors

The three [errors](https://ethect.dev/reference/errors/) every method can fail with. The cases specific to this
method, as anvil 1.9 reports them:

| Error | Reason | When |
| --- | --- | --- |
| `RpcError` | `ResourceNotFound` | no mined transaction has the hash. The message is `transaction not found`. |
| `RpcError` | `InternalError` | `tracer` is a name anvil does not know: it reads it as JavaScript, which does not evaluate |
| `CodecError` | `on: "params"` | the hash is not 32 bytes of hex: nothing is sent |

## JSON-RPC method

`debug_traceTransaction`
