@midnightntwrk/wallet-sdk-capabilities 4.0.0-rc.0 → 4.0.0-rc.2

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 (65) hide show
  1. package/README.md +10 -3
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.js +2 -1
  4. package/dist/liveness/index.d.ts +2 -0
  5. package/dist/liveness/index.js +14 -0
  6. package/dist/liveness/livenessReads.d.ts +73 -0
  7. package/dist/liveness/livenessReads.js +229 -0
  8. package/dist/liveness/livenessService.d.ts +137 -0
  9. package/dist/liveness/livenessService.js +200 -0
  10. package/dist/proving/index.d.ts +1 -0
  11. package/dist/proving/index.js +1 -0
  12. package/dist/proving/provingService.d.ts +15 -48
  13. package/dist/proving/provingService.js +1 -89
  14. package/dist/proving/v8ProvingService.d.ts +33 -6
  15. package/dist/proving/v8ProvingService.js +35 -5
  16. package/dist/proving/v9ProvingService.d.ts +108 -0
  17. package/dist/proving/v9ProvingService.js +146 -0
  18. package/dist/proving/versionedProving.d.ts +22 -4
  19. package/dist/proving/versionedProving.js +27 -1
  20. package/dist/simulation/index.d.ts +4 -6
  21. package/dist/simulation/index.js +4 -7
  22. package/dist/simulation/v8/Simulator.d.ts +0 -2
  23. package/dist/simulation/v8/Simulator.js +0 -2
  24. package/dist/simulation/v8/SimulatorState.d.ts +0 -9
  25. package/dist/simulation/v8/SimulatorState.js +0 -8
  26. package/dist/simulation/v8/index.d.ts +1 -1
  27. package/dist/simulation/v8/index.js +1 -1
  28. package/dist/simulation/v9/Simulator.d.ts +0 -2
  29. package/dist/simulation/v9/Simulator.js +0 -2
  30. package/dist/simulation/v9/SimulatorState.d.ts +0 -9
  31. package/dist/simulation/v9/SimulatorState.js +0 -8
  32. package/dist/simulation/v9/index.d.ts +1 -1
  33. package/dist/simulation/v9/index.js +1 -1
  34. package/dist/submission/submissionService.d.ts +57 -9
  35. package/dist/submission/submissionService.js +61 -15
  36. package/dist/transactionLifecycle/SnapshotFormat.d.ts +51 -0
  37. package/dist/transactionLifecycle/SnapshotFormat.js +120 -0
  38. package/dist/transactionLifecycle/index.d.ts +4 -0
  39. package/dist/{pendingTransactions → transactionLifecycle}/index.js +4 -2
  40. package/dist/transactionLifecycle/lifecycle.d.ts +402 -0
  41. package/dist/transactionLifecycle/lifecycle.js +407 -0
  42. package/dist/transactionLifecycle/lifecycleService.d.ts +448 -0
  43. package/dist/transactionLifecycle/lifecycleService.js +350 -0
  44. package/dist/transactionLifecycle/transactionTraits.d.ts +106 -0
  45. package/dist/transactionLifecycle/transactionTraits.js +53 -0
  46. package/dist/validation/blockData.d.ts +23 -4
  47. package/dist/validation/blockData.js +34 -10
  48. package/dist/validation/index.d.ts +1 -0
  49. package/dist/validation/index.js +1 -0
  50. package/dist/validation/promiseBoundary.d.ts +10 -0
  51. package/dist/validation/promiseBoundary.js +30 -0
  52. package/dist/validation/v8ValidationService.d.ts +5 -4
  53. package/dist/validation/v8ValidationService.js +10 -3
  54. package/dist/validation/v9ValidationService.d.ts +30 -0
  55. package/dist/validation/v9ValidationService.js +61 -0
  56. package/dist/validation/validationService.d.ts +53 -31
  57. package/dist/validation/validationService.js +29 -49
  58. package/dist/validation/versionedValidation.d.ts +5 -3
  59. package/dist/validation/versionedValidation.js +5 -3
  60. package/package.json +13 -13
  61. package/dist/pendingTransactions/index.d.ts +0 -2
  62. package/dist/pendingTransactions/pendingTransactions.d.ts +0 -165
  63. package/dist/pendingTransactions/pendingTransactions.js +0 -202
  64. package/dist/pendingTransactions/pendingTransactionsService.d.ts +0 -68
  65. package/dist/pendingTransactions/pendingTransactionsService.js +0 -158
package/README.md CHANGED
@@ -105,10 +105,12 @@ wallets are built with:
105
105
  ```typescript
106
106
  import { makeDefaultVersionedProvingService } from '@midnightntwrk/wallet-sdk-capabilities/proving';
107
107
 
108
+ // Either<VersionedProvingService<AnyVersionUnboundTransaction, AnyVersionUnprovenTransaction>,
109
+ // ProvingConfigurationError>
108
110
  const service = makeDefaultVersionedProvingService(
109
111
  { provers: { v8: { kind: 'server', url: v8ProofServer }, v9: { kind: 'wasm' } } },
110
112
  forks,
111
- ); // Either<VersionedProvingService, ProvingConfigurationError>
113
+ );
112
114
  ```
113
115
 
114
116
  - `provers` wins over `provingServerUrl`; naming neither is a `ProvingConfigurationError`. `v9` is required and `v8` is
@@ -118,8 +120,13 @@ const service = makeDefaultVersionedProvingService(
118
120
  operational fact about that server, not something the SDK enforces.
119
121
  - Each registered backend refuses the other ledger version's transaction with `ProvingEpochMismatchError` rather than
120
122
  handing it to a ledger that cannot read it.
121
- - `makeV9ServerProvingServiceEffect` / `makeV9WasmProvingServiceEffect` build a single ledger-v9 backend;
122
- `makeV8ServerProvingServiceEffect` / `makeV8WasmProvingServiceEffect` are their ledger-v8 twins.
123
+ - `makeV9ServerProvingServiceEffect` / `makeV9WasmProvingServiceEffect` build a single ledger-v9 backend, a
124
+ `V9ProvingServiceEffect` over `V9UnprovenTransaction`; `makeV8ServerProvingServiceEffect` /
125
+ `makeV8WasmProvingServiceEffect` are their ledger-v8 twins (`V8ProvingServiceEffect`, `V8UnprovenTransaction`). The
126
+ facade's `provingService` takes a prover over both ledger versions; to prove with one ledger version's backend alone,
127
+ name it in `provers` (`{ v9: { kind: 'wasm' } }`) instead.
128
+ - `makeV9SimulatorProvingServiceEffect` / `makeV8SimulatorProvingServiceEffect` erase proofs instead of proving them,
129
+ for the in-memory simulator.
123
130
 
124
131
  ## Exports
125
132
 
package/dist/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  export * from './balancer/index.js';
2
2
  export * from './chainVersion/index.js';
3
3
  export * from './codecs/index.js';
4
- export * from './pendingTransactions/index.js';
4
+ export * from './liveness/index.js';
5
+ export * from './transactionLifecycle/index.js';
5
6
  export * from './proving/index.js';
6
7
  export * from './signatures/index.js';
7
8
  export * from './simulation/index.js';
package/dist/index.js CHANGED
@@ -13,7 +13,8 @@
13
13
  export * from './balancer/index.js';
14
14
  export * from './chainVersion/index.js';
15
15
  export * from './codecs/index.js';
16
- export * from './pendingTransactions/index.js';
16
+ export * from './liveness/index.js';
17
+ export * from './transactionLifecycle/index.js';
17
18
  export * from './proving/index.js';
18
19
  export * from './signatures/index.js';
19
20
  export * from './simulation/index.js';
@@ -0,0 +1,2 @@
1
+ export * from './livenessReads.js';
2
+ export * from './livenessService.js';
@@ -0,0 +1,14 @@
1
+ // This file is part of MIDNIGHT-WALLET-SDK.
2
+ // Copyright (C) Midnight Foundation
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // You may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ export * from './livenessReads.js';
14
+ export * from './livenessService.js';
@@ -0,0 +1,73 @@
1
+ import { type NodeClient, type NodeClientError } from '@midnightntwrk/wallet-sdk-node-client/effect';
2
+ import { Effect, Option, Scope } from 'effect';
3
+ import { type LivenessReads } from './livenessService.js';
4
+ /**
5
+ * Parses a block height reported by the indexer.
6
+ *
7
+ * @remarks
8
+ * `BigInt` throws a `RangeError` on a non-integral number, and the indexer's payload is not validated against a schema
9
+ * anywhere on this path. A misbehaving indexer answering `1.5` would therefore raise a defect inside the poll and
10
+ * stop it permanently — letting the very party this check exists to catch switch it off. Parsing here keeps that a
11
+ * typed failure, which becomes an `Unavailable` verdict like any other unreadable answer.
12
+ * @param height - The value the indexer reported.
13
+ * @returns The height, or `Option.none` when it is not a whole non-negative number.
14
+ */
15
+ export declare const parseIndexerHeight: (height: unknown) => Option.Option<bigint>;
16
+ export type LivenessReadsConfiguration = {
17
+ readonly indexerClientConnection: {
18
+ readonly indexerHttpUrl: string;
19
+ };
20
+ readonly nodeClientConnection: {
21
+ readonly nodeURL: string;
22
+ };
23
+ };
24
+ /**
25
+ * The calls the liveness check makes on a node client.
26
+ *
27
+ * @remarks
28
+ * Narrowed to what the check uses so that a test double answers those methods rather than the whole of
29
+ * `NodeClient.Service`, and so that this module depends on no more of the node client's surface than it reads.
30
+ */
31
+ export type LivenessNodeReader = Pick<NodeClient.Service, 'getFinalizedBlock' | 'getGenesisHash' | 'getBlockHashAt'>;
32
+ /** Builds a client for the liveness check's node reads, scoped so the connection is released with its caller. */
33
+ export type NodeClientFactory = (nodeURL: URL) => Effect.Effect<LivenessNodeReader, NodeClientError.NodeClientError, Scope.Scope>;
34
+ /**
35
+ * Builds the reads a liveness check compares.
36
+ *
37
+ * @remarks
38
+ * This is the only place the two sources meet, and it exists in `capabilities` rather than in a wallet package so that
39
+ * no wallet has to depend on `node-client` directly.
40
+ *
41
+ * The node client is built once, on the first read that needs it, and then reused. Building one per read repeated the
42
+ * full `ApiPromise` handshake — including the runtime metadata download — on every poll, against a node the wallet
43
+ * does not own, to fetch two numbers. polkadot-js re-fetches metadata only when the api is not already ready
44
+ * (`_loadMeta`), so a reused client pays that cost once per wallet rather than once per poll. The socket itself is
45
+ * still closed between reads by `getFinalizedBlock`, so nothing is held open on the node's behalf.
46
+ *
47
+ * Creation is deferred to the first read rather than done here, because a connection failure at construction must
48
+ * become an {@link IndexerLiveness.Unavailable} verdict. Connecting while the sync stream is being assembled would put
49
+ * that failure in the stream's acquire instead, so an unreachable node would stop the wallet syncing — the one
50
+ * outcome this check must never cause.
51
+ *
52
+ * A failed read leaves the cached client in place. It recovers by itself: `getFinalizedBlock` reconnects through
53
+ * `ensureConnection`, and polkadot-js retries the metadata load on the next connect whenever an earlier one did not
54
+ * complete. Only construction failing leaves nothing cached, and the next read then starts over — so a node that is
55
+ * down when the first poll runs does not switch the check off for the rest of the session.
56
+ *
57
+ * Both failures are flattened into {@link LivenessReadError} so the service is coupled to neither the indexer's GraphQL
58
+ * errors nor the node client's error type.
59
+ * @example
60
+ * ```ts
61
+ * const reads = yield* makeDefaultLivenessReads({
62
+ * indexerClientConnection: { indexerHttpUrl: 'http://localhost:8088/api/v1/graphql' },
63
+ * nodeClientConnection: { nodeURL: 'ws://localhost:9944' },
64
+ * });
65
+ * ```;
66
+ *
67
+ * @param config - Where to reach the indexer and the node.
68
+ * @param makeNodeClient - How to build the node client. Defaults to a real connection; supplying this is how a test
69
+ * exercises the caching without a node.
70
+ * @returns An effect yielding reads suitable for {@link LivenessServiceImpl.make}. Scoped, because the client they share
71
+ * is released when that scope closes.
72
+ */
73
+ export declare const makeDefaultLivenessReads: (config: LivenessReadsConfiguration, makeNodeClient?: NodeClientFactory) => Effect.Effect<LivenessReads, never, Scope.Scope>;
@@ -0,0 +1,229 @@
1
+ // This file is part of MIDNIGHT-WALLET-SDK.
2
+ // Copyright (C) Midnight Foundation
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ // Licensed under the Apache License, Version 2.0 (the "License");
5
+ // You may not use this file except in compliance with the License.
6
+ // You may obtain a copy of the License at
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ import { BlockHash } from '@midnightntwrk/wallet-sdk-indexer-client';
14
+ import { HttpQueryClient } from '@midnightntwrk/wallet-sdk-indexer-client/effect';
15
+ import { PolkadotNodeClient, } from '@midnightntwrk/wallet-sdk-node-client/effect';
16
+ import { Duration, Effect, Option, Scope, SynchronizedRef } from 'effect';
17
+ import { LivenessReadError } from './livenessService.js';
18
+ /**
19
+ * How long to spend trying to reach the node before giving up on a poll.
20
+ *
21
+ * @remarks
22
+ * `PolkadotNodeClient` defaults to `Duration.infinity`, which suits transaction submission — a caller waiting to submit
23
+ * wants to keep trying. It is wrong here: a liveness check that waits forever on an unreachable node never publishes
24
+ * the {@link IndexerLiveness.Unavailable} verdict that exists to report exactly that condition, and its poll fibre
25
+ * hangs instead.
26
+ *
27
+ * The bound applies twice within one connection build — once to the handshake, once to the close that follows it — so
28
+ * the build's worst case is double this value. The poll's own deadline does not depend on it: the service disconnects
29
+ * the read before applying its timeout, so the verdict lands on time. A poll that gives up abandons a handshake still
30
+ * in progress, and the next poll starts a new one; a build that has connected finishes its close in the background
31
+ * and its client is cached for the next poll.
32
+ */
33
+ const NODE_CONNECTION_TIMEOUT = Duration.seconds(10);
34
+ /**
35
+ * Flattens a chain of wrapped errors into one line.
36
+ *
37
+ * @remarks
38
+ * Both sources wrap their failures — the node client reports "Failed to retrieve the finalized block" over whatever the
39
+ * RPC actually said. Only the outermost message would otherwise reach `Unavailable.lastError`, which names the
40
+ * operation that failed but not the reason, and so cannot be acted on.
41
+ */
42
+ const describeCause = (error) => error instanceof Error
43
+ ? error.cause === undefined || error.cause === null
44
+ ? error.message
45
+ : `${error.message}: ${describeCause(error.cause)}`
46
+ : String(error);
47
+ /**
48
+ * Parses a block height reported by the indexer.
49
+ *
50
+ * @remarks
51
+ * `BigInt` throws a `RangeError` on a non-integral number, and the indexer's payload is not validated against a schema
52
+ * anywhere on this path. A misbehaving indexer answering `1.5` would therefore raise a defect inside the poll and
53
+ * stop it permanently — letting the very party this check exists to catch switch it off. Parsing here keeps that a
54
+ * typed failure, which becomes an `Unavailable` verdict like any other unreadable answer.
55
+ * @param height - The value the indexer reported.
56
+ * @returns The height, or `Option.none` when it is not a whole non-negative number.
57
+ */
58
+ export const parseIndexerHeight = (height) => typeof height === 'number' && Number.isSafeInteger(height) && height >= 0
59
+ ? Option.some(BigInt(height))
60
+ : Option.none();
61
+ /**
62
+ * Parses a node endpoint.
63
+ *
64
+ * @remarks
65
+ * `new URL` throws on a malformed string — omitting the scheme, for instance — and a throw while constructing a read
66
+ * escapes before any Effect can catch it.
67
+ * @param nodeURL - The configured endpoint.
68
+ * @returns The parsed URL, or `Option.none` when it cannot be parsed.
69
+ */
70
+ const parseNodeURL = (nodeURL) => {
71
+ try {
72
+ return Option.some(new URL(nodeURL));
73
+ }
74
+ catch {
75
+ return Option.none();
76
+ }
77
+ };
78
+ /** Describes a failure in a way that is useful when it surfaces as `Unavailable.lastError`. */
79
+ const readError = (what, cause) => new LivenessReadError({
80
+ message: cause === undefined ? what : `${what}: ${describeCause(cause)}`,
81
+ cause,
82
+ });
83
+ /**
84
+ * Connects to the node with a bounded initial connection.
85
+ *
86
+ * @remarks
87
+ * Separated from {@link makeDefaultLivenessReads} so the caching around it can be tested without a node.
88
+ */
89
+ const connectToNode = (nodeURL) => PolkadotNodeClient.make({ nodeURL, reconnectionTimeout: NODE_CONNECTION_TIMEOUT });
90
+ /**
91
+ * Builds the reads a liveness check compares.
92
+ *
93
+ * @remarks
94
+ * This is the only place the two sources meet, and it exists in `capabilities` rather than in a wallet package so that
95
+ * no wallet has to depend on `node-client` directly.
96
+ *
97
+ * The node client is built once, on the first read that needs it, and then reused. Building one per read repeated the
98
+ * full `ApiPromise` handshake — including the runtime metadata download — on every poll, against a node the wallet
99
+ * does not own, to fetch two numbers. polkadot-js re-fetches metadata only when the api is not already ready
100
+ * (`_loadMeta`), so a reused client pays that cost once per wallet rather than once per poll. The socket itself is
101
+ * still closed between reads by `getFinalizedBlock`, so nothing is held open on the node's behalf.
102
+ *
103
+ * Creation is deferred to the first read rather than done here, because a connection failure at construction must
104
+ * become an {@link IndexerLiveness.Unavailable} verdict. Connecting while the sync stream is being assembled would put
105
+ * that failure in the stream's acquire instead, so an unreachable node would stop the wallet syncing — the one
106
+ * outcome this check must never cause.
107
+ *
108
+ * A failed read leaves the cached client in place. It recovers by itself: `getFinalizedBlock` reconnects through
109
+ * `ensureConnection`, and polkadot-js retries the metadata load on the next connect whenever an earlier one did not
110
+ * complete. Only construction failing leaves nothing cached, and the next read then starts over — so a node that is
111
+ * down when the first poll runs does not switch the check off for the rest of the session.
112
+ *
113
+ * Both failures are flattened into {@link LivenessReadError} so the service is coupled to neither the indexer's GraphQL
114
+ * errors nor the node client's error type.
115
+ * @example
116
+ * ```ts
117
+ * const reads = yield* makeDefaultLivenessReads({
118
+ * indexerClientConnection: { indexerHttpUrl: 'http://localhost:8088/api/v1/graphql' },
119
+ * nodeClientConnection: { nodeURL: 'ws://localhost:9944' },
120
+ * });
121
+ * ```;
122
+ *
123
+ * @param config - Where to reach the indexer and the node.
124
+ * @param makeNodeClient - How to build the node client. Defaults to a real connection; supplying this is how a test
125
+ * exercises the caching without a node.
126
+ * @returns An effect yielding reads suitable for {@link LivenessServiceImpl.make}. Scoped, because the client they share
127
+ * is released when that scope closes.
128
+ */
129
+ export const makeDefaultLivenessReads = (config, makeNodeClient = connectToNode) => Effect.gen(function* () {
130
+ // The scope the reads are built in, so the shared client is released when sync stops rather than when a read ends.
131
+ const scope = yield* Effect.scope;
132
+ // `SynchronizedRef`, not `Ref`: filling the cache is itself an effect, and two concurrent first reads must not race
133
+ // into building two clients — the second would replace the first, whose socket nothing would then close until the
134
+ // scope did.
135
+ const cachedClient = yield* SynchronizedRef.make(Option.none());
136
+ /**
137
+ * Yields the shared client, connecting on the first call.
138
+ *
139
+ * @remarks
140
+ * A failure to build leaves the cache empty, so the next read tries again rather than inheriting a verdict taken
141
+ * once.
142
+ *
143
+ * Uninterruptible, because the poll fails fast: when the sibling indexer read fails, the in-flight node read is
144
+ * interrupted. Without this the interrupt could land between the build completing and the cache write — stranding
145
+ * a fully-built client on the sync-lifetime scope with the cache still empty, once per poll for as long as the
146
+ * indexer stays down. It does not hold back the handshake: the client's bounded wait for the node runs in a child
147
+ * fiber, which takes the interrupt whatever this region's status, so a poll that fails fast abandons a handshake
148
+ * still in progress and its provider is disconnected. Once connected, the build defers the interrupt past its
149
+ * close and the cache write, at most the connection bound, so a built client is always cached. The poll does not
150
+ * wait for that — the service disconnects the read before applying its own timeout.
151
+ */
152
+ const client = (nodeURL) => Effect.uninterruptible(SynchronizedRef.modifyEffect(cachedClient, (current) => Option.match(current, {
153
+ onSome: (existing) => Effect.succeed([existing, current]),
154
+ onNone: () => makeNodeClient(nodeURL).pipe(
155
+ // Extended into the outer scope, not the read's: the client has to outlive the read that built it.
156
+ Scope.extend(scope), Effect.map((built) => [built, Option.some(built)])),
157
+ })));
158
+ /** Resolves the shared client from the configured endpoint — the step both node reads start with. */
159
+ const nodeReader = () => Option.match(parseNodeURL(config.nodeClientConnection.nodeURL), {
160
+ onNone: () => Effect.fail(readError(`Node endpoint is not a valid URL: ${config.nodeClientConnection.nodeURL}`, undefined)),
161
+ onSome: Effect.succeed,
162
+ }).pipe(Effect.flatMap((nodeURL) => client(nodeURL)));
163
+ return {
164
+ indexerTip: () => Effect.gen(function* () {
165
+ const query = yield* BlockHash;
166
+ const { block } = yield* query({ offset: null });
167
+ // A freshly started indexer has ingested nothing, so there is no block to compare against.
168
+ if (block === null || block === undefined) {
169
+ return yield* new LivenessReadError({ message: 'Indexer reported no latest block' });
170
+ }
171
+ return yield* Option.match(parseIndexerHeight(block.height), {
172
+ onNone: () => Effect.fail(new LivenessReadError({
173
+ message: `Indexer reported an unusable block height: ${String(block.height)}`,
174
+ })),
175
+ // The hash comes from the same answer as the height, so the two describe one block. Reading them
176
+ // separately would let a chain that advanced in between pair a height with another block's hash.
177
+ onSome: (height) => Effect.succeed({ height, hash: block.hash }),
178
+ });
179
+ }).pipe(Effect.provide(HttpQueryClient.layer({ url: config.indexerClientConnection.indexerHttpUrl })), Effect.scoped, Effect.catchAll((cause) => cause instanceof LivenessReadError
180
+ ? Effect.fail(cause)
181
+ : Effect.fail(readError('Failed to read the indexer’s latest block', cause)))),
182
+ finalizedBlock: () => nodeReader().pipe(Effect.flatMap((reader) => reader.getFinalizedBlock()),
183
+ // A bound on the whole read, not just the connection: a node that accepts a socket and then never answers would
184
+ // otherwise stall the poll just as effectively as one that refuses it.
185
+ Effect.timeoutFail({
186
+ duration: NODE_CONNECTION_TIMEOUT,
187
+ onTimeout: () => readError('Timed out reading the node’s finalized head', undefined),
188
+ }), Effect.catchAll((cause) => cause instanceof LivenessReadError
189
+ ? Effect.fail(cause)
190
+ : Effect.fail(readError('Failed to read the node’s finalized head', cause)))),
191
+ indexerBlockHashAt: (height) => Effect.gen(function* () {
192
+ const query = yield* BlockHash;
193
+ // `Number` rather than the bigint: the height is one the indexer itself just reported, so it is within the
194
+ // range the indexer's own payload uses.
195
+ const { block } = yield* query({ offset: { height: Number(height) } });
196
+ // Absence, not failure: the caller asked for a height this endpoint claimed to have passed, and "I have no
197
+ // block there" is an answer about the chain rather than a read that went wrong.
198
+ return block === null || block === undefined ? Option.none() : Option.some(block.hash);
199
+ }).pipe(Effect.provide(HttpQueryClient.layer({ url: config.indexerClientConnection.indexerHttpUrl })), Effect.scoped, Effect.catchAll((cause) => cause instanceof LivenessReadError
200
+ ? Effect.fail(cause)
201
+ : Effect.fail(readError(`Failed to read the indexer’s block at height ${height}`, cause)))),
202
+ nodeBlockHashAt: (height) => nodeReader().pipe(Effect.flatMap((reader) => reader.getBlockHashAt(height)), Effect.timeoutFail({
203
+ duration: NODE_CONNECTION_TIMEOUT,
204
+ onTimeout: () => readError(`Timed out reading the node’s block at height ${height}`, undefined),
205
+ }), Effect.catchAll((cause) => cause instanceof LivenessReadError
206
+ ? Effect.fail(cause)
207
+ : Effect.fail(readError(`Failed to read the node’s block at height ${height}`, cause)))),
208
+ indexerGenesisHash: () => Effect.gen(function* () {
209
+ const query = yield* BlockHash;
210
+ const { block } = yield* query({ offset: { height: 0 } });
211
+ // An indexer that has ingested nothing has no genesis block to name — which chain it is on is not yet known.
212
+ if (block === null || block === undefined) {
213
+ return yield* new LivenessReadError({ message: 'Indexer reported no genesis block' });
214
+ }
215
+ return block.hash;
216
+ }).pipe(Effect.provide(HttpQueryClient.layer({ url: config.indexerClientConnection.indexerHttpUrl })), Effect.scoped, Effect.catchAll((cause) => cause instanceof LivenessReadError
217
+ ? Effect.fail(cause)
218
+ : Effect.fail(readError('Failed to read the indexer’s genesis block', cause)))),
219
+ nodeGenesisHash: () => nodeReader().pipe(Effect.flatMap((reader) => reader.getGenesisHash()),
220
+ // The hash itself is served from client state, but the first call builds the client — a connection that
221
+ // must stay bounded like every other node read.
222
+ Effect.timeoutFail({
223
+ duration: NODE_CONNECTION_TIMEOUT,
224
+ onTimeout: () => readError('Timed out reading the node’s genesis hash', undefined),
225
+ }), Effect.catchAll((cause) => cause instanceof LivenessReadError
226
+ ? Effect.fail(cause)
227
+ : Effect.fail(readError('Failed to read the node’s genesis hash', cause)))),
228
+ };
229
+ });
@@ -0,0 +1,137 @@
1
+ import { IndexerLiveness } from '@midnightntwrk/wallet-sdk-abstractions';
2
+ import { Cause, Duration, Effect, Option, Stream } from 'effect';
3
+ declare const LivenessReadError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => Cause.YieldableError & {
4
+ readonly _tag: "LivenessReadError";
5
+ } & Readonly<A>;
6
+ /**
7
+ * A block height could not be read.
8
+ *
9
+ * @remarks
10
+ * The indexer and the node fail in their own vocabularies — a GraphQL error and a `NodeClientError` respectively. Each
11
+ * caller adapts its failure into this one type, so the service depends on neither and needs only what it actually
12
+ * uses: a message to report on an {@link IndexerLiveness.Unavailable} verdict.
13
+ */
14
+ export declare class LivenessReadError extends LivenessReadError_base<{
15
+ /** A short description of why the read failed, surfaced to callers for diagnosis. */
16
+ readonly message: string;
17
+ /** The underlying failure, retained for logging. */
18
+ readonly cause?: unknown;
19
+ }> {
20
+ }
21
+ /**
22
+ * The reads a liveness check runs, supplied as a dictionary so that callers decide where each comes from: the two tips
23
+ * it compares every poll, the block those tips share, and the two genesis hashes it compares once to establish that the
24
+ * tips describe the same chain.
25
+ *
26
+ * @remarks
27
+ * Every read is required. A service is only started when a node endpoint is configured — when none is, no service runs
28
+ * at all and the progress keeps its {@link IndexerLiveness.Skipped} default. That is why no read is optional: a
29
+ * service that might have no node would have to represent, and handle, a state it should never be in.
30
+ *
31
+ * The tips carry hashes as well as heights because a height alone proves nothing — it is a number the indexer chooses.
32
+ * The block at that height is what it cannot invent, so the check compares one block per poll: the newest one both
33
+ * endpoints claim to have passed.
34
+ */
35
+ export type LivenessReads = {
36
+ /** Reads the height and hash of the latest block the indexer reports having processed. */
37
+ readonly indexerTip: () => Effect.Effect<IndexerLiveness.BlockRef, LivenessReadError>;
38
+ /** Reads the height and hash of the node's highest finalized block. */
39
+ readonly finalizedBlock: () => Effect.Effect<IndexerLiveness.BlockRef, LivenessReadError>;
40
+ /**
41
+ * Reads the hash of the indexer's block at a given height, or `Option.none` when it has none there.
42
+ *
43
+ * @remarks
44
+ * Called only for a height the indexer has just claimed to have passed, which is why absence is part of a verdict
45
+ * rather than a failure: an indexer that cannot serve a block it reports having ingested contradicts its own
46
+ * answer.
47
+ */
48
+ readonly indexerBlockHashAt: (height: bigint) => Effect.Effect<Option.Option<string>, LivenessReadError>;
49
+ /**
50
+ * Reads the hash of the node's block at a given height, or `Option.none` when it has none there.
51
+ *
52
+ * @remarks
53
+ * Called only for a height at or below the node's own finalized head, where a canonical chain always has a block — so
54
+ * absence says this node does not have the block being claimed, not that the read went wrong.
55
+ */
56
+ readonly nodeBlockHashAt: (height: bigint) => Effect.Effect<Option.Option<string>, LivenessReadError>;
57
+ /** Reads the hash of the indexer's block at height zero — the chain the indexer is indexing. */
58
+ readonly indexerGenesisHash: () => Effect.Effect<string, LivenessReadError>;
59
+ /** Reads the hash of the node's genesis block — the chain the node is on. */
60
+ readonly nodeGenesisHash: () => Effect.Effect<string, LivenessReadError>;
61
+ };
62
+ /** How far apart the indexer and the node may be before the difference is reported. */
63
+ export type LivenessConfiguration = {
64
+ /** How many blocks the indexer may trail the finalized head by and still count as in sync. */
65
+ readonly maxBehindBlocks: bigint;
66
+ /** How many blocks the indexer may lead the finalized head by and still count as in sync. */
67
+ readonly maxAheadBlocks: bigint;
68
+ /**
69
+ * How long a single poll may run before it is abandoned and reported as {@link IndexerLiveness.Unavailable}.
70
+ *
71
+ * @remarks
72
+ * Defaults to {@link DEFAULT_POLL_TIMEOUT}. Polls run one at a time, so without this bound a read that hangs — an
73
+ * endpoint that accepts a connection and never answers — would stop the loop forever, freezing the verdict at
74
+ * whatever was published last. A hung read must not be able to switch the check off.
75
+ */
76
+ readonly pollTimeout?: Duration.Duration;
77
+ };
78
+ /**
79
+ * The default bound on a single poll.
80
+ *
81
+ * @remarks
82
+ * Comfortably above the node read's own ten-second connection bound, and below the default poll interval, so an
83
+ * abandoned poll never delays the tick that follows it.
84
+ */
85
+ export declare const DEFAULT_POLL_TIMEOUT: Duration.Duration;
86
+ /**
87
+ * Tolerances sized against Midnight's 6-second block slots (the indexer pins `SLOT_DURATION` at 6000 ms).
88
+ *
89
+ * @remarks
90
+ * `maxBehindBlocks` is a staleness allowance: ten blocks is about a minute of chain time, generous enough that an
91
+ * indexer briefly catching up is not reported as stale. `maxAheadBlocks` absorbs read skew — the two heights are read
92
+ * at different moments — while staying far below the thousands of blocks that separate two different networks.
93
+ */
94
+ export declare const DEFAULT_LIVENESS_CONFIGURATION: LivenessConfiguration;
95
+ /**
96
+ * How often to compare the indexer against the node, by default.
97
+ *
98
+ * @remarks
99
+ * Deliberately unhurried. Each poll costs a request to a node the wallet does not own, a stalled indexer is a
100
+ * slow-developing condition, and polling faster than blocks are produced only re-reads the same block. At Midnight's
101
+ * 6-second slots, half a minute is about five blocks, and it surfaces a stalled indexer well within the time any
102
+ * caller would notice.
103
+ */
104
+ export declare const DEFAULT_POLL_INTERVAL: Duration.Duration;
105
+ export type LivenessService = {
106
+ /**
107
+ * Consumes `ticks`, comparing the indexer against the node once per tick and publishing the verdict.
108
+ *
109
+ * @remarks
110
+ * Ticks are supplied by the caller rather than generated here, so that tests drive the loop directly instead of
111
+ * waiting on a clock. The returned effect cannot fail: a read that fails is folded into the verdict by
112
+ * {@link IndexerLiveness.afterFailedPoll} — {@link IndexerLiveness.Unavailable}, or a gating verdict kept as it is —
113
+ * because a check that gave up on its first network error would be useless against exactly the conditions it exists
114
+ * to detect.
115
+ */
116
+ readonly startPolling: (ticks: Stream.Stream<unknown>) => Effect.Effect<void>;
117
+ /** The current verdict, followed by each subsequent one. */
118
+ readonly state: () => Stream.Stream<IndexerLiveness.IndexerLiveness>;
119
+ };
120
+ export declare class LivenessServiceImpl implements LivenessService {
121
+ #private;
122
+ /**
123
+ * Creates a service whose verdict starts as {@link IndexerLiveness.Unknown} — a check exists but has not yet run.
124
+ *
125
+ * @param reads - Where the two heights come from.
126
+ * @param configuration - The tolerances to apply, and the bound on a single poll.
127
+ * @param initialVerdict - The verdict to start from. Callers that rebuild the service mid-session pass the verdict
128
+ * they already hold, so a reconnect does not erase a `Behind` the check had already reached — starting afresh at
129
+ * `Unknown` would hand back a stale-view answer the moment the gate re-opened.
130
+ * @returns An effect yielding the service.
131
+ */
132
+ static make(reads: LivenessReads, configuration?: LivenessConfiguration, initialVerdict?: IndexerLiveness.IndexerLiveness): Effect.Effect<LivenessServiceImpl>;
133
+ private constructor();
134
+ state(): Stream.Stream<IndexerLiveness.IndexerLiveness>;
135
+ startPolling(ticks: Stream.Stream<unknown>): Effect.Effect<void>;
136
+ }
137
+ export {};