@onekeyfe/hwk-trezor-adapter 1.2.3-alpha.8 → 1.2.3

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/dist/index.js CHANGED
@@ -5,20 +5,6 @@
5
5
 
6
6
 
7
7
 
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
-
21
-
22
8
 
23
9
 
24
10
 
@@ -776,14 +762,6 @@ function debugLog(...args) {
776
762
  emitLog("debug", ...args);
777
763
  }
778
764
 
779
- // src/utils/queueKey.ts
780
- function trezorQueueKey({
781
- operationId,
782
- connectId
783
- }) {
784
- return operationId || connectId || "";
785
- }
786
-
787
765
  // src/adapter/TrezorAdapter.ts
788
766
  var KNOWN_HARDWARE_ERROR_CODES = new Set(
789
767
  Object.values(_hwkadaptercore.HardwareErrorCode).filter((value) => typeof value === "number")
@@ -804,24 +782,9 @@ var TREZOR_BTC_NETWORK_COIN_MAP = {
804
782
  dash: "Dash"
805
783
  };
806
784
  var _TrezorAdapter = class _TrezorAdapter {
807
- constructor(connector, options) {
785
+ constructor(connector) {
808
786
  this.vendor = "trezor";
809
- // The connector has no protocol-level cancel: the adapter stops waiting and
810
- // drops the late response, the device carries on.
811
- this.cancelCapability = "stops-waiting";
812
787
  this._emitter = new (0, _hwkadaptercore.TypedEventEmitter)();
813
- this._operations = new (0, _hwkadaptercore.OperationRegistry)({
814
- vendor: "trezor",
815
- onEnded: (operation, reason) => {
816
- this._emitter.emit(_hwkadaptercore.SDK.OPERATION_ENDED, {
817
- type: _hwkadaptercore.SDK.OPERATION_ENDED,
818
- payload: { operationId: operation.operationId, reason }
819
- });
820
- if (reason === "timeout") {
821
- void this._releaseOperationConnection(operation).catch(() => void 0);
822
- }
823
- }
824
- });
825
788
  this._devices = /* @__PURE__ */ new Map();
826
789
  this._sessions = /* @__PURE__ */ new Map();
827
790
  this._connectingPromises = /* @__PURE__ */ new Map();
@@ -830,21 +793,12 @@ var _TrezorAdapter = class _TrezorAdapter {
830
793
  this._uiRegistry = new (0, _hwkadaptercore.UiRequestRegistry)();
831
794
  this._passphraseRequestContextByConnectId = /* @__PURE__ */ new Map();
832
795
  this._verifiedPassphraseSessionsByConnectId = /* @__PURE__ */ new Map();
833
- /** Raw connector calls that outlive an aborted caller, keyed by session. */
834
- this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
835
- this._connectorIdleWaiters = /* @__PURE__ */ new Set();
836
- this._resetPromise = null;
837
- this._connectorTeardownTail = Promise.resolve();
838
- this._pendingConnectorTeardowns = 0;
839
- this._stateGeneration = 0;
840
- this._knownDeviceConnections = /* @__PURE__ */ new Map();
841
796
  this._onDeviceConnect = (data) => {
842
797
  const device = this._connectorDeviceToDeviceInfo(data.device);
843
798
  this._devices.set(device.connectId, device);
844
799
  this._emitter.emit(_hwkadaptercore.DEVICE.CONNECT, { type: _hwkadaptercore.DEVICE.CONNECT, payload: device });
845
800
  };
846
801
  this._onDeviceDisconnect = (data) => {
847
- this._operations.endByConnectionKey(data.connectId, "disconnect");
848
802
  this._sessions.delete(data.connectId);
849
803
  this._verifiedPassphraseSessionsByConnectId.delete(data.connectId);
850
804
  this._devices.delete(data.connectId);
@@ -864,32 +818,25 @@ var _TrezorAdapter = class _TrezorAdapter {
864
818
  payload: { device }
865
819
  });
866
820
  };
867
- // The one outlet for every connector-raised UI request (PIN, passphrase,
868
- // button, THP pairing), so the operation is stamped here instead of at each
869
- // connector call site.
870
821
  this._onUiRequest = (data) => {
871
- const operationId = this._activeOperationId();
872
- const basePayload = data.payload && typeof data.payload === "object" ? data.payload : {};
873
- const attribution = operationId === void 0 ? {} : { operationId };
874
822
  if (data.type === _hwkadaptercore.UI_REQUEST.REQUEST_PASSPHRASE) {
875
- const connectId = typeof basePayload.connectId === "string" ? basePayload.connectId : void 0;
823
+ const payload = data.payload && typeof data.payload === "object" ? data.payload : {};
824
+ const connectId = typeof payload.connectId === "string" ? payload.connectId : void 0;
876
825
  const context = connectId ? this._passphraseRequestContextByConnectId.get(connectId) : void 0;
877
826
  this._emitter.emit(
878
827
  data.type,
879
828
  {
880
829
  ...data,
881
830
  payload: {
882
- ...basePayload,
831
+ ...payload,
883
832
  ..._optionalChain([context, 'optionalAccess', _13 => _13.passphraseState]) !== void 0 ? { passphraseState: context.passphraseState } : {},
884
- ..._optionalChain([context, 'optionalAccess', _14 => _14.useEmptyPassphrase]) !== void 0 ? { useEmptyPassphrase: context.useEmptyPassphrase } : {},
885
- ...attribution
833
+ ..._optionalChain([context, 'optionalAccess', _14 => _14.useEmptyPassphrase]) !== void 0 ? { useEmptyPassphrase: context.useEmptyPassphrase } : {}
886
834
  }
887
835
  }
888
836
  );
889
837
  return;
890
838
  }
891
- const payload = operationId === void 0 ? data.payload : { ...basePayload, ...attribution };
892
- this._emitter.emit(data.type, { ...data, payload });
839
+ this._emitter.emit(data.type, data);
893
840
  };
894
841
  this._onUiEvent = (data) => {
895
842
  this._emitter.emit("ui-event", data);
@@ -901,11 +848,6 @@ var _TrezorAdapter = class _TrezorAdapter {
901
848
  });
902
849
  };
903
850
  this._connector = connector;
904
- for (const connection of _nullishCoalesce(_optionalChain([options, 'optionalAccess', _15 => _15.knownDeviceConnections]), () => ( []))) {
905
- if (connection.deviceId) {
906
- this._knownDeviceConnections.set(connection.deviceId, { ...connection });
907
- }
908
- }
909
851
  this._jobQueue = new (0, _hwkadaptercore.DeviceJobQueue)();
910
852
  this._registerConnectorEvents();
911
853
  }
@@ -930,47 +872,29 @@ var _TrezorAdapter = class _TrezorAdapter {
930
872
  const {
931
873
  passphraseState,
932
874
  autoInstallApp: _autoInstallApp,
933
- operationId,
934
875
  useEmptyPassphrase,
935
- knownConnections,
936
- extra,
937
- allowDeviceSelection,
938
876
  ...rest
939
877
  } = params;
940
878
  return {
941
879
  passphraseState: typeof passphraseState === "string" ? passphraseState : void 0,
942
880
  useEmptyPassphrase: typeof useEmptyPassphrase === "boolean" ? useEmptyPassphrase : void 0,
943
- operationId: typeof operationId === "string" ? operationId : void 0,
944
- connectionContext: {
945
- knownConnections,
946
- extra,
947
- allowDeviceSelection: typeof allowDeviceSelection === "boolean" ? allowDeviceSelection : void 0
948
- },
949
881
  rest
950
882
  };
951
883
  }
952
884
  return { rest: _nullishCoalesce(params, () => ( {})) };
953
885
  }
954
886
  static _withAllNetworkRequestCommonParams(item, commonParams) {
955
- const autoInstallApp = _optionalChain([commonParams, 'optionalAccess', _16 => _16.autoInstallApp]);
956
- const passphraseState = _optionalChain([commonParams, 'optionalAccess', _17 => _17.passphraseState]);
957
- const useEmptyPassphrase = _optionalChain([commonParams, 'optionalAccess', _18 => _18.useEmptyPassphrase]);
958
- const operationId = _optionalChain([commonParams, 'optionalAccess', _19 => _19.operationId]);
959
- const knownConnections = _optionalChain([commonParams, 'optionalAccess', _20 => _20.knownConnections]);
960
- const extra = _optionalChain([commonParams, 'optionalAccess', _21 => _21.extra]);
961
- const allowDeviceSelection = _optionalChain([commonParams, 'optionalAccess', _22 => _22.allowDeviceSelection]);
962
- if (autoInstallApp === void 0 && passphraseState === void 0 && useEmptyPassphrase === void 0 && operationId === void 0 && knownConnections === void 0 && extra === void 0 && allowDeviceSelection === void 0) {
887
+ const autoInstallApp = _optionalChain([commonParams, 'optionalAccess', _15 => _15.autoInstallApp]);
888
+ const passphraseState = _optionalChain([commonParams, 'optionalAccess', _16 => _16.passphraseState]);
889
+ const useEmptyPassphrase = _optionalChain([commonParams, 'optionalAccess', _17 => _17.useEmptyPassphrase]);
890
+ if (autoInstallApp === void 0 && passphraseState === void 0 && useEmptyPassphrase === void 0) {
963
891
  return item;
964
892
  }
965
893
  return {
966
894
  ...item,
967
895
  ...autoInstallApp !== void 0 ? { autoInstallApp } : {},
968
896
  ...passphraseState !== void 0 ? { passphraseState } : {},
969
- ...useEmptyPassphrase !== void 0 ? { useEmptyPassphrase } : {},
970
- ...operationId !== void 0 ? { operationId } : {},
971
- ...knownConnections !== void 0 ? { knownConnections } : {},
972
- ...extra !== void 0 ? { extra } : {},
973
- ...allowDeviceSelection !== void 0 ? { allowDeviceSelection } : {}
897
+ ...useEmptyPassphrase !== void 0 ? { useEmptyPassphrase } : {}
974
898
  };
975
899
  }
976
900
  static _normalizeLogKey(key) {
@@ -1026,8 +950,8 @@ var _TrezorAdapter = class _TrezorAdapter {
1026
950
  };
1027
951
  }
1028
952
  static _trezorFailureMessage(error) {
1029
- const response = _optionalChain([error, 'optionalAccess', _23 => _23.response]);
1030
- const message = _optionalChain([response, 'optionalAccess', _24 => _24.message]);
953
+ const response = _optionalChain([error, 'optionalAccess', _18 => _18.response]);
954
+ const message = _optionalChain([response, 'optionalAccess', _19 => _19.message]);
1031
955
  if (!message || typeof message !== "object") return {};
1032
956
  const failureMessage = message;
1033
957
  return {
@@ -1036,7 +960,7 @@ var _TrezorAdapter = class _TrezorAdapter {
1036
960
  };
1037
961
  }
1038
962
  static _mapTrezorFailureCode(error) {
1039
- const directCode = _optionalChain([error, 'optionalAccess', _25 => _25.code]);
963
+ const directCode = _optionalChain([error, 'optionalAccess', _20 => _20.code]);
1040
964
  if (directCode === "Device_InitializeFailed") {
1041
965
  return _hwkadaptercore.HardwareErrorCode.PinCancelled;
1042
966
  }
@@ -1049,7 +973,7 @@ var _TrezorAdapter = class _TrezorAdapter {
1049
973
  if (directCode === "Failure_UnexpectedMessage") {
1050
974
  return _hwkadaptercore.HardwareErrorCode.MethodNotSupported;
1051
975
  }
1052
- const message = _optionalChain([error, 'optionalAccess', _26 => _26.message]);
976
+ const message = _optionalChain([error, 'optionalAccess', _21 => _21.message]);
1053
977
  if (typeof message === "string" && message.includes("Failed to execute 'transfer") && message.includes("on 'USBDevice'")) {
1054
978
  return _hwkadaptercore.HardwareErrorCode.TransportError;
1055
979
  }
@@ -1094,11 +1018,13 @@ var _TrezorAdapter = class _TrezorAdapter {
1094
1018
  * selected is gone (the device evicted it from its limited slot pool). The
1095
1019
  * caller drops the stale cache entry and recreates from scratch.
1096
1020
  *
1097
- * Match only the protocol's explicit unallocated-channel code. Guessing from
1098
- * an error message could replay a request after an unrelated business error.
1021
+ * NOTE: the exact eviction code still needs real-device confirmation — match
1022
+ * conservatively so a genuine error isn't mistaken for an evicted session
1023
+ * (which would silently re-prompt the passphrase).
1099
1024
  */
1100
1025
  static _isStaleSessionError(code) {
1101
- return code === "ThpUnallocatedChannel";
1026
+ if (typeof code !== "string") return false;
1027
+ return code === "ThpUnallocatedChannel" || /invalid.?session|unallocated.?session|session.?not.?found/i.test(code);
1102
1028
  }
1103
1029
  static _errorCode(error) {
1104
1030
  return _nullishCoalesce(error.code, () => ( _TrezorAdapter._trezorFailureMessage(error).code));
@@ -1112,13 +1038,13 @@ var _TrezorAdapter = class _TrezorAdapter {
1112
1038
  return protocolError.name === "TrezorProtocolError" && protocolError.code === "Malformed protocol format" && protocolError.message === "Malformed protocol format";
1113
1039
  }
1114
1040
  /**
1115
- * Race a promise against an abort signal. IConnector.call() can't actually
1116
- * be cancelled at the protocol level, so the caller gets the abort while the
1117
- * adapter keeps the transport exclusively reserved until the raw call drains.
1041
+ * Race a promise against an abort signal. Copied from LedgerAdapter:
1042
+ * IConnector.call() can't actually be cancelled at the protocol level, but
1043
+ * the caller gets the abort immediately and the underlying work completes
1044
+ * uselessly in the background.
1118
1045
  */
1119
1046
  static _abortable(signal, promise) {
1120
1047
  if (signal.aborted) {
1121
- void promise.catch(() => void 0);
1122
1048
  return Promise.reject(
1123
1049
  _nullishCoalesce(signal.reason, () => ( new Error("Aborted")))
1124
1050
  );
@@ -1140,37 +1066,17 @@ var _TrezorAdapter = class _TrezorAdapter {
1140
1066
  );
1141
1067
  });
1142
1068
  }
1143
- async _connectSession(connectId, signal, stateGeneration, transportType) {
1069
+ async _connectSession(connectId, signal) {
1144
1070
  const connectOnce = async () => {
1145
- if (_optionalChain([signal, 'optionalAccess', _27 => _27.aborted])) {
1146
- throw _nullishCoalesce(signal.reason, () => ( new Error("Aborted")));
1147
- }
1148
- this._assertConnectorIdle("connectDevice");
1149
- const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
1150
- let connectPromise;
1151
- try {
1152
- connectPromise = transportType ? this._connector.connect(connectId, { transportType }) : this._connector.connect(connectId);
1153
- } catch (error) {
1154
- releaseOperation();
1155
- throw error;
1156
- }
1157
- if (!signal) {
1158
- try {
1159
- return await connectPromise;
1160
- } finally {
1161
- releaseOperation();
1162
- }
1163
- }
1071
+ const connectPromise = this._connector.connect(connectId);
1072
+ if (!signal) return connectPromise;
1164
1073
  try {
1165
- const session2 = await _TrezorAdapter._abortable(signal, connectPromise);
1166
- releaseOperation();
1167
- return session2;
1074
+ return await _TrezorAdapter._abortable(signal, connectPromise);
1168
1075
  } catch (error) {
1169
- if (signal.aborted) {
1170
- void connectPromise.then((orphan) => this._connector.disconnect(orphan.sessionId).catch(() => void 0)).catch(() => void 0).finally(releaseOperation);
1171
- } else {
1172
- releaseOperation();
1173
- }
1076
+ void connectPromise.then(
1077
+ (orphan) => this._connector.disconnect(orphan.sessionId).catch(() => void 0),
1078
+ () => void 0
1079
+ );
1174
1080
  throw error;
1175
1081
  }
1176
1082
  };
@@ -1178,7 +1084,7 @@ var _TrezorAdapter = class _TrezorAdapter {
1178
1084
  try {
1179
1085
  session = await connectOnce();
1180
1086
  } catch (error) {
1181
- if (_optionalChain([signal, 'optionalAccess', _28 => _28.aborted]) || !_TrezorAdapter._isRecoverableProtocolResidueError(error)) {
1087
+ if (_optionalChain([signal, 'optionalAccess', _22 => _22.aborted]) || !_TrezorAdapter._isRecoverableProtocolResidueError(error)) {
1182
1088
  throw error;
1183
1089
  }
1184
1090
  debugLog("[TrezorAdapter] retrying connect after draining a stale THP frame", {
@@ -1186,13 +1092,8 @@ var _TrezorAdapter = class _TrezorAdapter {
1186
1092
  });
1187
1093
  session = await connectOnce();
1188
1094
  }
1189
- if (stateGeneration !== this._stateGeneration || this._disconnectRequested.delete(connectId)) {
1190
- const releaseCleanup = this._retainConnectorOperation(`disconnect:${session.sessionId}`);
1191
- try {
1192
- await this._connector.disconnect(session.sessionId).catch(() => void 0);
1193
- } finally {
1194
- releaseCleanup();
1195
- }
1095
+ if (this._disconnectRequested.delete(connectId)) {
1096
+ await this._connector.disconnect(session.sessionId).catch(() => void 0);
1196
1097
  throw Object.assign(new Error("Trezor connection aborted"), {
1197
1098
  code: _hwkadaptercore.HardwareErrorCode.UserAborted
1198
1099
  });
@@ -1208,9 +1109,14 @@ var _TrezorAdapter = class _TrezorAdapter {
1208
1109
  async init(_config) {
1209
1110
  }
1210
1111
  async dispose() {
1211
- await this._resetStateAndDisconnectSessions();
1212
1112
  this._unregisterConnectorEvents();
1113
+ this._uiRegistry.reset();
1114
+ this._jobQueue.clear();
1213
1115
  this._connector.reset();
1116
+ this._devices.clear();
1117
+ this._sessions.clear();
1118
+ this._verifiedPassphraseSessionsByConnectId.clear();
1119
+ this._connectingPromises.clear();
1214
1120
  this._emitter.removeAllListeners();
1215
1121
  }
1216
1122
  /**
@@ -1219,30 +1125,12 @@ var _TrezorAdapter = class _TrezorAdapter {
1219
1125
  * error flows. Aborts active jobs and releases UI waits.
1220
1126
  */
1221
1127
  resetState() {
1222
- void this._resetStateAndDisconnectSessions();
1223
- }
1224
- _resetStateAndDisconnectSessions() {
1225
- if (this._resetPromise) return this._resetPromise;
1226
- const sessionIds = new Set(this._sessions.values());
1227
- this._stateGeneration += 1;
1228
- this._operations.endAll("runtime-reset");
1229
1128
  this._uiRegistry.reset();
1230
1129
  this._jobQueue.clear();
1231
1130
  this._devices.clear();
1232
1131
  this._sessions.clear();
1233
1132
  this._verifiedPassphraseSessionsByConnectId.clear();
1234
1133
  this._connectingPromises.clear();
1235
- const resetPromise = this._runConnectorTeardown(async () => {
1236
- for (const sessionId of sessionIds) {
1237
- await this._connector.disconnect(sessionId).catch(() => void 0);
1238
- }
1239
- });
1240
- this._resetPromise = resetPromise;
1241
- return resetPromise.finally(() => {
1242
- if (this._resetPromise === resetPromise) {
1243
- this._resetPromise = null;
1244
- }
1245
- });
1246
1134
  }
1247
1135
  getAvailableTransports() {
1248
1136
  return this.activeTransport ? [this.activeTransport] : [];
@@ -1250,152 +1138,32 @@ var _TrezorAdapter = class _TrezorAdapter {
1250
1138
  async switchTransport(_type) {
1251
1139
  }
1252
1140
  async searchDevices(options) {
1253
- return this._searchDevices(options);
1254
- }
1255
- async _searchDevices(options, signal) {
1256
- if (_optionalChain([options, 'optionalAccess', _29 => _29.transportType]) && !(_nullishCoalesce(this._connector.availableTransports, () => ( [this._connector.connectionType]))).includes(
1257
- options.transportType
1258
- ))
1259
- return [];
1260
- if (_optionalChain([options, 'optionalAccess', _30 => _30.resetSession])) {
1261
- await this._resetStateAndDisconnectSessions();
1262
- } else {
1263
- await this._connectorTeardownTail;
1264
- }
1265
- if (_optionalChain([signal, 'optionalAccess', _31 => _31.aborted])) throw signal.reason;
1266
- const stateGeneration = this._stateGeneration;
1141
+ await this._ensureDevicePermission();
1267
1142
  const scanned = await this._connector.searchDevices(
1268
- _optionalChain([options, 'optionalAccess', _32 => _32.waitForAllTransports]) || _optionalChain([options, 'optionalAccess', _33 => _33.transportType]) ? {
1269
- ...options.waitForAllTransports ? { waitForAll: true } : {},
1270
- ...options.transportType ? { transportType: options.transportType } : {}
1271
- } : void 0
1143
+ _optionalChain([options, 'optionalAccess', _23 => _23.waitForAllTransports]) ? { waitForAll: true } : void 0
1272
1144
  );
1273
- if (_optionalChain([signal, 'optionalAccess', _34 => _34.aborted])) throw signal.reason;
1274
- if (stateGeneration !== this._stateGeneration) {
1275
- throw _hwkadaptercore.createHwkError.call(void 0, {
1276
- code: _hwkadaptercore.HardwareErrorCode.UserAborted,
1277
- message: "Trezor discovery belongs to an ended operation"
1278
- });
1279
- }
1280
1145
  const scannedIds = new Set(scanned.map((d) => d.connectId));
1281
1146
  for (const connectId of [...this._devices.keys()]) {
1282
- if ((!_optionalChain([options, 'optionalAccess', _35 => _35.transportType]) || _optionalChain([this, 'access', _36 => _36._devices, 'access', _37 => _37.get, 'call', _38 => _38(connectId), 'optionalAccess', _39 => _39.connectionType]) === options.transportType) && !scannedIds.has(connectId) && !this._sessions.has(connectId)) {
1147
+ if (!scannedIds.has(connectId) && !this._sessions.has(connectId)) {
1283
1148
  this._devices.delete(connectId);
1284
1149
  }
1285
1150
  }
1286
1151
  for (const device of scanned) {
1287
1152
  const info = this._connectorDeviceToDeviceInfo(device);
1288
- if (!this._sessions.has(info.connectId)) this._devices.set(info.connectId, info);
1153
+ this._devices.set(info.connectId, info);
1289
1154
  }
1290
- return Array.from(this._devices.values()).filter(
1291
- (device) => !_optionalChain([options, 'optionalAccess', _40 => _40.transportType]) || device.connectionType === options.transportType
1292
- );
1155
+ return Array.from(this._devices.values());
1293
1156
  }
1294
- async searchDeviceTargets(options) {
1295
- const devices = await this.searchDevices(options);
1296
- return devices.map((device) => ({
1297
- searchTargetId: device.connectId,
1298
- searchTargetReusePolicy: _hwkadaptercore.resolveSearchTargetReusePolicy.call(void 0, device),
1299
- vendor: "trezor",
1300
- connectionType: device.connectionType,
1301
- kind: "physical",
1302
- label: device.label,
1303
- model: device.model,
1304
- modelName: device.modelName,
1305
- serialNumber: device.serialNumber
1306
- }));
1307
- }
1308
- async listConnectionTargets(options) {
1309
- const targets = await this.searchDeviceTargets(options);
1310
- return targets.map(({ searchTargetId, ...target }) => ({
1311
- ...target,
1312
- targetId: searchTargetId
1313
- }));
1314
- }
1315
- async bindBleDevice(params) {
1316
- if (params.identity.vendor !== "trezor" || !params.identity.value) {
1317
- return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.InvalidParams, "Trezor device identity is required");
1318
- }
1319
- const { value: deviceId } = params.identity;
1157
+ async connectDevice(connectId) {
1320
1158
  try {
1321
- return await this._jobQueue.enqueue(
1322
- deviceId,
1323
- async (signal) => {
1324
- const selected = await this._selectBleDeviceForBinding(
1325
- deviceId,
1326
- signal,
1327
- { extra: params.extra },
1328
- "manual-rebind"
1329
- );
1330
- try {
1331
- const persisted = await this._emitVerifiedBinding(
1332
- deviceId,
1333
- selected.connectId,
1334
- selected.selectionRequestId,
1335
- { extra: params.extra },
1336
- signal
1337
- );
1338
- if (!persisted) {
1339
- throw _hwkadaptercore.createHwkError.call(void 0, {
1340
- code: _hwkadaptercore.HardwareErrorCode.UnknownError,
1341
- message: "Bluetooth binding could not be saved",
1342
- origin: "host"
1343
- });
1344
- }
1345
- this._rememberVerifiedConnection(deviceId, selected.connectId);
1346
- return _hwkadaptercore.success.call(void 0, selected.connectId);
1347
- } catch (error) {
1348
- await this._releaseProvisionalConnection(selected.connectId, signal);
1349
- throw error;
1350
- }
1351
- },
1352
- {
1353
- label: "bindBleDevice",
1354
- rejectIfBusy: true,
1355
- busyError: _TrezorAdapter._createDeviceBusyError("bindBleDevice")
1356
- }
1357
- );
1159
+ await this._ensureDevicePermission(connectId);
1160
+ await this._ensureSession(connectId);
1161
+ return _hwkadaptercore.success.call(void 0, connectId);
1358
1162
  } catch (error) {
1359
1163
  return this._errorToFailure(error);
1360
1164
  }
1361
1165
  }
1362
- async connectDevice(searchTargetId) {
1363
- try {
1364
- await this._ensureDevicePermission(
1365
- searchTargetId,
1366
- void 0,
1367
- _optionalChain([this, 'access', _41 => _41._devices, 'access', _42 => _42.get, 'call', _43 => _43(searchTargetId), 'optionalAccess', _44 => _44.connectionType])
1368
- );
1369
- await this._ensureSession(searchTargetId);
1370
- const device = this._devices.get(searchTargetId);
1371
- if (!device) {
1372
- return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.DeviceNotFound, "Trezor device not found after connect");
1373
- }
1374
- this._operations.endByConnectionKey(searchTargetId, "explicit");
1375
- const operation = this._operations.create({
1376
- searchTargetId,
1377
- connectId: searchTargetId,
1378
- device,
1379
- connectionType: device.connectionType,
1380
- connectionKeys: [_nullishCoalesce(this._sessions.get(searchTargetId), () => ( ""))]
1381
- });
1382
- return _hwkadaptercore.success.call(void 0, operation.operationId);
1383
- } catch (error) {
1384
- return this._errorToFailure(error);
1385
- }
1386
- }
1387
- async releaseOperation(operationId) {
1388
- const operation = this._operations.find(operationId);
1389
- if (!operation) {
1390
- this._operations.resolve(operationId);
1391
- return;
1392
- }
1393
- const endedOperation = this._operations.end(operationId, "explicit");
1394
- if (!endedOperation) return;
1395
- await this._releaseOperationConnection(endedOperation);
1396
- }
1397
- async _releaseOperationConnection(operation) {
1398
- const { connectId } = operation;
1166
+ async disconnectDevice(connectId) {
1399
1167
  const connecting = this._connectingPromises.has(connectId);
1400
1168
  this._connectingPromises.delete(connectId);
1401
1169
  const sessionId = this._sessions.get(connectId);
@@ -1405,132 +1173,88 @@ var _TrezorAdapter = class _TrezorAdapter {
1405
1173
  }
1406
1174
  this._sessions.delete(connectId);
1407
1175
  this._verifiedPassphraseSessionsByConnectId.delete(connectId);
1408
- await this._runConnectorTeardown(() => this._connector.disconnect(sessionId));
1176
+ await this._connector.disconnect(sessionId);
1409
1177
  }
1410
- async getDeviceInfo(connectIdOrOperationId, deviceId) {
1411
- let connectId;
1412
- try {
1413
- connectId = _hwkadaptercore.isHardwareOperationId.call(void 0, connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1414
- } catch (error) {
1415
- return this._errorToFailure(error);
1416
- }
1178
+ async getDeviceInfo(connectId, deviceId) {
1417
1179
  const device = _nullishCoalesce(this._devices.get(connectId), () => ( Array.from(this._devices.values()).find((item) => item.deviceId === deviceId)));
1418
1180
  if (!device) return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.DeviceNotFound, "Trezor device not found");
1419
1181
  return _hwkadaptercore.success.call(void 0, device);
1420
1182
  }
1183
+ getSupportedChains() {
1184
+ return ["btc", "evm", "sol", "tron"];
1185
+ }
1421
1186
  async allNetworkGetAddress(connectId, deviceId, params) {
1422
- const target = _hwkadaptercore.resolveHardwareOperationTarget.call(void 0, connectId, params.operationId, "trezor");
1423
- if (!target.success) return target;
1424
- let effectiveTargetId = _nullishCoalesce(target.payload.targetId, () => ( ""));
1425
- let releaseOperationRetention;
1426
- try {
1427
- releaseOperationRetention = target.payload.operationId ? this._operations.retain(target.payload.operationId) : void 0;
1428
- } catch (error) {
1429
- return this._errorToFailure(error);
1430
- }
1431
- const cancelScope = this._jobQueue.createCancelScope(
1432
- trezorQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
1433
- );
1434
1187
  let liveDeviceId = "";
1435
- const bundleContext = {};
1436
1188
  const topLevelFailureIndexes = /* @__PURE__ */ new Set();
1437
1189
  const isSingleNetworkBundle = params.bundle.every(
1438
- (item) => item.network === _optionalChain([params, 'access', _45 => _45.bundle, 'access', _46 => _46[0], 'optionalAccess', _47 => _47.network])
1190
+ (item) => item.network === _optionalChain([params, 'access', _24 => _24.bundle, 'access', _25 => _25[0], 'optionalAccess', _26 => _26.network])
1439
1191
  );
1440
- const getLiveDeviceId = async (expectedDeviceId) => {
1192
+ const getLiveDeviceId = async () => {
1441
1193
  if (liveDeviceId) return _hwkadaptercore.success.call(void 0, liveDeviceId);
1442
- const deviceIdResponse = await this._getTrezorDeviceId(
1443
- effectiveTargetId,
1444
- expectedDeviceId || deviceId,
1445
- params,
1446
- bundleContext
1447
- );
1194
+ const deviceIdResponse = await this._getTrezorDeviceId(connectId);
1448
1195
  if (deviceIdResponse.success) {
1449
1196
  liveDeviceId = deviceIdResponse.payload;
1450
- if (!target.payload.operationId) {
1451
- effectiveTargetId = _nullishCoalesce(_optionalChain([bundleContext, 'access', _48 => _48.connection, 'optionalAccess', _49 => _49.connectId]), () => ( effectiveTargetId));
1452
- }
1453
1197
  }
1454
1198
  return deviceIdResponse;
1455
1199
  };
1456
- try {
1457
- return await _hwkadaptercore.runAllNetworkGetAddress.call(void 0, {
1458
- connectId: effectiveTargetId,
1459
- deviceId,
1460
- params,
1461
- normalizeItem: _TrezorAdapter._normalizeAllNetworkItem,
1462
- callItem: async ({ method, item, index }) => {
1463
- if (cancelScope.signal.aborted) {
1200
+ return _hwkadaptercore.runAllNetworkGetAddress.call(void 0, {
1201
+ connectId,
1202
+ deviceId,
1203
+ params,
1204
+ normalizeItem: _TrezorAdapter._normalizeAllNetworkItem,
1205
+ callItem: async ({ method, item, index }) => {
1206
+ const expectedDeviceId = _nullishCoalesce(_TrezorAdapter._getItemDeviceId(item), () => ( deviceId));
1207
+ if (expectedDeviceId) {
1208
+ const fingerprint = await getLiveDeviceId();
1209
+ if (!fingerprint.success) {
1464
1210
  topLevelFailureIndexes.add(index);
1465
- return _TrezorAdapter._buildCancelledFailure(cancelScope.signal);
1211
+ return fingerprint;
1466
1212
  }
1467
- const expectedDeviceId = _nullishCoalesce(_TrezorAdapter._getItemDeviceId(item), () => ( deviceId));
1468
- if (expectedDeviceId) {
1469
- const fingerprint = await getLiveDeviceId(expectedDeviceId);
1470
- if (!fingerprint.success) {
1471
- topLevelFailureIndexes.add(index);
1472
- return fingerprint;
1473
- }
1474
- if (expectedDeviceId !== fingerprint.payload) {
1475
- topLevelFailureIndexes.add(index);
1476
- return _hwkadaptercore.failure.call(void 0,
1477
- _hwkadaptercore.HardwareErrorCode.DeviceMismatch,
1478
- `Wrong device: expected ${expectedDeviceId}, got ${fingerprint.payload}`,
1479
- { expected: expectedDeviceId, actual: fingerprint.payload }
1480
- );
1481
- }
1213
+ if (expectedDeviceId !== fingerprint.payload) {
1214
+ topLevelFailureIndexes.add(index);
1215
+ return _hwkadaptercore.failure.call(void 0,
1216
+ _hwkadaptercore.HardwareErrorCode.DeviceMismatch,
1217
+ `Wrong device: expected ${expectedDeviceId}, got ${fingerprint.payload}`,
1218
+ { expected: expectedDeviceId, actual: fingerprint.payload }
1219
+ );
1482
1220
  }
1483
- const callItem = _TrezorAdapter._withAllNetworkRequestCommonParams(item, params);
1484
- return this._callAllNetworkMethod(effectiveTargetId, method, callItem, bundleContext);
1485
- },
1486
- attachIdentity: async ({ item, chain, payload, index }) => {
1487
- if (!liveDeviceId) {
1488
- if (cancelScope.signal.aborted) {
1489
- topLevelFailureIndexes.add(index);
1490
- const cancelled = _TrezorAdapter._buildCancelledFailure(cancelScope.signal);
1491
- return { ...item, success: false, payload: cancelled.payload };
1492
- }
1493
- const fingerprint = await getLiveDeviceId(deviceId);
1494
- if (!fingerprint.success) {
1495
- return { ...item, success: false, payload: fingerprint.payload };
1496
- }
1221
+ }
1222
+ const callItem = _TrezorAdapter._withAllNetworkRequestCommonParams(item, params);
1223
+ return this._callAllNetworkMethod(connectId, method, callItem);
1224
+ },
1225
+ attachIdentity: async ({ item, chain, payload }) => {
1226
+ if (!liveDeviceId) {
1227
+ const fingerprint = await getLiveDeviceId();
1228
+ if (!fingerprint.success) {
1229
+ return { ...item, success: false, payload: fingerprint.payload };
1497
1230
  }
1498
- return {
1499
- ...item,
1500
- success: true,
1501
- payload: {
1502
- ...payload,
1503
- deviceIdentity: {
1504
- vendor: "trezor",
1505
- type: "deviceId",
1506
- value: liveDeviceId
1507
- },
1508
- chainFingerprint: liveDeviceId,
1509
- chainFingerprintChain: chain
1510
- }
1511
- };
1512
- },
1513
- // One named boolean per abort reason.
1514
- shouldAbortBundle: (response, { index }) => {
1515
- const isSessionLevelFailure = topLevelFailureIndexes.has(index);
1516
- const isWholeChainForbidden = isSingleNetworkBundle && _optionalChain([response, 'access', _50 => _50.payload, 'optionalAccess', _51 => _51.code]) === _hwkadaptercore.HardwareErrorCode.DevicePathForbidden;
1517
- const isPassphrasePolicyFailure = _optionalChain([response, 'access', _52 => _52.payload, 'optionalAccess', _53 => _53.code]) === _hwkadaptercore.HardwareErrorCode.PassphraseAlwaysOnDevice;
1518
- const { code } = _nullishCoalesce(response.payload, () => ( {}));
1519
- return isSessionLevelFailure || isWholeChainForbidden || isPassphrasePolicyFailure || _hwkadaptercore.isUserRefusal.call(void 0, code) || _hwkadaptercore.isConnectionLost.call(void 0, code);
1520
1231
  }
1521
- });
1522
- } finally {
1523
- cancelScope.release();
1524
- _optionalChain([releaseOperationRetention, 'optionalCall', _54 => _54()]);
1525
- }
1232
+ return {
1233
+ ...item,
1234
+ success: true,
1235
+ payload: {
1236
+ ...payload,
1237
+ deviceIdentity: {
1238
+ vendor: "trezor",
1239
+ type: "deviceId",
1240
+ value: liveDeviceId
1241
+ },
1242
+ chainFingerprint: liveDeviceId,
1243
+ chainFingerprintChain: chain
1244
+ }
1245
+ };
1246
+ },
1247
+ // One named boolean per abort reason.
1248
+ shouldAbortBundle: (response, { index }) => {
1249
+ const isSessionLevelFailure = topLevelFailureIndexes.has(index);
1250
+ const isWholeChainForbidden = isSingleNetworkBundle && _optionalChain([response, 'access', _27 => _27.payload, 'optionalAccess', _28 => _28.code]) === _hwkadaptercore.HardwareErrorCode.DevicePathForbidden;
1251
+ const isPassphrasePolicyFailure = _optionalChain([response, 'access', _29 => _29.payload, 'optionalAccess', _30 => _30.code]) === _hwkadaptercore.HardwareErrorCode.PassphraseAlwaysOnDevice;
1252
+ return isSessionLevelFailure || isWholeChainForbidden || isPassphrasePolicyFailure;
1253
+ }
1254
+ });
1526
1255
  }
1527
- getFeatures(connectId, operationContext) {
1528
- return this._callDeviceManagerMethod(
1529
- "getFeatures",
1530
- connectId,
1531
- {},
1532
- operationContext
1533
- );
1256
+ getFeatures(connectId) {
1257
+ return this._callDeviceManagerMethod("getFeatures", connectId, {});
1534
1258
  }
1535
1259
  /**
1536
1260
  * Device authenticity attestation. Sends a host-generated challenge, has the
@@ -1565,7 +1289,7 @@ var _TrezorAdapter = class _TrezorAdapter {
1565
1289
  if (!internalModel) {
1566
1290
  return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.UnknownError, "Device internal_model unavailable");
1567
1291
  }
1568
- const challengeHex = _nullishCoalesce(_optionalChain([params, 'access', _55 => _55.challenge, 'optionalAccess', _56 => _56.toLowerCase, 'call', _57 => _57()]), () => ( Buffer.from(_utils.randomBytes.call(void 0, 32)).toString("hex")));
1292
+ const challengeHex = _nullishCoalesce(_optionalChain([params, 'access', _31 => _31.challenge, 'optionalAccess', _32 => _32.toLowerCase, 'call', _33 => _33()]), () => ( Buffer.from(_utils.randomBytes.call(void 0, 32)).toString("hex")));
1569
1293
  const challenge = Buffer.from(challengeHex, "hex");
1570
1294
  const proofRes = await this._callDeviceManagerMethod(
1571
1295
  "authenticateDevice",
@@ -1590,64 +1314,28 @@ var _TrezorAdapter = class _TrezorAdapter {
1590
1314
  }
1591
1315
  });
1592
1316
  }
1593
- deviceSettings(connectId, params, operationContext) {
1317
+ deviceSettings(connectId, params) {
1594
1318
  return this._callDeviceManagerMethod(
1595
1319
  "deviceSettings",
1596
1320
  connectId,
1597
- params,
1598
- operationContext
1321
+ params
1599
1322
  );
1600
1323
  }
1601
- setBrightness(connectId, params = {}, operationContext) {
1324
+ setBrightness(connectId, params = {}) {
1602
1325
  return this._callDeviceManagerMethod(
1603
1326
  "setBrightness",
1604
1327
  connectId,
1605
- params,
1606
- operationContext
1328
+ params
1607
1329
  );
1608
1330
  }
1609
- changePin(connectId, params = {}, operationContext) {
1610
- return this._callDeviceManagerMethod(
1611
- "changePin",
1612
- connectId,
1613
- params,
1614
- operationContext
1615
- );
1331
+ changePin(connectId, params = {}) {
1332
+ return this._callDeviceManagerMethod("changePin", connectId, params);
1616
1333
  }
1617
- wipeDevice(connectId, operationContext) {
1618
- return this._callDeviceManagerMethod(
1619
- "wipeDevice",
1620
- connectId,
1621
- {},
1622
- operationContext
1623
- );
1334
+ wipeDevice(connectId) {
1335
+ return this._callDeviceManagerMethod("wipeDevice", connectId, {});
1624
1336
  }
1625
- async _getTrezorDeviceId(connectId, expectedDeviceId, commonParams, bundleContext) {
1626
- const hasConnectionContext = _optionalChain([commonParams, 'optionalAccess', _58 => _58.knownConnections]) !== void 0 || _optionalChain([commonParams, 'optionalAccess', _59 => _59.extra]) !== void 0;
1627
- const features = bundleContext || hasConnectionContext ? await this._callMethod(
1628
- "getFeatures",
1629
- connectId,
1630
- hasConnectionContext || !connectId ? expectedDeviceId : void 0,
1631
- hasConnectionContext ? {
1632
- operationId: commonParams.operationId,
1633
- knownConnections: commonParams.knownConnections,
1634
- extra: commonParams.extra,
1635
- allowDeviceSelection: commonParams.allowDeviceSelection,
1636
- passphraseState: commonParams.passphraseState,
1637
- useEmptyPassphrase: commonParams.useEmptyPassphrase
1638
- } : {},
1639
- false,
1640
- bundleContext
1641
- ) : await this.getFeatures(
1642
- connectId,
1643
- !connectId && expectedDeviceId ? {
1644
- expectedDeviceIdentity: {
1645
- vendor: "trezor",
1646
- type: "deviceId",
1647
- value: expectedDeviceId
1648
- }
1649
- } : void 0
1650
- );
1337
+ async _getTrezorDeviceId(connectId) {
1338
+ const features = await this.getFeatures(connectId);
1651
1339
  if (!features.success) return features;
1652
1340
  const liveDeviceId = features.payload.device_id;
1653
1341
  if (typeof liveDeviceId !== "string" || liveDeviceId.length === 0) {
@@ -1656,67 +1344,23 @@ var _TrezorAdapter = class _TrezorAdapter {
1656
1344
  return _hwkadaptercore.success.call(void 0, liveDeviceId);
1657
1345
  }
1658
1346
  cancel(connectId) {
1659
- if (_hwkadaptercore.isHardwareOperationId.call(void 0, connectId)) {
1660
- try {
1661
- this._operations.resolve(connectId);
1662
- } catch (e5) {
1663
- return;
1664
- }
1665
- }
1666
1347
  const userAbortReason = Object.assign(new Error("User aborted operation"), {
1667
1348
  code: _hwkadaptercore.HardwareErrorCode.UserAborted
1668
1349
  });
1669
- const activeJobId = _optionalChain([this, 'access', _60 => _60._jobQueue, 'access', _61 => _61.getActiveJob, 'call', _62 => _62(), 'optionalAccess', _63 => _63.deviceId]);
1670
- const targetId = _nullishCoalesce(connectId, () => ( activeJobId));
1671
- if (targetId) {
1672
- let resolvedConnectId = targetId;
1673
- let operationId;
1674
- if (_hwkadaptercore.isHardwareOperationId.call(void 0, targetId)) {
1675
- try {
1676
- operationId = targetId;
1677
- resolvedConnectId = this._operations.resolve(targetId).connectId;
1678
- } catch (e6) {
1679
- resolvedConnectId = "";
1680
- }
1681
- }
1682
- const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
1683
- const pendingOperationId = _nullishCoalesce(operationId, () => ( _optionalChain([interactionForPhysicalId, 'optionalAccess', _64 => _64.operationId])));
1684
- if (!connectId) {
1685
- this._uiRegistry.cancel();
1686
- } else if (pendingOperationId) {
1687
- this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
1688
- }
1689
- this._connector.uiResponse({ type: _hwkadaptercore.UI_RESPONSE.CANCEL });
1690
- const queueKeys = /* @__PURE__ */ new Set([trezorQueueKey({ connectId: targetId })]);
1691
- if (pendingOperationId) queueKeys.add(trezorQueueKey({ operationId: pendingOperationId }));
1692
- for (const key of queueKeys) {
1693
- this._jobQueue.cancelActiveAndPending(key, userAbortReason);
1694
- }
1695
- if (resolvedConnectId) {
1696
- void this._connector.cancel(_nullishCoalesce(this._sessions.get(resolvedConnectId), () => ( resolvedConnectId)));
1697
- }
1698
- return;
1699
- }
1700
1350
  this._uiRegistry.cancel();
1701
1351
  this._connector.uiResponse({ type: _hwkadaptercore.UI_RESPONSE.CANCEL });
1702
- this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
1352
+ if (connectId) {
1353
+ this._jobQueue.forceCancelActive(connectId, userAbortReason);
1354
+ void this._connector.cancel(_nullishCoalesce(this._sessions.get(connectId), () => ( connectId)));
1355
+ return;
1356
+ }
1357
+ for (const cid of this._sessions.keys()) {
1358
+ this._jobQueue.forceCancelActive(cid, userAbortReason);
1359
+ }
1703
1360
  for (const sessionId of this._sessions.values()) {
1704
1361
  void this._connector.cancel(sessionId);
1705
1362
  }
1706
1363
  }
1707
- /**
1708
- * The operation the running device job belongs to, so a UI request raised
1709
- * mid-call can name it. A call pinned to an operation queues under its id
1710
- * (`trezorQueueKey`); a call without one queues under the connectId, and the
1711
- * live operation on that connection is still the owner. Only work with no
1712
- * operation at all comes back undefined.
1713
- */
1714
- _activeOperationId() {
1715
- const activeJobId = _optionalChain([this, 'access', _65 => _65._jobQueue, 'access', _66 => _66.getActiveJob, 'call', _67 => _67(), 'optionalAccess', _68 => _68.deviceId]);
1716
- if (!activeJobId) return void 0;
1717
- if (_hwkadaptercore.isHardwareOperationId.call(void 0, activeJobId)) return activeJobId;
1718
- return _optionalChain([this, 'access', _69 => _69._operations, 'access', _70 => _70.findActiveByConnectionKey, 'call', _71 => _71(activeJobId), 'optionalAccess', _72 => _72.operationId]);
1719
- }
1720
1364
  /**
1721
1365
  * Routes to BOTH the adapter's local UI registry (preemption decisions,
1722
1366
  * future SELECT_DEVICE / DEVICE_PERMISSION) AND the connector's registry
@@ -1725,7 +1369,6 @@ var _TrezorAdapter = class _TrezorAdapter {
1725
1369
  */
1726
1370
  uiResponse(response) {
1727
1371
  this._uiRegistry.resolve(response.type, response.payload);
1728
- if (response.type === _hwkadaptercore.UI_RESPONSE.RECEIVE_SELECT_DEVICE) return;
1729
1372
  this._connector.uiResponse(response);
1730
1373
  }
1731
1374
  /**
@@ -1737,8 +1380,8 @@ var _TrezorAdapter = class _TrezorAdapter {
1737
1380
  * Unlike Ledger (which hashes a per-chain address), it is chain-global, so
1738
1381
  * `chain` is accepted for API parity but ignored.
1739
1382
  */
1740
- async getChainFingerprint(connectId, deviceId, _chain) {
1741
- return this._getTrezorDeviceId(connectId, deviceId);
1383
+ async getChainFingerprint(connectId, _deviceId, _chain) {
1384
+ return this._getTrezorDeviceId(connectId);
1742
1385
  }
1743
1386
  /**
1744
1387
  * Resolve the active passphrase wallet identity (`passphraseState`).
@@ -1748,93 +1391,17 @@ var _TrezorAdapter = class _TrezorAdapter {
1748
1391
  * can't interleave with a chain call on the same device (which would desync
1749
1392
  * the THP session selection).
1750
1393
  */
1751
- getPassphraseState(connectId, passphraseState, operationContext) {
1752
- const expectedIdentity = _optionalChain([operationContext, 'optionalAccess', _73 => _73.expectedDeviceIdentity]);
1753
- if (expectedIdentity && (expectedIdentity.vendor !== "trezor" || expectedIdentity.type !== "deviceId")) {
1754
- return Promise.resolve(
1755
- _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.InvalidParams, "Trezor device identity is required")
1756
- );
1757
- }
1758
- const target = _hwkadaptercore.resolveHardwareOperationTarget.call(void 0,
1759
- connectId,
1760
- _optionalChain([operationContext, 'optionalAccess', _74 => _74.operationId]),
1761
- "trezor"
1762
- );
1763
- if (!target.success) return Promise.resolve(target);
1764
- const { operationId } = target.payload;
1765
- let resolvedConnectId = _nullishCoalesce(target.payload.targetId, () => ( ""));
1766
- let releaseOperationRetention;
1767
- if (operationId) {
1768
- try {
1769
- resolvedConnectId = this._operations.resolve(operationId).connectId;
1770
- releaseOperationRetention = this._operations.retain(operationId);
1771
- } catch (error) {
1772
- return Promise.resolve(this._errorToFailure(error));
1773
- }
1774
- }
1394
+ getPassphraseState(connectId, passphraseState) {
1775
1395
  return this._jobQueue.enqueue(
1776
- trezorQueueKey({ operationId, connectId: resolvedConnectId }),
1396
+ connectId,
1777
1397
  async (signal) => {
1778
- let selectionRequestId;
1779
- let verified = false;
1398
+ const restorePassphraseRequestContext = this._setPassphraseRequestContext(connectId, {
1399
+ passphraseState
1400
+ });
1780
1401
  try {
1781
- if (!operationId && _optionalChain([expectedIdentity, 'optionalAccess', _75 => _75.value]) && (!connectId || _optionalChain([operationContext, 'optionalAccess', _76 => _76.knownConnections]) !== void 0)) {
1782
- const resolved = await this._resolveExpectedDeviceConnectId(
1783
- expectedIdentity.value,
1784
- signal,
1785
- operationContext
1786
- );
1787
- resolvedConnectId = resolved.connectId;
1788
- selectionRequestId = resolved.selectionRequestId;
1789
- }
1790
- if (_optionalChain([expectedIdentity, 'optionalAccess', _77 => _77.value])) {
1791
- if (!operationId) await this._ensureSession(resolvedConnectId, signal);
1792
- if (_optionalChain([this, 'access', _78 => _78._devices, 'access', _79 => _79.get, 'call', _80 => _80(resolvedConnectId), 'optionalAccess', _81 => _81.deviceId]) !== expectedIdentity.value) {
1793
- return _hwkadaptercore.failure.call(void 0,
1794
- _hwkadaptercore.HardwareErrorCode.DeviceMismatch,
1795
- "Trezor device identity does not match"
1796
- );
1797
- }
1798
- }
1799
- const restorePassphraseRequestContext = this._setPassphraseRequestContext(
1800
- resolvedConnectId,
1801
- {
1802
- passphraseState
1803
- }
1804
- );
1805
- try {
1806
- const result = await this._resolvePassphraseState(
1807
- resolvedConnectId,
1808
- passphraseState,
1809
- signal,
1810
- operationId
1811
- );
1812
- if (result.success && _optionalChain([expectedIdentity, 'optionalAccess', _82 => _82.value])) {
1813
- await this._emitVerifiedBinding(
1814
- expectedIdentity.value,
1815
- resolvedConnectId,
1816
- selectionRequestId,
1817
- operationContext,
1818
- signal
1819
- );
1820
- verified = true;
1821
- this._rememberVerifiedConnection(expectedIdentity.value, resolvedConnectId);
1822
- }
1823
- return result;
1824
- } finally {
1825
- restorePassphraseRequestContext();
1826
- }
1402
+ return await this._resolvePassphraseState(connectId, passphraseState, signal);
1827
1403
  } finally {
1828
- if (selectionRequestId && !verified) {
1829
- this._emitter.emit(_hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS, {
1830
- type: _hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS,
1831
- payload: {
1832
- selectionRequestId,
1833
- status: signal.aborted ? "cancelled" : "failed"
1834
- }
1835
- });
1836
- await this._releaseProvisionalConnection(resolvedConnectId, signal);
1837
- }
1404
+ restorePassphraseRequestContext();
1838
1405
  }
1839
1406
  },
1840
1407
  {
@@ -1842,7 +1409,7 @@ var _TrezorAdapter = class _TrezorAdapter {
1842
1409
  rejectIfBusy: true,
1843
1410
  busyError: _TrezorAdapter._createDeviceBusyError("getPassphraseState")
1844
1411
  }
1845
- ).catch((error) => this._errorToFailure(error)).finally(() => _optionalChain([releaseOperationRetention, 'optionalCall', _83 => _83()]));
1412
+ ).catch((error) => this._errorToFailure(error));
1846
1413
  }
1847
1414
  evmGetAddress(connectId, deviceId, params) {
1848
1415
  return this._callWalletMethod("evmGetAddress", connectId, deviceId, params);
@@ -1905,86 +1472,11 @@ var _TrezorAdapter = class _TrezorAdapter {
1905
1472
  }
1906
1473
  return result;
1907
1474
  }
1908
- async _callConnector(sessionId, method, params, signal) {
1909
- if (_optionalChain([signal, 'optionalAccess', _84 => _84.aborted])) {
1910
- throw _nullishCoalesce(signal.reason, () => ( new Error("Aborted")));
1911
- }
1912
- this._assertConnectorIdle(method);
1913
- const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
1914
- let promise;
1915
- try {
1916
- promise = this._connector.call(sessionId, method, params).finally(() => {
1917
- releaseOperation();
1918
- });
1919
- } catch (error) {
1920
- releaseOperation();
1921
- throw error;
1922
- }
1475
+ static async _callConnector(connector, sessionId, method, params, signal) {
1476
+ const promise = connector.call(sessionId, method, params);
1923
1477
  const result = signal ? await _TrezorAdapter._abortable(signal, promise) : await promise;
1924
1478
  return _TrezorAdapter._unwrapConnectorResult(result);
1925
1479
  }
1926
- _assertConnectorIdle(method) {
1927
- if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
1928
- throw _TrezorAdapter._createDeviceBusyError(method);
1929
- }
1930
- }
1931
- _runConnectorTeardown(task) {
1932
- const previous = this._connectorTeardownTail;
1933
- let releaseTail = () => void 0;
1934
- this._connectorTeardownTail = new Promise((resolve) => {
1935
- releaseTail = resolve;
1936
- });
1937
- this._pendingConnectorTeardowns += 1;
1938
- return (async () => {
1939
- try {
1940
- await previous;
1941
- await this._waitForConnectorOperationsToDrain();
1942
- await task();
1943
- } finally {
1944
- this._pendingConnectorTeardowns -= 1;
1945
- releaseTail();
1946
- }
1947
- })();
1948
- }
1949
- async _releaseProvisionalConnection(connectId, signal) {
1950
- const sessionId = this._sessions.get(connectId);
1951
- this._sessions.delete(connectId);
1952
- this._verifiedPassphraseSessionsByConnectId.delete(connectId);
1953
- if (!sessionId) return;
1954
- const teardown = this._runConnectorTeardown(() => this._connector.disconnect(sessionId)).catch(
1955
- () => void 0
1956
- );
1957
- if (!signal.aborted) await teardown;
1958
- }
1959
- _waitForConnectorOperationsToDrain() {
1960
- if (this._unsettledConnectorOperations.size === 0) {
1961
- return Promise.resolve();
1962
- }
1963
- return new Promise((resolve) => {
1964
- this._connectorIdleWaiters.add(resolve);
1965
- });
1966
- }
1967
- _retainConnectorOperation(key) {
1968
- this._unsettledConnectorOperations.set(
1969
- key,
1970
- (_nullishCoalesce(this._unsettledConnectorOperations.get(key), () => ( 0))) + 1
1971
- );
1972
- let released = false;
1973
- return () => {
1974
- if (released) return;
1975
- released = true;
1976
- const remaining = (_nullishCoalesce(this._unsettledConnectorOperations.get(key), () => ( 1))) - 1;
1977
- if (remaining > 0) {
1978
- this._unsettledConnectorOperations.set(key, remaining);
1979
- } else {
1980
- this._unsettledConnectorOperations.delete(key);
1981
- }
1982
- if (this._unsettledConnectorOperations.size === 0) {
1983
- for (const resolve of this._connectorIdleWaiters) resolve();
1984
- this._connectorIdleWaiters.clear();
1985
- }
1986
- };
1987
- }
1988
1480
  static _normalizeAllNetworkItem(method, item) {
1989
1481
  if (method !== "btcGetAddress" && method !== "btcGetPublicKey") {
1990
1482
  return item;
@@ -2003,21 +1495,18 @@ var _TrezorAdapter = class _TrezorAdapter {
2003
1495
  const { deviceId } = item;
2004
1496
  return typeof deviceId === "string" && deviceId.length > 0 ? deviceId : void 0;
2005
1497
  }
2006
- /** UserAborted is a top-level abort code, so this ends the bundle. */
2007
- static _buildCancelledFailure(signal) {
2008
- const reason = signal.reason;
2009
- const code = typeof _optionalChain([reason, 'optionalAccess', _85 => _85.code]) === "number" ? reason.code : _hwkadaptercore.HardwareErrorCode.UserAborted;
2010
- const message = typeof _optionalChain([reason, 'optionalAccess', _86 => _86.message]) === "string" ? reason.message : "";
2011
- return _hwkadaptercore.failure.call(void 0, code, message || "All-network get-address cancelled");
2012
- }
2013
- _callAllNetworkMethod(connectId, method, item, bundleContext) {
1498
+ _callAllNetworkMethod(connectId, method, item) {
2014
1499
  switch (method) {
2015
1500
  case "evmGetAddress":
1501
+ return this.evmGetAddress(connectId, "", item);
2016
1502
  case "btcGetAddress":
1503
+ return this.btcGetAddress(connectId, "", item);
2017
1504
  case "btcGetPublicKey":
1505
+ return this.btcGetPublicKey(connectId, "", item);
2018
1506
  case "solGetAddress":
1507
+ return this.solGetAddress(connectId, "", item);
2019
1508
  case "tronGetAddress":
2020
- return this._callMethod(method, connectId, "", item, true, bundleContext);
1509
+ return this.tronGetAddress(connectId, "", item);
2021
1510
  default:
2022
1511
  return Promise.resolve(
2023
1512
  _hwkadaptercore.failure.call(void 0,
@@ -2036,50 +1525,11 @@ var _TrezorAdapter = class _TrezorAdapter {
2036
1525
  _callWalletMethod(methodName, connectId, deviceId, params) {
2037
1526
  return this._callMethod(methodName, connectId, deviceId, params, true);
2038
1527
  }
2039
- _callDeviceManagerMethod(methodName, connectId, params, operationContext) {
2040
- const expectedIdentity = _optionalChain([operationContext, 'optionalAccess', _87 => _87.expectedDeviceIdentity]);
2041
- if (expectedIdentity && (expectedIdentity.vendor !== "trezor" || expectedIdentity.type !== "deviceId")) {
2042
- return Promise.resolve(
2043
- _hwkadaptercore.failure.call(void 0,
2044
- _hwkadaptercore.HardwareErrorCode.InvalidParams,
2045
- "Trezor device-manager operations require a Trezor deviceId identity"
2046
- )
2047
- );
2048
- }
2049
- return this._callMethod(
2050
- methodName,
2051
- connectId,
2052
- _optionalChain([expectedIdentity, 'optionalAccess', _88 => _88.value]),
2053
- {
2054
- ...params && typeof params === "object" ? params : {},
2055
- knownConnections: _optionalChain([operationContext, 'optionalAccess', _89 => _89.knownConnections]),
2056
- extra: _optionalChain([operationContext, 'optionalAccess', _90 => _90.extra]),
2057
- allowDeviceSelection: _optionalChain([operationContext, 'optionalAccess', _91 => _91.allowDeviceSelection]),
2058
- ..._optionalChain([operationContext, 'optionalAccess', _92 => _92.operationId]) ? { operationId: operationContext.operationId } : {}
2059
- },
2060
- false
2061
- );
1528
+ _callDeviceManagerMethod(methodName, connectId, params) {
1529
+ return this._callMethod(methodName, connectId, void 0, params, false);
2062
1530
  }
2063
- async _callMethod(methodName, connectId, deviceId, params, requiresWalletIntent, bundleContext) {
1531
+ async _callMethod(methodName, connectId, deviceId, params, requiresWalletIntent) {
2064
1532
  const call = _TrezorAdapter._normalizeCallArgs(connectId, deviceId, params);
2065
- const commonParams = _TrezorAdapter._splitCommonParams(call.params);
2066
- const positionalOperationId = _hwkadaptercore.isHardwareOperationId.call(void 0, call.connectId) ? call.connectId : void 0;
2067
- if (positionalOperationId && commonParams.operationId && positionalOperationId !== commonParams.operationId) {
2068
- return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.InvalidParams, "Conflicting Trezor operation ids", {
2069
- positionalOperationId,
2070
- commonOperationId: commonParams.operationId
2071
- });
2072
- }
2073
- const operationId = _nullishCoalesce(commonParams.operationId, () => ( positionalOperationId));
2074
- let releaseOperationRetention;
2075
- try {
2076
- if (operationId) {
2077
- call.connectId = this._operations.resolve(operationId).connectId;
2078
- releaseOperationRetention = this._operations.retain(operationId);
2079
- }
2080
- } catch (error) {
2081
- return this._errorToFailure(error);
2082
- }
2083
1533
  debugLog("[TrezorAdapter][REQ]", {
2084
1534
  method: methodName,
2085
1535
  connectId: call.connectId || "(empty)",
@@ -2088,40 +1538,15 @@ var _TrezorAdapter = class _TrezorAdapter {
2088
1538
  });
2089
1539
  try {
2090
1540
  const response = await this._jobQueue.enqueue(
2091
- trezorQueueKey({ operationId, connectId: call.connectId }),
2092
- async (signal) => {
2093
- let effectiveConnectId = call.connectId;
2094
- let selectionRequestId;
2095
- try {
2096
- if (!_optionalChain([bundleContext, 'optionalAccess', _93 => _93.connection]) && !operationId && deviceId && (!connectId || _optionalChain([commonParams, 'access', _94 => _94.connectionContext, 'optionalAccess', _95 => _95.knownConnections]) !== void 0)) {
2097
- const resolved = await this._resolveExpectedDeviceConnectId(
2098
- deviceId,
2099
- signal,
2100
- commonParams.connectionContext
2101
- );
2102
- effectiveConnectId = resolved.connectId;
2103
- selectionRequestId = resolved.selectionRequestId;
2104
- }
2105
- } catch (error) {
2106
- return this._errorToFailure(error);
2107
- }
2108
- const response2 = await this._callWithRetry(
2109
- _nullishCoalesce(_optionalChain([bundleContext, 'optionalAccess', _96 => _96.connection, 'optionalAccess', _97 => _97.connectId]), () => ( effectiveConnectId)),
2110
- methodName,
2111
- call.params,
2112
- deviceId || "",
2113
- requiresWalletIntent,
2114
- true,
2115
- signal,
2116
- operationId,
2117
- selectionRequestId,
2118
- bundleContext
2119
- );
2120
- if (!response2.success && selectionRequestId) {
2121
- await this._releaseProvisionalConnection(effectiveConnectId, signal);
2122
- }
2123
- return response2;
2124
- },
1541
+ call.connectId,
1542
+ (signal) => this._callWithRetry(
1543
+ call.connectId,
1544
+ methodName,
1545
+ call.params,
1546
+ requiresWalletIntent,
1547
+ true,
1548
+ signal
1549
+ ),
2125
1550
  {
2126
1551
  label: methodName,
2127
1552
  rejectIfBusy: true,
@@ -2142,53 +1567,16 @@ var _TrezorAdapter = class _TrezorAdapter {
2142
1567
  payload: _TrezorAdapter._sanitizeForLog(response.payload, methodName)
2143
1568
  });
2144
1569
  return response;
2145
- } finally {
2146
- _optionalChain([releaseOperationRetention, 'optionalCall', _98 => _98()]);
2147
1570
  }
2148
1571
  }
2149
- async _callWithRetry(connectId, methodName, params, expectedDeviceId, requiresWalletIntent, allowRetry, signal, operationId, selectionRequestId, bundleContext) {
2150
- const { passphraseState, useEmptyPassphrase, rest, connectionContext } = _TrezorAdapter._splitCommonParams(params);
2151
- let pendingBindingRequestId = selectionRequestId;
2152
- let businessCallStarted = false;
1572
+ async _callWithRetry(connectId, methodName, params, requiresWalletIntent, allowRetry, signal) {
1573
+ const { passphraseState, useEmptyPassphrase, rest } = _TrezorAdapter._splitCommonParams(params);
2153
1574
  const restorePassphraseRequestContext = this._setPassphraseRequestContext(connectId, {
2154
1575
  passphraseState,
2155
1576
  useEmptyPassphrase
2156
1577
  });
2157
1578
  try {
2158
- if (_optionalChain([bundleContext, 'optionalAccess', _99 => _99.connection])) {
2159
- const pinned = bundleContext.connection;
2160
- if (this._sessions.get(pinned.connectId) !== pinned.sessionId) {
2161
- return _hwkadaptercore.failure.call(void 0,
2162
- _hwkadaptercore.HardwareErrorCode.DeviceDisconnected,
2163
- "Trezor all-network connection ended"
2164
- );
2165
- }
2166
- }
2167
- const sessionId = operationId ? this._sessions.get(this._operations.resolve(operationId).connectId) : await this._ensureSession(connectId, signal);
2168
- if (!sessionId) {
2169
- if (operationId) {
2170
- this._operations.end(operationId, "disconnect");
2171
- return _hwkadaptercore.failure.call(void 0,
2172
- _hwkadaptercore.HardwareErrorCode.OperationEnded,
2173
- "Trezor operation connection is no longer active",
2174
- { operationId, reason: "disconnect" }
2175
- );
2176
- }
2177
- return _hwkadaptercore.failure.call(void 0, _hwkadaptercore.HardwareErrorCode.DeviceNotFound, "Trezor session was not found");
2178
- }
2179
- if (bundleContext && !bundleContext.connection) {
2180
- bundleContext.connection = { connectId, sessionId };
2181
- }
2182
- if (expectedDeviceId) {
2183
- const actualDeviceId = _optionalChain([this, 'access', _100 => _100._devices, 'access', _101 => _101.get, 'call', _102 => _102(connectId), 'optionalAccess', _103 => _103.deviceId]);
2184
- if (!actualDeviceId || actualDeviceId !== expectedDeviceId) {
2185
- return _hwkadaptercore.failure.call(void 0,
2186
- _hwkadaptercore.HardwareErrorCode.DeviceMismatch,
2187
- `Wrong device: expected ${expectedDeviceId}, got ${actualDeviceId || "unknown"}`,
2188
- { expected: expectedDeviceId, actual: actualDeviceId || "" }
2189
- );
2190
- }
2191
- }
1579
+ const sessionId = await this._ensureSession(connectId, signal);
2192
1580
  if (requiresWalletIntent && !passphraseState && useEmptyPassphrase !== true) {
2193
1581
  return _hwkadaptercore.failure.call(void 0,
2194
1582
  _hwkadaptercore.HardwareErrorCode.InvalidParams,
@@ -2203,89 +1591,39 @@ var _TrezorAdapter = class _TrezorAdapter {
2203
1591
  } else if (useEmptyPassphrase === true) {
2204
1592
  await _TrezorAdapter._abortable(signal, this._createFreshAppSession(sessionId, signal));
2205
1593
  }
2206
- if (expectedDeviceId) {
2207
- await this._emitVerifiedBinding(
2208
- expectedDeviceId,
2209
- connectId,
2210
- pendingBindingRequestId,
2211
- connectionContext,
2212
- signal
2213
- );
2214
- pendingBindingRequestId = void 0;
2215
- this._rememberVerifiedConnection(expectedDeviceId, connectId);
2216
- }
2217
- businessCallStarted = true;
2218
1594
  const result = await _TrezorAdapter._abortable(
2219
1595
  signal,
2220
- this._callConnector(sessionId, methodName, rest, signal)
1596
+ _TrezorAdapter._callConnector(this._connector, sessionId, methodName, rest)
2221
1597
  );
2222
1598
  return _hwkadaptercore.success.call(void 0, result);
2223
1599
  } catch (error) {
2224
1600
  if (signal.aborted) {
2225
- if (pendingBindingRequestId) {
2226
- this._emitter.emit(_hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS, {
2227
- type: _hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS,
2228
- payload: { selectionRequestId: pendingBindingRequestId, status: "cancelled" }
2229
- });
2230
- pendingBindingRequestId = void 0;
2231
- }
2232
1601
  return this._errorToFailure(error);
2233
1602
  }
2234
1603
  const code = _TrezorAdapter._errorCode(error);
2235
- const willRetryStaleSession = allowRetry && (passphraseState || useEmptyPassphrase === true) && _TrezorAdapter._isStaleSessionError(code);
2236
- if (pendingBindingRequestId && !willRetryStaleSession) {
2237
- this._emitter.emit(_hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS, {
2238
- type: _hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS,
2239
- payload: { selectionRequestId: pendingBindingRequestId, status: "failed" }
2240
- });
2241
- pendingBindingRequestId = void 0;
2242
- }
2243
- const ambiguousTransportFailure = code === _hwkadaptercore.HardwareErrorCode.DeviceDisconnected || code === _hwkadaptercore.HardwareErrorCode.OperationTimeout || code === _hwkadaptercore.HardwareErrorCode.TransportError;
2244
- if (operationId && ambiguousTransportFailure) {
1604
+ if (allowRetry && code === _hwkadaptercore.HardwareErrorCode.DeviceDisconnected) {
2245
1605
  this._sessions.delete(connectId);
2246
1606
  this._verifiedPassphraseSessionsByConnectId.delete(connectId);
2247
- this._operations.end(operationId, "disconnect");
2248
- return _hwkadaptercore.failure.call(void 0,
2249
- _hwkadaptercore.HardwareErrorCode.OperationEnded,
2250
- businessCallStarted && !_hwkadaptercore.canReplayHardwareMethodAfterTransportFailure.call(void 0, methodName) ? `Trezor ${methodName} may have completed before the connection was lost` : "Trezor operation connection was lost",
2251
- businessCallStarted && !_hwkadaptercore.canReplayHardwareMethodAfterTransportFailure.call(void 0, methodName) ? _hwkadaptercore.operationMayHaveCompletedParams.call(void 0, methodName, {
2252
- operationId,
2253
- reason: "disconnect"
2254
- }) : { operationId, reason: "disconnect" },
2255
- void 0,
2256
- businessCallStarted && !_hwkadaptercore.canReplayHardwareMethodAfterTransportFailure.call(void 0, methodName) ? { scope: "unknown" } : void 0
1607
+ return await this._callWithRetry(
1608
+ connectId,
1609
+ methodName,
1610
+ params,
1611
+ requiresWalletIntent,
1612
+ false,
1613
+ signal
2257
1614
  );
2258
1615
  }
2259
- if (!operationId && ambiguousTransportFailure) {
2260
- this._sessions.delete(connectId);
2261
- this._verifiedPassphraseSessionsByConnectId.delete(connectId);
2262
- if (businessCallStarted && !_hwkadaptercore.canReplayHardwareMethodAfterTransportFailure.call(void 0, methodName)) {
2263
- return _hwkadaptercore.failure.call(void 0,
2264
- code,
2265
- `Trezor ${methodName} may have completed before the connection was lost`,
2266
- _hwkadaptercore.operationMayHaveCompletedParams.call(void 0, methodName),
2267
- void 0,
2268
- { scope: "unknown" }
2269
- );
2270
- }
2271
- }
2272
- if (willRetryStaleSession) {
1616
+ if (allowRetry && (passphraseState || useEmptyPassphrase === true) && _TrezorAdapter._isStaleSessionError(code)) {
2273
1617
  if (passphraseState) {
2274
1618
  this._forgetVerifiedPassphraseSession(connectId, passphraseState);
2275
1619
  }
2276
- const retryBindingRequestId = pendingBindingRequestId;
2277
- pendingBindingRequestId = void 0;
2278
1620
  return await this._callWithRetry(
2279
1621
  connectId,
2280
1622
  methodName,
2281
1623
  params,
2282
- expectedDeviceId,
2283
1624
  requiresWalletIntent,
2284
1625
  false,
2285
- signal,
2286
- operationId,
2287
- retryBindingRequestId,
2288
- bundleContext
1626
+ signal
2289
1627
  );
2290
1628
  }
2291
1629
  debugLog("[TrezorAdapter][ERROR]", {
@@ -2296,267 +1634,36 @@ var _TrezorAdapter = class _TrezorAdapter {
2296
1634
  return this._errorToFailure(error);
2297
1635
  } finally {
2298
1636
  restorePassphraseRequestContext();
2299
- if (pendingBindingRequestId) {
2300
- this._emitter.emit(_hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS, {
2301
- type: _hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS,
2302
- payload: {
2303
- selectionRequestId: pendingBindingRequestId,
2304
- status: signal.aborted ? "cancelled" : "failed"
2305
- }
2306
- });
2307
- pendingBindingRequestId = void 0;
2308
- }
2309
1637
  }
2310
1638
  }
2311
- async _ensureSession(connectId, signal, transportType) {
1639
+ async _ensureSession(connectId, signal) {
2312
1640
  const existing = this._sessions.get(connectId);
2313
1641
  if (existing) return existing;
2314
1642
  const pending = this._connectingPromises.get(connectId);
2315
1643
  if (pending) return pending;
2316
- const stateGeneration = this._stateGeneration;
2317
1644
  const promise = (async () => {
2318
- if (_optionalChain([signal, 'optionalAccess', _104 => _104.aborted])) {
2319
- throw Object.assign(new Error("Trezor connection aborted"), {
2320
- code: _hwkadaptercore.HardwareErrorCode.UserAborted
2321
- });
2322
- }
2323
- try {
2324
- return await this._connectSession(connectId, signal, stateGeneration, transportType);
2325
- } catch (error) {
2326
- if (_TrezorAdapter._isConnectionUnavailableError(error)) {
2327
- this._sessions.delete(connectId);
2328
- this._verifiedPassphraseSessionsByConnectId.delete(connectId);
2329
- }
2330
- throw error;
2331
- }
2332
- })();
2333
- this._connectingPromises.set(connectId, promise);
2334
- try {
2335
- return await promise;
2336
- } finally {
2337
- if (this._connectingPromises.get(connectId) === promise) {
2338
- this._connectingPromises.delete(connectId);
2339
- }
2340
- this._disconnectRequested.delete(connectId);
2341
- }
2342
- }
2343
- async _resolveExpectedDeviceConnectId(expectedDeviceId, signal, context) {
2344
- const connectedMatch = Array.from(this._devices.values()).find(
2345
- (device) => device.deviceId === expectedDeviceId && this._sessions.has(device.connectId)
2346
- );
2347
- if (connectedMatch) return { connectId: connectedMatch.connectId };
2348
- const availableTransports = _nullishCoalesce(this._connector.availableTransports, () => ( [
2349
- this._connector.connectionType
2350
- ]));
2351
- if (availableTransports.includes("usb")) {
2352
- await _TrezorAdapter._abortable(
2353
- signal,
2354
- this._ensureDevicePermission(void 0, expectedDeviceId, "usb")
2355
- );
2356
- }
2357
- const candidates = await _TrezorAdapter._abortable(
2358
- signal,
2359
- this._searchDevices({ transportType: "usb" }, signal)
2360
- );
2361
- const mismatchedDeviceIds = [];
2362
- const knownConnection = this._knownDeviceConnections.get(expectedDeviceId);
2363
- const knownUsbIds = _optionalChain([context, 'optionalAccess', _105 => _105.knownConnections]) !== void 0 ? context.knownConnections.flatMap(
2364
- (connection) => connection.transport === "usb" ? [connection.connectId] : []
2365
- ) : [_optionalChain([knownConnection, 'optionalAccess', _106 => _106.usbConnectId])].filter((id) => Boolean(id));
2366
- const suppliedBleIds = _optionalChain([context, 'optionalAccess', _107 => _107.knownConnections, 'optionalAccess', _108 => _108.flatMap, 'call', _109 => _109(
2367
- (connection) => connection.transport === "ble" ? [connection.connectId] : []
2368
- )]);
2369
- const knownBleIds = _optionalChain([suppliedBleIds, 'optionalAccess', _110 => _110.length]) ? suppliedBleIds : [_optionalChain([knownConnection, 'optionalAccess', _111 => _111.bleConnectId])].filter((id) => Boolean(id));
2370
- const usbCandidates = candidates.filter(
2371
- (device) => device.connectionType === "usb" && (!knownUsbIds.length || knownUsbIds.includes(device.connectId))
2372
- );
2373
- for (const candidate of usbCandidates) {
2374
- let sessionId;
2375
- try {
2376
- sessionId = await this._ensureSession(candidate.connectId, signal, "usb");
2377
- const actualDeviceId = _nullishCoalesce(_optionalChain([this, 'access', _112 => _112._devices, 'access', _113 => _113.get, 'call', _114 => _114(candidate.connectId), 'optionalAccess', _115 => _115.deviceId]), () => ( ""));
2378
- if (actualDeviceId === expectedDeviceId) return { connectId: candidate.connectId };
2379
- mismatchedDeviceIds.push(actualDeviceId || "unknown");
2380
- } catch (error) {
2381
- if (signal.aborted) throw error;
2382
- if (!_TrezorAdapter._isConnectionUnavailableError(error)) throw error;
2383
- }
2384
- if (sessionId) {
2385
- const mismatchedSessionId = sessionId;
2386
- this._sessions.delete(candidate.connectId);
2387
- this._verifiedPassphraseSessionsByConnectId.delete(candidate.connectId);
2388
- await this._runConnectorTeardown(() => this._connector.disconnect(mismatchedSessionId));
2389
- }
2390
- }
2391
- if (mismatchedDeviceIds.length) {
2392
- throw _hwkadaptercore.createHwkError.call(void 0, {
2393
- code: _hwkadaptercore.HardwareErrorCode.DeviceSearchMismatch,
2394
- message: "The connected Trezor is not the wallet this operation needs. Unplug it and connect the right device.",
2395
- params: { connectedDeviceIds: mismatchedDeviceIds }
2396
- });
2397
- }
2398
- if (usbCandidates.length > 0) {
2399
- throw _hwkadaptercore.createHwkError.call(void 0, {
2400
- code: _hwkadaptercore.HardwareErrorCode.DeviceNotFound,
2401
- message: "Trezor devices are present but none could be opened to check its identity."
2402
- });
2403
- }
2404
- const [knownBleConnectId] = knownBleIds;
2405
- if (knownBleConnectId && availableTransports.includes("ble")) {
2406
- await _TrezorAdapter._abortable(
2407
- signal,
2408
- this._ensureDevicePermission(knownBleConnectId, expectedDeviceId, "ble")
2409
- );
2410
- await this._ensureSession(knownBleConnectId, signal, "ble");
2411
- const actualDeviceId = _optionalChain([this, 'access', _116 => _116._devices, 'access', _117 => _117.get, 'call', _118 => _118(knownBleConnectId), 'optionalAccess', _119 => _119.deviceId]);
2412
- if (actualDeviceId === expectedDeviceId) return { connectId: knownBleConnectId };
2413
- const sessionId = this._sessions.get(knownBleConnectId);
2414
- this._sessions.delete(knownBleConnectId);
2415
- this._verifiedPassphraseSessionsByConnectId.delete(knownBleConnectId);
2416
- if (sessionId) {
2417
- await this._runConnectorTeardown(() => this._connector.disconnect(sessionId));
2418
- }
2419
- throw _hwkadaptercore.createHwkError.call(void 0, {
2420
- code: _hwkadaptercore.HardwareErrorCode.DeviceMismatch,
2421
- message: "The bound Trezor Bluetooth device has a different identity"
2422
- });
2423
- }
2424
- if (_optionalChain([context, 'optionalAccess', _120 => _120.allowDeviceSelection]) === false) {
2425
- throw _hwkadaptercore.createHwkError.call(void 0, {
2426
- code: _hwkadaptercore.HardwareErrorCode.DeviceNotFound,
2427
- message: "No known Trezor connection is available"
2428
- });
2429
- }
2430
- return this._selectBleDeviceForBinding(expectedDeviceId, signal, context, "missing-binding");
2431
- }
2432
- async _selectBleDeviceForBinding(expectedDeviceId, signal, context, reason) {
2433
- const availableTransports = _nullishCoalesce(this._connector.availableTransports, () => ( [
2434
- this._connector.connectionType
2435
- ]));
2436
- const allowUsbFallback = reason !== "manual-rebind" && availableTransports.includes("usb");
2437
- const knownUsbIds = _optionalChain([context, 'optionalAccess', _121 => _121.knownConnections]) ? context.knownConnections.flatMap(
2438
- (connection) => connection.transport === "usb" ? [connection.connectId] : []
2439
- ) : [_optionalChain([this, 'access', _122 => _122._knownDeviceConnections, 'access', _123 => _123.get, 'call', _124 => _124(expectedDeviceId), 'optionalAccess', _125 => _125.usbConnectId])];
2440
- if (availableTransports.includes("ble")) {
2441
- await _TrezorAdapter._abortable(
2442
- signal,
2443
- this._ensureDevicePermission(void 0, expectedDeviceId, "ble")
2444
- );
2445
- }
2446
- const bleCandidates = (await _TrezorAdapter._abortable(
2447
- signal,
2448
- this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal)
2449
- )).filter((device) => device.connectionType === "ble");
2450
- if (signal.aborted) throw signal.reason;
2451
- const rejectedConnectIds = /* @__PURE__ */ new Set();
2452
- const bindingSessionId = this._uiRegistry.createRequestId();
2453
- let rejectedConnectId;
2454
- while (availableTransports.includes("ble") && this._emitter.listenerCount(_hwkadaptercore.UI_REQUEST.REQUEST_SELECT_DEVICE)) {
2455
- const { device: selected, requestId } = await _hwkadaptercore.requestBleDeviceSelection.call(void 0, {
2456
- emitter: this._emitter,
2457
- registry: this._uiRegistry,
2458
- signal,
2459
- allowUsbFallback,
2460
- scan: async () => {
2461
- if (allowUsbFallback) {
2462
- const usbCandidates = (await this._searchDevices({ transportType: "usb" }, signal)).filter(
2463
- (device) => device.connectionType === "usb" && !rejectedConnectIds.has(device.connectId)
2464
- );
2465
- const candidate = _nullishCoalesce(usbCandidates.find((device) => knownUsbIds.includes(device.connectId)), () => ( usbCandidates[0]));
2466
- if (candidate) return [candidate];
2467
- }
2468
- return (await this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal)).filter(
2469
- (device) => device.connectionType === "ble" && !rejectedConnectIds.has(device.connectId)
2470
- );
2471
- },
2472
- request: {
2473
- devices: bleCandidates.filter((device) => !rejectedConnectIds.has(device.connectId)),
2474
- bindingSessionId,
2475
- rejectedConnectId,
2476
- context: {
2477
- kind: "bind-connection",
2478
- transport: "ble",
2479
- reason
2480
- },
2481
- extra: _optionalChain([context, 'optionalAccess', _126 => _126.extra]),
2482
- operationId: this._activeOperationId()
2483
- }
2484
- });
2485
1645
  try {
2486
- if (reason === "manual-rebind") {
2487
- this._operations.endByConnectionKey(selected.connectId, "explicit");
2488
- await this._releaseProvisionalConnection(selected.connectId, signal);
1646
+ if (_optionalChain([signal, 'optionalAccess', _34 => _34.aborted])) {
1647
+ throw Object.assign(new Error("Trezor connection aborted"), {
1648
+ code: _hwkadaptercore.HardwareErrorCode.UserAborted
1649
+ });
2489
1650
  }
2490
- await this._ensureSession(selected.connectId, signal, selected.connectionType);
2491
- } catch (error) {
2492
- this._emitter.emit(_hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS, {
2493
- type: _hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS,
2494
- payload: {
2495
- selectionRequestId: requestId,
2496
- status: signal.aborted ? "cancelled" : "failed"
1651
+ try {
1652
+ return await this._connectSession(connectId, signal);
1653
+ } catch (error) {
1654
+ if (_TrezorAdapter._isConnectionUnavailableError(error)) {
1655
+ this._sessions.delete(connectId);
1656
+ this._verifiedPassphraseSessionsByConnectId.delete(connectId);
2497
1657
  }
2498
- });
2499
- throw error;
2500
- }
2501
- if (_optionalChain([this, 'access', _127 => _127._devices, 'access', _128 => _128.get, 'call', _129 => _129(selected.connectId), 'optionalAccess', _130 => _130.deviceId]) !== expectedDeviceId) {
2502
- const sessionId = this._sessions.get(selected.connectId);
2503
- this._sessions.delete(selected.connectId);
2504
- this._verifiedPassphraseSessionsByConnectId.delete(selected.connectId);
2505
- if (sessionId) {
2506
- await this._runConnectorTeardown(() => this._connector.disconnect(sessionId));
1658
+ throw error;
2507
1659
  }
2508
- rejectedConnectId = selected.connectId;
2509
- rejectedConnectIds.add(selected.connectId);
2510
- continue;
2511
- }
2512
- if (selected.connectionType === "usb") {
2513
- this._emitter.emit(_hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS, {
2514
- type: _hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS,
2515
- payload: { selectionRequestId: requestId, status: "cancelled" }
2516
- });
2517
- return { connectId: selected.connectId };
1660
+ } finally {
1661
+ this._connectingPromises.delete(connectId);
1662
+ this._disconnectRequested.delete(connectId);
2518
1663
  }
2519
- return { connectId: selected.connectId, selectionRequestId: requestId };
2520
- }
2521
- throw _hwkadaptercore.createHwkError.call(void 0, {
2522
- code: _hwkadaptercore.HardwareErrorCode.DeviceNotFound,
2523
- message: "No readable Trezor device is available"
2524
- });
2525
- }
2526
- _rememberVerifiedConnection(deviceId, connectId) {
2527
- const device = this._devices.get(connectId);
2528
- if (!device || device.deviceId !== deviceId) return;
2529
- const known = _nullishCoalesce(this._knownDeviceConnections.get(deviceId), () => ( { deviceId }));
2530
- if (device.connectionType === "ble") {
2531
- known.bleConnectId = connectId;
2532
- } else if (device.connectionType === "usb" && _optionalChain([device, 'access', _131 => _131.capabilities, 'optionalAccess', _132 => _132.persistentDeviceIdentity])) {
2533
- known.usbConnectId = connectId;
2534
- }
2535
- this._knownDeviceConnections.set(deviceId, known);
2536
- }
2537
- async _emitVerifiedBinding(deviceId, connectId, selectionRequestId, context, signal) {
2538
- if (!selectionRequestId) return false;
2539
- const device = this._devices.get(connectId);
2540
- if (!device || device.deviceId !== deviceId || device.connectionType !== "ble") {
2541
- this._emitter.emit(_hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS, {
2542
- type: _hwkadaptercore.UI_REQUEST.DEVICE_BINDING_STATUS,
2543
- payload: { selectionRequestId, status: "cancelled" }
2544
- });
2545
- return false;
2546
- }
2547
- const outcome = await _hwkadaptercore.requestSaveDeviceBinding.call(void 0,
2548
- this._emitter,
2549
- this._uiRegistry,
2550
- {
2551
- selectionRequestId,
2552
- connection: { transport: "ble", connectId },
2553
- identity: { vendor: "trezor", type: "deviceId", value: deviceId },
2554
- extra: _optionalChain([context, 'optionalAccess', _133 => _133.extra]),
2555
- operationId: this._activeOperationId()
2556
- },
2557
- signal
2558
- );
2559
- return outcome.saved;
1664
+ })();
1665
+ this._connectingPromises.set(connectId, promise);
1666
+ return promise;
2560
1667
  }
2561
1668
  /**
2562
1669
  * Pin the device's active wallet session to `passphraseState` (the target
@@ -2578,21 +1685,12 @@ var _TrezorAdapter = class _TrezorAdapter {
2578
1685
  if (reused) return;
2579
1686
  const created = await _TrezorAdapter._abortable(
2580
1687
  signal,
2581
- this._callConnector(
2582
- sessionId,
2583
- "__thpCreateSession",
2584
- {
2585
- passphraseMode: "prompt"
2586
- },
2587
- signal
2588
- )
1688
+ _TrezorAdapter._callConnector(this._connector, sessionId, "__thpCreateSession", {
1689
+ passphraseMode: "prompt"
1690
+ })
2589
1691
  );
2590
- if (_optionalChain([created, 'optionalAccess', _134 => _134.protocol]) === "thp" && !created.thpSessionId || _optionalChain([created, 'optionalAccess', _135 => _135.protocol]) !== "thp" && _optionalChain([created, 'optionalAccess', _136 => _136.protocol]) !== "v1") {
2591
- throw _hwkadaptercore.createHwkError.call(void 0, {
2592
- code: _hwkadaptercore.HardwareErrorCode.TransportError,
2593
- message: "Cannot verify the requested Trezor wallet session"
2594
- });
2595
- }
1692
+ if (_optionalChain([created, 'optionalAccess', _35 => _35.protocol]) === "thp" && !created.thpSessionId) return;
1693
+ if (_optionalChain([created, 'optionalAccess', _36 => _36.protocol]) !== "thp" && _optionalChain([created, 'optionalAccess', _37 => _37.protocol]) !== "v1") return;
2596
1694
  const state = await this._deriveState(sessionId, signal);
2597
1695
  if (state !== passphraseState) {
2598
1696
  throw Object.assign(
@@ -2606,13 +1704,13 @@ var _TrezorAdapter = class _TrezorAdapter {
2606
1704
  }
2607
1705
  _rememberVerifiedPassphraseSession(connectId, passphraseState, sessionId, created) {
2608
1706
  let session;
2609
- if (_optionalChain([created, 'optionalAccess', _137 => _137.protocol]) === "thp" && typeof created.thpSessionId === "string") {
1707
+ if (_optionalChain([created, 'optionalAccess', _38 => _38.protocol]) === "thp" && typeof created.thpSessionId === "string") {
2610
1708
  session = {
2611
1709
  sessionId,
2612
1710
  protocol: "thp",
2613
1711
  thpSessionId: created.thpSessionId
2614
1712
  };
2615
- } else if (_optionalChain([created, 'optionalAccess', _138 => _138.protocol]) === "v1") {
1713
+ } else if (_optionalChain([created, 'optionalAccess', _39 => _39.protocol]) === "v1") {
2616
1714
  session = {
2617
1715
  sessionId,
2618
1716
  protocol: "v1"
@@ -2632,7 +1730,7 @@ var _TrezorAdapter = class _TrezorAdapter {
2632
1730
  }
2633
1731
  }
2634
1732
  async _reuseVerifiedPassphraseSession(connectId, sessionId, passphraseState, signal) {
2635
- const cached = _optionalChain([this, 'access', _139 => _139._verifiedPassphraseSessionsByConnectId, 'access', _140 => _140.get, 'call', _141 => _141(connectId), 'optionalAccess', _142 => _142.get, 'call', _143 => _143(passphraseState)]);
1733
+ const cached = _optionalChain([this, 'access', _40 => _40._verifiedPassphraseSessionsByConnectId, 'access', _41 => _41.get, 'call', _42 => _42(connectId), 'optionalAccess', _43 => _43.get, 'call', _44 => _44(passphraseState)]);
2636
1734
  if (!cached || cached.sessionId !== sessionId) {
2637
1735
  this._forgetVerifiedPassphraseSession(connectId, passphraseState);
2638
1736
  return false;
@@ -2642,14 +1740,9 @@ var _TrezorAdapter = class _TrezorAdapter {
2642
1740
  if (!cached.thpSessionId) return false;
2643
1741
  await _TrezorAdapter._abortable(
2644
1742
  signal,
2645
- this._callConnector(
2646
- sessionId,
2647
- "__thpSelectSession",
2648
- {
2649
- thpSessionId: cached.thpSessionId
2650
- },
2651
- signal
2652
- )
1743
+ _TrezorAdapter._callConnector(this._connector, sessionId, "__thpSelectSession", {
1744
+ thpSessionId: cached.thpSessionId
1745
+ })
2653
1746
  );
2654
1747
  }
2655
1748
  const state = await this._deriveState(sessionId, signal);
@@ -2667,14 +1760,9 @@ var _TrezorAdapter = class _TrezorAdapter {
2667
1760
  async _createFreshAppSession(sessionId, signal) {
2668
1761
  await _TrezorAdapter._abortable(
2669
1762
  signal,
2670
- this._callConnector(
2671
- sessionId,
2672
- "__thpCreateSession",
2673
- {
2674
- passphraseMode: "empty"
2675
- },
2676
- signal
2677
- )
1763
+ _TrezorAdapter._callConnector(this._connector, sessionId, "__thpCreateSession", {
1764
+ passphraseMode: "empty"
1765
+ })
2678
1766
  );
2679
1767
  }
2680
1768
  /**
@@ -2689,17 +1777,12 @@ var _TrezorAdapter = class _TrezorAdapter {
2689
1777
  async _deriveState(sessionId, signal) {
2690
1778
  const derived = await _TrezorAdapter._abortable(
2691
1779
  signal,
2692
- this._callConnector(
2693
- sessionId,
2694
- "btcGetPublicKey",
2695
- {
2696
- path: "m/44'/0'/0'",
2697
- showOnDevice: false
2698
- },
2699
- signal
2700
- )
1780
+ _TrezorAdapter._callConnector(this._connector, sessionId, "btcGetPublicKey", {
1781
+ path: "m/44'/0'/0'",
1782
+ showOnDevice: false
1783
+ })
2701
1784
  );
2702
- const state = _optionalChain([derived, 'optionalAccess', _144 => _144.publicKey]);
1785
+ const state = _optionalChain([derived, 'optionalAccess', _45 => _45.publicKey]);
2703
1786
  if (!state) {
2704
1787
  throw Object.assign(new Error("Failed to derive passphrase state (wallet public key)"), {
2705
1788
  code: _hwkadaptercore.HardwareErrorCode.UnknownError
@@ -2707,36 +1790,25 @@ var _TrezorAdapter = class _TrezorAdapter {
2707
1790
  }
2708
1791
  return state;
2709
1792
  }
2710
- async _resolvePassphraseState(connectId, passphraseState, signal, operationId) {
1793
+ async _resolvePassphraseState(connectId, passphraseState, signal) {
2711
1794
  try {
2712
- const sessionId = operationId ? this._sessions.get(this._operations.resolve(operationId).connectId) : await this._ensureSession(connectId, signal);
2713
- if (!sessionId) {
2714
- return _hwkadaptercore.failure.call(void 0,
2715
- _hwkadaptercore.HardwareErrorCode.OperationEnded,
2716
- "Trezor operation connection is no longer active"
2717
- );
2718
- }
1795
+ const sessionId = await this._ensureSession(connectId, signal);
2719
1796
  if (passphraseState) {
2720
1797
  await this._alignAppSession(connectId, sessionId, passphraseState, signal);
2721
1798
  return _hwkadaptercore.success.call(void 0, passphraseState);
2722
1799
  }
2723
1800
  const created = await _TrezorAdapter._abortable(
2724
1801
  signal,
2725
- this._callConnector(
2726
- sessionId,
2727
- "__thpCreateSession",
2728
- {
2729
- passphraseMode: "prompt"
2730
- },
2731
- signal
2732
- )
1802
+ _TrezorAdapter._callConnector(this._connector, sessionId, "__thpCreateSession", {
1803
+ passphraseMode: "prompt"
1804
+ })
2733
1805
  );
2734
1806
  const state = await this._deriveState(sessionId, signal);
2735
1807
  const features = await _TrezorAdapter._abortable(
2736
1808
  signal,
2737
- this._callConnector(sessionId, "getFeatures", { refresh: true }, signal)
1809
+ _TrezorAdapter._callConnector(this._connector, sessionId, "getFeatures", { refresh: true })
2738
1810
  );
2739
- if (_optionalChain([features, 'optionalAccess', _145 => _145.passphrase_protection]) !== true) {
1811
+ if (_optionalChain([features, 'optionalAccess', _46 => _46.passphrase_protection]) !== true) {
2740
1812
  return _hwkadaptercore.success.call(void 0, null);
2741
1813
  }
2742
1814
  this._rememberVerifiedPassphraseSession(connectId, state, sessionId, created);
@@ -2784,16 +1856,7 @@ var _TrezorAdapter = class _TrezorAdapter {
2784
1856
  }
2785
1857
  const trustedNumericCode = typeof typed.code === "number" && KNOWN_HARDWARE_ERROR_CODES.has(typed.code) ? typed.code : void 0;
2786
1858
  const code = _nullishCoalesce(_nullishCoalesce(trustedNumericCode, () => ( _TrezorAdapter._mapTrezorFailureCode(error))), () => ( _hwkadaptercore.HardwareErrorCode.UnknownError));
2787
- const stampedOrigin = _optionalChain([error, 'optionalAccess', _146 => _146.origin]);
2788
- const origin = stampedOrigin === "device" || stampedOrigin === "transport" || stampedOrigin === "host" ? stampedOrigin : _hwkadaptercore.defaultOriginForCode.call(void 0, code);
2789
- const params = typed.params && typeof typed.params === "object" ? typed.params : void 0;
2790
- return _hwkadaptercore.failure.call(void 0,
2791
- code,
2792
- _nullishCoalesce(typed.message, () => ( String(error))),
2793
- params,
2794
- origin,
2795
- _hwkadaptercore.isHwkRecoveryHint.call(void 0, typed.recovery) ? typed.recovery : void 0
2796
- );
1859
+ return _hwkadaptercore.failure.call(void 0, code, _nullishCoalesce(typed.message, () => ( String(error))));
2797
1860
  }
2798
1861
  /**
2799
1862
  * Emit `REQUEST_DEVICE_PERMISSION` and await the host's
@@ -2808,19 +1871,18 @@ var _TrezorAdapter = class _TrezorAdapter {
2808
1871
  * - no `connectId` → environment-level check (scan / picker)
2809
1872
  * - with `connectId` → device-level check (per-call gating)
2810
1873
  */
2811
- async _ensureDevicePermission(connectId, deviceId, requestedTransport) {
1874
+ async _ensureDevicePermission(connectId, deviceId) {
2812
1875
  if (!this._emitter.listenerCount(_hwkadaptercore.UI_REQUEST.REQUEST_DEVICE_PERMISSION)) {
2813
1876
  return;
2814
1877
  }
2815
- const transportType = _nullishCoalesce(_nullishCoalesce(requestedTransport, () => ( this.activeTransport)), () => ( "usb"));
2816
- const operationId = this._activeOperationId();
1878
+ const transportType = _nullishCoalesce(this.activeTransport, () => ( "usb"));
2817
1879
  const waitPromise = this._uiRegistry.wait(
2818
1880
  _hwkadaptercore.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2819
- { timeoutMs: 6e4, operationId }
1881
+ { timeoutMs: 6e4 }
2820
1882
  );
2821
1883
  this._emitter.emit(_hwkadaptercore.UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
2822
1884
  type: _hwkadaptercore.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2823
- payload: { transportType, connectId, deviceId, operationId }
1885
+ payload: { transportType, connectId, deviceId }
2824
1886
  });
2825
1887
  const { granted } = await waitPromise;
2826
1888
  if (!granted) {
@@ -2832,8 +1894,6 @@ var _TrezorAdapter = class _TrezorAdapter {
2832
1894
  };
2833
1895
  // Keys are matched after normalizeLogKey, so snake_case/camelCase both hit.
2834
1896
  _TrezorAdapter._sensitiveLogKeys = /* @__PURE__ */ new Set([
2835
- "extra",
2836
- "knownconnections",
2837
1897
  "credential",
2838
1898
  "credentials",
2839
1899
  "entropy",
@@ -2952,7 +2012,7 @@ async function fetchDefinitionHex(url, fetchImpl) {
2952
2012
  }
2953
2013
  return arrayBufferToHex(await response.arrayBuffer());
2954
2014
  });
2955
- } catch (e7) {
2015
+ } catch (e5) {
2956
2016
  return void 0;
2957
2017
  }
2958
2018
  }
@@ -2981,7 +2041,7 @@ async function fetchSolanaTokenDefinition({
2981
2041
  }
2982
2042
  return Buffer.from(await response.arrayBuffer()).toString("hex");
2983
2043
  });
2984
- } catch (e8) {
2044
+ } catch (e6) {
2985
2045
  return void 0;
2986
2046
  }
2987
2047
  }