# Notifications

## Actions

#### Notification Management

* **`addUnreadNotification`**: Adds a new notification to the list of unread notifications.
* **`addReadNotification`**: Adds a new notification to the list of read notifications.
* **`setUnreadNotifications`**: Sets the entire list of unread notifications.
* **`setReadNotifications`**: Sets the entire list of read notifications.
* **`readOneNotification`**: Marks a specific notification as read, moving it from the unread to the read list.

#### Notification State Updates

* **`updateTimestamp`**: Updates the timestamp for the latest notification received.
* **`updateIsNewNotification`**: Sets a flag indicating whether there are new notifications since the last check.

## Hooks

* **`useUnreadNotifications`**: Retrieves a filtered list of unread notifications set to be shown in the modal.
* **`useReadNotifications`**: Fetches a filtered list of read notifications set to be shown in the modal.
* **`usePartialFillNotifications`**: Combines read and unread notifications not intended for modal display, typically for partial fill notifications.
* **`useVisibleNotifications`**: Retrieves a combined list of read and unread notifications set to be shown in the modal.
* **`useLastUpdateTimestamp`**: Accesses the timestamp of the last notification update.
* **`useNewNotification`**: Determines whether there is a new notification since the last check.
* **`useSetNewNotificationFlag`**: Sets the new notification flag and resets it after a short delay.
* **`useNotificationAdderCallback`**: Adds a notification to either the read or unread list based on the specified status.
* **`useMarkAsReadNotificationCallback`**: Marks a specific notification as read if it isn't already in the read notifications list.
* **`useMarkAsReadAllNotificationsCallback`**: Marks all unread notifications as read.

#### Mutators

* **`useSetNewNotificationFlag`**: A hook to trigger the new notification flag, automatically resetting after a brief period.
* **`useNotificationAdderCallback`**: Returns a callback function to add a notification as either read or unread based on the specified category.
* **`useMarkAsReadNotificationCallback`**: Provides a callback to mark a specific notification as read, ensuring it hasn't been marked as read previously.
* **`useMarkAsReadAllNotificationsCallback`**: Returns a callback to mark all unread notifications as read.
* Utilizes lodash's `find` and `remove` for efficient searching and modification of the notifications arrays to ensure immutability and prevent duplicate entries.

### Thunks

#### `getNotifications`

Fetches notifications for an account from the provided base URL, considering a minimum modification time (`timestamp`), and supports pagination through `start` and `size` parameters.

**Parameters**

* `baseUrl`: The base URL for the notifications endpoint.
* `account`: The account for which to fetch notifications.
* `timestamp`: The minimum modification time for notifications to fetch.
* `appName`: The name of the application making the request, for headers.
* `start`: The starting index for pagination (optional, default `0`).
* `size`: The number of notifications to fetch (optional, default `10`).

**Process**

1. Validates the `baseUrl` to ensure it's not empty.
2. Constructs a request to the notifications endpoint, including necessary headers and a body containing the `account` and `timestamp`.
3. On successful fetch, transforms the response data into `NotificationDetails` format, utilizing `groupingNotification` and `toNotification` helper functions to structure the notifications properly.
4. Catches and logs any errors that occur during the fetch operation, returning an empty array of notifications in such cases.

**Return**

Returns an object with `unreadNotifications` containing an array of notifications structured as `NotificationDetails`.

\
Types
-----

### Enums

#### `LastSeenAction`

Represents the last action seen by the hedger.

```typescript
export enum LastSeenAction {
  SEND_QUOTE = "SendQuote",
  FAILED_TO_PUT_ON_BINANCE = "FailedToPutOnBinance",
  REQUEST_TO_CANCEL_QUOTE = "RequestToCancelQuote",
  REQUEST_TO_CLOSE_POSITION = "RequestToClosePosition",
  UNLOCK_QUOTE = "UnlockQuote",
  REQUEST_TO_CANCEL_CLOSE_REQUEST = "RequestToCancelCloseRequest",
  LIQUIDATE_POSITION = "LiquidatePosition",
  FILL_LIMIT_ORDER_OPEN = "FillLimitOrderOpen",
  FILL_LIMIT_ORDER_CLOSE = "FillLimitOrderClose",
  INSTANT_REQUEST_TO_CLOSE_POSITION = "InstantRequestToClosePosition",
  FILL_ORDER_INSTANT_CLOSE = "FillOrderInstantClose",
}
```

#### `NotificationMessages`

Maps `LastSeenAction` values to user-friendly message strings.

#### `FailureType`

Categorizes types of failures, like solvency problems or system exceptions.

#### `ActionStatus`

Indicates the status of an action related to a notification.

#### `StateType`

Defines the type of notification state, such as report or alert.

#### `NotificationType`

Enumerates types of notifications, including partial fills, liquidation alerts, and success messages.

### Interfaces

#### `NotificationDetails`

Structure for detailed notification information, including identifiers, state type, creation and modification times, counterparty address, and specific notification type data.

* **`id`**: Unique identifier for the notification.
* **`quoteId`**: Associated quote identifier.
* **`stateType`**: The state type of the notification.
* **`createTime` & `modifyTime`**: Timestamps for the creation and last modification of the notification.
* **`counterpartyAddress`**: Address of the counterparty involved in the notification's context.
* **`notificationType`**: The specific type of notification.
* **`showInModal`**: Flag indicating whether the notification should be shown in a modal.
* **`version`**: Optional version number.
* **`filledAmountOpen/Close`**: The filled amounts for open or close actions.
* **`lastSeenAction`**: The last action seen by the hedger related to this notification.
* **`actionStatus`**: The status of the action.
* **`failureType` & `failureMessage`**: Details about the failure, if any.
* **`errorCode`**: Optional error code associated with the notification.
* **`transferAmount` & `transferType`**: Details specific to transfer notifications.

#### `NotificationResponse`

Defines the structure expected from the hedger API responses concerning notifications.

* `id`: Unique identifier for the notification.
* `quote_id`: Associated quote identifier.
* `create_time`: Timestamp for the creation of the notification.
* `modify_time`: Timestamp for the last modification of the notification.
* `counterparty_address`: Address of the counterparty involved in the notification's context.
* `filled_amount_open`: The filled amount for open actions.
* `filled_amount_close`: The filled amount for close actions.
* `last_seen_action`: The last action seen by the hedger related to this notification.
* `action_status`: The status of the action.
* `failure_type`: Details about the type of failure, if any.
* `failure_message`: Details about the failure message, if any.
* `error_code`: Optional error code associated with the notification.
* `state_type`: The state type of the notification.
* `version`: Optional version number.

#### `NotificationUrlResponseType`

Describes the response structure for API calls related to fetching notifications, containing an array of `NotificationResponse` objects.

* `position_state`: Array of `NotificationResponse` objects.

## Reducer

Initializes with a default `NotificationState` that tracks unread and read notifications, the status of notification fetching, the timestamp of the last update, and a flag for new notifications.

#### Actions Handled

* **`addUnreadNotification`**: Adds a notification to the unread list, removing duplicates based on specific conditions.
* **`addReadNotification`**: Adds a notification to the read list, ensuring no duplicates.
* **`setUnreadNotifications`**: Replaces the current unread notifications list with a new set.
* **`setReadNotifications`**: Replaces the current read notifications list with a new set.
* **`readOneNotification`**: Moves a notification from the unread to the read list after ensuring it exists and meets specific conditions.
* **`updateTimestamp`**: Updates the `lastUpdateTimestamp` state with a new timestamp.
* **`updateIsNewNotification`**: Sets the `isNewNotification` flag to indicate the presence of new notifications.

## Updater

### Overview

Defines the `NotificationUpdater` component and associated hooks responsible for fetching and handling notifications via both REST API and WebSocket connections.

### Components and Hooks

#### `NotificationUpdater`

&#x20;This does not render any UI but acts as a central hub for notifications management.

**Operations**

* Initiates fetching of notifications based on account and timestamp.
* Subscribes to WebSocket for real-time notification updates.

#### `useNotificationsWebSocket`

Establishes a WebSocket connec+tion for receiving notification updates, handling the connection lifecycle and processing incoming messages.

**Key Features**

* **Connection Management**: Automatically attempts to reconnect upon disconnection.
* **Message Handling**: Processes incoming WebSocket messages, converting them into `NotificationDetails` and adding them to the notification system.
* **User Whitelist Check**: Initiates WebSocket connection only if the user is whitelisted.

#### `useNotifications`

Fetches notifications based on the user's account and a specified timestamp, calling the `getNotifications` thunk.

**Parameters**

* `account`: Active account address.
* `fetchData`: Flag indicating whether to fetch data.
* `baseUrl`: Base URL for the notification service.
* `timestamp`: Timestamp for fetching notifications since a certain point.
* `thunkDispatch`: Dispatch function for thunk actions.

#### `toNotification`

Converts a `NotificationResponse` object from the API or WebSocket into a `NotificationDetails` object for internal use.

#### `groupingNotification`

Analyzes a `NotificationDetails` object to determine its type and visibility based on its status and state type.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://symmdocs.gitbook.io/frontend-sdk-technical-docs/frontend-sdk/state-management/notifications.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
