Compare commits

..
54 Commits
Author SHA1 Message Date
github-actions[bot] 62182bae03 [CI Skip] release/stable 12.4.2
skip-checks: true
2023-08-23 09:55:33 +00:00
Jaco 2ee03a5f81 12.4.2 (#1872) 2023-08-23 12:48:09 +03:00
github-actions[bot] 7a5a88a135 [CI Skip] bump/beta 12.4.2-5-x
skip-checks: true
2023-08-23 09:09:55 +00:00
Jaco f4e0e2111f Extend u8aToBuffer check with hasBuffer (#1871)
* Extend u8aToBuffer check with hasBuffer

* CHANGELOG

* Always return Uint8Array

* New instance of fallback
2023-08-23 12:01:59 +03:00
github-actions[bot] aac902011e [CI Skip] bump/beta 12.4.2-4-x
skip-checks: true
2023-08-23 08:29:44 +00:00
Jaco a030330808 Additional test cleanups (#1870)
* Additional test cleanups

* More compact test loops

* Correct float expected values

* Adjust
2023-08-23 11:23:45 +03:00
github-actions[bot] d108beafd4 [CI Skip] bump/beta 12.4.2-3-x
skip-checks: true
2023-08-23 06:21:04 +00:00
Jaco 90e20ed4d2 Some small test loop cleanups (#1869) 2023-08-23 09:14:55 +03:00
github-actions[bot] 723ec10fa1 [CI Skip] bump/beta 12.4.2-2-x
skip-checks: true
2023-08-22 17:56:58 +00:00
Jaco cf9082e03a Adjust BE u8aTo{Bn, BigInt, Number} check (#1868)
* Adjust BE u8aTo{Bn, BigInt, Numer} check

* Adjust function names (liberal find-and-replace)
2023-08-22 20:50:50 +03:00
github-actions[bot] 3dce4fe04a [CI Skip] bump/beta 12.4.2-1-x
skip-checks: true
2023-08-22 17:16:39 +00:00
Jaco 55ebc4f0d9 Check sign flag for i{8, 16, 32, ...} conversions (#1867)
* Check sign flag for i{8, 16, 32, ...} conversions

* Ensure negative path is tested on i32 perf

* CHANGELOG

* Comment check on top-most signed bit

* toBn test array

* toNumber uses exposed toBn tests

* Re-use tests in toBn

* Re-use expectations inside bnToU8a

* Remove explicit BE (swap to non-optimal reverse)

* Adjust

* Remove defunct "only BE" comment

* typo

* Use bnToU8a tests in biToU8a

* Flatten tests

* Additional tests

* Additional tests
2023-08-22 20:08:30 +03:00
github-actions[bot] ce2122e9fa [CI Skip] bump/beta 12.4.2-0-x
skip-checks: true
2023-08-20 06:55:29 +00:00
Jaco 0fb55fe633 Bump deps (#1865) 2023-08-20 09:49:19 +03:00
github-actions[bot] adca13bc8c [CI Skip] release/stable 12.4.1
skip-checks: true
2023-08-17 12:30:06 +00:00
Jaco b939c3593c 12.4.1 (#1864) 2023-08-17 15:21:30 +03:00
github-actions[bot] aa70b81a89 [CI Skip] bump/beta 12.3.3-12-x
skip-checks: true
2023-08-17 09:04:14 +00:00
Jaco f3e1d6beda Bump deps (#1863)
* Bump deps

* Adjust Buffer* types
2023-08-17 11:56:46 +03:00
github-actions[bot] 754bc4dc21 [CI Skip] bump/beta 12.3.3-11-x
skip-checks: true
2023-08-16 09:28:29 +00:00
Jaco a8df82dfe0 Update internal buffer types (#1862)
* Update internal buffer types

* u8aToBuffer/isBuffer does not require Buffer type

* Re-add BufferObj equals
2023-08-16 12:22:18 +03:00
github-actions[bot] 4ff56f5cfe [CI Skip] bump/beta 12.3.3-10-x
skip-checks: true
2023-08-16 08:18:29 +00:00
Jaco 1fd9f04458 Bump dev (#1861)
* Bump dev

* Adjust linting
2023-08-16 11:12:06 +03:00
github-actions[bot] a28306f487 [CI Skip] bump/beta 12.3.3-9-x
skip-checks: true
2023-08-16 06:23:08 +00:00
Jaco 19941bcb61 Bump deps (#1860) 2023-08-16 09:16:49 +03:00
github-actions[bot] 2cb85866ab [CI Skip] bump/beta 12.3.3-8-x
skip-checks: true
2023-08-01 13:10:02 +00:00
Jaco 8556de1fa2 Bump dev deps (#1859) 2023-08-01 16:02:08 +03:00
github-actions[bot] 143d070d21 [CI Skip] bump/beta 12.3.3-7-x
skip-checks: true
2023-07-27 11:13:56 +00:00
Jaco 2a53b1121e Bump deps (#1857) 2023-07-27 14:06:32 +03:00
github-actions[bot] 0733137f79 [CI Skip] bump/beta 12.3.3-6-x
skip-checks: true
2023-07-21 06:45:20 +00:00
Jaco cc918660cb Bump deps (#1856) 2023-07-21 09:38:52 +03:00
github-actions[bot] 3527f8c7d9 [CI Skip] bump/beta 12.3.3-5-x
skip-checks: true
2023-07-15 07:04:24 +00:00
Jaco 41caf2fd6d Bump dev (w/ ts-eslint updates) (#1854)
* Bump dev (w/ ts-eslint updates)

* Adjust ipfs compat check
2023-07-15 09:57:35 +03:00
github-actions[bot] d407513dd1 [CI Skip] bump/beta 12.3.3-4-x
skip-checks: true
2023-07-06 07:35:28 +00:00
Jaco bd76349552 Bump deps (#1853)
* Bump deps

* Rebuild networks test
2023-07-06 10:29:31 +03:00
github-actions[bot] 0ec894b732 [CI Skip] bump/beta 12.3.3-3-x
skip-checks: true
2023-06-27 08:42:17 +00:00
Jaco be4cb52dd3 Bump deps (#1851)
* Bump deps

* Update
2023-06-27 11:36:14 +03:00
github-actions[bot] 456eaeeb94 [CI Skip] bump/beta 12.3.3-2-x
skip-checks: true
2023-06-21 06:22:14 +00:00
Jaco 0ec50b6159 Support for signRaw on Ledger SubstrateApp (#1849)
* Support for signRaw on Ledger SubstrateApp

* Adjust with callback return

* Ensure message is wrapped before signing
2023-06-21 09:15:10 +03:00
github-actions[bot] 98336fd2e5 [CI Skip] bump/beta 12.3.3-1-x
skip-checks: true
2023-06-21 05:30:22 +00:00
Jaco 7b3bbd3ef2 Bump deps (#1850) 2023-06-21 08:24:21 +03:00
github-actions[bot] 49afd1fe09 [CI Skip] bump/beta 12.3.3-0-x
skip-checks: true
2023-06-16 06:42:19 +00:00
Jaco 0df17104d5 Use import.meta.url instead of process.cwd() (#1847) 2023-06-16 09:35:40 +03:00
github-actions[bot] db8434559e [CI Skip] release/stable 12.3.2
skip-checks: true
2023-06-12 05:27:44 +00:00
Jaco eaf9d97ae3 12.3.2 (#1846) 2023-06-12 08:20:17 +03:00
github-actions[bot] 3e6d86b768 [CI Skip] release/stable 12.3.1
skip-checks: true
2023-06-11 06:26:55 +00:00
Jaco 8aab41648e 12.3.1 (#1845) 2023-06-11 09:20:32 +03:00
github-actions[bot] 4a535c08c7 [CI Skip] bump/beta 12.2.3-3-x
skip-checks: true
2023-06-10 08:09:54 +00:00
Jaco 715486d54e Additional adjustments to keyring types (#1844) 2023-06-10 11:01:23 +03:00
github-actions[bot] 1073dc14aa [CI Skip] bump/beta 12.2.3-2-x
skip-checks: true
2023-06-10 04:50:38 +00:00
Jaco 5cca95e855 Adjust object index typings (#1843)
* Adjust object index typings

* Update packages/util/src/is/childClass.ts

* Expand meta definition

* Extend meta with extension info

* Adjust

* CHANGELOG
2023-06-10 07:44:28 +03:00
github-actions[bot] 942b623273 [CI Skip] bump/beta 12.2.3-1-x
skip-checks: true
2023-06-06 05:37:49 +00:00
Jaco eea99656ad Only allow padding characters in base64 strings (#1842)
* Only allow padding characters in base64 strings

* Explicit padding sequence error
2023-06-06 08:31:44 +03:00
github-actions[bot] 04b6df9ac5 [CI Skip] bump/beta 12.2.3-0-x
skip-checks: true
2023-06-05 18:29:35 +00:00
Carlo Sala d5132b56de feat(networks): add zeitgeist Ledger support (#1840)
* feat(networks): add zeitgeist Ledger support

* fix(networks): update test
2023-06-05 21:23:31 +03:00
138 changed files with 2009 additions and 2178 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2023 @polkadot/dev authors & contributors
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
module.exports = require('@polkadot/dev/config/prettier.cjs');
+37
View File
@@ -1,5 +1,42 @@
# CHANGELOG
## 12.4.2 Aug 23, 2023
Changes:
- Fix `u8aTo{BigInt, Bn, Number}` for non-negative `i{8, 16, 32...}` inputs
- Extend `u8aToBuffer` with `hasBuffer` check
- Adjust util tests (extract input/output arrays)
## 12.4.1 Aug 17, 2023
Changes:
- Add support for Ledger `signRaw`, as exposed by lower-level
- Update code to use `?.` shortcuts where appropriate
- Adjust `u8aToBuffer` & `isBuffer` typings to not require `Buffer`
- Use `stringify/import.meta.url` helpers in specs
- Upgrade dependencies to latest stable versions
## 12.3.2 Jun 12, 2023
Changes:
- Adjust `SubstrateNetwork` typing with `HexString` genesisHash
- Re-export `Constructor<T>` type (deprecated, replaced with `Class<T>`)
## 12.3.1 Jun 11, 2023
Changes:
- Only allow padding characters in base64 strings
- Expand typings for keyring meta with known keys
- Adjust object index access for stricter tsconfig settings
## 12.2.2 Jun 4, 2023
Changes:
+2 -2
View File
@@ -1,5 +1,5 @@
1622 Jaco 12.2.2 (#1839)
12 Carlo Sala feat(networks): support ledger for pendulum (#1739)
1648 Jaco 12.4.2 (#1872)
13 Carlo Sala feat(networks): add zeitgeist Ledger support (#1840)
9 Antoine Estienne Add eth uri keyring test (#1291)
6 Amaury Martiny Add tests from Rust (#283)
5 Jakub Pánik Add HydraDX parachain to genesis (#1583)
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2017-2023 @polkadot/dev authors & contributors
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import baseConfig from '@polkadot/dev/config/eslint';
+6 -6
View File
@@ -14,10 +14,10 @@
},
"sideEffects": false,
"type": "module",
"version": "12.2.2",
"version": "12.4.2",
"versions": {
"git": "12.2.2",
"npm": "12.2.2"
"git": "12.4.2",
"npm": "12.4.2"
},
"workspaces": [
"packages/*"
@@ -37,10 +37,10 @@
"test:one": "polkadot-dev-run-test --env browser"
},
"devDependencies": {
"@polkadot/dev": "^0.75.16",
"@types/node": "^20.2.5"
"@polkadot/dev": "^0.76.18",
"@types/node": "^20.5.3"
},
"resolutions": {
"typescript": "^5.1.3"
"typescript": "^5.1.6"
}
}
+7 -7
View File
@@ -14,18 +14,18 @@
},
"sideEffects": false,
"type": "module",
"version": "12.2.2",
"version": "12.4.2",
"browser": "browser.js",
"main": "node.js",
"react-native": "react-native.js",
"dependencies": {
"@ledgerhq/hw-transport": "^6.28.4",
"@ledgerhq/hw-transport-webhid": "^6.27.15",
"@ledgerhq/hw-transport-webusb": "^6.27.15",
"@polkadot/util": "12.2.2",
"tslib": "^2.5.3"
"@ledgerhq/hw-transport": "^6.28.8",
"@ledgerhq/hw-transport-webhid": "^6.27.19",
"@ledgerhq/hw-transport-webusb": "^6.27.19",
"@polkadot/util": "12.4.2",
"tslib": "^2.6.2"
},
"optionalDependencies": {
"@ledgerhq/hw-transport-node-hid-singleton": "^6.28.12"
"@ledgerhq/hw-transport-node-hid-singleton": "^6.28.18"
}
}
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/hw-ledger-transports', path: 'auto', type: 'auto', version: '12.2.2' };
export const packageInfo = { name: '@polkadot/hw-ledger-transports', path: 'auto', type: 'auto', version: '12.4.2' };
+5 -5
View File
@@ -17,12 +17,12 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "12.2.2",
"version": "12.4.2",
"main": "index.js",
"dependencies": {
"@polkadot/hw-ledger-transports": "12.2.2",
"@polkadot/util": "12.2.2",
"@zondax/ledger-substrate": "^0.40.7",
"tslib": "^2.5.3"
"@polkadot/hw-ledger-transports": "12.4.2",
"@polkadot/util": "12.4.2",
"@zondax/ledger-substrate": "^0.41.1",
"tslib": "^2.6.2"
}
}
+20 -9
View File
@@ -8,7 +8,7 @@ import type { AccountOptions, LedgerAddress, LedgerSignature, LedgerVersion } fr
import { newSubstrateApp } from '@zondax/ledger-substrate';
import { transports } from '@polkadot/hw-ledger-transports';
import { hexAddPrefix, u8aToBuffer } from '@polkadot/util';
import { hexAddPrefix, u8aToBuffer, u8aWrapBytes } from '@polkadot/util';
import { LEDGER_DEFAULT_ACCOUNT, LEDGER_DEFAULT_CHANGE, LEDGER_DEFAULT_INDEX, LEDGER_SUCCESS_CODE } from './constants.js';
import { ledgerApps } from './defaults.js';
@@ -30,6 +30,17 @@ async function wrapError <T extends WrappedResult> (promise: Promise<T>): Promis
return result;
}
/** @internal Wraps a sign/signRaw call and returns the associated signature */
function sign (method: 'sign' | 'signRaw', message: Uint8Array, accountOffset = 0, addressOffset = 0, { account = LEDGER_DEFAULT_ACCOUNT, addressIndex = LEDGER_DEFAULT_INDEX, change = LEDGER_DEFAULT_CHANGE }: Partial<AccountOptions> = {}): (app: SubstrateApp) => Promise<LedgerSignature> {
return async (app: SubstrateApp): Promise<LedgerSignature> => {
const { signature } = await wrapError(app[method](account + accountOffset, change, addressIndex + addressOffset, u8aToBuffer(message)));
return {
signature: hexAddPrefix(signature.toString('hex'))
};
};
}
/**
* @name Ledger
*
@@ -91,15 +102,15 @@ export class Ledger {
/**
* Signs a transaction on the Ledger device
*/
public async sign (message: Uint8Array, accountOffset = 0, addressOffset = 0, { account = LEDGER_DEFAULT_ACCOUNT, addressIndex = LEDGER_DEFAULT_INDEX, change = LEDGER_DEFAULT_CHANGE }: Partial<AccountOptions> = {}): Promise<LedgerSignature> {
return this.withApp(async (app: SubstrateApp): Promise<LedgerSignature> => {
const buffer = u8aToBuffer(message);
const { signature } = await wrapError(app.sign(account + accountOffset, change, addressIndex + addressOffset, buffer));
public async sign (message: Uint8Array, accountOffset?: number, addressOffset?: number, options?: Partial<AccountOptions>): Promise<LedgerSignature> {
return this.withApp(sign('sign', message, accountOffset, addressOffset, options));
}
return {
signature: hexAddPrefix(signature.toString('hex'))
};
});
/**
* Signs a message (non-transactional) on the Ledger device
*/
public async signRaw (message: Uint8Array, accountOffset?: number, addressOffset?: number, options?: Partial<AccountOptions>): Promise<LedgerSignature> {
return this.withApp(sign('signRaw', u8aWrapBytes(message), accountOffset, addressOffset, options));
}
/**
+2 -1
View File
@@ -38,5 +38,6 @@ export const ledgerApps: Record<string, string> = {
ternoa: 'Ternoa',
unique: 'Unique',
vtb: 'VTB',
xxnetwork: 'XXNetwork'
xxnetwork: 'XXNetwork',
zeitgeist: 'Zeitgeist'
};
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/hw-ledger', path: 'auto', type: 'auto', version: '12.2.2' };
export const packageInfo = { name: '@polkadot/hw-ledger', path: 'auto', type: 'auto', version: '12.4.2' };
+6 -6
View File
@@ -18,15 +18,15 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "12.2.2",
"version": "12.4.2",
"main": "index.js",
"dependencies": {
"@polkadot/util": "12.2.2",
"@polkadot/util-crypto": "12.2.2",
"tslib": "^2.5.3"
"@polkadot/util": "12.4.2",
"@polkadot/util-crypto": "12.4.2",
"tslib": "^2.6.2"
},
"peerDependencies": {
"@polkadot/util": "12.2.2",
"@polkadot/util-crypto": "12.2.2"
"@polkadot/util": "12.4.2",
"@polkadot/util-crypto": "12.4.2"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/keyring', path: 'auto', type: 'auto', version: '12.2.2' };
export const packageInfo = { name: '@polkadot/keyring', path: 'auto', type: 'auto', version: '12.4.2' };
+4 -5
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { EncryptedJsonEncoding, Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { KeyringPair, KeyringPair$Json, KeyringPair$Meta, SignOptions } from '../types.js';
import type { PairInfo } from './types.js';
@@ -165,7 +164,7 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
setMeta: (additional: KeyringPair$Meta): void => {
meta = objectSpread({}, meta, additional);
},
sign: (message: HexString | string | Uint8Array, options: SignOptions = {}): Uint8Array => {
sign: (message: string | Uint8Array, options: SignOptions = {}): Uint8Array => {
if (isLocked(secretKey)) {
throw new Error('Cannot sign with a locked key pair');
}
@@ -192,10 +191,10 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
unlock: (passphrase?: string): void => {
return decodePkcs8(passphrase);
},
verify: (message: HexString | string | Uint8Array, signature: HexString | string | Uint8Array, signerPublic: HexString | string | Uint8Array): boolean => {
verify: (message: string | Uint8Array, signature: string | Uint8Array, signerPublic: string | Uint8Array): boolean => {
return signatureVerify(message, signature, TYPE_ADDRESS[type](u8aToU8a(signerPublic))).isValid;
},
vrfSign: (message: HexString | string | Uint8Array, context?: HexString | string | Uint8Array, extra?: string | Uint8Array): Uint8Array => {
vrfSign: (message: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array => {
if (isLocked(secretKey)) {
throw new Error('Cannot sign with a locked key pair');
}
@@ -208,7 +207,7 @@ export function createPair ({ toSS58, type }: Setup, { publicKey, secretKey }: P
return u8aConcat(vrfHash(proof, context, extra), proof);
},
vrfVerify: (message: HexString | string | Uint8Array, vrfResult: Uint8Array, signerPublic: HexString | Uint8Array | string, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): boolean => {
vrfVerify: (message: string | Uint8Array, vrfResult: Uint8Array, signerPublic: Uint8Array | string, context?: string | Uint8Array, extra?: string | Uint8Array): boolean => {
if (type === 'sr25519') {
return sr25519VrfVerify(message, vrfResult, publicKey, context, extra);
}
+2 -3
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { KeyringPair, KeyringPairs } from './types.js';
import { isHex, isU8a, u8aToHex, u8aToU8a } from '@polkadot/util';
@@ -22,7 +21,7 @@ export class Pairs implements KeyringPairs {
return Object.values(this.#map);
}
public get (address: HexString | string | Uint8Array): KeyringPair {
public get (address: string | Uint8Array): KeyringPair {
const pair = this.#map[decodeAddress(address).toString()];
if (!pair) {
@@ -36,7 +35,7 @@ export class Pairs implements KeyringPairs {
return pair;
}
public remove (address: HexString | string | Uint8Array): void {
public remove (address: string | Uint8Array): void {
delete this.#map[decodeAddress(address).toString()];
}
}
+1 -1
View File
@@ -119,7 +119,7 @@ function createMeta (name?: string, seed?: string) {
return {
isTesting: true,
name: name || (seed && seed.replace('//', '_').toLowerCase())
name: name || seed?.replace('//', '_').toLowerCase()
};
}
+2 -3
View File
@@ -42,9 +42,7 @@ describe('testingPairs', (): void => {
const keyring = new Keyring({ type: 'ethereum' });
const pair = keyring.createFromUri('0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133');
expect(
pair && pair.address
).toEqual(TEST_ADD);
expect(pair?.address).toEqual(TEST_ADD);
});
describe('checks eth test addresses', (): void => {
@@ -62,6 +60,7 @@ describe('testingPairs', (): void => {
'0x4c42532034540267bf568198ccec4cb822a025da542861fcb146a5fab6433ff8',
'0x94c49300a58d576011096bcb006aa06f5a91b34b4383891e8029c21dc39fbb8b'];
// @ts-expect-error We should not delete from the maps, however this is a test
delete ring.nobody;
Object
+36 -3
View File
@@ -1,23 +1,56 @@
// Copyright 2017-2023 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { KeypairType } from '@polkadot/util-crypto/types';
import type { KeyringOptions, KeyringPair } from './types.js';
import { nobody } from './pair/nobody.js';
import { createTestKeyring } from './testing.js';
export interface TestKeyringMap {
nobody: KeyringPair;
[index: string]: KeyringPair;
}
export function createTestPairs (options?: KeyringOptions, isDerived = true): TestKeyringMap {
export interface TestKeyringMapSubstrate extends TestKeyringMap {
alice: KeyringPair;
bob: KeyringPair;
charlie: KeyringPair;
dave: KeyringPair;
eve: KeyringPair;
ferdie: KeyringPair;
}
export interface TestKeyringMapEthereum extends TestKeyringMap {
Alith: KeyringPair;
Baltathar: KeyringPair;
Charleth: KeyringPair;
Dorothy: KeyringPair;
Ethan: KeyringPair;
Faith: KeyringPair;
}
export type DetectMap<O extends KeyringOptions | undefined> = DetectPairType<O> extends 'ethereum'
? TestKeyringMapEthereum
: TestKeyringMapSubstrate;
export type DetectPairType<O extends KeyringOptions | undefined> = O extends KeyringOptions
? O['type'] extends KeypairType
? O['type']
: 'sr25519'
: 'sr25519';
export function createTestPairs <O extends KeyringOptions, M = DetectMap<O>> (options?: O, isDerived = true): M {
const keyring = createTestKeyring(options, isDerived);
const pairs = keyring.getPairs();
const map: TestKeyringMap = { nobody: nobody() };
for (const p of pairs) {
map[p.meta.name as string] = p;
if (p.meta.name) {
map[p.meta.name] = p;
}
}
return map;
return map as M;
}
+57 -6
View File
@@ -15,11 +15,62 @@ export interface KeyringOptions {
type?: KeypairType;
}
export type KeyringPair$Meta = Record<string, unknown>;
export interface KeyringPair$MetaHardware {
accountIndex?: number;
accountOffset?: number;
addressOffset?: number;
hardwareType?: 'ledger';
}
export interface KeyringPair$MetaFlags {
isDefaultAuthSelected?: boolean;
isExternal?: boolean;
isHardware?: boolean;
isHidden?: boolean;
isInjected?: boolean;
isMultisig?: boolean;
isProxied?: boolean;
isRecent?: boolean;
isTesting?: boolean;
}
export interface KeyringPair$MetaContract {
abi: string;
genesisHash?: HexString | null;
}
export interface KeyringPair$MetaExtension {
source?: string;
}
export interface KeyringPair$MetaMultisig {
threshold?: number;
who?: string[];
}
export interface KeyringPair$MetaParent {
parentAddress?: string;
parentName?: string;
}
export interface KeyringPair$Meta extends KeyringPair$MetaExtension, KeyringPair$MetaFlags, KeyringPair$MetaHardware, KeyringPair$MetaMultisig, KeyringPair$MetaParent {
address?: string;
contract?: KeyringPair$MetaContract;
genesisHash?: HexString | null;
name?: string;
suri?: string;
tags?: string[];
type?: KeypairType;
whenCreated?: number;
whenEdited?: number;
whenUsed?: number;
[key: string]: unknown;
}
export interface KeyringPair$Json extends EncryptedJson {
/** The ss58 encoded address or the hex-encoded version (the latter is for ETH-compat chains) */
address: string | HexString;
address: string;
/** The underlying metadata associated with the keypair */
meta: KeyringPair$Meta;
}
@@ -44,12 +95,12 @@ export interface KeyringPair {
encodePkcs8 (passphrase?: string): Uint8Array;
lock (): void;
setMeta (meta: KeyringPair$Meta): void;
sign (message: HexString | string | Uint8Array, options?: SignOptions): Uint8Array;
sign (message: string | Uint8Array, options?: SignOptions): Uint8Array;
toJson (passphrase?: string): KeyringPair$Json;
unlock (passphrase?: string): void;
verify (message: HexString | string | Uint8Array, signature: Uint8Array, signerPublic: HexString | string | Uint8Array): boolean;
vrfSign (message: HexString | string | Uint8Array, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): Uint8Array;
vrfVerify (message: HexString | string | Uint8Array, vrfResult: Uint8Array, signerPublic: HexString | Uint8Array | string, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): boolean;
verify (message: string | Uint8Array, signature: Uint8Array, signerPublic: string | Uint8Array): boolean;
vrfSign (message: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array;
vrfVerify (message: string | Uint8Array, vrfResult: Uint8Array, signerPublic: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): boolean;
}
export interface KeyringPairs {
+5 -5
View File
@@ -15,14 +15,14 @@
},
"sideEffects": false,
"type": "module",
"version": "12.2.2",
"version": "12.4.2",
"main": "index.js",
"dependencies": {
"@polkadot/util": "12.2.2",
"@substrate/ss58-registry": "^1.40.0",
"tslib": "^2.5.3"
"@polkadot/util": "12.4.2",
"@substrate/ss58-registry": "^1.43.0",
"tslib": "^2.6.2"
},
"devDependencies": {
"@polkadot/hw-ledger": "12.2.2"
"@polkadot/hw-ledger": "12.4.2"
}
}
@@ -157,5 +157,8 @@ export const knownGenesis: KnownGenesis = {
],
xxnetwork: [
'0x50dd5d206917bf10502c68fb4d18a59fc8aa31586f4e8856b493e43544aa82aa'
],
zeitgeist: [
'0x1bf2a2ecb4a868de66ea8610f2ce7c8c43706561b6476031315f6640fe38e060'
]
};
+2 -1
View File
@@ -42,5 +42,6 @@ export const knownLedger: KnownLedger = {
ternoa: 0x00003e3,
unique: 0x00000162,
vtb: 0x000002b6,
xxnetwork: 0x000007a3
xxnetwork: 0x000007a3,
zeitgeist: 0x00000162
};
+1 -1
View File
@@ -115,6 +115,6 @@ describe('selectableNetworks', (): void => {
it('has a sorted list (first external, last external)', (): void => {
expect(selectableNetworks[3].displayName).toEqual('3DP network');
expect(selectableNetworks[selectableNetworks.length - 1].displayName).toEqual('xx network');
expect(selectableNetworks[selectableNetworks.length - 1].displayName).toEqual('Zeitgeist');
});
});
+2 -2
View File
@@ -29,8 +29,8 @@ function toExpanded (o: KnownSubstrate): SubstrateNetwork {
n.isIgnored = n.isTestnet || (
!(
o.standardAccount &&
o.decimals && o.decimals.length &&
o.symbols && o.symbols.length
o.decimals?.length &&
o.symbols?.length
) &&
o.prefix !== 42
);
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/networks', path: 'auto', type: 'auto', version: '12.2.2' };
export const packageInfo = { name: '@polkadot/networks', path: 'auto', type: 'auto', version: '12.4.2' };
+12 -6
View File
@@ -5,24 +5,30 @@
import known from '@substrate/ss58-registry';
import fs from 'node:fs';
import path from 'node:path';
const other = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'packages/networks/test/ss58registry.json'), 'utf-8')) as unknown;
import { stringify } from '@polkadot/util';
describe('@substrate/ss58-registry', (): void => {
it('has known values', (): void => {
const json = JSON.stringify(known, null, 2);
const testUrl = new URL('../test/ss58registry.json', import.meta.url);
const json = stringify(known, 2);
try {
expect(JSON.parse(json)).toEqual(other);
expect(
JSON.parse(json)
).toEqual(
JSON.parse(
fs.readFileSync(testUrl, 'utf-8')
)
);
} catch (error) {
if (process.env.GITHUB_REPOSITORY) {
if (process.env['GITHUB_REPOSITORY']) {
console.error(json);
throw error;
}
fs.writeFileSync(path.join(process.cwd(), 'packages/networks/test/ss58registry.json'), json, { flag: 'w' });
fs.writeFileSync(testUrl, json, { flag: 'w' });
}
});
});
+3 -2
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { RegistryEntry } from '@substrate/ss58-registry';
import type { HexString } from '@polkadot/util/types';
export type Icon = 'beachball' | 'empty' | 'jdenticon' | 'polkadot' | 'substrate';
@@ -9,14 +10,14 @@ export type KnownIcon = Record<string, Icon>;
export type KnownLedger = Record<string, number>;
export type KnownGenesis = Record<string, string[]>;
export type KnownGenesis = Record<string, HexString[]>;
export type KnownSubstrate = RegistryEntry;
export type KnownTestnet = Record<string, true>;
export interface SubstrateNetwork extends KnownSubstrate {
genesisHash: string[];
genesisHash: HexString[];
hasLedgerSupport: boolean;
icon: Icon;
isIgnored: boolean;
+134 -6
View File
@@ -222,15 +222,13 @@
"network": "darwinia",
"displayName": "Darwinia Network",
"symbols": [
"RING",
"KTON"
"RING"
],
"decimals": [
9,
9
18
],
"standardAccount": "*25519",
"website": "https://darwinia.network/"
"standardAccount": "secp256k1",
"website": "https://darwinia.network"
},
{
"prefix": 19,
@@ -258,6 +256,19 @@
"standardAccount": "*25519",
"website": "https://stafi.io"
},
{
"prefix": 21,
"network": "karmachain",
"displayName": "Karmacoin",
"symbols": [
"KCOIN"
],
"decimals": [
6
],
"standardAccount": "*25519",
"website": "https://karmaco.in"
},
{
"prefix": 22,
"network": "dock-pos-mainnet",
@@ -713,6 +724,19 @@
"standardAccount": "*25519",
"website": "https://hydradx.io"
},
{
"prefix": 64,
"network": "ewx",
"displayName": "Energy Web X",
"symbols": [
"EWT"
],
"decimals": [
18
],
"standardAccount": "*25519",
"website": "https://www.energyweb.org"
},
{
"prefix": 65,
"network": "aventus",
@@ -1168,6 +1192,32 @@
"standardAccount": "*25519",
"website": "https://sora.org"
},
{
"prefix": 440,
"network": "allfeat_network",
"displayName": "Allfeat Network",
"symbols": [
"AFT"
],
"decimals": [
12
],
"standardAccount": "*25519",
"website": "https://allfeat.network"
},
{
"prefix": 666,
"network": "metaquity_network",
"displayName": "Metaquity Network",
"symbols": [
"MQTY"
],
"decimals": [
18
],
"standardAccount": "*25519",
"website": "https://metaquity.xyz/"
},
{
"prefix": 789,
"network": "geek",
@@ -1402,6 +1452,19 @@
"standardAccount": "*25519",
"website": "https://chainflip.io/"
},
{
"prefix": 2199,
"network": "moonsama",
"displayName": "Moonsama",
"symbols": [
"SAMA"
],
"decimals": [
18
],
"standardAccount": "secp256k1",
"website": "https://moonsama.com"
},
{
"prefix": 2206,
"network": "ICE",
@@ -1441,6 +1504,19 @@
"standardAccount": "*25519",
"website": "https://subspace.network"
},
{
"prefix": 3333,
"network": "peerplays",
"displayName": "Peerplays",
"symbols": [
"PPY"
],
"decimals": [
18
],
"standardAccount": "secp256k1",
"website": "https://www.peerplays.com/"
},
{
"prefix": 4006,
"network": "tangle",
@@ -1523,6 +1599,19 @@
"standardAccount": "*25519",
"website": "https://gmordie.com"
},
{
"prefix": 7306,
"network": "krigan",
"displayName": "Krigan Network",
"symbols": [
"KRGN"
],
"decimals": [
9
],
"standardAccount": "*25519",
"website": "https://krigan.network"
},
{
"prefix": 7391,
"network": "unique_mainnet",
@@ -1536,6 +1625,19 @@
"standardAccount": "*25519",
"website": "https://unique.network"
},
{
"prefix": 8866,
"network": "golden_gate",
"displayName": "Golden Gate",
"symbols": [
"GGX"
],
"decimals": [
18
],
"standardAccount": "*25519",
"website": "https://ggxchain.io/"
},
{
"prefix": 8883,
"network": "sapphire_mainnet",
@@ -1549,6 +1651,19 @@
"standardAccount": "*25519",
"website": "https://unique.network"
},
{
"prefix": 8886,
"network": "golden_gate_sydney",
"displayName": "Golden Gate Sydney",
"symbols": [
"GGXT"
],
"decimals": [
18
],
"standardAccount": "*25519",
"website": "https://ggxchain.io/"
},
{
"prefix": 9072,
"network": "hashed",
@@ -1691,5 +1806,18 @@
],
"standardAccount": "*25519",
"website": "https://bittensor.com"
},
{
"prefix": 14697,
"network": "goro",
"displayName": "GORO Network",
"symbols": [
"GORO"
],
"decimals": [
9
],
"standardAccount": "*25519",
"website": "https://goro.network"
}
]
+9 -9
View File
@@ -20,7 +20,7 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "12.2.2",
"version": "12.4.2",
"browser": {
"crypto": false,
"stream": false
@@ -29,16 +29,16 @@
"dependencies": {
"@noble/curves": "1.1.0",
"@noble/hashes": "1.3.1",
"@polkadot/networks": "12.2.2",
"@polkadot/util": "12.2.2",
"@polkadot/wasm-crypto": "^7.2.1",
"@polkadot/wasm-util": "^7.2.1",
"@polkadot/x-bigint": "12.2.2",
"@polkadot/x-randomvalues": "12.2.2",
"@polkadot/networks": "12.4.2",
"@polkadot/util": "12.4.2",
"@polkadot/wasm-crypto": "^7.2.2",
"@polkadot/wasm-util": "^7.2.2",
"@polkadot/x-bigint": "12.4.2",
"@polkadot/x-randomvalues": "12.4.2",
"@scure/base": "1.1.1",
"tslib": "^2.5.3"
"tslib": "^2.6.2"
},
"peerDependencies": {
"@polkadot/util": "12.2.2"
"@polkadot/util": "12.4.2"
}
}
@@ -1,14 +1,12 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { decodeAddress } from './decode.js';
/**
* @name addressToEvm
* @summary Converts an SS58 address to its corresponding EVM address.
*/
export function addressToEvm (address: HexString | string | Uint8Array, ignoreChecksum?: boolean): Uint8Array {
export function addressToEvm (address: string | Uint8Array, ignoreChecksum?: boolean): Uint8Array {
return decodeAddress(address, ignoreChecksum).subarray(0, 20);
}
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
import { base58Decode } from '../base58/index.js';
@@ -14,7 +13,7 @@ import { defaults } from './defaults.js';
* @description
* From the provided input, validate that the address is a valid input.
*/
export function checkAddress (address: HexString | string, prefix: Prefix): [boolean, string | null] {
export function checkAddress (address: string, prefix: Prefix): [boolean, string | null] {
let decoded;
try {
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L6
@@ -11,7 +10,7 @@ import { base58Decode } from '../base58/index.js';
import { checkAddressChecksum } from './checksum.js';
import { defaults } from './defaults.js';
export function decodeAddress (encoded?: HexString | string | Uint8Array | null, ignoreChecksum?: boolean, ss58Format: Prefix = -1): Uint8Array {
export function decodeAddress (encoded?: string | Uint8Array | null, ignoreChecksum?: boolean, ss58Format: Prefix = -1): Uint8Array {
if (!encoded) {
throw new Error('Invalid empty address passed');
}
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { DeriveJunction } from '../key/DeriveJunction.js';
import type { Prefix } from './types.js';
@@ -20,7 +19,7 @@ function filterHard ({ isHard }: DeriveJunction): boolean {
* @description
* Creates a sr25519 derived address based on the input address/publicKey and the uri supplied.
*/
export function deriveAddress (who: HexString | Uint8Array | string, suri: string, ss58Format?: Prefix): string {
export function deriveAddress (who: string | Uint8Array, suri: string, ss58Format?: Prefix): string {
const { path } = keyExtractPath(suri);
if (!path.length || path.every(filterHard)) {
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L34
@@ -12,7 +11,7 @@ import { decodeAddress } from './decode.js';
import { defaults } from './defaults.js';
import { sshash } from './sshash.js';
export function encodeAddress (key: HexString | Uint8Array | string, ss58Format: Prefix = defaults.prefix): string {
export function encodeAddress (key: string | Uint8Array, ss58Format: Prefix = defaults.prefix): string {
// decode it, this means we can re-encode an address
const u8a = decodeAddress(key);
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
import { decodeAddress } from './decode.js';
@@ -15,6 +14,6 @@ import { createKeyDerived } from './keyDerived.js';
* @description
* Creates a Substrate derived address based on the input address/publicKey and the index supplied.
*/
export function encodeDerivedAddress (who: HexString | Uint8Array | string, index: bigint | BN | number, ss58Format?: Prefix): string {
export function encodeDerivedAddress (who: string | Uint8Array, index: bigint | BN | number, ss58Format?: Prefix): string {
return encodeAddress(createKeyDerived(decodeAddress(who), index), ss58Format);
}
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
import { encodeAddress } from './encode.js';
@@ -14,6 +13,6 @@ import { createKeyMulti } from './keyMulti.js';
* @description
* Creates a Substrate multisig address based on the input address and the required threshold.
*/
export function encodeMultiAddress (who: (HexString | Uint8Array | string)[], threshold: bigint | BN | number, ss58Format?: Prefix): string {
export function encodeMultiAddress (who: (string | Uint8Array)[], threshold: bigint | BN | number, ss58Format?: Prefix): string {
return encodeAddress(createKeyMulti(who, threshold), ss58Format);
}
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aEq } from '@polkadot/util';
import { decodeAddress } from './decode.js';
@@ -21,6 +19,6 @@ import { decodeAddress } from './decode.js';
* u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true
* ```
*/
export function addressEq (a: HexString | string | Uint8Array, b: HexString | string | Uint8Array): boolean {
export function addressEq (a: string | Uint8Array, b: string | Uint8Array): boolean {
return u8aEq(decodeAddress(a), decodeAddress(b));
}
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { HashType } from '../secp256k1/types.js';
import type { Prefix } from './types.js';
@@ -14,7 +13,7 @@ import { encodeAddress } from './encode.js';
* @name evmToAddress
* @summary Converts an EVM address to its corresponding SS58 address.
*/
export function evmToAddress (evmAddress: HexString | string | Uint8Array, ss58Format?: Prefix, hashType: HashType = 'blake2'): string {
export function evmToAddress (evmAddress: string | Uint8Array, ss58Format?: Prefix, hashType: HashType = 'blake2'): string {
const message = u8aConcat('evm:', evmAddress);
if (message.length !== 24) {
+1 -2
View File
@@ -1,12 +1,11 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
import { validateAddress } from './validate.js';
export function isAddress (address?: HexString | string | null, ignoreChecksum?: boolean, ss58Format?: Prefix): address is string {
export function isAddress (address?: string | null, ignoreChecksum?: boolean, ss58Format?: Prefix): address is string {
try {
return validateAddress(address, ignoreChecksum, ss58Format);
} catch {
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import { bnToU8a, stringToU8a, u8aConcat } from '@polkadot/util';
@@ -12,7 +11,7 @@ import { decodeAddress } from './decode.js';
const PREFIX = stringToU8a('modlpy/utilisuba');
export function createKeyDerived (who: HexString | Uint8Array | string, index: bigint | BN | number): Uint8Array {
export function createKeyDerived (who: string | Uint8Array, index: bigint | BN | number): Uint8Array {
return blake2AsU8a(
u8aConcat(
PREFIX,
+1 -2
View File
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import { bnToU8a, compactToU8a, stringToU8a, u8aConcat, u8aSorted } from '@polkadot/util';
@@ -12,7 +11,7 @@ import { addressToU8a } from './util.js';
const PREFIX = stringToU8a('modlpy/utilisuba');
export function createKeyMulti (who: (HexString | Uint8Array | string)[], threshold: bigint | BN | number): Uint8Array {
export function createKeyMulti (who: (string | Uint8Array)[], threshold: bigint | BN | number): Uint8Array {
return blake2AsU8a(
u8aConcat(
PREFIX,
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
import { u8aSorted } from '@polkadot/util';
@@ -9,7 +8,7 @@ import { u8aSorted } from '@polkadot/util';
import { encodeAddress } from './encode.js';
import { addressToU8a } from './util.js';
export function sortAddresses (addresses: (HexString | Uint8Array | string)[], ss58Format?: Prefix): string[] {
export function sortAddresses (addresses: (string | Uint8Array)[], ss58Format?: Prefix): string[] {
const u8aToAddress = (u8a: Uint8Array) => encodeAddress(u8a, ss58Format);
return u8aSorted(
+1 -2
View File
@@ -1,11 +1,10 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js';
import { decodeAddress } from './decode.js';
export function validateAddress (encoded?: HexString | string | null, ignoreChecksum?: boolean, ss58Format?: Prefix): encoded is string {
export function validateAddress (encoded?: string | null, ignoreChecksum?: boolean, ss58Format?: Prefix): encoded is string {
return !!decodeAddress(encoded, ignoreChecksum, ss58Format);
}
+14 -8
View File
@@ -19,6 +19,7 @@ interface Config {
ipfs?: string;
regex?: RegExp;
type: string;
withPadding?: boolean;
}
type DecodeFn = (value: string, ipfsCompat?: boolean) => Uint8Array;
@@ -63,21 +64,26 @@ export function createIs (validate: ValidateFn): ValidateFn {
}
/** @internal */
export function createValidate ({ chars, ipfs, type }: Config): ValidateFn {
export function createValidate ({ chars, ipfs, type, withPadding }: Config): ValidateFn {
return (value?: unknown, ipfsCompat?: boolean): value is string => {
if (typeof value !== 'string') {
throw new Error(`Expected ${type} string input`);
} else if (ipfs && ipfsCompat && value[0] !== ipfs) {
} else if (ipfs && ipfsCompat && !value.startsWith(ipfs)) {
throw new Error(`Expected ipfs-compatible ${type} to start with '${ipfs}'`);
}
for (let i = (ipfsCompat ? 1 : 0), count = value.length; i < count; i++) {
if (!(chars.includes(value[i]) || (
value[i] === '=' && (
(i === value.length - 1) ||
!chars.includes(value[i + 1])
)
))) {
if (chars.includes(value[i])) {
// all ok, character found
} else if (withPadding && value[i] === '=') {
if (i === count - 1) {
// last character, everything ok
} else if (value[i + 1] === '=') {
// next one is also padding, sequence ok
} else {
throw new Error(`Invalid ${type} padding sequence "${value[i]}${value[i + 1]}" at index ${i}`);
}
} else {
throw new Error(`Invalid ${type} character "${value[i]}" (0x${value.charCodeAt(i).toString(16)}) at index ${i}`);
}
}
@@ -0,0 +1,20 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
/// <reference types="@polkadot/dev-test/globals.d.ts" />
import { base58Validate } from './index.js';
describe('base58Validate', (): void => {
it('validates encoded', (): void => {
expect(
base58Validate('a1UbyspTdnyZXLUQaQbciCxrCWWxz24kgSwGXSQnkbs', false)
).toEqual(true);
});
it('fails on string with extra padding', (): void => {
expect(
() => base58Validate('a1UbyspTdnyZXLUQaQbciCxrCWWxz24kgSwGXSQnkbs=', false)
).toThrow(/Invalid base58 character "="/);
});
});
+2 -1
View File
@@ -8,7 +8,8 @@ import { createDecode, createEncode, createIs, createValidate } from '../base32/
const config = {
chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
coder: base64,
type: 'base64'
type: 'base64',
withPadding: true
};
/**
+1 -1
View File
@@ -6,7 +6,7 @@
* @description Trims padding characters
*/
export function base64Trim (value: string): string {
while (value.length && value[value.length - 1] === '=') {
while (value.length && value.endsWith('=')) {
value = value.slice(0, -1);
}
@@ -11,4 +11,22 @@ describe('base64Validate', (): void => {
() => base64Validate('aGVsbG8gd29ybGQg0J/RgNC40LLQtd^GC0YHRgtCy0YPRjiDQvNC4IOS9oOWlvQ==')
).toThrow(/Invalid base64 character "\^" \(0x5e\) at index 30/);
});
it('validates with one extra padding character', (): void => {
expect(
base64Validate('bGlnaHQgd28=')
).toEqual(true);
});
it('validates with two extra padding characters', (): void => {
expect(
base64Validate('bGlnaHQgdw==')
).toEqual(true);
});
it('validates misplaced padding characters', (): void => {
expect(
() => base64Validate('bGlnaHQgdw=g=')
).toThrow(/Invalid base64 padding sequence "=g"/);
});
});
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { blake2b as blake2bJs } from '@noble/hashes/blake2b';
import { hasBigInt, u8aToU8a } from '@polkadot/util';
@@ -24,7 +22,7 @@ import { createAsHex } from '../helpers.js';
* blake2AsU8a('abc'); // => [0xba, 0x80, 0xa5, 0x3f, 0x98, 0x1c, 0x4d, 0x0d]
* ```
*/
export function blake2AsU8a (data: HexString | Uint8Array | string, bitLength: 64 | 128 | 256 | 384 | 512 = 256, key?: Uint8Array | null, onlyJs?: boolean): Uint8Array {
export function blake2AsU8a (data: string | Uint8Array, bitLength: 64 | 128 | 256 | 384 | 512 = 256, key?: Uint8Array | null, onlyJs?: boolean): Uint8Array {
const byteLength = Math.ceil(bitLength / 8);
const u8a = u8aToU8a(data);
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types.js';
import { ed25519 } from '@noble/curves/ed25519';
@@ -23,7 +22,7 @@ import { ed25519Sign as wasmSign, isReady } from '@polkadot/wasm-crypto';
* ed25519Sign([...], [...]); // => [...]
* ```
*/
export function ed25519Sign (message: HexString | Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>, onlyJs?: boolean): Uint8Array {
export function ed25519Sign (message: string | Uint8Array, { publicKey, secretKey }: Partial<Keypair>, onlyJs?: boolean): Uint8Array {
if (!secretKey) {
throw new Error('Expected a valid secretKey');
} else if (!publicKey) {
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { ed25519 } from '@noble/curves/ed25519';
import { hasBigInt, u8aToU8a } from '@polkadot/util';
@@ -22,7 +20,7 @@ import { ed25519Verify as wasmVerify, isReady } from '@polkadot/wasm-crypto';
* ed25519Verify([...], [...], [...]); // => true/false
* ```
*/
export function ed25519Verify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string, onlyJs?: boolean): boolean {
export function ed25519Verify (message: string | Uint8Array, signature: string | Uint8Array, publicKey: string | Uint8Array, onlyJs?: boolean): boolean {
const messageU8a = u8aToU8a(message);
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
+1 -1
View File
@@ -16,7 +16,7 @@ function getH160 (u8a: Uint8Array): Uint8Array {
return u8a.slice(-20);
}
export function ethereumEncode (addressOrPublic?: HexString | string | Uint8Array): HexString {
export function ethereumEncode (addressOrPublic?: string | Uint8Array): HexString {
if (!addressOrPublic) {
return '0x';
}
@@ -1,13 +1,11 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { isHex } from '@polkadot/util';
import { isEthereumChecksum } from './isChecksum.js';
export function isEthereumAddress (address?: HexString | string): boolean {
export function isEthereumAddress (address?: string): boolean {
if (!address || address.length !== 42 || !isHex(address)) {
return false;
} else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) {
+4 -4
View File
@@ -21,14 +21,14 @@ export function createAsHex <T extends (...args: never[]) => Uint8Array> (fn: T)
}
/** @internal */
export function createBitHasher (bitLength: 256 | 512, fn: (data: HexString | Uint8Array | string, bitLength: 256 | 512, onlyJs?: boolean) => Uint8Array): (data: HexString | Uint8Array | string, onlyJs?: boolean) => Uint8Array {
return (data: HexString | Uint8Array | string, onlyJs?: boolean): Uint8Array =>
export function createBitHasher (bitLength: 256 | 512, fn: (data: string | Uint8Array, bitLength: 256 | 512, onlyJs?: boolean) => Uint8Array): (data: string | Uint8Array, onlyJs?: boolean) => Uint8Array {
return (data: string | Uint8Array, onlyJs?: boolean): Uint8Array =>
fn(data, bitLength, onlyJs);
}
/** @internal */
export function createDualHasher (wa: DualHash, js: DualHash): (value: HexString | Uint8Array | string, bitLength?: 256 | 512, onlyJs?: boolean) => Uint8Array {
return (value: HexString | Uint8Array | string, bitLength: 256 | 512 = 256, onlyJs?: boolean): Uint8Array => {
export function createDualHasher (wa: DualHash, js: DualHash): (value: string | Uint8Array, bitLength?: 256 | 512, onlyJs?: boolean) => Uint8Array {
return (value: string | Uint8Array, bitLength: 256 | 512 = 256, onlyJs?: boolean): Uint8Array => {
const u8a = u8aToU8a(value);
return !hasBigInt || (!onlyJs && isReady())
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
export type EncryptedJsonVersion = '0' | '1' | '2' | '3';
export type EncryptedJsonEncoding = 'none' | 'scrypt' | 'xsalsa20-poly1305';
@@ -14,6 +12,6 @@ export interface EncryptedJsonDescriptor {
}
export interface EncryptedJson {
encoded: HexString | string;
encoded: string;
encoding: EncryptedJsonDescriptor;
}
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { BN, bnToU8a, compactAddLength, hexToU8a, isBigInt, isBn, isHex, isNumber, isString, stringToU8a } from '@polkadot/util';
import { blake2AsU8a } from '../blake2/asU8a.js';
@@ -46,7 +44,7 @@ export class DeriveJunction {
return !this.#isHard;
}
public hard (value: HexString | number | string | bigint | BN | Uint8Array): DeriveJunction {
public hard (value: number | string | bigint | BN | Uint8Array): DeriveJunction {
return this.soft(value).harden();
}
@@ -56,7 +54,7 @@ export class DeriveJunction {
return this;
}
public soft (value: HexString | number | string | bigint | BN | Uint8Array): DeriveJunction {
public soft (value: number | string | bigint | BN | Uint8Array): DeriveJunction {
if (isNumber(value) || isBn(value) || isBigInt(value)) {
return this.soft(bnToU8a(value, BN_LE_256_OPTS));
} else if (isHex(value)) {
+2 -2
View File
@@ -81,7 +81,7 @@ export function mnemonicToEntropy (mnemonic: string, wordlist: string[] = DEFAUL
// calculate the checksum and compare
const matched = entropyBits.match(/(.{1,8})/g);
const entropyBytes = matched && matched.map(binaryToByte);
const entropyBytes = matched?.map(binaryToByte);
if (!entropyBytes || (entropyBytes.length % 4 !== 0) || (entropyBytes.length < 16) || (entropyBytes.length > 32)) {
throw new Error(INVALID_ENTROPY);
@@ -103,7 +103,7 @@ export function entropyToMnemonic (entropy: Uint8Array, wordlist: string[] = DEF
}
const matched = `${bytesToBinary(Array.from(entropy))}${deriveChecksumBits(entropy)}`.match(/(.{1,11})/g);
const mapped = matched && matched.map((b) => wordlist[binaryToByte(b)]);
const mapped = matched?.map((b) => wordlist[binaryToByte(b)]);
if (!mapped || (mapped.length < 12)) {
throw new Error('Unable to map entropy to mnemonic');
@@ -136,7 +136,7 @@ describe('tweetnacl/secretbox', (): void => {
});
describe('tweetnacl/test/04-secretbox.js', (): void => {
for (let i = 0; i < TEST_DATA.length; i++) {
for (let i = 0, count = TEST_DATA.length; i < count; i++) {
const [keyBase64, nonceBase64, msgBase64, expBase64] = TEST_DATA[i];
it(`is ok on "${msgBase64}"`, (): void => {
+1 -1
View File
@@ -958,7 +958,7 @@ function checkLengths (k: Uint8Array, n: Uint8Array): void {
// }
function checkArrayTypes (...args: unknown[]): void {
for (let i = 0; i < args.length; i++) {
for (let i = 0, count = args.length; i < count; i++) {
if (!(args[i] instanceof Uint8Array))
throw new TypeError('unexpected type, use Uint8Array');
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/util-crypto', path: 'auto', type: 'auto', version: '12.2.2' };
export const packageInfo = { name: '@polkadot/util-crypto', path: 'auto', type: 'auto', version: '12.4.2' };
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { pbkdf2 as pbkdf2Js } from '@noble/hashes/pbkdf2';
import { sha512 } from '@noble/hashes/sha512';
@@ -17,7 +15,7 @@ interface Result {
salt: Uint8Array;
}
export function pbkdf2Encode (passphrase?: HexString | Uint8Array | string, salt: Uint8Array = randomAsU8a(), rounds = 2048, onlyJs?: boolean): Result {
export function pbkdf2Encode (passphrase?: string | Uint8Array, salt: Uint8Array = randomAsU8a(), rounds = 2048, onlyJs?: boolean): Result {
const u8aPass = u8aToU8a(passphrase);
const u8aSalt = u8aToU8a(salt);
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Params } from './types.js';
import { scrypt as scryptJs } from '@noble/hashes/scrypt';
@@ -18,7 +17,7 @@ interface Result {
salt: Uint8Array;
}
export function scryptEncode (passphrase?: HexString | Uint8Array | string, salt = randomAsU8a(), params = DEFAULT_PARAMS, onlyJs?: boolean): Result {
export function scryptEncode (passphrase?: string | Uint8Array, salt = randomAsU8a(), params = DEFAULT_PARAMS, onlyJs?: boolean): Result {
const u8a = u8aToU8a(passphrase);
return {
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { HashType } from './types.js';
import { secp256k1 } from '@noble/curves/secp256k1';
@@ -16,7 +15,7 @@ import { secp256k1Expand } from './expand.js';
* @name secp256k1Recover
* @description Recovers a publicKey from the supplied signature
*/
export function secp256k1Recover (msgHash: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, recovery: number, hashType: HashType = 'blake2', onlyJs?: boolean): Uint8Array {
export function secp256k1Recover (msgHash: string | Uint8Array, signature: string | Uint8Array, recovery: number, hashType: HashType = 'blake2', onlyJs?: boolean): Uint8Array {
const sig = u8aToU8a(signature).subarray(0, 64);
const msg = u8aToU8a(msgHash);
const publicKey = !hasBigInt || (!onlyJs && isReady())
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { HashType } from './types.js';
import { u8aEq, u8aToU8a } from '@polkadot/util';
@@ -13,7 +12,7 @@ import { secp256k1Recover } from './recover.js';
* @name secp256k1Verify
* @description Verifies the signature of `message`, using the supplied pair
*/
export function secp256k1Verify (msgHash: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, address: HexString | Uint8Array | string, hashType: HashType = 'blake2', onlyJs?: boolean): boolean {
export function secp256k1Verify (msgHash: string | Uint8Array, signature: string | Uint8Array, address: string | Uint8Array, hashType: HashType = 'blake2', onlyJs?: boolean): boolean {
const sig = u8aToU8a(signature);
if (sig.length !== 65) {
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { KeypairType, VerifyResult } from '../types.js';
import { u8aIsWrapped, u8aToU8a, u8aUnwrapBytes, u8aWrapBytes } from '@polkadot/util';
@@ -87,7 +86,7 @@ function getVerifyFn (signature: Uint8Array): VerifyFn {
: verifyDetect;
}
export function signatureVerify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, addressOrPublicKey: HexString | Uint8Array | string): VerifyResult {
export function signatureVerify (message: string | Uint8Array, signature: string | Uint8Array, addressOrPublicKey: string | Uint8Array): VerifyResult {
const signatureU8a = u8aToU8a(signature);
if (![64, 65, 66].includes(signatureU8a.length)) {
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util';
import { sr25519Agree } from '@polkadot/wasm-crypto';
@@ -10,7 +8,7 @@ import { sr25519Agree } from '@polkadot/wasm-crypto';
* @name sr25519Agreement
* @description Key agreement between other's public key and self secret key
*/
export function sr25519Agreement (secretKey: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string): Uint8Array {
export function sr25519Agreement (secretKey: string | Uint8Array, publicKey: string | Uint8Array): Uint8Array {
const secretKeyU8a = u8aToU8a(secretKey);
const publicKeyU8a = u8aToU8a(publicKey);
@@ -1,12 +1,10 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { isU8a, u8aToU8a } from '@polkadot/util';
import { sr25519DerivePublicSoft } from '@polkadot/wasm-crypto';
export function sr25519DerivePublic (publicKey: HexString | Uint8Array | string, chainCode: Uint8Array): Uint8Array {
export function sr25519DerivePublic (publicKey: string | Uint8Array, chainCode: Uint8Array): Uint8Array {
const publicKeyU8a = u8aToU8a(publicKey);
if (!isU8a(chainCode) || chainCode.length !== 32) {
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../../types.js';
import { u8aToU8a } from '@polkadot/util';
@@ -13,7 +12,7 @@ import { sr25519PairFromU8a } from './fromU8a.js';
* @name sr25519PairFromSeed
* @description Returns a object containing a `publicKey` & `secretKey` generated from the supplied seed.
*/
export function sr25519PairFromSeed (seed: HexString | Uint8Array | string): Keypair {
export function sr25519PairFromSeed (seed: string | Uint8Array): Keypair {
const seedU8a = u8aToU8a(seed);
if (seedU8a.length !== 32) {
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../../types.js';
import { u8aToU8a } from '@polkadot/util';
@@ -10,7 +9,7 @@ const SEC_LEN = 64;
const PUB_LEN = 32;
const TOT_LEN = SEC_LEN + PUB_LEN;
export function sr25519PairFromU8a (full: HexString | Uint8Array | string): Keypair {
export function sr25519PairFromU8a (full: string | Uint8Array): Keypair {
const fullU8a = u8aToU8a(full);
if (fullU8a.length !== TOT_LEN) {
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types.js';
import { u8aToU8a } from '@polkadot/util';
@@ -11,7 +10,7 @@ import { sr25519Sign as wasmSign } from '@polkadot/wasm-crypto';
* @name sr25519Sign
* @description Returns message signature of `message`, using the supplied pair
*/
export function sr25519Sign (message: HexString | Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
export function sr25519Sign (message: string | Uint8Array, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
if (publicKey?.length !== 32) {
throw new Error('Expected a valid publicKey, 32-bytes');
} else if (secretKey?.length !== 64) {
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util';
import { sr25519Verify as wasmVerify } from '@polkadot/wasm-crypto';
@@ -10,7 +8,7 @@ import { sr25519Verify as wasmVerify } from '@polkadot/wasm-crypto';
* @name sr25519Verify
* @description Verifies the signature of `message`, using the supplied pair
*/
export function sr25519Verify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, publicKey: HexString | Uint8Array | string): boolean {
export function sr25519Verify (message: string | Uint8Array, signature: string | Uint8Array, publicKey: string | Uint8Array): boolean {
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types.js';
import { u8aToU8a } from '@polkadot/util';
@@ -13,7 +12,7 @@ const EMPTY_U8A = new Uint8Array();
* @name sr25519VrfSign
* @description Sign with sr25519 vrf signing (deterministic)
*/
export function sr25519VrfSign (message: HexString | Uint8Array | string, { secretKey }: Partial<Keypair>, context: HexString | string | Uint8Array = EMPTY_U8A, extra: HexString | string | Uint8Array = EMPTY_U8A): Uint8Array {
export function sr25519VrfSign (message: string | Uint8Array, { secretKey }: Partial<Keypair>, context: string | Uint8Array = EMPTY_U8A, extra: string | Uint8Array = EMPTY_U8A): Uint8Array {
if (secretKey?.length !== 64) {
throw new Error('Invalid secretKey, expected 64-bytes');
}
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util';
import { vrfVerify } from '@polkadot/wasm-crypto';
@@ -12,7 +10,7 @@ const EMPTY_U8A = new Uint8Array();
* @name sr25519VrfVerify
* @description Verify with sr25519 vrf verification
*/
export function sr25519VrfVerify (message: HexString | Uint8Array | string, signOutput: HexString | string | Uint8Array, publicKey: HexString | Uint8Array | string, context: HexString | string | Uint8Array = EMPTY_U8A, extra: HexString | string | Uint8Array = EMPTY_U8A): boolean {
export function sr25519VrfVerify (message: string | Uint8Array, signOutput: string | Uint8Array, publicKey: string | Uint8Array, context: string | Uint8Array = EMPTY_U8A, extra: string | Uint8Array = EMPTY_U8A): boolean {
const publicKeyU8a = u8aToU8a(publicKey);
const proofU8a = u8aToU8a(signOutput);
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { hasBigInt, u8aToU8a } from '@polkadot/util';
import { isReady, twox } from '@polkadot/wasm-crypto';
@@ -23,7 +21,7 @@ import { xxhash64 } from './xxhash64.js';
* xxhashAsU8a('abc'); // => 0x44bc2cf5ad770999
* ```
*/
export function xxhashAsU8a (data: HexString | Uint8Array | string, bitLength: 64 | 128 | 192 | 256 | 320 | 384 | 448 | 512 = 64, onlyJs?: boolean): Uint8Array {
export function xxhashAsU8a (data: string | Uint8Array, bitLength: 64 | 128 | 192 | 256 | 320 | 384 | 448 | 512 = 64, onlyJs?: boolean): Uint8Array {
const rounds = Math.ceil(bitLength / 64);
const u8a = u8aToU8a(data);
+7 -7
View File
@@ -18,7 +18,7 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "12.2.2",
"version": "12.4.2",
"main": "index.js",
"exports": {
"./hex/toU8a": {
@@ -35,15 +35,15 @@
}
},
"dependencies": {
"@polkadot/x-bigint": "12.2.2",
"@polkadot/x-global": "12.2.2",
"@polkadot/x-textdecoder": "12.2.2",
"@polkadot/x-textencoder": "12.2.2",
"@polkadot/x-bigint": "12.4.2",
"@polkadot/x-global": "12.4.2",
"@polkadot/x-textdecoder": "12.4.2",
"@polkadot/x-textencoder": "12.4.2",
"@types/bn.js": "^5.1.1",
"bn.js": "^5.2.1",
"tslib": "^2.5.3"
"tslib": "^2.6.2"
},
"devDependencies": {
"@polkadot/x-randomvalues": "12.2.2"
"@polkadot/x-randomvalues": "12.4.2"
}
}
+3 -2
View File
@@ -3,6 +3,7 @@
/// <reference types="@polkadot/dev-test/globals.d.ts" />
import { stringify } from '../stringify.js';
import { perf } from '../test/index.js';
import { arrayRange, arrayShuffle } from './index.js';
@@ -30,8 +31,8 @@ describe('arrayShuffle', (): void => {
inp.filter((v) => !out.includes(v))
).toEqual([]);
expect(
JSON.stringify(inp)
).not.toEqual(JSON.stringify(out));
stringify(inp)
).not.toEqual(stringify(out));
});
perf('arrayShuffle', 1000, [[ptest]], arrayShuffle);
+8 -6
View File
@@ -7,7 +7,7 @@ import { BN } from '../bn/index.js';
import { _sqrt2pow53n, nSqrt } from './index.js';
// eslint-disable-next-line jest/no-export
export const SQRT_TESTS: [string | number | BN | bigint, string | number][] = [
export const TESTS: [value: string | number | BN | bigint, expected: string | number][] = [
[0, 0],
[1, 1],
[4, 2],
@@ -47,11 +47,13 @@ describe('nSqrt', (): void => {
).toEqual(true);
});
SQRT_TESTS.forEach(([value, expected], index): void => {
it(`calcs for test #${index}`, (): void => {
expect(
nSqrt(value) === BigInt(expected)
).toEqual(true);
describe('conversion tests', (): void => {
TESTS.forEach(([value, expected], i): void => {
it(`#${i}: calcs ${expected}`, (): void => {
expect(
nSqrt(value) === BigInt(expected)
).toEqual(true);
});
});
});
});
+2 -2
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '../bn/bn.js';
import type { HexString, ToBigInt, ToBn } from '../types.js';
import type { ToBigInt, ToBn } from '../types.js';
import { BigInt } from '@polkadot/x-bigint';
@@ -16,7 +16,7 @@ import { isToBn } from '../is/toBn.js';
* @name nToBigInt
* @summary Creates a bigInt value from a BN, bigint, string (base 10 or hex) or number input.
*/
export function nToBigInt <ExtToBn extends ToBigInt | ToBn> (value?: HexString | ExtToBn | BN | bigint | string | number | null): bigint {
export function nToBigInt <ExtToBn extends ToBigInt | ToBn> (value?: ExtToBn | BN | bigint | string | number | null): bigint {
return typeof value === 'bigint'
? value
: !value
+55 -18
View File
@@ -7,9 +7,64 @@ import { arrayRange } from '../array/index.js';
import { perf } from '../test/index.js';
import { nToU8a } from './index.js';
// eslint-disable-next-line jest/no-export
export const TESTS: [isLe: boolean, isNegative: boolean, numarr: number[], strval: string][] = [
// LE, positive numbers
[true, false, [0x12], '18'],
[true, false, [0x12, 0x34], '13330'],
[true, false, [0x12, 0x34, 0x56], '5649426'],
[true, false, [0x12, 0x34, 0x56, 0x78], '2018915346'],
[true, false, [0x12, 0x34, 0x56, 0x78, 0x9a], '663443878930'],
[true, false, [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc], '207371629900818'],
[true, false, [0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78], '159954953172672629770948536149615195154'],
// LE, positive numbers (w/ signed flag)
[true, true, [12], '12'],
[true, true, [210, 4], '1234'],
[true, true, [64, 226, 1], '123456'],
[true, true, [21, 205, 91, 7], '123456789'],
[true, true, [203, 36, 104, 12, 8], '34567890123'],
[true, true, [255, 159, 114, 78, 24, 9], '9999999999999'],
// LE, negative numbers
[true, true, [244], '-12'],
[true, true, [46, 251], '-1234'],
[true, true, [192, 29, 254], '-123456'],
[true, true, [255, 255, 255, 255], '-1'],
[true, true, [254, 255, 255, 255], '-2'],
[true, true, [235, 50, 164, 248], '-123456789'],
[true, true, [0, 0, 0, 128], '-2147483648'],
[true, true, [0, 0, 0, 240], '-268435456'],
[true, true, [65, 86, 129, 173, 254], '-5678999999'],
[true, true, [1, 96, 141, 177, 231, 246], '-9999999999999'],
[true, true, [1, 0, 156, 88, 76, 73, 31, 242], '-999999999999999999'],
// BE
[false, false, [0x12], '18'],
[false, false, [0x12, 0x34], '4660'],
[false, false, [0x12, 0x34, 0x56], '1193046'],
[false, false, [0x12, 0x34, 0x56, 0x78], '305419896'],
[false, true, [0xf2, 0x34, 0x56, 0x78], '-231451016'],
[false, false, [0x12, 0x34, 0x56, 0x78, 0x9a], '78187493530'],
[false, false, [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc], '20015998343868'],
[false, false, [0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78], '24197857161011715162171839636988778104']
];
const ptest = arrayRange(65536).map((v) => [v]);
describe('nToU8a', (): void => {
describe('conversion tests', (): void => {
TESTS.forEach(([isLe, isNegative, numarr, strval], i): void => {
const bitLength = numarr.length * 8;
it(`#${i}: converts from ${strval} (bitLength=${bitLength}, isLe=${isLe}, isNegative=${isNegative})`, (): void => {
expect(
nToU8a(
BigInt(strval),
{ bitLength, isLe, isNegative }
)
).toEqual(new Uint8Array(numarr));
});
});
});
it('converts null values to 0x00', (): void => {
expect(
nToU8a(null)
@@ -40,23 +95,5 @@ describe('nToU8a', (): void => {
).toEqual(new Uint8Array([0x56, 0x34, 0x12, 0x00]));
});
it('converts negative numbers', (): void => {
expect(
nToU8a(-1234n, { isNegative: true })
).toEqual(new Uint8Array([46, 251]));
});
it('converts negative numbers (BE)', (): void => {
expect(
nToU8a(-1234n, { isLe: false, isNegative: true })
).toEqual(new Uint8Array([251, 46]));
});
it('converts negative numbers (bitLength)', (): void => {
expect(
nToU8a(-1234n, { bitLength: 32, isNegative: true })
).toEqual(new Uint8Array([46, 251, 255, 255]));
});
perf('nToU8a', 250000, ptest, nToU8a);
});
+3 -2
View File
@@ -14,15 +14,16 @@ const NEG_MASK = BigInt(0xff);
function toU8a (value: bigint, isLe: boolean, isNegative: boolean): Uint8Array {
const arr: number[] = [];
const withSigned = isNegative && (value < _0n);
if (isNegative) {
if (withSigned) {
value = (value + _1n) * -_1n;
}
while (value !== _0n) {
const mod = value % DIV;
const val = Number(
isNegative
withSigned
? mod ^ NEG_MASK
: mod
);
+8 -6
View File
@@ -3,7 +3,7 @@
/// <reference types="@polkadot/dev-test/globals.d.ts" />
import { SQRT_TESTS } from '../bi/sqrt.spec.js';
import { TESTS } from '../bi/sqrt.spec.js';
import { BN, BN_SQRT_MAX_INTEGER, bnSqrt } from './index.js';
describe('bnSqrt', (): void => {
@@ -25,11 +25,13 @@ describe('bnSqrt', (): void => {
).toEqual(true);
});
SQRT_TESTS.forEach(([value, expected], index): void => {
it(`calcs for test #${index}`, (): void => {
expect(
bnSqrt(value).eq(new BN(expected))
).toEqual(true);
describe('conversion tests', (): void => {
TESTS.forEach(([value, expected], i): void => {
it(`#${i}: calcs ${expected}`, (): void => {
expect(
bnSqrt(value).eq(new BN(expected))
).toEqual(true);
});
});
});
});
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString, ToBigInt, ToBn } from '../types.js';
import type { ToBigInt, ToBn } from '../types.js';
import { hexToBn } from '../hex/toBn.js';
import { isBigInt } from '../is/bigInt.js';
@@ -26,7 +26,7 @@ import { BN } from './bn.js';
* bnToBn(new BN(0x1234)); // => BN(0x1234)
* ```
*/
export function bnToBn <ExtToBn extends ToBigInt | ToBn> (value?: HexString | ExtToBn | BN | bigint | string | number | null): BN {
export function bnToBn <ExtToBn extends ToBigInt | ToBn> (value?: ExtToBn | BN | bigint | string | number | null): BN {
return value
? BN.isBN(value)
? value
+12 -58
View File
@@ -4,6 +4,7 @@
/// <reference types="@polkadot/dev-test/globals.d.ts" />
import { arrayRange } from '../array/index.js';
import { TESTS } from '../bi/toU8a.spec.js';
import { perf } from '../test/index.js';
import { BN, bnToU8a } from './index.js';
@@ -40,65 +41,18 @@ describe('bnToU8a', (): void => {
).toEqual(new Uint8Array([0x56, 0x34, 0x12, 0x00]));
});
describe('signed', (): void => {
it('converts negative numbers (BE)', (): void => {
expect(
bnToU8a(new BN(-1234), { isLe: false, isNegative: true })
).toEqual(new Uint8Array([251, 46]));
});
describe('conversion tests', (): void => {
TESTS.forEach(([isLe, isNegative, numarr, strval], i): void => {
const bitLength = numarr.length * 8;
it('converts negative numbers (LE, i8)', (): void => {
expect(
bnToU8a(new BN(-12), { isNegative: true })
).toEqual(new Uint8Array([244]));
});
it('converts negative numbers (LE, i16)', (): void => {
expect(
bnToU8a(new BN(-1234), { isNegative: true })
).toEqual(new Uint8Array([46, 251]));
});
it('converts negative numbers (LE, i24)', (): void => {
expect(
bnToU8a(new BN(-123456), { isNegative: true })
).toEqual(new Uint8Array([192, 29, 254]));
});
it('converts negative numbers (LE, i32)', (): void => {
expect(
bnToU8a(new BN(-123456789), { isNegative: true })
).toEqual(new Uint8Array([235, 50, 164, 248]));
});
it('converts negative numbers (LE, i40)', (): void => {
expect(
bnToU8a(new BN(-5678999999), { isNegative: true })
).toEqual(new Uint8Array([65, 86, 129, 173, 254]));
});
it('converts negative numbers (LE, i48)', (): void => {
expect(
bnToU8a(new BN(-9999999999999), { isNegative: true })
).toEqual(new Uint8Array([1, 96, 141, 177, 231, 246]));
});
it('converts negative numbers (LE, i64)', (): void => {
expect(
bnToU8a(new BN('-999999999999999999'), { isNegative: true })
).toEqual(new Uint8Array([1, 0, 156, 88, 76, 73, 31, 242]));
});
it('converts negative numbers (LE, bitLength)', (): void => {
expect(
bnToU8a(new BN(-1234), { bitLength: 32, isNegative: true })
).toEqual(new Uint8Array([46, 251, 255, 255]));
});
it('converts negative numbers (LE, bitLength, check)', (): void => {
expect(
bnToU8a(new BN(-123456), { bitLength: 32, isNegative: true })
).toEqual(new Uint8Array([192, 29, 254, 255]));
it(`#${i}: converts from ${strval} (bitLength=${bitLength}, isLe=${isLe}, isNegative=${isNegative})`, (): void => {
expect(
bnToU8a(
new BN(strval),
{ bitLength, isLe, isNegative }
)
).toEqual(new Uint8Array(numarr));
});
});
});
+37 -104
View File
@@ -6,83 +6,36 @@
import { BN } from '../bn/index.js';
import { compactToU8a } from './index.js';
const TESTS: [output: string | Uint8Array, input: BN | number][] = [
// Rust tests
// Copied from https://github.com/paritytech/parity-codec/blob/master/src/codec.rs
['00', new BN('0')],
['fc', new BN('63')],
['01 01', new BN('64')],
['fd ff', new BN('16383')],
['02 00 01 00', new BN('16384')],
['fe ff ff ff', new BN('1073741823')],
['03 00 00 00 40', new BN('1073741824')],
['03 ff ff ff ff', new BN(`${1}${'0'.repeat(32)}`, 2).subn(1)],
['07 00 00 00 00 01', new BN(`${1}${'0'.repeat(32)}`, 2)],
['0b 00 00 00 00 00 01', new BN(`${1}${'0'.repeat(40)}`, 2)],
['0f 00 00 00 00 00 00 01', new BN(`${1}${'0'.repeat(48)}`, 2)],
['0f ff ff ff ff ff ff ff', new BN(`${1}${'0'.repeat(56)}`, 2).subn(1)],
['13 00 00 00 00 00 00 00 01', new BN(`${1}${'0'.repeat(56)}`, 2)],
['13 ff ff ff ff ff ff ff ff', new BN(`${1}${'0'.repeat(64)}`, 2).subn(1)],
// own tests
[new Uint8Array([18 << 2]), 18],
[new Uint8Array([0b11111100]), 63],
[new Uint8Array([0xbd, 0x01]), 111],
[new Uint8Array([0b11111101, 0b00000111]), 511],
[new Uint8Array([253, 127]), 0x1fff],
[new Uint8Array([254, 255, 3, 0]), 0xffff],
[new Uint8Array([3 + ((4 - 4) << 2), 249, 255, 255, 255]), 0xfffffff9],
[new Uint8Array([3 + ((6 - 4) << 2), 0x00, 0x40, 0x7a, 0x10, 0xf3, 0x5a]), new BN('00005af3107a4000', 16)],
[new Uint8Array([23, 52, 0x40, 0x7a, 0x10, 0xf3, 0x5a, 0, 0, 18]), new BN('1200005af3107a4034', 16)]
];
describe('encode', (): void => {
it('encodes short u8', (): void => {
expect(
compactToU8a(18)
).toEqual(
new Uint8Array([18 << 2])
);
});
it('encodes max u8 values', (): void => {
expect(
compactToU8a(new BN(63))
).toEqual(
new Uint8Array([0b11111100])
);
});
it('encodes basic u16 value', (): void => {
expect(
compactToU8a(511)
).toEqual(
new Uint8Array([0b11111101, 0b00000111])
);
});
it('encodes basic u16 (not at edge)', (): void => {
expect(
compactToU8a(111)
).toEqual(
new Uint8Array([0xbd, 0x01])
);
});
it('encodes basic u32 values (< 2^30)', (): void => {
expect(
compactToU8a(0x1fff)
).toEqual(
new Uint8Array([253, 127])
);
});
it('encodes basic u32 values (short)', (): void => {
expect(
compactToU8a(0xffff)
).toEqual(
new Uint8Array([254, 255, 3, 0])
);
});
it('encodes basic u32 values (full)', (): void => {
expect(
compactToU8a(0xfffffff9)
).toEqual(
new Uint8Array([3 + ((4 - 4) << 2), 249, 255, 255, 255])
);
});
it('encodes a large value (6 bytes)', (): void => {
expect(
compactToU8a(
new BN('00005af3107a4000', 16)
)
).toEqual(
new Uint8Array([3 + ((6 - 4) << 2), 0x00, 0x40, 0x7a, 0x10, 0xf3, 0x5a])
);
});
it('encodes a large value (9 bytes)', (): void => {
expect(
compactToU8a(
new BN('1200005af3107a4034', 16)
)
).toEqual(
new Uint8Array([23, 52, 0x40, 0x7a, 0x10, 0xf3, 0x5a, 0, 0, 18])
);
});
it('does not modify the original', (): void => {
const original = new BN(123456);
@@ -90,37 +43,17 @@ describe('encode', (): void => {
expect(original.toString()).toEqual('123456');
});
describe('from Rust', (): void => {
// Copied from https://github.com/paritytech/parity-codec/blob/master/src/codec.rs
const testCases = [
{ expected: '00', value: new BN('0') },
{ expected: 'fc', value: new BN('63') },
{ expected: '01 01', value: new BN('64') },
{ expected: 'fd ff', value: new BN('16383') },
{ expected: '02 00 01 00', value: new BN('16384') },
{ expected: 'fe ff ff ff', value: new BN('1073741823') },
{ expected: '03 00 00 00 40', value: new BN('1073741824') },
{ expected: '03 ff ff ff ff', value: new BN(`${1}${'0'.repeat(32)}`, 2).subn(1) },
{ expected: '07 00 00 00 00 01', value: new BN(`${1}${'0'.repeat(32)}`, 2) },
{ expected: '0b 00 00 00 00 00 01', value: new BN(`${1}${'0'.repeat(40)}`, 2) },
{ expected: '0f 00 00 00 00 00 00 01', value: new BN(`${1}${'0'.repeat(48)}`, 2) },
{ expected: '0f ff ff ff ff ff ff ff', value: new BN(`${1}${'0'.repeat(56)}`, 2).subn(1) },
{ expected: '13 00 00 00 00 00 00 00 01', value: new BN(`${1}${'0'.repeat(56)}`, 2) },
{ expected: '13 ff ff ff ff ff ff ff ff', value: new BN(`${1}${'0'.repeat(64)}`, 2).subn(1) }
];
function testEncode (value: BN, expected: string): void {
it(`encodes ${value.toString()}`, (): void => {
describe('conversion tests', (): void => {
TESTS.forEach(([output, input], i): void => {
it(`#${i}: encodes ${input.toString()}`, (): void => {
expect(
compactToU8a(value)
compactToU8a(input)
).toEqual(
Uint8Array.from(
expected.split(' ').map((s): number => parseInt(s, 16))
)
output instanceof Uint8Array
? output
: Uint8Array.from(output.split(' ').map((s) => parseInt(s, 16)))
);
});
}
testCases.forEach(({ expected, value }): void => testEncode(value, expected));
});
});
});
+29 -81
View File
@@ -6,8 +6,32 @@
import { u8aToHex } from '../u8a/index.js';
import { floatToU8a } from './index.js';
class ExtNumber extends Number {
foo = 'bar';
}
class ExtString extends String {
foo = 'bar';
}
// NOTE Hex value outputs created via online conversion tool:
// https://www.h-schmidt.net/FloatConverter/IEEE754.html
// eslint-disable-next-line @typescript-eslint/ban-types
const TESTS: [isLe: boolean | undefined, bitLength: 32 | 64 | undefined, input: String | string | number | Number, output: string][] = [
[undefined, undefined, +0.0, '0x00000000'],
[undefined, undefined, -0.0, '0x00000080'],
[undefined, undefined, 123.456, '0x79e9f642'],
[undefined, undefined, '123.456', '0x79e9f642'],
[undefined, undefined, new ExtNumber(123.456), '0x79e9f642'],
[undefined, undefined, new ExtString(123.456), '0x79e9f642'],
[true, 32, new ExtString(123.456), '0x79e9f642'],
[true, undefined, Number.NaN, '0x0000c07f'],
[false, undefined, -0.0, '0x80000000'],
[undefined, 64, +0.0, '0x0000000000000000'],
[true, 64, -0.0, '0x0000000000000080'],
[false, 64, -0.0, '0x8000000000000000'],
[undefined, 64, Number.NaN, '0x000000000000f87f']
];
describe('floatToU8a', (): void => {
it('throws on invalid bitLength', (): void => {
@@ -16,89 +40,13 @@ describe('floatToU8a', (): void => {
).toThrow();
});
describe('32-bit', (): void => {
it('correctly encodes +0.0', (): void => {
expect(
u8aToHex(floatToU8a(+0.0))
).toEqual('0x00000000');
});
it('correctly encodes -0.0', (): void => {
expect(
u8aToHex(floatToU8a(-0.0))
).toEqual('0x00000080');
});
it('correctly encodes -0.0 (BE)', (): void => {
expect(
u8aToHex(floatToU8a(-0.0, { isLe: false }))
).toEqual('0x80000000');
});
it('encodes NaN', (): void => {
expect(
u8aToHex(floatToU8a(Number.NaN, { isLe: true }))
).toEqual('0x0000c07f');
});
describe('equivalency', (): void => {
it('encodes number 123.456', (): void => {
describe('conversion tests', (): void => {
TESTS.forEach(([isLe, bitLength, input, output], i): void => {
it(`#${i}: correctly encodes ${typeof input === 'number' ? input : input.toString()} (typeof=${typeof input})`, (): void => {
expect(
u8aToHex(floatToU8a(123.456))
).toEqual('0x79e9f642');
u8aToHex(floatToU8a(input, { bitLength, isLe }))
).toEqual(output);
});
it('encodes string 123.456', (): void => {
expect(
u8aToHex(floatToU8a('123.456'))
).toEqual('0x79e9f642');
});
it('encodes Number 123.456', (): void => {
class Test extends Number {
foo = 'bar';
}
expect(
u8aToHex(floatToU8a(new Test(123.456)))
).toEqual('0x79e9f642');
});
it('encodes String 123.456', (): void => {
class Test extends String {
foo = 'bar';
}
expect(
u8aToHex(floatToU8a(new Test('123.456')))
).toEqual('0x79e9f642');
});
});
});
describe('64-bit', (): void => {
it('correctly encodes +0.0', (): void => {
expect(
u8aToHex(floatToU8a(+0.0, { bitLength: 64 }))
).toEqual('0x0000000000000000');
});
it('correctly encodes -0.0', (): void => {
expect(
u8aToHex(floatToU8a(-0.0, { bitLength: 64, isLe: true }))
).toEqual('0x0000000000000080');
});
it('correctly encodes -0.0 (BE)', (): void => {
expect(
u8aToHex(floatToU8a(-0.0, { bitLength: 64, isLe: false }))
).toEqual('0x8000000000000000');
});
it('encodes NaN', (): void => {
expect(
u8aToHex(floatToU8a(Number.NaN, { bitLength: 64 }))
).toEqual('0x000000000000f87f');
});
});
});
+1 -1
View File
@@ -24,7 +24,7 @@ function formatValue (elapsed: number): string {
* @description Formats an elapsed value into s, m, h or day segments
*/
export function formatElapsed <ExtToBn extends ToBn> (now?: Date | null, value?: bigint | BN | ExtToBn | Date | number | null): string {
const tsNow = (now && now.getTime()) || 0;
const tsNow = now?.getTime() || 0;
const tsValue = value instanceof Date
? value.getTime()
: bnToBn(value).toNumber();
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { BufferObjConstructor } from './types.js';
import type { BufferClass } from './types.js';
import { BigInt } from '@polkadot/x-bigint';
import { xglobal } from '@polkadot/x-global';
@@ -32,7 +32,7 @@ export const hasWasm = typeof WebAssembly !== 'undefined';
// that some bundlers such as parcel would add (this is a check, not a use)
/** true if the environment has support for Buffer (typically Node.js) */
export const hasBuffer = typeof xglobal.Buffer === 'function' && typeof (xglobal.Buffer as unknown as BufferObjConstructor).isBuffer === 'function';
export const hasBuffer = typeof xglobal.Buffer === 'function' && typeof (xglobal.Buffer as unknown as BufferClass).isBuffer === 'function';
/** true if the environment has process available (typically Node.js) */
export const hasProcess = typeof xglobal.process === 'object';
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types.js';
const CHR = '0123456789abcdef';
const U8 = new Uint8Array(256);
const U16 = new Uint8Array(256 * 256);
@@ -38,7 +36,7 @@ for (let i = 0; i < 256; i++) {
* hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
* ```
*/
export function hexToU8a (value?: HexString | string | null, bitLength = -1): Uint8Array {
export function hexToU8a (value?: string | null, bitLength = -1): Uint8Array {
if (!value) {
return new Uint8Array();
}
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types.js';
/**
* @name hexToU8a
* @summary Creates a Uint8Array object from a hex string.
@@ -18,7 +16,7 @@ import type { HexString } from '../types.js';
* hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
* ```
*/
export function hexToU8a (_value?: HexString | string | null, bitLength = -1): Uint8Array {
export function hexToU8a (_value?: string | null, bitLength = -1): Uint8Array {
if (!_value) {
return new Uint8Array();
}
+1 -1
View File
@@ -5,6 +5,6 @@
* @name isArray
* @summary Tests for a Array instance.
*/
export function isArray <T> (value?: unknown): value is Array<T> {
export function isArray <T> (value?: unknown): value is T[] {
return Array.isArray(value);
}
+3 -3
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { BufferObj, BufferObjConstructor } from '../types.js';
import type { BufferClass, BufferObject } from '../types.js';
import { xglobal } from '@polkadot/x-global';
@@ -22,7 +22,7 @@ import { isFunction } from './function.js';
* console.log('isBuffer', isBuffer(Buffer.from([]))); // => true
* ```
*/
export function isBuffer (value: unknown): value is Buffer {
export function isBuffer <T = BufferObject> (value: unknown): value is T {
// we do check a function first, since it is slightly faster than isBuffer itself
return hasBuffer && !!value && isFunction((value as unknown as BufferObj).readDoubleLE) && (xglobal.Buffer as unknown as BufferObjConstructor).isBuffer(value);
return hasBuffer && !!value && isFunction((value as unknown as BufferObject).readDoubleLE) && (xglobal.Buffer as unknown as BufferClass).isBuffer(value);
}
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Constructor } from '../types.js';
import type { Class } from '../types.js';
import { isClass } from './class.js';
@@ -20,7 +20,7 @@ import { isClass } from './class.js';
* console.log('isChildClass', isChildClass(BN, Uint8Array); // => false
* ```
*/
export function isChildClass <P extends Constructor> (Parent: P, Child?: unknown): Child is P {
export function isChildClass <P extends Class> (Parent: P, Child?: unknown): Child is P {
// https://stackoverflow.com/questions/30993434/check-if-a-constructor-inherits-another-in-es6/30993664
return isClass(Child) && isClass(Parent)
// eslint-disable-next-line no-prototype-builtins
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Constructor } from '../types.js';
import type { Class } from '../types.js';
import { isOnFunction } from './helpers.js';
@@ -9,4 +9,4 @@ import { isOnFunction } from './helpers.js';
* @name isClass
* Tests if the supplied argument is a Class
*/
export const isClass: <T extends Constructor> (value?: unknown) => value is T = /*#__PURE__*/ isOnFunction('isPrototypeOf', 'hasOwnProperty');
export const isClass: <T extends Class> (value?: unknown) => value is T = /*#__PURE__*/ isOnFunction('isPrototypeOf', 'hasOwnProperty');
+2 -4
View File
@@ -3,10 +3,8 @@
import { stringify } from '../stringify.js';
interface ObjectIndexed {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[index: string]: any;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ObjectIndexed = Record<string, any>;
/**
* @name isJsonObject
+2 -4
View File
@@ -1,10 +1,8 @@
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
interface ObjectIndexed {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[index: string]: any;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ObjectIndexed = Record<string, any>;
/**
* @name isObject
+1 -3
View File
@@ -3,8 +3,6 @@
// Adapted from https://github.com/JulienPalard/is_utf8/blob/master/is_utf8.c
import type { HexString } from '../types.js';
import { u8aToU8a } from '../u8a/toU8a.js';
import { isString } from './string.js';
@@ -14,7 +12,7 @@ import { isString } from './string.js';
* @description
* Checks to see if the input string or Uint8Array is valid Utf8
*/
export function isUtf8 (value?: HexString | number[] | Uint8Array | string | null): boolean {
export function isUtf8 (value?: number[] | Uint8Array | string | null): boolean {
if (!value) {
return isString(value);
}
+11 -10
View File
@@ -7,7 +7,7 @@ import { lazyMethod, lazyMethods } from './index.js';
describe('lazyMethod', (): void => {
it('adds a key on the object', (): void => {
const test: Record<string, unknown> = {};
const test: { a?: number } = {};
expect(test.a).not.toBeDefined();
@@ -17,7 +17,7 @@ describe('lazyMethod', (): void => {
});
it('allows the name to be retrieved', (): void => {
const test: Record<string, unknown> = {};
const test: { a?: number } = {};
expect(test.a).not.toBeDefined();
@@ -27,7 +27,7 @@ describe('lazyMethod', (): void => {
});
it('calls the getter lazily', (): void => {
const test: Record<string, unknown> = {};
const test: { a?: number } = {};
const getter = jest.fn(() => 123);
expect(test.a).not.toBeDefined();
@@ -41,7 +41,7 @@ describe('lazyMethod', (): void => {
});
it('calls the getter a single time', (): void => {
const test: Record<string, unknown> = {};
const test: { a?: number } = {};
const getter = jest.fn(() => 123);
lazyMethod(test, 'a', getter);
@@ -56,15 +56,16 @@ describe('lazyMethod', (): void => {
describe('lazyMethods', (): void => {
it('sets multiple properties', (): void => {
const test: Record<string, unknown> = {};
const test: { a?: string; b?: string; c?: string } = {};
const getter = jest.fn((name: string) => name);
const set = lazyMethods(test, ['a', 'b', 'c'], getter);
expect(set.a).toEqual('a');
expect(set.b).toEqual('b');
lazyMethods(test, ['a', 'b', 'c'], getter);
expect(test.a).toEqual('a');
expect(test.b).toEqual('b');
expect(getter).toHaveBeenCalledTimes(2);
expect(set.a).toEqual('a');
expect(set.b).toEqual('b');
expect(test.a).toEqual('a');
expect(test.b).toEqual('b');
expect(getter).toHaveBeenCalledTimes(2);
});
});
+2 -2
View File
@@ -1,9 +1,9 @@
// Copyright 2017-2023 @polkadot/types authors & contributors
// Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
type AnyFn = (...args: unknown[]) => unknown;
type WithToString = { toString: () => string };
interface WithToString { toString: () => string }
/**
* @name lazyMethod
+8 -8
View File
@@ -18,11 +18,11 @@ describe('logger', (): void => {
beforeEach((): void => {
oldEnv = process.env;
process.env.NODE_ENV = 'development';
process.env['NODE_ENV'] = 'development';
ln = logger('notDebug');
process.env.DEBUG = 'test';
process.env['DEBUG'] = 'test';
l = logger('test');
@@ -114,7 +114,7 @@ describe('logger', (): void => {
});
it('does debug log when DEBUG partial specified', (): void => {
process.env.DEBUG = 'test*';
process.env['DEBUG'] = 'test*';
l = logger('testing');
l.debug('test');
@@ -127,7 +127,7 @@ describe('logger', (): void => {
});
it('does not debug log when non-matching DEBUG specified', (): void => {
process.env.DEBUG = 'blah';
process.env['DEBUG'] = 'blah';
l = logger('test');
l.debug('test');
@@ -136,7 +136,7 @@ describe('logger', (): void => {
});
it('does debug log when DEBUG=* specified', (): void => {
process.env.DEBUG = '*';
process.env['DEBUG'] = '*';
l = logger('test');
l.debug('test');
@@ -160,7 +160,7 @@ describe('logger', (): void => {
});
it('does not debug log when explicitly excluded', (): void => {
process.env.DEBUG = '*,-test';
process.env['DEBUG'] = '*,-test';
l = logger('test');
l.debug('test');
@@ -169,7 +169,7 @@ describe('logger', (): void => {
});
it('does not debug log when part of exclusion group', (): void => {
process.env.DEBUG = '*,-test:*';
process.env['DEBUG'] = '*,-test:*';
l = logger('test:sub');
l.debug('test');
@@ -178,7 +178,7 @@ describe('logger', (): void => {
});
it('does debug log when not part of exclusion groups', (): void => {
process.env.DEBUG = '*,-test:*,-tes,-a:*';
process.env['DEBUG'] = '*,-test:*,-tes,-a:*';
l = logger('test');
l.debug('test');
+2 -2
View File
@@ -122,10 +122,10 @@ function getDebugFlag (env: readonly string[], type: string): boolean {
function parseEnv (type: string): [boolean, number] {
const env = (hasProcess ? xglobal.process as { env: Record<string, string> } : {}).env || {};
const maxSize = parseInt(env.DEBUG_MAX || '-1', 10);
const maxSize = parseInt(env['DEBUG_MAX'] || '-1', 10);
return [
getDebugFlag((env.DEBUG || '').toLowerCase().split(','), type),
getDebugFlag((env['DEBUG'] || '').toLowerCase().split(','), type),
isNaN(maxSize)
? -1
: maxSize

Some files were not shown because too many files have changed in this diff Show More