@exodus/bitcoin-api 5.0.3 → 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,28 @@
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
+
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)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * **bitcoin-api:** gracefully handle hardware wallets with incomplete xpubs ([#8429](https://github.com/ExodusMovement/assets/issues/8429)) ([6b7901e](https://github.com/ExodusMovement/assets/commit/6b7901ee09cf224442a64b94ecb973c1d1cca5ea))
21
+ * **bitcoin-api:** honor mempool Retry-After on HTTP 429 ([#8749](https://github.com/ExodusMovement/assets/issues/8749)) ([eedf948](https://github.com/ExodusMovement/assets/commit/eedf94874e688ffff72303a67233820a16384f0d))
22
+ * disable @exodus/hydra/no-param-reassign-prop-only warnings ([#8531](https://github.com/ExodusMovement/assets/issues/8531)) ([ddae556](https://github.com/ExodusMovement/assets/commit/ddae556361285919fe82cd10a81cfeae79ccc6b5))
23
+ * **lint:** convert console.log/info to console.debug and enforce no-console ([#8529](https://github.com/ExodusMovement/assets/issues/8529)) ([81cf5e9](https://github.com/ExodusMovement/assets/commit/81cf5e90b8157b084cf4cb311c02803c29e622e4))
24
+ * **lint:** migrate lodash to @exodus/basic-utils ([#8514](https://github.com/ExodusMovement/assets/issues/8514)) ([12c574f](https://github.com/ExodusMovement/assets/commit/12c574f1ac8ab0592700df574b2643141237090a))
25
+
26
+
27
+
6
28
  ## [5.0.3](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.0...@exodus/bitcoin-api@5.0.3) (2026-08-10)
7
29
 
8
30
 
package/README.md CHANGED
@@ -1,3 +1,23 @@
1
1
  # @exodus/bitcoin-api
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
+
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
+
11
+ ## Mempool Retry-After
12
+
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.
20
+
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.
22
+
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.3",
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",
@@ -16,9 +16,7 @@
16
16
  "provenance": false
17
17
  },
18
18
  "scripts": {
19
- "test": "run -T exodus-test --jest",
20
- "lint": "run -T eslintc .",
21
- "lint:fix": "yarn lint --fix"
19
+ "test": "exodus-test --jest"
22
20
  },
23
21
  "dependencies": {
24
22
  "@exodus/asset-lib": "^5.0.0",
@@ -28,18 +26,17 @@
28
26
  "@exodus/bip44-constants": "^195.0.0",
29
27
  "@exodus/bitcoin-lib": "^2.4.3",
30
28
  "@exodus/bitcoinjs": "^2.0.0",
29
+ "@exodus/bytes": "^1.16.0",
31
30
  "@exodus/crypto": "^1.0.0-rc.13",
32
31
  "@exodus/currency": "^6.0.1",
33
32
  "@exodus/i18n-dummy": "^1.0.0",
34
- "@exodus/key-identifier": "^1.3.0",
33
+ "@exodus/key-identifier": "^1.5.0",
35
34
  "@exodus/models": "^13.0.0",
36
35
  "@exodus/safe-string": "^1.4.0",
37
36
  "@exodus/send-validation-model": "^1.0.0",
38
37
  "@exodus/simple-retry": "^0.0.6",
39
38
  "@exodus/traceparent": "^3.0.1",
40
- "bech32": "^1.1.3",
41
39
  "bip32-path": "^0.4.2",
42
- "bs58check": "^3.0.1",
43
40
  "delay": "^4.0.1",
44
41
  "eventemitter3": "^5.0.4",
45
42
  "events": "^3.3.0",
@@ -48,8 +45,7 @@
48
45
  "ms": "^2.1.1",
49
46
  "socket.io-client": "^2.1.1",
50
47
  "url-join": "^4.0.0",
51
- "varuint-bitcoin": "^1.1.0",
52
- "wif": "^4.0.0"
48
+ "varuint-bitcoin": "^1.1.0"
53
49
  },
54
50
  "devDependencies": {
55
51
  "@exodus/bitcoin-meta": "^2.0.0",
@@ -63,5 +59,5 @@
63
59
  "type": "git",
64
60
  "url": "git+https://github.com/ExodusMovement/assets.git"
65
61
  },
66
- "gitHead": "e76fe6900a823d6abd2cbf7efa273132c5dab1ae"
62
+ "gitHead": "fb42d6502575a15419bff613b88aed10d2be8529"
67
63
  }
@@ -17,3 +17,64 @@ function parsePath(address) {
17
17
  const p1 = path ? path.replace('m/', '').split('/') : ['0', '0']
18
18
  return p1.map((i) => parseInt(i, 10))
19
19
  }
20
+
21
+ // The address provider's public-key-provider throws PublicKeyNotFoundError when the
22
+ // wallet account has no xpub in storage for the requested derivation path. The error
23
+ // carries no `code` and the class is not importable from this package (and instanceof
24
+ // would break across duplicated copies), so match on `name` — an own instance property
25
+ // that survives minification — with a message fallback for older provider versions.
26
+ export function isMissingXpubError(error) {
27
+ return (
28
+ error?.name === 'PublicKeyNotFoundError' || /no public key found/i.test(error?.message ?? '')
29
+ )
30
+ }
31
+
32
+ export async function getAvailablePurposes({
33
+ assetClientInterface,
34
+ assetName,
35
+ walletAccount,
36
+ multisigDataLength,
37
+ }) {
38
+ const supportedPurposes = await assetClientInterface.getSupportedPurposes({
39
+ assetName,
40
+ walletAccount,
41
+ })
42
+
43
+ // getSupportedPurposes reflects derivation capability, not which xpubs the wallet
44
+ // account actually has in storage — hardware wallets (e.g. old Trezor models) may
45
+ // only provide some of them. Probe the first address of each purpose and skip the
46
+ // purposes that cannot derive.
47
+ const probes = await Promise.all(
48
+ supportedPurposes.map(async (purpose) => {
49
+ try {
50
+ await assetClientInterface.getAddress({
51
+ assetName,
52
+ walletAccount,
53
+ purpose,
54
+ chainIndex: 0,
55
+ addressIndex: 0,
56
+ ...(multisigDataLength ? { multisigDataIndex: 0 } : Object.create(null)),
57
+ })
58
+ return { purpose }
59
+ } catch (error) {
60
+ // Degrade only on the condition this helper is about — a missing xpub. Any
61
+ // other failure (locked seed, storage error, timeout) is transient or a real
62
+ // bug: silently dropping the purpose would corrupt tx classification, while a
63
+ // thrown scan is recoverable on the next attempt.
64
+ if (!isMissingXpubError(error)) throw error
65
+
66
+ console.warn(
67
+ `${assetName}: no xpub for purpose ${purpose} in wallet account ${walletAccount}, skipping it. ${error.message}`
68
+ )
69
+ return { purpose, error }
70
+ }
71
+ })
72
+ )
73
+
74
+ const availablePurposes = probes.filter((probe) => !probe.error).map((probe) => probe.purpose)
75
+ if (supportedPurposes.length > 0 && availablePurposes.length === 0) {
76
+ throw probes[0].error
77
+ }
78
+
79
+ return availablePurposes
80
+ }
@@ -1,10 +1,11 @@
1
+ /* oxlint-disable @exodus/oxlint-plugin-restricted-imports/prefer-basic-utils -- identity not in basic-utils */
1
2
  import * as bitcoinjsOriginal from '@exodus/bitcoinjs'
2
- import * as bech32 from 'bech32'
3
- import bs58check from 'bs58check'
3
+ import { pickBy } from '@exodus/basic-utils'
4
+ import { fromBase58checkSync } from '@exodus/bytes/base58check.js'
4
5
  import lodash from 'lodash'
5
6
  import assert from 'minimalistic-assert'
6
7
 
7
- const { identity, pickBy } = lodash
8
+ const { identity } = lodash
8
9
 
9
10
  export const createBtcLikeAddress = ({
10
11
  versions,
@@ -21,8 +22,12 @@ export const createBtcLikeAddress = ({
21
22
  version === undefined
22
23
  ? undefined
23
24
  : (string) => {
24
- const payload = bs58check.decodeUnsafe(string)
25
- return !!payload && payload.length === 21 && payload[0] === version
25
+ try {
26
+ const payload = fromBase58checkSync(string)
27
+ return payload.length === 21 && payload[0] === version
28
+ } catch {
29
+ return false
30
+ }
26
31
  }
27
32
 
28
33
  const bech32ValidateFactory = (version, length) =>
@@ -30,13 +35,10 @@ export const createBtcLikeAddress = ({
30
35
  ? undefined
31
36
  : (string) => {
32
37
  try {
33
- const decoded = bech32.decode(string)
34
- // bech32 lib normalizes prefixes, so not worrying about uppercase
35
- if (decoded.prefix !== versions.bech32) return false
38
+ // fromBech32 normalizes prefixes, so not worrying about uppercase
39
+ const { prefix, version, data } = bitcoinjsOriginal.address.fromBech32(string)
36
40
  // NOTE: We only support version zero witness programs
37
- if (decoded.words[0] !== 0) return false
38
- // Ensure correct length
39
- return bech32.fromWords(decoded.words.slice(1)).length === length
41
+ return prefix === versions.bech32 && version === 0 && data.length === length
40
42
  } catch {
41
43
  return false
42
44
  }
@@ -1,18 +1,19 @@
1
+ /* oxlint-disable @exodus/oxlint-plugin-restricted-imports/prefer-basic-utils -- identity not in basic-utils */
1
2
  import * as defaultBitcoinjsLib from '@exodus/bitcoinjs'
3
+ import { pickBy } from '@exodus/basic-utils'
4
+ import { toBase58checkSync } from '@exodus/bytes/base58check.js'
5
+ import { fromWifStringSync, toWifStringSync } from '@exodus/bytes/wif.js'
2
6
  import * as secp256k1 from '@exodus/crypto/secp256k1'
3
- import * as bech32 from 'bech32'
4
- import bs58check from 'bs58check'
5
7
  import lodash from 'lodash'
6
8
  import assert from 'minimalistic-assert'
7
- import wif from 'wif'
8
9
 
9
10
  import { hash160 } from './hash-utils.js'
10
11
 
11
- const { identity, pickBy } = lodash
12
+ const { identity } = lodash
12
13
 
13
14
  export const publicKeyToHashFactory = (p2pkh) => (publicKey) => {
14
15
  const payload = Buffer.concat([Buffer.from([p2pkh]), hash160(publicKey)])
15
- return bs58check.encode(payload)
16
+ return toBase58checkSync(payload)
16
17
  }
17
18
 
18
19
  export const createBtcLikeKeys = ({
@@ -37,13 +38,13 @@ export const createBtcLikeKeys = ({
37
38
  const encodePrivate =
38
39
  encodePrivateCustom ||
39
40
  ((privateKey, compressed = true) => {
40
- return wif.encode(coinInfo.versions.private, privateKey, compressed)
41
+ return toWifStringSync({ version: coinInfo.versions.private, privateKey, compressed })
41
42
  })
42
43
  const encodePublicPurpose44 = encodePublicCustom || publicKeyToHashFactory(versions.p2pkh)
43
44
  const encodePublicFromWIF =
44
45
  encodePublicFromWIFCustom ||
45
46
  ((privateKeyWIF) => {
46
- const { privateKey, compressed } = wif.decode(privateKeyWIF, coinInfo.versions.private)
47
+ const { privateKey, compressed } = fromWifStringSync(privateKeyWIF, coinInfo.versions.private)
47
48
  const publicKey = secp256k1.privateKeyToPublicKey({ privateKey, compressed })
48
49
  return encodePublicPurpose44(publicKey)
49
50
  })
@@ -52,13 +53,12 @@ export const createBtcLikeKeys = ({
52
53
  (versions.bech32 === undefined
53
54
  ? undefined
54
55
  : (publicKey) => {
55
- const pubKeyHash = hash160(publicKey)
56
- const witnessVersion = Buffer.from([0])
57
- const witnessProgram = Buffer.concat([
56
+ const witnessVersion = 0
57
+ return defaultBitcoinjsLib.address.toBech32(
58
+ hash160(publicKey),
58
59
  witnessVersion,
59
- Buffer.from(bech32.toWords(pubKeyHash)),
60
- ])
61
- return bech32.encode(versions.bech32, witnessProgram)
60
+ versions.bech32
61
+ )
62
62
  })
63
63
  const encodePublicBech32FromWIF =
64
64
  encodePublicBech32FromWIFCustom ||
@@ -66,7 +66,7 @@ export const createBtcLikeKeys = ({
66
66
  ? (privateKeyWIF) => {
67
67
  // NOTE: No password support here
68
68
  const { versions } = coinInfo
69
- const { privateKey, compressed } = wif.decode(privateKeyWIF, versions.private)
69
+ const { privateKey, compressed } = fromWifStringSync(privateKeyWIF, versions.private)
70
70
  const publicKey = secp256k1.privateKeyToPublicKey({ privateKey, compressed })
71
71
  return encodePublicBech32(publicKey)
72
72
  }
@@ -1,4 +1,3 @@
1
- // eslint-disable-next-line @exodus/import/no-deprecated
2
1
  import { isNumberUnit, UnitType } from '@exodus/currency'
3
2
  import { UtxoCollection } from '@exodus/models'
4
3
  import assert from 'minimalistic-assert'
@@ -33,6 +32,23 @@ export function getExtraFee({ asset, inputs, feePerKB, unconfirmedTxAncestor })
33
32
  return extraFee
34
33
  }
35
34
 
35
+ export function parseCurrency(val, currency) {
36
+ assert(currency instanceof UnitType, 'Currency must be supples as a UnitType')
37
+
38
+ if (isNumberUnit(val)) return val // TODO: consider checking if the unitType.equals(currency) (if currency is object)
39
+
40
+ if (typeof val === 'string') return currency.parse(val)
41
+ return currency.parse(val.value + ' ' + val.unit)
42
+ }
43
+
44
+ export function serializeCurrency(val, currency) {
45
+ if (val === undefined) {
46
+ return val
47
+ }
48
+
49
+ return parseCurrency(val, currency).toDefaultString({ unit: true })
50
+ }
51
+
36
52
  export default function createDefaultFeeEstimator(getSize) {
37
53
  return (asset, feePerKB, options = {}) => {
38
54
  return ({
@@ -50,21 +66,3 @@ export default function createDefaultFeeEstimator(getSize) {
50
66
  }
51
67
  }
52
68
  }
53
-
54
- export function parseCurrency(val, currency) {
55
- assert(currency instanceof UnitType, 'Currency must be supples as a UnitType')
56
-
57
- // eslint-disable-next-line @exodus/import/no-deprecated
58
- if (isNumberUnit(val)) return val // TODO: consider checking if the unitType.equals(currency) (if currency is object)
59
-
60
- if (typeof val === 'string') return currency.parse(val)
61
- return currency.parse(val.value + ' ' + val.unit)
62
- }
63
-
64
- export function serializeCurrency(val, currency) {
65
- if (val === undefined) {
66
- return val
67
- }
68
-
69
- return parseCurrency(val, currency).toDefaultString({ unit: true })
70
- }
@@ -1,6 +1,5 @@
1
1
  import { memoizeLruCache } from '@exodus/asset-lib'
2
2
  import { scriptClassify } from '@exodus/bitcoinjs'
3
- // eslint-disable-next-line @exodus/import/no-deprecated
4
3
  import { hashSync } from '@exodus/crypto/hash'
5
4
  import assert from 'minimalistic-assert'
6
5
 
@@ -9,7 +8,6 @@ const { P2PKH, P2SH, P2WPKH, P2WSH, P2TR } = scriptClassify.types
9
8
  const cacheSize = 1000
10
9
  const maxSize = 30
11
10
  const hashStringIfTooBig = (str) =>
12
- // eslint-disable-next-line @exodus/import/no-deprecated
13
11
  str.length > maxSize ? hashSync('sha256', str, 'hex').slice(0, maxSize) : str
14
12
 
15
13
  export const scriptClassifierFactory = ({ addressApi }) => {
package/src/hash-utils.js CHANGED
@@ -1,12 +1,9 @@
1
- // eslint-disable-next-line @exodus/import/no-deprecated
2
1
  import { hashSync } from '@exodus/crypto/hash'
3
2
 
4
3
  export function hash160(buffer) {
5
- // eslint-disable-next-line @exodus/import/no-deprecated
6
4
  return hashSync('hash160', buffer)
7
5
  }
8
6
 
9
7
  export function sha256(buffer) {
10
- // eslint-disable-next-line @exodus/import/no-deprecated
11
8
  return hashSync('sha256', buffer)
12
9
  }
@@ -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)
@@ -221,7 +221,7 @@ export default class InsightAPIClient {
221
221
 
222
222
  async broadcastTx(rawTx) {
223
223
  const _rawTx = rawTx instanceof Uint8Array ? Buffer.from(rawTx).toString('hex') : rawTx
224
- console.log('gonna broadcastTx')
224
+ console.debug('gonna broadcastTx')
225
225
  const url = urlJoin(this.#baseURL, '/tx/send')
226
226
  const fetchOptions = {
227
227
  method: 'post',
@@ -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
+ }