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

# Index Solana DEX Swaps

> Track Solana DEX trading activity through the SQD Portal.

export const QueryInterfaceSolanaDexSwaps = () => {
  const useCasesConfig = [{
    id: "orca-whirlpool-swaps",
    name: "Track Orca Whirlpool swaps",
    network: "solana-mainnet",
    payload: {
      type: "solana",
      fromBlock: 280000000,
      toBlock: 280000003,
      fields: {
        block: {
          number: true,
          timestamp: true
        },
        instruction: {
          programId: true,
          accounts: true,
          data: true,
          transactionIndex: true
        }
      },
      instructions: [{
        programId: ["whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"],
        d8: ["0xf8c69e91e17587c8"]
      }]
    }
  }];
  const [queryFormat, setQueryFormat] = useState("curl");
  const [useCase, setUseCase] = useState("orca-whirlpool-swaps");
  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 Orca Whirlpool swap instructions to build DEX analytics dashboards, analyze liquidity patterns, or create price feeds.

## Use Case

DEX swap tracking enables you to:

* Build DEX trading analytics and volume trackers
* Monitor liquidity pool activity
* Analyze trading patterns and arbitrage
* Create real-time price feeds

## Code Example

<CodeGroup>
  ```bash curl theme={"system"}
  curl --compressed -X POST "https://portal.sqd.dev/datasets/solana-mainnet/stream" \
    -H 'Content-Type: application/json' \
    -d '{
      "type": "solana",
      "fromBlock": 280000000,
      "toBlock": 280000003,
      "fields": {
        "block": {
          "number": true,
          "timestamp": true
        },
        "instruction": {
          "programId": true,
          "accounts": true,
          "data": true,
          "transactionIndex": true
        }
      },
      "instructions": [{
        "programId": ["whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"],
        "d8": ["0xf8c69e91e17587c8"]
      }]
    }'
  ```

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

  const dataSource = new DataSource({
    network: "solana-mainnet",
  });

  // Orca Whirlpool program ID
  const WHIRLPOOL_PROGRAM = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc";
  // Swap instruction discriminator (first 8 bytes)
  const SWAP_D8 = "0xf8c69e91e17587c8";

  const blocks = await dataSource.getBlocks({
    from: 280000000,
    to: 280000003,
    fields: {
      block: { number: true, timestamp: true },
      instruction: {
        programId: true,
        accounts: true,
        data: true,
        transactionIndex: true,
      },
    },
    instructions: [
      {
        programId: [WHIRLPOOL_PROGRAM],
        d8: [SWAP_D8],
      },
    ],
  });

  // Process swaps
  for (const block of blocks) {
    for (const instruction of block.instructions) {
      console.log({
        slot: block.header.number,
        timestamp: block.header.timestamp,
        pool: instruction.accounts[2], // Whirlpool account (typically at index 2)
        txIndex: instruction.transactionIndex,
        // Decode swap amounts from instruction.data as needed
      });
    }
  }
  ```

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

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

  # Orca Whirlpool program ID
  whirlpool_program = "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"
  # Swap instruction discriminator
  swap_d8 = "0xf8c69e91e17587c8"

  payload = {
      "type": "solana",
      "fromBlock": 280000000,
      "toBlock": 280000003,
      "fields": {
          "block": {
              "number": True,
              "timestamp": True
          },
          "instruction": {
              "programId": True,
              "accounts": True,
              "data": True,
              "transactionIndex": True
          }
      },
      "instructions": [{
          "programId": [whirlpool_program],
          "d8": [swap_d8]
      }]
  }

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

  for line in response.text.strip().split('\n'):
      block = json.loads(line)
      for instruction in block.get('instructions', []):
          print({
              "slot": block['header']['number'],
              "timestamp": block['header']['timestamp'],
              "pool": instruction['accounts'][2] if len(instruction['accounts']) > 2 else None,
              "txIndex": instruction['transactionIndex']
          })
  ```
</CodeGroup>

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

<QueryInterfaceSolanaDexSwaps />

## Key Parameters

| Parameter   | Description                                                 |
| ----------- | ----------------------------------------------------------- |
| `programId` | DEX program address (e.g., Orca Whirlpool)                  |
| `d8`        | 8-byte instruction discriminator for swap instruction       |
| `accounts`  | Instruction account addresses (includes pool, tokens, etc.) |
| `data`      | Instruction data payload (contains swap amounts)            |

<Note>
  Different DEX protocols use different instruction discriminators. Check the
  program IDL to find the correct discriminator for your target DEX.
</Note>

## Expected Output

```json theme={"system"}
{
  "header": {
    "number": 259985000,
    "timestamp": 1697544779
  },
  "instructions": [
    {
      "programId": "whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc",
      "accounts": ["7qbRF6YsyGuLUVs6Y1q64bdVrfe4ZcUUz1JRdoVNUJnm", "..."],
      "data": "base58encodeddata...",
      "transactionIndex": 0
    }
  ]
}
```

## Track Specific Pool

Monitor swaps for a specific trading pair:

<CodeGroup>
  ```bash curl theme={"system"}
  curl --compressed -X POST "https://portal.sqd.dev/datasets/solana-mainnet/stream" \
    -H 'Content-Type: application/json' \
    -d '{
      "type": "solana",
      "fromBlock": 280000000,
      "toBlock": 280000003,
      "fields": {
        "instruction": {
          "programId": true,
          "accounts": true,
          "data": true
        }
      },
      "instructions": [{
        "programId": ["whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"],
        "d8": ["0xf8c69e91e17587c8"],
        "accounts": ["7qbRF6YsyGuLUVs6Y1q64bdVrfe4ZcUUz1JRdoVNUJnm"]
      }]
    }'
  ```

  ```typescript TypeScript theme={"system"}
  const USDC_SOL_POOL = "7qbRF6YsyGuLUVs6Y1q64bdVrfe4ZcUUz1JRdoVNUJnm"; // USDC/SOL pool

  const blocks = await dataSource.getBlocks({
    from: 280000000,
    to: 280000003,
    fields: {
      instruction: { programId: true, accounts: true, data: true },
    },
    instructions: [
      {
        programId: ["whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"],
        d8: ["0xf8c69e91e17587c8"],
        accounts: [USDC_SOL_POOL], // Filter by pool account
      },
    ],
  });
  ```

  ```python Python theme={"system"}
  usdc_sol_pool = "7qbRF6YsyGuLUVs6Y1q64bdVrfe4ZcUUz1JRdoVNUJnm"

  payload = {
      "type": "solana",
      "fromBlock": 280000000,
      "toBlock": 280000003,
      "fields": {
          "instruction": {
              "programId": True,
              "accounts": True,
              "data": True
          }
      },
      "instructions": [{
          "programId": ["whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc"],
          "d8": ["0xf8c69e91e17587c8"],
          "accounts": [usdc_sol_pool]
      }]
  }
  ```
</CodeGroup>

## Decode Swap Amounts

Swap amounts are encoded in the `data` field. Here's how to decode them for Orca Whirlpool:

<Tip>
  Use the Solana typegen tool to generate TypeScript decoders from program IDLs.
  See the [Solana SDK typegen
  documentation](/en/sdk/squid-sdk/solana/reference/solana-typegen) for details.
</Tip>

## Performance Tips

1. **Filter by pool address**: Query specific pools instead of all swaps
2. **Use slot ranges**: Process data in 10k-50k slot batches
3. **Decode off-chain**: Decode swap amounts in your application, not in the query
4. **Combine with token balances**: Use token balances to track actual amounts transferred

## Related Examples

<CardGroup cols={2}>
  <Card title="Query Instructions" icon="code" href="/en/portal/solana/examples/query-instructions">
    General instruction querying
  </Card>

  <Card title="Token Transfers" icon="coins" href="/en/portal/solana/examples/token-transfers">
    Track token movements
  </Card>

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

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


## Related topics

- [Index EVM DEX Swaps](/en/portal/evm/examples/dex-swaps.md)
- [Solana Portal Quickstart](/en/portal/solana/quickstart.md)
- [Build an Indexer from Scratch](/en/sdk/squid-sdk/solana/examples-tutorials/build-indexer-from-scratch.md)
- [Solana Portal API](/en/portal/solana/overview.md)
- [EVM Portal Quickstart](/en/portal/evm/quickstart.md)
