@ledgerhq/coin-module-framework 11.0.1 → 11.4.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.
- package/CHANGELOG.md +34 -0
- package/lib/api/getBlock/assertBlockHeight.d.ts +2 -0
- package/lib/api/getBlock/assertBlockHeight.d.ts.map +1 -0
- package/lib/api/getBlock/assertBlockHeight.js +12 -0
- package/lib/api/getBlock/assertBlockHeight.js.map +1 -0
- package/lib/api/impl.d.ts +22 -3
- package/lib/api/impl.d.ts.map +1 -1
- package/lib/api/impl.js +2 -0
- package/lib/api/impl.js.map +1 -1
- package/lib/api/notSupportedApi.d.ts.map +1 -1
- package/lib/api/notSupportedApi.js +1 -0
- package/lib/api/notSupportedApi.js.map +1 -1
- package/lib/api/types.d.ts +130 -2
- package/lib/api/types.d.ts.map +1 -1
- package/lib/api/withDefaults.d.ts +13 -2
- package/lib/api/withDefaults.d.ts.map +1 -1
- package/lib/api/withDefaults.js +36 -1
- package/lib/api/withDefaults.js.map +1 -1
- package/lib/currencies/formatCurrencyUnit.js +1 -1
- package/lib/currencies/formatCurrencyUnit.js.map +1 -1
- package/lib/currencies/parseCurrencyUnit.js +1 -1
- package/lib/currencies/parseCurrencyUnit.js.map +1 -1
- package/lib/errors.d.ts +37 -1
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +71 -2
- package/lib/errors.js.map +1 -1
- package/lib/promises/promises.d.ts +1 -1
- package/lib/promises/promises.d.ts.map +1 -1
- package/lib/promises/promises.js +1 -1
- package/lib/promises/promises.js.map +1 -1
- package/lib/utils.d.ts +1 -0
- package/lib/utils.d.ts.map +1 -1
- package/lib/utils.js +9 -0
- package/lib/utils.js.map +1 -1
- package/lib-es/api/getBlock/assertBlockHeight.d.ts +2 -0
- package/lib-es/api/getBlock/assertBlockHeight.d.ts.map +1 -0
- package/lib-es/api/getBlock/assertBlockHeight.js +9 -0
- package/lib-es/api/getBlock/assertBlockHeight.js.map +1 -0
- package/lib-es/api/impl.d.ts +22 -3
- package/lib-es/api/impl.d.ts.map +1 -1
- package/lib-es/api/impl.js +2 -0
- package/lib-es/api/impl.js.map +1 -1
- package/lib-es/api/notSupportedApi.d.ts.map +1 -1
- package/lib-es/api/notSupportedApi.js +1 -0
- package/lib-es/api/notSupportedApi.js.map +1 -1
- package/lib-es/api/types.d.ts +130 -2
- package/lib-es/api/types.d.ts.map +1 -1
- package/lib-es/api/withDefaults.d.ts +13 -2
- package/lib-es/api/withDefaults.d.ts.map +1 -1
- package/lib-es/api/withDefaults.js +36 -1
- package/lib-es/api/withDefaults.js.map +1 -1
- package/lib-es/currencies/formatCurrencyUnit.js +1 -1
- package/lib-es/currencies/formatCurrencyUnit.js.map +1 -1
- package/lib-es/currencies/parseCurrencyUnit.js +1 -1
- package/lib-es/currencies/parseCurrencyUnit.js.map +1 -1
- package/lib-es/errors.d.ts +37 -1
- package/lib-es/errors.d.ts.map +1 -1
- package/lib-es/errors.js +64 -1
- package/lib-es/errors.js.map +1 -1
- package/lib-es/promises/promises.d.ts +1 -1
- package/lib-es/promises/promises.d.ts.map +1 -1
- package/lib-es/promises/promises.js +1 -1
- package/lib-es/promises/promises.js.map +1 -1
- package/lib-es/utils.d.ts +1 -0
- package/lib-es/utils.d.ts.map +1 -1
- package/lib-es/utils.js +8 -0
- package/lib-es/utils.js.map +1 -1
- package/package.json +3 -3
- package/src/api/getBalance/rejectBalanceOptions.test.ts +8 -0
- package/src/api/getBlock/assertBlockHeight.test.ts +28 -0
- package/src/api/getBlock/assertBlockHeight.ts +10 -0
- package/src/api/impl.test.ts +3 -0
- package/src/api/impl.ts +24 -1
- package/src/api/notSupportedApi.ts +1 -0
- package/src/api/types.ts +155 -3
- package/src/api/withDefaults.test.ts +154 -1
- package/src/api/withDefaults.ts +66 -3
- package/src/currencies/formatCurrencyUnit.test.ts +14 -0
- package/src/currencies/formatCurrencyUnit.ts +1 -1
- package/src/currencies/parseCurrencyUnit.test.ts +5 -0
- package/src/currencies/parseCurrencyUnit.ts +1 -1
- package/src/errors.test.ts +89 -0
- package/src/errors.ts +59 -1
- package/src/promises/promises.test.ts +1 -1
- package/src/promises/promises.ts +1 -1
- package/src/test-utils/capabilities.test.ts +1 -0
- package/src/utils.test.ts +24 -1
- package/src/utils.ts +11 -0
|
@@ -67,6 +67,7 @@ export function notSupportedApi<
|
|
|
67
67
|
getNextSequence: notSupported('getNextSequence'),
|
|
68
68
|
validateIntent: notSupported('validateIntent'),
|
|
69
69
|
validateAddress: notSupported('validateAddress'),
|
|
70
|
+
listHoldings: notSupported('listHoldings'),
|
|
70
71
|
|
|
71
72
|
// Not a capability: absent metadata is an answer (ADR-045).
|
|
72
73
|
getAccountInfo: () => Promise.resolve({ type: 'none' }),
|
package/src/api/types.ts
CHANGED
|
@@ -84,10 +84,35 @@ export type Operation<MemoType extends Memo = MemoNotSupported> = {
|
|
|
84
84
|
* This can include things like status, error messages, swap info, etc.
|
|
85
85
|
*/
|
|
86
86
|
details?: Record<string, unknown>
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The transaction this operation belongs to.
|
|
90
|
+
*
|
|
91
|
+
* When the caller sets {@link ListOperationsOptions.feesAsset}, these rules apply:
|
|
92
|
+
*
|
|
93
|
+
* 1. When {@link tx.feesAsset} is absent, the fee is in the native coin.
|
|
94
|
+
* 2. A consumer debits {@link tx.fees} once, in {@link tx.feesAsset}, from {@link tx.feesPayer}. A failed transaction
|
|
95
|
+
* also pays.
|
|
96
|
+
* 3. Operations never include the fee movement, in any asset. When a chain emits the fee as token transfers, the
|
|
97
|
+
* module removes them.
|
|
98
|
+
* 4. When the fee is the only effect of a transaction on the account, the account gets one operation with
|
|
99
|
+
* {@link Operation.value} 0 that carries {@link tx.fees}, {@link tx.feesAsset} and {@link tx.feesPayer}.
|
|
100
|
+
* 5. {@link tx.fees} is the amount the chain debited, never a value converted from another unit.
|
|
101
|
+
*/
|
|
87
102
|
tx: {
|
|
88
103
|
hash: string // transaction hash
|
|
89
104
|
block: BlockInfo // block metadata, empty string for block hash if not available directly and no reorg possible
|
|
90
|
-
|
|
105
|
+
|
|
106
|
+
/** The network fees paid, in base units of {@link feesAsset}, or of the native coin when it is absent. */
|
|
107
|
+
fees: bigint
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* The asset that paid {@link fees}. Absent means the native coin.
|
|
111
|
+
*
|
|
112
|
+
* Set only when the caller sets {@link ListOperationsOptions.feesAsset}.
|
|
113
|
+
*/
|
|
114
|
+
feesAsset?: AssetInfo
|
|
115
|
+
|
|
91
116
|
// address that paid for this transaction's fees.
|
|
92
117
|
// optional as it may be unknown (e.g. the information is not available in the context of the operation).
|
|
93
118
|
// if it is unknown, it's expected that none of the sender addresses paid for the fees
|
|
@@ -130,6 +155,17 @@ export type Block = {
|
|
|
130
155
|
|
|
131
156
|
/**
|
|
132
157
|
* A transaction belonging to a {@link Block}, not specific to a particular account/address.
|
|
158
|
+
*
|
|
159
|
+
* When the caller sets {@link GetBlockOptions.feesAsset}, these rules apply:
|
|
160
|
+
*
|
|
161
|
+
* 1. When {@link feesAsset} is absent, the fee is in the native coin.
|
|
162
|
+
* 2. A consumer debits {@link fees} once, in {@link feesAsset}, from {@link feesPayer}. A failed transaction also
|
|
163
|
+
* pays.
|
|
164
|
+
* 3. {@link operations} never include the fee movement, in any asset. When a chain emits the fee as token transfers,
|
|
165
|
+
* the module removes them.
|
|
166
|
+
* 4. A transaction whose only effect is its fee is still included, with its fee fields. Its {@link operations} can be
|
|
167
|
+
* empty.
|
|
168
|
+
* 5. {@link fees} is the amount the chain debited, never a value converted from another unit.
|
|
133
169
|
*/
|
|
134
170
|
export type BlockTransaction = {
|
|
135
171
|
/** The transaction hash/digest (globally unique identifier). */
|
|
@@ -156,9 +192,19 @@ export type BlockTransaction = {
|
|
|
156
192
|
/** Network specific details for this transaction. */
|
|
157
193
|
details?: Record<string, unknown>
|
|
158
194
|
|
|
159
|
-
/**
|
|
195
|
+
/**
|
|
196
|
+
* The fee amount paid for this transaction, in base units of {@link feesAsset}, or of the native coin when it is
|
|
197
|
+
* absent. Always positive or zero.
|
|
198
|
+
*/
|
|
160
199
|
fees: bigint
|
|
161
200
|
|
|
201
|
+
/**
|
|
202
|
+
* The asset that paid {@link fees}. Absent means the native coin.
|
|
203
|
+
*
|
|
204
|
+
* Set only when the caller sets {@link GetBlockOptions.feesAsset}.
|
|
205
|
+
*/
|
|
206
|
+
feesAsset?: AssetInfo
|
|
207
|
+
|
|
162
208
|
/** The address that paid for this transaction's fees. */
|
|
163
209
|
feesPayer?: string
|
|
164
210
|
}
|
|
@@ -486,6 +532,44 @@ export type Page<T> = {
|
|
|
486
532
|
next?: Cursor | undefined
|
|
487
533
|
}
|
|
488
534
|
|
|
535
|
+
/**
|
|
536
|
+
* A unit of an address's funds: what a transaction spends, and what coin control selects.
|
|
537
|
+
*
|
|
538
|
+
* On UTXO, object and record chains it is one spendable unit (an unspent output, a coin object,
|
|
539
|
+
* a record); on account chains it is one balance per asset. A unit that carries several assets
|
|
540
|
+
* (a Cardano output with native tokens) is listed once per asset, the entries sharing its `id`:
|
|
541
|
+
* selecting or excluding that `id` takes the whole unit, all its assets.
|
|
542
|
+
*/
|
|
543
|
+
export type Holding = {
|
|
544
|
+
/**
|
|
545
|
+
* How a transaction intent refers to this holding. Opaque to the framework: its format belongs
|
|
546
|
+
* to the chain ("txid:vout", an object id, a record commitment, an account address…), and a
|
|
547
|
+
* caller only sends it back unchanged.
|
|
548
|
+
*/
|
|
549
|
+
id: string
|
|
550
|
+
/** The asset this holding is denominated in. */
|
|
551
|
+
asset: AssetInfo
|
|
552
|
+
/** The amount, in the asset's base unit. */
|
|
553
|
+
value: bigint
|
|
554
|
+
/** Block height the holding was created at; `null` while unconfirmed, absent if unknown. */
|
|
555
|
+
height?: number | null
|
|
556
|
+
/**
|
|
557
|
+
* The non-spendable part of {@link value}, as {@link Balance} `locked` (eg: a reserve, a frozen,
|
|
558
|
+
* staked, immature or time-locked amount).
|
|
559
|
+
*/
|
|
560
|
+
locked?: bigint
|
|
561
|
+
/** Chain-specific fields (script, record ciphertext…). */
|
|
562
|
+
details?: Record<string, unknown>
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/** Options for {@link CoinModuleApi#listHoldings}. */
|
|
566
|
+
export type ListHoldingsOptions = {
|
|
567
|
+
/** Only the holdings of this asset. Omitted: every asset. */
|
|
568
|
+
asset?: AssetInfo
|
|
569
|
+
/** A cursor from a previous page's `next`, to resume listing. */
|
|
570
|
+
cursor?: Cursor
|
|
571
|
+
}
|
|
572
|
+
|
|
489
573
|
/** Options for {@link CoinModuleApi#listOperations}. */
|
|
490
574
|
export type ListOperationsOptions = {
|
|
491
575
|
/**
|
|
@@ -517,6 +601,26 @@ export type ListOperationsOptions = {
|
|
|
517
601
|
* Implementation must raise a "not supported" error if order is set and not supported.
|
|
518
602
|
*/
|
|
519
603
|
order?: 'asc' | 'desc'
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* Report the asset that paid each fee, as `feesAsset` in {@link Operation.tx}, under the rules stated there.
|
|
607
|
+
*
|
|
608
|
+
* When it is not set, the output is the legacy one: `fees` is read as native. A module that honours this option
|
|
609
|
+
* declares it in `CoinModuleImpl.readOptions`; otherwise `withDefaults` rejects the call.
|
|
610
|
+
*/
|
|
611
|
+
feesAsset?: boolean
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** Options for {@link CoinModuleApi#getBlock}. */
|
|
615
|
+
export type GetBlockOptions = {
|
|
616
|
+
/**
|
|
617
|
+
* Report the asset that paid each fee in {@link BlockTransaction.feesAsset}, under the rules on
|
|
618
|
+
* {@link BlockTransaction}.
|
|
619
|
+
*
|
|
620
|
+
* When it is not set, the output is the legacy one: `fees` is read as native. A module that honours this option
|
|
621
|
+
* declares it in `CoinModuleImpl.readOptions`; otherwise `withDefaults` rejects the call.
|
|
622
|
+
*/
|
|
623
|
+
feesAsset?: boolean
|
|
520
624
|
}
|
|
521
625
|
|
|
522
626
|
/** A network validator */
|
|
@@ -601,6 +705,29 @@ export type BalanceOptions = {
|
|
|
601
705
|
* `knownAssets` is empty.
|
|
602
706
|
*/
|
|
603
707
|
scanAssetsMinHeight?: number
|
|
708
|
+
|
|
709
|
+
// Hints: coin module may respect these requirements or ignore it.
|
|
710
|
+
// A module that ignores them behaves as without them: it lists the validators, and fails when the
|
|
711
|
+
// listing fails.
|
|
712
|
+
|
|
713
|
+
/**
|
|
714
|
+
* Validators the caller knows for this account (the validators of the positions it stored),
|
|
715
|
+
* read unconditionally on top of those the delegation listing returns.
|
|
716
|
+
*
|
|
717
|
+
* Nothing is stored module-side: the caller keeps this list and passes it back on every call.
|
|
718
|
+
* When the listing fails, positions are returned for these validators alone, none when the list
|
|
719
|
+
* is empty. Absent means the caller knows nothing: a listing failure fails the call.
|
|
720
|
+
*/
|
|
721
|
+
knownValidatorIds?: string[] | undefined
|
|
722
|
+
|
|
723
|
+
/**
|
|
724
|
+
* Whether to call the delegation listing. Absent means `true`.
|
|
725
|
+
*
|
|
726
|
+
* `false` returns positions for {@link knownValidatorIds} alone, without calling the listing.
|
|
727
|
+
* A caller passes it only when it knows no position can have been added since its list was
|
|
728
|
+
* built. Ignored when {@link knownValidatorIds} is absent.
|
|
729
|
+
*/
|
|
730
|
+
listValidators?: boolean | undefined
|
|
604
731
|
}
|
|
605
732
|
|
|
606
733
|
export type StakesOptions = {
|
|
@@ -668,10 +795,15 @@ export type CoinModuleApi<
|
|
|
668
795
|
*
|
|
669
796
|
* @param context the {@link Context} carrying the coin config accessor and logger
|
|
670
797
|
* @param height the block height to query
|
|
798
|
+
* @param options see {@link GetBlockOptions}
|
|
671
799
|
* @returns the complete block with transactions
|
|
672
800
|
* @throws "not supported" if the blockchain does not support querying full blocks
|
|
673
801
|
*/
|
|
674
|
-
getBlock: (
|
|
802
|
+
getBlock: (
|
|
803
|
+
context: Context<ConfigType>,
|
|
804
|
+
height: number,
|
|
805
|
+
options?: GetBlockOptions
|
|
806
|
+
) => Promise<Block>
|
|
675
807
|
|
|
676
808
|
/**
|
|
677
809
|
* Perform a direct, read-only smart-contract call against the underlying node or indexer.
|
|
@@ -819,6 +951,26 @@ export type CoinModuleApi<
|
|
|
819
951
|
*/
|
|
820
952
|
getAccountInfo?: (context: Context<ConfigType>, address: string) => Promise<AccountInfo>
|
|
821
953
|
|
|
954
|
+
/**
|
|
955
|
+
* List the units an address's funds are made of: the spendable units a transaction consumes
|
|
956
|
+
* on UTXO, object and record chains, one holding per asset on account chains.
|
|
957
|
+
*
|
|
958
|
+
* Paginated: the response follows the {@link Page} contract.
|
|
959
|
+
*
|
|
960
|
+
* Implementations without a notion of holdings must raise a "not supported" error.
|
|
961
|
+
*
|
|
962
|
+
* @param context the {@link Context} carrying the coin config accessor and logger
|
|
963
|
+
* @param address the account address
|
|
964
|
+
* @param options asset filter and pagination cursor (see {@link ListHoldingsOptions})
|
|
965
|
+
* @returns a page of {@link Holding}
|
|
966
|
+
* @see getBalance
|
|
967
|
+
*/
|
|
968
|
+
listHoldings: (
|
|
969
|
+
context: Context<ConfigType>,
|
|
970
|
+
address: string,
|
|
971
|
+
options?: ListHoldingsOptions
|
|
972
|
+
) => Promise<Page<Holding>>
|
|
973
|
+
|
|
822
974
|
/**
|
|
823
975
|
* Register an account with the indexing backend selected by the context.
|
|
824
976
|
*
|
|
@@ -5,13 +5,20 @@ import type { CurrencyConfig, Context } from '../config'
|
|
|
5
5
|
import type { CoinModuleImpl } from './impl'
|
|
6
6
|
import type {
|
|
7
7
|
Balance,
|
|
8
|
+
Block,
|
|
8
9
|
BlockInfo,
|
|
9
10
|
CraftedTransaction,
|
|
10
11
|
FeeEstimation,
|
|
12
|
+
GetBlockOptions,
|
|
13
|
+
Holding,
|
|
14
|
+
ListHoldingsOptions,
|
|
11
15
|
ListOperationsOptions,
|
|
16
|
+
Operation,
|
|
17
|
+
Page,
|
|
12
18
|
TransactionIntent,
|
|
13
19
|
} from './types'
|
|
14
|
-
import {
|
|
20
|
+
import { InvalidParameterError } from '../errors'
|
|
21
|
+
import { isNotSupportedStub, notSupported } from './notSupported'
|
|
15
22
|
import { withDefaults } from './withDefaults'
|
|
16
23
|
|
|
17
24
|
const stubIntent: TransactionIntent = {
|
|
@@ -123,6 +130,34 @@ describe('withDefaults', () => {
|
|
|
123
130
|
expect(api.supports('getAccountInfo')).toBe(false)
|
|
124
131
|
})
|
|
125
132
|
|
|
133
|
+
it('backfills an omitted listHoldings with a throwing stub and reports it unsupported', () => {
|
|
134
|
+
const api = withDefaults(minimalModule)
|
|
135
|
+
expect(() => api.listHoldings(ctx, 'addr')).toThrow('listHoldings is not supported')
|
|
136
|
+
expect(api.supports('listHoldings')).toBe(false)
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it('passes an implemented listHoldings through with its arguments and reports it supported', async () => {
|
|
140
|
+
const holding: Holding = { id: 'txid:0', asset: { type: 'native' }, value: 1n, height: null }
|
|
141
|
+
const listHoldings = jest.fn((_ctx: Ctx, _addr: string, _opts?: ListHoldingsOptions) =>
|
|
142
|
+
Promise.resolve({ items: [holding], next: 'c1' })
|
|
143
|
+
)
|
|
144
|
+
const api = withDefaults({ ...minimalModule, listHoldings })
|
|
145
|
+
const options: ListHoldingsOptions = { asset: { type: 'native' }, cursor: 'c0' }
|
|
146
|
+
|
|
147
|
+
await expect(api.listHoldings(ctx, 'addr', options)).resolves.toEqual({
|
|
148
|
+
items: [holding],
|
|
149
|
+
next: 'c1',
|
|
150
|
+
})
|
|
151
|
+
expect(listHoldings).toHaveBeenCalledWith(ctx, 'addr', options)
|
|
152
|
+
expect(api.supports('listHoldings')).toBe(true)
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
it('counts a notSupported listHoldings stub as absent', () => {
|
|
156
|
+
const api = withDefaults({ ...minimalModule, listHoldings: notSupported('listHoldings') })
|
|
157
|
+
expect(api.supports('listHoldings')).toBe(false)
|
|
158
|
+
expect(() => api.listHoldings(ctx, 'addr')).toThrow('listHoldings is not supported')
|
|
159
|
+
})
|
|
160
|
+
|
|
126
161
|
it('preserves properties the impl carries beyond the API surface', () => {
|
|
127
162
|
const implWithExtra = { ...minimalModule, extraHelper: () => 'kept' }
|
|
128
163
|
const api = withDefaults(implWithExtra)
|
|
@@ -187,4 +222,122 @@ describe('withDefaults', () => {
|
|
|
187
222
|
expect(() => api.getStakes(ctx, 'addr')).toThrow('getStakes is not supported')
|
|
188
223
|
})
|
|
189
224
|
})
|
|
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
|
+
})
|
|
190
343
|
})
|
package/src/api/withDefaults.ts
CHANGED
|
@@ -2,13 +2,21 @@
|
|
|
2
2
|
// SPDX-License-Identifier: Apache-2.0
|
|
3
3
|
|
|
4
4
|
import type { CurrencyConfig } from '../config'
|
|
5
|
-
import type {
|
|
5
|
+
import type {
|
|
6
|
+
CoinModuleImpl,
|
|
7
|
+
OptionalApiKey,
|
|
8
|
+
ReadOption,
|
|
9
|
+
ReadOptionMethod,
|
|
10
|
+
ReadOptionsDeclaration,
|
|
11
|
+
} from './impl'
|
|
6
12
|
import type { CoinModuleApi, Memo, MemoNotSupported, TxData, TxDataNotSupported } from './types'
|
|
13
|
+
import { InvalidParameterError } from '../errors'
|
|
7
14
|
import { optionalApiKeys } from './impl'
|
|
8
15
|
import { isNotSupportedStub, notSupported } from './notSupported'
|
|
9
16
|
|
|
10
17
|
/**
|
|
11
|
-
* What {@link withDefaults} returns: the full consumer contract, plus `supports()
|
|
18
|
+
* What {@link withDefaults} returns: the full consumer contract, plus `supports()` and
|
|
19
|
+
* `supportsReadOption()`.
|
|
12
20
|
*
|
|
13
21
|
* `getAccountInfo` is narrowed to required. It is the one managed capability that
|
|
14
22
|
* {@link CoinModuleApi} itself declares optional, and `withDefaults` always supplies it — so
|
|
@@ -22,6 +30,13 @@ export type WithDefaultsResult<
|
|
|
22
30
|
> = CoinModuleApi<ConfigType, MemoType, TxDataType> &
|
|
23
31
|
Required<Pick<CoinModuleApi<ConfigType, MemoType, TxDataType>, 'getAccountInfo'>> & {
|
|
24
32
|
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
|
|
25
40
|
}
|
|
26
41
|
|
|
27
42
|
/**
|
|
@@ -35,6 +50,33 @@ function implemented<T>(value: T | undefined): T | undefined {
|
|
|
35
50
|
return value === undefined || isNotSupportedStub(value) ? undefined : value
|
|
36
51
|
}
|
|
37
52
|
|
|
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
|
+
|
|
38
80
|
/**
|
|
39
81
|
* Widens a {@link CoinModuleImpl} authoring value to the full {@link CoinModuleApi}
|
|
40
82
|
* consumer contract by backfilling the capability methods the author omitted, and attaches
|
|
@@ -49,6 +91,9 @@ function implemented<T>(value: T | undefined): T | undefined {
|
|
|
49
91
|
*
|
|
50
92
|
* A capability method is considered implemented only when the author supplied a real
|
|
51
93
|
* 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.
|
|
52
97
|
*/
|
|
53
98
|
export function withDefaults<
|
|
54
99
|
ConfigType extends CurrencyConfig,
|
|
@@ -61,12 +106,28 @@ export function withDefaults<
|
|
|
61
106
|
const implementedMethods = new Set<OptionalApiKey>(
|
|
62
107
|
optionalApiKeys.filter((k) => implemented(impl[k]) !== undefined)
|
|
63
108
|
)
|
|
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)
|
|
64
116
|
|
|
65
117
|
// Spread first so anything the module exposes beyond the API surface survives, then
|
|
66
118
|
// override every capability method with either the real implementation or the default.
|
|
67
119
|
return {
|
|
68
120
|
...impl,
|
|
69
|
-
|
|
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'),
|
|
70
131
|
getBlockInfo: implemented(impl.getBlockInfo) ?? notSupported('getBlockInfo'),
|
|
71
132
|
getStakes: implemented(impl.getStakes) ?? notSupported('getStakes'),
|
|
72
133
|
getRewards: implemented(impl.getRewards) ?? notSupported('getRewards'),
|
|
@@ -78,10 +139,12 @@ export function withDefaults<
|
|
|
78
139
|
getNextSequence: implemented(impl.getNextSequence) ?? notSupported('getNextSequence'),
|
|
79
140
|
validateIntent: implemented(impl.validateIntent) ?? notSupported('validateIntent'),
|
|
80
141
|
validateAddress: implemented(impl.validateAddress) ?? notSupported('validateAddress'),
|
|
142
|
+
listHoldings: implemented(impl.listHoldings) ?? notSupported('listHoldings'),
|
|
81
143
|
// ADR-045: an absent getAccountInfo means the chain has no extra account metadata to
|
|
82
144
|
// report, which is an answer rather than a missing capability — hence a sentinel instead
|
|
83
145
|
// of a throwing stub. Callers read `type` and branch on it.
|
|
84
146
|
getAccountInfo: implemented(impl.getAccountInfo) ?? (() => Promise.resolve({ type: 'none' })),
|
|
85
147
|
supports: (method: OptionalApiKey): boolean => implementedMethods.has(method),
|
|
148
|
+
supportsReadOption,
|
|
86
149
|
}
|
|
87
150
|
}
|
|
@@ -105,6 +105,20 @@ describe('formatCurrencyUnit', () => {
|
|
|
105
105
|
)
|
|
106
106
|
})
|
|
107
107
|
|
|
108
|
+
test('showAllDigits with magnitude above default DECIMAL_PLACES', () => {
|
|
109
|
+
const highMagUnit: Unit = { ...unit, magnitude: 24 }
|
|
110
|
+
expect(formatCurrencyUnit(highMagUnit, new BigNumber(1), { showAllDigits: true })).toBe(
|
|
111
|
+
'0.000000000000000000000001'
|
|
112
|
+
)
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
test('disableRounding with magnitude above default DECIMAL_PLACES', () => {
|
|
116
|
+
const highMagUnit: Unit = { ...unit, magnitude: 24 }
|
|
117
|
+
expect(formatCurrencyUnit(highMagUnit, new BigNumber(1), { disableRounding: true })).toBe(
|
|
118
|
+
'0.000000000000000000000001'
|
|
119
|
+
)
|
|
120
|
+
})
|
|
121
|
+
|
|
108
122
|
test('filters undefined options', () => {
|
|
109
123
|
expect(
|
|
110
124
|
// @ts-expect-error explicit undefined, for JS callers
|
|
@@ -100,7 +100,7 @@ const buildFormatState = (
|
|
|
100
100
|
staticSignificantDigits,
|
|
101
101
|
} = resolvedOptions
|
|
102
102
|
const { magnitude, code } = unit
|
|
103
|
-
const floatValue = value.
|
|
103
|
+
const floatValue = value.shiftedBy(-magnitude)
|
|
104
104
|
const floatValueAbs = floatValue.abs()
|
|
105
105
|
const minimumFractionDigits = showAllDigits ? magnitude : 0
|
|
106
106
|
const maximumFractionDigits = disableRounding
|
|
@@ -26,4 +26,9 @@ describe('parseCurrencyUnit', () => {
|
|
|
26
26
|
test('returns zero on invalid input', () => {
|
|
27
27
|
expect(parseCurrencyUnit(unit, 'invalid')).toEqual(new BigNumber(0))
|
|
28
28
|
})
|
|
29
|
+
|
|
30
|
+
test('parses magnitude above default DECIMAL_PLACES', () => {
|
|
31
|
+
const highMagUnit: Unit = { ...unit, magnitude: 24 }
|
|
32
|
+
expect(parseCurrencyUnit(highMagUnit, '0.000000000000000000000001')).toEqual(new BigNumber(1))
|
|
33
|
+
})
|
|
29
34
|
})
|
|
@@ -9,5 +9,5 @@ export const parseCurrencyUnit = (unit: Unit, valueString: string): BigNumber =>
|
|
|
9
9
|
const str = valueString.replace(/,/g, '.')
|
|
10
10
|
const value = new BigNumber(str)
|
|
11
11
|
if (value.isNaN()) return new BigNumber(0)
|
|
12
|
-
return value.
|
|
12
|
+
return value.shiftedBy(unit.magnitude).integerValue()
|
|
13
13
|
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: © 2026 LEDGER SAS
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
BlockNotFoundError,
|
|
6
|
+
GetBlockError,
|
|
7
|
+
GetBlockInfoError,
|
|
8
|
+
InvalidBlockHeightError,
|
|
9
|
+
InvalidExplorerResponse,
|
|
10
|
+
RateLimitError,
|
|
11
|
+
statusCodeOf,
|
|
12
|
+
} from './errors'
|
|
13
|
+
|
|
14
|
+
type ErrorClass = new (
|
|
15
|
+
message?: string,
|
|
16
|
+
fields?: Record<string, unknown>,
|
|
17
|
+
options?: { cause?: unknown }
|
|
18
|
+
) => Error
|
|
19
|
+
|
|
20
|
+
const ERRORS: Array<[string, ErrorClass, string | undefined]> = [
|
|
21
|
+
['BlockNotFoundError', BlockNotFoundError, undefined],
|
|
22
|
+
['InvalidBlockHeightError', InvalidBlockHeightError, undefined],
|
|
23
|
+
['RateLimitError', RateLimitError, 'Upstream rate limit exceeded (429), please retry later'],
|
|
24
|
+
['InvalidExplorerResponse', InvalidExplorerResponse, undefined],
|
|
25
|
+
['GetBlockInfoError', GetBlockInfoError, undefined],
|
|
26
|
+
['GetBlockError', GetBlockError, undefined],
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
describe.each(ERRORS)('%s', (name, ErrorType, defaultMessage) => {
|
|
30
|
+
it('is an Error named after its class with a default message', () => {
|
|
31
|
+
const error = new ErrorType()
|
|
32
|
+
|
|
33
|
+
expect(error).toBeInstanceOf(Error)
|
|
34
|
+
expect(error.name).toBe(name)
|
|
35
|
+
expect(error.message).toBe(defaultMessage ?? name)
|
|
36
|
+
expect(error).not.toHaveProperty('cause')
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('keeps a custom message', () => {
|
|
40
|
+
expect(new ErrorType('custom').message).toBe('custom')
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('exposes the fields as attributes', () => {
|
|
44
|
+
expect(new ErrorType('custom', { height: 12 })).toHaveProperty('height', 12)
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('attaches the cause', () => {
|
|
48
|
+
const cause = new Error('root')
|
|
49
|
+
|
|
50
|
+
expect(new ErrorType('custom', { height: 12 }, { cause })).toHaveProperty('cause', cause)
|
|
51
|
+
})
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
describe('statusCode', () => {
|
|
55
|
+
it.each<[string, ErrorClass, number]>([
|
|
56
|
+
['BlockNotFoundError', BlockNotFoundError, 404],
|
|
57
|
+
['InvalidBlockHeightError', InvalidBlockHeightError, 400],
|
|
58
|
+
['RateLimitError', RateLimitError, 429],
|
|
59
|
+
])('%s carries %d', (_name, ErrorType, statusCode) => {
|
|
60
|
+
expect(new ErrorType()).toHaveProperty('statusCode', statusCode)
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('can be overridden through the fields', () => {
|
|
64
|
+
expect(new BlockNotFoundError(undefined, { statusCode: 500 })).toHaveProperty('statusCode', 500)
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it.each<[string, ErrorClass]>([
|
|
68
|
+
['InvalidExplorerResponse', InvalidExplorerResponse],
|
|
69
|
+
['GetBlockInfoError', GetBlockInfoError],
|
|
70
|
+
['GetBlockError', GetBlockError],
|
|
71
|
+
])('%s carries none', (_name, ErrorType) => {
|
|
72
|
+
expect(new ErrorType()).not.toHaveProperty('statusCode')
|
|
73
|
+
})
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
describe('statusCodeOf', () => {
|
|
77
|
+
it('returns the numeric status code of an error', () => {
|
|
78
|
+
expect(statusCodeOf(new BlockNotFoundError())).toEqual(404)
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
it('returns nothing when the error has no numeric status code', () => {
|
|
82
|
+
expect(statusCodeOf(new Error('plain'))).toBeUndefined()
|
|
83
|
+
expect(statusCodeOf(Object.assign(new Error('plain'), { statusCode: '404' }))).toBeUndefined()
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
it('returns nothing when nothing was thrown', () => {
|
|
87
|
+
expect(statusCodeOf(undefined)).toBeUndefined()
|
|
88
|
+
})
|
|
89
|
+
})
|