# events_by_creation_number

## Overview

Retrieve events from a specific event stream identified by an account address and creation number. Each event handle in Aptos has a unique creation number assigned when the handle is created. This endpoint lets you query, paginate, and monitor individual event streams for specific on-chain activities like token transfers, staking rewards, or governance votes.

> **Operational note:** This route also relies on indexer-backed event readers on shared Dwellir Aptos fullnodes. If the backend responds with `internal_error` because the indexer reader is unavailable, use GraphQL or the owning resource as your fallback source of truth.

## Endpoint

`GET /v1/accounts/{address}/events/{creation_number}`

## Request Parameters

This method accepts no parameters.

## Request Example

```bash
# Get the first 10 events from creation number 2 (deposit events for 0x1)
    curl -X GET "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/events/2?limit=10" \
      -H "Accept: application/json"

    # Paginate from a specific sequence number
    curl -X GET "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/events/2?start=100&limit=100" \
      -H "Accept: application/json"
```

## Response Fields

- `version` (`string, required`): Ledger version when the event was emitted
- `guid.creation_number` (`string, required`): The creation number identifying this event stream
- `guid.account_address` (`string, required`): The account that owns this event stream
- `sequence_number` (`string, required`): Sequential number within this event stream (starts at 0)
- `type` (`string, required`): Fully qualified Move type of the event payload
- `data` (`object, required`): The structured event payload, fields vary by event type

## Successful Response

```json
[
  {
    "version": "123456789",
    "guid": {
      "creation_number": "2",
      "account_address": "0x1"
    },
    "sequence_number": "42",
    "type": "0x1::coin::DepositEvent",
    "data": {
      "amount": "1000000"
    }
  },
  {
    "version": "123456800",
    "guid": {
      "creation_number": "2",
      "account_address": "0x1"
    },
    "sequence_number": "43",
    "type": "0x1::coin::DepositEvent",
    "data": {
      "amount": "500000"
    }
  }
]
```

## Error Responses

### Error 1

- Code: `invalid_input`
- Description: Invalid address or creation number format

### Error 2

- Code: `resource_not_found`
- Description: Event stream does not exist at this creation number

### Error 3

- Code: `account_not_found`
- Description: Account does not exist

## Code Examples

cURL
Python
TypeScript
Rust

```bash
# Get the first 10 events from creation number 2 (deposit events for 0x1)
curl -X GET "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/events/2?limit=10" \
  -H "Accept: application/json"

# Paginate from a specific sequence number
curl -X GET "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/events/2?start=100&limit=100" \
  -H "Accept: application/json"
```

```python
from aptos_sdk.client import RestClient

client = RestClient("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1")

# Fetch recent events
events = client.account_events_by_creation_number("0x1", "2", start=None, limit=10)
for event in events:
    print(f"Seq {event['sequence_number']}: {event['type']} at version {event['version']}")
    print(f"  Data: {event['data']}")

# Paginate through all events
def stream_events(client, address, creation_number, start_seq=0):
    seq = start_seq
    while True:
        batch = client.account_events_by_creation_number(
            address, str(creation_number), start=str(seq), limit=100
        )
        if not batch:
            break
        for event in batch:
            yield event
        seq = int(batch[-1]["sequence_number"]) + 1

for event in stream_events(client, "0x1", 2):
    process_event(event)
```

```typescript
import { Aptos, AptosConfig } from "@aptos-labs/ts-sdk";

const config = new AptosConfig({
  fullnode: "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1"
});
const aptos = new Aptos(config);

// Fetch events via raw REST call
const response = await fetch(
  "https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1/accounts/0x1/events/2?limit=10",
  { headers: { "Accept": "application/json" } }
);
const events = await response.json();

for (const event of events) {
  console.log(`Event: ${event.type}, Amount: ${event.data.amount}`);
}
```

```rust
use aptos_sdk::rest_client::Client;

let client = Client::new("https://api-aptos-mainnet.n.dwellir.com/YOUR_API_KEY/v1".parse()?);

let events = client
    .get_account_events("0x1", "2", Some(0), Some(10))
    .await?;
for event in events.inner() {
    println!("Seq {}: {} at version {}",
        event.sequence_number, event.typ, event.version);
}
```

## Discovering Creation Numbers

Creation numbers are assigned sequentially when event handles are created in an account's resources. To find the creation number for a specific event stream:

1. **Query the resource** that contains the event handle:
   ```bash
   GET /v1/accounts/{address}/resource/0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>
   ```

2. **Find the event handle** in the response:
   ```json
   {
     "data": {
       "deposit_events": {
         "counter": "42",
         "guid": {
           "id": {
             "addr": "0x1",
             "creation_num": "2"
           }
         }
       },
       "withdraw_events": {
         "counter": "15",
         "guid": {
           "id": {
             "addr": "0x1",
             "creation_num": "3"
           }
         }
       }
     }
   }
   ```

3. **Use the creation\_num** value (e.g., `2` for deposits, `3` for withdrawals) with this endpoint.

Common creation numbers for standard accounts:

- `0` - Account creation event
- `1` - Key rotation event
- `2` - CoinStore deposit events (for the first registered coin)
- `3` - CoinStore withdraw events (for the first registered coin)

## Use Cases

1. **Transfer Monitoring**: Track all deposits and withdrawals for an account by monitoring creation numbers 2 and 3 (for CoinStore events), enabling real-time balance tracking and notifications.

2. **Event Stream Processing**: Build event-driven architectures that react to specific on-chain events, such as triggering webhooks when a deposit exceeds a threshold.

3. **Historical Event Analysis**: Paginate through historical events to analyze patterns, aggregate statistics (total volume, transaction counts), or reconstruct state changes over time.

4. **Audit Trail Construction**: Build comprehensive audit logs by retrieving all events emitted by critical accounts (treasury, governance, multisig) in chronological order.

5. **Notification Systems**: Poll for new events at regular intervals and trigger alerts (email, Slack, push notifications) when specific event types or amounts are detected.

6. **DeFi Position Tracking**: Monitor staking events, reward distributions, and liquidity pool events to maintain accurate portfolio tracking.

## Best Practices

**Creation Number Discovery**: Always discover creation numbers dynamically from the containing resource rather than hardcoding them. While standard CoinStore uses 2/3 for deposit/withdraw, custom modules may use different numbers.

**Pagination Strategy**: Use `limit=100` to minimize API calls for bulk historical retrieval. Use the last event's `sequence_number + 1` as the next `start` parameter.

**Sequence Number Properties**: Sequence numbers within a stream are guaranteed to be sequential with no gaps, starting from 0. Missing sequence numbers indicate data synchronization issues.

**Version Ordering**: While sequence numbers order events within a single stream, use the `version` field to establish ordering across different event streams or accounts.

**Legacy vs Modern Events**: This endpoint supports both the legacy event handle system and newer event handles. For new contracts using `0x1::event::emit()`, events may be queried differently through the indexer.

**Rate Limiting**: Avoid polling too frequently. For near-real-time monitoring, poll every 4-5 seconds (matching Aptos block time). For less urgent monitoring, poll every 30-60 seconds.

**Counter Check**: The `counter` field in the event handle resource tells you the total number of events emitted. Use this to determine if there are new events without fetching the events themselves.

## Performance Considerations

Event queries are efficient for reasonable ranges. Fetching 100 events typically completes in 50-100ms. Requesting the maximum of 100 events with complex payloads can take 100-200ms.

Events are stored in chronological order, making forward pagination (increasing sequence numbers) the most efficient access pattern. The creation number index provides O(1) lookup to the event stream root.

For applications requiring comprehensive event analysis across multiple accounts or event types, the GraphQL indexer provides more efficient bulk querying capabilities with complex filtering, aggregation, and cross-account event correlation.

## Related Endpoints

- `/v1/accounts/{address}/events/{event_handle}/{field_name}` - Query events by handle and field name
- `/v1/accounts/{address}/resource/{type}` - Discover event handles and creation numbers
- `/v1/accounts/{address}/resources` - List all resources to find event handles
- `/v1/transactions/by_version/{version}` - Get the transaction that emitted a specific event
