UNPKG

1.34 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3// Originally from https://github.com/polkadot-js/extension/pull/743
4import { u8aConcat } from "./concat.js";
5import { u8aEq } from "./eq.js";
6import { u8aToU8a } from "./toU8a.js";
7export const U8A_WRAP_ETHEREUM = u8aToU8a('\x19Ethereum Signed Message:\n');
8export const U8A_WRAP_PREFIX = u8aToU8a('<Bytes>');
9export const U8A_WRAP_POSTFIX = u8aToU8a('</Bytes>');
10const WRAP_LEN = U8A_WRAP_PREFIX.length + U8A_WRAP_POSTFIX.length;
11export function u8aIsWrapped(u8a, withEthereum) {
12 return u8a.length >= WRAP_LEN && u8aEq(u8a.subarray(0, U8A_WRAP_PREFIX.length), U8A_WRAP_PREFIX) && u8aEq(u8a.slice(-U8A_WRAP_POSTFIX.length), U8A_WRAP_POSTFIX) || withEthereum && u8a.length >= U8A_WRAP_ETHEREUM.length && u8aEq(u8a.subarray(0, U8A_WRAP_ETHEREUM.length), U8A_WRAP_ETHEREUM);
13}
14export function u8aUnwrapBytes(bytes) {
15 const u8a = u8aToU8a(bytes); // we don't want to unwrap Ethereum-style wraps
16
17 return u8aIsWrapped(u8a, false) ? u8a.subarray(U8A_WRAP_PREFIX.length, u8a.length - U8A_WRAP_POSTFIX.length) : u8a;
18}
19export function u8aWrapBytes(bytes) {
20 const u8a = u8aToU8a(bytes); // if Ethereum-wrapping, we don't add our wrapping bytes
21
22 return u8aIsWrapped(u8a, true) ? u8a : u8aConcat(U8A_WRAP_PREFIX, u8a, U8A_WRAP_POSTFIX);
23}
\No newline at end of file