index.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. "use strict";
  2. let _permanentCensorErrors = false;
  3. let _censorErrors = false;
  4. const LogLevels = { debug: 1, "default": 2, info: 2, warning: 3, error: 4, off: 5 };
  5. let _logLevel = LogLevels["default"];
  6. import { version } from "./_version";
  7. let _globalLogger = null;
  8. function _checkNormalize() {
  9. try {
  10. const missing = [];
  11. // Make sure all forms of normalization are supported
  12. ["NFD", "NFC", "NFKD", "NFKC"].forEach((form) => {
  13. try {
  14. if ("test".normalize(form) !== "test") {
  15. throw new Error("bad normalize");
  16. }
  17. ;
  18. }
  19. catch (error) {
  20. missing.push(form);
  21. }
  22. });
  23. if (missing.length) {
  24. throw new Error("missing " + missing.join(", "));
  25. }
  26. if (String.fromCharCode(0xe9).normalize("NFD") !== String.fromCharCode(0x65, 0x0301)) {
  27. throw new Error("broken implementation");
  28. }
  29. }
  30. catch (error) {
  31. return error.message;
  32. }
  33. return null;
  34. }
  35. const _normalizeError = _checkNormalize();
  36. export var LogLevel;
  37. (function (LogLevel) {
  38. LogLevel["DEBUG"] = "DEBUG";
  39. LogLevel["INFO"] = "INFO";
  40. LogLevel["WARNING"] = "WARNING";
  41. LogLevel["ERROR"] = "ERROR";
  42. LogLevel["OFF"] = "OFF";
  43. })(LogLevel || (LogLevel = {}));
  44. export var ErrorCode;
  45. (function (ErrorCode) {
  46. ///////////////////
  47. // Generic Errors
  48. // Unknown Error
  49. ErrorCode["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
  50. // Not Implemented
  51. ErrorCode["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED";
  52. // Unsupported Operation
  53. // - operation
  54. ErrorCode["UNSUPPORTED_OPERATION"] = "UNSUPPORTED_OPERATION";
  55. // Network Error (i.e. Ethereum Network, such as an invalid chain ID)
  56. // - event ("noNetwork" is not re-thrown in provider.ready; otherwise thrown)
  57. ErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
  58. // Some sort of bad response from the server
  59. ErrorCode["SERVER_ERROR"] = "SERVER_ERROR";
  60. // Timeout
  61. ErrorCode["TIMEOUT"] = "TIMEOUT";
  62. ///////////////////
  63. // Operational Errors
  64. // Buffer Overrun
  65. ErrorCode["BUFFER_OVERRUN"] = "BUFFER_OVERRUN";
  66. // Numeric Fault
  67. // - operation: the operation being executed
  68. // - fault: the reason this faulted
  69. ErrorCode["NUMERIC_FAULT"] = "NUMERIC_FAULT";
  70. ///////////////////
  71. // Argument Errors
  72. // Missing new operator to an object
  73. // - name: The name of the class
  74. ErrorCode["MISSING_NEW"] = "MISSING_NEW";
  75. // Invalid argument (e.g. value is incompatible with type) to a function:
  76. // - argument: The argument name that was invalid
  77. // - value: The value of the argument
  78. ErrorCode["INVALID_ARGUMENT"] = "INVALID_ARGUMENT";
  79. // Missing argument to a function:
  80. // - count: The number of arguments received
  81. // - expectedCount: The number of arguments expected
  82. ErrorCode["MISSING_ARGUMENT"] = "MISSING_ARGUMENT";
  83. // Too many arguments
  84. // - count: The number of arguments received
  85. // - expectedCount: The number of arguments expected
  86. ErrorCode["UNEXPECTED_ARGUMENT"] = "UNEXPECTED_ARGUMENT";
  87. ///////////////////
  88. // Blockchain Errors
  89. // Call exception
  90. // - transaction: the transaction
  91. // - address?: the contract address
  92. // - args?: The arguments passed into the function
  93. // - method?: The Solidity method signature
  94. // - errorSignature?: The EIP848 error signature
  95. // - errorArgs?: The EIP848 error parameters
  96. // - reason: The reason (only for EIP848 "Error(string)")
  97. ErrorCode["CALL_EXCEPTION"] = "CALL_EXCEPTION";
  98. // Insufficient funds (< value + gasLimit * gasPrice)
  99. // - transaction: the transaction attempted
  100. ErrorCode["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS";
  101. // Nonce has already been used
  102. // - transaction: the transaction attempted
  103. ErrorCode["NONCE_EXPIRED"] = "NONCE_EXPIRED";
  104. // The replacement fee for the transaction is too low
  105. // - transaction: the transaction attempted
  106. ErrorCode["REPLACEMENT_UNDERPRICED"] = "REPLACEMENT_UNDERPRICED";
  107. // The gas limit could not be estimated
  108. // - transaction: the transaction passed to estimateGas
  109. ErrorCode["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT";
  110. // The transaction was replaced by one with a higher gas price
  111. // - reason: "cancelled", "replaced" or "repriced"
  112. // - cancelled: true if reason == "cancelled" or reason == "replaced")
  113. // - hash: original transaction hash
  114. // - replacement: the full TransactionsResponse for the replacement
  115. // - receipt: the receipt of the replacement
  116. ErrorCode["TRANSACTION_REPLACED"] = "TRANSACTION_REPLACED";
  117. })(ErrorCode || (ErrorCode = {}));
  118. ;
  119. const HEX = "0123456789abcdef";
  120. export class Logger {
  121. constructor(version) {
  122. Object.defineProperty(this, "version", {
  123. enumerable: true,
  124. value: version,
  125. writable: false
  126. });
  127. }
  128. _log(logLevel, args) {
  129. const level = logLevel.toLowerCase();
  130. if (LogLevels[level] == null) {
  131. this.throwArgumentError("invalid log level name", "logLevel", logLevel);
  132. }
  133. if (_logLevel > LogLevels[level]) {
  134. return;
  135. }
  136. console.log.apply(console, args);
  137. }
  138. debug(...args) {
  139. this._log(Logger.levels.DEBUG, args);
  140. }
  141. info(...args) {
  142. this._log(Logger.levels.INFO, args);
  143. }
  144. warn(...args) {
  145. this._log(Logger.levels.WARNING, args);
  146. }
  147. makeError(message, code, params) {
  148. // Errors are being censored
  149. if (_censorErrors) {
  150. return this.makeError("censored error", code, {});
  151. }
  152. if (!code) {
  153. code = Logger.errors.UNKNOWN_ERROR;
  154. }
  155. if (!params) {
  156. params = {};
  157. }
  158. const messageDetails = [];
  159. Object.keys(params).forEach((key) => {
  160. const value = params[key];
  161. try {
  162. if (value instanceof Uint8Array) {
  163. let hex = "";
  164. for (let i = 0; i < value.length; i++) {
  165. hex += HEX[value[i] >> 4];
  166. hex += HEX[value[i] & 0x0f];
  167. }
  168. messageDetails.push(key + "=Uint8Array(0x" + hex + ")");
  169. }
  170. else {
  171. messageDetails.push(key + "=" + JSON.stringify(value));
  172. }
  173. }
  174. catch (error) {
  175. messageDetails.push(key + "=" + JSON.stringify(params[key].toString()));
  176. }
  177. });
  178. messageDetails.push(`code=${code}`);
  179. messageDetails.push(`version=${this.version}`);
  180. const reason = message;
  181. let url = "";
  182. switch (code) {
  183. case ErrorCode.NUMERIC_FAULT: {
  184. url = "NUMERIC_FAULT";
  185. const fault = message;
  186. switch (fault) {
  187. case "overflow":
  188. case "underflow":
  189. case "division-by-zero":
  190. url += "-" + fault;
  191. break;
  192. case "negative-power":
  193. case "negative-width":
  194. url += "-unsupported";
  195. break;
  196. case "unbound-bitwise-result":
  197. url += "-unbound-result";
  198. break;
  199. }
  200. break;
  201. }
  202. case ErrorCode.CALL_EXCEPTION:
  203. case ErrorCode.INSUFFICIENT_FUNDS:
  204. case ErrorCode.MISSING_NEW:
  205. case ErrorCode.NONCE_EXPIRED:
  206. case ErrorCode.REPLACEMENT_UNDERPRICED:
  207. case ErrorCode.TRANSACTION_REPLACED:
  208. case ErrorCode.UNPREDICTABLE_GAS_LIMIT:
  209. url = code;
  210. break;
  211. }
  212. if (url) {
  213. message += " [ See: https:/\/links.ethers.org/v5-errors-" + url + " ]";
  214. }
  215. if (messageDetails.length) {
  216. message += " (" + messageDetails.join(", ") + ")";
  217. }
  218. // @TODO: Any??
  219. const error = new Error(message);
  220. error.reason = reason;
  221. error.code = code;
  222. Object.keys(params).forEach(function (key) {
  223. error[key] = params[key];
  224. });
  225. return error;
  226. }
  227. throwError(message, code, params) {
  228. throw this.makeError(message, code, params);
  229. }
  230. throwArgumentError(message, name, value) {
  231. return this.throwError(message, Logger.errors.INVALID_ARGUMENT, {
  232. argument: name,
  233. value: value
  234. });
  235. }
  236. assert(condition, message, code, params) {
  237. if (!!condition) {
  238. return;
  239. }
  240. this.throwError(message, code, params);
  241. }
  242. assertArgument(condition, message, name, value) {
  243. if (!!condition) {
  244. return;
  245. }
  246. this.throwArgumentError(message, name, value);
  247. }
  248. checkNormalize(message) {
  249. if (message == null) {
  250. message = "platform missing String.prototype.normalize";
  251. }
  252. if (_normalizeError) {
  253. this.throwError("platform missing String.prototype.normalize", Logger.errors.UNSUPPORTED_OPERATION, {
  254. operation: "String.prototype.normalize", form: _normalizeError
  255. });
  256. }
  257. }
  258. checkSafeUint53(value, message) {
  259. if (typeof (value) !== "number") {
  260. return;
  261. }
  262. if (message == null) {
  263. message = "value not safe";
  264. }
  265. if (value < 0 || value >= 0x1fffffffffffff) {
  266. this.throwError(message, Logger.errors.NUMERIC_FAULT, {
  267. operation: "checkSafeInteger",
  268. fault: "out-of-safe-range",
  269. value: value
  270. });
  271. }
  272. if (value % 1) {
  273. this.throwError(message, Logger.errors.NUMERIC_FAULT, {
  274. operation: "checkSafeInteger",
  275. fault: "non-integer",
  276. value: value
  277. });
  278. }
  279. }
  280. checkArgumentCount(count, expectedCount, message) {
  281. if (message) {
  282. message = ": " + message;
  283. }
  284. else {
  285. message = "";
  286. }
  287. if (count < expectedCount) {
  288. this.throwError("missing argument" + message, Logger.errors.MISSING_ARGUMENT, {
  289. count: count,
  290. expectedCount: expectedCount
  291. });
  292. }
  293. if (count > expectedCount) {
  294. this.throwError("too many arguments" + message, Logger.errors.UNEXPECTED_ARGUMENT, {
  295. count: count,
  296. expectedCount: expectedCount
  297. });
  298. }
  299. }
  300. checkNew(target, kind) {
  301. if (target === Object || target == null) {
  302. this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name });
  303. }
  304. }
  305. checkAbstract(target, kind) {
  306. if (target === kind) {
  307. this.throwError("cannot instantiate abstract class " + JSON.stringify(kind.name) + " directly; use a sub-class", Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: "new" });
  308. }
  309. else if (target === Object || target == null) {
  310. this.throwError("missing new", Logger.errors.MISSING_NEW, { name: kind.name });
  311. }
  312. }
  313. static globalLogger() {
  314. if (!_globalLogger) {
  315. _globalLogger = new Logger(version);
  316. }
  317. return _globalLogger;
  318. }
  319. static setCensorship(censorship, permanent) {
  320. if (!censorship && permanent) {
  321. this.globalLogger().throwError("cannot permanently disable censorship", Logger.errors.UNSUPPORTED_OPERATION, {
  322. operation: "setCensorship"
  323. });
  324. }
  325. if (_permanentCensorErrors) {
  326. if (!censorship) {
  327. return;
  328. }
  329. this.globalLogger().throwError("error censorship permanent", Logger.errors.UNSUPPORTED_OPERATION, {
  330. operation: "setCensorship"
  331. });
  332. }
  333. _censorErrors = !!censorship;
  334. _permanentCensorErrors = !!permanent;
  335. }
  336. static setLogLevel(logLevel) {
  337. const level = LogLevels[logLevel.toLowerCase()];
  338. if (level == null) {
  339. Logger.globalLogger().warn("invalid log level - " + logLevel);
  340. return;
  341. }
  342. _logLevel = level;
  343. }
  344. static from(version) {
  345. return new Logger(version);
  346. }
  347. }
  348. Logger.errors = ErrorCode;
  349. Logger.levels = LogLevel;
  350. //# sourceMappingURL=index.js.map