# Notifications

Read, count, and mark the notifications in the caller's notification center.

`client.notifications` reads and marks the caller's notification center. Notifications belong to the root account. Errors carry `detail: { service: "notifications", code }`. Tree-shaken builds reach the same service with `notificationsService(core)` from `@polyester/sdk/services/notifications`.

`list`, `get`, and `getCounts` accept a session, or a root account API key whose policy grants `read-notifications`. Marking notifications read or unread takes a session: an API key gets `PermissionError` with `detail.code === "AUTH_SESSION_KIND_NOT_ALLOWED"`. A key scoped to a subaccount gets `PermissionError` with `detail.code === "AUTH_API_KEY_ACCESS_DENIED"`.

An unknown notification ID, including another account's, throws `ResourceNotFoundError` with `detail.code === "NOTIFICATION_NOT_FOUND"`. A `ServiceUnavailableError` means retry the same request. Invalid input throws `ValidationError` before the request is sent.

## Methods

| Method        | Summary                                                                 |
| ------------- | ----------------------------------------------------------------------- |
| `list`        | Page through notifications, newest first.                               |
| `get`         | Read one notification.                                                  |
| `getCounts`   | Count notifications and unread ones, in total and by type.              |
| `markRead`    | Mark notifications read.                                                |
| `markUnread`  | Mark notifications unread.                                              |
| `markAllRead` | Mark every unread notification read, by category and up to a given one. |

### `list(input?, options?)`

Returns `{ notifications, nextPageToken }`, newest first. Pass the previous `nextPageToken` as `pageToken` with the same filters; an empty `nextPageToken` means there are no more.

```ts
let pageToken = "";
do {
	const page = await client.notifications.list({ readState: "unread", pageToken });
	for (const notification of page.notifications) {
		console.log(notification.type, notification.title, notification.text);
	}
	pageToken = page.nextPageToken;
} while (pageToken !== "");
```

| Field        | Type                         | Notes                                                 |
| ------------ | ---------------------------- | ----------------------------------------------------- |
| `categories` | `("alerts" \| "security")[]` | Only these categories. Omit or `[]` for all.          |
| `readState`  | `"unread" \| "read"`         | Only unread or only read. Omit for both.              |
| `startTime`  | `number`                     | Epoch ms, inclusive.                                  |
| `endTime`    | `number`                     | Epoch ms, exclusive. After `startTime` when both set. |
| `limit`      | `number`                     | 1 to 100, default 25.                                 |
| `pageToken`  | `string`                     | The previous `nextPageToken`.                         |

### `get(input, options?)`

Reads one notification by `notificationId`.

### `getCounts(options?)`

Returns exact counts as of one moment: `{ total, unread, types }`. `types` lists every type in a fixed order, including types with no notification, each as `{ type, category, total, unread }`.

```ts
const counts = await client.notifications.getCounts();
console.log(counts.unread);
```

### `markRead(input, options?)` and `markUnread(input, options?)`

Mark 1 to 100 distinct `notificationIds` read or unread and return `{ changed }`, which leaves out notifications already in that state. All or nothing: one unknown ID throws `ResourceNotFoundError` and marks none.

```ts
await client.notifications.markRead({ notificationIds: [notification.notificationId] });
```

### `markAllRead(input?, options?)`

Marks every unread notification read and returns `{ changed }`. `categories` limits it to those categories. `throughNotificationId` marks only that notification and older ones: pass the newest one shown, so one that arrives later stays unread. Omit it to mark every notification that exists when the call runs.

```ts
const page = await client.notifications.list();
const newest = page.notifications[0];
if (newest) {
	await client.notifications.markAllRead({ throughNotificationId: newest.notificationId });
}
```

## Notification types

Each type belongs to one category, and `detail.type` matches `type`.

| `type`                    | `category` | Reports                                                                                                                                                                              |
| ------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `price_alert`             | `alerts`   | A price alert of the caller fired.                                                                                                                                                   |
| `telegram_approval`       | `security` | An action was approved from the Telegram account linked to the caller's account.                                                                                                     |
| `broker_allowlist_change` | `security` | A payout address change of a QuickSwap broker vault the caller is an Owner or Finance member of.                                                                                     |
| `telegram_linked`         | `security` | A Telegram account was linked to the caller's account. The linked Telegram account also receives it.                                                                                 |
| `admin_key_action`        | `security` | An [admin key](https://testnet.polyester.com/docs/sdk/typescript/reference/api-keys#admin-keys) created, changed, or revoked an API key, or changed an API key or subaccount policy. |
| `unspecified`             |            | A type this SDK build does not know. Show `title` and `text` only.                                                                                                                   |

If the caller did not approve a `telegram_approval` action or link the Telegram account of a `telegram_linked` notice, the linked Telegram account may be in someone else's hands: unlink it and review the account's sessions. If nobody on the account made an `admin_key_action` change, revoke the admin key and review the account's API keys. Show prominently a `change_requested` broker allowlist notice the caller did not request: an added address becomes payable 24 hours after it is listed.

## Shapes

```ts
import type {
	AccountNotification,
	AccountNotificationDetail,
	AdminKeyAction,
	TelegramApprovalAction,
} from "@polyester/sdk";

interface AccountNotification {
	notificationId: string;
	type:
		| "price_alert"
		| "telegram_approval"
		| "broker_allowlist_change"
		| "telegram_linked"
		| "admin_key_action"
		| "unspecified";
	category: "alerts" | "security" | "unspecified";
	title: string; // plain text, the same for every notification of a type
	text: string; // plain-text summary; may span several lines
	createdAt: number | null; // epoch ms
	readAt: number | null; // epoch ms; null while unread
	detail: AccountNotificationDetail;
}

type AccountNotificationDetail =
	| {
			type: "price_alert";
			alertId: string; // the alert's ID in client.priceAlerts
			symbolId: number;
			direction: "above" | "below" | "unspecified";
			priceSource: "last_price" | "index_price" | "unspecified";
			price: string; // alert price, a decimal string
			triggeredPrice: string; // price that fired the alert
			triggeredAt: number | null;
	  }
	| {
			type: "telegram_approval";
			approvalId: string; // the approval's ID in client.assistant
			action: TelegramApprovalAction;
			accountId: string; // trading account the action acted on
			summary: string;
			parameters: { label: string; value: string }[]; // display order, such as market, side, quantity
			approvedAt: number | null;
	  }
	| {
			type: "broker_allowlist_change";
			broker: string;
			vaultAccountId: string; // sub-account ID of the broker vault
			changeId: string; // the change's ID; key the vault allowlist view on it
			event: "change_requested" | "change_applied" | "change_not_applied" | "unspecified";
			action: "add_destination" | "remove_destination" | "unspecified";
			destinationChainId: string; // decimal string
			destinationAddress: string;
			label: string; // the requesting member's name for an added address; "" when none
			requestedByAccountId: string; // account ID of the member who requested the change
	  }
	| {
			type: "telegram_linked";
			linkedAt: number | null;
	  }
	| {
			type: "admin_key_action";
			adminKeyId: string; // the admin key that made the change
			action: AdminKeyAction;
			keyId: string; // the API key changed; "" for a subaccount policy change
			subaccountId: string | null; // null for the main account or a subaccount policy update
			policyId: string | null; // the policy set or updated; null when none
			sourceIp: string;
			changedAt: number | null;
	  }
	| { type: "unspecified" };
```

`TelegramApprovalAction` is what the approval approved: `place_order`, `place_orders`, `modify_orders`, `cancel_order` (an order or a trigger), `cancel_all_orders`, `modify_trigger`, `pause_trigger`, `resume_trigger`, `swap`, `convert_dust`, or `unspecified`. A broker allowlist `event` of `change_not_applied` is final: nothing changed.

`AdminKeyAction` is what the admin key changed: `create_api_key`, `update_api_key`, `delete_api_key`, `set_api_key_policy`, `set_subaccount_policy`, `update_subaccount_policy`, or `unspecified`. `policyId` is the API key policy for `set_api_key_policy` and the subaccount policy for the subaccount actions.

## Related

- [Price alerts](https://testnet.polyester.com/docs/sdk/typescript/reference/price-alerts) for the alerts behind `price_alert` notices.
- [Assistant](https://testnet.polyester.com/docs/sdk/typescript/reference/assistant) for approvals and Telegram approval limits.
- [API keys](https://testnet.polyester.com/docs/sdk/typescript/reference/api-keys#admin-keys) for the admin keys behind `admin_key_action` notices.
- [Errors](https://testnet.polyester.com/docs/sdk/typescript/reference/errors) for the error type reference.
