@ledgerhq/coin-module-framework 8.1.0 → 8.2.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 (108) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/lib/api/impl.d.ts +74 -0
  3. package/lib/api/impl.d.ts.map +1 -0
  4. package/lib/api/impl.js +60 -0
  5. package/lib/api/impl.js.map +1 -0
  6. package/lib/api/index.d.ts +4 -0
  7. package/lib/api/index.d.ts.map +1 -1
  8. package/lib/api/index.js +4 -0
  9. package/lib/api/index.js.map +1 -1
  10. package/lib/api/notSupported.d.ts +14 -0
  11. package/lib/api/notSupported.d.ts.map +1 -1
  12. package/lib/api/notSupported.js +31 -2
  13. package/lib/api/notSupported.js.map +1 -1
  14. package/lib/api/notSupportedApi.d.ts +37 -0
  15. package/lib/api/notSupportedApi.d.ts.map +1 -0
  16. package/lib/api/notSupportedApi.js +68 -0
  17. package/lib/api/notSupportedApi.js.map +1 -0
  18. package/lib/api/withDefaults.d.ts +31 -0
  19. package/lib/api/withDefaults.d.ts.map +1 -0
  20. package/lib/api/withDefaults.js +57 -0
  21. package/lib/api/withDefaults.js.map +1 -0
  22. package/lib/api/wrappers/index.d.ts +17 -0
  23. package/lib/api/wrappers/index.d.ts.map +1 -0
  24. package/lib/api/wrappers/index.js +35 -0
  25. package/lib/api/wrappers/index.js.map +1 -0
  26. package/lib/api/wrappers/instrumenter.d.ts +27 -0
  27. package/lib/api/wrappers/instrumenter.d.ts.map +1 -0
  28. package/lib/api/wrappers/instrumenter.js +46 -0
  29. package/lib/api/wrappers/instrumenter.js.map +1 -0
  30. package/lib/api/wrappers/withLogging.d.ts +11 -0
  31. package/lib/api/wrappers/withLogging.d.ts.map +1 -0
  32. package/lib/api/wrappers/withLogging.js +40 -0
  33. package/lib/api/wrappers/withLogging.js.map +1 -0
  34. package/lib/api/wrappers/withTracing.d.ts +18 -0
  35. package/lib/api/wrappers/withTracing.d.ts.map +1 -0
  36. package/lib/api/wrappers/withTracing.js +40 -0
  37. package/lib/api/wrappers/withTracing.js.map +1 -0
  38. package/lib/test-utils/capabilities.d.ts +44 -0
  39. package/lib/test-utils/capabilities.d.ts.map +1 -0
  40. package/lib/test-utils/capabilities.js +44 -0
  41. package/lib/test-utils/capabilities.js.map +1 -0
  42. package/lib/test-utils/helpers.d.ts +1 -1
  43. package/lib/test-utils/helpers.d.ts.map +1 -1
  44. package/lib/test-utils/helpers.js +15 -0
  45. package/lib/test-utils/helpers.js.map +1 -1
  46. package/lib-es/api/impl.d.ts +74 -0
  47. package/lib-es/api/impl.d.ts.map +1 -0
  48. package/lib-es/api/impl.js +57 -0
  49. package/lib-es/api/impl.js.map +1 -0
  50. package/lib-es/api/index.d.ts +4 -0
  51. package/lib-es/api/index.d.ts.map +1 -1
  52. package/lib-es/api/index.js +4 -0
  53. package/lib-es/api/index.js.map +1 -1
  54. package/lib-es/api/notSupported.d.ts +14 -0
  55. package/lib-es/api/notSupported.d.ts.map +1 -1
  56. package/lib-es/api/notSupported.js +30 -2
  57. package/lib-es/api/notSupported.js.map +1 -1
  58. package/lib-es/api/notSupportedApi.d.ts +37 -0
  59. package/lib-es/api/notSupportedApi.d.ts.map +1 -0
  60. package/lib-es/api/notSupportedApi.js +65 -0
  61. package/lib-es/api/notSupportedApi.js.map +1 -0
  62. package/lib-es/api/withDefaults.d.ts +31 -0
  63. package/lib-es/api/withDefaults.d.ts.map +1 -0
  64. package/lib-es/api/withDefaults.js +54 -0
  65. package/lib-es/api/withDefaults.js.map +1 -0
  66. package/lib-es/api/wrappers/index.d.ts +17 -0
  67. package/lib-es/api/wrappers/index.d.ts.map +1 -0
  68. package/lib-es/api/wrappers/index.js +19 -0
  69. package/lib-es/api/wrappers/index.js.map +1 -0
  70. package/lib-es/api/wrappers/instrumenter.d.ts +27 -0
  71. package/lib-es/api/wrappers/instrumenter.d.ts.map +1 -0
  72. package/lib-es/api/wrappers/instrumenter.js +43 -0
  73. package/lib-es/api/wrappers/instrumenter.js.map +1 -0
  74. package/lib-es/api/wrappers/withLogging.d.ts +11 -0
  75. package/lib-es/api/wrappers/withLogging.d.ts.map +1 -0
  76. package/lib-es/api/wrappers/withLogging.js +37 -0
  77. package/lib-es/api/wrappers/withLogging.js.map +1 -0
  78. package/lib-es/api/wrappers/withTracing.d.ts +18 -0
  79. package/lib-es/api/wrappers/withTracing.d.ts.map +1 -0
  80. package/lib-es/api/wrappers/withTracing.js +37 -0
  81. package/lib-es/api/wrappers/withTracing.js.map +1 -0
  82. package/lib-es/test-utils/capabilities.d.ts +44 -0
  83. package/lib-es/test-utils/capabilities.d.ts.map +1 -0
  84. package/lib-es/test-utils/capabilities.js +41 -0
  85. package/lib-es/test-utils/capabilities.js.map +1 -0
  86. package/lib-es/test-utils/helpers.d.ts +1 -1
  87. package/lib-es/test-utils/helpers.d.ts.map +1 -1
  88. package/lib-es/test-utils/helpers.js +1 -0
  89. package/lib-es/test-utils/helpers.js.map +1 -1
  90. package/package.json +1 -1
  91. package/src/api/impl.test.ts +83 -0
  92. package/src/api/impl.ts +112 -0
  93. package/src/api/index.ts +4 -0
  94. package/src/api/notSupported.ts +32 -2
  95. package/src/api/notSupportedApi.test.ts +67 -0
  96. package/src/api/notSupportedApi.ts +74 -0
  97. package/src/api/withDefaults.test.ts +190 -0
  98. package/src/api/withDefaults.ts +87 -0
  99. package/src/api/wrappers/index.ts +20 -0
  100. package/src/api/wrappers/instrumenter.test.ts +123 -0
  101. package/src/api/wrappers/instrumenter.ts +58 -0
  102. package/src/api/wrappers/withLogging.test.ts +137 -0
  103. package/src/api/wrappers/withLogging.ts +47 -0
  104. package/src/api/wrappers/withTracing.test.ts +125 -0
  105. package/src/api/wrappers/withTracing.ts +56 -0
  106. package/src/test-utils/capabilities.test.ts +108 -0
  107. package/src/test-utils/capabilities.ts +93 -0
  108. package/src/test-utils/helpers.ts +2 -0
@@ -0,0 +1,87 @@
1
+ // SPDX-FileCopyrightText: © 2024 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { CurrencyConfig } from '../config'
5
+ import type { CoinModuleImpl, OptionalApiKey } from './impl'
6
+ import type { CoinModuleApi, Memo, MemoNotSupported, TxData, TxDataNotSupported } from './types'
7
+ import { optionalApiKeys } from './impl'
8
+ import { isNotSupportedStub, notSupported } from './notSupported'
9
+
10
+ /**
11
+ * What {@link withDefaults} returns: the full consumer contract, plus `supports()`.
12
+ *
13
+ * `getAccountInfo` is narrowed to required. It is the one managed capability that
14
+ * {@link CoinModuleApi} itself declares optional, and `withDefaults` always supplies it — so
15
+ * callers can invoke it without a non-null assertion, and read `type` to tell a real answer from
16
+ * the `{ type: 'none' }` sentinel.
17
+ */
18
+ export type WithDefaultsResult<
19
+ ConfigType extends CurrencyConfig,
20
+ MemoType extends Memo = MemoNotSupported,
21
+ TxDataType extends TxData = TxDataNotSupported,
22
+ > = CoinModuleApi<ConfigType, MemoType, TxDataType> &
23
+ Required<Pick<CoinModuleApi<ConfigType, MemoType, TxDataType>, 'getAccountInfo'>> & {
24
+ supports: (method: OptionalApiKey) => boolean
25
+ }
26
+
27
+ /**
28
+ * Normalizes an authored capability method to "present" or "absent".
29
+ *
30
+ * A `notSupported()` stub counts as absent: it is a placeholder, not an implementation,
31
+ * so the framework's own default takes over. Behavior is unchanged either way (both throw
32
+ * the same `"<name> is not supported"`), but `supports()` then reports the truth.
33
+ */
34
+ function implemented<T>(value: T | undefined): T | undefined {
35
+ return value === undefined || isNotSupportedStub(value) ? undefined : value
36
+ }
37
+
38
+ /**
39
+ * Widens a {@link CoinModuleImpl} authoring value to the full {@link CoinModuleApi}
40
+ * consumer contract by backfilling the capability methods the author omitted, and attaches
41
+ * a `supports()` introspection helper.
42
+ *
43
+ * Default per omitted method:
44
+ * - `getAccountInfo` → a `{ type: 'none' }` sentinel (ADR-045): having no extra account
45
+ * metadata is an answer, so callers get one instead of an exception.
46
+ * - every other capability → `notSupported(name)`, which throws `"<name> is not supported"`.
47
+ *
48
+ * Properties the authoring object carries beyond the API surface are preserved.
49
+ *
50
+ * A capability method is considered implemented only when the author supplied a real
51
+ * function — a `notSupported()` stub is treated as if the method had been omitted.
52
+ */
53
+ export function withDefaults<
54
+ ConfigType extends CurrencyConfig,
55
+ MemoType extends Memo = MemoNotSupported,
56
+ TxDataType extends TxData = TxDataNotSupported,
57
+ Extra extends object = Record<never, never>,
58
+ >(
59
+ impl: CoinModuleImpl<ConfigType, MemoType, TxDataType> & Extra
60
+ ): WithDefaultsResult<ConfigType, MemoType, TxDataType> & Extra {
61
+ const implementedMethods = new Set<OptionalApiKey>(
62
+ optionalApiKeys.filter((k) => implemented(impl[k]) !== undefined)
63
+ )
64
+
65
+ // Spread first so anything the module exposes beyond the API surface survives, then
66
+ // override every capability method with either the real implementation or the default.
67
+ return {
68
+ ...impl,
69
+ getBlock: implemented(impl.getBlock) ?? notSupported('getBlock'),
70
+ getBlockInfo: implemented(impl.getBlockInfo) ?? notSupported('getBlockInfo'),
71
+ getStakes: implemented(impl.getStakes) ?? notSupported('getStakes'),
72
+ getRewards: implemented(impl.getRewards) ?? notSupported('getRewards'),
73
+ getValidators: implemented(impl.getValidators) ?? notSupported('getValidators'),
74
+ call: implemented(impl.call) ?? notSupported('call'),
75
+ craftRawTransaction:
76
+ implemented(impl.craftRawTransaction) ?? notSupported('craftRawTransaction'),
77
+ register: implemented(impl.register) ?? notSupported('register'),
78
+ getNextSequence: implemented(impl.getNextSequence) ?? notSupported('getNextSequence'),
79
+ validateIntent: implemented(impl.validateIntent) ?? notSupported('validateIntent'),
80
+ validateAddress: implemented(impl.validateAddress) ?? notSupported('validateAddress'),
81
+ // ADR-045: an absent getAccountInfo means the chain has no extra account metadata to
82
+ // report, which is an answer rather than a missing capability — hence a sentinel instead
83
+ // of a throwing stub. Callers read `type` and branch on it.
84
+ getAccountInfo: implemented(impl.getAccountInfo) ?? (() => Promise.resolve({ type: 'none' })),
85
+ supports: (method: OptionalApiKey): boolean => implementedMethods.has(method),
86
+ }
87
+ }
@@ -0,0 +1,20 @@
1
+ // SPDX-FileCopyrightText: © 2024 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Composable cross-cutting wrappers over a {@link CoinModuleApi}.
6
+ *
7
+ * Each takes a full API and returns one with identical generics, so they compose in any
8
+ * order and none of them belongs to the core contract: a consumer that wants no
9
+ * instrumentation never reaches this folder.
10
+ *
11
+ * That signature is the line between this folder and the core. `withDefaults` shares the
12
+ * `with*` name but stays in the core because it *changes* the type — it widens an authoring
13
+ * `CoinModuleImpl` into the `CoinModuleApi` consumers require, which is the adapter the
14
+ * authoring type exists for and not an optional concern. Anything that preserves the
15
+ * contract it receives belongs here; anything that produces it belongs in the core.
16
+ */
17
+
18
+ export * from './instrumenter'
19
+ export * from './withLogging'
20
+ export * from './withTracing'
@@ -0,0 +1,123 @@
1
+ // SPDX-FileCopyrightText: © 2024 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { CurrencyConfig, Context } from '../../config'
5
+ import type { CoinModuleImpl } from '../impl'
6
+ import type { BlockInfo, ListOperationsOptions, TransactionIntent } from '../types'
7
+ import { apiMethodKeys } from '../impl'
8
+ import { withDefaults } from '../withDefaults'
9
+ import { instrumentApi } from './instrumenter'
10
+
11
+ type Cfg = CurrencyConfig
12
+ type Ctx = Context<Cfg>
13
+
14
+ const minimalModule: CoinModuleImpl<Cfg> = {
15
+ lastBlock: (_ctx: Ctx): Promise<BlockInfo> => Promise.reject(new Error('stub')),
16
+ getBalance: (_ctx: Ctx, _addr: string) => Promise.resolve([]),
17
+ listOperations: (_ctx: Ctx, _addr: string, _opts: ListOperationsOptions) =>
18
+ Promise.resolve({ items: [] }),
19
+ craftTransaction: (_ctx: Ctx, _intent: TransactionIntent) => Promise.reject(new Error('stub')),
20
+ estimateFees: (_ctx: Ctx, _intent: TransactionIntent) => Promise.reject(new Error('stub')),
21
+ combine: (_ctx: Ctx, tx: string, _sig: string[]): string => tx,
22
+ broadcast: (_ctx: Ctx, _tx: string) => Promise.reject(new Error('stub')),
23
+ craftTransactionData: (_ctx: Ctx, _intent: TransactionIntent) => ({ type: 'none' }) as const,
24
+ }
25
+
26
+ const passthrough = (
27
+ _name: string,
28
+ fn: (...args: unknown[]) => unknown,
29
+ args: unknown[]
30
+ ): unknown => fn(...args)
31
+
32
+ const ctx: Ctx = { config: () => Promise.reject(new Error('stub')), logger: () => undefined }
33
+
34
+ const isMethod = (value: unknown): value is (...args: unknown[]) => unknown =>
35
+ typeof value === 'function'
36
+
37
+ const plainHelper = (): string => 'plain-call'
38
+
39
+ describe('instrumentApi', () => {
40
+ it('returns a referentially stable wrapper for repeated reads of a method', () => {
41
+ const api = instrumentApi(withDefaults(minimalModule), passthrough)
42
+ // A consumer using a method as a dependency key (React effect, memo cache) must not
43
+ // see a new function on every property access.
44
+ expect(api.getBalance).toBe(api.getBalance)
45
+ expect(api.combine).toBe(api.combine)
46
+ })
47
+
48
+ it('gives each method its own wrapper', () => {
49
+ const api = instrumentApi(withDefaults(minimalModule), passthrough)
50
+ expect(api.getBalance).not.toBe(api.combine)
51
+ })
52
+
53
+ it('instruments every method the contract declares', () => {
54
+ // The guarantee the previous Proxy got for free from intercepting any function: nothing
55
+ // the contract declares escapes instrumentation. Now that the wrapped set is an explicit
56
+ // list, this is what holds it to the contract — together with the compile-time
57
+ // exhaustiveness guard on `apiMethodKeys` itself.
58
+ const seen: string[] = []
59
+ // Records the call without invoking the underlying method, so the "not supported"
60
+ // stubs can be reached without throwing.
61
+ const api: Record<string, unknown> = instrumentApi(withDefaults(minimalModule), (name) => {
62
+ seen.push(name)
63
+ return undefined
64
+ })
65
+
66
+ const present = apiMethodKeys.filter((name) => isMethod(api[name]))
67
+ for (const name of present) {
68
+ const method = api[name]
69
+ if (isMethod(method)) method(ctx)
70
+ }
71
+
72
+ expect(seen).toEqual([...present])
73
+ // `listFeeOptions` is the one contract method withDefaults leaves absent; everything
74
+ // else must be there.
75
+ expect(apiMethodKeys.filter((name) => !present.includes(name))).toEqual(['listFeeOptions'])
76
+ })
77
+
78
+ it('routes each call through the instrument function', () => {
79
+ const seen: string[] = []
80
+ const api = instrumentApi(withDefaults(minimalModule), (name, fn, args) => {
81
+ seen.push(name)
82
+ return fn(...args)
83
+ })
84
+ expect(api.combine(ctx, 'tx', [])).toBe('tx')
85
+ expect(seen).toEqual(['combine'])
86
+ })
87
+
88
+ it('forwards non-function properties untouched', () => {
89
+ const api = instrumentApi(
90
+ { ...withDefaults(minimalModule), marker: 'plain-value' },
91
+ passthrough
92
+ )
93
+ expect(api.marker).toBe('plain-value')
94
+ })
95
+
96
+ it('leaves members outside the contract uninstrumented', () => {
97
+ // Ledger Live resolves a `CoinModuleApi & BridgeApi`: the non-API half must survive, and
98
+ // instrumenting it would be a wrapper reaching outside the contract it wraps.
99
+ const seen: string[] = []
100
+ const api = instrumentApi({ ...withDefaults(minimalModule), helper: plainHelper }, (name) => {
101
+ seen.push(name)
102
+ return undefined
103
+ })
104
+ expect(api.helper).toBe(plainHelper)
105
+ expect(api.helper()).toBe('plain-call')
106
+ expect(api.supports('getStakes')).toBe(false)
107
+ expect(seen).toEqual([])
108
+ })
109
+
110
+ it('preserves the receiver, so a method reading `this` still works', () => {
111
+ // Each method is bound once at wrap time rather than on every call. A module written
112
+ // with shorthand methods that reach a sibling through `this` depends on that binding.
113
+ const selfReferential = {
114
+ ...withDefaults(minimalModule),
115
+ suffix: '-signed',
116
+ combine(_ctx: Ctx, tx: string, _sig: string[]): string {
117
+ return tx + this.suffix
118
+ },
119
+ }
120
+ const api = instrumentApi(selfReferential, passthrough)
121
+ expect(api.combine(ctx, 'tx', [])).toBe('tx-signed')
122
+ })
123
+ })
@@ -0,0 +1,58 @@
1
+ // SPDX-FileCopyrightText: © 2024 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { CurrencyConfig } from '../../config'
5
+ import type { CoinModuleApi, Memo, TxData } from '../types'
6
+ import { apiMethodKeys } from '../impl'
7
+
8
+ /** Narrows a copied member to a callable without asserting its type. */
9
+ const isMethod = (value: unknown): value is (...args: unknown[]) => unknown =>
10
+ typeof value === 'function'
11
+
12
+ /**
13
+ * Returns a copy of a {@link CoinModuleApi} whose contract methods route through the
14
+ * provided `instrument` function. Everything else the object carries — non-API members
15
+ * such as the legacy bridge surface, or `supports` — is copied over untouched.
16
+ *
17
+ * Exported so other wrappers (withLogging, withTracing, withMetrics, …) can reuse the
18
+ * same interception mechanism without duplicating the boilerplate.
19
+ *
20
+ * The wrapped set is {@link apiMethodKeys}, the contract's own method list, rather than
21
+ * "every property that happens to be a function": what gets instrumented is then readable
22
+ * from the source, and a method added to the contract cannot be silently skipped — the
23
+ * exhaustiveness guard next to that list fails to compile first.
24
+ *
25
+ * Each method is wrapped and bound once, eagerly, so repeated reads are referentially
26
+ * stable (`api.getBalance === api.getBalance`) — a consumer using a method as a dependency
27
+ * key, a React effect or a memo cache, would otherwise see a new function every time — and
28
+ * no allocation happens on the call path.
29
+ *
30
+ * Expects a plain object, which is what a `createApi()` result and a `withDefaults` result
31
+ * both are. Methods living on a prototype rather than on the object itself are copied by
32
+ * value here, so a class instance that reassigns its own methods after wrapping would not
33
+ * see the change.
34
+ */
35
+ export function instrumentApi<
36
+ C extends CurrencyConfig,
37
+ M extends Memo,
38
+ T extends TxData,
39
+ Extra extends object = Record<never, never>,
40
+ >(
41
+ api: CoinModuleApi<C, M, T> & Extra,
42
+ instrument: (name: string, fn: (...args: unknown[]) => unknown, args: unknown[]) => unknown
43
+ ): CoinModuleApi<C, M, T> & Extra {
44
+ const instrumented: Record<string, unknown> = { ...api }
45
+
46
+ for (const name of apiMethodKeys) {
47
+ const method = instrumented[name]
48
+ // A contract method the object does not carry: `listFeeOptions`, which withDefaults
49
+ // leaves absent, or any method on a value that never went through withDefaults.
50
+ if (!isMethod(method)) continue
51
+
52
+ const bound = method.bind(api)
53
+ instrumented[name] = (...args: unknown[]): unknown => instrument(name, bound, args)
54
+ }
55
+
56
+ // oxlint-disable-next-line consistent-type-assertions -- every contract method was replaced by a wrapper of the same arity and the rest was copied verbatim, so the shape is unchanged; TS cannot follow that through an index-signature write
57
+ return instrumented as CoinModuleApi<C, M, T> & Extra
58
+ }
@@ -0,0 +1,137 @@
1
+ // SPDX-FileCopyrightText: © 2024 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { CurrencyConfig, Context } from '../../config'
5
+ import type { CoinModuleImpl } from '../impl'
6
+ import type { BlockInfo, ListOperationsOptions, TransactionIntent } from '../types'
7
+ import { withDefaults } from '../withDefaults'
8
+ import { withLogging } from './withLogging'
9
+
10
+ type Cfg = CurrencyConfig
11
+ type Ctx = Context<Cfg>
12
+
13
+ const block: BlockInfo = { height: 1, hash: '0xabc', time: new Date(0) }
14
+
15
+ const ctx: Ctx = {
16
+ config: () => Promise.reject(new Error('stub')),
17
+ logger: () => undefined,
18
+ }
19
+
20
+ const minimalModule: CoinModuleImpl<Cfg> = {
21
+ lastBlock: (_ctx: Ctx): Promise<BlockInfo> => Promise.reject(new Error('stub')),
22
+ getBalance: (_ctx: Ctx, _addr: string) => Promise.resolve([]),
23
+ listOperations: (_ctx: Ctx, _addr: string, _opts: ListOperationsOptions) =>
24
+ Promise.resolve({ items: [] }),
25
+ craftTransaction: (_ctx: Ctx, _intent: TransactionIntent) => Promise.reject(new Error('stub')),
26
+ estimateFees: (_ctx: Ctx, _intent: TransactionIntent) => Promise.reject(new Error('stub')),
27
+ combine: (_ctx: Ctx, tx: string, _sig: string[]): string => tx,
28
+ broadcast: (_ctx: Ctx, _tx: string) => Promise.reject(new Error('stub')),
29
+ craftTransactionData: (_ctx: Ctx, _intent: TransactionIntent) => ({ type: 'none' }) as const,
30
+ }
31
+
32
+ describe('withLogging', () => {
33
+ it('logs call and ok on a successful async method', async () => {
34
+ const logger = jest.fn()
35
+ const logCtx: Ctx = { ...ctx, logger }
36
+ const impl: CoinModuleImpl<Cfg> = {
37
+ ...minimalModule,
38
+ lastBlock: (_c: Ctx) => Promise.resolve(block),
39
+ }
40
+ const logged = withLogging(withDefaults(impl))
41
+ await logged.lastBlock(logCtx)
42
+ expect(logger).toHaveBeenNthCalledWith(1, '[coin-module] lastBlock: call')
43
+ expect(logger).toHaveBeenNthCalledWith(2, '[coin-module] lastBlock: ok')
44
+ })
45
+
46
+ it('logs call and error on a rejected async method and re-throws', async () => {
47
+ const logger = jest.fn()
48
+ const logCtx: Ctx = { ...ctx, logger }
49
+ const error = new Error('net-fail')
50
+ const impl: CoinModuleImpl<Cfg> = {
51
+ ...minimalModule,
52
+ lastBlock: (_c: Ctx) => Promise.reject(error),
53
+ }
54
+ const logged = withLogging(withDefaults(impl))
55
+ await expect(logged.lastBlock(logCtx)).rejects.toThrow(error)
56
+ expect(logger).toHaveBeenNthCalledWith(1, '[coin-module] lastBlock: call')
57
+ expect(logger).toHaveBeenNthCalledWith(2, '[coin-module] lastBlock: error', error)
58
+ })
59
+
60
+ it('logs call and ok on a synchronous method', () => {
61
+ const logger = jest.fn()
62
+ const logCtx: Ctx = { ...ctx, logger }
63
+ const logged = withLogging(withDefaults(minimalModule))
64
+ const result = logged.combine(logCtx, 'tx', [])
65
+ expect(result).toBe('tx')
66
+ expect(logger).toHaveBeenNthCalledWith(1, '[coin-module] combine: call')
67
+ expect(logger).toHaveBeenNthCalledWith(2, '[coin-module] combine: ok')
68
+ })
69
+
70
+ it('logs call and error on a synchronous throw and re-throws', () => {
71
+ const logger = jest.fn()
72
+ const logCtx: Ctx = { ...ctx, logger }
73
+ const error = new Error('sync-fail')
74
+ const impl: CoinModuleImpl<Cfg> = {
75
+ ...minimalModule,
76
+ combine: (_c: Ctx, _tx: string, _sig: string[]): string => {
77
+ throw error
78
+ },
79
+ }
80
+ const logged = withLogging(withDefaults(impl))
81
+ expect(() => logged.combine(logCtx, 'tx', [])).toThrow(error)
82
+ expect(logger).toHaveBeenNthCalledWith(1, '[coin-module] combine: call')
83
+ expect(logger).toHaveBeenNthCalledWith(2, '[coin-module] combine: error', error)
84
+ })
85
+
86
+ it('forwards the context object unchanged to the underlying method', async () => {
87
+ let capturedCtx: unknown
88
+ const logger = jest.fn()
89
+ const logCtx: Ctx = { ...ctx, logger }
90
+ const impl: CoinModuleImpl<Cfg> = {
91
+ ...minimalModule,
92
+ lastBlock: (c: Ctx) => {
93
+ capturedCtx = c
94
+ return Promise.resolve(block)
95
+ },
96
+ }
97
+ const logged = withLogging(withDefaults(impl))
98
+ await logged.lastBlock(logCtx)
99
+ expect(capturedCtx).toBe(logCtx)
100
+ })
101
+
102
+ it('applies logging twice when composed withLogging(withLogging(api))', async () => {
103
+ const logger = jest.fn()
104
+ const logCtx: Ctx = { ...ctx, logger }
105
+ const impl: CoinModuleImpl<Cfg> = {
106
+ ...minimalModule,
107
+ lastBlock: (_c: Ctx) => Promise.resolve(block),
108
+ }
109
+ const doubly = withLogging(withLogging(withDefaults(impl)))
110
+ await doubly.lastBlock(logCtx)
111
+ // Each layer emits call + ok: 4 total calls
112
+ expect(logger).toHaveBeenCalledTimes(4)
113
+ expect(logger.mock.calls[0][0]).toBe('[coin-module] lastBlock: call')
114
+ expect(logger.mock.calls[3][0]).toBe('[coin-module] lastBlock: ok')
115
+ })
116
+
117
+ // The consumer-side shape this whole chain exists for: Ledger Live's resolve point hands out
118
+ // `CoinModuleApi & BridgeApi`, so the members that are not part of the API must survive
119
+ // withDefaults + withLogging — at runtime AND in the type. `bridgeOnly` below is only reachable
120
+ // if both wrappers preserve the extra half, so this test doubles as a type-level guard: an
121
+ // erasing signature makes it a compile error, not a silent behavior change.
122
+ it('preserves non-API members through withDefaults + withLogging (consumer intersection)', async () => {
123
+ const logger = jest.fn()
124
+ const logCtx: Ctx = { ...ctx, logger }
125
+ const impl = {
126
+ ...minimalModule,
127
+ lastBlock: (_c: Ctx) => Promise.resolve(block),
128
+ bridgeOnly: (label: string): string => `bridge:${label}`,
129
+ }
130
+
131
+ const wired = withLogging(withDefaults(impl))
132
+
133
+ expect(wired.bridgeOnly('x')).toBe('bridge:x')
134
+ await wired.lastBlock(logCtx)
135
+ expect(logger).toHaveBeenNthCalledWith(1, '[coin-module] lastBlock: call')
136
+ })
137
+ })
@@ -0,0 +1,47 @@
1
+ // SPDX-FileCopyrightText: © 2024 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { Context, CurrencyConfig } from '../../config'
5
+ import type { CoinModuleApi, Memo, MemoNotSupported, TxData, TxDataNotSupported } from '../types'
6
+ import { instrumentApi } from './instrumenter'
7
+
8
+ /**
9
+ * Wraps a {@link CoinModuleApi} to emit log entries via the per-call {@link Context}'s
10
+ * logger before and after each method invocation, including on error.
11
+ *
12
+ * The Context is forwarded unchanged to the underlying method.
13
+ * Handles both synchronous methods (e.g. `combine`) and async methods uniformly.
14
+ */
15
+ export function withLogging<
16
+ C extends CurrencyConfig,
17
+ M extends Memo = MemoNotSupported,
18
+ T extends TxData = TxDataNotSupported,
19
+ Extra extends object = Record<never, never>,
20
+ >(api: CoinModuleApi<C, M, T> & Extra): CoinModuleApi<C, M, T> & Extra {
21
+ return instrumentApi(api, (name, fn, args) => {
22
+ // oxlint-disable-next-line consistent-type-assertions -- args[0] is always Context<C> per CoinModuleApi contract; unknown cast needed to access logger
23
+ const logger = (args[0] as Context<C> | undefined)?.logger
24
+ logger?.(`[coin-module] ${name}: call`)
25
+ let result: unknown
26
+ try {
27
+ result = fn(...args)
28
+ } catch (e) {
29
+ logger?.(`[coin-module] ${name}: error`, e)
30
+ throw e
31
+ }
32
+ if (result instanceof Promise) {
33
+ return result.then(
34
+ (v) => {
35
+ logger?.(`[coin-module] ${name}: ok`)
36
+ return v
37
+ },
38
+ (e) => {
39
+ logger?.(`[coin-module] ${name}: error`, e)
40
+ throw e
41
+ }
42
+ )
43
+ }
44
+ logger?.(`[coin-module] ${name}: ok`)
45
+ return result
46
+ })
47
+ }
@@ -0,0 +1,125 @@
1
+ // SPDX-FileCopyrightText: © 2024 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { CurrencyConfig, Context } from '../../config'
5
+ import type { CoinModuleImpl } from '../impl'
6
+ import type { BlockInfo, ListOperationsOptions, TransactionIntent } from '../types'
7
+ import type { Tracer, Span } from './withTracing'
8
+ import { withDefaults } from '../withDefaults'
9
+ import { withLogging } from './withLogging'
10
+ import { withTracing } from './withTracing'
11
+
12
+ type Cfg = CurrencyConfig
13
+ type Ctx = Context<Cfg>
14
+
15
+ const block: BlockInfo = { height: 1, hash: '0xabc', time: new Date(0) }
16
+
17
+ const ctx: Ctx = {
18
+ config: () => Promise.reject(new Error('stub')),
19
+ logger: () => undefined,
20
+ }
21
+
22
+ const minimalModule: CoinModuleImpl<Cfg> = {
23
+ lastBlock: (_ctx: Ctx): Promise<BlockInfo> => Promise.reject(new Error('stub')),
24
+ getBalance: (_ctx: Ctx, _addr: string) => Promise.resolve([]),
25
+ listOperations: (_ctx: Ctx, _addr: string, _opts: ListOperationsOptions) =>
26
+ Promise.resolve({ items: [] }),
27
+ craftTransaction: (_ctx: Ctx, _intent: TransactionIntent) => Promise.reject(new Error('stub')),
28
+ estimateFees: (_ctx: Ctx, _intent: TransactionIntent) => Promise.reject(new Error('stub')),
29
+ combine: (_ctx: Ctx, tx: string, _sig: string[]): string => tx,
30
+ broadcast: (_ctx: Ctx, _tx: string) => Promise.reject(new Error('stub')),
31
+ craftTransactionData: (_ctx: Ctx, _intent: TransactionIntent) => ({ type: 'none' }) as const,
32
+ }
33
+
34
+ function makeSpan(): { mock: Span; end: jest.Mock; setError: jest.Mock } {
35
+ const end = jest.fn()
36
+ const setError = jest.fn()
37
+ return { mock: { end, setError }, end, setError }
38
+ }
39
+
40
+ function makeTracer(span: Span): { mock: Tracer; startSpan: jest.Mock } {
41
+ const startSpan = jest.fn().mockReturnValue(span)
42
+ return { mock: { startSpan }, startSpan }
43
+ }
44
+
45
+ describe('withTracing', () => {
46
+ it('calls startSpan with the method name', async () => {
47
+ const { mock: span } = makeSpan()
48
+ const { mock: tracer, startSpan } = makeTracer(span)
49
+ const impl: CoinModuleImpl<Cfg> = {
50
+ ...minimalModule,
51
+ lastBlock: (_c: Ctx) => Promise.resolve(block),
52
+ }
53
+ await withTracing(withDefaults(impl), tracer).lastBlock(ctx)
54
+ expect(startSpan).toHaveBeenCalledWith('lastBlock')
55
+ })
56
+
57
+ it('calls span.end() after a successful async method', async () => {
58
+ const { mock: span, end } = makeSpan()
59
+ const { mock: tracer } = makeTracer(span)
60
+ const impl: CoinModuleImpl<Cfg> = {
61
+ ...minimalModule,
62
+ lastBlock: (_c: Ctx) => Promise.resolve(block),
63
+ }
64
+ await withTracing(withDefaults(impl), tracer).lastBlock(ctx)
65
+ expect(end).toHaveBeenCalledTimes(1)
66
+ })
67
+
68
+ it('calls span.setError and span.end then re-throws on a rejected async method', async () => {
69
+ const error = new Error('net-fail')
70
+ const { mock: span, end, setError } = makeSpan()
71
+ const { mock: tracer } = makeTracer(span)
72
+ const impl: CoinModuleImpl<Cfg> = {
73
+ ...minimalModule,
74
+ lastBlock: (_c: Ctx) => Promise.reject(error),
75
+ }
76
+ await expect(withTracing(withDefaults(impl), tracer).lastBlock(ctx)).rejects.toThrow(error)
77
+ expect(setError).toHaveBeenCalledWith(error)
78
+ expect(end).toHaveBeenCalledTimes(1)
79
+ })
80
+
81
+ it('calls span.end and returns result for a successful synchronous method', () => {
82
+ const { mock: span, end } = makeSpan()
83
+ const { mock: tracer } = makeTracer(span)
84
+ const result = withTracing(withDefaults(minimalModule), tracer).combine(ctx, 'tx', [])
85
+ expect(result).toBe('tx')
86
+ expect(end).toHaveBeenCalledTimes(1)
87
+ })
88
+
89
+ it('calls span.setError and span.end then re-throws on a synchronous throw', () => {
90
+ const error = new Error('sync-fail')
91
+ const { mock: span, end, setError } = makeSpan()
92
+ const { mock: tracer } = makeTracer(span)
93
+ const impl: CoinModuleImpl<Cfg> = {
94
+ ...minimalModule,
95
+ combine: (_c: Ctx, _tx: string, _sig: string[]): string => {
96
+ throw error
97
+ },
98
+ }
99
+ expect(() => withTracing(withDefaults(impl), tracer).combine(ctx, 'tx', [])).toThrow(error)
100
+ expect(setError).toHaveBeenCalledWith(error)
101
+ expect(end).toHaveBeenCalledTimes(1)
102
+ })
103
+
104
+ it('stacks logging and tracing when composed withLogging(withTracing(api, tracer))', async () => {
105
+ const logger = jest.fn()
106
+ const logCtx: Ctx = { ...ctx, logger }
107
+ const { mock: span, end } = makeSpan()
108
+ const { mock: tracer, startSpan } = makeTracer(span)
109
+ const impl: CoinModuleImpl<Cfg> = {
110
+ ...minimalModule,
111
+ lastBlock: (_c: Ctx) => Promise.resolve(block),
112
+ }
113
+ const composed = withLogging(withTracing(withDefaults(impl), tracer))
114
+ await composed.lastBlock(logCtx)
115
+ // Logging layer fired
116
+ expect(logger).toHaveBeenCalledWith('[coin-module] lastBlock: call')
117
+ expect(logger).toHaveBeenCalledWith('[coin-module] lastBlock: ok')
118
+ // Tracing layer fired
119
+ expect(startSpan).toHaveBeenCalledWith('lastBlock')
120
+ expect(end).toHaveBeenCalledTimes(1)
121
+ // The underlying method's return value is preserved through both layers
122
+ const result = await composed.lastBlock(logCtx)
123
+ expect(result).not.toBe(undefined)
124
+ })
125
+ })
@@ -0,0 +1,56 @@
1
+ // SPDX-FileCopyrightText: © 2024 LEDGER SAS
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type { CurrencyConfig } from '../../config'
5
+ import type { CoinModuleApi, Memo, MemoNotSupported, TxData, TxDataNotSupported } from '../types'
6
+ import { instrumentApi } from './instrumenter'
7
+
8
+ export interface Span {
9
+ end(): void
10
+ setError(error: unknown): void
11
+ }
12
+
13
+ export interface Tracer {
14
+ startSpan(name: string): Span
15
+ }
16
+
17
+ /**
18
+ * Wraps a {@link CoinModuleApi} to open a tracing span around each method invocation.
19
+ *
20
+ * The span is ended on success, or after `setError` on throw.
21
+ * The Context is forwarded unchanged to the underlying method.
22
+ * Handles both synchronous methods (e.g. `combine`) and async methods uniformly.
23
+ */
24
+ export function withTracing<
25
+ C extends CurrencyConfig,
26
+ M extends Memo = MemoNotSupported,
27
+ T extends TxData = TxDataNotSupported,
28
+ Extra extends object = Record<never, never>,
29
+ >(api: CoinModuleApi<C, M, T> & Extra, tracer: Tracer): CoinModuleApi<C, M, T> & Extra {
30
+ return instrumentApi(api, (name, fn, args) => {
31
+ const span = tracer.startSpan(name)
32
+ let result: unknown
33
+ try {
34
+ result = fn(...args)
35
+ } catch (e) {
36
+ span.setError(e)
37
+ span.end()
38
+ throw e
39
+ }
40
+ if (result instanceof Promise) {
41
+ return result.then(
42
+ (v) => {
43
+ span.end()
44
+ return v
45
+ },
46
+ (e) => {
47
+ span.setError(e)
48
+ span.end()
49
+ throw e
50
+ }
51
+ )
52
+ }
53
+ span.end()
54
+ return result
55
+ })
56
+ }