Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8f24a2758e | ||
|
|
3230663ae1 | ||
|
|
4a0fa7f615 | ||
|
|
0f05954dc5 | ||
|
|
55f442f9fa | ||
|
|
7e5edc46a3 | ||
|
|
d500f98fb4 | ||
|
|
7b8902ce3f | ||
|
|
98b3ad642f | ||
|
|
14466e27ac | ||
|
|
16ffd1b467 | ||
|
|
ca52fd7e5b | ||
|
|
ea5d3df64c | ||
|
|
b51ed71796 | ||
|
|
bf28507ae8 | ||
|
|
6715bef24a | ||
|
|
badbbd76cb | ||
|
|
253776a510 | ||
|
|
e1ef295bfa | ||
|
|
73c89f4e3c | ||
|
|
a52e0dfb16 | ||
|
|
9f8ed7bb50 | ||
|
|
a932f9408a | ||
|
|
7907ce6dbf | ||
|
|
230d510491 | ||
|
|
415fd1b2d1 | ||
|
|
89c954216d | ||
|
|
b689796b25 | ||
|
|
c4c18d324b | ||
|
|
b7bf500343 |
@@ -1,4 +0,0 @@
|
||||
// Copyright 2017-2020 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
module.exports = require('./babel.config.js');
|
||||
@@ -1,4 +0,0 @@
|
||||
.eslintrc.js
|
||||
**/build/*
|
||||
**/coverage/*
|
||||
**/node_modules/*
|
||||
@@ -5,6 +5,15 @@ const base = require('@polkadot/dev/config/eslint');
|
||||
|
||||
module.exports = {
|
||||
...base,
|
||||
ignorePatterns: [
|
||||
'.eslintrc.js',
|
||||
'.github/**',
|
||||
'.vscode/**',
|
||||
'.yarn/**',
|
||||
'**/build/*',
|
||||
'**/coverage/*',
|
||||
'**/node_modules/*'
|
||||
],
|
||||
parserOptions: {
|
||||
...base.parserOptions,
|
||||
project: [
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
---
|
||||
assignees: ['jacogr']
|
||||
title: SS58 registry is outdated
|
||||
labels: ci
|
||||
labels: ['ci', '@networks']
|
||||
---
|
||||
|
||||
cc @jacogr
|
||||
|
||||
Discrepancies detected between https://github.com/paritytech/substrate/blob/master/ss58-registry.json and https://github.com/polkadot-js/common/blob/master/packages/networks/src/index.ts
|
||||
|
||||
Check the nightly cron output or run `yarn networks:crosscheck` locally. The output as found from the test includes:
|
||||
|
||||
@@ -9,7 +9,7 @@ jobs:
|
||||
name: ${{ matrix.step }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v2
|
||||
- name: ${{ matrix.step }}
|
||||
env:
|
||||
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
|
||||
|
||||
@@ -13,7 +13,7 @@ jobs:
|
||||
if: "! startsWith(github.event.head_commit.message, '[CI Skip]') && github.repository == 'polkadot-js/common'"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v2
|
||||
with:
|
||||
token: ${{ secrets.GH_PAT }}
|
||||
- name: ${{ matrix.step }}
|
||||
|
||||
@@ -7,7 +7,7 @@ jobs:
|
||||
ss58:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/checkout@v2
|
||||
- name: check
|
||||
env:
|
||||
CI_LOG: 123
|
||||
|
||||
Vendored
-55
File diff suppressed because one or more lines are too long
+55
File diff suppressed because one or more lines are too long
+1
-1
@@ -12,4 +12,4 @@ plugins:
|
||||
- path: .yarn/plugins/@yarnpkg/plugin-workspace-tools.cjs
|
||||
spec: "@yarnpkg/plugin-workspace-tools"
|
||||
|
||||
yarnPath: .yarn/releases/yarn-2.2.2.cjs
|
||||
yarnPath: .yarn/releases/yarn-2.3.3.cjs
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
# CHANGELOG
|
||||
|
||||
## 3.7.1 Nov 1, 2020
|
||||
|
||||
Changes:
|
||||
|
||||
- Remove the use of `chalk` (logger) for less overall dependencies
|
||||
- `string*` utilities now also allows `String` (class) inputs
|
||||
- Align bip39 use with wasm-crypto for English-only wordlist, default, non supplied)
|
||||
- Adjust elliptic imports for explicit paths (allows tree-shaking)
|
||||
- Add Totem (ss58 prefix 14) into `@polkadot/networks`
|
||||
- Move `@polkadot/x-{fetch,textdecoder,textencoder,ws}` into `common` repo
|
||||
|
||||
|
||||
## 3.6.1 Oct 18, 2020
|
||||
|
||||
Contributed:
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Copyright 2017-2020 @polkadot/util authors & contributors
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
function copy_folder () {
|
||||
SRC="packages/$1/build"
|
||||
DST="../apps/node_modules/@polkadot/$1"
|
||||
|
||||
echo "** Copying $SRC to $DST"
|
||||
|
||||
rm -rf $DST
|
||||
cp -r $SRC $DST
|
||||
}
|
||||
|
||||
yarn polkadot-dev-build-ts
|
||||
|
||||
copy_folder "keyring"
|
||||
copy_folder "util"
|
||||
copy_folder "util-crypto"
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="initial-scale=0.5, maximum-scale=1">
|
||||
<meta http-equiv="refresh" content="0;URL='https://polkadot.js.org/docs/'" />
|
||||
<title>Redirecting to https://polkadot.js.org/docs/</title>
|
||||
</head>
|
||||
<body>
|
||||
Redirecting to <a href="https://polkadot.js.org/docs/">https://polkadot.js.org/docs/</a>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="initial-scale=0.5, maximum-scale=1">
|
||||
<meta http-equiv="refresh" content="0;URL='https://polkadot.js.org/docs/'" />
|
||||
<title>Redirecting to https://polkadot.js.org/docs/</title>
|
||||
</head>
|
||||
<body>
|
||||
Redirecting to <a href="https://polkadot.js.org/docs/">https://polkadot.js.org/docs/</a>
|
||||
</body>
|
||||
</html>
|
||||
+8
-3
@@ -9,13 +9,18 @@ module.exports = Object.assign({}, config, {
|
||||
'@polkadot/networks(.*)$': '<rootDir>/packages/networks/src/$1',
|
||||
'@polkadot/util-(crypto)(.*)$': '<rootDir>/packages/util-$1/src/$2',
|
||||
// eslint-disable-next-line sort-keys
|
||||
'@polkadot/util(.*)$': '<rootDir>/packages/util/src/$1'
|
||||
'@polkadot/util(.*)$': '<rootDir>/packages/util/src/$1',
|
||||
'@polkadot/x-(fetch|textdecoder|textencoder|ws)(.*)$': '<rootDir>/packages/x-$1/src/node'
|
||||
},
|
||||
modulePathIgnorePatterns: [
|
||||
'<rootDir>/packages/keyring/build',
|
||||
'<rootDir>/packages/networks/build',
|
||||
'<rootDir>/packages/util/build',
|
||||
'<rootDir>/packages/util-crypto/build'
|
||||
'<rootDir>/packages/util-crypto/build',
|
||||
'<rootDir>/packages/x-fetch/build',
|
||||
'<rootDir>/packages/x-textdecoder/build',
|
||||
'<rootDir>/packages/x-textencoder/build',
|
||||
'<rootDir>/packages/x-ws/build'
|
||||
],
|
||||
resolver: './jest.resolver.js'
|
||||
resolver: '@polkadot/dev/config/jest-resolver'
|
||||
});
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
// Copyright 2017-2020 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
const path = require('path');
|
||||
|
||||
module.exports = function resolver (file, config) {
|
||||
return file.includes('package.json')
|
||||
? path.join(config.basedir.replace('/src', '/'), file)
|
||||
: config.defaultResolver(file, config);
|
||||
};
|
||||
+5
-5
@@ -8,7 +8,7 @@
|
||||
],
|
||||
"resolutions": {
|
||||
"babel-core": "^7.0.0-bridge.0",
|
||||
"typescript": "^4.0.3"
|
||||
"typescript": "^4.0.5"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "polkadot-dev-build-ts",
|
||||
@@ -22,9 +22,9 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/core": "^7.12.3",
|
||||
"@polkadot/dev": "^0.58.3",
|
||||
"@polkadot/ts": "^0.3.49",
|
||||
"@types/jest": "^26.0.14"
|
||||
"@polkadot/dev": "^0.59.12",
|
||||
"@polkadot/ts": "^0.3.53",
|
||||
"@types/jest": "^26.0.15"
|
||||
},
|
||||
"version": "3.6.1"
|
||||
"version": "3.7.1"
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/keyring",
|
||||
"version": "3.6.1",
|
||||
"version": "3.7.1",
|
||||
"description": "Keyring management",
|
||||
"main": "index.js",
|
||||
"publishConfig": {
|
||||
@@ -28,7 +28,7 @@
|
||||
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/keyring#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.1",
|
||||
"@polkadot/util": "3.6.1",
|
||||
"@polkadot/util-crypto": "3.6.1"
|
||||
"@polkadot/util": "^3.7.1",
|
||||
"@polkadot/util-crypto": "^3.7.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/networks",
|
||||
"version": "3.6.1",
|
||||
"version": "3.7.1",
|
||||
"description": "A list of all available Substrate networks and their applicable prefixes",
|
||||
"main": "index.js",
|
||||
"publishConfig": {
|
||||
@@ -13,8 +13,7 @@
|
||||
},
|
||||
"keywords": [
|
||||
"Polkadot",
|
||||
"Keyring",
|
||||
"ed25519"
|
||||
"ss58"
|
||||
],
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"maintainers": [
|
||||
@@ -30,7 +29,7 @@
|
||||
"@babel/runtime": "^7.12.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@polkadot/util": "3.6.1",
|
||||
"@polkadot/x-fetch": "^0.3.3"
|
||||
"@polkadot/util": "^3.7.1",
|
||||
"@polkadot/x-fetch": "^3.7.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,16 @@ const UNSORTED = [0, 2, 42];
|
||||
// last. This make lookups for the current a simple genesisHash[0]
|
||||
// (See Kusama as an example)
|
||||
|
||||
const createReserved = (prefix: number, displayName = 'This prefix is reserved.'): NetworkFromSubstrate => ({
|
||||
decimals: null,
|
||||
displayName,
|
||||
network: `reserved${prefix}`,
|
||||
prefix,
|
||||
standardAccount: null,
|
||||
symbols: null,
|
||||
website: null
|
||||
});
|
||||
|
||||
const all: NetworkFromSubstrate[] = [
|
||||
{
|
||||
decimals: [10],
|
||||
@@ -23,15 +33,7 @@ const all: NetworkFromSubstrate[] = [
|
||||
symbols: ['DOT'],
|
||||
website: 'https://polkadot.network'
|
||||
},
|
||||
{
|
||||
decimals: null,
|
||||
displayName: 'This prefix is reserved.',
|
||||
network: 'reserved1',
|
||||
prefix: 1,
|
||||
standardAccount: null,
|
||||
symbols: null,
|
||||
website: null
|
||||
},
|
||||
createReserved(1),
|
||||
{
|
||||
decimals: [12],
|
||||
displayName: 'Kusama Relay Chain',
|
||||
@@ -47,15 +49,7 @@ const all: NetworkFromSubstrate[] = [
|
||||
symbols: ['KSM'],
|
||||
website: 'https://kusama.network'
|
||||
},
|
||||
{
|
||||
decimals: null,
|
||||
displayName: 'This prefix is reserved.',
|
||||
network: 'reserved3',
|
||||
prefix: 3,
|
||||
standardAccount: null,
|
||||
symbols: null,
|
||||
website: null
|
||||
},
|
||||
createReserved(3),
|
||||
{
|
||||
decimals: null,
|
||||
displayName: 'Katal Chain',
|
||||
@@ -148,6 +142,15 @@ const all: NetworkFromSubstrate[] = [
|
||||
symbols: null,
|
||||
website: 'https://www.substratee.com'
|
||||
},
|
||||
{
|
||||
decimals: [0],
|
||||
displayName: 'Totem',
|
||||
network: 'totem',
|
||||
prefix: 14,
|
||||
standardAccount: '*25519',
|
||||
symbols: ['XTX'],
|
||||
website: 'https://totemaccounting.com'
|
||||
},
|
||||
{
|
||||
decimals: [12],
|
||||
displayName: 'Kulupu',
|
||||
@@ -186,14 +189,14 @@ const all: NetworkFromSubstrate[] = [
|
||||
website: 'https://geekcash.org'
|
||||
},
|
||||
{
|
||||
decimals: null,
|
||||
decimals: [12],
|
||||
displayName: 'Stafi',
|
||||
genesisHash: ['0x290a4149f09ea0e402c74c1c7e96ae4239588577fe78932f94f5404c68243d80'],
|
||||
network: 'stafi',
|
||||
prefix: 20,
|
||||
standardAccount: '*25519',
|
||||
symbols: null,
|
||||
website: null
|
||||
symbols: ['FIS'],
|
||||
website: 'https://stafi.io'
|
||||
},
|
||||
{
|
||||
decimals: [6],
|
||||
@@ -324,15 +327,7 @@ const all: NetworkFromSubstrate[] = [
|
||||
symbols: null,
|
||||
website: 'https://substrate.dev/'
|
||||
},
|
||||
{
|
||||
decimals: null,
|
||||
displayName: 'This prefix is reserved.',
|
||||
network: 'reserved43',
|
||||
prefix: 43,
|
||||
standardAccount: null,
|
||||
symbols: null,
|
||||
website: null
|
||||
},
|
||||
createReserved(43),
|
||||
{
|
||||
decimals: [8],
|
||||
displayName: 'ChainX',
|
||||
@@ -342,33 +337,9 @@ const all: NetworkFromSubstrate[] = [
|
||||
symbols: ['PCX'],
|
||||
website: 'https://chainx.org/'
|
||||
},
|
||||
{
|
||||
decimals: null,
|
||||
displayName: 'This prefix is reserved.',
|
||||
network: 'reserved46',
|
||||
prefix: 46,
|
||||
standardAccount: null,
|
||||
symbols: null,
|
||||
website: null
|
||||
},
|
||||
{
|
||||
decimals: null,
|
||||
displayName: 'This prefix is reserved.',
|
||||
network: 'reserved47',
|
||||
prefix: 47,
|
||||
standardAccount: null,
|
||||
symbols: null,
|
||||
website: null
|
||||
},
|
||||
{
|
||||
decimals: null,
|
||||
displayName: 'All prefixes 48 and higher are reserved and cannot be allocated.',
|
||||
network: 'reserved48',
|
||||
prefix: 48,
|
||||
standardAccount: null,
|
||||
symbols: null,
|
||||
website: null
|
||||
}
|
||||
createReserved(46),
|
||||
createReserved(47),
|
||||
createReserved(48, 'All prefixes 48 and higher are reserved and cannot be allocated.')
|
||||
];
|
||||
|
||||
// The list of available/claimed prefixes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/util-crypto",
|
||||
"version": "3.6.1",
|
||||
"version": "3.7.1",
|
||||
"description": "A collection of useful crypto utilities for @polkadot",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,13 +26,13 @@
|
||||
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-crypto#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.1",
|
||||
"@polkadot/networks": "3.6.1",
|
||||
"@polkadot/util": "3.6.1",
|
||||
"@polkadot/networks": "^3.7.1",
|
||||
"@polkadot/util": "^3.7.1",
|
||||
"@polkadot/wasm-crypto": "^1.4.1",
|
||||
"base-x": "^3.0.8",
|
||||
"bip39": "^3.0.2",
|
||||
"blakejs": "^1.1.0",
|
||||
"bn.js": "^5.1.3",
|
||||
"create-hash": "^1.2.0",
|
||||
"elliptic": "^6.5.3",
|
||||
"js-sha3": "^0.8.0",
|
||||
"pbkdf2": "^3.1.1",
|
||||
@@ -42,6 +42,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bn.js": "^4.11.6",
|
||||
"@types/create-hash": "^1.2.2",
|
||||
"@types/elliptic": "^6.4.12",
|
||||
"@types/pbkdf2": "^3.1.0",
|
||||
"@types/scryptsy": "^2.0.0",
|
||||
|
||||
@@ -17,6 +17,25 @@ const LOOKUP = BASE32_ALPHABET
|
||||
return lookup;
|
||||
}, {});
|
||||
|
||||
/** @internal */
|
||||
function decode (output: Uint8Array, input: string, offset: number): [Uint8Array, number, number] {
|
||||
let bits = 0;
|
||||
let buffer = 0;
|
||||
let written = 0;
|
||||
|
||||
for (let i = offset; i < input.length; i++) {
|
||||
buffer = (buffer << BITS_PER_CHAR) | LOOKUP[input[i]];
|
||||
bits += BITS_PER_CHAR;
|
||||
|
||||
if (bits >= 8) {
|
||||
bits -= 8;
|
||||
output[written++] = 0xff & (buffer >> bits);
|
||||
}
|
||||
}
|
||||
|
||||
return [output, bits, buffer];
|
||||
}
|
||||
|
||||
/**
|
||||
* @name base32Decode
|
||||
* @summary Delookup a base32 value.
|
||||
@@ -26,22 +45,14 @@ const LOOKUP = BASE32_ALPHABET
|
||||
export default function base32Decode (value: string, ipfsCompat = false): Uint8Array {
|
||||
validate(value, ipfsCompat);
|
||||
|
||||
const out = new Uint8Array(((value.length - (ipfsCompat ? 1 : 0)) * BITS_PER_CHAR / 8) | 0);
|
||||
let bits = 0;
|
||||
let buffer = 0;
|
||||
let written = 0;
|
||||
|
||||
for (let i = (ipfsCompat ? 1 : 0); i < value.length; ++i) {
|
||||
buffer = (buffer << BITS_PER_CHAR) | LOOKUP[value[i]];
|
||||
bits += BITS_PER_CHAR;
|
||||
|
||||
if (bits >= 8) {
|
||||
bits -= 8;
|
||||
out[written++] = 0xff & (buffer >> bits);
|
||||
}
|
||||
}
|
||||
const offset = (ipfsCompat ? 1 : 0);
|
||||
const [output, bits, buffer] = decode(
|
||||
new Uint8Array(((value.length - offset) * BITS_PER_CHAR / 8) | 0),
|
||||
value,
|
||||
offset
|
||||
);
|
||||
|
||||
assert(!(bits >= BITS_PER_CHAR || 0xff & (buffer << (8 - bits))), 'Unexpected end of data');
|
||||
|
||||
return out;
|
||||
return output;
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,124 @@
|
||||
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Adapted from the bitcoinjs/bip39 source
|
||||
// https://github.com/bitcoinjs/bip39/blob/1d063b6a6aee4145b34d701037cd3e67f5446ff9/ts_src/index.ts
|
||||
// Copyright (c) 2014, Wei Lu <luwei.here@gmail.com> and Daniel Cousens <email@dcousens.com>
|
||||
// ISC Licence
|
||||
//
|
||||
// Change made in this version -
|
||||
// - Adjust formatting (just eslint differences)
|
||||
// - Only English wordlist (this aligns with the wasm-crypto implementation)
|
||||
// - Use util-crypto randomAsU8a (instead of randombytes)
|
||||
// - Remove setting of wordlost passing of wordlist in functions
|
||||
// - Remove mnemonicToSeed (we only use the sync variant)
|
||||
|
||||
import createHash from 'create-hash';
|
||||
import { pbkdf2Sync } from 'pbkdf2';
|
||||
import { assert, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import randomAsU8a from '../random/asU8a';
|
||||
import DEFAULT_WORDLIST from './bip39-en';
|
||||
|
||||
const INVALID_MNEMONIC = 'Invalid mnemonic';
|
||||
const INVALID_ENTROPY = 'Invalid entropy';
|
||||
const INVALID_CHECKSUM = 'Invalid mnemonic checksum';
|
||||
|
||||
function normalize (str?: string): string {
|
||||
return (str || '').normalize('NFKD');
|
||||
}
|
||||
|
||||
function binaryToByte (bin: string): number {
|
||||
return parseInt(bin, 2);
|
||||
}
|
||||
|
||||
function bytesToBinary (bytes: number[]): string {
|
||||
return bytes.map((x: number) => x.toString(2).padStart(8, '0')).join('');
|
||||
}
|
||||
|
||||
function deriveChecksumBits (entropyBuffer: Uint8Array): string {
|
||||
const ENT = entropyBuffer.length * 8;
|
||||
const CS = ENT / 32;
|
||||
const hash = createHash('sha256')
|
||||
.update(entropyBuffer)
|
||||
.digest();
|
||||
|
||||
return bytesToBinary(Array.from(hash)).slice(0, CS);
|
||||
}
|
||||
|
||||
function salt (password?: string): string {
|
||||
return 'mnemonic' + (password || '');
|
||||
}
|
||||
|
||||
export function mnemonicToSeedSync (mnemonic: string, password?: string): Buffer {
|
||||
const mnemonicBuffer = Buffer.from(normalize(mnemonic), 'utf8');
|
||||
const saltBuffer = Buffer.from(salt(normalize(password)), 'utf8');
|
||||
|
||||
return pbkdf2Sync(mnemonicBuffer, saltBuffer, 2048, 64, 'sha512');
|
||||
}
|
||||
|
||||
export function mnemonicToEntropy (mnemonic: string): Uint8Array {
|
||||
const words = normalize(mnemonic).split(' ');
|
||||
|
||||
assert(words.length % 3 === 0, INVALID_MNEMONIC);
|
||||
|
||||
// convert word indices to 11 bit binary strings
|
||||
const bits = words
|
||||
.map((word): string => {
|
||||
const index = DEFAULT_WORDLIST.indexOf(word);
|
||||
|
||||
assert(index !== -1, INVALID_MNEMONIC);
|
||||
|
||||
return index.toString(2).padStart(11, '0');
|
||||
})
|
||||
.join('');
|
||||
|
||||
// split the binary string into ENT/CS
|
||||
const dividerIndex = Math.floor(bits.length / 33) * 32;
|
||||
const entropyBits = bits.slice(0, dividerIndex);
|
||||
const checksumBits = bits.slice(dividerIndex);
|
||||
|
||||
// calculate the checksum and compare
|
||||
const entropyBytes = entropyBits.match(/(.{1,8})/g)?.map(binaryToByte);
|
||||
|
||||
assert(entropyBytes && entropyBytes.length % 4 === 0 && entropyBytes.length >= 16 && entropyBytes.length <= 32, INVALID_ENTROPY);
|
||||
|
||||
const entropy = u8aToU8a(entropyBytes);
|
||||
const newChecksum = deriveChecksumBits(entropy);
|
||||
|
||||
assert(newChecksum === checksumBits, INVALID_CHECKSUM);
|
||||
|
||||
return entropy;
|
||||
}
|
||||
|
||||
export function entropyToMnemonic (entropy: Uint8Array): string {
|
||||
// 128 <= ENT <= 256
|
||||
assert(entropy.length % 4 === 0 && entropy.length >= 16 && entropy.length <= 32, INVALID_ENTROPY);
|
||||
|
||||
const entropyBits = bytesToBinary(Array.from(entropy));
|
||||
const checksumBits = deriveChecksumBits(entropy);
|
||||
|
||||
// we just set it prior, so this is a safe check
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
return (entropyBits + checksumBits).match(/(.{1,11})/g)!
|
||||
.map((binary) => DEFAULT_WORDLIST[binaryToByte(binary)])
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
export function generateMnemonic (strength?: number): string {
|
||||
strength = strength || 128;
|
||||
|
||||
assert(strength % 32 === 0, INVALID_ENTROPY);
|
||||
|
||||
return entropyToMnemonic(randomAsU8a(strength / 8));
|
||||
}
|
||||
|
||||
export function validateMnemonic (mnemonic: string): boolean {
|
||||
try {
|
||||
mnemonicToEntropy(mnemonic);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -11,24 +11,20 @@ describe('mnemonicGenerate', (): void => {
|
||||
});
|
||||
|
||||
it('generates a valid mnemonic (default strength)', (): void => {
|
||||
const mnemonic = generate();
|
||||
|
||||
console.error(mnemonic);
|
||||
|
||||
expect(
|
||||
validate(mnemonic)
|
||||
validate(generate())
|
||||
).toEqual(true);
|
||||
});
|
||||
|
||||
([12, 15, 18, 21, 24] as WordCount[]).forEach((num: WordCount): void => {
|
||||
it(`generates a valid mnemonic (${num} words)`, (): void => {
|
||||
const mnemonic = generate(num);
|
||||
const isValid = validate(mnemonic);
|
||||
[false, true].forEach((onlyJs): void => {
|
||||
const mnemonic = generate(num, onlyJs);
|
||||
const isValid = validate(mnemonic);
|
||||
|
||||
console.error(mnemonic);
|
||||
|
||||
expect(mnemonic.split(' ')).toHaveLength(num);
|
||||
expect(isValid).toEqual(true);
|
||||
expect(mnemonic.split(' ')).toHaveLength(num);
|
||||
expect(isValid).toEqual(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
|
||||
import '../polyfill';
|
||||
|
||||
import { generateMnemonic } from 'bip39';
|
||||
import { bip39Generate, isReady } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { generateMnemonic } from './bip39';
|
||||
|
||||
export type WordCount = 12 | 15 | 18 | 21 | 24;
|
||||
|
||||
// mapping of words to the actual strength (as expected)
|
||||
@@ -29,8 +30,8 @@ const STRENGTH_MAP = {
|
||||
* const mnemonic = mnemonicGenerate(); // => string
|
||||
* ```
|
||||
*/
|
||||
export default function mnemonicGenerate (numWords: WordCount = 12): string {
|
||||
return isReady()
|
||||
export default function mnemonicGenerate (numWords: WordCount = 12, onlyJs = false): string {
|
||||
return isReady() && !onlyJs
|
||||
? bip39Generate(numWords)
|
||||
: generateMnemonic(STRENGTH_MAP[numWords]);
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ describe('mnemonicToEntropy', (): void => {
|
||||
tests.forEach(([mnemonic, entropy], index): void => {
|
||||
it(`Created correct entropy for ${index}`, (): void => {
|
||||
expect(u8aToHex(toEntropy(mnemonic))).toEqual(entropy);
|
||||
expect(u8aToHex(toEntropy(mnemonic, true))).toEqual(entropy);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,16 +3,12 @@
|
||||
|
||||
import '../polyfill';
|
||||
|
||||
import { mnemonicToEntropy } from 'bip39';
|
||||
import { hexAddPrefix, hexToU8a } from '@polkadot/util';
|
||||
import { bip39ToEntropy, isReady } from '@polkadot/wasm-crypto';
|
||||
|
||||
export default function toEntropy (mnemonic: string): Uint8Array {
|
||||
return isReady()
|
||||
import { mnemonicToEntropy } from './bip39';
|
||||
|
||||
export default function toEntropy (mnemonic: string, onlyJs = false): Uint8Array {
|
||||
return isReady() && !onlyJs
|
||||
? bip39ToEntropy(mnemonic)
|
||||
: hexToU8a(
|
||||
hexAddPrefix(
|
||||
mnemonicToEntropy(mnemonic)
|
||||
)
|
||||
);
|
||||
: mnemonicToEntropy(mnemonic);
|
||||
}
|
||||
|
||||
@@ -6,22 +6,20 @@ import { waitReady } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { mnemonicToLegacySeed } from './';
|
||||
|
||||
const MENMONIC = 'seed sock milk update focus rotate barely fade car face mechanic mercy';
|
||||
const SEED = '0x3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027';
|
||||
|
||||
describe('mnemonicToLegacySeed', (): void => {
|
||||
beforeEach(async (): Promise<void> => {
|
||||
await waitReady();
|
||||
});
|
||||
|
||||
it('generates a valid seed', (): void => {
|
||||
expect(
|
||||
u8aToHex(
|
||||
mnemonicToLegacySeed('seed sock milk update focus rotate barely fade car face mechanic mercy')
|
||||
)
|
||||
).toEqual('0x3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027');
|
||||
});
|
||||
|
||||
it('generates the seed via WASM', async (): Promise<void> => {
|
||||
await waitReady();
|
||||
|
||||
u8aToHex(mnemonicToLegacySeed(MENMONIC))
|
||||
).toEqual(SEED);
|
||||
expect(
|
||||
u8aToHex(
|
||||
mnemonicToLegacySeed('seed sock milk update focus rotate barely fade car face mechanic mercy')
|
||||
)
|
||||
).toEqual('0x3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027');
|
||||
u8aToHex(mnemonicToLegacySeed(MENMONIC, undefined, true))
|
||||
).toEqual(SEED);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { mnemonicToSeedSync } from 'bip39';
|
||||
import { bufferToU8a } from '@polkadot/util';
|
||||
|
||||
import { bip39ToSeed, isReady } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { mnemonicToSeedSync } from './bip39';
|
||||
|
||||
/**
|
||||
* @name toSeed
|
||||
* @summary Creates a valid Ethereum/Bitcoin-compatible seed from a mnemonic input
|
||||
@@ -23,8 +24,8 @@ import { bip39ToSeed, isReady } from '@polkadot/wasm-crypto';
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export default function toLegacy (mnemonic: string, password = ''): Uint8Array {
|
||||
return isReady()
|
||||
export default function toLegacy (mnemonic: string, password = '', onlyJs = false): Uint8Array {
|
||||
return isReady() && !onlyJs
|
||||
? bip39ToSeed(mnemonic, password)
|
||||
: bufferToU8a(mnemonicToSeedSync(mnemonic, password)).subarray(0, 32);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@ import mnemonicToMiniSecret from './toMiniSecret';
|
||||
import tests from '../schnorrkel/keypair/testing';
|
||||
import { cryptoWaitReady } from '..';
|
||||
|
||||
const MNEMONIC = 'seed sock milk update focus rotate barely fade car face mechanic mercy';
|
||||
const SEED = '0x4d1ab2a57929edfd018aaa974e62ed557e3f54b4104acabedf73c8f5a1dbb029';
|
||||
|
||||
describe('mnemonicToMiniSecret', (): void => {
|
||||
beforeEach(async (): Promise<void> => {
|
||||
await cryptoWaitReady();
|
||||
@@ -14,8 +17,11 @@ describe('mnemonicToMiniSecret', (): void => {
|
||||
|
||||
it('generates a valid seed', (): void => {
|
||||
expect(
|
||||
u8aToHex(mnemonicToMiniSecret('seed sock milk update focus rotate barely fade car face mechanic mercy'))
|
||||
).toEqual('0x4d1ab2a57929edfd018aaa974e62ed557e3f54b4104acabedf73c8f5a1dbb029');
|
||||
u8aToHex(mnemonicToMiniSecret(MNEMONIC))
|
||||
).toEqual(SEED);
|
||||
expect(
|
||||
u8aToHex(mnemonicToMiniSecret(MNEMONIC, undefined, true))
|
||||
).toEqual(SEED);
|
||||
});
|
||||
|
||||
tests.forEach(([mnemonic, , seed], index): void => {
|
||||
@@ -26,6 +32,12 @@ describe('mnemonicToMiniSecret', (): void => {
|
||||
// mini returned here, only check first 32-bytes (64 hex + 2 prefix)
|
||||
seed.substr(0, 66)
|
||||
);
|
||||
expect(
|
||||
u8aToHex(mnemonicToMiniSecret(mnemonic, 'Substrate', true))
|
||||
).toEqual(
|
||||
// mini returned here, only check first 32-bytes (64 hex + 2 prefix)
|
||||
seed.substr(0, 66)
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,8 +9,8 @@ import { bip39ToMiniSecret, isReady } from '@polkadot/wasm-crypto';
|
||||
|
||||
import toEntropy from './toEntropy';
|
||||
|
||||
export default function toMiniSecret (mnemonic: string, password = ''): Uint8Array {
|
||||
if (isReady()) {
|
||||
export default function toMiniSecret (mnemonic: string, password = '', onlyJs = false): Uint8Array {
|
||||
if (isReady() && !onlyJs) {
|
||||
return bip39ToMiniSecret(mnemonic, password);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,11 +13,17 @@ describe('mnemonicValidate', (): void => {
|
||||
expect(
|
||||
validate('seed sock milk update focus rotate barely fade car face mechanic mercy')
|
||||
).toEqual(true);
|
||||
expect(
|
||||
validate('seed sock milk update focus rotate barely fade car face mechanic mercy', true)
|
||||
).toEqual(true);
|
||||
});
|
||||
|
||||
it('returns false on invalid', (): void => {
|
||||
expect(
|
||||
validate('wine photo extra cushion basket dwarf humor cloud truck job boat submit')
|
||||
).toEqual(false);
|
||||
expect(
|
||||
validate('wine photo extra cushion basket dwarf humor cloud truck job boat submit', true)
|
||||
).toEqual(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,9 +3,10 @@
|
||||
|
||||
import '../polyfill';
|
||||
|
||||
import { validateMnemonic } from 'bip39';
|
||||
import { bip39Validate, isReady } from '@polkadot/wasm-crypto';
|
||||
|
||||
import { validateMnemonic } from './bip39';
|
||||
|
||||
/**
|
||||
* @name mnemonicValidate
|
||||
* @summary Validates a mnemonic input using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).
|
||||
@@ -19,8 +20,8 @@ import { bip39Validate, isReady } from '@polkadot/wasm-crypto';
|
||||
* const isValidMnemonic = mnemonicValidate(mnemonic); // => boolean
|
||||
* ```
|
||||
*/
|
||||
export default function mnemonicValidate (mnemonic: string): boolean {
|
||||
return isReady()
|
||||
export default function mnemonicValidate (mnemonic: string, onlyJs = false): boolean {
|
||||
return isReady() && !onlyJs
|
||||
? bip39Validate(mnemonic)
|
||||
: validateMnemonic(mnemonic);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import elliptic from 'elliptic';
|
||||
import { ec as EC } from 'elliptic';
|
||||
import { assert } from '@polkadot/util';
|
||||
|
||||
const EC = elliptic.ec;
|
||||
const ec = new EC('secp256k1');
|
||||
|
||||
export default function secp256k1Compress (publicKey: Uint8Array): Uint8Array {
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import elliptic from 'elliptic';
|
||||
import { ec as EC } from 'elliptic';
|
||||
import { assert, bnToU8a, u8aConcat } from '@polkadot/util';
|
||||
|
||||
const EC = elliptic.ec;
|
||||
const ec = new EC('secp256k1');
|
||||
|
||||
export default function secp256k1Expand (publicKey: Uint8Array): Uint8Array {
|
||||
|
||||
@@ -3,10 +3,9 @@
|
||||
|
||||
import { Keypair } from '../../types';
|
||||
|
||||
import elliptic from 'elliptic';
|
||||
import { ec as EC } from 'elliptic';
|
||||
import { assert, bnToU8a } from '@polkadot/util';
|
||||
|
||||
const EC = elliptic.ec;
|
||||
const ec = new EC('secp256k1');
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
// Copyright 2017-2020 @polkadot/util-crypto authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import elliptic from 'elliptic';
|
||||
import { ec as EC } from 'elliptic';
|
||||
|
||||
const EC = elliptic.ec;
|
||||
const ec = new EC('secp256k1');
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,12 +4,11 @@
|
||||
import { Keypair } from '../types';
|
||||
import { HashType } from './types';
|
||||
|
||||
import elliptic from 'elliptic';
|
||||
import { ec as EC } from 'elliptic';
|
||||
import { assert, bnToU8a, u8aConcat } from '@polkadot/util';
|
||||
|
||||
import hasher from './hasher';
|
||||
|
||||
const EC = elliptic.ec;
|
||||
const ec = new EC('secp256k1');
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,13 +3,12 @@
|
||||
|
||||
import { HashType } from './types';
|
||||
|
||||
import elliptic from 'elliptic';
|
||||
import { ec as EC } from 'elliptic';
|
||||
import { assert, u8aEq, u8aToU8a } from '@polkadot/util';
|
||||
|
||||
import secp256k1Expand from './expand';
|
||||
import hasher from './hasher';
|
||||
|
||||
const EC = elliptic.ec;
|
||||
const ec = new EC('secp256k1');
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@polkadot/util",
|
||||
"version": "3.6.1",
|
||||
"version": "3.7.1",
|
||||
"description": "A collection of useful utilities for @polkadot",
|
||||
"main": "index.js",
|
||||
"keywords": [
|
||||
@@ -26,12 +26,11 @@
|
||||
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.1",
|
||||
"@polkadot/x-textdecoder": "^0.3.3",
|
||||
"@polkadot/x-textencoder": "^0.3.3",
|
||||
"@polkadot/x-textdecoder": "^3.7.1",
|
||||
"@polkadot/x-textencoder": "^3.7.1",
|
||||
"@types/bn.js": "^4.11.6",
|
||||
"bn.js": "^5.1.3",
|
||||
"camelcase": "^5.3.1",
|
||||
"chalk": "^4.1.0",
|
||||
"ip-regex": "^4.2.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import isFunction from './is/function';
|
||||
import isUndefined from './is/undefined';
|
||||
|
||||
type MessageFn = () => string;
|
||||
|
||||
@@ -30,3 +31,13 @@ export default function assert (condition: unknown, message: string | MessageFn)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @name assertReturn
|
||||
* @summart Returns when the value is not undefined, otherwise throws assertion error
|
||||
*/
|
||||
export function assertReturn <T> (value: T | undefined, message: string | MessageFn): T {
|
||||
assert(!isUndefined(value), message);
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,15 @@ interface Options extends ToBnOptions {
|
||||
bitLength?: number;
|
||||
}
|
||||
|
||||
function setBn (valueBn: BN, byteLength: number, { isLe, isNegative }: Options): Uint8Array {
|
||||
const output = new Uint8Array(byteLength);
|
||||
const bn = isNegative ? valueBn.toTwos(byteLength * 8) : valueBn;
|
||||
|
||||
output.set(bn.toArray(isLe ? 'le' : 'be', byteLength), 0);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* @name bnToU8a
|
||||
* @summary Creates a Uint8Array object from a BN.
|
||||
@@ -29,7 +38,7 @@ interface Options extends ToBnOptions {
|
||||
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, options?: Options): Uint8Array;
|
||||
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, bitLength?: number, isLe?: boolean): Uint8Array;
|
||||
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number | null, arg1: number | Options = { bitLength: -1, isLe: true, isNegative: false }, arg2?: boolean): Uint8Array {
|
||||
const _options: Options = {
|
||||
const options: Options = {
|
||||
bitLength: -1,
|
||||
isLe: true,
|
||||
isNegative: false,
|
||||
@@ -37,25 +46,15 @@ function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | BigInt | number
|
||||
};
|
||||
|
||||
const valueBn = bnToBn(value);
|
||||
const byteLength = _options.bitLength === -1
|
||||
const byteLength = options.bitLength === -1
|
||||
? Math.ceil(valueBn.bitLength() / 8)
|
||||
: Math.ceil((_options.bitLength || 0) / 8);
|
||||
: Math.ceil((options.bitLength || 0) / 8);
|
||||
|
||||
if (!value) {
|
||||
return _options.bitLength === -1
|
||||
return value
|
||||
? setBn(valueBn, byteLength, options)
|
||||
: options.bitLength === -1
|
||||
? new Uint8Array()
|
||||
: new Uint8Array(byteLength);
|
||||
}
|
||||
|
||||
const output = new Uint8Array(byteLength);
|
||||
const bn = _options.isNegative ? valueBn.toTwos(byteLength * 8) : valueBn;
|
||||
|
||||
output.set(
|
||||
bn.toArray(_options.isLe ? 'le' : 'be', byteLength),
|
||||
0
|
||||
);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
export default bnToU8a;
|
||||
|
||||
@@ -20,6 +20,12 @@ describe('formatBalance', (): void => {
|
||||
).toEqual('123.4567 µUnit');
|
||||
});
|
||||
|
||||
it('formats 123,456 (decimals=0)', (): void => {
|
||||
expect(
|
||||
formatBalance(123456, { decimals: 0, withSi: true })
|
||||
).toEqual('123.4560 kUnit');
|
||||
});
|
||||
|
||||
it('formats BigInt numbers', (): void => {
|
||||
expect(
|
||||
formatBalance(123456789000n, { decimals: 15, withSi: true })
|
||||
|
||||
@@ -61,8 +61,8 @@ function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | B
|
||||
: options;
|
||||
|
||||
// NOTE We start at midpoint (8) minus 1 - this means that values display as
|
||||
// 123.456 instead of 0.123k (so always 6 relevant). Additionally we us ceil
|
||||
// so there are at most 3 decimal before the decimal seperator
|
||||
// 123.456 instead of 0.123k (so always 6 relevant). Additionally we use ceil
|
||||
// so there are at most 3 decimal before the decimal separator
|
||||
const si = calcSi(text, decimals, forceUnit);
|
||||
const mid = text.length - (decimals + si.power);
|
||||
const prefix = text.substr(0, mid);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Copyright 2017-2020 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// eslint-disable-next-line prefer-regex-literals
|
||||
const NUMBER_REGEX = new RegExp('(\\d+?)(?=(\\d{3})+(?!\\d)|$)', 'g');
|
||||
|
||||
export default function formatDecimal (value: string): string {
|
||||
|
||||
@@ -8,37 +8,38 @@ import BN from 'bn.js';
|
||||
import isToBn from '../is/toBn';
|
||||
|
||||
function getValue <ExtToBn extends ToBn> (value?: BN | ExtToBn | Date | number | null): number {
|
||||
if (value) {
|
||||
if (isToBn(value)) {
|
||||
return getValue(value.toBn());
|
||||
} else if (value instanceof Date) {
|
||||
return getValue(value.getTime());
|
||||
} else if (value instanceof BN) {
|
||||
return getValue(value.toNumber());
|
||||
}
|
||||
if (isToBn(value)) {
|
||||
return getValue(value.toBn());
|
||||
} else if (value instanceof Date) {
|
||||
return getValue(value.getTime());
|
||||
} else if (value instanceof BN) {
|
||||
return getValue(value.toNumber());
|
||||
}
|
||||
|
||||
return (value as number) || 0;
|
||||
return value || 0;
|
||||
}
|
||||
|
||||
function formatValue (elapsed: number): string {
|
||||
if (elapsed < 15) {
|
||||
return `${elapsed.toFixed(1)}s`;
|
||||
} else if (elapsed < 60) {
|
||||
return `${elapsed | 0}s`;
|
||||
} else if (elapsed < 3600) {
|
||||
return `${elapsed / 60 | 0}m`;
|
||||
}
|
||||
|
||||
return `${elapsed / 3600 | 0}h`;
|
||||
}
|
||||
|
||||
export default function formatElapsed <ExtToBn extends ToBn> (now?: Date | null, value?: BN | ExtToBn | Date | number | null): string {
|
||||
const tsNow = (now && now.getTime()) || 0;
|
||||
const tsValue = getValue(value);
|
||||
let display = '0.0s';
|
||||
|
||||
if (tsNow && tsValue) {
|
||||
const elapsed = Math.max(Math.abs(tsNow - tsValue), 0) / 1000;
|
||||
|
||||
if (elapsed < 15) {
|
||||
display = `${elapsed.toFixed(1)}s`;
|
||||
} else if (elapsed < 60) {
|
||||
display = `${elapsed | 0}s`;
|
||||
} else if (elapsed < 3600) {
|
||||
display = `${elapsed / 60 | 0}m`;
|
||||
} else {
|
||||
display = `${elapsed / 3600 | 0}h`;
|
||||
}
|
||||
return formatValue(elapsed);
|
||||
}
|
||||
|
||||
return display;
|
||||
return '0.0s';
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import hexStripPrefix from './stripPrefix';
|
||||
import { ToBnOptions } from '../types';
|
||||
|
||||
function reverse (value: string): string {
|
||||
return (value.match(new RegExp('.{1,2}', 'g')) || [])
|
||||
return (value.match(/.{1,2}/g) || [])
|
||||
.reverse()
|
||||
.join('');
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import './polyfill';
|
||||
* @summary Utility methods for this package are split into groups
|
||||
*/
|
||||
|
||||
export { default as assert } from './assert';
|
||||
export { default as assert, assertReturn } from './assert';
|
||||
export { default as detectPackage } from './detectPackage';
|
||||
export { default as extractTime } from './extractTime';
|
||||
export { default as logger } from './logger';
|
||||
|
||||
@@ -13,11 +13,7 @@ const FORMAT = [9, 10, 13];
|
||||
* Checks to see if the input string or Uint8Array is printable ASCII, 32-127 + formatters
|
||||
*/
|
||||
export default function isAscii (value?: number[] | Buffer | Uint8Array | string | null): boolean {
|
||||
if (!value) {
|
||||
return isString(value);
|
||||
}
|
||||
|
||||
const u8a = u8aToU8a(value);
|
||||
|
||||
return !u8a.some((byte) => (byte >= 127) || (byte < 32 && !FORMAT.includes(byte)));
|
||||
return value
|
||||
? !u8aToU8a(value).some((byte) => (byte >= 127) || (byte < 32 && !FORMAT.includes(byte)))
|
||||
: isString(value);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2017-2020 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
const re = new RegExp('(Development|Local Testnet)$');
|
||||
const re = /(Development|Local Testnet)$/;
|
||||
|
||||
export default function isTestChain (chain?: string | null): boolean {
|
||||
if (!chain) {
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
import { Logger } from './types';
|
||||
|
||||
import BN from 'bn.js';
|
||||
|
||||
import { logger } from '.';
|
||||
import { format } from './logger';
|
||||
|
||||
@@ -62,15 +64,17 @@ describe('logger', (): void => {
|
||||
);
|
||||
});
|
||||
|
||||
it('logs with mulptiple values', (): void => {
|
||||
l.log('test', 'a', 2);
|
||||
it('logs with multiple values', (): void => {
|
||||
l.log('test', 'a', 2, new BN('12345678900987654321'), Buffer.from([0, 1, 2, 3]));
|
||||
|
||||
expect(spy.log).toHaveBeenCalledWith(
|
||||
dateMatch,
|
||||
prefixMatch,
|
||||
expect.stringMatching('test'),
|
||||
expect.stringMatching('a'),
|
||||
2
|
||||
2,
|
||||
expect.stringMatching('12345678900987654321'),
|
||||
expect.stringMatching('0x00010203')
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -3,15 +3,14 @@
|
||||
|
||||
import { Logger, Logger$Data } from './types';
|
||||
|
||||
import chalk from 'chalk';
|
||||
|
||||
import formatDate from './format/formatDate';
|
||||
import isBn from './is/bn';
|
||||
import isBuffer from './is/buffer';
|
||||
import isFunction from './is/function';
|
||||
import isObject from './is/object';
|
||||
import isU8a from './is/u8a';
|
||||
import u8aToHex from './u8a/toHex';
|
||||
import u8aToU8a from './u8a/toU8a';
|
||||
import { isBuffer } from './is';
|
||||
|
||||
type ConsoleType = 'error' | 'log' | 'warn';
|
||||
type LogType = ConsoleType | 'debug';
|
||||
@@ -23,13 +22,6 @@ const logTo = {
|
||||
warn: 'warn'
|
||||
};
|
||||
|
||||
const chalked = {
|
||||
debug: chalk.gray,
|
||||
error: chalk.red,
|
||||
log: chalk.reset,
|
||||
warn: chalk.yellow
|
||||
};
|
||||
|
||||
function formatObject (value: Record<string, unknown>): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = {};
|
||||
|
||||
@@ -43,21 +35,11 @@ function formatObject (value: Record<string, unknown>): Record<string, unknown>
|
||||
export function format (value: unknown): unknown {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(format);
|
||||
}
|
||||
|
||||
if (isBn(value)) {
|
||||
} else if (isBn(value)) {
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
if (isBuffer(value)) {
|
||||
return `0x${value.toString('hex')}`;
|
||||
}
|
||||
|
||||
if (isU8a(value)) {
|
||||
return u8aToHex(value);
|
||||
}
|
||||
|
||||
if (value && isObject(value) && value.constructor === Object) {
|
||||
} else if (isU8a(value) || isBuffer(value)) {
|
||||
return u8aToHex(u8aToU8a(value));
|
||||
} else if (value && isObject(value) && value.constructor === Object) {
|
||||
return formatObject(value);
|
||||
}
|
||||
|
||||
@@ -71,12 +53,9 @@ function apply (log: LogType, type: string, values: Logger$Data): void {
|
||||
return apply(log, type, Array.isArray(fnResult) ? fnResult : [fnResult]);
|
||||
}
|
||||
|
||||
const chalk = (value: string): string =>
|
||||
chalked[log](value);
|
||||
|
||||
console[logTo[log] as 'log'](
|
||||
chalk(formatDate(new Date())),
|
||||
chalk(type),
|
||||
formatDate(new Date()),
|
||||
type,
|
||||
...values.map(format)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,50 +2,30 @@
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
/* eslint-disable no-extend-native */
|
||||
/* eslint-disable @typescript-eslint/unbound-method */
|
||||
|
||||
import assert from '../assert';
|
||||
|
||||
function getOffset (value: number, length: number): number {
|
||||
return value < 0
|
||||
? Math.max(length + value, 0)
|
||||
: Math.min(value, length);
|
||||
}
|
||||
|
||||
if (!Array.prototype.fill) {
|
||||
// eslint-disable-next-line no-extend-native,@typescript-eslint/no-explicit-any
|
||||
Array.prototype.fill = function fill (value: any, start = 0, end?: number): any[] {
|
||||
// Steps 1-2.
|
||||
if (!this) {
|
||||
throw new TypeError('this is null or not defined');
|
||||
}
|
||||
// eslint-disable-next-line no-extend-native
|
||||
Array.prototype.fill = function fill <T> (value: T, start = 0, end?: number): T[] {
|
||||
assert(this, 'this is null or not defined');
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
const A = Object(this);
|
||||
const A = Object(this) as T[];
|
||||
const relativeEnd = end ?? A.length;
|
||||
const final = getOffset(relativeEnd, A.length);
|
||||
let k = getOffset(start, A.length);
|
||||
|
||||
// Steps 3-5.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
const len = A.length >>> 0;
|
||||
|
||||
// Steps 6-7.
|
||||
const relativeStart = start >> 0;
|
||||
|
||||
// Step 8.
|
||||
let k = relativeStart < 0
|
||||
? Math.max(len + relativeStart, 0)
|
||||
: Math.min(relativeStart, len);
|
||||
|
||||
// Steps 9-10.
|
||||
const relativeEnd = end === undefined
|
||||
? len
|
||||
: end >> 0;
|
||||
|
||||
// Step 11.
|
||||
const final = relativeEnd < 0
|
||||
? Math.max(len + relativeEnd, 0)
|
||||
: Math.min(relativeEnd, len);
|
||||
|
||||
// Step 12.
|
||||
while (k < final) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment,@typescript-eslint/no-unsafe-member-access
|
||||
A[k] = value;
|
||||
k++;
|
||||
}
|
||||
|
||||
// Step 13.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return A;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -9,4 +9,10 @@ describe('stringCamelCase', (): void => {
|
||||
stringCamelCase('Snake_case')
|
||||
).toBe('snakeCase');
|
||||
});
|
||||
|
||||
it('works correctly for String (class', (): void => {
|
||||
expect(
|
||||
stringCamelCase(String('Snake_case'))
|
||||
).toBe('snakeCase');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
// Copyright 2017-2020 @polkadot/util authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import stringCamelCase from 'camelcase';
|
||||
import camelcase from 'camelcase';
|
||||
|
||||
export default stringCamelCase;
|
||||
/**
|
||||
* @name stringCamelCase
|
||||
* @summary Convert a dash/dot/underscore/space separated string/String to camelCase
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
export default function stringCamelCase (value: string | String): string {
|
||||
return camelcase(value.toString());
|
||||
}
|
||||
|
||||
@@ -10,6 +10,12 @@ describe('stringLowerFirst', (): void => {
|
||||
).toBe('aBC');
|
||||
});
|
||||
|
||||
it("lowers the first letter if it's a capital letter (String)", (): void => {
|
||||
expect(
|
||||
stringLowerFirst(String('ABC'))
|
||||
).toBe('aBC');
|
||||
});
|
||||
|
||||
it("lowers the first letter if it's a lowercase letter", (): void => {
|
||||
expect(
|
||||
stringLowerFirst('abc')
|
||||
|
||||
@@ -15,7 +15,8 @@
|
||||
* stringLowerFirst('ABC'); // => 'aBC'
|
||||
* ```
|
||||
*/
|
||||
export default function stringLowerFirst (value?: string | null): string {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
export default function stringLowerFirst (value?: string | String | null): string {
|
||||
return value
|
||||
? value.charAt(0).toLowerCase() + value.slice(1)
|
||||
: '';
|
||||
|
||||
@@ -15,4 +15,10 @@ describe('stringShorten', (): void => {
|
||||
stringShorten('0123456789', 3)
|
||||
).toEqual('012…789');
|
||||
});
|
||||
|
||||
it('returns the shortened value when > maxLength (String)', (): void => {
|
||||
expect(
|
||||
stringShorten(String('0123456789'), 3)
|
||||
).toEqual('012…789');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -15,10 +15,10 @@
|
||||
* stringShorten('1234567890', 2); // => 12..90
|
||||
* ```
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export default function stringShorten (value: string, prefixLength = 6): string {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
export default function stringShorten (value: String | string, prefixLength = 6): string {
|
||||
if (value.length <= 2 + 2 * prefixLength) {
|
||||
return value;
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
return `${value.substr(0, prefixLength)}…${value.slice(-prefixLength)}`;
|
||||
|
||||
@@ -15,4 +15,10 @@ describe('hexToString', (): void => {
|
||||
stringToHex('hello')
|
||||
).toEqual('0x68656c6c6f');
|
||||
});
|
||||
|
||||
it('converts to a hex from String', (): void => {
|
||||
expect(
|
||||
stringToHex(String('hello'))
|
||||
).toEqual('0x68656c6c6f');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,7 +18,8 @@ import stringToU8a from './toU8a';
|
||||
* stringToU8a('hello'); // 0x68656c6c6f
|
||||
* ```
|
||||
*/
|
||||
export default function stringToHex (value?: string): string {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
export default function stringToHex (value?: String | string): string {
|
||||
return u8aToHex(
|
||||
stringToU8a(value)
|
||||
);
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
import { stringToU8a } from '..';
|
||||
|
||||
const RUSS_HELLO = new Uint8Array([208, 159, 209, 128, 208, 184, 208, 178, 208, 181, 209, 130, 44, 32, 208, 188, 208, 184, 209, 128, 33]);
|
||||
|
||||
describe('stringToU8a', (): void => {
|
||||
it('decodes to an empty string for undefined', (): void => {
|
||||
expect(
|
||||
@@ -13,8 +15,12 @@ describe('stringToU8a', (): void => {
|
||||
it('encodes the string correctly', (): void => {
|
||||
expect(
|
||||
stringToU8a('Привет, мир!')
|
||||
).toEqual(
|
||||
new Uint8Array([208, 159, 209, 128, 208, 184, 208, 178, 208, 181, 209, 130, 44, 32, 208, 188, 208, 184, 209, 128, 33])
|
||||
);
|
||||
).toEqual(RUSS_HELLO);
|
||||
});
|
||||
|
||||
it('encodes the string correctly (String)', (): void => {
|
||||
expect(
|
||||
stringToU8a(String('Привет, мир!'))
|
||||
).toEqual(RUSS_HELLO);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,8 +19,9 @@ const encoder = new TextEncoder();
|
||||
* stringToU8a('hello'); // [0x68, 0x65, 0x6c, 0x6c, 0x6f]
|
||||
* ```
|
||||
*/
|
||||
export default function stringToU8a (value?: string): Uint8Array {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
export default function stringToU8a (value?: String | string): Uint8Array {
|
||||
return value
|
||||
? encoder.encode(value)
|
||||
? encoder.encode(value.toString())
|
||||
: new Uint8Array();
|
||||
}
|
||||
|
||||
@@ -16,6 +16,12 @@ describe('stringUpperFirst', (): void => {
|
||||
).toBe('Abc');
|
||||
});
|
||||
|
||||
it("uppers the first letter if it's a lowercase letter (String)", (): void => {
|
||||
expect(
|
||||
stringUpperFirst(String('abc'))
|
||||
).toBe('Abc');
|
||||
});
|
||||
|
||||
it('returns undefined as empty', (): void => {
|
||||
expect(
|
||||
stringUpperFirst()
|
||||
|
||||
@@ -15,7 +15,8 @@
|
||||
* stringUpperFirst('abc'); // => 'Abc'
|
||||
* ```
|
||||
*/
|
||||
export default function stringUpperFirst (value?: string | null): string {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
export default function stringUpperFirst (value?: String | string | null): string {
|
||||
return value
|
||||
? value.charAt(0).toUpperCase() + value.slice(1)
|
||||
: '';
|
||||
|
||||
@@ -7,6 +7,22 @@ for (let n = 0; n < 256; ++n) {
|
||||
ALPHABET[n] = n.toString(16).padStart(2, '0');
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function extract (value: Uint8Array): string {
|
||||
const result = new Array(value.length) as string[];
|
||||
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
result[i] = ALPHABET[value[i]];
|
||||
}
|
||||
|
||||
return result.join('');
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
function trim (value: Uint8Array, halfLength: number): string {
|
||||
return `${u8aToHex(value.subarray(0, halfLength), -1, false)}…${u8aToHex(value.subarray(value.length - halfLength), -1, false)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @name u8aToHex
|
||||
* @summary Creates a hex string from a Uint8Array object.
|
||||
@@ -32,17 +48,8 @@ export default function u8aToHex (value?: Uint8Array | null, bitLength = -1, isP
|
||||
|
||||
const byteLength = Math.ceil(bitLength / 8);
|
||||
|
||||
if (byteLength > 0 && value.length > byteLength) {
|
||||
const halfLength = Math.ceil(byteLength / 2);
|
||||
|
||||
return `${u8aToHex(value.subarray(0, halfLength), -1, isPrefixed)}…${u8aToHex(value.subarray(value.length - halfLength), -1, false)}`;
|
||||
}
|
||||
|
||||
const result = new Array(value.length) as string[];
|
||||
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
result[i] = ALPHABET[value[i]];
|
||||
}
|
||||
|
||||
return prefix + result.join('');
|
||||
return prefix + ((byteLength > 0 && value.length > byteLength)
|
||||
? trim(value, Math.ceil(byteLength / 2))
|
||||
: extract(value)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# @polkadot/x-fetch
|
||||
|
||||
A cross-environment fetch.
|
||||
|
||||
Install it via `yarn add @polkadot/x-fetch`
|
||||
|
||||
```js
|
||||
import fetch from '@polkadot/x-fetch';
|
||||
|
||||
...
|
||||
const response = await fetch('https://example.com/something.json');
|
||||
const json = await response.json();
|
||||
```
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "@polkadot/x-fetch",
|
||||
"version": "3.7.1",
|
||||
"description": "A cross-environment fetch replacement",
|
||||
"browser": "browser.js",
|
||||
"main": "node.js",
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"maintainers": [
|
||||
"Jaco Greeff <jacogr@gmail.com>"
|
||||
],
|
||||
"contributors": [],
|
||||
"license": "Apache-2.0",
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"registry": "https://registry.npmjs.org"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/polkadot-js/common.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/polkadot-js/common/issues"
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/x-fetch#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.1",
|
||||
"@types/node-fetch": "^2.5.7",
|
||||
"node-fetch": "^2.6.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright 2017-2020 @polkadot/x-fetch authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export default fetch;
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2020 @polkadot/x-fetch authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import nodeFetch from 'node-fetch';
|
||||
|
||||
export default typeof fetch === 'undefined'
|
||||
? nodeFetch as unknown as typeof fetch
|
||||
: fetch;
|
||||
@@ -0,0 +1,12 @@
|
||||
# @polkadot/x-textdecoder
|
||||
|
||||
A cross-environment TextDecoder.
|
||||
|
||||
Install it via `yarn add @polkadot/x-textdecoder`
|
||||
|
||||
```js
|
||||
import TextDecoder from '@polkadot/x-textdecoder';
|
||||
|
||||
...
|
||||
const decoder = new TextDecoder('utf-8');
|
||||
```
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "@polkadot/x-textdecoder",
|
||||
"version": "3.7.1",
|
||||
"description": "A TextDecoder replacement",
|
||||
"browser": "browser.js",
|
||||
"main": "node.js",
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"maintainers": [
|
||||
"Jaco Greeff <jacogr@gmail.com>"
|
||||
],
|
||||
"contributors": [],
|
||||
"license": "Apache-2.0",
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"registry": "https://registry.npmjs.org"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/polkadot-js/common.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/polkadot-js/common/issues"
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/x-textdecoder#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Copyright 2017-2020 @polkadot/x-textencoder authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export default typeof TextDecoder === 'undefined'
|
||||
? class {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars,no-useless-constructor
|
||||
constructor (_: 'utf-8') {
|
||||
// nothing
|
||||
}
|
||||
|
||||
decode (value: Uint8Array): string {
|
||||
return value.reduce((str, code): string => {
|
||||
return str + String.fromCharCode(code);
|
||||
}, '');
|
||||
}
|
||||
}
|
||||
: TextDecoder;
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2020 @polkadot/x-textencoder authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { TextDecoder as NodeTextDecoder } from 'util';
|
||||
|
||||
export default typeof TextDecoder === 'undefined'
|
||||
? NodeTextDecoder as unknown as typeof TextDecoder
|
||||
: TextDecoder;
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2020 @polkadot/x-textdecoder authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import BrowserTD from './browser';
|
||||
import NodeTD from './node';
|
||||
|
||||
console.log(new BrowserTD('utf-8').decode(new Uint8Array([1, 2, 3])));
|
||||
console.log(new NodeTD('utf-8').decode(new Uint8Array([1, 2, 3])));
|
||||
@@ -0,0 +1,12 @@
|
||||
# @polkadot/x-textencoder
|
||||
|
||||
A cross-environment TextEncoder.
|
||||
|
||||
Install it via `yarn add @polkadot/x-textencoder`
|
||||
|
||||
```js
|
||||
import TextEncoder from '@polkadot/x-textencoder';
|
||||
|
||||
...
|
||||
const encoder = new TextEncoder();
|
||||
```
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "@polkadot/x-textencoder",
|
||||
"version": "3.7.1",
|
||||
"description": "A TextDecoder replacement",
|
||||
"browser": "browser.js",
|
||||
"main": "node.js",
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"maintainers": [
|
||||
"Jaco Greeff <jacogr@gmail.com>"
|
||||
],
|
||||
"contributors": [],
|
||||
"license": "Apache-2.0",
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"registry": "https://registry.npmjs.org"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/polkadot-js/common.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/polkadot-js/common/issues"
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/x-textencoder#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Copyright 2017-2020 @polkadot/x-textencoder authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export default typeof TextEncoder === 'undefined'
|
||||
? class {
|
||||
encode (value: string): Uint8Array {
|
||||
const u8a = new Uint8Array(value.length);
|
||||
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
u8a[i] = value.charCodeAt(i);
|
||||
}
|
||||
|
||||
return u8a;
|
||||
}
|
||||
}
|
||||
: TextEncoder;
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright 2017-2020 @polkadot/x-textencoder authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { TextEncoder as NodeTextEncoder } from 'util';
|
||||
|
||||
export default typeof TextEncoder === 'undefined'
|
||||
? class {
|
||||
#encoder: NodeTextEncoder;
|
||||
|
||||
constructor () {
|
||||
this.#encoder = new NodeTextEncoder();
|
||||
}
|
||||
|
||||
// For a Jest 26.0.1 environment, Buffer !== Uint8Array
|
||||
encode (value: string): Uint8Array {
|
||||
const encoded = this.#encoder.encode(value);
|
||||
|
||||
return Uint8Array.from(encoded);
|
||||
}
|
||||
} as unknown as typeof TextEncoder
|
||||
: TextEncoder;
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2020 @polkadot/x-textencoder authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import BrowserTE from './browser';
|
||||
import NodeTE from './node';
|
||||
|
||||
console.log(new BrowserTE().encode('abc'));
|
||||
console.log(new NodeTE().encode('abc'));
|
||||
@@ -0,0 +1,12 @@
|
||||
# @polkadot/x-ws
|
||||
|
||||
A cross-environment WebSocket.
|
||||
|
||||
Install it via `yarn add @polkadot/x-ws`
|
||||
|
||||
```js
|
||||
import WebSocket from '@polkadot/x-ws';
|
||||
|
||||
...
|
||||
const ws = new WebSocket('wss://example.com');
|
||||
```
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "@polkadot/x-ws",
|
||||
"version": "3.7.1",
|
||||
"description": "A cross-environment WebSocket replacement",
|
||||
"browser": "browser.js",
|
||||
"main": "node.js",
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"maintainers": [
|
||||
"Jaco Greeff <jacogr@gmail.com>"
|
||||
],
|
||||
"contributors": [],
|
||||
"license": "Apache-2.0",
|
||||
"publishConfig": {
|
||||
"access": "public",
|
||||
"registry": "https://registry.npmjs.org"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/polkadot-js/common.git"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/polkadot-js/common/issues"
|
||||
},
|
||||
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/x-ws#readme",
|
||||
"dependencies": {
|
||||
"@babel/runtime": "^7.12.1",
|
||||
"@types/websocket": "^1.0.1",
|
||||
"websocket": "^1.0.32"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright 2017-2020 @polkadot/x-ws authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export default WebSocket;
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2020 @polkadot/x-ws authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { w3cwebsocket } from 'websocket';
|
||||
|
||||
export default typeof WebSocket === 'undefined'
|
||||
? w3cwebsocket as unknown as typeof WebSocket
|
||||
: WebSocket;
|
||||
+3
-2
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"extends": "./node_modules/@polkadot/dev/config/tsconfig",
|
||||
"extends": "@polkadot/dev/config/tsconfig",
|
||||
"exclude": [
|
||||
"build/**/*",
|
||||
"**/build/**/*"
|
||||
@@ -14,7 +14,8 @@
|
||||
"@polkadot/util-crypto": [ "packages/util-crypto/src" ],
|
||||
"@polkadot/util-crypto/*": [ "packages/util-crypto/src/*" ],
|
||||
"@polkadot/util": [ "packages/util/src" ],
|
||||
"@polkadot/util/*": [ "packages/util/src/*" ]
|
||||
"@polkadot/util/*": [ "packages/util/src/*" ],
|
||||
"@polkadot/x-*": [ "packages/x-*/src/browser" ]
|
||||
},
|
||||
"skipLibCheck": true,
|
||||
"typeRoots": [
|
||||
|
||||
Reference in New Issue
Block a user