@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.cjs.js CHANGED
@@ -6,6 +6,7 @@ var walletSdkAddressFormat = require('@midnight-ntwrk/wallet-sdk-address-format'
6
6
  var walletSdkDustWallet = require('@midnight-ntwrk/wallet-sdk-dust-wallet');
7
7
  var walletSdkFacade = require('@midnight-ntwrk/wallet-sdk-facade');
8
8
  var walletSdkShielded = require('@midnight-ntwrk/wallet-sdk-shielded');
9
+ var walletSdkAbstractions = require('@midnight-ntwrk/wallet-sdk-abstractions');
9
10
  var walletSdkUnshieldedWallet = require('@midnight-ntwrk/wallet-sdk-unshielded-wallet');
10
11
  var bip32 = require('@scure/bip32');
11
12
  var bs58 = require('bs58');
@@ -42,6 +43,32 @@ var MIDNIGHT_NETWORK_IDS = {
42
43
  preprod: 0,
43
44
  undeployed: 0
44
45
  };
46
+ /**
47
+ * Resolves the caller-supplied network identifier (numeric 0/1, network name,
48
+ * or "midnight:<network>" chainId) to the facade network tag. Defaults to
49
+ * 'preview' when absent — the legacy single-network behavior, so requests from
50
+ * hosts that predate per-network support are unchanged.
51
+ */ var resolveMidnightNetworkTag = function(networkId) {
52
+ if (networkId === undefined || networkId === null) return 'preview';
53
+ if (typeof networkId === 'number') return networkId === 1 ? 'mainnet' : 'preview';
54
+ var name = networkId.includes(':') ? networkId.split(':')[1] : networkId;
55
+ return name === 'mainnet' ? 'mainnet' : 'preview';
56
+ };
57
+ var MIDNIGHT_PROOF_SERVER_URL = 'https://proof-server.us-east-1.dynamic-preprod.xyz';
58
+ var MIDNIGHT_INFRA = {
59
+ mainnet: {
60
+ relayUrl: 'wss://rpc.mainnet.midnight.network',
61
+ provingServerUrl: MIDNIGHT_PROOF_SERVER_URL,
62
+ indexerHttpUrl: 'https://indexer.mainnet.midnight.network/api/v4/graphql',
63
+ indexerWsUrl: 'wss://indexer.mainnet.midnight.network/api/v4/graphql/ws'
64
+ },
65
+ preview: {
66
+ relayUrl: 'wss://rpc.preview.midnight.network',
67
+ provingServerUrl: MIDNIGHT_PROOF_SERVER_URL,
68
+ indexerHttpUrl: 'https://indexer.preview.midnight.network/api/v4/graphql',
69
+ indexerWsUrl: 'wss://indexer.preview.midnight.network/api/v4/graphql/ws'
70
+ }
71
+ };
45
72
  // Error messages
46
73
  var ERROR_ACCOUNT_ADDRESS_REQUIRED = 'Account address is required';
47
74
  var ERROR_NETWORK_ID_REQUIRED = 'Network ID is required for Midnight transactions';
@@ -232,7 +259,12 @@ function _ts_generator$1(thisArg, body) {
232
259
  }
233
260
  }
234
261
  var DB_NAME = 'dynamic-midnight-wallet-state';
235
- var DB_VERSION = 1;
262
+ // Open WITHOUT a fixed version. Passing a version LOWER than the one already in
263
+ // the browser throws `VersionError` (IndexedDB forbids downgrades) — which is
264
+ // exactly what broke the cache after an earlier `DB_VERSION = 2` experiment was
265
+ // reverted to 1: dev browsers still had v2, every open failed, and the wallet
266
+ // cold-synced on every load. Opening with no version adopts whatever version
267
+ // exists (or creates the DB fresh), so a downgrade error is impossible.
236
268
  var STORE_NAME = 'state';
237
269
  // Normalizes a DOMException | unknown into an Error so promise rejections
238
270
  // always carry an Error instance. Object-shaped errors (DOMException, plain
@@ -262,8 +294,10 @@ function openDb() {
262
294
  // the session (private-browsing bootup, transient quota errors, etc).
263
295
  // Re-throw so the original caller still sees the rejection.
264
296
  dbPromise = new Promise(function(resolve, reject) {
265
- var req = indexedDB.open(DB_NAME, DB_VERSION);
297
+ var req = indexedDB.open(DB_NAME);
266
298
  req.onupgradeneeded = function() {
299
+ // Fires only when the DB is first created (or an existing DB lacks the
300
+ // store). Create the store if absent; never destructive.
267
301
  var db = req.result;
268
302
  if (!db.objectStoreNames.contains(STORE_NAME)) {
269
303
  db.createObjectStore(STORE_NAME, {
@@ -322,7 +356,7 @@ function getWalletState(accountAddress) {
322
356
  }
323
357
  function _getWalletState() {
324
358
  _getWalletState = _async_to_generator$1(function(accountAddress) {
325
- var result;
359
+ var result, err;
326
360
  return _ts_generator$1(this, function(_state) {
327
361
  switch(_state.label){
328
362
  case 0:
@@ -345,8 +379,13 @@ function _getWalletState() {
345
379
  result !== null && result !== void 0 ? result : null
346
380
  ];
347
381
  case 2:
348
- _state.sent();
349
- // IndexedDB unavailable (private mode, corrupt DB, etc.) — behave as if empty.
382
+ err = _state.sent();
383
+ // IndexedDB unavailable (private mode, third-party storage partitioning,
384
+ // corrupt DB, etc.) — behave as if empty. Surface to the console so a
385
+ // blocked/partitioned store (which would force a cold sync every load)
386
+ // is visible instead of silently swallowed.
387
+ // eslint-disable-next-line no-console
388
+ console.warn('[Midnight] CACHE read FAILED (IndexedDB unavailable) — treating as empty:', err);
350
389
  return [
351
390
  2,
352
391
  null
@@ -365,7 +404,7 @@ function putWalletState(accountAddress, state) {
365
404
  }
366
405
  function _putWalletState() {
367
406
  _putWalletState = _async_to_generator$1(function(accountAddress, state) {
368
- var record;
407
+ var record, err;
369
408
  return _ts_generator$1(this, function(_state) {
370
409
  switch(_state.label){
371
410
  case 0:
@@ -391,12 +430,19 @@ function _putWalletState() {
391
430
  ];
392
431
  case 2:
393
432
  _state.sent();
433
+ // eslint-disable-next-line no-console
434
+ console.info("[Midnight] CACHE write OK — checkpoint saved (shielded=".concat(record.shielded.length, "B dust=").concat(record.dust.length, "B)"));
394
435
  return [
395
436
  3,
396
437
  4
397
438
  ];
398
439
  case 3:
399
- _state.sent();
440
+ err = _state.sent();
441
+ // Persist is best-effort. A failure just means next init will cold-sync —
442
+ // but surface it so a blocked/partitioned IndexedDB (third-party iframe)
443
+ // is visible rather than silently swallowed.
444
+ // eslint-disable-next-line no-console
445
+ console.warn('[Midnight] CACHE write FAILED (IndexedDB unavailable):', err);
400
446
  return [
401
447
  3,
402
448
  4
@@ -618,6 +664,33 @@ function _object_spread_props(target, source) {
618
664
  }
619
665
  return target;
620
666
  }
667
+ function _object_without_properties(source, excluded) {
668
+ if (source == null) return {};
669
+ var target = _object_without_properties_loose(source, excluded);
670
+ var key, i;
671
+ if (Object.getOwnPropertySymbols) {
672
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
673
+ for(i = 0; i < sourceSymbolKeys.length; i++){
674
+ key = sourceSymbolKeys[i];
675
+ if (excluded.indexOf(key) >= 0) continue;
676
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
677
+ target[key] = source[key];
678
+ }
679
+ }
680
+ return target;
681
+ }
682
+ function _object_without_properties_loose(source, excluded) {
683
+ if (source == null) return {};
684
+ var target = {};
685
+ var sourceKeys = Object.keys(source);
686
+ var key, i;
687
+ for(i = 0; i < sourceKeys.length; i++){
688
+ key = sourceKeys[i];
689
+ if (excluded.indexOf(key) >= 0) continue;
690
+ target[key] = source[key];
691
+ }
692
+ return target;
693
+ }
621
694
  function _possible_constructor_return(self, call) {
622
695
  if (call && (_type_of(call) === "object" || typeof call === "function")) {
623
696
  return call;
@@ -763,28 +836,33 @@ function _ts_values(o) {
763
836
  };
764
837
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
765
838
  }
839
+ /** Whether a sub-wallet side has finished syncing. `highestRelevantIndex`
840
+ * is 0 during sync, so `isStrictlyComplete()` is the authoritative signal. */ /** Strict base64 (with optional padding) — used to validate host-supplied
841
+ * serialized transactions before they reach the ledger WASM deserializer. */ var BASE64_PATTERN = /^[A-Za-z0-9+/]+={0,2}$/;
842
+ /** Upper bound on a serialized Midnight transaction the iframe will decode.
843
+ * Generous next to real transactions, small enough that a bad or hostile
844
+ * payload is rejected before any WASM work happens. */ var MAX_SERIALIZED_TRANSACTION_BYTES = 4 * 1024 * 1024;
845
+ var isSideSynced = function(side) {
846
+ var _side_state;
847
+ var _side_progress;
848
+ 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;
849
+ if (!p) return false;
850
+ if (typeof p.isStrictlyComplete === 'function') return p.isStrictlyComplete();
851
+ var _p_appliedIndex;
852
+ var applied = BigInt((_p_appliedIndex = p.appliedIndex) !== null && _p_appliedIndex !== void 0 ? _p_appliedIndex : 0n);
853
+ var _p_highestRelevantIndex;
854
+ var highestRelevant = BigInt((_p_highestRelevantIndex = p.highestRelevantIndex) !== null && _p_highestRelevantIndex !== void 0 ? _p_highestRelevantIndex : 0n);
855
+ return highestRelevant > 0n && applied >= highestRelevant;
856
+ };
857
+ /** Resolve predicate for the sync wait, per mode. */ var isSyncResolved = function(s, mode) {
858
+ return mode === 'full' ? Boolean(s.isSynced) : isSideSynced(s.shielded) && isSideSynced(s.unshielded);
859
+ };
766
860
  var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
767
861
  _inherits(DynamicMidnightWalletClient, DynamicWalletClient);
768
- function DynamicMidnightWalletClient(param, internalOptions) {
769
- 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 ? browser.AuthMode.HEADER : _param_authMode, sdkVersion = param.sdkVersion, forwardMPCClient = param.forwardMPCClient, logger = param.logger;
862
+ function DynamicMidnightWalletClient() {
770
863
  _class_call_check(this, DynamicMidnightWalletClient);
771
864
  var _this;
772
- _this = _call_super(this, DynamicMidnightWalletClient, [
773
- {
774
- environmentId: environmentId,
775
- authToken: authToken,
776
- baseApiUrl: baseApiUrl,
777
- baseMPCRelayApiUrl: baseMPCRelayApiUrl,
778
- storageKey: storageKey,
779
- debug: debug,
780
- featureFlags: featureFlags,
781
- authMode: authMode,
782
- sdkVersion: sdkVersion,
783
- forwardMPCClient: forwardMPCClient,
784
- logger: logger
785
- },
786
- internalOptions
787
- ]), _define_property(_this, "chainName", 'MIDNIGHT'), // Keep wallet alive between calls — avoids 90s re-sync per operation.
865
+ _this = _call_super(this, DynamicMidnightWalletClient, arguments), _define_property(_this, "chainName", 'MIDNIGHT'), // Keep wallet alive between calls — avoids 90s re-sync per operation.
788
866
  // `diagnosticSub` is the long-lived pending-tx log subscription attached
789
867
  // at init time; we hold onto its handle so account-switch / resetCache
790
868
  // paths can unsubscribe it and release the closure.
@@ -868,6 +946,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
868
946
  isDirty = pendingTxCount > 0 || unshieldedPending > 0 || shieldedPending > 0 || dustPending > 0;
869
947
  if (isDirty) {
870
948
  _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.");
949
+ // console.* because this.logger is a NoopLogger in the iframe — cache
950
+ // diagnostics must be visible in the browser console.
951
+ // eslint-disable-next-line no-console
952
+ 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"));
871
953
  return [
872
954
  2
873
955
  ];
@@ -896,7 +978,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
896
978
  }
897
979
  return [
898
980
  4,
899
- putWalletState(cached.accountAddress, {
981
+ putWalletState(DynamicMidnightWalletClient.walletStateKey(cached.accountAddress, cached.network), {
900
982
  shielded: shielded,
901
983
  dust: dust
902
984
  })
@@ -911,6 +993,8 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
911
993
  case 5:
912
994
  err = _state.sent();
913
995
  _this.logger.warn('[Midnight] Failed to persist wallet state:', err);
996
+ // eslint-disable-next-line no-console
997
+ console.warn('[Midnight] CACHE persist FAILED (write/serialize threw):', err);
914
998
  return [
915
999
  3,
916
1000
  6
@@ -927,10 +1011,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
927
1011
  {
928
1012
  key: "createWalletAccount",
929
1013
  value: function createWalletAccount(param) {
930
- var thresholdSignatureScheme = param.thresholdSignatureScheme, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, onError = param.onError, signedSessionId = param.signedSessionId;
1014
+ 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;
931
1015
  var _this = this;
932
1016
  return _async_to_generator(function() {
933
- var ceremonyCeremonyCompleteResolver, serverAccountAddress, ceremonyCompletePromise, _ref, publicKeyHex, clientKeyShares, accountAddress, pubKeyBytes, roleKeys, shieldedSecretKeys, shieldedAddr, shieldedBech32m, dustBech32m, dustSecretKey, dustAddr, toHex, correctAddresses, wallet, addrError, error;
1017
+ 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;
934
1018
  return _ts_generator(this, function(_state) {
935
1019
  switch(_state.label){
936
1020
  case 0:
@@ -947,9 +1031,11 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
947
1031
  4,
948
1032
  _this.keyGen({
949
1033
  chainName: _this.chainName,
1034
+ businessAccountId: businessAccountId,
950
1035
  thresholdSignatureScheme: thresholdSignatureScheme,
951
1036
  onError: onError,
952
- onCeremonyComplete: function(accountAddress, walletId) {
1037
+ onCeremonyComplete: function(param) {
1038
+ var accountAddress = param.accountAddress, walletId = param.walletId, shareSetId = param.shareSetId;
953
1039
  var chainConfig = browser.getMPCChainConfig(_this.chainName);
954
1040
  serverAccountAddress = accountAddress;
955
1041
  _this.initializeWalletMapEntry({
@@ -962,7 +1048,8 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
962
1048
  index,
963
1049
  value
964
1050
  ];
965
- })))
1051
+ }))),
1052
+ shareSetId: shareSetId
966
1053
  });
967
1054
  ceremonyCeremonyCompleteResolver(undefined);
968
1055
  },
@@ -999,7 +1086,8 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
999
1086
  accountAddress: accountAddress,
1000
1087
  clientKeyShares: clientKeyShares,
1001
1088
  password: password,
1002
- signedSessionId: signedSessionId
1089
+ signedSessionId: signedSessionId,
1090
+ businessAccountId: businessAccountId
1003
1091
  })
1004
1092
  ];
1005
1093
  case 4:
@@ -1025,13 +1113,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1025
1113
  roleKeys = _state.sent();
1026
1114
  shieldedSecretKeys = ledger__namespace.ZswapSecretKeys.fromSeed(new Uint8Array(Buffer.from(roleKeys.shielded, 'hex')));
1027
1115
  shieldedAddr = new walletSdkAddressFormat.ShieldedAddress(new walletSdkAddressFormat.ShieldedCoinPublicKey(Buffer.from(shieldedSecretKeys.coinPublicKey, 'hex')), new walletSdkAddressFormat.ShieldedEncryptionPublicKey(Buffer.from(shieldedSecretKeys.encryptionPublicKey, 'hex')));
1028
- shieldedBech32m = walletSdkAddressFormat.MidnightBech32m.encode('preview', shieldedAddr).toString();
1029
1116
  try {
1030
1117
  dustSecretKey = ledger__namespace.DustSecretKey.fromSeed(new Uint8Array(Buffer.from(roleKeys.dust, 'hex')));
1031
- dustAddr = new walletSdkAddressFormat.DustAddress(dustSecretKey.publicKey);
1032
- dustBech32m = walletSdkAddressFormat.MidnightBech32m.encode('preview', dustAddr).toString();
1033
1118
  } catch (dustErr) {
1034
- _this.logger.warn('[Midnight] Dust address encoding failed (skipping):', dustErr);
1119
+ _this.logger.warn('[Midnight] Dust key derivation failed (skipping dust addresses):', dustErr);
1035
1120
  }
1036
1121
  toHex = function(val) {
1037
1122
  if (typeof val === 'string') return val;
@@ -1039,24 +1124,58 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1039
1124
  if ((typeof val === "undefined" ? "undefined" : _type_of(val)) === 'bigint') return val.toString(16);
1040
1125
  return String(val);
1041
1126
  };
1042
- correctAddresses = [
1127
+ // One key, one encoding per network — only the bech32m HRP differs.
1128
+ // Preview first: Midnight's legacy default, so legacy first-match
1129
+ // lookups keep resolving the preview encoding. The mainnet network id
1130
+ // is the library's `mainnet` symbol (bare HRP, no network segment).
1131
+ correctionNetworks = [
1043
1132
  {
1044
- address: accountAddress,
1045
- type: 'midnight_unshielded',
1046
- publicKey: toHex(publicKeyHex)
1133
+ tag: 'preview',
1134
+ encodeId: 'preview'
1047
1135
  },
1048
1136
  {
1049
- address: shieldedBech32m,
1050
- type: 'midnight_shielded',
1051
- publicKey: toHex(shieldedSecretKeys.coinPublicKey)
1137
+ tag: 'mainnet',
1138
+ encodeId: walletSdkAddressFormat.mainnet
1052
1139
  }
1053
1140
  ];
1054
- if (dustBech32m && dustSecretKey) {
1055
- correctAddresses.push({
1056
- address: dustBech32m,
1057
- type: 'midnight_dust',
1058
- publicKey: toHex(dustSecretKey.publicKey)
1059
- });
1141
+ correctAddresses = [];
1142
+ _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1143
+ try {
1144
+ for(_iterator = correctionNetworks[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1145
+ _step_value = _step.value, tag = _step_value.tag, encodeId = _step_value.encodeId;
1146
+ correctAddresses.push({
1147
+ address: walletSdkAddressFormat.MidnightBech32m.encode(encodeId, shieldedAddr).toString(),
1148
+ type: 'midnight_shielded',
1149
+ publicKey: toHex(shieldedSecretKeys.coinPublicKey),
1150
+ network: tag
1151
+ });
1152
+ if (dustSecretKey) {
1153
+ try {
1154
+ dustAddr = new walletSdkAddressFormat.DustAddress(dustSecretKey.publicKey);
1155
+ correctAddresses.push({
1156
+ address: walletSdkAddressFormat.MidnightBech32m.encode(encodeId, dustAddr).toString(),
1157
+ type: 'midnight_dust',
1158
+ publicKey: toHex(dustSecretKey.publicKey),
1159
+ network: tag
1160
+ });
1161
+ } catch (dustErr) {
1162
+ _this.logger.warn('[Midnight] Dust address encoding failed (skipping):', dustErr);
1163
+ }
1164
+ }
1165
+ }
1166
+ } catch (err) {
1167
+ _didIteratorError = true;
1168
+ _iteratorError = err;
1169
+ } finally{
1170
+ try {
1171
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1172
+ _iterator.return();
1173
+ }
1174
+ } finally{
1175
+ if (_didIteratorError) {
1176
+ throw _iteratorError;
1177
+ }
1178
+ }
1060
1179
  }
1061
1180
  _this.logger.info('[Midnight] Updating additional addresses with correct derivation');
1062
1181
  return [
@@ -1103,12 +1222,14 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1103
1222
  ];
1104
1223
  case 11:
1105
1224
  error = _state.sent();
1106
- // Re-throw password mismatch errors without wrapping
1107
- if (_instanceof(error, Error) && error.message === browser.ERROR_PASSWORD_MISMATCH) {
1225
+ // Re-throw known business-rule rejections without wrapping
1226
+ if (_instanceof(error, Error) && (error.message === browser.ERROR_PASSWORD_MISMATCH || error.message === browser.ERROR_MULTIPLE_WALLETS_PER_CHAIN)) {
1108
1227
  throw error;
1109
1228
  }
1110
1229
  _this.logger.error(ERROR_CREATE_WALLET_ACCOUNT, error);
1111
- throw new Error(ERROR_CREATE_WALLET_ACCOUNT);
1230
+ throw new Error(ERROR_CREATE_WALLET_ACCOUNT, {
1231
+ cause: error
1232
+ });
1112
1233
  case 12:
1113
1234
  return [
1114
1235
  2
@@ -1121,7 +1242,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1121
1242
  {
1122
1243
  key: "signMessage",
1123
1244
  value: function signMessage(param) {
1124
- 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;
1245
+ 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;
1125
1246
  var _this = this;
1126
1247
  return _async_to_generator(function() {
1127
1248
  var messageHex, resolvedContext, signature, error;
@@ -1166,6 +1287,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1166
1287
  signedSessionId: signedSessionId,
1167
1288
  mfaToken: mfaToken,
1168
1289
  context: resolvedContext,
1290
+ approvalQuorum: approvalQuorum,
1169
1291
  onError: onError
1170
1292
  })
1171
1293
  ];
@@ -1177,8 +1299,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1177
1299
  ];
1178
1300
  case 4:
1179
1301
  error = _state.sent();
1180
- _this.logger.error(ERROR_SIGN_MESSAGE, error);
1181
- throw new Error(ERROR_SIGN_MESSAGE);
1302
+ _this.logOperationFailure(ERROR_SIGN_MESSAGE, error);
1303
+ throw new Error(ERROR_SIGN_MESSAGE, {
1304
+ cause: error
1305
+ });
1182
1306
  case 5:
1183
1307
  return [
1184
1308
  2
@@ -1199,7 +1323,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1199
1323
  * entry). If the caller never calls submitTransaction, that entry sits
1200
1324
  * until the next re-sync drops it.
1201
1325
  */ function signTransaction(param) {
1202
- 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;
1326
+ 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;
1203
1327
  var _this = this;
1204
1328
  return _async_to_generator(function() {
1205
1329
  var resolvedNetworkId, wallet, txBytes, unsignedTx, signedRecipe, finalized, error;
@@ -1239,7 +1363,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1239
1363
  signedSessionId: signedSessionId,
1240
1364
  mfaToken: mfaToken,
1241
1365
  elevatedAccessToken: elevatedAccessToken
1242
- })
1366
+ }, 'full', resolveMidnightNetworkTag(networkId))
1243
1367
  ];
1244
1368
  case 3:
1245
1369
  wallet = _state.sent().wallet;
@@ -1259,6 +1383,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1259
1383
  fullTxBase64: transaction,
1260
1384
  networkId: resolvedNetworkId,
1261
1385
  baseContext: context,
1386
+ approvalQuorum: approvalQuorum,
1262
1387
  proofMarker: 'pre-proof'
1263
1388
  })
1264
1389
  ];
@@ -1281,7 +1406,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1281
1406
  ];
1282
1407
  case 6:
1283
1408
  error = _state.sent();
1284
- _this.logger.error(ERROR_SIGN_TRANSACTION, error);
1409
+ _this.logOperationFailure(ERROR_SIGN_TRANSACTION, error);
1285
1410
  onError === null || onError === void 0 ? void 0 : onError(error);
1286
1411
  throw _instanceof(error, Error) ? error : new Error(ERROR_SIGN_TRANSACTION);
1287
1412
  case 7:
@@ -1425,13 +1550,15 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1425
1550
  chainName: chainName,
1426
1551
  thresholdSignatureScheme: thresholdSignatureScheme,
1427
1552
  privateKey: formattedPrivateKey,
1428
- onCeremonyComplete: function(accountAddress, walletId) {
1553
+ onCeremonyComplete: function(param) {
1554
+ var accountAddress = param.accountAddress, walletId = param.walletId, shareSetId = param.shareSetId;
1429
1555
  serverAccountAddress = accountAddress;
1430
1556
  _this.initializeWalletMapEntry({
1431
1557
  accountAddress: accountAddress,
1432
1558
  walletId: walletId,
1433
1559
  chainName: _this.chainName,
1434
- thresholdSignatureScheme: thresholdSignatureScheme
1560
+ thresholdSignatureScheme: thresholdSignatureScheme,
1561
+ shareSetId: shareSetId
1435
1562
  });
1436
1563
  ceremonyCeremonyCompleteResolver(undefined);
1437
1564
  },
@@ -1675,25 +1802,29 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1675
1802
  {
1676
1803
  key: "initMidnightWallet",
1677
1804
  value: function initMidnightWallet(label, mpcParams) {
1805
+ var mode = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 'full', network = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 'preview';
1678
1806
  var _this = this;
1679
1807
  return _async_to_generator(function() {
1680
- var accountAddress, inFlight, initPromise;
1808
+ var accountAddress, initKey, inFlight, initPromise;
1681
1809
  return _ts_generator(this, function(_state) {
1682
1810
  switch(_state.label){
1683
1811
  case 0:
1684
1812
  accountAddress = mpcParams.accountAddress;
1685
- // If another init for this same account is in flight, return its promise
1686
- // instead of kicking off a second, redundant WalletFacade.init.
1687
- inFlight = _this.pendingInits.get(accountAddress);
1813
+ initKey = "".concat(accountAddress, "::").concat(network);
1814
+ // If another init for this same (account, network) is in flight, return its
1815
+ // promise instead of kicking off a second, redundant WalletFacade.init. The
1816
+ // first caller's `mode` wins; that's fine — the wallet is created/cached once
1817
+ // and keeps syncing dust in the background regardless of who waited for what.
1818
+ inFlight = _this.pendingInits.get(initKey);
1688
1819
  if (inFlight) {
1689
- _this.logger.info("[Midnight] ".concat(label, ": joining in-flight init for ").concat(accountAddress));
1820
+ _this.logger.info("[Midnight] ".concat(label, ": joining in-flight init for ").concat(initKey));
1690
1821
  return [
1691
1822
  2,
1692
1823
  inFlight
1693
1824
  ];
1694
1825
  }
1695
- initPromise = _this.runMidnightWalletInit(label, mpcParams);
1696
- _this.pendingInits.set(accountAddress, initPromise);
1826
+ initPromise = _this.runMidnightWalletInit(label, mpcParams, mode, network);
1827
+ _this.pendingInits.set(initKey, initPromise);
1697
1828
  _state.label = 1;
1698
1829
  case 1:
1699
1830
  _state.trys.push([
@@ -1712,7 +1843,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1712
1843
  _state.sent()
1713
1844
  ];
1714
1845
  case 3:
1715
- _this.pendingInits.delete(accountAddress);
1846
+ _this.pendingInits.delete(initKey);
1716
1847
  return [
1717
1848
  7
1718
1849
  ];
@@ -1728,9 +1859,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1728
1859
  {
1729
1860
  key: "runMidnightWalletInit",
1730
1861
  value: function runMidnightWalletInit(label, mpcParams) {
1862
+ var mode = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 'full', network = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 'preview';
1731
1863
  var _this = this;
1732
1864
  return _async_to_generator(function() {
1733
- var _this_cachedWallet, roleKeys, accountAddress, state, _this_cachedWallet_diagnosticSub, shieldedSecretKeys, dustSecretKey, unshieldedKeystore, config, savedState, wallet, syncStart, lastLogTime, fmtSide, state1, err, lastPendingCount, lastPendingSig, diagnosticSub;
1865
+ 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;
1734
1866
  return _ts_generator(this, function(_state) {
1735
1867
  switch(_state.label){
1736
1868
  case 0:
@@ -1741,7 +1873,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1741
1873
  case 1:
1742
1874
  roleKeys = _state.sent();
1743
1875
  accountAddress = mpcParams.accountAddress;
1744
- if (!(((_this_cachedWallet = _this.cachedWallet) === null || _this_cachedWallet === void 0 ? void 0 : _this_cachedWallet.accountAddress) === accountAddress)) return [
1876
+ 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 [
1745
1877
  3,
1746
1878
  3
1747
1879
  ];
@@ -1761,7 +1893,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1761
1893
  reject(new Error('Wallet re-sync timeout'));
1762
1894
  }, 30000);
1763
1895
  sub = _this.cachedWallet.wallet.state().subscribe(function(s) {
1764
- if (s.isSynced) {
1896
+ if (isSyncResolved(s, mode)) {
1765
1897
  clearTimeout(tid);
1766
1898
  // Defer to a microtask so `sub` is definitely assigned whether the
1767
1899
  // emission is synchronous or async.
@@ -1822,30 +1954,43 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1822
1954
  case 8:
1823
1955
  shieldedSecretKeys = ledger__namespace.ZswapSecretKeys.fromSeed(new Uint8Array(Buffer.from(roleKeys.shielded, 'hex')));
1824
1956
  dustSecretKey = ledger__namespace.DustSecretKey.fromSeed(new Uint8Array(Buffer.from(roleKeys.dust, 'hex')));
1825
- unshieldedKeystore = walletSdkUnshieldedWallet.createKeystore(new Uint8Array(Buffer.from(roleKeys.unshielded, 'hex')), 'preview');
1957
+ unshieldedKeystore = walletSdkUnshieldedWallet.createKeystore(new Uint8Array(Buffer.from(roleKeys.unshielded, 'hex')), network);
1958
+ infra = MIDNIGHT_INFRA[network];
1826
1959
  config = {
1827
- networkId: 'preview',
1960
+ networkId: network,
1828
1961
  costParameters: {
1829
1962
  feeBlocksMargin: 5
1830
1963
  },
1831
- relayURL: new URL('wss://rpc.preview.midnight.network'),
1832
- provingServerUrl: new URL('http://localhost:6300'),
1964
+ relayURL: new URL(infra.relayUrl),
1965
+ provingServerUrl: new URL(infra.provingServerUrl),
1833
1966
  indexerClientConnection: {
1834
- indexerHttpUrl: 'https://indexer.preview.midnight.network/api/v4/graphql',
1835
- indexerWsUrl: 'wss://indexer.preview.midnight.network/api/v4/graphql/ws'
1967
+ indexerHttpUrl: infra.indexerHttpUrl,
1968
+ indexerWsUrl: infra.indexerWsUrl
1969
+ },
1970
+ // v4 sync batching. `size` = updates fetched per indexer round-trip.
1971
+ // Measured: 2000 vs 10000 gave the same ~750 entries/sec (≈130s dust cold
1972
+ // sync), so dust is apply-bound (per-entry WASM compute), not fetch-bound
1973
+ // — batch size doesn't move the total. Kept at 2000.
1974
+ batchUpdates: {
1975
+ size: 2000
1836
1976
  },
1837
- txHistoryStorage: new walletSdkUnshieldedWallet.NoOpTransactionHistoryStorage()
1977
+ txHistoryStorage: new walletSdkAbstractions.NoOpTransactionHistoryStorage()
1838
1978
  };
1839
1979
  return [
1840
1980
  4,
1841
- getWalletState(accountAddress)
1981
+ getWalletState(DynamicMidnightWalletClient.walletStateKey(accountAddress, network))
1842
1982
  ];
1843
1983
  case 9:
1844
1984
  savedState = _state.sent();
1845
1985
  if (savedState) {
1846
1986
  _this.logger.info("[Midnight] ".concat(label, ": found persisted state — resuming sync from checkpoint"));
1987
+ // console.* because this.logger is a NoopLogger in the iframe.
1988
+ // eslint-disable-next-line no-console
1989
+ 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)"));
1847
1990
  } else {
1848
1991
  _this.logger.info("[Midnight] ".concat(label, ": no persisted state — cold sync from genesis"));
1992
+ // eslint-disable-next-line no-console
1993
+ console.info("[Midnight] ".concat(label, ": CACHE MISS — no IndexedDB checkpoint for this account, cold sync from genesis"));
1849
1994
  }
1850
1995
  _this.logger.info("[Midnight] ".concat(label, ": initializing wallet..."));
1851
1996
  return [
@@ -1874,31 +2019,56 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1874
2019
  _this.logger.debug("[Midnight] ".concat(label, ": syncing..."));
1875
2020
  syncStart = Date.now();
1876
2021
  lastLogTime = 0;
1877
- // Per-side sync-progress summary. Fields are bigints; `gap` is how many
1878
- // updates still need to be applied to reach the latest relevant index
1879
- // (not the chain tip — `highestRelevantIndex` is what matters for balance).
1880
- // Read the progress object the SDK itself uses for isSynced. For shielded
1881
- // and dust it lives at `side.state.progress`; for unshielded it's
1882
- // `side.progress`. Fall back across both to be safe.
1883
- fmtSide = function(side) {
2022
+ SIDE_NAMES = [
2023
+ 'shielded',
2024
+ 'unshielded',
2025
+ 'dust'
2026
+ ];
2027
+ // Per-tick throughput tracking: appliedIndex per side at the previous log,
2028
+ // so each periodic line shows how many chunks were applied in the interval
2029
+ // (a non-zero delta = still actively polling/applying index chunks). And
2030
+ // the wall-clock at which each side individually completed, so we can see
2031
+ // which dimension is the slow one.
2032
+ lastApplied = {};
2033
+ sideDoneAtMs = {};
2034
+ // In v4 every WalletState (shielded/unshielded/dust) exposes the full
2035
+ // SyncProgress via the `progress` getter (appliedIndex, highestRelevantIndex,
2036
+ // highestIndex). Read that FIRST — `side.state.progress` is the inner
2037
+ // CoreWallet's partial progress (has appliedIndex but leaves the highest*
2038
+ // fields at 0, which is why `gap`/`tip` showed 0 before).
2039
+ readProgress = function(side) {
1884
2040
  var _side_state;
1885
- var _side_state_progress;
1886
- 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;
1887
- if (!p) return 'n/a';
2041
+ var _side_progress;
2042
+ 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;
2043
+ if (!p) return undefined;
1888
2044
  var _p_appliedIndex;
1889
- var applied = (_p_appliedIndex = p.appliedIndex) !== null && _p_appliedIndex !== void 0 ? _p_appliedIndex : 0n;
2045
+ var applied = BigInt((_p_appliedIndex = p.appliedIndex) !== null && _p_appliedIndex !== void 0 ? _p_appliedIndex : 0n);
1890
2046
  var _p_highestRelevantIndex;
1891
- var highestRelevant = (_p_highestRelevantIndex = p.highestRelevantIndex) !== null && _p_highestRelevantIndex !== void 0 ? _p_highestRelevantIndex : 0n;
1892
- var _p_highestRelevantWalletIndex;
1893
- var highestRelevantWallet = (_p_highestRelevantWalletIndex = p.highestRelevantWalletIndex) !== null && _p_highestRelevantWalletIndex !== void 0 ? _p_highestRelevantWalletIndex : 0n;
2047
+ var highestRelevant = BigInt((_p_highestRelevantIndex = p.highestRelevantIndex) !== null && _p_highestRelevantIndex !== void 0 ? _p_highestRelevantIndex : 0n);
1894
2048
  var _p_highestIndex;
1895
- var highest = (_p_highestIndex = p.highestIndex) !== null && _p_highestIndex !== void 0 ? _p_highestIndex : 0n;
1896
- var connected = p.isConnected ? '✓' : '✗';
1897
- var done = '?';
1898
- if (typeof p.isStrictlyComplete === 'function') {
1899
- done = p.isStrictlyComplete() ? '✓' : '✗';
1900
- }
1901
- return "done=".concat(done, " \xb7 applied=").concat(applied, " \xb7 hrw=").concat(highestRelevantWallet, " \xb7 hr=").concat(highestRelevant, " \xb7 tip=").concat(highest, " \xb7 ws=").concat(connected);
2049
+ var highest = BigInt((_p_highestIndex = p.highestIndex) !== null && _p_highestIndex !== void 0 ? _p_highestIndex : 0n);
2050
+ var done = typeof p.isStrictlyComplete === 'function' ? p.isStrictlyComplete() : highestRelevant > 0n && applied >= highestRelevant;
2051
+ return {
2052
+ applied: applied,
2053
+ connected: Boolean(p.isConnected),
2054
+ done: done,
2055
+ highest: highest,
2056
+ highestRelevant: highestRelevant
2057
+ };
2058
+ };
2059
+ // `remaining` = updates still to apply to reach the latest relevant index
2060
+ // (the target for isSynced — not the chain tip). `+N` = entries applied
2061
+ // since the previous periodic log. `pct` = applied / highestRelevant.
2062
+ fmtSide = function(name, side) {
2063
+ var p = readProgress(side);
2064
+ if (!p) return "".concat(name, "=n/a");
2065
+ var _lastApplied_name;
2066
+ var prev = (_lastApplied_name = lastApplied[name]) !== null && _lastApplied_name !== void 0 ? _lastApplied_name : p.applied;
2067
+ var delta = p.applied - prev;
2068
+ lastApplied[name] = p.applied;
2069
+ var remaining = p.highestRelevant > p.applied ? p.highestRelevant - p.applied : 0n;
2070
+ var pct = p.highestRelevant > 0n ? "".concat((Number(p.applied) / Number(p.highestRelevant) * 100).toFixed(1), "%") : 'n/a';
2071
+ 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 ? '✓' : '✗', "]");
1902
2072
  };
1903
2073
  _state.label = 12;
1904
2074
  case 12:
@@ -1923,16 +2093,54 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1923
2093
  }, 300000);
1924
2094
  sub = wallet.state().subscribe(function(s) {
1925
2095
  var now = Date.now();
2096
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
2097
+ try {
2098
+ // Record the moment each side individually completes (checked every
2099
+ // tick so the timestamp is precise, not rounded to the 5s log).
2100
+ for(var _iterator = SIDE_NAMES[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
2101
+ var name = _step.value;
2102
+ var _readProgress;
2103
+ if (sideDoneAtMs[name] === undefined && ((_readProgress = readProgress(s[name])) === null || _readProgress === void 0 ? void 0 : _readProgress.done)) {
2104
+ sideDoneAtMs[name] = now;
2105
+ // console.* (not this.logger, which is a NoopLogger / remote
2106
+ // shipper here) so these sync-timing diagnostics are visible in
2107
+ // the browser console.
2108
+ // eslint-disable-next-line no-console
2109
+ console.info("[Midnight] ".concat(label, ": ").concat(name, " side synced in ").concat(((now - syncStart) / 1000).toFixed(1), "s"));
2110
+ }
2111
+ }
2112
+ } catch (err) {
2113
+ _didIteratorError = true;
2114
+ _iteratorError = err;
2115
+ } finally{
2116
+ try {
2117
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
2118
+ _iterator.return();
2119
+ }
2120
+ } finally{
2121
+ if (_didIteratorError) {
2122
+ throw _iteratorError;
2123
+ }
2124
+ }
2125
+ }
1926
2126
  if (now - lastLogTime > 5000) {
1927
2127
  lastLogTime = now;
1928
- _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)));
2128
+ // eslint-disable-next-line no-console
2129
+ 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)));
1929
2130
  }
1930
- if (s.isSynced) {
2131
+ if (isSyncResolved(s, mode)) {
1931
2132
  clearTimeout(timeoutId);
1932
2133
  queueMicrotask(function() {
1933
2134
  return sub === null || sub === void 0 ? void 0 : sub.unsubscribe();
1934
2135
  });
1935
- _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)));
2136
+ var elapsed = (Date.now() - syncStart) / 1000;
2137
+ var perSide = SIDE_NAMES.map(function(name) {
2138
+ var at = sideDoneAtMs[name];
2139
+ var when = at === undefined ? 'n/a' : "".concat(((at - syncStart) / 1000).toFixed(1), "s");
2140
+ return "".concat(name, "=").concat(when);
2141
+ }).join(' · ');
2142
+ // eslint-disable-next-line no-console
2143
+ console.info("[Midnight] ".concat(label, ": fully synced in ").concat(elapsed.toFixed(1), "s \xb7 per-side: ").concat(perSide));
1936
2144
  resolve(s);
1937
2145
  }
1938
2146
  });
@@ -1945,7 +2153,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1945
2153
  19
1946
2154
  ];
1947
2155
  case 14:
1948
- err = _state.sent();
2156
+ err1 = _state.sent();
1949
2157
  _state.label = 15;
1950
2158
  case 15:
1951
2159
  _state.trys.push([
@@ -1971,7 +2179,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1971
2179
  18
1972
2180
  ];
1973
2181
  case 18:
1974
- throw err;
2182
+ throw err1;
1975
2183
  case 19:
1976
2184
  // Diagnostic: track pending-tx transitions so we can observe TTL
1977
2185
  // auto-revert (entry flips from result=undefined → result.status='FAILURE'
@@ -1981,8 +2189,28 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
1981
2189
  // full log-format state for the lifetime of the client.
1982
2190
  lastPendingCount = -1;
1983
2191
  lastPendingSig = '';
2192
+ // Dust telemetry. The foreground sync logger (above) unsubscribes the
2193
+ // instant shielded + unshielded resolve, so this long-lived subscription is
2194
+ // the ONLY window into the background dust fold. Log dust progress every
2195
+ // ~5s while it's still folding (so we can see `applied` climbing vs frozen),
2196
+ // and once when it finally reports strictly-complete (or never, which is
2197
+ // itself the answer). Reuses fmtSide for a format consistent with the
2198
+ // foreground log.
2199
+ lastDustLogTime = 0;
2200
+ dustDoneLogged = false;
1984
2201
  diagnosticSub = wallet.state().subscribe(function(s) {
1985
2202
  var _s_pending;
2203
+ var dustNow = Date.now();
2204
+ var dustDone = isSideSynced(s.dust);
2205
+ if (dustDone && !dustDoneLogged) {
2206
+ dustDoneLogged = true;
2207
+ // eslint-disable-next-line no-console
2208
+ console.info("[Midnight] ".concat(label, ": dust fully synced in ").concat(((dustNow - syncStart) / 1000).toFixed(1), "s \xb7 ").concat(fmtSide('dust', s.dust)));
2209
+ } else if (!dustDone && dustNow - lastDustLogTime > 5000) {
2210
+ lastDustLogTime = dustNow;
2211
+ // eslint-disable-next-line no-console
2212
+ console.info("[Midnight] ".concat(label, ": dust @ ").concat(((dustNow - syncStart) / 1000).toFixed(1), "s \xb7 ").concat(fmtSide('dust', s.dust)));
2213
+ }
1986
2214
  var _s_pending_all;
1987
2215
  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 : [];
1988
2216
  var sig = JSON.stringify(pending.map(function(p) {
@@ -2056,6 +2284,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2056
2284
  ledger: ledger__namespace,
2057
2285
  roleKeys: roleKeys,
2058
2286
  accountAddress: accountAddress,
2287
+ network: network,
2059
2288
  shieldedSecretKeys: shieldedSecretKeys,
2060
2289
  dustSecretKey: dustSecretKey,
2061
2290
  diagnosticSub: diagnosticSub
@@ -2121,10 +2350,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2121
2350
  {
2122
2351
  key: "getPrivateBalance",
2123
2352
  value: function getPrivateBalance(param) {
2124
- var accountAddress = param.accountAddress, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken;
2353
+ var accountAddress = param.accountAddress, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, networkId = param.networkId;
2125
2354
  var _this = this;
2126
2355
  return _async_to_generator(function() {
2127
- 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;
2356
+ 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;
2128
2357
  return _ts_generator(this, function(_state) {
2129
2358
  switch(_state.label){
2130
2359
  case 0:
@@ -2136,7 +2365,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2136
2365
  signedSessionId: signedSessionId,
2137
2366
  mfaToken: mfaToken,
2138
2367
  elevatedAccessToken: elevatedAccessToken
2139
- })
2368
+ }, // Resolve once shielded + unshielded are ready; let dust finish in the
2369
+ // background so the public/shielded balance shows without the ~130s
2370
+ // dust cold-sync.
2371
+ 'shielded-unshielded', resolveMidnightNetworkTag(networkId))
2140
2372
  ];
2141
2373
  case 1:
2142
2374
  _ref = _state.sent(), state = _ref.state, addr = _ref.accountAddress;
@@ -2182,10 +2414,22 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2182
2414
  }
2183
2415
  }
2184
2416
  }
2417
+ // v4 exposes the dust generation cap per coin (DustFullInfo.maxCap). The
2418
+ // wallet-level cap is the sum across the wallet's dust coins.
2419
+ now = new Date();
2420
+ 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;
2421
+ 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) {
2422
+ var _coin_maxCap;
2423
+ return sum + ((_coin_maxCap = coin.maxCap) !== null && _coin_maxCap !== void 0 ? _coin_maxCap : 0n);
2424
+ }, 0n);
2185
2425
  result = {
2186
2426
  unshielded: unshieldedByToken,
2187
2427
  shielded: shieldedByToken,
2188
- 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(),
2428
+ dust: {
2429
+ balance: dustBalance.toString(),
2430
+ cap: dustCap.toString()
2431
+ },
2432
+ dustSynced: isSideSynced(state.dust),
2189
2433
  address: addr
2190
2434
  };
2191
2435
  // Fire-and-forget snapshot so the next init resumes from here instead
@@ -2203,7 +2447,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2203
2447
  {
2204
2448
  key: "registerDust",
2205
2449
  value: function registerDust(param) {
2206
- var accountAddress = param.accountAddress, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken;
2450
+ var accountAddress = param.accountAddress, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, networkId = param.networkId;
2207
2451
  var _this = this;
2208
2452
  return _async_to_generator(function() {
2209
2453
  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;
@@ -2218,7 +2462,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2218
2462
  signedSessionId: signedSessionId,
2219
2463
  mfaToken: mfaToken,
2220
2464
  elevatedAccessToken: elevatedAccessToken
2221
- })
2465
+ }, 'full', resolveMidnightNetworkTag(networkId))
2222
2466
  ];
2223
2467
  case 1:
2224
2468
  _ref = _state.sent(), wallet = _ref.wallet, state = _ref.state, ledger = _ref.ledger, roleKeys = _ref.roleKeys;
@@ -2318,13 +2562,14 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2318
2562
  * No MPC, no proof server, no broadcast — pair with signTransaction and
2319
2563
  * submitTransaction.
2320
2564
  */ function createTransferTransaction(param) {
2321
- var accountAddress = param.accountAddress, transfers = param.transfers, ttlMinutes = param.ttlMinutes, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken;
2565
+ 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;
2322
2566
  var _this = this;
2323
2567
  return _async_to_generator(function() {
2324
- 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;
2568
+ 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;
2325
2569
  return _ts_generator(this, function(_state) {
2326
2570
  switch(_state.label){
2327
2571
  case 0:
2572
+ network = resolveMidnightNetworkTag(networkId);
2328
2573
  if (!transfers || transfers.length === 0) {
2329
2574
  throw new Error('At least one transfer is required');
2330
2575
  }
@@ -2336,7 +2581,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2336
2581
  signedSessionId: signedSessionId,
2337
2582
  mfaToken: mfaToken,
2338
2583
  elevatedAccessToken: elevatedAccessToken
2339
- })
2584
+ }, 'full', network)
2340
2585
  ];
2341
2586
  case 1:
2342
2587
  _ref = _state.sent(), wallet = _ref.wallet, state = _ref.state, shieldedSecretKeys = _ref.shieldedSecretKeys, dustSecretKey = _ref.dustSecretKey;
@@ -2416,7 +2661,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2416
2661
  var receiverAddress;
2417
2662
  try {
2418
2663
  var parsed = walletSdkAddressFormat.MidnightBech32m.parse(t.recipientAddress);
2419
- receiverAddress = t.type === 'unshielded' ? parsed.decode(walletSdkAddressFormat.UnshieldedAddress, 'preview') : parsed.decode(walletSdkAddressFormat.ShieldedAddress, 'preview');
2664
+ receiverAddress = t.type === 'unshielded' ? parsed.decode(walletSdkAddressFormat.UnshieldedAddress, network) : parsed.decode(walletSdkAddressFormat.ShieldedAddress, network);
2420
2665
  } catch (err) {
2421
2666
  throw new Error("Invalid ".concat(t.type, " recipient address ").concat(t.recipientAddress, ": ").concat(err.message));
2422
2667
  }
@@ -2471,10 +2716,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2471
2716
  * server; reuses the cached wallet's node connection. Optionally blocks
2472
2717
  * until the unshielded balance for tokenType stabilizes.
2473
2718
  */ function submitTransaction(param) {
2474
- 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;
2719
+ 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;
2475
2720
  var _this = this;
2476
2721
  return _async_to_generator(function() {
2477
- var _updatedState_unshielded_balances, _updatedState_unshielded, wallet, txBytes, finalized, txIdentifier, txHash, balanceBeforeBig, updatedState, _updatedState_unshielded_balances_tokenType, balanceAfter;
2722
+ var _updatedState_unshielded_balances, _updatedState_unshielded, wallet, txBytes, finalized, txIdentifier, submissionIdentifier, txHash, canonicalHash, balanceBeforeBig, updatedState, _updatedState_unshielded_balances_tokenType, balanceAfter;
2478
2723
  return _ts_generator(this, function(_state) {
2479
2724
  switch(_state.label){
2480
2725
  case 0:
@@ -2486,7 +2731,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2486
2731
  signedSessionId: signedSessionId,
2487
2732
  mfaToken: mfaToken,
2488
2733
  elevatedAccessToken: elevatedAccessToken
2489
- })
2734
+ }, 'full', resolveMidnightNetworkTag(networkId))
2490
2735
  ];
2491
2736
  case 1:
2492
2737
  wallet = _state.sent().wallet;
@@ -2499,14 +2744,30 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2499
2744
  ];
2500
2745
  case 2:
2501
2746
  txIdentifier = _state.sent();
2502
- txHash = DynamicMidnightWalletClient.toTxHashString(txIdentifier);
2747
+ // The facade returns the submission *identifier* (used to watch for the tx),
2748
+ // but the block explorer indexes by the canonical transaction hash. Derive
2749
+ // that hash from the finalized ledger transaction so explorer links resolve;
2750
+ // fall back to the identifier if the hash can't be computed.
2751
+ // Returned alongside txHash: midnight-js polls
2752
+ // `transactions(offset: { identifier })` to observe inclusion, so a caller
2753
+ // handed only the canonical hash waits forever on a transaction that
2754
+ // actually succeeded.
2755
+ submissionIdentifier = DynamicMidnightWalletClient.toTxHashString(txIdentifier);
2756
+ txHash = submissionIdentifier;
2757
+ try {
2758
+ canonicalHash = DynamicMidnightWalletClient.toTxHashString(finalized.transactionHash());
2759
+ if (canonicalHash) txHash = canonicalHash;
2760
+ } catch (err) {
2761
+ _this.logger.warn('[Midnight] submitTransaction: could not derive canonical tx hash, using submission identifier', err);
2762
+ }
2503
2763
  _this.logger.info('[Midnight] submitTransaction: broadcast, txHash=', txHash);
2504
2764
  if (!waitForBalance) {
2505
2765
  void _this.persistCachedWalletState();
2506
2766
  return [
2507
2767
  2,
2508
2768
  {
2509
- txHash: txHash
2769
+ txHash: txHash,
2770
+ txIdentifier: submissionIdentifier
2510
2771
  }
2511
2772
  ];
2512
2773
  }
@@ -2557,6 +2818,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2557
2818
  2,
2558
2819
  {
2559
2820
  txHash: txHash,
2821
+ txIdentifier: submissionIdentifier,
2560
2822
  balanceAfter: balanceAfter.toString()
2561
2823
  }
2562
2824
  ];
@@ -2628,9 +2890,9 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2628
2890
  case 1:
2629
2891
  _state.trys.push([
2630
2892
  1,
2631
- 8,
2893
+ 9,
2632
2894
  ,
2633
- 9
2895
+ 10
2634
2896
  ]);
2635
2897
  if (!(((_this_cachedWallet = _this.cachedWallet) === null || _this_cachedWallet === void 0 ? void 0 : _this_cachedWallet.accountAddress) === accountAddress)) return [
2636
2898
  3,
@@ -2669,20 +2931,28 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2669
2931
  _this.cachedWallet = null;
2670
2932
  _state.label = 6;
2671
2933
  case 6:
2934
+ // Nuclear reset is network-agnostic: clear both networks' checkpoints so
2935
+ // no stale snapshot survives on either facade.
2672
2936
  return [
2673
2937
  4,
2674
- deleteWalletState(accountAddress)
2938
+ deleteWalletState(DynamicMidnightWalletClient.walletStateKey(accountAddress, 'preview'))
2675
2939
  ];
2676
2940
  case 7:
2677
2941
  _state.sent();
2678
2942
  return [
2679
- 3,
2680
- 9
2943
+ 4,
2944
+ deleteWalletState(DynamicMidnightWalletClient.walletStateKey(accountAddress, 'mainnet'))
2681
2945
  ];
2682
2946
  case 8:
2947
+ _state.sent();
2948
+ return [
2949
+ 3,
2950
+ 10
2951
+ ];
2952
+ case 9:
2683
2953
  err = _state.sent();
2684
2954
  throw new Error("resetCache failed: ".concat(err.message));
2685
- case 9:
2955
+ case 10:
2686
2956
  _this.logger.info('[Midnight] revertTransaction[resetCache]: cache cleared');
2687
2957
  return [
2688
2958
  2,
@@ -2715,7 +2985,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2715
2985
  signedSessionId: params.signedSessionId,
2716
2986
  mfaToken: params.mfaToken,
2717
2987
  elevatedAccessToken: params.elevatedAccessToken
2718
- })
2988
+ }, 'full', resolveMidnightNetworkTag(params.networkId))
2719
2989
  ];
2720
2990
  case 1:
2721
2991
  wallet = _state.sent().wallet;
@@ -2760,7 +3030,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2760
3030
  signedSessionId: params.signedSessionId,
2761
3031
  mfaToken: params.mfaToken,
2762
3032
  elevatedAccessToken: params.elevatedAccessToken
2763
- })
3033
+ }, 'full', resolveMidnightNetworkTag(params.networkId))
2764
3034
  ];
2765
3035
  case 1:
2766
3036
  wallet = _state.sent().wallet;
@@ -2922,11 +3192,11 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2922
3192
  */ function mpcSignIntents(tx, options) {
2923
3193
  var _this = this;
2924
3194
  return _async_to_generator(function() {
2925
- 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;
3195
+ 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;
2926
3196
  return _ts_generator(this, function(_state) {
2927
3197
  switch(_state.label){
2928
3198
  case 0:
2929
- 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;
3199
+ 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;
2930
3200
  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 : [];
2931
3201
  if (segments.length === 0) return [
2932
3202
  2
@@ -2978,7 +3248,8 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
2978
3248
  serializedTransaction: fullTxBase64,
2979
3249
  networkId: networkId
2980
3250
  }
2981
- })
3251
+ }),
3252
+ approvalQuorum: approvalQuorum
2982
3253
  })
2983
3254
  ];
2984
3255
  case 2:
@@ -3061,19 +3332,110 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3061
3332
  })();
3062
3333
  }
3063
3334
  },
3335
+ {
3336
+ key: "getWalletProviderPublicKeys",
3337
+ value: /**
3338
+ * Initializes the iframe-resident wallet provider and returns only its public
3339
+ * keys. Secret wallet state never crosses the iframe transport boundary.
3340
+ */ function getWalletProviderPublicKeys(params) {
3341
+ var _this = this;
3342
+ return _async_to_generator(function() {
3343
+ var walletProvider;
3344
+ return _ts_generator(this, function(_state) {
3345
+ switch(_state.label){
3346
+ case 0:
3347
+ return [
3348
+ 4,
3349
+ _this.getWalletProvider(params)
3350
+ ];
3351
+ case 1:
3352
+ walletProvider = _state.sent().walletProvider;
3353
+ return [
3354
+ 2,
3355
+ {
3356
+ coinPublicKey: walletProvider.getCoinPublicKey(),
3357
+ encryptionPublicKey: walletProvider.getEncryptionPublicKey(),
3358
+ status: 'ready'
3359
+ }
3360
+ ];
3361
+ }
3362
+ });
3363
+ })();
3364
+ }
3365
+ },
3366
+ {
3367
+ key: "balanceWalletProviderTransaction",
3368
+ value: /**
3369
+ * Balances a midnight-js UnboundTransaction inside the iframe. The host sends
3370
+ * only serialized transaction data; MPC, shielded, and DUST keys remain here.
3371
+ */ function balanceWalletProviderTransaction(_param) {
3372
+ var _this = this;
3373
+ return _async_to_generator(function() {
3374
+ var transaction, ttl, providerParams, ttlDate, txBytes, unboundTransaction, walletProvider, finalizedTransaction;
3375
+ return _ts_generator(this, function(_state) {
3376
+ switch(_state.label){
3377
+ case 0:
3378
+ transaction = _param.transaction, ttl = _param.ttl, providerParams = _object_without_properties(_param, [
3379
+ "transaction",
3380
+ "ttl"
3381
+ ]);
3382
+ if (!transaction) {
3383
+ throw new Error('balanceWalletProviderTransaction: transaction is required');
3384
+ }
3385
+ ttlDate = ttl ? new Date(ttl) : undefined;
3386
+ if (ttlDate && Number.isNaN(ttlDate.getTime())) {
3387
+ throw new Error('balanceWalletProviderTransaction: ttl must be a valid ISO-8601 date');
3388
+ }
3389
+ // Host-controlled string, so validate shape before the WASM deserializer.
3390
+ // `Buffer.from(..., 'base64')` silently drops invalid characters rather than
3391
+ // throwing, so a malformed payload would otherwise reach `deserialize` as
3392
+ // truncated-but-plausible bytes and fail with an opaque WASM error. The
3393
+ // upper bound also stops a huge body from being decoded at all.
3394
+ if (!BASE64_PATTERN.test(transaction)) {
3395
+ throw new Error('balanceWalletProviderTransaction: transaction must be base64');
3396
+ }
3397
+ txBytes = Buffer.from(transaction, 'base64');
3398
+ if (txBytes.length === 0 || txBytes.length > MAX_SERIALIZED_TRANSACTION_BYTES) {
3399
+ throw new Error("balanceWalletProviderTransaction: transaction must decode to 1..".concat(MAX_SERIALIZED_TRANSACTION_BYTES, " bytes, got ").concat(txBytes.length));
3400
+ }
3401
+ unboundTransaction = ledger__namespace.Transaction.deserialize('signature', 'proof', 'pre-binding', new Uint8Array(txBytes));
3402
+ return [
3403
+ 4,
3404
+ _this.getWalletProvider(providerParams)
3405
+ ];
3406
+ case 1:
3407
+ walletProvider = _state.sent().walletProvider;
3408
+ return [
3409
+ 4,
3410
+ walletProvider.balanceTx(unboundTransaction, ttlDate)
3411
+ ];
3412
+ case 2:
3413
+ finalizedTransaction = _state.sent();
3414
+ return [
3415
+ 2,
3416
+ {
3417
+ transaction: Buffer.from(finalizedTransaction.serialize()).toString('base64')
3418
+ }
3419
+ ];
3420
+ }
3421
+ });
3422
+ })();
3423
+ }
3424
+ },
3064
3425
  {
3065
3426
  key: "getWalletProvider",
3066
3427
  value: /**
3067
3428
  * Returns a Midnight.js-compatible WalletProvider for use with
3068
3429
  * midnight-js-contracts. Signing goes through MPC — no private key exposed.
3069
3430
  */ function getWalletProvider(param) {
3070
- var accountAddress = param.accountAddress, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken;
3431
+ var accountAddress = param.accountAddress, password = param.password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, networkId = param.networkId;
3071
3432
  var _this = this;
3072
3433
  return _async_to_generator(function() {
3073
- var _ref, wallet, state, shieldedSecretKeys, dustSecretKey, walletProvider;
3434
+ var network, _ref, wallet, state, shieldedSecretKeys, dustSecretKey, walletProvider;
3074
3435
  return _ts_generator(this, function(_state) {
3075
3436
  switch(_state.label){
3076
3437
  case 0:
3438
+ network = resolveMidnightNetworkTag(networkId);
3077
3439
  return [
3078
3440
  4,
3079
3441
  _this.initMidnightWallet('walletProvider', {
@@ -3082,7 +3444,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3082
3444
  signedSessionId: signedSessionId,
3083
3445
  mfaToken: mfaToken,
3084
3446
  elevatedAccessToken: elevatedAccessToken
3085
- })
3447
+ }, 'full', network)
3086
3448
  ];
3087
3449
  case 1:
3088
3450
  _ref = _state.sent(), wallet = _ref.wallet, state = _ref.state, shieldedSecretKeys = _ref.shieldedSecretKeys, dustSecretKey = _ref.dustSecretKey;
@@ -3111,8 +3473,8 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3111
3473
  ];
3112
3474
  case 1:
3113
3475
  recipe = _state.sent();
3114
- // The proven base tx uses the 'proof' marker. networkId 0 matches
3115
- // the 'preview' facade network this provider is configured for.
3476
+ // The proven base tx uses the 'proof' marker. The numeric networkId
3477
+ // must match the facade network this provider was configured for.
3116
3478
  baseTxB64 = Buffer.from(recipe.baseTransaction.serialize()).toString('base64');
3117
3479
  return [
3118
3480
  4,
@@ -3123,7 +3485,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3123
3485
  mfaToken: mfaToken,
3124
3486
  elevatedAccessToken: elevatedAccessToken,
3125
3487
  fullTxBase64: baseTxB64,
3126
- networkId: 0,
3488
+ networkId: MIDNIGHT_NETWORK_IDS[network],
3127
3489
  proofMarker: 'proof'
3128
3490
  })
3129
3491
  ];
@@ -3143,7 +3505,7 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3143
3505
  mfaToken: mfaToken,
3144
3506
  elevatedAccessToken: elevatedAccessToken,
3145
3507
  fullTxBase64: balancingTxB64,
3146
- networkId: 0,
3508
+ networkId: MIDNIGHT_NETWORK_IDS[network],
3147
3509
  proofMarker: 'pre-proof'
3148
3510
  })
3149
3511
  ];
@@ -3185,13 +3547,23 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3185
3547
  }
3186
3548
  ], [
3187
3549
  {
3188
- key: "toTxHashString",
3550
+ key: "walletStateKey",
3189
3551
  value: /**
3190
3552
  * Coerce the value returned by `wallet.submitTransaction(...)` to a string.
3191
3553
  * Midnight's facade returns either a string txId, or a TransactionIdentifier
3192
3554
  * object with a `.toHex()` method. We normalize so callers always see a
3193
3555
  * string, and fall back to `String(...)` if neither shape matches.
3194
- */ function toTxHashString(txIdentifier) {
3556
+ */ /**
3557
+ * IndexedDB checkpoint key. Sync state is per (account, network) — restoring
3558
+ * a preview snapshot into a mainnet facade would corrupt sync. Preview keeps
3559
+ * the bare-address key so pre-existing checkpoints stay valid.
3560
+ */ function walletStateKey(accountAddress, network) {
3561
+ return network === 'mainnet' ? "".concat(accountAddress, "::mainnet") : accountAddress;
3562
+ }
3563
+ },
3564
+ {
3565
+ key: "toTxHashString",
3566
+ value: function toTxHashString(txIdentifier) {
3195
3567
  if (typeof txIdentifier === 'string') return txIdentifier;
3196
3568
  var maybeHex = txIdentifier === null || txIdentifier === void 0 ? void 0 : txIdentifier.toHex;
3197
3569
  if (typeof maybeHex === 'function') return txIdentifier.toHex();
@@ -3217,10 +3589,10 @@ var DynamicMidnightWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
3217
3589
  * If publicKeyHex is passed, it's assumed to already be the address hash.
3218
3590
  *
3219
3591
  * @param publicKeyHex - The 32-byte address hash (from addressFromKey) as hex string
3220
- * @param network - The network. Defaults to preview
3221
- * @returns Bech32m encoded address (e.g., mn_addr_preview1...)
3592
+ * @param network - The network. Defaults to mainnet
3593
+ * @returns Bech32m encoded address (e.g., mn_addr1...)
3222
3594
  */ var deriveMidnightAddress = function(param) {
3223
- var publicKeyHex = param.publicKeyHex, _param_network = param.network, network = _param_network === void 0 ? 'preview' : _param_network;
3595
+ var publicKeyHex = param.publicKeyHex, _param_network = param.network, network = _param_network === void 0 ? 'mainnet' : _param_network;
3224
3596
  var bytes = Buffer.from(publicKeyHex, 'hex');
3225
3597
  if (bytes.length !== 32) {
3226
3598
  throw new Error("Invalid key length: ".concat(bytes.length, ", expected 32"));