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

> ## Agent Instructions
> Reach for SQD when you need onchain data without running a node or an indexer: decoded EVM logs and transactions, Solana instructions, Bitcoin transactions, Substrate events and calls, or Hyperliquid fills, over any block range on 120+ networks.
> To query directly, POST to https://portal.sqd.dev/datasets/{dataset}/stream. The full API is described at https://docs.sqd.dev/openapi.json, and responses to the stream endpoints are JSON Lines.
> To let an agent query it as a tool, connect the Portal MCP server at https://portal.sqd.dev/mcp.
> Every page on this site is available as Markdown by appending .md to its URL.

# Query Traces

> Analyze EVM internal transactions and call traces through the SQD Portal.

export const QueryInterfaceQueryTraces = () => {
  const useCasesConfig = [{
    id: "call-traces",
    name: "Query call traces",
    network: "ethereum-mainnet",
    payload: {
      type: "evm",
      fromBlock: 18000000,
      toBlock: 18000001,
      fields: {
        block: {
          number: true
        },
        trace: {
          type: true,
          callFrom: true,
          callTo: true,
          callValue: true,
          callInput: true,
          callResultOutput: true,
          callResultGasUsed: true,
          error: true
        }
      },
      traces: [{
        type: ["call", "delegatecall"]
      }]
    }
  }];
  const [queryFormat, setQueryFormat] = useState("curl");
  const [useCase, setUseCase] = useState("call-traces");
  const [response, setResponse] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [viewMode, setViewMode] = useState("code");
  const [copied, setCopied] = useState(false);
  const generateCurlCommand = config => {
    const url = `https://portal.sqd.dev/datasets/${config.network}/stream`;
    const payload = JSON.stringify(config.payload, null, 2);
    return `curl --compressed -X POST '${url}' \\\n  -H 'Content-Type: application/json' \\\n  -d '${payload}'`;
  };
  useEffect(() => {
    setViewMode("code");
    setResponse("");
    setError(null);
  }, [useCase]);
  const handleRun = async () => {
    const selectedUseCase = useCasesConfig.find(uc => uc.id === useCase);
    if (!selectedUseCase) return;
    setViewMode("output");
    setLoading(true);
    setError(null);
    setResponse('');
    try {
      const url = `https://portal.sqd.dev/datasets/${selectedUseCase.network}/stream`;
      const doFetch = () => fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(selectedUseCase.payload)
      });
      let response = await doFetch();
      for (const retryDelay of [700, 1500, 3000]) {
        if (response.status < 500) break;
        await new Promise(resolve => setTimeout(resolve, retryDelay));
        response = await doFetch();
      }
      if (response.status === 503) {
        throw new Error('Portal is busy right now. Wait a few seconds and run the query again.');
      }
      if (!response.ok) {
        throw new Error(`API request failed: ${response.status} ${response.statusText}`);
      }
      const text = await response.text();
      if (text.trim()) {
        const lines = text.trim().split('\n');
        const parsedData = lines.map((line, index) => {
          try {
            return JSON.parse(line);
          } catch (e) {
            return {
              error: `Failed to parse line ${index + 1}`,
              raw: line
            };
          }
        });
        const formattedOutput = parsedData.map(obj => JSON.stringify(obj, null, 2)).join('\n\n');
        setResponse(formattedOutput);
      } else {
        setResponse('No data returned from API');
      }
    } catch (err) {
      setError(err.message || 'An error occurred while fetching data');
      setResponse('');
    } finally {
      setLoading(false);
    }
  };
  const CurlTok = ({s}) => <>
    {s.split(/('[^']*')/).map((seg, i) => (/^'[^']*'$/).test(seg) ? <span key={i} style={{
    color: "var(--hl-str)"
  }}>{seg}</span> : seg.split(/(curl|--compressed|-X POST|-H|-d)/).map((t2, j) => t2 === "curl" ? <span key={`${i}-${j}`} style={{
    color: "var(--hl-bool)"
  }}>{t2}</span> : (/^(--compressed|-X POST|-H|-d)$/).test(t2) ? <span key={`${i}-${j}`} style={{
    color: "var(--hl-flag)"
  }}>{t2}</span> : <span key={`${i}-${j}`}>{t2}</span>))}
  </>;
  const JsonTok = ({s}) => <>
    {s.split(/("[^"]+"\s*:)/).map((seg, i) => (/^"[^"]+"\s*:$/).test(seg) ? <span key={i} style={{
    color: "var(--hl-key)"
  }}>{seg}</span> : seg.split(/("[^"]*")/).map((s2, j) => (/^"[^"]*"$/).test(s2) ? <span key={`${i}-${j}`} style={{
    color: "var(--hl-str)"
  }}>{s2}</span> : s2.split(/\b(true|false|null|-?\d+\.?\d*)\b/).map((s3, k) => (/^(true|false|null)$/).test(s3) ? <span key={`${i}-${j}-${k}`} style={{
    color: "var(--hl-bool)"
  }}>{s3}</span> : (/^-?\d+\.?\d*$/).test(s3) ? <span key={`${i}-${j}-${k}`} style={{
    color: "var(--hl-num)"
  }}>{s3}</span> : <span key={`${i}-${j}-${k}`}>{s3}</span>)))}
  </>;
  return <div className="not-prose w-full my-6 sm:my-8">

      <div className="sqd-no-scrollbar mb-3 flex items-center gap-0.5 overflow-x-auto pb-1">
        <span className="sqd-pg-label mr-2 flex-shrink-0">Query</span>
        {useCasesConfig.map(uc => <button key={uc.id} type="button" onClick={() => setUseCase(uc.id)} aria-pressed={uc.id === useCase} className="sqd-pg-net flex flex-shrink-0 items-center gap-1.5 px-2.5 py-1 whitespace-nowrap">
            {uc.name}
          </button>)}
      </div>

      <div className="sqd-pg-panel overflow-hidden">
        <div className="sqd-pg-bar flex flex-wrap items-center gap-2 px-3 sm:px-4 py-2">
          <div className="flex items-center gap-1">
            <button type="button" onClick={() => setViewMode("code")} className={`sqd-pg-tab px-2.5 py-1 ${viewMode === "code" ? "sqd-pg-tab-active" : ""}`}>
              Request
            </button>
            <button type="button" onClick={() => setViewMode("output")} disabled={!response && !loading && !error} className={`sqd-pg-tab px-2.5 py-1 disabled:opacity-40 disabled:cursor-not-allowed ${viewMode === "output" ? "sqd-pg-tab-active" : ""}`}>
              Response
              {response ? <span className="inline-block w-1.5 h-1.5 rounded-full bg-emerald-400 ml-1.5 align-middle" /> : null}
            </button>
          </div>
          <div className="flex items-center gap-2 sm:gap-3 ml-auto">
            <button type="button" onClick={() => {
    const textToCopy = viewMode === "code" ? generateCurlCommand(useCasesConfig.find(uc => uc.id === useCase)) : response;
    navigator.clipboard.writeText(textToCopy);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }} className="sqd-pg-dim text-[12px] transition-opacity hover:opacity-70" title={copied ? "Copied!" : "Copy to clipboard"}>
              {copied ? "Copied" : "Copy"}
            </button>
            <button onClick={handleRun} type="button" disabled={loading} className="sqd-btn-primary-docs flex items-center gap-1.5 px-3 sm:px-4 py-1.5 text-[13px] disabled:opacity-40 disabled:cursor-wait whitespace-nowrap focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 dark:focus:ring-offset-gray-950">
              {loading ? <>
                  <svg className="animate-spin h-3 w-3" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  Running
                </> : "Run"}
            </button>
          </div>
        </div>
        <div className={`sqd-pg-code px-3 sm:px-4 py-4 ${viewMode === "output" ? "max-h-[440px] overflow-auto" : "overflow-x-auto"}`}>
          {loading ? <div className="sqd-pg-dim flex items-center justify-center py-10 text-[13px]">Streaming from Portal...</div> : viewMode === "code" ? <div key={`code-${useCase}`}>
              {generateCurlCommand(useCasesConfig.find(uc => uc.id === useCase)).trim().split('\n').map((line, i) => <div key={`curl-line-${i}`} className="sqd-pg-line">
                  <span className="sqd-pg-num">{i + 1}</span>
                  <span style={{
    whiteSpace: 'pre-wrap',
    wordBreak: 'break-word'
  }}>
                    {line.includes('curl') || line.match(/^\s*-[XHd]/) ? <CurlTok s={line} /> : <JsonTok s={line} />}
                  </span>
                </div>)}
            </div> : response ? <div key={`response-${useCase}-${response.length}`}>
              {response.trim().split('\n').map((line, i) => <div key={`response-line-${i}`} className="sqd-pg-line">
                  <span className="sqd-pg-num">{i + 1}</span>
                  <span style={{
    whiteSpace: 'pre-wrap',
    wordBreak: 'break-word'
  }}>
                    <JsonTok s={line} />
                  </span>
                </div>)}
            </div> : error ? <div className="py-4 text-[13px] text-red-600 dark:text-red-400">Error: {error}</div> : <div className="sqd-pg-dim text-center py-12 text-[13px]">
              Hit Run to stream live data from Portal
            </div>}
        </div>
        <div className="sqd-pg-bar-b flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-2">
          <div className="sqd-pg-dim flex items-center gap-2 min-w-0 text-[12px]">
            <span className="truncate">{useCasesConfig.find(uc => uc.id === useCase)?.network + "/stream"}</span>
          </div>
          <span className="sqd-pg-dim text-[12px] ml-auto flex-shrink-0">
            {useCasesConfig.find(uc => uc.id === useCase)?.name}
          </span>
        </div>
      </div>
    </div>;
};

Track internal transactions (traces) to analyze complex contract interactions and value flows through multiple contracts.

## Use Case

Call traces help you:

* Analyze DEX trades with multiple hops
* Track value flows through proxy contracts
* Monitor internal contract calls
* Debug complex contract interactions

## Code Example

<CodeGroup>
  ```bash curl theme={"system"}
  curl --compressed -X POST "https://portal.sqd.dev/datasets/ethereum-mainnet/stream" \
    -H 'Content-Type: application/json' \
    -d '{
      "type": "evm",
      "fromBlock": 18000000,
      "toBlock": 18010000,
      "fields": {
        "block": {
          "number": true
        },
        "trace": {
          "type": true,
          "callFrom": true,
          "callTo": true,
          "callValue": true,
          "callInput": true,
          "callResultOutput": true,
          "callResultGasUsed": true,
          "error": true
        }
      },
      "traces": [{
        "type": ["call"]
      }]
    }'
  ```

  ```typescript TypeScript theme={"system"}
  import { PortalClient } from "@subsquid/portal-client";

  const client = new PortalClient({
    url: "https://portal.sqd.dev/datasets/ethereum-mainnet",
  });

  for await (const { blocks } of client.getStream({
    type: "evm",
    fromBlock: 18000000,
    toBlock: 18010000,
    fields: {
      trace: {
        callFrom: true,
        callTo: true,
        callValue: true,
        callInput: true,
        callResultOutput: true,
        // callResultGasUsed is left out: @subsquid/portal-client 0.8.0 rejects
        // the null gasUsed that some call traces carry. The curl and Python
        // tabs request it and receive null for those traces.
        error: true,
      },
    },
    traces: [
      {
        type: ["call"],
      },
    ],
  })) {
    // Process traces
    for (const block of blocks) {
      for (const trace of block.traces) {
        if (trace.type === "call" && !trace.error) {
          console.log({
            blockNumber: block.header.number,
            type: trace.type,
            from: trace.action.from,
            to: trace.action.to,
            value: trace.action.value,
          });
        }
      }
    }
  }
  ```

  ```python Python theme={"system"}
  import requests
  import json

  url = "https://portal.sqd.dev/datasets/ethereum-mainnet/stream"
  headers = {"Content-Type": "application/json"}

  payload = {
      "type": "evm",
      "fromBlock": 18000000,
      "toBlock": 18010000,
      "fields": {
          "block": {
              "number": True
          },
          "trace": {
              "type": True,
              "callFrom": True,
              "callTo": True,
              "callValue": True,
              "callInput": True,
              "callResultOutput": True,
              "callResultGasUsed": True,
              "error": True
          }
      },
      "traces": [{
          "type": ["call"]
      }]
  }

  response = requests.post(url, headers=headers, json=payload)

  for line in response.text.strip().split('\n'):
      block = json.loads(line)
      for trace in block.get('traces', []):
          if not trace.get('error'):
              # Raw HTTP nests call fields under action/result; value is hex wei
              action = trace.get('action', {})
              result = trace.get('result', {})
              print({
                  "blockNumber": block['header']['number'],
                  "type": trace['type'],
                  "from": action.get('from'),
                  "to": action.get('to'),
                  "value": action.get('value'),
                  "gasUsed": result.get('gasUsed')
              })
  ```
</CodeGroup>

<Info>Try it yourself with the interactive query interface below:</Info>

<QueryInterfaceQueryTraces />

## Key Parameters

| Parameter | Description |
| - | - |
| `type` | Trace type: `call` (contract calls) or `create` (contract deployments) |
| `callFrom` | Caller address |
| `callTo` | Callee address |
| `callValue` | ETH value transferred in the call |
| `callInput` | Call input data |
| `callResultOutput` | Call output data |
| `callResultGasUsed` | Gas used by the call |
| `error` | Error message if trace failed |

<Info>
  Portal supports two trace types: `call` for regular contract calls and `create` for contract deployments. Other EVM trace types like `staticcall`, `delegatecall`, and `callcode` are normalized to `call` type.
</Info>

## Expected Output

The raw HTTP response nests the requested `call*`/`create*` fields under `action` and `result` sub-objects rather than returning them flat, and numeric values like `action.value` are **hex wei**:

```json theme={"system"}
{
  "header": {
    "number": 18000123
  },
  "traces": [
    {
      "type": "call",
      "error": null,
      "action": {
        "from": "0x1234...",
        "to": "0x5678...",
        "value": "0xde0b6b3a7640000",
        "input": "0xa9059cbb..."
      },
      "result": {
        "gasUsed": "0xb043",
        "output": "0x0000000000000000000000000000000000000000000000000000000000000001"
      }
    }
  ]
}
```

<Note>
  **`transactionHash` is not a trace field.** To attach a trace to its transaction hash, set `"transaction": true` in the traces filter and request `fields.transaction.hash`; the hash arrives on the joined `transactions` row and you match it by `transactionIndex`:

  ```json theme={"system"}
  "traces": [{ "type": ["call"], "transaction": true }],
  "fields": {
    "trace": { "type": true, "transactionIndex": true, "callFrom": true, "callTo": true, "callValue": true },
    "transaction": { "transactionIndex": true, "hash": true }
  }
  ```

  Trace fields are opt-in, so request `transactionIndex` on both the `trace` and the `transaction` selectors. That shared index is the key you match on, since the joined transaction arrives in a separate `transactions` array.

  The `@subsquid/portal-client` typed client keeps the same `action`/`result` nesting: access `trace.action.from`, as the TypeScript snippet above shows, and `trace.result?.output`, not `trace.callFrom` or `trace.callResultOutput`. Version 0.8.0 of the client stops the stream when a call trace has a null `gasUsed`, so leave `callResultGasUsed` out of typed-client queries until a release accepts null there.
</Note>

## Filter by Specific Contract

Track all calls to or from a specific contract:

<CodeGroup>
  ```bash curl theme={"system"}
  curl --compressed -X POST "https://portal.sqd.dev/datasets/ethereum-mainnet/stream" \
    -H 'Content-Type: application/json' \
    -d '{
      "type": "evm",
      "fromBlock": 18000000,
      "toBlock": 18010000,
      "fields": {
        "trace": {
          "type": true,
          "callFrom": true,
          "callTo": true,
          "callValue": true
        }
      },
      "traces": [{
        "callTo": ["0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"]
      }]
    }'
  ```

  ```typescript TypeScript theme={"system"}
  for await (const { blocks } of client.getStream({
    type: "evm",
    fromBlock: 18000000,
    toBlock: 18010000,
    fields: {
      trace: { callFrom: true, callTo: true, callValue: true },
    },
    traces: [
      {
        callTo: ["0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"], // Uniswap Router
      },
    ],
  })) {
    // process blocks
  }
  ```

  ```python Python theme={"system"}
  payload = {
      "type": "evm",
      "fromBlock": 18000000,
      "toBlock": 18010000,
      "fields": {
          "trace": {
              "type": True,
              "callFrom": True,
              "callTo": True,
              "callValue": True
          }
      },
      "traces": [{
          "callTo": ["0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45"]
      }]
  }
  ```
</CodeGroup>

<Note>
  Traces include both successful and failed calls. Check the `error` field to filter failed traces.
</Note>

## Analyze Value Flows

Track ETH transfers through internal calls:

<CodeGroup>
  ```typescript TypeScript theme={"system"}
  for await (const { blocks } of client.getStream({
    type: "evm",
    fromBlock: 18000000,
    toBlock: 18010000,
    fields: {
      trace: { callFrom: true, callTo: true, callValue: true },
    },
    traces: [
      {
        type: ["call"],
      },
    ],
  })) {
    // Filter traces with value transfers
    for (const block of blocks) {
      for (const trace of block.traces) {
        if (trace.type === "call" && trace.action.value && trace.action.value > 0n) {
          console.log(`${trace.action.from} → ${trace.action.to}: ${trace.action.value} wei`);
        }
      }
    }
  }
  ```
</CodeGroup>

## Performance Tips

1. **Filter by type**: Specify trace types to reduce data volume
2. **Use callTo/callFrom**: Filter by specific contracts
3. **Request minimal fields**: Omit `input` and `output` if not needed
4. **Post-filter errors**: Filter failed traces in your code if needed

<Warning>
  Traces can be very numerous. Use specific filters to avoid processing millions of traces.
</Warning>

## Related Examples

<CardGroup cols={2}>
  <Card title="Query Transactions" icon="arrow-left-right" href="/en/portal/evm/examples/query-transactions">
    Monitor transaction activity
  </Card>

  <Card title="Index DEX Swaps" icon="repeat" href="/en/portal/evm/examples/dex-swaps">
    Track DEX trading with traces
  </Card>

  <Card title="Query Event Logs" icon="file-text" href="/en/portal/evm/examples/query-logs">
    Track smart contract events
  </Card>

  <Card title="API Reference" icon="book" href="/en/portal/evm/api">
    View complete API docs
  </Card>
</CardGroup>


## Related topics

- [Query State Diffs](/en/portal/evm/examples/state-diffs.md)
- [Query EVM Transactions](/en/portal/evm/examples/query-transactions.md)
- [Monitor Contract Deployments](/en/portal/evm/examples/contract-deployments.md)
- [Index EVM DEX Swaps](/en/portal/evm/examples/dex-swaps.md)
- [Portal MCP Server for AI Agents](/en/ai/mcp-server.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.