@l.x/prices 1.0.3 → 1.0.5
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/.depcheckrc +14 -0
- package/.eslintrc.js +20 -0
- package/LICENSE +122 -0
- package/README.md +3 -0
- package/package.json +44 -1
- package/project.json +22 -0
- package/src/context/PriceServiceContext.test.tsx +63 -0
- package/src/context/PriceServiceContext.tsx +36 -0
- package/src/hooks/useConnectionStatus.ts +11 -0
- package/src/hooks/usePrice.ts +48 -0
- package/src/index.ts +45 -0
- package/src/queries/priceKeys.test.ts +23 -0
- package/src/queries/priceKeys.ts +6 -0
- package/src/queries/tokenPriceQueryOptions.ts +41 -0
- package/src/sources/rest/RestPriceBatcher.test.ts +223 -0
- package/src/sources/rest/RestPriceBatcher.ts +110 -0
- package/src/sources/rest/constants.ts +9 -0
- package/src/sources/rest/types.ts +13 -0
- package/src/sources/websocket/messageParser.ts +79 -0
- package/src/sources/websocket/subscriptionApi.ts +105 -0
- package/src/types.ts +96 -0
- package/src/utils/tokenIdentifier.test.ts +145 -0
- package/src/utils/tokenIdentifier.ts +111 -0
- package/tsconfig.json +35 -0
- package/tsconfig.lint.json +8 -0
- package/vitest.config.ts +22 -0
- package/index.d.ts +0 -1
- package/index.js +0 -1
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { BATCH_DELAY_MS, MAX_BATCH_SIZE } from '@l.x/prices/src/sources/rest/constants'
|
|
2
|
+
import { RestPriceBatcher } from '@l.x/prices/src/sources/rest/RestPriceBatcher'
|
|
3
|
+
import type { RestPriceClient } from '@l.x/prices/src/sources/rest/types'
|
|
4
|
+
import type { TokenPriceData } from '@l.x/prices/src/types'
|
|
5
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
6
|
+
|
|
7
|
+
function createMockClient(
|
|
8
|
+
handler: (tokens: { chainId: number; address: string }[]) => Promise<Map<string, TokenPriceData>>,
|
|
9
|
+
): RestPriceClient {
|
|
10
|
+
return { getTokenPrices: vi.fn(handler) }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function priceData(price: number, timestamp = Date.now()): TokenPriceData {
|
|
14
|
+
return { price, timestamp }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
describe('RestPriceBatcher', () => {
|
|
18
|
+
beforeEach(() => {
|
|
19
|
+
vi.useFakeTimers()
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
afterEach(() => {
|
|
23
|
+
vi.useRealTimers()
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('batches multiple fetch calls within the batching window', async () => {
|
|
27
|
+
const client = createMockClient(async (tokens) => {
|
|
28
|
+
const result = new Map<string, TokenPriceData>()
|
|
29
|
+
for (const t of tokens) {
|
|
30
|
+
result.set(`${t.chainId}-${t.address}`, priceData(100 + t.chainId))
|
|
31
|
+
}
|
|
32
|
+
return result
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
const batcher = new RestPriceBatcher(client)
|
|
36
|
+
|
|
37
|
+
// Fire multiple fetches synchronously (same batching window)
|
|
38
|
+
const p1 = batcher.fetch({ chainId: 1, address: '0xaaa' })
|
|
39
|
+
const p2 = batcher.fetch({ chainId: 42161, address: '0xbbb' })
|
|
40
|
+
|
|
41
|
+
// Advance past the batch delay to trigger flush
|
|
42
|
+
vi.advanceTimersByTime(BATCH_DELAY_MS)
|
|
43
|
+
|
|
44
|
+
const [r1, r2] = await Promise.all([p1, p2])
|
|
45
|
+
|
|
46
|
+
expect(r1).toEqual(priceData(101, r1!.timestamp))
|
|
47
|
+
expect(r2).toEqual(priceData(42261, r2!.timestamp))
|
|
48
|
+
expect(client.getTokenPrices).toHaveBeenCalledTimes(1)
|
|
49
|
+
expect(client.getTokenPrices).toHaveBeenCalledWith([
|
|
50
|
+
{ chainId: 1, address: '0xaaa' },
|
|
51
|
+
{ chainId: 42161, address: '0xbbb' },
|
|
52
|
+
])
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it('deduplicates tokens within the same batch', async () => {
|
|
56
|
+
const client = createMockClient(async (tokens) => {
|
|
57
|
+
const result = new Map<string, TokenPriceData>()
|
|
58
|
+
for (const t of tokens) {
|
|
59
|
+
result.set(`${t.chainId}-${t.address}`, priceData(50))
|
|
60
|
+
}
|
|
61
|
+
return result
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
const batcher = new RestPriceBatcher(client)
|
|
65
|
+
|
|
66
|
+
const p1 = batcher.fetch({ chainId: 1, address: '0xAAA' })
|
|
67
|
+
const p2 = batcher.fetch({ chainId: 1, address: '0xaaa' }) // Same after lowercase
|
|
68
|
+
|
|
69
|
+
vi.advanceTimersByTime(BATCH_DELAY_MS)
|
|
70
|
+
|
|
71
|
+
const [r1, r2] = await Promise.all([p1, p2])
|
|
72
|
+
|
|
73
|
+
expect(r1).toEqual(priceData(50, r1!.timestamp))
|
|
74
|
+
expect(r2).toEqual(priceData(50, r2!.timestamp))
|
|
75
|
+
// Only 1 unique token sent to the client
|
|
76
|
+
expect(client.getTokenPrices).toHaveBeenCalledWith([{ chainId: 1, address: '0xaaa' }])
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it('chunks large batches to respect MAX_BATCH_SIZE', async () => {
|
|
80
|
+
const client = createMockClient(async (tokens) => {
|
|
81
|
+
const result = new Map<string, TokenPriceData>()
|
|
82
|
+
for (const t of tokens) {
|
|
83
|
+
result.set(`${t.chainId}-${t.address}`, priceData(1))
|
|
84
|
+
}
|
|
85
|
+
return result
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
const batcher = new RestPriceBatcher(client)
|
|
89
|
+
|
|
90
|
+
// Create MAX_BATCH_SIZE + 10 unique tokens
|
|
91
|
+
const count = MAX_BATCH_SIZE + 10
|
|
92
|
+
const promises = Array.from({ length: count }, (_, i) =>
|
|
93
|
+
batcher.fetch({ chainId: 1, address: `0x${i.toString(16).padStart(40, '0')}` }),
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
vi.advanceTimersByTime(BATCH_DELAY_MS)
|
|
97
|
+
|
|
98
|
+
const results = await Promise.all(promises)
|
|
99
|
+
|
|
100
|
+
expect(results).toHaveLength(count)
|
|
101
|
+
expect(results.every((r) => r !== undefined)).toBe(true)
|
|
102
|
+
// Should have been split into 2 REST calls
|
|
103
|
+
expect(client.getTokenPrices).toHaveBeenCalledTimes(2)
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
it('propagates errors to all pending promises', async () => {
|
|
107
|
+
const error = new Error('network failure')
|
|
108
|
+
const client = createMockClient(async () => {
|
|
109
|
+
throw error
|
|
110
|
+
})
|
|
111
|
+
|
|
112
|
+
const batcher = new RestPriceBatcher(client)
|
|
113
|
+
|
|
114
|
+
const p1 = batcher.fetch({ chainId: 1, address: '0xaaa' })
|
|
115
|
+
const p2 = batcher.fetch({ chainId: 42161, address: '0xbbb' })
|
|
116
|
+
|
|
117
|
+
vi.advanceTimersByTime(BATCH_DELAY_MS)
|
|
118
|
+
|
|
119
|
+
await expect(p1).rejects.toThrow('network failure')
|
|
120
|
+
await expect(p2).rejects.toThrow('network failure')
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
it('returns undefined for tokens not in REST response', async () => {
|
|
124
|
+
const client = createMockClient(async () => {
|
|
125
|
+
// Return empty map (no prices available)
|
|
126
|
+
return new Map<string, TokenPriceData>()
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
const batcher = new RestPriceBatcher(client)
|
|
130
|
+
|
|
131
|
+
const promise = batcher.fetch({ chainId: 1, address: '0xaaa' })
|
|
132
|
+
|
|
133
|
+
vi.advanceTimersByTime(BATCH_DELAY_MS)
|
|
134
|
+
|
|
135
|
+
const result = await promise
|
|
136
|
+
|
|
137
|
+
expect(result).toBeUndefined()
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
it('processes sequential batches independently', async () => {
|
|
141
|
+
let callCount = 0
|
|
142
|
+
const client = createMockClient(async (tokens) => {
|
|
143
|
+
callCount++
|
|
144
|
+
const result = new Map<string, TokenPriceData>()
|
|
145
|
+
for (const t of tokens) {
|
|
146
|
+
result.set(`${t.chainId}-${t.address}`, priceData(callCount * 100))
|
|
147
|
+
}
|
|
148
|
+
return result
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
const batcher = new RestPriceBatcher(client)
|
|
152
|
+
|
|
153
|
+
// First batch
|
|
154
|
+
const p1 = batcher.fetch({ chainId: 1, address: '0xaaa' })
|
|
155
|
+
vi.advanceTimersByTime(BATCH_DELAY_MS)
|
|
156
|
+
const r1 = await p1
|
|
157
|
+
expect(r1?.price).toBe(100)
|
|
158
|
+
|
|
159
|
+
// Second batch (new timer window)
|
|
160
|
+
const p2 = batcher.fetch({ chainId: 1, address: '0xbbb' })
|
|
161
|
+
vi.advanceTimersByTime(BATCH_DELAY_MS)
|
|
162
|
+
const r2 = await p2
|
|
163
|
+
expect(r2?.price).toBe(200)
|
|
164
|
+
|
|
165
|
+
expect(client.getTokenPrices).toHaveBeenCalledTimes(2)
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
it('lowercases addresses for deduplication', async () => {
|
|
169
|
+
const client = createMockClient(async (tokens) => {
|
|
170
|
+
const result = new Map<string, TokenPriceData>()
|
|
171
|
+
for (const t of tokens) {
|
|
172
|
+
result.set(`${t.chainId}-${t.address}`, priceData(42))
|
|
173
|
+
}
|
|
174
|
+
return result
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
const batcher = new RestPriceBatcher(client)
|
|
178
|
+
|
|
179
|
+
const promise = batcher.fetch({ chainId: 1, address: '0xAbCdEf' })
|
|
180
|
+
|
|
181
|
+
vi.advanceTimersByTime(BATCH_DELAY_MS)
|
|
182
|
+
|
|
183
|
+
const result = await promise
|
|
184
|
+
|
|
185
|
+
expect(result?.price).toBe(42)
|
|
186
|
+
expect(client.getTokenPrices).toHaveBeenCalledWith([{ chainId: 1, address: '0xabcdef' }])
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
it('batches requests arriving in separate macrotasks within the delay window', async () => {
|
|
190
|
+
const client = createMockClient(async (tokens) => {
|
|
191
|
+
const result = new Map<string, TokenPriceData>()
|
|
192
|
+
for (const t of tokens) {
|
|
193
|
+
result.set(`${t.chainId}-${t.address}`, priceData(99))
|
|
194
|
+
}
|
|
195
|
+
return result
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
const batcher = new RestPriceBatcher(client)
|
|
199
|
+
|
|
200
|
+
// First request starts the timer
|
|
201
|
+
const p1 = batcher.fetch({ chainId: 1, address: '0xaaa' })
|
|
202
|
+
|
|
203
|
+
// Advance partway through the delay (simulating a second macrotask arriving)
|
|
204
|
+
vi.advanceTimersByTime(BATCH_DELAY_MS / 2)
|
|
205
|
+
|
|
206
|
+
// Second request arrives before the timer fires
|
|
207
|
+
const p2 = batcher.fetch({ chainId: 10, address: '0xbbb' })
|
|
208
|
+
|
|
209
|
+
// Now advance past the delay to flush
|
|
210
|
+
vi.advanceTimersByTime(BATCH_DELAY_MS)
|
|
211
|
+
|
|
212
|
+
const [r1, r2] = await Promise.all([p1, p2])
|
|
213
|
+
|
|
214
|
+
expect(r1?.price).toBe(99)
|
|
215
|
+
expect(r2?.price).toBe(99)
|
|
216
|
+
// Both should be in a single batch
|
|
217
|
+
expect(client.getTokenPrices).toHaveBeenCalledTimes(1)
|
|
218
|
+
expect(client.getTokenPrices).toHaveBeenCalledWith([
|
|
219
|
+
{ chainId: 1, address: '0xaaa' },
|
|
220
|
+
{ chainId: 10, address: '0xbbb' },
|
|
221
|
+
])
|
|
222
|
+
})
|
|
223
|
+
})
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { BATCH_DELAY_MS, MAX_BATCH_SIZE } from '@l.x/prices/src/sources/rest/constants'
|
|
2
|
+
import type { RestPriceClient } from '@l.x/prices/src/sources/rest/types'
|
|
3
|
+
import type { TokenIdentifier, TokenPriceData } from '@l.x/prices/src/types'
|
|
4
|
+
import { createPriceKey } from '@l.x/prices/src/utils/tokenIdentifier'
|
|
5
|
+
|
|
6
|
+
interface PendingRequest {
|
|
7
|
+
token: TokenIdentifier
|
|
8
|
+
resolve: (value: TokenPriceData | undefined) => void
|
|
9
|
+
reject: (error: unknown) => void
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Timer-based batcher for REST price fetches.
|
|
14
|
+
*
|
|
15
|
+
* Individual `fetch(token)` calls are coalesced into a single batch REST
|
|
16
|
+
* request within a short delay window (BATCH_DELAY_MS ≈ one frame). This
|
|
17
|
+
* ensures requests from separate macrotasks (e.g. React Query refetchInterval
|
|
18
|
+
* callbacks) are grouped together. Duplicate tokens share the same result.
|
|
19
|
+
* Batches exceeding MAX_BATCH_SIZE are chunked into parallel requests.
|
|
20
|
+
*/
|
|
21
|
+
export class RestPriceBatcher {
|
|
22
|
+
private readonly client: RestPriceClient
|
|
23
|
+
private pending: PendingRequest[] = []
|
|
24
|
+
private flushTimer: ReturnType<typeof setTimeout> | null = null
|
|
25
|
+
|
|
26
|
+
constructor(client: RestPriceClient) {
|
|
27
|
+
this.client = client
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Request a price for a single token. Multiple calls within the same
|
|
32
|
+
* batching window (BATCH_DELAY_MS) are batched into one REST request.
|
|
33
|
+
*
|
|
34
|
+
* @returns The price data, or undefined if the token has no price.
|
|
35
|
+
*/
|
|
36
|
+
fetch(token: TokenIdentifier): Promise<TokenPriceData | undefined> {
|
|
37
|
+
return new Promise<TokenPriceData | undefined>((resolve, reject) => {
|
|
38
|
+
this.pending.push({
|
|
39
|
+
token: { chainId: token.chainId, address: token.address.toLowerCase() },
|
|
40
|
+
resolve,
|
|
41
|
+
reject,
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
if (this.flushTimer === null) {
|
|
45
|
+
this.flushTimer = setTimeout(() => this.flush(), BATCH_DELAY_MS)
|
|
46
|
+
}
|
|
47
|
+
})
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
private async flush(): Promise<void> {
|
|
51
|
+
const batch = this.pending
|
|
52
|
+
this.pending = []
|
|
53
|
+
this.flushTimer = null
|
|
54
|
+
|
|
55
|
+
if (batch.length === 0) {
|
|
56
|
+
return
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Group resolvers by price key (deduplication)
|
|
60
|
+
const resolversByKey = new Map<string, PendingRequest[]>()
|
|
61
|
+
const uniqueTokens = new Map<string, TokenIdentifier>()
|
|
62
|
+
|
|
63
|
+
for (const request of batch) {
|
|
64
|
+
const key = createPriceKey(request.token.chainId, request.token.address)
|
|
65
|
+
const existing = resolversByKey.get(key)
|
|
66
|
+
if (existing) {
|
|
67
|
+
existing.push(request)
|
|
68
|
+
} else {
|
|
69
|
+
resolversByKey.set(key, [request])
|
|
70
|
+
uniqueTokens.set(key, request.token)
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const tokens = Array.from(uniqueTokens.values())
|
|
75
|
+
|
|
76
|
+
// Chunk into batches of MAX_BATCH_SIZE
|
|
77
|
+
const chunks: TokenIdentifier[][] = []
|
|
78
|
+
for (let i = 0; i < tokens.length; i += MAX_BATCH_SIZE) {
|
|
79
|
+
chunks.push(tokens.slice(i, i + MAX_BATCH_SIZE))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
try {
|
|
83
|
+
// Fetch all chunks in parallel
|
|
84
|
+
const results = await Promise.all(chunks.map((chunk) => this.client.getTokenPrices(chunk)))
|
|
85
|
+
|
|
86
|
+
// Merge all chunk results
|
|
87
|
+
const merged = new Map<string, TokenPriceData>()
|
|
88
|
+
for (const chunkResult of results) {
|
|
89
|
+
for (const [key, value] of chunkResult) {
|
|
90
|
+
merged.set(key, value)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Resolve all pending requests
|
|
95
|
+
for (const [key, requests] of resolversByKey) {
|
|
96
|
+
const data = merged.get(key)
|
|
97
|
+
for (const request of requests) {
|
|
98
|
+
request.resolve(data)
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
} catch (error) {
|
|
102
|
+
// On error, reject all pending promises (React Query retries individually)
|
|
103
|
+
for (const requests of resolversByKey.values()) {
|
|
104
|
+
for (const request of requests) {
|
|
105
|
+
request.reject(error)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** How often to poll REST as a fallback for fresh prices */
|
|
2
|
+
export const REST_POLL_INTERVAL_MS = 30_000
|
|
3
|
+
|
|
4
|
+
/** Maximum tokens per REST request (backend limit) */
|
|
5
|
+
export const MAX_BATCH_SIZE = 100
|
|
6
|
+
|
|
7
|
+
/** Delay before flushing a batch (~one frame). Allows requests from separate
|
|
8
|
+
* macrotasks (e.g. React Query refetchInterval callbacks) to be grouped. */
|
|
9
|
+
export const BATCH_DELAY_MS = 16
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { TokenIdentifier, TokenPriceData } from '@l.x/prices/src/types'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Contract for fetching token prices via REST.
|
|
5
|
+
* Implementations handle the actual transport (ConnectRPC, fetch, etc.).
|
|
6
|
+
*/
|
|
7
|
+
export interface RestPriceClient {
|
|
8
|
+
/**
|
|
9
|
+
* Fetches prices for a batch of tokens.
|
|
10
|
+
* @returns Map keyed by price key ("chainId-address"), missing tokens omitted.
|
|
11
|
+
*/
|
|
12
|
+
getTokenPrices(tokens: TokenIdentifier[]): Promise<Map<string, TokenPriceData>>
|
|
13
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { ConnectionEstablishedMessage, RawTokenPriceMessage, TokenPriceMessage } from '@l.x/prices/src/types'
|
|
2
|
+
import { createPriceKey } from '@l.x/prices/src/utils/tokenIdentifier'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Type guard for RawTokenPriceMessage
|
|
6
|
+
*/
|
|
7
|
+
export function isRawTokenPriceMessage(message: unknown): message is RawTokenPriceMessage {
|
|
8
|
+
return (
|
|
9
|
+
typeof message === 'object' &&
|
|
10
|
+
message !== null &&
|
|
11
|
+
'type' in message &&
|
|
12
|
+
message.type === 'token_price_update' &&
|
|
13
|
+
'payload' in message &&
|
|
14
|
+
typeof message.payload === 'object' &&
|
|
15
|
+
message.payload !== null
|
|
16
|
+
)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Type guard for ConnectionEstablishedMessage
|
|
21
|
+
*/
|
|
22
|
+
export function isConnectionEstablishedMessage(message: unknown): message is ConnectionEstablishedMessage {
|
|
23
|
+
return (
|
|
24
|
+
typeof message === 'object' &&
|
|
25
|
+
message !== null &&
|
|
26
|
+
'connectionEstablished' in message &&
|
|
27
|
+
typeof message.connectionEstablished === 'object' &&
|
|
28
|
+
message.connectionEstablished !== null &&
|
|
29
|
+
'connectionId' in message.connectionEstablished
|
|
30
|
+
)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Parses a raw WebSocket message into a typed price update.
|
|
35
|
+
* Returns null if the message is not a price update.
|
|
36
|
+
*
|
|
37
|
+
* Used both as the `parseMessage` config for createWebSocketClient
|
|
38
|
+
* and in the `onRawMessage` callback to write to React Query cache.
|
|
39
|
+
*/
|
|
40
|
+
export function parseTokenPriceMessage(raw: unknown): TokenPriceMessage | null {
|
|
41
|
+
if (!isRawTokenPriceMessage(raw)) {
|
|
42
|
+
return null
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const { chainId, tokenAddress, priceUsd } = raw.payload
|
|
46
|
+
const price = parseFloat(priceUsd)
|
|
47
|
+
|
|
48
|
+
if (Number.isNaN(price)) {
|
|
49
|
+
return null
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const timestamp = new Date(raw.timestamp).getTime()
|
|
53
|
+
const key = createPriceKey(chainId, tokenAddress)
|
|
54
|
+
|
|
55
|
+
return {
|
|
56
|
+
channel: 'token_price',
|
|
57
|
+
key,
|
|
58
|
+
data: {
|
|
59
|
+
chainId,
|
|
60
|
+
tokenAddress: tokenAddress.toLowerCase(),
|
|
61
|
+
priceUsd: price,
|
|
62
|
+
timestamp,
|
|
63
|
+
},
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Parses a raw WebSocket message for connection establishment.
|
|
69
|
+
* Returns null if the message is not a connection message.
|
|
70
|
+
*/
|
|
71
|
+
export function parseConnectionMessage(raw: unknown): { connectionId: string } | null {
|
|
72
|
+
if (!isConnectionEstablishedMessage(raw)) {
|
|
73
|
+
return null
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
connectionId: raw.connectionEstablished.connectionId,
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { FetchClient } from '@l.x/api'
|
|
2
|
+
import type { TokenSubscriptionParams } from '@l.x/prices/src/types'
|
|
3
|
+
import type { SubscriptionHandler } from '@l.x/websocket'
|
|
4
|
+
|
|
5
|
+
const EVENT_SUBSCRIPTION_TYPE_TOKEN_PRICE = 'EVENT_SUBSCRIPTION_TYPE_TOKEN_PRICE'
|
|
6
|
+
|
|
7
|
+
export interface SubscriptionApiOptions {
|
|
8
|
+
client: FetchClient
|
|
9
|
+
onError?: (error: unknown, operation: string) => void
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Creates a subscription handler for token price subscriptions.
|
|
14
|
+
* This implements the SubscriptionHandler interface from @l.x/websocket.
|
|
15
|
+
*/
|
|
16
|
+
export function createPriceSubscriptionHandler(
|
|
17
|
+
options: SubscriptionApiOptions,
|
|
18
|
+
): SubscriptionHandler<TokenSubscriptionParams> {
|
|
19
|
+
const { client, onError } = options
|
|
20
|
+
|
|
21
|
+
async function subscribe(connectionId: string, params: TokenSubscriptionParams): Promise<void> {
|
|
22
|
+
try {
|
|
23
|
+
await client.post('/lx.notificationservice.v1.EventSubscriptionService/Subscribe', {
|
|
24
|
+
body: JSON.stringify({
|
|
25
|
+
eventSubscriptionType: EVENT_SUBSCRIPTION_TYPE_TOKEN_PRICE,
|
|
26
|
+
connectionId,
|
|
27
|
+
events: [{ token: { chainId: params.chainId, tokenAddress: params.tokenAddress } }],
|
|
28
|
+
}),
|
|
29
|
+
})
|
|
30
|
+
} catch (error) {
|
|
31
|
+
onError?.(error, 'subscribe')
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function unsubscribe(connectionId: string, params: TokenSubscriptionParams): Promise<void> {
|
|
36
|
+
try {
|
|
37
|
+
await client.post('/lx.notificationservice.v1.EventSubscriptionService/Unsubscribe', {
|
|
38
|
+
body: JSON.stringify({
|
|
39
|
+
eventSubscriptionType: EVENT_SUBSCRIPTION_TYPE_TOKEN_PRICE,
|
|
40
|
+
connectionId,
|
|
41
|
+
events: [{ token: { chainId: params.chainId, tokenAddress: params.tokenAddress } }],
|
|
42
|
+
}),
|
|
43
|
+
})
|
|
44
|
+
} catch (error) {
|
|
45
|
+
onError?.(error, 'unsubscribe')
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function subscribeBatch(connectionId: string, paramsList: TokenSubscriptionParams[]): Promise<void> {
|
|
50
|
+
if (paramsList.length === 0) {
|
|
51
|
+
return
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
await client.post('/lx.notificationservice.v1.EventSubscriptionService/Subscribe', {
|
|
56
|
+
body: JSON.stringify({
|
|
57
|
+
eventSubscriptionType: EVENT_SUBSCRIPTION_TYPE_TOKEN_PRICE,
|
|
58
|
+
connectionId,
|
|
59
|
+
events: paramsList.map((p) => ({ token: { chainId: p.chainId, tokenAddress: p.tokenAddress } })),
|
|
60
|
+
}),
|
|
61
|
+
})
|
|
62
|
+
} catch (error) {
|
|
63
|
+
onError?.(error, 'subscribeBatch')
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function unsubscribeBatch(connectionId: string, paramsList: TokenSubscriptionParams[]): Promise<void> {
|
|
68
|
+
if (paramsList.length === 0) {
|
|
69
|
+
return
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
try {
|
|
73
|
+
await client.post('/lx.notificationservice.v1.EventSubscriptionService/Unsubscribe', {
|
|
74
|
+
body: JSON.stringify({
|
|
75
|
+
eventSubscriptionType: EVENT_SUBSCRIPTION_TYPE_TOKEN_PRICE,
|
|
76
|
+
connectionId,
|
|
77
|
+
events: paramsList.map((p) => ({ token: { chainId: p.chainId, tokenAddress: p.tokenAddress } })),
|
|
78
|
+
}),
|
|
79
|
+
})
|
|
80
|
+
} catch (error) {
|
|
81
|
+
onError?.(error, 'unsubscribeBatch')
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function refreshSession(connectionId: string): Promise<void> {
|
|
86
|
+
try {
|
|
87
|
+
await client.post('/lx.notificationservice.v1.EventSubscriptionService/RefreshSession', {
|
|
88
|
+
body: JSON.stringify({
|
|
89
|
+
eventSubscriptionType: EVENT_SUBSCRIPTION_TYPE_TOKEN_PRICE,
|
|
90
|
+
connectionId,
|
|
91
|
+
}),
|
|
92
|
+
})
|
|
93
|
+
} catch (error) {
|
|
94
|
+
onError?.(error, 'refreshSession')
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
subscribe,
|
|
100
|
+
unsubscribe,
|
|
101
|
+
subscribeBatch,
|
|
102
|
+
unsubscribeBatch,
|
|
103
|
+
refreshSession,
|
|
104
|
+
}
|
|
105
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { Currency } from '@luxamm/sdk-core'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A token identifier with chain and address.
|
|
5
|
+
* Can be used instead of a full Currency object.
|
|
6
|
+
*/
|
|
7
|
+
export interface TokenIdentifier {
|
|
8
|
+
chainId: number
|
|
9
|
+
address: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Token price data with timestamp.
|
|
14
|
+
*/
|
|
15
|
+
export interface TokenPrice {
|
|
16
|
+
price: number
|
|
17
|
+
timestamp: number
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Shape stored in the React Query cache for each token price.
|
|
22
|
+
*/
|
|
23
|
+
export interface TokenPriceData {
|
|
24
|
+
price: number
|
|
25
|
+
timestamp: number
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Key used to identify a token price in the store.
|
|
30
|
+
* Format: "chainId-address" (e.g., "1-0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2")
|
|
31
|
+
* Matches CurrencyId convention from lx/src/utils/currencyId.ts
|
|
32
|
+
*/
|
|
33
|
+
export type PriceKey = string
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Token identifier format used by the subscription API.
|
|
37
|
+
*/
|
|
38
|
+
export interface TokenSubscriptionParams {
|
|
39
|
+
chainId: number
|
|
40
|
+
tokenAddress: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Parsed WebSocket message for token price updates.
|
|
45
|
+
* Wraps channel, key, and the inner data payload.
|
|
46
|
+
*/
|
|
47
|
+
export interface TokenPriceMessage {
|
|
48
|
+
channel: string
|
|
49
|
+
key: string
|
|
50
|
+
data: {
|
|
51
|
+
chainId: number
|
|
52
|
+
tokenAddress: string
|
|
53
|
+
priceUsd: number
|
|
54
|
+
timestamp: number
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Raw WebSocket message format from server (strings, optional fields).
|
|
60
|
+
* Parsed into {@link TokenPriceMessage} by messageParser before app consumption.
|
|
61
|
+
*/
|
|
62
|
+
export interface RawTokenPriceMessage {
|
|
63
|
+
type: 'token_price_update'
|
|
64
|
+
payload: {
|
|
65
|
+
chainId: number
|
|
66
|
+
tokenAddress: string
|
|
67
|
+
priceUsd: string
|
|
68
|
+
symbol?: string
|
|
69
|
+
timestamp?: string
|
|
70
|
+
}
|
|
71
|
+
timestamp: string
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Connection established message from server.
|
|
76
|
+
*/
|
|
77
|
+
export interface ConnectionEstablishedMessage {
|
|
78
|
+
connectionEstablished: {
|
|
79
|
+
connectionId: string
|
|
80
|
+
timestamp: string
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Logger interface for optional logging.
|
|
86
|
+
*/
|
|
87
|
+
export interface Logger {
|
|
88
|
+
debug: (tag: string, context: string, message: string, data?: unknown) => void
|
|
89
|
+
warn: (tag: string, context: string, message: string, data?: unknown) => void
|
|
90
|
+
error: (tag: string, context: string, message: string, data?: unknown) => void
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Type guard input - any token that can provide chain and address.
|
|
95
|
+
*/
|
|
96
|
+
export type TokenInput = TokenIdentifier | Currency
|