@lifi/sdk 0.0.0-preview-dd8065ff → 0.0.0-preview-1b774eec

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 (132) hide show
  1. package/CHANGELOG.md +55 -2
  2. package/README.md +9 -0
  3. package/dist/cjs/actions/getChains.js +7 -1
  4. package/dist/cjs/actions/getChains.js.map +1 -1
  5. package/dist/cjs/actions/getContractCallsQuote.js +1 -1
  6. package/dist/cjs/actions/getGasRecommendation.js +1 -1
  7. package/dist/cjs/actions/getQuote.js +1 -1
  8. package/dist/cjs/actions/getRelayedTransactionStatus.js +1 -1
  9. package/dist/cjs/actions/getRelayerQuote.js +1 -1
  10. package/dist/cjs/actions/getRoutes.js +1 -1
  11. package/dist/cjs/actions/getStatus.js +1 -1
  12. package/dist/cjs/actions/getToken.js +1 -1
  13. package/dist/cjs/actions/getTokens.js +7 -1
  14. package/dist/cjs/actions/getTokens.js.map +1 -1
  15. package/dist/cjs/actions/relayTransaction.js +1 -1
  16. package/dist/cjs/client/createClient.js +33 -10
  17. package/dist/cjs/client/createClient.js.map +1 -1
  18. package/dist/cjs/client/findProvider.d.ts +10 -0
  19. package/dist/cjs/client/findProvider.js +11 -0
  20. package/dist/cjs/client/findProvider.js.map +1 -0
  21. package/dist/cjs/core/tasks/helpers/checkBalance.js +6 -3
  22. package/dist/cjs/core/tasks/helpers/checkBalance.js.map +1 -1
  23. package/dist/cjs/index.d.ts +5 -3
  24. package/dist/cjs/index.js +6 -3
  25. package/dist/cjs/types/core.d.ts +62 -2
  26. package/dist/cjs/utils/abort.d.ts +6 -0
  27. package/dist/cjs/utils/abort.js +10 -0
  28. package/dist/cjs/utils/abort.js.map +1 -0
  29. package/dist/cjs/utils/checkPackageUpdates.js +1 -1
  30. package/dist/cjs/utils/convertQuoteToRoute.js +1 -1
  31. package/dist/cjs/utils/formatUnits.js +1 -0
  32. package/dist/cjs/utils/formatUnits.js.map +1 -1
  33. package/dist/cjs/utils/lru.d.ts +14 -0
  34. package/dist/cjs/utils/lru.js +35 -0
  35. package/dist/cjs/utils/lru.js.map +1 -0
  36. package/dist/cjs/utils/parseUnits.js +30 -16
  37. package/dist/cjs/utils/parseUnits.js.map +1 -1
  38. package/dist/cjs/utils/request.js +2 -2
  39. package/dist/cjs/utils/sleep.d.ts +7 -1
  40. package/dist/cjs/utils/sleep.js +22 -3
  41. package/dist/cjs/utils/sleep.js.map +1 -1
  42. package/dist/cjs/utils/waitForResult.d.ts +4 -4
  43. package/dist/cjs/utils/waitForResult.js +4 -4
  44. package/dist/cjs/utils/waitForResult.js.map +1 -1
  45. package/dist/cjs/utils/withDedupe.d.ts +15 -12
  46. package/dist/cjs/utils/withDedupe.js +69 -25
  47. package/dist/cjs/utils/withDedupe.js.map +1 -1
  48. package/dist/cjs/utils/withTimeout.js +6 -2
  49. package/dist/cjs/utils/withTimeout.js.map +1 -1
  50. package/dist/cjs/version.d.ts +1 -1
  51. package/dist/cjs/version.js +1 -1
  52. package/dist/cjs/version.js.map +1 -1
  53. package/dist/esm/actions/getChains.d.ts.map +1 -1
  54. package/dist/esm/actions/getChains.js +7 -1
  55. package/dist/esm/actions/getChains.js.map +1 -1
  56. package/dist/esm/actions/getContractCallsQuote.js +1 -1
  57. package/dist/esm/actions/getGasRecommendation.js +1 -1
  58. package/dist/esm/actions/getQuote.js +1 -1
  59. package/dist/esm/actions/getRelayedTransactionStatus.js +1 -1
  60. package/dist/esm/actions/getRelayerQuote.js +1 -1
  61. package/dist/esm/actions/getRoutes.d.ts.map +1 -1
  62. package/dist/esm/actions/getRoutes.js +1 -1
  63. package/dist/esm/actions/getStatus.js +1 -1
  64. package/dist/esm/actions/getToken.js +1 -1
  65. package/dist/esm/actions/getTokens.d.ts.map +1 -1
  66. package/dist/esm/actions/getTokens.js +7 -1
  67. package/dist/esm/actions/getTokens.js.map +1 -1
  68. package/dist/esm/actions/index.d.ts.map +1 -1
  69. package/dist/esm/actions/relayTransaction.js +1 -1
  70. package/dist/esm/client/createClient.d.ts.map +1 -1
  71. package/dist/esm/client/createClient.js +33 -10
  72. package/dist/esm/client/createClient.js.map +1 -1
  73. package/dist/esm/client/findProvider.d.ts +10 -0
  74. package/dist/esm/client/findProvider.d.ts.map +1 -0
  75. package/dist/esm/client/findProvider.js +10 -0
  76. package/dist/esm/client/findProvider.js.map +1 -0
  77. package/dist/esm/core/tasks/helpers/checkBalance.js +6 -3
  78. package/dist/esm/core/tasks/helpers/checkBalance.js.map +1 -1
  79. package/dist/esm/index.d.ts +5 -3
  80. package/dist/esm/index.js +6 -4
  81. package/dist/esm/types/actions.d.ts.map +1 -1
  82. package/dist/esm/types/core.d.ts +62 -2
  83. package/dist/esm/types/core.d.ts.map +1 -1
  84. package/dist/esm/utils/abort.d.ts +6 -0
  85. package/dist/esm/utils/abort.d.ts.map +1 -0
  86. package/dist/esm/utils/abort.js +8 -0
  87. package/dist/esm/utils/abort.js.map +1 -0
  88. package/dist/esm/utils/checkPackageUpdates.js +1 -1
  89. package/dist/esm/utils/convertQuoteToRoute.js +1 -1
  90. package/dist/esm/utils/formatUnits.js +1 -0
  91. package/dist/esm/utils/formatUnits.js.map +1 -1
  92. package/dist/esm/utils/lru.d.ts +14 -0
  93. package/dist/esm/utils/lru.d.ts.map +1 -0
  94. package/dist/esm/utils/lru.js +34 -0
  95. package/dist/esm/utils/lru.js.map +1 -0
  96. package/dist/esm/utils/parseUnits.js +30 -16
  97. package/dist/esm/utils/parseUnits.js.map +1 -1
  98. package/dist/esm/utils/request.js +2 -2
  99. package/dist/esm/utils/sleep.d.ts +7 -1
  100. package/dist/esm/utils/sleep.d.ts.map +1 -1
  101. package/dist/esm/utils/sleep.js +22 -3
  102. package/dist/esm/utils/sleep.js.map +1 -1
  103. package/dist/esm/utils/waitForResult.d.ts +4 -4
  104. package/dist/esm/utils/waitForResult.js +4 -4
  105. package/dist/esm/utils/waitForResult.js.map +1 -1
  106. package/dist/esm/utils/withDedupe.d.ts +15 -12
  107. package/dist/esm/utils/withDedupe.d.ts.map +1 -1
  108. package/dist/esm/utils/withDedupe.js +71 -25
  109. package/dist/esm/utils/withDedupe.js.map +1 -1
  110. package/dist/esm/utils/withTimeout.d.ts.map +1 -1
  111. package/dist/esm/utils/withTimeout.js +6 -2
  112. package/dist/esm/utils/withTimeout.js.map +1 -1
  113. package/dist/esm/version.d.ts +1 -1
  114. package/dist/esm/version.js +1 -1
  115. package/dist/esm/version.js.map +1 -1
  116. package/package.json +2 -2
  117. package/src/actions/getChains.ts +12 -4
  118. package/src/actions/getTokens.ts +12 -4
  119. package/src/client/createClient.ts +59 -7
  120. package/src/client/findProvider.ts +21 -0
  121. package/src/core/tasks/helpers/checkBalance.ts +11 -3
  122. package/src/index.ts +5 -1
  123. package/src/types/core.ts +65 -2
  124. package/src/utils/abort.ts +10 -0
  125. package/src/utils/formatUnits.ts +6 -0
  126. package/src/utils/lru.ts +38 -0
  127. package/src/utils/parseUnits.ts +53 -20
  128. package/src/utils/sleep.ts +27 -3
  129. package/src/utils/waitForResult.ts +4 -4
  130. package/src/utils/withDedupe.ts +121 -27
  131. package/src/utils/withTimeout.ts +7 -2
  132. package/src/version.ts +1 -1
@@ -4,6 +4,7 @@ import type {
4
4
  ExtendedChain,
5
5
  RequestOptions,
6
6
  } from '@lifi/types'
7
+ import { SDKError } from '../errors/SDKError.js'
7
8
  import type { SDKBaseConfig, SDKClient } from '../types/core.js'
8
9
  import { request } from '../utils/request.js'
9
10
  import { withDedupe } from '../utils/withDedupe.js'
@@ -41,15 +42,22 @@ export const _getChains = async (
41
42
  params as Record<string, string>
42
43
  ).toString()
43
44
  const response = await withDedupe(
44
- () =>
45
+ (signal) =>
45
46
  request<ChainsResponse>(
46
47
  config,
47
48
  `${config.apiUrl}/chains?${urlSearchParams}`,
48
49
  {
49
- signal: options?.signal,
50
+ signal,
50
51
  }
51
52
  ),
52
- { id: `${getChains.name}.${urlSearchParams}` }
53
- )
53
+ {
54
+ id: `${getChains.name}.${config.apiUrl}.${urlSearchParams}`,
55
+ signal: options?.signal,
56
+ }
57
+ ).catch((error) => {
58
+ // A caller that aborts leaves before the request settles; keep its error
59
+ // shaped like one from `request`.
60
+ throw error instanceof SDKError ? error : new SDKError(error)
61
+ })
54
62
  return response.chains
55
63
  }
@@ -4,6 +4,7 @@ import type {
4
4
  TokensRequest,
5
5
  TokensResponse,
6
6
  } from '@lifi/types'
7
+ import { SDKError } from '../errors/SDKError.js'
7
8
  import type { SDKClient } from '../types/core.js'
8
9
  import { request } from '../utils/request.js'
9
10
  import { withDedupe } from '../utils/withDedupe.js'
@@ -43,15 +44,22 @@ export async function getTokens(
43
44
  ).toString()
44
45
  const _isExtended = params?.extended === true
45
46
  const response = await withDedupe(
46
- () =>
47
+ (signal) =>
47
48
  request<
48
49
  typeof _isExtended extends true
49
50
  ? TokensExtendedResponse
50
51
  : TokensResponse
51
52
  >(client.config, `${client.config.apiUrl}/tokens?${urlSearchParams}`, {
52
- signal: options?.signal,
53
+ signal,
53
54
  }),
54
- { id: `${getTokens.name}.${urlSearchParams}` }
55
- )
55
+ {
56
+ id: `${getTokens.name}.${client.config.apiUrl}.${urlSearchParams}`,
57
+ signal: options?.signal,
58
+ }
59
+ ).catch((error) => {
60
+ // A caller that aborts leaves before the request settles; keep its error
61
+ // shaped like one from `request`.
62
+ throw error instanceof SDKError ? error : new SDKError(error)
63
+ })
56
64
  return response
57
65
  }
@@ -1,5 +1,6 @@
1
1
  import type { ChainId, ChainType, ExtendedChain } from '@lifi/types'
2
2
  import type {
3
+ RPCUrls,
3
4
  SDKBaseConfig,
4
5
  SDKClient,
5
6
  SDKConfig,
@@ -7,8 +8,16 @@ import type {
7
8
  } from '../types/core.js'
8
9
  import { checkPackageUpdates } from '../utils/checkPackageUpdates.js'
9
10
  import { name, version } from '../version.js'
11
+ import { findProvider } from './findProvider.js'
10
12
  import { getClientStorage } from './getClientStorage.js'
11
13
 
14
+ // A provider replaces only one that serves the same chains. A provider that
15
+ // lists no chains keeps the bare type, so even an empty list stays apart.
16
+ const providerScope = (provider: SDKProvider): string =>
17
+ provider.chainIds
18
+ ? `${provider.type}:${[...provider.chainIds].sort().join(',')}`
19
+ : provider.type
20
+
12
21
  export function createClient(options: SDKConfig): SDKClient {
13
22
  if (!options.integrator) {
14
23
  throw new Error(
@@ -20,12 +29,38 @@ export function createClient(options: SDKConfig): SDKClient {
20
29
  checkPackageUpdates(name, version)
21
30
  }
22
31
 
23
- const { providers, ...configOptions } = options
32
+ const { providers, rpcUrls, ...configOptions } = options
33
+
34
+ // Role entries split once, here: the config keeps plain read lists, so
35
+ // everything that reads `config.rpcUrls` sees `string[]` as before.
36
+ const readRpcUrls: RPCUrls = {}
37
+ const writeRpcUrls: RPCUrls = {}
38
+ const bundleRpcUrls: RPCUrls = {}
39
+ let hasRoles = false
40
+ for (const key in rpcUrls) {
41
+ const chainId = Number(key) as ChainId
42
+ const entry = rpcUrls[chainId]
43
+ if (Array.isArray(entry)) {
44
+ readRpcUrls[chainId] = entry
45
+ } else if (entry) {
46
+ hasRoles = true
47
+ if (entry.read) {
48
+ readRpcUrls[chainId] = entry.read
49
+ }
50
+ if (entry.write?.length) {
51
+ writeRpcUrls[chainId] = entry.write
52
+ }
53
+ if (entry.bundle?.length) {
54
+ bundleRpcUrls[chainId] = entry.bundle
55
+ }
56
+ }
57
+ }
24
58
 
25
59
  const _config: SDKBaseConfig = {
26
60
  ...configOptions,
27
61
  apiUrl: configOptions?.apiUrl ?? 'https://li.quest/v1',
28
- rpcUrls: configOptions?.rpcUrls ?? {},
62
+ // Plain lists only: the caller's own object, exactly as before.
63
+ rpcUrls: hasRoles ? readRpcUrls : ((rpcUrls ?? {}) as RPCUrls),
29
64
  debug: configOptions?.debug ?? false,
30
65
  preloadChains: configOptions?.preloadChains ?? true,
31
66
  integrator: configOptions?.integrator ?? 'lifi-sdk',
@@ -41,15 +76,15 @@ export function createClient(options: SDKConfig): SDKClient {
41
76
  get providers() {
42
77
  return _providers
43
78
  },
44
- getProvider(type: ChainType) {
45
- return this.providers.find((provider) => provider.type === type)
79
+ getProvider(type: ChainType, chainId?: ChainId) {
80
+ return findProvider(this.providers, type, chainId)
46
81
  },
47
82
  setProviders(newProviders: SDKProvider[]) {
48
83
  const providerMap = new Map(
49
- this.providers.map((provider) => [provider.type, provider])
84
+ this.providers.map((provider) => [providerScope(provider), provider])
50
85
  )
51
86
  for (const provider of newProviders) {
52
- providerMap.set(provider.type, provider)
87
+ providerMap.set(providerScope(provider), provider)
53
88
  }
54
89
  _providers = Array.from(providerMap.values())
55
90
  },
@@ -78,6 +113,12 @@ export function createClient(options: SDKConfig): SDKClient {
78
113
  }
79
114
  return chainRpcUrls
80
115
  },
116
+ async getWriteRpcUrlsByChainId(chainId: ChainId) {
117
+ return writeRpcUrls[chainId] ?? []
118
+ },
119
+ async getBundleRpcUrlsByChainId(chainId: ChainId) {
120
+ return bundleRpcUrls[chainId] ?? []
121
+ },
81
122
  }
82
123
 
83
124
  function extend<TClient extends SDKClient>(
@@ -87,7 +128,18 @@ export function createClient(options: SDKConfig): SDKClient {
87
128
  ) => TClient & TExtensions {
88
129
  return (extendFn) => {
89
130
  const extensions = extendFn(base)
90
- const extended = { ...base, ...extensions } as TClient & typeof extensions
131
+ // Copy descriptors rather than spreading. `config` and `providers` are
132
+ // accessors over closure variables, and `setProviders` reassigns
133
+ // `_providers` — so a spread would freeze the extension on the values
134
+ // those getters happened to return at extend time, leaving it with a
135
+ // provider list that never updates.
136
+ const extended = Object.defineProperties(
137
+ {},
138
+ {
139
+ ...Object.getOwnPropertyDescriptors(base),
140
+ ...Object.getOwnPropertyDescriptors(extensions),
141
+ }
142
+ ) as TClient & typeof extensions
91
143
 
92
144
  // Preserve the extend function for further extensions
93
145
  return Object.assign(extended, {
@@ -0,0 +1,21 @@
1
+ import type { ChainId, ChainType } from '@lifi/types'
2
+ import type { SDKProvider } from '../types/core.js'
3
+
4
+ /**
5
+ * The provider that serves a chain: the one that lists `chainId` in its
6
+ * `chainIds`, otherwise the provider of `chainType` that lists no chains.
7
+ */
8
+ export const findProvider = <T extends Pick<SDKProvider, 'type' | 'chainIds'>>(
9
+ providers: readonly T[],
10
+ chainType: ChainType,
11
+ chainId?: ChainId
12
+ ): T | undefined =>
13
+ (chainId === undefined
14
+ ? undefined
15
+ : providers.find(
16
+ (provider) =>
17
+ provider.type === chainType && provider.chainIds?.includes(chainId)
18
+ )) ??
19
+ providers.find(
20
+ (provider) => provider.type === chainType && !provider.chainIds
21
+ )
@@ -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
@@ -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'
@@ -97,6 +98,8 @@ export type {
97
98
  RouteExecutionDictionary,
98
99
  RouteExtended,
99
100
  RPCUrls,
101
+ RPCUrlsByRole,
102
+ RPCUrlsConfig,
100
103
  SDKBaseConfig,
101
104
  SDKClient,
102
105
  SDKConfig,
@@ -121,9 +124,10 @@ export { convertQuoteToRoute } from './utils/convertQuoteToRoute.js'
121
124
  export { fetchTxErrorDetails } from './utils/fetchTxErrorDetails.js'
122
125
  export { formatUnits } from './utils/formatUnits.js'
123
126
  export { isHex } from './utils/isHex.js'
127
+ export { LruMap } from './utils/lru.js'
124
128
  export { parseUnits } from './utils/parseUnits.js'
125
129
  export { sleep } from './utils/sleep.js'
126
130
  export { waitForResult } from './utils/waitForResult.js'
127
- export { LruMap, withDedupe } from './utils/withDedupe.js'
131
+ export { withDedupe } from './utils/withDedupe.js'
128
132
  export { withTimeout } from './utils/withTimeout.js'
129
133
  export { name, version } from './version.js'
package/src/types/core.ts CHANGED
@@ -38,15 +38,64 @@ export interface SDKBaseConfig {
38
38
  storage?: SDKStorage
39
39
  }
40
40
 
41
- export interface SDKConfig extends Partial<Omit<SDKBaseConfig, 'integrator'>> {
41
+ export interface SDKConfig
42
+ extends Partial<Omit<SDKBaseConfig, 'integrator' | 'rpcUrls'>> {
42
43
  integrator: string
44
+ /**
45
+ * Per chain, one list for reads and sends, or lists by role. The client
46
+ * keeps the read lists in `config.rpcUrls` and serves the write and bundle
47
+ * lists through `getWriteRpcUrlsByChainId` and `getBundleRpcUrlsByChainId`.
48
+ */
49
+ rpcUrls?: RPCUrlsConfig
43
50
  providers?: SDKProvider[]
44
51
  }
45
52
 
53
+ /**
54
+ * RPC URLs for one chain, split by what they are used for.
55
+ */
56
+ export interface RPCUrlsByRole {
57
+ /**
58
+ * Reads: balances, simulation and confirmation. Unset, the chain's own RPC
59
+ * URLs serve reads, as for a chain with no `rpcUrls` entry.
60
+ */
61
+ read?: string[]
62
+ /**
63
+ * Sends. Unset or empty, the read URLs send as well. While `write` is set,
64
+ * nothing is sent through the read URLs: when `bundle` is unset, the write
65
+ * URLs that support bundles also submit bundles, and with none of them, a
66
+ * route that needs a bundle fails.
67
+ *
68
+ * Only `@lifi/sdk-provider-solana` uses this today; other providers ignore
69
+ * it.
70
+ */
71
+ write?: string[]
72
+ /**
73
+ * Bundle submissions (Jito `sendBundle`). Unset, empty, or with no URL that
74
+ * supports bundles, the write URLs that do submit them. While `bundle` or
75
+ * `write` is set, bundles never go to the read URLs.
76
+ *
77
+ * Only `@lifi/sdk-provider-solana` uses this today; other providers ignore
78
+ * it.
79
+ */
80
+ bundle?: string[]
81
+ }
82
+
83
+ /**
84
+ * The `rpcUrls` option of `createClient`: per chain, either one list for reads
85
+ * and sends, or lists by role.
86
+ */
87
+ export type RPCUrlsConfig = Partial<Record<ChainId, string[] | RPCUrlsByRole>>
88
+
89
+ /** RPC URL lists per chain. `client.config.rpcUrls` holds the read lists. */
46
90
  export type RPCUrls = Partial<Record<ChainId, string[]>>
47
91
 
48
92
  export interface SDKProvider {
49
93
  readonly type: ChainType
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[]
50
99
  /**
51
100
  * Validates a wallet address. With `chainId`, a provider whose chains use
52
101
  * different address formats accepts only that chain's format and refuses a
@@ -77,13 +126,27 @@ export interface SDKProvider {
77
126
  export interface SDKClient {
78
127
  config: SDKBaseConfig
79
128
  providers: SDKProvider[]
80
- getProvider(type: ChainType): SDKProvider | undefined
129
+ getProvider(type: ChainType, chainId?: ChainId): SDKProvider | undefined
81
130
  setProviders(providers: SDKProvider[]): void
82
131
  setChains(chains: ExtendedChain[]): void
83
132
  getChains(): Promise<ExtendedChain[]>
84
133
  getChainById(chainId: ChainId): Promise<ExtendedChain>
85
134
  getRpcUrls(): Promise<RPCUrls>
86
135
  getRpcUrlsByChainId(chainId: ChainId): Promise<string[]>
136
+ /**
137
+ * The chain's dedicated write RPC URLs (`rpcUrls[chainId].write`). Empty
138
+ * when the chain has none.
139
+ *
140
+ * Optional so clients from other SDK versions, and hand-written ones, still
141
+ * satisfy `SDKClient`. Providers treat a missing method as no write list.
142
+ */
143
+ getWriteRpcUrlsByChainId?(chainId: ChainId): Promise<string[]>
144
+ /**
145
+ * The chain's dedicated bundle RPC URLs (`rpcUrls[chainId].bundle`). Empty
146
+ * when the chain has none. Optional for the same reason as
147
+ * `getWriteRpcUrlsByChainId`.
148
+ */
149
+ getBundleRpcUrlsByChainId?(chainId: ChainId): Promise<string[]>
87
150
  }
88
151
 
89
152
  export interface StepExecutorOptions {
@@ -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>,