UNPKG

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