All files / ethers.js/src.ts/utils rlp-encode.ts

100% Statements 64/64
100% Branches 16/16
100% Functions 3/3
100% Lines 64/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 651x 1x 1x 1x 1x 1x 1x 483372x 483372x 483372x 525465x 525465x 525465x 483372x 483372x 1x 2622338x 2622338x 497339x 497339x 2418506x 497339x 497339x 497339x 116599x 116599x 116599x 380739x 380739x 380739x 380739x 380739x 380739x 380739x 2124999x 2124999x 2124999x 2622338x 136589x 136589x 2622338x 1885776x 1885776x 1885776x 102633x 102633x 102633x 102633x 102633x 102633x 1x 1x 1x 1x 1x 1x 1x 203832x 203832x 36505714x 36505714x 36505714x 203831x 203831x  
//See: https://github.com/ethereum/wiki/wiki/RLP
 
import { getBytes } from "./data.js";
 
import type { RlpStructuredDataish } from "./rlp.js";
 
 
function arrayifyInteger(value: number): Array<number> {
    const result: Array<number> = [];
    while (value) {
        result.unshift(value & 0xff);
        value >>= 8;
    }
    return result;
}
 
function _encode(object: Array<any> | string | Uint8Array): Array<number> {
    if (Array.isArray(object)) {
        let payload: Array<number> = [];
        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);
 
    }
 
    const data: Array<number> = Array.prototype.slice.call(getBytes(object, "object"));
 
    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";
 
/**
 *  Encodes %%object%% as an RLP-encoded [[DataHexString]].
 */
export function encodeRlp(object: RlpStructuredDataish): string {
    let result = "0x";
    for (const v of _encode(object)) {
        result += nibbles[v >> 4];
        result += nibbles[v & 0xf];
    }
    return result;
}