@ledgerhq/coin-module-framework 8.0.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 (113) hide show
  1. package/CHANGELOG.md +106 -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/types.d.ts +4 -0
  19. package/lib/api/types.d.ts.map +1 -1
  20. package/lib/api/withDefaults.d.ts +31 -0
  21. package/lib/api/withDefaults.d.ts.map +1 -0
  22. package/lib/api/withDefaults.js +57 -0
  23. package/lib/api/withDefaults.js.map +1 -0
  24. package/lib/api/wrappers/index.d.ts +17 -0
  25. package/lib/api/wrappers/index.d.ts.map +1 -0
  26. package/lib/api/wrappers/index.js +35 -0
  27. package/lib/api/wrappers/index.js.map +1 -0
  28. package/lib/api/wrappers/instrumenter.d.ts +27 -0
  29. package/lib/api/wrappers/instrumenter.d.ts.map +1 -0
  30. package/lib/api/wrappers/instrumenter.js +46 -0
  31. package/lib/api/wrappers/instrumenter.js.map +1 -0
  32. package/lib/api/wrappers/withLogging.d.ts +11 -0
  33. package/lib/api/wrappers/withLogging.d.ts.map +1 -0
  34. package/lib/api/wrappers/withLogging.js +40 -0
  35. package/lib/api/wrappers/withLogging.js.map +1 -0
  36. package/lib/api/wrappers/withTracing.d.ts +18 -0
  37. package/lib/api/wrappers/withTracing.d.ts.map +1 -0
  38. package/lib/api/wrappers/withTracing.js +40 -0
  39. package/lib/api/wrappers/withTracing.js.map +1 -0
  40. package/lib/test-utils/capabilities.d.ts +44 -0
  41. package/lib/test-utils/capabilities.d.ts.map +1 -0
  42. package/lib/test-utils/capabilities.js +44 -0
  43. package/lib/test-utils/capabilities.js.map +1 -0
  44. package/lib/test-utils/helpers.d.ts +1 -1
  45. package/lib/test-utils/helpers.d.ts.map +1 -1
  46. package/lib/test-utils/helpers.js +15 -0
  47. package/lib/test-utils/helpers.js.map +1 -1
  48. package/lib-es/api/impl.d.ts +74 -0
  49. package/lib-es/api/impl.d.ts.map +1 -0
  50. package/lib-es/api/impl.js +57 -0
  51. package/lib-es/api/impl.js.map +1 -0
  52. package/lib-es/api/index.d.ts +4 -0
  53. package/lib-es/api/index.d.ts.map +1 -1
  54. package/lib-es/api/index.js +4 -0
  55. package/lib-es/api/index.js.map +1 -1
  56. package/lib-es/api/notSupported.d.ts +14 -0
  57. package/lib-es/api/notSupported.d.ts.map +1 -1
  58. package/lib-es/api/notSupported.js +30 -2
  59. package/lib-es/api/notSupported.js.map +1 -1
  60. package/lib-es/api/notSupportedApi.d.ts +37 -0
  61. package/lib-es/api/notSupportedApi.d.ts.map +1 -0
  62. package/lib-es/api/notSupportedApi.js +65 -0
  63. package/lib-es/api/notSupportedApi.js.map +1 -0
  64. package/lib-es/api/types.d.ts +4 -0
  65. package/lib-es/api/types.d.ts.map +1 -1
  66. package/lib-es/api/withDefaults.d.ts +31 -0
  67. package/lib-es/api/withDefaults.d.ts.map +1 -0
  68. package/lib-es/api/withDefaults.js +54 -0
  69. package/lib-es/api/withDefaults.js.map +1 -0
  70. package/lib-es/api/wrappers/index.d.ts +17 -0
  71. package/lib-es/api/wrappers/index.d.ts.map +1 -0
  72. package/lib-es/api/wrappers/index.js +19 -0
  73. package/lib-es/api/wrappers/index.js.map +1 -0
  74. package/lib-es/api/wrappers/instrumenter.d.ts +27 -0
  75. package/lib-es/api/wrappers/instrumenter.d.ts.map +1 -0
  76. package/lib-es/api/wrappers/instrumenter.js +43 -0
  77. package/lib-es/api/wrappers/instrumenter.js.map +1 -0
  78. package/lib-es/api/wrappers/withLogging.d.ts +11 -0
  79. package/lib-es/api/wrappers/withLogging.d.ts.map +1 -0
  80. package/lib-es/api/wrappers/withLogging.js +37 -0
  81. package/lib-es/api/wrappers/withLogging.js.map +1 -0
  82. package/lib-es/api/wrappers/withTracing.d.ts +18 -0
  83. package/lib-es/api/wrappers/withTracing.d.ts.map +1 -0
  84. package/lib-es/api/wrappers/withTracing.js +37 -0
  85. package/lib-es/api/wrappers/withTracing.js.map +1 -0
  86. package/lib-es/test-utils/capabilities.d.ts +44 -0
  87. package/lib-es/test-utils/capabilities.d.ts.map +1 -0
  88. package/lib-es/test-utils/capabilities.js +41 -0
  89. package/lib-es/test-utils/capabilities.js.map +1 -0
  90. package/lib-es/test-utils/helpers.d.ts +1 -1
  91. package/lib-es/test-utils/helpers.d.ts.map +1 -1
  92. package/lib-es/test-utils/helpers.js +1 -0
  93. package/lib-es/test-utils/helpers.js.map +1 -1
  94. package/package.json +1 -1
  95. package/src/api/impl.test.ts +83 -0
  96. package/src/api/impl.ts +112 -0
  97. package/src/api/index.ts +4 -0
  98. package/src/api/notSupported.ts +32 -2
  99. package/src/api/notSupportedApi.test.ts +67 -0
  100. package/src/api/notSupportedApi.ts +74 -0
  101. package/src/api/types.ts +4 -0
  102. package/src/api/withDefaults.test.ts +190 -0
  103. package/src/api/withDefaults.ts +87 -0
  104. package/src/api/wrappers/index.ts +20 -0
  105. package/src/api/wrappers/instrumenter.test.ts +123 -0
  106. package/src/api/wrappers/instrumenter.ts +58 -0
  107. package/src/api/wrappers/withLogging.test.ts +137 -0
  108. package/src/api/wrappers/withLogging.ts +47 -0
  109. package/src/api/wrappers/withTracing.test.ts +125 -0
  110. package/src/api/wrappers/withTracing.ts +56 -0
  111. package/src/test-utils/capabilities.test.ts +108 -0
  112. package/src/test-utils/capabilities.ts +93 -0
  113. package/src/test-utils/helpers.ts +2 -0
package/src/api/types.ts CHANGED
@@ -410,6 +410,10 @@ export type TransactionValidation = {
410
410
 
411
411
  export type FeeEstimation = {
412
412
  value: bigint
413
+ /** Standard burn cost for comparison display (present when an alternative fee option was priced). */
414
+ originalValue?: bigint
415
+ /** max(0, originalValue - value); 0n when the alternative fee option costs more than the standard burn. */
416
+ savings?: bigint
413
417
  parameters?: Record<string, unknown>
414
418
  }
415
419
 
@@ -0,0 +1,190 @@
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 {
7
+ Balance,
8
+ BlockInfo,
9
+ CraftedTransaction,
10
+ FeeEstimation,
11
+ ListOperationsOptions,
12
+ TransactionIntent,
13
+ } from './types'
14
+ import { notSupported } from './notSupported'
15
+ import { withDefaults } from './withDefaults'
16
+
17
+ const stubIntent: TransactionIntent = {
18
+ intentType: 'transaction',
19
+ type: 'send',
20
+ sender: 'addr',
21
+ recipient: 'addr',
22
+ amount: 0n,
23
+ asset: { type: 'native' },
24
+ }
25
+
26
+ type Cfg = CurrencyConfig
27
+ type Ctx = Context<Cfg>
28
+
29
+ const ctx: Ctx = {
30
+ config: () => Promise.reject(new Error('stub')),
31
+ logger: () => undefined,
32
+ }
33
+
34
+ const minimalModule: CoinModuleImpl<Cfg> = {
35
+ lastBlock: (_ctx: Ctx): Promise<BlockInfo> => Promise.reject(new Error('stub')),
36
+ getBalance: (_ctx: Ctx, _addr: string): Promise<Balance[]> => Promise.resolve([]),
37
+ listOperations: (_ctx: Ctx, _addr: string, _opts: ListOperationsOptions) =>
38
+ Promise.resolve({ items: [] }),
39
+ craftTransaction: (_ctx: Ctx, _intent: TransactionIntent): Promise<CraftedTransaction> =>
40
+ Promise.reject(new Error('stub')),
41
+ estimateFees: (_ctx: Ctx, _intent: TransactionIntent): Promise<FeeEstimation> =>
42
+ Promise.reject(new Error('stub')),
43
+ combine: (_ctx: Ctx, tx: string, _sig: string[]): string => tx,
44
+ broadcast: (_ctx: Ctx, _tx: string): Promise<string> => Promise.reject(new Error('stub')),
45
+ craftTransactionData: (_ctx: Ctx, _intent: TransactionIntent) => ({ type: 'none' }) as const,
46
+ }
47
+
48
+ describe('withDefaults', () => {
49
+ it('widens a minimal impl to the full CoinModuleApi shape', () => {
50
+ const api = withDefaults(minimalModule)
51
+
52
+ // Required methods forwarded from impl
53
+ expect(api.lastBlock).not.toBe(undefined)
54
+ expect(api.getBalance).not.toBe(undefined)
55
+ expect(api.listOperations).not.toBe(undefined)
56
+ expect(api.craftTransaction).not.toBe(undefined)
57
+ expect(api.estimateFees).not.toBe(undefined)
58
+ expect(api.combine).not.toBe(undefined)
59
+ expect(api.broadcast).not.toBe(undefined)
60
+ expect(api.craftTransactionData).not.toBe(undefined)
61
+
62
+ // Capability methods are backfilled (never absent on result)
63
+ expect(api.getBlock).not.toBe(undefined)
64
+ expect(api.getBlockInfo).not.toBe(undefined)
65
+ expect(api.getStakes).not.toBe(undefined)
66
+ expect(api.getRewards).not.toBe(undefined)
67
+ expect(api.getValidators).not.toBe(undefined)
68
+ expect(api.call).not.toBe(undefined)
69
+ expect(api.craftRawTransaction).not.toBe(undefined)
70
+ expect(api.register).not.toBe(undefined)
71
+ expect(api.getNextSequence).not.toBe(undefined)
72
+ expect(api.validateIntent).not.toBe(undefined)
73
+ expect(api.validateAddress).not.toBe(undefined)
74
+ expect(api.getAccountInfo).not.toBe(undefined)
75
+
76
+ // Introspection helper present
77
+ expect(api.supports).not.toBe(undefined)
78
+ })
79
+
80
+ it('backfills capability methods that throw "<name> is not supported"', () => {
81
+ const api = withDefaults(minimalModule)
82
+
83
+ expect(() => api.getBlock(ctx, 1)).toThrow('getBlock is not supported')
84
+ expect(() => api.getBlockInfo(ctx, 1)).toThrow('getBlockInfo is not supported')
85
+ expect(() => api.getStakes(ctx, 'addr')).toThrow('getStakes is not supported')
86
+ expect(() => api.call(ctx, {})).toThrow('call is not supported')
87
+ expect(() => api.getNextSequence(ctx, 'addr')).toThrow('getNextSequence is not supported')
88
+ expect(() => api.validateIntent(ctx, stubIntent, [])).toThrow('validateIntent is not supported')
89
+ })
90
+
91
+ it('backfills validateAddress with a throwing stub rather than a permissive default', () => {
92
+ const api = withDefaults(minimalModule)
93
+ // A validator that silently answers "valid" for every address would let a bad
94
+ // recipient through, so an omitted validateAddress fails loud like any other capability.
95
+ expect(() => api.validateAddress(ctx, 'someaddr', {})).toThrow(
96
+ 'validateAddress is not supported'
97
+ )
98
+ })
99
+
100
+ it('backfills an omitted getAccountInfo with the {type:none} sentinel', async () => {
101
+ const api = withDefaults(minimalModule)
102
+ // ADR-045: no extra account metadata is an answer, not a missing capability, so this
103
+ // resolves rather than throwing like the other backfilled capabilities.
104
+ await expect(api.getAccountInfo(ctx, 'addr')).resolves.toEqual({ type: 'none' })
105
+ })
106
+
107
+ it('uses the impl getAccountInfo when it is provided', async () => {
108
+ const implWithInfo: CoinModuleImpl<Cfg> = {
109
+ ...minimalModule,
110
+ getAccountInfo: (_ctx: Ctx, _addr: string) =>
111
+ Promise.resolve({ type: 'tezos', revealed: true }),
112
+ }
113
+ const api = withDefaults(implWithInfo)
114
+ await expect(api.getAccountInfo(ctx, 'addr')).resolves.toEqual({
115
+ type: 'tezos',
116
+ revealed: true,
117
+ })
118
+ expect(api.supports('getAccountInfo')).toBe(true)
119
+ })
120
+
121
+ it('reports an omitted getAccountInfo as unsupported', () => {
122
+ const api = withDefaults(minimalModule)
123
+ expect(api.supports('getAccountInfo')).toBe(false)
124
+ })
125
+
126
+ it('preserves properties the impl carries beyond the API surface', () => {
127
+ const implWithExtra = { ...minimalModule, extraHelper: () => 'kept' }
128
+ const api = withDefaults(implWithExtra)
129
+ expect(api.extraHelper()).toBe('kept')
130
+ })
131
+
132
+ it('uses the impl method when it is provided instead of the backfilled default', async () => {
133
+ let called = false
134
+ const implWithStakes: CoinModuleImpl<Cfg> = {
135
+ ...minimalModule,
136
+ getStakes: (_ctx: Ctx, _addr: string) => {
137
+ called = true
138
+ return Promise.resolve({ items: [] })
139
+ },
140
+ }
141
+ const api = withDefaults(implWithStakes)
142
+ await api.getStakes(ctx, 'addr')
143
+ expect(called).toBe(true)
144
+ })
145
+
146
+ describe('supports()', () => {
147
+ it('returns false for capability methods absent from the impl', () => {
148
+ const api = withDefaults(minimalModule)
149
+ expect(api.supports('getStakes')).toBe(false)
150
+ expect(api.supports('getBlock')).toBe(false)
151
+ expect(api.supports('call')).toBe(false)
152
+ expect(api.supports('getNextSequence')).toBe(false)
153
+ expect(api.supports('validateAddress')).toBe(false)
154
+ })
155
+
156
+ it('returns true for capability methods present in the impl', () => {
157
+ const implWithStakes: CoinModuleImpl<Cfg> = {
158
+ ...minimalModule,
159
+ getStakes: (_ctx: Ctx, _addr: string) => Promise.resolve({ items: [] }),
160
+ }
161
+ const api = withDefaults(implWithStakes)
162
+ expect(api.supports('getStakes')).toBe(true)
163
+ // Other optionals remain absent
164
+ expect(api.supports('getBlock')).toBe(false)
165
+ expect(api.supports('validateAddress')).toBe(false)
166
+ })
167
+
168
+ it('returns false for a method filled with a notSupported() stub', () => {
169
+ // The shape every not-yet-migrated module ships: the key is present, but it is a
170
+ // placeholder that throws. Reporting it as supported would make supports() lie.
171
+ const implWithStub: CoinModuleImpl<Cfg> = {
172
+ ...minimalModule,
173
+ getStakes: notSupported('getStakes'),
174
+ getBlock: notSupported('getBlock'),
175
+ }
176
+ const api = withDefaults(implWithStub)
177
+ expect(api.supports('getStakes')).toBe(false)
178
+ expect(api.supports('getBlock')).toBe(false)
179
+ })
180
+
181
+ it('keeps the "not supported" behavior when a stub is normalized away', () => {
182
+ const implWithStub: CoinModuleImpl<Cfg> = {
183
+ ...minimalModule,
184
+ getStakes: notSupported('getStakes'),
185
+ }
186
+ const api = withDefaults(implWithStub)
187
+ expect(() => api.getStakes(ctx, 'addr')).toThrow('getStakes is not supported')
188
+ })
189
+ })
190
+ })
@@ -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
+ }