UNPKG

16.5 kBJavaScriptView Raw
1/* eslint-disable no-continue */
2/* eslint-disable no-param-reassign */
3/* eslint-disable no-prototype-builtins */
4var errorClasses = {};
5var deserializers = {};
6var addCustomErrorDeserializer = function (name, deserializer) {
7 deserializers[name] = deserializer;
8};
9var createCustomErrorClass = function (name) {
10 var C = function CustomError(message, fields) {
11 Object.assign(this, fields);
12 this.name = name;
13 this.message = message || name;
14 this.stack = new Error().stack;
15 };
16 C.prototype = new Error();
17 errorClasses[name] = C;
18 return C;
19};
20// inspired from https://github.com/programble/errio/blob/master/index.js
21var deserializeError = function (object) {
22 if (typeof object === "object" && object) {
23 try {
24 // $FlowFixMe FIXME HACK
25 var msg = JSON.parse(object.message);
26 if (msg.message && msg.name) {
27 object = msg;
28 }
29 }
30 catch (e) {
31 // nothing
32 }
33 var error = void 0;
34 if (typeof object.name === "string") {
35 var name_1 = object.name;
36 var des = deserializers[name_1];
37 if (des) {
38 error = des(object);
39 }
40 else {
41 var constructor = name_1 === "Error" ? Error : errorClasses[name_1];
42 if (!constructor) {
43 console.warn("deserializing an unknown class '" + name_1 + "'");
44 constructor = createCustomErrorClass(name_1);
45 }
46 error = Object.create(constructor.prototype);
47 try {
48 for (var prop in object) {
49 if (object.hasOwnProperty(prop)) {
50 error[prop] = object[prop];
51 }
52 }
53 }
54 catch (e) {
55 // sometimes setting a property can fail (e.g. .name)
56 }
57 }
58 }
59 else {
60 error = new Error(object.message);
61 }
62 if (!error.stack && Error.captureStackTrace) {
63 Error.captureStackTrace(error, deserializeError);
64 }
65 return error;
66 }
67 return new Error(String(object));
68};
69// inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js
70var serializeError = function (value) {
71 if (!value)
72 return value;
73 if (typeof value === "object") {
74 return destroyCircular(value, []);
75 }
76 if (typeof value === "function") {
77 return "[Function: " + (value.name || "anonymous") + "]";
78 }
79 return value;
80};
81// https://www.npmjs.com/package/destroy-circular
82function destroyCircular(from, seen) {
83 var to = {};
84 seen.push(from);
85 for (var _i = 0, _a = Object.keys(from); _i < _a.length; _i++) {
86 var key = _a[_i];
87 var value = from[key];
88 if (typeof value === "function") {
89 continue;
90 }
91 if (!value || typeof value !== "object") {
92 to[key] = value;
93 continue;
94 }
95 if (seen.indexOf(from[key]) === -1) {
96 to[key] = destroyCircular(from[key], seen.slice(0));
97 continue;
98 }
99 to[key] = "[Circular]";
100 }
101 if (typeof from.name === "string") {
102 to.name = from.name;
103 }
104 if (typeof from.message === "string") {
105 to.message = from.message;
106 }
107 if (typeof from.stack === "string") {
108 to.stack = from.stack;
109 }
110 return to;
111}
112
113var AccountNameRequiredError = createCustomErrorClass("AccountNameRequired");
114var AccountNotSupported = createCustomErrorClass("AccountNotSupported");
115var AmountRequired = createCustomErrorClass("AmountRequired");
116var BluetoothRequired = createCustomErrorClass("BluetoothRequired");
117var BtcUnmatchedApp = createCustomErrorClass("BtcUnmatchedApp");
118var CantOpenDevice = createCustomErrorClass("CantOpenDevice");
119var CashAddrNotSupported = createCustomErrorClass("CashAddrNotSupported");
120var CurrencyNotSupported = createCustomErrorClass("CurrencyNotSupported");
121var DeviceAppVerifyNotSupported = createCustomErrorClass("DeviceAppVerifyNotSupported");
122var DeviceGenuineSocketEarlyClose = createCustomErrorClass("DeviceGenuineSocketEarlyClose");
123var DeviceNotGenuineError = createCustomErrorClass("DeviceNotGenuine");
124var DeviceOnDashboardExpected = createCustomErrorClass("DeviceOnDashboardExpected");
125var DeviceOnDashboardUnexpected = createCustomErrorClass("DeviceOnDashboardUnexpected");
126var DeviceInOSUExpected = createCustomErrorClass("DeviceInOSUExpected");
127var DeviceHalted = createCustomErrorClass("DeviceHalted");
128var DeviceNameInvalid = createCustomErrorClass("DeviceNameInvalid");
129var DeviceSocketFail = createCustomErrorClass("DeviceSocketFail");
130var DeviceSocketNoBulkStatus = createCustomErrorClass("DeviceSocketNoBulkStatus");
131var DisconnectedDevice = createCustomErrorClass("DisconnectedDevice");
132var DisconnectedDeviceDuringOperation = createCustomErrorClass("DisconnectedDeviceDuringOperation");
133var EnpointConfigError = createCustomErrorClass("EnpointConfig");
134var EthAppPleaseEnableContractData = createCustomErrorClass("EthAppPleaseEnableContractData");
135var FeeEstimationFailed = createCustomErrorClass("FeeEstimationFailed");
136var FirmwareNotRecognized = createCustomErrorClass("FirmwareNotRecognized");
137var HardResetFail = createCustomErrorClass("HardResetFail");
138var InvalidXRPTag = createCustomErrorClass("InvalidXRPTag");
139var InvalidAddress = createCustomErrorClass("InvalidAddress");
140var InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass("InvalidAddressBecauseDestinationIsAlsoSource");
141var LatestMCUInstalledError = createCustomErrorClass("LatestMCUInstalledError");
142var UnknownMCU = createCustomErrorClass("UnknownMCU");
143var LedgerAPIError = createCustomErrorClass("LedgerAPIError");
144var LedgerAPIErrorWithMessage = createCustomErrorClass("LedgerAPIErrorWithMessage");
145var LedgerAPINotAvailable = createCustomErrorClass("LedgerAPINotAvailable");
146var ManagerAppAlreadyInstalledError = createCustomErrorClass("ManagerAppAlreadyInstalled");
147var ManagerAppRelyOnBTCError = createCustomErrorClass("ManagerAppRelyOnBTC");
148var ManagerAppDepInstallRequired = createCustomErrorClass("ManagerAppDepInstallRequired");
149var ManagerAppDepUninstallRequired = createCustomErrorClass("ManagerAppDepUninstallRequired");
150var ManagerDeviceLockedError = createCustomErrorClass("ManagerDeviceLocked");
151var ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass("ManagerFirmwareNotEnoughSpace");
152var ManagerNotEnoughSpaceError = createCustomErrorClass("ManagerNotEnoughSpace");
153var ManagerUninstallBTCDep = createCustomErrorClass("ManagerUninstallBTCDep");
154var NetworkDown = createCustomErrorClass("NetworkDown");
155var NoAddressesFound = createCustomErrorClass("NoAddressesFound");
156var NotEnoughBalance = createCustomErrorClass("NotEnoughBalance");
157var NotEnoughBalanceToDelegate = createCustomErrorClass("NotEnoughBalanceToDelegate");
158var NotEnoughBalanceInParentAccount = createCustomErrorClass("NotEnoughBalanceInParentAccount");
159var NotEnoughSpendableBalance = createCustomErrorClass("NotEnoughSpendableBalance");
160var NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass("NotEnoughBalanceBecauseDestinationNotCreated");
161var NoAccessToCamera = createCustomErrorClass("NoAccessToCamera");
162var NotEnoughGas = createCustomErrorClass("NotEnoughGas");
163var NotSupportedLegacyAddress = createCustomErrorClass("NotSupportedLegacyAddress");
164var GasLessThanEstimate = createCustomErrorClass("GasLessThanEstimate");
165var PasswordsDontMatchError = createCustomErrorClass("PasswordsDontMatch");
166var PasswordIncorrectError = createCustomErrorClass("PasswordIncorrect");
167var RecommendSubAccountsToEmpty = createCustomErrorClass("RecommendSubAccountsToEmpty");
168var RecommendUndelegation = createCustomErrorClass("RecommendUndelegation");
169var TimeoutTagged = createCustomErrorClass("TimeoutTagged");
170var UnexpectedBootloader = createCustomErrorClass("UnexpectedBootloader");
171var MCUNotGenuineToDashboard = createCustomErrorClass("MCUNotGenuineToDashboard");
172var RecipientRequired = createCustomErrorClass("RecipientRequired");
173var UnavailableTezosOriginatedAccountReceive = createCustomErrorClass("UnavailableTezosOriginatedAccountReceive");
174var UnavailableTezosOriginatedAccountSend = createCustomErrorClass("UnavailableTezosOriginatedAccountSend");
175var UpdateFetchFileFail = createCustomErrorClass("UpdateFetchFileFail");
176var UpdateIncorrectHash = createCustomErrorClass("UpdateIncorrectHash");
177var UpdateIncorrectSig = createCustomErrorClass("UpdateIncorrectSig");
178var UpdateYourApp = createCustomErrorClass("UpdateYourApp");
179var UserRefusedDeviceNameChange = createCustomErrorClass("UserRefusedDeviceNameChange");
180var UserRefusedAddress = createCustomErrorClass("UserRefusedAddress");
181var UserRefusedFirmwareUpdate = createCustomErrorClass("UserRefusedFirmwareUpdate");
182var UserRefusedAllowManager = createCustomErrorClass("UserRefusedAllowManager");
183var UserRefusedOnDevice = createCustomErrorClass("UserRefusedOnDevice"); // TODO rename because it's just for transaction refusal
184var TransportOpenUserCancelled = createCustomErrorClass("TransportOpenUserCancelled");
185var TransportInterfaceNotAvailable = createCustomErrorClass("TransportInterfaceNotAvailable");
186var TransportRaceCondition = createCustomErrorClass("TransportRaceCondition");
187var TransportWebUSBGestureRequired = createCustomErrorClass("TransportWebUSBGestureRequired");
188var DeviceShouldStayInApp = createCustomErrorClass("DeviceShouldStayInApp");
189var WebsocketConnectionError = createCustomErrorClass("WebsocketConnectionError");
190var WebsocketConnectionFailed = createCustomErrorClass("WebsocketConnectionFailed");
191var WrongDeviceForAccount = createCustomErrorClass("WrongDeviceForAccount");
192var WrongAppForCurrency = createCustomErrorClass("WrongAppForCurrency");
193var ETHAddressNonEIP = createCustomErrorClass("ETHAddressNonEIP");
194var CantScanQRCode = createCustomErrorClass("CantScanQRCode");
195var FeeNotLoaded = createCustomErrorClass("FeeNotLoaded");
196var FeeRequired = createCustomErrorClass("FeeRequired");
197var FeeTooHigh = createCustomErrorClass("FeeTooHigh");
198var SyncError = createCustomErrorClass("SyncError");
199var PairingFailed = createCustomErrorClass("PairingFailed");
200var GenuineCheckFailed = createCustomErrorClass("GenuineCheckFailed");
201var LedgerAPI4xx = createCustomErrorClass("LedgerAPI4xx");
202var LedgerAPI5xx = createCustomErrorClass("LedgerAPI5xx");
203var FirmwareOrAppUpdateRequired = createCustomErrorClass("FirmwareOrAppUpdateRequired");
204// db stuff, no need to translate
205var NoDBPathGiven = createCustomErrorClass("NoDBPathGiven");
206var DBWrongPassword = createCustomErrorClass("DBWrongPassword");
207var DBNotReset = createCustomErrorClass("DBNotReset");
208/**
209 * TransportError is used for any generic transport errors.
210 * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason.
211 */
212function TransportError(message, id) {
213 this.name = "TransportError";
214 this.message = message;
215 this.stack = new Error().stack;
216 this.id = id;
217}
218TransportError.prototype = new Error();
219addCustomErrorDeserializer("TransportError", function (e) { return new TransportError(e.message, e.id); });
220var StatusCodes = {
221 PIN_REMAINING_ATTEMPTS: 0x63c0,
222 INCORRECT_LENGTH: 0x6700,
223 MISSING_CRITICAL_PARAMETER: 0x6800,
224 COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981,
225 SECURITY_STATUS_NOT_SATISFIED: 0x6982,
226 CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985,
227 INCORRECT_DATA: 0x6a80,
228 NOT_ENOUGH_MEMORY_SPACE: 0x6a84,
229 REFERENCED_DATA_NOT_FOUND: 0x6a88,
230 FILE_ALREADY_EXISTS: 0x6a89,
231 INCORRECT_P1_P2: 0x6b00,
232 INS_NOT_SUPPORTED: 0x6d00,
233 CLA_NOT_SUPPORTED: 0x6e00,
234 TECHNICAL_PROBLEM: 0x6f00,
235 OK: 0x9000,
236 MEMORY_PROBLEM: 0x9240,
237 NO_EF_SELECTED: 0x9400,
238 INVALID_OFFSET: 0x9402,
239 FILE_NOT_FOUND: 0x9404,
240 INCONSISTENT_FILE: 0x9408,
241 ALGORITHM_NOT_SUPPORTED: 0x9484,
242 INVALID_KCV: 0x9485,
243 CODE_NOT_INITIALIZED: 0x9802,
244 ACCESS_CONDITION_NOT_FULFILLED: 0x9804,
245 CONTRADICTION_SECRET_CODE_STATUS: 0x9808,
246 CONTRADICTION_INVALIDATION: 0x9810,
247 CODE_BLOCKED: 0x9840,
248 MAX_VALUE_REACHED: 0x9850,
249 GP_AUTH_FAILED: 0x6300,
250 LICENSING: 0x6f42,
251 HALTED: 0x6faa,
252};
253function getAltStatusMessage(code) {
254 switch (code) {
255 // improve text of most common errors
256 case 0x6700:
257 return "Incorrect length";
258 case 0x6800:
259 return "Missing critical parameter";
260 case 0x6982:
261 return "Security not satisfied (dongle locked or have invalid access rights)";
262 case 0x6985:
263 return "Condition of use not satisfied (denied by the user?)";
264 case 0x6a80:
265 return "Invalid data received";
266 case 0x6b00:
267 return "Invalid parameter received";
268 }
269 if (0x6f00 <= code && code <= 0x6fff) {
270 return "Internal error, please report";
271 }
272}
273/**
274 * Error thrown when a device returned a non success status.
275 * the error.statusCode is one of the `StatusCodes` exported by this library.
276 */
277function TransportStatusError(statusCode) {
278 this.name = "TransportStatusError";
279 var statusText = Object.keys(StatusCodes).find(function (k) { return StatusCodes[k] === statusCode; }) ||
280 "UNKNOWN_ERROR";
281 var smsg = getAltStatusMessage(statusCode) || statusText;
282 var statusCodeStr = statusCode.toString(16);
283 this.message = "Ledger device: " + smsg + " (0x" + statusCodeStr + ")";
284 this.stack = new Error().stack;
285 this.statusCode = statusCode;
286 this.statusText = statusText;
287}
288TransportStatusError.prototype = new Error();
289addCustomErrorDeserializer("TransportStatusError", function (e) { return new TransportStatusError(e.statusCode); });
290
291export { AccountNameRequiredError, AccountNotSupported, AmountRequired, BluetoothRequired, BtcUnmatchedApp, CantOpenDevice, CantScanQRCode, CashAddrNotSupported, CurrencyNotSupported, DBNotReset, DBWrongPassword, DeviceAppVerifyNotSupported, DeviceGenuineSocketEarlyClose, DeviceHalted, DeviceInOSUExpected, DeviceNameInvalid, DeviceNotGenuineError, DeviceOnDashboardExpected, DeviceOnDashboardUnexpected, DeviceShouldStayInApp, DeviceSocketFail, DeviceSocketNoBulkStatus, DisconnectedDevice, DisconnectedDeviceDuringOperation, ETHAddressNonEIP, EnpointConfigError, EthAppPleaseEnableContractData, FeeEstimationFailed, FeeNotLoaded, FeeRequired, FeeTooHigh, FirmwareNotRecognized, FirmwareOrAppUpdateRequired, GasLessThanEstimate, GenuineCheckFailed, HardResetFail, InvalidAddress, InvalidAddressBecauseDestinationIsAlsoSource, InvalidXRPTag, LatestMCUInstalledError, LedgerAPI4xx, LedgerAPI5xx, LedgerAPIError, LedgerAPIErrorWithMessage, LedgerAPINotAvailable, MCUNotGenuineToDashboard, ManagerAppAlreadyInstalledError, ManagerAppDepInstallRequired, ManagerAppDepUninstallRequired, ManagerAppRelyOnBTCError, ManagerDeviceLockedError, ManagerFirmwareNotEnoughSpaceError, ManagerNotEnoughSpaceError, ManagerUninstallBTCDep, NetworkDown, NoAccessToCamera, NoAddressesFound, NoDBPathGiven, NotEnoughBalance, NotEnoughBalanceBecauseDestinationNotCreated, NotEnoughBalanceInParentAccount, NotEnoughBalanceToDelegate, NotEnoughGas, NotEnoughSpendableBalance, NotSupportedLegacyAddress, PairingFailed, PasswordIncorrectError, PasswordsDontMatchError, RecipientRequired, RecommendSubAccountsToEmpty, RecommendUndelegation, StatusCodes, SyncError, TimeoutTagged, TransportError, TransportInterfaceNotAvailable, TransportOpenUserCancelled, TransportRaceCondition, TransportStatusError, TransportWebUSBGestureRequired, UnavailableTezosOriginatedAccountReceive, UnavailableTezosOriginatedAccountSend, UnexpectedBootloader, UnknownMCU, UpdateFetchFileFail, UpdateIncorrectHash, UpdateIncorrectSig, UpdateYourApp, UserRefusedAddress, UserRefusedAllowManager, UserRefusedDeviceNameChange, UserRefusedFirmwareUpdate, UserRefusedOnDevice, WebsocketConnectionError, WebsocketConnectionFailed, WrongAppForCurrency, WrongDeviceForAccount, addCustomErrorDeserializer, createCustomErrorClass, deserializeError, getAltStatusMessage, serializeError };