UNPKG

1.65 kBJavaScriptView Raw
1import { u8aConcatStrict } from './concat.js';
2import { u8aEq } from './eq.js';
3import { u8aToU8a } from './toU8a.js';
4/** @internal */
5export const U8A_WRAP_ETHEREUM = /*#__PURE__*/ u8aToU8a('\x19Ethereum Signed Message:\n');
6/** @internal */
7export const U8A_WRAP_PREFIX = /*#__PURE__*/ u8aToU8a('<Bytes>');
8/** @internal */
9export const U8A_WRAP_POSTFIX = /*#__PURE__*/ u8aToU8a('</Bytes>');
10const WRAP_LEN = U8A_WRAP_PREFIX.length + U8A_WRAP_POSTFIX.length;
11/** @internal */
12export function u8aIsWrapped(u8a, withEthereum) {
13 return ((u8a.length >= WRAP_LEN &&
14 u8aEq(u8a.subarray(0, U8A_WRAP_PREFIX.length), U8A_WRAP_PREFIX) &&
15 u8aEq(u8a.slice(-U8A_WRAP_POSTFIX.length), U8A_WRAP_POSTFIX)) ||
16 (withEthereum &&
17 u8a.length >= U8A_WRAP_ETHEREUM.length &&
18 u8aEq(u8a.subarray(0, U8A_WRAP_ETHEREUM.length), U8A_WRAP_ETHEREUM)));
19}
20/**
21 * @name u8aUnwrapBytes
22 * @description Removes all <Bytes>...</Bytes> wrappers from the supplied value
23 */
24export function u8aUnwrapBytes(bytes) {
25 const u8a = u8aToU8a(bytes);
26 // we don't want to unwrap Ethereum-style wraps
27 return u8aIsWrapped(u8a, false)
28 ? u8a.subarray(U8A_WRAP_PREFIX.length, u8a.length - U8A_WRAP_POSTFIX.length)
29 : u8a;
30}
31/**
32 * @name u8aWrapBytes
33 * @description
34 * Adds a <Bytes>...</Bytes> wrapper to the supplied value, if
35 * - We don't already have a Bytes wrapper
36 * - The message is not an Ethereum-style message
37 */
38export function u8aWrapBytes(bytes) {
39 const u8a = u8aToU8a(bytes);
40 return u8aIsWrapped(u8a, true)
41 ? u8a
42 : u8aConcatStrict([U8A_WRAP_PREFIX, u8a, U8A_WRAP_POSTFIX]);
43}