Compare commits

...
72 Commits
Author SHA1 Message Date
github-actions[bot] 67fe7738d8 [CI Skip] release/stable 12.5.1
skip-checks: true
2023-09-15 05:53:02 +00:00
Jaco 13c6b4e553 12.5.1 (#1881) 2023-09-15 08:45:57 +03:00
github-actions[bot] 9306f9db92 [CI Skip] bump/beta 12.4.3-7-x
skip-checks: true
2023-09-14 18:24:39 +00:00
Leonardo Custodio 62a30f258e Ledger support (#1879) 2023-09-14 21:18:10 +03:00
github-actions[bot] 81609aba59 [CI Skip] bump/beta 12.4.3-6-x
skip-checks: true
2023-09-14 05:19:48 +00:00
Jaco 301d73d13f Bump deps (w/ ledger) (#1880) 2023-09-14 08:13:48 +03:00
github-actions[bot] 92abf4463d [CI Skip] bump/beta 12.4.3-5-x
skip-checks: true
2023-09-06 10:02:03 +00:00
peetzweg/ b018f78b77 adds isRiscV guard function similar to isWasm (#1878) 2023-09-06 12:55:36 +03:00
github-actions[bot] 608117f04a [CI Skip] bump/beta 12.4.3-4-x
skip-checks: true
2023-08-31 05:13:47 +00:00
Jaco 2ac00565b0 Bump deps (#1877) 2023-08-31 08:07:35 +03:00
github-actions[bot] 673a59af58 [CI Skip] bump/beta 12.4.3-3-x
skip-checks: true
2023-08-30 09:13:53 +00:00
Jaco aa394fe7cd Explicit note for test genesis (standalone or para) (#1876)
* Explicit note for test genesis (standalone or para)

* Add test for testnet exclusions

* Extract keys
2023-08-30 12:07:29 +03:00
github-actions[bot] ee7f2cc7f5 [CI Skip] bump/beta 12.4.3-2-x
skip-checks: true
2023-08-30 08:32:15 +00:00
Jaco da6efc821e Add additional comments on type interfaces (#1875) 2023-08-30 11:25:10 +03:00
github-actions[bot] a3b884d437 [CI Skip] bump/beta 12.4.3-1-x
skip-checks: true
2023-08-30 06:37:14 +00:00
Jaco 560c054750 Bump dev deps (#1874) 2023-08-30 09:31:15 +03:00
github-actions[bot] 09621d0010 [CI Skip] bump/beta 12.4.3-0-x
skip-checks: true
2023-08-24 05:17:05 +00:00
Jaco 37a81d9594 Bump deps (noble hashes/curves) (#1873)
* Bump deps (noble hashes/curves)

* Adjust dep range
2023-08-24 08:10:54 +03:00
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
149 changed files with 2202 additions and 2259 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 // SPDX-License-Identifier: Apache-2.0
module.exports = require('@polkadot/dev/config/prettier.cjs'); module.exports = require('@polkadot/dev/config/prettier.cjs');
+50
View File
@@ -1,5 +1,55 @@
# CHANGELOG # CHANGELOG
## 12.5.1 Sep 15, 2023
Contributed:
- Add `isRiskV` helper (Thanks to https://github.com/peetzweg)
- Ledger support for Enjin & Matrixchain (Thanks to https://github.com/leonardocustodio)
Changes:
- Expand interface type comments (assists in-editor helpers)
- Upgrade dependencies to latest stable versions
## 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 ## 12.2.2 Jun 4, 2023
Changes: Changes:
+4 -2
View File
@@ -1,5 +1,5 @@
1622 Jaco 12.2.2 (#1839) 1655 Jaco 12.5.1 (#1881)
12 Carlo Sala feat(networks): support ledger for pendulum (#1739) 13 Carlo Sala feat(networks): add zeitgeist Ledger support (#1840)
9 Antoine Estienne Add eth uri keyring test (#1291) 9 Antoine Estienne Add eth uri keyring test (#1291)
6 Amaury Martiny Add tests from Rust (#283) 6 Amaury Martiny Add tests from Rust (#283)
5 Jakub Pánik Add HydraDX parachain to genesis (#1583) 5 Jakub Pánik Add HydraDX parachain to genesis (#1583)
@@ -36,6 +36,7 @@
1 JesseAbram added check if valid address to docs (#440) 1 JesseAbram added check if valid address to docs (#440)
1 joe petrowski Add example for multisig address creation (#590) 1 joe petrowski Add example for multisig address creation (#590)
1 kaelnew add ledger support for stafi (#1569) 1 kaelnew add ledger support for stafi (#1569)
1 Leonardo Custodio Ledger support (#1879)
1 Lezek123 logger - wildcard include/exclude with DEBUG env (#932) 1 Lezek123 logger - wildcard include/exclude with DEBUG env (#932)
1 Mario Neises remove redudant export (#257) 1 Mario Neises remove redudant export (#257)
1 Miguel Hervas Add CFG Ledger Support (#1057) 1 Miguel Hervas Add CFG Ledger Support (#1057)
@@ -43,6 +44,7 @@
1 Mohsan Riaz Add Ternoa for ledger hardware support (#1711) 1 Mohsan Riaz Add Ternoa for ledger hardware support (#1711)
1 nahuseyoum Reserving 65 for Aventus based on the new extended range (#871) 1 nahuseyoum Reserving 65 for Aventus based on the new extended range (#871)
1 Nantian add acala ledger config (#1485) 1 Nantian add acala ledger config (#1485)
1 peetzweg/ adds `isRiscV` guard function similar to isWasm (#1878)
1 qwer951123 Add acala genesis (#1161) 1 qwer951123 Add acala genesis (#1161)
1 Raoul Millais Fix yarn add instructions in x-global README (#873) 1 Raoul Millais Fix yarn add instructions in x-global README (#873)
1 Raymond Zhong Add Edgeware ledger app (#1006) 1 Raymond Zhong Add Edgeware ledger app (#1006)
+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 // SPDX-License-Identifier: Apache-2.0
import baseConfig from '@polkadot/dev/config/eslint'; import baseConfig from '@polkadot/dev/config/eslint';
+6 -6
View File
@@ -14,10 +14,10 @@
}, },
"sideEffects": false, "sideEffects": false,
"type": "module", "type": "module",
"version": "12.2.2", "version": "12.5.1",
"versions": { "versions": {
"git": "12.2.2", "git": "12.5.1",
"npm": "12.2.2" "npm": "12.5.1"
}, },
"workspaces": [ "workspaces": [
"packages/*" "packages/*"
@@ -37,10 +37,10 @@
"test:one": "polkadot-dev-run-test --env browser" "test:one": "polkadot-dev-run-test --env browser"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/dev": "^0.75.16", "@polkadot/dev": "^0.76.25",
"@types/node": "^20.2.5" "@types/node": "^20.6.0"
}, },
"resolutions": { "resolutions": {
"typescript": "^5.1.3" "typescript": "^5.1.6"
} }
} }
+7 -7
View File
@@ -14,18 +14,18 @@
}, },
"sideEffects": false, "sideEffects": false,
"type": "module", "type": "module",
"version": "12.2.2", "version": "12.5.1",
"browser": "browser.js", "browser": "browser.js",
"main": "node.js", "main": "node.js",
"react-native": "react-native.js", "react-native": "react-native.js",
"dependencies": { "dependencies": {
"@ledgerhq/hw-transport": "^6.28.4", "@ledgerhq/hw-transport": "^6.28.8",
"@ledgerhq/hw-transport-webhid": "^6.27.15", "@ledgerhq/hw-transport-webhid": "^6.27.19",
"@ledgerhq/hw-transport-webusb": "^6.27.15", "@ledgerhq/hw-transport-webusb": "^6.27.19",
"@polkadot/util": "12.2.2", "@polkadot/util": "12.5.1",
"tslib": "^2.5.3" "tslib": "^2.6.2"
}, },
"optionalDependencies": { "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 // 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.5.1' };
+5 -5
View File
@@ -17,12 +17,12 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "12.2.2", "version": "12.5.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@polkadot/hw-ledger-transports": "12.2.2", "@polkadot/hw-ledger-transports": "12.5.1",
"@polkadot/util": "12.2.2", "@polkadot/util": "12.5.1",
"@zondax/ledger-substrate": "^0.40.7", "@zondax/ledger-substrate": "^0.41.2",
"tslib": "^2.5.3" "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 { newSubstrateApp } from '@zondax/ledger-substrate';
import { transports } from '@polkadot/hw-ledger-transports'; 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 { LEDGER_DEFAULT_ACCOUNT, LEDGER_DEFAULT_CHANGE, LEDGER_DEFAULT_INDEX, LEDGER_SUCCESS_CODE } from './constants.js';
import { ledgerApps } from './defaults.js'; import { ledgerApps } from './defaults.js';
@@ -30,6 +30,17 @@ async function wrapError <T extends WrappedResult> (promise: Promise<T>): Promis
return result; 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 * @name Ledger
* *
@@ -91,15 +102,15 @@ export class Ledger {
/** /**
* Signs a transaction on the Ledger device * 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> { public async sign (message: Uint8Array, accountOffset?: number, addressOffset?: number, options?: Partial<AccountOptions>): Promise<LedgerSignature> {
return this.withApp(async (app: SubstrateApp): Promise<LedgerSignature> => { return this.withApp(sign('sign', message, accountOffset, addressOffset, options));
const buffer = u8aToBuffer(message); }
const { signature } = await wrapError(app.sign(account + accountOffset, change, addressIndex + addressOffset, buffer));
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));
} }
/** /**
+4 -1
View File
@@ -15,6 +15,7 @@ export const ledgerApps: Record<string, string> = {
darwinia: 'Darwinia', darwinia: 'Darwinia',
'dock-mainnet': 'Dock', 'dock-mainnet': 'Dock',
edgeware: 'Edgeware', edgeware: 'Edgeware',
enjin: 'Enjin',
equilibrium: 'Equilibrium', equilibrium: 'Equilibrium',
genshiro: 'Genshiro', genshiro: 'Genshiro',
hydradx: 'HydraDX', hydradx: 'HydraDX',
@@ -22,6 +23,7 @@ export const ledgerApps: Record<string, string> = {
karura: 'Karura', karura: 'Karura',
khala: 'Khala', khala: 'Khala',
kusama: 'Kusama', kusama: 'Kusama',
matrixchain: 'Matrixchain',
nodle: 'Nodle', nodle: 'Nodle',
origintrail: 'OriginTrail', origintrail: 'OriginTrail',
parallel: 'Parallel', parallel: 'Parallel',
@@ -38,5 +40,6 @@ export const ledgerApps: Record<string, string> = {
ternoa: 'Ternoa', ternoa: 'Ternoa',
unique: 'Unique', unique: 'Unique',
vtb: 'VTB', vtb: 'VTB',
xxnetwork: 'XXNetwork' xxnetwork: 'XXNetwork',
zeitgeist: 'Zeitgeist'
}; };
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // 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.5.1' };
+6 -6
View File
@@ -18,15 +18,15 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "12.2.2", "version": "12.5.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@polkadot/util": "12.2.2", "@polkadot/util": "12.5.1",
"@polkadot/util-crypto": "12.2.2", "@polkadot/util-crypto": "12.5.1",
"tslib": "^2.5.3" "tslib": "^2.6.2"
}, },
"peerDependencies": { "peerDependencies": {
"@polkadot/util": "12.2.2", "@polkadot/util": "12.5.1",
"@polkadot/util-crypto": "12.2.2" "@polkadot/util-crypto": "12.5.1"
} }
} }
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // 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.5.1' };
+4 -5
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/keyring authors & contributors // Copyright 2017-2023 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0 // 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 { EncryptedJsonEncoding, Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { KeyringPair, KeyringPair$Json, KeyringPair$Meta, SignOptions } from '../types.js'; import type { KeyringPair, KeyringPair$Json, KeyringPair$Meta, SignOptions } from '../types.js';
import type { PairInfo } 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 => { setMeta: (additional: KeyringPair$Meta): void => {
meta = objectSpread({}, meta, additional); meta = objectSpread({}, meta, additional);
}, },
sign: (message: HexString | string | Uint8Array, options: SignOptions = {}): Uint8Array => { sign: (message: string | Uint8Array, options: SignOptions = {}): Uint8Array => {
if (isLocked(secretKey)) { if (isLocked(secretKey)) {
throw new Error('Cannot sign with a locked key pair'); 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 => { unlock: (passphrase?: string): void => {
return decodePkcs8(passphrase); 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; 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)) { if (isLocked(secretKey)) {
throw new Error('Cannot sign with a locked key pair'); 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); 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') { if (type === 'sr25519') {
return sr25519VrfVerify(message, vrfResult, publicKey, context, extra); return sr25519VrfVerify(message, vrfResult, publicKey, context, extra);
} }
+2 -3
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/keyring authors & contributors // Copyright 2017-2023 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { KeyringPair, KeyringPairs } from './types.js'; import type { KeyringPair, KeyringPairs } from './types.js';
import { isHex, isU8a, u8aToHex, u8aToU8a } from '@polkadot/util'; import { isHex, isU8a, u8aToHex, u8aToU8a } from '@polkadot/util';
@@ -22,7 +21,7 @@ export class Pairs implements KeyringPairs {
return Object.values(this.#map); 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()]; const pair = this.#map[decodeAddress(address).toString()];
if (!pair) { if (!pair) {
@@ -36,7 +35,7 @@ export class Pairs implements KeyringPairs {
return pair; return pair;
} }
public remove (address: HexString | string | Uint8Array): void { public remove (address: string | Uint8Array): void {
delete this.#map[decodeAddress(address).toString()]; delete this.#map[decodeAddress(address).toString()];
} }
} }
+1 -1
View File
@@ -119,7 +119,7 @@ function createMeta (name?: string, seed?: string) {
return { return {
isTesting: true, 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 keyring = new Keyring({ type: 'ethereum' });
const pair = keyring.createFromUri('0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133'); const pair = keyring.createFromUri('0x5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133');
expect( expect(pair?.address).toEqual(TEST_ADD);
pair && pair.address
).toEqual(TEST_ADD);
}); });
describe('checks eth test addresses', (): void => { describe('checks eth test addresses', (): void => {
@@ -62,6 +60,7 @@ describe('testingPairs', (): void => {
'0x4c42532034540267bf568198ccec4cb822a025da542861fcb146a5fab6433ff8', '0x4c42532034540267bf568198ccec4cb822a025da542861fcb146a5fab6433ff8',
'0x94c49300a58d576011096bcb006aa06f5a91b34b4383891e8029c21dc39fbb8b']; '0x94c49300a58d576011096bcb006aa06f5a91b34b4383891e8029c21dc39fbb8b'];
// @ts-expect-error We should not delete from the maps, however this is a test
delete ring.nobody; delete ring.nobody;
Object Object
+36 -3
View File
@@ -1,23 +1,56 @@
// Copyright 2017-2023 @polkadot/keyring authors & contributors // Copyright 2017-2023 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { KeypairType } from '@polkadot/util-crypto/types';
import type { KeyringOptions, KeyringPair } from './types.js'; import type { KeyringOptions, KeyringPair } from './types.js';
import { nobody } from './pair/nobody.js'; import { nobody } from './pair/nobody.js';
import { createTestKeyring } from './testing.js'; import { createTestKeyring } from './testing.js';
export interface TestKeyringMap { export interface TestKeyringMap {
nobody: KeyringPair;
[index: string]: 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 keyring = createTestKeyring(options, isDerived);
const pairs = keyring.getPairs(); const pairs = keyring.getPairs();
const map: TestKeyringMap = { nobody: nobody() }; const map: TestKeyringMap = { nobody: nobody() };
for (const p of pairs) { 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;
} }
+60 -15
View File
@@ -5,29 +5,74 @@ import type { HexString } from '@polkadot/util/types';
import type { EncryptedJson, Keypair, KeypairType, Prefix } from '@polkadot/util-crypto/types'; import type { EncryptedJson, Keypair, KeypairType, Prefix } from '@polkadot/util-crypto/types';
export interface KeyringOptions { export interface KeyringOptions {
/** /** The ss58Format to use for address encoding (defaults to 42) */
* @description The ss58Format to use for address encoding (defaults to 42)
*/
ss58Format?: Prefix; ss58Format?: Prefix;
/** /** The type of keyring to create (defaults to ed25519) */
* @description The type of keyring to create (defaults to ed25519)
*/
type?: KeypairType; 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 { export interface KeyringPair$Json extends EncryptedJson {
/** The ss58 encoded address or the hex-encoded version (the latter is for ETH-compat chains) */ /** 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 */ /** The underlying metadata associated with the keypair */
meta: KeyringPair$Meta; meta: KeyringPair$Meta;
} }
export interface SignOptions { export interface SignOptions {
/** /** Create a MultiSignature-compatible output with an indicator type */
* @description Create a MultiSignature-compatible output with an indicator type
**/
withType?: boolean; withType?: boolean;
} }
@@ -44,12 +89,12 @@ export interface KeyringPair {
encodePkcs8 (passphrase?: string): Uint8Array; encodePkcs8 (passphrase?: string): Uint8Array;
lock (): void; lock (): void;
setMeta (meta: KeyringPair$Meta): 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; toJson (passphrase?: string): KeyringPair$Json;
unlock (passphrase?: string): void; unlock (passphrase?: string): void;
verify (message: HexString | string | Uint8Array, signature: Uint8Array, signerPublic: HexString | string | Uint8Array): boolean; verify (message: string | Uint8Array, signature: Uint8Array, signerPublic: string | Uint8Array): boolean;
vrfSign (message: HexString | string | Uint8Array, context?: HexString | string | Uint8Array, extra?: HexString | string | Uint8Array): Uint8Array; vrfSign (message: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): Uint8Array;
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: string | Uint8Array, context?: string | Uint8Array, extra?: string | Uint8Array): boolean;
} }
export interface KeyringPairs { export interface KeyringPairs {
+5 -5
View File
@@ -15,14 +15,14 @@
}, },
"sideEffects": false, "sideEffects": false,
"type": "module", "type": "module",
"version": "12.2.2", "version": "12.5.1",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@polkadot/util": "12.2.2", "@polkadot/util": "12.5.1",
"@substrate/ss58-registry": "^1.40.0", "@substrate/ss58-registry": "^1.43.0",
"tslib": "^2.5.3" "tslib": "^2.6.2"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/hw-ledger": "12.2.2" "@polkadot/hw-ledger": "12.5.1"
} }
} }
+15 -4
View File
@@ -6,22 +6,33 @@
import { ledgerApps } from '@polkadot/hw-ledger/defaults'; import { ledgerApps } from '@polkadot/hw-ledger/defaults';
import { isHex } from '@polkadot/util'; import { isHex } from '@polkadot/util';
import { knownGenesis, knownLedger } from './defaults/index.js'; import { knownGenesis, knownLedger, knownTestnet } from './defaults/index.js';
describe('defaults', (): void => { describe('defaults', (): void => {
const genesisKeys = Object.keys(knownGenesis);
const ledgerKeys = Object.keys(knownLedger);
describe('genesis', (): void => { describe('genesis', (): void => {
it('has hex values for all genesis chains', (): void => { it('has hex values for all genesis chains', (): void => {
expect( expect(
Object.keys(knownGenesis).filter((network) => genesisKeys.filter((network) =>
!knownGenesis[network].length || !knownGenesis[network].length ||
knownGenesis[network].some((g) => !isHex(g, 256)) knownGenesis[network].some((g) => !isHex(g, 256))
) )
).toEqual([]); ).toEqual([]);
}); });
it('has no entries for testnets', (): void => {
expect(
genesisKeys.filter((network) =>
knownTestnet[network]
)
).toEqual([]);
});
it('has genesis for all Ledger chains', (): void => { it('has genesis for all Ledger chains', (): void => {
expect( expect(
Object.keys(knownLedger).filter((network) => ledgerKeys.filter((network) =>
!knownGenesis[network] !knownGenesis[network]
) )
).toEqual([]); ).toEqual([]);
@@ -31,7 +42,7 @@ describe('defaults', (): void => {
describe('Ledger', (): void => { describe('Ledger', (): void => {
it('has entries for each of the apps (hwledger -> networks)', (): void => { it('has entries for each of the apps (hwledger -> networks)', (): void => {
expect( expect(
Object.keys(knownLedger).filter((network) => ledgerKeys.filter((network) =>
!ledgerApps[network] !ledgerApps[network]
) )
).toEqual([]); ).toEqual([]);
+17 -4
View File
@@ -3,10 +3,14 @@
import type { KnownGenesis } from '../types.js'; import type { KnownGenesis } from '../types.js';
// NOTE: In the case where the network was hard-spooned and multiple genesisHashes // In the case where the network was hard-spooned and multiple genesisHashes
// are provided, it needs to be in reverse order, i.e. most-recent first, oldest // are provided, it needs to be in reverse order, i.e. most-recent goes first,
// last. This make lookups for the current a simple genesisHash[0] // oldest goes last. This make lookups for the current a simple genesisHash[0]
// (See Kusama as an example) // where the latest ios always the first entry (See Kusama as an example)
//
// IMPORTANT: Apart from the test relays, this list is limited to live parachains
// and live production networks. It does not and should not contain any testnets,
// either stand-alone or connected to test relays such as Westend/Rococo
export const knownGenesis: KnownGenesis = { export const knownGenesis: KnownGenesis = {
acala: [ acala: [
'0xfc41b9bd8ef8fe53d58c7ea67c794c7ec9a73daf05e6d54b14ff6342c99ba64c' '0xfc41b9bd8ef8fe53d58c7ea67c794c7ec9a73daf05e6d54b14ff6342c99ba64c'
@@ -52,6 +56,9 @@ export const knownGenesis: KnownGenesis = {
edgeware: [ edgeware: [
'0x742a2ca70c2fda6cee4f8df98d64c4c670a052d9568058982dad9d5a7a135c5b' '0x742a2ca70c2fda6cee4f8df98d64c4c670a052d9568058982dad9d5a7a135c5b'
], ],
enjin: [
'0xd8761d3c88f26dc12875c00d3165f7d67243d56fc85b4cf19937601a7916e5a9'
],
equilibrium: [ equilibrium: [
'0x6f1a800de3daff7f5e037ddf66ab22ce03ab91874debeddb1086f5f7dbd48925' '0x6f1a800de3daff7f5e037ddf66ab22ce03ab91874debeddb1086f5f7dbd48925'
], ],
@@ -82,6 +89,9 @@ export const knownGenesis: KnownGenesis = {
'0xe3777fa922cafbff200cadeaea1a76bd7898ad5b89f7848999058b50e715f636', // Kusama CC2 '0xe3777fa922cafbff200cadeaea1a76bd7898ad5b89f7848999058b50e715f636', // Kusama CC2
'0x3fd7b9eb6a00376e5be61f01abb429ffb0b104be05eaff4d458da48fcd425baf' // Kusama CC1 '0x3fd7b9eb6a00376e5be61f01abb429ffb0b104be05eaff4d458da48fcd425baf' // Kusama CC1
], ],
matrixchain: [
'0x3af4ff48ec76d2efc8476730f423ac07e25ad48f5f4c9dc39c778b164d808615'
],
nodle: [ nodle: [
'0x97da7ede98d7bad4e36b4d734b6055425a3be036da2a332ea5a7037656427a21' '0x97da7ede98d7bad4e36b4d734b6055425a3be036da2a332ea5a7037656427a21'
], ],
@@ -157,5 +167,8 @@ export const knownGenesis: KnownGenesis = {
], ],
xxnetwork: [ xxnetwork: [
'0x50dd5d206917bf10502c68fb4d18a59fc8aa31586f4e8856b493e43544aa82aa' '0x50dd5d206917bf10502c68fb4d18a59fc8aa31586f4e8856b493e43544aa82aa'
],
zeitgeist: [
'0x1bf2a2ecb4a868de66ea8610f2ce7c8c43706561b6476031315f6640fe38e060'
] ]
}; };
+4 -1
View File
@@ -19,6 +19,7 @@ export const knownLedger: KnownLedger = {
darwinia: 0x00000162, darwinia: 0x00000162,
'dock-mainnet': 0x00000252, 'dock-mainnet': 0x00000252,
edgeware: 0x0000020b, edgeware: 0x0000020b,
enjin: 0x00000483,
equilibrium: 0x05f5e0fd, equilibrium: 0x05f5e0fd,
genshiro: 0x05f5e0fc, genshiro: 0x05f5e0fc,
hydradx: 0x00000162, hydradx: 0x00000162,
@@ -26,6 +27,7 @@ export const knownLedger: KnownLedger = {
karura: 0x000002ae, karura: 0x000002ae,
khala: 0x000001b2, khala: 0x000001b2,
kusama: 0x000001b2, kusama: 0x000001b2,
matrixchain: 0x00000483,
nodle: 0x000003eb, nodle: 0x000003eb,
origintrail: 0x00000162, origintrail: 0x00000162,
parallel: 0x00000162, parallel: 0x00000162,
@@ -42,5 +44,6 @@ export const knownLedger: KnownLedger = {
ternoa: 0x00003e3, ternoa: 0x00003e3,
unique: 0x00000162, unique: 0x00000162,
vtb: 0x000002b6, 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 => { it('has a sorted list (first external, last external)', (): void => {
expect(selectableNetworks[3].displayName).toEqual('3DP network'); 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 || ( n.isIgnored = n.isTestnet || (
!( !(
o.standardAccount && o.standardAccount &&
o.decimals && o.decimals.length && o.decimals?.length &&
o.symbols && o.symbols.length o.symbols?.length
) && ) &&
o.prefix !== 42 o.prefix !== 42
); );
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // 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.5.1' };
+12 -6
View File
@@ -5,24 +5,30 @@
import known from '@substrate/ss58-registry'; import known from '@substrate/ss58-registry';
import fs from 'node:fs'; 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 => { describe('@substrate/ss58-registry', (): void => {
it('has known values', (): 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 { try {
expect(JSON.parse(json)).toEqual(other); expect(
JSON.parse(json)
).toEqual(
JSON.parse(
fs.readFileSync(testUrl, 'utf-8')
)
);
} catch (error) { } catch (error) {
if (process.env.GITHUB_REPOSITORY) { if (process.env['GITHUB_REPOSITORY']) {
console.error(json); console.error(json);
throw error; throw error;
} }
fs.writeFileSync(path.join(process.cwd(), 'packages/networks/test/ss58registry.json'), json, { flag: 'w' }); fs.writeFileSync(testUrl, json, { flag: 'w' });
} }
}); });
}); });
+10 -2
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { RegistryEntry } from '@substrate/ss58-registry'; import type { RegistryEntry } from '@substrate/ss58-registry';
import type { HexString } from '@polkadot/util/types';
export type Icon = 'beachball' | 'empty' | 'jdenticon' | 'polkadot' | 'substrate'; export type Icon = 'beachball' | 'empty' | 'jdenticon' | 'polkadot' | 'substrate';
@@ -9,22 +10,29 @@ export type KnownIcon = Record<string, Icon>;
export type KnownLedger = Record<string, number>; export type KnownLedger = Record<string, number>;
export type KnownGenesis = Record<string, string[]>; export type KnownGenesis = Record<string, HexString[]>;
export type KnownSubstrate = RegistryEntry; export type KnownSubstrate = RegistryEntry;
export type KnownTestnet = Record<string, true>; export type KnownTestnet = Record<string, true>;
export interface SubstrateNetwork extends KnownSubstrate { export interface SubstrateNetwork extends KnownSubstrate {
genesisHash: string[]; /** The genesisHash for the chain */
genesisHash: HexString[];
/** Does the chain has support for Ledger devices */
hasLedgerSupport: boolean; hasLedgerSupport: boolean;
/** The IdentityIcon to use for the chain */
icon: Icon; icon: Icon;
/** Flag set when we don't include this chain */
isIgnored: boolean; isIgnored: boolean;
/** Flag to indicate a testnet */
isTestnet: boolean; isTestnet: boolean;
/** The Ledger-specific/required slip44 for the chain */
slip44?: number | null; slip44?: number | null;
} }
export interface Network extends SubstrateNetwork { export interface Network extends SubstrateNetwork {
/** The network assigned to this chain */
network: string; network: string;
} }
+134 -6
View File
@@ -222,15 +222,13 @@
"network": "darwinia", "network": "darwinia",
"displayName": "Darwinia Network", "displayName": "Darwinia Network",
"symbols": [ "symbols": [
"RING", "RING"
"KTON"
], ],
"decimals": [ "decimals": [
9, 18
9
], ],
"standardAccount": "*25519", "standardAccount": "secp256k1",
"website": "https://darwinia.network/" "website": "https://darwinia.network"
}, },
{ {
"prefix": 19, "prefix": 19,
@@ -258,6 +256,19 @@
"standardAccount": "*25519", "standardAccount": "*25519",
"website": "https://stafi.io" "website": "https://stafi.io"
}, },
{
"prefix": 21,
"network": "karmachain",
"displayName": "Karmacoin",
"symbols": [
"KCOIN"
],
"decimals": [
6
],
"standardAccount": "*25519",
"website": "https://karmaco.in"
},
{ {
"prefix": 22, "prefix": 22,
"network": "dock-pos-mainnet", "network": "dock-pos-mainnet",
@@ -713,6 +724,19 @@
"standardAccount": "*25519", "standardAccount": "*25519",
"website": "https://hydradx.io" "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, "prefix": 65,
"network": "aventus", "network": "aventus",
@@ -1168,6 +1192,32 @@
"standardAccount": "*25519", "standardAccount": "*25519",
"website": "https://sora.org" "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, "prefix": 789,
"network": "geek", "network": "geek",
@@ -1402,6 +1452,19 @@
"standardAccount": "*25519", "standardAccount": "*25519",
"website": "https://chainflip.io/" "website": "https://chainflip.io/"
}, },
{
"prefix": 2199,
"network": "moonsama",
"displayName": "Moonsama",
"symbols": [
"SAMA"
],
"decimals": [
18
],
"standardAccount": "secp256k1",
"website": "https://moonsama.com"
},
{ {
"prefix": 2206, "prefix": 2206,
"network": "ICE", "network": "ICE",
@@ -1441,6 +1504,19 @@
"standardAccount": "*25519", "standardAccount": "*25519",
"website": "https://subspace.network" "website": "https://subspace.network"
}, },
{
"prefix": 3333,
"network": "peerplays",
"displayName": "Peerplays",
"symbols": [
"PPY"
],
"decimals": [
18
],
"standardAccount": "secp256k1",
"website": "https://www.peerplays.com/"
},
{ {
"prefix": 4006, "prefix": 4006,
"network": "tangle", "network": "tangle",
@@ -1523,6 +1599,19 @@
"standardAccount": "*25519", "standardAccount": "*25519",
"website": "https://gmordie.com" "website": "https://gmordie.com"
}, },
{
"prefix": 7306,
"network": "krigan",
"displayName": "Krigan Network",
"symbols": [
"KRGN"
],
"decimals": [
9
],
"standardAccount": "*25519",
"website": "https://krigan.network"
},
{ {
"prefix": 7391, "prefix": 7391,
"network": "unique_mainnet", "network": "unique_mainnet",
@@ -1536,6 +1625,19 @@
"standardAccount": "*25519", "standardAccount": "*25519",
"website": "https://unique.network" "website": "https://unique.network"
}, },
{
"prefix": 8866,
"network": "golden_gate",
"displayName": "Golden Gate",
"symbols": [
"GGX"
],
"decimals": [
18
],
"standardAccount": "*25519",
"website": "https://ggxchain.io/"
},
{ {
"prefix": 8883, "prefix": 8883,
"network": "sapphire_mainnet", "network": "sapphire_mainnet",
@@ -1549,6 +1651,19 @@
"standardAccount": "*25519", "standardAccount": "*25519",
"website": "https://unique.network" "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, "prefix": 9072,
"network": "hashed", "network": "hashed",
@@ -1691,5 +1806,18 @@
], ],
"standardAccount": "*25519", "standardAccount": "*25519",
"website": "https://bittensor.com" "website": "https://bittensor.com"
},
{
"prefix": 14697,
"network": "goro",
"displayName": "GORO Network",
"symbols": [
"GORO"
],
"decimals": [
9
],
"standardAccount": "*25519",
"website": "https://goro.network"
} }
] ]
+12 -12
View File
@@ -20,25 +20,25 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "12.2.2", "version": "12.5.1",
"browser": { "browser": {
"crypto": false, "crypto": false,
"stream": false "stream": false
}, },
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"@noble/curves": "1.1.0", "@noble/curves": "^1.2.0",
"@noble/hashes": "1.3.1", "@noble/hashes": "^1.3.2",
"@polkadot/networks": "12.2.2", "@polkadot/networks": "12.5.1",
"@polkadot/util": "12.2.2", "@polkadot/util": "12.5.1",
"@polkadot/wasm-crypto": "^7.2.1", "@polkadot/wasm-crypto": "^7.2.2",
"@polkadot/wasm-util": "^7.2.1", "@polkadot/wasm-util": "^7.2.2",
"@polkadot/x-bigint": "12.2.2", "@polkadot/x-bigint": "12.5.1",
"@polkadot/x-randomvalues": "12.2.2", "@polkadot/x-randomvalues": "12.5.1",
"@scure/base": "1.1.1", "@scure/base": "^1.1.3",
"tslib": "^2.5.3" "tslib": "^2.6.2"
}, },
"peerDependencies": { "peerDependencies": {
"@polkadot/util": "12.2.2" "@polkadot/util": "12.5.1"
} }
} }
@@ -1,14 +1,12 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { decodeAddress } from './decode.js'; import { decodeAddress } from './decode.js';
/** /**
* @name addressToEvm * @name addressToEvm
* @summary Converts an SS58 address to its corresponding EVM address. * @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); return decodeAddress(address, ignoreChecksum).subarray(0, 20);
} }
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js'; import type { Prefix } from './types.js';
import { base58Decode } from '../base58/index.js'; import { base58Decode } from '../base58/index.js';
@@ -14,7 +13,7 @@ import { defaults } from './defaults.js';
* @description * @description
* From the provided input, validate that the address is a valid input. * 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; let decoded;
try { try {
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js'; import type { Prefix } from './types.js';
// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L6 // 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 { checkAddressChecksum } from './checksum.js';
import { defaults } from './defaults.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) { if (!encoded) {
throw new Error('Invalid empty address passed'); throw new Error('Invalid empty address passed');
} }
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { DeriveJunction } from '../key/DeriveJunction.js'; import type { DeriveJunction } from '../key/DeriveJunction.js';
import type { Prefix } from './types.js'; import type { Prefix } from './types.js';
@@ -20,7 +19,7 @@ function filterHard ({ isHard }: DeriveJunction): boolean {
* @description * @description
* Creates a sr25519 derived address based on the input address/publicKey and the uri supplied. * 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); const { path } = keyExtractPath(suri);
if (!path.length || path.every(filterHard)) { if (!path.length || path.every(filterHard)) {
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js'; import type { Prefix } from './types.js';
// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L34 // 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 { defaults } from './defaults.js';
import { sshash } from './sshash.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 // decode it, this means we can re-encode an address
const u8a = decodeAddress(key); const u8a = decodeAddress(key);
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util'; import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js'; import type { Prefix } from './types.js';
import { decodeAddress } from './decode.js'; import { decodeAddress } from './decode.js';
@@ -15,6 +14,6 @@ import { createKeyDerived } from './keyDerived.js';
* @description * @description
* Creates a Substrate derived address based on the input address/publicKey and the index supplied. * 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); return encodeAddress(createKeyDerived(decodeAddress(who), index), ss58Format);
} }
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util'; import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js'; import type { Prefix } from './types.js';
import { encodeAddress } from './encode.js'; import { encodeAddress } from './encode.js';
@@ -14,6 +13,6 @@ import { createKeyMulti } from './keyMulti.js';
* @description * @description
* Creates a Substrate multisig address based on the input address and the required threshold. * 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); return encodeAddress(createKeyMulti(who, threshold), ss58Format);
} }
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aEq } from '@polkadot/util'; import { u8aEq } from '@polkadot/util';
import { decodeAddress } from './decode.js'; import { decodeAddress } from './decode.js';
@@ -21,6 +19,6 @@ import { decodeAddress } from './decode.js';
* u8aEq(new Uint8Array([0x68, 0x65]), new Uint8Array([0x68, 0x65])); // true * 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)); return u8aEq(decodeAddress(a), decodeAddress(b));
} }
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { HashType } from '../secp256k1/types.js'; import type { HashType } from '../secp256k1/types.js';
import type { Prefix } from './types.js'; import type { Prefix } from './types.js';
@@ -14,7 +13,7 @@ import { encodeAddress } from './encode.js';
* @name evmToAddress * @name evmToAddress
* @summary Converts an EVM address to its corresponding SS58 address. * @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); const message = u8aConcat('evm:', evmAddress);
if (message.length !== 24) { if (message.length !== 24) {
+1 -2
View File
@@ -1,12 +1,11 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js'; import type { Prefix } from './types.js';
import { validateAddress } from './validate.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 { try {
return validateAddress(address, ignoreChecksum, ss58Format); return validateAddress(address, ignoreChecksum, ss58Format);
} catch { } catch {
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util'; import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import { bnToU8a, stringToU8a, u8aConcat } from '@polkadot/util'; import { bnToU8a, stringToU8a, u8aConcat } from '@polkadot/util';
@@ -12,7 +11,7 @@ import { decodeAddress } from './decode.js';
const PREFIX = stringToU8a('modlpy/utilisuba'); 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( return blake2AsU8a(
u8aConcat( u8aConcat(
PREFIX, PREFIX,
+1 -2
View File
@@ -2,7 +2,6 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { BN } from '@polkadot/util'; import type { BN } from '@polkadot/util';
import type { HexString } from '@polkadot/util/types';
import { bnToU8a, compactToU8a, stringToU8a, u8aConcat, u8aSorted } from '@polkadot/util'; import { bnToU8a, compactToU8a, stringToU8a, u8aConcat, u8aSorted } from '@polkadot/util';
@@ -12,7 +11,7 @@ import { addressToU8a } from './util.js';
const PREFIX = stringToU8a('modlpy/utilisuba'); 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( return blake2AsU8a(
u8aConcat( u8aConcat(
PREFIX, PREFIX,
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util authors & contributors // Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js'; import type { Prefix } from './types.js';
import { u8aSorted } from '@polkadot/util'; import { u8aSorted } from '@polkadot/util';
@@ -9,7 +8,7 @@ import { u8aSorted } from '@polkadot/util';
import { encodeAddress } from './encode.js'; import { encodeAddress } from './encode.js';
import { addressToU8a } from './util.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); const u8aToAddress = (u8a: Uint8Array) => encodeAddress(u8a, ss58Format);
return u8aSorted( return u8aSorted(
+1 -2
View File
@@ -1,11 +1,10 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Prefix } from './types.js'; import type { Prefix } from './types.js';
import { decodeAddress } from './decode.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); return !!decodeAddress(encoded, ignoreChecksum, ss58Format);
} }
+14 -8
View File
@@ -19,6 +19,7 @@ interface Config {
ipfs?: string; ipfs?: string;
regex?: RegExp; regex?: RegExp;
type: string; type: string;
withPadding?: boolean;
} }
type DecodeFn = (value: string, ipfsCompat?: boolean) => Uint8Array; type DecodeFn = (value: string, ipfsCompat?: boolean) => Uint8Array;
@@ -63,21 +64,26 @@ export function createIs (validate: ValidateFn): ValidateFn {
} }
/** @internal */ /** @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 => { return (value?: unknown, ipfsCompat?: boolean): value is string => {
if (typeof value !== 'string') { if (typeof value !== 'string') {
throw new Error(`Expected ${type} string input`); 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}'`); throw new Error(`Expected ipfs-compatible ${type} to start with '${ipfs}'`);
} }
for (let i = (ipfsCompat ? 1 : 0), count = value.length; i < count; i++) { for (let i = (ipfsCompat ? 1 : 0), count = value.length; i < count; i++) {
if (!(chars.includes(value[i]) || ( if (chars.includes(value[i])) {
value[i] === '=' && ( // all ok, character found
(i === value.length - 1) || } else if (withPadding && value[i] === '=') {
!chars.includes(value[i + 1]) 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}`); 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 = { const config = {
chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
coder: base64, coder: base64,
type: 'base64' type: 'base64',
withPadding: true
}; };
/** /**
+1 -1
View File
@@ -6,7 +6,7 @@
* @description Trims padding characters * @description Trims padding characters
*/ */
export function base64Trim (value: string): string { export function base64Trim (value: string): string {
while (value.length && value[value.length - 1] === '=') { while (value.length && value.endsWith('=')) {
value = value.slice(0, -1); value = value.slice(0, -1);
} }
@@ -11,4 +11,22 @@ describe('base64Validate', (): void => {
() => base64Validate('aGVsbG8gd29ybGQg0J/RgNC40LLQtd^GC0YHRgtCy0YPRjiDQvNC4IOS9oOWlvQ==') () => base64Validate('aGVsbG8gd29ybGQg0J/RgNC40LLQtd^GC0YHRgtCy0YPRjiDQvNC4IOS9oOWlvQ==')
).toThrow(/Invalid base64 character "\^" \(0x5e\) at index 30/); ).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 // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { blake2b as blake2bJs } from '@noble/hashes/blake2b'; import { blake2b as blake2bJs } from '@noble/hashes/blake2b';
import { hasBigInt, u8aToU8a } from '@polkadot/util'; 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] * 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 byteLength = Math.ceil(bitLength / 8);
const u8a = u8aToU8a(data); const u8a = u8aToU8a(data);
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types.js'; import type { Keypair } from '../types.js';
import { ed25519 } from '@noble/curves/ed25519'; import { ed25519 } from '@noble/curves/ed25519';
@@ -23,7 +22,7 @@ import { ed25519Sign as wasmSign, isReady } from '@polkadot/wasm-crypto';
* ed25519Sign([...], [...]); // => [...] * 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) { if (!secretKey) {
throw new Error('Expected a valid secretKey'); throw new Error('Expected a valid secretKey');
} else if (!publicKey) { } else if (!publicKey) {
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { ed25519 } from '@noble/curves/ed25519'; import { ed25519 } from '@noble/curves/ed25519';
import { hasBigInt, u8aToU8a } from '@polkadot/util'; import { hasBigInt, u8aToU8a } from '@polkadot/util';
@@ -22,7 +20,7 @@ import { ed25519Verify as wasmVerify, isReady } from '@polkadot/wasm-crypto';
* ed25519Verify([...], [...], [...]); // => true/false * 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 messageU8a = u8aToU8a(message);
const publicKeyU8a = u8aToU8a(publicKey); const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature); const signatureU8a = u8aToU8a(signature);
+1 -1
View File
@@ -16,7 +16,7 @@ function getH160 (u8a: Uint8Array): Uint8Array {
return u8a.slice(-20); return u8a.slice(-20);
} }
export function ethereumEncode (addressOrPublic?: HexString | string | Uint8Array): HexString { export function ethereumEncode (addressOrPublic?: string | Uint8Array): HexString {
if (!addressOrPublic) { if (!addressOrPublic) {
return '0x'; return '0x';
} }
@@ -1,13 +1,11 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { isHex } from '@polkadot/util'; import { isHex } from '@polkadot/util';
import { isEthereumChecksum } from './isChecksum.js'; 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)) { if (!address || address.length !== 42 || !isHex(address)) {
return false; return false;
} else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) { } 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 */ /** @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 { export function createBitHasher (bitLength: 256 | 512, fn: (data: string | Uint8Array, bitLength: 256 | 512, onlyJs?: boolean) => Uint8Array): (data: string | Uint8Array, onlyJs?: boolean) => Uint8Array {
return (data: HexString | Uint8Array | string, onlyJs?: boolean): Uint8Array => return (data: string | Uint8Array, onlyJs?: boolean): Uint8Array =>
fn(data, bitLength, onlyJs); fn(data, bitLength, onlyJs);
} }
/** @internal */ /** @internal */
export function createDualHasher (wa: DualHash, js: DualHash): (value: HexString | Uint8Array | string, bitLength?: 256 | 512, onlyJs?: boolean) => Uint8Array { export function createDualHasher (wa: DualHash, js: DualHash): (value: string | Uint8Array, bitLength?: 256 | 512, onlyJs?: boolean) => Uint8Array {
return (value: HexString | Uint8Array | string, bitLength: 256 | 512 = 256, onlyJs?: boolean): Uint8Array => { return (value: string | Uint8Array, bitLength: 256 | 512 = 256, onlyJs?: boolean): Uint8Array => {
const u8a = u8aToU8a(value); const u8a = u8aToU8a(value);
return !hasBigInt || (!onlyJs && isReady()) return !hasBigInt || (!onlyJs && isReady())
+6 -3
View File
@@ -1,19 +1,22 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
export type EncryptedJsonVersion = '0' | '1' | '2' | '3'; export type EncryptedJsonVersion = '0' | '1' | '2' | '3';
export type EncryptedJsonEncoding = 'none' | 'scrypt' | 'xsalsa20-poly1305'; export type EncryptedJsonEncoding = 'none' | 'scrypt' | 'xsalsa20-poly1305';
export interface EncryptedJsonDescriptor { export interface EncryptedJsonDescriptor {
/** Descriptor for the content */
content: string[]; content: string[];
/** The encoding (in current/latest versions this is always an array) */
type: EncryptedJsonEncoding | EncryptedJsonEncoding[]; type: EncryptedJsonEncoding | EncryptedJsonEncoding[];
/** The version of encoding applied */
version: EncryptedJsonVersion; version: EncryptedJsonVersion;
} }
export interface EncryptedJson { export interface EncryptedJson {
encoded: HexString | string; /** The encoded string */
encoded: string;
/** The encoding used */
encoding: EncryptedJsonDescriptor; encoding: EncryptedJsonDescriptor;
} }
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // 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 { BN, bnToU8a, compactAddLength, hexToU8a, isBigInt, isBn, isHex, isNumber, isString, stringToU8a } from '@polkadot/util';
import { blake2AsU8a } from '../blake2/asU8a.js'; import { blake2AsU8a } from '../blake2/asU8a.js';
@@ -46,7 +44,7 @@ export class DeriveJunction {
return !this.#isHard; 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(); return this.soft(value).harden();
} }
@@ -56,7 +54,7 @@ export class DeriveJunction {
return this; 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)) { if (isNumber(value) || isBn(value) || isBigInt(value)) {
return this.soft(bnToU8a(value, BN_LE_256_OPTS)); return this.soft(bnToU8a(value, BN_LE_256_OPTS));
} else if (isHex(value)) { } else if (isHex(value)) {
+1 -1
View File
@@ -6,7 +6,7 @@ import { DeriveJunction } from './DeriveJunction.js';
const RE_JUNCTION = /\/(\/?)([^/]+)/g; const RE_JUNCTION = /\/(\/?)([^/]+)/g;
export interface ExtractResult { export interface ExtractResult {
parts: null | string[]; parts: string[] | null;
path: DeriveJunction[]; path: DeriveJunction[];
} }
+1 -1
View File
@@ -25,7 +25,7 @@ export function keyExtractSuri (suri: string): ExtractResult {
throw new Error('Unable to match provided value to a secret URI'); throw new Error('Unable to match provided value to a secret URI');
} }
const [, phrase, , derivePath, , , password] = matches as string[]; const [, phrase, , derivePath, , , password] = matches;
const { path } = keyExtractPath(derivePath); const { path } = keyExtractPath(derivePath);
return { return {
+2 -2
View File
@@ -81,7 +81,7 @@ export function mnemonicToEntropy (mnemonic: string, wordlist: string[] = DEFAUL
// calculate the checksum and compare // calculate the checksum and compare
const matched = entropyBits.match(/(.{1,8})/g); 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)) { if (!entropyBytes || (entropyBytes.length % 4 !== 0) || (entropyBytes.length < 16) || (entropyBytes.length > 32)) {
throw new Error(INVALID_ENTROPY); 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 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)) { if (!mapped || (mapped.length < 12)) {
throw new Error('Unable to map entropy to mnemonic'); throw new Error('Unable to map entropy to mnemonic');
@@ -136,7 +136,7 @@ describe('tweetnacl/secretbox', (): void => {
}); });
describe('tweetnacl/test/04-secretbox.js', (): 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]; const [keyBase64, nonceBase64, msgBase64, expBase64] = TEST_DATA[i];
it(`is ok on "${msgBase64}"`, (): void => { 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 { 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)) if (!(args[i] instanceof Uint8Array))
throw new TypeError('unexpected type, use Uint8Array'); throw new TypeError('unexpected type, use Uint8Array');
} }
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev // 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.5.1' };
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { pbkdf2 as pbkdf2Js } from '@noble/hashes/pbkdf2'; import { pbkdf2 as pbkdf2Js } from '@noble/hashes/pbkdf2';
import { sha512 } from '@noble/hashes/sha512'; import { sha512 } from '@noble/hashes/sha512';
@@ -17,7 +15,7 @@ interface Result {
salt: Uint8Array; 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 u8aPass = u8aToU8a(passphrase);
const u8aSalt = u8aToU8a(salt); const u8aSalt = u8aToU8a(salt);
+3 -1
View File
@@ -1,7 +1,9 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export const DEFAULT_PARAMS = { import type { ScryptParams } from './types.js';
export const DEFAULT_PARAMS: ScryptParams = {
N: 1 << 15, N: 1 << 15,
p: 1, p: 1,
r: 8 r: 8
+3 -4
View File
@@ -1,8 +1,7 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types'; import type { ScryptParams } from './types.js';
import type { Params } from './types.js';
import { scrypt as scryptJs } from '@noble/hashes/scrypt'; import { scrypt as scryptJs } from '@noble/hashes/scrypt';
@@ -13,12 +12,12 @@ import { randomAsU8a } from '../random/asU8a.js';
import { DEFAULT_PARAMS } from './defaults.js'; import { DEFAULT_PARAMS } from './defaults.js';
interface Result { interface Result {
params: Params, params: ScryptParams,
password: Uint8Array; password: Uint8Array;
salt: Uint8Array; 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); const u8a = u8aToU8a(passphrase);
return { return {
+6 -5
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { Params } from './types.js'; import type { ScryptParams } from './types.js';
import { u8aToBn } from '@polkadot/util'; import { u8aToBn } from '@polkadot/util';
@@ -9,7 +9,7 @@ import { BN_LE_OPTS } from '../bn.js';
import { DEFAULT_PARAMS } from './defaults.js'; import { DEFAULT_PARAMS } from './defaults.js';
interface Result { interface Result {
params: Params, params: ScryptParams,
salt: Uint8Array; salt: Uint8Array;
} }
@@ -19,9 +19,10 @@ export function scryptFromU8a (data: Uint8Array): Result {
const p = u8aToBn(data.subarray(32 + 4, 32 + 8), BN_LE_OPTS).toNumber(); const p = u8aToBn(data.subarray(32 + 4, 32 + 8), BN_LE_OPTS).toNumber();
const r = u8aToBn(data.subarray(32 + 8, 32 + 12), BN_LE_OPTS).toNumber(); const r = u8aToBn(data.subarray(32 + 8, 32 + 12), BN_LE_OPTS).toNumber();
// FIXME At this moment we assume these to be fixed params, this is not a great idea since we lose flexibility // FIXME At this moment we assume these to be fixed params, this is not a great idea
// and updates for greater security. However we need some protection against carefully-crafted params that can // since we lose flexibility and updates for greater security. However we need some
// eat up CPU since these are user inputs. So we need to get very clever here, but atm we only allow the defaults // protection against carefully-crafted params that can eat up CPU since these are user
// inputs. So we need to get very clever here, but atm we only allow the defaults
// and if no match, bail out // and if no match, bail out
if (N !== DEFAULT_PARAMS.N || p !== DEFAULT_PARAMS.p || r !== DEFAULT_PARAMS.r) { if (N !== DEFAULT_PARAMS.N || p !== DEFAULT_PARAMS.p || r !== DEFAULT_PARAMS.r) {
throw new Error('Invalid injected scrypt params found'); throw new Error('Invalid injected scrypt params found');
+2 -2
View File
@@ -1,13 +1,13 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { Params } from './types.js'; import type { ScryptParams } from './types.js';
import { bnToU8a, u8aConcat } from '@polkadot/util'; import { bnToU8a, u8aConcat } from '@polkadot/util';
import { BN_LE_32_OPTS } from '../bn.js'; import { BN_LE_32_OPTS } from '../bn.js';
export function scryptToU8a (salt: Uint8Array, { N, p, r }: Params): Uint8Array { export function scryptToU8a (salt: Uint8Array, { N, p, r }: ScryptParams): Uint8Array {
return u8aConcat( return u8aConcat(
salt, salt,
bnToU8a(N, BN_LE_32_OPTS), bnToU8a(N, BN_LE_32_OPTS),
+2 -1
View File
@@ -1,7 +1,8 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
export interface Params { /** The params that control scrypt generation */
export interface ScryptParams {
N: number; N: number;
p: number; p: number;
r: number; r: number;
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { HashType } from './types.js'; import type { HashType } from './types.js';
import { secp256k1 } from '@noble/curves/secp256k1'; import { secp256k1 } from '@noble/curves/secp256k1';
@@ -16,7 +15,7 @@ import { secp256k1Expand } from './expand.js';
* @name secp256k1Recover * @name secp256k1Recover
* @description Recovers a publicKey from the supplied signature * @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 sig = u8aToU8a(signature).subarray(0, 64);
const msg = u8aToU8a(msgHash); const msg = u8aToU8a(msgHash);
const publicKey = !hasBigInt || (!onlyJs && isReady()) const publicKey = !hasBigInt || (!onlyJs && isReady())
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { HashType } from './types.js'; import type { HashType } from './types.js';
import { u8aEq, u8aToU8a } from '@polkadot/util'; import { u8aEq, u8aToU8a } from '@polkadot/util';
@@ -13,7 +12,7 @@ import { secp256k1Recover } from './recover.js';
* @name secp256k1Verify * @name secp256k1Verify
* @description Verifies the signature of `message`, using the supplied pair * @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); const sig = u8aToU8a(signature);
if (sig.length !== 65) { if (sig.length !== 65) {
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { KeypairType, VerifyResult } from '../types.js'; import type { KeypairType, VerifyResult } from '../types.js';
import { u8aIsWrapped, u8aToU8a, u8aUnwrapBytes, u8aWrapBytes } from '@polkadot/util'; import { u8aIsWrapped, u8aToU8a, u8aUnwrapBytes, u8aWrapBytes } from '@polkadot/util';
@@ -87,7 +86,7 @@ function getVerifyFn (signature: Uint8Array): VerifyFn {
: verifyDetect; : 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); const signatureU8a = u8aToU8a(signature);
if (![64, 65, 66].includes(signatureU8a.length)) { if (![64, 65, 66].includes(signatureU8a.length)) {
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util'; import { u8aToU8a } from '@polkadot/util';
import { sr25519Agree } from '@polkadot/wasm-crypto'; import { sr25519Agree } from '@polkadot/wasm-crypto';
@@ -10,7 +8,7 @@ import { sr25519Agree } from '@polkadot/wasm-crypto';
* @name sr25519Agreement * @name sr25519Agreement
* @description Key agreement between other's public key and self secret key * @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 secretKeyU8a = u8aToU8a(secretKey);
const publicKeyU8a = u8aToU8a(publicKey); const publicKeyU8a = u8aToU8a(publicKey);
@@ -1,12 +1,10 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { isU8a, u8aToU8a } from '@polkadot/util'; import { isU8a, u8aToU8a } from '@polkadot/util';
import { sr25519DerivePublicSoft } from '@polkadot/wasm-crypto'; 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); const publicKeyU8a = u8aToU8a(publicKey);
if (!isU8a(chainCode) || chainCode.length !== 32) { if (!isU8a(chainCode) || chainCode.length !== 32) {
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../../types.js'; import type { Keypair } from '../../types.js';
import { u8aToU8a } from '@polkadot/util'; import { u8aToU8a } from '@polkadot/util';
@@ -13,7 +12,7 @@ import { sr25519PairFromU8a } from './fromU8a.js';
* @name sr25519PairFromSeed * @name sr25519PairFromSeed
* @description Returns a object containing a `publicKey` & `secretKey` generated from the supplied seed. * @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); const seedU8a = u8aToU8a(seed);
if (seedU8a.length !== 32) { if (seedU8a.length !== 32) {
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../../types.js'; import type { Keypair } from '../../types.js';
import { u8aToU8a } from '@polkadot/util'; import { u8aToU8a } from '@polkadot/util';
@@ -10,7 +9,7 @@ const SEC_LEN = 64;
const PUB_LEN = 32; const PUB_LEN = 32;
const TOT_LEN = SEC_LEN + PUB_LEN; 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); const fullU8a = u8aToU8a(full);
if (fullU8a.length !== TOT_LEN) { if (fullU8a.length !== TOT_LEN) {
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types.js'; import type { Keypair } from '../types.js';
import { u8aToU8a } from '@polkadot/util'; import { u8aToU8a } from '@polkadot/util';
@@ -11,7 +10,7 @@ import { sr25519Sign as wasmSign } from '@polkadot/wasm-crypto';
* @name sr25519Sign * @name sr25519Sign
* @description Returns message signature of `message`, using the supplied pair * @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) { if (publicKey?.length !== 32) {
throw new Error('Expected a valid publicKey, 32-bytes'); throw new Error('Expected a valid publicKey, 32-bytes');
} else if (secretKey?.length !== 64) { } else if (secretKey?.length !== 64) {
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util'; import { u8aToU8a } from '@polkadot/util';
import { sr25519Verify as wasmVerify } from '@polkadot/wasm-crypto'; import { sr25519Verify as wasmVerify } from '@polkadot/wasm-crypto';
@@ -10,7 +8,7 @@ import { sr25519Verify as wasmVerify } from '@polkadot/wasm-crypto';
* @name sr25519Verify * @name sr25519Verify
* @description Verifies the signature of `message`, using the supplied pair * @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 publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature); const signatureU8a = u8aToU8a(signature);
+1 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types.js'; import type { Keypair } from '../types.js';
import { u8aToU8a } from '@polkadot/util'; import { u8aToU8a } from '@polkadot/util';
@@ -13,7 +12,7 @@ const EMPTY_U8A = new Uint8Array();
* @name sr25519VrfSign * @name sr25519VrfSign
* @description Sign with sr25519 vrf signing (deterministic) * @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) { if (secretKey?.length !== 64) {
throw new Error('Invalid secretKey, expected 64-bytes'); throw new Error('Invalid secretKey, expected 64-bytes');
} }
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { u8aToU8a } from '@polkadot/util'; import { u8aToU8a } from '@polkadot/util';
import { vrfVerify } from '@polkadot/wasm-crypto'; import { vrfVerify } from '@polkadot/wasm-crypto';
@@ -12,7 +10,7 @@ const EMPTY_U8A = new Uint8Array();
* @name sr25519VrfVerify * @name sr25519VrfVerify
* @description Verify with sr25519 vrf verification * @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 publicKeyU8a = u8aToU8a(publicKey);
const proofU8a = u8aToU8a(signOutput); const proofU8a = u8aToU8a(signOutput);
+9
View File
@@ -5,20 +5,29 @@ export * from './address/types.js';
export * from './json/types.js'; export * from './json/types.js';
export interface Keypair { export interface Keypair {
/** The publicKey for this pair */
publicKey: Uint8Array; publicKey: Uint8Array;
/** The secretKey for this pair */
secretKey: Uint8Array; secretKey: Uint8Array;
} }
export interface Seedpair { export interface Seedpair {
/** The publicKey for this pair */
publicKey: Uint8Array; publicKey: Uint8Array;
/** The seed used to construct the pair */
seed: Uint8Array; seed: Uint8Array;
} }
/** The supported types of pairs */
export type KeypairType = 'ed25519' | 'sr25519' | 'ecdsa' | 'ethereum'; export type KeypairType = 'ed25519' | 'sr25519' | 'ecdsa' | 'ethereum';
export interface VerifyResult { export interface VerifyResult {
/** The detected crypto interface, or 'none' if not detected */
crypto: 'none' | KeypairType; crypto: 'none' | KeypairType;
/** The validity for this result, false if invalid */
isValid: boolean; isValid: boolean;
/** Flag to indicate if the passed data was wrapped in <Bytes>...</Bytes> */
isWrapped: boolean; isWrapped: boolean;
/** The extracted publicKey */
publicKey: Uint8Array; publicKey: Uint8Array;
} }
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util-crypto authors & contributors // Copyright 2017-2023 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '@polkadot/util/types';
import { hasBigInt, u8aToU8a } from '@polkadot/util'; import { hasBigInt, u8aToU8a } from '@polkadot/util';
import { isReady, twox } from '@polkadot/wasm-crypto'; import { isReady, twox } from '@polkadot/wasm-crypto';
@@ -23,7 +21,7 @@ import { xxhash64 } from './xxhash64.js';
* xxhashAsU8a('abc'); // => 0x44bc2cf5ad770999 * 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 rounds = Math.ceil(bitLength / 64);
const u8a = u8aToU8a(data); const u8a = u8aToU8a(data);
+7 -7
View File
@@ -18,7 +18,7 @@
"./detectPackage.cjs" "./detectPackage.cjs"
], ],
"type": "module", "type": "module",
"version": "12.2.2", "version": "12.5.1",
"main": "index.js", "main": "index.js",
"exports": { "exports": {
"./hex/toU8a": { "./hex/toU8a": {
@@ -35,15 +35,15 @@
} }
}, },
"dependencies": { "dependencies": {
"@polkadot/x-bigint": "12.2.2", "@polkadot/x-bigint": "12.5.1",
"@polkadot/x-global": "12.2.2", "@polkadot/x-global": "12.5.1",
"@polkadot/x-textdecoder": "12.2.2", "@polkadot/x-textdecoder": "12.5.1",
"@polkadot/x-textencoder": "12.2.2", "@polkadot/x-textencoder": "12.5.1",
"@types/bn.js": "^5.1.1", "@types/bn.js": "^5.1.1",
"bn.js": "^5.2.1", "bn.js": "^5.2.1",
"tslib": "^2.5.3" "tslib": "^2.6.2"
}, },
"devDependencies": { "devDependencies": {
"@polkadot/x-randomvalues": "12.2.2" "@polkadot/x-randomvalues": "12.5.1"
} }
} }
+3 -2
View File
@@ -3,6 +3,7 @@
/// <reference types="@polkadot/dev-test/globals.d.ts" /> /// <reference types="@polkadot/dev-test/globals.d.ts" />
import { stringify } from '../stringify.js';
import { perf } from '../test/index.js'; import { perf } from '../test/index.js';
import { arrayRange, arrayShuffle } from './index.js'; import { arrayRange, arrayShuffle } from './index.js';
@@ -30,8 +31,8 @@ describe('arrayShuffle', (): void => {
inp.filter((v) => !out.includes(v)) inp.filter((v) => !out.includes(v))
).toEqual([]); ).toEqual([]);
expect( expect(
JSON.stringify(inp) stringify(inp)
).not.toEqual(JSON.stringify(out)); ).not.toEqual(stringify(out));
}); });
perf('arrayShuffle', 1000, [[ptest]], arrayShuffle); 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'; import { _sqrt2pow53n, nSqrt } from './index.js';
// eslint-disable-next-line jest/no-export // 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], [0, 0],
[1, 1], [1, 1],
[4, 2], [4, 2],
@@ -47,11 +47,13 @@ describe('nSqrt', (): void => {
).toEqual(true); ).toEqual(true);
}); });
SQRT_TESTS.forEach(([value, expected], index): void => { describe('conversion tests', (): void => {
it(`calcs for test #${index}`, (): void => { TESTS.forEach(([value, expected], i): void => {
expect( it(`#${i}: calcs ${expected}`, (): void => {
nSqrt(value) === BigInt(expected) expect(
).toEqual(true); nSqrt(value) === BigInt(expected)
).toEqual(true);
});
}); });
}); });
}); });
+2 -2
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { BN } from '../bn/bn.js'; 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'; import { BigInt } from '@polkadot/x-bigint';
@@ -16,7 +16,7 @@ import { isToBn } from '../is/toBn.js';
* @name nToBigInt * @name nToBigInt
* @summary Creates a bigInt value from a BN, bigint, string (base 10 or hex) or number input. * @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' return typeof value === 'bigint'
? value ? value
: !value : !value
+55 -18
View File
@@ -7,9 +7,64 @@ import { arrayRange } from '../array/index.js';
import { perf } from '../test/index.js'; import { perf } from '../test/index.js';
import { nToU8a } from './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]); const ptest = arrayRange(65536).map((v) => [v]);
describe('nToU8a', (): void => { 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 => { it('converts null values to 0x00', (): void => {
expect( expect(
nToU8a(null) nToU8a(null)
@@ -40,23 +95,5 @@ describe('nToU8a', (): void => {
).toEqual(new Uint8Array([0x56, 0x34, 0x12, 0x00])); ).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); 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 { function toU8a (value: bigint, isLe: boolean, isNegative: boolean): Uint8Array {
const arr: number[] = []; const arr: number[] = [];
const withSigned = isNegative && (value < _0n);
if (isNegative) { if (withSigned) {
value = (value + _1n) * -_1n; value = (value + _1n) * -_1n;
} }
while (value !== _0n) { while (value !== _0n) {
const mod = value % DIV; const mod = value % DIV;
const val = Number( const val = Number(
isNegative withSigned
? mod ^ NEG_MASK ? mod ^ NEG_MASK
: mod : mod
); );
+8 -6
View File
@@ -3,7 +3,7 @@
/// <reference types="@polkadot/dev-test/globals.d.ts" /> /// <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'; import { BN, BN_SQRT_MAX_INTEGER, bnSqrt } from './index.js';
describe('bnSqrt', (): void => { describe('bnSqrt', (): void => {
@@ -25,11 +25,13 @@ describe('bnSqrt', (): void => {
).toEqual(true); ).toEqual(true);
}); });
SQRT_TESTS.forEach(([value, expected], index): void => { describe('conversion tests', (): void => {
it(`calcs for test #${index}`, (): void => { TESTS.forEach(([value, expected], i): void => {
expect( it(`#${i}: calcs ${expected}`, (): void => {
bnSqrt(value).eq(new BN(expected)) expect(
).toEqual(true); bnSqrt(value).eq(new BN(expected))
).toEqual(true);
});
}); });
}); });
}); });
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/util authors & contributors // Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0 // 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 { hexToBn } from '../hex/toBn.js';
import { isBigInt } from '../is/bigInt.js'; import { isBigInt } from '../is/bigInt.js';
@@ -26,7 +26,7 @@ import { BN } from './bn.js';
* bnToBn(new BN(0x1234)); // => BN(0x1234) * 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 return value
? BN.isBN(value) ? BN.isBN(value)
? value ? value
+12 -58
View File
@@ -4,6 +4,7 @@
/// <reference types="@polkadot/dev-test/globals.d.ts" /> /// <reference types="@polkadot/dev-test/globals.d.ts" />
import { arrayRange } from '../array/index.js'; import { arrayRange } from '../array/index.js';
import { TESTS } from '../bi/toU8a.spec.js';
import { perf } from '../test/index.js'; import { perf } from '../test/index.js';
import { BN, bnToU8a } from './index.js'; import { BN, bnToU8a } from './index.js';
@@ -40,65 +41,18 @@ describe('bnToU8a', (): void => {
).toEqual(new Uint8Array([0x56, 0x34, 0x12, 0x00])); ).toEqual(new Uint8Array([0x56, 0x34, 0x12, 0x00]));
}); });
describe('signed', (): void => { describe('conversion tests', (): void => {
it('converts negative numbers (BE)', (): void => { TESTS.forEach(([isLe, isNegative, numarr, strval], i): void => {
expect( const bitLength = numarr.length * 8;
bnToU8a(new BN(-1234), { isLe: false, isNegative: true })
).toEqual(new Uint8Array([251, 46]));
});
it('converts negative numbers (LE, i8)', (): void => { it(`#${i}: converts from ${strval} (bitLength=${bitLength}, isLe=${isLe}, isNegative=${isNegative})`, (): void => {
expect( expect(
bnToU8a(new BN(-12), { isNegative: true }) bnToU8a(
).toEqual(new Uint8Array([244])); new BN(strval),
}); { bitLength, isLe, isNegative }
)
it('converts negative numbers (LE, i16)', (): void => { ).toEqual(new Uint8Array(numarr));
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]));
}); });
}); });
+37 -104
View File
@@ -6,83 +6,36 @@
import { BN } from '../bn/index.js'; import { BN } from '../bn/index.js';
import { compactToU8a } from './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 => { 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 => { it('does not modify the original', (): void => {
const original = new BN(123456); const original = new BN(123456);
@@ -90,37 +43,17 @@ describe('encode', (): void => {
expect(original.toString()).toEqual('123456'); expect(original.toString()).toEqual('123456');
}); });
describe('from Rust', (): void => { describe('conversion tests', (): void => {
// Copied from https://github.com/paritytech/parity-codec/blob/master/src/codec.rs TESTS.forEach(([output, input], i): void => {
const testCases = [ it(`#${i}: encodes ${input.toString()}`, (): void => {
{ 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 => {
expect( expect(
compactToU8a(value) compactToU8a(input)
).toEqual( ).toEqual(
Uint8Array.from( output instanceof Uint8Array
expected.split(' ').map((s): number => parseInt(s, 16)) ? 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 { u8aToHex } from '../u8a/index.js';
import { floatToU8a } from './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: // NOTE Hex value outputs created via online conversion tool:
// https://www.h-schmidt.net/FloatConverter/IEEE754.html // 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 => { describe('floatToU8a', (): void => {
it('throws on invalid bitLength', (): void => { it('throws on invalid bitLength', (): void => {
@@ -16,89 +40,13 @@ describe('floatToU8a', (): void => {
).toThrow(); ).toThrow();
}); });
describe('32-bit', (): void => { describe('conversion tests', (): void => {
it('correctly encodes +0.0', (): void => { TESTS.forEach(([isLe, bitLength, input, output], i): void => {
expect( it(`#${i}: correctly encodes ${typeof input === 'number' ? input : input.toString()} (typeof=${typeof input})`, (): void => {
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 => {
expect( expect(
u8aToHex(floatToU8a(123.456)) u8aToHex(floatToU8a(input, { bitLength, isLe }))
).toEqual('0x79e9f642'); ).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 * @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 { 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 const tsValue = value instanceof Date
? value.getTime() ? value.getTime()
: bnToBn(value).toNumber(); : bnToBn(value).toNumber();
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/util authors & contributors // Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0 // 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 { BigInt } from '@polkadot/x-bigint';
import { xglobal } from '@polkadot/x-global'; 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) // 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) */ /** 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) */ /** true if the environment has process available (typically Node.js) */
export const hasProcess = typeof xglobal.process === 'object'; export const hasProcess = typeof xglobal.process === 'object';
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util authors & contributors // Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types.js';
const CHR = '0123456789abcdef'; const CHR = '0123456789abcdef';
const U8 = new Uint8Array(256); const U8 = new Uint8Array(256);
const U16 = new Uint8Array(256 * 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]) * 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) { if (!value) {
return new Uint8Array(); return new Uint8Array();
} }
+1 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2023 @polkadot/util authors & contributors // Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { HexString } from '../types.js';
/** /**
* @name hexToU8a * @name hexToU8a
* @summary Creates a Uint8Array object from a hex string. * @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]) * 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) { if (!_value) {
return new Uint8Array(); return new Uint8Array();
} }
+1 -1
View File
@@ -5,6 +5,6 @@
* @name isArray * @name isArray
* @summary Tests for a Array instance. * @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); return Array.isArray(value);
} }
+3 -3
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2023 @polkadot/util authors & contributors // Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0 // 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'; import { xglobal } from '@polkadot/x-global';
@@ -22,7 +22,7 @@ import { isFunction } from './function.js';
* console.log('isBuffer', isBuffer(Buffer.from([]))); // => true * 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 // 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 // Copyright 2017-2023 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
import type { Constructor } from '../types.js'; import type { Class } from '../types.js';
import { isClass } from './class.js'; import { isClass } from './class.js';
@@ -20,7 +20,7 @@ import { isClass } from './class.js';
* console.log('isChildClass', isChildClass(BN, Uint8Array); // => false * 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 // https://stackoverflow.com/questions/30993434/check-if-a-constructor-inherits-another-in-es6/30993664
return isClass(Child) && isClass(Parent) return isClass(Child) && isClass(Parent)
// eslint-disable-next-line no-prototype-builtins // eslint-disable-next-line no-prototype-builtins

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