@midnightntwrk/testkit-js 0.0.0-stage → 5.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.
Files changed (56) hide show
  1. package/README.md +409 -2
  2. package/dist/fixtures/hf/README.md +781 -0
  3. package/dist/fixtures/hf/coin-receiver-016/coin-receiver.compact +24 -0
  4. package/dist/fixtures/hf/coin-receiver-016/compiled/compiler/contract-info.json +104 -0
  5. package/dist/fixtures/hf/coin-receiver-016/compiled/contract/index.d.ts +47 -0
  6. package/dist/fixtures/hf/coin-receiver-016/compiled/contract/index.js +412 -0
  7. package/dist/fixtures/hf/coin-receiver-016/receive-coin-transcript.recording.json +668 -0
  8. package/dist/fixtures/hf/coin-receiver-016/state-v6-envelope.hex +1 -0
  9. package/dist/fixtures/hf/coin-receiver-016/state-v9.hex +1 -0
  10. package/dist/fixtures/hf/counter-016/compiled/compiler/contract-info.json +31 -0
  11. package/dist/fixtures/hf/counter-016/compiled/contract/index.d.ts +39 -0
  12. package/dist/fixtures/hf/counter-016/compiled/contract/index.js +189 -0
  13. package/dist/fixtures/hf/counter-016/compiled/keys/increment.prover +0 -0
  14. package/dist/fixtures/hf/counter-016/compiled/keys/increment.verifier +0 -0
  15. package/dist/fixtures/hf/counter-016/compiled/zkir/increment.bzkir +0 -0
  16. package/dist/fixtures/hf/counter-016/compiled/zkir/increment.zkir +22 -0
  17. package/dist/fixtures/hf/counter-016/increment-transcript.golden.json +23 -0
  18. package/dist/fixtures/hf/fixtures.json +69 -0
  19. package/dist/fixtures/hf/pre-fork-private-state-store/.gitattributes +8 -0
  20. package/dist/fixtures/hf/pre-fork-private-state-store/ENVELOPE.md +70 -0
  21. package/dist/fixtures/hf/pre-fork-private-state-store/store/000005.ldb +0 -0
  22. package/dist/fixtures/hf/pre-fork-private-state-store/store/000006.log +0 -0
  23. package/dist/fixtures/hf/pre-fork-private-state-store/store/CURRENT +1 -0
  24. package/dist/fixtures/hf/pre-fork-private-state-store/store/MANIFEST-000004 +0 -0
  25. package/dist/fixtures/hf/private-counter-016/README.md +13 -0
  26. package/dist/fixtures/hf/private-counter-016/compiled/compiler/contract-info.json +40 -0
  27. package/dist/fixtures/hf/private-counter-016/compiled/contract/index.d.ts +40 -0
  28. package/dist/fixtures/hf/private-counter-016/compiled/contract/index.js +211 -0
  29. package/dist/fixtures/hf/private-counter-twin/compiled/compiler/contract-info.json +41 -0
  30. package/dist/fixtures/hf/private-counter-twin/compiled/contract/index.js +271 -0
  31. package/dist/fixtures/hf/private-counter-twin/private-counter.compact +27 -0
  32. package/dist/fixtures/hf/state-both-keys.hex +1 -0
  33. package/dist/fixtures/hf/state-co-v2-only-foreign.hex +1 -0
  34. package/dist/fixtures/hf/state-migrated-v9-merkle.hex +1 -0
  35. package/dist/fixtures/hf/state-migrated-v9.hex +1 -0
  36. package/dist/fixtures/hf/state-tampered-bytes.hex +1 -0
  37. package/dist/fixtures/hf/state-tampered-keyset-v8to9.hex +1 -0
  38. package/dist/fixtures/hf/state-tampered-keyset-v9to8.hex +1 -0
  39. package/dist/fixtures/hf/state-v8-v6-envelope.hex +1 -0
  40. package/dist/fixtures/hf/state-v8.hex +1 -0
  41. package/dist/fixtures/hf/twin-contract/compiled/compiler/contract-info.json +31 -0
  42. package/dist/fixtures/hf/twin-contract/compiled/compiler/contract-manifest.json +58 -0
  43. package/dist/fixtures/hf/twin-contract/compiled/contract/index.d.ts +40 -0
  44. package/dist/fixtures/hf/twin-contract/compiled/contract/index.js +196 -0
  45. package/dist/fixtures/hf/twin-contract/compiled/keys/increment.prover +0 -0
  46. package/dist/fixtures/hf/twin-contract/compiled/keys/increment.verifier +0 -0
  47. package/dist/fixtures/hf/twin-contract/compiled/zkir/increment.bzkir +0 -0
  48. package/dist/fixtures/hf/twin-contract/compiled/zkir/increment.zkir +22 -0
  49. package/dist/fixtures/hf/twin-contract/counter.compact +15 -0
  50. package/dist/fixtures-hf.d.ts +70 -0
  51. package/dist/fixtures-hf.js +161 -0
  52. package/dist/fixtures-hf.js.map +1 -0
  53. package/dist/index.d.ts +1067 -0
  54. package/dist/index.js +3459 -0
  55. package/dist/index.js.map +1 -0
  56. package/package.json +82 -3
package/dist/index.js ADDED
@@ -0,0 +1,3459 @@
1
+ import { Transaction, ContractState as ContractState$1, LedgerState, LedgerParameters, unshieldedToken, ZswapSecretKeys, DustSecretKey } from '@midnightntwrk/midnight-js-protocol/v9';
2
+ import { ContractState } from '@midnightntwrk/midnight-js-protocol/v9/compact-runtime';
3
+ import { SucceedEntirely, MAX_EXPORT_SIGNING_KEYS, InvalidExportFormatError, ExportDecryptionError, ImportConflictError, SigningKeyExportError, ImportPasswordValidationError, MAX_EXPORT_STATES, PrivateStateExportError, createWalletProviderFromHandlers, createMidnightProviderFromHandlers } from '@midnightntwrk/midnight-js-types';
4
+ import { assertDefined, assertIsContractAddress, PasswordValidationError, isValidSigningKey, createMidnightProviders, ttlOneHour, fromHex, toHex, networks } from '@midnightntwrk/midnight-js-utils';
5
+ import axios from 'axios';
6
+ import path$1 from 'path';
7
+ import { Wait, DockerComposeEnvironment } from 'testcontainers';
8
+ import { rm, mkdir, writeFile } from 'node:fs/promises';
9
+ import * as path from 'node:path';
10
+ import path__default from 'node:path';
11
+ import pino from 'pino';
12
+ import pinoPretty from 'pino-pretty';
13
+ import { InvalidArgumentError } from '@midnightntwrk/midnight-js-protocol/errors';
14
+ import { randomBytes, createDecipheriv, createCipheriv, pbkdf2Sync } from 'crypto';
15
+ import { httpClientProofProvider } from '@midnightntwrk/midnight-js-http-client-proof-provider';
16
+ import { indexerPublicDataProvider } from '@midnightntwrk/midnight-js-indexer-public-data-provider';
17
+ import { levelPrivateStateProvider } from '@midnightntwrk/midnight-js-level-private-state-provider';
18
+ import { NodeZkConfigProvider } from '@midnightntwrk/midnight-js-node-zk-config-provider';
19
+ import { ErrorCodes } from '@midnightntwrk/dapp-connector-api';
20
+ import { MidnightBech32m, DustAddress } from '@midnightntwrk/wallet-sdk/address-format';
21
+ import { WasmProver } from '@midnightntwrk/wallet-sdk-prover-client/effect';
22
+ import { provingProvider } from '@midnightntwrk/zkir-v3';
23
+ import * as Rx from 'rxjs';
24
+ import { firstValueFrom } from 'rxjs';
25
+ import { InMemoryTransactionHistoryStorage, DefaultForkSchedule, WalletEntrySchema, mergeWalletEntries, ShieldedWallet, UnshieldedWallet, PublicKey, DustWallet, WalletFacade, generateRandomSeed, Roles, HDWallet, createKeystore, WalletTransaction, ProtocolVersion, NetworkId } from '@midnightntwrk/wallet-sdk';
26
+ import { mnemonicToSeedSync } from '@scure/bip39';
27
+ import { createGzip, createGunzip } from 'node:zlib';
28
+ import { createReadStream, createWriteStream } from 'fs';
29
+ import * as WalletLedger9 from '@midnightntwrk/wallet-sdk/ledger/v9';
30
+ import { Either } from 'effect';
31
+ import fs from 'node:fs';
32
+ import { execFile } from 'node:child_process';
33
+ import { randomUUID } from 'node:crypto';
34
+ import { promisify } from 'node:util';
35
+
36
+ /*
37
+ * This file is part of midnight-js.
38
+ * Copyright (C) Midnight Foundation
39
+ * SPDX-License-Identifier: Apache-2.0
40
+ * Licensed under the Apache License, Version 2.0 (the "License");
41
+ * You may not use this file except in compliance with the License.
42
+ * You may obtain a copy of the License at
43
+ * http://www.apache.org/licenses/LICENSE-2.0
44
+ * Unless required by applicable law or agreed to in writing, software
45
+ * distributed under the License is distributed on an "AS IS" BASIS,
46
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
47
+ * See the License for the specific language governing permissions and
48
+ * limitations under the License.
49
+ */
50
+ const stateValueEqual = (a, b) => {
51
+ return a.toString(false) === b.toString(false);
52
+ };
53
+ const txsEqual = (a, b) => {
54
+ return a.toString(false) === b.toString(false);
55
+ };
56
+ const ledger9DeployPublicData = (foundDeployTxData) => {
57
+ const found = foundDeployTxData.public;
58
+ if (found.era !== 'v9') {
59
+ throw new Error(`expected a contract deployed in ledger 9, found one recorded in '${found.era}'`);
60
+ }
61
+ return found;
62
+ };
63
+ const expectFoundAndDeployedTxPublicDataEqual = (deployTxData, foundDeployTxData) => {
64
+ const found = ledger9DeployPublicData(foundDeployTxData);
65
+ expect(stateValueEqual(deployTxData.public.initialContractState.deserialize({ v9: ContractState }).data.state, found.initialContractState.deserialize({ v9: ContractState }).data.state)).toBeTruthy();
66
+ expect(deployTxData.public.contractAddress).toEqual(found.contractAddress);
67
+ expect(deployTxData.public.blockHash).toEqual(found.blockHash);
68
+ expect(deployTxData.public.blockHeight).toEqual(found.blockHeight);
69
+ expect(deployTxData.public.txHash).toEqual(found.txHash);
70
+ expect(deployTxData.public.identifiers).toEqual(found.identifiers);
71
+ expect(deployTxData.public.status).toEqual(found.status);
72
+ expect(txsEqual(deployTxData.public.tx.deserialize({ v9: Transaction }), found.tx.deserialize({ v9: Transaction }))).toBeTruthy();
73
+ };
74
+ const expectFoundAndDeployedTxPrivateDataEqual = (deployTxData, foundDeployTxData) => {
75
+ // For our purposes, we always find with the same private state that the contract is deployed with
76
+ // so this comparison is justified.
77
+ expect(deployTxData.private.initialPrivateState).toEqual(foundDeployTxData.private.initialPrivateState);
78
+ };
79
+ const expectFoundAndDeployedTxDataEqual = (deployTxData, foundDeployTxData) => {
80
+ expectFoundAndDeployedTxPublicDataEqual(deployTxData, foundDeployTxData);
81
+ expectFoundAndDeployedTxPrivateDataEqual(deployTxData, foundDeployTxData);
82
+ };
83
+ const expectFoundAndDeployedStatesEqual = async (providers, deployTxData, foundDeployTxData, privateStateId, initialPrivateState) => {
84
+ const found = ledger9DeployPublicData(foundDeployTxData);
85
+ const deployedLedgerState = await providers.publicDataProvider.queryContractState(deployTxData.public.contractAddress);
86
+ assertDefined(deployedLedgerState);
87
+ const state = deployedLedgerState.contractState.deserialize({ v9: ContractState });
88
+ expect(stateValueEqual(state.data.state, found.initialContractState.deserialize({ v9: ContractState }).data.state)).toBeTruthy();
89
+ if (privateStateId) {
90
+ const privateState = await providers.privateStateProvider
91
+ .forContract(deployTxData.public.contractAddress)
92
+ .get(privateStateId);
93
+ expect(privateState).toEqual(foundDeployTxData.private.initialPrivateState);
94
+ if (initialPrivateState !== undefined) {
95
+ expect(privateState).toEqual(initialPrivateState);
96
+ }
97
+ }
98
+ };
99
+ const expectSuccessfulTxData = (finalizedTxData) => {
100
+ expect(finalizedTxData.status).toEqual(SucceedEntirely);
101
+ expect(finalizedTxData.tx).toBeTruthy();
102
+ expect(finalizedTxData.txId).toBeTruthy();
103
+ expect(finalizedTxData.txHash).toBeTruthy();
104
+ expect(finalizedTxData.blockHeight).toBeTruthy();
105
+ expect(finalizedTxData.blockHash).toBeTruthy();
106
+ };
107
+ const expectSuccessfulDeployTx = async (providers, deployTxData, deployTxOptions) => {
108
+ expectSuccessfulTxData(deployTxData.public);
109
+ expect(deployTxData.public.contractAddress).toBeTruthy();
110
+ const deployedLedgerState = await providers.publicDataProvider.queryContractState(deployTxData.public.contractAddress);
111
+ assertDefined(deployedLedgerState);
112
+ const state = deployedLedgerState.contractState.deserialize({ v9: ContractState });
113
+ expect(stateValueEqual(deployTxData.public.initialContractState.deserialize({ v9: ContractState }).data.state, state.data.state)).toBeTruthy();
114
+ expect(deployTxData.public.initialContractState).toBeTruthy();
115
+ // Checks that the signing key and private state passed in the deploy configuration
116
+ // were stored correctly.
117
+ if (deployTxOptions) {
118
+ if (deployTxOptions.signingKey) {
119
+ expect(deployTxData.private.signingKey).toEqual(deployTxOptions.signingKey);
120
+ const storedSigningKey = await providers.privateStateProvider.getSigningKey(deployTxData.public.contractAddress);
121
+ expect(storedSigningKey).toBeDefined();
122
+ expect(storedSigningKey).toEqual(deployTxOptions.signingKey);
123
+ }
124
+ // We only test contracts that pass 'initialPrivateState' through the contract constructor unchanged
125
+ // so this equality comparison is justified.
126
+ if ('privateStateId' in deployTxOptions && 'initialPrivateState' in deployTxOptions) {
127
+ // `DeployContractOptionsBase` declares both members as `undefined`, so these `in` checks narrow
128
+ // to presence only; both deploy entry points refuse an undefined id, so this only narrows the type.
129
+ const { privateStateId, initialPrivateState } = deployTxOptions;
130
+ assertDefined(privateStateId, "'privateStateId' was given as undefined");
131
+ expect(deployTxData.private.initialPrivateState).toEqual(initialPrivateState);
132
+ const storedPrivateState = await providers.privateStateProvider
133
+ .forContract(deployTxData.public.contractAddress)
134
+ .get(privateStateId);
135
+ expect(storedPrivateState).toBeDefined();
136
+ expect(storedPrivateState).toEqual(initialPrivateState);
137
+ }
138
+ }
139
+ };
140
+ const expectSuccessfulCallTx = async (providers, callTxData, callTxOptions, nextPrivateState) => {
141
+ expectSuccessfulTxData(callTxData.public);
142
+ expect(callTxData.public.nextContractState).toBeTruthy();
143
+ expect(callTxData.private.nextZswapLocalState).toBeTruthy();
144
+ if (callTxOptions) {
145
+ if ('privateStateId' in callTxOptions) {
146
+ const storedPrivateState = await providers.privateStateProvider
147
+ .forContract(callTxOptions.contractAddress)
148
+ .get(callTxOptions.privateStateId);
149
+ expect(storedPrivateState).toBeDefined();
150
+ expect(storedPrivateState).toEqual(callTxData.private.nextPrivateState);
151
+ if (nextPrivateState) {
152
+ expect(nextPrivateState).toEqual(callTxData.private.nextPrivateState);
153
+ }
154
+ }
155
+ }
156
+ };
157
+
158
+ /*
159
+ * This file is part of midnight-js.
160
+ * Copyright (C) Midnight Foundation
161
+ * SPDX-License-Identifier: Apache-2.0
162
+ * Licensed under the Apache License, Version 2.0 (the "License");
163
+ * You may not use this file except in compliance with the License.
164
+ * You may obtain a copy of the License at
165
+ * http://www.apache.org/licenses/LICENSE-2.0
166
+ * Unless required by applicable law or agreed to in writing, software
167
+ * distributed under the License is distributed on an "AS IS" BASIS,
168
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
169
+ * See the License for the specific language governing permissions and
170
+ * limitations under the License.
171
+ */
172
+ /**
173
+ * A wait strategy that waits for a specified delay before considering the container ready.
174
+ */
175
+ class DelayWaitStrategy {
176
+ delayMs;
177
+ startupTimeoutMs = 60_000;
178
+ startupTimeoutSet = false;
179
+ constructor(delayMs) {
180
+ this.delayMs = delayMs;
181
+ }
182
+ async waitUntilReady() {
183
+ await new Promise((resolve) => setTimeout(resolve, this.delayMs));
184
+ }
185
+ withStartupTimeout(startupTimeoutMs) {
186
+ this.startupTimeoutMs = startupTimeoutMs;
187
+ this.startupTimeoutSet = true;
188
+ return this;
189
+ }
190
+ isStartupTimeoutSet() {
191
+ return this.startupTimeoutSet;
192
+ }
193
+ getStartupTimeout() {
194
+ return this.startupTimeoutMs;
195
+ }
196
+ }
197
+ /**
198
+ * A wait strategy that first waits for a delay, then delegates to another wait strategy.
199
+ */
200
+ class DelayedWaitStrategy {
201
+ delayMs;
202
+ delegate;
203
+ startupTimeoutMs = 60_000;
204
+ startupTimeoutSet = false;
205
+ constructor(delayMs, delegate) {
206
+ this.delayMs = delayMs;
207
+ this.delegate = delegate;
208
+ }
209
+ async waitUntilReady(...args) {
210
+ console.log(`[DelayedWaitStrategy] Starting ${this.delayMs}ms delay before health check...`);
211
+ await new Promise((resolve) => setTimeout(resolve, this.delayMs));
212
+ console.log(`[DelayedWaitStrategy] Delay complete, now checking health...`);
213
+ await this.delegate.waitUntilReady(...args);
214
+ console.log(`[DelayedWaitStrategy] Health check passed`);
215
+ }
216
+ withStartupTimeout(startupTimeoutMs) {
217
+ this.startupTimeoutMs = startupTimeoutMs;
218
+ this.startupTimeoutSet = true;
219
+ this.delegate.withStartupTimeout(startupTimeoutMs);
220
+ return this;
221
+ }
222
+ isStartupTimeoutSet() {
223
+ return this.startupTimeoutSet;
224
+ }
225
+ getStartupTimeout() {
226
+ return this.startupTimeoutMs;
227
+ }
228
+ }
229
+ /**
230
+ * Factory functions for creating delay wait strategies.
231
+ */
232
+ const WaitStrategies = {
233
+ /**
234
+ * Creates a wait strategy that waits for a specified delay.
235
+ * @param delayMs The delay in milliseconds.
236
+ */
237
+ forDelay(delayMs) {
238
+ return new DelayWaitStrategy(delayMs);
239
+ },
240
+ /**
241
+ * Creates a wait strategy that first waits for a delay, then delegates to another strategy.
242
+ * @param delayMs The delay in milliseconds before checking the delegate strategy.
243
+ * @param delegate The wait strategy to delegate to after the delay.
244
+ */
245
+ forDelayedStrategy(delayMs, delegate) {
246
+ return new DelayedWaitStrategy(delayMs, delegate);
247
+ }
248
+ };
249
+
250
+ /*
251
+ * This file is part of midnight-js.
252
+ * Copyright (C) Midnight Foundation
253
+ * SPDX-License-Identifier: Apache-2.0
254
+ * Licensed under the Apache License, Version 2.0 (the "License");
255
+ * You may not use this file except in compliance with the License.
256
+ * You may obtain a copy of the License at
257
+ * http://www.apache.org/licenses/LICENSE-2.0
258
+ * Unless required by applicable law or agreed to in writing, software
259
+ * distributed under the License is distributed on an "AS IS" BASIS,
260
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
261
+ * See the License for the specific language governing permissions and
262
+ * limitations under the License.
263
+ */
264
+ const currentWorkingDir = path$1.resolve(`${process.cwd()}`);
265
+ const HEALTH_CHECK_TIMEOUT_MS = 10_000;
266
+ const defaultContainersConfiguration = {
267
+ proofServer: {
268
+ path: currentWorkingDir,
269
+ fileName: 'proof-server.yml',
270
+ container: {
271
+ name: 'proof-server',
272
+ port: 6300,
273
+ waitStrategy: Wait.forListeningPorts().withStartupTimeout(3 * 60_000)
274
+ }
275
+ },
276
+ standalone: {
277
+ path: currentWorkingDir,
278
+ fileName: 'compose.yml',
279
+ container: {
280
+ proofServer: {
281
+ name: 'proof-server',
282
+ port: 6300,
283
+ waitStrategy: Wait.forListeningPorts().withStartupTimeout(3 * 60_000)
284
+ },
285
+ node: {
286
+ name: 'node',
287
+ port: 9944,
288
+ waitStrategy: WaitStrategies.forDelayedStrategy(10_000, Wait.forHealthCheck())
289
+ },
290
+ indexer: {
291
+ name: 'indexer',
292
+ port: 8088,
293
+ waitStrategy: Wait.forHealthCheck().withStartupTimeout(3 * 60_000)
294
+ }
295
+ }
296
+ },
297
+ log: {
298
+ fileName: `tests_${new Date().toISOString().replace(/:/g, '_')}.log`,
299
+ path: path$1.resolve(currentWorkingDir, 'logs', 'tests'),
300
+ level: 'info'
301
+ }
302
+ };
303
+ const latestContainersConfiguration = {
304
+ ...defaultContainersConfiguration,
305
+ standalone: {
306
+ ...defaultContainersConfiguration.standalone,
307
+ fileName: 'compose-latest.yml'
308
+ },
309
+ proofServer: {
310
+ ...defaultContainersConfiguration.proofServer,
311
+ fileName: 'proof-server-latest.yml'
312
+ }
313
+ };
314
+ let containersConfiguration = defaultContainersConfiguration;
315
+ const getContainersConfiguration = () => {
316
+ return containersConfiguration;
317
+ };
318
+ const setContainersConfiguration = (containersConfig) => {
319
+ containersConfiguration = containersConfig;
320
+ };
321
+
322
+ /*
323
+ * This file is part of midnight-js.
324
+ * Copyright (C) Midnight Foundation
325
+ * SPDX-License-Identifier: Apache-2.0
326
+ * Licensed under the Apache License, Version 2.0 (the "License");
327
+ * You may not use this file except in compliance with the License.
328
+ * You may obtain a copy of the License at
329
+ * http://www.apache.org/licenses/LICENSE-2.0
330
+ * Unless required by applicable law or agreed to in writing, software
331
+ * distributed under the License is distributed on an "AS IS" BASIS,
332
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
333
+ * See the License for the specific language governing permissions and
334
+ * limitations under the License.
335
+ */
336
+ const { level } = getContainersConfiguration().log;
337
+ function createLogger(fileName, dir = getContainersConfiguration().log.path) {
338
+ let logPath = path.resolve(fileName);
339
+ if (!fileName.includes('/')) {
340
+ logPath = path.resolve(dir, fileName);
341
+ }
342
+ const prettyStream = pinoPretty({
343
+ colorize: true,
344
+ sync: true
345
+ });
346
+ const prettyFileStream = pinoPretty({
347
+ mkdir: true,
348
+ colorize: false,
349
+ sync: true,
350
+ append: true,
351
+ destination: logPath
352
+ });
353
+ return pino({
354
+ level,
355
+ depthLimit: 20
356
+ }, pino.multistream([
357
+ { stream: prettyStream, level },
358
+ { stream: prettyFileStream, level }
359
+ ]));
360
+ }
361
+ function createDefaultTestLogger() {
362
+ return createLogger(getContainersConfiguration().log.fileName, getContainersConfiguration().log.path);
363
+ }
364
+ const logger = createDefaultTestLogger();
365
+
366
+ /*
367
+ * This file is part of midnight-js.
368
+ * Copyright (C) Midnight Foundation
369
+ * SPDX-License-Identifier: Apache-2.0
370
+ * Licensed under the Apache License, Version 2.0 (the "License");
371
+ * You may not use this file except in compliance with the License.
372
+ * You may obtain a copy of the License at
373
+ * http://www.apache.org/licenses/LICENSE-2.0
374
+ * Unless required by applicable law or agreed to in writing, software
375
+ * distributed under the License is distributed on an "AS IS" BASIS,
376
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
377
+ * See the License for the specific language governing permissions and
378
+ * limitations under the License.
379
+ */
380
+ const MINUTE = 60_000;
381
+ /**
382
+ * Creates a Promise that resolves after a specified delay.
383
+ * @param ms The delay duration in milliseconds.
384
+ * @returns A Promise that resolves after the specified delay.
385
+ * @example
386
+ * // Wait for 1 second
387
+ * await delay(1000);
388
+ */
389
+ const delay = (ms) => {
390
+ return new Promise((resolve) => {
391
+ setTimeout(resolve, ms);
392
+ });
393
+ };
394
+ /**
395
+ * Deletes a directory and its contents recursively.
396
+ * @param {string} dirPath - The path to the directory to delete
397
+ * @returns {Promise<void>} A promise that resolves when the directory is deleted
398
+ * @private
399
+ */
400
+ const tryDeleteDirectory = async (dirPath) => {
401
+ try {
402
+ const resolvedPath = path$1.resolve(dirPath);
403
+ await rm(resolvedPath, { recursive: true, force: true });
404
+ logger.info(`Directory ${resolvedPath} deleted successfully.`);
405
+ }
406
+ catch (error) {
407
+ if (error instanceof Error) {
408
+ logger.error(`Error deleting directory: ${error.message}`);
409
+ }
410
+ else {
411
+ logger.error('Unknown error occurred');
412
+ }
413
+ }
414
+ };
415
+ const buildUrlWithPath = (baseUrl, urlPath) => {
416
+ const url = new URL(baseUrl);
417
+ url.pathname = urlPath;
418
+ url.hash = '';
419
+ return url.toString();
420
+ };
421
+ const redactUrl = (value) => {
422
+ if (!URL.canParse(value)) {
423
+ return value;
424
+ }
425
+ const url = new URL(value);
426
+ const hasUserInfo = url.username !== '' || url.password !== '';
427
+ if (url.search === '' && !hasUserInfo) {
428
+ return value;
429
+ }
430
+ const userInfo = hasUserInfo ? '<redacted>@' : '';
431
+ const query = url.search === '' ? '' : '?<redacted>';
432
+ return `${url.protocol}//${userInfo}${url.host}${url.pathname}${query}`;
433
+ };
434
+ const redactedJson = (value) => JSON.stringify(value, (_key, field) => (typeof field === 'string' ? redactUrl(field) : field));
435
+
436
+ /*
437
+ * This file is part of midnight-js.
438
+ * Copyright (C) Midnight Foundation
439
+ * SPDX-License-Identifier: Apache-2.0
440
+ * Licensed under the Apache License, Version 2.0 (the "License");
441
+ * You may not use this file except in compliance with the License.
442
+ * You may obtain a copy of the License at
443
+ * http://www.apache.org/licenses/LICENSE-2.0
444
+ * Unless required by applicable law or agreed to in writing, software
445
+ * distributed under the License is distributed on an "AS IS" BASIS,
446
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
447
+ * See the License for the specific language governing permissions and
448
+ * limitations under the License.
449
+ */
450
+ /**
451
+ * Client for interacting with the Midnight faucet service.
452
+ * Provides functionality to request test tokens for wallet addresses.
453
+ */
454
+ class FaucetClient {
455
+ faucetUrl;
456
+ logger;
457
+ /**
458
+ * Creates a new FaucetClient instance.
459
+ * @param {string} faucetUrl - The URL of the faucet service endpoint
460
+ * @param {Logger} logger - Logger instance for recording operations
461
+ */
462
+ constructor(faucetUrl, logger) {
463
+ this.faucetUrl = faucetUrl;
464
+ this.logger = logger;
465
+ }
466
+ /**
467
+ * Checks the health status of the faucet service.
468
+ * Makes a GET request to the health endpoint of the faucet service.
469
+ * @returns {Promise<AxiosResponse | void>} A promise that resolves to the response of the health check or logs an error if the request fails
470
+ */
471
+ async health() {
472
+ const url = buildUrlWithPath(this.faucetUrl, '/api/health');
473
+ const response = await axios.get(url, { timeout: HEALTH_CHECK_TIMEOUT_MS });
474
+ this.logger.info(`Connected to faucet ${redactUrl(url)}: ${JSON.stringify(response.data)}`);
475
+ return response;
476
+ }
477
+ /**
478
+ * Requests test tokens from the faucet for a specified wallet address.
479
+ * Makes a POST request to the faucet service with the wallet address.
480
+ * @param {string} walletAddress - The address to receive the test tokens
481
+ * @returns {Promise<void>} A promise that resolves when the request is complete
482
+ * @throws Will log but not throw if the request fails
483
+ */
484
+ async requestTokens(walletAddress) {
485
+ this.logger.info(`Requesting tokens from '${redactUrl(this.faucetUrl)}' for address: '${walletAddress}'`);
486
+ const response = await axios.post(this.faucetUrl, {
487
+ recipientAddress: walletAddress,
488
+ amount: '1000'
489
+ }, {
490
+ headers: {
491
+ 'Content-Type': 'application/json',
492
+ 'X-Captcha-Token': 'XXXX.DUMMY.TOKEN.XXXX',
493
+ 'x-turnstile-token': process.env.TURNSTILE_HEADER ?? ''
494
+ }
495
+ });
496
+ this.logger.info(`Faucet response: ${response.statusText}`);
497
+ }
498
+ }
499
+
500
+ /*
501
+ * This file is part of midnight-js.
502
+ * Copyright (C) Midnight Foundation
503
+ * SPDX-License-Identifier: Apache-2.0
504
+ * Licensed under the Apache License, Version 2.0 (the "License");
505
+ * You may not use this file except in compliance with the License.
506
+ * You may obtain a copy of the License at
507
+ * http://www.apache.org/licenses/LICENSE-2.0
508
+ * Unless required by applicable law or agreed to in writing, software
509
+ * distributed under the License is distributed on an "AS IS" BASIS,
510
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
511
+ * See the License for the specific language governing permissions and
512
+ * limitations under the License.
513
+ */
514
+ class IndexerClient {
515
+ indexerUrl;
516
+ logger;
517
+ /**
518
+ * Creates an instance of IndexerClient.
519
+ * @param {string} indexerUrl - The URL of the indexer service.
520
+ * @param {Logger} logger - The logger instance for logging information.
521
+ */
522
+ constructor(indexerUrl, logger) {
523
+ this.indexerUrl = indexerUrl;
524
+ this.logger = logger;
525
+ }
526
+ /**
527
+ * Checks the health status of the indexer service.
528
+ * Makes a GET request to the status endpoint of the indexer service.
529
+ * @returns {Promise<AxiosResponse | void>} A promise that resolves to the response of the health check or logs an error if the request fails.
530
+ */
531
+ async health() {
532
+ const url = buildUrlWithPath(this.indexerUrl, '/ready');
533
+ const response = await axios.get(url, { timeout: HEALTH_CHECK_TIMEOUT_MS });
534
+ this.logger.info(`Connected to indexer ${redactUrl(url)}: ${JSON.stringify(response.data)}`);
535
+ return response;
536
+ }
537
+ }
538
+
539
+ /*
540
+ * This file is part of midnight-js.
541
+ * Copyright (C) Midnight Foundation
542
+ * SPDX-License-Identifier: Apache-2.0
543
+ * Licensed under the Apache License, Version 2.0 (the "License");
544
+ * You may not use this file except in compliance with the License.
545
+ * You may obtain a copy of the License at
546
+ * http://www.apache.org/licenses/LICENSE-2.0
547
+ * Unless required by applicable law or agreed to in writing, software
548
+ * distributed under the License is distributed on an "AS IS" BASIS,
549
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
550
+ * See the License for the specific language governing permissions and
551
+ * limitations under the License.
552
+ */
553
+ /**
554
+ * Client for interacting with a Midnight node's JSON-RPC API
555
+ */
556
+ class NodeClient {
557
+ nodeURL;
558
+ logger;
559
+ networkId;
560
+ /**
561
+ * Creates a new NodeClient instance
562
+ * @param {string} nodeURL - URL of the Midnight node
563
+ * @param {Logger} logger - Logger instance for recording operations
564
+ * @param {NetworkId} networkId - Network the node serves, used to address contract state
565
+ */
566
+ constructor(nodeURL, logger, networkId) {
567
+ if (typeof networkId !== 'string' || networkId.length === 0 || networkId.trim() !== networkId) {
568
+ throw new TypeError(`NodeClient networkId must be a non-empty string without surrounding whitespace, got ${JSON.stringify(networkId)}.`);
569
+ }
570
+ this.nodeURL = nodeURL;
571
+ this.logger = logger;
572
+ this.networkId = networkId;
573
+ }
574
+ /**
575
+ * Checks the health status of the node.
576
+ * Makes a GET request to the health endpoint of the node.
577
+ * @returns {Promise<AxiosResponse | void>} A promise that resolves to the response of the health check or logs an error if the request fails.
578
+ */
579
+ async health() {
580
+ const url = buildUrlWithPath(this.nodeURL, '/health');
581
+ const response = await axios.get(url, { timeout: HEALTH_CHECK_TIMEOUT_MS });
582
+ this.logger.info(`Connected to node ${redactUrl(url)}: ${JSON.stringify(response.data)}`);
583
+ return response;
584
+ }
585
+ /**
586
+ * Validates response format and throws if unexpected
587
+ * @param {AxiosResponse} response - Response from node API
588
+ * @throws {Error} If response format is unexpected
589
+ * @private
590
+ */
591
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
592
+ static throwOnUnexpected(response) {
593
+ if (typeof response.data !== 'object' || !response.data.result || typeof response.data.result !== 'string') {
594
+ throw new Error(`Unexpected response format: ${JSON.stringify(response.data)}`);
595
+ }
596
+ }
597
+ /**
598
+ * Makes a JSON-RPC request to the node
599
+ * @param {string} method - RPC method name
600
+ * @param {any[]} params - RPC method parameters
601
+ * @returns {Promise<string>} Response result as string
602
+ * @private
603
+ */
604
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
605
+ async jsonRPC(method, params) {
606
+ const response = await axios.post(this.nodeURL, {
607
+ id: 1,
608
+ jsonrpc: '2.0',
609
+ method,
610
+ params
611
+ }, {
612
+ headers: {
613
+ 'Content-Type': 'application/json'
614
+ }
615
+ });
616
+ this.logger.info(`Node response: ${response.statusText}`);
617
+ NodeClient.throwOnUnexpected(response);
618
+ return response.data.result;
619
+ }
620
+ /**
621
+ * Fetches the state of a contract
622
+ * @param {ContractAddress} contractAddress - Address of the contract
623
+ * @returns {Promise<ContractState | null>} Contract state or null if not found
624
+ */
625
+ async contractState(contractAddress) {
626
+ this.logger.info(`Fetching contract state for address '${contractAddress}'`);
627
+ const result = await this.jsonRPC('midnight_contractState', [
628
+ `${this.networkId}${contractAddress}`
629
+ ]);
630
+ return result === '' ? null : ContractState$1.deserialize(Buffer.from(result, 'hex'));
631
+ }
632
+ /**
633
+ * Fetches the ledger state at a given block
634
+ * @param {BlockHash} blockHash - Hash of the block
635
+ * @returns {Promise<LedgerState>} Ledger state
636
+ */
637
+ async ledgerState(blockHash) {
638
+ const blob = await this.ledgerStateBlob(blockHash);
639
+ return LedgerState.deserialize(blob);
640
+ }
641
+ /**
642
+ * Fetches the raw ledger state blob at a given block
643
+ * @param {BlockHash} blockHash - Hash of the block
644
+ * @returns {Promise<Uint8Array>} Raw ledger state data
645
+ * @throws {Error} If no ledger state is found
646
+ */
647
+ async ledgerStateBlob(blockHash) {
648
+ this.logger.info(`Fetching ledger state at block hash '${blockHash}'`);
649
+ const result = await this.jsonRPC('midnight_getLedgerState', [blockHash]);
650
+ if (result === '') {
651
+ throw new Error(`No ledger state found at block hash '${blockHash}'`);
652
+ }
653
+ return Buffer.from(result.slice(4), 'hex');
654
+ }
655
+ /**
656
+ * Fetches the ledger version at a given block
657
+ * @param {BlockHash} blockHash - Hash of the block
658
+ * @returns {Promise<string>} Ledger version
659
+ * @throws {Error} If no ledger version is found
660
+ */
661
+ async ledgerVersion(blockHash) {
662
+ this.logger.info(`Fetching ledger version at block hash '${blockHash}'`);
663
+ const result = await this.jsonRPC('midnight_ledgerVersion', [blockHash]);
664
+ if (result === '') {
665
+ throw new Error(`No ledger version found at block hash '${blockHash}'`);
666
+ }
667
+ return result;
668
+ }
669
+ }
670
+
671
+ /*
672
+ * This file is part of midnight-js.
673
+ * Copyright (C) Midnight Foundation
674
+ * SPDX-License-Identifier: Apache-2.0
675
+ * Licensed under the Apache License, Version 2.0 (the "License");
676
+ * You may not use this file except in compliance with the License.
677
+ * You may obtain a copy of the License at
678
+ * http://www.apache.org/licenses/LICENSE-2.0
679
+ * Unless required by applicable law or agreed to in writing, software
680
+ * distributed under the License is distributed on an "AS IS" BASIS,
681
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
682
+ * See the License for the specific language governing permissions and
683
+ * limitations under the License.
684
+ */
685
+ class ProofServerClient {
686
+ proofServer;
687
+ logger;
688
+ /**
689
+ * Creates an instance of ProofServerClient.
690
+ * @param {string} proofServer - The URL of the proof server service.
691
+ * @param {Logger} logger - The logger instance for logging information.
692
+ */
693
+ constructor(proofServer, logger) {
694
+ this.proofServer = proofServer;
695
+ this.logger = logger;
696
+ }
697
+ /**
698
+ * Checks the health status of the indexer service.
699
+ * Makes a GET request to the status endpoint of the indexer service.
700
+ * @returns {Promise<AxiosResponse | void>} A promise that resolves to the response of the health check or logs an error if the request fails.
701
+ */
702
+ async health() {
703
+ const url = buildUrlWithPath(this.proofServer, '/health');
704
+ const response = await axios.get(url, { timeout: HEALTH_CHECK_TIMEOUT_MS });
705
+ this.logger.info(`Connected to proof server ${redactUrl(url)}: ${JSON.stringify(response.data)}`);
706
+ return response;
707
+ }
708
+ /**
709
+ * Proves a transaction by sending a POST request to the proof server.
710
+ * @param data serialized transaction data
711
+ * @param config Axios request configuration
712
+ */
713
+ async proveTx(data, config = {
714
+ timeout: 3 * 60_000
715
+ }) {
716
+ const url = buildUrlWithPath(this.proofServer, '/prove-tx');
717
+ const response = await axios.post(url, data, config);
718
+ this.logger.info(`Received data from proof server ${redactUrl(url)}`);
719
+ return response;
720
+ }
721
+ }
722
+
723
+ /*
724
+ * This file is part of midnight-js.
725
+ * Copyright (C) Midnight Foundation
726
+ * SPDX-License-Identifier: Apache-2.0
727
+ * Licensed under the Apache License, Version 2.0 (the "License");
728
+ * You may not use this file except in compliance with the License.
729
+ * You may obtain a copy of the License at
730
+ * http://www.apache.org/licenses/LICENSE-2.0
731
+ * Unless required by applicable law or agreed to in writing, software
732
+ * distributed under the License is distributed on an "AS IS" BASIS,
733
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
734
+ * See the License for the specific language governing permissions and
735
+ * limitations under the License.
736
+ */
737
+ const ALGORITHM = 'aes-256-gcm';
738
+ const KEY_LENGTH = 32;
739
+ const IV_LENGTH = 12;
740
+ const AUTH_TAG_LENGTH = 16;
741
+ const SALT_LENGTH = 32;
742
+ const PBKDF2_ITERATIONS = 100000;
743
+ const ENCRYPTION_VERSION = 1;
744
+ const MIN_PASSWORD_LENGTH = 16;
745
+ const EXPECTED_SALT_LENGTH = 64;
746
+ const CURRENT_EXPORT_VERSION = 1;
747
+ const SUPPORTED_EXPORT_VERSIONS = [1];
748
+ const deriveKey = (password, salt) => {
749
+ return pbkdf2Sync(password, salt, PBKDF2_ITERATIONS, KEY_LENGTH, 'sha256');
750
+ };
751
+ const encrypt = (data, password, salt) => {
752
+ const key = deriveKey(password, salt);
753
+ const plaintext = Buffer.from(data, 'utf-8');
754
+ const iv = randomBytes(IV_LENGTH);
755
+ const cipher = createCipheriv(ALGORITHM, key, iv);
756
+ const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
757
+ const authTag = cipher.getAuthTag();
758
+ const version = Buffer.from([ENCRYPTION_VERSION]);
759
+ const result = Buffer.concat([version, salt, iv, authTag, encrypted]);
760
+ return result.toString('base64');
761
+ };
762
+ const decrypt = (encryptedData, password, expectedSalt) => {
763
+ const data = Buffer.from(encryptedData, 'base64');
764
+ const headerLength = 1 + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH;
765
+ if (data.length < headerLength) {
766
+ throw new Error('Invalid encrypted data: too short');
767
+ }
768
+ const version = data[0];
769
+ if (version !== ENCRYPTION_VERSION) {
770
+ throw new Error(`Unsupported encryption version: ${version}`);
771
+ }
772
+ const salt = data.subarray(1, 1 + SALT_LENGTH);
773
+ const iv = data.subarray(1 + SALT_LENGTH, 1 + SALT_LENGTH + IV_LENGTH);
774
+ const authTag = data.subarray(1 + SALT_LENGTH + IV_LENGTH, 1 + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
775
+ const encrypted = data.subarray(headerLength);
776
+ if (!expectedSalt.equals(salt)) {
777
+ throw new Error('Salt mismatch');
778
+ }
779
+ const key = deriveKey(password, salt);
780
+ const decipher = createDecipheriv(ALGORITHM, key, iv, { authTagLength: AUTH_TAG_LENGTH });
781
+ decipher.setAuthTag(authTag);
782
+ const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
783
+ return decrypted.toString('utf-8');
784
+ };
785
+ const validateExportPassword = (password) => {
786
+ if (password.length < MIN_PASSWORD_LENGTH) {
787
+ throw new PrivateStateExportError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters`);
788
+ }
789
+ };
790
+ const validateSigningKeyExportPassword = (password) => {
791
+ if (password.length < MIN_PASSWORD_LENGTH) {
792
+ throw new SigningKeyExportError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters`);
793
+ }
794
+ };
795
+ const validateImportPassword = (password) => {
796
+ if (password.length < MIN_PASSWORD_LENGTH) {
797
+ throw new ImportPasswordValidationError(new PasswordValidationError(`Password must be at least ${MIN_PASSWORD_LENGTH} characters`, 'too_short'));
798
+ }
799
+ };
800
+ const validateSalt = (salt) => {
801
+ if (salt.length !== EXPECTED_SALT_LENGTH) {
802
+ throw new InvalidExportFormatError('Invalid salt length');
803
+ }
804
+ if (!/^[0-9a-fA-F]+$/.test(salt)) {
805
+ throw new InvalidExportFormatError('Invalid salt format');
806
+ }
807
+ };
808
+ const validateSigningKeyAddress = (address) => {
809
+ try {
810
+ assertIsContractAddress(address);
811
+ }
812
+ catch (error) {
813
+ if (!(error instanceof InvalidArgumentError)) {
814
+ throw error;
815
+ }
816
+ throw new InvalidExportFormatError(`Invalid contract address in import: ${error.message}`);
817
+ }
818
+ };
819
+ const validateSigningKeyValue = (value) => {
820
+ if (!isValidSigningKey(value)) {
821
+ throw new InvalidExportFormatError('Invalid signing key value');
822
+ }
823
+ };
824
+ const storedAddress = (address) => address.toLowerCase();
825
+ /**
826
+ * A simple in-memory implementation of private state provider. Makes it easy to capture and rewrite private state from deploy.
827
+ *
828
+ * Note: Unlike `levelPrivateStateProvider`, this provider has no storage password configured.
829
+ * Therefore, export/import operations always require an explicit password in the options.
830
+ *
831
+ * @template PSI - Type of the private state identifier.
832
+ * @template PS - Type of the private state.
833
+ * @returns {PrivateStateProvider<PSI, PS>} An in-memory private state provider.
834
+ */
835
+ const inMemoryPrivateStateProvider = () => {
836
+ const record = new Map();
837
+ const signingKeys = {};
838
+ const contractPrivateStates = (contractAddress) => {
839
+ const prefix = `${contractAddress}:`;
840
+ const scopedKey = (key) => `${prefix}${key}`;
841
+ const ownKeys = () => Array.from(record.keys()).filter((key) => key.startsWith(prefix));
842
+ return {
843
+ contractAddress,
844
+ /**
845
+ * Sets the private state for a given key.
846
+ * @param {PSI} key - The key for the private state.
847
+ * @param {PS} state - The private state to set.
848
+ * @returns {Promise<void>} A promise that resolves when the state is set.
849
+ */
850
+ set(key, state) {
851
+ record.set(scopedKey(key), state);
852
+ return Promise.resolve();
853
+ },
854
+ /**
855
+ * Gets the private state for a given key.
856
+ * @param {PSI} key - The key for the private state.
857
+ * @returns {Promise<PS | null>} A promise that resolves to the private state or null if not found.
858
+ */
859
+ get(key) {
860
+ const value = record.get(scopedKey(key)) ?? null;
861
+ return Promise.resolve(value);
862
+ },
863
+ /**
864
+ * Removes the private state for a given key.
865
+ * @param {PSI} key - The key for the private state.
866
+ * @returns {Promise<void>} A promise that resolves when the state is removed.
867
+ */
868
+ remove(key) {
869
+ record.delete(scopedKey(key));
870
+ return Promise.resolve();
871
+ },
872
+ /**
873
+ * Clears the private states of this contract.
874
+ * @returns {Promise<void>} A promise that resolves when the states are cleared.
875
+ */
876
+ clear() {
877
+ ownKeys().forEach((key) => record.delete(key));
878
+ return Promise.resolve();
879
+ },
880
+ /**
881
+ * Exports the private states of this contract as an encrypted JSON-serializable structure.
882
+ * @param {ExportPrivateStatesOptions} options - Export options including password.
883
+ * @returns {Promise<PrivateStateExport>} A promise that resolves to the export structure.
884
+ */
885
+ async exportPrivateStates(options) {
886
+ const maxStates = options?.maxStates ?? MAX_EXPORT_STATES;
887
+ if (!options?.password) {
888
+ throw new PrivateStateExportError('Password is required for in-memory provider export');
889
+ }
890
+ validateExportPassword(options.password);
891
+ const keys = ownKeys();
892
+ if (keys.length === 0) {
893
+ throw new PrivateStateExportError('No private states to export');
894
+ }
895
+ if (keys.length > maxStates) {
896
+ throw new PrivateStateExportError(`Too many states to export (${keys.length}). Maximum allowed: ${maxStates}`);
897
+ }
898
+ const payload = {
899
+ version: CURRENT_EXPORT_VERSION,
900
+ exportedAt: new Date().toISOString(),
901
+ stateCount: keys.length,
902
+ states: Object.fromEntries(keys.map((key) => [key.slice(prefix.length), JSON.stringify(record.get(key))]))
903
+ };
904
+ const salt = randomBytes(SALT_LENGTH);
905
+ const encryptedPayload = encrypt(JSON.stringify(payload), options.password, salt);
906
+ return {
907
+ format: 'midnight-private-state-export',
908
+ encryptedPayload,
909
+ salt: salt.toString('hex')
910
+ };
911
+ },
912
+ /**
913
+ * Imports private states from a previously exported structure into this contract.
914
+ * @param {PrivateStateExport} exportData - The export data structure to import.
915
+ * @param {ImportPrivateStatesOptions} options - Import options including password and conflict strategy.
916
+ * @returns {Promise<ImportPrivateStatesResult>} A promise that resolves to the import result.
917
+ */
918
+ async importPrivateStates(exportData, options) {
919
+ const conflictStrategy = options?.conflictStrategy ?? 'error';
920
+ const maxStates = options?.maxStates ?? MAX_EXPORT_STATES;
921
+ if (exportData.format !== 'midnight-private-state-export') {
922
+ throw new InvalidExportFormatError('Unrecognized export format');
923
+ }
924
+ if (!exportData.encryptedPayload || !exportData.salt) {
925
+ throw new InvalidExportFormatError('Missing required fields');
926
+ }
927
+ validateSalt(exportData.salt);
928
+ if (!options?.password) {
929
+ throw new InvalidExportFormatError('Password is required for in-memory provider import');
930
+ }
931
+ validateImportPassword(options.password);
932
+ let payload;
933
+ try {
934
+ const salt = Buffer.from(exportData.salt, 'hex');
935
+ const decryptedJson = decrypt(exportData.encryptedPayload, options.password, salt);
936
+ payload = JSON.parse(decryptedJson);
937
+ }
938
+ catch {
939
+ throw new ExportDecryptionError();
940
+ }
941
+ if (!payload.states ||
942
+ typeof payload.states !== 'object' ||
943
+ typeof payload.version !== 'number' ||
944
+ typeof payload.stateCount !== 'number') {
945
+ throw new ExportDecryptionError();
946
+ }
947
+ if (!SUPPORTED_EXPORT_VERSIONS.includes(payload.version)) {
948
+ throw new InvalidExportFormatError(`Export version ${payload.version} is not supported. Supported versions: ${SUPPORTED_EXPORT_VERSIONS.join(', ')}`);
949
+ }
950
+ const stateIds = Object.keys(payload.states);
951
+ if (stateIds.length !== payload.stateCount) {
952
+ throw new ExportDecryptionError();
953
+ }
954
+ if (stateIds.length > maxStates) {
955
+ throw new InvalidExportFormatError(`Too many states in export (${stateIds.length}). Maximum allowed: ${maxStates}`);
956
+ }
957
+ if (conflictStrategy === 'error') {
958
+ const conflictCount = stateIds.filter((id) => record.has(scopedKey(id))).length;
959
+ if (conflictCount > 0) {
960
+ throw new ImportConflictError(conflictCount);
961
+ }
962
+ }
963
+ let imported = 0;
964
+ let skipped = 0;
965
+ let overwritten = 0;
966
+ for (const stateId of stateIds) {
967
+ const serializedState = payload.states[stateId];
968
+ const existingState = record.get(scopedKey(stateId));
969
+ if (existingState !== undefined) {
970
+ if (conflictStrategy === 'skip') {
971
+ skipped++;
972
+ continue;
973
+ }
974
+ else if (conflictStrategy === 'overwrite') {
975
+ overwritten++;
976
+ }
977
+ }
978
+ const state = JSON.parse(serializedState);
979
+ record.set(scopedKey(stateId), state);
980
+ if (existingState === undefined) {
981
+ imported++;
982
+ }
983
+ }
984
+ return { imported, skipped, overwritten };
985
+ }
986
+ };
987
+ };
988
+ return {
989
+ /**
990
+ * Returns the private states of the contract at the given address.
991
+ * @param {ContractAddress} contractAddress - The contract address the view is fixed to.
992
+ * @returns {ContractPrivateStates<PSI, PS>} The per-contract view.
993
+ */
994
+ forContract(contractAddress) {
995
+ assertIsContractAddress(contractAddress);
996
+ return contractPrivateStates(storedAddress(contractAddress));
997
+ },
998
+ /**
999
+ * Clears the private states of every contract.
1000
+ * @returns {Promise<void>} A promise that resolves when all states are cleared.
1001
+ */
1002
+ clearAll() {
1003
+ record.clear();
1004
+ return Promise.resolve();
1005
+ },
1006
+ /**
1007
+ * Sets the signing key for a given contract address.
1008
+ * @param {ContractAddress} address - The contract address.
1009
+ * @param {SigningKey} signingKey - The signing key to set.
1010
+ * @returns {Promise<void>} A promise that resolves when the signing key is set.
1011
+ * @throws {InvalidArgumentError} If `address` is not a contract address.
1012
+ */
1013
+ async setSigningKey(address, signingKey) {
1014
+ assertIsContractAddress(address);
1015
+ signingKeys[storedAddress(address)] = signingKey;
1016
+ },
1017
+ /**
1018
+ * Gets the signing key for a given contract address.
1019
+ * @param {ContractAddress} address - The contract address.
1020
+ * @returns {Promise<SigningKey | null>} A promise that resolves to the signing key or null if not found.
1021
+ * @throws {InvalidArgumentError} If `address` is not a contract address.
1022
+ */
1023
+ async getSigningKey(address) {
1024
+ assertIsContractAddress(address);
1025
+ return signingKeys[storedAddress(address)] ?? null;
1026
+ },
1027
+ /**
1028
+ * Removes the signing key for a given contract address.
1029
+ * @param {ContractAddress} address - The contract address.
1030
+ * @returns {Promise<void>} A promise that resolves when the signing key is removed.
1031
+ * @throws {InvalidArgumentError} If `address` is not a contract address.
1032
+ */
1033
+ async removeSigningKey(address) {
1034
+ assertIsContractAddress(address);
1035
+ delete signingKeys[storedAddress(address)];
1036
+ },
1037
+ /**
1038
+ * Clears all signing keys.
1039
+ * @returns {Promise<void>} A promise that resolves when all signing keys are cleared.
1040
+ */
1041
+ clearSigningKeys() {
1042
+ Object.keys(signingKeys).forEach((addr) => {
1043
+ delete signingKeys[addr];
1044
+ });
1045
+ return Promise.resolve();
1046
+ },
1047
+ /**
1048
+ * Exports all signing keys as an encrypted JSON-serializable structure.
1049
+ * @param {ExportSigningKeysOptions} options - Export options including password.
1050
+ * @returns {Promise<SigningKeyExport>} A promise that resolves to the export structure.
1051
+ */
1052
+ async exportSigningKeys(options) {
1053
+ const maxKeys = options?.maxKeys ?? MAX_EXPORT_SIGNING_KEYS;
1054
+ if (!options?.password) {
1055
+ throw new SigningKeyExportError('Password is required for in-memory provider export');
1056
+ }
1057
+ validateSigningKeyExportPassword(options.password);
1058
+ const keyCount = Object.keys(signingKeys).length;
1059
+ if (keyCount === 0) {
1060
+ throw new SigningKeyExportError('No signing keys to export');
1061
+ }
1062
+ if (keyCount > maxKeys) {
1063
+ throw new SigningKeyExportError(`Too many keys to export (${keyCount}). Maximum allowed: ${maxKeys}`);
1064
+ }
1065
+ const payload = {
1066
+ version: CURRENT_EXPORT_VERSION,
1067
+ exportedAt: new Date().toISOString(),
1068
+ keyCount,
1069
+ keys: { ...signingKeys }
1070
+ };
1071
+ const salt = randomBytes(SALT_LENGTH);
1072
+ const encryptedPayload = encrypt(JSON.stringify(payload), options.password, salt);
1073
+ return {
1074
+ format: 'midnight-signing-key-export',
1075
+ encryptedPayload,
1076
+ salt: salt.toString('hex')
1077
+ };
1078
+ },
1079
+ /**
1080
+ * Imports signing keys from a previously exported structure.
1081
+ * @param {SigningKeyExport} exportData - The export data structure to import.
1082
+ * @param {ImportSigningKeysOptions} options - Import options including password and conflict strategy.
1083
+ * @returns {Promise<ImportSigningKeysResult>} A promise that resolves to the import result.
1084
+ */
1085
+ async importSigningKeys(exportData, options) {
1086
+ const conflictStrategy = options?.conflictStrategy ?? 'error';
1087
+ const maxKeys = options?.maxKeys ?? MAX_EXPORT_SIGNING_KEYS;
1088
+ if (exportData.format !== 'midnight-signing-key-export') {
1089
+ throw new InvalidExportFormatError('Unrecognized export format');
1090
+ }
1091
+ if (!exportData.encryptedPayload || !exportData.salt) {
1092
+ throw new InvalidExportFormatError('Missing required fields');
1093
+ }
1094
+ validateSalt(exportData.salt);
1095
+ if (!options?.password) {
1096
+ throw new InvalidExportFormatError('Password is required for in-memory provider import');
1097
+ }
1098
+ validateImportPassword(options.password);
1099
+ let payload;
1100
+ try {
1101
+ const salt = Buffer.from(exportData.salt, 'hex');
1102
+ const decryptedJson = decrypt(exportData.encryptedPayload, options.password, salt);
1103
+ payload = JSON.parse(decryptedJson);
1104
+ }
1105
+ catch {
1106
+ throw new ExportDecryptionError();
1107
+ }
1108
+ if (!payload.keys ||
1109
+ typeof payload.keys !== 'object' ||
1110
+ typeof payload.version !== 'number' ||
1111
+ typeof payload.keyCount !== 'number') {
1112
+ throw new ExportDecryptionError();
1113
+ }
1114
+ if (!SUPPORTED_EXPORT_VERSIONS.includes(payload.version)) {
1115
+ throw new InvalidExportFormatError(`Export version ${payload.version} is not supported. Supported versions: ${SUPPORTED_EXPORT_VERSIONS.join(', ')}`);
1116
+ }
1117
+ const addresses = Object.keys(payload.keys);
1118
+ if (addresses.length !== payload.keyCount) {
1119
+ throw new ExportDecryptionError();
1120
+ }
1121
+ if (addresses.length > maxKeys) {
1122
+ throw new InvalidExportFormatError(`Too many keys in export (${addresses.length}). Maximum allowed: ${maxKeys}`);
1123
+ }
1124
+ for (const address of addresses) {
1125
+ validateSigningKeyAddress(address);
1126
+ validateSigningKeyValue(payload.keys[address]);
1127
+ }
1128
+ if (conflictStrategy === 'error') {
1129
+ const conflictCount = addresses.filter((addr) => signingKeys[storedAddress(addr)] !== undefined).length;
1130
+ if (conflictCount > 0) {
1131
+ throw new ImportConflictError(conflictCount, 'signing key');
1132
+ }
1133
+ }
1134
+ let imported = 0;
1135
+ let skipped = 0;
1136
+ let overwritten = 0;
1137
+ for (const address of addresses) {
1138
+ const signingKey = payload.keys[address];
1139
+ const existingKey = signingKeys[storedAddress(address)];
1140
+ if (existingKey !== undefined) {
1141
+ if (conflictStrategy === 'skip') {
1142
+ skipped++;
1143
+ continue;
1144
+ }
1145
+ else if (conflictStrategy === 'overwrite') {
1146
+ overwritten++;
1147
+ }
1148
+ }
1149
+ signingKeys[storedAddress(address)] = signingKey;
1150
+ if (existingKey === undefined) {
1151
+ imported++;
1152
+ }
1153
+ }
1154
+ return { imported, skipped, overwritten };
1155
+ }
1156
+ };
1157
+ };
1158
+
1159
+ /*
1160
+ * This file is part of midnight-js.
1161
+ * Copyright (C) Midnight Foundation
1162
+ * SPDX-License-Identifier: Apache-2.0
1163
+ * Licensed under the Apache License, Version 2.0 (the "License");
1164
+ * You may not use this file except in compliance with the License.
1165
+ * You may obtain a copy of the License at
1166
+ * http://www.apache.org/licenses/LICENSE-2.0
1167
+ * Unless required by applicable law or agreed to in writing, software
1168
+ * distributed under the License is distributed on an "AS IS" BASIS,
1169
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1170
+ * See the License for the specific language governing permissions and
1171
+ * limitations under the License.
1172
+ */
1173
+ /**
1174
+ * Configures and returns the required providers for a Midnight contract.
1175
+ *
1176
+ * @template PCK - Type parameter for the input circuit key string
1177
+ * @template PS - Type parameter for the private state
1178
+ *
1179
+ * @param {MidnightWalletProvider} midnightWalletProvider - The midnightWalletProvider provider instance to use for transactions
1180
+ * @param {EnvironmentConfiguration} environmentConfiguration - Configuration for the environment including indexer and proof server details
1181
+ * @param {ContractConfiguration} contractConfiguration - Configuration specific to the contract including storage names and ZK config path
1182
+ *
1183
+ * @returns {MidnightProviders} An object containing all configured providers:
1184
+ * - privateStateProvider: For managing private contract state
1185
+ * - publicDataProvider: For accessing public blockchain data
1186
+ * - zkConfigProvider: For zero-knowledge proof configurations
1187
+ * - proofProvider: For generating and verifying proofs
1188
+ * - walletProvider: For midnightWalletProvider operations
1189
+ * - midnightProvider: For Midnight-specific operations
1190
+ * - config: The environment's network id and a one-hour TTL
1191
+ *
1192
+ * @throws InvalidArgumentError If `environmentConfiguration.networkId` is not a non-empty string without surrounding whitespace,
1193
+ * reported by {@link createMidnightProviders} as `providers.config.networkId`.
1194
+ */
1195
+ const initializeMidnightProviders = (midnightWalletProvider, environmentConfiguration, contractConfiguration) => {
1196
+ const zkConfigProvider = new NodeZkConfigProvider(contractConfiguration.zkConfigPath, contractConfiguration.zkConfigIntegrity);
1197
+ return createMidnightProviders({
1198
+ privateStateProvider: levelPrivateStateProvider({
1199
+ privateStateStoreName: contractConfiguration.privateStateStoreName,
1200
+ signingKeyStoreName: `${contractConfiguration.privateStateStoreName}-signing-keys`,
1201
+ privateStoragePasswordProvider: () => { return 'Answer to the Ultimate Question of Life, the Universe, and Everything!'; },
1202
+ accountId: midnightWalletProvider.getCoinPublicKey()
1203
+ }),
1204
+ publicDataProvider: indexerPublicDataProvider(environmentConfiguration.indexer, environmentConfiguration.indexerWS),
1205
+ zkConfigProvider,
1206
+ proofProvider: httpClientProofProvider(environmentConfiguration.proofServer, zkConfigProvider),
1207
+ walletProvider: midnightWalletProvider,
1208
+ midnightProvider: midnightWalletProvider,
1209
+ config: { networkId: environmentConfiguration.networkId, ttlSeconds: 3600 }
1210
+ });
1211
+ };
1212
+
1213
+ /*
1214
+ * This file is part of midnight-js.
1215
+ * Copyright (C) Midnight Foundation
1216
+ * SPDX-License-Identifier: Apache-2.0
1217
+ * Licensed under the Apache License, Version 2.0 (the "License");
1218
+ * You may not use this file except in compliance with the License.
1219
+ * You may obtain a copy of the License at
1220
+ * http://www.apache.org/licenses/LICENSE-2.0
1221
+ * Unless required by applicable law or agreed to in writing, software
1222
+ * distributed under the License is distributed on an "AS IS" BASIS,
1223
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1224
+ * See the License for the specific language governing permissions and
1225
+ * limitations under the License.
1226
+ */
1227
+ /**
1228
+ * A proof server container that is started and stopped dynamically by the test
1229
+ * suite on random port.
1230
+ */
1231
+ class DynamicProofServerContainer {
1232
+ /** The Docker Compose environment running the container */
1233
+ dockerEnv;
1234
+ /** Unique identifier for the container instance */
1235
+ uid;
1236
+ /** Configuration for the proof server container */
1237
+ config;
1238
+ /**
1239
+ * Creates a new DynamicProofServerContainer instance.
1240
+ * @param {StartedDockerComposeEnvironment} dockerEnv - The started Docker Compose environment
1241
+ * @param {string} uid - Unique identifier for the container
1242
+ * @private
1243
+ */
1244
+ constructor(dockerEnv, uid) {
1245
+ this.dockerEnv = dockerEnv;
1246
+ this.uid = uid;
1247
+ this.config = getContainersConfiguration().proofServer;
1248
+ }
1249
+ /**
1250
+ * Starts a new proof server container.
1251
+ * @param {Logger} logger - Logger instance for recording operations
1252
+ * @param {string} [maybeUID] - Optional unique identifier for the container
1253
+ * @param {string} [maybeNetworkId] - Optional network ID for the container
1254
+ * @returns {Promise<DynamicProofServerContainer>} A promise that resolves to the new container instance
1255
+ */
1256
+ static async start(logger, maybeUID, maybeNetworkId) {
1257
+ const config = getContainersConfiguration().proofServer;
1258
+ const uid = maybeUID ?? Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString();
1259
+ const networkId = maybeNetworkId;
1260
+ logger.info(`Starting proof server: path='${config.path}', file=${config.fileName}, networkId=${networkId}, uid=${uid}`);
1261
+ const dockerEnv = await new DockerComposeEnvironment(config.path, config.fileName)
1262
+ .withWaitStrategy(`${config.container.name}_${uid}`, config.container.waitStrategy)
1263
+ .withEnvironment({
1264
+ TESTCONTAINERS_UID: uid,
1265
+ NETWORK_ID: networkId ?? 'undeployed'
1266
+ })
1267
+ .up();
1268
+ return new DynamicProofServerContainer(dockerEnv, uid);
1269
+ }
1270
+ /**
1271
+ * Stops the proof server container.
1272
+ * @returns {Promise<void>} A promise that resolves when the container is stopped
1273
+ */
1274
+ async stop() {
1275
+ await this.dockerEnv.stop();
1276
+ }
1277
+ /**
1278
+ * Gets the mapped port number for the container.
1279
+ * @returns {number} The mapped port number
1280
+ */
1281
+ getMappedPort() {
1282
+ return this.dockerEnv
1283
+ .getContainer(`${this.config.container.name}_${this.uid}`)
1284
+ .getMappedPort(this.config.container.port);
1285
+ }
1286
+ /**
1287
+ * Gets the URL where the proof server can be accessed.
1288
+ * @returns {string} The URL of the proof server
1289
+ */
1290
+ getUrl() {
1291
+ return `http://localhost:${this.getMappedPort()}`;
1292
+ }
1293
+ }
1294
+ /**
1295
+ * A proof server that is currently running on a specific port.
1296
+ * Used for connecting to an existing proof server instance.
1297
+ */
1298
+ class StaticProofServerContainer {
1299
+ /** The port number where the proof server is running */
1300
+ port;
1301
+ /**
1302
+ * Creates a new StaticProofServerContainer instance.
1303
+ * @param {number} port - The port number where the proof server is running (default: 6300)
1304
+ */
1305
+ constructor(port = 6300) {
1306
+ this.port = port;
1307
+ }
1308
+ /**
1309
+ * Gets the URL where the proof server can be accessed.
1310
+ * @returns {string} The URL of the proof server
1311
+ */
1312
+ getUrl() {
1313
+ return `http://localhost:${this.port}`;
1314
+ }
1315
+ /**
1316
+ * No-op stop method since this represents an external proof server.
1317
+ * @returns {Promise<void>} A resolved promise
1318
+ */
1319
+ stop() {
1320
+ return Promise.resolve(undefined);
1321
+ }
1322
+ }
1323
+
1324
+ /*
1325
+ * This file is part of midnight-js.
1326
+ * Copyright (C) Midnight Foundation
1327
+ * SPDX-License-Identifier: Apache-2.0
1328
+ * Licensed under the Apache License, Version 2.0 (the "License");
1329
+ * You may not use this file except in compliance with the License.
1330
+ * You may obtain a copy of the License at
1331
+ * http://www.apache.org/licenses/LICENSE-2.0
1332
+ * Unless required by applicable law or agreed to in writing, software
1333
+ * distributed under the License is distributed on an "AS IS" BASIS,
1334
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1335
+ * See the License for the specific language governing permissions and
1336
+ * limitations under the License.
1337
+ */
1338
+ const getEnvVarEnvironment = () => {
1339
+ if (process.env.MN_TEST_ENVIRONMENT === undefined || process.env.MN_TEST_ENVIRONMENT === 'undefined') {
1340
+ return 'undeployed';
1341
+ }
1342
+ return process.env.MN_TEST_ENVIRONMENT;
1343
+ };
1344
+ const getEnvVarWalletSeeds = () => {
1345
+ const envSeeds = process.env.MN_TEST_WALLET_SEED || process.env.TEST_WALLET_SEED;
1346
+ return envSeeds ? envSeeds.split(',') : undefined;
1347
+ };
1348
+ const getMnTestIndexer = () => process.env.MN_TEST_INDEXER;
1349
+ const getMnTestIndexerWs = () => process.env.MN_TEST_INDEXER_WS;
1350
+ const getMnTestNode = () => process.env.MN_TEST_NODE;
1351
+ const getMnTestNodeWs = () => process.env.MN_TEST_NODE_WS;
1352
+ const getMnTestFaucet = () => process.env.MN_TEST_FAUCET;
1353
+ const getMnTestNetworkId = () => process.env.MN_TEST_NETWORK_ID;
1354
+ const getMnTestWalletNetworkId = () => process.env.MN_TEST_WALLET_NETWORK_ID;
1355
+
1356
+ /*
1357
+ * This file is part of midnight-js.
1358
+ * Copyright (C) Midnight Foundation
1359
+ * SPDX-License-Identifier: Apache-2.0
1360
+ * Licensed under the Apache License, Version 2.0 (the "License");
1361
+ * You may not use this file except in compliance with the License.
1362
+ * You may obtain a copy of the License at
1363
+ * http://www.apache.org/licenses/LICENSE-2.0
1364
+ * Unless required by applicable law or agreed to in writing, software
1365
+ * distributed under the License is distributed on an "AS IS" BASIS,
1366
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1367
+ * See the License for the specific language governing permissions and
1368
+ * limitations under the License.
1369
+ */
1370
+ /**
1371
+ * An error representing a required, but missing, environment variable.
1372
+ */
1373
+ class MissingEnvironmentVariable extends Error {
1374
+ environmentVariable;
1375
+ /**
1376
+ * @param environmentVariable The name of the missing environment variable.
1377
+ */
1378
+ constructor(environmentVariable) {
1379
+ super(`Environment variable '${environmentVariable}' is required`);
1380
+ this.environmentVariable = environmentVariable;
1381
+ }
1382
+ }
1383
+
1384
+ /*
1385
+ * This file is part of midnight-js.
1386
+ * Copyright (C) Midnight Foundation
1387
+ * SPDX-License-Identifier: Apache-2.0
1388
+ * Licensed under the Apache License, Version 2.0 (the "License");
1389
+ * You may not use this file except in compliance with the License.
1390
+ * You may obtain a copy of the License at
1391
+ * http://www.apache.org/licenses/LICENSE-2.0
1392
+ * Unless required by applicable law or agreed to in writing, software
1393
+ * distributed under the License is distributed on an "AS IS" BASIS,
1394
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1395
+ * See the License for the specific language governing permissions and
1396
+ * limitations under the License.
1397
+ */
1398
+ BigInt.prototype.toJSON = function () {
1399
+ return this.toString();
1400
+ };
1401
+
1402
+ /*
1403
+ * This file is part of midnight-js.
1404
+ * Copyright (C) Midnight Foundation
1405
+ * SPDX-License-Identifier: Apache-2.0
1406
+ * Licensed under the Apache License, Version 2.0 (the "License");
1407
+ * You may not use this file except in compliance with the License.
1408
+ * You may obtain a copy of the License at
1409
+ * http://www.apache.org/licenses/LICENSE-2.0
1410
+ * Unless required by applicable law or agreed to in writing, software
1411
+ * distributed under the License is distributed on an "AS IS" BASIS,
1412
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1413
+ * See the License for the specific language governing permissions and
1414
+ * limitations under the License.
1415
+ */
1416
+ class DAppConnectorInitialAPI {
1417
+ rdns;
1418
+ name;
1419
+ icon;
1420
+ apiVersion;
1421
+ connectedWallet;
1422
+ expectedNetworkId;
1423
+ constructor(connectedWallet, networkId, options) {
1424
+ this.connectedWallet = connectedWallet;
1425
+ this.expectedNetworkId = networkId;
1426
+ this.rdns = options?.rdns ?? 'com.midnight.test-wallet';
1427
+ this.name = options?.name ?? 'Test Wallet';
1428
+ this.icon = options?.icon ?? 'data:image/svg+xml,<svg/>';
1429
+ this.apiVersion = options?.apiVersion ?? '4.0.1';
1430
+ }
1431
+ async connect(networkId) {
1432
+ if (networkId !== this.expectedNetworkId) {
1433
+ throw new Error(`Network ID mismatch: expected '${this.expectedNetworkId}', got '${networkId}'`);
1434
+ }
1435
+ return this.connectedWallet;
1436
+ }
1437
+ }
1438
+
1439
+ /*
1440
+ * This file is part of midnight-js.
1441
+ * Copyright (C) Midnight Foundation
1442
+ * SPDX-License-Identifier: Apache-2.0
1443
+ * Licensed under the Apache License, Version 2.0 (the "License");
1444
+ * You may not use this file except in compliance with the License.
1445
+ * You may obtain a copy of the License at
1446
+ * http://www.apache.org/licenses/LICENSE-2.0
1447
+ * Unless required by applicable law or agreed to in writing, software
1448
+ * distributed under the License is distributed on an "AS IS" BASIS,
1449
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1450
+ * See the License for the specific language governing permissions and
1451
+ * limitations under the License.
1452
+ */
1453
+ const invalidRequest = (reason, cause) => Object.assign(new Error(reason, { cause }), {
1454
+ type: 'DAppConnectorAPIError',
1455
+ code: ErrorCodes.InvalidRequest,
1456
+ reason,
1457
+ });
1458
+ class DAppConnectorWalletAdapter {
1459
+ walletProvider;
1460
+ environmentConfiguration;
1461
+ cachedDefaultKeyMaterialProvider;
1462
+ constructor(walletProvider, environmentConfiguration) {
1463
+ this.walletProvider = walletProvider;
1464
+ this.environmentConfiguration = environmentConfiguration;
1465
+ }
1466
+ async getShieldedAddresses() {
1467
+ const state = await firstValueFrom(this.walletProvider.wallet.shielded.state);
1468
+ return {
1469
+ shieldedAddress: MidnightBech32m.encode(this.environmentConfiguration.networkId, state.address).asString(),
1470
+ shieldedCoinPublicKey: state.address.coinPublicKeyString(),
1471
+ shieldedEncryptionPublicKey: state.address.encryptionPublicKeyString(),
1472
+ };
1473
+ }
1474
+ async getUnshieldedAddress() {
1475
+ return {
1476
+ unshieldedAddress: this.walletProvider.unshieldedKeystore.getBech32Address().asString(),
1477
+ };
1478
+ }
1479
+ async getDustAddress() {
1480
+ return {
1481
+ dustAddress: DustAddress.encodePublicKey(this.environmentConfiguration.networkId, this.walletProvider.dustSecretKey.publicKey),
1482
+ };
1483
+ }
1484
+ async getShieldedBalances() {
1485
+ const state = await firstValueFrom(this.walletProvider.wallet.shielded.state);
1486
+ return state.balances;
1487
+ }
1488
+ async getUnshieldedBalances() {
1489
+ const state = await firstValueFrom(this.walletProvider.wallet.unshielded.state);
1490
+ return state.balances;
1491
+ }
1492
+ async getDustBalance() {
1493
+ const state = await firstValueFrom(this.walletProvider.wallet.dust.state);
1494
+ return {
1495
+ balance: state.balance(new Date()),
1496
+ cap: 0n,
1497
+ };
1498
+ }
1499
+ async balanceUnsealedTransaction(tx, options) {
1500
+ const tokenKindsToBalance = options?.payFees === false ? ['shielded', 'unshielded'] : 'all';
1501
+ const unbound = this.adopt(tx, 'Unbound');
1502
+ const recipe = await this.walletProvider.wallet.balanceUnboundTransaction(unbound, {
1503
+ ttl: ttlOneHour(),
1504
+ tokenKindsToBalance,
1505
+ });
1506
+ return this.signAndFinalize(recipe);
1507
+ }
1508
+ async balanceSealedTransaction(tx, options) {
1509
+ const tokenKindsToBalance = options?.payFees === false ? ['shielded', 'unshielded'] : 'all';
1510
+ const finalized = this.adopt(tx, 'Finalized');
1511
+ const recipe = await this.walletProvider.wallet.balanceFinalizedTransaction(finalized, {
1512
+ ttl: ttlOneHour(),
1513
+ tokenKindsToBalance,
1514
+ });
1515
+ return this.signAndFinalize(recipe);
1516
+ }
1517
+ async submitTransaction(tx) {
1518
+ const finalized = this.adopt(tx, 'Finalized');
1519
+ await this.walletProvider.wallet.submitTransaction(finalized);
1520
+ }
1521
+ async signData(data, options) {
1522
+ let bytes;
1523
+ switch (options.encoding) {
1524
+ case 'hex':
1525
+ bytes = fromHex(data);
1526
+ break;
1527
+ case 'base64':
1528
+ bytes = Buffer.from(data, 'base64');
1529
+ break;
1530
+ case 'text':
1531
+ bytes = Buffer.from(data, 'utf-8');
1532
+ break;
1533
+ }
1534
+ const signature = this.walletProvider.unshieldedKeystore.signData(bytes);
1535
+ return {
1536
+ data,
1537
+ signature: signature.value,
1538
+ verifyingKey: this.walletProvider.unshieldedKeystore.getPublicKey().value,
1539
+ };
1540
+ }
1541
+ async getProvingProvider(keyMaterialProvider) {
1542
+ const defaultProvider = this.getDefaultKeyMaterialProvider();
1543
+ const zkirProvider = {
1544
+ async lookupKey(keyLocation) {
1545
+ const [ir, proverKey, verifierKey] = await Promise.all([
1546
+ keyMaterialProvider.getZKIR(keyLocation),
1547
+ keyMaterialProvider.getProverKey(keyLocation),
1548
+ keyMaterialProvider.getVerifierKey(keyLocation),
1549
+ ]);
1550
+ return { ir, proverKey, verifierKey };
1551
+ },
1552
+ async getParams(k) {
1553
+ return defaultProvider.getParams(k);
1554
+ },
1555
+ };
1556
+ // compactc 0.36 emits ZKIR v3 only, so the prover engine is zkir-v3's provingProvider. Its SRS params
1557
+ // still come from WasmProver (wallet-sdk-prover-client), which is built on @midnight-ntwrk/zkir-v2 ^2.1.0.
1558
+ // An engine/params mismatch yields proofs the node rejects as InvalidProof (RPC 1010, Custom error 115).
1559
+ return provingProvider(zkirProvider);
1560
+ }
1561
+ async getConfiguration() {
1562
+ return {
1563
+ indexerUri: this.environmentConfiguration.indexer,
1564
+ indexerWsUri: this.environmentConfiguration.indexerWS,
1565
+ proverServerUri: this.environmentConfiguration.proofServer,
1566
+ substrateNodeUri: this.environmentConfiguration.node,
1567
+ networkId: this.environmentConfiguration.networkId,
1568
+ };
1569
+ }
1570
+ async getConnectionStatus() {
1571
+ return { status: 'connected', networkId: this.environmentConfiguration.networkId };
1572
+ }
1573
+ async hintUsage(_methodNames) {
1574
+ // No-op for test wallet
1575
+ }
1576
+ async makeTransfer(_desiredOutputs, _options) {
1577
+ throw new Error('Not implemented in DAppConnectorWalletAdapter');
1578
+ }
1579
+ async makeIntent(_desiredInputs, _desiredOutputs, _options) {
1580
+ throw new Error('Not implemented in DAppConnectorWalletAdapter');
1581
+ }
1582
+ async getTxHistory(_pageNumber, _pageSize) {
1583
+ throw new Error('Not implemented in DAppConnectorWalletAdapter');
1584
+ }
1585
+ /**
1586
+ * Reads a transaction a dApp handed over, at the protocol version the wallet is acting at.
1587
+ *
1588
+ * A refusal here says the dApp's bytes are unreadable -- authored against the other side of a protocol boundary,
1589
+ * or at another stage -- not that the wallet failed. That is the connector's `InvalidRequest`, so it reaches the
1590
+ * caller in the connector's own vocabulary rather than the wallet SDK's, with the refusal kept as the cause.
1591
+ */
1592
+ adopt(tx, stage) {
1593
+ try {
1594
+ return this.walletProvider.wallet.adoptTransaction(fromHex(tx), stage);
1595
+ }
1596
+ catch (cause) {
1597
+ throw invalidRequest(`The transaction could not be read at stage ${stage} as this wallet's protocol version.`, cause);
1598
+ }
1599
+ }
1600
+ async signAndFinalize(recipe) {
1601
+ const signed = await this.walletProvider.wallet.signRecipe(recipe, (payload) => this.walletProvider.unshieldedKeystore.signDataAsync(payload));
1602
+ const finalized = await this.walletProvider.wallet.finalizeRecipe(signed);
1603
+ return { tx: toHex(finalized.serialize()) };
1604
+ }
1605
+ getDefaultKeyMaterialProvider() {
1606
+ this.cachedDefaultKeyMaterialProvider ??= WasmProver.makeDefaultKeyMaterialProvider();
1607
+ return this.cachedDefaultKeyMaterialProvider;
1608
+ }
1609
+ }
1610
+
1611
+ /*
1612
+ * This file is part of midnight-js.
1613
+ * Copyright (C) Midnight Foundation
1614
+ * SPDX-License-Identifier: Apache-2.0
1615
+ * Licensed under the Apache License, Version 2.0 (the "License");
1616
+ * You may not use this file except in compliance with the License.
1617
+ * You may obtain a copy of the License at
1618
+ * http://www.apache.org/licenses/LICENSE-2.0
1619
+ * Unless required by applicable law or agreed to in writing, software
1620
+ * distributed under the License is distributed on an "AS IS" BASIS,
1621
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1622
+ * See the License for the specific language governing permissions and
1623
+ * limitations under the License.
1624
+ */
1625
+ const FORK_SCHEDULE = DefaultForkSchedule;
1626
+ function mapEnvironmentToConfiguration(env) {
1627
+ return {
1628
+ forks: FORK_SCHEDULE,
1629
+ indexerClientConnection: {
1630
+ indexerHttpUrl: env.indexer,
1631
+ indexerWsUrl: env.indexerWS
1632
+ },
1633
+ provingServerUrl: new URL(env.proofServer),
1634
+ networkId: env.walletNetworkId,
1635
+ relayURL: new URL(env.nodeWS),
1636
+ txHistoryStorage: new InMemoryTransactionHistoryStorage(WalletEntrySchema, mergeWalletEntries),
1637
+ costParameters: {
1638
+ feeBlocksMargin: 5
1639
+ }
1640
+ };
1641
+ }
1642
+
1643
+ /*
1644
+ * This file is part of midnight-js.
1645
+ * Copyright (C) Midnight Foundation
1646
+ * SPDX-License-Identifier: Apache-2.0
1647
+ * Licensed under the Apache License, Version 2.0 (the "License");
1648
+ * You may not use this file except in compliance with the License.
1649
+ * You may obtain a copy of the License at
1650
+ * http://www.apache.org/licenses/LICENSE-2.0
1651
+ * Unless required by applicable law or agreed to in writing, software
1652
+ * distributed under the License is distributed on an "AS IS" BASIS,
1653
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1654
+ * See the License for the specific language governing permissions and
1655
+ * limitations under the License.
1656
+ */
1657
+ const DEFAULT_DUST_OPTIONS = {
1658
+ ledgerParams: LedgerParameters.initialParameters(),
1659
+ additionalFeeOverhead: 0n,
1660
+ feeBlocksMargin: 5
1661
+ };
1662
+ class WalletFactory {
1663
+ static createShieldedWallet(config, seed) {
1664
+ const Shielded = ShieldedWallet(config);
1665
+ return Shielded.startWithSeed(seed);
1666
+ }
1667
+ static createUnshieldedWallet(config, unshieldedKeystore) {
1668
+ return UnshieldedWallet({
1669
+ ...config,
1670
+ txHistoryStorage: new InMemoryTransactionHistoryStorage(WalletEntrySchema, mergeWalletEntries)
1671
+ }).startWithPublicKey(PublicKey.fromKeyStore(unshieldedKeystore));
1672
+ }
1673
+ static createDustWallet(config, seed, dustOptions = DEFAULT_DUST_OPTIONS) {
1674
+ const dustConfig = {
1675
+ ...config,
1676
+ costParameters: {
1677
+ ledgerParams: dustOptions.ledgerParams,
1678
+ additionalFeeOverhead: dustOptions.additionalFeeOverhead,
1679
+ feeBlocksMargin: dustOptions.feeBlocksMargin
1680
+ }
1681
+ };
1682
+ logger.info(`Creating dust wallet with params: ${JSON.stringify(dustConfig)}`);
1683
+ const Dust = DustWallet(dustConfig);
1684
+ return Dust.startWithSeed(seed);
1685
+ }
1686
+ static async createWalletFacade(config, shieldedWallet, unshieldedWallet, dustWallet) {
1687
+ return WalletFacade.init({
1688
+ configuration: config,
1689
+ shielded: () => shieldedWallet,
1690
+ unshielded: () => unshieldedWallet,
1691
+ dust: () => dustWallet
1692
+ });
1693
+ }
1694
+ static async startWalletFacade(wallet, seeds) {
1695
+ logger.info('Starting wallet facade...');
1696
+ await wallet.start(seeds);
1697
+ return wallet;
1698
+ }
1699
+ static async restoreShieldedWallet(config, serializedState) {
1700
+ return ShieldedWallet(config).restore(serializedState);
1701
+ }
1702
+ }
1703
+
1704
+ /*
1705
+ * This file is part of midnight-js.
1706
+ * Copyright (C) Midnight Foundation
1707
+ * SPDX-License-Identifier: Apache-2.0
1708
+ * Licensed under the Apache License, Version 2.0 (the "License");
1709
+ * You may not use this file except in compliance with the License.
1710
+ * You may obtain a copy of the License at
1711
+ * http://www.apache.org/licenses/LICENSE-2.0
1712
+ * Unless required by applicable law or agreed to in writing, software
1713
+ * distributed under the License is distributed on an "AS IS" BASIS,
1714
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1715
+ * See the License for the specific language governing permissions and
1716
+ * limitations under the License.
1717
+ */
1718
+ const TEST_MNEMONIC = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon diesel';
1719
+ const deriveKeyForRole = (seed, role, account = 0, keyIndex = 0) => {
1720
+ if (!seed || seed.length === 0) {
1721
+ throw new Error('Seed cannot be empty');
1722
+ }
1723
+ const seedBuffer = Buffer.from(seed, 'hex');
1724
+ const hdWalletResult = HDWallet.fromSeed(seedBuffer);
1725
+ if (hdWalletResult.type !== 'seedOk') {
1726
+ throw new Error('Invalid seed: failed to create HD wallet');
1727
+ }
1728
+ const derivationResult = hdWalletResult.hdWallet
1729
+ .selectAccount(account)
1730
+ .selectRole(role)
1731
+ .deriveKeyAt(keyIndex);
1732
+ if (derivationResult.type === 'keyOutOfBounds') {
1733
+ throw new Error(`Key derivation out of bounds for role ${role} at index ${keyIndex}`);
1734
+ }
1735
+ return derivationResult.key;
1736
+ };
1737
+ const getShieldedSeed = (seed) => {
1738
+ return deriveKeyForRole(seed, Roles.Zswap);
1739
+ };
1740
+ const getUnshieldedSeed = (seed) => {
1741
+ return deriveKeyForRole(seed, Roles.NightExternal);
1742
+ };
1743
+ const getDustSeed = (seed) => {
1744
+ return deriveKeyForRole(seed, Roles.Dust);
1745
+ };
1746
+ class WalletSeeds {
1747
+ masterSeed;
1748
+ shielded;
1749
+ unshielded;
1750
+ dust;
1751
+ constructor(masterSeed, shielded, unshielded, dust) {
1752
+ this.masterSeed = masterSeed;
1753
+ this.shielded = shielded;
1754
+ this.unshielded = unshielded;
1755
+ this.dust = dust;
1756
+ }
1757
+ static fromMasterSeed(seed) {
1758
+ if (!seed || seed.length === 0) {
1759
+ throw new Error('Master seed cannot be empty');
1760
+ }
1761
+ return new WalletSeeds(seed, getShieldedSeed(seed), getUnshieldedSeed(seed), getDustSeed(seed));
1762
+ }
1763
+ static generateRandom() {
1764
+ const randomSeed = Buffer.from(generateRandomSeed()).toString('hex');
1765
+ return WalletSeeds.fromMasterSeed(randomSeed);
1766
+ }
1767
+ static fromMnemonic(mnemonic) {
1768
+ if (!mnemonic || mnemonic.trim().length === 0) {
1769
+ throw new Error('Mnemonic cannot be empty');
1770
+ }
1771
+ const seed = Buffer.from(mnemonicToSeedSync(mnemonic)).toString('hex');
1772
+ return WalletSeeds.fromMasterSeed(seed);
1773
+ }
1774
+ static testWallet() {
1775
+ return WalletSeeds.fromMnemonic(TEST_MNEMONIC);
1776
+ }
1777
+ }
1778
+
1779
+ /*
1780
+ * This file is part of midnight-js.
1781
+ * Copyright (C) Midnight Foundation
1782
+ * SPDX-License-Identifier: Apache-2.0
1783
+ * Licensed under the Apache License, Version 2.0 (the "License");
1784
+ * You may not use this file except in compliance with the License.
1785
+ * You may obtain a copy of the License at
1786
+ * http://www.apache.org/licenses/LICENSE-2.0
1787
+ * Unless required by applicable law or agreed to in writing, software
1788
+ * distributed under the License is distributed on an "AS IS" BASIS,
1789
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1790
+ * See the License for the specific language governing permissions and
1791
+ * limitations under the License.
1792
+ */
1793
+ class FluentWalletBuilder {
1794
+ config;
1795
+ networkId;
1796
+ seeds;
1797
+ dustOptions;
1798
+ constructor(config, networkId, seeds, dustOptions = DEFAULT_DUST_OPTIONS) {
1799
+ this.config = config;
1800
+ this.networkId = networkId;
1801
+ this.seeds = seeds;
1802
+ this.dustOptions = dustOptions;
1803
+ }
1804
+ static forEnvironment(envConfig) {
1805
+ if (!envConfig) {
1806
+ throw new Error('Environment configuration is required');
1807
+ }
1808
+ logger.info(`Initializing wallet builder for ${envConfig.walletNetworkId}`);
1809
+ const config = mapEnvironmentToConfiguration(envConfig);
1810
+ return new FluentWalletBuilder(config, envConfig.walletNetworkId);
1811
+ }
1812
+ withSeed(seed) {
1813
+ if (!seed || seed.length === 0) {
1814
+ throw new Error('Seed cannot be empty');
1815
+ }
1816
+ this.seeds = WalletSeeds.fromMasterSeed(seed);
1817
+ return this;
1818
+ }
1819
+ withRandomSeed() {
1820
+ this.seeds = WalletSeeds.generateRandom();
1821
+ logger.info(`Generated random wallet seed: ${this.seeds.masterSeed}`);
1822
+ return this;
1823
+ }
1824
+ withMnemonic(mnemonic) {
1825
+ if (!mnemonic || mnemonic.trim().length === 0) {
1826
+ throw new Error('Mnemonic cannot be empty');
1827
+ }
1828
+ this.seeds = WalletSeeds.fromMnemonic(mnemonic);
1829
+ return this;
1830
+ }
1831
+ withTestWallet() {
1832
+ this.seeds = WalletSeeds.testWallet();
1833
+ logger.info('Using test wallet with known mnemonic');
1834
+ return this;
1835
+ }
1836
+ withDustOptions(options) {
1837
+ if (!options) {
1838
+ throw new Error('Dust options cannot be null or undefined');
1839
+ }
1840
+ this.dustOptions = options;
1841
+ return this;
1842
+ }
1843
+ async build() {
1844
+ const seeds = this.seeds ?? (() => {
1845
+ logger.info('No seed provided, generating random seed');
1846
+ return WalletSeeds.generateRandom();
1847
+ })();
1848
+ const unshieldedKeystore = createKeystore({ kind: 'schnorr', secret: seeds.unshielded }, this.networkId);
1849
+ const [shieldedWallet, unshieldedWallet, dustWallet] = await Promise.all([
1850
+ WalletFactory.createShieldedWallet(this.config, seeds.shielded),
1851
+ WalletFactory.createUnshieldedWallet(this.config, unshieldedKeystore),
1852
+ WalletFactory.createDustWallet(this.config, seeds.dust, this.dustOptions)
1853
+ ]);
1854
+ const walletFacade = await WalletFactory.createWalletFacade(this.config, shieldedWallet, unshieldedWallet, dustWallet);
1855
+ return WalletFactory.startWalletFacade(walletFacade, seeds);
1856
+ }
1857
+ async buildWithoutStarting() {
1858
+ const seeds = this.seeds ?? (() => {
1859
+ logger.info('No seed provided, generating random seed');
1860
+ return WalletSeeds.generateRandom();
1861
+ })();
1862
+ const unshieldedKeystore = createKeystore({ kind: 'schnorr', secret: seeds.unshielded }, this.networkId);
1863
+ const [shieldedWallet, unshieldedWallet, dustWallet] = await Promise.all([
1864
+ WalletFactory.createShieldedWallet(this.config, seeds.shielded),
1865
+ WalletFactory.createUnshieldedWallet(this.config, unshieldedKeystore),
1866
+ WalletFactory.createDustWallet(this.config, seeds.dust, this.dustOptions)
1867
+ ]);
1868
+ const walletFacade = await WalletFactory.createWalletFacade(this.config, shieldedWallet, unshieldedWallet, dustWallet);
1869
+ return {
1870
+ wallet: walletFacade,
1871
+ seeds,
1872
+ keystore: unshieldedKeystore
1873
+ };
1874
+ }
1875
+ }
1876
+
1877
+ /*
1878
+ * This file is part of midnight-js.
1879
+ * Copyright (C) Midnight Foundation
1880
+ * SPDX-License-Identifier: Apache-2.0
1881
+ * Licensed under the Apache License, Version 2.0 (the "License");
1882
+ * You may not use this file except in compliance with the License.
1883
+ * You may obtain a copy of the License at
1884
+ * http://www.apache.org/licenses/LICENSE-2.0
1885
+ * Unless required by applicable law or agreed to in writing, software
1886
+ * distributed under the License is distributed on an "AS IS" BASIS,
1887
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1888
+ * See the License for the specific language governing permissions and
1889
+ * limitations under the License.
1890
+ */
1891
+ /**
1892
+ * A class for compressing and decompressing files using gzip.
1893
+ */
1894
+ class GzipFile {
1895
+ /** The path to the input file */
1896
+ inputFile;
1897
+ /** The path to the output file */
1898
+ outputFile;
1899
+ /**
1900
+ * Creates a new GzipFile instance.
1901
+ * @param inputFile - The path to the input file to compress/decompress
1902
+ * @param outputFile - The path where the compressed file will be saved
1903
+ */
1904
+ constructor(inputFile, outputFile) {
1905
+ this.inputFile = inputFile;
1906
+ this.outputFile = outputFile;
1907
+ }
1908
+ /**
1909
+ * Compresses the input file using gzip compression.
1910
+ * @returns A promise that resolves when compression is complete
1911
+ * @throws If there is an error during compression
1912
+ */
1913
+ compress = () => {
1914
+ const gzip = createGzip();
1915
+ const source = createReadStream(this.inputFile);
1916
+ const destination = createWriteStream(this.outputFile);
1917
+ return new Promise((resolve, reject) => {
1918
+ source
1919
+ .pipe(gzip)
1920
+ .pipe(destination)
1921
+ .on('finish', () => {
1922
+ resolve();
1923
+ })
1924
+ .on('error', (err) => {
1925
+ reject(err);
1926
+ });
1927
+ });
1928
+ };
1929
+ /**
1930
+ * Decompresses the input gzip file and returns its contents as a string.
1931
+ * @returns A promise that resolves with the decompressed file contents as a string
1932
+ * @throws If there is an error during decompression
1933
+ */
1934
+ decompress = () => {
1935
+ const gunzip = createGunzip();
1936
+ const source = createReadStream(this.inputFile);
1937
+ return new Promise((resolve, reject) => {
1938
+ let data = '';
1939
+ source
1940
+ .pipe(gunzip)
1941
+ .on('data', (chunk) => {
1942
+ data += chunk.toString();
1943
+ })
1944
+ .on('end', () => {
1945
+ resolve(data);
1946
+ })
1947
+ .on('error', (err) => {
1948
+ reject(err);
1949
+ });
1950
+ });
1951
+ };
1952
+ }
1953
+
1954
+ /*
1955
+ * This file is part of midnight-js.
1956
+ * Copyright (C) Midnight Foundation
1957
+ * SPDX-License-Identifier: Apache-2.0
1958
+ * Licensed under the Apache License, Version 2.0 (the "License");
1959
+ * You may not use this file except in compliance with the License.
1960
+ * You may obtain a copy of the License at
1961
+ * http://www.apache.org/licenses/LICENSE-2.0
1962
+ * Unless required by applicable law or agreed to in writing, software
1963
+ * distributed under the License is distributed on an "AS IS" BASIS,
1964
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1965
+ * See the License for the specific language governing permissions and
1966
+ * limitations under the License.
1967
+ */
1968
+ let walletLedger8Module;
1969
+ /**
1970
+ * The wallet SDK's own copy of the v8 ledger, reached through its `./ledger/v8`
1971
+ * subpath.
1972
+ *
1973
+ * Everything this file builds is handed to the SDK, so it must be built with the
1974
+ * SDK's copy — `ledger-v8` is installed twice and the two copies' classes refuse
1975
+ * each other.
1976
+ *
1977
+ * Lazy, and a failed load is not memoised: the next call retries rather than
1978
+ * serving the first rejection forever.
1979
+ *
1980
+ * @see docs/architecture/retained-era-coverage.md
1981
+ */
1982
+ const loadWalletLedger8 = () => (walletLedger8Module ??= import('@midnightntwrk/wallet-sdk/ledger/v8').catch((error) => {
1983
+ walletLedger8Module = undefined;
1984
+ throw new Error("the wallet SDK's ledger 8 module ('@midnightntwrk/wallet-sdk/ledger/v8') could not be loaded", {
1985
+ cause: error
1986
+ });
1987
+ }));
1988
+ const walletDecoders = Object.freeze({
1989
+ v8: async () => {
1990
+ const { Transaction } = await loadWalletLedger8();
1991
+ return {
1992
+ Unbound: (bytes) => Transaction.deserialize('signature', 'proof', 'pre-binding', bytes),
1993
+ Finalized: (bytes) => Transaction.deserialize('signature', 'proof', 'binding', bytes)
1994
+ };
1995
+ },
1996
+ v9: () => Promise.resolve({
1997
+ Unbound: (bytes) => WalletLedger9.Transaction.deserialize('signature', 'proof', 'pre-binding', bytes),
1998
+ Finalized: (bytes) => WalletLedger9.Transaction.deserialize('signature', 'proof', 'binding', bytes)
1999
+ })
2000
+ });
2001
+ const activeProtocolVersion = async (wallet) => (await Rx.firstValueFrom(wallet.state())).activeProtocolVersion;
2002
+ /**
2003
+ * The epoch the chain is in right now, which is the only one a wallet will
2004
+ * unwrap into.
2005
+ *
2006
+ * Derived from the wallet's own `activeProtocolVersion` rather than pinned to a
2007
+ * single era: below the fork version that is the retained epoch, from it the
2008
+ * current one, and a caller that hardcodes either is wrong on one side of the
2009
+ * boundary.
2010
+ */
2011
+ const activeEpoch = async (wallet) => ProtocolVersion.epochOf(await activeProtocolVersion(wallet), FORK_SCHEDULE.v9);
2012
+ /**
2013
+ * Hands a transaction handle to the wallet SDK.
2014
+ *
2015
+ * The handle's bytes are decoded with the wallet SDK's own copy of the era's
2016
+ * ledger, then adopted at the chain's active protocol version.
2017
+ */
2018
+ const adoptInWallet = async (wallet, era, stage, tx) => {
2019
+ const decoders = await walletDecoders[era]();
2020
+ return WalletTransaction.adopt(stage, decoders[stage](tx.serialize()), await activeProtocolVersion(wallet));
2021
+ };
2022
+ /**
2023
+ * Reads the bytes of a finalized wallet SDK handle. The wallet provider factory
2024
+ * seals them in the era of the request and decodes them once.
2025
+ */
2026
+ const finalizedFromWallet = async (wallet, handle) => {
2027
+ const unwrapped = WalletTransaction.unwrapWithin(handle, await activeEpoch(wallet));
2028
+ if (Either.isLeft(unwrapped)) {
2029
+ throw unwrapped.left;
2030
+ }
2031
+ return unwrapped.right.serialize();
2032
+ };
2033
+
2034
+ /*
2035
+ * This file is part of midnight-js.
2036
+ * Copyright (C) Midnight Foundation
2037
+ * SPDX-License-Identifier: Apache-2.0
2038
+ * Licensed under the Apache License, Version 2.0 (the "License");
2039
+ * You may not use this file except in compliance with the License.
2040
+ * You may obtain a copy of the License at
2041
+ * http://www.apache.org/licenses/LICENSE-2.0
2042
+ * Unless required by applicable law or agreed to in writing, software
2043
+ * distributed under the License is distributed on an "AS IS" BASIS,
2044
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2045
+ * See the License for the specific language governing permissions and
2046
+ * limitations under the License.
2047
+ */
2048
+ const getInitialState = async (wallet) => {
2049
+ return Rx.firstValueFrom(wallet.state);
2050
+ };
2051
+ const getInitialShieldedState = async (wallet) => {
2052
+ logger.info('Getting initial state of wallet...');
2053
+ return Rx.firstValueFrom(wallet.state);
2054
+ };
2055
+ const getInitialUnshieldedState = async (wallet) => {
2056
+ logger.info('Getting initial state of wallet...');
2057
+ return Rx.firstValueFrom(wallet.state);
2058
+ };
2059
+ const syncWallet = (wallet, throttleTime = 2_000, timeout = 90_000) => {
2060
+ logger.info('Syncing wallet...');
2061
+ return Rx.firstValueFrom(wallet.state().pipe(Rx.tap((state) => {
2062
+ logger.info(`Wallet synced state emission: { shielded=${state.shielded.progress.isStrictlyComplete()}, unshielded=${state.unshielded.progress.isStrictlyComplete()}, dust=${state.dust.progress.isStrictlyComplete()} }`);
2063
+ }), Rx.throttleTime(throttleTime), Rx.tap((state) => {
2064
+ const isSynced = state.shielded.progress.isStrictlyComplete() &&
2065
+ state.dust.progress.isStrictlyComplete() &&
2066
+ state.unshielded.progress?.isStrictlyComplete() === true;
2067
+ logger.info(`Wallet synced state emission (synced=${isSynced}, protocol=${state.protocol._tag}): { shielded=${state.shielded.progress.isStrictlyComplete()}, unshielded=${state.unshielded.progress.isStrictlyComplete()}, dust=${state.dust.progress.isStrictlyComplete()} }`);
2068
+ }), Rx.filter((state) => state.shielded.progress.isStrictlyComplete() &&
2069
+ state.dust.progress.isStrictlyComplete() &&
2070
+ state.unshielded.progress.isStrictlyComplete() === true &&
2071
+ state.protocol._tag === 'Settled'), Rx.tap(() => logger.info('Sync complete')), Rx.tap((state) => {
2072
+ const shieldedBalances = state.shielded.balances || {};
2073
+ const unshieldedBalances = state.unshielded.balances || {};
2074
+ const dustBalances = state.dust.balance(new Date(Date.now())) || {};
2075
+ logger.info(`Wallet balances after sync - Shielded: ${JSON.stringify(shieldedBalances)}, Unshielded: ${JSON.stringify(unshieldedBalances)}, Dust: ${JSON.stringify(dustBalances)}`);
2076
+ }), Rx.timeout({
2077
+ each: timeout,
2078
+ with: () => Rx.throwError(() => new Error(`Wallet sync timeout after ${timeout}ms`))
2079
+ })));
2080
+ };
2081
+ const registerNightUtxosForDust = async (wallet, unshieldedKeystore) => {
2082
+ const state = await Rx.firstValueFrom(wallet.state());
2083
+ const unshieldedRaw = unshieldedToken().raw;
2084
+ const unregistered = state.unshielded.availableCoins.filter((coin) => coin.utxo.type === unshieldedRaw && coin.meta.registeredForDustGeneration === false);
2085
+ if (unregistered.length === 0) {
2086
+ logger.warn('No unregistered NIGHT UTXOs available to register for dust generation');
2087
+ return undefined;
2088
+ }
2089
+ logger.info(`Registering ${unregistered.length} NIGHT UTXO(s) for dust generation...`);
2090
+ const recipe = await wallet.registerNightUtxosForDustGeneration(unregistered, unshieldedKeystore.getPublicKey(), (payload) => unshieldedKeystore.signDataAsync(payload));
2091
+ const finalized = await wallet.finalizeRecipe(recipe);
2092
+ const txId = await wallet.submitTransaction(finalized);
2093
+ logger.info(`Dust registration tx submitted: ${txId}`);
2094
+ return txId;
2095
+ };
2096
+ const waitForFunds = async (wallet, env, fundFromFaucet = false, unshieldedKeystore) => {
2097
+ const unshieldedAddress = unshieldedKeystore.getBech32Address().asString();
2098
+ const nightTokenRaw = unshieldedToken().raw;
2099
+ logger.info(`Your wallet address is: ${unshieldedAddress}, waiting for NIGHT funds...`);
2100
+ let syncedState = await syncWallet(wallet);
2101
+ const alreadyFunded = (syncedState.unshielded.balances[nightTokenRaw] ?? 0n) > 0n;
2102
+ if (!alreadyFunded && fundFromFaucet && env.faucet) {
2103
+ logger.info('Wallet has no NIGHT; requesting tokens from faucet...');
2104
+ try {
2105
+ await new FaucetClient(env.faucet, logger).requestTokens(unshieldedAddress);
2106
+ }
2107
+ catch (error) {
2108
+ if (!(axios.isAxiosError(error) && error.response?.status === 429)) {
2109
+ throw error;
2110
+ }
2111
+ }
2112
+ syncedState = await syncWallet(wallet);
2113
+ }
2114
+ if (unshieldedKeystore && syncedState.dust.balance(new Date()) === 0n) {
2115
+ logger.info('Wallet has no dust; registering NIGHT UTXOs for dust generation...');
2116
+ const registrationTxId = await registerNightUtxosForDust(wallet, unshieldedKeystore);
2117
+ if (registrationTxId !== undefined) {
2118
+ syncedState = await syncWallet(wallet);
2119
+ }
2120
+ }
2121
+ const balance = syncedState.unshielded.balances[nightTokenRaw] ?? 0n;
2122
+ logger.info(`Your wallet NIGHT balance is: ${balance}`);
2123
+ return balance;
2124
+ };
2125
+
2126
+ /*
2127
+ * This file is part of midnight-js.
2128
+ * Copyright (C) Midnight Foundation
2129
+ * SPDX-License-Identifier: Apache-2.0
2130
+ * Licensed under the Apache License, Version 2.0 (the "License");
2131
+ * You may not use this file except in compliance with the License.
2132
+ * You may obtain a copy of the License at
2133
+ * http://www.apache.org/licenses/LICENSE-2.0
2134
+ * Unless required by applicable law or agreed to in writing, software
2135
+ * distributed under the License is distributed on an "AS IS" BASIS,
2136
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2137
+ * See the License for the specific language governing permissions and
2138
+ * limitations under the License.
2139
+ */
2140
+ /**
2141
+ * Provider class that implements wallet functionality for the Midnight network.
2142
+ * Handles transaction balancing, submission, and wallet state management.
2143
+ */
2144
+ class MidnightWalletProvider {
2145
+ /** Both eras, on both providers this class implements. */
2146
+ supportedEras;
2147
+ balancer;
2148
+ submitter;
2149
+ logger;
2150
+ env;
2151
+ wallet;
2152
+ unshieldedKeystore;
2153
+ zswapSecretKeys;
2154
+ dustSecretKey;
2155
+ seeds;
2156
+ constructor(logger, environmentConfiguration, wallet, seeds, unshieldedKeystore) {
2157
+ this.logger = logger;
2158
+ this.env = environmentConfiguration;
2159
+ this.wallet = wallet;
2160
+ this.seeds = seeds;
2161
+ this.zswapSecretKeys = ZswapSecretKeys.fromSeed(seeds.shielded);
2162
+ this.dustSecretKey = DustSecretKey.fromSeed(seeds.dust);
2163
+ this.unshieldedKeystore = unshieldedKeystore;
2164
+ this.balancer = createWalletProviderFromHandlers({
2165
+ v8: (tx, ttl) => this.balance('v8', tx, ttl),
2166
+ v9: (tx, ttl) => this.balance('v9', tx, ttl),
2167
+ getCoinPublicKey: () => this.getCoinPublicKey(),
2168
+ getEncryptionPublicKey: () => this.getEncryptionPublicKey()
2169
+ });
2170
+ this.submitter = createMidnightProviderFromHandlers({
2171
+ v8: (tx) => this.submit('v8', tx),
2172
+ v9: (tx) => this.submit('v9', tx)
2173
+ });
2174
+ this.supportedEras = this.balancer.supportedEras;
2175
+ }
2176
+ getCoinPublicKey() {
2177
+ return this.zswapSecretKeys.coinPublicKey;
2178
+ }
2179
+ getEncryptionPublicKey() {
2180
+ return this.zswapSecretKeys.encryptionPublicKey;
2181
+ }
2182
+ balanceTx(tx, ttl) {
2183
+ return this.balancer.balanceTx(tx, ttl);
2184
+ }
2185
+ submitTx(tx) {
2186
+ return this.submitter.submitTx(tx);
2187
+ }
2188
+ async balance(era, tx, ttl = ttlOneHour()) {
2189
+ const finalizedTransactionRecipe = await this.wallet.balanceUnboundTransaction(await adoptInWallet(this.wallet, era, 'Unbound', tx), { ttl });
2190
+ const signed = await this.wallet.signRecipe(finalizedTransactionRecipe, (payload) => this.unshieldedKeystore.signDataAsync(payload));
2191
+ return finalizedFromWallet(this.wallet, await this.wallet.finalizeRecipe(signed));
2192
+ }
2193
+ async submit(era, tx) {
2194
+ return this.wallet.submitTransaction(await adoptInWallet(this.wallet, era, 'Finalized', tx));
2195
+ }
2196
+ async start(waitForFundsInWallet = true) {
2197
+ this.logger.info('Starting wallet...');
2198
+ await this.wallet.start(this.seeds);
2199
+ if (waitForFundsInWallet) {
2200
+ const balance = await waitForFunds(this.wallet, this.env, true, this.unshieldedKeystore);
2201
+ this.logger.info(`Your wallet NIGHT balance is: ${balance}`);
2202
+ }
2203
+ }
2204
+ async stop() {
2205
+ return this.wallet.stop();
2206
+ }
2207
+ static async build(logger, env, seed) {
2208
+ const builder = FluentWalletBuilder.forEnvironment(env);
2209
+ const { wallet, seeds, keystore } = seed
2210
+ ? await builder.withSeed(seed).buildWithoutStarting()
2211
+ : await builder.withRandomSeed().buildWithoutStarting();
2212
+ const initialState = await getInitialShieldedState(wallet.shielded);
2213
+ logger.info(`Your wallet seed is: ${seeds.masterSeed} and your address is: ${initialState.address.coinPublicKeyString()}`);
2214
+ return new MidnightWalletProvider(logger, env, wallet, seeds, keystore);
2215
+ }
2216
+ static async withWallet(logger, env, wallet, seeds, unshieldedKeystore) {
2217
+ return new MidnightWalletProvider(logger, env, wallet, seeds, unshieldedKeystore);
2218
+ }
2219
+ }
2220
+
2221
+ /*
2222
+ * This file is part of midnight-js.
2223
+ * Copyright (C) Midnight Foundation
2224
+ * SPDX-License-Identifier: Apache-2.0
2225
+ * Licensed under the Apache License, Version 2.0 (the "License");
2226
+ * You may not use this file except in compliance with the License.
2227
+ * You may obtain a copy of the License at
2228
+ * http://www.apache.org/licenses/LICENSE-2.0
2229
+ * Unless required by applicable law or agreed to in writing, software
2230
+ * distributed under the License is distributed on an "AS IS" BASIS,
2231
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2232
+ * See the License for the specific language governing permissions and
2233
+ * limitations under the License.
2234
+ */
2235
+ /** Default directory path for storing wallet state files */
2236
+ const DEFAULT_WALLET_STATE_DIRECTORY = `./.states`;
2237
+ /**
2238
+ * Generates a filename for the wallet state file based on environment and optional seed
2239
+ * @returns {string} Generated filename for the wallet state
2240
+ * @param seed
2241
+ */
2242
+ const getWalletStateFilename = (seed) => {
2243
+ if (seed === undefined) {
2244
+ return `wallet.${getEnvVarEnvironment()}.state.gz`;
2245
+ }
2246
+ return `wallet.${getEnvVarEnvironment()}.${seed}.state.gz`;
2247
+ };
2248
+ /**
2249
+ * Provider class for saving and loading wallet state to/from compressed files
2250
+ */
2251
+ class WalletSaveStateProvider {
2252
+ /** Logger instance for recording operations */
2253
+ logger;
2254
+ /** Absolute path to the directory containing wallet state files */
2255
+ directoryPath;
2256
+ /** Full path including filename for the wallet state file */
2257
+ filePath;
2258
+ /**
2259
+ * Creates a new WalletSaveStateProvider instance
2260
+ * @param {Logger} logger - Logger instance for recording operations
2261
+ * @param seed
2262
+ * @param {string} [directoryPath=DEFAULT_WALLET_STATE_DIRECTORY] - Directory path for wallet state files
2263
+ * @param {string} [filename] - Filename for the wallet state file
2264
+ */
2265
+ constructor(logger, seed, directoryPath = DEFAULT_WALLET_STATE_DIRECTORY, filename = getWalletStateFilename(seed)) {
2266
+ this.logger = logger;
2267
+ if (!directoryPath.startsWith('/')) {
2268
+ this.directoryPath = `${process.cwd()}/${directoryPath}`;
2269
+ }
2270
+ else {
2271
+ this.directoryPath = directoryPath;
2272
+ }
2273
+ this.filePath = `${this.directoryPath}/${filename}`;
2274
+ }
2275
+ /**
2276
+ * Saves the wallet state to a compressed file
2277
+ * @param {ShieldedWalletAPI | UnshieldedWalletAPI} wallet - The wallet instance to save state from
2278
+ * @returns {Promise<void>} A promise that resolves when the save is complete
2279
+ */
2280
+ async save(wallet) {
2281
+ this.logger.info(`Saving state in ${this.filePath}`);
2282
+ fs.mkdirSync(this.directoryPath, { recursive: true });
2283
+ const serializedState = await wallet.serializeState();
2284
+ const tempFile = this.filePath.endsWith('.gz') ? this.filePath.slice(0, -3) : this.filePath;
2285
+ fs.writeFileSync(tempFile, serializedState);
2286
+ this.logger.info(`File '${tempFile}' written successfully.`);
2287
+ await new GzipFile(tempFile, `${tempFile}.gz`).compress();
2288
+ fs.rmSync(tempFile);
2289
+ this.logger.info(`File '${this.filePath}' written successfully.`);
2290
+ }
2291
+ /**
2292
+ * Loads and decompresses the wallet state from a file
2293
+ * @returns {Promise<string>} A promise that resolves with the decompressed wallet state as a string
2294
+ * @throws {Error} If there is an error reading or decompressing the file
2295
+ */
2296
+ async load() {
2297
+ this.logger.info(`Loading state from ${this.filePath}`);
2298
+ try {
2299
+ return await new GzipFile(this.filePath, `${this.filePath.replaceAll('.gz', '')}.gz`).decompress();
2300
+ }
2301
+ catch (error) {
2302
+ this.logger.error(error instanceof Error ? error.message : String(error));
2303
+ throw error;
2304
+ }
2305
+ }
2306
+ }
2307
+
2308
+ /*
2309
+ * This file is part of midnight-js.
2310
+ * Copyright (C) Midnight Foundation
2311
+ * SPDX-License-Identifier: Apache-2.0
2312
+ * Licensed under the Apache License, Version 2.0 (the "License");
2313
+ * You may not use this file except in compliance with the License.
2314
+ * You may obtain a copy of the License at
2315
+ * http://www.apache.org/licenses/LICENSE-2.0
2316
+ * Unless required by applicable law or agreed to in writing, software
2317
+ * distributed under the License is distributed on an "AS IS" BASIS,
2318
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2319
+ * See the License for the specific language governing permissions and
2320
+ * limitations under the License.
2321
+ */
2322
+ /**
2323
+ * Abstract base class for test environments.
2324
+ * Provides common functionality for managing test wallets and environments.
2325
+ */
2326
+ class TestEnvironment {
2327
+ /** Logger instance for recording operations */
2328
+ logger;
2329
+ /** Unique identifier for this test environment instance */
2330
+ uid;
2331
+ /**
2332
+ * Creates a new TestEnvironment instance.
2333
+ * @param {Logger} logger - Logger instance for recording operations
2334
+ */
2335
+ constructor(logger) {
2336
+ this.logger = logger;
2337
+ this.uid = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString();
2338
+ }
2339
+ /**
2340
+ * Starts a single wallet instance.
2341
+ * @returns {Promise<MidnightWalletProvider>} A promise that resolves to the started wallet
2342
+ * @throws {Error} If no wallet could be started
2343
+ */
2344
+ getMidnightWalletProvider = async () => {
2345
+ const [walletProvider] = await this.startMidnightWalletProviders();
2346
+ if (!walletProvider) {
2347
+ throw Error('Undefined walletProvider found, but expected to have one');
2348
+ }
2349
+ return walletProvider;
2350
+ };
2351
+ }
2352
+
2353
+ /*
2354
+ * This file is part of midnight-js.
2355
+ * Copyright (C) Midnight Foundation
2356
+ * SPDX-License-Identifier: Apache-2.0
2357
+ * Licensed under the Apache License, Version 2.0 (the "License");
2358
+ * You may not use this file except in compliance with the License.
2359
+ * You may obtain a copy of the License at
2360
+ * http://www.apache.org/licenses/LICENSE-2.0
2361
+ * Unless required by applicable law or agreed to in writing, software
2362
+ * distributed under the License is distributed on an "AS IS" BASIS,
2363
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2364
+ * See the License for the specific language governing permissions and
2365
+ * limitations under the License.
2366
+ */
2367
+ /**
2368
+ * Base class for remote test environments that connect to external network services.
2369
+ * Provides functionality for managing walletProviders and a proof server container.
2370
+ */
2371
+ class RemoteTestEnvironment extends TestEnvironment {
2372
+ proofServerContainer;
2373
+ environmentConfiguration;
2374
+ walletProviders = undefined;
2375
+ /**
2376
+ * Creates and starts the specified number of wallet providers.
2377
+ * @returns {Promise<MidnightWalletProvider[]>} Array of started wallet providers
2378
+ */
2379
+ startMidnightWalletProviders = async (amount = 1, seeds = getEnvVarWalletSeeds()) => {
2380
+ if (amount > 1 && seeds && seeds.length !== amount) {
2381
+ throw new Error(`Number of seeds provided (${seeds.length}) does not match the amount of wallets requested (${amount})`);
2382
+ }
2383
+ this.logger.info(`Getting ${amount} wallets...`);
2384
+ const buildWallet = (seed) => MidnightWalletProvider.build(this.logger, this.environmentConfiguration, seed);
2385
+ const seeds2 = seeds || Array(amount).fill(undefined);
2386
+ this.walletProviders = await Promise.all(seeds2.map(buildWallet));
2387
+ await Promise.all(this.walletProviders.map((wallet) => wallet.start()));
2388
+ return this.walletProviders;
2389
+ };
2390
+ /**
2391
+ * Shuts down the test environment by closing all walletProviders and stopping the proof server.
2392
+ */
2393
+ shutdown = async (saveWalletState) => {
2394
+ this.logger.info(`Shutting down test environment...`);
2395
+ if (this.walletProviders) {
2396
+ if (saveWalletState) {
2397
+ await Promise.all(this.walletProviders.map((midnightWallet) => new WalletSaveStateProvider(logger, midnightWallet.zswapSecretKeys.coinPublicKey).save(midnightWallet.wallet.shielded)));
2398
+ }
2399
+ await Promise.all(this.walletProviders.map((wallet) => wallet.stop()));
2400
+ }
2401
+ if (this.proofServerContainer) {
2402
+ await this.proofServerContainer.stop();
2403
+ }
2404
+ };
2405
+ /**
2406
+ * Performs a health check for the environment.
2407
+ * Checks the health of the node, indexer, and optionally the faucet services.
2408
+ * @returns {Promise<void>} A promise that resolves when the health check is complete.
2409
+ */
2410
+ healthCheck = async () => {
2411
+ this.logger.info('Performing env health check');
2412
+ await new NodeClient(this.environmentConfiguration.node, this.logger, this.environmentConfiguration.networkId).health();
2413
+ await new IndexerClient(this.environmentConfiguration.indexer, this.logger).health();
2414
+ await new ProofServerClient(this.environmentConfiguration.proofServer, this.logger).health();
2415
+ if (this.environmentConfiguration.faucet) {
2416
+ await new FaucetClient(this.environmentConfiguration.faucet, this.logger).health();
2417
+ }
2418
+ };
2419
+ /**
2420
+ * Starts the test environment by initializing the proof server and environment configuration.
2421
+ * @param {ProofServerContainer} maybeProofServerContainer Optional proof server container to use instead of creating a new one
2422
+ * @returns {Promise<EnvironmentConfiguration>} The environment configuration
2423
+ */
2424
+ start = async (maybeProofServerContainer) => {
2425
+ this.logger.info(`Starting test environment... `);
2426
+ this.proofServerContainer =
2427
+ maybeProofServerContainer ?? (await DynamicProofServerContainer.start(this.logger, this.uid));
2428
+ this.environmentConfiguration = this.getEnvironmentConfiguration();
2429
+ this.logger.info(`Test environment configuration: ${redactedJson(this.environmentConfiguration)}`);
2430
+ await this.healthCheck();
2431
+ return this.environmentConfiguration;
2432
+ };
2433
+ }
2434
+
2435
+ /*
2436
+ * This file is part of midnight-js.
2437
+ * Copyright (C) Midnight Foundation
2438
+ * SPDX-License-Identifier: Apache-2.0
2439
+ * Licensed under the Apache License, Version 2.0 (the "License");
2440
+ * You may not use this file except in compliance with the License.
2441
+ * You may obtain a copy of the License at
2442
+ * http://www.apache.org/licenses/LICENSE-2.0
2443
+ * Unless required by applicable law or agreed to in writing, software
2444
+ * distributed under the License is distributed on an "AS IS" BASIS,
2445
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2446
+ * See the License for the specific language governing permissions and
2447
+ * limitations under the License.
2448
+ */
2449
+ /**
2450
+ * List of required environment variables that must be set for this test environment
2451
+ */
2452
+ const MN_REQUIRED_ENVIRONMENT_VARIABLES = ['MN_TEST_INDEXER', 'MN_TEST_INDEXER_WS', 'MN_TEST_NODE', 'MN_TEST_NODE_WS', 'MN_TEST_NETWORK_ID'];
2453
+ /**
2454
+ * Test environment that configures services using environment variables.
2455
+ * Allows specifying custom endpoints through environment variables.
2456
+ */
2457
+ class EnvVarRemoteTestEnvironment extends RemoteTestEnvironment {
2458
+ /**
2459
+ * Returns the configuration for environment services based on environment variables.
2460
+ * Required environment variables:
2461
+ * - MN_TEST_NETWORK_ID: Network identifier (e.g., 'testnet', 'devnet')
2462
+ * - MN_TEST_INDEXER: GraphQL API endpoint for the indexer
2463
+ * - MN_TEST_INDEXER_WS: WebSocket endpoint for the indexer
2464
+ * - MN_TEST_NODE: RPC endpoint for the blockchain node
2465
+ * Optional environment variables:
2466
+ * - MN_TEST_FAUCET: API endpoint for requesting test tokens
2467
+ * @returns {EnvironmentConfiguration} Object containing service URLs from environment variables
2468
+ * @throws {MissingEnvironmentVariable} If any required environment variable is not set
2469
+ */
2470
+ getEnvironmentConfiguration() {
2471
+ // Throw is any of the required MN_* environment variables are missing.
2472
+ MN_REQUIRED_ENVIRONMENT_VARIABLES.forEach((envVar) => {
2473
+ if (!process.env[envVar]) {
2474
+ throw new MissingEnvironmentVariable(envVar);
2475
+ }
2476
+ });
2477
+ return {
2478
+ walletNetworkId: getMnTestWalletNetworkId(),
2479
+ networkId: getMnTestNetworkId(),
2480
+ indexer: getMnTestIndexer(),
2481
+ indexerWS: getMnTestIndexerWs(),
2482
+ node: getMnTestNode(),
2483
+ nodeWS: getMnTestNodeWs(),
2484
+ faucet: getMnTestFaucet(),
2485
+ proofServer: this.proofServerContainer?.getUrl()
2486
+ };
2487
+ }
2488
+ }
2489
+
2490
+ /*
2491
+ * This file is part of midnight-js.
2492
+ * Copyright (C) Midnight Foundation
2493
+ * SPDX-License-Identifier: Apache-2.0
2494
+ * Licensed under the Apache License, Version 2.0 (the "License");
2495
+ * You may not use this file except in compliance with the License.
2496
+ * You may obtain a copy of the License at
2497
+ * http://www.apache.org/licenses/LICENSE-2.0
2498
+ * Unless required by applicable law or agreed to in writing, software
2499
+ * distributed under the License is distributed on an "AS IS" BASIS,
2500
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
2501
+ * See the License for the specific language governing permissions and
2502
+ * limitations under the License.
2503
+ */
2504
+ const execFileAsync = promisify(execFile);
2505
+ const FORK_COMPOSE_FILE = 'compose-fork.yml';
2506
+ /** The runtime blob the `runtime-blob` service lifts out of the new node image, as the toolkit sees it. */
2507
+ const RUNTIME_WASM_PATH = '/runtime/midnight_node_runtime.compact.compressed.wasm';
2508
+ /**
2509
+ * Image tags the lane may be pointed at, so a workflow input reaches compose unchanged. Every one
2510
+ * has a default in `compose-fork.yml`; only variables set to a non-empty value are forwarded, so an
2511
+ * unset (or blanked) variable keeps the pinned default rather than resolving to an empty tag.
2512
+ */
2513
+ const IMAGE_TAG_VARIABLES = [
2514
+ 'FORK_FROM_NODE_TAG',
2515
+ 'NODE_TAG',
2516
+ 'TOOLKIT_TAG',
2517
+ 'INDEXER_TAG',
2518
+ 'PROOF_SERVER_TAG',
2519
+ 'PROOF_SERVER_V8_TAG'
2520
+ ];
2521
+ const NODE_PORT = 9944;
2522
+ const INDEXER_PORT = 8088;
2523
+ const PROOF_SERVER_PORT = 6300;
2524
+ /**
2525
+ * The node's address on the compose project network, which is how the toolkit container reaches it.
2526
+ *
2527
+ * Plain `ws`: the node serves no TLS and there is no terminator in front of it on that network.
2528
+ */
2529
+ // nosemgrep: javascript.lang.security.detect-insecure-websocket.detect-insecure-websocket
2530
+ const NODE_INTERNAL_WS_URL = `ws://node:${NODE_PORT}`;
2531
+ /**
2532
+ * Deadlines, each a ceiling on one step rather than a target.
2533
+ *
2534
+ * `enactFork` runs four of them back to back, so its worst case is
2535
+ * `FIRST_BLOCK_FINALIZATION + TOOLKIT + RUNTIME_APPLIED + POST_FORK_FINALIZATION` = 12 minutes. A
2536
+ * caller's own test timeout has to exceed that, or the inner deadline that would have named the
2537
+ * failure never fires and the run reports a bare timeout instead.
2538
+ */
2539
+ const SERVICE_STARTUP_TIMEOUT = 5 * MINUTE;
2540
+ const FIRST_BLOCK_FINALIZATION_TIMEOUT = 2 * MINUTE;
2541
+ const TOOLKIT_TIMEOUT = 5 * MINUTE;
2542
+ const RUNTIME_APPLIED_TIMEOUT = 3 * MINUTE;
2543
+ const POST_FORK_FINALIZATION_TIMEOUT = 2 * MINUTE;
2544
+ const CHAIN_POLL_INTERVAL = 3_000;
2545
+ const STACK_SHUTDOWN_TIMEOUT = 30_000;
2546
+ /**
2547
+ * The services {@link ForkTestEnvironment.captureContainerLogs} dumps.
2548
+ *
2549
+ * Both proof servers are included: which one served a call is decided by the head, and a rejection
2550
+ * blamed on the chain has been a prover fault before.
2551
+ */
2552
+ const LOGGED_SERVICES = ['node', 'indexer', 'proof-server', 'proof-server-v8'];
2553
+ /**
2554
+ * One service's log dump ceiling.
2555
+ *
2556
+ * A backstop rather than the mechanism: the command below terminates on its own, so reaching this
2557
+ * means the docker CLI itself is wedged.
2558
+ */
2559
+ const LOG_CAPTURE_TIMEOUT = 30_000;
2560
+ /** A single RPC round trip's ceiling, so a node that accepts a connection and never answers cannot outlive a poll deadline. */
2561
+ const RPC_TIMEOUT = 10_000;
2562
+ const TOOLKIT_MAX_OUTPUT_BYTES = 32 * 1024 * 1024;
2563
+ /**
2564
+ * The governance seeds the dev preset's council and technical committee are built from. These are
2565
+ * the public Substrate development URIs, i.e. well-known constants rather than secrets.
2566
+ */
2567
+ const COUNCIL_SEEDS = ['//Dave', '//Eve'];
2568
+ const TECHNICAL_COMMITTEE_SEEDS = ['//Alice', '//Bob'];
2569
+ const SIGNER_SEED = '//Alice';
2570
+ const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
2571
+ /**
2572
+ * One JSON-RPC round trip, returning the `result` member unexamined.
2573
+ *
2574
+ * The shape checks are guards rather than casts, so a malformed answer surfaces here under the
2575
+ * method that produced it.
2576
+ */
2577
+ const rpc = async (url, method, params = []) => {
2578
+ const response = await fetch(url, {
2579
+ method: 'POST',
2580
+ headers: { 'Content-Type': 'application/json' },
2581
+ body: JSON.stringify({ id: 1, jsonrpc: '2.0', method, params }),
2582
+ signal: AbortSignal.timeout(RPC_TIMEOUT)
2583
+ });
2584
+ if (!response.ok) {
2585
+ throw new Error(`${method} -> HTTP ${response.status} ${response.statusText}`);
2586
+ }
2587
+ const payload = await response.json();
2588
+ if (!isRecord(payload)) {
2589
+ throw new Error(`${method} -> response was not a JSON object`);
2590
+ }
2591
+ if (payload.error !== undefined) {
2592
+ throw new Error(`${method} -> ${JSON.stringify(payload.error)}`);
2593
+ }
2594
+ if (payload.result === undefined) {
2595
+ throw new Error(`${method} -> response carried neither a result nor an error`);
2596
+ }
2597
+ return payload.result;
2598
+ };
2599
+ const rpcString = async (url, method, params = []) => {
2600
+ const result = await rpc(url, method, params);
2601
+ if (typeof result !== 'string') {
2602
+ throw new Error(`${method} -> expected a string result, got ${typeof result}`);
2603
+ }
2604
+ return result;
2605
+ };
2606
+ const specVersionAtHeight = async (url, height) => {
2607
+ const blockHash = await rpcString(url, 'chain_getBlockHash', [height]);
2608
+ const result = await rpc(url, 'state_getRuntimeVersion', [blockHash]);
2609
+ if (!isRecord(result) || typeof result.specVersion !== 'number') {
2610
+ throw new Error('state_getRuntimeVersion -> result carried no numeric specVersion');
2611
+ }
2612
+ return result.specVersion;
2613
+ };
2614
+ const finalizedHeight = async (url) => {
2615
+ const header = await rpc(url, 'chain_getHeader', [await rpcString(url, 'chain_getFinalizedHead')]);
2616
+ if (!isRecord(header) || typeof header.number !== 'string') {
2617
+ throw new Error('chain_getHeader -> result carried no header number');
2618
+ }
2619
+ const height = Number(header.number);
2620
+ if (!Number.isFinite(height)) {
2621
+ throw new Error(`chain_getHeader -> header number ${header.number} is not a number`);
2622
+ }
2623
+ return height;
2624
+ };
2625
+ /**
2626
+ * Waits until the chain has finalized `height`.
2627
+ *
2628
+ * A failed read is retried rather than fatal, because the node's RPC is not always up on the first
2629
+ * iterations. The last failure is carried onto the deadline error as its `cause`, so a node that
2630
+ * never answered is distinguishable from one that answered slowly -- reporting the latter's height
2631
+ * for the former would name the wrong problem.
2632
+ */
2633
+ const waitForFinalized = async (url, height, deadline) => {
2634
+ let lastError;
2635
+ let lastHeight;
2636
+ for (;;) {
2637
+ try {
2638
+ lastHeight = await finalizedHeight(url);
2639
+ lastError = undefined;
2640
+ if (lastHeight >= height) {
2641
+ return;
2642
+ }
2643
+ }
2644
+ catch (error) {
2645
+ lastError = error;
2646
+ }
2647
+ if (Date.now() >= deadline) {
2648
+ const observed = lastHeight === undefined ? 'the node never answered' : `the chain last reported #${lastHeight}`;
2649
+ throw new Error(`Timed out waiting for finalized block #${height}; ${observed}`, { cause: lastError });
2650
+ }
2651
+ await delay(CHAIN_POLL_INTERVAL);
2652
+ }
2653
+ };
2654
+ /**
2655
+ * Waits until a finalized block reports a spec version above `oldSpecVersion`, and answers with that
2656
+ * height.
2657
+ *
2658
+ * The toolkit's `runtime-upgrade` returns once governance has been *submitted*: `set_code` takes
2659
+ * effect a block later and finality lags further still. Reading the head straight after it returns
2660
+ * therefore finds no applying block yet, which is a timing condition rather than a failed upgrade.
2661
+ * Polling here is what separates the two, so the deadline error can say which one happened.
2662
+ */
2663
+ const waitForRuntimeApplied = async (url, oldSpecVersion, deadline) => {
2664
+ let lastError;
2665
+ let lastHeight;
2666
+ let lastSpecVersion;
2667
+ for (;;) {
2668
+ try {
2669
+ lastHeight = await finalizedHeight(url);
2670
+ lastSpecVersion = await specVersionAtHeight(url, lastHeight);
2671
+ lastError = undefined;
2672
+ if (lastSpecVersion > oldSpecVersion) {
2673
+ return lastHeight;
2674
+ }
2675
+ }
2676
+ catch (error) {
2677
+ lastError = error;
2678
+ }
2679
+ if (Date.now() >= deadline) {
2680
+ const observed = lastSpecVersion === undefined
2681
+ ? 'the node never reported a spec version'
2682
+ : `spec is still ${lastSpecVersion} at finalized head #${String(lastHeight)}`;
2683
+ throw new Error(`The runtime upgrade never applied: ${observed}. Either the governance motion did not reach ` +
2684
+ `threshold or the submitted wasm was rejected.`, { cause: lastError });
2685
+ }
2686
+ await delay(CHAIN_POLL_INTERVAL);
2687
+ }
2688
+ };
2689
+ /**
2690
+ * The first height in `[lo, hi]` whose spec version is above `oldSpecVersion` -- the block that
2691
+ * applied the new code.
2692
+ *
2693
+ * `specVersion` only moves up along the chain, so this is a bisection rather than a scan. It
2694
+ * requires `spec(hi) > oldSpecVersion`, which callers get from {@link waitForRuntimeApplied};
2695
+ * without it the search converges on `hi` and would report the head as the applying block.
2696
+ */
2697
+ const findApplyingBlock = async (url, oldSpecVersion, lo, hi) => {
2698
+ let low = lo;
2699
+ let high = hi;
2700
+ while (low < high) {
2701
+ const mid = low + Math.floor((high - low) / 2);
2702
+ const spec = await specVersionAtHeight(url, mid);
2703
+ if (spec > oldSpecVersion) {
2704
+ high = mid;
2705
+ }
2706
+ else {
2707
+ low = mid + 1;
2708
+ }
2709
+ }
2710
+ return low;
2711
+ };
2712
+ const imageTagOverrides = () => {
2713
+ const overrides = {};
2714
+ for (const name of IMAGE_TAG_VARIABLES) {
2715
+ const value = process.env[name];
2716
+ if (value !== undefined && value !== '') {
2717
+ overrides[name] = value;
2718
+ }
2719
+ }
2720
+ return overrides;
2721
+ };
2722
+ /** `execFile` appends the child's stderr to the error message but drops stdout, which is where the toolkit reports governance progress. */
2723
+ const describeExecFailure = (error) => {
2724
+ if (!isRecord(error)) {
2725
+ return String(error);
2726
+ }
2727
+ const sections = [`code=${String(error.code)} signal=${String(error.signal)}`];
2728
+ if (typeof error.stdout === 'string' && error.stdout !== '') {
2729
+ sections.push(`--- toolkit stdout ---\n${error.stdout}`);
2730
+ }
2731
+ if (typeof error.stderr === 'string' && error.stderr !== '') {
2732
+ sections.push(`--- toolkit stderr ---\n${error.stderr}`);
2733
+ }
2734
+ return sections.join('\n');
2735
+ };
2736
+ /**
2737
+ * Names the failure the toolkit actually hit. A killed process is our doing, not a rejected
2738
+ * governance motion, and reporting it as one sends the reader after the wrong bug.
2739
+ */
2740
+ const toolkitFailureMessage = (error) => {
2741
+ if (isRecord(error) && error.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
2742
+ return `The toolkit produced more than ${TOOLKIT_MAX_OUTPUT_BYTES} bytes of output and was killed; the runtime-upgrade may or may not have been submitted`;
2743
+ }
2744
+ if (isRecord(error) && error.killed === true) {
2745
+ return `The toolkit did not finish within ${TOOLKIT_TIMEOUT}ms and was killed; the runtime-upgrade may or may not have been submitted`;
2746
+ }
2747
+ return `The toolkit's runtime-upgrade failed`;
2748
+ };
2749
+ /**
2750
+ * Configuration of the fork stack for a given side of the boundary.
2751
+ *
2752
+ * The only field that moves across the fork is `proofServer`: the stack runs one proof server per
2753
+ * era because no published image serves both. That split is a property of this harness, not the
2754
+ * topology the product assumes -- see `docs/architecture/fork-e2e-environment.md`.
2755
+ */
2756
+ class ForkTestConfiguration {
2757
+ walletNetworkId;
2758
+ networkId;
2759
+ indexer;
2760
+ indexerWS;
2761
+ node;
2762
+ nodeWS;
2763
+ proofServer;
2764
+ faucet;
2765
+ constructor(ports, proofServerUrl) {
2766
+ this.walletNetworkId = NetworkId.NetworkId.Undeployed;
2767
+ this.networkId = 'undeployed';
2768
+ this.indexer = `http://127.0.0.1:${ports.indexer}/api/v4/graphql`;
2769
+ this.indexerWS = `ws://127.0.0.1:${ports.indexer}/api/v4/graphql/ws`;
2770
+ this.node = `http://127.0.0.1:${ports.node}`;
2771
+ this.nodeWS = `ws://127.0.0.1:${ports.node}`;
2772
+ this.proofServer = proofServerUrl;
2773
+ this.faucet = undefined;
2774
+ }
2775
+ }
2776
+ /**
2777
+ * A chain whose genesis carries the ledger-v8 runtime, running on the ledger-v9 node binary, plus
2778
+ * the governance call that moves it across the boundary.
2779
+ *
2780
+ * A test that wants the fork constructs this class directly -- `getTestEnvironment` never returns
2781
+ * it. Why it is a sibling of the other environments rather than a mode of one, and why it runs two
2782
+ * proof servers, is recorded in `docs/architecture/fork-e2e-environment.md`.
2783
+ *
2784
+ * Wallets are not supported here; {@link ForkTestEnvironment.startMidnightWalletProviders} refuses.
2785
+ *
2786
+ * @example
2787
+ * ```ts
2788
+ * const environment = new ForkTestEnvironment(logger);
2789
+ * const preFork = await environment.start(); // chain is on the ledger-v8 runtime
2790
+ * const { appliedAtBlockHeight } = await environment.enactFork(); // governance set_code, finalized past
2791
+ * const postFork = environment.getEnvironmentConfiguration(); // now points at the v9 proof server
2792
+ * ```
2793
+ */
2794
+ class ForkTestEnvironment extends TestEnvironment {
2795
+ dockerEnv;
2796
+ environmentConfiguration;
2797
+ forkEnactment;
2798
+ composeDirectory;
2799
+ composeFile;
2800
+ projectName;
2801
+ composeEnvironment;
2802
+ constructor(logger) {
2803
+ super(logger);
2804
+ this.composeDirectory = getContainersConfiguration().standalone.path;
2805
+ this.composeFile = path__default.join(this.composeDirectory, FORK_COMPOSE_FILE);
2806
+ this.projectName = `fork-${randomUUID()}`;
2807
+ this.composeEnvironment = { TESTCONTAINERS_UID: this.uid, ...imageTagOverrides() };
2808
+ }
2809
+ /**
2810
+ * The compose project this stack runs under.
2811
+ *
2812
+ * Exposed so a caller can drive the same project itself -- `compose run
2813
+ * --profile tools toolkit ...` for a node-side reading, say -- and reach the
2814
+ * node under its service name rather than through a mapped port.
2815
+ */
2816
+ get composeProject() {
2817
+ return this.projectName;
2818
+ }
2819
+ /** Whether {@link ForkTestEnvironment.enactFork} has already moved this chain across the boundary. */
2820
+ get hasForked() {
2821
+ return this.forkEnactment !== undefined;
2822
+ }
2823
+ /**
2824
+ * The current environment configuration. Its `proofServer` names the pre-fork server until
2825
+ * {@link ForkTestEnvironment.enactFork} runs and the post-fork one afterwards; every other field
2826
+ * is fixed for the life of the stack.
2827
+ *
2828
+ * @returns {EnvironmentConfiguration} The configuration for the side of the boundary the chain is on.
2829
+ * @throws {Error} If the environment has not been started, or has already been shut down.
2830
+ */
2831
+ getEnvironmentConfiguration() {
2832
+ if (this.environmentConfiguration === undefined) {
2833
+ throw new Error('Fork test environment has not been started; call start() first');
2834
+ }
2835
+ return this.environmentConfiguration;
2836
+ }
2837
+ /**
2838
+ * The proof server that proves transactions built below the boundary.
2839
+ *
2840
+ * @returns {string} The pre-fork (ledger-8) proof server's URL.
2841
+ */
2842
+ getPreForkProofServer() {
2843
+ return `http://127.0.0.1:${this.mappedPort('proof-server-v8', PROOF_SERVER_PORT)}`;
2844
+ }
2845
+ /**
2846
+ * The proof server that proves transactions built above the boundary.
2847
+ *
2848
+ * @returns {string} The post-fork (ledger-9) proof server's URL.
2849
+ */
2850
+ getPostForkProofServer() {
2851
+ return `http://127.0.0.1:${this.mappedPort('proof-server', PROOF_SERVER_PORT)}`;
2852
+ }
2853
+ /**
2854
+ * The runtime spec version at the chain's finalized head, read from the node rather than from any
2855
+ * state this class holds. Lets a caller check the era against the chain itself.
2856
+ *
2857
+ * @returns {Promise<number>} The spec version in force at the finalized head.
2858
+ */
2859
+ async specVersionAtFinalizedHead() {
2860
+ const url = this.getNodeHttpUrl();
2861
+ return specVersionAtHeight(url, await finalizedHeight(url));
2862
+ }
2863
+ /**
2864
+ * Starts the fork stack and returns its configuration on the pre-fork side of the boundary.
2865
+ *
2866
+ * @param {ProofServerContainer} maybeProofServerContainer - Must be nullish; present only to satisfy the base-class signature.
2867
+ * @returns {Promise<EnvironmentConfiguration>} The pre-fork environment configuration.
2868
+ * @throws {Error} If a proof server container is injected, since neither of this stack's two can be replaced.
2869
+ * @throws {Error} If the stack has already been started, since a second start would orphan the first.
2870
+ */
2871
+ start = async (maybeProofServerContainer) => {
2872
+ if (maybeProofServerContainer !== undefined && maybeProofServerContainer !== null) {
2873
+ throw new Error('Invalid usage: the fork test environment runs one proof server per era and cannot take an injected one');
2874
+ }
2875
+ if (this.dockerEnv !== undefined) {
2876
+ throw new Error('Fork test environment is already started; construct a second instance for a second chain');
2877
+ }
2878
+ this.logger.info(`Starting fork test environment... project=${this.projectName}, uid=${this.uid}`);
2879
+ // The resolved tags are the load-bearing fact about a version-boundary test, and a mistyped
2880
+ // variable name is otherwise indistinguishable from an unset one -- both leave the default.
2881
+ this.logger.info(`Fork stack image tags: ${IMAGE_TAG_VARIABLES.map((name) => `${name}=${this.composeEnvironment[name] ?? '<compose default>'}`).join(' ')}`);
2882
+ this.dockerEnv = await new DockerComposeEnvironment(this.composeDirectory, FORK_COMPOSE_FILE)
2883
+ // Named so `enactFork`'s `compose run` targets this same project, and so a leftover stack is
2884
+ // identifiable rather than anonymous.
2885
+ .withProjectName(this.projectName)
2886
+ .withEnvironment(this.composeEnvironment)
2887
+ // No wait strategy for `chainspec` or `runtime-blob`: they have exited by the time `up()`
2888
+ // returns, so testcontainers never matches them and warns about the unused strategy instead.
2889
+ // `depends_on: service_completed_successfully` in the compose file is what orders them.
2890
+ .withWaitStrategy(`node_${this.uid}`, Wait.forHealthCheck().withStartupTimeout(SERVICE_STARTUP_TIMEOUT))
2891
+ // Probed from the host over the mapped port rather than in-container, because a listening port
2892
+ // alone does not mean the API is serving.
2893
+ .withWaitStrategy(`indexer_${this.uid}`, Wait.forHttp('/ready', INDEXER_PORT).withStartupTimeout(SERVICE_STARTUP_TIMEOUT))
2894
+ .withWaitStrategy(`proof-server_${this.uid}`, Wait.forListeningPorts().withStartupTimeout(SERVICE_STARTUP_TIMEOUT))
2895
+ .withWaitStrategy(`proof-server-v8_${this.uid}`, Wait.forListeningPorts().withStartupTimeout(SERVICE_STARTUP_TIMEOUT))
2896
+ // Deliberately no environment-level `withStartupTimeout`: testcontainers applies it to every
2897
+ // selected strategy, overwriting the per-service values above.
2898
+ .up();
2899
+ this.environmentConfiguration = this.configurationFor(this.getPreForkProofServer());
2900
+ this.logger.info(`Fork test environment configuration: ${redactedJson(this.environmentConfiguration)}`);
2901
+ return this.environmentConfiguration;
2902
+ };
2903
+ /**
2904
+ * Enacts the ledger-8 to ledger-9 fork on the running chain and waits for it to finalize past the
2905
+ * applying block. From here on {@link ForkTestEnvironment.getEnvironmentConfiguration} reports the
2906
+ * post-fork proof server.
2907
+ *
2908
+ * The toolkit runs through `docker compose run` rather than as a testcontainer so that it joins
2909
+ * the project network and reaches the node under its service name.
2910
+ *
2911
+ * @returns {Promise<ForkEnactment>} The spec versions either side of the boundary and the applying height.
2912
+ * @throws {Error} If the fork has already been enacted on this chain.
2913
+ * @throws {Error} If the governance call fails, or if no finalized block reports a higher spec version in time.
2914
+ * @throws {Error} If the chain does not reach or finalize past the applying block in time.
2915
+ */
2916
+ enactFork = async () => {
2917
+ if (this.forkEnactment !== undefined) {
2918
+ throw new Error('The fork has already been enacted on this chain');
2919
+ }
2920
+ const url = this.getNodeHttpUrl();
2921
+ await waitForFinalized(url, 1, Date.now() + FIRST_BLOCK_FINALIZATION_TIMEOUT);
2922
+ const oldSpecVersion = await specVersionAtHeight(url, 1);
2923
+ this.logger.info(`spec_version at #1: ${oldSpecVersion}`);
2924
+ await this.runToolkitUpgrade();
2925
+ const appliedHead = await waitForRuntimeApplied(url, oldSpecVersion, Date.now() + RUNTIME_APPLIED_TIMEOUT);
2926
+ const appliedAtBlockHeight = await findApplyingBlock(url, oldSpecVersion, 1, appliedHead);
2927
+ const newSpecVersion = await specVersionAtHeight(url, appliedAtBlockHeight);
2928
+ this.logger.info(`New runtime applied at #${appliedAtBlockHeight} (spec ${oldSpecVersion} -> ${newSpecVersion})`);
2929
+ await waitForFinalized(url, appliedAtBlockHeight + 1, Date.now() + POST_FORK_FINALIZATION_TIMEOUT);
2930
+ this.forkEnactment = { oldSpecVersion, newSpecVersion, appliedAtBlockHeight };
2931
+ this.environmentConfiguration = this.configurationFor(this.getPostForkProofServer());
2932
+ return this.forkEnactment;
2933
+ };
2934
+ /**
2935
+ * Not supported on this stack. A wallet cannot sync a chain whose history spans the boundary, so
2936
+ * there is nothing here for a wallet-driven test to build on and refusing beats handing back a
2937
+ * provider that cannot see its own funds.
2938
+ *
2939
+ * @returns {Promise<MidnightWalletProvider[]>} Never resolves.
2940
+ * @throws {Error} Always.
2941
+ */
2942
+ startMidnightWalletProviders = () => {
2943
+ throw new Error('Wallets are not supported on the fork test environment; use LocalTestEnvironment for wallet-driven tests');
2944
+ };
2945
+ /**
2946
+ * Tears the stack down, volumes included, and forgets the configuration it was reporting.
2947
+ *
2948
+ * @returns {Promise<void>} Resolves once the stack is down.
2949
+ */
2950
+ /**
2951
+ * Writes each stack container's logs into `directory`, one file per service, and answers with the
2952
+ * paths written.
2953
+ *
2954
+ * For the failures the framework's own errors cannot explain. A submission the NODE rejects
2955
+ * surfaces as `SubmissionError: Transaction submission error` with no reason on it, and the error
2956
+ * that wraps it redacts the provider's message deliberately -- so the only account of WHY the
2957
+ * chain refused is in the node's log.
2958
+ *
2959
+ * `docker compose logs` WITHOUT `-f`, and that is the load-bearing detail. The obvious route --
2960
+ * `getContainer(...).logs()` and drain the stream to `'end'` -- FOLLOWS a running container, so
2961
+ * `'end'` never arrives; awaiting it leaves the process with a pending promise, and a pending
2962
+ * promise under the driver's top-level `await` ends the run with `Detected unsettled top-level
2963
+ * await` and exit 13, taking the failure report with it. That was measured twice, and bounding the
2964
+ * drain with a timer only traded one hang for another. A command that terminates by itself removes
2965
+ * the condition instead of racing it.
2966
+ *
2967
+ * Must be called BEFORE {@link shutdown}, which removes the containers and their logs with them.
2968
+ * Never throws: it runs on a failure path, where losing the original error to a logging problem
2969
+ * would be the worse outcome. A service whose log cannot be read is reported by its absence from
2970
+ * the returned list.
2971
+ *
2972
+ * @param directory The directory the log files are written into; created if absent.
2973
+ * @returns {Promise<string[]>} The paths written, one per service whose log could be read.
2974
+ */
2975
+ captureContainerLogs = async (directory) => {
2976
+ if (this.dockerEnv === undefined) {
2977
+ return [];
2978
+ }
2979
+ await mkdir(directory, { recursive: true });
2980
+ const written = [];
2981
+ for (const service of LOGGED_SERVICES) {
2982
+ const destination = path__default.join(directory, `${service}.log`);
2983
+ try {
2984
+ const { stdout, stderr } = await execFileAsync('docker', ['compose', '-f', this.composeFile, '-p', this.projectName, 'logs', '--no-color', service], {
2985
+ env: { ...process.env, ...this.composeEnvironment },
2986
+ // Larger than `runToolkit`'s: a node that has been running through a fork enactment
2987
+ // produces far more than one toolkit command does, and a truncated log is worth less
2988
+ // than the round trip it costs to hold it.
2989
+ maxBuffer: 64 * 1024 * 1024,
2990
+ timeout: LOG_CAPTURE_TIMEOUT
2991
+ });
2992
+ // Both streams, in that order: compose writes the container's stdout and stderr to its own
2993
+ // stdout, but its own diagnostics go to stderr, and a log that is missing because the
2994
+ // service was never up is a fact worth keeping in the file.
2995
+ await writeFile(destination, `${stdout}${stderr}`);
2996
+ written.push(destination);
2997
+ }
2998
+ catch (error) {
2999
+ this.logger.warn(`Could not capture logs for '${service}': ${String(error)}`);
3000
+ }
3001
+ }
3002
+ return written;
3003
+ };
3004
+ shutdown = async () => {
3005
+ this.logger.info('Shutting down fork test environment...');
3006
+ // Cleared before the await so a failing `down()` cannot leave this instance reporting URLs for
3007
+ // containers that are on their way out.
3008
+ this.environmentConfiguration = undefined;
3009
+ this.forkEnactment = undefined;
3010
+ const dockerEnv = this.dockerEnv;
3011
+ this.dockerEnv = undefined;
3012
+ if (dockerEnv) {
3013
+ await dockerEnv.down({ timeout: STACK_SHUTDOWN_TIMEOUT, removeVolumes: true });
3014
+ }
3015
+ };
3016
+ /** The node's JSON-RPC endpoint over HTTP, which is how this environment reads the chain. */
3017
+ getNodeHttpUrl() {
3018
+ return `http://127.0.0.1:${this.mappedPort('node', NODE_PORT)}`;
3019
+ }
3020
+ configurationFor(proofServerUrl) {
3021
+ return new ForkTestConfiguration({ indexer: this.mappedPort('indexer', INDEXER_PORT), node: this.mappedPort('node', NODE_PORT) }, proofServerUrl);
3022
+ }
3023
+ mappedPort(service, port) {
3024
+ if (this.dockerEnv === undefined) {
3025
+ throw new Error('Fork test environment has not been started; call start() first');
3026
+ }
3027
+ return this.dockerEnv.getContainer(`${service}_${this.uid}`).getMappedPort(port);
3028
+ }
3029
+ /**
3030
+ * Runs one node-toolkit command against this stack and returns its combined output.
3031
+ *
3032
+ * Through `compose run` rather than as a testcontainer, so it joins the project
3033
+ * network and reaches the node under its service name. Exposed because a caller
3034
+ * may need the NODE's own answer about the chain: the indexer serves the latest
3035
+ * contract action at or before a block, so on questions about migrated state
3036
+ * the two sources can legitimately differ and the difference is the finding.
3037
+ *
3038
+ * @param args The toolkit subcommand and its arguments.
3039
+ * @returns stdout and stderr, concatenated.
3040
+ * @throws Error, with the toolkit's stderr on `cause`, if the command fails.
3041
+ */
3042
+ runToolkit = async (args) => {
3043
+ const composeArgs = [
3044
+ 'compose',
3045
+ '-f',
3046
+ this.composeFile,
3047
+ '-p',
3048
+ this.projectName,
3049
+ '--profile',
3050
+ 'tools',
3051
+ 'run',
3052
+ '--rm',
3053
+ 'toolkit',
3054
+ ...args
3055
+ ];
3056
+ try {
3057
+ const { stdout, stderr } = await execFileAsync('docker', composeArgs, {
3058
+ env: { ...process.env, ...this.composeEnvironment },
3059
+ maxBuffer: 32 * 1024 * 1024
3060
+ });
3061
+ return `${stdout}\n${stderr}`;
3062
+ }
3063
+ catch (cause) {
3064
+ throw new Error(`The node toolkit command ${args.join(' ')} failed`, { cause });
3065
+ }
3066
+ };
3067
+ async runToolkitUpgrade() {
3068
+ const composeArgs = [
3069
+ 'compose',
3070
+ '-f',
3071
+ this.composeFile,
3072
+ '-p',
3073
+ this.projectName,
3074
+ '--profile',
3075
+ 'tools',
3076
+ 'run',
3077
+ '--rm',
3078
+ 'toolkit'
3079
+ ];
3080
+ const upgradeArgs = [
3081
+ 'runtime-upgrade',
3082
+ '--wasm-file',
3083
+ RUNTIME_WASM_PATH,
3084
+ ...COUNCIL_SEEDS.flatMap((seed) => ['-c', seed]),
3085
+ ...TECHNICAL_COMMITTEE_SEEDS.flatMap((seed) => ['-t', seed]),
3086
+ '--rpc-url',
3087
+ NODE_INTERNAL_WS_URL,
3088
+ '--signer-key',
3089
+ SIGNER_SEED
3090
+ ];
3091
+ this.logger.info('Enacting the fork (governance set_code) through the node toolkit...');
3092
+ try {
3093
+ const { stdout } = await execFileAsync('docker', [...composeArgs, ...upgradeArgs], {
3094
+ env: { ...process.env, ...this.composeEnvironment },
3095
+ maxBuffer: TOOLKIT_MAX_OUTPUT_BYTES,
3096
+ timeout: TOOLKIT_TIMEOUT
3097
+ });
3098
+ // "submitted", not "enacted": a zero exit means the CLI drove governance to completion, not
3099
+ // that the new code is in force. `enactFork` proves that separately, against the chain.
3100
+ this.logger.info(`Toolkit runtime-upgrade exited 0 (submitted, not yet enacted):\n${stdout}`);
3101
+ }
3102
+ catch (error) {
3103
+ this.logger.error(`The toolkit's runtime-upgrade failed.\n${describeExecFailure(error)}`);
3104
+ throw new Error(toolkitFailureMessage(error), { cause: error });
3105
+ }
3106
+ }
3107
+ }
3108
+
3109
+ /*
3110
+ * This file is part of midnight-js.
3111
+ * Copyright (C) Midnight Foundation
3112
+ * SPDX-License-Identifier: Apache-2.0
3113
+ * Licensed under the Apache License, Version 2.0 (the "License");
3114
+ * You may not use this file except in compliance with the License.
3115
+ * You may obtain a copy of the License at
3116
+ * http://www.apache.org/licenses/LICENSE-2.0
3117
+ * Unless required by applicable law or agreed to in writing, software
3118
+ * distributed under the License is distributed on an "AS IS" BASIS,
3119
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3120
+ * See the License for the specific language governing permissions and
3121
+ * limitations under the License.
3122
+ */
3123
+ /**
3124
+ * Configuration class for local test environment implementing EnvironmentConfiguration
3125
+ */
3126
+ const LOCAL_NETWORK_ID = 'undeployed';
3127
+ class LocalTestConfiguration {
3128
+ walletNetworkId;
3129
+ networkId;
3130
+ indexer;
3131
+ indexerWS;
3132
+ node;
3133
+ nodeWS;
3134
+ proofServer;
3135
+ faucet;
3136
+ /**
3137
+ * Creates a new LocalTestConfiguration instance
3138
+ * @param {ComponentPortsConfiguration} ports - Object containing port numbers for each component
3139
+ */
3140
+ constructor({ indexer, node, proofServer }) {
3141
+ this.walletNetworkId = NetworkId.NetworkId.Undeployed;
3142
+ this.networkId = LOCAL_NETWORK_ID;
3143
+ this.indexer = `http://127.0.0.1:${indexer}/api/v4/graphql`;
3144
+ this.indexerWS = `ws://127.0.0.1:${indexer}/api/v4/graphql/ws`;
3145
+ this.node = `http://127.0.0.1:${node}`;
3146
+ this.nodeWS = `ws://127.0.0.1:${node}`;
3147
+ this.proofServer = `http://127.0.0.1:${proofServer}`;
3148
+ this.faucet = undefined;
3149
+ }
3150
+ }
3151
+ /**
3152
+ * Test environment for local development using Docker containers
3153
+ * Manages containers for node, indexer and proof server components
3154
+ */
3155
+ class LocalTestEnvironment extends TestEnvironment {
3156
+ static MAX_NUMBER_OF_WALLETS = 4;
3157
+ genesisMintWalletSeed = [
3158
+ '0000000000000000000000000000000000000000000000000000000000000002',
3159
+ '0000000000000000000000000000000000000000000000000000000000000001',
3160
+ '0000000000000000000000000000000000000000000000000000000000000003',
3161
+ '0000000000000000000000000000000000000000000000000000000000000004'
3162
+ ];
3163
+ config;
3164
+ environmentConfiguration;
3165
+ dockerEnv;
3166
+ walletProviders;
3167
+ /**
3168
+ * Creates a new LocalTestEnvironment instance
3169
+ * @param {Logger} logger - Logger instance for recording operations
3170
+ */
3171
+ constructor(logger) {
3172
+ super(logger);
3173
+ this.config = getContainersConfiguration().standalone;
3174
+ }
3175
+ /**
3176
+ * Returns the configuration for the testnet environment services.
3177
+ * @returns {EnvironmentConfiguration} Object containing URLs for testnet services:
3178
+ * - indexer: GraphQL API endpoint for the indexer
3179
+ * - indexerWS: WebSocket endpoint for the indexer
3180
+ * - node: RPC endpoint for the blockchain node
3181
+ * - faucet: API endpoint for requesting test tokens
3182
+ * - proofServer: URL for the proof generation server
3183
+ */
3184
+ getEnvironmentConfiguration() {
3185
+ return {
3186
+ walletNetworkId: this.environmentConfiguration?.walletNetworkId,
3187
+ networkId: this.environmentConfiguration?.networkId,
3188
+ indexer: this.environmentConfiguration?.indexer,
3189
+ indexerWS: this.environmentConfiguration?.indexerWS,
3190
+ node: this.environmentConfiguration?.node,
3191
+ nodeWS: this.environmentConfiguration?.nodeWS,
3192
+ faucet: this.environmentConfiguration?.faucet,
3193
+ proofServer: this.environmentConfiguration?.proofServer
3194
+ };
3195
+ }
3196
+ /**
3197
+ * Gets the mapped ports for all containers in the environment
3198
+ * @returns {ComponentPortsConfiguration} Object containing mapped port numbers
3199
+ * @private
3200
+ */
3201
+ getMappedPorts = () => ({
3202
+ indexer: this.dockerEnv
3203
+ .getContainer(`${this.config.container.indexer.name}_${this.uid}`)
3204
+ .getMappedPort(this.config.container.indexer.port),
3205
+ node: this.dockerEnv
3206
+ .getContainer(`${this.config.container.node.name}_${this.uid}`)
3207
+ .getMappedPort(this.config.container.node.port),
3208
+ proofServer: this.dockerEnv
3209
+ .getContainer(`${this.config.container.proofServer.name}_${this.uid}`)
3210
+ .getMappedPort(this.config.container.proofServer.port)
3211
+ });
3212
+ /**
3213
+ * Instead of starting the test environment by building the docker containers
3214
+ * from the default configuration files in this package, start the test environment
3215
+ * by passing an existing {@link StartedDockerComposeEnvironment} along with the
3216
+ * ports for the containers in the environment.
3217
+ *
3218
+ * @param {StartedDockerComposeEnvironment} dockerEnv - A started docker compose environment
3219
+ * @param {ComponentPortsConfiguration} ports - The ports of the containers in the given environment
3220
+ * @returns {Promise<EnvironmentConfiguration>} The environment configuration
3221
+ */
3222
+ startWithInjectedEnvironment = async (dockerEnv, ports) => {
3223
+ this.logger.info(`Starting test environment...`);
3224
+ this.dockerEnv = dockerEnv;
3225
+ this.environmentConfiguration = new LocalTestConfiguration(ports);
3226
+ this.logger.info(`Test environment configuration: ${redactedJson(this.environmentConfiguration)}`);
3227
+ return this.environmentConfiguration;
3228
+ };
3229
+ /**
3230
+ * Starts the test environment by creating and configuring Docker containers
3231
+ * @param {ProofServerContainer} maybeProofServerContainer - Optional proof server container
3232
+ * @returns {Promise<EnvironmentConfiguration>} The environment configuration
3233
+ * @throws {Error} If trying to inject proof server container when starting new environment
3234
+ */
3235
+ start = async (maybeProofServerContainer) => {
3236
+ this.logger.info(`Starting test environment... path=${this.config.path}, file=${this.config.fileName}, uid=${this.uid}`);
3237
+ if (maybeProofServerContainer) {
3238
+ throw new Error('Invalid usage, trying to inject proof server container instance when starting new test environment with another proof server...');
3239
+ }
3240
+ this.dockerEnv = await new DockerComposeEnvironment(this.config.path, this.config.fileName)
3241
+ .withWaitStrategy(`${this.config.container.proofServer.name}_${this.uid}`, this.config.container.proofServer.waitStrategy)
3242
+ .withWaitStrategy(`${this.config.container.node.name}_${this.uid}`, this.config.container.node.waitStrategy)
3243
+ .withWaitStrategy(`${this.config.container.indexer.name}_${this.uid}`, this.config.container.indexer.waitStrategy)
3244
+ .withEnvironment({
3245
+ TESTCONTAINERS_UID: this.uid,
3246
+ NETWORK_ID: LOCAL_NETWORK_ID
3247
+ })
3248
+ .up();
3249
+ this.environmentConfiguration = new LocalTestConfiguration(this.getMappedPorts());
3250
+ this.logger.info(`Test environment configuration: ${redactedJson(this.environmentConfiguration)}`);
3251
+ return this.environmentConfiguration;
3252
+ };
3253
+ /**
3254
+ * Shuts down the test environment, closing walletProviders and stopping containers
3255
+ * @returns {Promise<void>}
3256
+ */
3257
+ shutdown = async (saveWalletState) => {
3258
+ this.logger.info(`Shutting down test environment...`);
3259
+ if (this.walletProviders) {
3260
+ if (saveWalletState) {
3261
+ this.logger.warn('Skipping wallet save state as it is obsolete in this context...');
3262
+ }
3263
+ await Promise.all(this.walletProviders.map((wallet) => wallet.stop()));
3264
+ }
3265
+ if (this.dockerEnv) {
3266
+ await this.dockerEnv.down({ timeout: 10000, removeVolumes: true });
3267
+ }
3268
+ };
3269
+ /**
3270
+ * Creates and starts the specified number of wallet providers
3271
+ * @throws {Error} If requested amount exceeds maximum supported walletProviders
3272
+ * @returns {Promise<MidnightWalletProvider[]>} A promise that resolves to an array of started wallets
3273
+ */
3274
+ startMidnightWalletProviders = async (amount = 1, seeds = getEnvVarWalletSeeds()) => {
3275
+ this.logger.info(`Getting ${amount} wallets...`);
3276
+ if (seeds) {
3277
+ this.logger.warn('Provided seeds will be ignored, using genesis mint wallet seeds');
3278
+ }
3279
+ if (amount > LocalTestEnvironment.MAX_NUMBER_OF_WALLETS) {
3280
+ throw new Error(`Maximum supported number of wallets for this environment reached: ${LocalTestEnvironment.MAX_NUMBER_OF_WALLETS}`);
3281
+ }
3282
+ this.walletProviders = await Promise.all(Array.from({ length: amount }).map((_elem, index) => MidnightWalletProvider.build(this.logger, this.environmentConfiguration, this.genesisMintWalletSeed[index])));
3283
+ await Promise.all(this.walletProviders.map((wallet) => wallet.start()));
3284
+ return this.walletProviders;
3285
+ };
3286
+ }
3287
+
3288
+ /*
3289
+ * This file is part of midnight-js.
3290
+ * Copyright (C) Midnight Foundation
3291
+ * SPDX-License-Identifier: Apache-2.0
3292
+ * Licensed under the Apache License, Version 2.0 (the "License");
3293
+ * You may not use this file except in compliance with the License.
3294
+ * You may obtain a copy of the License at
3295
+ * http://www.apache.org/licenses/LICENSE-2.0
3296
+ * Unless required by applicable law or agreed to in writing, software
3297
+ * distributed under the License is distributed on an "AS IS" BASIS,
3298
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3299
+ * See the License for the specific language governing permissions and
3300
+ * limitations under the License.
3301
+ */
3302
+ /**
3303
+ * Test environment configuration for the Midnight preprod network.
3304
+ * Provides URLs and endpoints for preprod network services.
3305
+ */
3306
+ class PreprodTestEnvironment extends RemoteTestEnvironment {
3307
+ /**
3308
+ * Returns the configuration for the preprod environment services.
3309
+ * @returns {EnvironmentConfiguration} Object containing URLs for preprod services:
3310
+ * - indexer: GraphQL API endpoint for the indexer
3311
+ * - indexerWS: WebSocket endpoint for the indexer
3312
+ * - node: RPC endpoint for the blockchain node
3313
+ * - faucet: API endpoint for requesting test tokens
3314
+ * - proofServer: URL for the proof generation server
3315
+ */
3316
+ getEnvironmentConfiguration() {
3317
+ return {
3318
+ walletNetworkId: NetworkId.NetworkId.PreProd,
3319
+ networkId: 'preprod',
3320
+ indexer: 'https://indexer.preprod.midnight.network/api/v4/graphql',
3321
+ indexerWS: 'wss://indexer.preprod.midnight.network/api/v4/graphql/ws',
3322
+ node: 'https://rpc.preprod.midnight.network',
3323
+ nodeWS: 'wss://rpc.preprod.midnight.network',
3324
+ faucet: 'https://faucet.preprod.midnight.network/api/drips',
3325
+ proofServer: this.proofServerContainer?.getUrl()
3326
+ };
3327
+ }
3328
+ }
3329
+
3330
+ /*
3331
+ * This file is part of midnight-js.
3332
+ * Copyright (C) Midnight Foundation
3333
+ * SPDX-License-Identifier: Apache-2.0
3334
+ * Licensed under the Apache License, Version 2.0 (the "License");
3335
+ * You may not use this file except in compliance with the License.
3336
+ * You may obtain a copy of the License at
3337
+ * http://www.apache.org/licenses/LICENSE-2.0
3338
+ * Unless required by applicable law or agreed to in writing, software
3339
+ * distributed under the License is distributed on an "AS IS" BASIS,
3340
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3341
+ * See the License for the specific language governing permissions and
3342
+ * limitations under the License.
3343
+ */
3344
+ /**
3345
+ * Test environment configuration for the Midnight preview network.
3346
+ * Provides URLs and endpoints for preview network services.
3347
+ */
3348
+ class PreviewTestEnvironment extends RemoteTestEnvironment {
3349
+ /**
3350
+ * Returns the configuration for the preview environment services.
3351
+ * @returns {EnvironmentConfiguration} Object containing URLs for preview services:
3352
+ * - indexer: GraphQL API endpoint for the indexer
3353
+ * - indexerWS: WebSocket endpoint for the indexer
3354
+ * - node: RPC endpoint for the blockchain node
3355
+ * - faucet: API endpoint for requesting test tokens
3356
+ * - proofServer: URL for the proof generation server
3357
+ */
3358
+ getEnvironmentConfiguration() {
3359
+ const preview = networks.preview();
3360
+ return {
3361
+ walletNetworkId: NetworkId.NetworkId.Preview,
3362
+ networkId: preview.networkId,
3363
+ indexer: preview.indexer.queryURL,
3364
+ indexerWS: preview.indexer.subscriptionURL,
3365
+ node: preview.nodeURL,
3366
+ nodeWS: preview.nodeWsURL,
3367
+ faucet: 'https://faucet.preview.midnight.network/api/drips',
3368
+ proofServer: this.proofServerContainer?.getUrl()
3369
+ };
3370
+ }
3371
+ }
3372
+
3373
+ /*
3374
+ * This file is part of midnight-js.
3375
+ * Copyright (C) Midnight Foundation
3376
+ * SPDX-License-Identifier: Apache-2.0
3377
+ * Licensed under the Apache License, Version 2.0 (the "License");
3378
+ * You may not use this file except in compliance with the License.
3379
+ * You may obtain a copy of the License at
3380
+ * http://www.apache.org/licenses/LICENSE-2.0
3381
+ * Unless required by applicable law or agreed to in writing, software
3382
+ * distributed under the License is distributed on an "AS IS" BASIS,
3383
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3384
+ * See the License for the specific language governing permissions and
3385
+ * limitations under the License.
3386
+ */
3387
+ /**
3388
+ * Test environment configuration for the Midnight QA network.
3389
+ * Provides URLs and endpoints for QA network services.
3390
+ */
3391
+ class QanetTestEnvironment extends RemoteTestEnvironment {
3392
+ /**
3393
+ * Returns the configuration for the QA network environment services.
3394
+ * @returns {EnvironmentConfiguration} Object containing URLs for QA network services:
3395
+ * - indexer: GraphQL API endpoint for the indexer
3396
+ * - indexerWS: WebSocket endpoint for the indexer
3397
+ * - node: RPC endpoint for the blockchain node
3398
+ * - faucet: API endpoint for requesting test tokens
3399
+ * - proofServer: URL for the proof generation server
3400
+ */
3401
+ getEnvironmentConfiguration() {
3402
+ return {
3403
+ walletNetworkId: NetworkId.NetworkId.QaNet,
3404
+ networkId: 'qanet',
3405
+ indexer: 'https://indexer.qanet.midnight.network/api/v4/graphql',
3406
+ indexerWS: 'wss://indexer.qanet.midnight.network/api/v4/graphql/ws',
3407
+ node: 'https://rpc.qanet.midnight.network',
3408
+ nodeWS: 'wss://rpc.qanet.midnight.network',
3409
+ faucet: 'https://faucet.qanet.midnight.network/api/drips',
3410
+ proofServer: this.proofServerContainer?.getUrl()
3411
+ };
3412
+ }
3413
+ }
3414
+
3415
+ /*
3416
+ * This file is part of midnight-js.
3417
+ * Copyright (C) Midnight Foundation
3418
+ * SPDX-License-Identifier: Apache-2.0
3419
+ * Licensed under the Apache License, Version 2.0 (the "License");
3420
+ * You may not use this file except in compliance with the License.
3421
+ * You may obtain a copy of the License at
3422
+ * http://www.apache.org/licenses/LICENSE-2.0
3423
+ * Unless required by applicable law or agreed to in writing, software
3424
+ * distributed under the License is distributed on an "AS IS" BASIS,
3425
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
3426
+ * See the License for the specific language governing permissions and
3427
+ * limitations under the License.
3428
+ */
3429
+ /**
3430
+ * Returns the appropriate test environment based on the MN_TEST_ENVIRONMENT variable.
3431
+ * @param {Logger} logger - The logger instance to be used by the test environment.
3432
+ * @returns { TestEnvironment} The selected test environment instance.
3433
+ */
3434
+ const getTestEnvironment = (logger) => {
3435
+ const testEnv = getEnvVarEnvironment().toLowerCase();
3436
+ let env;
3437
+ switch (testEnv) {
3438
+ case 'preview':
3439
+ env = new PreviewTestEnvironment(logger);
3440
+ break;
3441
+ case 'preprod':
3442
+ env = new PreprodTestEnvironment(logger);
3443
+ break;
3444
+ case 'qanet':
3445
+ env = new QanetTestEnvironment(logger);
3446
+ break;
3447
+ case 'env-var-remote':
3448
+ env = new EnvVarRemoteTestEnvironment(logger);
3449
+ // Fails fast when a required MN_TEST_* variable is missing.
3450
+ env.getEnvironmentConfiguration();
3451
+ break;
3452
+ default:
3453
+ env = new LocalTestEnvironment(logger);
3454
+ }
3455
+ return env;
3456
+ };
3457
+
3458
+ export { DAppConnectorInitialAPI, DAppConnectorWalletAdapter, DEFAULT_DUST_OPTIONS, DEFAULT_WALLET_STATE_DIRECTORY, DynamicProofServerContainer, EnvVarRemoteTestEnvironment, FaucetClient, FluentWalletBuilder, ForkTestEnvironment, GzipFile, HEALTH_CHECK_TIMEOUT_MS, IndexerClient, LocalTestConfiguration, LocalTestEnvironment, MINUTE, MidnightWalletProvider, NodeClient, PreprodTestEnvironment, PreviewTestEnvironment, ProofServerClient, QanetTestEnvironment, RemoteTestEnvironment, StaticProofServerContainer, TEST_MNEMONIC, TestEnvironment, WalletFactory, WalletSaveStateProvider, WalletSeeds, buildUrlWithPath, createDefaultTestLogger, createLogger, defaultContainersConfiguration, delay, expectFoundAndDeployedStatesEqual, expectFoundAndDeployedTxDataEqual, expectFoundAndDeployedTxPrivateDataEqual, expectFoundAndDeployedTxPublicDataEqual, expectSuccessfulCallTx, expectSuccessfulDeployTx, expectSuccessfulTxData, getContainersConfiguration, getDustSeed, getInitialShieldedState, getInitialState, getInitialUnshieldedState, getShieldedSeed, getTestEnvironment, getUnshieldedSeed, getWalletStateFilename, inMemoryPrivateStateProvider, initializeMidnightProviders, latestContainersConfiguration, logger, redactUrl, redactedJson, setContainersConfiguration, stateValueEqual, syncWallet, tryDeleteDirectory, txsEqual, waitForFunds };
3459
+ //# sourceMappingURL=index.js.map