logsSubscribe | Alchemy Docs

logsSubscribe

Subscribe to Solana transaction log messages that match a log filter.

The logsSubscribe method opens a stream that emits a notification any time a transaction is committed and its logs match the supplied filter. Pair it with logsUnsubscribe to stop receiving notifications.

Parameters

Request

wscat

// initiate websocket stream first
wscat -c wss://solana-mainnet.streaming.alchemy.com/v2/<-- ALCHEMY APP API KEY -->

// then call subscription
{"jsonrpc":"2.0","id":1,"method":"logsSubscribe","params":[{"mentions":["11111111111111111111111111111111"]},{"commitment":"finalized"}]} 
import { Connection, PublicKey } from '@solana/web3.js'

const connection = new Connection(
  'https://solana-mainnet.g.alchemy.com/v2/<-- ALCHEMY APP API KEY -->',
  {
    wsEndpoint: 'wss://solana-mainnet.streaming.alchemy.com/v2/<-- ALCHEMY APP API KEY -->',
    commitment: 'finalized'
  }
)

const subscriptionId = connection.onLogs(
  new PublicKey('11111111111111111111111111111111'),
  (logs, context) => {
    console.log('Logs at slot', context.slot, {
      signature: logs.signature,
      err: logs.err,
      logs: logs.logs
    })
  },
  'finalized'
)

// To unsubscribe later:
// await connection.removeOnLogsListener(subscriptionId)

Result

Response

// subscribe response
{"jsonrpc":"2.0","result":24040,"id":1}

// notification
{
  "jsonrpc": "2.0",
  "method": "logsNotification",
  "params": {
    "result": {
      "context": { "slot": 5208469 },
      "value": {
        "signature": "5h6xBEauJ3PK6SWCZ1PGjBvj8vDdWG3KpwATGy1ARAXFSDwt8GFXM7W5Ncn16wmqokgpiKRLuS83KUxyZyv2sUYv",
        "err": null,
        "logs": [
          "Program 11111111111111111111111111111111 invoke [1]",
          "Program 11111111111111111111111111111111 success"
        ]
      }
    },
    "subscription": 24040
  }
}

Unsubscribe

Use logsUnsubscribe with the subscription id returned by logsSubscribe to cancel the stream.

wscat

{"jsonrpc":"2.0","id":1,"method":"logsUnsubscribe","params":[subscription_id]}
{"jsonrpc":"2.0","result":true,"id":1}

When using @solana/web3.js, call connection.removeOnLogsListener(subscriptionId) instead of sending the raw JSON-RPC request.