UNPKG

1.67 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 { u8aConcatStrict } from "./concat.js";
5import { u8aEq } from "./eq.js";
6import { u8aToU8a } from "./toU8a.js";
7/** @internal */
8
9export const U8A_WRAP_ETHEREUM = u8aToU8a('\x19Ethereum Signed Message:\n');
10/** @internal */
11
12export const U8A_WRAP_PREFIX = u8aToU8a('<Bytes>');
13/** @internal */
14
15export const U8A_WRAP_POSTFIX = u8aToU8a('</Bytes>');
16const WRAP_LEN = U8A_WRAP_PREFIX.length + U8A_WRAP_POSTFIX.length;
17/** @internal */
18
19export function u8aIsWrapped(u8a, withEthereum) {
20 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);
21}
22/**
23 * @name u8aUnwrapBytes
24 * @description Removes all <Bytes>...</Bytes> wrappers from the supplied value
25 */
26
27export function u8aUnwrapBytes(bytes) {
28 const u8a = u8aToU8a(bytes); // we don't want to unwrap Ethereum-style wraps
29
30 return u8aIsWrapped(u8a, false) ? u8a.subarray(U8A_WRAP_PREFIX.length, u8a.length - U8A_WRAP_POSTFIX.length) : u8a;
31}
32/**
33 * @name u8aWrapBytes
34 * @description Adds a <Bytes>...</Bytes> wrapper to the supplied value (if not already existing)
35 */
36
37export function u8aWrapBytes(bytes) {
38 const u8a = u8aToU8a(bytes); // if Ethereum-wrapping, we don't add our wrapping bytes
39
40 return u8aIsWrapped(u8a, true) ? u8a : u8aConcatStrict([U8A_WRAP_PREFIX, u8a, U8A_WRAP_POSTFIX]);
41}
\No newline at end of file