@lifi/sdk 4.9.0 → 4.10.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.
Files changed (76) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/cjs/core/tasks/helpers/checkBalance.js +6 -3
  3. package/dist/cjs/core/tasks/helpers/checkBalance.js.map +1 -1
  4. package/dist/cjs/index.d.ts +2 -1
  5. package/dist/cjs/index.js +2 -1
  6. package/dist/cjs/utils/abort.d.ts +6 -0
  7. package/dist/cjs/utils/abort.js +10 -0
  8. package/dist/cjs/utils/abort.js.map +1 -0
  9. package/dist/cjs/utils/checkPackageUpdates.js +1 -1
  10. package/dist/cjs/utils/formatUnits.js +1 -0
  11. package/dist/cjs/utils/formatUnits.js.map +1 -1
  12. package/dist/cjs/utils/lru.d.ts +14 -0
  13. package/dist/cjs/utils/lru.js +35 -0
  14. package/dist/cjs/utils/lru.js.map +1 -0
  15. package/dist/cjs/utils/parseUnits.js +30 -16
  16. package/dist/cjs/utils/parseUnits.js.map +1 -1
  17. package/dist/cjs/utils/sleep.d.ts +7 -1
  18. package/dist/cjs/utils/sleep.js +22 -3
  19. package/dist/cjs/utils/sleep.js.map +1 -1
  20. package/dist/cjs/utils/waitForResult.d.ts +4 -4
  21. package/dist/cjs/utils/waitForResult.js +4 -4
  22. package/dist/cjs/utils/waitForResult.js.map +1 -1
  23. package/dist/cjs/utils/withDedupe.d.ts +0 -10
  24. package/dist/cjs/utils/withDedupe.js +4 -23
  25. package/dist/cjs/utils/withDedupe.js.map +1 -1
  26. package/dist/cjs/utils/withTimeout.js +6 -2
  27. package/dist/cjs/utils/withTimeout.js.map +1 -1
  28. package/dist/cjs/version.d.ts +1 -1
  29. package/dist/cjs/version.js +1 -1
  30. package/dist/cjs/version.js.map +1 -1
  31. package/dist/esm/core/tasks/helpers/checkBalance.js +6 -3
  32. package/dist/esm/core/tasks/helpers/checkBalance.js.map +1 -1
  33. package/dist/esm/index.d.ts +2 -1
  34. package/dist/esm/index.js +2 -1
  35. package/dist/esm/utils/abort.d.ts +6 -0
  36. package/dist/esm/utils/abort.d.ts.map +1 -0
  37. package/dist/esm/utils/abort.js +8 -0
  38. package/dist/esm/utils/abort.js.map +1 -0
  39. package/dist/esm/utils/checkPackageUpdates.js +1 -1
  40. package/dist/esm/utils/formatUnits.js +1 -0
  41. package/dist/esm/utils/formatUnits.js.map +1 -1
  42. package/dist/esm/utils/lru.d.ts +14 -0
  43. package/dist/esm/utils/lru.d.ts.map +1 -0
  44. package/dist/esm/utils/lru.js +34 -0
  45. package/dist/esm/utils/lru.js.map +1 -0
  46. package/dist/esm/utils/parseUnits.js +30 -16
  47. package/dist/esm/utils/parseUnits.js.map +1 -1
  48. package/dist/esm/utils/sleep.d.ts +7 -1
  49. package/dist/esm/utils/sleep.d.ts.map +1 -1
  50. package/dist/esm/utils/sleep.js +22 -3
  51. package/dist/esm/utils/sleep.js.map +1 -1
  52. package/dist/esm/utils/waitForResult.d.ts +4 -4
  53. package/dist/esm/utils/waitForResult.js +4 -4
  54. package/dist/esm/utils/waitForResult.js.map +1 -1
  55. package/dist/esm/utils/withDedupe.d.ts +0 -10
  56. package/dist/esm/utils/withDedupe.d.ts.map +1 -1
  57. package/dist/esm/utils/withDedupe.js +5 -22
  58. package/dist/esm/utils/withDedupe.js.map +1 -1
  59. package/dist/esm/utils/withTimeout.d.ts.map +1 -1
  60. package/dist/esm/utils/withTimeout.js +6 -2
  61. package/dist/esm/utils/withTimeout.js.map +1 -1
  62. package/dist/esm/version.d.ts +1 -1
  63. package/dist/esm/version.js +1 -1
  64. package/dist/esm/version.js.map +1 -1
  65. package/package.json +2 -2
  66. package/src/core/tasks/helpers/checkBalance.ts +11 -3
  67. package/src/index.ts +2 -1
  68. package/src/utils/abort.ts +10 -0
  69. package/src/utils/formatUnits.ts +6 -0
  70. package/src/utils/lru.ts +38 -0
  71. package/src/utils/parseUnits.ts +53 -20
  72. package/src/utils/sleep.ts +27 -3
  73. package/src/utils/waitForResult.ts +4 -4
  74. package/src/utils/withDedupe.ts +4 -28
  75. package/src/utils/withTimeout.ts +7 -2
  76. package/src/version.ts +1 -1
@@ -1,6 +1,6 @@
1
1
  //#region src/version.ts
2
2
  const name = "@lifi/sdk";
3
- const version = "4.9.0";
3
+ const version = "4.10.0";
4
4
  //#endregion
5
5
  export { name, version };
6
6
 
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../../src/version.ts"],"sourcesContent":["export const name = '@lifi/sdk'\nexport const version = '4.9.0'\n"],"mappings":";AAAA,MAAa,OAAO;AACpB,MAAa,UAAU"}
1
+ {"version":3,"file":"version.js","names":[],"sources":["../../src/version.ts"],"sourcesContent":["export const name = '@lifi/sdk'\nexport const version = '4.10.0'\n"],"mappings":";AAAA,MAAa,OAAO;AACpB,MAAa,UAAU"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lifi/sdk",
3
- "version": "4.9.0",
3
+ "version": "4.10.0",
4
4
  "description": "LI.FI SDK for Any-to-Any Cross-Chain-Swap",
5
5
  "homepage": "https://github.com/lifinance/sdk",
6
6
  "bugs": {
@@ -28,7 +28,7 @@
28
28
  "./package.json": "./package.json"
29
29
  },
30
30
  "dependencies": {
31
- "@lifi/types": "^18.10.0"
31
+ "@lifi/types": "^18.12.1"
32
32
  },
33
33
  "publishConfig": {
34
34
  "access": "public"
@@ -118,6 +118,11 @@ export const checkBalance = async (
118
118
  Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION))
119
119
  )
120
120
 
121
+ // Aborted once `withTimeout` settles. A timeout rejects at once, but the
122
+ // loop keeps running; the signal stops it before it can change `step`.
123
+ const controller = new AbortController()
124
+ const { signal } = controller
125
+
121
126
  await withTimeout(
122
127
  async () => {
123
128
  for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
@@ -133,9 +138,12 @@ export const checkBalance = async (
133
138
  error as Error
134
139
  )
135
140
  }
136
- await sleep(BACKOFF_BASE_MS * 2 ** attempt)
141
+ await sleep(BACKOFF_BASE_MS * 2 ** attempt, { signal })
137
142
  continue
138
143
  }
144
+ if (signal.aborted) {
145
+ return
146
+ }
139
147
 
140
148
  const balanceByAddress = new Map(
141
149
  balances.map((b) => [b.address.toLowerCase(), b.amount] as const)
@@ -207,12 +215,12 @@ export const checkBalance = async (
207
215
  )
208
216
  }
209
217
 
210
- await sleep(BACKOFF_BASE_MS * 2 ** attempt)
218
+ await sleep(BACKOFF_BASE_MS * 2 ** attempt, { signal })
211
219
  }
212
220
  },
213
221
  {
214
222
  timeout: OVERALL_TIMEOUT_MS,
215
223
  errorInstance: new BalanceError('Could not read wallet balance.'),
216
224
  }
217
- )
225
+ ).finally(() => controller.abort())
218
226
  }
package/src/index.ts CHANGED
@@ -123,9 +123,10 @@ export { convertQuoteToRoute } from './utils/convertQuoteToRoute.js'
123
123
  export { fetchTxErrorDetails } from './utils/fetchTxErrorDetails.js'
124
124
  export { formatUnits } from './utils/formatUnits.js'
125
125
  export { isHex } from './utils/isHex.js'
126
+ export { LruMap } from './utils/lru.js'
126
127
  export { parseUnits } from './utils/parseUnits.js'
127
128
  export { sleep } from './utils/sleep.js'
128
129
  export { waitForResult } from './utils/waitForResult.js'
129
- export { LruMap, withDedupe } from './utils/withDedupe.js'
130
+ export { withDedupe } from './utils/withDedupe.js'
130
131
  export { withTimeout } from './utils/withTimeout.js'
131
132
  export { name, version } from './version.js'
@@ -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'
@@ -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('-')
@@ -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
+ }
@@ -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 (!/^(-?)([0-9]*)\.?([0-9]*)$/.test(value)) {
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
- if (Math.round(Number(`.${fraction}`)) === 1) {
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 [left, unit, right] = [
27
- fraction.slice(0, decimals - 1),
28
- fraction.slice(decimals - 1, decimals),
29
- fraction.slice(decimals),
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 (fraction.length > decimals) {
40
- fraction = fraction.slice(1)
41
- integer = `${BigInt(integer) + 1n}`
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
+ }
@@ -1,5 +1,29 @@
1
- export function sleep(ms: number): Promise<null> {
2
- return new Promise((resolve) => {
3
- setTimeout(() => resolve(null), ms)
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,13 +1,13 @@
1
1
  import { sleep } from './sleep.js'
2
2
 
3
3
  /**
4
- * Repeatedly calls a given asynchronous function until it resolves with a value
5
- * @param fn The function that should be repeated
4
+ * Repeatedly calls a given asynchronous function until it resolves with a truthy value
5
+ * @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
6
  * @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 retries before throwing an error, defaults to 3
7
+ * @param maxRetries Maximum number of calls that throw before the error is rethrown, defaults to 3
8
8
  * @param shouldRetry Optional predicate to determine if an error should trigger a retry
9
9
  * @returns The result of the fn function
10
- * @throws Error if maximum retries is reached, if function keeps returning undefined, or if shouldRetry returns false
10
+ * @throws The error of fn if maximum retries is reached, or if shouldRetry returns false
11
11
  */
12
12
  export const waitForResult = async <T>(
13
13
  fn: () => Promise<T | undefined>,
@@ -1,24 +1,5 @@
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 set(key: string, value: value): this {
15
- super.set(key, value)
16
- if (this.maxSize && this.size > this.maxSize) {
17
- this.delete(this.keys().next().value!)
18
- }
19
- return this
20
- }
21
- }
1
+ import { getAbortError } from './abort.js'
2
+ import { LruMap } from './lru.js'
22
3
 
23
4
  type Caller = {
24
5
  resolve: (value: any) => void
@@ -70,7 +51,7 @@ export function withDedupe<T>(
70
51
  return fn(signal)
71
52
  }
72
53
  if (signal?.aborted) {
73
- return Promise.reject(abortReason(signal))
54
+ return Promise.reject(getAbortError(signal))
74
55
  }
75
56
  let inFlight = promiseCache.get(id)
76
57
  if (!inFlight) {
@@ -108,7 +89,7 @@ function join<T>(
108
89
  // `leave` can run without the event, so the listener is not always gone.
109
90
  signal.removeEventListener('abort', leave)
110
91
  callers.delete(caller)
111
- const reason = abortReason(signal)
92
+ const reason = getAbortError(signal)
112
93
  reject(reason)
113
94
  if (!inFlight.pinned && callers.size === 0) {
114
95
  // A caller arriving now must start a new request, not join this one.
@@ -156,8 +137,3 @@ function evict(id: string, promise: Promise<unknown>): void {
156
137
  promiseCache.delete(id)
157
138
  }
158
139
  }
159
-
160
- /** Older runtimes and polyfills can abort a signal without a `reason`. */
161
- const abortReason = (signal: AbortSignal): unknown =>
162
- signal.reason ??
163
- Object.assign(new Error('This operation was aborted'), { name: 'AbortError' })
@@ -1,3 +1,5 @@
1
+ import { isAbortError } from './abort.js'
2
+
1
3
  /**
2
4
  * Wraps a function in a timeout.
3
5
  * Based on viem's withTimeout implementation.
@@ -25,8 +27,8 @@ export function withTimeout<T>(
25
27
  return new Promise((resolve, reject) => {
26
28
  ;(async () => {
27
29
  let timeoutId!: NodeJS.Timeout
30
+ const controller = new AbortController()
28
31
  try {
29
- const controller = new AbortController()
30
32
  if (timeout > 0) {
31
33
  timeoutId = setTimeout(() => {
32
34
  if (signal) {
@@ -38,8 +40,11 @@ export function withTimeout<T>(
38
40
  }
39
41
  resolve(await fn({ signal: controller?.signal || null }))
40
42
  } catch (err) {
41
- if ((err as Error)?.name === 'AbortError') {
43
+ // Only an abort from our own timeout is a timeout. Any other
44
+ // AbortError belongs to the caller and passes through.
45
+ if (controller.signal.aborted && isAbortError(err)) {
42
46
  reject(errorInstance)
47
+ return
43
48
  }
44
49
  reject(err)
45
50
  } finally {
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export const name = '@lifi/sdk'
2
- export const version = '4.9.0'
2
+ export const version = '4.10.0'