30 lines
766 B
TypeScript
Raw Normal View History

2022-02-04 14:12:00 +11:00
import { keccak256, Message } from "js-sha3";
import { fromString } from "uint8arrays/from-string";
import { toString } from "uint8arrays/to-string";
2022-01-13 11:33:26 +11:00
2022-02-14 10:50:02 +11:00
/**
* Convert input to a byte array.
*
* Handles both `0x` prefixed and non-prefixed strings.
2022-02-14 10:50:02 +11:00
*/
export function hexToBytes(hex: string | Uint8Array): Uint8Array {
if (typeof hex === "string") {
const _hex = hex.replace(/^0x/i, "");
return fromString(_hex, "base16");
2022-02-14 10:50:02 +11:00
}
return hex;
}
/**
* Convert byte array to hex string (no `0x` prefix).
*/
export const bytesToHex = (bytes: Uint8Array): string =>
toString(bytes, "base16");
2022-02-14 10:50:02 +11:00
2022-02-11 17:27:15 +11:00
/**
* Return Keccak-256 of the input.
*/
2022-02-16 14:08:48 +11:00
export function keccak256Buf(message: Message): Uint8Array {
return new Uint8Array(keccak256.arrayBuffer(message));
2022-01-13 11:33:26 +11:00
}