Compare commits

..
8 Commits
Author SHA1 Message Date
Github Actions 9708131620 [CI Skip] 2.4.1
skip-checks: true
2020-02-18 08:02:01 +00:00
Jaco Greeff c539430a0b 2.4 (#539) 2020-02-18 09:00:08 +01:00
Github Actions 8defc792a9 [CI Skip] 2.4.0-beta.2
skip-checks: true
2020-02-17 15:25:48 +00:00
Jaco Greeff 76a0daeed6 Use ss58 format on keyring for the keyring only (#538)
* Use ss58 format on keyring for the keyring only

* Cleanup args

* Cleanup failures

* Remove deprecated addressPrefix

* Update CHANGELOG
2020-02-17 16:24:03 +01:00
Github Actions e236fdc396 [CI Skip] 2.4.0-beta.1
skip-checks: true
2020-02-17 14:07:53 +00:00
Jaco Greeff e30dd7c0d9 Add GH actions yarn cache (#537) 2020-02-17 15:06:00 +01:00
Github Actions f3ac6b2674 [CI Skip] 2.4.0-beta.0
skip-checks: true
2020-02-17 11:18:01 +00:00
Jaco Greeff 171015fbba formatBalance adjustments (#536)
* formatBalance extensions

* Fly-by any removals

* isBn updates

* Remove unneeded ()'s
2020-02-17 12:16:02 +01:00
21 changed files with 197 additions and 103 deletions
+40
View File
@@ -14,6 +14,16 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Config yarn cache
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: lint
run: |
yarn install --frozen-lockfile
@@ -31,6 +41,16 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Config yarn cache
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: test
env:
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
@@ -50,6 +70,16 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Config yarn cache
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: build
run: |
yarn install --frozen-lockfile
@@ -67,6 +97,16 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Config yarn cache
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: build
run: |
yarn install --frozen-lockfile
+20
View File
@@ -20,6 +20,16 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Config yarn cache
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: build
env:
CC_TEST_REPORTER_ID: ${{ secrets.CC_TEST_REPORTER_ID }}
@@ -44,6 +54,16 @@ jobs:
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Config yarn cache
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- uses: actions/cache@v1
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: build
env:
GH_PAT: ${{ secrets.GH_PAT }}
+8
View File
@@ -1,3 +1,11 @@
# 2.4.1 Feb 18, 2020
- Ensure that `formatBalance` does not apply unit overrides apply when no SI is applicable
- Adjust `formatBalance(<balance>, <options>)` to take expanded `withUnit: string | boolean` option where string is an actual unit, e.g. `KSM`
- The `decimals` option to `formatBalance` should now be passed as part of the `options` (previous last-param deprecated)
- The `.setSS58Format` on keyring will now just operate on pairs created on the keyring, not globally. The global `setSS58Format` in `@polkadot/util-crypto` will be deprecated.
- The deprecated `addressPrefix` option to keyring has been belatedly removed (Use `ss58Format` rather)
# 2.3.1 Feb 15, 2020
- Remove dependency on moment.js with `formatDate` function (Thanks to https://github.com/AndreasGassmann)
+1 -1
View File
@@ -9,5 +9,5 @@
"packages": [
"packages/*"
],
"version": "2.3.1"
"version": "2.4.1"
}
+2 -2
View File
@@ -1,5 +1,5 @@
{
"version": "2.3.1",
"version": "2.4.1",
"private": true,
"engines": {
"yarn": "^1.10.1"
@@ -21,7 +21,7 @@
},
"devDependencies": {
"@babel/core": "^7.8.4",
"@polkadot/dev": "^0.40.16",
"@polkadot/dev": "^0.40.18",
"@polkadot/ts": "^0.2.3"
}
}
+3 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/keyring",
"version": "2.3.1",
"version": "2.4.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.8.4",
"@polkadot/util": "^2.3.1",
"@polkadot/util-crypto": "^2.3.1"
"@polkadot/util": "^2.4.1",
"@polkadot/util-crypto": "^2.4.1"
}
}
+30 -36
View File
@@ -3,7 +3,7 @@
// of the Apache-2.0 license. See the LICENSE file for details.
import { hexToU8a, stringToU8a } from '@polkadot/util';
import { cryptoWaitReady, setSS58Format } from '@polkadot/util-crypto';
import { cryptoWaitReady, setSS58Format, encodeAddress } from '@polkadot/util-crypto';
import Keyring from '.';
@@ -17,57 +17,55 @@ describe('keypair', (): void => {
const publicKeyTwo = new Uint8Array([215, 90, 152, 1, 130, 177, 10, 183, 213, 75, 254, 211, 201, 100, 7, 58, 14, 225, 114, 243, 218, 166, 35, 37, 175, 2, 26, 104, 247, 7, 81, 26]);
const seedOne = stringToU8a('12345678901234567890123456789012');
const seedTwo = hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60');
let keypair: Keyring;
let keyring: Keyring;
beforeEach((): void => {
keypair = new Keyring({ type: 'ed25519' });
keyring = new Keyring({ ss58Format: 42, type: 'ed25519' });
keypair.addFromSeed(seedOne, {});
});
afterEach((): void => {
setSS58Format(42);
keyring.addFromSeed(seedOne, {});
});
it('adds the pair', (): void => {
expect(
keypair.addFromSeed(seedTwo, {}).publicKey
keyring.addFromSeed(seedTwo, {}).publicKey
).toEqual(publicKeyTwo);
});
it('creates a ed25519 pair via mnemonicToSeed', (): void => {
expect(
keypair.addFromUri(
keyring.addFromUri(
'seed sock milk update focus rotate barely fade car face mechanic mercy'
).address
).toEqual('5DkQP32jP4DVJLWWBRBoZF2tpWjqFrcrTBo6H5NcSk7MxKCC');
});
it('adds from a mnemonic', (): void => {
setSS58Format(68);
it('adds from a mnemonic, with correct ss58', (): void => {
setSS58Format(20); // this would not be used
keyring.setSS58Format(68); // this would be used
expect(
keypair.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address
).toEqual('7sPsxWPE5DzAyPT3VuoJYw5NTGscx9QYN9oddQx4kALKC3hH');
const pair = keyring.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {});
expect(pair.address).toEqual('7sPsxWPE5DzAyPT3VuoJYw5NTGscx9QYN9oddQx4kALKC3hH');
expect(encodeAddress(pair.publicKey)).toEqual('35cDYtPsdG1HUa2n2MaARgJyRz1WKMBZK1DL6c5cX7nugQh1');
});
it('allows publicKeys retrieval', (): void => {
keypair.addFromSeed(seedTwo, {});
keyring.addFromSeed(seedTwo, {});
expect(
keypair.getPublicKeys()
keyring.getPublicKeys()
).toEqual([publicKeyOne, publicKeyTwo]);
});
it('allows retrieval of a specific item', (): void => {
expect(
keypair.getPair(publicKeyOne).publicKey
keyring.getPair(publicKeyOne).publicKey
).toEqual(publicKeyOne);
});
it('allows adding from JSON', (): void => {
expect(
keypair.addFromJson(
keyring.addFromJson(
JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}')
).publicKey
).toEqual(
@@ -77,7 +75,7 @@ describe('keypair', (): void => {
it('signs and verifies', (): void => {
const MESSAGE = stringToU8a('this is a message');
const pair = keypair.getPair(publicKeyOne);
const pair = keyring.getPair(publicKeyOne);
const signature = pair.sign(MESSAGE);
expect(pair.verify(MESSAGE, signature)).toBe(true);
@@ -89,55 +87,51 @@ describe('keypair', (): void => {
const publicKeyTwo = hexToU8a('0x44a996beb1eef7bdcab976ab6d2ca26104834164ecf28fb375600576fcc6eb0f');
const seedOne = stringToU8a('12345678901234567890123456789012');
const seedTwo = hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60');
let keypair: Keyring;
let keyring: Keyring;
beforeEach((): void => {
keypair = new Keyring({ type: 'sr25519' });
keyring = new Keyring({ ss58Format: 42, type: 'sr25519' });
keypair.addFromSeed(seedOne, {});
});
afterEach((): void => {
setSS58Format(42);
keyring.addFromSeed(seedOne, {});
});
it('creates with dev phrase when only path specified', (): void => {
expect(
keypair.createFromUri('//Alice').address
keyring.createFromUri('//Alice').address
).toEqual('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY');
});
it('adds the pair', (): void => {
expect(
keypair.addFromSeed(seedTwo, {}).publicKey
keyring.addFromSeed(seedTwo, {}).publicKey
).toEqual(publicKeyTwo);
});
it('adds from a mnemonic', (): void => {
setSS58Format(68);
keyring.setSS58Format(68);
expect(
keypair.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address
keyring.addFromMnemonic('moral movie very draw assault whisper awful rebuild speed purity repeat card', {}).address
).toEqual('7qQGarA4PWjPPVHG4USn1yuuVZvEHN7XZz8o7EbAp48jayZQ');
});
it('allows publicKeys retrieval', (): void => {
keypair.addFromSeed(seedTwo, {});
keyring.addFromSeed(seedTwo, {});
expect(
keypair.getPublicKeys()
keyring.getPublicKeys()
).toEqual([publicKeyOne, publicKeyTwo]);
});
it('allows retrieval of a specific item', (): void => {
expect(
keypair.getPair(publicKeyOne).publicKey
keyring.getPair(publicKeyOne).publicKey
).toEqual(publicKeyOne);
});
it('allows adding from JSON', (): void => {
expect(
keypair.addFromJson(
keyring.addFromJson(
JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}')
).publicKey
).toEqual(
@@ -147,7 +141,7 @@ describe('keypair', (): void => {
it('signs and verifies', (): void => {
const MESSAGE = stringToU8a('this is a message');
const pair = keypair.getPair(publicKeyOne);
const pair = keyring.getPair(publicKeyOne);
const signature = pair.sign(MESSAGE);
expect(pair.verify(MESSAGE, signature)).toBe(true);
+2 -7
View File
@@ -7,13 +7,8 @@ import { decodeAddress, encodeAddress, setSS58Format } from '@polkadot/util-cryp
import Keyring from './keyring';
// eslint-disable-next-line no-useless-catch
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
detectPackage(require('./package.json'), __dirname);
} catch (error) {
throw error;
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
detectPackage(require('./package.json'), __dirname);
export default Keyring;
+25 -17
View File
@@ -5,8 +5,8 @@
import { KeypairType } from '@polkadot/util-crypto/types';
import { KeyringInstance, KeyringPair, KeyringPair$Json, KeyringPair$Meta, KeyringOptions } from './types';
import { assert, hexToU8a, isNumber, isHex, stringToU8a } from '@polkadot/util';
import { decodeAddress, encodeAddress, keyExtractSuri, keyFromPath, naclKeypairFromSeed as naclFromSeed, schnorrkelKeypairFromSeed as schnorrkelFromSeed, mnemonicToMiniSecret, setSS58Format } from '@polkadot/util-crypto';
import { assert, hexToU8a, isHex, stringToU8a } from '@polkadot/util';
import { decodeAddress, encodeAddress, keyExtractSuri, keyFromPath, naclKeypairFromSeed as naclFromSeed, schnorrkelKeypairFromSeed as schnorrkelFromSeed, mnemonicToMiniSecret } from '@polkadot/util-crypto';
import { DEV_PHRASE } from './defaults';
import createPair from './pair';
@@ -31,28 +31,20 @@ import Pairs from './pairs';
export default class Keyring implements KeyringInstance {
private _pairs: Pairs;
private _ss58?: number;
private _type: KeypairType;
public decodeAddress = decodeAddress;
public encodeAddress = encodeAddress;
public setSS58Format = setSS58Format;
constructor (options: KeyringOptions = {}) {
options.type = options.type || 'ed25519';
options.ss58Format = isNumber(options.ss58Format)
? options.addressPrefix
: options.ss58Format;
assert(options && ['ed25519', 'sr25519'].includes(options.type || 'undefined'), `Expected a keyring type of either 'ed25519' or 'sr25519', found '${options.type}`);
this._pairs = new Pairs();
this._ss58 = options.ss58Format;
this._type = options.type;
if (isNumber(options.ss58Format)) {
setSS58Format(options.ss58Format);
}
}
/**
@@ -95,7 +87,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, secretKey: new Uint8Array(64) }, meta, encoded));
return this.addPair(createPair({ toSS58: this.encodeAddress, type }, { publicKey, secretKey: new Uint8Array(64) }, meta, encoded));
}
/**
@@ -137,7 +129,7 @@ export default class Keyring implements KeyringInstance {
? schnorrkelFromSeed(seed)
: naclFromSeed(seed);
return this.addPair(createPair(type, keypair, meta, null));
return this.addPair(createPair({ toSS58: this.encodeAddress, type }, keypair, meta, null));
}
/**
@@ -153,7 +145,7 @@ export default class Keyring implements KeyringInstance {
/**
* @name createFromUri
* @summry Creates a Keypair from an suri
* @summary Creates a Keypair from an suri
* @description This creates a pair from the suri, but does not add it to the keyring
*/
public createFromUri (_suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair {
@@ -188,7 +180,15 @@ export default class Keyring implements KeyringInstance {
: naclFromSeed(seed);
const derived = keyFromPath(keypair, path, type);
return createPair(type, derived, meta, null);
return createPair({ toSS58: this.encodeAddress, type }, derived, meta, null);
}
/**
* @name encodeAddress
* @description Encodes the input into an ss58 representation
*/
public encodeAddress = (key: Uint8Array | string, ss58Format?: number): string => {
return encodeAddress(key, ss58Format || this._ss58);
}
/**
@@ -231,6 +231,14 @@ export default class Keyring implements KeyringInstance {
this._pairs.remove(address);
}
/**
* @name setSS58Format;
* @description Sets the ss58 format for the keyring
*/
public setSS58Format (ss58: number): void {
this._ss58 = ss58;
}
/**
* @name toJson
* @summary Returns a JSON object associated with the input argument that contains metadata assocated with an account
+3 -3
View File
@@ -2,7 +2,7 @@
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
import { cryptoWaitReady, setSS58Format } from '@polkadot/util-crypto';
import { cryptoWaitReady, encodeAddress as toSS58, setSS58Format } from '@polkadot/util-crypto';
import { PAIRS } from '../testing';
import testingPairs from '../testingPairs';
@@ -79,14 +79,14 @@ describe('pair', (): void => {
const PASS = 'testing';
const encoded = keyring.alice.encodePkcs8(PASS);
const pair = createPair('sr25519', { publicKey: keyring.alice.publicKey });
const pair = createPair({ toSS58, type: 'sr25519' }, { publicKey: keyring.alice.publicKey });
pair.decodePkcs8(PASS, encoded);
expect(pair.isLocked).toEqual(false);
});
it('allows derivation on the pair', (): void => {
const alice = createPair('sr25519', { publicKey: PAIRS[0].publicKey, secretKey: PAIRS[0].secretKey }, {});
const alice = createPair({ toSS58, type: 'sr25519' }, { publicKey: PAIRS[0].publicKey, secretKey: PAIRS[0].secretKey }, {});
const stash = alice.derive('//stash');
const soft = alice.derive('//funding/0');
+9 -4
View File
@@ -7,12 +7,17 @@ import { KeyringPair, KeyringPair$Json, KeyringPair$Meta, SignOptions } from '..
import { PairInfo } from './types';
import { u8aConcat, assert } from '@polkadot/util';
import { encodeAddress, keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, naclVerify, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVerify } from '@polkadot/util-crypto';
import { keyExtractPath, keyFromPath, naclKeypairFromSeed as naclFromSeed, naclSign, naclVerify, schnorrkelKeypairFromSeed as schnorrkelFromSeed, schnorrkelSign, schnorrkelVerify } from '@polkadot/util-crypto';
import decode from './decode';
import encode from './encode';
import toJson from './toJson';
interface Setup {
toSS58: (publicKey: Uint8Array) => string;
type: KeypairType;
}
const SIG_TYPE_NONE = new Uint8Array();
const SIG_TYPE_ED25519 = new Uint8Array([0]);
const SIG_TYPE_SR25519 = new Uint8Array([1]);
@@ -88,10 +93,10 @@ function verify (type: KeypairType, message: Uint8Array, signature: Uint8Array,
* an `encoded` property that is assigned with the encoded public key in hex format, and an `encoding`
* property that indicates whether the public key value of the `encoded` property is encoded or not.
*/
export default function createPair (type: KeypairType, { publicKey, secretKey }: PairInfo, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null): KeyringPair {
export default function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: PairInfo, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null): KeyringPair {
return {
get address (): string {
return encodeAddress(publicKey);
return toSS58(publicKey);
},
get meta (): KeyringPair$Meta {
return meta;
@@ -124,7 +129,7 @@ export default function createPair (type: KeypairType, { publicKey, secretKey }:
const { path } = keyExtractPath(suri);
const derived = keyFromPath({ publicKey, secretKey: secretKey }, path, type);
return createPair(type, derived, meta, null);
return createPair({ toSS58, type }, derived, meta, null);
},
encodePkcs8: (passphrase?: string): Uint8Array =>
encode({ publicKey, secretKey }, passphrase),
+2 -2
View File
@@ -73,7 +73,7 @@ export const PAIRS: PairDef[] = [
export default function testKeyring (options: KeyringOptions = {}, isDerived = true): KeyringInstance {
const keyring = new Keyring(options);
PAIRS.forEach(({ name, publicKey, secretKey, seed, type }): void => {
PAIRS.forEach(({ name, publicKey, secretKey, seed, type = 'sr25519' }): void => {
const meta = {
isTesting: true,
name: name || seed.replace('//', '_').toLowerCase()
@@ -82,7 +82,7 @@ export default function testKeyring (options: KeyringOptions = {}, isDerived = t
const pair = !isDerived && !name
? keyring.addFromUri(seed, meta, options.type)
: keyring.addPair(
createPair(type || 'sr25519', { publicKey, secretKey }, meta)
createPair({ toSS58: keyring.encodeAddress, type }, { publicKey, secretKey }, meta)
);
pair.lock = (): void => {
-2
View File
@@ -7,8 +7,6 @@ import { Prefix } from '@polkadot/util-crypto/address/types';
import { KeypairType } from '@polkadot/util-crypto/types';
export interface KeyringOptions {
// @deprecated
addressPrefix?: Prefix;
ss58Format?: Prefix;
type?: KeypairType;
}
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util-crypto",
"version": "2.3.1",
"version": "2.4.1",
"description": "A collection of useful crypto utilities for @polkadot",
"main": "index.js",
"keywords": [
@@ -26,7 +26,7 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util-crypto#readme",
"dependencies": {
"@babel/runtime": "^7.8.4",
"@polkadot/util": "^2.3.1",
"@polkadot/util": "^2.4.1",
"@polkadot/wasm-crypto": "^1.0.1",
"base-x": "^3.0.7",
"bip39": "^3.0.2",
@@ -40,6 +40,7 @@
"xxhashjs": "^0.2.2"
},
"devDependencies": {
"@types/bn.js": "^4.11.6",
"@types/bs58": "^4.0.0",
"@types/elliptic": "^6.4.12",
"@types/pbkdf2": "^3.0.0",
@@ -6,6 +6,10 @@ import { Prefix } from './types';
import defaults from './defaults';
/**
* @description Sets the global SS58 format to use for address encoding
* @deprecated Use keyring.setSS58Format
*/
export default function setSS58Format (prefix: Prefix): void {
defaults.prefix = prefix;
}
+2 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@polkadot/util",
"version": "2.3.1",
"version": "2.4.1",
"description": "A collection of useful utilities for @polkadot",
"main": "index.js",
"keywords": [
@@ -26,12 +26,10 @@
"homepage": "https://github.com/polkadot-js/common/tree/master/packages/util#readme",
"dependencies": {
"@babel/runtime": "^7.8.4",
"@types/bn.js": "^4.11.6",
"bn.js": "^5.1.1",
"camelcase": "^5.3.1",
"chalk": "^3.0.0",
"ip-regex": "^4.1.0"
},
"devDependencies": {
"@types/bn.js": "^4.11.6"
}
}
+1 -2
View File
@@ -22,8 +22,7 @@ type MessageFn = () => string;
* assert(false, () => 'message'); // Error with 'message'
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function assert (condition: any, message: string | MessageFn): asserts condition {
export default function assert (condition: boolean | object | string | number | undefined | null, message: string | MessageFn): asserts condition {
if (!condition) {
throw new Error(
isFunction(message)
+28 -4
View File
@@ -16,14 +16,20 @@ describe('formatBalance', (): void => {
});
it('formats 123,456,789,000 (decimals=15)', (): void => {
expect(
formatBalance(TESTVAL, { withSi: true, decimals: 15 })
).toEqual('123.456µ Unit');
});
it('formats 123,456,789,000 (decimals=15, old style)', (): void => {
expect(
formatBalance(TESTVAL, { withSi: true }, 15)
).toEqual('123.456µ Unit');
});
it('formats 123,456,789,000 (decimals=36)', (): void => {
it('formats 123,456,789,000 (decimals=36, option)', (): void => {
expect(
formatBalance(TESTVAL, { withSi: true }, 36)
formatBalance(TESTVAL, { withSi: true, decimals: 36 })
).toEqual('0.123y Unit');
});
@@ -34,13 +40,13 @@ describe('formatBalance', (): void => {
something: 'else'
};
expect(
formatBalance(compact, { withSi: true }, 15)
formatBalance(compact, { withSi: true, decimals: 15 })
).toEqual('123.456µ Unit');
});
it('formats 123,456,789,000 (decimals=12)', (): void => {
expect(
formatBalance(TESTVAL, { withSi: true }, 12)
formatBalance(TESTVAL, { withSi: true, decimals: 12 })
).toEqual('123.456m Unit');
});
@@ -50,6 +56,18 @@ describe('formatBalance', (): void => {
).toEqual('123.456 Unit');
});
it('formats 123,456,789,000 (decimals=9, no unit)', (): void => {
expect(
formatBalance(TESTVAL, { withSi: true, withUnit: false }, 9)
).toEqual('123.456');
});
it('formats 123,456,789,000 (decimals=9, unit given)', (): void => {
expect(
formatBalance(TESTVAL, { withSi: true, withUnit: 'FOO' }, 9)
).toEqual('123.456 FOO');
});
it('formats 123,456,789,000 (decimals=12, no SI)', (): void => {
expect(
formatBalance(TESTVAL, { withSi: false }, 12)
@@ -80,6 +98,12 @@ describe('formatBalance', (): void => {
).toEqual('123.456k Unit');
});
it('formats 123,456,789,000 (decimals=6, unit specified)', (): void => {
expect(
formatBalance(TESTVAL, { withSi: true, withUnit: 'BAR' }, 6)
).toEqual('123.456k BAR');
});
it('formats 123,456,789,000 * 10 (decimals=12)', (): void => {
expect(
formatBalance(TESTVAL.muln(10), { withSi: true }, 12)
+9 -8
View File
@@ -18,10 +18,11 @@ interface Defaults {
}
interface Options {
decimals?: number;
forceUnit?: string;
withSi?: boolean;
withSiFull?: boolean;
withUnit?: boolean;
withUnit?: boolean | string;
}
interface BalanceFormatter {
@@ -40,7 +41,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, options: Options | boolean = true, decimals: number = defaultDecimals): string {
function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | ExtToBn, options: Options | boolean = true, optDecimals: number = defaultDecimals): string {
let text = bnToBn(input).toString();
if (text.length === 0 || text === '0') {
@@ -56,7 +57,7 @@ function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | E
}
// extract options - the boolean case is for backwards-compat
const { forceUnit = undefined, withSi = true, withSiFull = false, withUnit = true } = isBoolean(options)
const { decimals = optDecimals, forceUnit = undefined, withSi = true, withSiFull = false, withUnit = true } = isBoolean(options)
? { withSi: options }
: options;
@@ -69,11 +70,11 @@ function _formatBalance <ExtToBn extends ToBn> (input?: number | string | BN | E
const padding = mid < 0 ? 0 - mid : 0;
const postfix = `${`${new Array(padding + 1).join('0')}${text}`.substr(mid < 0 ? 0 : mid)}000`.substr(0, 3);
const units = withSi || withSiFull
? (
si.value === '-'
? ` ${si.text}`
: `${withSiFull ? ` ${si.text}` : si.value}${withUnit ? ` ${SI[SI_MID].text}` : ''}`
)
? si.value === '-'
? withUnit
? ` ${isBoolean(withUnit) ? si.text : withUnit}`
: ''
: `${withSiFull ? ` ${si.text}` : si.value}${withUnit ? ` ${isBoolean(withUnit) ? SI[SI_MID].text : withUnit}` : ''}`
: '';
return `${isNegative ? '-' : ''}${formatDecimal(prefix || '0')}.${postfix}${units}`;
+1 -2
View File
@@ -19,7 +19,6 @@ import BN from 'bn.js';
* console.log('isBn', isBn(new BN(1))); // => true
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export default function isBn (value: any): value is BN {
export default function isBn (value: object | string | number | undefined | null): value is BN {
return BN.isBN(value);
}
+4 -4
View File
@@ -2016,10 +2016,10 @@
dependencies:
"@types/node" ">= 8"
"@polkadot/dev@^0.40.16":
version "0.40.16"
resolved "https://registry.yarnpkg.com/@polkadot/dev/-/dev-0.40.16.tgz#45dc5ec8f791e38bed0fb4f9d8fde2a0854e488a"
integrity sha512-/vlk7E8TwnmAlLfwNE/7ePMuqSgapPcheWxnH7L+6hXNWKaAVAphjNEDq89D4DpHECxuL9pQvlwGTFM1r8/qkw==
"@polkadot/dev@^0.40.18":
version "0.40.18"
resolved "https://registry.yarnpkg.com/@polkadot/dev/-/dev-0.40.18.tgz#6ca40304bcc7c75b26c0190d60cb5b892a512dc5"
integrity sha512-SEkmrdZPYcnFzXnfpIjnvNfrwdBS3uAenEt8ZYBMkay59+XgFnPKi7xKV92x5iGYEiAXfcKFYjCAN0Nk2rXV5Q==
dependencies:
"@babel/cli" "^7.8.4"
"@babel/core" "^7.8.4"