# getEvents

> For the complete documentation index, see [llms.txt](/docs/llms.txt).

POST https://stellar-mainnet.g.alchemy.com/v2/{apiKey}

Clients can request a filtered list of events emitted by a given ledger range.

Stellar-RPC will support querying within a maximum 7 days of recent ledgers.

Note, this could be used by the client to only prompt a refresh when there is a new ledger with relevant events. It should also be used by backend Dapp components to "ingest" events into their own database for querying and serving.

If making multiple requests, clients should deduplicate any events received, based on the event's unique id field. This prevents double-processing in the case of duplicate events being received.

By default stellar-rpc retains the most recent 24 hours of events.

Reference: https://www.alchemy.com/docs/chains/stellar/stellar-api-endpoints/get-events

## Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| startLedger | number | No | Ledger sequence number to start fetching responses from (inclusive). This method will return an error if `startLedger` is less than the oldest ledger stored in this node, or greater than the latest ledger seen by this node. If a cursor is included in the request, `startLedger` must be omitted. |
| endLedger | number | No | Ledger sequence number represents the end of search window (exclusive). If a cursor is included in the request, `endLedger` must be omitted. |
| filters | object[] | No | List of filters for the returned events. Events matching any of the filters are included. To match a filter, an event must match both a contractId and a topic. Maximum 5 filters are allowed per request. |
| pagination | object | No | Pagination in stellar-rpc is similar to pagination in Horizon. See [Pagination](https://developers.stellar.org/docs/data/rpc/api-reference/structure/pagination). |
| xdrFormat | string | No | Lets the user choose the format in which the response should be returned - either as unpacked JSON or as base64-encoded XDR strings. Note that you should not rely on any schema for the JSON, as it will change when the underlying XDR changes. |

## Result

**getEventsResult** (object)

## Code Examples

### cURL

```bash
curl --request POST \
  --url https://stellar-mainnet.g.alchemy.com/v2/docs-demo \
  --header 'Content-Type: application/json' \
  --data '{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getEvents",
  "params": [
    1,
    1,
    [
      {
        "type": "system",
        "contractIds": [
          "string"
        ],
        "topics": [
          [
            "string"
          ]
        ]
      }
    ],
    {
      "cursor": "string",
      "limit": 1
    },
    "string"
  ]
}'
```

### JavaScript

```javascript
const options = {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    jsonrpc: '2.0',
    id: 1,
    method: 'getEvents',
    params: [
      1,
      1,
      [{type: 'system', contractIds: ['string'], topics: [['string']]}],
      {cursor: 'string', limit: 1},
      'string'
    ]
  })
};

fetch('https://stellar-mainnet.g.alchemy.com/v2/docs-demo', options)
  .then(res => res.json())
  .then(res => console.log(res))
  .catch(err => console.error(err));
```

### Python

```python
import requests

url = "https://stellar-mainnet.g.alchemy.com/v2/docs-demo"

payload = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "getEvents",
    "params": [
        1,
        1,
        [
            {
                "type": "system",
                "contractIds": ["string"],
                "topics": [["string"]]
            }
        ],
        {
            "cursor": "string",
            "limit": 1
        },
        "string"
    ]
}
headers = {"Content-Type": "application/json"}

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

print(response.text)
```

### Go

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://stellar-mainnet.g.alchemy.com/v2/docs-demo"

	payload := strings.NewReader("{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"method\": \"getEvents\",\n  \"params\": [\n    1,\n    1,\n    [\n      {\n        \"type\": \"system\",\n        \"contractIds\": [\n          \"string\"\n        ],\n        \"topics\": [\n          [\n            \"string\"\n          ]\n        ]\n      }\n    ],\n    {\n      \"cursor\": \"string\",\n      \"limit\": 1\n    },\n    \"string\"\n  ]\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(string(body))

}
```

### Java

```java
HttpResponse<String> response = Unirest.post("https://stellar-mainnet.g.alchemy.com/v2/docs-demo")
  .header("Content-Type", "application/json")
  .body("{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"method\": \"getEvents\",\n  \"params\": [\n    1,\n    1,\n    [\n      {\n        \"type\": \"system\",\n        \"contractIds\": [\n          \"string\"\n        ],\n        \"topics\": [\n          [\n            \"string\"\n          ]\n        ]\n      }\n    ],\n    {\n      \"cursor\": \"string\",\n      \"limit\": 1\n    },\n    \"string\"\n  ]\n}")
  .asString();
```

### C#

```csharp
using RestSharp;


var options = new RestClientOptions("https://stellar-mainnet.g.alchemy.com/v2/docs-demo");
var client = new RestClient(options);
var request = new RestRequest("");
request.AddJsonBody("{\n  \"jsonrpc\": \"2.0\",\n  \"id\": 1,\n  \"method\": \"getEvents\",\n  \"params\": [\n    1,\n    1,\n    [\n      {\n        \"type\": \"system\",\n        \"contractIds\": [\n          \"string\"\n        ],\n        \"topics\": [\n          [\n            \"string\"\n          ]\n        ]\n      }\n    ],\n    {\n      \"cursor\": \"string\",\n      \"limit\": 1\n    },\n    \"string\"\n  ]\n}", false);
var response = await client.PostAsync(request);

Console.WriteLine("{0}", response.Content);

```


## OpenRPC Method Specification

```yaml
name: getEvents
summary: returns contract events
description: |-
  Clients can request a filtered list of events emitted by a given ledger range.

  Stellar-RPC will support querying within a maximum 7 days of recent ledgers.

  Note, this could be used by the client to only prompt a refresh when there is a new ledger with relevant events. It should also be used by backend Dapp components to "ingest" events into their own database for querying and serving.

  If making multiple requests, clients should deduplicate any events received, based on the event's unique id field. This prevents double-processing in the case of duplicate events being received.

  By default stellar-rpc retains the most recent 24 hours of events.
externalDocs:
  url: https://developers.stellar.org/docs/data/apis/rpc/api-reference/methods/getEvents
paramStructure: by-name
params:
  - name: startLedger
    summary: ledger to begin searching from
    description: Ledger sequence number to start fetching responses from (inclusive). This method will return an error if `startLedger` is less than the oldest ledger stored in this node, or greater than the latest ledger seen by this node. If a cursor is included in the request, `startLedger` must be omitted.
    required: false
    schema:
      title: ledgerSequence
      description: Sequence number of the ledger.
      type: number
  - name: endLedger
    summary: ledger represents the end of search window
    description: Ledger sequence number represents the end of search window (exclusive). If a cursor is included in the request, `endLedger` must be omitted.
    required: false
    schema:
      title: ledgerSequence
      description: Sequence number of the ledger.
      type: number
  - name: filters
    summary: filters to narrow events search
    description: List of filters for the returned events. Events matching any of the filters are included. To match a filter, an event must match both a contractId and a topic. Maximum 5 filters are allowed per request.
    schema:
      type: array
      maxItems: 5
      items:
        type: object
        required: []
        properties:
          type:
            title: type
            type: string
            description: Filter events by type. If omitted, all event types are included.
            enum:
              - system
              - contract
          contractIds:
            title: contractIds
            type: array
            description: List of contract IDs to query for events. If omitted, return events for all contracts. Maximum 5 contract IDs are allowed per request.
            maxItems: 5
            items:
              title: contractId
              description: A StrKey representation of a contract address (`C...`). ([SEP-23](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0023.md#specification)).
              type: string
          topics:
            title: topics
            type: array
            description: A list of topic filters. Each filter is itself an array of one to four `SegmentMatcher` elements (see below). If omitted, query for all events. If multiple filters are specified, events will be included if they match any of the filters.
            maxItems: 5
            items:
              type: array
              description: |-
                A `TopicFilter` is `SegmentMatcher[]`

                - The list can be 1-4 `SegmentMatchers` long.
              minItems: 1
              maxItems: 4
              items:
                title: SegmentMatcher
                type: string
                description: |+
                  A `SegmentMatcher` is one of the following:

                  - For an exact segment match, a string containing a base64-encoded ScVal

                  - The string "*" functions as a wildcard that matches exactly one segment.

                  - The string "**" matches zero or more segments and is used to match events with variable topic lengths. It can only appear as the final segment and does not count towards the 4-segment limit.

    required: false
  - name: pagination
    summary: pagination options
    description: Pagination in stellar-rpc is similar to pagination in Horizon. See [Pagination](https://developers.stellar.org/docs/data/rpc/api-reference/structure/pagination).
    required: false
    schema:
      type: object
      required: []
      properties:
        cursor:
          type: string
          description: An opaque string which acts as a paging token. To obtain the next page of results occurring after a given response set this value to the `cursor` field of the response.
        limit:
          type: number
          description: The maximum number of records returned. The limit for getEvents can range from 1 to 10000 - an upper limit that is hardcoded in Stellar-RPC for performance reasons. If this argument isn't designated, it defaults to 100.
  - name: xdrFormat
    summary: 'chooses a response format for XDR fields: ''json'' or ''base64'''
    required: false
    description: Lets the user choose the format in which the response should be returned - either as unpacked JSON or as base64-encoded XDR strings. Note that you should not rely on any schema for the JSON, as it will change when the underlying XDR changes.
    schema:
      title: xdrFormat
      type: string
      description: Specifies whether XDR should be encoded as Base64 (default or 'base64') or JSON ('json').
result:
  name: getEventsResult
  schema:
    type: object
    properties:
      latestLedger:
        title: latestLedger
        description: The sequence number of the latest ledger known to Stellar RPC at the time it handled the request.
        type: number
      events:
        type: array
        items:
          type: object
          properties:
            type:
              title: type
              description: The type of event emission.
              type: string
              enum:
                - contract
                - system
            ledger:
              title: ledgerSequence
              description: Sequence number of the ledger in which this event was emitted.
              type: number
            ledgerClosedAt:
              type: string
              description: '[ISO-8601](https://www.iso.org/iso-8601-date-and-time-format.html) timestamp of the ledger closing time'
            contractId:
              title: contractId
              description: StrKey representation of the contract address that emitted this event.
              type: string
            id:
              description: |-
                Unique identifier for this event, based on the [TOID](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0035.md#specification) format. It combines a 19-character TOID and a 10-character, zero-padded event index, separated by a hyphen. 

                - For example: `0000000000000123456-0000000001`
              type: string
            transactionIndex:
              description: The index of the transaction within the ledger this event occurred in.
              type: number
            operationIndex:
              description: The index of the operation within the transaction this event occurred in.
              type: number
            inSuccessfulContractCall:
              description: If true the event was emitted during a successful contract call.
              deprecated: true
              type: boolean
            topic:
              type: array
              description: The [ScVal](https://github.com/stellar/stellar-xdr/blob/v22.0/Stellar-contract.x#L214)s containing the topics this event was emitted with (as a base64 string).
              minItems: 1
              maxItems: 4
              items:
                title: SegmentMatcher
                type: string
                description: |+
                  A `SegmentMatcher` is one of the following:

                  - For an exact segment match, a string containing a base64-encoded ScVal

                  - The string "*" functions as a wildcard that matches exactly one segment.

                  - The string "**" matches zero or more segments and is used to match events with variable topic lengths. It can only appear as the final segment and does not count towards the 4-segment limit.

            value:
              description: The data emitted by the event (an [ScVal](https://github.com/stellar/stellar-xdr/blob/v22.0/Stellar-contract.x#L214), serialized as a base64 string).
              type: string
            txHash:
              title: hash
              type: string
              minLength: 64
              maxLength: 64
              pattern: ^[a-f\d]{64}$
              description: The transaction which triggered this event.
      cursor:
        title: cursor
        type: string
        description: A token which can be included in a subsequent request to obtain the next page of results.
```
