Compare commits

...
40 Commits
Author SHA1 Message Date
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
124 changed files with 1650 additions and 1133 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');
+28
View File
@@ -1,5 +1,33 @@
# CHANGELOG
## 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)
1641 Jaco 12.4.1 (#1864)
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.1",
"versions": {
"git": "12.2.2",
"npm": "12.2.2"
"git": "12.4.1",
"npm": "12.4.1"
},
"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.15",
"@types/node": "^20.5.0"
},
"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.1",
"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.1",
"tslib": "^2.6.1"
},
"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.1' };
+5 -5
View File
@@ -17,12 +17,12 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "12.2.2",
"version": "12.4.1",
"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.1",
"@polkadot/util": "12.4.1",
"@zondax/ledger-substrate": "^0.41.1",
"tslib": "^2.6.1"
}
}
+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.1' };
+6 -6
View File
@@ -18,15 +18,15 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "12.2.2",
"version": "12.4.1",
"main": "index.js",
"dependencies": {
"@polkadot/util": "12.2.2",
"@polkadot/util-crypto": "12.2.2",
"tslib": "^2.5.3"
"@polkadot/util": "12.4.1",
"@polkadot/util-crypto": "12.4.1",
"tslib": "^2.6.1"
},
"peerDependencies": {
"@polkadot/util": "12.2.2",
"@polkadot/util-crypto": "12.2.2"
"@polkadot/util": "12.4.1",
"@polkadot/util-crypto": "12.4.1"
}
}
+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.1' };
+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.1",
"main": "index.js",
"dependencies": {
"@polkadot/util": "12.2.2",
"@substrate/ss58-registry": "^1.40.0",
"tslib": "^2.5.3"
"@polkadot/util": "12.4.1",
"@substrate/ss58-registry": "^1.43.0",
"tslib": "^2.6.1"
},
"devDependencies": {
"@polkadot/hw-ledger": "12.2.2"
"@polkadot/hw-ledger": "12.4.1"
}
}
@@ -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.1' };
+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.1",
"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.1",
"@polkadot/util": "12.4.1",
"@polkadot/wasm-crypto": "^7.2.2",
"@polkadot/wasm-util": "^7.2.2",
"@polkadot/x-bigint": "12.4.1",
"@polkadot/x-randomvalues": "12.4.1",
"@scure/base": "1.1.1",
"tslib": "^2.5.3"
"tslib": "^2.6.1"
},
"peerDependencies": {
"@polkadot/util": "12.2.2"
"@polkadot/util": "12.4.1"
}
}
@@ -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.1' };
+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.1",
"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.1",
"@polkadot/x-global": "12.4.1",
"@polkadot/x-textdecoder": "12.4.1",
"@polkadot/x-textencoder": "12.4.1",
"@types/bn.js": "^5.1.1",
"bn.js": "^5.2.1",
"tslib": "^2.5.3"
"tslib": "^2.6.1"
},
"devDependencies": {
"@polkadot/x-randomvalues": "12.2.2"
"@polkadot/x-randomvalues": "12.4.1"
}
}
+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);
+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
+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
+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
+1 -1
View File
@@ -40,7 +40,7 @@ export function memoize <T, F extends (...args: any[]) => T> (fn: F, { getInstan
const stringParams = stringify(args);
const instanceId = getInstanceId();
if (cache[instanceId] && cache[instanceId][stringParams] !== undefined) {
if (cache[instanceId]?.[stringParams] !== undefined) {
delete cache[instanceId][stringParams];
}
};
+8 -8
View File
@@ -8,7 +8,7 @@ import { objectProperties, objectProperty } from './index.js';
describe('objectProperty/objectProperties', (): void => {
it('sets a property', (): void => {
const test: Record<string, unknown> = {};
const test: { a?: unknown } = {};
expect(test.a).toEqual(undefined);
@@ -20,7 +20,7 @@ describe('objectProperty/objectProperties', (): void => {
});
it('does not override an existing property (record)', (): void => {
const test: Record<string, unknown> = { a: 1 };
const test = { a: 1 };
expect(test.a).toEqual(1);
@@ -34,7 +34,7 @@ describe('objectProperty/objectProperties', (): void => {
b = 1;
get a () {
return 1;
return 1 + 0;
}
}
@@ -75,7 +75,7 @@ describe('objectProperty/objectProperties', (): void => {
}
}
const test = new Child() as unknown as Record<string, unknown>;
const test = new Child() as unknown as { a: number; b: number; c?: number };
expect(test.a).toEqual(1);
expect(test.b).toEqual(1);
@@ -99,7 +99,7 @@ describe('objectProperty/objectProperties', (): void => {
}
}
const test = new Test() as unknown as Record<string, unknown>;
const test = new Test() as unknown as { a: number };
expect(test.a).toEqual(1);
});
@@ -116,14 +116,14 @@ describe('objectProperty/objectProperties', (): void => {
}
}
const test = new Test() as unknown as Record<string, unknown>;
const test = new Test() as unknown as { a: number; b: number };
expect(test.a).toEqual(1);
expect(test.b).toEqual(2);
});
it('calls back with the key name (single)', (): void => {
const test: Record<string, unknown> = {};
const test: { a?: number } = {};
const getter = jest.fn(() => 123);
objectProperty(test, 'a', getter);
@@ -134,7 +134,7 @@ describe('objectProperty/objectProperties', (): void => {
});
it('calls back with the key name & index (numtiple)', (): void => {
const test: Record<string, unknown> = {};
const test: { a?: number; b?: number; c?: number } = {};
const getter = jest.fn(() => 123);
objectProperties(test, ['a', 'b', 'c'], getter);
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/util', path: 'auto', type: 'auto', version: '12.2.2' };
export const packageInfo = { name: '@polkadot/util', path: 'auto', type: 'auto', version: '12.4.1' };
+4 -4
View File
@@ -5,7 +5,7 @@
/* global it, expect */
import { formatDecimal, formatNumber } from '../index.js';
import { formatDecimal, formatNumber, stringify } from '../index.js';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ExecFn = (...params: any[]) => unknown;
@@ -44,7 +44,7 @@ ${formatFixed(micro).padStart(NUM_PAD + PRE_PAD + 1)} μs/op`;
}
export function perf (name: string, count: number, inputs: readonly unknown[][], exec: ExecFn, withLog?: boolean): void {
const test = process.env.GITHUB_REPOSITORY
const test = process.env['GITHUB_REPOSITORY']
? it.skip
: it;
@@ -64,7 +64,7 @@ ${`${name}:`.padStart(PRE_PAD)} ${time.toFixed(2).padStart(NUM_PAD)} ms${formatO
}
export function perfCmp (name: string, [first, second]: [string, string], count: number, inputs: readonly unknown[][], exec: ExecFn): void {
const test = process.env.GITHUB_REPOSITORY
const test = process.env['GITHUB_REPOSITORY']
? it.skip
: it;
@@ -85,7 +85,7 @@ ${`${second}:`.padStart(PRE_PAD)} ${t2.toFixed(2).padStart(NUM_PAD)} ms ${t1 > t
expect(
r1.filter((_, i) =>
JSON.stringify(r1[i]) !== JSON.stringify(r2[i])
stringify(r1[i]) !== stringify(r2[i])
)
).toHaveLength(0);
});
+20 -8
View File
@@ -3,16 +3,20 @@
import type { BN } from './bn/bn.js';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export interface Constructor<T = any> {
/* eslint-disable @typescript-eslint/no-explicit-any */
export interface Class<T = any, A extends unknown[] = any[]> {
prototype: T;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
new (...args: any[]): T;
new (...args: A): T;
hasOwnProperty (prop: string): boolean;
isPrototypeOf (other: unknown): boolean;
}
// @deprecated Use Class<T, A> instead
export type Constructor<T = any, A extends unknown[] = any[]> = Class<T, A>;
export interface ToBigInt {
toBigInt: () => bigint;
}
@@ -73,20 +77,28 @@ export type HexDigit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
// One day when template strings support regex, we can improve this
export type HexString = `0x${string}`;
// BufferObj interface compatible with Buffer since we don't want to require
// BufferObject interface compatible with Buffer since we don't want to require
// references to the Buffer types from the node typings
export interface BufferObj extends Uint8Array {
//
// Caveat: the references still do sneak in in the d.ts files, specifically
// inside u8a/toBuffer & is/buffer (but not in compiled outputs)
export interface BufferObject extends Uint8Array {
// Possibly used externally via type imports
equals: (otherBuffer: Uint8Array) => boolean;
// As used in is/buffer
readDoubleLE: (offset?: number) => number;
}
// We define a scappy low-level interface to mock Buffer
// (this removes the need for the node typings in built bundles)
export interface BufferObjConstructor extends Constructor<BufferObj> {
export interface BufferClass extends Class<BufferObject> {
// As used in u8a/toBuffer
from: <T = BufferObject>(value: unknown) => T;
// As used in is/buffer
isBuffer: (value: unknown) => boolean;
}
export type U8aLike = HexString | number[] | Uint8Array | AnyString;
export type U8aLike = number[] | Uint8Array | AnyString;
export interface Observable {
next: (...params: unknown[]) => unknown;
+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';
import { u8aToU8a } from './toU8a.js';
/**
@@ -21,7 +19,7 @@ import { u8aToU8a } from './toU8a.js';
* u8aCmp(new Uint8Array([0x69, 0x65]), new Uint8Array([0x68, 0x65])); // +1
* ```
*/
export function u8aCmp (a: HexString | Uint8Array | string, b: HexString | Uint8Array | string): number {
export function u8aCmp (a: string | Uint8Array, b: string | Uint8Array): number {
const u8aa = u8aToU8a(a);
const u8ab = u8aToU8a(b);
let i = 0;
+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';
import { u8aToU8a } from './toU8a.js';
/**
@@ -19,7 +17,7 @@ import { u8aToU8a } from './toU8a.js';
* u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true
* ```
*/
export function u8aEq (a: HexString | Uint8Array | string, b: HexString | Uint8Array | string): boolean {
export function u8aEq (a: string | Uint8Array, b: string | Uint8Array): boolean {
const u8aa = u8aToU8a(a);
const u8ab = u8aToU8a(b);

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