@exodus/bitcoin-api 4.16.0 → 5.0.0

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,29 @@
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.0](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@4.16.1...@exodus/bitcoin-api@5.0.0) (2026-07-10)
7
+
8
+
9
+ ### ⚠ BREAKING CHANGES
10
+
11
+ * **bitcoin:** broadcast btc via mempool space send path (#8349)
12
+
13
+ ### Features
14
+
15
+ * **bitcoin:** broadcast btc via mempool space send path ([#8349](https://github.com/ExodusMovement/assets/issues/8349)) ([ff44736](https://github.com/ExodusMovement/assets/commit/ff44736b7aae845e5261bd60c8583d5871adb8f2))
16
+
17
+
18
+
19
+ ## [4.16.1](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@4.16.0...@exodus/bitcoin-api@4.16.1) (2026-07-09)
20
+
21
+
22
+ ### Bug Fixes
23
+
24
+ * cache mempool tip height with short TTL to dedup reqs ([#8333](https://github.com/ExodusMovement/assets/issues/8333)) ([77e2c40](https://github.com/ExodusMovement/assets/commit/77e2c4025b728e6992f037dabf9a636bfbca829e))
25
+ * **decred-plugin:** fail fast on unresponsive dcrdata endpoint to speed up restore ([#8351](https://github.com/ExodusMovement/assets/issues/8351)) ([9346786](https://github.com/ExodusMovement/assets/commit/934678607553a740786ba3fe906dfd38c2fdd040))
26
+
27
+
28
+
6
29
  ## [4.16.0](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@4.15.10...@exodus/bitcoin-api@4.16.0) (2026-06-29)
7
30
 
8
31
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/bitcoin-api",
3
- "version": "4.16.0",
3
+ "version": "5.0.0",
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",
@@ -63,5 +63,5 @@
63
63
  "type": "git",
64
64
  "url": "git+https://github.com/ExodusMovement/assets.git"
65
65
  },
66
- "gitHead": "d57432d4ef29f2dc1bc269d501fd29d9a0063f1c"
66
+ "gitHead": "1d7fd9da145bcfeb290441b3b8c72f9f5310eaca"
67
67
  }
@@ -66,29 +66,48 @@ const fetchJson = async (
66
66
  }
67
67
  }
68
68
 
69
- async function fetchJsonRetry(url, fetchOptions, httpErrorMessage) {
70
- const waitTimes = ['2s', '5s', '10s', '20s']
69
+ const DEFAULT_ADDRESS_TXS_TIMEOUT = 25_000
70
+ const DEFAULT_ADDRESS_TXS_RETRY_WAIT_TIMES = ['2s', '5s', '10s', '20s']
71
+
72
+ async function fetchJsonRetry(
73
+ url,
74
+ fetchOptions,
75
+ httpErrorMessage,
76
+ waitTimes = DEFAULT_ADDRESS_TXS_RETRY_WAIT_TIMES
77
+ ) {
71
78
  const fetchWithRetry = retry(fetchJson, { delayTimesMs: waitTimes })
72
79
  return fetchWithRetry(url, fetchOptions, false, httpErrorMessage)
73
80
  }
74
81
 
75
82
  export default class InsightAPIClient {
76
- constructor(baseURL) {
77
- this._baseURL = baseURL
83
+ #baseURL
84
+ #addressTxsTimeout
85
+ #addressTxsRetryWaitTimes
86
+
87
+ constructor(
88
+ baseURL,
89
+ {
90
+ addressTxsTimeout = DEFAULT_ADDRESS_TXS_TIMEOUT,
91
+ addressTxsRetryWaitTimes = DEFAULT_ADDRESS_TXS_RETRY_WAIT_TIMES,
92
+ } = Object.create(null)
93
+ ) {
94
+ this.#baseURL = baseURL
95
+ this.#addressTxsTimeout = addressTxsTimeout
96
+ this.#addressTxsRetryWaitTimes = addressTxsRetryWaitTimes
78
97
  }
79
98
 
80
99
  setBaseUrl(baseURL) {
81
- this._baseURL = baseURL
100
+ this.#baseURL = baseURL
82
101
  }
83
102
 
84
103
  async fetchBalance(address) {
85
104
  const encodedAddress = encodeURIComponent(address)
86
- const url = urlJoin(this._baseURL, `/balance/${encodedAddress}`)
105
+ const url = urlJoin(this.#baseURL, `/balance/${encodedAddress}`)
87
106
  return fetchJson(url, undefined, false, INSIGHT_HTTP_ERROR_BALANCE_MESSAGE)
88
107
  }
89
108
 
90
109
  async fetchBlockHeight() {
91
- const url = urlJoin(this._baseURL, '/status')
110
+ const url = urlJoin(this.#baseURL, '/status')
92
111
  const status = await fetchJson(
93
112
  url,
94
113
  { timeout: 10_000 },
@@ -105,7 +124,7 @@ export default class InsightAPIClient {
105
124
  query.set('assetNames', assetNames.join(','))
106
125
  }
107
126
 
108
- const url = urlJoin(this._baseURL, `/addrs/${encodedAddress}/utxo?${query}`)
127
+ const url = urlJoin(this.#baseURL, `/addrs/${encodedAddress}/utxo?${query}`)
109
128
  const utxos = await fetchJson(url, undefined, false, INSIGHT_HTTP_ERROR_UTXO_MESSAGE)
110
129
 
111
130
  return utxos.map((utxo) => ({
@@ -122,12 +141,12 @@ export default class InsightAPIClient {
122
141
 
123
142
  async fetchTx(txId) {
124
143
  const encodedTxId = encodeURIComponent(txId)
125
- const url = urlJoin(this._baseURL, `/tx/${encodedTxId}`)
144
+ const url = urlJoin(this.#baseURL, `/tx/${encodedTxId}`)
126
145
  return fetchJson(url, undefined, true, INSIGHT_HTTP_ERROR_TX_MESSAGE)
127
146
  }
128
147
 
129
148
  async fetchTxObject(txId) {
130
- const url = urlJoin(this._baseURL, `/fulltx?${new URLSearchParams({ hash: txId })}`)
149
+ const url = urlJoin(this.#baseURL, `/fulltx?${new URLSearchParams({ hash: txId })}`)
131
150
  const object = await fetchJson(url, undefined, true, INSIGHT_HTTP_ERROR_FULLTX_MESSAGE)
132
151
  if (!object || isEmpty(object)) {
133
152
  return null
@@ -138,7 +157,7 @@ export default class InsightAPIClient {
138
157
 
139
158
  async fetchRawTx(txId) {
140
159
  const encodedTxId = encodeURIComponent(txId)
141
- const url = urlJoin(this._baseURL, `/rawtx/${encodedTxId}`)
160
+ const url = urlJoin(this.#baseURL, `/rawtx/${encodedTxId}`)
142
161
  const { rawtx } = await fetchJson(url, undefined, false, INSIGHT_HTTP_ERROR_RAWTX_MESSAGE)
143
162
  return rawtx
144
163
  }
@@ -147,7 +166,7 @@ export default class InsightAPIClient {
147
166
  if (!Array.isArray(addrs) || addrs.length === 0) return { items: [], totalItems: 0 }
148
167
 
149
168
  options = { noScriptSig: 1, noAsm: 1, noSpent: 0, from: 0, to: 10, ...options }
150
- const url = `${urlJoin(this._baseURL, '/addrs/txs')}?${new URLSearchParams(options)}`
169
+ const url = `${urlJoin(this.#baseURL, '/addrs/txs')}?${new URLSearchParams(options)}`
151
170
 
152
171
  const fetchOptions = {
153
172
  method: 'post',
@@ -156,10 +175,15 @@ export default class InsightAPIClient {
156
175
  'Content-Type': 'application/json',
157
176
  },
158
177
  body: JSON.stringify({ addrs: addrs.join(',') }),
159
- timeout: 25_000,
178
+ timeout: this.#addressTxsTimeout,
160
179
  }
161
180
 
162
- return fetchJsonRetry(url, fetchOptions, INSIGHT_HTTP_ERROR_ADDRS_TXS_MESSAGE)
181
+ return fetchJsonRetry(
182
+ url,
183
+ fetchOptions,
184
+ INSIGHT_HTTP_ERROR_ADDRS_TXS_MESSAGE,
185
+ this.#addressTxsRetryWaitTimes
186
+ )
163
187
  }
164
188
 
165
189
  async fetchAllTxData(addrs = [], chunk = 25, httpDelay = 2000, shouldStopFetching = () => {}) {
@@ -181,19 +205,19 @@ export default class InsightAPIClient {
181
205
 
182
206
  async fetchUnconfirmedAncestorData(txId) {
183
207
  const encodedTxId = encodeURIComponent(txId)
184
- const url = urlJoin(this._baseURL, `/unconfirmed_ancestor/${encodedTxId}`)
208
+ const url = urlJoin(this.#baseURL, `/unconfirmed_ancestor/${encodedTxId}`)
185
209
  return fetchJson(url, undefined, false, INSIGHT_HTTP_ERROR_UNCONFIRMED_ANCESTOR_MESSAGE)
186
210
  }
187
211
 
188
212
  async fetchFeeRate() {
189
- const url = urlJoin(this._baseURL, '/v2/fees')
213
+ const url = urlJoin(this.#baseURL, '/v2/fees')
190
214
  return fetchJson(url, undefined, false, INSIGHT_HTTP_ERROR_FEES_MESSAGE)
191
215
  }
192
216
 
193
217
  async broadcastTx(rawTx) {
194
218
  const _rawTx = rawTx instanceof Uint8Array ? Buffer.from(rawTx).toString('hex') : rawTx
195
219
  console.log('gonna broadcastTx')
196
- const url = urlJoin(this._baseURL, '/tx/send')
220
+ const url = urlJoin(this.#baseURL, '/tx/send')
197
221
  const fetchOptions = {
198
222
  method: 'post',
199
223
  headers: {
@@ -9,11 +9,15 @@ import fetchWithTimeout from './fetch-with-timeout.js'
9
9
  const API_PAGE_SIZE = 25
10
10
  const DEFAULT_PAGE_SIZE = 10
11
11
  const RETRY_WAIT_TIMES = ['5s', '10s', '20s', '30s']
12
+ // A monitor tick scans every wallet account in parallel and each scan asks for the
13
+ // tip height, producing identical /blocks/tip/height requests within the same second.
14
+ // Serving them from a short-lived cache keeps one request per tick without letting
15
+ // confirmation counts go meaningfully stale.
16
+ const TIP_HEIGHT_CACHE_TTL_MS = 10_000
12
17
 
13
18
  const MEMPOOL_HTTP_ERROR_MESSAGE = safeString`mempool-api-http-error`
14
- const MEMPOOL_INSIGHT_JSON_ERROR_MESSAGE = safeString`mempool-insight-api-invalid-json`
15
- const MEMPOOL_INSIGHT_MISSING_TXID_MESSAGE = safeString`mempool-insight-api-missing-txid`
16
- const MEMPOOL_INSIGHT_HTTP_ERROR_BROADCAST_MESSAGE = safeString`mempool-insight-api-http-error:broadcast`
19
+ const MEMPOOL_MISSING_TXID_MESSAGE = safeString`mempool-api-missing-txid`
20
+ const MEMPOOL_HTTP_ERROR_BROADCAST_MESSAGE = safeString`mempool-api-http-error:broadcast`
17
21
  const MEMPOOL_JSON_ERROR_MESSAGE = safeString`mempool-api-invalid-json`
18
22
  const MEMPOOL_TEXT_ERROR_MESSAGE = safeString`mempool-api-invalid-text`
19
23
  const MEMPOOL_HTTP_ERROR_TX_MESSAGE = safeString`mempool-api-http-error:tx`
@@ -29,6 +33,9 @@ const MEMPOOL_HTTP_ERROR_CPFP_MESSAGE = safeString`mempool-api-http-error:cpfp`
29
33
  const MEMPOOL_FEES_PAYLOAD_ERROR_MESSAGE = safeString`mempool-api-invalid-fees-payload`
30
34
  const MEMPOOL_INVALID_VALUE_ERROR_MESSAGE = safeString`mempool-api-invalid-value`
31
35
 
36
+ // A txid is a double-SHA256 hash: always exactly 32 bytes / 64 hex chars.
37
+ const TXID_HEX_PATTERN = /^[\da-f]{64}$/i
38
+
32
39
  const parseBroadcastErrorReason = (data) => {
33
40
  if (!data) {
34
41
  return null
@@ -208,24 +215,19 @@ const normalizeTx = (tx, tipHeight, outspends) => {
208
215
  }
209
216
 
210
217
  export default class MempoolRestClient {
211
- constructor({
212
- mempoolBaseURL,
213
- clarityBaseURL,
214
- retryWaitTimes = RETRY_WAIT_TIMES,
215
- configMinFeeRate = 10,
216
- } = {}) {
218
+ constructor({ mempoolBaseURL, retryWaitTimes = RETRY_WAIT_TIMES, configMinFeeRate = 10 } = {}) {
217
219
  this._mempoolBaseURL = mempoolBaseURL
218
- this._clarityBaseURL = clarityBaseURL
219
220
  this._retryWaitTimes = retryWaitTimes
220
221
  this._configMinFeeRate = configMinFeeRate
222
+ this._tipHeightCache = null
221
223
  }
222
224
 
223
225
  setMempoolBaseUrl(mempoolBaseURL) {
224
- this._mempoolBaseURL = mempoolBaseURL
225
- }
226
+ if (mempoolBaseURL !== this._mempoolBaseURL) {
227
+ this._tipHeightCache = null
228
+ }
226
229
 
227
- setClarityBaseUrl(clarityBaseURL) {
228
- this._clarityBaseURL = clarityBaseURL
230
+ this._mempoolBaseURL = mempoolBaseURL
229
231
  }
230
232
 
231
233
  _mempoolApiUrl(path, { version } = {}) {
@@ -233,6 +235,29 @@ export default class MempoolRestClient {
233
235
  }
234
236
 
235
237
  async _fetchTipHeight() {
238
+ const now = Date.now()
239
+ if (this._tipHeightCache && now - this._tipHeightCache.startedAt < TIP_HEIGHT_CACHE_TTL_MS) {
240
+ return this._tipHeightCache.promise
241
+ }
242
+
243
+ // Start one fetch and cache its promise right away, before it finishes.
244
+ // Anyone who asks for the tip height while it's still loading gets the same
245
+ // promise back, so N concurrent callers result in exactly one network request.
246
+ const promise = this._fetchTipHeightFresh()
247
+ const cacheEntry = { promise, startedAt: now }
248
+ this._tipHeightCache = cacheEntry
249
+ promise.catch(() => {
250
+ // The fetch failed, so throw this entry away — otherwise every caller for
251
+ // the next TTL would receive the same error instead of a retry. Only clear
252
+ // it if it's still ours: a newer fetch may have replaced it already.
253
+ if (this._tipHeightCache === cacheEntry) {
254
+ this._tipHeightCache = null
255
+ }
256
+ })
257
+ return promise
258
+ }
259
+
260
+ async _fetchTipHeightFresh() {
236
261
  const tipText = await fetchText(
237
262
  this._mempoolApiUrl('/blocks/tip/height'),
238
263
  { timeout: 10_000 },
@@ -622,47 +647,37 @@ export default class MempoolRestClient {
622
647
  return { size, fees: Math.round(fees) }
623
648
  }
624
649
 
625
- // Keep broadcast behavior aligned with the existing insight client.
626
- // Our Insight/Magnifier path fans out to Exodus-managed bitcoin nodes and has the
627
- // operational behavior we already depend on when propagation is slow or a rejection
628
- // is temporary. The mempool REST API alone is not a drop-in replacement for that.
650
+ // mempool.space/esplora broadcast: POST the raw hex as text, success is the
651
+ // txid as plain text, rejections are 400s whose text body carries bitcoind's
652
+ // sendrawtransaction reason (e.g. `txn-already-in-mempool`, `missing inputs`).
653
+ // That reason is preserved on `error.reason` because tx-send retry
654
+ // classification (broadcast-tx.js) pattern-matches it.
629
655
  async broadcastTx(rawTx) {
630
656
  const payload = rawTx instanceof Uint8Array ? Buffer.from(rawTx).toString('hex') : rawTx
631
- const response = await fetch(urlJoin(this._clarityBaseURL, '/tx/send'), {
657
+ const response = await fetch(this._mempoolApiUrl('/tx'), {
632
658
  method: 'post',
633
659
  headers: {
634
- Accept: 'application/json',
635
- 'Content-Type': 'application/json',
660
+ Accept: 'text/plain',
661
+ 'Content-Type': 'text/plain',
636
662
  },
637
- body: JSON.stringify({ rawtx: payload }),
663
+ body: payload,
638
664
  })
639
665
 
640
- let data = await response.text()
666
+ const data = await response.text()
641
667
 
642
668
  if (!response.ok) {
643
- console.warn(`Mempool Client's Insight Broadcast HTTP Error:`)
669
+ console.warn(`Mempool Client's Broadcast HTTP Error:`)
644
670
  console.warn(response.statusText)
645
671
  console.warn(data)
646
- const error = createHttpError(response, MEMPOOL_INSIGHT_HTTP_ERROR_BROADCAST_MESSAGE)
672
+ const error = createHttpError(response, MEMPOOL_HTTP_ERROR_BROADCAST_MESSAGE)
647
673
  error.reason = parseBroadcastErrorReason(data)
648
674
  throw error
649
675
  }
650
676
 
651
- try {
652
- data = JSON.parse(data)
653
- } catch (err) {
654
- console.warn(`Mempool Client's Insight Broadcast JSON Parse Error:`, err.message, data)
655
- const error = new Error(MEMPOOL_INSIGHT_JSON_ERROR_MESSAGE, { cause: err })
656
- const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
657
- if (traceId) {
658
- error.traceId = traceId
659
- }
660
-
661
- throw error
662
- }
663
-
664
- if (!data.txid) {
665
- const error = new Error(MEMPOOL_INSIGHT_MISSING_TXID_MESSAGE)
677
+ const txid = String(data).trim()
678
+ if (!TXID_HEX_PATTERN.test(txid)) {
679
+ console.warn(`Mempool Client's Broadcast Unexpected Payload:`, data)
680
+ const error = new Error(MEMPOOL_MISSING_TXID_MESSAGE)
666
681
  const traceId = TraceId.fromResponse && TraceId.fromResponse(response)
667
682
  if (traceId) {
668
683
  error.traceId = traceId
@@ -671,7 +686,6 @@ export default class MempoolRestClient {
671
686
  throw error
672
687
  }
673
688
 
674
- const { txid } = data
675
689
  return { txid }
676
690
  }
677
691
  }
@@ -118,10 +118,9 @@ export function toMempoolWebSocketUrl(apiUrl) {
118
118
  export function normalizeInsightConfig(config, monitorType) {
119
119
  const apiUrl = config?.insightServers?.[0]
120
120
  const mempoolApiUrl = config?.mempoolServer
121
- const clarityApiUrl = config?.clarityServer
122
121
  const wsUrl =
123
122
  monitorType === 'mempool'
124
123
  ? config?.mempoolServerWS || toMempoolWebSocketUrl(mempoolApiUrl)
125
124
  : config?.insightServersWS?.[0] || toWSUrl(apiUrl)
126
- return { apiUrl, mempoolApiUrl, clarityApiUrl, wsUrl }
125
+ return { apiUrl, mempoolApiUrl, wsUrl }
127
126
  }
@@ -91,21 +91,12 @@ export class Monitor extends BaseMonitor {
91
91
  }
92
92
 
93
93
  setServer(assetConfig = {}) {
94
- const { apiUrl, mempoolApiUrl, clarityApiUrl, wsUrl } = normalizeInsightConfig(
95
- assetConfig,
96
- this.#monitorType
97
- )
94
+ const { apiUrl, mempoolApiUrl, wsUrl } = normalizeInsightConfig(assetConfig, this.#monitorType)
98
95
 
99
96
  if (this.#monitorType === 'mempool') {
100
- const clarityBaseUrl = clarityApiUrl || apiUrl
101
-
102
97
  if (mempoolApiUrl) {
103
98
  this.#insightClient.setMempoolBaseUrl(mempoolApiUrl)
104
99
  }
105
-
106
- if (clarityBaseUrl) {
107
- this.#insightClient.setClarityBaseUrl(clarityBaseUrl)
108
- }
109
100
  } else if (apiUrl) {
110
101
  this.#insightClient.setBaseUrl(apiUrl)
111
102
  }