@exodus/bitcoin-api 5.0.4 → 5.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/CHANGELOG.md CHANGED
@@ -3,6 +3,15 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [5.0.5](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.4...@exodus/bitcoin-api@5.0.5) (2026-10-06)
7
+
8
+
9
+ ### Bug Fixes
10
+
11
+ * **bitcoin-api:** throttle mempool requests and reuse websocket updates ([#8862](https://github.com/ExodusMovement/assets/issues/8862)) ([4ef88a6](https://github.com/ExodusMovement/assets/commit/4ef88a6f7ad895b60d2d758875c66f653acf2be5))
12
+
13
+
14
+
6
15
  ## [5.0.4](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.3...@exodus/bitcoin-api@5.0.4) (2026-09-28)
7
16
 
8
17
 
package/README.md CHANGED
@@ -2,10 +2,22 @@
2
2
 
3
3
  Transaction monitors, fee monitors, RPC with the blockchain node, and other networking code for Bitcoin and Bitcoin-like assets (e.g. dogecoin, litecoin, zcash). See [Asset Packages](../../docs/asset-packages.md) for more detail on this package's role.
4
4
 
5
+ ## Mempool WebSocket-assisted confirmation checks
6
+
7
+ Confirmation-only scans reuse WebSocket transaction statuses and block heights for ten seconds, with at most 1,000 statuses per client. Missing or expired hints fall back to `/api/tx/:txid/status` instead of full transaction/outspend reads. New or replacement blocks, disconnect, stop, and backend changes invalidate the caches; standalone confirmations require a fresh tip lookup. Full history, UTXO, address-event, and reconnect reconciliation remain unchanged, as do Insight-backed monitors.
8
+
9
+ Confirmation checks recheck their inputs if a WebSocket update, disconnect, or backend change arrives during a lookup. They retry once, then fail rather than return obsolete confirmations if invalidated again.
10
+
5
11
  ## Mempool Retry-After
6
12
 
7
- When a mempool REST request receives HTTP 429 with a valid future `Retry-After`, subsequent requests to the same origin fail locally until the cooldown expires. Each response's cooldown is capped at five minutes so a single excessive server value cannot lock out reads and sends indefinitely. Shorter delays are honored as supplied. The cooldown is shared across client instances within the application process and accepts both delay-seconds and HTTP-date headers, using the server's `Date` header when available to account for clock skew. Already-running requests are not cancelled, and cooldowns do not persist across application restarts.
13
+ Every HTTP 429 starts a process-local cooldown shared across clients and endpoints on the same origin. Valid `Retry-After` seconds or HTTP dates take precedence, using the server's `Date` header for clock skew when available, and are capped at five minutes. Missing or invalid values use a ten-second fallback; failed recovery doubles it with 0–20% positive jitter, also capped at five minutes. Concurrent responses from the original burst do not multiply backoff, but longer server deadlines are preserved.
14
+
15
+ The dispatched request fails with code `429`, `finalError`, bounded `retryAt`/`retryAfterMs`, and hint `mempoolRateLimited`; generic retries stop. Queued reads wait until one recovery read can run, with a ten-second timeout including its body. Success or an ordinary 404 releases the cooldown; other HTTP, transport, or body failures renew it. No recovery request is generated when the queue is empty.
16
+
17
+ ## Mempool request scheduling
18
+
19
+ At most two REST requests run concurrently, including body consumption, with at least 200 ms between starts. Reads queue FIFO, bounded to 100 entries and a 30-second wait including cooldown. Abort signals remove queued reads; expired or cancelled entries never dispatch later. Normal requests have a 30-second dispatch-time timeout including the body, respecting shorter caller timeouts. History scans submit two address batches at a time while retaining full address coverage; Insight concurrency is unchanged.
8
20
 
9
- These errors retain code `429` and expose the bounded `retryAt`, `retryAfterMs`, and the safe hint `mempoolRateLimited`. They stop the generic retry loop; reads resume on the next normal request after the deadline. A new 429 with a valid future `Retry-After` starts another bounded cooldown. The cap can allow requests earlier than the server requested and does not guarantee that the server will accept them. Broadcasts also fail immediately during the cooldown rather than being queued or retried later.
21
+ Broadcasts wait only for a short pacing interval (at most one second) when capacity is available and no request is queued. Busy, cooling, or recovering origins reject sends rather than retaining them for later broadcast. Queue overflow/expiry use `MEMPOOL_REQUEST_BUSY`/`MEMPOOL_REQUEST_QUEUE_TIMEOUT` with `finalError`. Broadcasts are never recovery probes, and dispatched broadcasts receiving 429 are not automatically replayed.
10
22
 
11
- Missing, malformed, zero, or expired `Retry-After` values keep the existing HTTP-error and retry behavior. This change does not add a fallback cooldown, concurrency limits, or backoff changes for other responses.
23
+ Recovery resumes paced traffic rather than a burst. This client budget is not a vendor quota and cannot guarantee freedom from rate limits or bans. The five-minute cap may permit requests earlier than the server requested; queues and cooldowns are not persisted or coordinated across processes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/bitcoin-api",
3
- "version": "5.0.4",
3
+ "version": "5.0.5",
4
4
  "description": "Bitcoin transaction and fee monitors, RPC with the blockchain node, other networking code.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -59,5 +59,5 @@
59
59
  "type": "git",
60
60
  "url": "git+https://github.com/ExodusMovement/assets.git"
61
61
  },
62
- "gitHead": "c24c69f957a347f7b0439d0a83814707aa840fd2"
62
+ "gitHead": "fb42d6502575a15419bff613b88aed10d2be8529"
63
63
  }
@@ -1,6 +1,10 @@
1
1
  const isPositiveTimeout = (timeout) => Number.isFinite(timeout) && timeout > 0
2
2
 
3
- export default async function fetchWithTimeout(url, fetchOptions) {
3
+ export default async function fetchWithTimeout(
4
+ url,
5
+ fetchOptions,
6
+ consumeResponse = (response) => response
7
+ ) {
4
8
  const { timeout, signal, ...restFetchOptions } = fetchOptions || Object.create(null)
5
9
  const hasFetchOptions = signal !== undefined || Object.keys(restFetchOptions).length > 0
6
10
  const normalizedFetchOptions = hasFetchOptions
@@ -10,7 +14,7 @@ export default async function fetchWithTimeout(url, fetchOptions) {
10
14
  : undefined
11
15
 
12
16
  if (!isPositiveTimeout(timeout) || typeof AbortController !== 'function') {
13
- return fetch(url, normalizedFetchOptions)
17
+ return consumeResponse(await fetch(url, normalizedFetchOptions))
14
18
  }
15
19
 
16
20
  const controller = new AbortController()
@@ -26,7 +30,9 @@ export default async function fetchWithTimeout(url, fetchOptions) {
26
30
  }
27
31
 
28
32
  try {
29
- return await fetch(url, { ...restFetchOptions, signal: controller.signal })
33
+ return await consumeResponse(
34
+ await fetch(url, { ...restFetchOptions, signal: controller.signal })
35
+ )
30
36
  } finally {
31
37
  clearTimeout(timeoutId)
32
38
  signal?.removeEventListener?.('abort', abort)
@@ -0,0 +1,121 @@
1
+ import { safeString } from '@exodus/safe-string'
2
+
3
+ const MAX_ACTIVE_REQUESTS = 2
4
+ const REQUEST_INTERVAL_MS = 200
5
+ const MAX_QUEUED_REQUESTS = 100
6
+ const MAX_QUEUE_WAIT_MS = 30_000
7
+ const schedulersByOrigin = new Map()
8
+
9
+ const createAbortError = (signal) => {
10
+ const error = new Error('request-aborted', { cause: signal.reason })
11
+ error.name = 'AbortError'
12
+ error.finalError = true
13
+ return error
14
+ }
15
+
16
+ const createQueueError = (code) => {
17
+ const error = new Error('mempool-api-request-busy')
18
+ error.code = code
19
+ error.hint = safeString`mempoolRequestBusy`
20
+ error.finalError = true
21
+ return error
22
+ }
23
+
24
+ const drain = (origin) => {
25
+ const scheduler = schedulersByOrigin.get(origin)
26
+ if (!scheduler) return
27
+ for (const entry of scheduler.queue.slice()) {
28
+ if (entry.expiresAt <= Date.now()) {
29
+ entry.cancel(createQueueError('MEMPOOL_REQUEST_QUEUE_TIMEOUT'))
30
+ }
31
+ }
32
+ clearTimeout(scheduler.wakeTimer)
33
+ scheduler.wakeTimer = null
34
+ const cooldown = scheduler.getCooldown?.()
35
+ if (scheduler.queue.length > 0 && cooldown?.retryAt > Date.now()) {
36
+ scheduler.wakeTimer = setTimeout(() => drain(origin), cooldown.retryAt - Date.now())
37
+ } else if (
38
+ scheduler.active < MAX_ACTIVE_REQUESTS &&
39
+ !scheduler.timer &&
40
+ !cooldown?.recovering &&
41
+ scheduler.queue.length > 0
42
+ ) {
43
+ const entry = scheduler.queue.shift()
44
+ entry.cleanup()
45
+ scheduler.active++
46
+ scheduler.timer = setTimeout(() => {
47
+ scheduler.timer = null
48
+ drain(origin)
49
+ }, REQUEST_INTERVAL_MS)
50
+ const run = async () => {
51
+ try {
52
+ entry.resolve(await entry.execute())
53
+ } catch (error) {
54
+ entry.reject(error)
55
+ } finally {
56
+ scheduler.active--
57
+ drain(origin)
58
+ }
59
+ }
60
+ void run()
61
+ }
62
+
63
+ if (scheduler.active === 0 && scheduler.queue.length === 0 && !scheduler.timer) {
64
+ schedulersByOrigin.delete(origin)
65
+ }
66
+ }
67
+
68
+ export const resumeMempoolRequests = (origin) => drain(origin)
69
+
70
+ export default function scheduleMempoolRequest(
71
+ origin,
72
+ execute,
73
+ { signal, isBroadcast, getCooldown } = {}
74
+ ) {
75
+ if (signal?.aborted) return Promise.reject(createAbortError(signal))
76
+ let scheduler = schedulersByOrigin.get(origin)
77
+ if (!scheduler) {
78
+ scheduler = { active: 0, timer: null, wakeTimer: null, queue: [], getCooldown }
79
+ schedulersByOrigin.set(origin, scheduler)
80
+ }
81
+
82
+ if (
83
+ scheduler.queue.length >= MAX_QUEUED_REQUESTS ||
84
+ (isBroadcast && (scheduler.active >= MAX_ACTIVE_REQUESTS || scheduler.queue.length > 0))
85
+ ) {
86
+ return Promise.reject(createQueueError('MEMPOOL_REQUEST_BUSY'))
87
+ }
88
+
89
+ return new Promise((resolve, reject) => {
90
+ const maxWaitMs = isBroadcast ? 1000 : MAX_QUEUE_WAIT_MS
91
+ const entry = {
92
+ execute,
93
+ resolve,
94
+ reject,
95
+ expiresAt: Date.now() + maxWaitMs,
96
+ cleanup: () => {
97
+ clearTimeout(timeout)
98
+ signal?.removeEventListener('abort', onAbort)
99
+ },
100
+ }
101
+ const cancel = (error) => {
102
+ const index = scheduler.queue.indexOf(entry)
103
+ if (index === -1) return
104
+ scheduler.queue.splice(index, 1)
105
+ entry.cleanup()
106
+ reject(error)
107
+ }
108
+ entry.cancel = cancel
109
+ const onAbort = () => {
110
+ cancel(createAbortError(signal))
111
+ drain(origin)
112
+ }
113
+ const timeout = setTimeout(() => {
114
+ cancel(createQueueError('MEMPOOL_REQUEST_QUEUE_TIMEOUT'))
115
+ drain(origin)
116
+ }, maxWaitMs)
117
+ signal?.addEventListener('abort', onAbort, { once: true })
118
+ scheduler.queue.push(entry)
119
+ drain(origin)
120
+ })
121
+ }
@@ -2,9 +2,14 @@ import { safeString } from '@exodus/safe-string'
2
2
  import { TraceId } from '@exodus/traceparent'
3
3
 
4
4
  import fetchWithTimeout from './fetch-with-timeout.js'
5
+ import scheduleMempoolRequest, { resumeMempoolRequests } from './mempool-request-scheduler.js'
5
6
 
6
7
  const MAX_RETRY_AFTER_MS = 5 * 60_000
7
- const retryAtByOrigin = new Map()
8
+ const INITIAL_BACKOFF_MS = 10_000
9
+ const RECOVERY_TIMEOUT_MS = 10_000
10
+ const REQUEST_TIMEOUT_MS = 30_000
11
+ const rateLimitsByOrigin = new Map()
12
+ const recoveringOrigins = new Set()
8
13
 
9
14
  const getRetryAfterMs = (response, now) => {
10
15
  const header = response.headers?.get?.('retry-after')?.trim()
@@ -36,22 +41,114 @@ const createRateLimitError = (retryAt, response) => {
36
41
  return error
37
42
  }
38
43
 
39
- export default async function mempoolRequest(url, fetchOptions) {
44
+ const enterCooldown = (origin, recoveryState, retryAfterMs) => {
45
+ let state = rateLimitsByOrigin.get(origin)
46
+ if (!state || recoveryState || retryAfterMs !== undefined) {
47
+ const backoffMs = state
48
+ ? Math.min(state.backoffMs * (recoveryState ? 2 : 1), MAX_RETRY_AFTER_MS)
49
+ : INITIAL_BACKOFF_MS
50
+ const duration =
51
+ retryAfterMs ??
52
+ Math.min(Math.round(backoffMs * (1 + Math.random() * 0.2)), MAX_RETRY_AFTER_MS)
53
+ state = {
54
+ retryAt: Math.max(state?.retryAt ?? 0, Date.now() + duration),
55
+ backoffMs,
56
+ }
57
+ rateLimitsByOrigin.set(origin, state)
58
+ }
59
+ resumeMempoolRequests(origin)
60
+ return state
61
+ }
62
+
63
+ const checkCooldown = (origin, isBroadcast) => {
64
+ const state = rateLimitsByOrigin.get(origin)
65
+ if (state && (Date.now() < state.retryAt || recoveringOrigins.has(origin) || isBroadcast)) {
66
+ throw createRateLimitError(state.retryAt)
67
+ }
68
+ }
69
+
70
+ async function executeRequest(url, fetchOptions, consumeResponse, isBroadcast) {
40
71
  const origin = new URL(url).origin
41
- const blockedUntil = retryAtByOrigin.get(origin)
42
- if (Date.now() < blockedUntil) throw createRateLimitError(blockedUntil)
43
- retryAtByOrigin.delete(origin)
44
-
45
- const response = await fetchWithTimeout(url, fetchOptions)
46
- if (response.status === 429) {
47
- const now = Date.now()
48
- const retryAfterMs = getRetryAfterMs(response, now)
49
- if (retryAfterMs !== undefined) {
50
- const retryAt = Math.max(retryAtByOrigin.get(origin) ?? 0, now + retryAfterMs)
51
- retryAtByOrigin.set(origin, retryAt)
52
- throw createRateLimitError(retryAt, response)
72
+ checkCooldown(origin, isBroadcast)
73
+ const recoveryState = rateLimitsByOrigin.get(origin)
74
+ let recoveryResponseHandled = false
75
+ if (recoveryState) {
76
+ recoveringOrigins.add(origin)
77
+ }
78
+ const timeout = fetchOptions?.timeout
79
+ const maximumTimeout = recoveryState ? RECOVERY_TIMEOUT_MS : REQUEST_TIMEOUT_MS
80
+ fetchOptions = {
81
+ ...fetchOptions,
82
+ timeout:
83
+ Number.isFinite(timeout) && timeout > 0 ? Math.min(timeout, maximumTimeout) : maximumTimeout,
84
+ }
85
+
86
+ try {
87
+ return await fetchWithTimeout(url, fetchOptions, async (response) => {
88
+ try {
89
+ if (response.status === 429) {
90
+ const state = enterCooldown(origin, recoveryState, getRetryAfterMs(response, Date.now()))
91
+ recoveryResponseHandled = true
92
+ throw createRateLimitError(state.retryAt, response)
93
+ }
94
+
95
+ if (recoveryState && !response.ok) {
96
+ if (response.status === 404) {
97
+ if (rateLimitsByOrigin.get(origin) === recoveryState) rateLimitsByOrigin.delete(origin)
98
+ } else {
99
+ enterCooldown(origin, recoveryState)
100
+ }
101
+ recoveryResponseHandled = true
102
+ }
103
+
104
+ const result = await consumeResponse(response)
105
+ if (recoveryState && rateLimitsByOrigin.get(origin) === recoveryState && response.ok) {
106
+ rateLimitsByOrigin.delete(origin)
107
+ }
108
+ return result
109
+ } finally {
110
+ try {
111
+ await response.body?.cancel?.()
112
+ } catch {}
113
+ }
114
+ })
115
+ } catch (error) {
116
+ if (recoveryState) {
117
+ const state = recoveryResponseHandled
118
+ ? rateLimitsByOrigin.get(origin)
119
+ : enterCooldown(origin, recoveryState)
120
+ error.finalError = true
121
+ if (state) {
122
+ error.retryAt = state.retryAt
123
+ error.retryAfterMs = Math.max(0, state.retryAt - Date.now())
124
+ }
53
125
  }
126
+
127
+ throw error
128
+ } finally {
129
+ if (recoveryState) recoveringOrigins.delete(origin)
54
130
  }
131
+ }
55
132
 
56
- return response
133
+ export default async function mempoolRequest(
134
+ url,
135
+ fetchOptions,
136
+ consumeResponse,
137
+ { isBroadcast = false } = {}
138
+ ) {
139
+ const origin = new URL(url).origin
140
+ if (isBroadcast) checkCooldown(origin, true)
141
+ return scheduleMempoolRequest(
142
+ origin,
143
+ () => executeRequest(url, fetchOptions, consumeResponse, isBroadcast),
144
+ {
145
+ signal: fetchOptions?.signal,
146
+ isBroadcast,
147
+ getCooldown: () => {
148
+ const state = rateLimitsByOrigin.get(origin)
149
+ const recovering = recoveringOrigins.has(origin)
150
+ return state || recovering ? { ...state, recovering } : undefined
151
+ },
152
+ }
153
+ )
57
154
  }
@@ -14,6 +14,8 @@ const RETRY_WAIT_TIMES = ['5s', '10s', '20s', '30s']
14
14
  // Serving them from a short-lived cache keeps one request per tick without letting
15
15
  // confirmation counts go meaningfully stale.
16
16
  const TIP_HEIGHT_CACHE_TTL_MS = 10_000
17
+ const WS_STATUS_CACHE_TTL_MS = 10_000
18
+ const MAX_WS_CACHED_STATUSES = 1000
17
19
 
18
20
  const MEMPOOL_HTTP_ERROR_MESSAGE = safeString`mempool-api-http-error`
19
21
  const MEMPOOL_MISSING_TXID_MESSAGE = safeString`mempool-api-missing-txid`
@@ -32,6 +34,7 @@ const MEMPOOL_HTTP_ERROR_FEES_MESSAGE = safeString`mempool-api-http-error:fees`
32
34
  const MEMPOOL_HTTP_ERROR_CPFP_MESSAGE = safeString`mempool-api-http-error:cpfp`
33
35
  const MEMPOOL_FEES_PAYLOAD_ERROR_MESSAGE = safeString`mempool-api-invalid-fees-payload`
34
36
  const MEMPOOL_INVALID_VALUE_ERROR_MESSAGE = safeString`mempool-api-invalid-value`
37
+ const MEMPOOL_STALE_CONFIRMATIONS_MESSAGE = safeString`mempool-api-stale-confirmations`
35
38
 
36
39
  // A txid is a double-SHA256 hash: always exactly 32 bytes / 64 hex chars.
37
40
  const TXID_HEX_PATTERN = /^[\da-f]{64}$/i
@@ -54,6 +57,7 @@ const parseBroadcastErrorReason = (data) => {
54
57
  }
55
58
 
56
59
  const isFiniteNumber = (value) => typeof value === 'number' && Number.isFinite(value)
60
+ const isBlockHeight = (height) => Number.isSafeInteger(height) && height >= 0
57
61
 
58
62
  const toBTCStringFromSatsString = (satsString) => {
59
63
  let value = String(satsString)
@@ -122,49 +126,51 @@ async function withRetry(fn, args = [], { waitTimes = RETRY_WAIT_TIMES } = {}) {
122
126
  }
123
127
 
124
128
  async function fetchJson(url, fetchOptions, { nullWhen404 = false, httpErrorMessage } = {}) {
125
- const response = await mempoolRequest(url, fetchOptions)
126
- if (nullWhen404 && response.status === 404) {
127
- return null
128
- }
129
-
130
- if (!response.ok) {
131
- throw createHttpError(response, httpErrorMessage || MEMPOOL_HTTP_ERROR_MESSAGE)
132
- }
129
+ return mempoolRequest(url, fetchOptions, async (response) => {
130
+ if (nullWhen404 && response.status === 404) {
131
+ return null
132
+ }
133
133
 
134
- try {
135
- return await response.json()
136
- } catch (err) {
137
- const error = new Error(MEMPOOL_JSON_ERROR_MESSAGE, { cause: err })
138
- const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
139
- if (traceId) {
140
- error.traceId = traceId
134
+ if (!response.ok) {
135
+ throw createHttpError(response, httpErrorMessage || MEMPOOL_HTTP_ERROR_MESSAGE)
141
136
  }
142
137
 
143
- throw error
144
- }
138
+ try {
139
+ return await response.json()
140
+ } catch (err) {
141
+ const error = new Error(MEMPOOL_JSON_ERROR_MESSAGE, { cause: err })
142
+ const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
143
+ if (traceId) {
144
+ error.traceId = traceId
145
+ }
146
+
147
+ throw error
148
+ }
149
+ })
145
150
  }
146
151
 
147
152
  async function fetchText(url, fetchOptions, { nullWhen404 = false, httpErrorMessage } = {}) {
148
- const response = await mempoolRequest(url, fetchOptions)
149
- if (nullWhen404 && response.status === 404) {
150
- return null
151
- }
152
-
153
- if (!response.ok) {
154
- throw createHttpError(response, httpErrorMessage || MEMPOOL_HTTP_ERROR_MESSAGE)
155
- }
153
+ return mempoolRequest(url, fetchOptions, async (response) => {
154
+ if (nullWhen404 && response.status === 404) {
155
+ return null
156
+ }
156
157
 
157
- try {
158
- return await response.text()
159
- } catch (err) {
160
- const error = new Error(MEMPOOL_TEXT_ERROR_MESSAGE, { cause: err })
161
- const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
162
- if (traceId) {
163
- error.traceId = traceId
158
+ if (!response.ok) {
159
+ throw createHttpError(response, httpErrorMessage || MEMPOOL_HTTP_ERROR_MESSAGE)
164
160
  }
165
161
 
166
- throw error
167
- }
162
+ try {
163
+ return await response.text()
164
+ } catch (err) {
165
+ const error = new Error(MEMPOOL_TEXT_ERROR_MESSAGE, { cause: err })
166
+ const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
167
+ if (traceId) {
168
+ error.traceId = traceId
169
+ }
170
+
171
+ throw error
172
+ }
173
+ })
168
174
  }
169
175
 
170
176
  const normalizeVin = (vin) => {
@@ -224,16 +230,69 @@ export default class MempoolRestClient {
224
230
  this._retryWaitTimes = retryWaitTimes
225
231
  this._configMinFeeRate = configMinFeeRate
226
232
  this._tipHeightCache = null
233
+ this._webSocketTxStatuses = new Map()
234
+ this._webSocketCacheRevision = 0
227
235
  }
228
236
 
229
237
  setMempoolBaseUrl(mempoolBaseURL) {
230
238
  if (mempoolBaseURL !== this._mempoolBaseURL) {
231
- this._tipHeightCache = null
239
+ this.clearWebSocketCache()
232
240
  }
233
241
 
234
242
  this._mempoolBaseURL = mempoolBaseURL
235
243
  }
236
244
 
245
+ clearWebSocketCache() {
246
+ this._webSocketCacheRevision++
247
+ this._tipHeightCache = null
248
+ this._webSocketTxStatuses.clear()
249
+ }
250
+
251
+ updateFromWebSocket(payload) {
252
+ const now = Date.now()
253
+ const blockHeight = payload?.block?.height
254
+ if (payload?.block) {
255
+ this.clearWebSocketCache()
256
+ if (isBlockHeight(blockHeight)) {
257
+ this._tipHeightCache = { promise: Promise.resolve(blockHeight), startedAt: now }
258
+ }
259
+ }
260
+
261
+ const addresses = payload?.['multi-address-transactions']
262
+ if (!addresses || typeof addresses !== 'object' || Array.isArray(addresses)) return
263
+
264
+ for (const transactions of Object.values(addresses)) {
265
+ for (const kind of ['mempool', 'confirmed', 'removed']) {
266
+ if (!Array.isArray(transactions?.[kind])) continue
267
+ for (const transaction of transactions[kind]) {
268
+ const txid = transaction?.txid
269
+ if (typeof txid !== 'string' || !TXID_HEX_PATTERN.test(txid)) continue
270
+ this._webSocketCacheRevision++
271
+ this._webSocketTxStatuses.delete(txid)
272
+ if (kind === 'removed') continue
273
+
274
+ const height = isBlockHeight(blockHeight)
275
+ ? blockHeight
276
+ : transaction.status?.confirmed === true
277
+ ? transaction.status.block_height
278
+ : undefined
279
+ if (kind === 'confirmed' && !isBlockHeight(height)) continue
280
+
281
+ if (kind === 'confirmed' && !isBlockHeight(blockHeight)) {
282
+ this._tipHeightCache = null
283
+ }
284
+
285
+ const status =
286
+ kind === 'confirmed' ? { confirmed: true, block_height: height } : { confirmed: false }
287
+ this._webSocketTxStatuses.set(txid, { status, receivedAt: now })
288
+ if (this._webSocketTxStatuses.size > MAX_WS_CACHED_STATUSES) {
289
+ this._webSocketTxStatuses.delete(this._webSocketTxStatuses.keys().next().value)
290
+ }
291
+ }
292
+ }
293
+ }
294
+ }
295
+
237
296
  _mempoolApiUrl(path, { version } = {}) {
238
297
  return urlJoin(this._mempoolBaseURL, version === 'v1' ? '/api/v1' : '/api', path)
239
298
  }
@@ -395,6 +454,32 @@ export default class MempoolRestClient {
395
454
  return this._fetchTipHeight()
396
455
  }
397
456
 
457
+ async fetchTxConfirmations(txid) {
458
+ for (let attempt = 0; attempt < 2; attempt++) {
459
+ const revision = this._webSocketCacheRevision
460
+ const cached = this._webSocketTxStatuses.get(txid)
461
+ const fresh = cached && Date.now() - cached.receivedAt < WS_STATUS_CACHE_TTL_MS
462
+ if (!fresh) this._webSocketTxStatuses.delete(txid)
463
+ const status = fresh
464
+ ? cached.status
465
+ : await fetchJson(
466
+ this._mempoolApiUrl(`/tx/${encodeURIComponent(txid)}/status`),
467
+ undefined,
468
+ {
469
+ nullWhen404: true,
470
+ httpErrorMessage: MEMPOOL_HTTP_ERROR_STATUS_MESSAGE,
471
+ }
472
+ )
473
+ if (revision !== this._webSocketCacheRevision) continue
474
+ if (!status?.confirmed) return 0
475
+ const tipHeight = await this._fetchTipHeight()
476
+ if (revision === this._webSocketCacheRevision) {
477
+ return normalizeTxConfirmations(status, tipHeight)
478
+ }
479
+ }
480
+ throw new Error(MEMPOOL_STALE_CONFIRMATIONS_MESSAGE)
481
+ }
482
+
398
483
  async fetchTx(txid) {
399
484
  const tipHeightPromise = this._fetchTipHeight()
400
485
  const encodedTxid = encodeURIComponent(txid)
@@ -658,38 +743,43 @@ export default class MempoolRestClient {
658
743
  // classification (broadcast-tx.js) pattern-matches it.
659
744
  async broadcastTx(rawTx) {
660
745
  const payload = rawTx instanceof Uint8Array ? Buffer.from(rawTx).toString('hex') : rawTx
661
- const response = await mempoolRequest(this._mempoolApiUrl('/tx'), {
662
- method: 'post',
663
- headers: {
664
- Accept: 'text/plain',
665
- 'Content-Type': 'text/plain',
746
+ return mempoolRequest(
747
+ this._mempoolApiUrl('/tx'),
748
+ {
749
+ method: 'post',
750
+ headers: {
751
+ Accept: 'text/plain',
752
+ 'Content-Type': 'text/plain',
753
+ },
754
+ body: payload,
666
755
  },
667
- body: payload,
668
- })
669
-
670
- const data = await response.text()
671
-
672
- if (!response.ok) {
673
- console.warn(`Mempool Client's Broadcast HTTP Error:`)
674
- console.warn(response.statusText)
675
- console.warn(data)
676
- const error = createHttpError(response, MEMPOOL_HTTP_ERROR_BROADCAST_MESSAGE)
677
- error.reason = parseBroadcastErrorReason(data)
678
- throw error
679
- }
756
+ async (response) => {
757
+ const data = await response.text()
758
+
759
+ if (!response.ok) {
760
+ console.warn(`Mempool Client's Broadcast HTTP Error:`)
761
+ console.warn(response.statusText)
762
+ console.warn(data)
763
+ const error = createHttpError(response, MEMPOOL_HTTP_ERROR_BROADCAST_MESSAGE)
764
+ error.reason = parseBroadcastErrorReason(data)
765
+ throw error
766
+ }
680
767
 
681
- const txid = String(data).trim()
682
- if (!TXID_HEX_PATTERN.test(txid)) {
683
- console.warn(`Mempool Client's Broadcast Unexpected Payload:`, data)
684
- const error = new Error(MEMPOOL_MISSING_TXID_MESSAGE)
685
- const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
686
- if (traceId) {
687
- error.traceId = traceId
688
- }
768
+ const txid = String(data).trim()
769
+ if (!TXID_HEX_PATTERN.test(txid)) {
770
+ console.warn(`Mempool Client's Broadcast Unexpected Payload:`, data)
771
+ const error = new Error(MEMPOOL_MISSING_TXID_MESSAGE)
772
+ const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
773
+ if (traceId) {
774
+ error.traceId = traceId
775
+ }
689
776
 
690
- throw error
691
- }
777
+ throw error
778
+ }
692
779
 
693
- return { txid }
780
+ return { txid }
781
+ },
782
+ { isBroadcast: true }
783
+ )
694
784
  }
695
785
  }
@@ -257,6 +257,10 @@ export default class MempoolWSClient extends EventEmitter {
257
257
  this.#clearPongTimeout()
258
258
  }
259
259
 
260
+ if (payload.block || payload['multi-address-transactions']) {
261
+ this.emit('update', payload)
262
+ }
263
+
260
264
  if (payload.block) {
261
265
  this.emit('block', payload.block)
262
266
  }
@@ -33,6 +33,7 @@ export class BitcoinMonitorScanner {
33
33
  #extraChainIndex
34
34
  #gapLimit
35
35
  #refreshGapLimit
36
+ #addressBatchConcurrency
36
37
  constructor({
37
38
  asset,
38
39
  assetClientInterface,
@@ -43,6 +44,7 @@ export class BitcoinMonitorScanner {
43
44
  extraChainIndex,
44
45
  gapLimit = 10,
45
46
  refreshGapLimit = 10,
47
+ addressBatchConcurrency = Infinity,
46
48
  }) {
47
49
  assert(asset, 'asset is required!')
48
50
  assert(assetClientInterface, 'assetClientInterface is required!')
@@ -51,6 +53,11 @@ export class BitcoinMonitorScanner {
51
53
  assert(typeof shouldExcludeVoutUtxo === 'function', 'shouldExcludeVoutUtxo must be a function')
52
54
  assert(typeof gapLimit === 'number', 'gapLimit must be a number')
53
55
  assert(typeof refreshGapLimit === 'number', 'refreshGapLimit must be a number')
56
+ assert(
57
+ addressBatchConcurrency === Infinity ||
58
+ (Number.isSafeInteger(addressBatchConcurrency) && addressBatchConcurrency > 0),
59
+ 'addressBatchConcurrency must be positive'
60
+ )
54
61
 
55
62
  this.#asset = asset
56
63
  this.#insightClient = insightClient
@@ -61,6 +68,7 @@ export class BitcoinMonitorScanner {
61
68
  this.#extraChainIndex = extraChainIndex
62
69
  this.#gapLimit = gapLimit
63
70
  this.#refreshGapLimit = refreshGapLimit
71
+ this.#addressBatchConcurrency = addressBatchConcurrency
64
72
  }
65
73
 
66
74
  async #getGapLimit({ assetConfig, refresh }) {
@@ -244,22 +252,25 @@ export class BitcoinMonitorScanner {
244
252
  const fetchAllTxs = async (addresses) => {
245
253
  if (addresses.length === 0) return []
246
254
 
247
- const promises = []
255
+ const batches = []
248
256
  const fetchTimeout = 250
249
257
 
250
258
  const fetchAddressesSize = 25
251
- for (let i = 0; i < addresses.length; i += fetchAddressesSize) {
252
- const fetchAddresses = addresses.slice(i, i + fetchAddressesSize)
253
- const promise = insightClient.fetchAllTxData(
254
- fetchAddresses,
255
- txFetchLimit,
256
- fetchTimeout,
257
- shouldStop
258
- )
259
- promises.push(promise)
259
+ for (let start = 0; start < addresses.length; start += fetchAddressesSize) {
260
+ batches.push(addresses.slice(start, start + fetchAddressesSize))
260
261
  }
261
262
 
262
- const listOfTxs = await Promise.all(promises)
263
+ const listOfTxs = []
264
+ for (let start = 0; start < batches.length; start += this.#addressBatchConcurrency) {
265
+ const transactions = await Promise.all(
266
+ batches
267
+ .slice(start, start + this.#addressBatchConcurrency)
268
+ .map((fetchAddresses) =>
269
+ insightClient.fetchAllTxData(fetchAddresses, txFetchLimit, fetchTimeout, shouldStop)
270
+ )
271
+ )
272
+ listOfTxs.push(...transactions)
273
+ }
263
274
  return listOfTxs.flat()
264
275
  }
265
276
 
@@ -766,12 +777,18 @@ export class BitcoinMonitorScanner {
766
777
 
767
778
  const maybeConfirmationList = await Promise.all(
768
779
  unconfirmedTxIds.map(async (txId) => {
769
- const txStatus = await this.#insightClient.fetchTx(txId)
770
- if (!txStatus?.confirmations) {
780
+ let confirmations
781
+ if (this.#insightClient.fetchTxConfirmations) {
782
+ confirmations = await this.#insightClient.fetchTxConfirmations(txId)
783
+ } else {
784
+ const transaction = await this.#insightClient.fetchTx(txId)
785
+ confirmations = transaction?.confirmations
786
+ }
787
+ if (!confirmations) {
771
788
  return
772
789
  }
773
790
 
774
- return { txId, confirmations: txStatus.confirmations }
791
+ return { txId, confirmations }
775
792
  })
776
793
  )
777
794
  const confirmationsList = maybeConfirmationList.filter(Boolean)
@@ -76,6 +76,7 @@ export class Monitor extends BaseMonitor {
76
76
  assetClientInterface,
77
77
  insightClient,
78
78
  ...extraScannerParams,
79
+ addressBatchConcurrency: monitorType === 'mempool' ? 2 : Infinity,
79
80
  })
80
81
 
81
82
  this.addHook('after-tick-multiple-wallet-accounts', () => this.#subscribeToNewAddresses())
@@ -84,6 +85,7 @@ export class Monitor extends BaseMonitor {
84
85
  this.#ws.close()
85
86
  this.#ws = null
86
87
  }
88
+ if (this.#monitorType === 'mempool') this.#insightClient.clearWebSocketCache?.()
87
89
  })
88
90
  this.addHook('after-stop', async () =>
89
91
  Promise.all(Object.keys(this.#runningByWalletAccount).map(this.#waitForWalletToFinish))
@@ -172,6 +174,9 @@ export class Monitor extends BaseMonitor {
172
174
  }
173
175
 
174
176
  this.#ws.connect(addressesArr)
177
+ if (this.#monitorType === 'mempool') {
178
+ this.#ws.on('update', (payload) => this.#insightClient.updateFromWebSocket?.(payload))
179
+ }
175
180
  this.#ws.on('connect', () => {
176
181
  this.#logWsStatus('connect to addresses', addressesArr)
177
182
  this.timer.setNewInterval(this.#wsInterval)
@@ -184,6 +189,7 @@ export class Monitor extends BaseMonitor {
184
189
  })
185
190
  this.#ws.on('block', () => this.onNewBlock())
186
191
  this.#ws.on('disconnect', () => {
192
+ if (this.#monitorType === 'mempool') this.#insightClient.clearWebSocketCache?.()
187
193
  this.#logWsStatus('disconnect')
188
194
  this.timer.setNewInterval(this.interval)
189
195
  })
@@ -211,6 +211,9 @@ export const sendTxFactory = ({
211
211
  try {
212
212
  await broadcastTransaction({ asset, rawTx })
213
213
  } catch (err) {
214
+ if (['MEMPOOL_REQUEST_BUSY', 'MEMPOOL_REQUEST_QUEUE_TIMEOUT'].includes(err.code)) {
215
+ throw err
216
+ }
214
217
  const txExists = await checkTxExists({ asset, txId })
215
218
  if (txExists) {
216
219
  console.warn(`tx-send: ${assetName} tx already broadcast`, txId)