@lifi/sdk 4.9.0 → 4.11.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 +50 -0
- package/README.md +9 -0
- package/dist/cjs/client/createClient.js +6 -4
- package/dist/cjs/client/createClient.js.map +1 -1
- package/dist/cjs/client/findProvider.d.ts +10 -0
- package/dist/cjs/client/findProvider.js +11 -0
- package/dist/cjs/client/findProvider.js.map +1 -0
- package/dist/cjs/core/BaseStepExecutor.d.ts +1 -1
- package/dist/cjs/core/BaseStepExecutor.js +21 -9
- package/dist/cjs/core/BaseStepExecutor.js.map +1 -1
- package/dist/cjs/core/StatusManager.d.ts +10 -0
- package/dist/cjs/core/StatusManager.js +105 -3
- package/dist/cjs/core/StatusManager.js.map +1 -1
- package/dist/cjs/core/execution.js +30 -14
- package/dist/cjs/core/execution.js.map +1 -1
- package/dist/cjs/core/executionState.d.ts +34 -2
- package/dist/cjs/core/executionState.js +44 -1
- package/dist/cjs/core/executionState.js.map +1 -1
- package/dist/cjs/core/prepareRestart.js +14 -6
- package/dist/cjs/core/prepareRestart.js.map +1 -1
- package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js +4 -2
- package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
- package/dist/cjs/core/tasks/helpers/checkBalance.js +6 -3
- package/dist/cjs/core/tasks/helpers/checkBalance.js.map +1 -1
- package/dist/cjs/core/tasks/helpers/getStepStatusRequest.d.ts +10 -0
- package/dist/cjs/core/tasks/helpers/getStepStatusRequest.js +20 -0
- package/dist/cjs/core/tasks/helpers/getStepStatusRequest.js.map +1 -0
- package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.d.ts +21 -0
- package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.js +44 -0
- package/dist/cjs/core/tasks/helpers/isKnownToStatusApi.js.map +1 -0
- package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.d.ts +22 -1
- package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.js +76 -17
- package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
- package/dist/cjs/core/transactionState.d.ts +121 -0
- package/dist/cjs/core/transactionState.js +164 -0
- package/dist/cjs/core/transactionState.js.map +1 -0
- package/dist/cjs/errors/errors.d.ts +13 -2
- package/dist/cjs/errors/errors.js +5 -2
- package/dist/cjs/errors/errors.js.map +1 -1
- package/dist/cjs/index.d.ts +7 -3
- package/dist/cjs/index.js +16 -1
- package/dist/cjs/types/core.d.ts +49 -3
- package/dist/cjs/types/execution.d.ts +8 -0
- package/dist/cjs/utils/abort.d.ts +6 -0
- package/dist/cjs/utils/abort.js +10 -0
- package/dist/cjs/utils/abort.js.map +1 -0
- package/dist/cjs/utils/checkPackageUpdates.js +1 -1
- package/dist/cjs/utils/formatUnits.js +1 -0
- package/dist/cjs/utils/formatUnits.js.map +1 -1
- package/dist/cjs/utils/lru.d.ts +14 -0
- package/dist/cjs/utils/lru.js +35 -0
- package/dist/cjs/utils/lru.js.map +1 -0
- package/dist/cjs/utils/parseUnits.js +30 -16
- package/dist/cjs/utils/parseUnits.js.map +1 -1
- package/dist/cjs/utils/sleep.d.ts +7 -1
- package/dist/cjs/utils/sleep.js +22 -3
- package/dist/cjs/utils/sleep.js.map +1 -1
- package/dist/cjs/utils/waitForResult.d.ts +7 -5
- package/dist/cjs/utils/waitForResult.js +19 -14
- package/dist/cjs/utils/waitForResult.js.map +1 -1
- package/dist/cjs/utils/withDedupe.d.ts +0 -10
- package/dist/cjs/utils/withDedupe.js +4 -23
- package/dist/cjs/utils/withDedupe.js.map +1 -1
- package/dist/cjs/utils/withTimeout.js +6 -2
- package/dist/cjs/utils/withTimeout.js.map +1 -1
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/version.js.map +1 -1
- package/dist/esm/actions/getRoutes.d.ts.map +1 -1
- package/dist/esm/actions/index.d.ts.map +1 -1
- package/dist/esm/client/createClient.d.ts.map +1 -1
- package/dist/esm/client/createClient.js +6 -4
- package/dist/esm/client/createClient.js.map +1 -1
- package/dist/esm/client/findProvider.d.ts +10 -0
- package/dist/esm/client/findProvider.d.ts.map +1 -0
- package/dist/esm/client/findProvider.js +10 -0
- package/dist/esm/client/findProvider.js.map +1 -0
- package/dist/esm/core/BaseStepExecutor.d.ts +1 -1
- package/dist/esm/core/BaseStepExecutor.d.ts.map +1 -1
- package/dist/esm/core/BaseStepExecutor.js +22 -10
- package/dist/esm/core/BaseStepExecutor.js.map +1 -1
- package/dist/esm/core/StatusManager.d.ts +10 -0
- package/dist/esm/core/StatusManager.d.ts.map +1 -1
- package/dist/esm/core/StatusManager.js +105 -3
- package/dist/esm/core/StatusManager.js.map +1 -1
- package/dist/esm/core/execution.d.ts.map +1 -1
- package/dist/esm/core/execution.js +30 -14
- package/dist/esm/core/execution.js.map +1 -1
- package/dist/esm/core/executionState.d.ts +34 -2
- package/dist/esm/core/executionState.d.ts.map +1 -1
- package/dist/esm/core/executionState.js +44 -1
- package/dist/esm/core/executionState.js.map +1 -1
- package/dist/esm/core/prepareRestart.d.ts.map +1 -1
- package/dist/esm/core/prepareRestart.js +14 -6
- package/dist/esm/core/prepareRestart.js.map +1 -1
- package/dist/esm/core/tasks/WaitForTransactionStatusTask.d.ts.map +1 -1
- package/dist/esm/core/tasks/WaitForTransactionStatusTask.js +4 -2
- package/dist/esm/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
- package/dist/esm/core/tasks/helpers/checkBalance.js +6 -3
- package/dist/esm/core/tasks/helpers/checkBalance.js.map +1 -1
- package/dist/esm/core/tasks/helpers/getStepStatusRequest.d.ts +10 -0
- package/dist/esm/core/tasks/helpers/getStepStatusRequest.d.ts.map +1 -0
- package/dist/esm/core/tasks/helpers/getStepStatusRequest.js +19 -0
- package/dist/esm/core/tasks/helpers/getStepStatusRequest.js.map +1 -0
- package/dist/esm/core/tasks/helpers/isKnownToStatusApi.d.ts +21 -0
- package/dist/esm/core/tasks/helpers/isKnownToStatusApi.d.ts.map +1 -0
- package/dist/esm/core/tasks/helpers/isKnownToStatusApi.js +43 -0
- package/dist/esm/core/tasks/helpers/isKnownToStatusApi.js.map +1 -0
- package/dist/esm/core/tasks/helpers/waitForTransactionStatus.d.ts +22 -1
- package/dist/esm/core/tasks/helpers/waitForTransactionStatus.d.ts.map +1 -1
- package/dist/esm/core/tasks/helpers/waitForTransactionStatus.js +76 -18
- package/dist/esm/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
- package/dist/esm/core/transactionState.d.ts +121 -0
- package/dist/esm/core/transactionState.d.ts.map +1 -0
- package/dist/esm/core/transactionState.js +152 -0
- package/dist/esm/core/transactionState.js.map +1 -0
- package/dist/esm/errors/errors.d.ts +13 -2
- package/dist/esm/errors/errors.d.ts.map +1 -1
- package/dist/esm/errors/errors.js +5 -2
- package/dist/esm/errors/errors.js.map +1 -1
- package/dist/esm/index.d.ts +7 -3
- package/dist/esm/index.js +6 -2
- package/dist/esm/types/actions.d.ts.map +1 -1
- package/dist/esm/types/core.d.ts +49 -3
- package/dist/esm/types/core.d.ts.map +1 -1
- package/dist/esm/types/execution.d.ts +8 -0
- package/dist/esm/types/execution.d.ts.map +1 -1
- package/dist/esm/utils/abort.d.ts +6 -0
- package/dist/esm/utils/abort.d.ts.map +1 -0
- package/dist/esm/utils/abort.js +8 -0
- package/dist/esm/utils/abort.js.map +1 -0
- package/dist/esm/utils/checkPackageUpdates.js +1 -1
- package/dist/esm/utils/formatUnits.js +1 -0
- package/dist/esm/utils/formatUnits.js.map +1 -1
- package/dist/esm/utils/lru.d.ts +14 -0
- package/dist/esm/utils/lru.d.ts.map +1 -0
- package/dist/esm/utils/lru.js +34 -0
- package/dist/esm/utils/lru.js.map +1 -0
- package/dist/esm/utils/parseUnits.js +30 -16
- package/dist/esm/utils/parseUnits.js.map +1 -1
- package/dist/esm/utils/sleep.d.ts +7 -1
- package/dist/esm/utils/sleep.d.ts.map +1 -1
- package/dist/esm/utils/sleep.js +22 -3
- package/dist/esm/utils/sleep.js.map +1 -1
- package/dist/esm/utils/waitForResult.d.ts +7 -5
- package/dist/esm/utils/waitForResult.d.ts.map +1 -1
- package/dist/esm/utils/waitForResult.js +19 -14
- package/dist/esm/utils/waitForResult.js.map +1 -1
- package/dist/esm/utils/withDedupe.d.ts +0 -10
- package/dist/esm/utils/withDedupe.d.ts.map +1 -1
- package/dist/esm/utils/withDedupe.js +5 -22
- package/dist/esm/utils/withDedupe.js.map +1 -1
- package/dist/esm/utils/withTimeout.d.ts.map +1 -1
- package/dist/esm/utils/withTimeout.js +6 -2
- package/dist/esm/utils/withTimeout.js.map +1 -1
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/version.js.map +1 -1
- package/package.json +2 -2
- package/src/client/createClient.ts +12 -4
- package/src/client/findProvider.ts +21 -0
- package/src/core/BaseStepExecutor.ts +40 -6
- package/src/core/StatusManager.ts +211 -2
- package/src/core/execution.ts +69 -20
- package/src/core/executionState.ts +84 -1
- package/src/core/prepareRestart.ts +29 -13
- package/src/core/tasks/WaitForTransactionStatusTask.ts +10 -1
- package/src/core/tasks/helpers/checkBalance.ts +11 -3
- package/src/core/tasks/helpers/getStepStatusRequest.ts +20 -0
- package/src/core/tasks/helpers/isKnownToStatusApi.ts +57 -0
- package/src/core/tasks/helpers/waitForTransactionStatus.ts +128 -17
- package/src/core/transactionState.ts +194 -0
- package/src/errors/errors.ts +21 -2
- package/src/index.ts +16 -1
- package/src/types/core.ts +50 -3
- package/src/types/execution.ts +8 -0
- package/src/utils/abort.ts +10 -0
- package/src/utils/formatUnits.ts +6 -0
- package/src/utils/lru.ts +38 -0
- package/src/utils/parseUnits.ts +53 -20
- package/src/utils/sleep.ts +27 -3
- package/src/utils/waitForResult.ts +20 -10
- package/src/utils/withDedupe.ts +4 -28
- package/src/utils/withTimeout.ts +7 -2
- package/src/version.ts +1 -1
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { LiFiErrorCode } from '../errors/constants.js'
|
|
2
|
+
import { TransactionError } from '../errors/errors.js'
|
|
3
|
+
import type {
|
|
4
|
+
ExecutionAction,
|
|
5
|
+
ExecutionActionType,
|
|
6
|
+
LiFiStepExtended,
|
|
7
|
+
} from '../types/core.js'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Action types that carry the step's own transaction.
|
|
11
|
+
*
|
|
12
|
+
* @internal
|
|
13
|
+
*/
|
|
14
|
+
export const TRANSACTION_ACTION_TYPES: readonly ExecutionActionType[] = [
|
|
15
|
+
'SWAP',
|
|
16
|
+
'CROSS_CHAIN',
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Stored bytes on a chain without its own expiry (Sui, Solana with a durable
|
|
21
|
+
* nonce, Bitcoin) are resent only this long after signing. Past it, a page
|
|
22
|
+
* load could otherwise execute a swap on a quote the user no longer expects.
|
|
23
|
+
*
|
|
24
|
+
* @internal
|
|
25
|
+
*/
|
|
26
|
+
export const MAX_RESEND_AGE_MS = 120_000
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Without an expiry verdict, a signature younger than this is never declared
|
|
30
|
+
* dropped. Solana blockhashes and Tron transactions expire well before it.
|
|
31
|
+
*
|
|
32
|
+
* @internal
|
|
33
|
+
*/
|
|
34
|
+
export const DROPPED_FALLBACK_AGE_MS = 300_000
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Subtracted from `execution.signedAt` (the device clock) when it anchors a
|
|
38
|
+
* history-coverage check, so a device clock that runs fast cannot make a node
|
|
39
|
+
* look like it covers the signing time when it does not.
|
|
40
|
+
*
|
|
41
|
+
* @internal
|
|
42
|
+
*/
|
|
43
|
+
export const CLOCK_SKEW_MARGIN_MS = 600_000
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Fields a sign task clears before it writes a new transaction's data, and
|
|
47
|
+
* that re-initializing a final-failed action clears. `taskId` is included: a
|
|
48
|
+
* stale relayed or batched task id would otherwise keep the action open.
|
|
49
|
+
*
|
|
50
|
+
* @internal
|
|
51
|
+
*/
|
|
52
|
+
export const CLEARED_TRANSACTION_FIELDS: Readonly<
|
|
53
|
+
Pick<ExecutionAction, 'txHash' | 'txLink' | 'txHex' | 'txFinal' | 'taskId'>
|
|
54
|
+
> = Object.freeze({
|
|
55
|
+
txHash: undefined,
|
|
56
|
+
txLink: undefined,
|
|
57
|
+
txHex: undefined,
|
|
58
|
+
txFinal: undefined,
|
|
59
|
+
taskId: undefined,
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* True when the action has a transaction to follow, landed or not: a hash, a
|
|
64
|
+
* task id or stored signed bytes, unless the action FAILED with a final
|
|
65
|
+
* outcome. Every resume decision uses this one predicate, so the pipeline
|
|
66
|
+
* selector and the pre-sign guard can never disagree.
|
|
67
|
+
*
|
|
68
|
+
* Resume rules for providers. A step never signs or sends a second
|
|
69
|
+
* transaction while an earlier one can still land:
|
|
70
|
+
* 1. Pick the first task with this predicate: open and DONE, the status
|
|
71
|
+
* wait; open, the provider's wait task; otherwise the first task.
|
|
72
|
+
* 2. In the sign task, call `assertNoOpenTransaction` at the start, right
|
|
73
|
+
* before each wallet call and, where the SDK sends, right after the
|
|
74
|
+
* wallet returns. Write the new data with `CLEARED_TRANSACTION_FIELDS`
|
|
75
|
+
* and `signedAt`.
|
|
76
|
+
* 3. From the last check, nothing awaits until the send or, where the SDK
|
|
77
|
+
* sends signed bytes, until they are stored as `txHex`, before the first
|
|
78
|
+
* send. Clear `txHex` only when the outcome is known, no node can still
|
|
79
|
+
* hold the bytes, or they no longer decode.
|
|
80
|
+
* 4. A resume never signs. It looks the transaction up and resends the
|
|
81
|
+
* stored bytes only while `isResendAllowed` (or the chain's own expiry)
|
|
82
|
+
* allows it; otherwise it only waits.
|
|
83
|
+
* 5. Mark an error final only on a verdict about the transaction: failed
|
|
84
|
+
* or reverted (on chain or at the relayer), cancelled, replaced, or
|
|
85
|
+
* dropped with proof. Dropped needs all three: the transaction can no
|
|
86
|
+
* longer land, a node that covers its window reports it absent (in the
|
|
87
|
+
* same response where the chain allows it), and `isKnownToStatusApi` is
|
|
88
|
+
* false. In doubt, throw without the marker and keep the fields.
|
|
89
|
+
* 6. Give `context.signal` only to waits that start after the broadcast. On
|
|
90
|
+
* abort, return `PAUSED` and write nothing.
|
|
91
|
+
*/
|
|
92
|
+
export function hasOpenTransaction(action?: ExecutionAction): boolean {
|
|
93
|
+
if (!action) {
|
|
94
|
+
return false
|
|
95
|
+
}
|
|
96
|
+
if (!(action.txHash || action.taskId || action.txHex)) {
|
|
97
|
+
return false
|
|
98
|
+
}
|
|
99
|
+
return !(action.status === 'FAILED' && action.txFinal === true)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* True when any SWAP / CROSS_CHAIN action of the step has an open transaction.
|
|
104
|
+
*
|
|
105
|
+
* @internal
|
|
106
|
+
*/
|
|
107
|
+
export function hasStepOpenTransaction(step: LiFiStepExtended): boolean {
|
|
108
|
+
return !!step.execution?.actions?.some(
|
|
109
|
+
(action) =>
|
|
110
|
+
TRANSACTION_ACTION_TYPES.includes(action.type) &&
|
|
111
|
+
hasOpenTransaction(action)
|
|
112
|
+
)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Walks the error and its `cause` chain. Parsers may rebuild errors, so the
|
|
117
|
+
* marker is read from the original error. A property check instead of
|
|
118
|
+
* `instanceof` keeps it working across duplicated installs.
|
|
119
|
+
*
|
|
120
|
+
* @internal
|
|
121
|
+
*/
|
|
122
|
+
export function isFinalTransactionError(error: unknown): boolean {
|
|
123
|
+
const seen = new Set<unknown>()
|
|
124
|
+
let current: unknown = error
|
|
125
|
+
while (current && typeof current === 'object' && !seen.has(current)) {
|
|
126
|
+
seen.add(current)
|
|
127
|
+
if ((current as { final?: unknown }).final === true) {
|
|
128
|
+
return true
|
|
129
|
+
}
|
|
130
|
+
current = (current as { cause?: unknown }).cause
|
|
131
|
+
}
|
|
132
|
+
return false
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* The error of a step that would sign a second transaction while its first
|
|
137
|
+
* one may still land.
|
|
138
|
+
*
|
|
139
|
+
* @internal
|
|
140
|
+
*/
|
|
141
|
+
export function transactionConflictError(): TransactionError {
|
|
142
|
+
return new TransactionError(
|
|
143
|
+
LiFiErrorCode.TransactionConflict,
|
|
144
|
+
'A transaction for this step was already signed and may still land. Resume the route to wait for it instead of signing a new one.'
|
|
145
|
+
)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Called first in every sign task. With correct pipeline selectors it never
|
|
150
|
+
* throws; it stops a second signature if a selector ever routes an open
|
|
151
|
+
* transaction back to signing. Every sign task calls it again on the freshly
|
|
152
|
+
* found action right before its wallet call: a late write of an older run can
|
|
153
|
+
* merge a transaction into the action during the awaits in between. A sign
|
|
154
|
+
* task that sends the transaction itself calls it once more after the wallet
|
|
155
|
+
* returns, before it writes or sends anything: the merge can also land while
|
|
156
|
+
* the prompt is open.
|
|
157
|
+
*
|
|
158
|
+
* @internal
|
|
159
|
+
*/
|
|
160
|
+
export function assertNoOpenTransaction(action?: ExecutionAction): void {
|
|
161
|
+
if (hasOpenTransaction(action)) {
|
|
162
|
+
throw transactionConflictError()
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Unknown signing time never allows a resend. Nor does a signing time in the
|
|
168
|
+
* future: a device clock that ran ahead at signing and was corrected later
|
|
169
|
+
* would otherwise stretch the cap by the clock error.
|
|
170
|
+
*
|
|
171
|
+
* @internal
|
|
172
|
+
*/
|
|
173
|
+
export function isResendAllowed(
|
|
174
|
+
signedAt: number | undefined,
|
|
175
|
+
now: number = Date.now()
|
|
176
|
+
): boolean {
|
|
177
|
+
return (
|
|
178
|
+
signedAt !== undefined &&
|
|
179
|
+
now >= signedAt &&
|
|
180
|
+
now - signedAt < MAX_RESEND_AGE_MS
|
|
181
|
+
)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Unknown signing time never allows a drop.
|
|
186
|
+
*
|
|
187
|
+
* @internal
|
|
188
|
+
*/
|
|
189
|
+
export function isOldEnoughToDrop(
|
|
190
|
+
signedAt: number | undefined,
|
|
191
|
+
now: number = Date.now()
|
|
192
|
+
): boolean {
|
|
193
|
+
return signedAt !== undefined && now - signedAt > DROPPED_FALLBACK_AGE_MS
|
|
194
|
+
}
|
package/src/errors/errors.ts
CHANGED
|
@@ -14,9 +14,27 @@ export class ProviderError extends BaseError {
|
|
|
14
14
|
}
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
export interface TransactionErrorOptions {
|
|
18
|
+
/**
|
|
19
|
+
* A definite verdict about the transaction (failed or reverted on chain or
|
|
20
|
+
* at the relayer, cancelled, replaced, or dropped with proof). The step
|
|
21
|
+
* executor then flags the failed action with `txFinal`, so a restart signs
|
|
22
|
+
* a new transaction.
|
|
23
|
+
*/
|
|
24
|
+
final?: boolean
|
|
25
|
+
}
|
|
26
|
+
|
|
17
27
|
export class TransactionError extends BaseError {
|
|
18
|
-
|
|
28
|
+
readonly final: boolean
|
|
29
|
+
|
|
30
|
+
constructor(
|
|
31
|
+
code: LiFiErrorCode,
|
|
32
|
+
message: string,
|
|
33
|
+
cause?: Error,
|
|
34
|
+
options?: TransactionErrorOptions
|
|
35
|
+
) {
|
|
19
36
|
super(ErrorName.TransactionError, code, message, cause)
|
|
37
|
+
this.final = options?.final ?? false
|
|
20
38
|
}
|
|
21
39
|
}
|
|
22
40
|
|
|
@@ -47,7 +65,8 @@ export class ValidationError extends BaseError {
|
|
|
47
65
|
/**
|
|
48
66
|
* Thrown by a step executor when executeStep should be retried with the given params
|
|
49
67
|
* (e.g. wallet rejected 7702 upgrade → retry with atomicityNotReady).
|
|
50
|
-
* The execution layer catches this and retries executeStep(client, step, retryParams)
|
|
68
|
+
* The execution layer catches this and retries executeStep(client, step, retryParams),
|
|
69
|
+
* unless the route was stopped or the step has an open transaction.
|
|
51
70
|
*/
|
|
52
71
|
export class ExecuteStepRetryError extends BaseError {
|
|
53
72
|
readonly retryParams: ExecuteStepRetryParams
|
package/src/index.ts
CHANGED
|
@@ -23,6 +23,7 @@ export { actions } from './actions/index.js'
|
|
|
23
23
|
export { patchContractCalls } from './actions/patchContractCalls.js'
|
|
24
24
|
export { relayTransaction } from './actions/relayTransaction.js'
|
|
25
25
|
export { createClient } from './client/createClient.js'
|
|
26
|
+
export { findProvider } from './client/findProvider.js'
|
|
26
27
|
export { getActionMessage, getSubstatusMessage } from './core/actionMessages.js'
|
|
27
28
|
export { BaseStepExecutionTask } from './core/BaseStepExecutionTask.js'
|
|
28
29
|
export { BaseStepExecutor } from './core/BaseStepExecutor.js'
|
|
@@ -48,12 +49,25 @@ export {
|
|
|
48
49
|
checkBalance,
|
|
49
50
|
} from './core/tasks/helpers/checkBalance.js'
|
|
50
51
|
export { getTransactionRequestData } from './core/tasks/helpers/getTransactionRequestData.js'
|
|
52
|
+
export { isKnownToStatusApi } from './core/tasks/helpers/isKnownToStatusApi.js'
|
|
51
53
|
export { stepComparison } from './core/tasks/helpers/stepComparison.js'
|
|
52
54
|
export { PrepareTransactionTask } from './core/tasks/PrepareTransactionTask.js'
|
|
53
55
|
export { WaitForTransactionStatusTask } from './core/tasks/WaitForTransactionStatusTask.js'
|
|
56
|
+
export {
|
|
57
|
+
assertNoOpenTransaction,
|
|
58
|
+
CLEARED_TRANSACTION_FIELDS,
|
|
59
|
+
CLOCK_SKEW_MARGIN_MS,
|
|
60
|
+
DROPPED_FALLBACK_AGE_MS,
|
|
61
|
+
hasOpenTransaction,
|
|
62
|
+
isFinalTransactionError,
|
|
63
|
+
isOldEnoughToDrop,
|
|
64
|
+
isResendAllowed,
|
|
65
|
+
MAX_RESEND_AGE_MS,
|
|
66
|
+
} from './core/transactionState.js'
|
|
54
67
|
export { BaseError } from './errors/baseError.js'
|
|
55
68
|
export type { ErrorCode } from './errors/constants.js'
|
|
56
69
|
export { ErrorMessage, ErrorName, LiFiErrorCode } from './errors/constants.js'
|
|
70
|
+
export type { TransactionErrorOptions } from './errors/errors.js'
|
|
57
71
|
export {
|
|
58
72
|
BalanceError,
|
|
59
73
|
ExecuteStepRetryError,
|
|
@@ -123,9 +137,10 @@ export { convertQuoteToRoute } from './utils/convertQuoteToRoute.js'
|
|
|
123
137
|
export { fetchTxErrorDetails } from './utils/fetchTxErrorDetails.js'
|
|
124
138
|
export { formatUnits } from './utils/formatUnits.js'
|
|
125
139
|
export { isHex } from './utils/isHex.js'
|
|
140
|
+
export { LruMap } from './utils/lru.js'
|
|
126
141
|
export { parseUnits } from './utils/parseUnits.js'
|
|
127
142
|
export { sleep } from './utils/sleep.js'
|
|
128
143
|
export { waitForResult } from './utils/waitForResult.js'
|
|
129
|
-
export {
|
|
144
|
+
export { withDedupe } from './utils/withDedupe.js'
|
|
130
145
|
export { withTimeout } from './utils/withTimeout.js'
|
|
131
146
|
export { name, version } from './version.js'
|
package/src/types/core.ts
CHANGED
|
@@ -91,7 +91,18 @@ export type RPCUrls = Partial<Record<ChainId, string[]>>
|
|
|
91
91
|
|
|
92
92
|
export interface SDKProvider {
|
|
93
93
|
readonly type: ChainType
|
|
94
|
-
|
|
94
|
+
/**
|
|
95
|
+
* The chains this provider serves. Omit it to serve every chain of `type`
|
|
96
|
+
* that no other provider lists.
|
|
97
|
+
*/
|
|
98
|
+
readonly chainIds?: readonly ChainId[]
|
|
99
|
+
/**
|
|
100
|
+
* Validates a wallet address. With `chainId`, a provider whose chains use
|
|
101
|
+
* different address formats accepts only that chain's format and refuses a
|
|
102
|
+
* chain it does not know. Never forward `chainId` to a library function whose
|
|
103
|
+
* second parameter means something else.
|
|
104
|
+
*/
|
|
105
|
+
isAddress(address: string, chainId?: ChainId): boolean
|
|
95
106
|
/**
|
|
96
107
|
* Validates a token identifier, which several ecosystems shape unlike a
|
|
97
108
|
* wallet address. A provider that omits the method has no token address
|
|
@@ -115,7 +126,7 @@ export interface SDKProvider {
|
|
|
115
126
|
export interface SDKClient {
|
|
116
127
|
config: SDKBaseConfig
|
|
117
128
|
providers: SDKProvider[]
|
|
118
|
-
getProvider(type: ChainType): SDKProvider | undefined
|
|
129
|
+
getProvider(type: ChainType, chainId?: ChainId): SDKProvider | undefined
|
|
119
130
|
setProviders(providers: SDKProvider[]): void
|
|
120
131
|
setChains(chains: ExtendedChain[]): void
|
|
121
132
|
getChains(): Promise<ExtendedChain[]>
|
|
@@ -159,10 +170,15 @@ export interface StepExecutor {
|
|
|
159
170
|
allowUserInteraction: boolean
|
|
160
171
|
allowExecution: boolean
|
|
161
172
|
setInteraction(settings?: InteractionSettings): void
|
|
173
|
+
/**
|
|
174
|
+
* @param signal Aborts when the execution stops. Only waits that start
|
|
175
|
+
* after the broadcast may use it (`StepExecutorBaseContext.signal`).
|
|
176
|
+
*/
|
|
162
177
|
executeStep(
|
|
163
178
|
client: SDKClient,
|
|
164
179
|
step: LiFiStepExtended,
|
|
165
|
-
retryParams?: ExecuteStepRetryParams
|
|
180
|
+
retryParams?: ExecuteStepRetryParams,
|
|
181
|
+
signal?: AbortSignal
|
|
166
182
|
): Promise<LiFiStepExtended>
|
|
167
183
|
}
|
|
168
184
|
|
|
@@ -203,6 +219,18 @@ export type TransactionParameters = {
|
|
|
203
219
|
|
|
204
220
|
export type RouteExecutionDictionary = Partial<Record<string, Promise<Route>>>
|
|
205
221
|
|
|
222
|
+
/**
|
|
223
|
+
* Called on every update of the route. It receives the SDK's working copy of
|
|
224
|
+
* the route: the same object on every call of one execution, which the SDK
|
|
225
|
+
* keeps changing after the hook returns. Copy or serialize it before you
|
|
226
|
+
* store it.
|
|
227
|
+
*
|
|
228
|
+
* After `stopRouteExecution` it can still be called, but only to deliver the
|
|
229
|
+
* transaction data (`txHash`, `txHex`, `taskId`, `txFinal`) of a task that
|
|
230
|
+
* was still running at the stop, for example in an open wallet prompt. Store
|
|
231
|
+
* that data, so a resume waits for that transaction instead of signing
|
|
232
|
+
* again. If you deleted the route, ignore the call.
|
|
233
|
+
*/
|
|
206
234
|
export type UpdateRouteHook = (updatedRoute: RouteExtended) => void
|
|
207
235
|
|
|
208
236
|
export interface TransactionRequestParameters extends TransactionParameters {
|
|
@@ -264,6 +292,11 @@ export type GetContractCallsHook = (
|
|
|
264
292
|
|
|
265
293
|
export interface ExecutionOptions {
|
|
266
294
|
acceptExchangeRateUpdateHook?: AcceptExchangeRateUpdateHook
|
|
295
|
+
/**
|
|
296
|
+
* Receives the route on every update, and after `stopRouteExecution` the
|
|
297
|
+
* late transaction data of a task that was still running. See
|
|
298
|
+
* {@link UpdateRouteHook}.
|
|
299
|
+
*/
|
|
267
300
|
updateRouteHook?: UpdateRouteHook
|
|
268
301
|
updateTransactionRequestHook?: TransactionRequestUpdateHook
|
|
269
302
|
getContractCalls?: GetContractCallsHook
|
|
@@ -304,7 +337,21 @@ export type ExecutionAction = {
|
|
|
304
337
|
txLink?: string
|
|
305
338
|
taskId?: string
|
|
306
339
|
txType?: TransactionMethodType
|
|
340
|
+
/**
|
|
341
|
+
* Provider-specific serialized signed transaction (hex, XDR, base64 or JSON).
|
|
342
|
+
* Present while the transaction may still need to be (re)sent or looked up.
|
|
343
|
+
* Stellar keeps it, and Bitcoin keeps it unless every node refuses its first
|
|
344
|
+
* send; Solana, Tron and Sui clear it when no longer needed.
|
|
345
|
+
*/
|
|
307
346
|
txHex?: string
|
|
347
|
+
/**
|
|
348
|
+
* Set together with status `FAILED` when the outcome of this action's
|
|
349
|
+
* transaction is known and final (failed or reverted on chain or at the
|
|
350
|
+
* relayer, cancelled, replaced, or dropped with proof).
|
|
351
|
+
* A FAILED action without this flag has an unknown outcome and is re-checked
|
|
352
|
+
* on resume instead of being signed again.
|
|
353
|
+
*/
|
|
354
|
+
txFinal?: boolean
|
|
308
355
|
// Errors occured during the action execution (within tasks)
|
|
309
356
|
error?: { code: string | number; message: string; htmlMessage?: string }
|
|
310
357
|
}
|
package/src/types/execution.ts
CHANGED
|
@@ -17,6 +17,14 @@ export interface StepExecutorBaseContext {
|
|
|
17
17
|
step: LiFiStepExtended
|
|
18
18
|
allowUserInteraction: boolean
|
|
19
19
|
retryParams?: ExecuteStepRetryParams
|
|
20
|
+
/**
|
|
21
|
+
* Aborts when `stopRouteExecution` stops the execution. Give it only to a
|
|
22
|
+
* wait that starts after the transaction is broadcast, such as the
|
|
23
|
+
* `/status` poll. Never give it to a sign, send or wallet call: a stopped
|
|
24
|
+
* run must finish those, so its late transaction data still reaches the
|
|
25
|
+
* stored route and a resume does not sign again.
|
|
26
|
+
*/
|
|
27
|
+
signal?: AbortSignal
|
|
20
28
|
}
|
|
21
29
|
|
|
22
30
|
export interface StepExecutorContext extends StepExecutorBaseContext {
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Older runtimes and polyfills can abort a signal without a `reason`. */
|
|
2
|
+
export const getAbortError = (signal: AbortSignal): unknown =>
|
|
3
|
+
signal.reason ??
|
|
4
|
+
Object.assign(new Error('This operation was aborted'), { name: 'AbortError' })
|
|
5
|
+
|
|
6
|
+
export const isAbortError = (error: unknown): boolean =>
|
|
7
|
+
typeof error === 'object' &&
|
|
8
|
+
error !== null &&
|
|
9
|
+
'name' in error &&
|
|
10
|
+
error.name === 'AbortError'
|
package/src/utils/formatUnits.ts
CHANGED
|
@@ -2,6 +2,12 @@
|
|
|
2
2
|
* Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number.
|
|
3
3
|
*/
|
|
4
4
|
export function formatUnits(value: bigint, decimals: number): string {
|
|
5
|
+
if (!Number.isInteger(decimals) || decimals < 0) {
|
|
6
|
+
throw new Error(
|
|
7
|
+
`\`decimals\` must be a non-negative integer. Got \`${decimals}\`.`
|
|
8
|
+
)
|
|
9
|
+
}
|
|
10
|
+
|
|
5
11
|
let display = value.toString()
|
|
6
12
|
|
|
7
13
|
const negative = display.startsWith('-')
|
package/src/utils/lru.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Map with a LRU (Least recently used) policy.
|
|
3
|
+
*
|
|
4
|
+
* https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
|
|
5
|
+
*/
|
|
6
|
+
export class LruMap<value = unknown> extends Map<string, value> {
|
|
7
|
+
maxSize: number
|
|
8
|
+
|
|
9
|
+
constructor(size: number) {
|
|
10
|
+
super()
|
|
11
|
+
this.maxSize = size
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
override get(key: string): value | undefined {
|
|
15
|
+
const value = super.get(key)
|
|
16
|
+
if (super.has(key)) {
|
|
17
|
+
super.delete(key)
|
|
18
|
+
super.set(key, value as value)
|
|
19
|
+
}
|
|
20
|
+
return value
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
override set(key: string, value: value): this {
|
|
24
|
+
if (super.has(key)) {
|
|
25
|
+
super.delete(key)
|
|
26
|
+
}
|
|
27
|
+
super.set(key, value)
|
|
28
|
+
if (this.maxSize && this.size > this.maxSize) {
|
|
29
|
+
// `super.keys()`, not `this.keys()`: on iOS 18 the subclass iterator
|
|
30
|
+
// can yield `undefined`, and the map then grows without limit.
|
|
31
|
+
const firstKey = super.keys().next().value
|
|
32
|
+
if (firstKey !== undefined) {
|
|
33
|
+
super.delete(firstKey)
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return this
|
|
37
|
+
}
|
|
38
|
+
}
|
package/src/utils/parseUnits.ts
CHANGED
|
@@ -2,49 +2,82 @@
|
|
|
2
2
|
* Multiplies a string representation of a number by a given exponent of base 10 (10exponent).
|
|
3
3
|
*/
|
|
4
4
|
export function parseUnits(value: string, decimals: number): bigint {
|
|
5
|
-
if (
|
|
5
|
+
if (!Number.isInteger(decimals) || decimals < 0) {
|
|
6
|
+
throw new Error(
|
|
7
|
+
`\`decimals\` must be a non-negative integer. Got \`${decimals}\`.`
|
|
8
|
+
)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
// An input with no digit is 0n: the widget parses an empty amount field.
|
|
12
|
+
if (/^-?\.?$/.test(value)) {
|
|
13
|
+
return 0n
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
if (!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(value)) {
|
|
6
17
|
throw new Error(`Number \`${value}\` is not a valid decimal number.`)
|
|
7
18
|
}
|
|
8
19
|
|
|
9
|
-
let [integer, fraction = '0'] = value.split('.')
|
|
20
|
+
let [integer = '', fraction = '0'] = value.split('.')
|
|
10
21
|
|
|
11
22
|
const negative = integer.startsWith('-')
|
|
12
23
|
if (negative) {
|
|
13
24
|
integer = integer.slice(1)
|
|
14
25
|
}
|
|
26
|
+
if (integer === '') {
|
|
27
|
+
integer = '0'
|
|
28
|
+
}
|
|
15
29
|
|
|
16
30
|
// trim trailing zeros.
|
|
17
31
|
fraction = fraction.replace(/(0+)$/, '')
|
|
18
32
|
|
|
19
33
|
// round off if the fraction is larger than the number of decimals.
|
|
20
34
|
if (decimals === 0) {
|
|
21
|
-
|
|
35
|
+
// Round half away from zero by the first fractional digit.
|
|
36
|
+
if (fraction.length > 0 && Number.parseInt(fraction[0], 10) >= 5) {
|
|
22
37
|
integer = `${BigInt(integer) + 1n}`
|
|
23
38
|
}
|
|
24
39
|
fraction = ''
|
|
25
40
|
} else if (fraction.length > decimals) {
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
fraction.slice(decimals
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
const rounded = Math.round(Number(`${unit}.${right}`))
|
|
33
|
-
if (rounded > 9) {
|
|
34
|
-
fraction = `${BigInt(left) + BigInt(1)}0`.padStart(left.length + 1, '0')
|
|
35
|
-
} else {
|
|
36
|
-
fraction = `${left}${rounded}`
|
|
37
|
-
}
|
|
41
|
+
const left = fraction.slice(0, decimals)
|
|
42
|
+
const roundDigit = Number.parseInt(
|
|
43
|
+
fraction.slice(decimals, decimals + 1),
|
|
44
|
+
10
|
|
45
|
+
)
|
|
38
46
|
|
|
39
|
-
if (
|
|
40
|
-
|
|
41
|
-
|
|
47
|
+
if (roundDigit >= 5) {
|
|
48
|
+
// Carry in decimal space, not through a JS number: a float loses
|
|
49
|
+
// precision on long fractions and can round the wrong way.
|
|
50
|
+
const carried = carry(left)
|
|
51
|
+
if (carried.length > decimals) {
|
|
52
|
+
// The carry overflowed into the integer part.
|
|
53
|
+
fraction = carried.slice(1)
|
|
54
|
+
integer = `${BigInt(integer) + 1n}`
|
|
55
|
+
} else {
|
|
56
|
+
fraction = carried
|
|
57
|
+
}
|
|
58
|
+
} else {
|
|
59
|
+
fraction = left
|
|
42
60
|
}
|
|
43
|
-
|
|
44
|
-
fraction = fraction.slice(0, decimals)
|
|
45
61
|
} else {
|
|
46
62
|
fraction = fraction.padEnd(decimals, '0')
|
|
47
63
|
}
|
|
48
64
|
|
|
49
65
|
return BigInt(`${negative ? '-' : ''}${integer}${fraction}`)
|
|
50
66
|
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Adds 1 to a digit string. The result has the same length, unless the carry
|
|
70
|
+
* passes the most significant digit: then it is one digit longer.
|
|
71
|
+
*/
|
|
72
|
+
function carry(digits: string): string {
|
|
73
|
+
const out = digits.split('')
|
|
74
|
+
for (let i = out.length - 1; i >= 0; i--) {
|
|
75
|
+
const digit = Number.parseInt(out[i], 10) + 1
|
|
76
|
+
if (digit < 10) {
|
|
77
|
+
out[i] = String(digit)
|
|
78
|
+
return out.join('')
|
|
79
|
+
}
|
|
80
|
+
out[i] = '0'
|
|
81
|
+
}
|
|
82
|
+
return `1${out.join('')}`
|
|
83
|
+
}
|
package/src/utils/sleep.ts
CHANGED
|
@@ -1,5 +1,29 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
import { getAbortError } from './abort.js'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Resolves with `null` after `ms`. With a `signal`, it rejects with the abort
|
|
5
|
+
* reason as soon as the signal aborts, and clears its timer.
|
|
6
|
+
*/
|
|
7
|
+
export function sleep(
|
|
8
|
+
ms: number,
|
|
9
|
+
{ signal }: { signal?: AbortSignal | undefined } = {}
|
|
10
|
+
): Promise<null> {
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
if (signal?.aborted) {
|
|
13
|
+
reject(getAbortError(signal))
|
|
14
|
+
return
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const cleanup = (): void => signal?.removeEventListener('abort', onAbort)
|
|
18
|
+
const timer = setTimeout(() => {
|
|
19
|
+
cleanup()
|
|
20
|
+
resolve(null)
|
|
21
|
+
}, ms)
|
|
22
|
+
const onAbort = (): void => {
|
|
23
|
+
clearTimeout(timer)
|
|
24
|
+
cleanup()
|
|
25
|
+
reject(getAbortError(signal!))
|
|
26
|
+
}
|
|
27
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
4
28
|
})
|
|
5
29
|
}
|
|
@@ -1,19 +1,23 @@
|
|
|
1
|
+
import { getAbortError } from './abort.js'
|
|
1
2
|
import { sleep } from './sleep.js'
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
|
-
* Repeatedly calls a given asynchronous function until it resolves with a value
|
|
5
|
-
* @param fn The function that should be repeated
|
|
5
|
+
* Repeatedly calls a given asynchronous function until it resolves with a truthy value
|
|
6
|
+
* @param fn The function that should be repeated. A falsy result means "no result yet" and polls again, with no limit on the number of polls
|
|
6
7
|
* @param interval The timeout in milliseconds between retries, or a function that receives the current poll count and returns the interval. Defaults to 5000
|
|
7
|
-
* @param maxRetries Maximum number of
|
|
8
|
+
* @param maxRetries Maximum number of calls that throw before the error is rethrown, defaults to 3
|
|
8
9
|
* @param shouldRetry Optional predicate to determine if an error should trigger a retry
|
|
10
|
+
* @param signal Optional signal that ends the wait: no call starts after it aborts, and the sleep between calls ends at once
|
|
9
11
|
* @returns The result of the fn function
|
|
10
|
-
* @throws
|
|
12
|
+
* @throws The error of fn if maximum retries is reached, or if shouldRetry returns false
|
|
13
|
+
* @throws The abort reason of `signal` once it aborts
|
|
11
14
|
*/
|
|
12
15
|
export const waitForResult = async <T>(
|
|
13
16
|
fn: () => Promise<T | undefined>,
|
|
14
17
|
interval: number | ((poll: number) => number) = 5000,
|
|
15
18
|
maxRetries = 3,
|
|
16
|
-
shouldRetry: (count: number, error: unknown) => boolean = () => true
|
|
19
|
+
shouldRetry: (count: number, error: unknown) => boolean = () => true,
|
|
20
|
+
signal?: AbortSignal
|
|
17
21
|
): Promise<T> => {
|
|
18
22
|
let result: T | undefined
|
|
19
23
|
let attempts = 0
|
|
@@ -22,13 +26,16 @@ export const waitForResult = async <T>(
|
|
|
22
26
|
const getInterval = typeof interval === 'function' ? interval : () => interval
|
|
23
27
|
|
|
24
28
|
while (!result) {
|
|
29
|
+
if (signal?.aborted) {
|
|
30
|
+
throw getAbortError(signal)
|
|
31
|
+
}
|
|
25
32
|
try {
|
|
26
33
|
result = await fn()
|
|
27
|
-
if (!result) {
|
|
28
|
-
await sleep(getInterval(polls))
|
|
29
|
-
polls++
|
|
30
|
-
}
|
|
31
34
|
} catch (error) {
|
|
35
|
+
// An error of a call that the abort cut short is not a reason to retry.
|
|
36
|
+
if (signal?.aborted) {
|
|
37
|
+
throw getAbortError(signal)
|
|
38
|
+
}
|
|
32
39
|
if (!shouldRetry(attempts, error)) {
|
|
33
40
|
throw error
|
|
34
41
|
}
|
|
@@ -36,7 +43,10 @@ export const waitForResult = async <T>(
|
|
|
36
43
|
if (attempts === maxRetries) {
|
|
37
44
|
throw error
|
|
38
45
|
}
|
|
39
|
-
|
|
46
|
+
}
|
|
47
|
+
if (!result) {
|
|
48
|
+
// Rejects at once, also when the signal aborted during the call.
|
|
49
|
+
await sleep(getInterval(polls), { signal })
|
|
40
50
|
polls++
|
|
41
51
|
}
|
|
42
52
|
}
|