@metamask-previews/social-controllers 3.20.0-preview-d853a918a → 3.21.0-preview-8e636eabf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,17 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [3.21.0]
11
+
10
12
  ### Added
11
13
 
12
14
  - Add `following_v1` to `FeedScope`, so `fetchFeed` can request the following feed in the shape of the all feed ([#11424](https://github.com/MetaMask/core/pull/11424))
13
15
  - social-api returns the all-feed items of the profiles the user follows, without the user's own: one item per position trade plus one per author comment, ordered by `occurredAt`, each with `feedItemId`, `eventId`, `revision` and `occurredAt`.
14
16
  - Its cursors are the all-feed cursors, so they cannot be passed to `following`, and vice versa.
15
17
  - `following` is unchanged.
18
+ - Keep the prices social-api adds to realtime feed items ([#11442](https://github.com/MetaMask/core/pull/11442))
19
+ - `parseRealtimeFeedItem` and `normalizeRealtimeFeedItem` now copy `currentValueUSD`, `positionValueUSD`, `pnlValueUsd` and `pnlPercent` from a hydrated socket payload onto the `FeedItem`, so a realtime item can show a value before the client's live price loads.
20
+ - A field the payload omits stays absent, and an explicit `null` stays `null`.
16
21
 
17
22
  ### Changed
18
23
 
19
24
  - Bump `@metamask/profile-sync-controller` from `^36.1.0` to `^36.1.1` ([#11419](https://github.com/MetaMask/core/pull/11419))
20
25
 
26
+ ### Fixed
27
+
28
+ - Keep the realtime feed subscribed when `SocialRealtimeService.setScopes` is called with the scopes already active ([#11438](https://github.com/MetaMask/core/pull/11438))
29
+ - `setScopes` no longer resubscribes when the scope set is unchanged.
30
+ - A scope replacement no longer unsubscribes the previous subscription when the backend returns the same subscription id for it. The backend does this for a repeat subscribe to the same channels, so the unsubscribe ended the replacement and the feed stopped receiving events.
31
+
21
32
  ## [3.20.0]
22
33
 
23
34
  ### Added
@@ -425,7 +436,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
425
436
  - `unfollowTrader` — unfollows traders and removes addresses from state
426
437
  - `updateFollowing` — fetches following list and replaces addresses in state
427
438
 
428
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/social-controllers@3.20.0...HEAD
439
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/social-controllers@3.21.0...HEAD
440
+ [3.21.0]: https://github.com/MetaMask/core/compare/@metamask/social-controllers@3.20.0...@metamask/social-controllers@3.21.0
429
441
  [3.20.0]: https://github.com/MetaMask/core/compare/@metamask/social-controllers@3.19.0...@metamask/social-controllers@3.20.0
430
442
  [3.19.0]: https://github.com/MetaMask/core/compare/@metamask/social-controllers@3.18.0...@metamask/social-controllers@3.19.0
431
443
  [3.18.0]: https://github.com/MetaMask/core/compare/@metamask/social-controllers@3.17.0...@metamask/social-controllers@3.18.0
@@ -1 +1 @@
1
- {"version":3,"file":"SocialRealtimeService.d.ts","sourceRoot":"","sources":["../src/SocialRealtimeService.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,gCAAgC,EAGjC,MAAM,wBAAwB,CAAC;AAGhC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAErE,eAAO,MAAM,oBAAoB;aAC/B,GAAG,EAAE,oBAAoB;aACzB,QAAQ,EAAE,yBAAyB;CAC3B,CAAC;AAEX,MAAM,MAAM,uBAAuB,GAAG,MAAM,OAAO,oBAAoB,CAAC;AAExE,eAAO,MAAM,wBAAwB,EAAG,WAAoB,CAAC;AAE7D,MAAM,MAAM,eAAe,GAAG;IAC5B,OAAO,EAAE,CAAC,CAAC;IACX,IAAI,EAAE,WAAW,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,qBAAqB,CAAC;CAC7B,CAAC;AAEF,MAAM,MAA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;IACX,IAAI,EAAE,WAAW,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,qBAAqB,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,uBAAuB,GAAG,CACpC,KAAK,EAAE,eAAe,EACtB,KAAK,EAAE,uBAAuB,KAC3B,IAAI,CAAC;AACV,MAAM,MAAM,2BAA2B,GAAG,MAAM,IAAI,CAAC;AAErD,MAAM,MAAM,4BAA4B,GAAG;IACzC,SAAS,EAAE,gCAAgC,CAAC;IAC5C,MAAM,EAAE,SAAS,uBAAuB,EAAE,CAAC;IAC3C,SAAS,CAAC,EAAE,MAAM,OAAO,CAAC;CAC3B,CAAC;AAyDF;;;;;GAKG;AACH,qBAAa,qBAAqB;;IAChC,QAAQ,CAAC,IAAI,EAAG,uBAAuB,CAAU;IA4BjD,YAAY,EACV,SAAS,EACT,MAAM,EACN,SAA+B,GAChC,EAAE,4BAA4B,EA6B9B;IAED,WAAW,CAAC,QAAQ,EAAE,uBAAuB,GAAG,MAAM,IAAI,CAGzD;IAED,oBAAoB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,MAAM,IAAI,CAGtE;IAEK,SAAS,CAAC,MAAM,EAAE,SAAS,uBAAuB,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAiBzE;IAgCK,SAAS,CAAC,MAAM,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAU9C;CA8JF"}
@@ -13,6 +13,7 @@ const normalizeScopes = (scopes) => {
13
13
  }
14
14
  return normalized;
15
15
  };
16
+ const haveSameScopes = (left, right) => left.length === right.length && left.every((scope) => right.includes(scope));
16
17
  const scopeForChannel = (channel) => Object.entries(SOCIAL_FEED_CHANNELS).find(([, value]) => value === channel)?.[0] ?? undefined;
17
18
  const parseSocialFeedEvent = (data) => {
18
19
  if (!isRecord(data)) {
@@ -112,6 +113,9 @@ export class SocialRealtimeService {
112
113
  this.#scopes = normalizedScopes;
113
114
  return;
114
115
  }
116
+ if (this.#subscription && haveSameScopes(this.#scopes, normalizedScopes)) {
117
+ return;
118
+ }
115
119
  const previousScopes = this.#scopes;
116
120
  const connectionVersion = this.#connectionVersion;
117
121
  this.#scopes = normalizedScopes;
@@ -207,7 +211,12 @@ export class SocialRealtimeService {
207
211
  throw error;
208
212
  }
209
213
  const replacementSubscription = this.#subscription;
210
- if (existingSubscription && existingSubscription !== this.#subscription) {
214
+ // The backend answers a repeat subscribe to the same channels with the same
215
+ // subscription id. Unsubscribing the old handle would end the replacement.
216
+ if (existingSubscription &&
217
+ existingSubscription !== this.#subscription &&
218
+ existingSubscription.subscriptionId !==
219
+ replacementSubscription?.subscriptionId) {
211
220
  try {
212
221
  await existingSubscription.unsubscribe();
213
222
  }
@@ -1 +1 @@
1
- {"version":3,"file":"SocialRealtimeService.js","sourceRoot":"","sources":["../src/SocialRealtimeService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAOxD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAGhE,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,GAAG,EAAE,oBAAoB;IACzB,QAAQ,EAAE,yBAAyB;CAC3B,CAAC;AAIX,MAAM,CAAC,MAAM,wBAAwB,GAAG,WAAoB,CAAC;AAwB7D,MAAM,QAAQ,GAAG,CAAC,KAAc,EAAoC,EAAE,CACpE,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC;AAE9C,MAAM,eAAe,GAAG,CACtB,MAA0C,EACf,EAAE;IAC7B,MAAM,UAAU,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IACxC,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,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I,CAAC,uBAAuB,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;YACpD,CAAC;YAAC,MAAM,CAAC;gBACP,4DAA4D;YAC9D,CAAC;QACH,CAAC;IACH,CAAC;IAED,mBAAmB,CAAC,YAAuC;QACzD,MAAM,KAAK,GAAG,eAAe,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QACpD,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YAC5C,OAAO;QACT,CAAC;QAED,qBAAqB,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;YACzD,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;QAChE,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { WebSocketState } from '@metamask/core-backend';\nimport type {\n BackendWebSocketServiceMessenger,\n ServerNotificationMessage,\n WebSocketSubscription,\n} from '@metamask/core-backend';\n\nimport { parseRealtimeFeedItem } from './realtime-feed-item.js';\nimport type { RealtimeFeedEventData } from './realtime-feed-item.js';\n\nexport const SOCIAL_FEED_CHANNELS = {\n all: 'social.v1.feed.all',\n trending: 'social.v1.feed.trending',\n} as const;\n\nexport type SocialFeedRealtimeScope = keyof typeof SOCIAL_FEED_CHANNELS;\n\nexport const SOCIAL_FEED_CHANNEL_TYPE = 'social.v1' as const;\n\nexport type SocialFeedEvent = {\n version: 1;\n kind: 'feed-item';\n eventId: string;\n feedItemId: string;\n revision: number;\n occurredAt: string;\n data: RealtimeFeedEventData;\n};\n\nexport type SocialFeedEventListener = (\n event: SocialFeedEvent,\n scope: SocialFeedRealtimeScope,\n) => void;\nexport type SocialFeedReconnectListener = () => void;\n\nexport type SocialRealtimeServiceOptions = {\n messenger: BackendWebSocketServiceMessenger;\n scopes: readonly SocialFeedRealtimeScope[];\n isEnabled?: () => boolean;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\nconst normalizeScopes = (\n scopes: readonly SocialFeedRealtimeScope[],\n): SocialFeedRealtimeScope[] => {\n const normalized = [...new Set(scopes)];\n if (normalized.length === 0) {\n throw new Error('At least one Social feed scope is required');\n }\n return normalized;\n};\n\nconst scopeForChannel = (\n channel: string,\n): SocialFeedRealtimeScope | undefined =>\n (Object.entries(SOCIAL_FEED_CHANNELS).find(\n ([, value]) => value === channel,\n )?.[0] as SocialFeedRealtimeScope | undefined) ?? undefined;\n\nconst parseSocialFeedEvent = (data: unknown): SocialFeedEvent | undefined => {\n if (!isRecord(data)) {\n return undefined;\n }\n\n const feedItem = parseRealtimeFeedItem(data.data);\n if (\n data.version !== 1 ||\n data.kind !== 'feed-item' ||\n typeof data.eventId !== 'string' ||\n typeof data.feedItemId !== 'string' ||\n typeof data.revision !== 'number' ||\n typeof data.occurredAt !== 'string' ||\n feedItem === undefined\n ) {\n return undefined;\n }\n\n return { ...data, data: feedItem } as unknown as SocialFeedEvent;\n};\n\nconst parseSocialFeedEvents = (data: unknown): SocialFeedEvent[] => {\n const entries = Array.isArray(data) ? data : [data];\n\n return entries\n .map((entry) => parseSocialFeedEvent(entry))\n .filter((event): event is SocialFeedEvent => event !== undefined);\n};\n\n/**\n * Social realtime subscription service built on the shared backend WebSocket.\n *\n * Clients explicitly select one or more global feed scopes. Additional Social\n * channels can be added here without creating another WebSocket connection.\n */\nexport class SocialRealtimeService {\n readonly name = 'SocialRealtimeService' as const;\n\n readonly #messenger: BackendWebSocketServiceMessenger;\n\n readonly #listeners = new Set<SocialFeedEventListener>();\n\n readonly #reconnectListeners = new Set<SocialFeedReconnectListener>();\n\n readonly #isEnabled: () => boolean;\n\n #scopes: SocialFeedRealtimeScope[];\n\n #scopeUpdatePromise: Promise<void> | undefined;\n\n #active = false;\n\n #subscription: WebSocketSubscription | undefined;\n\n #subscriptionToken: symbol | undefined;\n\n #subscriptionPromise: Promise<void> | undefined;\n\n readonly #pendingUnsubscriptions = new Set<WebSocketSubscription>();\n\n #connectionVersion = 0;\n\n #wasDisconnected = false;\n\n constructor({\n messenger,\n scopes,\n isEnabled = (): boolean => true,\n }: SocialRealtimeServiceOptions) {\n this.#messenger = messenger;\n this.#scopes = normalizeScopes(scopes);\n this.#isEnabled = isEnabled;\n\n this.#messenger.subscribe(\n 'BackendWebSocketService:connectionStateChanged',\n ({ state }: { state: WebSocketState }): void => {\n if (state === WebSocketState.DISCONNECTED) {\n this.#connectionVersion += 1;\n this.#subscription = undefined;\n this.#subscriptionToken = undefined;\n this.#wasDisconnected = true;\n }\n\n if (state === WebSocketState.CONNECTED && this.#active) {\n const isReconnect = this.#wasDisconnected;\n this.#wasDisconnected = false;\n // eslint-disable-next-line no-void\n void this.#subscribeToFeed()\n .then(() => {\n if (isReconnect) {\n this.#reconnectListeners.forEach((listener) => listener());\n }\n })\n .catch(() => undefined);\n }\n },\n );\n }\n\n addListener(listener: SocialFeedEventListener): () => void {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n\n addReconnectListener(listener: SocialFeedReconnectListener): () => void {\n this.#reconnectListeners.add(listener);\n return () => this.#reconnectListeners.delete(listener);\n }\n\n async setScopes(scopes: readonly SocialFeedRealtimeScope[]): Promise<void> {\n const normalizedScopes = normalizeScopes(scopes);\n\n const scopeUpdate = this.#scopeUpdatePromise\n ? this.#scopeUpdatePromise\n .catch(() => undefined)\n .then(() => this.#applyScopes(normalizedScopes))\n : this.#applyScopes(normalizedScopes);\n this.#scopeUpdatePromise = scopeUpdate;\n\n try {\n await scopeUpdate;\n } finally {\n if (this.#scopeUpdatePromise === scopeUpdate) {\n this.#scopeUpdatePromise = Promise.resolve();\n }\n }\n }\n\n async #applyScopes(\n normalizedScopes: SocialFeedRealtimeScope[],\n ): Promise<void> {\n if (!this.#active) {\n this.#scopes = normalizedScopes;\n return;\n }\n\n const previousScopes = this.#scopes;\n const connectionVersion = this.#connectionVersion;\n this.#scopes = normalizedScopes;\n\n try {\n await this.#resubscribeToFeed();\n } catch (error) {\n if (\n this.#active &&\n this.#connectionVersion === connectionVersion &&\n this.#subscription\n ) {\n this.#scopes = previousScopes;\n }\n throw error;\n }\n }\n\n async setActive(active: boolean): Promise<void> {\n this.#active = active && this.#isEnabled();\n\n if (!this.#active) {\n await this.#unsubscribeFromFeed();\n return;\n }\n\n await this.#retryPendingUnsubscriptions();\n await this.#subscribeToFeed();\n }\n\n async #subscribeToFeed(): Promise<void> {\n if (!this.#active || this.#subscription) {\n return;\n }\n\n while (this.#subscriptionPromise) {\n await this.#subscriptionPromise;\n\n if (!this.#active || this.#subscription) {\n return;\n }\n }\n\n const subscriptionPromise = Promise.resolve().then(\n async (): Promise<void> => {\n await this.#messenger.call('BackendWebSocketService:connect');\n\n const subscriptionToken = Symbol('social-feed-subscription');\n\n // Each service needs its own callback and subscription lifecycle.\n const subscription = await this.#messenger.call(\n 'BackendWebSocketService:subscribe',\n {\n channels: this.#scopes.map((scope) => SOCIAL_FEED_CHANNELS[scope]),\n channelType: SOCIAL_FEED_CHANNEL_TYPE,\n callback: (notification: ServerNotificationMessage) => {\n if (this.#subscriptionToken !== subscriptionToken) {\n return;\n }\n this.#handleNotification(notification);\n },\n },\n );\n\n if (!this.#active) {\n await subscription.unsubscribe();\n return;\n }\n\n this.#subscription = subscription;\n this.#subscriptionToken = subscriptionToken;\n },\n );\n this.#subscriptionPromise = subscriptionPromise;\n\n try {\n await subscriptionPromise;\n } finally {\n this.#subscriptionPromise = undefined;\n }\n }\n\n async #resubscribeToFeed(): Promise<void> {\n while (this.#subscriptionPromise) {\n await this.#subscriptionPromise;\n }\n\n await this.#retryPendingUnsubscriptions();\n\n const existingSubscription = this.#subscription;\n const existingSubscriptionToken = this.#subscriptionToken;\n const connectionVersion = this.#connectionVersion;\n this.#subscription = undefined;\n\n try {\n await this.#subscribeToFeed();\n } catch (error) {\n if (this.#active && this.#connectionVersion === connectionVersion) {\n this.#subscription = existingSubscription;\n this.#subscriptionToken = existingSubscriptionToken;\n } else {\n this.#subscription = undefined;\n this.#subscriptionToken = undefined;\n\n if (existingSubscription) {\n try {\n await existingSubscription.unsubscribe();\n } catch {\n this.#pendingUnsubscriptions.add(existingSubscription);\n }\n }\n }\n throw error;\n }\n\n const replacementSubscription = this.#subscription as\n | WebSocketSubscription\n | undefined;\n if (existingSubscription && existingSubscription !== this.#subscription) {\n try {\n await existingSubscription.unsubscribe();\n } catch (error) {\n if (this.#active && this.#connectionVersion === connectionVersion) {\n this.#subscription = existingSubscription;\n this.#subscriptionToken = existingSubscriptionToken;\n } else {\n this.#subscription = undefined;\n this.#subscriptionToken = undefined;\n this.#pendingUnsubscriptions.add(existingSubscription);\n }\n\n if (replacementSubscription) {\n try {\n await replacementSubscription.unsubscribe();\n } catch {\n this.#pendingUnsubscriptions.add(replacementSubscription);\n }\n }\n\n throw error;\n }\n }\n }\n\n async #unsubscribeFromFeed(): Promise<void> {\n const subscription = this.#subscription;\n this.#subscription = undefined;\n this.#subscriptionToken = undefined;\n\n try {\n if (subscription) {\n await subscription.unsubscribe();\n }\n } finally {\n await this.#retryPendingUnsubscriptions();\n }\n }\n\n async #retryPendingUnsubscriptions(): Promise<void> {\n for (const subscription of this.#pendingUnsubscriptions) {\n try {\n await subscription.unsubscribe();\n this.#pendingUnsubscriptions.delete(subscription);\n } catch {\n // Keep the subscription queued for a later cleanup attempt.\n }\n }\n }\n\n #handleNotification(notification: ServerNotificationMessage): void {\n const scope = scopeForChannel(notification.channel);\n if (!scope || !this.#scopes.includes(scope)) {\n return;\n }\n\n parseSocialFeedEvents(notification.data).forEach((event) => {\n this.#listeners.forEach((listener) => listener(event, scope));\n });\n }\n}\n"]}
1
+ {"version":3,"file":"SocialRealtimeService.js","sourceRoot":"","sources":["../src/SocialRealtimeService.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC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I,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YAC5C,OAAO;QACT,CAAC;QAED,qBAAqB,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;YACzD,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;QAChE,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { WebSocketState } from '@metamask/core-backend';\nimport type {\n BackendWebSocketServiceMessenger,\n ServerNotificationMessage,\n WebSocketSubscription,\n} from '@metamask/core-backend';\n\nimport { parseRealtimeFeedItem } from './realtime-feed-item.js';\nimport type { RealtimeFeedEventData } from './realtime-feed-item.js';\n\nexport const SOCIAL_FEED_CHANNELS = {\n all: 'social.v1.feed.all',\n trending: 'social.v1.feed.trending',\n} as const;\n\nexport type SocialFeedRealtimeScope = keyof typeof SOCIAL_FEED_CHANNELS;\n\nexport const SOCIAL_FEED_CHANNEL_TYPE = 'social.v1' as const;\n\nexport type SocialFeedEvent = {\n version: 1;\n kind: 'feed-item';\n eventId: string;\n feedItemId: string;\n revision: number;\n occurredAt: string;\n data: RealtimeFeedEventData;\n};\n\nexport type SocialFeedEventListener = (\n event: SocialFeedEvent,\n scope: SocialFeedRealtimeScope,\n) => void;\nexport type SocialFeedReconnectListener = () => void;\n\nexport type SocialRealtimeServiceOptions = {\n messenger: BackendWebSocketServiceMessenger;\n scopes: readonly SocialFeedRealtimeScope[];\n isEnabled?: () => boolean;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null;\n\nconst normalizeScopes = (\n scopes: readonly SocialFeedRealtimeScope[],\n): SocialFeedRealtimeScope[] => {\n const normalized = [...new Set(scopes)];\n if (normalized.length === 0) {\n throw new Error('At least one Social feed scope is required');\n }\n return normalized;\n};\n\nconst haveSameScopes = (\n left: readonly SocialFeedRealtimeScope[],\n right: readonly SocialFeedRealtimeScope[],\n): boolean =>\n left.length === right.length && left.every((scope) => right.includes(scope));\n\nconst scopeForChannel = (\n channel: string,\n): SocialFeedRealtimeScope | undefined =>\n (Object.entries(SOCIAL_FEED_CHANNELS).find(\n ([, value]) => value === channel,\n )?.[0] as SocialFeedRealtimeScope | undefined) ?? undefined;\n\nconst parseSocialFeedEvent = (data: unknown): SocialFeedEvent | undefined => {\n if (!isRecord(data)) {\n return undefined;\n }\n\n const feedItem = parseRealtimeFeedItem(data.data);\n if (\n data.version !== 1 ||\n data.kind !== 'feed-item' ||\n typeof data.eventId !== 'string' ||\n typeof data.feedItemId !== 'string' ||\n typeof data.revision !== 'number' ||\n typeof data.occurredAt !== 'string' ||\n feedItem === undefined\n ) {\n return undefined;\n }\n\n return { ...data, data: feedItem } as unknown as SocialFeedEvent;\n};\n\nconst parseSocialFeedEvents = (data: unknown): SocialFeedEvent[] => {\n const entries = Array.isArray(data) ? data : [data];\n\n return entries\n .map((entry) => parseSocialFeedEvent(entry))\n .filter((event): event is SocialFeedEvent => event !== undefined);\n};\n\n/**\n * Social realtime subscription service built on the shared backend WebSocket.\n *\n * Clients explicitly select one or more global feed scopes. Additional Social\n * channels can be added here without creating another WebSocket connection.\n */\nexport class SocialRealtimeService {\n readonly name = 'SocialRealtimeService' as const;\n\n readonly #messenger: BackendWebSocketServiceMessenger;\n\n readonly #listeners = new Set<SocialFeedEventListener>();\n\n readonly #reconnectListeners = new Set<SocialFeedReconnectListener>();\n\n readonly #isEnabled: () => boolean;\n\n #scopes: SocialFeedRealtimeScope[];\n\n #scopeUpdatePromise: Promise<void> | undefined;\n\n #active = false;\n\n #subscription: WebSocketSubscription | undefined;\n\n #subscriptionToken: symbol | undefined;\n\n #subscriptionPromise: Promise<void> | undefined;\n\n readonly #pendingUnsubscriptions = new Set<WebSocketSubscription>();\n\n #connectionVersion = 0;\n\n #wasDisconnected = false;\n\n constructor({\n messenger,\n scopes,\n isEnabled = (): boolean => true,\n }: SocialRealtimeServiceOptions) {\n this.#messenger = messenger;\n this.#scopes = normalizeScopes(scopes);\n this.#isEnabled = isEnabled;\n\n this.#messenger.subscribe(\n 'BackendWebSocketService:connectionStateChanged',\n ({ state }: { state: WebSocketState }): void => {\n if (state === WebSocketState.DISCONNECTED) {\n this.#connectionVersion += 1;\n this.#subscription = undefined;\n this.#subscriptionToken = undefined;\n this.#wasDisconnected = true;\n }\n\n if (state === WebSocketState.CONNECTED && this.#active) {\n const isReconnect = this.#wasDisconnected;\n this.#wasDisconnected = false;\n // eslint-disable-next-line no-void\n void this.#subscribeToFeed()\n .then(() => {\n if (isReconnect) {\n this.#reconnectListeners.forEach((listener) => listener());\n }\n })\n .catch(() => undefined);\n }\n },\n );\n }\n\n addListener(listener: SocialFeedEventListener): () => void {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n\n addReconnectListener(listener: SocialFeedReconnectListener): () => void {\n this.#reconnectListeners.add(listener);\n return () => this.#reconnectListeners.delete(listener);\n }\n\n async setScopes(scopes: readonly SocialFeedRealtimeScope[]): Promise<void> {\n const normalizedScopes = normalizeScopes(scopes);\n\n const scopeUpdate = this.#scopeUpdatePromise\n ? this.#scopeUpdatePromise\n .catch(() => undefined)\n .then(() => this.#applyScopes(normalizedScopes))\n : this.#applyScopes(normalizedScopes);\n this.#scopeUpdatePromise = scopeUpdate;\n\n try {\n await scopeUpdate;\n } finally {\n if (this.#scopeUpdatePromise === scopeUpdate) {\n this.#scopeUpdatePromise = Promise.resolve();\n }\n }\n }\n\n async #applyScopes(\n normalizedScopes: SocialFeedRealtimeScope[],\n ): Promise<void> {\n if (!this.#active) {\n this.#scopes = normalizedScopes;\n return;\n }\n\n if (this.#subscription && haveSameScopes(this.#scopes, normalizedScopes)) {\n return;\n }\n\n const previousScopes = this.#scopes;\n const connectionVersion = this.#connectionVersion;\n this.#scopes = normalizedScopes;\n\n try {\n await this.#resubscribeToFeed();\n } catch (error) {\n if (\n this.#active &&\n this.#connectionVersion === connectionVersion &&\n this.#subscription\n ) {\n this.#scopes = previousScopes;\n }\n throw error;\n }\n }\n\n async setActive(active: boolean): Promise<void> {\n this.#active = active && this.#isEnabled();\n\n if (!this.#active) {\n await this.#unsubscribeFromFeed();\n return;\n }\n\n await this.#retryPendingUnsubscriptions();\n await this.#subscribeToFeed();\n }\n\n async #subscribeToFeed(): Promise<void> {\n if (!this.#active || this.#subscription) {\n return;\n }\n\n while (this.#subscriptionPromise) {\n await this.#subscriptionPromise;\n\n if (!this.#active || this.#subscription) {\n return;\n }\n }\n\n const subscriptionPromise = Promise.resolve().then(\n async (): Promise<void> => {\n await this.#messenger.call('BackendWebSocketService:connect');\n\n const subscriptionToken = Symbol('social-feed-subscription');\n\n // Each service needs its own callback and subscription lifecycle.\n const subscription = await this.#messenger.call(\n 'BackendWebSocketService:subscribe',\n {\n channels: this.#scopes.map((scope) => SOCIAL_FEED_CHANNELS[scope]),\n channelType: SOCIAL_FEED_CHANNEL_TYPE,\n callback: (notification: ServerNotificationMessage) => {\n if (this.#subscriptionToken !== subscriptionToken) {\n return;\n }\n this.#handleNotification(notification);\n },\n },\n );\n\n if (!this.#active) {\n await subscription.unsubscribe();\n return;\n }\n\n this.#subscription = subscription;\n this.#subscriptionToken = subscriptionToken;\n },\n );\n this.#subscriptionPromise = subscriptionPromise;\n\n try {\n await subscriptionPromise;\n } finally {\n this.#subscriptionPromise = undefined;\n }\n }\n\n async #resubscribeToFeed(): Promise<void> {\n while (this.#subscriptionPromise) {\n await this.#subscriptionPromise;\n }\n\n await this.#retryPendingUnsubscriptions();\n\n const existingSubscription = this.#subscription;\n const existingSubscriptionToken = this.#subscriptionToken;\n const connectionVersion = this.#connectionVersion;\n this.#subscription = undefined;\n\n try {\n await this.#subscribeToFeed();\n } catch (error) {\n if (this.#active && this.#connectionVersion === connectionVersion) {\n this.#subscription = existingSubscription;\n this.#subscriptionToken = existingSubscriptionToken;\n } else {\n this.#subscription = undefined;\n this.#subscriptionToken = undefined;\n\n if (existingSubscription) {\n try {\n await existingSubscription.unsubscribe();\n } catch {\n this.#pendingUnsubscriptions.add(existingSubscription);\n }\n }\n }\n throw error;\n }\n\n const replacementSubscription = this.#subscription as\n | WebSocketSubscription\n | undefined;\n // The backend answers a repeat subscribe to the same channels with the same\n // subscription id. Unsubscribing the old handle would end the replacement.\n if (\n existingSubscription &&\n existingSubscription !== this.#subscription &&\n existingSubscription.subscriptionId !==\n replacementSubscription?.subscriptionId\n ) {\n try {\n await existingSubscription.unsubscribe();\n } catch (error) {\n if (this.#active && this.#connectionVersion === connectionVersion) {\n this.#subscription = existingSubscription;\n this.#subscriptionToken = existingSubscriptionToken;\n } else {\n this.#subscription = undefined;\n this.#subscriptionToken = undefined;\n this.#pendingUnsubscriptions.add(existingSubscription);\n }\n\n if (replacementSubscription) {\n try {\n await replacementSubscription.unsubscribe();\n } catch {\n this.#pendingUnsubscriptions.add(replacementSubscription);\n }\n }\n\n throw error;\n }\n }\n }\n\n async #unsubscribeFromFeed(): Promise<void> {\n const subscription = this.#subscription;\n this.#subscription = undefined;\n this.#subscriptionToken = undefined;\n\n try {\n if (subscription) {\n await subscription.unsubscribe();\n }\n } finally {\n await this.#retryPendingUnsubscriptions();\n }\n }\n\n async #retryPendingUnsubscriptions(): Promise<void> {\n for (const subscription of this.#pendingUnsubscriptions) {\n try {\n await subscription.unsubscribe();\n this.#pendingUnsubscriptions.delete(subscription);\n } catch {\n // Keep the subscription queued for a later cleanup attempt.\n }\n }\n }\n\n #handleNotification(notification: ServerNotificationMessage): void {\n const scope = scopeForChannel(notification.channel);\n if (!scope || !this.#scopes.includes(scope)) {\n return;\n }\n\n parseSocialFeedEvents(notification.data).forEach((event) => {\n this.#listeners.forEach((listener) => listener(event, scope));\n });\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"realtime-feed-item.d.ts","sourceRoot":"","sources":["../src/realtime-feed-item.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAEV,QAAQ,EAIT,MAAM,mBAAmB,CAAC;AA0F3B,MAAM,MAAM,qBAAqB,GAAG,QAAQ,CAAC;AAqG7C,eAAO,MAAM,yBAAyB,UAC7B,OAAO,KACb,QAAQ,GAAG,SAiDb,CAAC;AAEF,eAAO,MAAM,qBAAqB,UACzB,OAAO,KACb,qBAAqB,GAAG,SAO1B,CAAC"}
1
+ {"version":3,"file":"realtime-feed-item.d.ts","sourceRoot":"","sources":["../src/realtime-feed-item.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAEV,QAAQ,EAIT,MAAM,mBAAmB,CAAC;AAgH3B,MAAM,MAAM,qBAAqB,GAAG,QAAQ,CAAC;AAqG7C,eAAO,MAAM,yBAAyB,UAC7B,OAAO,KACb,QAAQ,GAAG,SAkDb,CAAC;AAEF,eAAO,MAAM,qBAAqB,UACzB,OAAO,KACb,qBAAqB,GAAG,SAO1B,CAAC"}
@@ -77,7 +77,20 @@ const RawHydratedPositionStruct = structType({
77
77
  entryPriceUsd: optional(nullable(number())),
78
78
  authorComment: optional(nullable(AuthorCommentStruct)),
79
79
  flags: optional(nullable(array(string()))),
80
+ currentValueUSD: optional(nullable(number())),
81
+ positionValueUSD: optional(nullable(number())),
82
+ pnlValueUsd: optional(nullable(number())),
83
+ pnlPercent: optional(nullable(number())),
80
84
  });
85
+ const PRICED_KEYS = [
86
+ 'currentValueUSD',
87
+ 'positionValueUSD',
88
+ 'pnlValueUsd',
89
+ 'pnlPercent',
90
+ ];
91
+ // The server prices the card when it publishes it. A field it did not send
92
+ // stays absent, so the client keeps using its own live price for it.
93
+ const toPricedFields = (value) => Object.fromEntries(PRICED_KEYS.flatMap((key) => value[key] === undefined ? [] : [[key, value[key]]]));
81
94
  const readNumber = (value) => typeof value === 'number' && Number.isFinite(value) ? value : undefined;
82
95
  const readNullableNumber = (value) => readNumber(value) ?? null;
83
96
  const addNullableNumbers = (left, right) => (left === null || right === null ? null : left + right);
@@ -178,6 +191,7 @@ export const normalizeRealtimeFeedItem = (value) => {
178
191
  // `flags` lives on the hydrated card, beside `metadata`. The server does
179
192
  // not set `metadata.flags`.
180
193
  ...(value.flags === undefined ? {} : { flags: value.flags }),
194
+ ...toPricedFields(value),
181
195
  };
182
196
  };
183
197
  export const parseRealtimeFeedItem = (value) => {
@@ -1 +1 @@
1
- {"version":3,"file":"realtime-feed-item.js","sourceRoot":"","sources":["../src/realtime-feed-item.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,MAAM,EACN,OAAO,EACP,KAAK,EACL,EAAE,EACF,OAAO,EACP,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,MAAM,EACN,MAAM,EACN,IAAI,IAAI,UAAU,EAClB,OAAO,IAAI,aAAa,GACzB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAQ1D,OAAO,EACL,mBAAmB,EACnB,uBAAuB,EACvB,cAAc,GACf,MAAM,cAAc,CAAC;AAEtB,MAAM,qBAAqB,GAAG,UAAU,CAAC;IACvC,GAAG,EAAE,MAAM,EAAE;IACb,WAAW,EAAE,MAAM,EAAE;IACrB,SAAS,EAAE,MAAM,EAAE;IACnB,cAAc,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;IAC5C,YAAY,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;IAClD,OAAO,EAAE,uBAAuB;IAChC,OAAO,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa,EAAE,CAAC,CAAC;CAC1C,CAAC,CAAC;AAEH,MAAM,cAAc,GAAG,MAAM,CAC3B,UAAU,CAAC;IACT,WAAW,EAAE,MAAM,EAAE;IACrB,OAAO,EAAE,MAAM,EAAE;IACjB,SAAS,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC;IAC7B,SAAS,EAAE,MAAM,EAAE;IACnB,eAAe,EAAE,MAAM,EAAE;IACzB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,CAAC,CAAC,EAAE,aAAa,EAAE,KAAK,CAAC,aAAa,EAAE,CAAC;QAC3C,YAAY,EAAE,KAAK,CAAC,OAAO,CAAC,YAAY;QACxC,UAAU,EAAE,KAAK,CAAC,OAAO,CAAC,UAAU;QACpC,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC,SAAS,IAAI,CAAC;QACvC,YAAY,EAAE,KAAK,CAAC,YAAY,IAAI,IAAI;QACxC,UAAU,EAAE,KAAK,CAAC,UAAU,IAAI,IAAI;QACpC,aAAa,EAAE,KAAK,CAAC,aAAa,IAAI,IAAI;QAC1C,yEAAyE;QACzE,4BAA4B;QAC5B,GAAG,CAAC,KAAK,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC;KAC7D,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACnC,KAAc,EACqB,EAAE;IACrC,MAAM,UAAU,GAAG,yBAAyB,CAAC,KAAK,CAAC,CAAC;IACpD,IAAI,UAAU,EAAE,CAAC;QACf,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,OAAO,4BAA4B,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACjE,CAAC,CAAC","sourcesContent":["import {\n array,\n assign,\n boolean,\n enums,\n is,\n literal,\n nullable,\n number,\n optional,\n record,\n string,\n type as structType,\n unknown as unknownStruct,\n} from '@metamask/superstruct';\n\nimport { ProfileIdentityStruct } from './social-types.js';\nimport type {\n AuthorComment,\n FeedItem,\n FeedActorSummary,\n ProfileIdentity,\n Trade,\n} from './social-types.js';\nimport {\n AuthorCommentStruct,\n CommentEngagementStruct,\n FeedItemStruct,\n} from './structs.js';\n\nconst RawTradeCommentStruct = structType({\n uid: string(),\n commentText: string(),\n timestamp: number(),\n sourceLanguage: optional(nullable(string())),\n translations: optional(record(string(), string())),\n metrics: CommentEngagementStruct,\n replies: optional(array(unknownStruct())),\n});\n\nconst RawTradeStruct = assign(\n structType({\n tokenAmount: number(),\n usdCost: number(),\n marketCap: nullable(number()),\n timestamp: number(),\n transactionHash: string(),\n direction: enums(['buy', 'sell']),\n classification: nullable(enums(['spot', 'perp', 'send', 'receive'])),\n intent: enums(['enter', 'exit']),\n perpPositionType: nullable(enums(['long', 'short'])),\n perpLeverage: nullable(number()),\n }),\n structType({\n comments: array(unknownStruct()),\n }),\n);\n\nconst RawHydratedPositionStruct = structType({\n itemId: string(),\n timestamp: number(),\n cardLatestTradeAt: number(),\n actor: structType({\n type: literal('user'),\n address: string(),\n name: string(),\n images: structType({\n raw: nullable(string()),\n xs: nullable(string()),\n sm: nullable(string()),\n }),\n profile: structType({\n id: string(),\n metadata: record(string(), unknownStruct()),\n ...ProfileIdentityStruct.schema,\n }),\n followerCount: optional(nullable(number())),\n }),\n metadata: structType({\n tokenChain: string(),\n tokenSymbol: string(),\n tokenName: string(),\n tokenAddress: string(),\n positionAmount: number(),\n positionStats: structType({\n boughtUSD: nullable(number()),\n soldUSD: nullable(number()),\n realizedGainsUSD: nullable(number()),\n holdingsCostBasisUSD: nullable(number()),\n receivedCostBasisUSD: nullable(number()),\n holdingReceivedCostBasisUSD: nullable(number()),\n isOpen: boolean(),\n }),\n trades: array(RawTradeStruct),\n perpPositionType: optional(nullable(enums(['long', 'short']))),\n perpLeverage: optional(nullable(number())),\n positionAmountWithLeverage: optional(nullable(number())),\n }),\n metrics: structType({\n reactions: array(unknownStruct()),\n userReaction: nullable(string()),\n commentCount: number(),\n replyCount: number(),\n copyCount: optional(nullable(number())),\n }),\n imageUrl: optional(nullable(string())),\n firstTradeAt: optional(nullable(number())),\n holdTimeMs: optional(nullable(number())),\n entryPriceUsd: optional(nullable(number())),\n authorComment: optional(nullable(AuthorCommentStruct)),\n flags: optional(nullable(array(string()))),\n});\n\nexport type RealtimeFeedEventData = FeedItem;\n\nconst readNumber = (value: unknown): number | undefined =>\n typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n\nconst readNullableNumber = (value: unknown): number | null =>\n readNumber(value) ?? null;\n\nconst addNullableNumbers = (\n left: number | null,\n right: number | null,\n): number | null => (left === null || right === null ? null : left + right);\n\nconst PROFILE_IDENTITY_KEYS = Object.keys(\n ProfileIdentityStruct.schema,\n) as (keyof ProfileIdentity)[];\n\n// Copies only the identity fields the socket payload sent, as the REST\n// payload omits the ones a profile has no value for.\nconst toIdentity = (profile: ProfileIdentity): ProfileIdentity =>\n Object.fromEntries(\n PROFILE_IDENTITY_KEYS.flatMap((key) =>\n profile[key] === undefined ? [] : [[key, profile[key]]],\n ),\n );\n\nconst toActor = (actor: {\n address: string;\n name: string;\n images: { raw: string | null; sm: string | null };\n profile: ProfileIdentity & { id: string; metadata: Record<string, unknown> };\n followerCount?: number | null;\n}): FeedActorSummary => ({\n profileId: actor.profile.id,\n address: actor.address,\n name: actor.name,\n imageUrl: actor.images.sm ?? actor.images.raw,\n ...toIdentity(actor.profile),\n winRate30d: readNullableNumber(actor.profile.metadata.winRate30d),\n pnl30d: readNullableNumber(actor.profile.metadata.pnl30d),\n volumeUsd30d: readNullableNumber(actor.profile.metadata.volumeUsd30d),\n volumeUsd7d: readNullableNumber(actor.profile.metadata.volumeUsd7d),\n tradeCount30d: readNullableNumber(actor.profile.metadata.tradeCount30d),\n ...(actor.followerCount === undefined\n ? {}\n : { followerCount: actor.followerCount }),\n});\n\n// Same mapping as social-api's `mapAuthorComment`, so a socket fill carries\n// the comments the REST payload would. Malformed entries are dropped.\nconst toTradeComments = (comments: unknown[]): AuthorComment[] =>\n comments.flatMap((comment) => {\n if (!is(comment, RawTradeCommentStruct)) {\n return [];\n }\n return [\n {\n uid: comment.uid,\n text: comment.commentText,\n timestamp: comment.timestamp,\n sourceLanguage: comment.sourceLanguage ?? null,\n translations: comment.translations ?? {},\n engagement: {\n reactions: comment.metrics.reactions,\n userReaction: comment.metrics.userReaction,\n replyCount: comment.replies?.length ?? 0,\n },\n },\n ];\n });\n\nconst toTrade = (trade: {\n direction: 'buy' | 'sell';\n intent: 'enter' | 'exit';\n classification: 'spot' | 'perp' | 'send' | 'receive' | null;\n perpPositionType: 'long' | 'short' | null;\n perpLeverage: number | null;\n tokenAmount: number;\n usdCost: number;\n marketCap: number | null;\n timestamp: number;\n transactionHash: string;\n comments: unknown[];\n}): Trade => ({\n direction: trade.direction,\n intent: trade.intent,\n ...(trade.classification === null ? {} : { category: trade.classification }),\n classification: trade.classification,\n perpPositionType: trade.perpPositionType,\n perpLeverage: trade.perpLeverage,\n tokenAmount: trade.tokenAmount,\n usdCost: trade.usdCost,\n marketCap: trade.marketCap,\n timestamp: trade.timestamp,\n transactionHash: trade.transactionHash,\n comments: toTradeComments(trade.comments),\n});\n\nconst isNormalizedRealtimeFeedItem = (value: unknown): value is FeedItem =>\n is(value, FeedItemStruct);\n\nexport const normalizeRealtimeFeedItem = (\n value: unknown,\n): FeedItem | undefined => {\n if (!is(value, RawHydratedPositionStruct)) {\n return undefined;\n }\n\n const stats = value.metadata.positionStats;\n const receivedCostBasis = stats.receivedCostBasisUSD;\n const holdingReceivedCostBasis = stats.holdingReceivedCostBasisUSD;\n\n return {\n positionId: value.itemId,\n tokenSymbol: value.metadata.tokenSymbol,\n tokenName: value.metadata.tokenName,\n tokenAddress: value.metadata.tokenAddress,\n chain: value.metadata.tokenChain,\n positionAmount: value.metadata.positionAmount,\n isOpen: stats.isOpen,\n boughtUsd: addNullableNumbers(stats.boughtUSD, receivedCostBasis),\n soldUsd: stats.soldUSD,\n realizedPnl: stats.realizedGainsUSD,\n costBasis: addNullableNumbers(\n stats.holdingsCostBasisUSD,\n holdingReceivedCostBasis,\n ),\n trades: value.metadata.trades.map(toTrade),\n lastTradeAt: value.cardLatestTradeAt,\n tokenImageUrl: value.imageUrl,\n perpPositionType: value.metadata.perpPositionType,\n perpLeverage: value.metadata.perpLeverage,\n positionAmountWithLeverage:\n value.metadata.positionAmountWithLeverage ?? null,\n actor: toActor(value.actor),\n timestamp: value.timestamp,\n // The socket payload carries the server's selected author comment. It is\n // passed through as sent: an absent field stays absent, an explicit null\n // stays null, and a malformed value already dropped the item above.\n ...(value.authorComment === undefined\n ? {}\n : { authorComment: value.authorComment }),\n commentCount: value.metrics.commentCount,\n replyCount: value.metrics.replyCount,\n copyCount: value.metrics.copyCount ?? 0,\n firstTradeAt: value.firstTradeAt ?? null,\n holdTimeMs: value.holdTimeMs ?? null,\n entryPriceUsd: value.entryPriceUsd ?? null,\n // `flags` lives on the hydrated card, beside `metadata`. The server does\n // not set `metadata.flags`.\n ...(value.flags === undefined ? {} : { flags: value.flags }),\n };\n};\n\nexport const parseRealtimeFeedItem = (\n value: unknown,\n): RealtimeFeedEventData | undefined => {\n const normalized = normalizeRealtimeFeedItem(value);\n if (normalized) {\n return normalized;\n }\n\n return isNormalizedRealtimeFeedItem(value) ? value : undefined;\n};\n"]}
1
+ {"version":3,"file":"realtime-feed-item.js","sourceRoot":"","sources":["../src/realtime-feed-item.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,MAAM,EACN,OAAO,EACP,KAAK,EACL,EAAE,EACF,OAAO,EACP,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,MAAM,EACN,MAAM,EACN,IAAI,IAAI,UAAU,EAClB,OAAO,IAAI,aAAa,GACzB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAQ1D,OAAO,EACL,mBAAmB,EACnB,uBAAuB,EACvB,cAAc,GACf,MAAM,cAAc,CAAC;AAEtB,MAAM,qBAAqB,GAAG,UAAU,CAAC;IACvC,GAAG,EAAE,MAAM,EAAE;IACb,WAAW,EAAE,MAAM,EAAE;IACrB,SAAS,EAAE,MAAM,EAAE;IACnB,cAAc,EAAE,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;IAC5C,YAAY,EAAE,QAAQ,CAAC,MA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,UAAU;QACpC,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC,SAAS,IAAI,CAAC;QACvC,YAAY,EAAE,KAAK,CAAC,YAAY,IAAI,IAAI;QACxC,UAAU,EAAE,KAAK,CAAC,UAAU,IAAI,IAAI;QACpC,aAAa,EAAE,KAAK,CAAC,aAAa,IAAI,IAAI;QAC1C,yEAAyE;QACzE,4BAA4B;QAC5B,GAAG,CAAC,KAAK,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC;QAC5D,GAAG,cAAc,CAAC,KAAK,CAAC;KACzB,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG,CACnC,KAAc,EACqB,EAAE;IACrC,MAAM,UAAU,GAAG,yBAAyB,CAAC,KAAK,CAAC,CAAC;IACpD,IAAI,UAAU,EAAE,CAAC;QACf,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,OAAO,4BAA4B,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACjE,CAAC,CAAC","sourcesContent":["import {\n array,\n assign,\n boolean,\n enums,\n is,\n literal,\n nullable,\n number,\n optional,\n record,\n string,\n type as structType,\n unknown as unknownStruct,\n} from '@metamask/superstruct';\n\nimport { ProfileIdentityStruct } from './social-types.js';\nimport type {\n AuthorComment,\n FeedItem,\n FeedActorSummary,\n ProfileIdentity,\n Trade,\n} from './social-types.js';\nimport {\n AuthorCommentStruct,\n CommentEngagementStruct,\n FeedItemStruct,\n} from './structs.js';\n\nconst RawTradeCommentStruct = structType({\n uid: string(),\n commentText: string(),\n timestamp: number(),\n sourceLanguage: optional(nullable(string())),\n translations: optional(record(string(), string())),\n metrics: CommentEngagementStruct,\n replies: optional(array(unknownStruct())),\n});\n\nconst RawTradeStruct = assign(\n structType({\n tokenAmount: number(),\n usdCost: number(),\n marketCap: nullable(number()),\n timestamp: number(),\n transactionHash: string(),\n direction: enums(['buy', 'sell']),\n classification: nullable(enums(['spot', 'perp', 'send', 'receive'])),\n intent: enums(['enter', 'exit']),\n perpPositionType: nullable(enums(['long', 'short'])),\n perpLeverage: nullable(number()),\n }),\n structType({\n comments: array(unknownStruct()),\n }),\n);\n\nconst RawHydratedPositionStruct = structType({\n itemId: string(),\n timestamp: number(),\n cardLatestTradeAt: number(),\n actor: structType({\n type: literal('user'),\n address: string(),\n name: string(),\n images: structType({\n raw: nullable(string()),\n xs: nullable(string()),\n sm: nullable(string()),\n }),\n profile: structType({\n id: string(),\n metadata: record(string(), unknownStruct()),\n ...ProfileIdentityStruct.schema,\n }),\n followerCount: optional(nullable(number())),\n }),\n metadata: structType({\n tokenChain: string(),\n tokenSymbol: string(),\n tokenName: string(),\n tokenAddress: string(),\n positionAmount: number(),\n positionStats: structType({\n boughtUSD: nullable(number()),\n soldUSD: nullable(number()),\n realizedGainsUSD: nullable(number()),\n holdingsCostBasisUSD: nullable(number()),\n receivedCostBasisUSD: nullable(number()),\n holdingReceivedCostBasisUSD: nullable(number()),\n isOpen: boolean(),\n }),\n trades: array(RawTradeStruct),\n perpPositionType: optional(nullable(enums(['long', 'short']))),\n perpLeverage: optional(nullable(number())),\n positionAmountWithLeverage: optional(nullable(number())),\n }),\n metrics: structType({\n reactions: array(unknownStruct()),\n userReaction: nullable(string()),\n commentCount: number(),\n replyCount: number(),\n copyCount: optional(nullable(number())),\n }),\n imageUrl: optional(nullable(string())),\n firstTradeAt: optional(nullable(number())),\n holdTimeMs: optional(nullable(number())),\n entryPriceUsd: optional(nullable(number())),\n authorComment: optional(nullable(AuthorCommentStruct)),\n flags: optional(nullable(array(string()))),\n currentValueUSD: optional(nullable(number())),\n positionValueUSD: optional(nullable(number())),\n pnlValueUsd: optional(nullable(number())),\n pnlPercent: optional(nullable(number())),\n});\n\nconst PRICED_KEYS = [\n 'currentValueUSD',\n 'positionValueUSD',\n 'pnlValueUsd',\n 'pnlPercent',\n] as const;\n\ntype PricedFields = Pick<FeedItem, (typeof PRICED_KEYS)[number]>;\n\n// The server prices the card when it publishes it. A field it did not send\n// stays absent, so the client keeps using its own live price for it.\nconst toPricedFields = (value: PricedFields): PricedFields =>\n Object.fromEntries(\n PRICED_KEYS.flatMap((key) =>\n value[key] === undefined ? [] : [[key, value[key]]],\n ),\n );\n\nexport type RealtimeFeedEventData = FeedItem;\n\nconst readNumber = (value: unknown): number | undefined =>\n typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n\nconst readNullableNumber = (value: unknown): number | null =>\n readNumber(value) ?? null;\n\nconst addNullableNumbers = (\n left: number | null,\n right: number | null,\n): number | null => (left === null || right === null ? null : left + right);\n\nconst PROFILE_IDENTITY_KEYS = Object.keys(\n ProfileIdentityStruct.schema,\n) as (keyof ProfileIdentity)[];\n\n// Copies only the identity fields the socket payload sent, as the REST\n// payload omits the ones a profile has no value for.\nconst toIdentity = (profile: ProfileIdentity): ProfileIdentity =>\n Object.fromEntries(\n PROFILE_IDENTITY_KEYS.flatMap((key) =>\n profile[key] === undefined ? [] : [[key, profile[key]]],\n ),\n );\n\nconst toActor = (actor: {\n address: string;\n name: string;\n images: { raw: string | null; sm: string | null };\n profile: ProfileIdentity & { id: string; metadata: Record<string, unknown> };\n followerCount?: number | null;\n}): FeedActorSummary => ({\n profileId: actor.profile.id,\n address: actor.address,\n name: actor.name,\n imageUrl: actor.images.sm ?? actor.images.raw,\n ...toIdentity(actor.profile),\n winRate30d: readNullableNumber(actor.profile.metadata.winRate30d),\n pnl30d: readNullableNumber(actor.profile.metadata.pnl30d),\n volumeUsd30d: readNullableNumber(actor.profile.metadata.volumeUsd30d),\n volumeUsd7d: readNullableNumber(actor.profile.metadata.volumeUsd7d),\n tradeCount30d: readNullableNumber(actor.profile.metadata.tradeCount30d),\n ...(actor.followerCount === undefined\n ? {}\n : { followerCount: actor.followerCount }),\n});\n\n// Same mapping as social-api's `mapAuthorComment`, so a socket fill carries\n// the comments the REST payload would. Malformed entries are dropped.\nconst toTradeComments = (comments: unknown[]): AuthorComment[] =>\n comments.flatMap((comment) => {\n if (!is(comment, RawTradeCommentStruct)) {\n return [];\n }\n return [\n {\n uid: comment.uid,\n text: comment.commentText,\n timestamp: comment.timestamp,\n sourceLanguage: comment.sourceLanguage ?? null,\n translations: comment.translations ?? {},\n engagement: {\n reactions: comment.metrics.reactions,\n userReaction: comment.metrics.userReaction,\n replyCount: comment.replies?.length ?? 0,\n },\n },\n ];\n });\n\nconst toTrade = (trade: {\n direction: 'buy' | 'sell';\n intent: 'enter' | 'exit';\n classification: 'spot' | 'perp' | 'send' | 'receive' | null;\n perpPositionType: 'long' | 'short' | null;\n perpLeverage: number | null;\n tokenAmount: number;\n usdCost: number;\n marketCap: number | null;\n timestamp: number;\n transactionHash: string;\n comments: unknown[];\n}): Trade => ({\n direction: trade.direction,\n intent: trade.intent,\n ...(trade.classification === null ? {} : { category: trade.classification }),\n classification: trade.classification,\n perpPositionType: trade.perpPositionType,\n perpLeverage: trade.perpLeverage,\n tokenAmount: trade.tokenAmount,\n usdCost: trade.usdCost,\n marketCap: trade.marketCap,\n timestamp: trade.timestamp,\n transactionHash: trade.transactionHash,\n comments: toTradeComments(trade.comments),\n});\n\nconst isNormalizedRealtimeFeedItem = (value: unknown): value is FeedItem =>\n is(value, FeedItemStruct);\n\nexport const normalizeRealtimeFeedItem = (\n value: unknown,\n): FeedItem | undefined => {\n if (!is(value, RawHydratedPositionStruct)) {\n return undefined;\n }\n\n const stats = value.metadata.positionStats;\n const receivedCostBasis = stats.receivedCostBasisUSD;\n const holdingReceivedCostBasis = stats.holdingReceivedCostBasisUSD;\n\n return {\n positionId: value.itemId,\n tokenSymbol: value.metadata.tokenSymbol,\n tokenName: value.metadata.tokenName,\n tokenAddress: value.metadata.tokenAddress,\n chain: value.metadata.tokenChain,\n positionAmount: value.metadata.positionAmount,\n isOpen: stats.isOpen,\n boughtUsd: addNullableNumbers(stats.boughtUSD, receivedCostBasis),\n soldUsd: stats.soldUSD,\n realizedPnl: stats.realizedGainsUSD,\n costBasis: addNullableNumbers(\n stats.holdingsCostBasisUSD,\n holdingReceivedCostBasis,\n ),\n trades: value.metadata.trades.map(toTrade),\n lastTradeAt: value.cardLatestTradeAt,\n tokenImageUrl: value.imageUrl,\n perpPositionType: value.metadata.perpPositionType,\n perpLeverage: value.metadata.perpLeverage,\n positionAmountWithLeverage:\n value.metadata.positionAmountWithLeverage ?? null,\n actor: toActor(value.actor),\n timestamp: value.timestamp,\n // The socket payload carries the server's selected author comment. It is\n // passed through as sent: an absent field stays absent, an explicit null\n // stays null, and a malformed value already dropped the item above.\n ...(value.authorComment === undefined\n ? {}\n : { authorComment: value.authorComment }),\n commentCount: value.metrics.commentCount,\n replyCount: value.metrics.replyCount,\n copyCount: value.metrics.copyCount ?? 0,\n firstTradeAt: value.firstTradeAt ?? null,\n holdTimeMs: value.holdTimeMs ?? null,\n entryPriceUsd: value.entryPriceUsd ?? null,\n // `flags` lives on the hydrated card, beside `metadata`. The server does\n // not set `metadata.flags`.\n ...(value.flags === undefined ? {} : { flags: value.flags }),\n ...toPricedFields(value),\n };\n};\n\nexport const parseRealtimeFeedItem = (\n value: unknown,\n): RealtimeFeedEventData | undefined => {\n const normalized = normalizeRealtimeFeedItem(value);\n if (normalized) {\n return normalized;\n }\n\n return isNormalizedRealtimeFeedItem(value) ? value : undefined;\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/social-controllers",
3
- "version": "3.20.0-preview-d853a918a",
3
+ "version": "3.21.0-preview-8e636eabf",
4
4
  "description": "A collection of social related controllers",
5
5
  "keywords": [
6
6
  "Ethereum",