> ## 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.

# Track NFT Transfers

> Monitor ERC-721 and ERC-1155 NFT transfers through the SQD Portal.

export const QueryInterfaceNftTransfers = () => {
  const useCasesConfig = [{
    id: "nft-transfers",
    name: "Track NFT transfers",
    network: "ethereum-mainnet",
    payload: {
      type: "evm",
      fromBlock: 18000000,
      toBlock: 18010000,
      fields: {
        block: {
          number: true,
          timestamp: true
        },
        log: {
          address: true,
          topics: true,
          transactionHash: true
        }
      },
      logs: [{
        address: ["0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D", "0x60E4d786628Fea6478F785A6d7e704777c86a7c6", "0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB"],
        topic0: ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
      }]
    }
  }];
  const [queryFormat, setQueryFormat] = useState("curl");
  const [useCase, setUseCase] = useState("nft-transfers");
  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>;
};

Monitor ERC-721 Transfer events across multiple NFT collections to track collection activity, analyze whale movements, or build NFT analytics platforms.

## Use Case

NFT transfer tracking enables you to:

* Build NFT transfer trackers and analytics
* Monitor collection activity and floor prices
* Track whale movements across collections
* Analyze trading patterns and market trends

## 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,
          "timestamp": true
        },
        "log": {
          "address": true,
          "topics": true,
          "transactionHash": true
        }
      },
      "logs": [{
        "address": [
          "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D",
          "0x60E4d786628Fea6478F785A6d7e704777c86a7c6",
          "0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB"
        ],
        "topic0": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
      }]
    }'
  ```

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

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

  // Popular NFT collections
  const NFT_CONTRACTS = [
    "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D", // BAYC
    "0x60E4d786628Fea6478F785A6d7e704777c86a7c6", // MAYC
    "0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB", // CryptoPunks
  ];

  const TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";

  for await (const { blocks } of client.getStream({
    type: "evm",
    fromBlock: 18000000,
    toBlock: 18010000,
    fields: {
      block: { timestamp: true },
      log: {
        address: true,
        topics: true,
        transactionHash: true,
      },
    },
    logs: [
      {
        address: NFT_CONTRACTS,
        topic0: [TRANSFER_TOPIC],
      },
    ],
  })) {
    // Process NFT transfers
    for (const block of blocks) {
      for (const log of block.logs) {
        // A few legacy collections (e.g. CryptoPunks) reuse the Transfer topic0
        // but only emit 3 topics, with no indexed token ID.
        if (log.topics.length < 4) continue;

        const from = `0x${log.topics[1].slice(26)}`;
        const to = `0x${log.topics[2].slice(26)}`;
        const tokenId = BigInt(log.topics[3]);

        console.log({
          blockNumber: block.header.number,
          collection: log.address,
          from,
          to,
          tokenId: tokenId.toString(),
          txHash: log.transactionHash,
        });
      }
    }
  }
  ```

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

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

  # Popular NFT collections
  nft_contracts = [
      "0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D",  # BAYC
      "0x60E4d786628Fea6478F785A6d7e704777c86a7c6",  # MAYC
      "0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB"   # CryptoPunks
  ]

  payload = {
      "type": "evm",
      "fromBlock": 18000000,
      "toBlock": 18010000,
      "fields": {
          "block": {
              "number": True,
              "timestamp": True
          },
          "log": {
              "address": True,
              "topics": True,
              "transactionHash": True
          }
      },
      "logs": [{
          "address": nft_contracts,
          "topic0": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"]
      }]
  }

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

  for line in response.text.strip().split('\n'):
      block = json.loads(line)
      for log in block.get('logs', []):
          # A few legacy collections (e.g. CryptoPunks) reuse the Transfer topic0
          # but only emit 3 topics, with no indexed token ID.
          if len(log['topics']) < 4:
              continue

          from_address = "0x" + log['topics'][1][26:]
          to_address = "0x" + log['topics'][2][26:]
          token_id = int(log['topics'][3], 16)
          
          print({
              "blockNumber": block['header']['number'],
              "collection": log['address'],
              "from": from_address,
              "to": to_address,
              "tokenId": token_id,
              "txHash": log['transactionHash']
          })
  ```
</CodeGroup>

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

<QueryInterfaceNftTransfers />

## Key Parameters

| Parameter | Description |
| - | - |
| `address` | NFT collection contract addresses. Multiple addresses use OR logic |
| `topic0` | Transfer event signature (same for ERC-721 and ERC-20) |
| `topics[1]` | From address (indexed parameter) |
| `topics[2]` | To address (indexed parameter) |
| `topics[3]` | Token ID (indexed parameter in ERC-721) |

<Tip>
  ERC-721 Transfer events have the token ID in `topics[3]`. ERC-20 transfers don't have this field (amount is in `data` instead). A few legacy collections, such as CryptoPunks, share the same `topic0` but only emit 3 topics; check `topics.length` before reading `topics[3]`.
</Tip>

## Expected Output

```json theme={"system"}
{
  "header": {
    "number": 18000123,
    "timestamp": 1697544779
  },
  "logs": [
    {
      "address": "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d",
      "topics": [
        "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
        "0x000000000000000000000000a9d1e08c7793af67e9d92fe308d5697fb81d3e43",
        "0x00000000000000000000000028c6c06298d514db089934071355e5743bf21d60",
        "0x0000000000000000000000000000000000000000000000000000000000000001"
      ],
      "transactionHash": "0x123..."
    }
  ]
}
```

## Track Specific Wallet Activity

Monitor NFT transfers for a specific wallet address:

<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": {
        "log": {
          "address": true,
          "topics": true,
          "transactionHash": true
        }
      },
      "logs": [{
        "address": ["0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D"],
        "topic0": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"],
        "topic2": ["0x00000000000000000000000028c6c06298d514db089934071355e5743bf21d60"]
      }]
    }'
  ```

  ```typescript TypeScript theme={"system"}
  const WALLET = "0x28c6c06298d514db089934071355e5743bf21d60";

  for await (const { blocks } of client.getStream({
    type: "evm",
    fromBlock: 18000000,
    toBlock: 18010000,
    fields: {
      log: { address: true, topics: true, transactionHash: true },
    },
    logs: [
      {
        address: ["0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D"], // BAYC
        topic0: ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"],
        topic2: [`0x000000000000000000000000${WALLET.slice(2)}`], // To address
      },
    ],
  })) {
    // process blocks
  }
  ```

  ```python Python theme={"system"}
  wallet = "0x28c6c06298d514db089934071355e5743bf21d60"

  payload = {
      "type": "evm",
      "fromBlock": 18000000,
      "toBlock": 18010000,
      "fields": {
          "log": {
              "address": True,
              "topics": True,
              "transactionHash": True
          }
      },
      "logs": [{
          "address": ["0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D"],
          "topic0": ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"],
          "topic2": [f"0x000000000000000000000000{wallet[2:]}"]
      }]
  }
  ```
</CodeGroup>

## Track Minting Events

Monitor NFT mints (transfers from null address):

<CodeGroup>
  ```typescript TypeScript theme={"system"}
  for await (const { blocks } of client.getStream({
    type: "evm",
    fromBlock: 18000000,
    toBlock: 18010000,
    fields: {
      log: { address: true, topics: true },
    },
    logs: [
      {
        address: ["0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D"],
        topic0: ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"],
        topic1: ["0x0000000000000000000000000000000000000000000000000000000000000000"], // From null
      },
    ],
  })) {
    // process blocks
  }
  ```
</CodeGroup>

<Note>
  Minting is represented as a transfer from the zero address (`0x000...000`).
</Note>

## ERC-1155 Transfers

For ERC-1155 NFTs, use different event signatures:

<CodeGroup>
  ```typescript TypeScript theme={"system"}
  // ERC-1155 TransferSingle event
  const TRANSFER_SINGLE = "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62";

  // ERC-1155 TransferBatch event
  const TRANSFER_BATCH = "0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb";

  for await (const { blocks } of client.getStream({
    type: "evm",
    fromBlock: 18000000,
    toBlock: 18010000,
    fields: {
      log: { address: true, topics: true, data: true },
    },
    logs: [
      {
        address: ["0x..."], // ERC-1155 contract
        topic0: [TRANSFER_SINGLE, TRANSFER_BATCH],
      },
    ],
  })) {
    // process blocks
  }
  ```
</CodeGroup>

## Performance Tips

1. **Filter by collection**: Specify exact contract addresses
2. **Use topic filters**: Filter by from/to addresses at Portal level
3. **Batch processing**: Query 10k-50k blocks at a time
4. **Minimal fields**: Request only needed fields

## Related Examples

<CardGroup cols={2}>
  <Card title="Query Event Logs" icon="file-text" href="/en/portal/evm/examples/query-logs">
    General event log querying
  </Card>

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

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

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


## Related topics

- [Query Event Logs](/en/portal/evm/examples/query-logs.md)
- [EVM Portal Quickstart](/en/portal/evm/quickstart.md)
- [Index EVM DEX Swaps](/en/portal/evm/examples/dex-swaps.md)
- [Track Token Transfers](/en/portal/solana/examples/token-transfers.md)
- [EVM Portal API](/en/portal/evm/overview.md)


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