@midnightntwrk/wallet-sdk-testkit 1.0.1-rc.0 → 1.0.1

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.
@@ -9,8 +9,17 @@ export type LifecycleWallet = SnapshotSource & {
9
9
  export type ReleaseOptions = {
10
10
  /** Directory to snapshot the wallets to before stopping them. Nothing is saved when it is unset or empty. */
11
11
  readonly syncCacheDir?: string | undefined;
12
- /** Whether the wallets are in a position worth saving; pass `shouldPersistState(context)`. */
12
+ /**
13
+ * Whether the wallets are in a position worth saving; pass `shouldPersistState(context)`. When it is false, the
14
+ * snapshot each wallet would have been saved to is deleted instead, so the next run does not restore a snapshot that
15
+ * may be why this test failed.
16
+ */
13
17
  readonly persist: boolean;
18
+ /**
19
+ * Whether vitest will run the test again; pass `willRetry(context)`. A test that did not pass but will be retried
20
+ * keeps its snapshots for the retry to restore.
21
+ */
22
+ readonly willRetry?: boolean;
14
23
  };
15
24
  /**
16
25
  * The wallets one test's `beforeEach` started, for its `afterEach` to save and stop.
@@ -36,7 +45,8 @@ export type WalletLifecycle = {
36
45
  */
37
46
  readonly adopt: <T extends LifecycleWallet>(started: Promise<T>, filename?: string) => Promise<T>;
38
47
  /**
39
- * Saves every adopted wallet that has a filename, when asked to, then stops every adopted wallet.
48
+ * Saves every adopted wallet that has a filename when asked to, or deletes its snapshot when not, then stops every
49
+ * adopted wallet.
40
50
  *
41
51
  * @param options Where to save, and whether to.
42
52
  */
package/dist/lifecycle.js CHANGED
@@ -11,7 +11,12 @@
11
11
  // See the License for the specific language governing permissions and
12
12
  // limitations under the License.
13
13
  import { logger } from './logger.js';
14
- import { saveState } from './snapshot.js';
14
+ import { removeState, saveState } from './snapshot.js';
15
+ /**
16
+ * Every namespace a snapshot can be saved in. A wallet that has not finished starting has not said which sync model it
17
+ * runs, so its snapshot is deleted from all of them. Keyed by the type so that a new model cannot be left out.
18
+ */
19
+ const snapshotModels = { events: null, projections: null, custom: null };
15
20
  /**
16
21
  * Creates the lifecycle for one test's wallets. Create a new one in each `beforeEach`.
17
22
  *
@@ -27,9 +32,19 @@ import { saveState } from './snapshot.js';
27
32
  export const createWalletLifecycle = () => {
28
33
  // Mutable by design: this is test teardown bookkeeping, filled in as `beforeEach` starts wallets and closed by
29
34
  // `afterEach`.
30
- const state = { adopted: [], released: false };
35
+ const state = {
36
+ adopted: [],
37
+ starting: [],
38
+ released: false,
39
+ };
31
40
  const adopt = async (started, filename) => {
32
- const wallet = await started;
41
+ // Recorded before the wait, so a test torn down while this wallet is still restoring can delete its snapshot: a
42
+ // restore that never finishes is the likeliest reason the test failed.
43
+ const starting = filename === undefined ? [] : [{ filename }];
44
+ state.starting = [...state.starting, ...starting];
45
+ const wallet = await started.finally(() => {
46
+ state.starting = state.starting.filter((entry) => !starting.includes(entry));
47
+ });
33
48
  if (state.released) {
34
49
  const tornDown = 'The wallet finished starting after its test was torn down';
35
50
  const stopError = await wallet.wallet.stop().then(() => undefined, (error) => error ?? new Error('stop() rejected without a reason'));
@@ -40,22 +55,30 @@ export const createWalletLifecycle = () => {
40
55
  state.adopted = [...state.adopted, { wallet, filename }];
41
56
  return wallet;
42
57
  };
43
- const release = async ({ syncCacheDir, persist }) => {
58
+ const release = async ({ syncCacheDir, persist, willRetry = false }) => {
44
59
  // Only the first release saves and stops: a second would stop wallets that are already stopped.
45
60
  if (state.released)
46
61
  return;
47
62
  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
- : [];
63
+ const { adopted, starting } = state;
64
+ // Type cast required because: `Object.keys` returns `string[]`, and these are exactly the record's typed keys.
65
+ const models = Object.keys(snapshotModels);
66
+ const snapshotWork = (dir) => persist
67
+ ? adopted.flatMap(({ wallet, filename }) => (filename === undefined ? [] : [saveState(wallet, dir, filename)]))
68
+ : willRetry
69
+ ? []
70
+ : [
71
+ ...adopted.flatMap(({ wallet, filename }) => filename === undefined ? [] : [removeState(wallet, dir, filename)]),
72
+ ...starting.flatMap(({ filename }) => models.map((dustSyncModel) => removeState({ dustSyncModel }, dir, filename))),
73
+ ];
74
+ const snapshots = syncCacheDir ? await Promise.allSettled(snapshotWork(syncCacheDir)) : [];
52
75
  const stops = await Promise.allSettled(adopted.map(({ wallet }) => wallet.wallet.stop()));
53
76
  logger.info('Wallets stopped');
54
- const failures = [...saves, ...stops].flatMap((result) => result.status === 'rejected' ? [result.reason] : []);
77
+ const failures = [...snapshots, ...stops].flatMap((result) => result.status === 'rejected' ? [result.reason] : []);
55
78
  if (failures.length === 1)
56
79
  throw failures[0];
57
80
  if (failures.length > 1)
58
- throw new AggregateError(failures, `${failures.length} wallet saves or stops failed`);
81
+ throw new AggregateError(failures, `${failures.length} wallet snapshot writes, deletions or stops failed`);
59
82
  };
60
83
  return { adopt, release };
61
84
  };
@@ -19,7 +19,7 @@ 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, shouldPersistState, withProjectionsDefault, } from '../wallet.js';
22
+ import { provideWallet, shouldPersistState, willRetry, withProjectionsDefault, } from '../wallet.js';
23
23
  import { createWalletLifecycle } from '../lifecycle.js';
24
24
  import { logger } from '../logger.js';
25
25
  /** Registers the dust register/deregister healthchecks under a `describe('Dust tests')` block. */
@@ -33,7 +33,9 @@ export function registerDustHealthchecks({ getEnv, seed, syncCacheDir, timeout =
33
33
  const own = createWalletLifecycle();
34
34
  lifecycle = own;
35
35
  const env = getEnv();
36
- const filenameWallet = `${seed.substring(0, 7)}-${env.network}.state`;
36
+ // A name of its own, apart from the token-transfer scenario's snapshot of the same seed: a dust test that fails
37
+ // deletes the snapshot it started from, and must not take the token-transfer wallet's with it.
38
+ const filenameWallet = `dust-${seed.substring(0, 7)}-${env.network}.state`;
37
39
  wallet = await own.adopt(provideWallet(env, {
38
40
  ...withProjectionsDefault(walletOptions),
39
41
  seed,
@@ -42,8 +44,13 @@ export function registerDustHealthchecks({ getEnv, seed, syncCacheDir, timeout =
42
44
  }), filenameWallet);
43
45
  });
44
46
  afterEach(async (context) => {
45
- // Only a passing test leaves its wallets in a resumable position; see `shouldPersistState`.
46
- await lifecycle.release({ syncCacheDir, persist: shouldPersistState(context) });
47
+ // Only a passing test leaves its wallets in a resumable position; see `shouldPersistState`. A failed attempt that
48
+ // vitest will retry keeps their snapshots for the retry to restore.
49
+ await lifecycle.release({
50
+ syncCacheDir,
51
+ persist: shouldPersistState(context),
52
+ willRetry: willRetry(context),
53
+ });
47
54
  });
48
55
  test('Able to register Night tokens for Dust generation @healthcheck', async () => {
49
56
  const initialState = await wallet.wallet.waitForSyncedState();
@@ -13,7 +13,9 @@ export interface TokenTransferScenarioDeps {
13
13
  syncCacheDir?: string | undefined;
14
14
  /**
15
15
  * Timeout for the sync-heavy `beforeEach` and the healthcheck test in ms. Defaults to 15 minutes — a longer bound
16
- * does not rescue a wedged wallet, it only spends lane time before reporting.
16
+ * does not rescue a wedged wallet, it only spends lane time before reporting. The `beforeEach` restores the two
17
+ * wallets one after the other and gives each up to 10 minutes to catch up before building it from scratch, so a bound
18
+ * that is to replace two snapshots that never catch up needs about 20 minutes plus a sync from scratch.
17
19
  */
18
20
  syncTimeout?: number | undefined;
19
21
  /** Timeout for the `afterEach` teardown in ms. Defaults to 10 minutes. */
@@ -21,7 +21,7 @@ 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, shouldPersistState, withProjectionsDefault, } from '../wallet.js';
24
+ import { provideWallet, shouldPersistState, willRetry, withProjectionsDefault, } from '../wallet.js';
25
25
  import { createWalletLifecycle } from '../lifecycle.js';
26
26
  import { tNightAmount } from '../primitives.js';
27
27
  import { getShieldedAddress, getUnshieldedAddress } from '../addresses.js';
@@ -81,8 +81,13 @@ export function useTokenTransferWallets({ getEnv, fundedSeed, secondSeed, syncCa
81
81
  }
82
82
  }, syncTimeout);
83
83
  afterEach(async (context) => {
84
- // Only a passing test leaves its wallets in a resumable position; see `shouldPersistState`.
85
- await lifecycle.release({ syncCacheDir, persist: shouldPersistState(context) });
84
+ // Only a passing test leaves its wallets in a resumable position; see `shouldPersistState`. A failed attempt that
85
+ // vitest will retry keeps their snapshots for the retry to restore.
86
+ await lifecycle.release({
87
+ syncCacheDir,
88
+ persist: shouldPersistState(context),
89
+ willRetry: willRetry(context),
90
+ });
86
91
  }, timeout);
87
92
  const requireWallet = (w, label) => {
88
93
  if (!w)
@@ -51,6 +51,15 @@ export declare const readSnapshot: (syncCacheDir: string, filename: string, mode
51
51
  * saved must not pass as if it had been.
52
52
  */
53
53
  export declare const saveState: (walletInit: SnapshotSource, syncCacheDir: string, filename: string) => Promise<void>;
54
+ /**
55
+ * Deletes the snapshot {@link saveState} would write for this wallet, if there is one.
56
+ *
57
+ * @param walletInit The wallet whose snapshot to delete; only its dust sync model is read, to find the namespace.
58
+ * @param syncCacheDir The directory the snapshot is in.
59
+ * @param filename The name it was saved under.
60
+ * @throws When the file exists but cannot be deleted.
61
+ */
62
+ export declare const removeState: (walletInit: Pick<SnapshotSource, "dustSyncModel">, syncCacheDir: string, filename: string) => Promise<void>;
54
63
  /**
55
64
  * Starts a facade assembled from a snapshot and checks that it synchronizes.
56
65
  *
package/dist/snapshot.js CHANGED
@@ -102,8 +102,25 @@ export const saveState = async (walletInit, syncCacheDir, filename) => {
102
102
  logger.info(`State written to ${target}`);
103
103
  };
104
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.
105
+ * Deletes the snapshot {@link saveState} would write for this wallet, if there is one.
106
+ *
107
+ * @param walletInit The wallet whose snapshot to delete; only its dust sync model is read, to find the namespace.
108
+ * @param syncCacheDir The directory the snapshot is in.
109
+ * @param filename The name it was saved under.
110
+ * @throws When the file exists but cannot be deleted.
111
+ */
112
+ export const removeState = async (walletInit, syncCacheDir, filename) => {
113
+ const target = snapshotPath(syncCacheDir, filename, walletInit.dustSyncModel);
114
+ if (!existsSync(target))
115
+ return;
116
+ await fsAsync.rm(target, { force: true });
117
+ logger.info(`Removed ${target}`);
118
+ };
119
+ /**
120
+ * How long a restored wallet may take to catch up before it is given up on. Wallets are restored one after another, so
121
+ * a `beforeEach` that restores two of them spends up to 20 minutes here before building from scratch: the 15 minutes
122
+ * the token-transfer scenario allows by default covers one wedged restore, and the 45 minutes the remote healthchecks
123
+ * pass covers two plus a sync from scratch.
107
124
  */
108
125
  const RESTORED_SYNC_TIMEOUT_MS = 10 * 60 * 1000;
109
126
  /** Resolves `true` once the facade has caught up, or `false` if it has not within `timeoutMs`. */
package/dist/wallet.d.ts CHANGED
@@ -2,6 +2,7 @@ import { type WalletSeeds } from '@midnightntwrk/wallet-sdk-hd';
2
2
  import * as ledger from '@midnightntwrk/ledger-v9';
3
3
  import { WalletFacade } from '@midnightntwrk/wallet-sdk-facade';
4
4
  import { type UnshieldedKeystore } from '@midnightntwrk/wallet-sdk-unshielded-wallet';
5
+ import { type TestError } from 'vitest';
5
6
  import { type WalletTestEnvironment } from './types.js';
6
7
  import { type DustSnapshotModel, type DustWalletFactory } from './dust-sync.js';
7
8
  export type WalletInit = {
@@ -95,6 +96,30 @@ export declare const shouldPersistState: (context: {
95
96
  };
96
97
  };
97
98
  }) => boolean;
99
+ /**
100
+ * Whether vitest will run this test again once the attempt now finishing is torn down. A failed attempt that will be
101
+ * retried keeps its wallets' snapshots, so the retry restores them rather than syncing from scratch.
102
+ *
103
+ * Pass the `afterEach` context: `lifecycle.release({ syncCacheDir, persist: shouldPersistState(ctx), willRetry:
104
+ * willRetry(ctx) })`.
105
+ *
106
+ * @param context The `afterEach` context.
107
+ * @returns `true` when the attempt failed, the test's `retry` count is not used up, and the test's retry `condition`,
108
+ * if it sets one, accepts the attempt's last error.
109
+ */
110
+ export declare const willRetry: (context: {
111
+ readonly task: {
112
+ readonly retry?: number | {
113
+ readonly count?: number;
114
+ readonly condition?: RegExp | ((error: TestError) => boolean);
115
+ };
116
+ readonly result?: {
117
+ readonly state?: string;
118
+ readonly retryCount?: number;
119
+ readonly errors?: readonly TestError[];
120
+ };
121
+ };
122
+ }) => boolean;
98
123
  export { saveState, type SnapshotSource } from './snapshot.js';
99
124
  /** Options for {@link initWalletWithSeed}, a subset of {@link ProvideWalletOptions}. */
100
125
  export type InitWalletOptions = Pick<ProvideWalletOptions, 'dustWallet' | 'manualSync'>;
package/dist/wallet.js CHANGED
@@ -179,6 +179,34 @@ export const provideWallet = async (env, options) => {
179
179
  * Pass the `afterEach` context: `afterEach((ctx) => { if (shouldPersistState(ctx)) await saveState(...) })`.
180
180
  */
181
181
  export const shouldPersistState = (context) => context.task.result?.state === 'pass';
182
+ /**
183
+ * Whether vitest will run this test again once the attempt now finishing is torn down. A failed attempt that will be
184
+ * retried keeps its wallets' snapshots, so the retry restores them rather than syncing from scratch.
185
+ *
186
+ * Pass the `afterEach` context: `lifecycle.release({ syncCacheDir, persist: shouldPersistState(ctx), willRetry:
187
+ * willRetry(ctx) })`.
188
+ *
189
+ * @param context The `afterEach` context.
190
+ * @returns `true` when the attempt failed, the test's `retry` count is not used up, and the test's retry `condition`,
191
+ * if it sets one, accepts the attempt's last error.
192
+ */
193
+ export const willRetry = (context) => {
194
+ const { retry, result } = context.task;
195
+ const retries = typeof retry === 'number' ? retry : (retry?.count ?? 0);
196
+ // vitest counts the attempt now finishing in `retryCount` and raises it only after `afterEach` has run.
197
+ return (result?.state === 'fail' &&
198
+ (result.retryCount ?? 0) < retries &&
199
+ passesRetryCondition(typeof retry === 'number' ? undefined : retry?.condition, result.errors));
200
+ };
201
+ // vitest tests only the attempt's last error against the condition; a test with no condition retries any failure.
202
+ const passesRetryCondition = (condition, errors) => {
203
+ const last = errors?.at(-1);
204
+ if (condition === undefined)
205
+ return true;
206
+ if (last === undefined)
207
+ return false;
208
+ return condition instanceof RegExp ? condition.test(last.message) : condition(last);
209
+ };
182
210
  export { saveState } from './snapshot.js';
183
211
  /** Builds and starts a fresh {@link WalletFacade} from `seed`, with no disk persistence. */
184
212
  export const initWalletWithSeed = async (env, seed, options = {}) => {
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.1-rc.0",
4
+ "version": "1.0.1",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.js",
@@ -39,23 +39,23 @@
39
39
  }
40
40
  },
41
41
  "dependencies": {
42
- "@midnightntwrk/ledger-v9": "1.0.2-rc.0",
42
+ "@midnightntwrk/ledger-v9": "1.0.2",
43
43
  "@midnightntwrk/wallet-sdk-abstractions": "3.0.0",
44
- "@midnightntwrk/wallet-sdk-address-format": "4.0.1-rc.0",
45
- "@midnightntwrk/wallet-sdk-capabilities": "4.0.1-rc.0",
46
- "@midnightntwrk/wallet-sdk-dust-wallet": "5.1.0-rc.0",
47
- "@midnightntwrk/wallet-sdk-facade": "5.0.1-rc.0",
44
+ "@midnightntwrk/wallet-sdk-address-format": "4.0.1",
45
+ "@midnightntwrk/wallet-sdk-capabilities": "4.0.1",
46
+ "@midnightntwrk/wallet-sdk-dust-wallet": "5.1.0",
47
+ "@midnightntwrk/wallet-sdk-facade": "5.0.1",
48
48
  "@midnightntwrk/wallet-sdk-hd": "4.0.0",
49
- "@midnightntwrk/wallet-sdk-indexer-client": "2.0.1-rc.0",
50
- "@midnightntwrk/wallet-sdk-shielded": "4.0.1-rc.0",
51
- "@midnightntwrk/wallet-sdk-unshielded-wallet": "4.0.1-rc.0",
49
+ "@midnightntwrk/wallet-sdk-indexer-client": "2.0.1",
50
+ "@midnightntwrk/wallet-sdk-shielded": "4.0.1",
51
+ "@midnightntwrk/wallet-sdk-unshielded-wallet": "4.0.1",
52
52
  "effect": "^3.19.19",
53
53
  "pino": "^10.3.1",
54
54
  "pino-pretty": "^13.1.3",
55
55
  "rxjs": "^7.8.2"
56
56
  },
57
57
  "peerDependencies": {
58
- "@midnightntwrk/wallet-sdk-utilities": "1.3.1-rc.0",
58
+ "@midnightntwrk/wallet-sdk-utilities": "1.3.1",
59
59
  "testcontainers": "^11.12.0",
60
60
  "vitest": "^4.1.4"
61
61
  },