@ledgerhq/coin-module-framework 11.4.0 → 13.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.
@@ -5,20 +5,15 @@ import type { CurrencyConfig, Context } from '../config'
5
5
  import type { CoinModuleImpl } from './impl'
6
6
  import type {
7
7
  Balance,
8
- Block,
9
8
  BlockInfo,
10
9
  CraftedTransaction,
11
10
  FeeEstimation,
12
- GetBlockOptions,
13
11
  Holding,
14
12
  ListHoldingsOptions,
15
13
  ListOperationsOptions,
16
- Operation,
17
- Page,
18
14
  TransactionIntent,
19
15
  } from './types'
20
- import { InvalidParameterError } from '../errors'
21
- import { isNotSupportedStub, notSupported } from './notSupported'
16
+ import { notSupported } from './notSupported'
22
17
  import { withDefaults } from './withDefaults'
23
18
 
24
19
  const stubIntent: TransactionIntent = {
@@ -222,122 +217,4 @@ describe('withDefaults', () => {
222
217
  expect(() => api.getStakes(ctx, 'addr')).toThrow('getStakes is not supported')
223
218
  })
224
219
  })
225
-
226
- describe('read options', () => {
227
- const block: Block = { info: { height: 1, hash: 'h', time: new Date(0) }, transactions: [] }
228
- const page: Page<Operation> = { items: [] }
229
- const listOperations = jest.fn((_ctx: Ctx, _addr: string, _opts: ListOperationsOptions) =>
230
- Promise.resolve(page)
231
- )
232
- const getBlock = jest.fn((_ctx: Ctx, _height: number, _opts?: GetBlockOptions) =>
233
- Promise.resolve(block)
234
- )
235
- const withBlock: CoinModuleImpl<Cfg> = { ...minimalModule, listOperations, getBlock }
236
-
237
- beforeEach(() => {
238
- listOperations.mockClear()
239
- getBlock.mockClear()
240
- })
241
-
242
- it('passes declared methods through untouched', async () => {
243
- const api = withDefaults({
244
- ...withBlock,
245
- readOptions: { listOperations: ['feesAsset'], getBlock: ['feesAsset'] },
246
- })
247
-
248
- expect(api.listOperations).toBe(listOperations)
249
- expect(api.getBlock).toBe(getBlock)
250
- expect(api.supportsReadOption('listOperations', 'feesAsset')).toBe(true)
251
- expect(api.supportsReadOption('getBlock', 'feesAsset')).toBe(true)
252
- await expect(api.getBlock(ctx, 1, { feesAsset: true })).resolves.toBe(block)
253
- })
254
-
255
- it('rejects an opted-in call to a method that does not declare the option', async () => {
256
- const api = withDefaults(withBlock)
257
-
258
- expect(api.supportsReadOption('listOperations', 'feesAsset')).toBe(false)
259
- expect(api.supportsReadOption('getBlock', 'feesAsset')).toBe(false)
260
- await expect(
261
- api.listOperations(ctx, 'addr', { minHeight: 0, feesAsset: true })
262
- ).rejects.toThrow(
263
- new InvalidParameterError('listOperations does not support the feesAsset option')
264
- )
265
- await expect(api.getBlock(ctx, 1, { feesAsset: true })).rejects.toThrow(
266
- new InvalidParameterError('getBlock does not support the feesAsset option')
267
- )
268
- expect(listOperations).not.toHaveBeenCalled()
269
- expect(getBlock).not.toHaveBeenCalled()
270
- })
271
-
272
- it('calls through unchanged when the option is not set', async () => {
273
- const api = withDefaults(withBlock)
274
- const options: ListOperationsOptions = { minHeight: 0, feesAsset: false }
275
-
276
- await expect(api.listOperations(ctx, 'addr', options)).resolves.toBe(page)
277
- await expect(api.getBlock(ctx, 1)).resolves.toBe(block)
278
- await expect(api.getBlock(ctx, 2, {})).resolves.toBe(block)
279
- expect(listOperations).toHaveBeenCalledWith(ctx, 'addr', options)
280
- expect(getBlock.mock.calls).toEqual([
281
- [ctx, 1],
282
- [ctx, 2, {}],
283
- ])
284
- })
285
-
286
- it('keeps the receiver of a guarded method', async () => {
287
- const impl = {
288
- ...minimalModule,
289
- page,
290
- listOperations(
291
- this: { page: Page<Operation> },
292
- _ctx: Ctx,
293
- _addr: string,
294
- _opts: ListOperationsOptions
295
- ) {
296
- return Promise.resolve(this.page)
297
- },
298
- }
299
- const api = withDefaults(impl)
300
-
301
- await expect(api.listOperations(ctx, 'addr', { minHeight: 0 })).resolves.toBe(page)
302
- })
303
-
304
- it('guards each method on its own declaration', async () => {
305
- const api = withDefaults({ ...withBlock, readOptions: { getBlock: ['feesAsset'] } })
306
-
307
- expect(api.supportsReadOption('getBlock', 'feesAsset')).toBe(true)
308
- expect(api.supportsReadOption('listOperations', 'feesAsset')).toBe(false)
309
- await expect(api.getBlock(ctx, 1, { feesAsset: true })).resolves.toBe(block)
310
- await expect(
311
- api.listOperations(ctx, 'addr', { minHeight: 0, feesAsset: true })
312
- ).rejects.toThrow(InvalidParameterError)
313
- })
314
-
315
- it('keeps a listOperations stub tagged', () => {
316
- const api = withDefaults({
317
- ...minimalModule,
318
- listOperations: notSupported('listOperations'),
319
- readOptions: { listOperations: ['feesAsset'] },
320
- })
321
-
322
- expect(isNotSupportedStub(api.listOperations)).toBe(true)
323
- expect(api.supportsReadOption('listOperations', 'feesAsset')).toBe(false)
324
- expect(() => api.listOperations(ctx, 'addr', { minHeight: 0, feesAsset: true })).toThrow(
325
- 'listOperations is not supported'
326
- )
327
- })
328
-
329
- it('keeps the getBlock fallback stub when getBlock is not implemented', () => {
330
- const api = withDefaults({ ...minimalModule, readOptions: { getBlock: ['feesAsset'] } })
331
- const rewrapped = withDefaults(api)
332
-
333
- for (const resolved of [api, rewrapped]) {
334
- expect(isNotSupportedStub(resolved.getBlock)).toBe(true)
335
- expect(resolved.supports('getBlock')).toBe(false)
336
- expect(resolved.supportsReadOption('getBlock', 'feesAsset')).toBe(false)
337
- expect(() => resolved.getBlock(ctx, 1, { feesAsset: true })).toThrow(
338
- 'getBlock is not supported'
339
- )
340
- }
341
- })
342
- })
343
220
  })
@@ -2,21 +2,13 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
4
  import type { CurrencyConfig } from '../config'
5
- import type {
6
- CoinModuleImpl,
7
- OptionalApiKey,
8
- ReadOption,
9
- ReadOptionMethod,
10
- ReadOptionsDeclaration,
11
- } from './impl'
5
+ import type { CoinModuleImpl, OptionalApiKey } from './impl'
12
6
  import type { CoinModuleApi, Memo, MemoNotSupported, TxData, TxDataNotSupported } from './types'
13
- import { InvalidParameterError } from '../errors'
14
7
  import { optionalApiKeys } from './impl'
15
8
  import { isNotSupportedStub, notSupported } from './notSupported'
16
9
 
17
10
  /**
18
- * What {@link withDefaults} returns: the full consumer contract, plus `supports()` and
19
- * `supportsReadOption()`.
11
+ * What {@link withDefaults} returns: the full consumer contract, plus `supports()`.
20
12
  *
21
13
  * `getAccountInfo` is narrowed to required. It is the one managed capability that
22
14
  * {@link CoinModuleApi} itself declares optional, and `withDefaults` always supplies it — so
@@ -30,13 +22,6 @@ export type WithDefaultsResult<
30
22
  > = CoinModuleApi<ConfigType, MemoType, TxDataType> &
31
23
  Required<Pick<CoinModuleApi<ConfigType, MemoType, TxDataType>, 'getAccountInfo'>> & {
32
24
  supports: (method: OptionalApiKey) => boolean
33
- /**
34
- * Whether `method` honours the read `option`: the module implements the method and declares
35
- * the option in `readOptions`. When the method is implemented but does not declare the option,
36
- * an opted-in call rejects with an {@link InvalidParameterError}. When the method is not
37
- * implemented, every call throws `"<method> is not supported"`, as without the option.
38
- */
39
- supportsReadOption: (method: ReadOptionMethod, option: ReadOption) => boolean
40
25
  }
41
26
 
42
27
  /**
@@ -50,33 +35,6 @@ function implemented<T>(value: T | undefined): T | undefined {
50
35
  return value === undefined || isNotSupportedStub(value) ? undefined : value
51
36
  }
52
37
 
53
- function declares(
54
- readOptions: ReadOptionsDeclaration | undefined,
55
- method: ReadOptionMethod,
56
- option: ReadOption
57
- ): boolean {
58
- return readOptions?.[method]?.includes(option) ?? false
59
- }
60
-
61
- /**
62
- * Rejects an opted-in call to a method that does not declare the `feesAsset` read option.
63
- *
64
- * Both guarded methods take their options as the third argument. A call without the option goes
65
- * through with its arguments and its receiver unchanged: an implementation may read `this`.
66
- */
67
- function guardFeesAsset<Args extends [unknown, unknown, ({ feesAsset?: boolean } | undefined)?], R>(
68
- method: ReadOptionMethod,
69
- fn: (...args: Args) => Promise<R>,
70
- declared: boolean
71
- ): (...args: Args) => Promise<R> {
72
- if (declared) return fn
73
- return function (this: unknown, ...args: Args): Promise<R> {
74
- return args[2]?.feesAsset
75
- ? Promise.reject(new InvalidParameterError(`${method} does not support the feesAsset option`))
76
- : fn.apply(this, args)
77
- }
78
- }
79
-
80
38
  /**
81
39
  * Widens a {@link CoinModuleImpl} authoring value to the full {@link CoinModuleApi}
82
40
  * consumer contract by backfilling the capability methods the author omitted, and attaches
@@ -91,9 +49,6 @@ function guardFeesAsset<Args extends [unknown, unknown, ({ feesAsset?: boolean }
91
49
  *
92
50
  * A capability method is considered implemented only when the author supplied a real
93
51
  * function — a `notSupported()` stub is treated as if the method had been omitted.
94
- *
95
- * `listOperations` and `getBlock` reject a call that sets a read option the module does not
96
- * declare in `readOptions` (see `ReadOptionsDeclaration`). Calls without it are unchanged.
97
52
  */
98
53
  export function withDefaults<
99
54
  ConfigType extends CurrencyConfig,
@@ -106,28 +61,12 @@ export function withDefaults<
106
61
  const implementedMethods = new Set<OptionalApiKey>(
107
62
  optionalApiKeys.filter((k) => implemented(impl[k]) !== undefined)
108
63
  )
109
- // A stub stays the tagged stub, not a guarded wrapper: callers detect it as "not supported".
110
- // listOperations is required, but a read-only module built on notSupportedApi() may stub it.
111
- const listOperations = implemented(impl.listOperations)
112
- const getBlock = implemented(impl.getBlock)
113
- const supportsReadOption = (method: ReadOptionMethod, option: ReadOption): boolean =>
114
- (method === 'listOperations' ? listOperations !== undefined : getBlock !== undefined) &&
115
- declares(impl.readOptions, method, option)
116
64
 
117
65
  // Spread first so anything the module exposes beyond the API surface survives, then
118
66
  // override every capability method with either the real implementation or the default.
119
67
  return {
120
68
  ...impl,
121
- listOperations: listOperations
122
- ? guardFeesAsset(
123
- 'listOperations',
124
- listOperations,
125
- supportsReadOption('listOperations', 'feesAsset')
126
- )
127
- : impl.listOperations,
128
- getBlock: getBlock
129
- ? guardFeesAsset('getBlock', getBlock, supportsReadOption('getBlock', 'feesAsset'))
130
- : notSupported('getBlock'),
69
+ getBlock: implemented(impl.getBlock) ?? notSupported('getBlock'),
131
70
  getBlockInfo: implemented(impl.getBlockInfo) ?? notSupported('getBlockInfo'),
132
71
  getStakes: implemented(impl.getStakes) ?? notSupported('getStakes'),
133
72
  getRewards: implemented(impl.getRewards) ?? notSupported('getRewards'),
@@ -145,6 +84,5 @@ export function withDefaults<
145
84
  // of a throwing stub. Callers read `type` and branch on it.
146
85
  getAccountInfo: implemented(impl.getAccountInfo) ?? (() => Promise.resolve({ type: 'none' })),
147
86
  supports: (method: OptionalApiKey): boolean => implementedMethods.has(method),
148
- supportsReadOption,
149
87
  }
150
88
  }
@@ -25,40 +25,36 @@ const minimalModule: CoinModuleImpl<Cfg> = {
25
25
  craftTransactionData: (_ctx: Ctx, _intent: TransactionIntent) => ({ type: 'none' }) as const,
26
26
  }
27
27
 
28
- // Every optional capability but getAccountInfo, which ADR-045 answers with a sentinel rather
29
- // than an error and which the report therefore leaves out.
30
- const ALL_CAPABILITIES = [
31
- 'call',
32
- 'craftRawTransaction',
33
- 'getBlock',
34
- 'getBlockInfo',
35
- 'getNextSequence',
36
- 'getRewards',
37
- 'getStakes',
38
- 'getValidators',
39
- 'listHoldings',
40
- 'register',
41
- 'validateAddress',
42
- 'validateIntent',
43
- ]
44
-
45
28
  describe('capabilityReport', () => {
46
- it('lists every capability a minimal module leaves out', async () => {
29
+ it('reports nothing supported for a minimal module', async () => {
47
30
  await expect(capabilityReport(minimalModule, ctx)).resolves.toEqual({
48
- unsupported: ALL_CAPABILITIES,
31
+ supported: [],
49
32
  inconsistent: [],
50
33
  })
51
34
  })
52
35
 
53
- it('drops a capability from the list once the module implements it', async () => {
54
- const withStaking: CoinModuleImpl<Cfg> = {
36
+ it('lists the capabilities a module implements, sorted', async () => {
37
+ const withReads: CoinModuleImpl<Cfg> = {
55
38
  ...minimalModule,
56
39
  getStakes: (_ctx: Ctx, _addr: string) => Promise.resolve({ items: [] }),
40
+ getBlockInfo: (_ctx: Ctx, _height: number): Promise<BlockInfo> =>
41
+ Promise.reject(new Error('stub')),
42
+ }
43
+ await expect(capabilityReport(withReads, ctx)).resolves.toEqual({
44
+ supported: ['getBlockInfo', 'getStakes'],
45
+ inconsistent: [],
46
+ })
47
+ })
48
+
49
+ // `getAccountInfo` answers a sentinel rather than an error (ADR-045), so it is no capability
50
+ // in the sense of this report, implemented or not.
51
+ it('leaves getAccountInfo out', async () => {
52
+ const withAccountInfo: CoinModuleImpl<Cfg> = {
53
+ ...minimalModule,
54
+ getAccountInfo: (_ctx: Ctx, _addr: string) => Promise.resolve({ type: 'none' } as const),
57
55
  }
58
- const report = await capabilityReport(withStaking, ctx)
59
- expect(report.unsupported).not.toContain('getStakes')
60
- expect(report.unsupported).toContain('getRewards')
61
- expect(report.inconsistent).toEqual([])
56
+ const report = await capabilityReport(withAccountInfo, ctx)
57
+ expect(report.supported).not.toContain('getAccountInfo')
62
58
  })
63
59
 
64
60
  // A module built by spreading `notSupportedApi()` carries a stub for everything, where a
@@ -71,10 +67,10 @@ describe('capabilityReport', () => {
71
67
  getBalance: minimalModule.getBalance,
72
68
  getStakes: (_ctx: Ctx, _addr: string) => Promise.resolve({ items: [] }),
73
69
  }
74
- const report = await capabilityReport(spread, ctx)
75
- expect(report.unsupported).not.toContain('getStakes')
76
- expect(report.unsupported).toContain('getValidators')
77
- expect(report.inconsistent).toEqual([])
70
+ await expect(capabilityReport(spread, ctx)).resolves.toEqual({
71
+ supported: ['getStakes'],
72
+ inconsistent: [],
73
+ })
78
74
  })
79
75
 
80
76
  it('never invokes an implemented capability', async () => {
@@ -83,27 +79,29 @@ describe('capabilityReport', () => {
83
79
  expect(network).not.toHaveBeenCalled()
84
80
  })
85
81
 
86
- it('counts a stub that rejects asynchronously as raising the error', async () => {
82
+ it('counts a hand-written stub as implemented', async () => {
87
83
  const asyncStub = {
88
84
  ...minimalModule,
89
85
  getRewards: (_ctx: Ctx, _addr: string) =>
90
86
  Promise.reject(new Error('getRewards is not supported')),
91
87
  }
92
- const report = await capabilityReport(asyncStub, ctx)
93
- // The module fills the slot, so `supports()` calls it implemented and the report skips it —
94
- // the tagged-stub check is what tells a placeholder apart, and an inline throw cannot be
95
- // told apart from an implementation.
96
- expect(report.unsupported).not.toContain('getRewards')
97
- expect(report.inconsistent).toEqual([])
88
+ // The module fills the slot, so `supports()` calls it implemented — the tagged-stub check is
89
+ // what tells a placeholder apart, and an inline throw cannot be told apart from an
90
+ // implementation.
91
+ await expect(capabilityReport(asyncStub, ctx)).resolves.toEqual({
92
+ supported: ['getRewards'],
93
+ inconsistent: [],
94
+ })
98
95
  })
99
96
 
100
97
  it('re-labels a tagged stub whose error names another method', async () => {
101
98
  const mislabelled = { ...minimalModule, getValidators: notSupported('getStakes') }
102
- const report = await capabilityReport(mislabelled, ctx)
103
99
  // A tagged stub counts as omitted, so `withDefaults` replaces it with its own — which names
104
100
  // the method it stands for. The mislabelling `coin-canton` shipped cannot survive the
105
101
  // resolver, and `inconsistent` stays empty: it only fills if a backfill goes missing.
106
- expect(report.unsupported).toContain('getValidators')
107
- expect(report.inconsistent).toEqual([])
102
+ await expect(capabilityReport(mislabelled, ctx)).resolves.toEqual({
103
+ supported: [],
104
+ inconsistent: [],
105
+ })
108
106
  })
109
107
  })
@@ -12,28 +12,34 @@ const isMethod = (value: unknown): value is (...args: unknown[]) => unknown =>
12
12
  typeof value === 'function'
13
13
 
14
14
  /**
15
- * What a module reports about the capabilities it does not implement, as a consumer sees it
16
- * through `withDefaults`. Meant to be asserted whole:
15
+ * What a module reports about its optional capabilities, as a consumer sees it through
16
+ * `withDefaults`. Meant to be asserted whole:
17
17
  *
18
18
  * ```ts
19
19
  * await expect(capabilityReport(createApi(), context)).resolves.toEqual({
20
- * unsupported: ['call', 'craftRawTransaction', 'getRewards', 'getValidators', 'register'],
20
+ * supported: ['getBlock', 'getBlockInfo', 'getStakes', 'validateAddress', 'validateIntent'],
21
21
  * inconsistent: [],
22
22
  * })
23
23
  * ```
24
24
  *
25
- * One expectation then covers what a module's api test used to spell out method by method:
26
- * that each capability is absent, that reaching it raises `"<name> is not supported"`, and
27
- * that `supports()` agrees. `toEqual` makes it exhaustive — a capability dropped or newly
28
- * implemented changes the list, so the test notices instead of silently still passing.
25
+ * `supported` lists what the module implements, so it changes only when the module does: a
26
+ * capability dropped or newly implemented changes the list, and the test notices instead of
27
+ * silently still passing. A capability the framework adds is not implemented by an existing
28
+ * module, so it leaves the list alone: a framework release that adds a capability does not break
29
+ * the modules' tests.
30
+ *
31
+ * Every other capability is reached, and must raise `"<name> is not supported"`; one that does
32
+ * not lands in `inconsistent`. An empty `inconsistent` therefore covers what a module's api test
33
+ * used to spell out method by method: that each absent capability raises its error, and that
34
+ * `supports()` agrees.
29
35
  *
30
36
  * It reads a module written either way: a `CoinModuleImpl` that omits its capabilities, or a
31
37
  * value built by spreading `notSupportedApi()`. Both are "not implemented" as far as
32
38
  * `supports()` is concerned, which is what this observes.
33
39
  */
34
40
  export type CapabilityReport = {
35
- /** Capabilities the module does not implement, sorted, each verified to raise its error. */
36
- unsupported: OptionalApiKey[]
41
+ /** Capabilities the module implements, sorted: those `supports()` reports present. */
42
+ supported: OptionalApiKey[]
37
43
  /**
38
44
  * Capabilities `supports()` calls absent but which did not raise `"<name> is not
39
45
  * supported"` when reached — a missing backfill, or an error naming another method.
@@ -64,11 +70,15 @@ export async function capabilityReport<
64
70
  } = withDefaults(impl)
65
71
  const asRecord: Record<string, unknown> = resolved
66
72
 
67
- const unsupported: OptionalApiKey[] = []
73
+ const supported: OptionalApiKey[] = []
68
74
  const inconsistent: OptionalApiKey[] = []
69
75
 
70
76
  for (const name of optionalApiKeys) {
71
- if (name === 'getAccountInfo' || resolved.supports(name)) continue
77
+ if (name === 'getAccountInfo') continue
78
+ if (resolved.supports(name)) {
79
+ supported.push(name)
80
+ continue
81
+ }
72
82
 
73
83
  const method = asRecord[name]
74
84
  if (!isMethod(method)) {
@@ -85,9 +95,11 @@ export async function capabilityReport<
85
95
  (error: unknown) => (error instanceof Error ? error.message : String(error))
86
96
  )
87
97
 
88
- if (raised === `${name} is not supported`) unsupported.push(name)
89
- else inconsistent.push(name)
98
+ if (raised !== `${name} is not supported`) inconsistent.push(name)
90
99
  }
91
100
 
92
- return { unsupported: unsupported.sort(), inconsistent: inconsistent.sort() }
101
+ return {
102
+ supported: supported.sort(),
103
+ inconsistent: inconsistent.sort(),
104
+ }
93
105
  }