@dynamic-labs-wallet/midnight 0.0.353 → 0.1.0-request-signing

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.esm.js CHANGED
@@ -1,10 +1,11 @@
1
- import { AuthMode, DynamicWalletClient, ERROR_PASSWORD_MISMATCH, getMPCChainConfig, getMPCSigner, WalletOperation } from '@dynamic-labs-wallet/browser';
1
+ import { DynamicWalletClient, ERROR_PASSWORD_MISMATCH, ERROR_MULTIPLE_WALLETS_PER_CHAIN, getMPCChainConfig, getMPCSigner, WalletOperation } from '@dynamic-labs-wallet/browser';
2
2
  import * as ledger from '@midnight-ntwrk/ledger-v8';
3
- import { ShieldedAddress, ShieldedCoinPublicKey, ShieldedEncryptionPublicKey, MidnightBech32m, DustAddress, UnshieldedAddress } from '@midnight-ntwrk/wallet-sdk-address-format';
3
+ import { ShieldedAddress, ShieldedCoinPublicKey, ShieldedEncryptionPublicKey, MidnightBech32m, DustAddress, mainnet, UnshieldedAddress } from '@midnight-ntwrk/wallet-sdk-address-format';
4
4
  import { DustWallet } from '@midnight-ntwrk/wallet-sdk-dust-wallet';
5
5
  import { WalletFacade } from '@midnight-ntwrk/wallet-sdk-facade';
6
6
  import { ShieldedWallet } from '@midnight-ntwrk/wallet-sdk-shielded';
7
- import { UnshieldedWallet, PublicKey, createKeystore, NoOpTransactionHistoryStorage } from '@midnight-ntwrk/wallet-sdk-unshielded-wallet';
7
+ import { NoOpTransactionHistoryStorage } from '@midnight-ntwrk/wallet-sdk-abstractions';
8
+ import { UnshieldedWallet, PublicKey, createKeystore } from '@midnight-ntwrk/wallet-sdk-unshielded-wallet';
8
9
  import { HDKey } from '@scure/bip32';
9
10
  import bs58 from 'bs58';
10
11
  import { bech32m } from 'bech32';
@@ -21,6 +22,32 @@ var MIDNIGHT_NETWORK_IDS = {
21
22
  preprod: 0,
22
23
  undeployed: 0
23
24
  };
25
+ /**
26
+ * Resolves the caller-supplied network identifier (numeric 0/1, network name,
27
+ * or "midnight:<network>" chainId) to the facade network tag. Defaults to
28
+ * 'preview' when absent — the legacy single-network behavior, so requests from
29
+ * hosts that predate per-network support are unchanged.
30
+ */ var resolveMidnightNetworkTag = function(networkId) {
31
+ if (networkId === undefined || networkId === null) return 'preview';
32
+ if (typeof networkId === 'number') return networkId === 1 ? 'mainnet' : 'preview';
33
+ var name = networkId.includes(':') ? networkId.split(':')[1] : networkId;
34
+ return name === 'mainnet' ? 'mainnet' : 'preview';
35
+ };
36
+ var MIDNIGHT_PROOF_SERVER_URL = 'https://proof-server.us-east-1.dynamic-preprod.xyz';
37
+ var MIDNIGHT_INFRA = {
38
+ mainnet: {
39
+ relayUrl: 'wss://rpc.mainnet.midnight.network',
40
+ provingServerUrl: MIDNIGHT_PROOF_SERVER_URL,
41
+ indexerHttpUrl: 'https://indexer.mainnet.midnight.network/api/v4/graphql',
42
+ indexerWsUrl: 'wss://indexer.mainnet.midnight.network/api/v4/graphql/ws'
43
+ },
44
+ preview: {
45
+ relayUrl: 'wss://rpc.preview.midnight.network',
46
+ provingServerUrl: MIDNIGHT_PROOF_SERVER_URL,
47
+ indexerHttpUrl: 'https://indexer.preview.midnight.network/api/v4/graphql',
48
+ indexerWsUrl: 'wss://indexer.preview.midnight.network/api/v4/graphql/ws'
49
+ }
50
+ };
24
51
  // Error messages
25
52
  var ERROR_ACCOUNT_ADDRESS_REQUIRED = 'Account address is required';
26
53
  var ERROR_NETWORK_ID_REQUIRED = 'Network ID is required for Midnight transactions';
@@ -211,7 +238,12 @@ function _ts_generator$1(thisArg, body) {
211
238
  }
212
239
  }
213
240
  var DB_NAME = 'dynamic-midnight-wallet-state';
214
- var DB_VERSION = 1;
241
+ // Open WITHOUT a fixed version. Passing a version LOWER than the one already in
242
+ // the browser throws `VersionError` (IndexedDB forbids downgrades) — which is
243
+ // exactly what broke the cache after an earlier `DB_VERSION = 2` experiment was
244
+ // reverted to 1: dev browsers still had v2, every open failed, and the wallet
245
+ // cold-synced on every load. Opening with no version adopts whatever version
246
+ // exists (or creates the DB fresh), so a downgrade error is impossible.
215
247
  var STORE_NAME = 'state';
216
248
  // Normalizes a DOMException | unknown into an Error so promise rejections
217
249
  // always carry an Error instance. Object-shaped errors (DOMException, plain
@@ -241,8 +273,10 @@ function openDb() {
241
273
  // the session (private-browsing bootup, transient quota errors, etc).
242
274
  // Re-throw so the original caller still sees the rejection.
243
275
  dbPromise = new Promise(function(resolve, reject) {
244
- var req = indexedDB.open(DB_NAME, DB_VERSION);
276
+ var req = indexedDB.open(DB_NAME);
245
277
  req.onupgradeneeded = function() {
278
+ // Fires only when the DB is first created (or an existing DB lacks the
279
+ // store). Create the store if absent; never destructive.
246
280
  var db = req.result;
247
281
  if (!db.objectStoreNames.contains(STORE_NAME)) {
248
282
  db.createObjectStore(STORE_NAME, {
@@ -301,7 +335,7 @@ function getWalletState(accountAddress) {
301
335
  }
302
336
  function _getWalletState() {
303
337
  _getWalletState = _async_to_generator$1(function(accountAddress) {
304
- var result;
338
+ var result, err;
305
339
  return _ts_generator$1(this, function(_state) {
306
340
  switch(_state.label){
307
341
  case 0:
@@ -324,8 +358,13 @@ function _getWalletState() {
324
358
  result !== null && result !== void 0 ? result : null
325
359
  ];
326
360
  case 2:
327
- _state.sent();
328
- // IndexedDB unavailable (private mode, corrupt DB, etc.) — behave as if empty.
361
+ err = _state.sent();
362
+ // IndexedDB unavailable (private mode, third-party storage partitioning,
363
+ // corrupt DB, etc.) — behave as if empty. Surface to the console so a
364
+ // blocked/partitioned store (which would force a cold sync every load)
365
+ // is visible instead of silently swallowed.
366
+ // eslint-disable-next-line no-console
367
+ console.warn('[Midnight] CACHE read FAILED (IndexedDB unavailable) — treating as empty:', err);
329
368
  return [
330
369
  2,
331
370
  null
@@ -344,7 +383,7 @@ function putWalletState(accountAddress, state) {
344
383
  }
345
384
  function _putWalletState() {
346
385
  _putWalletState = _async_to_generator$1(function(accountAddress, state) {
347
- var record;
386
+ var record, err;
348
387
  return _ts_generator$1(this, function(_state) {
349
388
  switch(_state.label){
350
389
  case 0:
@@ -370,12 +409,19 @@ function _putWalletState() {
370
409
  ];
371
410
  case 2:
372
411
  _state.sent();
412
+ // eslint-disable-next-line no-console
413
+ console.info("[Midnight] CACHE write OK — checkpoint saved (shielded=".concat(record.shielded.length, "B dust=").concat(record.dust.length, "B)"));
373
414
  return [
374
415
  3,
375
416
  4
376
417
  ];
377
418
  case 3:
378
- _state.sent();
419
+ err = _state.sent();
420
+ // Persist is best-effort. A failure just means next init will cold-sync —
421
+ // but surface it so a blocked/partitioned IndexedDB (third-party iframe)
422
+ // is visible rather than silently swallowed.
423
+ // eslint-disable-next-line no-console
424
+ console.warn('[Midnight] CACHE write FAILED (IndexedDB unavailable):', err);
379
425
  return [
380
426
  3,
381
427
  4
@@ -597,6 +643,33 @@ function _object_spread_props(target, source) {
597
643
  }
598
644
  return target;
599
645
  }
646
+ function _object_without_properties(source, excluded) {
647
+ if (source == null) return {};
648
+ var target = _object_without_properties_loose(source, excluded);
649
+ var key, i;
650
+ if (Object.getOwnPropertySymbols) {
651
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
652
+ for(i = 0; i < sourceSymbolKeys.length; i++){
653
+ key = sourceSymbolKeys[i];
654
+ if (excluded.indexOf(key) >= 0) continue;
655
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
656
+ target[key] = source[key];
657
+ }
658
+ }
659
+ return target;
660
+ }
661
+ function _object_without_properties_loose(source, excluded) {
662
+ if (source == null) return {};
663
+ var target = {};
664
+ var sourceKeys = Object.keys(source);
665
+ var key, i;
666
+ for(i = 0; i < sourceKeys.length; i++){
667
+ key = sourceKeys[i];
668
+ if (excluded.indexOf(key) >= 0) continue;
669
+ target[key] = source[key];
670
+ }
671
+ return target;
672
+ }
600
673
  function _possible_constructor_return(self, call) {
601
674
  if (call && (_type_of(call) === "object" || typeof call === "function")) {
602
675
  return call;
@@ -742,28 +815,33 @@ function _ts_values(o) {
742
815
  };
743
816
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
744
817
  }
818
+ /** Whether a sub-wallet side has finished syncing. `highestRelevantIndex`
819
+ * is 0 during sync, so `isStrictlyComplete()` is the authoritative signal. */ /** Strict base64 (with optional padding) — used to validate host-supplied
820
+ * serialized transactions before they reach the ledger WASM deserializer. */ var BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
821
+ /** Upper bound on a serialized Midnight transaction the iframe will decode.
822
+ * Generous next to real transactions, small enough that a bad or hostile
823
+ * payload is rejected before any WASM work happens. */ var MAX_SERIALIZED_TRANSACTION_BYTES = 4 * 1024 * 1024;
824
+ var isSideSynced = function(side) {
825
+ var _side_state;
826
+ var _side_progress;
827
+ var p = (_side_progress = side === null || side === void 0 ? void 0 : side.progress) !== null && _side_progress !== void 0 ? _side_progress : side === null || side === void 0 ? void 0 : (_side_state = side.state) === null || _side_state === void 0 ? void 0 : _side_state.progress;
828
+ if (!p) return false;
829
+ if (typeof p.isStrictlyComplete === 'function') return p.isStrictlyComplete();
830
+ var _p_appliedIndex;
831
+ var applied = BigInt((_p_appliedIndex = p.appliedIndex) !== null && _p_appliedIndex !== void 0 ? _p_appliedIndex : 0n);
832
+ var _p_highestRelevantIndex;
833
+ var highestRelevant = BigInt((_p_highestRelevantIndex = p.highestRelevantIndex) !== null && _p_highestRelevantIndex !== void 0 ? _p_highestRelevantIndex : 0n);
834
+ return highestRelevant > 0n && applied >= highestRelevant;
835
+ };
836
+ /** Resolve predicate for the sync wait, per mode. */ var isSyncResolved = function(s, mode) {
837
+ return mode === 'full' ? Boolean(s.isSynced) : isSideSynced(s.shielded) && isSideSynced(s.unshielded);
838
+ };
745
839
  var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
746
840
  _inherits(DynamicMidnightWalletClient, DynamicWalletClient);
747
- function DynamicMidnightWalletClient(param, internalOptions) {
748
- var environmentId = param.environmentId, authToken = param.authToken, baseApiUrl = param.baseApiUrl, baseMPCRelayApiUrl = param.baseMPCRelayApiUrl, storageKey = param.storageKey, debug = param.debug, featureFlags = param.featureFlags, _param_authMode = param.authMode, authMode = _param_authMode === void 0 ? AuthMode.HEADER : _param_authMode, sdkVersion = param.sdkVersion, forwardMPCClient = param.forwardMPCClient, logger = param.logger;
841
+ function DynamicMidnightWalletClient() {
749
842
  _class_call_check(this, DynamicMidnightWalletClient);
750
843
  var _this;
751
- _this = _call_super(this, DynamicMidnightWalletClient, [
752
- {
753
- environmentId: environmentId,
754
- authToken: authToken,
755
- baseApiUrl: baseApiUrl,
756
- baseMPCRelayApiUrl: baseMPCRelayApiUrl,
757
- storageKey: storageKey,
758
- debug: debug,
759
- featureFlags: featureFlags,
760
- authMode: authMode,
761
- sdkVersion: sdkVersion,
762
- forwardMPCClient: forwardMPCClient,
763
- logger: logger
764
- },
765
- internalOptions
766
- ]), _define_property(_this, "chainName", 'MIDNIGHT'), // Keep wallet alive between calls — avoids 90s re-sync per operation.
844
+ _this = _call_super(this, DynamicMidnightWalletClient, arguments), _define_property(_this, "chainName", 'MIDNIGHT'), // Keep wallet alive between calls — avoids 90s re-sync per operation.
767
845
  // `diagnosticSub` is the long-lived pending-tx log subscription attached
768
846
  // at init time; we hold onto its handle so account-switch / resetCache
769
847
  // paths can unsubscribe it and release the closure.
@@ -847,6 +925,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
847
925
  isDirty = pendingTxCount > 0 || unshieldedPending > 0 || shieldedPending > 0 || dustPending > 0;
848
926
  if (isDirty) {
849
927
  _this.logger.debug("[Midnight] persist skipped — state is dirty \xb7 " + "pendingTxs=".concat(pendingTxCount, " \xb7 unshieldedPending=").concat(unshieldedPending, " \xb7 ") + "shieldedPending=".concat(shieldedPending, " \xb7 dustPending=").concat(dustPending, ". ") + "IndexedDB retains last clean snapshot.");
928
+ // console.* because this.logger is a NoopLogger in the iframe — cache
929
+ // diagnostics must be visible in the browser console.
930
+ // eslint-disable-next-line no-console
931
+ console.info("[Midnight] CACHE persist SKIPPED (state dirty) \xb7 pendingTxs=".concat(pendingTxCount, " ") + "unshieldedPending=".concat(unshieldedPending, " shieldedPending=").concat(shieldedPending, " dustPending=").concat(dustPending, " — no checkpoint saved, next load cold-syncs"));
850
932
  return [
851
933
  2
852
934
  ];
@@ -875,7 +957,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
875
957
  }
876
958
  return [
877
959
  4,
878
- putWalletState(cached.accountAddress, {
960
+ putWalletState(DynamicMidnightWalletClient.walletStateKey(cached.accountAddress, cached.network), {
879
961
  shielded: shielded,
880
962
  dust: dust
881
963
  })
@@ -890,6 +972,8 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
890
972
  case 5:
891
973
  err = _state.sent();
892
974
  _this.logger.warn('[Midnight] Failed to persist wallet state:', err);
975
+ // eslint-disable-next-line no-console
976
+ console.warn('[Midnight] CACHE persist FAILED (write/serialize threw):', err);
893
977
  return [
894
978
  3,
895
979
  6
@@ -906,10 +990,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
906
990
  {
907
991
  key: "createWalletAccount",
908
992
  value: function createWalletAccount(param) {
909
- var thresholdSignatureScheme = param.thresholdSignatureScheme, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, onError = param.onError, signedSessionId = param.signedSessionId;
993
+ var thresholdSignatureScheme = param.thresholdSignatureScheme, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, onError = param.onError, signedSessionId = param.signedSessionId, businessAccountId = param.businessAccountId;
910
994
  var _this = this;
911
995
  return _async_to_generator(function() {
912
- var ceremonyCeremonyCompleteResolver, serverAccountAddress, ceremonyCompletePromise, _ref, publicKeyHex, clientKeyShares, accountAddress, pubKeyBytes, roleKeys, shieldedSecretKeys, shieldedAddr, shieldedBech32m, dustBech32m, dustSecretKey, dustAddr, toHex, correctAddresses, wallet, addrError, error;
996
+ var ceremonyCeremonyCompleteResolver, serverAccountAddress, ceremonyCompletePromise, _ref, publicKeyHex, clientKeyShares, accountAddress, pubKeyBytes, roleKeys, shieldedSecretKeys, shieldedAddr, dustSecretKey, toHex, correctionNetworks, correctAddresses, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, _step_value, tag, encodeId, dustAddr, wallet, addrError, error;
913
997
  return _ts_generator(this, function(_state) {
914
998
  switch(_state.label){
915
999
  case 0:
@@ -926,9 +1010,11 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
926
1010
  4,
927
1011
  _this.keyGen({
928
1012
  chainName: _this.chainName,
1013
+ businessAccountId: businessAccountId,
929
1014
  thresholdSignatureScheme: thresholdSignatureScheme,
930
1015
  onError: onError,
931
- onCeremonyComplete: function(accountAddress, walletId) {
1016
+ onCeremonyComplete: function(param) {
1017
+ var accountAddress = param.accountAddress, walletId = param.walletId, shareSetId = param.shareSetId;
932
1018
  var chainConfig = getMPCChainConfig(_this.chainName);
933
1019
  serverAccountAddress = accountAddress;
934
1020
  _this.initializeWalletMapEntry({
@@ -941,7 +1027,8 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
941
1027
  index,
942
1028
  value
943
1029
  ];
944
- })))
1030
+ }))),
1031
+ shareSetId: shareSetId
945
1032
  });
946
1033
  ceremonyCeremonyCompleteResolver(undefined);
947
1034
  },
@@ -978,7 +1065,8 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
978
1065
  accountAddress: accountAddress,
979
1066
  clientKeyShares: clientKeyShares,
980
1067
  password: password,
981
- signedSessionId: signedSessionId
1068
+ signedSessionId: signedSessionId,
1069
+ businessAccountId: businessAccountId
982
1070
  })
983
1071
  ];
984
1072
  case 4:
@@ -1004,13 +1092,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1004
1092
  roleKeys = _state.sent();
1005
1093
  shieldedSecretKeys = ledger.ZswapSecretKeys.fromSeed(new Uint8Array(Buffer.from(roleKeys.shielded, 'hex')));
1006
1094
  shieldedAddr = new ShieldedAddress(new ShieldedCoinPublicKey(Buffer.from(shieldedSecretKeys.coinPublicKey, 'hex')), new ShieldedEncryptionPublicKey(Buffer.from(shieldedSecretKeys.encryptionPublicKey, 'hex')));
1007
- shieldedBech32m = MidnightBech32m.encode('preview', shieldedAddr).toString();
1008
1095
  try {
1009
1096
  dustSecretKey = ledger.DustSecretKey.fromSeed(new Uint8Array(Buffer.from(roleKeys.dust, 'hex')));
1010
- dustAddr = new DustAddress(dustSecretKey.publicKey);
1011
- dustBech32m = MidnightBech32m.encode('preview', dustAddr).toString();
1012
1097
  } catch (dustErr) {
1013
- _this.logger.warn('[Midnight] Dust address encoding failed (skipping):', dustErr);
1098
+ _this.logger.warn('[Midnight] Dust key derivation failed (skipping dust addresses):', dustErr);
1014
1099
  }
1015
1100
  toHex = function(val) {
1016
1101
  if (typeof val === 'string') return val;
@@ -1018,24 +1103,58 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1018
1103
  if ((typeof val === "undefined" ? "undefined" : _type_of(val)) === 'bigint') return val.toString(16);
1019
1104
  return String(val);
1020
1105
  };
1021
- correctAddresses = [
1106
+ // One key, one encoding per network — only the bech32m HRP differs.
1107
+ // Preview first: Midnight's legacy default, so legacy first-match
1108
+ // lookups keep resolving the preview encoding. The mainnet network id
1109
+ // is the library's `mainnet` symbol (bare HRP, no network segment).
1110
+ correctionNetworks = [
1022
1111
  {
1023
- address: accountAddress,
1024
- type: 'midnight_unshielded',
1025
- publicKey: toHex(publicKeyHex)
1112
+ tag: 'preview',
1113
+ encodeId: 'preview'
1026
1114
  },
1027
1115
  {
1028
- address: shieldedBech32m,
1029
- type: 'midnight_shielded',
1030
- publicKey: toHex(shieldedSecretKeys.coinPublicKey)
1116
+ tag: 'mainnet',
1117
+ encodeId: mainnet
1031
1118
  }
1032
1119
  ];
1033
- if (dustBech32m && dustSecretKey) {
1034
- correctAddresses.push({
1035
- address: dustBech32m,
1036
- type: 'midnight_dust',
1037
- publicKey: toHex(dustSecretKey.publicKey)
1038
- });
1120
+ correctAddresses = [];
1121
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1122
+ try {
1123
+ for(_iterator = correctionNetworks[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1124
+ _step_value = _step.value, tag = _step_value.tag, encodeId = _step_value.encodeId;
1125
+ correctAddresses.push({
1126
+ address: MidnightBech32m.encode(encodeId, shieldedAddr).toString(),
1127
+ type: 'midnight_shielded',
1128
+ publicKey: toHex(shieldedSecretKeys.coinPublicKey),
1129
+ network: tag
1130
+ });
1131
+ if (dustSecretKey) {
1132
+ try {
1133
+ dustAddr = new DustAddress(dustSecretKey.publicKey);
1134
+ correctAddresses.push({
1135
+ address: MidnightBech32m.encode(encodeId, dustAddr).toString(),
1136
+ type: 'midnight_dust',
1137
+ publicKey: toHex(dustSecretKey.publicKey),
1138
+ network: tag
1139
+ });
1140
+ } catch (dustErr) {
1141
+ _this.logger.warn('[Midnight] Dust address encoding failed (skipping):', dustErr);
1142
+ }
1143
+ }
1144
+ }
1145
+ } catch (err) {
1146
+ _didIteratorError = true;
1147
+ _iteratorError = err;
1148
+ } finally{
1149
+ try {
1150
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1151
+ _iterator.return();
1152
+ }
1153
+ } finally{
1154
+ if (_didIteratorError) {
1155
+ throw _iteratorError;
1156
+ }
1157
+ }
1039
1158
  }
1040
1159
  _this.logger.info('[Midnight] Updating additional addresses with correct derivation');
1041
1160
  return [
@@ -1082,12 +1201,14 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1082
1201
  ];
1083
1202
  case 11:
1084
1203
  error = _state.sent();
1085
- // Re-throw password mismatch errors without wrapping
1086
- if (_instanceof(error, Error) && error.message === ERROR_PASSWORD_MISMATCH) {
1204
+ // Re-throw known business-rule rejections without wrapping
1205
+ if (_instanceof(error, Error) && (error.message === ERROR_PASSWORD_MISMATCH || error.message === ERROR_MULTIPLE_WALLETS_PER_CHAIN)) {
1087
1206
  throw error;
1088
1207
  }
1089
1208
  _this.logger.error(ERROR_CREATE_WALLET_ACCOUNT, error);
1090
- throw new Error(ERROR_CREATE_WALLET_ACCOUNT);
1209
+ throw new Error(ERROR_CREATE_WALLET_ACCOUNT, {
1210
+ cause: error
1211
+ });
1091
1212
  case 12:
1092
1213
  return [
1093
1214
  2
@@ -1100,7 +1221,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1100
1221
  {
1101
1222
  key: "signMessage",
1102
1223
  value: function signMessage(param) {
1103
- var message = param.message, accountAddress = param.accountAddress, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, context = param.context, onError = param.onError;
1224
+ var message = param.message, accountAddress = param.accountAddress, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, context = param.context, approvalQuorum = param.approvalQuorum, onError = param.onError;
1104
1225
  var _this = this;
1105
1226
  return _async_to_generator(function() {
1106
1227
  var messageHex, resolvedContext, signature, error;
@@ -1145,6 +1266,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1145
1266
  signedSessionId: signedSessionId,
1146
1267
  mfaToken: mfaToken,
1147
1268
  context: resolvedContext,
1269
+ approvalQuorum: approvalQuorum,
1148
1270
  onError: onError
1149
1271
  })
1150
1272
  ];
@@ -1156,8 +1278,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1156
1278
  ];
1157
1279
  case 4:
1158
1280
  error = _state.sent();
1159
- _this.logger.error(ERROR_SIGN_MESSAGE, error);
1160
- throw new Error(ERROR_SIGN_MESSAGE);
1281
+ _this.logOperationFailure(ERROR_SIGN_MESSAGE, error);
1282
+ throw new Error(ERROR_SIGN_MESSAGE, {
1283
+ cause: error
1284
+ });
1161
1285
  case 5:
1162
1286
  return [
1163
1287
  2
@@ -1178,7 +1302,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1178
1302
  * entry). If the caller never calls submitTransaction, that entry sits
1179
1303
  * until the next re-sync drops it.
1180
1304
  */ function signTransaction(param) {
1181
- var senderAddress = param.senderAddress, transaction = param.transaction, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, networkId = param.networkId, context = param.context, onError = param.onError;
1305
+ var senderAddress = param.senderAddress, transaction = param.transaction, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, networkId = param.networkId, context = param.context, approvalQuorum = param.approvalQuorum, onError = param.onError;
1182
1306
  var _this = this;
1183
1307
  return _async_to_generator(function() {
1184
1308
  var resolvedNetworkId, wallet, txBytes, unsignedTx, signedRecipe, finalized, error;
@@ -1218,7 +1342,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1218
1342
  signedSessionId: signedSessionId,
1219
1343
  mfaToken: mfaToken,
1220
1344
  elevatedAccessToken: elevatedAccessToken
1221
- })
1345
+ }, 'full', resolveMidnightNetworkTag(networkId))
1222
1346
  ];
1223
1347
  case 3:
1224
1348
  wallet = _state.sent().wallet;
@@ -1238,6 +1362,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1238
1362
  fullTxBase64: transaction,
1239
1363
  networkId: resolvedNetworkId,
1240
1364
  baseContext: context,
1365
+ approvalQuorum: approvalQuorum,
1241
1366
  proofMarker: 'pre-proof'
1242
1367
  })
1243
1368
  ];
@@ -1260,7 +1385,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1260
1385
  ];
1261
1386
  case 6:
1262
1387
  error = _state.sent();
1263
- _this.logger.error(ERROR_SIGN_TRANSACTION, error);
1388
+ _this.logOperationFailure(ERROR_SIGN_TRANSACTION, error);
1264
1389
  onError === null || onError === void 0 ? void 0 : onError(error);
1265
1390
  throw _instanceof(error, Error) ? error : new Error(ERROR_SIGN_TRANSACTION);
1266
1391
  case 7:
@@ -1404,13 +1529,15 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1404
1529
  chainName: chainName,
1405
1530
  thresholdSignatureScheme: thresholdSignatureScheme,
1406
1531
  privateKey: formattedPrivateKey,
1407
- onCeremonyComplete: function(accountAddress, walletId) {
1532
+ onCeremonyComplete: function(param) {
1533
+ var accountAddress = param.accountAddress, walletId = param.walletId, shareSetId = param.shareSetId;
1408
1534
  serverAccountAddress = accountAddress;
1409
1535
  _this.initializeWalletMapEntry({
1410
1536
  accountAddress: accountAddress,
1411
1537
  walletId: walletId,
1412
1538
  chainName: _this.chainName,
1413
- thresholdSignatureScheme: thresholdSignatureScheme
1539
+ thresholdSignatureScheme: thresholdSignatureScheme,
1540
+ shareSetId: shareSetId
1414
1541
  });
1415
1542
  ceremonyCeremonyCompleteResolver(undefined);
1416
1543
  },
@@ -1654,25 +1781,29 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1654
1781
  {
1655
1782
  key: "initMidnightWallet",
1656
1783
  value: function initMidnightWallet(label, mpcParams) {
1784
+ var mode = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 'full', network = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 'preview';
1657
1785
  var _this = this;
1658
1786
  return _async_to_generator(function() {
1659
- var accountAddress, inFlight, initPromise;
1787
+ var accountAddress, initKey, inFlight, initPromise;
1660
1788
  return _ts_generator(this, function(_state) {
1661
1789
  switch(_state.label){
1662
1790
  case 0:
1663
1791
  accountAddress = mpcParams.accountAddress;
1664
- // If another init for this same account is in flight, return its promise
1665
- // instead of kicking off a second, redundant WalletFacade.init.
1666
- inFlight = _this.pendingInits.get(accountAddress);
1792
+ initKey = "".concat(accountAddress, "::").concat(network);
1793
+ // If another init for this same (account, network) is in flight, return its
1794
+ // promise instead of kicking off a second, redundant WalletFacade.init. The
1795
+ // first caller's `mode` wins; that's fine — the wallet is created/cached once
1796
+ // and keeps syncing dust in the background regardless of who waited for what.
1797
+ inFlight = _this.pendingInits.get(initKey);
1667
1798
  if (inFlight) {
1668
- _this.logger.info("[Midnight] ".concat(label, ": joining in-flight init for ").concat(accountAddress));
1799
+ _this.logger.info("[Midnight] ".concat(label, ": joining in-flight init for ").concat(initKey));
1669
1800
  return [
1670
1801
  2,
1671
1802
  inFlight
1672
1803
  ];
1673
1804
  }
1674
- initPromise = _this.runMidnightWalletInit(label, mpcParams);
1675
- _this.pendingInits.set(accountAddress, initPromise);
1805
+ initPromise = _this.runMidnightWalletInit(label, mpcParams, mode, network);
1806
+ _this.pendingInits.set(initKey, initPromise);
1676
1807
  _state.label = 1;
1677
1808
  case 1:
1678
1809
  _state.trys.push([
@@ -1691,7 +1822,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1691
1822
  _state.sent()
1692
1823
  ];
1693
1824
  case 3:
1694
- _this.pendingInits.delete(accountAddress);
1825
+ _this.pendingInits.delete(initKey);
1695
1826
  return [
1696
1827
  7
1697
1828
  ];
@@ -1707,9 +1838,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1707
1838
  {
1708
1839
  key: "runMidnightWalletInit",
1709
1840
  value: function runMidnightWalletInit(label, mpcParams) {
1841
+ var mode = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 'full', network = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 'preview';
1710
1842
  var _this = this;
1711
1843
  return _async_to_generator(function() {
1712
- var _this_cachedWallet, roleKeys, accountAddress, state, _this_cachedWallet_diagnosticSub, shieldedSecretKeys, dustSecretKey, unshieldedKeystore, config, savedState, wallet, syncStart, lastLogTime, fmtSide, state1, err, lastPendingCount, lastPendingSig, diagnosticSub;
1844
+ var _this_cachedWallet, _this_cachedWallet1, roleKeys, accountAddress, state, _this_cachedWallet_diagnosticSub, shieldedSecretKeys, dustSecretKey, unshieldedKeystore, infra, config, savedState, _savedState_shielded, _savedState_dust, _savedState_shielded_length, _savedState_dust_length, wallet, syncStart, lastLogTime, SIDE_NAMES, lastApplied, sideDoneAtMs, readProgress, fmtSide, state1, err1, lastPendingCount, lastPendingSig, lastDustLogTime, dustDoneLogged, diagnosticSub;
1713
1845
  return _ts_generator(this, function(_state) {
1714
1846
  switch(_state.label){
1715
1847
  case 0:
@@ -1720,7 +1852,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1720
1852
  case 1:
1721
1853
  roleKeys = _state.sent();
1722
1854
  accountAddress = mpcParams.accountAddress;
1723
- if (!(((_this_cachedWallet = _this.cachedWallet) === null || _this_cachedWallet === void 0 ? void 0 : _this_cachedWallet.accountAddress) === accountAddress)) return [
1855
+ if (!(((_this_cachedWallet = _this.cachedWallet) === null || _this_cachedWallet === void 0 ? void 0 : _this_cachedWallet.accountAddress) === accountAddress && ((_this_cachedWallet1 = _this.cachedWallet) === null || _this_cachedWallet1 === void 0 ? void 0 : _this_cachedWallet1.network) === network)) return [
1724
1856
  3,
1725
1857
  3
1726
1858
  ];
@@ -1740,7 +1872,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1740
1872
  reject(new Error('Wallet re-sync timeout'));
1741
1873
  }, 30000);
1742
1874
  sub = _this.cachedWallet.wallet.state().subscribe(function(s) {
1743
- if (s.isSynced) {
1875
+ if (isSyncResolved(s, mode)) {
1744
1876
  clearTimeout(tid);
1745
1877
  // Defer to a microtask so `sub` is definitely assigned whether the
1746
1878
  // emission is synchronous or async.
@@ -1801,30 +1933,43 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1801
1933
  case 8:
1802
1934
  shieldedSecretKeys = ledger.ZswapSecretKeys.fromSeed(new Uint8Array(Buffer.from(roleKeys.shielded, 'hex')));
1803
1935
  dustSecretKey = ledger.DustSecretKey.fromSeed(new Uint8Array(Buffer.from(roleKeys.dust, 'hex')));
1804
- unshieldedKeystore = createKeystore(new Uint8Array(Buffer.from(roleKeys.unshielded, 'hex')), 'preview');
1936
+ unshieldedKeystore = createKeystore(new Uint8Array(Buffer.from(roleKeys.unshielded, 'hex')), network);
1937
+ infra = MIDNIGHT_INFRA[network];
1805
1938
  config = {
1806
- networkId: 'preview',
1939
+ networkId: network,
1807
1940
  costParameters: {
1808
1941
  feeBlocksMargin: 5
1809
1942
  },
1810
- relayURL: new URL('wss://rpc.preview.midnight.network'),
1811
- provingServerUrl: new URL('http://localhost:6300'),
1943
+ relayURL: new URL(infra.relayUrl),
1944
+ provingServerUrl: new URL(infra.provingServerUrl),
1812
1945
  indexerClientConnection: {
1813
- indexerHttpUrl: 'https://indexer.preview.midnight.network/api/v4/graphql',
1814
- indexerWsUrl: 'wss://indexer.preview.midnight.network/api/v4/graphql/ws'
1946
+ indexerHttpUrl: infra.indexerHttpUrl,
1947
+ indexerWsUrl: infra.indexerWsUrl
1948
+ },
1949
+ // v4 sync batching. `size` = updates fetched per indexer round-trip.
1950
+ // Measured: 2000 vs 10000 gave the same ~750 entries/sec (≈130s dust cold
1951
+ // sync), so dust is apply-bound (per-entry WASM compute), not fetch-bound
1952
+ // — batch size doesn't move the total. Kept at 2000.
1953
+ batchUpdates: {
1954
+ size: 2000
1815
1955
  },
1816
1956
  txHistoryStorage: new NoOpTransactionHistoryStorage()
1817
1957
  };
1818
1958
  return [
1819
1959
  4,
1820
- getWalletState(accountAddress)
1960
+ getWalletState(DynamicMidnightWalletClient.walletStateKey(accountAddress, network))
1821
1961
  ];
1822
1962
  case 9:
1823
1963
  savedState = _state.sent();
1824
1964
  if (savedState) {
1825
1965
  _this.logger.info("[Midnight] ".concat(label, ": found persisted state — resuming sync from checkpoint"));
1966
+ // console.* because this.logger is a NoopLogger in the iframe.
1967
+ // eslint-disable-next-line no-console
1968
+ console.info("[Midnight] ".concat(label, ": CACHE HIT — restoring from IndexedDB checkpoint ") + "(updatedAt=".concat(savedState.updatedAt ? new Date(savedState.updatedAt).toISOString() : 'n/a', " ") + "shielded=".concat((_savedState_shielded_length = (_savedState_shielded = savedState.shielded) === null || _savedState_shielded === void 0 ? void 0 : _savedState_shielded.length) !== null && _savedState_shielded_length !== void 0 ? _savedState_shielded_length : 0, "B dust=").concat((_savedState_dust_length = (_savedState_dust = savedState.dust) === null || _savedState_dust === void 0 ? void 0 : _savedState_dust.length) !== null && _savedState_dust_length !== void 0 ? _savedState_dust_length : 0, "B)"));
1826
1969
  } else {
1827
1970
  _this.logger.info("[Midnight] ".concat(label, ": no persisted state — cold sync from genesis"));
1971
+ // eslint-disable-next-line no-console
1972
+ console.info("[Midnight] ".concat(label, ": CACHE MISS — no IndexedDB checkpoint for this account, cold sync from genesis"));
1828
1973
  }
1829
1974
  _this.logger.info("[Midnight] ".concat(label, ": initializing wallet..."));
1830
1975
  return [
@@ -1853,31 +1998,56 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1853
1998
  _this.logger.debug("[Midnight] ".concat(label, ": syncing..."));
1854
1999
  syncStart = Date.now();
1855
2000
  lastLogTime = 0;
1856
- // Per-side sync-progress summary. Fields are bigints; `gap` is how many
1857
- // updates still need to be applied to reach the latest relevant index
1858
- // (not the chain tip — `highestRelevantIndex` is what matters for balance).
1859
- // Read the progress object the SDK itself uses for isSynced. For shielded
1860
- // and dust it lives at `side.state.progress`; for unshielded it's
1861
- // `side.progress`. Fall back across both to be safe.
1862
- fmtSide = function(side) {
2001
+ SIDE_NAMES = [
2002
+ 'shielded',
2003
+ 'unshielded',
2004
+ 'dust'
2005
+ ];
2006
+ // Per-tick throughput tracking: appliedIndex per side at the previous log,
2007
+ // so each periodic line shows how many chunks were applied in the interval
2008
+ // (a non-zero delta = still actively polling/applying index chunks). And
2009
+ // the wall-clock at which each side individually completed, so we can see
2010
+ // which dimension is the slow one.
2011
+ lastApplied = {};
2012
+ sideDoneAtMs = {};
2013
+ // In v4 every WalletState (shielded/unshielded/dust) exposes the full
2014
+ // SyncProgress via the `progress` getter (appliedIndex, highestRelevantIndex,
2015
+ // highestIndex). Read that FIRST — `side.state.progress` is the inner
2016
+ // CoreWallet's partial progress (has appliedIndex but leaves the highest*
2017
+ // fields at 0, which is why `gap`/`tip` showed 0 before).
2018
+ readProgress = function(side) {
1863
2019
  var _side_state;
1864
- var _side_state_progress;
1865
- var p = (_side_state_progress = side === null || side === void 0 ? void 0 : (_side_state = side.state) === null || _side_state === void 0 ? void 0 : _side_state.progress) !== null && _side_state_progress !== void 0 ? _side_state_progress : side === null || side === void 0 ? void 0 : side.progress;
1866
- if (!p) return 'n/a';
2020
+ var _side_progress;
2021
+ var p = (_side_progress = side === null || side === void 0 ? void 0 : side.progress) !== null && _side_progress !== void 0 ? _side_progress : side === null || side === void 0 ? void 0 : (_side_state = side.state) === null || _side_state === void 0 ? void 0 : _side_state.progress;
2022
+ if (!p) return undefined;
1867
2023
  var _p_appliedIndex;
1868
- var applied = (_p_appliedIndex = p.appliedIndex) !== null && _p_appliedIndex !== void 0 ? _p_appliedIndex : 0n;
2024
+ var applied = BigInt((_p_appliedIndex = p.appliedIndex) !== null && _p_appliedIndex !== void 0 ? _p_appliedIndex : 0n);
1869
2025
  var _p_highestRelevantIndex;
1870
- var highestRelevant = (_p_highestRelevantIndex = p.highestRelevantIndex) !== null && _p_highestRelevantIndex !== void 0 ? _p_highestRelevantIndex : 0n;
1871
- var _p_highestRelevantWalletIndex;
1872
- var highestRelevantWallet = (_p_highestRelevantWalletIndex = p.highestRelevantWalletIndex) !== null && _p_highestRelevantWalletIndex !== void 0 ? _p_highestRelevantWalletIndex : 0n;
2026
+ var highestRelevant = BigInt((_p_highestRelevantIndex = p.highestRelevantIndex) !== null && _p_highestRelevantIndex !== void 0 ? _p_highestRelevantIndex : 0n);
1873
2027
  var _p_highestIndex;
1874
- var highest = (_p_highestIndex = p.highestIndex) !== null && _p_highestIndex !== void 0 ? _p_highestIndex : 0n;
1875
- var connected = p.isConnected ? '✓' : '✗';
1876
- var done = '?';
1877
- if (typeof p.isStrictlyComplete === 'function') {
1878
- done = p.isStrictlyComplete() ? '✓' : '✗';
1879
- }
1880
- return "done=".concat(done, " \xb7 applied=").concat(applied, " \xb7 hrw=").concat(highestRelevantWallet, " \xb7 hr=").concat(highestRelevant, " \xb7 tip=").concat(highest, " \xb7 ws=").concat(connected);
2028
+ var highest = BigInt((_p_highestIndex = p.highestIndex) !== null && _p_highestIndex !== void 0 ? _p_highestIndex : 0n);
2029
+ var done = typeof p.isStrictlyComplete === 'function' ? p.isStrictlyComplete() : highestRelevant > 0n && applied >= highestRelevant;
2030
+ return {
2031
+ applied: applied,
2032
+ connected: Boolean(p.isConnected),
2033
+ done: done,
2034
+ highest: highest,
2035
+ highestRelevant: highestRelevant
2036
+ };
2037
+ };
2038
+ // `remaining` = updates still to apply to reach the latest relevant index
2039
+ // (the target for isSynced — not the chain tip). `+N` = entries applied
2040
+ // since the previous periodic log. `pct` = applied / highestRelevant.
2041
+ fmtSide = function(name, side) {
2042
+ var p = readProgress(side);
2043
+ if (!p) return "".concat(name, "=n/a");
2044
+ var _lastApplied_name;
2045
+ var prev = (_lastApplied_name = lastApplied[name]) !== null && _lastApplied_name !== void 0 ? _lastApplied_name : p.applied;
2046
+ var delta = p.applied - prev;
2047
+ lastApplied[name] = p.applied;
2048
+ var remaining = p.highestRelevant > p.applied ? p.highestRelevant - p.applied : 0n;
2049
+ var pct = p.highestRelevant > 0n ? "".concat((Number(p.applied) / Number(p.highestRelevant) * 100).toFixed(1), "%") : 'n/a';
2050
+ return "".concat(name, "[done=").concat(p.done ? '✓' : '✗', " ").concat(p.applied, "/").concat(p.highestRelevant, " (").concat(pct, ", +").concat(delta, ") remaining=").concat(remaining, " tip=").concat(p.highest, " ws=").concat(p.connected ? '✓' : '✗', "]");
1881
2051
  };
1882
2052
  _state.label = 12;
1883
2053
  case 12:
@@ -1902,16 +2072,54 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1902
2072
  }, 300000);
1903
2073
  sub = wallet.state().subscribe(function(s) {
1904
2074
  var now = Date.now();
2075
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2076
+ try {
2077
+ // Record the moment each side individually completes (checked every
2078
+ // tick so the timestamp is precise, not rounded to the 5s log).
2079
+ for(var _iterator = SIDE_NAMES[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2080
+ var name = _step.value;
2081
+ var _readProgress;
2082
+ if (sideDoneAtMs[name] === undefined && ((_readProgress = readProgress(s[name])) === null || _readProgress === void 0 ? void 0 : _readProgress.done)) {
2083
+ sideDoneAtMs[name] = now;
2084
+ // console.* (not this.logger, which is a NoopLogger / remote
2085
+ // shipper here) so these sync-timing diagnostics are visible in
2086
+ // the browser console.
2087
+ // eslint-disable-next-line no-console
2088
+ console.info("[Midnight] ".concat(label, ": ").concat(name, " side synced in ").concat(((now - syncStart) / 1000).toFixed(1), "s"));
2089
+ }
2090
+ }
2091
+ } catch (err) {
2092
+ _didIteratorError = true;
2093
+ _iteratorError = err;
2094
+ } finally{
2095
+ try {
2096
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
2097
+ _iterator.return();
2098
+ }
2099
+ } finally{
2100
+ if (_didIteratorError) {
2101
+ throw _iteratorError;
2102
+ }
2103
+ }
2104
+ }
1905
2105
  if (now - lastLogTime > 5000) {
1906
2106
  lastLogTime = now;
1907
- _this.logger.debug("[Midnight] ".concat(label, ": sync @ ").concat(((now - syncStart) / 1000).toFixed(1), "s \xb7 ") + "isSynced=".concat(s.isSynced, " \xb7 ") + "shielded=".concat(fmtSide(s.shielded), " \xb7 ") + "unshielded=".concat(fmtSide(s.unshielded), " \xb7 ") + "dust=".concat(fmtSide(s.dust)));
2107
+ // eslint-disable-next-line no-console
2108
+ console.info("[Midnight] ".concat(label, ": sync @ ").concat(((now - syncStart) / 1000).toFixed(1), "s \xb7 ") + "isSynced=".concat(s.isSynced, " \xb7 ") + "".concat(fmtSide('shielded', s.shielded), " \xb7 ") + "".concat(fmtSide('unshielded', s.unshielded), " \xb7 ") + "".concat(fmtSide('dust', s.dust)));
1908
2109
  }
1909
- if (s.isSynced) {
2110
+ if (isSyncResolved(s, mode)) {
1910
2111
  clearTimeout(timeoutId);
1911
2112
  queueMicrotask(function() {
1912
2113
  return sub === null || sub === void 0 ? void 0 : sub.unsubscribe();
1913
2114
  });
1914
- _this.logger.debug("[Midnight] ".concat(label, ": synced in ").concat(((Date.now() - syncStart) / 1000).toFixed(1), "s \xb7 ") + "shielded=".concat(fmtSide(s.shielded), " \xb7 ") + "unshielded=".concat(fmtSide(s.unshielded), " \xb7 ") + "dust=".concat(fmtSide(s.dust)));
2115
+ var elapsed = (Date.now() - syncStart) / 1000;
2116
+ var perSide = SIDE_NAMES.map(function(name) {
2117
+ var at = sideDoneAtMs[name];
2118
+ var when = at === undefined ? 'n/a' : "".concat(((at - syncStart) / 1000).toFixed(1), "s");
2119
+ return "".concat(name, "=").concat(when);
2120
+ }).join(' · ');
2121
+ // eslint-disable-next-line no-console
2122
+ console.info("[Midnight] ".concat(label, ": fully synced in ").concat(elapsed.toFixed(1), "s \xb7 per-side: ").concat(perSide));
1915
2123
  resolve(s);
1916
2124
  }
1917
2125
  });
@@ -1924,7 +2132,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1924
2132
  19
1925
2133
  ];
1926
2134
  case 14:
1927
- err = _state.sent();
2135
+ err1 = _state.sent();
1928
2136
  _state.label = 15;
1929
2137
  case 15:
1930
2138
  _state.trys.push([
@@ -1950,7 +2158,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1950
2158
  18
1951
2159
  ];
1952
2160
  case 18:
1953
- throw err;
2161
+ throw err1;
1954
2162
  case 19:
1955
2163
  // Diagnostic: track pending-tx transitions so we can observe TTL
1956
2164
  // auto-revert (entry flips from result=undefined → result.status='FAILURE'
@@ -1960,8 +2168,28 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1960
2168
  // full log-format state for the lifetime of the client.
1961
2169
  lastPendingCount = -1;
1962
2170
  lastPendingSig = '';
2171
+ // Dust telemetry. The foreground sync logger (above) unsubscribes the
2172
+ // instant shielded + unshielded resolve, so this long-lived subscription is
2173
+ // the ONLY window into the background dust fold. Log dust progress every
2174
+ // ~5s while it's still folding (so we can see `applied` climbing vs frozen),
2175
+ // and once when it finally reports strictly-complete (or never, which is
2176
+ // itself the answer). Reuses fmtSide for a format consistent with the
2177
+ // foreground log.
2178
+ lastDustLogTime = 0;
2179
+ dustDoneLogged = false;
1963
2180
  diagnosticSub = wallet.state().subscribe(function(s) {
1964
2181
  var _s_pending;
2182
+ var dustNow = Date.now();
2183
+ var dustDone = isSideSynced(s.dust);
2184
+ if (dustDone && !dustDoneLogged) {
2185
+ dustDoneLogged = true;
2186
+ // eslint-disable-next-line no-console
2187
+ console.info("[Midnight] ".concat(label, ": dust fully synced in ").concat(((dustNow - syncStart) / 1000).toFixed(1), "s \xb7 ").concat(fmtSide('dust', s.dust)));
2188
+ } else if (!dustDone && dustNow - lastDustLogTime > 5000) {
2189
+ lastDustLogTime = dustNow;
2190
+ // eslint-disable-next-line no-console
2191
+ console.info("[Midnight] ".concat(label, ": dust @ ").concat(((dustNow - syncStart) / 1000).toFixed(1), "s \xb7 ").concat(fmtSide('dust', s.dust)));
2192
+ }
1965
2193
  var _s_pending_all;
1966
2194
  var pending = (_s_pending_all = s === null || s === void 0 ? void 0 : (_s_pending = s.pending) === null || _s_pending === void 0 ? void 0 : _s_pending.all) !== null && _s_pending_all !== void 0 ? _s_pending_all : [];
1967
2195
  var sig = JSON.stringify(pending.map(function(p) {
@@ -2035,6 +2263,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2035
2263
  ledger: ledger,
2036
2264
  roleKeys: roleKeys,
2037
2265
  accountAddress: accountAddress,
2266
+ network: network,
2038
2267
  shieldedSecretKeys: shieldedSecretKeys,
2039
2268
  dustSecretKey: dustSecretKey,
2040
2269
  diagnosticSub: diagnosticSub
@@ -2100,10 +2329,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2100
2329
  {
2101
2330
  key: "getPrivateBalance",
2102
2331
  value: function getPrivateBalance(param) {
2103
- var accountAddress = param.accountAddress, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken;
2332
+ var accountAddress = param.accountAddress, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, networkId = param.networkId;
2104
2333
  var _this = this;
2105
2334
  return _async_to_generator(function() {
2106
- var _state_unshielded, _state_shielded, _state_dust_balance, _state_dust, _ref, state, addr, unshieldedByToken, _state_unshielded_balances, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, _step_value, tokenType, value, shieldedByToken, _state_shielded_balances, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, _step_value1, tokenType1, value1, _state_dust_balance1, result;
2335
+ var _state_unshielded, _state_shielded, _state_dust_balance, _state_dust, _state_dust1, _ref, state, addr, unshieldedByToken, _state_unshielded_balances, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, _step_value, tokenType, value, shieldedByToken, _state_shielded_balances, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, _step_value1, tokenType1, value1, now, _state_dust_balance1, dustBalance, _state_dust_totalCoins, dustCap, result;
2107
2336
  return _ts_generator(this, function(_state) {
2108
2337
  switch(_state.label){
2109
2338
  case 0:
@@ -2115,7 +2344,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2115
2344
  signedSessionId: signedSessionId,
2116
2345
  mfaToken: mfaToken,
2117
2346
  elevatedAccessToken: elevatedAccessToken
2118
- })
2347
+ }, // Resolve once shielded + unshielded are ready; let dust finish in the
2348
+ // background so the public/shielded balance shows without the ~130s
2349
+ // dust cold-sync.
2350
+ 'shielded-unshielded', resolveMidnightNetworkTag(networkId))
2119
2351
  ];
2120
2352
  case 1:
2121
2353
  _ref = _state.sent(), state = _ref.state, addr = _ref.accountAddress;
@@ -2161,10 +2393,22 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2161
2393
  }
2162
2394
  }
2163
2395
  }
2396
+ // v4 exposes the dust generation cap per coin (DustFullInfo.maxCap). The
2397
+ // wallet-level cap is the sum across the wallet's dust coins.
2398
+ now = new Date();
2399
+ dustBalance = (_state_dust_balance1 = (_state_dust = state.dust) === null || _state_dust === void 0 ? void 0 : (_state_dust_balance = _state_dust.balance) === null || _state_dust_balance === void 0 ? void 0 : _state_dust_balance.call(_state_dust, now)) !== null && _state_dust_balance1 !== void 0 ? _state_dust_balance1 : 0n;
2400
+ dustCap = ((_state_dust_totalCoins = (_state_dust1 = state.dust) === null || _state_dust1 === void 0 ? void 0 : _state_dust1.totalCoins) !== null && _state_dust_totalCoins !== void 0 ? _state_dust_totalCoins : []).reduce(function(sum, coin) {
2401
+ var _coin_maxCap;
2402
+ return sum + ((_coin_maxCap = coin.maxCap) !== null && _coin_maxCap !== void 0 ? _coin_maxCap : 0n);
2403
+ }, 0n);
2164
2404
  result = {
2165
2405
  unshielded: unshieldedByToken,
2166
2406
  shielded: shieldedByToken,
2167
- dust: ((_state_dust_balance1 = (_state_dust = state.dust) === null || _state_dust === void 0 ? void 0 : (_state_dust_balance = _state_dust.balance) === null || _state_dust_balance === void 0 ? void 0 : _state_dust_balance.call(_state_dust, new Date())) !== null && _state_dust_balance1 !== void 0 ? _state_dust_balance1 : 0n).toString(),
2407
+ dust: {
2408
+ balance: dustBalance.toString(),
2409
+ cap: dustCap.toString()
2410
+ },
2411
+ dustSynced: isSideSynced(state.dust),
2168
2412
  address: addr
2169
2413
  };
2170
2414
  // Fire-and-forget snapshot so the next init resumes from here instead
@@ -2182,7 +2426,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2182
2426
  {
2183
2427
  key: "registerDust",
2184
2428
  value: function registerDust(param) {
2185
- var accountAddress = param.accountAddress, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken;
2429
+ var accountAddress = param.accountAddress, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, networkId = param.networkId;
2186
2430
  var _this = this;
2187
2431
  return _async_to_generator(function() {
2188
2432
  var _state_dust_balance, _state_dust, _state_unshielded, _state_dust_balance1, _state_dust1, _ref, wallet, state, ledger, roleKeys, _state_dust_balance2, existingDust, _state_unshielded_availableCoins, allUtxos, nightUtxos, _state_dust_balance3, _state_dust2, _state_dust_balance4, dustBalance, verifyingKey, recipe, finalized, submitId, submitIdStr, _state_dust_balance5;
@@ -2197,7 +2441,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2197
2441
  signedSessionId: signedSessionId,
2198
2442
  mfaToken: mfaToken,
2199
2443
  elevatedAccessToken: elevatedAccessToken
2200
- })
2444
+ }, 'full', resolveMidnightNetworkTag(networkId))
2201
2445
  ];
2202
2446
  case 1:
2203
2447
  _ref = _state.sent(), wallet = _ref.wallet, state = _ref.state, ledger = _ref.ledger, roleKeys = _ref.roleKeys;
@@ -2297,13 +2541,14 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2297
2541
  * No MPC, no proof server, no broadcast — pair with signTransaction and
2298
2542
  * submitTransaction.
2299
2543
  */ function createTransferTransaction(param) {
2300
- var accountAddress = param.accountAddress, transfers = param.transfers, ttlMinutes = param.ttlMinutes, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken;
2544
+ var accountAddress = param.accountAddress, transfers = param.transfers, ttlMinutes = param.ttlMinutes, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, networkId = param.networkId;
2301
2545
  var _this = this;
2302
2546
  return _async_to_generator(function() {
2303
- var _state_dust_balance, _state_dust, _ref, wallet, state, shieldedSecretKeys, dustSecretKey, _state_dust_balance1, dustBalance, nativeToken, requiredByKey, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, t, _t_tokenType, token, key, existing, _existing_required, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, _step_value, side, token1, required, _state_unshielded, _state_shielded, balances, _balances_token, have, sdkTransfers, ttlMs, recipe;
2547
+ var _state_dust_balance, _state_dust, network, _ref, wallet, state, shieldedSecretKeys, dustSecretKey, _state_dust_balance1, dustBalance, nativeToken, requiredByKey, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, t, _t_tokenType, token, key, existing, _existing_required, _iteratorNormalCompletion1, _didIteratorError1, _iteratorError1, _iterator1, _step1, _step_value, side, token1, required, _state_unshielded, _state_shielded, balances, _balances_token, have, sdkTransfers, ttlMs, recipe;
2304
2548
  return _ts_generator(this, function(_state) {
2305
2549
  switch(_state.label){
2306
2550
  case 0:
2551
+ network = resolveMidnightNetworkTag(networkId);
2307
2552
  if (!transfers || transfers.length === 0) {
2308
2553
  throw new Error('At least one transfer is required');
2309
2554
  }
@@ -2315,7 +2560,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2315
2560
  signedSessionId: signedSessionId,
2316
2561
  mfaToken: mfaToken,
2317
2562
  elevatedAccessToken: elevatedAccessToken
2318
- })
2563
+ }, 'full', network)
2319
2564
  ];
2320
2565
  case 1:
2321
2566
  _ref = _state.sent(), wallet = _ref.wallet, state = _ref.state, shieldedSecretKeys = _ref.shieldedSecretKeys, dustSecretKey = _ref.dustSecretKey;
@@ -2395,7 +2640,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2395
2640
  var receiverAddress;
2396
2641
  try {
2397
2642
  var parsed = MidnightBech32m.parse(t.recipientAddress);
2398
- receiverAddress = t.type === 'unshielded' ? parsed.decode(UnshieldedAddress, 'preview') : parsed.decode(ShieldedAddress, 'preview');
2643
+ receiverAddress = t.type === 'unshielded' ? parsed.decode(UnshieldedAddress, network) : parsed.decode(ShieldedAddress, network);
2399
2644
  } catch (err) {
2400
2645
  throw new Error("Invalid ".concat(t.type, " recipient address ").concat(t.recipientAddress, ": ").concat(err.message));
2401
2646
  }
@@ -2450,10 +2695,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2450
2695
  * server; reuses the cached wallet's node connection. Optionally blocks
2451
2696
  * until the unshielded balance for tokenType stabilizes.
2452
2697
  */ function submitTransaction(param) {
2453
- var accountAddress = param.accountAddress, transaction = param.transaction, _param_waitForBalance = param.waitForBalance, waitForBalance = _param_waitForBalance === void 0 ? false : _param_waitForBalance, tokenType = param.tokenType, balanceBefore = param.balanceBefore, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken;
2698
+ var accountAddress = param.accountAddress, transaction = param.transaction, _param_waitForBalance = param.waitForBalance, waitForBalance = _param_waitForBalance === void 0 ? false : _param_waitForBalance, tokenType = param.tokenType, balanceBefore = param.balanceBefore, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, networkId = param.networkId;
2454
2699
  var _this = this;
2455
2700
  return _async_to_generator(function() {
2456
- var _updatedState_unshielded_balances, _updatedState_unshielded, wallet, txBytes, finalized, txIdentifier, txHash, balanceBeforeBig, updatedState, _updatedState_unshielded_balances_tokenType, balanceAfter;
2701
+ var _updatedState_unshielded_balances, _updatedState_unshielded, wallet, txBytes, finalized, txIdentifier, submissionIdentifier, txHash, canonicalHash, balanceBeforeBig, updatedState, _updatedState_unshielded_balances_tokenType, balanceAfter;
2457
2702
  return _ts_generator(this, function(_state) {
2458
2703
  switch(_state.label){
2459
2704
  case 0:
@@ -2465,7 +2710,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2465
2710
  signedSessionId: signedSessionId,
2466
2711
  mfaToken: mfaToken,
2467
2712
  elevatedAccessToken: elevatedAccessToken
2468
- })
2713
+ }, 'full', resolveMidnightNetworkTag(networkId))
2469
2714
  ];
2470
2715
  case 1:
2471
2716
  wallet = _state.sent().wallet;
@@ -2478,14 +2723,30 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2478
2723
  ];
2479
2724
  case 2:
2480
2725
  txIdentifier = _state.sent();
2481
- txHash = DynamicMidnightWalletClient.toTxHashString(txIdentifier);
2726
+ // The facade returns the submission *identifier* (used to watch for the tx),
2727
+ // but the block explorer indexes by the canonical transaction hash. Derive
2728
+ // that hash from the finalized ledger transaction so explorer links resolve;
2729
+ // fall back to the identifier if the hash can't be computed.
2730
+ // Returned alongside txHash: midnight-js polls
2731
+ // `transactions(offset: { identifier })` to observe inclusion, so a caller
2732
+ // handed only the canonical hash waits forever on a transaction that
2733
+ // actually succeeded.
2734
+ submissionIdentifier = DynamicMidnightWalletClient.toTxHashString(txIdentifier);
2735
+ txHash = submissionIdentifier;
2736
+ try {
2737
+ canonicalHash = DynamicMidnightWalletClient.toTxHashString(finalized.transactionHash());
2738
+ if (canonicalHash) txHash = canonicalHash;
2739
+ } catch (err) {
2740
+ _this.logger.warn('[Midnight] submitTransaction: could not derive canonical tx hash, using submission identifier', err);
2741
+ }
2482
2742
  _this.logger.info('[Midnight] submitTransaction: broadcast, txHash=', txHash);
2483
2743
  if (!waitForBalance) {
2484
2744
  void _this.persistCachedWalletState();
2485
2745
  return [
2486
2746
  2,
2487
2747
  {
2488
- txHash: txHash
2748
+ txHash: txHash,
2749
+ txIdentifier: submissionIdentifier
2489
2750
  }
2490
2751
  ];
2491
2752
  }
@@ -2536,6 +2797,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2536
2797
  2,
2537
2798
  {
2538
2799
  txHash: txHash,
2800
+ txIdentifier: submissionIdentifier,
2539
2801
  balanceAfter: balanceAfter.toString()
2540
2802
  }
2541
2803
  ];
@@ -2607,9 +2869,9 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2607
2869
  case 1:
2608
2870
  _state.trys.push([
2609
2871
  1,
2610
- 8,
2872
+ 9,
2611
2873
  ,
2612
- 9
2874
+ 10
2613
2875
  ]);
2614
2876
  if (!(((_this_cachedWallet = _this.cachedWallet) === null || _this_cachedWallet === void 0 ? void 0 : _this_cachedWallet.accountAddress) === accountAddress)) return [
2615
2877
  3,
@@ -2648,20 +2910,28 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2648
2910
  _this.cachedWallet = null;
2649
2911
  _state.label = 6;
2650
2912
  case 6:
2913
+ // Nuclear reset is network-agnostic: clear both networks' checkpoints so
2914
+ // no stale snapshot survives on either facade.
2651
2915
  return [
2652
2916
  4,
2653
- deleteWalletState(accountAddress)
2917
+ deleteWalletState(DynamicMidnightWalletClient.walletStateKey(accountAddress, 'preview'))
2654
2918
  ];
2655
2919
  case 7:
2656
2920
  _state.sent();
2657
2921
  return [
2658
- 3,
2659
- 9
2922
+ 4,
2923
+ deleteWalletState(DynamicMidnightWalletClient.walletStateKey(accountAddress, 'mainnet'))
2660
2924
  ];
2661
2925
  case 8:
2926
+ _state.sent();
2927
+ return [
2928
+ 3,
2929
+ 10
2930
+ ];
2931
+ case 9:
2662
2932
  err = _state.sent();
2663
2933
  throw new Error("resetCache failed: ".concat(err.message));
2664
- case 9:
2934
+ case 10:
2665
2935
  _this.logger.info('[Midnight] revertTransaction[resetCache]: cache cleared');
2666
2936
  return [
2667
2937
  2,
@@ -2694,7 +2964,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2694
2964
  signedSessionId: params.signedSessionId,
2695
2965
  mfaToken: params.mfaToken,
2696
2966
  elevatedAccessToken: params.elevatedAccessToken
2697
- })
2967
+ }, 'full', resolveMidnightNetworkTag(params.networkId))
2698
2968
  ];
2699
2969
  case 1:
2700
2970
  wallet = _state.sent().wallet;
@@ -2739,7 +3009,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2739
3009
  signedSessionId: params.signedSessionId,
2740
3010
  mfaToken: params.mfaToken,
2741
3011
  elevatedAccessToken: params.elevatedAccessToken
2742
- })
3012
+ }, 'full', resolveMidnightNetworkTag(params.networkId))
2743
3013
  ];
2744
3014
  case 1:
2745
3015
  wallet = _state.sent().wallet;
@@ -2901,11 +3171,11 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2901
3171
  */ function mpcSignIntents(tx, options) {
2902
3172
  var _this = this;
2903
3173
  return _async_to_generator(function() {
2904
- var _tx_intents, accountAddress, password, signedSessionId, mfaToken, elevatedAccessToken, fullTxBase64, networkId, baseContext, _options_proofMarker, proofMarker, _tx_intents_keys_toArray, segments, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _loop, _iterator, _step, err;
3174
+ var _tx_intents, accountAddress, password, signedSessionId, mfaToken, elevatedAccessToken, fullTxBase64, networkId, baseContext, approvalQuorum, _options_proofMarker, proofMarker, _tx_intents_keys_toArray, segments, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _loop, _iterator, _step, err;
2905
3175
  return _ts_generator(this, function(_state) {
2906
3176
  switch(_state.label){
2907
3177
  case 0:
2908
- accountAddress = options.accountAddress, password = options.password, signedSessionId = options.signedSessionId, mfaToken = options.mfaToken, elevatedAccessToken = options.elevatedAccessToken, fullTxBase64 = options.fullTxBase64, networkId = options.networkId, baseContext = options.baseContext, _options_proofMarker = options.proofMarker, proofMarker = _options_proofMarker === void 0 ? 'pre-proof' : _options_proofMarker;
3178
+ accountAddress = options.accountAddress, password = options.password, signedSessionId = options.signedSessionId, mfaToken = options.mfaToken, elevatedAccessToken = options.elevatedAccessToken, fullTxBase64 = options.fullTxBase64, networkId = options.networkId, baseContext = options.baseContext, approvalQuorum = options.approvalQuorum, _options_proofMarker = options.proofMarker, proofMarker = _options_proofMarker === void 0 ? 'pre-proof' : _options_proofMarker;
2909
3179
  segments = (_tx_intents_keys_toArray = (_tx_intents = tx.intents) === null || _tx_intents === void 0 ? void 0 : _tx_intents.keys().toArray()) !== null && _tx_intents_keys_toArray !== void 0 ? _tx_intents_keys_toArray : [];
2910
3180
  if (segments.length === 0) return [
2911
3181
  2
@@ -2957,7 +3227,8 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2957
3227
  serializedTransaction: fullTxBase64,
2958
3228
  networkId: networkId
2959
3229
  }
2960
- })
3230
+ }),
3231
+ approvalQuorum: approvalQuorum
2961
3232
  })
2962
3233
  ];
2963
3234
  case 2:
@@ -3040,19 +3311,110 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3040
3311
  })();
3041
3312
  }
3042
3313
  },
3314
+ {
3315
+ key: "getWalletProviderPublicKeys",
3316
+ value: /**
3317
+ * Initializes the iframe-resident wallet provider and returns only its public
3318
+ * keys. Secret wallet state never crosses the iframe transport boundary.
3319
+ */ function getWalletProviderPublicKeys(params) {
3320
+ var _this = this;
3321
+ return _async_to_generator(function() {
3322
+ var walletProvider;
3323
+ return _ts_generator(this, function(_state) {
3324
+ switch(_state.label){
3325
+ case 0:
3326
+ return [
3327
+ 4,
3328
+ _this.getWalletProvider(params)
3329
+ ];
3330
+ case 1:
3331
+ walletProvider = _state.sent().walletProvider;
3332
+ return [
3333
+ 2,
3334
+ {
3335
+ coinPublicKey: walletProvider.getCoinPublicKey(),
3336
+ encryptionPublicKey: walletProvider.getEncryptionPublicKey(),
3337
+ status: 'ready'
3338
+ }
3339
+ ];
3340
+ }
3341
+ });
3342
+ })();
3343
+ }
3344
+ },
3345
+ {
3346
+ key: "balanceWalletProviderTransaction",
3347
+ value: /**
3348
+ * Balances a midnight-js UnboundTransaction inside the iframe. The host sends
3349
+ * only serialized transaction data; MPC, shielded, and DUST keys remain here.
3350
+ */ function balanceWalletProviderTransaction(_param) {
3351
+ var _this = this;
3352
+ return _async_to_generator(function() {
3353
+ var transaction, ttl, providerParams, ttlDate, txBytes, unboundTransaction, walletProvider, finalizedTransaction;
3354
+ return _ts_generator(this, function(_state) {
3355
+ switch(_state.label){
3356
+ case 0:
3357
+ transaction = _param.transaction, ttl = _param.ttl, providerParams = _object_without_properties(_param, [
3358
+ "transaction",
3359
+ "ttl"
3360
+ ]);
3361
+ if (!transaction) {
3362
+ throw new Error('balanceWalletProviderTransaction: transaction is required');
3363
+ }
3364
+ ttlDate = ttl ? new Date(ttl) : undefined;
3365
+ if (ttlDate && Number.isNaN(ttlDate.getTime())) {
3366
+ throw new Error('balanceWalletProviderTransaction: ttl must be a valid ISO-8601 date');
3367
+ }
3368
+ // Host-controlled string, so validate shape before the WASM deserializer.
3369
+ // `Buffer.from(..., 'base64')` silently drops invalid characters rather than
3370
+ // throwing, so a malformed payload would otherwise reach `deserialize` as
3371
+ // truncated-but-plausible bytes and fail with an opaque WASM error. The
3372
+ // upper bound also stops a huge body from being decoded at all.
3373
+ if (!BASE64_PATTERN.test(transaction)) {
3374
+ throw new Error('balanceWalletProviderTransaction: transaction must be base64');
3375
+ }
3376
+ txBytes = Buffer.from(transaction, 'base64');
3377
+ if (txBytes.length === 0 || txBytes.length > MAX_SERIALIZED_TRANSACTION_BYTES) {
3378
+ throw new Error("balanceWalletProviderTransaction: transaction must decode to 1..".concat(MAX_SERIALIZED_TRANSACTION_BYTES, " bytes, got ").concat(txBytes.length));
3379
+ }
3380
+ unboundTransaction = ledger.Transaction.deserialize('signature', 'proof', 'pre-binding', new Uint8Array(txBytes));
3381
+ return [
3382
+ 4,
3383
+ _this.getWalletProvider(providerParams)
3384
+ ];
3385
+ case 1:
3386
+ walletProvider = _state.sent().walletProvider;
3387
+ return [
3388
+ 4,
3389
+ walletProvider.balanceTx(unboundTransaction, ttlDate)
3390
+ ];
3391
+ case 2:
3392
+ finalizedTransaction = _state.sent();
3393
+ return [
3394
+ 2,
3395
+ {
3396
+ transaction: Buffer.from(finalizedTransaction.serialize()).toString('base64')
3397
+ }
3398
+ ];
3399
+ }
3400
+ });
3401
+ })();
3402
+ }
3403
+ },
3043
3404
  {
3044
3405
  key: "getWalletProvider",
3045
3406
  value: /**
3046
3407
  * Returns a Midnight.js-compatible WalletProvider for use with
3047
3408
  * midnight-js-contracts. Signing goes through MPC — no private key exposed.
3048
3409
  */ function getWalletProvider(param) {
3049
- var accountAddress = param.accountAddress, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken;
3410
+ var accountAddress = param.accountAddress, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, networkId = param.networkId;
3050
3411
  var _this = this;
3051
3412
  return _async_to_generator(function() {
3052
- var _ref, wallet, state, shieldedSecretKeys, dustSecretKey, walletProvider;
3413
+ var network, _ref, wallet, state, shieldedSecretKeys, dustSecretKey, walletProvider;
3053
3414
  return _ts_generator(this, function(_state) {
3054
3415
  switch(_state.label){
3055
3416
  case 0:
3417
+ network = resolveMidnightNetworkTag(networkId);
3056
3418
  return [
3057
3419
  4,
3058
3420
  _this.initMidnightWallet('walletProvider', {
@@ -3061,7 +3423,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3061
3423
  signedSessionId: signedSessionId,
3062
3424
  mfaToken: mfaToken,
3063
3425
  elevatedAccessToken: elevatedAccessToken
3064
- })
3426
+ }, 'full', network)
3065
3427
  ];
3066
3428
  case 1:
3067
3429
  _ref = _state.sent(), wallet = _ref.wallet, state = _ref.state, shieldedSecretKeys = _ref.shieldedSecretKeys, dustSecretKey = _ref.dustSecretKey;
@@ -3090,8 +3452,8 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3090
3452
  ];
3091
3453
  case 1:
3092
3454
  recipe = _state.sent();
3093
- // The proven base tx uses the 'proof' marker. networkId 0 matches
3094
- // the 'preview' facade network this provider is configured for.
3455
+ // The proven base tx uses the 'proof' marker. The numeric networkId
3456
+ // must match the facade network this provider was configured for.
3095
3457
  baseTxB64 = Buffer.from(recipe.baseTransaction.serialize()).toString('base64');
3096
3458
  return [
3097
3459
  4,
@@ -3102,7 +3464,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3102
3464
  mfaToken: mfaToken,
3103
3465
  elevatedAccessToken: elevatedAccessToken,
3104
3466
  fullTxBase64: baseTxB64,
3105
- networkId: 0,
3467
+ networkId: MIDNIGHT_NETWORK_IDS[network],
3106
3468
  proofMarker: 'proof'
3107
3469
  })
3108
3470
  ];
@@ -3122,7 +3484,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3122
3484
  mfaToken: mfaToken,
3123
3485
  elevatedAccessToken: elevatedAccessToken,
3124
3486
  fullTxBase64: balancingTxB64,
3125
- networkId: 0,
3487
+ networkId: MIDNIGHT_NETWORK_IDS[network],
3126
3488
  proofMarker: 'pre-proof'
3127
3489
  })
3128
3490
  ];
@@ -3164,13 +3526,23 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3164
3526
  }
3165
3527
  ], [
3166
3528
  {
3167
- key: "toTxHashString",
3529
+ key: "walletStateKey",
3168
3530
  value: /**
3169
3531
  * Coerce the value returned by `wallet.submitTransaction(...)` to a string.
3170
3532
  * Midnight's facade returns either a string txId, or a TransactionIdentifier
3171
3533
  * object with a `.toHex()` method. We normalize so callers always see a
3172
3534
  * string, and fall back to `String(...)` if neither shape matches.
3173
- */ function toTxHashString(txIdentifier) {
3535
+ */ /**
3536
+ * IndexedDB checkpoint key. Sync state is per (account, network) — restoring
3537
+ * a preview snapshot into a mainnet facade would corrupt sync. Preview keeps
3538
+ * the bare-address key so pre-existing checkpoints stay valid.
3539
+ */ function walletStateKey(accountAddress, network) {
3540
+ return network === 'mainnet' ? "".concat(accountAddress, "::mainnet") : accountAddress;
3541
+ }
3542
+ },
3543
+ {
3544
+ key: "toTxHashString",
3545
+ value: function toTxHashString(txIdentifier) {
3174
3546
  if (typeof txIdentifier === 'string') return txIdentifier;
3175
3547
  var maybeHex = txIdentifier === null || txIdentifier === void 0 ? void 0 : txIdentifier.toHex;
3176
3548
  if (typeof maybeHex === 'function') return txIdentifier.toHex();
@@ -3196,10 +3568,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3196
3568
  * If publicKeyHex is passed, it's assumed to already be the address hash.
3197
3569
  *
3198
3570
  * @param publicKeyHex - The 32-byte address hash (from addressFromKey) as hex string
3199
- * @param network - The network. Defaults to preview
3200
- * @returns Bech32m encoded address (e.g., mn_addr_preview1...)
3571
+ * @param network - The network. Defaults to mainnet
3572
+ * @returns Bech32m encoded address (e.g., mn_addr1...)
3201
3573
  */ var deriveMidnightAddress = function(param) {
3202
- var publicKeyHex = param.publicKeyHex, _param_network = param.network, network = _param_network === void 0 ? 'preview' : _param_network;
3574
+ var publicKeyHex = param.publicKeyHex, _param_network = param.network, network = _param_network === void 0 ? 'mainnet' : _param_network;
3203
3575
  var bytes = Buffer.from(publicKeyHex, 'hex');
3204
3576
  if (bytes.length !== 32) {
3205
3577
  throw new Error("Invalid key length: ".concat(bytes.length, ", expected 32"));