@radixdlt/primitives
Version:
69 lines • 2.83 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isUInt256 = exports.secureRandomUInt256 = exports.uint256Max = exports.bnFromUInt256 = exports.uint256FromUnsafe = exports.isUnsafeInputForUInt256 = exports.uint256FromBN = exports.fitsInUInt256 = void 0;
const tslib_1 = require("tslib");
const bn_js_1 = (0, tslib_1.__importDefault)(require("bn.js"));
const neverthrow_1 = require("neverthrow");
const uint256_1 = require("@radixdlt/uint256");
const util_1 = require("@radixdlt/util");
const bnUInt256Max = new bn_js_1.default(2).pow(new bn_js_1.default(256)).sub(new bn_js_1.default(1));
const fitsInUInt256 = (number) => {
const bn = new bn_js_1.default(number);
const isNotTooBig = bn.lte(bnUInt256Max);
const isNonNegative = bn.gte(new bn_js_1.default(0));
return isNotTooBig && isNonNegative;
};
exports.fitsInUInt256 = fitsInUInt256;
/**
* Converts a big number (BN) into a UInt256
*
* @param {BN} bn - A big number to be converted into a UInt256.
* @returns {UInt256} A 256 bit wide unsigned integer.
*/
const uint256FromBN = (bn) => {
if (!(0, exports.fitsInUInt256)(bn)) {
return (0, neverthrow_1.err)(new Error(`BN is either less than 0 or larger than 2^256 - 1, which does not fit in a UInt256.`));
}
return (0, neverthrow_1.ok)(new uint256_1.UInt256(bn.toString('hex'), 16));
};
exports.uint256FromBN = uint256FromBN;
// eslint-disable-next-line complexity
const isUnsafeInputForUInt256 = (something) => {
if (typeof something === 'number') {
return true;
}
else if (typeof something === 'string') {
return true;
}
else if ((0, util_1.isNumberArray)(something)) {
return true;
}
else if (something instanceof Uint8Array) {
return true;
}
else
return something instanceof Buffer;
};
exports.isUnsafeInputForUInt256 = isUnsafeInputForUInt256;
const uint256FromUnsafe = (unsafe) => {
// eslint-disable-next-line functional/no-try-statement
try {
const bn = new bn_js_1.default(unsafe);
return (0, exports.uint256FromBN)(bn);
}
catch (e) {
return (0, neverthrow_1.err)(e);
}
};
exports.uint256FromUnsafe = uint256FromUnsafe;
const bnFromUInt256 = (uint256) => new bn_js_1.default(uint256.toString(16), 'hex');
exports.bnFromUInt256 = bnFromUInt256;
exports.uint256Max = (0, exports.uint256FromBN)(bnUInt256Max)._unsafeUnwrap();
const secureRandomUInt256 = (secureRandom = util_1.secureRandomGenerator) => {
const randomBytes = secureRandom.randomSecureBytes(32);
return new uint256_1.UInt256(randomBytes, 16);
};
exports.secureRandomUInt256 = secureRandomUInt256;
const isUInt256 = (something) => something instanceof uint256_1.UInt256;
exports.isUInt256 = isUInt256;
//# sourceMappingURL=uint256-extensions.js.map