@midnightntwrk/wallet-sdk-testkit 1.0.0-rc.1 → 1.0.0-rc.3

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/README.md CHANGED
@@ -104,10 +104,10 @@ written by one model and restored into the other resumes from a position that is
104
104
  never reports synced. Hard-coding `DustWallet(...)` as the restore target while the run uses projections does exactly
105
105
  that.
106
106
 
107
- Snapshots on disk are protected from this automatically: they are stored per model, so switching models finds no
108
- snapshot and rebuilds from scratch rather than resuming wrongly, with no cache to clear by hand. That protection does
109
- not extend to state serialized and restored in memory within a test — hence the rule above. The shielded and unshielded
110
- snapshots are model-independent and shared.
107
+ Snapshots on disk are protected from this automatically: `saveState` writes the shielded and Dust states together, to
108
+ one file per model (`snapshotPath`), so switching models finds no snapshot and rebuilds from scratch rather than
109
+ resuming wrongly, with no cache to clear by hand. The unshielded state is not saved, because a restore never reads it.
110
+ That protection does not extend to state serialized and restored in memory within a test — hence the rule above.
111
111
 
112
112
  ## Peer dependencies
113
113
 
package/dist/core.d.ts CHANGED
@@ -6,3 +6,4 @@ export * from './seeds.js';
6
6
  export * from './primitives.js';
7
7
  export * from './wallet.js';
8
8
  export * from './dust-sync.js';
9
+ export * from './lifecycle.js';
package/dist/core.js CHANGED
@@ -23,3 +23,4 @@ export * from './seeds.js';
23
23
  export * from './primitives.js';
24
24
  export * from './wallet.js';
25
25
  export * from './dust-sync.js';
26
+ export * from './lifecycle.js';
@@ -1,5 +1,4 @@
1
- import { type DustParameters } from '@midnightntwrk/ledger-v9';
2
- import { type DefaultDustConfiguration, type DustWalletAPI } from '@midnightntwrk/wallet-sdk-dust-wallet';
1
+ import { type DefaultDustConfiguration, type DustGenerationRates, type DustKeysByEpoch, type DustWalletAPI } from '@midnightntwrk/wallet-sdk-dust-wallet';
3
2
  /**
4
3
  * The factory shape {@link provideWallet} and the scenarios accept for the dust sub-wallet.
5
4
  *
@@ -11,9 +10,9 @@ import { type DefaultDustConfiguration, type DustWalletAPI } from '@midnightntwr
11
10
  * it picks a variant.
12
11
  */
13
12
  export type DustWalletFactory = (config: DefaultDustConfiguration) => {
14
- startWithSeed(seed: Uint8Array, dustParameters?: DustParameters): DustWalletAPI | Promise<DustWalletAPI>;
13
+ startWithSeed(seed: Uint8Array, dustParameters?: DustGenerationRates): DustWalletAPI<DustKeysByEpoch> | Promise<DustWalletAPI<DustKeysByEpoch>>;
15
14
  /** Also required, because `provideWallet` restores a snapshot into whatever composition it was given. */
16
- restore(serializedState: string): DustWalletAPI;
15
+ restore(serializedState: string): DustWalletAPI<DustKeysByEpoch>;
17
16
  };
18
17
  /**
19
18
  * A dust sub-wallet that syncs from indexer projections instead of the event stream.
@@ -45,7 +44,7 @@ export declare const eventLessDustWallet: DustWalletFactory;
45
44
  * the subscription from a position that is not an event id at all, and because the cursor is trusted rather than
46
45
  * validated, the effect would be silently skipped events rather than an error.
47
46
  *
48
- * Callers do not have to guard against that: dust snapshots are stored per sync model (see {@link dustSnapshotPath}), so
47
+ * Callers do not have to guard against that: dust snapshots are stored per sync model (see {@link snapshotPath}), so
49
48
  * switching a wallet's model finds no snapshot and rebuilds from scratch instead of resuming from a cursor that is not
50
49
  * one.
51
50
  */
@@ -89,15 +88,21 @@ export declare const dustSyncModelFromEnv: (env?: Record<string, string | undefi
89
88
  */
90
89
  export declare const dustWalletFromEnv: (env?: Record<string, string | undefined>, fallback?: DustSyncModel) => DustWalletFactory;
91
90
  /**
92
- * Where the dust sub-wallet's snapshot lives, namespaced by the sync model that wrote it.
91
+ * Where a wallet's snapshot lives, namespaced by the dust sync model that wrote it.
93
92
  *
94
- * The two models disagree on the meaning of the one progress value a snapshot carries, so a snapshot must never be
93
+ * The two models disagree on the meaning of the one progress value a dust state carries, so a snapshot must never be
95
94
  * restored into the other model — see {@link eventBasedDustWallet}. Keeping them in separate files makes a model switch
96
95
  * degrade to a from-scratch build rather than to a wrong resume position, with no cache-clearing step to remember.
97
96
  *
98
- * The shielded and unshielded snapshots are model-independent and are not namespaced.
97
+ * The whole snapshot is namespaced, not only its dust state, because a wallet's sub-wallet states are saved and
98
+ * restored as one: a wallet whose dust state cannot be restored is built from scratch anyway.
99
+ *
100
+ * @param syncCacheDir The directory snapshots are saved to.
101
+ * @param filename The name the wallet is saved under.
102
+ * @param model The dust sync model that produced the snapshot.
103
+ * @returns The snapshot's path.
99
104
  */
100
- export declare const dustSnapshotPath: (syncCacheDir: string, filename: string, model: DustSnapshotModel) => string;
105
+ export declare const snapshotPath: (syncCacheDir: string, filename: string, model: DustSnapshotModel) => string;
101
106
  /**
102
107
  * The projections dust sync, synchronizing in the background like the event-based sync does.
103
108
  *
package/dist/dust-sync.js CHANGED
@@ -10,11 +10,10 @@
10
10
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
11
  // See the License for the specific language governing permissions and
12
12
  // limitations under the License.
13
- import { LedgerParameters } from '@midnightntwrk/ledger-v9';
14
13
  import { makeIndexerChainVersionProbe } from '@midnightntwrk/wallet-sdk-capabilities/chainVersion';
15
- import { asV8DustParameters, CustomForkingDustWallet, DustWallet, makeEventLessSyncCapability, makeEventLessSyncService, } from '@midnightntwrk/wallet-sdk-dust-wallet';
14
+ import { CustomForkingDustWallet, DustWallet, dustVariantConfigurations, } from '@midnightntwrk/wallet-sdk-dust-wallet';
16
15
  import { V1Builder } from '@midnightntwrk/wallet-sdk-dust-wallet/v1';
17
- import { Migration, V2Builder } from '@midnightntwrk/wallet-sdk-dust-wallet/v2';
16
+ import { SyncService, V2Builder } from '@midnightntwrk/wallet-sdk-dust-wallet/v2';
18
17
  /**
19
18
  * A dust sub-wallet that syncs from indexer projections instead of the event stream.
20
19
  *
@@ -36,20 +35,15 @@ import { Migration, V2Builder } from '@midnightntwrk/wallet-sdk-dust-wallet/v2';
36
35
  * while syncing their Dust from projections.
37
36
  */
38
37
  export const eventLessDustWallet = (config) => {
39
- const dustParameters = config.dustParameters ?? LedgerParameters.initialParameters().dust;
40
- return CustomForkingDustWallet({ ...config, chainVersionProbe: config.chainVersionProbe ?? makeIndexerChainVersionProbe(config) }, {
41
- builder: new V1Builder().withDefaults(),
42
- // The one field that cannot be shared: `dustParameters` is a WASM object of whichever ledger module produced it,
43
- // so the V1 variant is handed the ledger-v8 rebuild of the same rates rather than the object itself.
44
- configuration: { ...config, dustParameters: asV8DustParameters(dustParameters) },
45
- }, {
38
+ const { v1, v2, migration } = dustVariantConfigurations(config);
39
+ return CustomForkingDustWallet({ ...config, chainVersionProbe: config.chainVersionProbe ?? makeIndexerChainVersionProbe(config) }, { builder: new V1Builder().withDefaults(), configuration: v1 }, {
46
40
  builder: new V2Builder()
47
41
  .withDefaults()
48
- .withSync(makeEventLessSyncService, makeEventLessSyncCapability)
42
+ .withSync(SyncService.makeEventLessSyncService, SyncService.makeEventLessSyncCapability)
49
43
  // Restated because `withSync` drops it: the seed-to-key derivation a start from a seed needs.
50
44
  .withStartAuxDefaults()
51
- .withMigration(() => Migration.makeCrossLedgerMigration({ dustParameters })),
52
- configuration: config,
45
+ .withMigration(migration),
46
+ configuration: v2,
53
47
  });
54
48
  };
55
49
  /**
@@ -61,7 +55,7 @@ export const eventLessDustWallet = (config) => {
61
55
  * the subscription from a position that is not an event id at all, and because the cursor is trusted rather than
62
56
  * validated, the effect would be silently skipped events rather than an error.
63
57
  *
64
- * Callers do not have to guard against that: dust snapshots are stored per sync model (see {@link dustSnapshotPath}), so
58
+ * Callers do not have to guard against that: dust snapshots are stored per sync model (see {@link snapshotPath}), so
65
59
  * switching a wallet's model finds no snapshot and rebuilds from scratch instead of resuming from a cursor that is not
66
60
  * one.
67
61
  */
@@ -103,15 +97,21 @@ export const dustSyncModelFromEnv = (env = process.env, fallback = 'events') =>
103
97
  */
104
98
  export const dustWalletFromEnv = (env = process.env, fallback = 'events') => dustWalletFor(dustSyncModelFromEnv(env, fallback));
105
99
  /**
106
- * Where the dust sub-wallet's snapshot lives, namespaced by the sync model that wrote it.
100
+ * Where a wallet's snapshot lives, namespaced by the dust sync model that wrote it.
107
101
  *
108
- * The two models disagree on the meaning of the one progress value a snapshot carries, so a snapshot must never be
102
+ * The two models disagree on the meaning of the one progress value a dust state carries, so a snapshot must never be
109
103
  * restored into the other model — see {@link eventBasedDustWallet}. Keeping them in separate files makes a model switch
110
104
  * degrade to a from-scratch build rather than to a wrong resume position, with no cache-clearing step to remember.
111
105
  *
112
- * The shielded and unshielded snapshots are model-independent and are not namespaced.
106
+ * The whole snapshot is namespaced, not only its dust state, because a wallet's sub-wallet states are saved and
107
+ * restored as one: a wallet whose dust state cannot be restored is built from scratch anyway.
108
+ *
109
+ * @param syncCacheDir The directory snapshots are saved to.
110
+ * @param filename The name the wallet is saved under.
111
+ * @param model The dust sync model that produced the snapshot.
112
+ * @returns The snapshot's path.
113
113
  */
114
- export const dustSnapshotPath = (syncCacheDir, filename, model) => `${syncCacheDir}/dust-${model}-${filename}`;
114
+ export const snapshotPath = (syncCacheDir, filename, model) => `${syncCacheDir}/snapshot-${model}-${filename}`;
115
115
  /**
116
116
  * The projections dust sync, synchronizing in the background like the event-based sync does.
117
117
  *
@@ -1,6 +1,20 @@
1
1
  import { type MidnightNetwork, type RemoteNetwork, type ResolvedEndpoints, type WalletTestEnvironment } from './types.js';
2
2
  /** Public service endpoints for each remote network, minus the (caller-supplied) prover URL. */
3
3
  export type RemoteNetworkPreset = Omit<ResolvedEndpoints, 'proverUrl'>;
4
+ /**
5
+ * Reads a network name, such as the `NETWORK` environment variable, as a {@link MidnightNetwork}.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const env = createTestContainersEnvironment({ network: parseMidnightNetwork(process.env['NETWORK']) });
10
+ * ```;
11
+ *
12
+ * @param raw The name to read.
13
+ * @returns The network it names.
14
+ * @throws When `raw` names no network, so a mistyped or missing name is reported as such rather than surfacing later as
15
+ * a failure on endpoints there is no preset for.
16
+ */
17
+ export declare const parseMidnightNetwork: (raw: string | undefined) => MidnightNetwork;
4
18
  /**
5
19
  * Endpoint presets lifted verbatim from the old `TestContainersFixture` getters. The proof server is intentionally
6
20
  * absent — there is no public prover, so every remote environment must be told where to find one.
@@ -12,6 +12,35 @@
12
12
  // limitations under the License.
13
13
  import { InMemoryTransactionHistoryStorage, NetworkId, ProtocolVersion } from '@midnightntwrk/wallet-sdk-abstractions';
14
14
  import { WalletEntrySchema, mergeWalletEntries } from '@midnightntwrk/wallet-sdk-facade';
15
+ // A record rather than a list, so a network added to `MidnightNetwork` fails to compile here until it is listed.
16
+ const midnightNetworks = {
17
+ undeployed: true,
18
+ qanet: true,
19
+ devnet: true,
20
+ preview: true,
21
+ preprod: true,
22
+ stagenet: true,
23
+ };
24
+ const isMidnightNetwork = (raw) => Object.hasOwn(midnightNetworks, raw);
25
+ /**
26
+ * Reads a network name, such as the `NETWORK` environment variable, as a {@link MidnightNetwork}.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * const env = createTestContainersEnvironment({ network: parseMidnightNetwork(process.env['NETWORK']) });
31
+ * ```;
32
+ *
33
+ * @param raw The name to read.
34
+ * @returns The network it names.
35
+ * @throws When `raw` names no network, so a mistyped or missing name is reported as such rather than surfacing later as
36
+ * a failure on endpoints there is no preset for.
37
+ */
38
+ export const parseMidnightNetwork = (raw) => {
39
+ if (raw === undefined || !isMidnightNetwork(raw)) {
40
+ throw new Error(`Unrecognized network: ${String(raw)}`);
41
+ }
42
+ return raw;
43
+ };
15
44
  /**
16
45
  * Endpoint presets lifted verbatim from the old `TestContainersFixture` getters. The proof server is intentionally
17
46
  * absent — there is no public prover, so every remote environment must be told where to find one.
@@ -0,0 +1,57 @@
1
+ import { type SnapshotSource } from './snapshot.js';
2
+ /** A started wallet the lifecycle can snapshot and stop. */
3
+ export type LifecycleWallet = SnapshotSource & {
4
+ readonly wallet: {
5
+ stop(): Promise<void>;
6
+ };
7
+ };
8
+ /** Options for {@link WalletLifecycle.release}. */
9
+ export type ReleaseOptions = {
10
+ /** Directory to snapshot the wallets to before stopping them. Nothing is saved when it is unset or empty. */
11
+ readonly syncCacheDir?: string | undefined;
12
+ /** Whether the wallets are in a position worth saving; pass `shouldPersistState(context)`. */
13
+ readonly persist: boolean;
14
+ };
15
+ /**
16
+ * The wallets one test's `beforeEach` started, for its `afterEach` to save and stop.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * let lifecycle: WalletLifecycle;
21
+ * beforeEach(async () => {
22
+ * const own = createWalletLifecycle();
23
+ * lifecycle = own;
24
+ * wallet = await own.adopt(provideWallet(env, { seed, syncCacheDir, filename }), filename);
25
+ * });
26
+ * afterEach((context) => lifecycle.release({ syncCacheDir, persist: shouldPersistState(context) }));
27
+ * ```;
28
+ */
29
+ export type WalletLifecycle = {
30
+ /**
31
+ * Records a wallet as started, so that {@link WalletLifecycle.release} stops it.
32
+ *
33
+ * @param started The wallet being started.
34
+ * @param filename The name to snapshot it under on release; omit for a wallet that is never saved.
35
+ * @returns The started wallet.
36
+ */
37
+ readonly adopt: <T extends LifecycleWallet>(started: Promise<T>, filename?: string) => Promise<T>;
38
+ /**
39
+ * Saves every adopted wallet that has a filename, when asked to, then stops every adopted wallet.
40
+ *
41
+ * @param options Where to save, and whether to.
42
+ */
43
+ readonly release: (options: ReleaseOptions) => Promise<void>;
44
+ };
45
+ /**
46
+ * Creates the lifecycle for one test's wallets. Create a new one in each `beforeEach`.
47
+ *
48
+ * Release saves every wallet before stopping any, since saving serializes live state, and settles every save and every
49
+ * stop before reporting: one wallet that cannot be saved or stopped never leaves another running. Each failure is
50
+ * reported — one as itself, several as an `AggregateError`.
51
+ *
52
+ * A wallet that finishes starting only after release has run — a `beforeEach` that outlived its timeout, which vitest
53
+ * does not cancel — is stopped as it arrives instead of synchronizing into the next test.
54
+ *
55
+ * @returns An empty lifecycle.
56
+ */
57
+ export declare const createWalletLifecycle: () => WalletLifecycle;
@@ -0,0 +1,61 @@
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 { logger } from './logger.js';
14
+ import { saveState } from './snapshot.js';
15
+ /**
16
+ * Creates the lifecycle for one test's wallets. Create a new one in each `beforeEach`.
17
+ *
18
+ * Release saves every wallet before stopping any, since saving serializes live state, and settles every save and every
19
+ * stop before reporting: one wallet that cannot be saved or stopped never leaves another running. Each failure is
20
+ * reported — one as itself, several as an `AggregateError`.
21
+ *
22
+ * A wallet that finishes starting only after release has run — a `beforeEach` that outlived its timeout, which vitest
23
+ * does not cancel — is stopped as it arrives instead of synchronizing into the next test.
24
+ *
25
+ * @returns An empty lifecycle.
26
+ */
27
+ export const createWalletLifecycle = () => {
28
+ // Mutable by design: this is test teardown bookkeeping, filled in as `beforeEach` starts wallets and closed by
29
+ // `afterEach`.
30
+ const state = { adopted: [], released: false };
31
+ const adopt = async (started, filename) => {
32
+ const wallet = await started;
33
+ if (state.released) {
34
+ const tornDown = 'The wallet finished starting after its test was torn down';
35
+ const stopError = await wallet.wallet.stop().then(() => undefined, (error) => error ?? new Error('stop() rejected without a reason'));
36
+ if (stopError !== undefined)
37
+ throw new AggregateError([stopError], `${tornDown}, and stopping it failed`);
38
+ throw new Error(`${tornDown}, so it has been stopped`);
39
+ }
40
+ state.adopted = [...state.adopted, { wallet, filename }];
41
+ return wallet;
42
+ };
43
+ const release = async ({ syncCacheDir, persist }) => {
44
+ // Only the first release saves and stops: a second would stop wallets that are already stopped.
45
+ if (state.released)
46
+ return;
47
+ state.released = true;
48
+ const { adopted } = state;
49
+ const saves = syncCacheDir && persist
50
+ ? await Promise.allSettled(adopted.flatMap(({ wallet, filename }) => filename === undefined ? [] : [saveState(wallet, syncCacheDir, filename)]))
51
+ : [];
52
+ const stops = await Promise.allSettled(adopted.map(({ wallet }) => wallet.wallet.stop()));
53
+ logger.info('Wallets stopped');
54
+ const failures = [...saves, ...stops].flatMap((result) => result.status === 'rejected' ? [result.reason] : []);
55
+ if (failures.length === 1)
56
+ throw failures[0];
57
+ if (failures.length > 1)
58
+ throw new AggregateError(failures, `${failures.length} wallet saves or stops failed`);
59
+ };
60
+ return { adopt, release };
61
+ };
@@ -19,31 +19,31 @@ import { describe, test, expect, beforeEach, afterEach } from 'vitest';
19
19
  import { inspect } from 'node:util';
20
20
  import * as rx from 'rxjs';
21
21
  import * as ledger from '@midnightntwrk/ledger-v9';
22
- import { provideWallet, saveState, shouldPersistState, withProjectionsDefault, } from '../wallet.js';
22
+ import { provideWallet, shouldPersistState, withProjectionsDefault, } from '../wallet.js';
23
+ import { createWalletLifecycle } from '../lifecycle.js';
23
24
  import { logger } from '../logger.js';
24
25
  /** Registers the dust register/deregister healthchecks under a `describe('Dust tests')` block. */
25
26
  export function registerDustHealthchecks({ getEnv, seed, syncCacheDir, timeout = 900_000, walletOptions, }) {
26
27
  describe('Dust tests', () => {
27
28
  const unshieldedTokenRaw = ledger.unshieldedToken().raw;
28
29
  let wallet;
29
- let filenameWallet;
30
+ let lifecycle;
30
31
  beforeEach(async () => {
32
+ // This hook's own lifecycle, so a wallet that finishes starting after `afterEach` has run is stopped by it.
33
+ const own = createWalletLifecycle();
34
+ lifecycle = own;
31
35
  const env = getEnv();
32
- filenameWallet = `${seed.substring(0, 7)}-${env.network}.state`;
33
- wallet = await provideWallet(env, {
36
+ const filenameWallet = `${seed.substring(0, 7)}-${env.network}.state`;
37
+ wallet = await own.adopt(provideWallet(env, {
34
38
  ...withProjectionsDefault(walletOptions),
35
39
  seed,
36
40
  syncCacheDir,
37
41
  filename: filenameWallet,
38
- });
42
+ }), filenameWallet);
39
43
  });
40
44
  afterEach(async (context) => {
41
45
  // Only a passing test leaves its wallets in a resumable position; see `shouldPersistState`.
42
- if (syncCacheDir && shouldPersistState(context)) {
43
- await saveState(wallet, syncCacheDir, filenameWallet);
44
- }
45
- await wallet.wallet.stop();
46
- logger.info('Wallet stopped');
46
+ await lifecycle.release({ syncCacheDir, persist: shouldPersistState(context) });
47
47
  });
48
48
  test('Able to register Night tokens for Dust generation @healthcheck', async () => {
49
49
  const initialState = await wallet.wallet.waitForSyncedState();
@@ -21,7 +21,8 @@ import { firstValueFrom } from 'rxjs';
21
21
  import { inspect } from 'node:util';
22
22
  import * as ledger from '@midnightntwrk/ledger-v9';
23
23
  import { ProtocolVersion, WalletTransaction } from '@midnightntwrk/wallet-sdk-abstractions';
24
- import { provideWallet, saveState, shouldPersistState, withProjectionsDefault, } from '../wallet.js';
24
+ import { provideWallet, shouldPersistState, withProjectionsDefault, } from '../wallet.js';
25
+ import { createWalletLifecycle } from '../lifecycle.js';
25
26
  import { tNightAmount } from '../primitives.js';
26
27
  import { getShieldedAddress, getUnshieldedAddress } from '../addresses.js';
27
28
  import { waitForFacadePendingClear, waitForTxInHistory } from '../state-waiters.js';
@@ -39,25 +40,27 @@ export function useTokenTransferWallets({ getEnv, fundedSeed, secondSeed, syncCa
39
40
  let wallet;
40
41
  let wallet2;
41
42
  let networkId;
42
- let filenameWallet;
43
- let filenameWallet2;
43
+ let lifecycle;
44
44
  beforeEach(async () => {
45
+ // This hook's own lifecycle, so a wallet that finishes starting after `afterEach` has run is stopped by it.
46
+ const own = createWalletLifecycle();
47
+ lifecycle = own;
45
48
  const env = getEnv();
46
49
  networkId = env.endpoints.networkId;
47
- filenameWallet = `${fundedSeed.substring(0, 7)}-${env.network}.state`;
48
- filenameWallet2 = `${secondSeed.substring(0, 7)}-${env.network}.state`;
49
- wallet = await provideWallet(env, {
50
+ const filenameWallet = `${fundedSeed.substring(0, 7)}-${env.network}.state`;
51
+ const filenameWallet2 = `${secondSeed.substring(0, 7)}-${env.network}.state`;
52
+ wallet = await own.adopt(provideWallet(env, {
50
53
  ...withProjectionsDefault(walletOptions),
51
54
  seed: fundedSeed,
52
55
  syncCacheDir,
53
56
  filename: filenameWallet,
54
- });
55
- wallet2 = await provideWallet(env, {
57
+ }), filenameWallet);
58
+ wallet2 = await own.adopt(provideWallet(env, {
56
59
  ...withProjectionsDefault(walletOptions),
57
60
  seed: secondSeed,
58
61
  syncCacheDir,
59
62
  filename: filenameWallet2,
60
- });
63
+ }), filenameWallet2);
61
64
  logger.info('Two wallets started');
62
65
  const [state1, state2] = await Promise.all([
63
66
  wallet.wallet.waitForSyncedState(),
@@ -79,13 +82,7 @@ export function useTokenTransferWallets({ getEnv, fundedSeed, secondSeed, syncCa
79
82
  }, syncTimeout);
80
83
  afterEach(async (context) => {
81
84
  // Only a passing test leaves its wallets in a resumable position; see `shouldPersistState`.
82
- if (syncCacheDir && shouldPersistState(context)) {
83
- await saveState(wallet, syncCacheDir, filenameWallet);
84
- await saveState(wallet2, syncCacheDir, filenameWallet2);
85
- }
86
- await sender.wallet.stop();
87
- await receiver.wallet.stop();
88
- logger.info('Wallets stopped');
85
+ await lifecycle.release({ syncCacheDir, persist: shouldPersistState(context) });
89
86
  }, timeout);
90
87
  const requireWallet = (w, label) => {
91
88
  if (!w)
@@ -0,0 +1,68 @@
1
+ import type { WalletSeeds } from '@midnightntwrk/wallet-sdk-hd';
2
+ import type { WalletFacade } from '@midnightntwrk/wallet-sdk-facade';
3
+ import { type DustSnapshotModel } from './dust-sync.js';
4
+ /**
5
+ * What a snapshot is taken from: the shielded and dust sub-wallets' serializers, and the dust sync model that produced
6
+ * the dust state, which decides where that state may be restored.
7
+ *
8
+ * The unshielded wallet is not part of a snapshot: a restore starts it from its public key and it synchronizes from
9
+ * genesis, so a serialized state of it would never be read.
10
+ */
11
+ export type SnapshotSource = {
12
+ readonly wallet: {
13
+ readonly shielded: {
14
+ serializeState(): Promise<string>;
15
+ };
16
+ readonly dust: {
17
+ serializeState(): Promise<string>;
18
+ };
19
+ };
20
+ readonly dustSyncModel: DustSnapshotModel;
21
+ };
22
+ /** The serialized states of one wallet, as {@link saveState} wrote them. */
23
+ export type WalletSnapshot = {
24
+ readonly shielded: string;
25
+ readonly dust: string;
26
+ };
27
+ /**
28
+ * Reads back the snapshot {@link saveState} wrote for `filename` under the given dust sync model.
29
+ *
30
+ * @param syncCacheDir The directory the snapshot was saved to.
31
+ * @param filename The name it was saved under.
32
+ * @param model The dust sync model the restored wallet will run.
33
+ * @returns The snapshot, or `undefined` when there is no complete one to restore.
34
+ */
35
+ export declare const readSnapshot: (syncCacheDir: string, filename: string, model: DustSnapshotModel) => Promise<WalletSnapshot | undefined>;
36
+ /**
37
+ * Serializes the shielded and dust sub-wallet states into one snapshot in `syncCacheDir`, keyed by `filename` and by
38
+ * the dust sync model that produced the dust state.
39
+ *
40
+ * The snapshot is written whole under a temporary name and then renamed over the previous one, which replaces it in a
41
+ * single step. A save that fails, or a process killed part-way through one, therefore leaves the previous snapshot as
42
+ * it was — never a mix of two runs that the next run would restore as one wallet.
43
+ *
44
+ * Takes the whole source rather than the facade alone so the snapshot is always written to the namespace of the sync
45
+ * model that produced it — a model and a facade passed separately could disagree.
46
+ *
47
+ * @param walletInit The wallet to snapshot, with the dust sync model it runs.
48
+ * @param syncCacheDir The directory to save to; created if missing.
49
+ * @param filename The name to save under.
50
+ * @throws When a sub-wallet cannot be serialized or the snapshot cannot be written. A test whose state could not be
51
+ * saved must not pass as if it had been.
52
+ */
53
+ export declare const saveState: (walletInit: SnapshotSource, syncCacheDir: string, filename: string) => Promise<void>;
54
+ /**
55
+ * Starts a facade assembled from a snapshot and checks that it synchronizes.
56
+ *
57
+ * @param facade The restored facade, not yet started.
58
+ * @param seeds The seeds to start it with.
59
+ * @param manualSync Whether to start it without background synchronization.
60
+ * @param options How long to wait for the restored facade to catch up; ten minutes unless given.
61
+ * @returns `true` when the restored facade synchronizes; `false`, with the facade stopped, when it cannot or does not
62
+ * catch up in time, so the caller builds from scratch instead.
63
+ * @throws What starting or checking the facade threw, after stopping it, so a failed restore does not leave a facade
64
+ * synchronizing that nothing holds a reference to.
65
+ */
66
+ export declare const startRestoredFacade: (facade: Pick<WalletFacade, "start" | "stop" | "state">, seeds: WalletSeeds, manualSync: boolean, options?: {
67
+ readonly timeoutMs?: number;
68
+ }) => Promise<boolean>;
@@ -0,0 +1,156 @@
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
+ //
14
+ // Writing and reading the wallet snapshots `provideWallet` restores from. Internal to the testkit: `saveState` is
15
+ // re-exported from `wallet.ts`, the rest is not part of the public API.
16
+ import { randomUUID } from 'node:crypto';
17
+ import { existsSync } from 'node:fs';
18
+ import * as fsAsync from 'node:fs/promises';
19
+ import * as rx from 'rxjs';
20
+ import { logger } from './logger.js';
21
+ import { snapshotPath } from './dust-sync.js';
22
+ const readIfExists = async (p) => {
23
+ try {
24
+ if (!existsSync(p))
25
+ return undefined;
26
+ return await fsAsync.readFile(p, 'utf-8');
27
+ }
28
+ catch (err) {
29
+ logger.error(`Failed to read ${p}: ${err instanceof Error ? err.message : String(err)}`);
30
+ return undefined;
31
+ }
32
+ };
33
+ const parseSnapshot = (raw) => {
34
+ try {
35
+ const parsed = JSON.parse(raw);
36
+ if (typeof parsed !== 'object' || parsed === null)
37
+ return undefined;
38
+ if (!('shielded' in parsed && 'dust' in parsed))
39
+ return undefined;
40
+ const { shielded, dust } = parsed;
41
+ return typeof shielded === 'string' && typeof dust === 'string' ? { shielded, dust } : undefined;
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ };
47
+ /**
48
+ * Reads back the snapshot {@link saveState} wrote for `filename` under the given dust sync model.
49
+ *
50
+ * @param syncCacheDir The directory the snapshot was saved to.
51
+ * @param filename The name it was saved under.
52
+ * @param model The dust sync model the restored wallet will run.
53
+ * @returns The snapshot, or `undefined` when there is no complete one to restore.
54
+ */
55
+ export const readSnapshot = async (syncCacheDir, filename, model) => {
56
+ const path = snapshotPath(syncCacheDir, filename, model);
57
+ const raw = await readIfExists(path);
58
+ if (raw === undefined)
59
+ return undefined;
60
+ const snapshot = parseSnapshot(raw);
61
+ if (snapshot === undefined)
62
+ logger.warn(`Ignoring ${path}: not a complete wallet snapshot`);
63
+ return snapshot;
64
+ };
65
+ /**
66
+ * Serializes the shielded and dust sub-wallet states into one snapshot in `syncCacheDir`, keyed by `filename` and by
67
+ * the dust sync model that produced the dust state.
68
+ *
69
+ * The snapshot is written whole under a temporary name and then renamed over the previous one, which replaces it in a
70
+ * single step. A save that fails, or a process killed part-way through one, therefore leaves the previous snapshot as
71
+ * it was — never a mix of two runs that the next run would restore as one wallet.
72
+ *
73
+ * Takes the whole source rather than the facade alone so the snapshot is always written to the namespace of the sync
74
+ * model that produced it — a model and a facade passed separately could disagree.
75
+ *
76
+ * @param walletInit The wallet to snapshot, with the dust sync model it runs.
77
+ * @param syncCacheDir The directory to save to; created if missing.
78
+ * @param filename The name to save under.
79
+ * @throws When a sub-wallet cannot be serialized or the snapshot cannot be written. A test whose state could not be
80
+ * saved must not pass as if it had been.
81
+ */
82
+ export const saveState = async (walletInit, syncCacheDir, filename) => {
83
+ const target = snapshotPath(syncCacheDir, filename, walletInit.dustSyncModel);
84
+ logger.info(`Saving state to ${target}`);
85
+ await fsAsync.mkdir(syncCacheDir, { recursive: true });
86
+ const [shielded, dust] = await Promise.all([
87
+ walletInit.wallet.shielded.serializeState(),
88
+ walletInit.wallet.dust.serializeState(),
89
+ ]);
90
+ const snapshot = { shielded, dust };
91
+ const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`;
92
+ try {
93
+ await fsAsync.writeFile(temporary, JSON.stringify(snapshot), 'utf-8');
94
+ await fsAsync.rename(temporary, target);
95
+ }
96
+ catch (err) {
97
+ // Best effort: a temporary file that cannot be removed is never read, and the error rethrown here is the one that
98
+ // matters.
99
+ await fsAsync.rm(temporary, { force: true }).catch(() => undefined);
100
+ throw err;
101
+ }
102
+ logger.info(`State written to ${target}`);
103
+ };
104
+ /**
105
+ * How long a restored wallet may take to catch up before it is given up on. Well short of the quarter-hour the remote
106
+ * suites allow a `beforeEach`, so a wedged restore still falls back to a from-scratch build inside that budget.
107
+ */
108
+ const RESTORED_SYNC_TIMEOUT_MS = 10 * 60 * 1000;
109
+ /** Resolves `true` once the facade has caught up, or `false` if it has not within `timeoutMs`. */
110
+ const caughtUpWithin = async (wallet, timeoutMs) => await rx
111
+ .firstValueFrom(wallet.state().pipe(rx.throttleTime(5000), rx.tap((state) => {
112
+ const applyGap = state.unshielded.progress.highestTransactionId - state.unshielded.progress.appliedId;
113
+ logger.info(`Wallet facade behind by ${applyGap}`);
114
+ }), rx.filter((state) => state.unshielded.progress.isStrictlyComplete()), rx.timeout({ first: timeoutMs })))
115
+ .then(() => true, (error) => {
116
+ if (error instanceof rx.TimeoutError)
117
+ return false;
118
+ throw error;
119
+ });
120
+ /**
121
+ * Starts a facade assembled from a snapshot and checks that it synchronizes.
122
+ *
123
+ * @param facade The restored facade, not yet started.
124
+ * @param seeds The seeds to start it with.
125
+ * @param manualSync Whether to start it without background synchronization.
126
+ * @param options How long to wait for the restored facade to catch up; ten minutes unless given.
127
+ * @returns `true` when the restored facade synchronizes; `false`, with the facade stopped, when it cannot or does not
128
+ * catch up in time, so the caller builds from scratch instead.
129
+ * @throws What starting or checking the facade threw, after stopping it, so a failed restore does not leave a facade
130
+ * synchronizing that nothing holds a reference to.
131
+ */
132
+ export const startRestoredFacade = async (facade, seeds, manualSync, options = {}) => {
133
+ const timeoutMs = options.timeoutMs ?? RESTORED_SYNC_TIMEOUT_MS;
134
+ const synchronizes = async () => {
135
+ await facade.start(seeds, { manualSync });
136
+ if (!(await caughtUpWithin(facade, timeoutMs))) {
137
+ logger.warn(`Restored wallet did not catch up within ${timeoutMs}ms`);
138
+ return false;
139
+ }
140
+ const restoredWalletState = await rx.firstValueFrom(facade.state());
141
+ const applyGap = restoredWalletState.unshielded.progress.highestTransactionId - restoredWalletState.unshielded.progress.appliedId;
142
+ logger.info(`Apply gap: ${applyGap}`);
143
+ return applyGap >= 0;
144
+ };
145
+ const outcome = await synchronizes().then((ok) => ({ ok }), (error) => ({ ok: false, error }));
146
+ if (!outcome.ok) {
147
+ await facade.stop().catch((stopError) => {
148
+ logger.error(`Failed to stop restored wallet: ${stopError instanceof Error ? stopError.message : String(stopError)}`);
149
+ });
150
+ }
151
+ if ('error' in outcome)
152
+ throw outcome.error;
153
+ if (!outcome.ok)
154
+ logger.warn('Unable to sync restored wallet. Building wallet facade from scratch');
155
+ return outcome.ok;
156
+ };
@@ -34,7 +34,7 @@ export declare const waitForSyncUnshielded: (wallet: UnshieldedWallet) => Promis
34
34
  export declare const waitForFacadePending: (wallet: WalletFacade) => Promise<import("@midnightntwrk/wallet-sdk-facade").FacadeState>;
35
35
  export declare const waitForFacadePendingClear: (wallet: WalletFacade) => Promise<import("@midnightntwrk/wallet-sdk-facade").FacadeState>;
36
36
  export declare const waitForDustBalance: (wallet: WalletFacade, threshold?: bigint) => Promise<import("@midnightntwrk/wallet-sdk-facade").FacadeState>;
37
- export declare const waitForFinalizedShieldedBalance: (wallet: ShieldedWalletAPI) => Promise<import("@midnightntwrk/wallet-sdk-shielded").ShieldedWalletState<string, ledger.FinalizedTransaction>>;
37
+ export declare const waitForFinalizedShieldedBalance: (wallet: ShieldedWalletAPI) => Promise<import("@midnightntwrk/wallet-sdk-shielded").ShieldedWalletState<string>>;
38
38
  export declare const waitForUnshieldedCoinUpdate: (wallet: WalletFacade, initialNumAvailableCoins: number) => Promise<import("@midnightntwrk/wallet-sdk-facade").FacadeState>;
39
39
  export declare const waitForStateAfterDustRegistration: (wallet: WalletFacade, finalizedTx: ledger.FinalizedTransaction) => Promise<import("@midnightntwrk/wallet-sdk-facade").FacadeState>;
40
40
  export declare const waitForRegisteredTokens: (wallet: WalletFacade) => Promise<import("@midnightntwrk/wallet-sdk-facade").FacadeState>;
@@ -56,9 +56,9 @@ export const waitForStableState = (source, predicate, description, settleMs = DE
56
56
  })));
57
57
  };
58
58
  export const waitForSyncUnshielded = (wallet) => rx.firstValueFrom(wallet.state.pipe(rx.throttleTime(5_000), rx.tap((state) => {
59
- const applyGap = state.state.progress.highestTransactionId - state.state.progress.appliedId;
59
+ const applyGap = state.progress.highestTransactionId - state.progress.appliedId;
60
60
  logger.info(`Wallet behind by ${applyGap} indices`);
61
- }), rx.filter((state) => state.state.progress.isStrictlyComplete())));
61
+ }), rx.filter((state) => state.progress.isStrictlyComplete())));
62
62
  export const waitForFacadePending = (wallet) => rx.firstValueFrom(wallet.state().pipe(rx.tap((state) => {
63
63
  const shieldedPending = state.shielded.pendingCoins.length;
64
64
  logger.info(`Shielded wallet pending coins: ${shieldedPending}, waiting for pending coins...`);
package/dist/wallet.d.ts CHANGED
@@ -28,7 +28,7 @@ export interface ProvideWalletOptions {
28
28
  * Explicitly allows `undefined` for pass-through under `exactOptionalPropertyTypes`.
29
29
  */
30
30
  syncCacheDir?: string | undefined;
31
- /** Filename suffix for the three serialized state files. Required when `syncCacheDir` is set. */
31
+ /** Name the snapshot is saved under, within its sync model's namespace. Required when `syncCacheDir` is set. */
32
32
  filename?: string | undefined;
33
33
  /**
34
34
  * Replaces the dust sub-wallet factory. Defaults to whatever `DUST_SYNC` selects (the event-based `DustWallet` when
@@ -60,13 +60,24 @@ export interface ProvideWalletOptions {
60
60
  * @returns The options to hand {@link provideWallet}.
61
61
  */
62
62
  export declare const withProjectionsDefault: (walletOptions: Pick<ProvideWalletOptions, "dustWallet" | "manualSync"> | undefined) => Pick<ProvideWalletOptions, "dustWallet" | "manualSync">;
63
+ /** A wallet {@link provideWallet} has started, and whether it came from a snapshot or was built from scratch. */
64
+ export type ProvidedWallet = WalletInit & {
65
+ readonly restored: boolean;
66
+ };
63
67
  /**
64
68
  * Builds a fully-started {@link WalletFacade} (shielded + unshielded + dust) for the given seed.
65
69
  *
66
70
  * If `syncCacheDir`/`filename` are provided, attempts to restore serialized state from disk and verify it syncs;
67
71
  * otherwise (or on any restore failure) builds from scratch via {@link initWalletWithSeed}.
72
+ *
73
+ * The result says which happened. A restore that fails falls back silently, so a test about restoring must check
74
+ * `restored` rather than infer it from balances a from-scratch build would reach too.
75
+ *
76
+ * @param env The environment to build the wallet against.
77
+ * @param options The seed, and where to look for a snapshot.
78
+ * @returns The started wallet, and whether it was restored from the snapshot.
68
79
  */
69
- export declare const provideWallet: (env: WalletTestEnvironment, options: ProvideWalletOptions) => Promise<WalletInit>;
80
+ export declare const provideWallet: (env: WalletTestEnvironment, options: ProvideWalletOptions) => Promise<ProvidedWallet>;
70
81
  /**
71
82
  * Whether the test that has just finished is safe to persist wallet state from.
72
83
  *
@@ -84,13 +95,7 @@ export declare const shouldPersistState: (context: {
84
95
  };
85
96
  };
86
97
  }) => boolean;
87
- /**
88
- * Serializes all three sub-wallet states into `syncCacheDir`, keyed by `filename`.
89
- *
90
- * Takes the whole {@link WalletInit} rather than the facade alone so the dust snapshot is always written to the
91
- * namespace of the sync model that produced it — a model and a facade passed separately could disagree.
92
- */
93
- export declare const saveState: (walletInit: Pick<WalletInit, "wallet" | "dustSyncModel">, syncCacheDir: string, filename: string) => Promise<void>;
98
+ export { saveState, type SnapshotSource } from './snapshot.js';
94
99
  /** Options for {@link initWalletWithSeed}, a subset of {@link ProvideWalletOptions}. */
95
100
  export type InitWalletOptions = Pick<ProvideWalletOptions, 'dustWallet' | 'manualSync'>;
96
101
  /** Builds and starts a fresh {@link WalletFacade} from `seed`, with no disk persistence. */
package/dist/wallet.js CHANGED
@@ -10,9 +10,6 @@
10
10
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
11
  // See the License for the specific language governing permissions and
12
12
  // limitations under the License.
13
- import * as rx from 'rxjs';
14
- import { existsSync } from 'node:fs';
15
- import * as fsAsync from 'node:fs/promises';
16
13
  import * as ledger from '@midnightntwrk/ledger-v9';
17
14
  import { InMemoryTransactionHistoryStorage, } from '@midnightntwrk/wallet-sdk-abstractions';
18
15
  import { ShieldedWallet } from '@midnightntwrk/wallet-sdk-shielded';
@@ -20,71 +17,58 @@ import { WalletFacade, WalletEntrySchema, mergeWalletEntries } from '@midnightnt
20
17
  import { createKeystore, PublicKey, UnshieldedWallet, } from '@midnightntwrk/wallet-sdk-unshielded-wallet';
21
18
  import { logger } from './logger.js';
22
19
  import { getDustSeed, getShieldedSeed, getUnshieldedSeed } from './seeds.js';
23
- import { dustSnapshotPath, dustSyncModelOf, dustWalletFromEnv, } from './dust-sync.js';
24
- const waitForSyncProgress = async (wallet) => await rx.firstValueFrom(wallet.state().pipe(rx.throttleTime(5000), rx.tap((state) => {
25
- const applyGap = state.unshielded.progress.highestTransactionId - state.unshielded.progress.appliedId;
26
- logger.info(`Wallet facade behind by ${applyGap}`);
27
- }), rx.filter((state) => state.unshielded.progress.isStrictlyComplete())));
28
- const restoreShieldedWallet = async (path, Wallet, readIfExists) => {
20
+ import { readSnapshot, startRestoredFacade } from './snapshot.js';
21
+ import { dustSyncModelOf, dustWalletFromEnv } from './dust-sync.js';
22
+ const restoreShieldedWallet = (serialized, Wallet) => {
29
23
  try {
30
- const serialized = await readIfExists(path);
31
- if (serialized) {
32
- const wallet = Wallet.restore(serialized);
33
- logger.info(`Restored shielded wallet from ${path}`);
34
- return wallet;
35
- }
36
- logger.warn('Unable to restore shielded wallet.');
24
+ const wallet = Wallet.restore(serialized);
25
+ logger.info('Restored shielded wallet');
26
+ return wallet;
37
27
  }
38
28
  catch (err) {
39
29
  logger.error(`Failed to restore shielded wallet: ${err instanceof Error ? err.message : String(err)}`);
30
+ return undefined;
40
31
  }
41
- return undefined;
42
32
  };
43
- const restoreUnshieldedWallet = async (path, seed, env, readIfExists, txHistoryStorage) => {
33
+ // The unshielded snapshot is only checked for, not read: the wallet is started from its public key and synchronizes
34
+ // from genesis.
35
+ const restoreUnshieldedWallet = async (seed, env, txHistoryStorage) => {
44
36
  try {
45
- const serialized = await readIfExists(path);
46
- if (serialized) {
47
- const keyStore = createKeystore({ kind: 'schnorr', secret: getUnshieldedSeed(seed) }, env.endpoints.networkId);
48
- const wallet = await UnshieldedWallet({
49
- networkId: env.endpoints.networkId,
50
- indexerClientConnection: {
51
- indexerHttpUrl: env.endpoints.indexerHttpUrl,
52
- indexerWsUrl: env.endpoints.indexerWsUrl,
53
- },
54
- txHistoryStorage,
55
- // The same boundary the shielded configuration names, taken from the one place this environment defines it.
56
- forks: env.getWalletConfig().forks,
57
- }).startWithPublicKey(PublicKey.fromKeyStore(keyStore));
58
- logger.info(`Restored unshielded wallet from ${path}`);
59
- return wallet;
60
- }
61
- logger.warn('Unable to restore unshielded wallet.');
37
+ const keyStore = createKeystore({ kind: 'schnorr', secret: getUnshieldedSeed(seed) }, env.endpoints.networkId);
38
+ const wallet = await UnshieldedWallet({
39
+ networkId: env.endpoints.networkId,
40
+ indexerClientConnection: {
41
+ indexerHttpUrl: env.endpoints.indexerHttpUrl,
42
+ indexerWsUrl: env.endpoints.indexerWsUrl,
43
+ },
44
+ txHistoryStorage,
45
+ // The same boundary the shielded configuration names, taken from the one place this environment defines it.
46
+ forks: env.getWalletConfig().forks,
47
+ }).startWithPublicKey(PublicKey.fromKeyStore(keyStore));
48
+ logger.info('Restored unshielded wallet');
49
+ return wallet;
62
50
  }
63
51
  catch (err) {
64
52
  logger.error(`Failed to restore unshielded wallet: ${err instanceof Error ? err.message : String(err)}`);
53
+ return undefined;
65
54
  }
66
- return undefined;
67
55
  };
68
- const restoreDustWallet = async (path, walletConfig, readIfExists, dustWallet) => {
56
+ const restoreDustWallet = (serialized, walletConfig, dustWallet) => {
69
57
  try {
70
- const serialized = await readIfExists(path);
71
- if (serialized) {
72
- const DustInstance = dustWallet({
73
- ...walletConfig,
74
- costParameters: walletConfig?.costParameters ?? {
75
- feeBlocksMargin: 5,
76
- },
77
- });
78
- const wallet = DustInstance.restore(serialized);
79
- logger.info(`Restored dust wallet from ${path}`);
80
- return wallet;
81
- }
82
- logger.warn('Unable to restore dust wallet.');
58
+ const DustInstance = dustWallet({
59
+ ...walletConfig,
60
+ costParameters: walletConfig?.costParameters ?? {
61
+ feeBlocksMargin: 5,
62
+ },
63
+ });
64
+ const wallet = DustInstance.restore(serialized);
65
+ logger.info('Restored dust wallet');
66
+ return wallet;
83
67
  }
84
68
  catch (err) {
85
69
  logger.error(`Failed to restore dust wallet: ${err instanceof Error ? err.message : String(err)}`);
70
+ return undefined;
86
71
  }
87
- return undefined;
88
72
  };
89
73
  /**
90
74
  * Scenario wallet options with the projections default filled in **per field** rather than wholesale.
@@ -111,6 +95,13 @@ export const withProjectionsDefault = (walletOptions) => ({
111
95
  *
112
96
  * If `syncCacheDir`/`filename` are provided, attempts to restore serialized state from disk and verify it syncs;
113
97
  * otherwise (or on any restore failure) builds from scratch via {@link initWalletWithSeed}.
98
+ *
99
+ * The result says which happened. A restore that fails falls back silently, so a test about restoring must check
100
+ * `restored` rather than infer it from balances a from-scratch build would reach too.
101
+ *
102
+ * @param env The environment to build the wallet against.
103
+ * @param options The seed, and where to look for a snapshot.
104
+ * @returns The started wallet, and whether it was restored from the snapshot.
114
105
  */
115
106
  export const provideWallet = async (env, options) => {
116
107
  const { seed, syncCacheDir, filename, manualSync } = options;
@@ -119,9 +110,18 @@ export const provideWallet = async (env, options) => {
119
110
  const dustWallet = options.dustWallet ?? dustWalletFromEnv();
120
111
  const dustSyncModel = dustSyncModelOf(dustWallet);
121
112
  const fromScratch = { dustWallet, manualSync };
113
+ const buildFromScratch = async () => ({
114
+ ...(await initWalletWithSeed(env, seed, fromScratch)),
115
+ restored: false,
116
+ });
122
117
  if (!syncCacheDir || !filename) {
123
118
  logger.info('No sync cache configured; building wallet facade from scratch');
124
- return initWalletWithSeed(env, seed, fromScratch);
119
+ return buildFromScratch();
120
+ }
121
+ const snapshot = await readSnapshot(syncCacheDir, filename, dustSyncModel);
122
+ if (!snapshot) {
123
+ logger.info(`No snapshot for ${filename} in ${syncCacheDir}; building wallet facade from scratch`);
124
+ return buildFromScratch();
125
125
  }
126
126
  // Single shared tx-history storage so all three sub-wallets and the facade read/write
127
127
  // the same instance; otherwise shielded/unshielded writes go to a storage the facade
@@ -138,52 +138,35 @@ export const provideWallet = async (env, options) => {
138
138
  const shieldedSecretKeys = ledger.ZswapSecretKeys.fromSeed(seeds.shielded);
139
139
  const dustSecretKey = ledger.DustSecretKey.fromSeed(seeds.dust);
140
140
  const unshieldedKeystore = createKeystore({ kind: 'schnorr', secret: seeds.unshielded }, env.endpoints.networkId);
141
- const readIfExists = async (p) => {
142
- try {
143
- if (!existsSync(p))
144
- return undefined;
145
- return await fsAsync.readFile(p, 'utf-8');
146
- }
147
- catch (err) {
148
- logger.error(`Failed to read ${p}: ${err instanceof Error ? err.message : String(err)}`);
149
- return undefined;
150
- }
151
- };
152
- const [restoredShielded, restoredUnshielded, restoredDust] = await Promise.all([
153
- restoreShieldedWallet(`${syncCacheDir}/shielded-${filename}`, Wallet, readIfExists),
154
- restoreUnshieldedWallet(`${syncCacheDir}/unshielded-${filename}`, seed, env, readIfExists, txHistoryStorage),
155
- restoreDustWallet(dustSnapshotPath(syncCacheDir, filename, dustSyncModel), { ...walletConfig, ...dustWalletConfig }, readIfExists, dustWallet),
156
- ]);
141
+ const restoredShielded = restoreShieldedWallet(snapshot.shielded, Wallet);
142
+ const restoredUnshielded = await restoreUnshieldedWallet(seed, env, txHistoryStorage);
143
+ const restoredDust = restoreDustWallet(snapshot.dust, { ...walletConfig, ...dustWalletConfig }, dustWallet);
157
144
  if (!restoredShielded || !restoredUnshielded || !restoredDust) {
158
145
  logger.info('Building wallet facade from scratch');
159
- return initWalletWithSeed(env, seed, fromScratch);
146
+ return buildFromScratch();
160
147
  }
161
- else {
162
- const restoredWallet = await WalletFacade.init({
163
- configuration: {
164
- ...walletConfig,
165
- ...dustWalletConfig,
166
- },
167
- shielded: () => restoredShielded,
168
- unshielded: () => restoredUnshielded,
169
- dust: () => restoredDust,
170
- });
171
- await restoredWallet.start(seeds, { manualSync: manualSync ?? false });
172
- // check if wallet is syncing correctly
173
- await waitForSyncProgress(restoredWallet);
174
- const restoredWalletState = await rx.firstValueFrom(restoredWallet.state());
175
- const applyGap = restoredWalletState.unshielded.progress.highestTransactionId - restoredWalletState.unshielded.progress.appliedId;
176
- logger.info(`Apply gap: ${applyGap}`);
177
- if ((applyGap ?? 0) < 0) {
178
- logger.warn('Unable to sync restored wallet. Building wallet facade from scratch');
179
- await restoredWallet.stop();
180
- return initWalletWithSeed(env, seed, fromScratch);
181
- }
182
- else {
183
- logger.info('Successfully restored wallet facade.');
184
- return { wallet: restoredWallet, shieldedSecretKeys, dustSecretKey, seeds, unshieldedKeystore, dustSyncModel };
185
- }
148
+ const restoredWallet = await WalletFacade.init({
149
+ configuration: {
150
+ ...walletConfig,
151
+ ...dustWalletConfig,
152
+ },
153
+ shielded: () => restoredShielded,
154
+ unshielded: () => restoredUnshielded,
155
+ dust: () => restoredDust,
156
+ });
157
+ if (!(await startRestoredFacade(restoredWallet, seeds, manualSync ?? false))) {
158
+ return buildFromScratch();
186
159
  }
160
+ logger.info('Successfully restored wallet facade.');
161
+ return {
162
+ wallet: restoredWallet,
163
+ shieldedSecretKeys,
164
+ dustSecretKey,
165
+ seeds,
166
+ unshieldedKeystore,
167
+ dustSyncModel,
168
+ restored: true,
169
+ };
187
170
  };
188
171
  /**
189
172
  * Whether the test that has just finished is safe to persist wallet state from.
@@ -196,50 +179,7 @@ export const provideWallet = async (env, options) => {
196
179
  * Pass the `afterEach` context: `afterEach((ctx) => { if (shouldPersistState(ctx)) await saveState(...) })`.
197
180
  */
198
181
  export const shouldPersistState = (context) => context.task.result?.state === 'pass';
199
- /**
200
- * Serializes all three sub-wallet states into `syncCacheDir`, keyed by `filename`.
201
- *
202
- * Takes the whole {@link WalletInit} rather than the facade alone so the dust snapshot is always written to the
203
- * namespace of the sync model that produced it — a model and a facade passed separately could disagree.
204
- */
205
- export const saveState = async (walletInit, syncCacheDir, filename) => {
206
- logger.info(`Saving state in ${syncCacheDir}/${filename}`);
207
- try {
208
- await fsAsync.mkdir(syncCacheDir, { recursive: true });
209
- // Serialize all three states
210
- const [shieldedSerializedState, unshieldedSerializedState, dustSerializedState] = await Promise.all([
211
- walletInit.wallet.shielded.serializeState(),
212
- walletInit.wallet.unshielded.serializeState(),
213
- walletInit.wallet.dust.serializeState(),
214
- ]);
215
- const files = [
216
- { path: `${syncCacheDir}/shielded-${filename}`, data: shieldedSerializedState },
217
- { path: `${syncCacheDir}/unshielded-${filename}`, data: unshieldedSerializedState },
218
- { path: dustSnapshotPath(syncCacheDir, filename, walletInit.dustSyncModel), data: dustSerializedState },
219
- ];
220
- const results = await Promise.allSettled(files.map((f) => fsAsync.writeFile(f.path, f.data, 'utf-8')));
221
- for (const [i, res] of results.entries()) {
222
- const pathWritten = files[i].path;
223
- if (res.status === 'fulfilled') {
224
- logger.info(`State written to file ${pathWritten}`);
225
- }
226
- else {
227
- logger.error(`Failed to write ${pathWritten}: ${res.reason instanceof Error ? res.reason.message : String(res.reason)}`);
228
- }
229
- }
230
- }
231
- catch (e) {
232
- if (typeof e === 'string') {
233
- logger.warn(e);
234
- }
235
- else if (e instanceof Error) {
236
- logger.warn(e.message);
237
- }
238
- else {
239
- logger.warn('Unknown error while saving state');
240
- }
241
- }
242
- };
182
+ export { saveState } from './snapshot.js';
243
183
  /** Builds and starts a fresh {@link WalletFacade} from `seed`, with no disk persistence. */
244
184
  export const initWalletWithSeed = async (env, seed, options = {}) => {
245
185
  const dustWalletClass = options.dustWallet ?? dustWalletFromEnv();
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@midnightntwrk/wallet-sdk-testkit",
3
3
  "description": "Reusable wallet-SDK test harness: environment provisioning, wallet bootstrapping, sync waiters and tx-history assertions",
4
- "version": "1.0.0-rc.1",
4
+ "version": "1.0.0-rc.3",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.js",
@@ -39,22 +39,23 @@
39
39
  }
40
40
  },
41
41
  "dependencies": {
42
- "@midnightntwrk/ledger-v9": "1.0.0-rc.5",
43
- "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-rc.1",
44
- "@midnightntwrk/wallet-sdk-address-format": "4.0.0-rc.0",
45
- "@midnightntwrk/wallet-sdk-capabilities": "4.0.0-rc.1",
46
- "@midnightntwrk/wallet-sdk-dust-wallet": "5.0.0-rc.1",
47
- "@midnightntwrk/wallet-sdk-facade": "5.0.0-rc.1",
48
- "@midnightntwrk/wallet-sdk-hd": "3.1.0-rc.0",
49
- "@midnightntwrk/wallet-sdk-indexer-client": "2.0.0-rc.1",
50
- "@midnightntwrk/wallet-sdk-shielded": "4.0.0-rc.1",
51
- "@midnightntwrk/wallet-sdk-unshielded-wallet": "4.0.0-rc.1",
42
+ "@midnightntwrk/ledger-v9": "1.0.0-rc.7",
43
+ "@midnightntwrk/wallet-sdk-abstractions": "3.0.0-rc.2",
44
+ "@midnightntwrk/wallet-sdk-address-format": "4.0.0-rc.2",
45
+ "@midnightntwrk/wallet-sdk-capabilities": "4.0.0-rc.2",
46
+ "@midnightntwrk/wallet-sdk-dust-wallet": "5.0.0-rc.3",
47
+ "@midnightntwrk/wallet-sdk-facade": "5.0.0-rc.3",
48
+ "@midnightntwrk/wallet-sdk-hd": "4.0.0-rc.1",
49
+ "@midnightntwrk/wallet-sdk-indexer-client": "2.0.0-rc.2",
50
+ "@midnightntwrk/wallet-sdk-shielded": "4.0.0-rc.3",
51
+ "@midnightntwrk/wallet-sdk-unshielded-wallet": "4.0.0-rc.3",
52
+ "effect": "^3.19.19",
52
53
  "pino": "^10.3.1",
53
54
  "pino-pretty": "^13.1.3",
54
55
  "rxjs": "^7.8.2"
55
56
  },
56
57
  "peerDependencies": {
57
- "@midnightntwrk/wallet-sdk-utilities": "1.2.2-rc.0",
58
+ "@midnightntwrk/wallet-sdk-utilities": "1.3.0-rc.1",
58
59
  "testcontainers": "^11.12.0",
59
60
  "vitest": "^4.1.4"
60
61
  },
@@ -71,7 +72,7 @@
71
72
  "rimraf": "6.1.3",
72
73
  "testcontainers": "11.14.0",
73
74
  "typescript": "5.9.3",
74
- "vitest": "4.1.11"
75
+ "vitest": "4.1.12"
75
76
  },
76
77
  "scripts": {
77
78
  "typecheck": "tsc -b ./tsconfig.json --noEmit --force",