> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chainstack.com/llms.txt
> Use this file to discover all available pages before exploring further.

# trace_transaction | Ethereum

> Ethereum API method that traces a specific transaction. trace_transaction JSON-RPC method available on the Ethereum blockchain via Chainstack.

Ethereum API method that traces a specific transaction. It provides a detailed record of all the steps taken by the Ethereum Virtual Machine (EVM) during the execution, including all the operations performed and the changes made to the blockchain state. This method is available on Erigon only.

<Check>
  **Get your own node endpoint today**

  [Start for free](https://console.chainstack.com/) and get your app to production levels immediately. No credit card required.

  You can sign up with your GitHub, X, Google, or Microsoft account.
</Check>

## Parameters

* `hash` — the hash identifying a transaction

## Response

* `action` — an object that describes the action taken by the transaction:
  * `from` — the address of the sender who initiated the transaction.
  * `callType` — the type of call, `call` or `delegatecall`, two ways to invoke a function in a smart contract. `call` creates a new environment for the function to work in, so changes made in that function won't affect the environment where the function was called. `delegatecall` doesn't create a new environment. Instead, it runs the function within the environment of the caller, so changes made in that function will affect the caller's environment.
  * `gas` — the units of gas included in the transaction by the sender.
  * `input` — the optional input data sent with the transaction, usually used to interact with smart contracts.
  * `to` — the address of the recipient of the transaction if it was a transaction to an address. For contract creation transactions, this field is null.
  * `value` — the value of the native token transferred along with the transaction, in Wei.
  * `blockHash` — the hash of the block in which the transaction was included.
  * `blockNumber` — the number of the block in which the transaction was included.
  * `error` — a string that indicates whether the transaction was successful or not. `null` if successful, `Reverted` if not.
  * `result` — an object that contains additional data about the execution of the transaction:
    * `gasUsed` — the total used gas by the call, encoded as hexadecimal.
    * `output` — the return value of the call, encoded as a hexadecimal string.
  * `subtraces` — the number of sub-traces created during execution. When a transaction is executed on the EVM, it may trigger additional sub-executions, such as when a smart contract calls another smart contract or when an external account is accessed.
  * `traceAddress` — an array that indicates the position of the transaction in the trace.
  * `transactionHash` — the hash of the transaction.
  * `transactionPosition` — the position of the transaction in the block.
  * `type` — the type of action taken by the transaction, `call` or `create`. `call`  is the most common type of trace and occurs when a smart contract invokes another contract's function. `create` represents the creation of a new smart contract. This type of trace occurs when a smart contract is deployed to the blockchain.

## `trace_transaction` code examples

<Note>
  Learn more about the `ChainstackProvider` in `ethers.js`: [ethers ChainstackProvider Documentation](/reference/ethersjs-chainstackprovider).
</Note>

<CodeGroup>
  ```javascript ethers.js theme={"system"}
  const ethers = require("ethers");

  // Create a ChainstackProvider instance for Ethereum mainnet
  const chainstack = new ethers.ChainstackProvider("mainnet");

  const traceTransaction = async (txHash) => {
    const traces = await chainstack.send("trace_transaction", [txHash]);
    console.log(traces);
  };

  traceTransaction(
    "0xa63fdfaddf1c5c738f1332ff4f4e0f258d2cbad901d853221c729c8ad28a5093"
  );
  ```

  ```javascript web3.js theme={"system"}
  const { Web3, Web3PluginBase } = require("web3");
  const NODE_URL = "CHAINSTACK_NODE_URL";
  const web3 = new Web3(NODE_URL);

  // Define the TraceBlockPlugin class
  class TraceBlockPlugin extends Web3PluginBase {
      pluginNamespace = 'erigon';

      async traceTransaction(txHash) {
          return this.requestManager.send({
              method: 'trace_transaction',
              params: [txHash],
          });
      }
  }

  // Register the plugin
  web3.registerPlugin(new TraceBlockPlugin());

  async function traceTransaction(txHash) {
      const result = await web3.erigon.traceTransaction(txHash);
      console.log(result);
  }

  traceTransaction("0xa63fdfaddf1c5c738f1332ff4f4e0f258d2cbad901d853221c729c8ad28a5093");
  ```

  ```python web3.py theme={"system"}
  from web3 import Web3  
  node_url = "CHAINSTACK_NODE_URL" 
  web3 = Web3.HTTPProvider(node_url)

  tx_hash = "0xa63fdfaddf1c5c738f1332ff4f4e0f258d2cbad901d853221c729c8ad28a5093"

  traces = web3.provider.make_request('trace_transaction', [tx_hash])
  print(traces)
  ```
</CodeGroup>

## Use case

A practical use case of the `trace_transaction` method can be in inspecting NFT transfers, allowing you to identify internal transactions, the sender and receiver, and the amounts transferred. This can be especially useful when analyzing an ERC-721 token purchase on a marketplace like Opensea, where the transfer of funds is not always straightforward due to multiple internal calls for transferring funds to the NFT owner, paying royalties to the creator, and other factors. By using `trace_transaction`, you can gain a more comprehensive understanding of the transaction flow.

The following is an implementation of the logic using web3.js inspecting an [ERC-721 transfer from Opensea on Ethereum](https://polygonscan.com/tx/0xe2eb8be0ea71220bc298e48ba58034d49efb2d311ca45dfe228cb564cd8a3fb5):

```javascript index.js theme={"system"}
const { Web3, Web3PluginBase } = require("web3");
const NODE_URL = "CHAINSTACK_NODE_URL";
const web3 = new Web3(NODE_URL);

// Define the TraceBlockPlugin class
class TraceBlockPlugin extends Web3PluginBase {
    pluginNamespace = 'erigon';

    async traceTransaction(txHash) {
        return this.requestManager.send({
            method: 'trace_transaction',
            params: [txHash],
        });
    }
}

// Register the plugin
web3.registerPlugin(new TraceBlockPlugin());

// Trace a transaction using the web3.debug.traceTransaction method
async function traceTransaction(txHash) {
    const result = await web3.erigon.traceTransaction(txHash);
    return result.map(({ action }) => action);
  }
  
  // Parse a value in wei to ether
  function parseValue(wei) {
    const etherValue = web3.utils.fromWei(wei, "ether")
    return etherValue;
  }
  
  // Main function to run the program
  async function main() {
    const txHash = "0x853b50ccf670f6f2b573d7c58e7bf735bc4623ce434e529d4ad5176c1a5a1efa";
    const transactionTraces = await traceTransaction(txHash); // Trace the specified transaction
    const extractedData = transactionTraces.map(({ from, to, value }) => ({ from, to, value })); // Extract relevant data from the transaction trace
  
    // Loop through each extracted data object and print relevant information
    for (const { from, to, value } of extractedData) {
      const parsedValue = parseValue(value); // Parse the value to ether
  
      // Print information about non-zero value transfers
      if (parsedValue !== '0') {
        console.log('===== Call =====');
        console.log(`From address: ${from}`);
        console.log(`To address: ${to}`);
        console.log(`Value of ${parsedValue} MATIC\n`);
      }
    }
  }
  
  main(); // Call the main function to start the program
```

A custom method called `traceTransaction` is defined using the `extend` method in web3.js. This method is used to trace the execution of an Ethereum transaction and returns an array of actions that occurred during its execution.

The `parseValue` function is defined to convert the value from Wei (the smallest denomination of ether) to its equivalent ether value.

Finally, the main function is defined, which traces the specified Ethereum transaction using the `traceTransaction` method extracts relevant data from the transaction trace, parses the transaction value to ether using the `parseValue` function, and prints information about non-zero value transfers that occurred during the transaction execution.

In this case, the program extracts the `sender`, `receiver`, and `value` of each call. This allows to understand that the third and gourth transfers are some kind of royalty fee, and the last transfer is the seller of the NFT receiving the amount.

```shell Shell theme={"system"}
===== Call =====
From address: 0x82791b169a317bd1613ff54f2d8fbf889ee41964
To address: 0x000000000000ad05ccc4f10045630fb830b95127  
Value of 15.4774 ETH

===== Call =====
From address: 0x000000000000ad05ccc4f10045630fb830b95127
To address: 0xb38827497daf7f28261910e33e22219de087c8f5  
Value of 15.4774 ETH

===== Call =====
From address: 0x000000000000ad05ccc4f10045630fb830b95127
To address: 0xa858ddc0445d8131dac4d1de01f834ffcba52ef1  
Value of 0.077387 ETH

===== Call =====
From address: 0xa858ddc0445d8131dac4d1de01f834ffcba52ef1
To address: 0xd9db270c1b5e3bd161e8c8503c55ceabee709552  
Value of 0.077387 ETH

===== Call =====
From address: 0x000000000000ad05ccc4f10045630fb830b95127
To address: 0x276cd56089e7576fb80d39a763aa0d213b98e948  
Value of 15.400013 ETH
```

From this, we can see that address `0x82791b169a317bd1613ff54f2d8fbf889ee41964` pays 15.47 ETH to buy an NFT, fees of 0.077 ETH are taken from the total amount, and the seller `0x276cd56089e7576fb80d39a763aa0d213b98e948` receives 15.4 ETH. The next step could be to find out what Token ID is bought during this transaction. This information is not readily available in the `trace_transaction` response. If you dig, you can find it in the `input` field of one of the calls, but it is encoded. The best solution is to run the same transaction hash using [eth\_getTransactionReceipt](/reference/ethereum-gettransactionreceipt) and decode the logs.

<Note>
  Read [Tracking some Bored Apes: The Ethereum event logs tutorial](/docs/tracking-some-bored-apes-the-ethereum-event-logs-tutorial) to learn how to read and decode event logs.
</Note>


## OpenAPI

````yaml /openapi/ethereum_node_api/debug_and_trace/trace_transaction.json POST /0a9d79d93fb2f4a4b1e04695da2b77a7
openapi: 3.0.0
info:
  title: Chainstack Node API
  version: 1.0.0
  description: This is an API for interacting with a Chainstack node.
servers:
  - url: https://nd-422-757-666.p2pify.com
security: []
paths:
  /0a9d79d93fb2f4a4b1e04695da2b77a7:
    post:
      tags:
        - upload
      summary: trace_transaction
      operationId: trace_transaction
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                id:
                  type: integer
                  default: 1
                jsonrpc:
                  type: string
                  default: '2.0'
                method:
                  type: string
                  default: trace_transaction
                params:
                  type: array
                  items:
                    anyOf:
                      - type: string
                        title: Transaction hash
                        description: The hash of the transaction to trace.
                  default:
                    - >-
                      0x4fc2005859dccab5d9c73c543f533899fe50e25e8d6365c9c335f267d6d12541
      responses:
        '200':
          description: The transaction's trace.
          content:
            application/json:
              schema:
                type: object
                properties:
                  jsonrpc:
                    type: string
                  id:
                    type: integer
                  result:
                    type: object

````