ethers.js/lib.commonjs/utils/rlp-encode.js

53 lines
1.5 KiB
JavaScript
Raw Normal View History

2022-09-05 23:57:11 +03:00
"use strict";
//See: https://github.com/ethereum/wiki/wiki/RLP
Object.defineProperty(exports, "__esModule", { value: true });
exports.encodeRlp = void 0;
2022-09-16 05:58:45 +03:00
const data_js_1 = require("./data.js");
2022-09-05 23:57:11 +03:00
function arrayifyInteger(value) {
const result = [];
while (value) {
result.unshift(value & 0xff);
value >>= 8;
}
return result;
}
function _encode(object) {
if (Array.isArray(object)) {
let payload = [];
object.forEach(function (child) {
payload = payload.concat(_encode(child));
});
if (payload.length <= 55) {
payload.unshift(0xc0 + payload.length);
return payload;
}
const length = arrayifyInteger(payload.length);
length.unshift(0xf7 + length.length);
return length.concat(payload);
}
2022-09-16 05:58:45 +03:00
const data = Array.prototype.slice.call((0, data_js_1.getBytes)(object, "object"));
2022-09-05 23:57:11 +03:00
if (data.length === 1 && data[0] <= 0x7f) {
return data;
}
else if (data.length <= 55) {
data.unshift(0x80 + data.length);
return data;
}
const length = arrayifyInteger(data.length);
length.unshift(0xb7 + length.length);
return length.concat(data);
}
const nibbles = "0123456789abcdef";
2022-09-16 05:58:45 +03:00
/**
* Encodes %%object%% as an RLP-encoded [[HexDataString]].
*/
2022-09-05 23:57:11 +03:00
function encodeRlp(object) {
let result = "0x";
for (const v of _encode(object)) {
result += nibbles[v >> 4];
result += nibbles[v & 0xf];
}
return result;
}
exports.encodeRlp = encodeRlp;
//# sourceMappingURL=rlp-encode.js.map