> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirador.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Events

> Recording timestamped milestones in your traces

## What are Events?

**Events** are timestamped milestones within a trace. They record significant moments in your application flow, such as user actions, state changes, or external interactions.

<Note>
  Events recorded while a [span](/concepts/spans) is open nest under it in the trace timeline. Use `span.addEvent()` (or `trace.addEvent()` while a span is active) to group events by operation.
</Note>

## Adding Events

Use `addEvent()` to record an event:

```typescript theme={null}
trace.addEvent('button_clicked');
```

### With Details

Events can include additional details as a string or object:

```typescript theme={null}
// String details
trace.addEvent('error_occurred', 'Connection timeout');

// Object details (automatically stringified)
trace.addEvent('transaction_sent', {
  txHash: '0x123...',
  gasUsed: 21000,
  blockNumber: 12345678
});
```

### With Custom Timestamp

By default, events use the current time. You can provide a custom timestamp using a `Date` object:

```typescript theme={null}
const startTime = new Date();

// ... some operation ...

trace.addEvent('operation_started', null, { timestamp: startTime });
trace.addEvent('operation_completed');
```

## Event Patterns

### User Interaction Flow

```typescript theme={null}
const trace = client.trace({ name: 'Checkout' });

trace.addEvent('cart_viewed')
     .addEvent('checkout_initiated')
     .addEvent('payment_method_selected', { method: 'crypto' })
     .addEvent('transaction_submitted')
     .addEvent('transaction_confirmed');
```

### Error Handling

```typescript theme={null}
try {
  trace.addEvent('operation_started');
  await riskyOperation();
  trace.addEvent('operation_succeeded');
} catch (error) {
  trace.addEvent('operation_failed', {
    error: error.message,
    code: error.code
  });
}
```

### State Transitions

```typescript theme={null}
trace.addEvent('state_change', { from: 'pending', to: 'processing' });
// ... later ...
trace.addEvent('state_change', { from: 'processing', to: 'completed' });
```

## Method Signature

```typescript theme={null}
addEvent(
  name: string,
  details?: string | object,
  options?: AddEventOptions
): Trace
```

| Parameter | Type               | Required | Description                                                   |
| --------- | ------------------ | -------- | ------------------------------------------------------------- |
| `name`    | `string`           | Yes      | Event name                                                    |
| `details` | `string \| object` | No       | Additional context                                            |
| `options` | `AddEventOptions`  | No       | Options (e.g. `{ captureStackTrace: true, timestamp: date }`) |

### AddEventOptions

| Option              | Type       | Default | Description                                      |
| ------------------- | ---------- | ------- | ------------------------------------------------ |
| `captureStackTrace` | `boolean`  | `false` | Capture stack trace at event location            |
| `timestamp`         | `Date`     | `now`   | Custom timestamp for the event                   |
| `severity`          | `Severity` | —       | Event severity level: `info`, `warn`, or `error` |

## Severity Levels

Events can carry a severity level to distinguish informational milestones from warnings and errors. You can set the severity explicitly via the `severity` option:

```typescript theme={null}
trace.addEvent('cache_miss', { key: 'user:123' }, { severity: 'info' });
trace.addEvent('rate_limit_approaching', { remaining: 5 }, { severity: 'warn' });
trace.addEvent('payment_failed', { code: 'REVERT' }, { severity: 'error' });
```

### Convenience Methods

`info()`, `warn()`, and `error()` are shortcuts that set the severity automatically:

```typescript theme={null}
info(name: string, details?: string | object, options?: AddEventOptions): Trace
warn(name: string, details?: string | object, options?: AddEventOptions): Trace
error(name: string, details?: string | object, options?: AddEventOptions): Trace
```

```typescript theme={null}
trace.info('User logged in', { userId: 'user-123' });
trace.warn('Rate limit approaching', { remaining: 5 });
trace.error('Payment failed', { code: 'INSUFFICIENT_FUNDS' });
```

### When to Use Each Level

| Level   | Use For                                               | Examples                                     |
| ------- | ----------------------------------------------------- | -------------------------------------------- |
| `info`  | Normal milestones and successful operations           | User actions, state transitions, completions |
| `warn`  | Degraded states or conditions that may need attention | Rate limits, retries, fallback paths         |
| `error` | Failures that prevent an operation from completing    | Reverted transactions, API errors, timeouts  |

### Example: Severity in a Try/Catch Flow

```typescript theme={null}
const trace = client.trace({ name: 'SwapExecution' });

trace.info('swap_initiated', { pair: 'ETH/USDC', amount: '1.5' });

try {
  const tx = await executeSwap();
  trace.info('swap_confirmed', { txHash: tx.hash, gasUsed: tx.gasUsed });
} catch (err) {
  if (err.code === 'SLIPPAGE_EXCEEDED') {
    trace.warn('swap_slippage', { expected: '1.5%', actual: '3.2%' });
  } else {
    trace.error('swap_failed', { error: err.message, code: err.code });
  }
}
```

## Best Practices

### Use Consistent Naming

Adopt a naming convention for events:

```typescript theme={null}
// snake_case for event names
trace.addEvent('wallet_connected');
trace.addEvent('transaction_signed');
trace.addEvent('swap_completed');
```

### Record Both Success and Failure

Always capture the outcome:

```typescript theme={null}
trace.addEvent('api_call_started', { endpoint: '/swap' });

if (success) {
  trace.addEvent('api_call_succeeded', { status: 200 });
} else {
  trace.addEvent('api_call_failed', { status: 500, error: message });
}
```

### Include Relevant Context

Add details that help with debugging:

```typescript theme={null}
trace.addEvent('validation_failed', {
  field: 'amount',
  value: userInput,
  reason: 'exceeds_balance'
});
```

### Don't Over-Event

Record significant milestones, not every micro-operation:

```typescript theme={null}
// Good - meaningful milestones
trace.addEvent('form_submitted');
trace.addEvent('validation_passed');
trace.addEvent('transaction_sent');

// Avoid - too granular
trace.addEvent('field_focused');
trace.addEvent('character_typed');
trace.addEvent('field_blurred');
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Attributes & Tags" icon="tags" href="/concepts/attributes-and-tags">
    Add metadata to your traces
  </Card>

  <Card title="Transaction Hints" icon="cube" href="/concepts/transaction-hints">
    Correlate with blockchain transactions
  </Card>
</CardGroup>
