@openzeppelin/compact-deployer 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +304 -0
  3. package/dist/config/compact-config.d.ts +31 -0
  4. package/dist/config/compact-config.js +123 -0
  5. package/dist/config/compact-config.js.map +1 -0
  6. package/dist/config/schema.d.ts +688 -0
  7. package/dist/config/schema.js +90 -0
  8. package/dist/config/schema.js.map +1 -0
  9. package/dist/deployer.d.ts +154 -0
  10. package/dist/deployer.js +916 -0
  11. package/dist/deployer.js.map +1 -0
  12. package/dist/deployments.d.ts +119 -0
  13. package/dist/deployments.js +144 -0
  14. package/dist/deployments.js.map +1 -0
  15. package/dist/errors.d.ts +94 -0
  16. package/dist/errors.js +124 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/loaders/args.d.ts +22 -0
  19. package/dist/loaders/args.js +72 -0
  20. package/dist/loaders/args.js.map +1 -0
  21. package/dist/loaders/argv.d.ts +36 -0
  22. package/dist/loaders/argv.js +101 -0
  23. package/dist/loaders/argv.js.map +1 -0
  24. package/dist/loaders/artifact-path.d.ts +16 -0
  25. package/dist/loaders/artifact-path.js +35 -0
  26. package/dist/loaders/artifact-path.js.map +1 -0
  27. package/dist/loaders/artifact.d.ts +43 -0
  28. package/dist/loaders/artifact.js +115 -0
  29. package/dist/loaders/artifact.js.map +1 -0
  30. package/dist/loaders/constructor-meta.d.ts +17 -0
  31. package/dist/loaders/constructor-meta.js +99 -0
  32. package/dist/loaders/constructor-meta.js.map +1 -0
  33. package/dist/loaders/context.d.ts +14 -0
  34. package/dist/loaders/context.js +43 -0
  35. package/dist/loaders/context.js.map +1 -0
  36. package/dist/loaders/contract-resolve.d.ts +15 -0
  37. package/dist/loaders/contract-resolve.js +53 -0
  38. package/dist/loaders/contract-resolve.js.map +1 -0
  39. package/dist/loaders/init-state.d.ts +8 -0
  40. package/dist/loaders/init-state.js +37 -0
  41. package/dist/loaders/init-state.js.map +1 -0
  42. package/dist/loaders/ref-resolver.d.ts +8 -0
  43. package/dist/loaders/ref-resolver.js +27 -0
  44. package/dist/loaders/ref-resolver.js.map +1 -0
  45. package/dist/loaders/signing-key.d.ts +10 -0
  46. package/dist/loaders/signing-key.js +23 -0
  47. package/dist/loaders/signing-key.js.map +1 -0
  48. package/dist/providers/build.d.ts +20 -0
  49. package/dist/providers/build.js +41 -0
  50. package/dist/providers/build.js.map +1 -0
  51. package/dist/providers/network.d.ts +6 -0
  52. package/dist/providers/network.js +36 -0
  53. package/dist/providers/network.js.map +1 -0
  54. package/dist/providers/private-state-password.d.ts +12 -0
  55. package/dist/providers/private-state-password.js +27 -0
  56. package/dist/providers/private-state-password.js.map +1 -0
  57. package/dist/providers/proof-server.d.ts +29 -0
  58. package/dist/providers/proof-server.js +97 -0
  59. package/dist/providers/proof-server.js.map +1 -0
  60. package/dist/runDeploy.d.ts +167 -0
  61. package/dist/runDeploy.js +228 -0
  62. package/dist/runDeploy.js.map +1 -0
  63. package/dist/services/atomic-json.d.ts +7 -0
  64. package/dist/services/atomic-json.js +34 -0
  65. package/dist/services/atomic-json.js.map +1 -0
  66. package/dist/services/chain-state.d.ts +75 -0
  67. package/dist/services/chain-state.js +151 -0
  68. package/dist/services/chain-state.js.map +1 -0
  69. package/dist/services/contract-state.d.ts +29 -0
  70. package/dist/services/contract-state.js +54 -0
  71. package/dist/services/contract-state.js.map +1 -0
  72. package/dist/services/deploy-plan.d.ts +36 -0
  73. package/dist/services/deploy-plan.js +45 -0
  74. package/dist/services/deploy-plan.js.map +1 -0
  75. package/dist/services/deploy-tx.d.ts +189 -0
  76. package/dist/services/deploy-tx.js +297 -0
  77. package/dist/services/deploy-tx.js.map +1 -0
  78. package/dist/services/error-format.d.ts +10 -0
  79. package/dist/services/error-format.js +91 -0
  80. package/dist/services/error-format.js.map +1 -0
  81. package/dist/services/file-lock.d.ts +23 -0
  82. package/dist/services/file-lock.js +90 -0
  83. package/dist/services/file-lock.js.map +1 -0
  84. package/dist/services/maintenance-tx.d.ts +49 -0
  85. package/dist/services/maintenance-tx.js +43 -0
  86. package/dist/services/maintenance-tx.js.map +1 -0
  87. package/dist/services/wallet-cache.d.ts +99 -0
  88. package/dist/services/wallet-cache.js +239 -0
  89. package/dist/services/wallet-cache.js.map +1 -0
  90. package/dist/services/wallet-sync.d.ts +89 -0
  91. package/dist/services/wallet-sync.js +249 -0
  92. package/dist/services/wallet-sync.js.map +1 -0
  93. package/dist/wallet/handler.d.ts +64 -0
  94. package/dist/wallet/handler.js +151 -0
  95. package/dist/wallet/handler.js.map +1 -0
  96. package/dist/wallet/keystore.d.ts +55 -0
  97. package/dist/wallet/keystore.js +213 -0
  98. package/dist/wallet/keystore.js.map +1 -0
  99. package/dist/wallet/seeds.d.ts +41 -0
  100. package/dist/wallet/seeds.js +84 -0
  101. package/dist/wallet/seeds.js.map +1 -0
  102. package/package.json +133 -0
  103. package/proof-server.yml +16 -0
@@ -0,0 +1,249 @@
1
+ import { shieldedToken, unshieldedToken } from '@midnight-ntwrk/ledger-v8';
2
+ import { getNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
3
+ import { DustAddress, ShieldedAddress, UnshieldedAddress, } from '@midnight-ntwrk/wallet-sdk-address-format';
4
+ import { PendingTransactions } from '@midnight-ntwrk/wallet-sdk-capabilities';
5
+ import * as Rx from 'rxjs';
6
+ import { UnfundedWalletError, WalletError } from "../errors.js";
7
+ import { formatError } from "./error-format.js";
8
+ /**
9
+ * Default sync ceiling (10 min). Overrides testkit-js's hardcoded 90 s
10
+ * `waitForFunds` timeout, which is too short for real networks.
11
+ */
12
+ export const DEFAULT_SYNC_TIMEOUT_MS = 10 * 60 * 1000;
13
+ /**
14
+ * Tolerated sync gap, in events, for the chain-tip gate.
15
+ * `FacadeState.isSynced` requires every sub-wallet to be *strictly*
16
+ * complete (gap 0). On a live network the global dust stream advances
17
+ * continuously, so the dust wallet sits a few events behind the tip
18
+ * indefinitely and strict `isSynced` never flips. The gate would then time
19
+ * out on a wallet that is in fact fully usable. `isCompleteWithin(50)` is the
20
+ * SDK default (and what the unshielded wallet uses internally): it treats
21
+ * "within 50 events of tip" as synced, which a live wallet reaches and
22
+ * holds. See OpenZeppelin/compact-tools#115.
23
+ */
24
+ export const SYNC_MAX_GAP = 50n;
25
+ /**
26
+ * Print the wallet's three bech32m addresses so the user can verify
27
+ * the seed before a long sync. Best-effort: warn-and-continue on
28
+ * failure.
29
+ */
30
+ export async function logWalletAddresses(wallet, logger) {
31
+ try {
32
+ const networkId = getNetworkId();
33
+ const [shieldedState, unshieldedState, dustState] = await Promise.all([
34
+ Rx.firstValueFrom(wallet.wallet.shielded.state),
35
+ Rx.firstValueFrom(wallet.wallet.unshielded.state),
36
+ Rx.firstValueFrom(wallet.wallet.dust.state),
37
+ ]);
38
+ const shielded = ShieldedAddress.codec
39
+ .encode(networkId, shieldedState.address)
40
+ .toString();
41
+ const unshielded = UnshieldedAddress.codec
42
+ .encode(networkId, unshieldedState.address)
43
+ .toString();
44
+ const dust = DustAddress.codec
45
+ .encode(networkId, dustState.address)
46
+ .toString();
47
+ logger.info('Wallet addresses (verify these match your seed):');
48
+ logger.info(` shielded: ${shielded}`);
49
+ logger.info(` unshielded: ${unshielded}`);
50
+ logger.info(` dust: ${dust}`);
51
+ }
52
+ catch (e) {
53
+ logger.warn({ err: formatError(e) }, 'Could not derive wallet addresses for display; continuing');
54
+ }
55
+ }
56
+ /**
57
+ * One-liner progress string for "Still syncing". Accepts both progress
58
+ * shapes (shielded/dust use `appliedIndex`/`highestIndex`; unshielded
59
+ * uses `appliedId`/`highestTransactionId`).
60
+ */
61
+ export function describeProgress(p) {
62
+ const complete = p.isStrictlyComplete();
63
+ const indexed = 'appliedIndex' in p;
64
+ const applied = indexed ? p.appliedIndex : p.appliedId;
65
+ const highest = indexed ? p.highestIndex : p.highestTransactionId;
66
+ const connected = p.isConnected;
67
+ // Once the indexer has told the wallet its max event id, we can
68
+ // render a real progress percentage. Until then surface "applied,
69
+ // highest unknown" and the subscription's connection state so the
70
+ // user can tell "still connecting" from "connected but no events yet"
71
+ // from "events flowing".
72
+ if (highest === 0n) {
73
+ return `applied=${applied} highest=? connected=${connected} complete=${complete}`;
74
+ }
75
+ const pct = Number((applied * 100n) / highest);
76
+ return `${applied}/${highest} (${pct}%) connected=${connected} complete=${complete}`;
77
+ }
78
+ /**
79
+ * The dust index the wallet must pass before its view can include a spend
80
+ * submitted now. Read immediately before submitting.
81
+ */
82
+ export async function readDustTip(wallet) {
83
+ const state = await Rx.firstValueFrom(wallet.wallet.state());
84
+ return state.dust.state.progress.highestRelevantWalletIndex;
85
+ }
86
+ /**
87
+ * Whether the wallet has caught up with a spend submitted at `appliedBeyond`.
88
+ *
89
+ * Two conditions, because neither alone is enough. The dust index is a global
90
+ * event id, so on a busy chain an unrelated event can carry it past the mark
91
+ * before our own spend applies. The facade's pending set names the
92
+ * transactions it is still waiting on, which is exactly our spend. A state
93
+ * without a pending set is unsettled: the index alone cannot prove the spend
94
+ * applied.
95
+ */
96
+ function dustCaughtUp(state, appliedBeyond) {
97
+ if (state.dust.state.progress.appliedIndex <= appliedBeyond)
98
+ return false;
99
+ const pending = state.pending;
100
+ if (pending === undefined)
101
+ return false;
102
+ return PendingTransactions.allPending(pending).length === 0;
103
+ }
104
+ /**
105
+ * Wait for the wallet to have applied dust events past `appliedBeyond` and to
106
+ * hold no transaction of its own still pending.
107
+ *
108
+ * Two fragments balanced against the same dust UTXO make the second a
109
+ * double-spend. `isCompleteWithin` is not enough: it passes a wallet sitting a
110
+ * few events behind the tip, which is exactly the window where the spend is
111
+ * still unseen.
112
+ */
113
+ export async function awaitDustSettled({ wallet, appliedBeyond, timeoutMs, }) {
114
+ try {
115
+ await Rx.firstValueFrom(wallet.wallet.state().pipe(Rx.filter((s) => dustCaughtUp(s, appliedBeyond)), Rx.timeout({ each: timeoutMs })));
116
+ }
117
+ catch (e) {
118
+ throw new WalletError(`The wallet did not apply dust events past index ${appliedBeyond} within ${timeoutMs} ms, so the next transaction could double-spend`, { cause: e });
119
+ }
120
+ }
121
+ /**
122
+ * Drive the wallet to chain tip and assert spendable funds. Gates on each
123
+ * sub-wallet being within {@link SYNC_MAX_GAP} events of the tip rather
124
+ * than strictly complete: on a live network the global dust stream never
125
+ * settles to gap 0, so strict `FacadeState.isSynced` never fires and the
126
+ * gate times out on a perfectly usable wallet (#115). The gate still waits
127
+ * on all three sub-wallets; dropping the dust/shielded wait entirely
128
+ * regressed on local with `Invalid Transaction (custom error 170)`.
129
+ * Throttles progress logs to once per 30 s. Throws {@link WalletError} on
130
+ * timeout and {@link UnfundedWalletError} on an empty wallet.
131
+ */
132
+ export async function syncAndVerifyFunds(args) {
133
+ const { wallet, timeoutMs, logger, onCheckpoint } = args;
134
+ logger.info(`Syncing wallet to chain tip (timeout ${Math.round(timeoutMs / 1000)}s)…`);
135
+ const start = Date.now();
136
+ // Two subscriptions to the same observable: one logs throttled
137
+ // progress lines for UX, the other waits for completion. The progress
138
+ // tap deliberately runs through `Rx.throttleTime(30_000)` so the
139
+ // shielded-sync flood doesn't drown the terminal; the completion gate
140
+ // doesn't throttle, so the deploy proceeds the instant sync flips.
141
+ const state$ = wallet.wallet.state();
142
+ const progressSub = state$
143
+ .pipe(Rx.throttleTime(30_000, undefined, { leading: false, trailing: true }))
144
+ .subscribe((s) => {
145
+ const elapsedSec = Math.round((Date.now() - start) / 1000);
146
+ const elapsedHms = elapsedSec < 60
147
+ ? `${elapsedSec}s`
148
+ : `${Math.floor(elapsedSec / 60)}m ${elapsedSec % 60}s`;
149
+ // Pull running balance projections each tick so the user can
150
+ // see funds materialise mid-sync (NIGHT becomes visible the
151
+ // moment unshielded completes; dust accumulates as the wallet
152
+ // processes events even before its sync is strictly complete).
153
+ const shieldedBal = s.shielded.balances[shieldedToken().raw] ?? 0n;
154
+ const unshieldedBal = s.unshielded.balances[unshieldedToken().raw] ?? 0n;
155
+ const dustBal = s.dust.balance(new Date());
156
+ logger.info(`Still syncing (${elapsedHms} elapsed). ` +
157
+ `shielded ${describeProgress(s.shielded.state.progress)} balance=${shieldedBal}; ` +
158
+ `unshielded ${describeProgress(s.unshielded.progress)} balance=${unshieldedBal}; ` +
159
+ `dust ${describeProgress(s.dust.state.progress)} balance=${dustBal}`);
160
+ });
161
+ // Periodic checkpoint: snapshot the wallet caches every 5 min so a
162
+ // user who Ctrl+C's a long preprod first-run can resume from the
163
+ // latest snapshot instead of starting at id=0 again. Best-effort:
164
+ // a failed save logs a warning and the sync keeps going. Skipped
165
+ // when `onCheckpoint` is not provided (i.e. injected-wallet callers
166
+ // where the deployer doesn't own persistence).
167
+ let checkpointInFlight = false;
168
+ const checkpointSub = onCheckpoint
169
+ ? state$
170
+ .pipe(Rx.throttleTime(5 * 60 * 1000, undefined, {
171
+ leading: false,
172
+ trailing: true,
173
+ }))
174
+ .subscribe(() => {
175
+ if (checkpointInFlight)
176
+ return;
177
+ checkpointInFlight = true;
178
+ onCheckpoint()
179
+ .catch((e) => {
180
+ logger.warn({ err: formatError(e) }, 'Wallet cache checkpoint failed; continuing sync');
181
+ })
182
+ .finally(() => {
183
+ checkpointInFlight = false;
184
+ });
185
+ })
186
+ : undefined;
187
+ // Per-sub-wallet edge-trigger: the first time each sub-wallet flips
188
+ // to `complete=true`, log its current balance immediately. This lets
189
+ // a user with NIGHT+dust (the typical preprod-faucet wallet shape)
190
+ // see their unshielded balance after ~30 s instead of waiting for
191
+ // the full shielded sync (30 – 60 min) to surface anything.
192
+ const seenComplete = { shielded: false, unshielded: false, dust: false };
193
+ const balanceSub = state$.subscribe((s) => {
194
+ if (!seenComplete.unshielded &&
195
+ s.unshielded.progress.isStrictlyComplete()) {
196
+ seenComplete.unshielded = true;
197
+ const bal = s.unshielded.balances[unshieldedToken().raw] ?? 0n;
198
+ logger.info(`Unshielded sync complete — NIGHT balance: ${bal}`);
199
+ }
200
+ if (!seenComplete.dust && s.dust.state.progress.isStrictlyComplete()) {
201
+ seenComplete.dust = true;
202
+ const bal = s.dust.balance(new Date());
203
+ logger.info(`Dust sync complete — dust balance: ${bal}`);
204
+ }
205
+ if (!seenComplete.shielded &&
206
+ s.shielded.state.progress.isStrictlyComplete()) {
207
+ seenComplete.shielded = true;
208
+ const bal = s.shielded.balances[shieldedToken().raw] ?? 0n;
209
+ logger.info(`Shielded sync complete — shielded balance: ${bal}`);
210
+ }
211
+ });
212
+ let synced;
213
+ try {
214
+ synced = await Rx.firstValueFrom(state$.pipe(
215
+ // Tolerant tip gate: all three sub-wallets within SYNC_MAX_GAP
216
+ // events of the tip. Strict `s.isSynced` never fires on a live
217
+ // chain because the global dust stream keeps advancing (#115).
218
+ Rx.filter((s) => s.shielded.state.progress.isCompleteWithin(SYNC_MAX_GAP) &&
219
+ s.dust.state.progress.isCompleteWithin(SYNC_MAX_GAP) &&
220
+ s.unshielded.progress.isCompleteWithin(SYNC_MAX_GAP)), Rx.timeout({
221
+ each: timeoutMs,
222
+ with: () => Rx.throwError(() => new WalletError(`Wallet sync timeout after ${timeoutMs}ms`)),
223
+ })));
224
+ }
225
+ finally {
226
+ progressSub.unsubscribe();
227
+ balanceSub.unsubscribe();
228
+ checkpointSub?.unsubscribe();
229
+ }
230
+ const totalSec = Math.round((Date.now() - start) / 1000);
231
+ const totalHms = totalSec < 60
232
+ ? `${totalSec}s`
233
+ : `${Math.floor(totalSec / 60)}m ${totalSec % 60}s`;
234
+ logger.info(`Sync complete after ${totalHms}`);
235
+ // Accept funds in either shielded or unshielded. Preprod faucets
236
+ // hand out unshielded NIGHT, while a freshly bridged wallet may sit
237
+ // entirely in the shielded layer. Both are deployable: dust for
238
+ // fees auto-generates from either NIGHT or shielded holdings.
239
+ // Mirrors midnight-apps's `waitForUnshieldedFunds` semantics.
240
+ const shieldedBal = synced.shielded.balances[shieldedToken().raw];
241
+ const unshieldedBal = synced.unshielded.balances[unshieldedToken().raw];
242
+ const hasShielded = shieldedBal !== undefined && shieldedBal > 0n;
243
+ const hasUnshielded = unshieldedBal !== undefined && unshieldedBal > 0n;
244
+ if (!hasShielded && !hasUnshielded) {
245
+ throw new UnfundedWalletError(wallet.getCoinPublicKey());
246
+ }
247
+ logger.info(`Wallet balance: shielded=${shieldedBal ?? 0n}, unshielded=${unshieldedBal ?? 0n}`);
248
+ }
249
+ //# sourceMappingURL=wallet-sync.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wallet-sync.js","sourceRoot":"","sources":["../../src/services/wallet-sync.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,MAAM,wCAAwC,CAAC;AAEtE,OAAO,EACL,WAAW,EACX,eAAe,EACf,iBAAiB,GAClB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AAG9E,OAAO,KAAK,EAAE,MAAM,MAAM,CAAC;AAC3B,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAEtD;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,GAAG,CAAC;AAEhC;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,MAA8B,EAC9B,MAAc;IAEd,IAAI,CAAC;QACH,MAAM,SAAS,GAAG,YAAY,EAAE,CAAC;QACjC,MAAM,CAAC,aAAa,EAAE,eAAe,EAAE,SAAS,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;YACpE,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;YAC/C,EAAE,CAAC,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,CA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CAAC;IAC/B,CAAC;IAED,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;IACzD,MAAM,QAAQ,GACZ,QAAQ,GAAG,EAAE;QACX,CAAC,CAAC,GAAG,QAAQ,GAAG;QAChB,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,EAAE,CAAC,KAAK,QAAQ,GAAG,EAAE,GAAG,CAAC;IACxD,MAAM,CAAC,IAAI,CAAC,uBAAuB,QAAQ,EAAE,CAAC,CAAC;IAE/C,iEAAiE;IACjE,oEAAoE;IACpE,gEAAgE;IAChE,8DAA8D;IAC9D,8DAA8D;IAC9D,MAAM,WAAW,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,GAAG,CAAC,CAAC;IAClE,MAAM,aAAa,GAAG,MAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,eAAe,EAAE,CAAC,GAAG,CAAC,CAAC;IACxE,MAAM,WAAW,GAAG,WAAW,KAAK,SAAS,IAAI,WAAW,GAAG,EAAE,CAAC;IAClE,MAAM,aAAa,GAAG,aAAa,KAAK,SAAS,IAAI,aAAa,GAAG,EAAE,CAAC;IACxE,IAAI,CAAC,WAAW,IAAI,CAAC,aAAa,EAAE,CAAC;QACnC,MAAM,IAAI,mBAAmB,CAAC,MAAM,CAAC,gBAAgB,EAAE,CAAC,CAAC;IAC3D,CAAC;IACD,MAAM,CAAC,IAAI,CACT,4BAA4B,WAAW,IAAI,EAAE,gBAAgB,aAAa,IAAI,EAAE,EAAE,CACnF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,64 @@
1
+ import { type EnvironmentConfiguration, MidnightWalletProvider } from '@midnight-ntwrk/testkit-js';
2
+ import { type UnshieldedKeystore } from '@midnight-ntwrk/wallet-sdk-unshielded-wallet';
3
+ import type { Logger } from 'pino';
4
+ import type { WalletSeed } from './seeds.ts';
5
+ export interface WalletHandlerBuildOptions {
6
+ /** Directory `compact.toml` was loaded from; see `CompactConfig.rootDir`. */
7
+ rootDir: string;
8
+ /** Force a fresh sync from genesis (skip the on-disk cache). Default `false`. */
9
+ skipWalletCache?: boolean;
10
+ /**
11
+ * Import a pre-warmed dust wallet state file into `.states/` before
12
+ * the restore path runs. Accepts raw JSON (output of
13
+ * `DustWallet.serializeState()`) or a gzipped copy; gzip is detected
14
+ * by magic bytes. Overwrites any existing cache for the seed.
15
+ * Ignored under {@link skipWalletCache}.
16
+ */
17
+ seedCacheDust?: string;
18
+ /** Like {@link seedCacheDust} but for the shielded sub-wallet. */
19
+ seedCacheShielded?: string;
20
+ /** Like {@link seedCacheDust} but for the unshielded sub-wallet. */
21
+ seedCacheUnshielded?: string;
22
+ /**
23
+ * Sync batch size for the shielded + dust sub-wallets. Defaults to
24
+ * {@link DEFAULT_SYNC_BATCH_SIZE} (5000). Raise it to replay a long dust
25
+ * history faster (more memory per batch); lower it on a memory-constrained
26
+ * host. The SDK default of 10 OOMs on preprod's ~1M-event dust stream.
27
+ */
28
+ syncBatchSize?: number;
29
+ }
30
+ /**
31
+ * Owned wallet handle: a built `MidnightWalletProvider` plus the
32
+ * on-disk caches for its three sub-wallets. Acquire via {@link build}
33
+ * and an `AsyncDisposableStack.use()`; call {@link saveCache} after
34
+ * sync.
35
+ */
36
+ export declare class WalletHandler implements AsyncDisposable {
37
+ #private;
38
+ /** The underlying testkit-js wallet provider. */
39
+ readonly provider: MidnightWalletProvider;
40
+ /** The unshielded keystore the wallet was built with. */
41
+ readonly unshieldedKeystore: UnshieldedKeystore;
42
+ private constructor();
43
+ /**
44
+ * Build a `MidnightWalletProvider` with three fixes over the bare
45
+ * testkit-js builder:
46
+ * 1. Tunes `additionalFeeOverhead` down to real wallet dust balances.
47
+ * 2. Routes mnemonic vs hex seed through the right derivation path
48
+ * (they derive *different* wallets from the same input).
49
+ * 3. Restores all three sub-wallets from on-disk cache when present
50
+ * (saves the 30–60 min first-preprod sync).
51
+ * Caller drives `provider.start()`; call {@link saveCache} post-sync.
52
+ */
53
+ static build(logger: Logger, env: EnvironmentConfiguration, seed: WalletSeed, opts: WalletHandlerBuildOptions): Promise<WalletHandler>;
54
+ /**
55
+ * Snapshot all three sub-wallets to disk. Best-effort and independent
56
+ * per sub-wallet. Shielded and dust are cached because they are slow
57
+ * on first sync (shielded trial-decrypts every note; dust streams the
58
+ * global unfiltered ledger event log). Unshielded is cached because
59
+ * the sync gate waits on its progress, so an uncached one re-syncs
60
+ * from genesis and dominates an otherwise-warm boot.
61
+ */
62
+ saveCache(): Promise<void>;
63
+ [Symbol.asyncDispose](): Promise<void>;
64
+ }
@@ -0,0 +1,151 @@
1
+ import { DustSecretKey, ZswapSecretKeys } from '@midnight-ntwrk/ledger-v8';
2
+ import { DEFAULT_DUST_OPTIONS, FluentWalletBuilder, MidnightWalletProvider, logger as testkitLogger, WalletFactory, WalletSeeds, } from '@midnight-ntwrk/testkit-js';
3
+ import { createKeystore, } from '@midnight-ntwrk/wallet-sdk-unshielded-wallet';
4
+ import { formatError } from "../services/error-format.js";
5
+ import { WalletCache } from "../services/wallet-cache.js";
6
+ // testkit-js builds its own pino logger at import and pretty-prints through it
7
+ // to stdout, ignoring the logger passed into every call. `--json` reserves
8
+ // stdout for the single result object, so silence it before the first
9
+ // `FluentWalletBuilder.forEnvironment` call.
10
+ testkitLogger.level = 'silent';
11
+ /**
12
+ * Default sync batch size for the shielded + dust sub-wallets, overridable
13
+ * per build via {@link WalletHandlerBuildOptions.syncBatchSize}. The SDK
14
+ * default (size 10) exhausts the V8 heap replaying preprod's ~1M-event
15
+ * global dust stream on `wallet-sdk-dust-wallet@4.0.0`
16
+ * (midnightntwrk/midnight-wallet#425, "Ineffective mark-compacts near heap
17
+ * limit"). A larger batch streams the replay in bigger chunks; size 5000
18
+ * was validated at ~146 MB peak, ~1000 events/sec. Kept on the shipped
19
+ * 4.1.0, which has not been run without it.
20
+ */
21
+ const DEFAULT_SYNC_BATCH_SIZE = 5000;
22
+ /** `timeout`/`spacing` companions to the batch size; left at the validated values. */
23
+ const SYNC_BATCH_TIMING = { timeout: 1, spacing: 4 };
24
+ /**
25
+ * Owned wallet handle: a built `MidnightWalletProvider` plus the
26
+ * on-disk caches for its three sub-wallets. Acquire via {@link build}
27
+ * and an `AsyncDisposableStack.use()`; call {@link saveCache} after
28
+ * sync.
29
+ */
30
+ export class WalletHandler {
31
+ /** The underlying testkit-js wallet provider. */
32
+ provider;
33
+ /** The unshielded keystore the wallet was built with. */
34
+ unshieldedKeystore;
35
+ #logger;
36
+ #cache;
37
+ constructor(provider, keystore, logger, cache) {
38
+ this.provider = provider;
39
+ this.unshieldedKeystore = keystore;
40
+ this.#logger = logger;
41
+ this.#cache = cache;
42
+ }
43
+ /**
44
+ * Build a `MidnightWalletProvider` with three fixes over the bare
45
+ * testkit-js builder:
46
+ * 1. Tunes `additionalFeeOverhead` down to real wallet dust balances.
47
+ * 2. Routes mnemonic vs hex seed through the right derivation path
48
+ * (they derive *different* wallets from the same input).
49
+ * 3. Restores all three sub-wallets from on-disk cache when present
50
+ * (saves the 30–60 min first-preprod sync).
51
+ * Caller drives `provider.start()`; call {@link saveCache} post-sync.
52
+ */
53
+ static async build(logger, env, seed, opts) {
54
+ const dustOptions = {
55
+ ...DEFAULT_DUST_OPTIONS,
56
+ // testkit's 5e20 default exceeds a typical preview/preprod
57
+ // wallet's ~3e15 dust, breaking fee balance. 5e14 keeps margin
58
+ // without exceeding the balance on any network the deployer accepts.
59
+ additionalFeeOverhead: 500000000000000n,
60
+ };
61
+ const walletSeeds = seed.kind === 'mnemonic'
62
+ ? WalletSeeds.fromMnemonic(seed.value)
63
+ : WalletSeeds.fromMasterSeed(seed.value);
64
+ // testkit-js doesn't export `mapEnvironmentToConfiguration` and
65
+ // the `config` field isn't on the .d.ts. Cast through unknown.
66
+ const builderForConfig = FluentWalletBuilder.forEnvironment(env);
67
+ const config = builderForConfig
68
+ .config;
69
+ // Raise the sync batch size on the *shared* config so it applies to
70
+ // every sub-wallet built off it: shielded and dust, fresh-sync and
71
+ // cache-restore alike. `buildDustConfig` spreads this config, so the
72
+ // restore path inherits it too. Setting it only on the fresh-build
73
+ // path would be bypassed the moment an on-disk snapshot exists, which
74
+ // is exactly when preprod's dust replay OOMs. See
75
+ // {@link DEFAULT_SYNC_BATCH_SIZE} and OpenZeppelin/compact-tools#115.
76
+ config.batchUpdates = {
77
+ size: opts.syncBatchSize ?? DEFAULT_SYNC_BATCH_SIZE,
78
+ ...SYNC_BATCH_TIMING,
79
+ };
80
+ const unshieldedKeystore = createKeystore(walletSeeds.unshielded, env.walletNetworkId);
81
+ const cache = new WalletCache({
82
+ logger,
83
+ env,
84
+ rootDir: opts.rootDir,
85
+ shieldedSeed: walletSeeds.shielded,
86
+ dustSeed: walletSeeds.dust,
87
+ unshieldedSeed: walletSeeds.unshielded,
88
+ });
89
+ // Pre-warmed cache import: place the user-supplied state file at
90
+ // the seed-derived `.states/` path so the existing restore path
91
+ // picks it up. Mutual exclusion with `--no-cache` is a warn, not a
92
+ // hard error — keeps the flag combinations cheap.
93
+ if (opts.skipWalletCache === true) {
94
+ if (opts.seedCacheShielded ||
95
+ opts.seedCacheDust ||
96
+ opts.seedCacheUnshielded) {
97
+ logger.warn('--seed-cache-from-* is ignored under --no-cache (cache load is disabled)');
98
+ }
99
+ }
100
+ else {
101
+ if (opts.seedCacheShielded) {
102
+ cache.importSeedCache(opts.seedCacheShielded, 'shielded');
103
+ }
104
+ if (opts.seedCacheDust) {
105
+ cache.importSeedCache(opts.seedCacheDust, 'dust');
106
+ }
107
+ if (opts.seedCacheUnshielded) {
108
+ cache.importSeedCache(opts.seedCacheUnshielded, 'unshielded');
109
+ }
110
+ }
111
+ const shieldedWallet = await cache.loadOrCreateShieldedWallet({
112
+ config,
113
+ seed: walletSeeds.shielded,
114
+ skipCache: opts.skipWalletCache === true,
115
+ });
116
+ const unshieldedWallet = await cache.loadOrCreateUnshieldedWallet({
117
+ config,
118
+ keystore: unshieldedKeystore,
119
+ skipCache: opts.skipWalletCache === true,
120
+ });
121
+ const dustWallet = await cache.loadOrCreateDustWallet({
122
+ config,
123
+ seed: walletSeeds.dust,
124
+ dustOptions,
125
+ skipCache: opts.skipWalletCache === true,
126
+ });
127
+ const walletFacade = await WalletFactory.createWalletFacade(config, shieldedWallet, unshieldedWallet, dustWallet);
128
+ const provider = await MidnightWalletProvider.withWallet(logger, env, walletFacade, ZswapSecretKeys.fromSeed(walletSeeds.shielded), DustSecretKey.fromSeed(walletSeeds.dust), unshieldedKeystore);
129
+ return new WalletHandler(provider, unshieldedKeystore, logger, cache);
130
+ }
131
+ /**
132
+ * Snapshot all three sub-wallets to disk. Best-effort and independent
133
+ * per sub-wallet. Shielded and dust are cached because they are slow
134
+ * on first sync (shielded trial-decrypts every note; dust streams the
135
+ * global unfiltered ledger event log). Unshielded is cached because
136
+ * the sync gate waits on its progress, so an uncached one re-syncs
137
+ * from genesis and dominates an otherwise-warm boot.
138
+ */
139
+ async saveCache() {
140
+ await this.#cache.save(this.provider.wallet);
141
+ }
142
+ async [Symbol.asyncDispose]() {
143
+ try {
144
+ await this.provider.stop();
145
+ }
146
+ catch (e) {
147
+ this.#logger.warn({ err: formatError(e) }, 'Wallet stop failed');
148
+ }
149
+ }
150
+ }
151
+ //# sourceMappingURL=handler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handler.js","sourceRoot":"","sources":["../../src/wallet/handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,EACL,oBAAoB,EAGpB,mBAAmB,EACnB,sBAAsB,EACtB,MAAM,IAAI,aAAa,EACvB,aAAa,EACb,WAAW,GACZ,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EACL,cAAc,GAEf,MAAM,8CAA8C,CAAC;AAEtD,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;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I,CAAC;YACH,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC7B,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,WAAW,CAAC,CAAC,CAAC,EAAE,EAAE,oBAAoB,CAAC,CAAC;QACnE,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Web3 Secret Storage v3-shaped JSON keystore (scrypt + AES-128-CTR +
3
+ * SHA-256 MAC) with a `version: "midnight-1"` marker so future schema
4
+ * bumps don't collide with Ethereum tooling that reads v3.
5
+ */
6
+ declare const VERSION = "midnight-1";
7
+ /** On-disk JSON shape. Exported so consumers can transport keystores verbatim. */
8
+ export interface MidnightKeystore {
9
+ version: typeof VERSION;
10
+ id: string;
11
+ crypto: {
12
+ cipher: 'aes-128-ctr';
13
+ ciphertext: string;
14
+ cipherparams: {
15
+ iv: string;
16
+ };
17
+ kdf: 'scrypt';
18
+ kdfparams: {
19
+ dklen: number;
20
+ n: number;
21
+ p: number;
22
+ r: number;
23
+ salt: string;
24
+ };
25
+ mac: string;
26
+ };
27
+ }
28
+ export interface KeystoreCreateOptions {
29
+ scryptN?: number;
30
+ scryptP?: number;
31
+ scryptR?: number;
32
+ dklen?: number;
33
+ }
34
+ /** Encrypted wallet-seed wrapper; invariants enforced at construction. */
35
+ export declare class Keystore {
36
+ #private;
37
+ private constructor();
38
+ /** Encrypt a 32-byte hex seed (with or without `0x`) under `passphrase`. Override {@link DEFAULTS} only for tests that need fast scrypt. */
39
+ static encrypt(seedHex: string, passphrase: string, opts?: KeystoreCreateOptions): Keystore;
40
+ /** Read + parse a JSON keystore file. Validates via {@link Keystore.fromJSON}. */
41
+ static readFromFile(path: string): Promise<Keystore>;
42
+ /**
43
+ * Wrap parsed keystore JSON. Validates the complete shape, so `decrypt`
44
+ * can index into `crypto` without guards and never surfaces a raw
45
+ * `TypeError` from a hand-edited or truncated file.
46
+ */
47
+ static fromJSON(data: unknown): Keystore;
48
+ /** Recover the hex-encoded seed. Throws {@link WalletError} on MAC mismatch. */
49
+ decrypt(passphrase: string): string;
50
+ /** Write to disk as pretty JSON with mode `0o600`. */
51
+ writeToFile(path: string): Promise<void>;
52
+ /** Return the on-disk JSON shape. */
53
+ toJSON(): MidnightKeystore;
54
+ }
55
+ export {};