@exodus/bitcoin-api 5.0.13 → 5.1.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 +23 -0
- package/README.md +5 -3
- package/package.json +3 -3
- package/src/errors.js +209 -0
- package/src/insight-api-client/mempool-request-scheduler.js +19 -10
- package/src/insight-api-client/mempool-request.js +14 -8
- package/src/send-validation.js +1 -1
- package/src/tx-create/create-tx.js +23 -14
- package/src/tx-send/batch-tx.js +13 -2
- package/src/tx-send/index.js +69 -49
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.1.0](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.14...@exodus/bitcoin-api@5.1.0) (2026-11-16)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
### Features
|
|
10
|
+
|
|
11
|
+
* **bitcoin-api:** add EXOD send error codes and user hints ([#9206](https://github.com/ExodusMovement/assets/issues/9206)) ([83c3d0a](https://github.com/ExodusMovement/assets/commit/83c3d0a8c7277f4a84c492f7ffc7590b074363be))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
### Bug Fixes
|
|
15
|
+
|
|
16
|
+
* **bitcoin-api:** show dust limit in default units in send message ([#9334](https://github.com/ExodusMovement/assets/issues/9334)) ([cc7f622](https://github.com/ExodusMovement/assets/commit/cc7f622db063684f576ddd385d1fa9584504634f))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
## [5.0.14](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.13...@exodus/bitcoin-api@5.0.14) (2026-11-10)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
### Bug Fixes
|
|
24
|
+
|
|
25
|
+
* **bitcoin:** prioritize broadcasts over queued mempool reads ([#9260](https://github.com/ExodusMovement/assets/issues/9260)) ([616b21b](https://github.com/ExodusMovement/assets/commit/616b21bbbd82afd138a569323ef82e7e9e48eab4))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
6
29
|
## [5.0.13](https://github.com/ExodusMovement/assets/compare/@exodus/bitcoin-api@5.0.12...@exodus/bitcoin-api@5.0.13) (2026-11-03)
|
|
7
30
|
|
|
8
31
|
|
package/README.md
CHANGED
|
@@ -16,14 +16,16 @@ Confirmation checks recheck their inputs if a WebSocket update, disconnect, or b
|
|
|
16
16
|
|
|
17
17
|
## Mempool Retry-After
|
|
18
18
|
|
|
19
|
-
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.
|
|
19
|
+
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. A 429 from a broadcast dispatched during cooldown or recovery renews the read cooldown, including the fallback for missing or invalid `Retry-After`; an older recovery response cannot release that renewed cooldown. Broadcasts do not increase the fallback as failed recovery reads do.
|
|
20
20
|
|
|
21
21
|
Reads receiving HTTP 429 rejoin the end of the queue instead of immediately failing the monitor scan. Each read permits at most two retries, sharing its original 30-second queue deadline; cancellation, overflow, or expiry still fail finally. Exhausted retries fail 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.
|
|
22
22
|
|
|
23
23
|
## Mempool request scheduling
|
|
24
24
|
|
|
25
|
-
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
|
|
25
|
+
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 requests; 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.
|
|
26
26
|
|
|
27
|
-
Broadcasts
|
|
27
|
+
Broadcasts jump ahead of queued reads only when request capacity is available. Active requests and broadcasts waiting for pacing reserve the two request slots; when both slots are occupied or reserved, a new broadcast fails immediately with `MEMPOOL_REQUEST_BUSY` and `finalError`, without automatic retry or later dispatch. The read queue limit does not consume broadcast capacity. Accepted broadcasts preserve FIFO order and 200 ms pacing, with the original one-second queue deadline; expired broadcasts fail finally with `MEMPOOL_REQUEST_QUEUE_TIMEOUT`. Active requests remain uninterrupted. New and queued broadcasts bypass local cooldown and recovery waits. Broadcasts never become recovery probes, and their success does not release read cooldown. Dispatched broadcasts receiving 429 still establish read cooldown and fail without automatic replay.
|
|
28
|
+
|
|
29
|
+
Queue and request deadlines apply per attempt. The send wrapper can retry one non-final broadcast failure after ten seconds, so pacing waits and network timeouts across both attempts can total about 72 seconds, excluding transaction preparation and post-failure checks. The broadcast client does not currently accept a caller cancellation signal; consumers should await the send result rather than assume an earlier UI timeout cancels it.
|
|
28
30
|
|
|
29
31
|
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
|
+
"version": "5.1.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",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"test": "exodus-test --jest"
|
|
20
20
|
},
|
|
21
21
|
"dependencies": {
|
|
22
|
-
"@exodus/asset-lib": "^5.
|
|
22
|
+
"@exodus/asset-lib": "^5.10.0",
|
|
23
23
|
"@exodus/basic-utils": "^5.1.0",
|
|
24
24
|
"@exodus/bip32": "^4.1.0",
|
|
25
25
|
"@exodus/bip322-js": "^3.2.4",
|
|
@@ -60,5 +60,5 @@
|
|
|
60
60
|
"type": "git",
|
|
61
61
|
"url": "git+https://github.com/ExodusMovement/assets.git"
|
|
62
62
|
},
|
|
63
|
-
"gitHead": "
|
|
63
|
+
"gitHead": "2189bb5f649f746ce303d0453daf7c82ede80c8f"
|
|
64
64
|
}
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { createSendErrorTable, hasSendErrorCode, setSendErrorFields } from '@exodus/asset-lib'
|
|
2
|
+
import { safeString } from '@exodus/safe-string'
|
|
3
|
+
|
|
4
|
+
export const BTC_ERRORS = createSendErrorTable(3100, {
|
|
5
|
+
INPUTS_ALREADY_SPENT: {
|
|
6
|
+
code: 'EXOD-3163',
|
|
7
|
+
hint: safeString`Some funds were already spent, refresh your wallet and try again`,
|
|
8
|
+
action: 'refresh-and-retry',
|
|
9
|
+
patterns: [/missing inputs|missingorspent|inputs-spent|txn-mempool-conflict/i],
|
|
10
|
+
},
|
|
11
|
+
FEE_TOO_HIGH: {
|
|
12
|
+
code: 'EXOD-3102',
|
|
13
|
+
hint: safeString`Network fee is too high, lower the fee and try again`,
|
|
14
|
+
action: 'edit-transaction',
|
|
15
|
+
patterns: [/absurdly-high-fee|max-fee-exceeded/i],
|
|
16
|
+
},
|
|
17
|
+
FEE_TOO_LOW: {
|
|
18
|
+
code: 'EXOD-3101',
|
|
19
|
+
hint: safeString`Network fee is too low, raise the fee and try again`,
|
|
20
|
+
action: 'edit-transaction',
|
|
21
|
+
patterns: [/min relay fee not met|mempool min fee not met|insufficient fee|min-fee-not-met/i],
|
|
22
|
+
},
|
|
23
|
+
TOO_MANY_UNCONFIRMED: {
|
|
24
|
+
code: 'EXOD-3142',
|
|
25
|
+
hint: safeString`Too many unconfirmed transactions, wait for a confirmation and try again`,
|
|
26
|
+
action: 'retry-later',
|
|
27
|
+
patterns: [/too-long-mempool-chain/i],
|
|
28
|
+
},
|
|
29
|
+
TX_TOO_LARGE: {
|
|
30
|
+
code: 'EXOD-3141',
|
|
31
|
+
hint: safeString`Transaction is too large, try sending a smaller amount`,
|
|
32
|
+
action: 'edit-transaction',
|
|
33
|
+
patterns: [/tx-size(?!-small)|bad-txns-oversize/i],
|
|
34
|
+
},
|
|
35
|
+
AMOUNT_TOO_SMALL: {
|
|
36
|
+
code: 'EXOD-3140',
|
|
37
|
+
hint: safeString`Amount is too small to send`,
|
|
38
|
+
action: 'edit-transaction',
|
|
39
|
+
patterns: [/\bdust\b/i],
|
|
40
|
+
},
|
|
41
|
+
INVALID_SIGNATURE: {
|
|
42
|
+
code: 'EXOD-3143',
|
|
43
|
+
hint: safeString`Network rejected the transaction signature`,
|
|
44
|
+
action: 'contact-support',
|
|
45
|
+
patterns: [/script-verify-flag/i],
|
|
46
|
+
},
|
|
47
|
+
REPLACEMENT_REJECTED: {
|
|
48
|
+
code: 'EXOD-3181',
|
|
49
|
+
hint: safeString`Network rejected the speed up, try again later`,
|
|
50
|
+
action: 'retry-later',
|
|
51
|
+
patterns: [/replacement-adds-unconfirmed|too many potential replacements/i],
|
|
52
|
+
},
|
|
53
|
+
INVALID_RECIPIENT: {
|
|
54
|
+
code: 'EXOD-3120',
|
|
55
|
+
hint: safeString`Recipient address is not supported on this network`,
|
|
56
|
+
action: 'edit-transaction',
|
|
57
|
+
patterns: [/has no matching script|invalid address|\bscriptpubkey\b/i],
|
|
58
|
+
},
|
|
59
|
+
INSUFFICIENT_FUNDS: {
|
|
60
|
+
code: 'EXOD-3100',
|
|
61
|
+
hint: safeString`Not enough funds to cover the amount and network fee`,
|
|
62
|
+
action: 'add-funds',
|
|
63
|
+
patterns: [/^not enough funds\.?$|insufficient funds/i],
|
|
64
|
+
},
|
|
65
|
+
CANNOT_SPEED_UP: {
|
|
66
|
+
code: 'EXOD-3180',
|
|
67
|
+
hint: safeString`This transaction can no longer be sped up`,
|
|
68
|
+
action: 'edit-transaction',
|
|
69
|
+
patterns: [/cannot bump transaction|unable to bump/i],
|
|
70
|
+
},
|
|
71
|
+
BUILD_FAILED: {
|
|
72
|
+
code: 'EXOD-3145',
|
|
73
|
+
hint: safeString`Transaction could not be built, try a different amount`,
|
|
74
|
+
action: 'edit-transaction',
|
|
75
|
+
patterns: [/cannot create transaction without outputs/i],
|
|
76
|
+
},
|
|
77
|
+
|
|
78
|
+
SIGNING_FAILED: {
|
|
79
|
+
code: 'EXOD-3144',
|
|
80
|
+
hint: safeString`Transaction was not signed, try again`,
|
|
81
|
+
action: 'retry',
|
|
82
|
+
},
|
|
83
|
+
NETWORK_UNREACHABLE: {
|
|
84
|
+
code: 'EXOD-3160',
|
|
85
|
+
hint: safeString`Could not reach the network, check your connection and try again`,
|
|
86
|
+
action: 'retry',
|
|
87
|
+
},
|
|
88
|
+
NETWORK_BUSY: {
|
|
89
|
+
code: 'EXOD-3161',
|
|
90
|
+
hint: safeString`Network is busy, try again in a moment`,
|
|
91
|
+
action: 'retry-later',
|
|
92
|
+
},
|
|
93
|
+
NODE_UNAVAILABLE: {
|
|
94
|
+
code: 'EXOD-3162',
|
|
95
|
+
hint: safeString`Network service is unavailable, try again later`,
|
|
96
|
+
action: 'retry-later',
|
|
97
|
+
},
|
|
98
|
+
TX_REJECTED: {
|
|
99
|
+
code: 'EXOD-3164',
|
|
100
|
+
hint: safeString`Network rejected this transaction`,
|
|
101
|
+
action: 'contact-support',
|
|
102
|
+
},
|
|
103
|
+
BROADCAST_OUTCOME_UNKNOWN: {
|
|
104
|
+
code: 'EXOD-3165',
|
|
105
|
+
hint: safeString`Transaction status is unknown, check your history before sending again`,
|
|
106
|
+
action: 'check-history',
|
|
107
|
+
},
|
|
108
|
+
TX_RECORD_FAILED: {
|
|
109
|
+
code: 'EXOD-3166',
|
|
110
|
+
hint: safeString`The transaction was sent but could not be saved, check your history before sending again`,
|
|
111
|
+
action: 'check-history',
|
|
112
|
+
},
|
|
113
|
+
UNKNOWN_SEND_FAILURE: {
|
|
114
|
+
code: 'EXOD-3199',
|
|
115
|
+
hint: safeString`Transaction failed, try again or contact support`,
|
|
116
|
+
action: 'refresh-and-retry',
|
|
117
|
+
},
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
const ENTRIES = Object.entries(BTC_ERRORS)
|
|
121
|
+
|
|
122
|
+
const findPatternKey = (text) =>
|
|
123
|
+
ENTRIES.find(([, { patterns }]) => patterns?.some((pattern) => pattern.test(text)))?.[0]
|
|
124
|
+
|
|
125
|
+
const TRANSPORT_PATTERN =
|
|
126
|
+
/network request failed|failed to fetch|fetch failed|timed out|socket hang up|ECONNRESET|ECONNREFUSED|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|ENETUNREACH|EPIPE/i
|
|
127
|
+
const NOT_SENT_CODES = new Set([
|
|
128
|
+
'ENOTFOUND',
|
|
129
|
+
'EAI_AGAIN',
|
|
130
|
+
'ECONNREFUSED',
|
|
131
|
+
'ENETUNREACH',
|
|
132
|
+
'EHOSTUNREACH',
|
|
133
|
+
])
|
|
134
|
+
const OUTCOME_UNKNOWN_PATTERN =
|
|
135
|
+
/network request failed|failed to fetch|fetch failed|^terminated$|timed out|timeout|socket hang up|ECONNRESET|ETIMEDOUT|EPIPE|UND_ERR_SOCKET/i
|
|
136
|
+
const OUTCOME_UNKNOWN_HTTP_CODES = new Set(['502', '504', '520', '524'])
|
|
137
|
+
const NATIVE_ABORT_NAMES = new Set(['AbortError', 'TimeoutError'])
|
|
138
|
+
const BAD_PAYLOAD_PATTERN = /^(insight|mempool)-api-(invalid-json|invalid-text|missing-txid)$/
|
|
139
|
+
const BROADCAST_MESSAGE_PATTERN = /-api-http-error:broadcast$/
|
|
140
|
+
const BUSY_CODES = new Set(['429', 'MEMPOOL_REQUEST_BUSY', 'MEMPOOL_REQUEST_QUEUE_TIMEOUT'])
|
|
141
|
+
|
|
142
|
+
const getErrorText = (error) =>
|
|
143
|
+
[error.message, error.reason].filter((value) => typeof value === 'string').join(' ')
|
|
144
|
+
|
|
145
|
+
const getTransportText = (error) =>
|
|
146
|
+
[error.message, error.code, error.cause?.message, error.cause?.code]
|
|
147
|
+
.filter((value) => typeof value === 'string')
|
|
148
|
+
.join(' ')
|
|
149
|
+
|
|
150
|
+
export function parseBtcErrorKey(error) {
|
|
151
|
+
const text = getErrorText(error)
|
|
152
|
+
const code = typeof error.code === 'string' ? error.code : undefined
|
|
153
|
+
|
|
154
|
+
const patternKey = findPatternKey(text)
|
|
155
|
+
if (patternKey) return patternKey
|
|
156
|
+
|
|
157
|
+
if (code && BUSY_CODES.has(code)) return 'NETWORK_BUSY'
|
|
158
|
+
if (NATIVE_ABORT_NAMES.has(error.name) || TRANSPORT_PATTERN.test(text)) {
|
|
159
|
+
return 'NETWORK_UNREACHABLE'
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if ((code && /^5\d\d$/.test(code)) || BAD_PAYLOAD_PATTERN.test(error.message)) {
|
|
163
|
+
return 'NODE_UNAVAILABLE'
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (BROADCAST_MESSAGE_PATTERN.test(error.message)) return 'TX_REJECTED'
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function setBtcErrorCode(error, key) {
|
|
170
|
+
return setSendErrorFields(error, BTC_ERRORS, key)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function toBtcSendError(error, fallbackKey = 'UNKNOWN_SEND_FAILURE') {
|
|
174
|
+
if (!error || typeof error !== 'object') return error
|
|
175
|
+
if (hasSendErrorCode(BTC_ERRORS, error.code)) return error
|
|
176
|
+
if (NATIVE_ABORT_NAMES.has(error.name)) return setBtcErrorCode(error, 'NETWORK_UNREACHABLE')
|
|
177
|
+
|
|
178
|
+
return setBtcErrorCode(error, parseBtcErrorKey(error) ?? fallbackKey)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const isOutcomeUnknownAttempt = (error) => {
|
|
182
|
+
if (!error || typeof error !== 'object') return false
|
|
183
|
+
if (NATIVE_ABORT_NAMES.has(error.name)) return true
|
|
184
|
+
if (BUSY_CODES.has(error.code)) return false
|
|
185
|
+
if (NOT_SENT_CODES.has(error.code) || NOT_SENT_CODES.has(error.cause?.code)) return false
|
|
186
|
+
if (findPatternKey(getErrorText(error))) return false
|
|
187
|
+
const text = getTransportText(error)
|
|
188
|
+
return (
|
|
189
|
+
OUTCOME_UNKNOWN_PATTERN.test(text) ||
|
|
190
|
+
OUTCOME_UNKNOWN_HTTP_CODES.has(error.code) ||
|
|
191
|
+
BAD_PAYLOAD_PATTERN.test(error.message) ||
|
|
192
|
+
parseBtcErrorKey(error) === undefined
|
|
193
|
+
)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function toBtcBroadcastError(error) {
|
|
197
|
+
if (!error || typeof error !== 'object' || hasSendErrorCode(BTC_ERRORS, error.code)) return error
|
|
198
|
+
const attempts = [error, ...(Array.isArray(error.errorChain) ? error.errorChain : [])]
|
|
199
|
+
if (attempts.some(isOutcomeUnknownAttempt)) {
|
|
200
|
+
return setBtcErrorCode(error, 'BROADCAST_OUTCOME_UNKNOWN')
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return toBtcSendError(error, 'BROADCAST_OUTCOME_UNKNOWN')
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function toBtcTxRecordError(error) {
|
|
207
|
+
if (!error || typeof error !== 'object') return error
|
|
208
|
+
return setBtcErrorCode(error, 'TX_RECORD_FAILED')
|
|
209
|
+
}
|
|
@@ -2,8 +2,9 @@ import { safeString } from '@exodus/safe-string'
|
|
|
2
2
|
|
|
3
3
|
const MAX_ACTIVE_REQUESTS = 2
|
|
4
4
|
const REQUEST_INTERVAL_MS = 200
|
|
5
|
-
const
|
|
5
|
+
const MAX_QUEUED_READS = 100
|
|
6
6
|
const MAX_QUEUE_WAIT_MS = 30_000
|
|
7
|
+
const MAX_BROADCAST_QUEUE_WAIT_MS = 1000
|
|
7
8
|
const MAX_READ_RETRIES = 2
|
|
8
9
|
const schedulersByOrigin = new Map()
|
|
9
10
|
|
|
@@ -33,15 +34,17 @@ const drain = (origin) => {
|
|
|
33
34
|
clearTimeout(scheduler.wakeTimer)
|
|
34
35
|
scheduler.wakeTimer = null
|
|
35
36
|
const cooldown = scheduler.getCooldown?.()
|
|
36
|
-
|
|
37
|
+
const broadcastIndex = scheduler.queue.findIndex((entry) => entry.isBroadcast)
|
|
38
|
+
if (broadcastIndex === -1 && scheduler.queue.length > 0 && cooldown?.retryAt > Date.now()) {
|
|
37
39
|
scheduler.wakeTimer = setTimeout(() => drain(origin), cooldown.retryAt - Date.now())
|
|
38
40
|
} else if (
|
|
39
41
|
scheduler.active < MAX_ACTIVE_REQUESTS &&
|
|
40
42
|
!scheduler.timer &&
|
|
41
|
-
!cooldown?.recovering &&
|
|
43
|
+
(broadcastIndex !== -1 || !cooldown?.recovering) &&
|
|
42
44
|
scheduler.queue.length > 0
|
|
43
45
|
) {
|
|
44
|
-
|
|
46
|
+
// Give sends the next available slot without interrupting active requests.
|
|
47
|
+
const [entry] = scheduler.queue.splice(broadcastIndex === -1 ? 0 : broadcastIndex, 1)
|
|
45
48
|
entry.cleanup()
|
|
46
49
|
scheduler.active++
|
|
47
50
|
scheduler.timer = setTimeout(() => {
|
|
@@ -68,7 +71,11 @@ const drain = (origin) => {
|
|
|
68
71
|
|
|
69
72
|
export const resumeMempoolRequests = (origin) => drain(origin)
|
|
70
73
|
|
|
71
|
-
function enqueueMempoolRequest(
|
|
74
|
+
function enqueueMempoolRequest(
|
|
75
|
+
origin,
|
|
76
|
+
execute,
|
|
77
|
+
{ signal, isBroadcast = false, getCooldown, expiresAt }
|
|
78
|
+
) {
|
|
72
79
|
if (signal?.aborted) return Promise.reject(createAbortError(signal))
|
|
73
80
|
const maxWaitMs = expiresAt - Date.now()
|
|
74
81
|
if (maxWaitMs <= 0) {
|
|
@@ -80,10 +87,10 @@ function enqueueMempoolRequest(origin, execute, { signal, isBroadcast, getCooldo
|
|
|
80
87
|
schedulersByOrigin.set(origin, scheduler)
|
|
81
88
|
}
|
|
82
89
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
) {
|
|
90
|
+
const queuedCount = scheduler.queue.filter((entry) => entry.isBroadcast === isBroadcast).length
|
|
91
|
+
// Broadcasts can wait for pacing, but never for an occupied request slot.
|
|
92
|
+
const queueLimit = isBroadcast ? MAX_ACTIVE_REQUESTS - scheduler.active : MAX_QUEUED_READS
|
|
93
|
+
if (queuedCount >= queueLimit) {
|
|
87
94
|
return Promise.reject(createQueueError('MEMPOOL_REQUEST_BUSY'))
|
|
88
95
|
}
|
|
89
96
|
|
|
@@ -93,6 +100,7 @@ function enqueueMempoolRequest(origin, execute, { signal, isBroadcast, getCooldo
|
|
|
93
100
|
resolve,
|
|
94
101
|
reject,
|
|
95
102
|
expiresAt,
|
|
103
|
+
isBroadcast,
|
|
96
104
|
cleanup: () => {
|
|
97
105
|
clearTimeout(timeout)
|
|
98
106
|
signal?.removeEventListener('abort', onAbort)
|
|
@@ -121,7 +129,8 @@ function enqueueMempoolRequest(origin, execute, { signal, isBroadcast, getCooldo
|
|
|
121
129
|
}
|
|
122
130
|
|
|
123
131
|
export default async function scheduleMempoolRequest(origin, execute, options = {}) {
|
|
124
|
-
const expiresAt =
|
|
132
|
+
const expiresAt =
|
|
133
|
+
Date.now() + (options.isBroadcast ? MAX_BROADCAST_QUEUE_WAIT_MS : MAX_QUEUE_WAIT_MS)
|
|
125
134
|
for (let attempt = 0; ; attempt++) {
|
|
126
135
|
try {
|
|
127
136
|
return await enqueueMempoolRequest(origin, execute, { ...options, expiresAt })
|
|
@@ -41,9 +41,9 @@ const createRateLimitError = (retryAt, response) => {
|
|
|
41
41
|
return error
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
-
const enterCooldown = (origin, recoveryState, retryAfterMs) => {
|
|
44
|
+
const enterCooldown = (origin, recoveryState, retryAfterMs, renewCooldown = false) => {
|
|
45
45
|
let state = rateLimitsByOrigin.get(origin)
|
|
46
|
-
if (!state || recoveryState || retryAfterMs !== undefined) {
|
|
46
|
+
if (!state || recoveryState || retryAfterMs !== undefined || renewCooldown) {
|
|
47
47
|
const backoffMs = state
|
|
48
48
|
? Math.min(state.backoffMs * (recoveryState ? 2 : 1), MAX_RETRY_AFTER_MS)
|
|
49
49
|
: INITIAL_BACKOFF_MS
|
|
@@ -60,17 +60,18 @@ const enterCooldown = (origin, recoveryState, retryAfterMs) => {
|
|
|
60
60
|
return state
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
const checkCooldown = (origin
|
|
63
|
+
const checkCooldown = (origin) => {
|
|
64
64
|
const state = rateLimitsByOrigin.get(origin)
|
|
65
|
-
if (state && (Date.now() < state.retryAt || recoveringOrigins.has(origin)
|
|
65
|
+
if (state && (Date.now() < state.retryAt || recoveringOrigins.has(origin))) {
|
|
66
66
|
throw createRateLimitError(state.retryAt)
|
|
67
67
|
}
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
async function executeRequest(url, fetchOptions, consumeResponse, isBroadcast) {
|
|
71
71
|
const origin = new URL(url).origin
|
|
72
|
-
checkCooldown(origin
|
|
73
|
-
const
|
|
72
|
+
if (!isBroadcast) checkCooldown(origin)
|
|
73
|
+
const cooldownAtDispatch = rateLimitsByOrigin.get(origin)
|
|
74
|
+
const recoveryState = isBroadcast ? undefined : cooldownAtDispatch
|
|
74
75
|
let recoveryResponseHandled = false
|
|
75
76
|
if (recoveryState) {
|
|
76
77
|
recoveringOrigins.add(origin)
|
|
@@ -87,7 +88,13 @@ async function executeRequest(url, fetchOptions, consumeResponse, isBroadcast) {
|
|
|
87
88
|
return await fetchWithTimeout(url, fetchOptions, async (response) => {
|
|
88
89
|
try {
|
|
89
90
|
if (response.status === 429) {
|
|
90
|
-
|
|
91
|
+
// A new send during cooldown must renew it; delayed pre-cooldown responses need not.
|
|
92
|
+
const state = enterCooldown(
|
|
93
|
+
origin,
|
|
94
|
+
recoveryState,
|
|
95
|
+
getRetryAfterMs(response, Date.now()),
|
|
96
|
+
isBroadcast && cooldownAtDispatch !== undefined
|
|
97
|
+
)
|
|
91
98
|
recoveryResponseHandled = true
|
|
92
99
|
throw createRateLimitError(state.retryAt, response)
|
|
93
100
|
}
|
|
@@ -137,7 +144,6 @@ export default async function mempoolRequest(
|
|
|
137
144
|
{ isBroadcast = false } = {}
|
|
138
145
|
) {
|
|
139
146
|
const origin = new URL(url).origin
|
|
140
|
-
if (isBroadcast) checkCooldown(origin, true)
|
|
141
147
|
return scheduleMempoolRequest(
|
|
142
148
|
origin,
|
|
143
149
|
() => executeRequest(url, fetchOptions, consumeResponse, isBroadcast),
|
package/src/send-validation.js
CHANGED
|
@@ -4,6 +4,7 @@ import lodash from 'lodash'
|
|
|
4
4
|
import assert from 'minimalistic-assert'
|
|
5
5
|
|
|
6
6
|
import { getChangeDustValue } from '../dust.js'
|
|
7
|
+
import { setBtcErrorCode, toBtcSendError } from '../errors.js'
|
|
7
8
|
import { parseCurrency, serializeCurrency } from '../fee/fee-utils.js'
|
|
8
9
|
import { selectUtxos } from '../fee/utxo-selector.js'
|
|
9
10
|
import { createPsbtWithMetadata } from '../psbt-builder.js'
|
|
@@ -468,7 +469,7 @@ const transferHandler = {
|
|
|
468
469
|
let selectedUtxos = initialSelectedUtxos
|
|
469
470
|
|
|
470
471
|
if (!selectedUtxos?.size && !replaceTx) {
|
|
471
|
-
throw new Error('Not enough funds.')
|
|
472
|
+
throw setBtcErrorCode(new Error('Not enough funds.'), 'INSUFFICIENT_FUNDS')
|
|
472
473
|
}
|
|
473
474
|
|
|
474
475
|
// When bumping a tx, we can either replace the tx with RBF or spend its selected change.
|
|
@@ -554,19 +555,18 @@ const transferHandler = {
|
|
|
554
555
|
},
|
|
555
556
|
}
|
|
556
557
|
|
|
557
|
-
export const createTxFactory =
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
async ({
|
|
558
|
+
export const createTxFactory = ({
|
|
559
|
+
getFeeEstimator,
|
|
560
|
+
allowUnconfirmedRbfEnabledUtxos,
|
|
561
|
+
utxosDescendingOrder,
|
|
562
|
+
assetClientInterface,
|
|
563
|
+
changeAddressType,
|
|
564
|
+
allowedPurposes,
|
|
565
|
+
authenticateReplacementTransactions = false,
|
|
566
|
+
Psbt = DefaultPsbt,
|
|
567
|
+
Transaction = DefaultTransaction,
|
|
568
|
+
}) => {
|
|
569
|
+
const createTx = async ({
|
|
570
570
|
asset,
|
|
571
571
|
walletAccount,
|
|
572
572
|
type,
|
|
@@ -617,3 +617,12 @@ export const createTxFactory =
|
|
|
617
617
|
authenticateReplacementTransactions,
|
|
618
618
|
})
|
|
619
619
|
}
|
|
620
|
+
|
|
621
|
+
return async (params) => {
|
|
622
|
+
try {
|
|
623
|
+
return await createTx(params)
|
|
624
|
+
} catch (err) {
|
|
625
|
+
throw toBtcSendError(err)
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
}
|
package/src/tx-send/batch-tx.js
CHANGED
|
@@ -4,6 +4,7 @@ import BipPath from 'bip32-path'
|
|
|
4
4
|
import lodash from 'lodash' // mockable in tests
|
|
5
5
|
import assert from 'minimalistic-assert'
|
|
6
6
|
|
|
7
|
+
import { setBtcErrorCode, toBtcSendError } from '../errors.js'
|
|
7
8
|
import { selectUtxos } from '../fee/utxo-selector.js'
|
|
8
9
|
import { getUnconfirmedTxAncestorMap } from '../unconfirmed-ancestor-data.js'
|
|
9
10
|
import { getUsableUtxos, getUtxos } from '../utxos-utils.js'
|
|
@@ -21,7 +22,7 @@ export const getCreateBatchTransaction = ({
|
|
|
21
22
|
}) => {
|
|
22
23
|
assert(assetClientInterface, `assetClientInterface must be supplied in sendTx`)
|
|
23
24
|
|
|
24
|
-
|
|
25
|
+
const createBatchTx = async ({ asset, walletAccount, recipients, options = {} }) => {
|
|
25
26
|
const assetName = asset.name
|
|
26
27
|
const {
|
|
27
28
|
feeData = await assetClientInterface.getFeeConfig({ assetName }),
|
|
@@ -59,7 +60,9 @@ export const getCreateBatchTransaction = ({
|
|
|
59
60
|
allowUnconfirmedRbfEnabledUtxos,
|
|
60
61
|
})
|
|
61
62
|
|
|
62
|
-
if (!selectedUtxos?.size)
|
|
63
|
+
if (!selectedUtxos?.size) {
|
|
64
|
+
throw setBtcErrorCode(new Error('Not enough funds.'), 'INSUFFICIENT_FUNDS')
|
|
65
|
+
}
|
|
63
66
|
|
|
64
67
|
const addressPathsMap = selectedUtxos.getAddressPathsMap()
|
|
65
68
|
|
|
@@ -222,4 +225,12 @@ export const getCreateBatchTransaction = ({
|
|
|
222
225
|
|
|
223
226
|
return psbt
|
|
224
227
|
}
|
|
228
|
+
|
|
229
|
+
return async (params) => {
|
|
230
|
+
try {
|
|
231
|
+
return await createBatchTx(params)
|
|
232
|
+
} catch (err) {
|
|
233
|
+
throw toBtcSendError(err)
|
|
234
|
+
}
|
|
235
|
+
}
|
|
225
236
|
}
|
package/src/tx-send/index.js
CHANGED
|
@@ -2,6 +2,7 @@ import * as defaultBitcoinjsLib from '@exodus/bitcoinjs'
|
|
|
2
2
|
import { Psbt as DefaultPsbt, Transaction as DefaultTransaction } from '@exodus/bitcoinjs'
|
|
3
3
|
import assert from 'minimalistic-assert'
|
|
4
4
|
|
|
5
|
+
import { toBtcBroadcastError, toBtcSendError, toBtcTxRecordError } from '../errors.js'
|
|
5
6
|
import { extractTransactionContext } from '../psbt-parser.js'
|
|
6
7
|
import { broadcastTransaction } from './broadcast-tx.js'
|
|
7
8
|
import { repairConfirmedSpentInputs } from './repair-spent-inputs.js'
|
|
@@ -152,7 +153,12 @@ export const sendTxFactory = ({
|
|
|
152
153
|
assert(assetClientInterface, 'assetClientInterface is required')
|
|
153
154
|
assert(createTx, 'createTx is required')
|
|
154
155
|
|
|
155
|
-
|
|
156
|
+
const sendTx = async ({
|
|
157
|
+
asset,
|
|
158
|
+
walletAccount,
|
|
159
|
+
unsignedTx: providedUnsignedTx,
|
|
160
|
+
...legacyParams
|
|
161
|
+
}) => {
|
|
156
162
|
const { address, ...createTxParams } = legacyParams
|
|
157
163
|
const assetName = asset.name
|
|
158
164
|
const accountState = await assetClientInterface.getAccountState({ assetName, walletAccount })
|
|
@@ -205,6 +211,8 @@ export const sendTxFactory = ({
|
|
|
205
211
|
assetName,
|
|
206
212
|
unsignedTx,
|
|
207
213
|
walletAccount,
|
|
214
|
+
}).catch((err) => {
|
|
215
|
+
throw toBtcSendError(err, 'SIGNING_FAILED')
|
|
208
216
|
})
|
|
209
217
|
|
|
210
218
|
// Broadcast transaction
|
|
@@ -212,7 +220,7 @@ export const sendTxFactory = ({
|
|
|
212
220
|
await broadcastTransaction({ asset, rawTx })
|
|
213
221
|
} catch (err) {
|
|
214
222
|
if (['MEMPOOL_REQUEST_BUSY', 'MEMPOOL_REQUEST_QUEUE_TIMEOUT'].includes(err.code)) {
|
|
215
|
-
throw err
|
|
223
|
+
throw toBtcBroadcastError(err)
|
|
216
224
|
}
|
|
217
225
|
const txExists = await checkTxExists({ asset, txId })
|
|
218
226
|
if (txExists) {
|
|
@@ -244,62 +252,66 @@ export const sendTxFactory = ({
|
|
|
244
252
|
})
|
|
245
253
|
}
|
|
246
254
|
|
|
247
|
-
throw err
|
|
255
|
+
throw toBtcBroadcastError(err)
|
|
248
256
|
}
|
|
249
257
|
}
|
|
250
258
|
|
|
251
259
|
const changeUtxoIndex = changeOutputIndex ?? -1
|
|
252
260
|
const sendUtxoIndex = sendOutputIndexes?.[0] ?? -1
|
|
253
261
|
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
262
|
+
try {
|
|
263
|
+
const { script, size } = getSizeAndChangeScript({
|
|
264
|
+
assetName,
|
|
265
|
+
tx,
|
|
266
|
+
rawTx,
|
|
267
|
+
changeUtxoIndex,
|
|
268
|
+
txId,
|
|
269
|
+
})
|
|
261
270
|
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
271
|
+
// Publish change and its recent-send history together so refresh cannot mistake
|
|
272
|
+
// newly created change for an orphan while transaction metadata is being derived.
|
|
273
|
+
const batch = assetClientInterface.createOperationsBatch()
|
|
274
|
+
updateAccountStateBatch({
|
|
275
|
+
batch,
|
|
276
|
+
assetClientInterface,
|
|
277
|
+
assetName,
|
|
278
|
+
walletAccount,
|
|
279
|
+
accountState,
|
|
280
|
+
txId,
|
|
281
|
+
changeUtxoIndex,
|
|
282
|
+
script,
|
|
283
|
+
selectedUtxos,
|
|
284
|
+
replaceTx,
|
|
285
|
+
changeAmount,
|
|
286
|
+
ourAddress,
|
|
287
|
+
rbfEnabled,
|
|
288
|
+
})
|
|
280
289
|
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
290
|
+
await updateTransactionLogBatch({
|
|
291
|
+
batch,
|
|
292
|
+
asset,
|
|
293
|
+
assetClientInterface,
|
|
294
|
+
walletAccount,
|
|
295
|
+
txId,
|
|
296
|
+
totalAmount,
|
|
297
|
+
selectedUtxos,
|
|
298
|
+
replaceTx,
|
|
299
|
+
changeOutput,
|
|
300
|
+
ourAddress,
|
|
301
|
+
fee,
|
|
302
|
+
blockHeight,
|
|
303
|
+
rbfEnabled,
|
|
304
|
+
toAddress,
|
|
305
|
+
sendAmount,
|
|
306
|
+
changeAmount,
|
|
307
|
+
bumpTxId,
|
|
308
|
+
size,
|
|
309
|
+
})
|
|
301
310
|
|
|
302
|
-
|
|
311
|
+
await assetClientInterface.executeOperationsBatch(batch)
|
|
312
|
+
} catch (err) {
|
|
313
|
+
throw toBtcTxRecordError(err)
|
|
314
|
+
}
|
|
303
315
|
|
|
304
316
|
return {
|
|
305
317
|
txId,
|
|
@@ -308,6 +320,14 @@ export const sendTxFactory = ({
|
|
|
308
320
|
replacedTxId: replaceTx?.txId,
|
|
309
321
|
}
|
|
310
322
|
}
|
|
323
|
+
|
|
324
|
+
return async (params) => {
|
|
325
|
+
try {
|
|
326
|
+
return await sendTx(params)
|
|
327
|
+
} catch (err) {
|
|
328
|
+
throw toBtcSendError(err)
|
|
329
|
+
}
|
|
330
|
+
}
|
|
311
331
|
}
|
|
312
332
|
|
|
313
333
|
// back compatibiliy
|