Compare commits

...

39 Commits

Author SHA1 Message Date
Travis CI
1018a11548 [CI Skip] 1.3.1 2019-09-10 17:14:48 +00:00
Jaco Greeff
dc55f2170f 1.3.1 (#467)
* 1.3.1

* CHANGELOG bump
2019-09-10 19:08:12 +02:00
Travis CI
36cd5cd504 [CI Skip] 1.3.0-beta.1 2019-09-10 15:51:48 +00:00
Jaco Greeff
a5d23696e6 Remove ExtError 2019-09-10 17:44:47 +02:00
Travis CI
5adc753f81 [CI Skip] 1.3.0-beta.0 2019-09-10 15:16:34 +00:00
Jaco Greeff
5e494b7163 Fix ExtError construction 2019-09-10 17:03:21 +02:00
Travis CI
3b6d383ace [CI Skip] 1.2.1 2019-09-09 12:14:50 +00:00
Jaco Greeff
e2ec7d0108 1.2 (#466) 2019-09-09 14:08:18 +02:00
Travis CI
33afae891f [CI Skip] 1.2.0-beta.7 2019-09-05 09:32:43 +00:00
Jaco Greeff
a1c2f03469 Bump deps (#465) 2019-09-05 11:26:08 +02:00
Travis CI
14d07988c3 [CI Skip] 1.2.0-beta.6 2019-09-01 18:02:57 +00:00
Jaco Greeff
9a4938bfc5 Add copy-to-apps script 2019-09-01 19:56:10 +02:00
Jaco Greeff
4323343973 Update eslint config (#464)
* Update eslint config

* isEmpty test
2019-09-01 19:46:40 +02:00
Travis CI
402048a414 [CI Skip] 1.2.0-beta.5 2019-08-31 12:33:04 +00:00
Jaco Greeff
22e76c17ca Allow addFromAddress to be encodable (#463) 2019-08-31 14:26:47 +02:00
Travis CI
b2ed63b66a [CI Skip] 1.2.0-beta.4 2019-08-30 10:30:38 +00:00
Jaco Greeff
25fc033728 typescript-eslint 2 (#462)
* typescript-eslint 2

* startsWith fixes

* padStart/padEnd
2019-08-30 12:24:16 +02:00
Travis CI
67513ed7a4 [CI Skip] 1.2.0-beta.3 2019-08-29 13:56:04 +00:00
Jaco Greeff
ef385913c4 Bump deps (#461)
* Bump deps

* Window & globalThis
2019-08-29 15:50:21 +02:00
Travis CI
9abf16e9e6 [CI Skip] 1.2.0-beta.2 2019-08-27 10:17:20 +00:00
Jaco Greeff
a8b28a2172 Bump dev (#460)
* Bump dev

* Linting cleanups (stricter rules)
2019-08-27 12:11:26 +02:00
Travis CI
2d18f9d190 [CI Skip] 1.2.0-beta.1 2019-08-13 08:29:01 +00:00
Jaco Greeff
4308722ef6 Try bumping gh-pages (#458) 2019-08-13 10:22:53 +02:00
Jaco Greeff
1e67f589b9 Maintainability indicator 2019-08-12 09:09:45 +02:00
Jaco Greeff
1fa08117bb Cleanup README 2019-08-11 08:08:28 +02:00
Jaco Greeff
0d9f30006c Update README.md 2019-08-10 15:21:04 +02:00
Jaco Greeff
b48420f299 Update README.md 2019-08-10 14:50:32 +02:00
Jaco Greeff
ac4e0904e9 Update README.md 2019-08-10 14:24:46 +02:00
Jaco Greeff
70cca25cb1 README badges 2019-08-10 14:23:37 +02:00
Travis CI
0afcb24885 [CI Skip] 1.2.0-beta.0 2019-08-09 13:34:11 +00:00
Jaco Greeff
808b6330a4 Bump deps (#457)
* Bump deps

* Rewrite lock

* jest --runInBand

* Rewrite lockfile
2019-08-09 15:28:25 +02:00
Travis CI
7505e6c1f6 [CI Skip] 1.1.1 2019-08-09 10:05:42 +00:00
Jaco Greeff
1d0a4e727c 1.1 (#456) 2019-08-09 11:59:51 +02:00
Travis CI
bc941b3fc2 [CI Skip] 1.1.0-beta.2 2019-08-09 08:19:54 +00:00
Jaco Greeff
09e0b80dc6 assertSingleton warns, not throws (#455) 2019-08-09 10:13:43 +02:00
Travis CI
16340c59d8 [CI Skip] 1.1.0-beta.1 2019-08-03 20:39:48 +00:00
Jaco Greeff
f0aebfc1bf .123trigger 2019-08-03 22:33:22 +02:00
Travis CI
775ee9999f [CI Skip] 1.1.0-beta.0 2019-08-03 18:14:40 +00:00
Jaco Greeff
395569c588 unbump gh-pages dep (#453) 2019-08-03 20:06:15 +02:00
94 changed files with 1192 additions and 1316 deletions

21
.circleci/config.yml Normal file
View File

@@ -0,0 +1,21 @@
version: 2
jobs:
build:
working_directory: ~/polkadot-js
docker:
- image: circleci/node:10
steps:
- checkout
- restore_cache:
key: dependency-cache-{{ checksum "yarn.lock" }}
- run:
name: install-deps
command: yarn install --frozen-lockfile
- save_cache:
key: dependency-cache-{{ checksum "yarn.lock" }}
paths:
- ./node_modules
- ~/.cache/yarn
- run:
name: build
command: yarn polkadot-dev-circleci-build

View File

@@ -1 +1,11 @@
module.exports = require('@polkadot/dev/config/eslint');
const base = require('@polkadot/dev/config/eslint');
module.exports = {
...base,
parserOptions: {
...base.parserOptions,
project: [
'./tsconfig.eslint.json'
]
}
};

View File

@@ -1,4 +1,17 @@
# 1.0.0
# 1.3.1
- Remove the `ExtError` class, always prefer the standard JS `Error` object for errors. This would bre a breaking change for any appliactions using `ExtError`
# 1.2.1
- Keyring `addFromAddress` can now be used to store external accounts, for example those provided by external signers
- Maintainability updates
# 1.1.1
- `assertSingletonPackage` now warns via console.warn, but does not throw. This does allow the info to come accross while still allowing the app developers using multiple libraries time to fix.
# 1.0.1
- `formatBalance` now allows for `Compact` inputs
- `formaBalance` now allows correct formatting of very large decimals

View File

@@ -1,11 +1,9 @@
[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange.svg?style=flat-square)](https://polkadot.js.org)
![license](https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square)
[![style](https://img.shields.io/badge/code%20style-semistandard-lightgrey.svg?style=flat-square)](https://github.com/Flet/semistandard)
[![npm](https://img.shields.io/npm/v/@polkadot/util.svg?style=flat-square)](https://www.npmjs.com/package/@polkadot/util)
[![travis](https://img.shields.io/travis/polkadot-js/common.svg?style=flat-square)](https://travis-ci.com/polkadot-js/common)
[![maintainability](https://img.shields.io/codeclimate/maintainability/polkadot-js/common.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/common)
[![coverage](https://img.shields.io/codeclimate/coverage/polkadot-js/common.svg?style=flat-square)](https://codeclimate.com/github/polkadot-js/common)
[![greenkeeper](https://img.shields.io/badge/greenkeeper-enabled-brightgreen.svg?style=flat-square)](https://greenkeeper.io/)
[![polkadotjs](https://img.shields.io/badge/polkadot-js-orange?logo=&style=flat-square)](https://polkadot.js.org)
![license](https://img.shields.io/badge/License-Apache%202.0-blue?logo=apache&style=flat-square)
[![npm](https://img.shields.io/npm/v/@polkadot/util?logo=npm&style=flat-square)](https://www.npmjs.com/package/@polkadot/util)
[![beta](https://img.shields.io/npm/v/@polkadot/util/beta?label=beta&logo=npm&style=flat-square)](https://www.npmjs.com/package/@polkadot/util)
[![maintainability](https://img.shields.io/codeclimate/maintainability-percentage/polkadot-js/common?logo=code-climate&style=flat-square)](https://codeclimate.com/github/polkadot-js/common)
[![coverage](https://img.shields.io/codeclimate/coverage/polkadot-js/common?logo=code-climate&style=flat-square)](https://codeclimate.com/github/polkadot-js/common)
# @polkadot/common

17
copy-to-apps.sh Executable file
View File

@@ -0,0 +1,17 @@
#!/bin/bash
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"

View File

@@ -1,3 +1,5 @@
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-var-requires */
// Import Keyring class and utility function
const Keyring = require('@polkadot/keyring').default;

View File

@@ -1,3 +1,5 @@
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-var-requires */
// Import Keyring class and utility function
const Keyring = require('@polkadot/keyring').default;

View File

@@ -1,3 +1,5 @@
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-var-requires */
const { naclEncrypt, naclDecrypt } = require('@polkadot/util-crypto');

View File

@@ -1,3 +1,5 @@
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/no-var-requires */
const { stringToU8a, u8aToHex } = require('@polkadot/util');
const { naclEncrypt, naclKeypairFromSeed, naclSign, naclVerify, randomAsU8a } = require('@polkadot/util-crypto');

View File

@@ -1,3 +1,5 @@
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/require-await */
/* eslint-disable @typescript-eslint/no-var-requires,@typescript-eslint/no-unused-vars */
const { mnemonicGenerate, mnemonicToSeed, mnemonicValidate, naclKeypairFromSeed } = require('@polkadot/util-crypto');

View File

@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "1.0.1"
"version": "1.3.1"
}

View File

@@ -1,5 +1,5 @@
{
"version": "1.0.1",
"version": "1.3.1",
"private": true,
"engines": {
"yarn": "^1.10.1"
@@ -9,7 +9,7 @@
],
"resolutions": {
"babel-core": "^7.0.0-bridge.0",
"typescript": "^3.5.3"
"typescript": "^3.6.2"
},
"scripts": {
"build": "polkadot-dev-build-ts && polkadot-dev-build-docs",
@@ -17,13 +17,13 @@
"lint": "eslint . --ext .js,.jsx,.ts,.tsx . && tsc --noEmit --pretty",
"clean": "polkadot-dev-clean-build",
"postinstall": "polkadot-dev-yarn-only",
"test": "jest --coverage",
"test": "jest --coverage --runInBand",
"test:one": "jest"
},
"devDependencies": {
"@babel/core": "^7.5.5",
"@polkadot/dev": "^0.30.0-beta.24",
"@polkadot/ts": "^0.1.62",
"gh-pages": "^2.1.0"
"@polkadot/dev": "^0.31.0-beta.7",
"@polkadot/ts": "^0.1.71",
"gh-pages": "^2.1.1"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@polkadot/chainspec",
"version": "1.0.1",
"version": "1.3.1",
"description": "Contains chain specifications for known chains",
"main": "index.js",
"keywords": [
@@ -26,6 +26,6 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/chainspec#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/util": "^1.0.1"
"@polkadot/util": "^1.3.1"
}
}

View File

@@ -4,7 +4,6 @@
import { Chainspec } from './types';
// eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion
export default {
name: 'Alexander',
id: 'alexander',

View File

@@ -4,7 +4,6 @@
import { Chainspec } from './types';
// eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion
export default {
name: 'Dried Danta',
id: 'dried-danta',

View File

@@ -1,6 +1,6 @@
{
"name": "@polkadot/db",
"version": "1.0.1",
"version": "1.3.1",
"description": "Implementation of a basic sync in-memory and on-disk databases with overlays",
"main": "index.js",
"keywords": [
@@ -26,8 +26,8 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/db#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/trie-hash": "^1.0.1",
"@polkadot/util": "^1.0.1",
"@polkadot/trie-hash": "^1.3.1",
"@polkadot/util": "^1.3.1",
"lru_map": "^0.3.3"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@polkadot/keyring",
"version": "1.0.1",
"version": "1.3.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.5.5",
"@polkadot/util": "^1.0.1",
"@polkadot/util-crypto": "^1.0.1"
"@polkadot/util": "^1.3.1",
"@polkadot/util-crypto": "^1.3.1"
}
}

View File

@@ -19,7 +19,7 @@ describe('keypair', (): void => {
const seedTwo = hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60');
let keypair: Keyring;
beforeEach(async (): Promise<void> => {
beforeEach((): void => {
keypair = new Keyring({ type: 'ed25519' });
keypair.addFromSeed(seedOne, {});

View File

@@ -90,7 +90,7 @@ export default class Keyring implements KeyringInstance {
public addFromAddress (address: string | Uint8Array, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null, type: KeypairType = this.type, ignoreChecksum?: boolean): KeyringPair {
const publicKey = this.decodeAddress(address, ignoreChecksum);
return this.addPair(createPair(type, { publicKey }, meta, encoded));
return this.addPair(createPair(type, { publicKey, secretKey: new Uint8Array(64) }, meta, encoded));
}
/**
@@ -153,7 +153,7 @@ export default class Keyring implements KeyringInstance {
*/
public createFromUri (_suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair {
// here we only aut-add the dev phrase if we have a hard-derived path
const suri = _suri.indexOf('//') === 0
const suri = _suri.startsWith('//')
? `${DEV_PHRASE}${_suri}`
: _suri;
const { password, phrase, path } = keyExtractSuri(suri);

View File

@@ -15,7 +15,7 @@ type DecodeResult = PairInfo & {
};
export default function decode (passphrase?: string, _encrypted?: Uint8Array | null): DecodeResult {
assert(_encrypted, `No encrypted data available to decode`);
assert(_encrypted, 'No encrypted data available to decode');
const encrypted = (_encrypted as Uint8Array);
const encoded = passphrase
@@ -26,7 +26,7 @@ export default function decode (passphrase?: string, _encrypted?: Uint8Array | n
) as Uint8Array)
: encrypted;
assert(encoded, `Unable to unencrypt using the supplied passphrase`);
assert(encoded, 'Unable to unencrypt using the supplied passphrase');
const header = encoded.subarray(0, PKCS8_HEADER.length);

View File

@@ -12,6 +12,10 @@ import decode from './decode';
import encode from './encode';
import toJson from './toJson';
function isEmpty (u8a: Uint8Array): boolean {
return u8a.reduce((count, u8): number => count + u8, 0) === 0;
}
const isSr25519 = (type: KeypairType): boolean =>
type === 'sr25519';
@@ -86,7 +90,7 @@ export default function createPair (type: KeypairType, { publicKey, secretKey }:
return meta;
},
get isLocked (): boolean {
return !secretKey || secretKey.length === 0;
return !secretKey || secretKey.length === 0 || isEmpty(secretKey);
},
lock: (): void => {
secretKey = new Uint8Array(0);

View File

@@ -7,10 +7,7 @@ import { KeyringPairs, KeyringPair } from './types';
import { assert, isHex, isU8a, u8aToHex, u8aToU8a } from '@polkadot/util';
import { decodeAddress } from '@polkadot/util-crypto';
interface KeyringPairMap {
// @ts-ignore we use coercion :(
[index: Uint8Array]: KeyringPair;
}
type KeyringPairMap = Record<string, KeyringPair>;
export default class Pairs implements KeyringPairs {
private _map: KeyringPairMap;
@@ -20,8 +17,7 @@ export default class Pairs implements KeyringPairs {
}
public add (pair: KeyringPair): KeyringPair {
// @ts-ignore we use coercion :(
this._map[pair.publicKey] = pair;
this._map[pair.publicKey.toString()] = pair;
return pair;
}
@@ -31,8 +27,7 @@ export default class Pairs implements KeyringPairs {
}
public get (address: string | Uint8Array): KeyringPair {
// @ts-ignore we use coercion :(
const pair = this._map[decodeAddress(address)];
const pair = this._map[decodeAddress(address).toString()];
assert(pair, (): string => {
const formatted: string = isU8a(address) || isHex(address)
@@ -46,7 +41,6 @@ export default class Pairs implements KeyringPairs {
}
public remove (address: string | Uint8Array): void {
// @ts-ignore we use coercion :(
delete this._map[decodeAddress(address)];
delete this._map[decodeAddress(address).toString()];
}
}

View File

@@ -77,7 +77,7 @@ const PAIRS: PairDef[] = [
* @description The test accounts (i.e. alice, bob, dave, eve, ferdie)
* are available on the dev chain and each test account is initialised with DOT funds.
*/
export default function testKeyring (options: KeyringOptions = {}, isDerived: boolean = true): KeyringInstance {
export default function testKeyring (options: KeyringOptions = {}, isDerived = true): KeyringInstance {
const keyring = new Keyring(options);
PAIRS.forEach(({ name, publicKey, secretKey, seed, type }): void => {

View File

@@ -11,7 +11,7 @@ export interface TestKeyringMap {
[index: string]: KeyringPair;
}
export default function testKeyringPairs (options?: KeyringOptions, isDerived: boolean = true): TestKeyringMap {
export default function testKeyringPairs (options?: KeyringOptions, isDerived = true): TestKeyringMap {
const keyring = createKeyring(options, isDerived);
const pairs = keyring.getPairs();
const map: TestKeyringMap = { nobody: nobody() };

View File

@@ -1,6 +1,6 @@
{
"name": "@polkadot/trie-codec",
"version": "1.0.1",
"version": "1.3.1",
"description": "This is an implementation of the codec for Substrate Trie",
"main": "index.js",
"keywords": [
@@ -26,6 +26,6 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/trie-codec#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/util": "^1.0.1"
"@polkadot/util": "^1.3.1"
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "@polkadot/trie-db",
"version": "1.0.1",
"version": "1.3.1",
"description": "This is an implementation of the modified merkle patricia tree as specified in Ethereum's yellow paper, adapted for Polkadot",
"main": "index.js",
"keywords": [
@@ -26,15 +26,15 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/trie-db#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/db": "^1.0.1",
"@polkadot/trie-codec": "^1.0.1",
"@polkadot/trie-hash": "^1.0.1",
"@polkadot/util": "^1.0.1",
"@polkadot/util-crypto": "^1.0.1"
"@polkadot/db": "^1.3.1",
"@polkadot/trie-codec": "^1.3.1",
"@polkadot/trie-hash": "^1.3.1",
"@polkadot/util": "^1.3.1",
"@polkadot/util-crypto": "^1.3.1"
},
"devDependencies": {
"@polkadot/chainspec": "^1.0.1",
"@polkadot/util-rlp": "^1.0.1",
"@polkadot/chainspec": "^1.3.1",
"@polkadot/util-rlp": "^1.3.1",
"ethereumjs-testing": "1.0.4"
}
}

View File

@@ -43,9 +43,8 @@ describe.skip('official tests', (): void => {
it(name, (): void => {
keys.forEach((key: string): void => {
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-explicit-any
trie.put(toU8a(key), toU8a(input[key as any]));
trie.put(toU8a(key), toU8a(input[key as any] as string));
});
expect(

View File

@@ -36,7 +36,7 @@ describe('snapshots', (): void => {
trie.put(toU8a('doge'), toU8a('coin'));
trie.del(toU8a('doge'));
trie.snapshot(back, (): undefined => void 0);
trie.snapshot(back, (): void => {});
expect(u8aToHex(back.getRoot())).toEqual(u8aToHex(root));
expect(back.get(values[0].k)).toEqual(values[0].v);
@@ -48,7 +48,7 @@ describe('snapshots', (): void => {
values.forEach(({ k, v }): void => {
trie.put(k, v);
});
trie.snapshot(back, (): undefined => void 0);
trie.snapshot(back, (): void => {});
expect(u8aToHex(back.getRoot())).toEqual(u8aToHex(root));

View File

@@ -24,7 +24,7 @@ export function getNodeType (node: Node): NodeType {
return NodeType.BRANCH;
}
throw new Error(`Unable to determine node type`);
throw new Error('Unable to determine node type');
}
export function decodeNode (codec: Codec, encoded: Uint8Array | Node): Node {

View File

@@ -1,6 +1,6 @@
{
"name": "@polkadot/trie-hash",
"version": "1.0.1",
"version": "1.3.1",
"description": "Generates trie roots from key-value pairs",
"main": "index.js",
"keywords": [
@@ -26,9 +26,9 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/trie-hash#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/util": "^1.0.1"
"@polkadot/util": "^1.3.1"
},
"devDependencies": {
"@polkadot/chainspec": "^1.0.1"
"@polkadot/chainspec": "^1.3.1"
}
}

View File

@@ -78,7 +78,7 @@ function _buildTrie (input: [Uint8Array, Uint8Array][], cursor: number, codec: C
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function buildTrie (input: [Uint8Array, Uint8Array][], cursor: number = 0, codec: Codec = DEFAULT_CODEC, stream: any = DEFAULT_STREAM): Uint8Array {
export default function buildTrie (input: [Uint8Array, Uint8Array][], cursor = 0, codec: Codec = DEFAULT_CODEC, stream: any = DEFAULT_STREAM): Uint8Array {
const trie = _buildTrie(input, cursor, codec, stream);
return trie;

View File

@@ -1,6 +1,6 @@
{
"name": "@polkadot/util-crypto",
"version": "1.0.1",
"version": "1.3.1",
"description": "A collection of useful crypto utilities for @polkadot",
"main": "index.js",
"keywords": [
@@ -26,8 +26,8 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-crypto#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/util": "^1.0.1",
"@polkadot/wasm-crypto": "^0.13.1",
"@polkadot/util": "^1.3.1",
"@polkadot/wasm-crypto": "^0.14.1",
"@types/bip39": "^2.4.2",
"@types/bs58": "^4.0.0",
"@types/pbkdf2": "^3.0.0",

View File

@@ -8,7 +8,7 @@ import decode from './decode';
describe('decode', (): void => {
let keyring: TestKeyringMap;
beforeAll(async (): Promise<void> => {
beforeAll((): void => {
keyring = testingPairs({ type: 'sr25519' });
});

View File

@@ -20,7 +20,7 @@ import blake2AsU8a from './asU8a';
* blake2AsHex('abc'); // => 0xba80a53f981c4d0d
* ```
*/
export default function blake2AsHex (data: Uint8Array | string, bitLength: number = 256): string {
export default function blake2AsHex (data: Uint8Array | string, bitLength = 256): string {
return u8aToHex(
blake2AsU8a(data, bitLength)
);

View File

@@ -20,7 +20,7 @@ import { blake2b, isReady } from '@polkadot/wasm-crypto';
* blake2AsU8a('abc'); // => [0xba, 0x80, 0xa53, 0xf98, 0x1c, 0x4d, 0x0d]
* ```
*/
export default function blake2AsU8a (data: Uint8Array | string, bitLength: number = 256, key: Uint8Array | null = null): Uint8Array {
export default function blake2AsU8a (data: Uint8Array | string, bitLength = 256, key: Uint8Array | null = null): Uint8Array {
const byteLength = Math.ceil(bitLength / 8);
return isReady()

View File

@@ -18,10 +18,10 @@ const BN_OPTIONS = {
export default class DeriveJunction {
private _chainCode: Uint8Array = new Uint8Array(32);
private _isHard: boolean = false;
private _isHard = false;
public static from (value: string): DeriveJunction {
const [code, isHard] = value[0] === '/'
const [code, isHard] = value.startsWith('/')
? [value.substr(1), true]
: [value, false];
const result = new DeriveJunction();

View File

@@ -19,6 +19,7 @@ const RE_CAPTURE = /^(\w+( \w+)*)((\/\/?[^/]+)*)(\/\/\/(.*))?$/;
* @description Extracts the phrase, path and password from a SURI format for specifying secret keys `<secret>/<soft-key>//<hard-key>///<password>` (the `///password` may be omitted, and `/<soft-key>` and `//<hard-key>` maybe repeated and mixed).
*/
export default function keyExtract (suri: string): ExtractResult {
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const matches = suri.match(RE_CAPTURE);
assert(!isNull(matches), `Unable to match '${suri}' to a secret URI`);

View File

@@ -10,7 +10,7 @@ import { bip39ToMiniSecret, isReady } from '@polkadot/wasm-crypto';
import toEntropy from './toEntropy';
export default function toMiniSecret (mnemonic: string, password: string = ''): Uint8Array {
export default function toMiniSecret (mnemonic: string, password = ''): Uint8Array {
if (isReady()) {
return bip39ToMiniSecret(mnemonic, password);
}

View File

@@ -23,7 +23,7 @@ import { bip39ToSeed, isReady } from '@polkadot/wasm-crypto';
* }
* ```
*/
export default function toSeed (mnemonic: string, password: string = ''): Uint8Array {
export default function toSeed (mnemonic: string, password = ''): Uint8Array {
return isReady()
? bip39ToSeed(mnemonic, password)
: bufferToU8a(mnemonicToSeed(mnemonic, password)).subarray(0, 32);

View File

@@ -20,7 +20,7 @@ import randomAsU8a from './asU8a';
* randomAsHex(); // => 0x...
* ```
*/
export default function randomAsHex (length: number = 32): string {
export default function randomAsHex (length = 32): string {
return u8aToHex(
randomAsU8a(length)
);

View File

@@ -18,6 +18,6 @@ import nacl from 'tweetnacl';
* randomAsU8a(); // => Uint8Array([...])
* ```
*/
export default function randomAsU8a (length: number = 32): Uint8Array {
export default function randomAsU8a (length = 32): Uint8Array {
return nacl.randomBytes(length);
}

View File

@@ -20,7 +20,7 @@ import xxhashAsU8a from './asU8a';
* xxhashAsHex('abc'); // => 0x44bc2cf5ad770999
* ```
*/
export default function xxhashAsHex (data: Buffer | Uint8Array | string, bitLength: number = 64): string {
export default function xxhashAsHex (data: Buffer | Uint8Array | string, bitLength = 64): string {
return u8aToHex(
xxhashAsU8a(data, bitLength)
);

View File

@@ -21,7 +21,7 @@ import xxhash64AsBn from './xxhash64/asBn';
* xxhashAsU8a('abc'); // => 0x44bc2cf5ad770999
* ```
*/
export default function xxhashAsU8a (data: Buffer | Uint8Array | string, bitLength: number = 64): Uint8Array {
export default function xxhashAsU8a (data: Buffer | Uint8Array | string, bitLength = 64): Uint8Array {
const iterations = Math.ceil(bitLength / 64);
if (isReady()) {

View File

@@ -21,13 +21,11 @@ import { isBuffer, isString, u8aToBuffer } from '@polkadot/util';
*/
export default function xxhash64AsValue (data: Buffer | Uint8Array | string, seed: number): number {
if (isBuffer(data) || isString(data)) {
// @ts-ignore Buffer is ArrayBuffer underlying
return xxhashjs.h64(data, seed);
return xxhashjs.h64(data, seed) as unknown as number;
}
// @ts-ignore conversion works, yields correct result
return xxhashjs.h64(
u8aToBuffer(data),
seed
) as number;
) as unknown as number;
}

View File

@@ -1,6 +1,6 @@
{
"name": "@polkadot/util-rlp",
"version": "1.0.1",
"version": "1.3.1",
"description": "RLP encoding and decoding",
"main": "index.js",
"keywords": [
@@ -28,7 +28,7 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-rlp#readme",
"dependencies": {
"@babel/runtime": "^7.5.5",
"@polkadot/util": "^1.0.1"
"@polkadot/util": "^1.3.1"
},
"devDependencies": {
"ethereumjs-testing": "1.0.4"

View File

@@ -30,6 +30,5 @@ export default function decode (input: Uint8Array): DecodeOutput {
assert(decoder, 'Unable to find decoder for input type');
// @ts-ignore assert catches invalids, which _should_ not happen...
return decoder.fn(decode, input);
return (decoder as Decoder).fn(decode, input);
}

View File

@@ -9,7 +9,7 @@ import { u8aConcat } from '@polkadot/util';
import encodeLength from './length';
export default function encodeArray (encoder: EncodeFunc, input: (Uint8Array | null)[]): Uint8Array {
const encoded = u8aConcat.apply(null, input.map(encoder));
const encoded = u8aConcat(...input.map(encoder));
return u8aConcat(
encodeLength(encoded.length, 192),

View File

@@ -45,6 +45,5 @@ export default function toU8a (value?: any): Uint8Array {
assert(encoder, 'invalid type');
// @ts-ignore the assert catches any unknowns
return encoder.fn(value);
return (encoder as Encoder).fn(value);
}

View File

@@ -19,9 +19,10 @@ export default function getTests (file: string): Test[] {
return Object.keys(tests).map((name): Test => ({
name,
input: tests[name].in[0] !== '#'
? tests[name].in
: bnToU8a(new BN(tests[name].in.slice(1)), { isLe: false }),
// eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with
input: tests[name].in[0] === '#'
? bnToU8a(new BN(tests[name].in.slice(1)), { isLe: false })
: tests[name].in,
output: tests[name].out
? `0x${tests[name].out.toLowerCase()}`
: undefined,

View File

@@ -1,6 +1,6 @@
{
"name": "@polkadot/util",
"version": "1.0.1",
"version": "1.3.1",
"description": "A collection of useful utilities for @polkadot",
"main": "index.js",
"keywords": [

View File

@@ -7,13 +7,13 @@ import { arrayFilter } from '.';
describe('filterArray', (): void => {
it('filters arrays, removing undefined', (): void => {
expect(
arrayFilter([0, '', null, false, void 0, NaN])
arrayFilter([0, '', null, false, undefined, NaN])
).toEqual([0, '', null, false, NaN]);
});
it('filters arrays, removing undefined & null (allowNull = false)', (): void => {
expect(
arrayFilter([0, '', null, false, void 0, NaN], false)
arrayFilter([0, '', null, false, undefined, NaN], false)
).toEqual([0, '', false, NaN]);
});
});

View File

@@ -21,7 +21,7 @@ import isUndefined from '../is/undefined';
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function arrayFilter (array: any[], allowNulls: boolean = true): any[] {
export default function arrayFilter (array: any[], allowNulls = true): any[] {
return array.filter((value): boolean => {
return !isUndefined(value) && (allowNulls || !isNull(value));
});

View File

@@ -22,14 +22,4 @@ describe('assert', (): void => {
(): boolean => assert(false, (): string => 'message from function')
).toThrow(/message from function/);
});
it('throws a valid constructed ExtError', (): void => {
try {
assert(false, 'error', -666, 'data');
} catch (error) {
expect(error.code).toEqual(-666);
expect(error.data).toEqual('data');
expect(error.message).toEqual('error');
}
});
});

View File

@@ -2,7 +2,6 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import ExtError from './ext/error';
import isFunction from './is/function';
type MessageFn = () => string;
@@ -11,9 +10,9 @@ type Falsy = null | undefined | false | 0 | ''; // No NaN type
/**
* @name assert
* @summary Checks for a valid test, if not ExtError is thrown.
* @summary Checks for a valid test, if not Error is thrown.
* @description
* Checks that `test` is a truthy value. If value is falsy (`null`, `undefined`, `false`, ...), it throws an ExtError with the supplied `message` and an optional `code` and `data`. When `test` passes, `true` is returned.
* Checks that `test` is a truthy value. If value is falsy (`null`, `undefined`, `false`, ...), it throws an Error with the supplied `message`. When `test` passes, `true` is returned.
* @example
* <BR>
*
@@ -21,11 +20,11 @@ type Falsy = null | undefined | false | 0 | ''; // No NaN type
* const { assert } from '@polkadot/util';
*
* assert(true, 'True should be true'); // true returned
* assert(false, 'False should not be true'); // ExtError thrown
* assert(false, () => 'message'); // ExtError with 'message'
* assert(false, 'False should not be true'); // Error thrown
* assert(false, () => 'message'); // Error with 'message'
* ```
*/
export default function assert<T> (test: Falsy | T, message: string | MessageFn, code: number = ExtError.CODES.ASSERT, data?: string | number): test is T {
export default function assert<T> (test: Falsy | T, message: string | MessageFn): test is T {
if (test) {
return true;
}
@@ -34,5 +33,5 @@ export default function assert<T> (test: Falsy | T, message: string | MessageFn,
message = message();
}
throw new ExtError(message, code, data);
throw new Error(message);
}

View File

@@ -7,15 +7,19 @@ import { assertSingletonPackage } from '.';
describe('assertSingletonPackage', (): void => {
const NAME = 'assertSingletonPackage';
it('should not throw the first time', (): void => {
expect(
(): void => assertSingletonPackage(NAME)
).not.toThrow();
it('should not log the first time', (): void => {
const spy = jest.spyOn(console, 'warn');
assertSingletonPackage(NAME);
expect(spy).not.toHaveBeenCalled();
spy.mockRestore();
});
it('should throw the second time', (): void => {
expect(
(): void => assertSingletonPackage(NAME)
).toThrow(/Multiple versions of assertSingletonPackage detected/);
it('should log the second time', (): void => {
const spy = jest.spyOn(console, 'warn');
assertSingletonPackage(NAME);
expect(spy).toHaveBeenCalledWith('Multiple versions of assertSingletonPackage detected, ensure that there is only one version in your dependency tree');
spy.mockRestore();
});
});

View File

@@ -3,9 +3,11 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import isUndefined from './is/undefined';
import assert from './assert';
interface PjsChecks {
// eslint-disable-next-line no-undef
type This = typeof globalThis;
interface PjsChecks extends This {
__polkadotjs: Record<string, boolean>;
}
@@ -25,7 +27,9 @@ export default function assertSingletonPackage (name: string): void {
_global.__polkadotjs = {};
}
assert(isUndefined(_global.__polkadotjs[name]), `Multiple versions of ${name} detected, ensure that there is only version one in your dependency tree`);
if (!isUndefined(_global.__polkadotjs[name])) {
console.warn(`Multiple versions of ${name} detected, ensure that there is only one version in your dependency tree`);
}
_global.__polkadotjs[name] = true;
}

View File

@@ -37,5 +37,5 @@ export default function bnToBn <ExtToBn extends ToBn> (value?: ExtToBn | BN | st
? value
: isToBn(value)
? value.toBn()
: new BN(value as number);
: new BN(value);
}

View File

@@ -1,101 +0,0 @@
// Copyright 2017-2019 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import isError from '../is/error';
import { ExtError } from '.';
describe('ExtError', (): void => {
describe('constructor', (): void => {
it('constructs an Error that is still an Error', (): void => {
expect(
isError(
new ExtError()
)
).toEqual(true);
});
});
describe('static', (): void => {
it('exposes the .CODES as a static', (): void => {
expect(
Object.keys(ExtError.CODES)
).not.toEqual(0);
});
});
describe('constructor properties', (): void => {
it('sets the .message property', (): void => {
expect(
new ExtError('test message').message
).toEqual('test message');
});
it("sets the .message to '' when not set", (): void => {
expect(
new ExtError().message
).toEqual('');
});
it('sets the .code property', (): void => {
expect(
new ExtError('test message', 1234).code
).toEqual(1234);
});
it('sets the .code to UKNOWN when not set', (): void => {
expect(
new ExtError('test message').code
).toEqual(ExtError.CODES.UNKNOWN);
});
it('sets the .data property', (): void => {
const data = 'here';
expect(
new ExtError('test message', 1234, data).data
).toEqual(data);
});
});
describe('stack traces', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let captureStackTrace: (targetObject: Record<string, any>, constructorOpt?: Function | undefined) => void;
beforeEach((): void => {
captureStackTrace = Error.captureStackTrace;
Error.captureStackTrace = function (error): void {
Object.defineProperty(error, 'stack', {
configurable: true,
get: function getStack (): string {
const value = 'some stack returned';
Object.defineProperty(this, 'stack', { value });
return value;
}
});
};
});
afterEach((): void => {
Error.captureStackTrace = captureStackTrace;
});
it('captures via captureStackTrace when available', (): void => {
expect(
new ExtError().stack
).toEqual('some stack returned');
});
it('captures via stack when captureStackTrace not available', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Error.captureStackTrace = null as any;
expect(
new ExtError().stack.length
).not.toEqual(0);
});
});
});

View File

@@ -1,69 +0,0 @@
// Copyright 2017-2019 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { ExtErrorInterface } from '../types';
import isFunction from '../is/function';
const UNKNOWN = -99999;
function extend (that: ExtError, name: string, value?: string | number): void {
Object.defineProperty(that, name, {
configurable: true,
enumerable: false,
value
});
}
/**
* @name ExtError
* @summary Extension to the basic JS Error.
* @description
* The built-in JavaScript Error class is extended by adding a code to allow for Error categorization. In addition to the normal `stack`, `message`, the numeric `code` and `data` (any types) parameters are available on the object.
* @example
* <BR>
*
* ```javascript
* const { ExtError } from '@polkadot/util');
*
* throw new ExtError('some message', ExtError.CODES.METHOD_NOT_FOUND); // => error.code = -32601
* ```
*/
export default class ExtError extends Error implements ExtErrorInterface {
// @ts-ignore we are assigning it via extend
public code: number;
public data?: number | string;
// @ts-ignore we are assigning it via extend
public message: string;
// @ts-ignore we are assigning it via extend
public name: string;
// @ts-ignore we are assigning it via extend
public stack: string;
public constructor (message: string = '', code: number = UNKNOWN, data?: number | string) {
super();
extend(this, 'message', String(message));
extend(this, 'name', this.constructor.name);
extend(this, 'data', data);
extend(this, 'code', code);
if (isFunction(Error.captureStackTrace)) {
Error.captureStackTrace(this, this.constructor);
} else {
extend(this, 'stack', (new Error(message)).stack);
}
}
public static CODES = {
ASSERT: -90009,
UNKNOWN,
INVALID_JSONRPC: -99998,
METHOD_NOT_FOUND: -32601 // Rust client
};
}

View File

@@ -1,9 +0,0 @@
// Copyright 2017-2019 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
/**
* @summary Extensions to basic classes
*/
export { default as ExtError } from './error';

View File

@@ -32,7 +32,7 @@ let defaultDecimals = DEFAULT_DECIMALS;
let defaultUnit = DEFAULT_UNIT;
// Formats a string/number with <prefix>.<postfix><type> notation
function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | ExtToBn, withSi: boolean = true, decimals: number = defaultDecimals): string {
function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | ExtToBn, withSi = true, decimals: number = defaultDecimals): string {
let text = bnToBn(input).toString();
if (text.length === 0 || text === '0') {
@@ -41,7 +41,7 @@ function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | E
// strip the negative sign so we can work with clean groupings, re-add this in the
// end when we return the result (from here on we work with positive numbers)
const isNegative = text[0] === '-';
const isNegative = text[0].startsWith('-');
if (isNegative) {
text = text.substr(1);
@@ -68,10 +68,14 @@ function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | E
const formatBalance = _formatBalance as BalanceFormatter;
// eslint-disable-next-line @typescript-eslint/unbound-method
formatBalance.calcSi = (text: string, decimals: number = defaultDecimals): SiDef =>
calcSi(text, decimals);
// eslint-disable-next-line @typescript-eslint/unbound-method
formatBalance.findSi = findSi;
// eslint-disable-next-line @typescript-eslint/unbound-method
formatBalance.getDefaults = (): Defaults => {
return {
decimals: defaultDecimals,
@@ -80,6 +84,7 @@ formatBalance.getDefaults = (): Defaults => {
};
// get allowable options to display in a dropdown
// eslint-disable-next-line @typescript-eslint/unbound-method
formatBalance.getOptions = (decimals: number = defaultDecimals): SiDef[] => {
return SI.filter(({ power }): boolean =>
power < 0
@@ -89,6 +94,7 @@ formatBalance.getOptions = (decimals: number = defaultDecimals): SiDef[] => {
};
// Sets the default decimals to use for formatting (ui-wide)
// eslint-disable-next-line @typescript-eslint/unbound-method
formatBalance.setDefaults = ({ decimals, unit }: Partial<Defaults>): void => {
defaultDecimals = isUndefined(decimals) ? defaultDecimals : decimals;
defaultUnit = isUndefined(unit) ? defaultUnit : unit;

View File

@@ -7,7 +7,7 @@ const NUMBER_REGEX = new RegExp('(\\d+?)(?=(\\d{3})+(?!\\d)|$)', 'g');
export default function formatDecimal (value: string): string {
// We can do this by adjusting the regx, however for the sake of clarity
// we rather strip and re-add the negative sign in the output
const isNegative = value[0] === '-';
const isNegative = value[0].startsWith('-');
const matched = isNegative
? value.substr(1).match(NUMBER_REGEX)
: value.match(NUMBER_REGEX);

View File

@@ -21,7 +21,7 @@ import hexStripPrefix from './stripPrefix';
* console.log('fixed', hexFixLength('0x0012', 8)); // => 0x12
* ```
*/
export default function hexFixLength (value: string, bitLength: number = -1, withPadding: boolean = false): string {
export default function hexFixLength (value: string, bitLength = -1, withPadding = false): string {
const strLength = Math.ceil(bitLength / 4);
const hexLength = strLength + 2;

View File

@@ -21,7 +21,7 @@ import hexStripPrefix from './stripPrefix';
* hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
* ```
*/
export default function hexToU8a (_value?: string | null, bitLength: number = -1): Uint8Array {
export default function hexToU8a (_value?: string | null, bitLength = -1): Uint8Array {
if (!_value) {
return new Uint8Array([]);
}

View File

@@ -17,7 +17,6 @@ export * from './array';
export * from './bn';
export * from './buffer';
export * from './compact';
export * from './ext';
export * from './format';
export * from './hex';
export * from './is';

View File

@@ -22,7 +22,7 @@ const HEX_REGEX = /^0x[a-fA-F0-9]+$/;
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/ban-types
export default function isHex (value: any, bitLength: number = -1, ignoreLength: boolean = false): value is string | String {
export default function isHex (value: any, bitLength = -1, ignoreLength = false): value is string | String {
const isValidHex = value === '0x' || (isString(value) && HEX_REGEX.test(value.toString()));
if (isValidHex && bitLength !== -1) {

View File

@@ -24,12 +24,9 @@ type IpTypes = 'v4' | 'v6';
* ```
*/
export default function isIp (value: string, type?: IpTypes): boolean {
// FIXME @types/ip-regex defintions are outdated
if (type === 'v4') {
// @ts-ignore
return ipRegex.v4({ exact: true }).test(value);
} else if (type === 'v6') {
// @ts-ignore
return ipRegex.v6({ exact: true }).test(value);
}

View File

@@ -44,7 +44,7 @@ describe('isJsonObject', (): void => {
it('returns false on invalid JSON', (): void => {
expect(
isJsonObject(`{"abc", "def"}`)
isJsonObject('{"abc", "def"}')
).toEqual(false);
});
});

View File

@@ -147,7 +147,7 @@ describe('logger', (): void => {
it('does not debug log when no process.env', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
process.env = void 0 as any;
process.env = undefined as any;
l = logger('test');
l.debug('test');

View File

@@ -80,13 +80,10 @@ function apply (log: LogType, type: string, values: Logger$Data): void {
const chalk = (value: string): string =>
chalked[log](value);
// @ts-ignore Not sure how to coax TS here...
console[logTo[log]].apply(
console, [
chalk(moment().format('YYYY-MM-DD HH:mm:ss')), chalk(type)
].concat(
values.map(format)
)
console[logTo[log] as 'log'](
chalk(moment().format('YYYY-MM-DD HH:mm:ss')),
chalk(type),
...values.map(format)
);
}
@@ -117,7 +114,7 @@ export default function logger (_type: string): Logger {
const isTest = process.env.NODE_ENV === 'test';
const debugList = (process.env.DEBUG || '').split(',');
isDebug = isTest || !!debugList.find((entry): boolean => _type.indexOf(entry) === 0);
isDebug = isTest || !!debugList.find((entry): boolean => _type.startsWith(entry));
} catch (error) {
isDebug = false;
}

View File

@@ -21,7 +21,7 @@ import isUndefined from '../is/undefined';
* numberToHex(0x1234, 32); // => 0x00001234
* ```
*/
export default function numberToHex (value?: number | null, bitLength: number = -1): string {
export default function numberToHex (value?: number | null, bitLength = -1): string {
if (isUndefined(value) || isNull(value) || isNaN(value)) {
return '0x';
}

View File

@@ -19,7 +19,7 @@ import numberToHex from './toHex';
* numberToU8a(0x1234); // => [0x12, 0x34]
* ```
*/
export default function numberToU8a (value?: number | null, bitLength: number = -1): Uint8Array {
export default function numberToU8a (value?: number | null, bitLength = -1): Uint8Array {
if (!value || isNaN(value)) {
return new Uint8Array([]);
}

View File

@@ -1,3 +1,6 @@
/* eslint-disable @typescript-eslint/ban-ts-ignore */
/* eslint-disable no-extend-native */
/* eslint-disable @typescript-eslint/unbound-method */
// Copyright 2017-2019 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -12,19 +15,15 @@ describe('Array.fill', (): void => {
u8aFill = Uint8Array.prototype.fill;
// @ts-ignore
// eslint-disable-next-line no-extend-native
Array.prototype.fill = null;
// @ts-ignore
// eslint-disable-next-line no-extend-native
Uint8Array.prototype.fill = null;
require('./fill');
});
afterEach((): void => {
// eslint-disable-next-line no-extend-native
Array.prototype.fill = arrayFill;
// eslint-disable-next-line no-extend-native
Uint8Array.prototype.fill = u8aFill;
});

View File

@@ -1,10 +1,12 @@
/* eslint-disable no-extend-native */
/* eslint-disable @typescript-eslint/unbound-method */
// Copyright 2017-2019 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
if (!Array.prototype.fill) {
// eslint-disable-next-line no-extend-native,@typescript-eslint/no-explicit-any
Array.prototype.fill = function fill (value: any, start: number = 0, end?: number): 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');
@@ -45,7 +47,7 @@ if (!Array.prototype.fill) {
}
if (!Uint8Array.prototype.fill) {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
// eslint-disable-next-line no-extend-native
Uint8Array.prototype.fill = Array.prototype.fill;
}

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/unbound-method */
// Copyright 2017-2019 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

View File

@@ -1,10 +1,11 @@
/* eslint-disable no-extend-native */
/* eslint-disable @typescript-eslint/unbound-method */
// Copyright 2017-2019 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
if (!String.prototype.padEnd) {
// eslint-disable-next-line no-extend-native
String.prototype.padEnd = function padEnd (length: number, char: string = ' '): string {
String.prototype.padEnd = function padEnd (length: number, char = ' '): string {
let result = String(this);
while (result.length < length) {

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/unbound-method */
// Copyright 2017-2019 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

View File

@@ -1,10 +1,11 @@
/* eslint-disable no-extend-native */
/* eslint-disable @typescript-eslint/unbound-method */
// Copyright 2017-2019 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
if (!String.prototype.padStart) {
// eslint-disable-next-line no-extend-native
String.prototype.padStart = function padStart (length: number, char: string = ' '): string {
String.prototype.padStart = function padStart (length: number, char = ' '): string {
let result = String(this);
while (result.length < length) {

View File

@@ -1,3 +1,6 @@
/* eslint-disable no-proto */
/* eslint-disable @typescript-eslint/ban-ts-ignore */
/* eslint-disable @typescript-eslint/unbound-method */
// Copyright 2017-2019 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
@@ -23,7 +26,6 @@ describe('setPrototypeOf', (): void => {
const obj = {};
const proto = { foo: 'bar' };
// eslint-disable-next-line no-proto
expect(Object.setPrototypeOf(obj, proto).__proto__).toBe(proto);
});
});

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/unbound-method */
// Copyright 2017-2019 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.

View File

@@ -19,6 +19,7 @@ describe('TextDecoder', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(global as any).TextDecoder = null;
// eslint-disable-next-line @typescript-eslint/no-var-requires
expect(require('./textDecoder')).toBeDefined();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((global as any).TextDecoder).toBeDefined();
@@ -28,6 +29,7 @@ describe('TextDecoder', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(global as any).TextDecoder = require('util').TextDecoder;
// eslint-disable-next-line @typescript-eslint/no-var-requires
expect(require('./textDecoder')).toBeDefined();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((global as any).TextDecoder).toBeDefined();

View File

@@ -1,11 +1,11 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
// Copyright 2017-2019 @polkadot/util authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
if (typeof TextDecoder === 'undefined') {
try {
// @ts-ignore
global.TextDecoder = require('util').TextDecoder;
(global as any).TextDecoder = require('util').TextDecoder;
} catch (error) {
// noop
}

View File

@@ -19,6 +19,7 @@ describe('TextEncoder', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(global as any).TextEncoder = null;
// eslint-disable-next-line @typescript-eslint/no-var-requires
expect(require('./textEncoder')).toBeDefined();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((global as any).TextEncoder).toBeDefined();
@@ -28,6 +29,7 @@ describe('TextEncoder', (): void => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(global as any).TextEncoder = require('util').TextEncoder;
// eslint-disable-next-line @typescript-eslint/no-var-requires
expect(require('./textEncoder')).toBeDefined();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((global as any).TextEncoder).toBeDefined();

View File

@@ -4,8 +4,8 @@
if (typeof TextEncoder === 'undefined') {
try {
// @ts-ignore For the Node.js case
global.TextEncoder = require('util').TextEncoder;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(global as any).TextEncoder = require('util').TextEncoder;
} catch (error) {
// noop
}

View File

@@ -31,7 +31,6 @@ describe('promisify', (): void => {
const fn = (a: number, b: boolean, cb: (error: Error | null, result?: [number, boolean]) => void): void =>
cb(null, [a, b]);
// @ts-ignore
return promisify(null, fn, 2, false).then((result: [number, boolean]): void => {
expect(result).toEqual([2, false]);
});
@@ -41,19 +40,8 @@ describe('promisify', (): void => {
const fn = (a: number, b: boolean, c: string, cb: (error: Error | null, result?: [number, boolean, string]) => void): void =>
cb(new Error(`test reject: ${a},${b},${c}`));
// @ts-ignore
return promisify(null, fn, 3, 'string', true).catch((error: Error): void => {
expect(error.message).toEqual('test reject: 3,string,true');
});
});
it('applies the correct this argument', (): Promise<void> => {
const self = { something: 'something' };
return promisify(self, function (cb: (error: Error | null) => void): void {
// @ts-ignore
expect(this).toEqual(self);
cb(null);
});
});
});

View File

@@ -4,19 +4,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
// this is horrible, but we want it typed, so... 6 params should be enough for everybody?
export interface PromisifyFn {
(cb: (error: Error | null, result?: any) => any): any;
(a: any, cb: (error: Error | null, result?: any) => any): any;
(a: any, b: any, cb: (error: Error | null, result?: any) => any): any;
(a: any, b: any, c: any, cb: (error: Error | null, result?: any) => any): any;
(a: any, b: any, c: any, d: any, cb: (error: Error | null, result?: any) => any): any;
(a: any, b: any, c: any, d: any, e: any, cb: (error: Error | null, result?: any) => any): any;
(a: any, b: any, c: any, d: any, e: any, f: any, cb: (error: Error | null, result?: any) => any): any;
}
type ParamType = [] | [any] | [any, any] | [any, any, any]| [any, any, any, any]| [any, any, any, any, any]| [any, any, any, any, any, any];
/**
* @name promisify
* @summary Wraps an async callback into a `Promise`
@@ -32,17 +19,16 @@ type ParamType = [] | [any] | [any, any] | [any, any, any]| [any, any, any, any]
* await promisify(null, (cb) => cb(new Error('error!'))); // rejects with `error!`
* ```
*/
export default function promisify (self: any, fn: PromisifyFn, ...params: ParamType): Promise<any> {
export default function promisify (self: any, fn: Function, ...params: any[]): Promise<any> {
return new Promise((resolve, reject): void => {
fn.apply(self, params.concat([
// @ts-ignore
(error: Error | null, result?: any): void => {
if (error) {
reject(error);
} else {
resolve(result);
}
const handler = (error: Error | null, result?: any): void => {
if (error) {
reject(error);
} else {
resolve(result);
}
]));
};
fn.apply(self, [...params, handler]);
});
}

View File

@@ -17,7 +17,7 @@
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function stringShorten (_value?: any, prefixLength: number = 6): string {
export default function stringShorten (_value?: any, prefixLength = 6): string {
const value = `${_value}`;
if (value.length <= 2 + 2 * prefixLength) {

View File

@@ -8,13 +8,6 @@ export interface ToBn {
toBn: () => BN;
}
export interface ExtErrorInterface {
code: number;
data?: string | number;
message: string;
stack: string;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Logger$Data$Fn = () => any[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any

View File

@@ -18,7 +18,7 @@
* u8aFixLength('0x1234', 8) // => 0x12
* ```
*/
export default function u8aFixLength (value: Uint8Array, bitLength: number = -1, atStart: boolean = false): Uint8Array {
export default function u8aFixLength (value: Uint8Array, bitLength = -1, atStart = false): Uint8Array {
const byteLength = Math.ceil(bitLength / 8);
if (bitLength === -1 || value.length === byteLength) {

View File

@@ -21,6 +21,5 @@ export default function u8aToBuffer (value?: Uint8Array | null): Buffer {
return Buffer.from([]);
}
// @ts-ignore yes, from also works with u8a
return Buffer.from(value);
}

View File

@@ -18,7 +18,7 @@ const ALPHABET = '0123456789abcdef';
* u8aToHex(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf])); // 0x68656c0f
* ```
*/
export default function u8aToHex (value?: Uint8Array | null, bitLength: number = -1, isPrefixed: boolean = true): string {
export default function u8aToHex (value?: Uint8Array | null, bitLength = -1, isPrefixed = true): string {
const prefix = isPrefixed
? '0x'
: '';

11
tsconfig.eslint.json Normal file
View File

@@ -0,0 +1,11 @@
{
"extends": "./tsconfig.json",
"exclude": [
"build",
"packages/*/build"
],
"compilerOptions": {
"allowJs": true,
"checkJs": true
}
}

1866
yarn.lock

File diff suppressed because it is too large Load Diff