bytes.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. /*
  3. This file is part of web3.js.
  4. web3.js is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. web3.js is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License
  13. along with web3.js. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. Object.defineProperty(exports, "__esModule", { value: true });
  16. exports.isBytes = exports.isUint8Array = void 0;
  17. const utils_js_1 = require("../utils.js");
  18. const string_js_1 = require("./string.js");
  19. /**
  20. * checks input if typeof data is valid Uint8Array input
  21. */
  22. const isUint8Array = (data) => data instanceof Uint8Array;
  23. exports.isUint8Array = isUint8Array;
  24. const isBytes = (value, options = {
  25. abiType: 'bytes',
  26. }) => {
  27. if (typeof value !== 'string' && !Array.isArray(value) && !(value instanceof Uint8Array)) {
  28. return false;
  29. }
  30. // isHexStrict also accepts - prefix which can not exists in bytes
  31. if (typeof value === 'string' && (0, string_js_1.isHexStrict)(value) && value.startsWith('-')) {
  32. return false;
  33. }
  34. if (typeof value === 'string' && !(0, string_js_1.isHexStrict)(value)) {
  35. return false;
  36. }
  37. let valueToCheck;
  38. if (typeof value === 'string') {
  39. if (value.length % 2 !== 0) {
  40. // odd length hex
  41. return false;
  42. }
  43. valueToCheck = (0, utils_js_1.hexToUint8Array)(value);
  44. }
  45. else if (Array.isArray(value)) {
  46. if (value.some(d => d < 0 || d > 255 || !Number.isInteger(d))) {
  47. return false;
  48. }
  49. valueToCheck = new Uint8Array(value);
  50. }
  51. else {
  52. valueToCheck = value;
  53. }
  54. if (options === null || options === void 0 ? void 0 : options.abiType) {
  55. const { baseTypeSize } = (0, utils_js_1.parseBaseType)(options.abiType);
  56. return baseTypeSize ? valueToCheck.length === baseTypeSize : true;
  57. }
  58. if (options === null || options === void 0 ? void 0 : options.size) {
  59. return valueToCheck.length === (options === null || options === void 0 ? void 0 : options.size);
  60. }
  61. return true;
  62. };
  63. exports.isBytes = isBytes;
  64. //# sourceMappingURL=bytes.js.map