@exodus/ethereumjs-util
Version:
A collection of utility functions for Ethereum
198 lines • 6.07 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.baToJSON = exports.addHexPrefix = exports.toUnsigned = exports.fromSigned = exports.bufferToHex = exports.bufferToInt = exports.toBuffer = exports.unpadHexString = exports.unpadArray = exports.unpadBuffer = exports.setLengthRight = exports.setLengthLeft = exports.zeros = void 0;
const bn_js_1 = __importDefault(require("bn.js"));
const ethjs_util_1 = require("ethjs-util");
const helpers_1 = require("./helpers");
/**
* Returns a buffer filled with 0s.
* @param bytes the number of bytes the buffer should be
*/
exports.zeros = function (bytes) {
return Buffer.allocUnsafe(bytes).fill(0);
};
/**
* Pads a `Buffer` with zeros till it has `length` bytes.
* Truncates the beginning or end of input if its length exceeds `length`.
* @param msg the value to pad (Buffer)
* @param length the number of bytes the output should be
* @param right whether to start padding form the left or right
* @return (Buffer)
*/
const setLength = function (msg, length, right) {
const buf = exports.zeros(length);
if (right) {
if (msg.length < length) {
msg.copy(buf);
return buf;
}
return msg.slice(0, length);
}
else {
if (msg.length < length) {
msg.copy(buf, length - msg.length);
return buf;
}
return msg.slice(-length);
}
};
/**
* Left Pads a `Buffer` with leading zeros till it has `length` bytes.
* Or it truncates the beginning if it exceeds.
* @param msg the value to pad (Buffer)
* @param length the number of bytes the output should be
* @return (Buffer)
*/
exports.setLengthLeft = function (msg, length) {
helpers_1.assertIsBuffer(msg);
return setLength(msg, length, false);
};
/**
* Right Pads a `Buffer` with trailing zeros till it has `length` bytes.
* it truncates the end if it exceeds.
* @param msg the value to pad (Buffer)
* @param length the number of bytes the output should be
* @return (Buffer)
*/
exports.setLengthRight = function (msg, length) {
helpers_1.assertIsBuffer(msg);
return setLength(msg, length, true);
};
/**
* Trims leading zeros from a `Buffer`, `String` or `Number[]`.
* @param a (Buffer|Array|String)
* @return (Buffer|Array|String)
*/
const stripZeros = function (a) {
let first = a[0];
while (a.length > 0 && first.toString() === '0') {
a = a.slice(1);
first = a[0];
}
return a;
};
/**
* Trims leading zeros from a `Buffer`.
* @param a (Buffer)
* @return (Buffer)
*/
exports.unpadBuffer = function (a) {
helpers_1.assertIsBuffer(a);
return stripZeros(a);
};
/**
* Trims leading zeros from an `Array` (of numbers).
* @param a (number[])
* @return (number[])
*/
exports.unpadArray = function (a) {
helpers_1.assertIsArray(a);
return stripZeros(a);
};
/**
* Trims leading zeros from a hex-prefixed `String`.
* @param a (String)
* @return (String)
*/
exports.unpadHexString = function (a) {
helpers_1.assertIsHexString(a);
a = ethjs_util_1.stripHexPrefix(a);
return stripZeros(a);
};
/**
* Attempts to turn a value into a `Buffer`.
* Inputs supported: `Buffer`, `String` (hex-prefixed), `Number`, null/undefined, `BN` and other objects
* with a `toArray()` or `toBuffer()` method.
* @param v the value
*/
exports.toBuffer = function (v) {
if (v === null || v === undefined) {
return Buffer.allocUnsafe(0);
}
if (Buffer.isBuffer(v)) {
return Buffer.from(v);
}
if (Array.isArray(v) || v instanceof Uint8Array) {
return Buffer.from(v);
}
if (typeof v === 'string') {
if (!ethjs_util_1.isHexString(v)) {
throw new Error(`Cannot convert string to buffer. toBuffer only supports 0x-prefixed hex strings and this string was given: ${v}`);
}
return Buffer.from(ethjs_util_1.padToEven(ethjs_util_1.stripHexPrefix(v)), 'hex');
}
if (typeof v === 'number') {
return ethjs_util_1.intToBuffer(v);
}
if (bn_js_1.default.isBN(v)) {
return v.toArrayLike(Buffer);
}
if (v.toArray) {
// converts a BN to a Buffer
return Buffer.from(v.toArray());
}
if (v.toBuffer) {
return Buffer.from(v.toBuffer());
}
throw new Error('invalid type');
};
/**
* Converts a `Buffer` to a `Number`.
* @param buf `Buffer` object to convert
* @throws If the input number exceeds 53 bits.
*/
exports.bufferToInt = function (buf) {
return new bn_js_1.default(exports.toBuffer(buf)).toNumber();
};
/**
* Converts a `Buffer` into a `0x`-prefixed hex `String`.
* @param buf `Buffer` object to convert
*/
exports.bufferToHex = function (buf) {
buf = exports.toBuffer(buf);
return '0x' + buf.toString('hex');
};
/**
* Interprets a `Buffer` as a signed integer and returns a `BN`. Assumes 256-bit numbers.
* @param num Signed integer value
*/
exports.fromSigned = function (num) {
return new bn_js_1.default(num).fromTwos(256);
};
/**
* Converts a `BN` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers.
* @param num
*/
exports.toUnsigned = function (num) {
return Buffer.from(num.toTwos(256).toArray());
};
/**
* Adds "0x" to a given `String` if it does not already start with "0x".
*/
exports.addHexPrefix = function (str) {
if (typeof str !== 'string') {
return str;
}
return ethjs_util_1.isHexPrefixed(str) ? str : '0x' + str;
};
/**
* Converts a `Buffer` or `Array` to JSON.
* @param ba (Buffer|Array)
* @return (Array|String|null)
*/
exports.baToJSON = function (ba) {
if (Buffer.isBuffer(ba)) {
return `0x${ba.toString('hex')}`;
}
else if (ba instanceof Array) {
const array = [];
for (let i = 0; i < ba.length; i++) {
array.push(exports.baToJSON(ba[i]));
}
return array;
}
};
//# sourceMappingURL=bytes.js.map