Compare commits

...
110 Commits
Author SHA1 Message Date
github-actions[bot] 5ca6575245 [CI Skip] release/stable 9.7.1
skip-checks: true
2022-07-01 14:45:17 +00:00
Jaco 4cadf3bcb7 9.7.1 (#1572) 2022-07-01 17:40:21 +03:00
github-actions[bot] 81f8f16b98 [CI Skip] bump/beta 9.6.3-1-x
skip-checks: true
2022-06-30 11:38:33 +00:00
Jaco 8edfb1139f Bump dev deps (#1570) 2022-06-30 14:35:05 +03:00
github-actions[bot] 69d1d896d1 [CI Skip] bump/beta 9.6.3-0-x
skip-checks: true
2022-06-28 07:56:25 +00:00
Jaco 3bc62adf6f Sprinkle in readonly on array inputs (#1568) 2022-06-28 10:52:57 +03:00
github-actions[bot] 691a8e9b18 [CI Skip] release/stable 9.6.2
skip-checks: true
2022-06-25 05:26:53 +00:00
Jaco fc812590e5 Fix hexToU8a where 0x is not correctly converted (#1567)
* Fix `hexToU8a` where `0x` is not correctly converted

* 9.6.2

* CHANGELOG
2022-06-25 08:23:36 +03:00
github-actions[bot] 05499abcd5 [CI Skip] bump/beta 9.6.2-2-x
skip-checks: true
2022-06-23 17:05:08 +00:00
Jaco e375dd8a9d Bump dev (w/ deno build fix) (#1566) 2022-06-23 20:01:35 +03:00
github-actions[bot] 3269883e8f [CI Skip] bump/beta 9.6.2-1-x
skip-checks: true
2022-06-23 11:19:10 +00:00
Jaco c99129ee06 Rebump dev 2022-06-23 14:14:53 +03:00
github-actions[bot] 2514e107bf [CI Skip] bump/beta 9.6.2-0-x
skip-checks: true
2022-06-23 11:08:07 +00:00
Jaco 3c34a0e1f2 Bump dev 2022-06-23 14:04:35 +03:00
github-actions[bot] f704e371c8 [CI Skip] release/stable 9.6.1
skip-checks: true
2022-06-23 08:14:26 +00:00
Jaco 97e3443e74 9.6.1 (#1565) 2022-06-23 11:10:14 +03:00
github-actions[bot] a84e101666 [CI Skip] release/beta 9.5.2-19
skip-checks: true
2022-06-23 07:56:55 +00:00
Jaco a799918d58 Bump wasm & dev (#1564) 2022-06-23 10:53:26 +03:00
github-actions[bot] 429390fb62 [CI Skip] release/beta 9.5.2-18
skip-checks: true
2022-06-22 11:38:19 +00:00
Jaco 05d0109b72 Bump dev (w/ 3rd-part from esm.sh) (#1563) 2022-06-22 14:34:06 +03:00
github-actions[bot] 02b1429979 [CI Skip] release/beta 9.5.2-17
skip-checks: true
2022-06-22 10:46:27 +00:00
Jaco 6e1853d01f Bump dev (w/ deno ensure filename fixes) (#1562) 2022-06-22 13:42:58 +03:00
github-actions[bot] aa9c406d01 [CI Skip] release/beta 9.5.2-16
skip-checks: true
2022-06-22 10:10:41 +00:00
Jaco f9ec44823d Added mapping for @noble/secp256k1 to deno.land/x (#1561) 2022-06-22 13:07:12 +03:00
github-actions[bot] 54218651f9 [CI Skip] release/beta 9.5.2-15
skip-checks: true
2022-06-22 08:56:23 +00:00
Jaco 571c9eff6a Bump dev (& ignore perf tests on CI) (#1560) 2022-06-22 11:52:18 +03:00
github-actions[bot] 5b7333b8dd [CI Skip] release/beta 9.5.2-14
skip-checks: true
2022-06-22 08:17:21 +00:00
Jaco 938fa8b967 Bump dev (w/ publish updates) (#1559) 2022-06-22 11:13:18 +03:00
github-actions[bot] b99a69871e [CI Skip] release/beta 9.5.2-13
skip-checks: true
2022-06-22 06:45:47 +00:00
Jaco b1da8f575b Trigger deno build 2022-06-22 09:40:32 +03:00
github-actions[bot] a960aaf6ae [CI Skip] release/beta 9.5.2-12
skip-checks: true
2022-06-22 06:34:30 +00:00
Jaco f88c647ad0 Bump deps (#1558)
* Bump deps

* 3rd party bumps
2022-06-22 09:30:31 +03:00
github-actions[bot] 7ff11925d9 [CI Skip] release/beta 9.5.2-11
skip-checks: true
2022-06-21 13:03:57 +00:00
Jaco cb5a588489 Bump dev (w/ stable deno publish) (#1557)
* Bump dev (w/ stable deno publish)

* Adjust

* Bump dev
2022-06-21 15:59:46 +03:00
github-actions[bot] 09019224e3 [CI Skip] release/beta 9.5.2-10
skip-checks: true
2022-06-21 04:49:51 +00:00
Jaco 2d7031831a Bump TS to 4.7.4 (#1556) 2022-06-21 07:44:57 +03:00
github-actions[bot] faf7ea2b17 [CI Skip] release/beta 9.5.2-9
skip-checks: true
2022-06-21 03:32:33 +00:00
Jaco af973de694 Bump deps (#1555) 2022-06-21 06:28:19 +03:00
github-actions[bot] dfede866b2 [CI Skip] release/beta 9.5.2-8
skip-checks: true
2022-06-20 14:11:41 +00:00
Jaco 0f0b243815 Adjust isNull & isUndefined checks (#1554) 2022-06-20 17:06:35 +03:00
github-actions[bot] 29f53fe906 [CI Skip] release/beta 9.5.2-7
skip-checks: true
2022-06-20 13:30:11 +00:00
Jaco 225c250634 Adjust asserts (#1548)
* Adjust asserts

* Fix linting & build
2022-06-20 16:26:07 +03:00
github-actions[bot] c871e9d735 [CI Skip] release/beta 9.5.2-6
skip-checks: true
2022-06-20 10:19:45 +00:00
Jaco b42ead28e5 Optimize isAsicc check (#1553) 2022-06-20 13:15:00 +03:00
github-actions[bot] db0581c051 [CI Skip] release/beta 9.5.2-5
skip-checks: true
2022-06-20 08:54:49 +00:00
Jaco e7ac095ace Slight improvment to hexToU8a (#1552) 2022-06-20 11:49:41 +03:00
github-actions[bot] a7d9fc48e9 [CI Skip] release/beta 9.5.2-4
skip-checks: true
2022-06-20 08:34:19 +00:00
Jaco 3db2990ce7 Change Date.now() to performance.now() (#1551)
* Change Date.now() to performance.now()

* Adjust
2022-06-20 11:29:59 +03:00
github-actions[bot] 4b7cda243b [CI Skip] release/beta 9.5.2-3
skip-checks: true
2022-06-20 05:13:47 +00:00
Jaco c4ceeb8382 Additional float conversion tests (#1550) 2022-06-20 08:09:51 +03:00
github-actions[bot] 540971d388 [CI Skip] release/beta 9.5.2-2
skip-checks: true
2022-06-19 18:33:38 +00:00
Jaco b4d65a1c49 floatToU8a adjustment (#1549) 2022-06-19 21:29:34 +03:00
github-actions[bot] 4fd4660853 [CI Skip] release/beta 9.5.2-1
skip-checks: true
2022-06-19 07:22:23 +00:00
Jaco 4b46c179b2 floatToU8a & u8aToFloat (#1547)
* floatToU8a & u8aToFloat

* test for asserts
2022-06-19 10:17:35 +03:00
github-actions[bot] 3c6d297ecd [CI Skip] release/beta 9.5.2-0
skip-checks: true
2022-06-18 18:37:12 +00:00
Jaco 4a6e620acc Adjust isUndefined check (#1546) 2022-06-18 21:33:19 +03:00
github-actions[bot] 50b494ee2e [CI Skip] release/stable 9.5.1
skip-checks: true
2022-06-18 11:21:50 +00:00
Jaco 5b551ca976 9.5.1 (#1545) 2022-06-18 14:18:04 +03:00
github-actions[bot] 5f2a0e25f9 [CI Skip] release/beta 9.4.2-25
skip-checks: true
2022-06-18 10:35:02 +00:00
Jaco 4edb0f00b6 Adjust asserts (#1544) 2022-06-18 13:31:25 +03:00
github-actions[bot] 096c772d7d [CI Skip] release/beta 9.4.2-24
skip-checks: true
2022-06-18 06:02:51 +00:00
Jaco d771d4c243 Performance test for isCodec vs instanceof (#1543) 2022-06-18 08:58:59 +03:00
github-actions[bot] e038c36719 [CI Skip] release/beta 9.4.2-23
skip-checks: true
2022-06-17 06:28:47 +00:00
Jaco 19c8799986 Additional property tests (#1542) 2022-06-17 09:25:01 +03:00
github-actions[bot] e7f642e7fb [CI Skip] release/beta 9.4.2-22
skip-checks: true
2022-06-17 04:59:00 +00:00
Jaco 90e05a7907 Adjust objectProperties with key in that check (#1541) 2022-06-17 07:55:08 +03:00
github-actions[bot] 1ad961eb93 [CI Skip] release/beta 9.4.2-21
skip-checks: true
2022-06-16 18:38:27 +00:00
Jaco 8549f1fe89 Adjust isAscii str vs u8a loops (#1540) 2022-06-16 21:34:35 +03:00
github-actions[bot] 0be212bd49 [CI Skip] release/beta 9.4.2-20
skip-checks: true
2022-06-16 14:18:23 +00:00
Jaco 2dd2f78f7e Use \d in regex (as applicable) (#1539)
* Use \d in regex (as applicable)

* Adjust
2022-06-16 17:13:34 +03:00
github-actions[bot] d5ce0ff4d1 [CI Skip] release/beta 9.4.2-19
skip-checks: true
2022-06-16 13:52:39 +00:00
Jaco 4d887e889a Adjust testing for uppercase words in stringCamelCase (#1538)
* Adjust testing for uppercase words in stringCamelCase

* Use \d

* Revert
2022-06-16 16:47:52 +03:00
github-actions[bot] 1113d09315 [CI Skip] release/beta 9.4.2-18
skip-checks: true
2022-06-16 13:12:24 +00:00
Jaco b774b7804b Small camelCase conversion adjustments (#1537)
* Small camelCase conversion adjustments

* Remove unused exports

* Extract formatRuns
2022-06-16 16:07:45 +03:00
github-actions[bot] 6c1b0e7346 [CI Skip] release/beta 9.4.2-17
skip-checks: true
2022-06-16 11:56:18 +00:00
Jaco 68ba664c4c hexToU8a adjustments (#1536)
* hexToU8a adjustments

* Adjust test
2022-06-16 14:51:34 +03:00
github-actions[bot] c3c4ceab8b [CI Skip] release/beta 9.4.2-16
skip-checks: true
2022-06-16 08:34:08 +00:00
Jaco fff30601a0 Unroll u8aToBn loops (#1535)
* Unroll u8aToBn loops

* Adjust with additional xor shortcuts

* Adjust mult -> shift (where below u32)

* assertUnreachable

* Add u8aToNumber
2022-06-16 11:29:23 +03:00
github-actions[bot] cfb5d24a87 [CI Skip] release/beta 9.4.2-15
skip-checks: true
2022-06-15 18:51:31 +00:00
Jaco 7ce4ed1504 Cleanup comments (#1534) 2022-06-15 21:47:23 +03:00
github-actions[bot] 5a00b146fc [CI Skip] release/beta 9.4.2-14
skip-checks: true
2022-06-15 18:22:28 +00:00
Jaco 1a73a3407e Adjust option extraction for helpers (#1533)
* Adjust option extraction for helpers

* Adjust
2022-06-15 21:17:07 +03:00
github-actions[bot] 0db66346a6 [CI Skip] release/beta 9.4.2-13
skip-checks: true
2022-06-14 04:28:47 +00:00
Jaco a07bfe1234 Bump dev (#1532) 2022-06-14 07:24:11 +03:00
github-actions[bot] 5feb233abc [CI Skip] release/beta 9.4.2-12
skip-checks: true
2022-06-13 05:15:51 +00:00
Jaco 16951c6feb Bump 3rd-party deps 2022-06-13 08:11:43 +03:00
github-actions[bot] 22aa8d7adb [CI Skip] release/beta 9.4.2-11
skip-checks: true
2022-06-12 08:16:35 +00:00
Jaco dfaf954f75 Update issue template (#1530) 2022-06-12 11:12:07 +03:00
github-actions[bot] 78911607e8 [CI Skip] release/beta 9.4.2-10
skip-checks: true
2022-06-12 06:15:23 +00:00
Jaco cdcc331e6e Additional internal comments for exposed functions (#1529) 2022-06-12 09:11:12 +03:00
github-actions[bot] 882b29eebd [CI Skip] release/beta 9.4.2-9
skip-checks: true
2022-06-11 20:37:42 +00:00
Jaco de5c9a1594 Inline function for min/max creator (#1528) 2022-06-11 23:33:42 +03:00
github-actions[bot] 2fc26b5533 [CI Skip] release/beta 9.4.2-8
skip-checks: true
2022-06-11 15:21:18 +00:00
Jaco 6d795ecc5d Shared helper function for bn/bi min/max compares (#1527)
* Shared helper function for bn/bi min/max compares

* min/max test
2022-06-11 18:17:21 +03:00
github-actions[bot] a0c3aa3059 [CI Skip] release/beta 9.4.2-7
skip-checks: true
2022-06-11 14:32:46 +00:00
Jaco e30bac1ed6 Test for sqrt(MAX_SAFE_INT) (w/ comments for excluded functions) (#1526)
* Test for sqrt(MAX_SAFE_INT) (w/ comments for excluded functions)

* Adjust {bi, bn}{Max, Min} with factory
2022-06-11 17:28:55 +03:00
github-actions[bot] 50a061eab3 [CI Skip] release/beta 9.4.2-6
skip-checks: true
2022-06-11 07:52:58 +00:00
Jaco f2064f059f Additional @internal markers (#1525) 2022-06-11 10:48:51 +03:00
github-actions[bot] 768cd68146 [CI Skip] release/beta 9.4.2-5
skip-checks: true
2022-06-11 05:43:44 +00:00
Jaco 0a5bfdca5e Bump deps (& issue template) (#1524) 2022-06-11 08:39:52 +03:00
github-actions[bot] 3ec2f6dcb2 [CI Skip] release/beta 9.4.2-4
skip-checks: true
2022-06-10 11:53:05 +00:00
Jaco 0f2a3a142f CHANGELOG (#1523) 2022-06-10 14:48:56 +03:00
github-actions[bot] 6f5a706ec9 [CI Skip] release/beta 9.4.2-3
skip-checks: true
2022-06-10 10:56:44 +00:00
pan 7e0f917c2b update bifrost genesis hash (#1521) 2022-06-10 13:52:50 +03:00
github-actions[bot] 99731a6664 [CI Skip] release/beta 9.4.2-2
skip-checks: true
2022-06-07 06:02:06 +00:00
Jaco 7765476a26 Use bitwise not as Math.floor replacement (#1518)
* Use bitwise not as Math.floor replacement

* No objectSpread in extractTime

* Flatten extractTime calls
2022-06-07 08:58:11 +03:00
github-actions[bot] 2cd9633afe [CI Skip] release/beta 9.4.2-1
skip-checks: true
2022-06-07 05:47:38 +00:00
Jaco 72749d083f Bump deps (#1519) 2022-06-07 08:43:50 +03:00
github-actions[bot] 9ede85f99a [CI Skip] release/beta 9.4.2-0
skip-checks: true
2022-06-06 06:00:31 +00:00
Carlo SalaandJaco d6a390beb4 add Composable support for ledger (#1515)
* fix(networks): move centrifuge to new parachain chain

* feat: add composable support for ledger

* Update packages/networks/src/defaults/genesis.ts

Co-authored-by: Jaco <jacogr@gmail.com>
2022-06-06 08:55:46 +03:00
174 changed files with 3272 additions and 2096 deletions
+1
View File
@@ -0,0 +1 @@
9.7.1
+2 -1
View File
@@ -27,4 +27,5 @@
8.1.2
8.2.2
8.3.2
8.3.3
8.3.3
9.6.2
+50
View File
@@ -0,0 +1,50 @@
<!--
For general support, howto, coding and bundling questions, please use the Substrate & Polkadot StackExchange at https://substrate.stackexchange.com/ and get other ecosystem developers involved. This issues in this repository are meant for the tracking of feature requests and bug reports.
While all issues are looked at non-bug and non-features would take quite a bit longer to get to and may yield less than satisfactory responses in this format.
Additionally, please ensure you have done a search on the existing and closed issues before logging a new request. This saves time on all sides.
-->
* **I'm submitting a ...**
<!--- Try and classify your actual report -->
- [ ] Bug report
- [ ] Feature request
- [ ] Support request (please bear the comments above in mind)
- [ ] Other
* **What is the current behavior and expected behavior?**
<!--- If you're describing a bug, tell us what should happen -->
<!--- If you're suggesting a change/improvement, tell us how it should work -->
* **What is the motivation for changing the behavior?**
<!--- Not obligatory, but suggest a motivation for the request -->
<!--- or ideas how to implement the addition or change -->
* **Please tell us about your environment:**
<!--- Include as many relevant details about the environment you experienced the issue in -->
<!--- Also snsure that you have tested against the latest stable releases if a bug -->
- Version:
- Environment:
- [ ] Node.js
- [ ] Browser
- [ ] Other (limited support for other environments available)
- Language:
- [ ] JavaScript
- [ ] TypeScript
- [ ] Other
+1
View File
@@ -3,6 +3,7 @@ _book/
build/
build-cjs/
build-esm/
build-deno/
build-docs/
coverage/
docs/.vuepress/dist/
+44
View File
@@ -1,5 +1,49 @@
# CHANGELOG
## 9.7.1 Jul 1, 2022
Changes:
- Update signatures where `readonly` arrays are used
- Upgrade dependencies to latest stable versions
- Upgrade to `@polkadot/wasm-crypto` 6.2.1
## 9.6.2 Jun 25, 2022
Changes:
- Fix `hexToU8a` where `0x` is not correctly converted
## 9.6.1 Jun 23, 2022
Changes:
- Add `floatToU8a` and `u8aToFloat` (both 32 & 64-bit, le & be)
- Adjust `isUndefined` check (local variable available)
- Adjust use of `assert`, `isUndefined` & `isNull`
## 9.5.1 Jun 18, 2022
Contributed:
- Update Bifrost genesisHash (Thanks to https://github.com/awesomepan)
- Add Ledger support for Composable (Thanks to https://github.com/carlosala)
Changes:
- Add `u8aToNumber` (limited, <= 48 bits) function
- Use `~~` as bitwise/faster `Math.floor` replacement
- Remove unneeded `objectSpread` option expansions
- Optimize `hexToU8a` operations
- Optimize `stringCamelCase` operations
- Optimize `u8aToBn` operations
- Additional internal/external comments (as missing)
- Upgrade dependencies to latest stable versions
## 9.4.1 Jun 4, 2022
Changes:
+3 -3
View File
@@ -1,11 +1,12 @@
1338 Jaco 9.4.1 (#1514)
1391 Jaco 9.7.1 (#1572)
9 Antoine Estienne Add eth uri keyring test (#1291)
6 Amaury Martiny Add tests from Rust (#283)
5 kwingram25 Add BN consts and timeToString (#610)
4 Adam Dossa Update Polymesh Genesis Hash (#1193)
4 Carlo Sala add Composable support for ledger (#1515)
4 Jakub Pánik Add basilisk 🐍 (#1396)
3 Carlo Sala some changes to KnownLedger (#1497)
3 Luke Schoen docs: Fix example in readme since we use default imports (#243)
3 pan update bifrost genesis hash (#1521)
2 AndreasGassmann feat(dependencies): remove moment.js (#530)
2 Gav Wood Fix stake:unstake (#182)
2 Hyungsuk Kang Add cross client Encryption/Decryption (#496)
@@ -13,7 +14,6 @@
2 Kami Adding Westend genesis. (#1429)
2 Lovesh Harchandani Update genesis hash of Dock mainnet (#1436)
2 Nantian fix bigint type (#1079)
2 pan add bifrost (#1296)
2 Stefanie Doll Add missing dependencies to util-crypto (#424)
1 Agustinus Theodorus docs: fix typo in naclSeal docs. (#1005)
1 Alexander Krupenkin Added ECDSA keypair support (#589)
+5 -5
View File
@@ -10,7 +10,7 @@
"url": "https://github.com/polkadot-js/common.git"
},
"sideEffects": false,
"version": "9.4.1",
"version": "9.7.1",
"workspaces": [
"packages/*"
],
@@ -27,11 +27,11 @@
"test:one": "polkadot-dev-run-test --runInBand"
},
"devDependencies": {
"@babel/core": "^7.18.2",
"@polkadot/dev": "^0.66.34",
"@types/jest": "^28.1.0"
"@babel/core": "^7.18.6",
"@polkadot/dev": "^0.67.46",
"@types/jest": "^28.1.4"
},
"resolutions": {
"typescript": "^4.7.3"
"typescript": "^4.7.4"
}
}
+3 -3
View File
@@ -16,16 +16,16 @@
},
"sideEffects": false,
"type": "module",
"version": "9.4.1",
"version": "9.7.1",
"browser": "browser.js",
"main": "node.js",
"react-native": "react-native.js",
"dependencies": {
"@babel/runtime": "^7.18.3",
"@babel/runtime": "^7.18.6",
"@ledgerhq/hw-transport": "^6.27.1",
"@ledgerhq/hw-transport-webhid": "^6.27.1",
"@ledgerhq/hw-transport-webusb": "^6.27.1",
"@polkadot/util": "9.4.1"
"@polkadot/util": "9.7.1"
},
"optionalDependencies": {
"@ledgerhq/hw-transport-node-hid-singleton": "^6.27.1"
@@ -0,0 +1,8 @@
// Copyright 2017-2022 @polkadot/hw-ledger authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { TransportDef } from './types';
export { packageInfo } from './packageInfo';
export const transports: TransportDef[] = [];
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/hw-ledger authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './empty';
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/hw-ledger-transports', path: 'auto', type: 'auto', version: '9.4.1' };
export const packageInfo = { name: '@polkadot/hw-ledger-transports', path: 'auto', type: 'auto', version: '9.7.1' };
@@ -1,8 +1,4 @@
// Copyright 2017-2022 @polkadot/hw-ledger authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { TransportDef } from './types';
export { packageInfo } from './packageInfo';
export const transports: TransportDef[] = [];
export * from './empty';
+5 -5
View File
@@ -19,13 +19,13 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "9.4.1",
"version": "9.7.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.3",
"@babel/runtime": "^7.18.6",
"@ledgerhq/hw-transport": "^6.27.1",
"@polkadot/hw-ledger-transports": "9.4.1",
"@polkadot/util": "9.4.1",
"@zondax/ledger-substrate": "^0.30.0"
"@polkadot/hw-ledger-transports": "9.7.1",
"@polkadot/util": "9.7.1",
"@zondax/ledger-substrate": "^0.31.0"
}
}
+12 -5
View File
@@ -5,7 +5,7 @@ import type { ResponseBase, SubstrateApp } from '@zondax/ledger-substrate';
import type { AccountOptions, LedgerAddress, LedgerSignature, LedgerTypes, LedgerVersion } from './types';
import { transports } from '@polkadot/hw-ledger-transports';
import { assert, u8aToBuffer } from '@polkadot/util';
import { u8aToBuffer } from '@polkadot/util';
import { LEDGER_DEFAULT_ACCOUNT, LEDGER_DEFAULT_CHANGE, LEDGER_DEFAULT_INDEX, LEDGER_SUCCESS_CODE } from './constants';
import { ledgerApps } from './defaults';
@@ -26,8 +26,11 @@ export class Ledger {
constructor (transport: LedgerTypes, chain: Chain) {
// u2f is deprecated
assert(['hid', 'webusb'].includes(transport), () => `Unsupported transport ${transport}`);
assert(Object.keys(ledgerApps).includes(chain), () => `Unsupported chain ${chain}`);
if (!['hid', 'webusb'].includes(transport)) {
throw new Error(`Unsupported transport ${transport}`);
} else if (!Object.keys(ledgerApps).includes(chain)) {
throw new Error(`Unsupported chain ${chain}`);
}
this.#chain = chain;
this.#transport = transport;
@@ -71,7 +74,9 @@ export class Ledger {
if (!this.#app) {
const def = transports.find(({ type }) => type === this.#transport);
assert(def, () => `Unable to find a transport for ${this.#transport}`);
if (!def) {
throw new Error(`Unable to find a transport for ${this.#transport}`);
}
const transport = await def.create();
@@ -96,7 +101,9 @@ export class Ledger {
#wrapError = async <T extends ResponseBase> (promise: Promise<T>): Promise<T> => {
const result = await promise;
assert(result.return_code === LEDGER_SUCCESS_CODE, () => result.error_message);
if (result.return_code !== LEDGER_SUCCESS_CODE) {
throw new Error(result.error_message);
}
return result;
};
+2 -1
View File
@@ -4,7 +4,7 @@
import type Transport from '@ledgerhq/hw-transport';
import type { SubstrateApp } from '@zondax/ledger-substrate';
import { newAcalaApp, newAstarApp, newBifrostApp, newCentrifugeApp, newDockApp, newEdgewareApp, newEquilibriumApp, newGenshiroApp, newKaruraApp, newKusamaApp, newNodleApp, newParallelApp, newPolkadexApp, newPolkadotApp, newPolymeshApp, newSoraApp, newStatemineApp, newStatemintApp, newXXNetworkApp } from '@zondax/ledger-substrate';
import { newAcalaApp, newAstarApp, newBifrostApp, newCentrifugeApp, newComposableApp, newDockApp, newEdgewareApp, newEquilibriumApp, newGenshiroApp, newKaruraApp, newKusamaApp, newNodleApp, newParallelApp, newPolkadexApp, newPolkadotApp, newPolymeshApp, newSoraApp, newStatemineApp, newStatemintApp, newXXNetworkApp } from '@zondax/ledger-substrate';
// These match up with the keys of the knownLedger object in the @polkadot/networks/defaults/ledger.ts
export const ledgerApps: Record<string, (transport: Transport) => SubstrateApp> = {
@@ -12,6 +12,7 @@ export const ledgerApps: Record<string, (transport: Transport) => SubstrateApp>
astar: newAstarApp,
bifrost: newBifrostApp,
centrifuge: newCentrifugeApp,
composable: newComposableApp,
'dock-mainnet': newDockApp,
edgeware: newEdgewareApp,
equilibrium: newEquilibriumApp,
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/hw-ledger authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/hw-ledger', path: 'auto', type: 'auto', version: '9.4.1' };
export const packageInfo = { name: '@polkadot/hw-ledger', path: 'auto', type: 'auto', version: '9.7.1' };
+6 -6
View File
@@ -20,15 +20,15 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "9.4.1",
"version": "9.7.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.3",
"@polkadot/util": "9.4.1",
"@polkadot/util-crypto": "9.4.1"
"@babel/runtime": "^7.18.6",
"@polkadot/util": "9.7.1",
"@polkadot/util-crypto": "9.7.1"
},
"peerDependencies": {
"@polkadot/util": "9.4.1",
"@polkadot/util-crypto": "9.4.1"
"@polkadot/util": "9.7.1",
"@polkadot/util-crypto": "9.7.1"
}
}
+14 -6
View File
@@ -4,7 +4,7 @@
import type { EncryptedJsonEncoding, Keypair, KeypairType } from '@polkadot/util-crypto/types';
import type { KeyringInstance, KeyringOptions, KeyringPair, KeyringPair$Json, KeyringPair$Meta } from './types';
import { assert, hexToU8a, isHex, isUndefined, stringToU8a } from '@polkadot/util';
import { hexToU8a, isHex, stringToU8a } from '@polkadot/util';
import { base64Decode, decodeAddress, ed25519PairFromSeed as ed25519FromSeed, encodeAddress, ethereumEncode, hdEthereum, keyExtractSuri, keyFromPath, mnemonicToLegacySeed, mnemonicToMiniSecret, secp256k1PairFromSeed as secp256k1FromSeed, sr25519PairFromSeed as sr25519FromSeed } from '@polkadot/util-crypto';
import { DEV_PHRASE } from './defaults';
@@ -50,7 +50,9 @@ export class Keyring implements KeyringInstance {
constructor (options: KeyringOptions = {}) {
options.type = options.type || 'ed25519';
assert(['ecdsa', 'ethereum', 'ed25519', 'sr25519'].includes(options.type || 'undefined'), () => `Expected a keyring type of either 'ed25519', 'sr25519', 'ethereum' or 'ecdsa', found '${options.type || 'unknown'}`);
if (!['ecdsa', 'ethereum', 'ed25519', 'sr25519'].includes(options.type || 'undefined')) {
throw new Error(`Expected a keyring type of either 'ed25519', 'sr25519', 'ethereum' or 'ecdsa', found '${options.type || 'unknown'}`);
}
this.#pairs = new Pairs();
this.#ss58 = options.ss58Format;
@@ -162,7 +164,9 @@ export class Keyring implements KeyringInstance {
* @description Creates a pair from a JSON keyfile
*/
public createFromJson ({ address, encoded, encoding: { content, type, version }, meta }: KeyringPair$Json, ignoreChecksum?: boolean): KeyringPair {
assert(version !== '3' || content[0] === 'pkcs8', () => `Unable to decode non-pkcs8 type, [${content.join(',')}] found}`);
if (version === '3' && content[0] !== 'pkcs8') {
throw new Error(`Unable to decode non-pkcs8 type, [${content.join(',')}] found}`);
}
const cryptoType = version === '0' || !Array.isArray(content)
? this.type
@@ -171,7 +175,9 @@ export class Keyring implements KeyringInstance {
? [type]
: type;
assert(['ed25519', 'sr25519', 'ecdsa', 'ethereum'].includes(cryptoType), () => `Unknown crypto type ${cryptoType}`);
if (!['ed25519', 'sr25519', 'ecdsa', 'ethereum'].includes(cryptoType)) {
throw new Error(`Unknown crypto type ${cryptoType}`);
}
// Here the address and publicKey are 32 bytes and isomorphic. This is why the address field needs to be the public key for ethereum type pairs
const publicKey = isHex(address)
@@ -216,7 +222,9 @@ export class Keyring implements KeyringInstance {
? mnemonicToLegacySeed(phrase, '', false, 64)
: mnemonicToMiniSecret(phrase, password);
} else {
assert(phrase.length <= 32, 'specified phrase is not a valid mnemonic and is invalid as a raw seed at > 32 bytes');
if (phrase.length > 32) {
throw new Error('specified phrase is not a valid mnemonic and is invalid as a raw seed at > 32 bytes');
}
seed = stringToU8a(phrase.padEnd(32));
}
@@ -238,7 +246,7 @@ export class Keyring implements KeyringInstance {
public encodeAddress = (address: Uint8Array | string, ss58Format?: number): string => {
return this.type === 'ethereum'
? ethereumEncode(address)
: encodeAddress(address, isUndefined(ss58Format) ? this.#ss58 : ss58Format);
: encodeAddress(address, ss58Format === undefined ? this.#ss58 : ss58Format);
};
/**
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/keyring authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/keyring', path: 'auto', type: 'auto', version: '9.4.1' };
export const packageInfo = { name: '@polkadot/keyring', path: 'auto', type: 'auto', version: '9.7.1' };
+2 -2
View File
@@ -4,7 +4,7 @@
import type { EncryptedJsonEncoding } from '@polkadot/util-crypto/types';
import type { PairInfo } from './types';
import { assert, isUndefined, u8aEq } from '@polkadot/util';
import { assert, u8aEq } from '@polkadot/util';
import { jsonDecryptData } from '@polkadot/util-crypto';
import { PKCS8_DIVIDER, PKCS8_HEADER, PUB_LENGTH, SEC_LENGTH, SEED_LENGTH } from './defaults';
@@ -16,7 +16,7 @@ type DecodeResult = PairInfo & {
};
export function decodePair (passphrase?: string, encrypted?: Uint8Array | null, _encType?: EncryptedJsonEncoding | EncryptedJsonEncoding[]): DecodeResult {
const encType = Array.isArray(_encType) || isUndefined(_encType)
const encType = Array.isArray(_encType) || _encType === undefined
? _encType
: [_encType];
const decrypted = jsonDecryptData(encrypted, passphrase, encType);
+8 -6
View File
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types';
import type { KeyringPair, KeyringPairs } from './types';
import { assert, isHex, isU8a, u8aToHex, u8aToU8a } from '@polkadot/util';
import { isHex, isU8a, u8aToHex, u8aToU8a } from '@polkadot/util';
import { decodeAddress } from '@polkadot/util-crypto';
type KeyringPairMap = Record<string, KeyringPair>;
@@ -25,11 +25,13 @@ export class Pairs implements KeyringPairs {
public get (address: HexString | string | Uint8Array): KeyringPair {
const pair = this.#map[decodeAddress(address).toString()];
assert(pair, () => `Unable to retrieve keypair '${
isU8a(address) || isHex(address)
? u8aToHex(u8aToU8a(address))
: address
}'`);
if (!pair) {
throw new Error(`Unable to retrieve keypair '${
isU8a(address) || isHex(address)
? u8aToHex(u8aToU8a(address))
: address
}'`);
}
return pair;
}
+4 -2
View File
@@ -3,7 +3,7 @@
import type { KeyringInstance, KeyringOptions } from './types';
import { assert, hexToU8a } from '@polkadot/util';
import { hexToU8a } from '@polkadot/util';
import { KeypairType } from '@polkadot/util-crypto/types';
import { Keyring } from './keyring';
@@ -112,7 +112,9 @@ export const PAIRSETHEREUM: PairDef[] = [
];
function createMeta (name?: string, seed?: string) {
assert(name || seed, 'Testing pair should have either a name or a seed');
if (!name && !seed) {
throw new Error('Testing pair should have either a name or a seed');
}
return {
isTesting: true,
+6 -6
View File
@@ -17,15 +17,15 @@
},
"sideEffects": false,
"type": "module",
"version": "9.4.1",
"version": "9.7.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.3",
"@polkadot/util": "9.4.1",
"@substrate/ss58-registry": "^1.22.0"
"@babel/runtime": "^7.18.6",
"@polkadot/util": "9.7.1",
"@substrate/ss58-registry": "^1.23.0"
},
"devDependencies": {
"@polkadot/hw-ledger": "9.4.1",
"@polkadot/x-fetch": "9.4.1"
"@polkadot/hw-ledger": "9.7.1",
"@polkadot/x-fetch": "9.7.1"
}
}
+5 -1
View File
@@ -18,11 +18,15 @@ export const knownGenesis: KnownGenesis = {
'0xa85cfb9b9fd4d622a5b28289a02347af987d8f73fa3108450e2b4a11c1ce5755'
],
bifrost: [
'0x9f28c6a68e0fc9646eff64935684f6eeeece527e37bbe1f213d22caa1d9d6bed'
'0x262e1b2ad728475fd6fe88e62d34c200abe6fd693931ddad144059b1eb884e5b'
],
centrifuge: [
'0xb3db41421702df9a7fcac62b53ffeac85f7853cc4e689e0b93aeb3db18c09d82',
'0x67dddf2673b69e5f875f6f25277495834398eafd67f492e09f3f3345e003d1b5'
],
composable: [
'0xdaab8df776eb52ec604a5df5d388bb62a050a0aaec4556a64265b9d42755552d'
],
'dock-mainnet': [
'0x6bfe24dca2a3be10f22212678ac13a6446ec764103c0f3471c71609eac384aae',
'0xf73467c6544aa68df2ee546b135f955c46b90fa627e9b5d7935f41061bb8a5a9'
+1
View File
@@ -12,6 +12,7 @@ export const knownLedger: KnownLedger = {
astar: 0x0000032a,
bifrost: 0x00000314,
centrifuge: 0x000002eb,
composable: 0x00000162,
'dock-mainnet': 0x00000252,
edgeware: 0x0000020b,
equilibrium: 0x05f5e0fd,
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/networks authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/networks', path: 'auto', type: 'auto', version: '9.4.1' };
export const packageInfo = { name: '@polkadot/networks', path: 'auto', type: 'auto', version: '9.7.1' };
@@ -438,7 +438,7 @@
"NODL"
],
"decimals": [
18
11
],
"standardAccount": "*25519",
"website": "https://nodle.io/"
@@ -659,6 +659,32 @@
"standardAccount": "*25519",
"website": "https://xx.network"
},
{
"prefix": 56,
"network": "pendulum",
"displayName": "Pendulum chain",
"symbols": [
"PEN"
],
"decimals": [
12
],
"standardAccount": "*25519",
"website": "https://pendulumchain.org/"
},
{
"prefix": 57,
"network": "amplitude",
"displayName": "Amplitude chain",
"symbols": [
"AMPE"
],
"decimals": [
12
],
"standardAccount": "*25519",
"website": "https://pendulumchain.org/"
},
{
"prefix": 63,
"network": "hydradx",
@@ -1036,6 +1062,32 @@
"standardAccount": "Sr25519",
"website": "https://efinity.io/"
},
{
"prefix": 1221,
"network": "peaq",
"displayName": "Peaq Network",
"symbols": [
"PEAQ"
],
"decimals": [
18
],
"standardAccount": "Sr25519",
"website": "https://www.peaq.network/"
},
{
"prefix": 1222,
"network": "apex",
"displayName": "Apex Network",
"symbols": [
"APEX"
],
"decimals": [
18
],
"standardAccount": "Sr25519",
"website": "https://www.peaq.network/"
},
{
"prefix": 1284,
"network": "moonbeam",
@@ -1244,6 +1296,21 @@
"standardAccount": "*25519",
"website": "https://ata.network"
},
{
"prefix": 15253,
"network": "ice-network",
"displayName": "ICE Network",
"symbols": [
"ICX",
"ICY"
],
"decimals": [
18,
18
],
"standardAccount": "*25519",
"website": "https://icenetwork.io"
},
{
"prefix": 12191,
"network": "nftmart",
+11 -11
View File
@@ -22,22 +22,22 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "9.4.1",
"version": "9.7.1",
"browser": {
"crypto": false,
"stream": false
},
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.3",
"@noble/hashes": "1.0.0",
"@noble/secp256k1": "1.5.5",
"@polkadot/networks": "9.4.1",
"@polkadot/util": "9.4.1",
"@polkadot/wasm-crypto": "^6.1.1",
"@polkadot/x-bigint": "9.4.1",
"@polkadot/x-randomvalues": "9.4.1",
"@scure/base": "1.0.0",
"@babel/runtime": "^7.18.6",
"@noble/hashes": "1.1.2",
"@noble/secp256k1": "1.6.0",
"@polkadot/networks": "9.7.1",
"@polkadot/util": "9.7.1",
"@polkadot/wasm-crypto": "^6.2.1",
"@polkadot/x-bigint": "9.7.1",
"@polkadot/x-randomvalues": "9.7.1",
"@scure/base": "1.1.1",
"ed2curve": "^0.3.0",
"tweetnacl": "^1.0.3"
},
@@ -45,6 +45,6 @@
"@types/ed2curve": "^0.2.2"
},
"peerDependencies": {
"@polkadot/util": "9.4.1"
"@polkadot/util": "9.7.1"
}
}
@@ -27,6 +27,7 @@ type EncodeFn = (value: U8aLike, ipfsCompat?: boolean) => string;
type ValidateFn = (value?: unknown, ipfsCompat?: boolean) => value is string;
/** @internal */
export function createDecode ({ coder, ipfs }: Config, validate: ValidateFn): DecodeFn {
return (value: string, ipfsCompat?: boolean): Uint8Array => {
validate(value, ipfsCompat);
@@ -39,6 +40,7 @@ export function createDecode ({ coder, ipfs }: Config, validate: ValidateFn): De
};
}
/** @internal */
export function createEncode ({ coder, ipfs }: Config): EncodeFn {
return (value: U8aLike, ipfsCompat?: boolean): string => {
const out = coder.encode(u8aToU8a(value));
@@ -49,6 +51,7 @@ export function createEncode ({ coder, ipfs }: Config): EncodeFn {
};
}
/** @internal */
export function createIs (validate: ValidateFn): ValidateFn {
return (value?: unknown, ipfsCompat?: boolean): value is string => {
try {
@@ -59,6 +62,7 @@ export function createIs (validate: ValidateFn): ValidateFn {
};
}
/** @internal */
export function createValidate ({ chars, ipfs, type }: Config): ValidateFn {
return (value?: unknown, ipfsCompat?: boolean): value is string => {
assert(value && typeof value === 'string', () => `Expected non-null, non-empty ${type} string input`);
+3
View File
@@ -14,16 +14,19 @@ interface DualHash {
512: (u8a: Uint8Array) => Uint8Array;
}
/** @internal */
export function createAsHex <T extends (...args: never[]) => Uint8Array> (fn: T): (...args: Parameters<T>) => HexString {
return (...args: Parameters<T>): HexString =>
u8aToHex(fn(...args));
}
/** @internal */
export function createBitHasher (bitLength: 256 | 512, fn: (data: HexString | Buffer | Uint8Array | string, bitLength: 256 | 512, onlyJs?: boolean) => Uint8Array): (data: HexString | Buffer | Uint8Array | string, onlyJs?: boolean) => Uint8Array {
return (data: HexString | Buffer | Uint8Array | string, onlyJs?: boolean): Uint8Array =>
fn(data, bitLength, onlyJs);
}
/** @internal */
export function createDualHasher (wa: DualHash, js: DualHash): (value: HexString | Buffer | Uint8Array | string, bitLength?: 256 | 512, onlyJs?: boolean) => Uint8Array {
return (value: HexString | Buffer | Uint8Array | string, bitLength: 256 | 512 = 256, onlyJs?: boolean): Uint8Array => {
const u8a = u8aToU8a(value);
+3 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert, isNull } from '@polkadot/util';
import { DeriveJunction } from './DeriveJunction';
import { keyExtractPath } from './extractPath';
@@ -22,7 +20,9 @@ export function keyExtractSuri (suri: string): ExtractResult {
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const matches = suri.match(RE_CAPTURE);
assert(!isNull(matches), 'Unable to match provided value to a secret URI');
if (matches === null) {
throw new Error('Unable to match provided value to a secret URI');
}
const [, phrase, , derivePath, , , password] = matches as string[];
const { path } = keyExtractPath(derivePath);
@@ -1,7 +1,7 @@
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert, hasBigInt } from '@polkadot/util';
import { hasBigInt } from '@polkadot/util';
import { bip39ToSeed, isReady } from '@polkadot/wasm-crypto';
import { mnemonicToSeedSync } from './bip39';
@@ -25,8 +25,11 @@ import { mnemonicValidate } from './validate';
* ```
*/
export function mnemonicToLegacySeed (mnemonic: string, password = '', onlyJs?: boolean, byteLength: 32 | 64 = 32): Uint8Array {
assert(mnemonicValidate(mnemonic), 'Invalid bip39 mnemonic specified');
assert([32, 64].includes(byteLength), () => `Invalid seed length ${byteLength}, expected 32 or 64`);
if (!mnemonicValidate(mnemonic)) {
throw new Error('Invalid bip39 mnemonic specified');
} else if (![32, 64].includes(byteLength)) {
throw new Error(`Invalid seed length ${byteLength}, expected 32 or 64`);
}
return byteLength === 32
? !hasBigInt || (!onlyJs && isReady())
@@ -1,7 +1,7 @@
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert, stringToU8a } from '@polkadot/util';
import { stringToU8a } from '@polkadot/util';
import { bip39ToMiniSecret, isReady } from '@polkadot/wasm-crypto';
import { pbkdf2Encode } from '../pbkdf2';
@@ -9,7 +9,9 @@ import { mnemonicToEntropy } from './toEntropy';
import { mnemonicValidate } from './validate';
export function mnemonicToMiniSecret (mnemonic: string, password = '', onlyJs?: boolean): Uint8Array {
assert(mnemonicValidate(mnemonic), 'Invalid bip39 mnemonic specified');
if (!mnemonicValidate(mnemonic)) {
throw new Error('Invalid bip39 mnemonic specified');
}
if (!onlyJs && isReady()) {
return bip39ToMiniSecret(mnemonic, password);
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from './index';
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/util-crypto', path: 'auto', type: 'auto', version: '9.4.1' };
export const packageInfo = { name: '@polkadot/util-crypto', path: 'auto', type: 'auto', version: '9.7.1' };
+4 -2
View File
@@ -3,7 +3,7 @@
import type { Params } from './types';
import { assert, u8aToBn } from '@polkadot/util';
import { u8aToBn } from '@polkadot/util';
import { BN_LE_OPTS } from '../bn';
import { DEFAULT_PARAMS } from './defaults';
@@ -23,7 +23,9 @@ export function scryptFromU8a (data: Uint8Array): Result {
// and updates for greater security. However we need some 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
assert(N === DEFAULT_PARAMS.N && p === DEFAULT_PARAMS.p && r === DEFAULT_PARAMS.r, 'Invalid injected scrypt params found');
if (N !== DEFAULT_PARAMS.N || p !== DEFAULT_PARAMS.p || r !== DEFAULT_PARAMS.r) {
throw new Error('Invalid injected scrypt params found');
}
return { params: { N, p, r }, salt };
}
@@ -3,7 +3,7 @@
import { Point } from '@noble/secp256k1';
import { assert, hasBigInt } from '@polkadot/util';
import { hasBigInt } from '@polkadot/util';
import { isReady, secp256k1Compress as wasm } from '@polkadot/wasm-crypto';
export function secp256k1Compress (publicKey: Uint8Array, onlyJs?: boolean): Uint8Array {
@@ -11,7 +11,9 @@ export function secp256k1Compress (publicKey: Uint8Array, onlyJs?: boolean): Uin
return publicKey;
}
assert(publicKey.length === 65, 'Invalid publicKey provided');
if (publicKey.length !== 65) {
throw new Error('Invalid publicKey provided');
}
return !hasBigInt || (!onlyJs && isReady())
? wasm(publicKey)
@@ -1,14 +1,16 @@
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert, compactAddLength, isU8a, stringToU8a, u8aConcat } from '@polkadot/util';
import { compactAddLength, isU8a, stringToU8a, u8aConcat } from '@polkadot/util';
import { blake2AsU8a } from '../blake2/asU8a';
const HDKD = compactAddLength(stringToU8a('Secp256k1HDKD'));
export function secp256k1DeriveHard (seed: Uint8Array, chainCode: Uint8Array): Uint8Array {
assert(isU8a(chainCode) && chainCode.length === 32, 'Invalid chainCode passed to derive');
if (!isU8a(chainCode) || chainCode.length !== 32) {
throw new Error('Invalid chainCode passed to derive');
}
// NOTE This is specific to the Substrate HDD derivation, so always use the blake2 hasher
return blake2AsU8a(u8aConcat(HDKD, seed, chainCode), 256);
+4 -2
View File
@@ -3,7 +3,7 @@
import { Point } from '@noble/secp256k1';
import { assert, bnToU8a, hasBigInt, u8aConcat } from '@polkadot/util';
import { bnToU8a, hasBigInt, u8aConcat } from '@polkadot/util';
import { isReady, secp256k1Expand as wasm } from '@polkadot/wasm-crypto';
import { BN_BE_256_OPTS } from '../bn';
@@ -13,7 +13,9 @@ export function secp256k1Expand (publicKey: Uint8Array, onlyJs?: boolean): Uint8
return publicKey.subarray(1);
}
assert(publicKey.length === 33, 'Invalid publicKey provided');
if (publicKey.length !== 33) {
throw new Error('Invalid publicKey provided');
}
if (!hasBigInt || (!onlyJs && isReady())) {
return wasm(publicKey).subarray(1);
@@ -5,7 +5,7 @@ import type { Keypair } from '../../types';
import { getPublicKey } from '@noble/secp256k1';
import { assert, hasBigInt, u8aEmpty } from '@polkadot/util';
import { hasBigInt, u8aEmpty } from '@polkadot/util';
import { isReady, secp256k1FromSeed } from '@polkadot/wasm-crypto';
/**
@@ -13,7 +13,9 @@ import { isReady, secp256k1FromSeed } from '@polkadot/wasm-crypto';
* @description Returns a object containing a `publicKey` & `secretKey` generated from the supplied seed.
*/
export function secp256k1PairFromSeed (seed: Uint8Array, onlyJs?: boolean): Keypair {
assert(seed.length === 32, 'Expected valid 32-byte private key as a seed');
if (seed.length !== 32) {
throw new Error('Expected valid 32-byte private key as a seed');
}
if (!hasBigInt || (!onlyJs && isReady())) {
const full = secp256k1FromSeed(seed);
@@ -23,7 +25,9 @@ export function secp256k1PairFromSeed (seed: Uint8Array, onlyJs?: boolean): Keyp
// it seems that the lazy static section yields invalid results on the _first_ run.
// If this happens, fail outright, we cannot allow invalid return values
// https://github.com/polkadot-js/wasm/issues/307
assert(!u8aEmpty(publicKey), 'Invalid publicKey generated from WASM interface');
if (u8aEmpty(publicKey)) {
throw new Error('Invalid publicKey generated from WASM interface');
}
return {
publicKey,
@@ -6,7 +6,7 @@ import type { HashType } from './types';
import { recoverPublicKey, Signature } from '@noble/secp256k1';
import { assert, hasBigInt, u8aToU8a } from '@polkadot/util';
import { hasBigInt, u8aToU8a } from '@polkadot/util';
import { isReady, secp256k1Recover as wasm } from '@polkadot/wasm-crypto';
import { secp256k1Compress } from './compress';
@@ -23,7 +23,9 @@ export function secp256k1Recover (msgHash: HexString | Uint8Array | string, sign
? wasm(msg, sig, recovery)
: recoverPublicKey(msg, Signature.fromCompact(sig).toRawBytes(), recovery);
assert(publicKey, 'Unable to recover publicKey from signature');
if (!publicKey) {
throw new Error('Unable to recover publicKey from signature');
}
return hashType === 'keccak'
? secp256k1Expand(publicKey, onlyJs)
+4 -2
View File
@@ -6,7 +6,7 @@ import type { HashType } from './types';
import { Signature, signSync } from '@noble/secp256k1';
import { assert, bnToU8a, hasBigInt, u8aConcat } from '@polkadot/util';
import { bnToU8a, hasBigInt, u8aConcat } from '@polkadot/util';
import { isReady, secp256k1Sign as wasm } from '@polkadot/wasm-crypto';
import { BN_BE_256_OPTS } from '../bn';
@@ -17,7 +17,9 @@ import { hasher } from './hasher';
* @description Returns message signature of `message`, using the supplied pair
*/
export function secp256k1Sign (message: Uint8Array | string, { secretKey }: Partial<Keypair>, hashType: HashType = 'blake2', onlyJs?: boolean): Uint8Array {
assert(secretKey?.length === 32, 'Expected valid secp256k1 secretKey, 32-bytes');
if (secretKey?.length !== 32) {
throw new Error('Expected valid secp256k1 secretKey, 32-bytes');
}
const data = hasher(hashType, message, onlyJs);
+18 -7
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { _0n, assert, BN, bnToU8a, hasBigInt, isU8a, nToU8a, u8aToBigInt } from '@polkadot/util';
import { _0n, BN, bnToU8a, hasBigInt, isU8a, nToU8a, u8aToBigInt } from '@polkadot/util';
import { BigInt } from '@polkadot/x-bigint';
import { BN_BE_256_OPTS, BN_BE_OPTS } from '../bn';
@@ -15,7 +15,9 @@ const N_BN = new BN(N, 'hex');
function addBi (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
let res = u8aToBigInt(tweak, BN_BE_OPTS);
assert(res < N_BI, 'Tweak parameter is out of range');
if (res >= N_BI) {
throw new Error('Tweak parameter is out of range');
}
res += u8aToBigInt(seckey, BN_BE_OPTS);
@@ -23,7 +25,9 @@ function addBi (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
res -= N_BI;
}
assert(res !== _0n, 'Invalid resulting private key');
if (res === _0n) {
throw new Error('Invalid resulting private key');
}
return nToU8a(res, BN_BE_256_OPTS);
}
@@ -31,7 +35,9 @@ function addBi (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
function addBn (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
const res = new BN(tweak);
assert(res.cmp(N_BN) < 0, 'Tweak parameter is out of range');
if (res.cmp(N_BN) >= 0) {
throw new Error('Tweak parameter is out of range');
}
res.iadd(new BN(seckey));
@@ -39,14 +45,19 @@ function addBn (seckey: Uint8Array, tweak: Uint8Array): Uint8Array {
res.isub(N_BN);
}
assert(!res.isZero(), 'Invalid resulting private key');
if (res.isZero()) {
throw new Error('Invalid resulting private key');
}
return bnToU8a(res, BN_BE_256_OPTS);
}
export function secp256k1PrivateKeyTweakAdd (seckey: Uint8Array, tweak: Uint8Array, onlyBn?: boolean): Uint8Array {
assert(isU8a(seckey) && seckey.length === 32, 'Expected seckey to be an Uint8Array with length 32');
assert(isU8a(tweak) && tweak.length === 32, 'Expected tweak to be an Uint8Array with length 32');
if (!isU8a(seckey) || seckey.length !== 32) {
throw new Error('Expected seckey to be an Uint8Array with length 32');
} else if (!isU8a(tweak) || tweak.length !== 32) {
throw new Error('Expected tweak to be an Uint8Array with length 32');
}
return !hasBigInt || onlyBn
? addBn(seckey, tweak)
+4 -2
View File
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types';
import type { HashType } from './types';
import { assert, u8aEq, u8aToU8a } from '@polkadot/util';
import { u8aEq, u8aToU8a } from '@polkadot/util';
import { hasher } from './hasher';
import { secp256k1Recover } from './recover';
@@ -16,7 +16,9 @@ import { secp256k1Recover } from './recover';
export function secp256k1Verify (msgHash: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, address: HexString | Uint8Array | string, hashType: HashType = 'blake2', onlyJs?: boolean): boolean {
const sig = u8aToU8a(signature);
assert(sig.length === 65, `Expected signature with 65 bytes, ${sig.length} found instead`);
if (sig.length !== 65) {
throw new Error(`Expected signature with 65 bytes, ${sig.length} found instead`);
}
const publicKey = secp256k1Recover(hasher(hashType, msgHash), sig, sig[64], hashType, onlyJs);
const signerAddr = hasher(hashType, publicKey, onlyJs);
+7 -3
View File
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types';
import type { KeypairType, VerifyResult } from '../types';
import { assert, u8aIsWrapped, u8aToU8a, u8aUnwrapBytes, u8aWrapBytes } from '@polkadot/util';
import { u8aIsWrapped, u8aToU8a, u8aUnwrapBytes, u8aWrapBytes } from '@polkadot/util';
import { decodeAddress } from '../address/decode';
import { ed25519Verify } from '../ed25519/verify';
@@ -57,7 +57,9 @@ function verifyDetect (result: VerifyResult, { message, publicKey, signature }:
}
function verifyMultisig (result: VerifyResult, { message, publicKey, signature }: VerifyInput): VerifyResult {
assert([0, 1, 2].includes(signature[0]), () => `Unknown crypto type, expected signature prefix [0..2], found ${signature[0]}`);
if (![0, 1, 2].includes(signature[0])) {
throw new Error(`Unknown crypto type, expected signature prefix [0..2], found ${signature[0]}`);
}
const type = CRYPTO_TYPES[signature[0]] || 'none';
@@ -88,7 +90,9 @@ function getVerifyFn (signature: Uint8Array): VerifyFn {
export function signatureVerify (message: HexString | Uint8Array | string, signature: HexString | Uint8Array | string, addressOrPublicKey: HexString | Uint8Array | string): VerifyResult {
const signatureU8a = u8aToU8a(signature);
assert([64, 65, 66].includes(signatureU8a.length), () => `Invalid signature length, expected [64..66] bytes, found ${signatureU8a.length}`);
if (![64, 65, 66].includes(signatureU8a.length)) {
throw new Error(`Invalid signature length, expected [64..66] bytes, found ${signatureU8a.length}`);
}
const publicKey = decodeAddress(addressOrPublicKey);
const input = { message: u8aToU8a(message), publicKey, signature: signatureU8a };
@@ -3,7 +3,7 @@
import type { HexString } from '@polkadot/util/types';
import { assert, u8aToU8a } from '@polkadot/util';
import { u8aToU8a } from '@polkadot/util';
import { sr25519Agree } from '@polkadot/wasm-crypto';
/**
@@ -14,8 +14,11 @@ export function sr25519Agreement (secretKey: HexString | Uint8Array | string, pu
const secretKeyU8a = u8aToU8a(secretKey);
const publicKeyU8a = u8aToU8a(publicKey);
assert(publicKeyU8a.length === 32, () => `Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
assert(secretKeyU8a.length === 64, () => `Invalid secretKey, received ${secretKeyU8a.length} bytes, expected 64`);
if (publicKeyU8a.length !== 32) {
throw new Error(`Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
} else if (secretKeyU8a.length !== 64) {
throw new Error(`Invalid secretKey, received ${secretKeyU8a.length} bytes, expected 64`);
}
return sr25519Agree(publicKeyU8a, secretKeyU8a);
}
+4 -2
View File
@@ -3,14 +3,16 @@
import type { Keypair } from '../types';
import { assert, isU8a } from '@polkadot/util';
import { isU8a } from '@polkadot/util';
import { sr25519PairFromU8a } from './pair/fromU8a';
import { sr25519KeypairToU8a } from './pair/toU8a';
export function createDeriveFn (derive: (pair: Uint8Array, cc: Uint8Array) => Uint8Array): (keypair: Keypair, chainCode: Uint8Array) => Keypair {
return (keypair: Keypair, chainCode: Uint8Array): Keypair => {
assert(isU8a(chainCode) && chainCode.length === 32, 'Invalid chainCode passed to derive');
if (!isU8a(chainCode) || chainCode.length !== 32) {
throw new Error('Invalid chainCode passed to derive');
}
return sr25519PairFromU8a(
derive(sr25519KeypairToU8a(keypair), chainCode)
@@ -3,14 +3,17 @@
import type { HexString } from '@polkadot/util/types';
import { assert, isU8a, u8aToU8a } from '@polkadot/util';
import { isU8a, u8aToU8a } from '@polkadot/util';
import { sr25519DerivePublicSoft } from '@polkadot/wasm-crypto';
export function sr25519DerivePublic (publicKey: HexString | Uint8Array | string, chainCode: Uint8Array): Uint8Array {
const publicKeyU8a = u8aToU8a(publicKey);
assert(isU8a(chainCode) && chainCode.length === 32, 'Invalid chainCode passed to derive');
assert(publicKeyU8a.length === 32, () => `Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
if (!isU8a(chainCode) || chainCode.length !== 32) {
throw new Error('Invalid chainCode passed to derive');
} else if (publicKeyU8a.length !== 32) {
throw new Error(`Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
}
return sr25519DerivePublicSoft(publicKeyU8a, chainCode);
}
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../../types';
import { assert, u8aToU8a } from '@polkadot/util';
import { u8aToU8a } from '@polkadot/util';
import { sr25519KeypairFromSeed } from '@polkadot/wasm-crypto';
import { sr25519PairFromU8a } from './fromU8a';
@@ -16,7 +16,9 @@ import { sr25519PairFromU8a } from './fromU8a';
export function sr25519PairFromSeed (seed: HexString | Uint8Array | string): Keypair {
const seedU8a = u8aToU8a(seed);
assert(seedU8a.length === 32, () => `Expected a seed matching 32 bytes, found ${seedU8a.length}`);
if (seedU8a.length !== 32) {
throw new Error(`Expected a seed matching 32 bytes, found ${seedU8a.length}`);
}
return sr25519PairFromU8a(
sr25519KeypairFromSeed(seedU8a)
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../../types';
import { assert, u8aToU8a } from '@polkadot/util';
import { u8aToU8a } from '@polkadot/util';
const SEC_LEN = 64;
const PUB_LEN = 32;
@@ -13,7 +13,9 @@ const TOT_LEN = SEC_LEN + PUB_LEN;
export function sr25519PairFromU8a (full: HexString | Uint8Array | string): Keypair {
const fullU8a = u8aToU8a(full);
assert(fullU8a.length === TOT_LEN, () => `Expected keypair with ${TOT_LEN} bytes, found ${fullU8a.length}`);
if (fullU8a.length !== TOT_LEN) {
throw new Error(`Expected keypair with ${TOT_LEN} bytes, found ${fullU8a.length}`);
}
return {
publicKey: fullU8a.slice(SEC_LEN, TOT_LEN),
+6 -3
View File
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types';
import { assert, u8aToU8a } from '@polkadot/util';
import { u8aToU8a } from '@polkadot/util';
import { sr25519Sign as wasmSign } from '@polkadot/wasm-crypto';
/**
@@ -12,8 +12,11 @@ import { sr25519Sign as wasmSign } from '@polkadot/wasm-crypto';
* @description Returns message signature of `message`, using the supplied pair
*/
export function sr25519Sign (message: HexString | Uint8Array | string, { publicKey, secretKey }: Partial<Keypair>): Uint8Array {
assert(publicKey?.length === 32, 'Expected a valid publicKey, 32-bytes');
assert(secretKey?.length === 64, 'Expected a valid secretKey, 64-bytes');
if (publicKey?.length !== 32) {
throw new Error('Expected a valid publicKey, 32-bytes');
} else if (secretKey?.length !== 64) {
throw new Error('Expected a valid secretKey, 64-bytes');
}
return wasmSign(publicKey, secretKey, u8aToU8a(message));
}
+6 -3
View File
@@ -3,7 +3,7 @@
import type { HexString } from '@polkadot/util/types';
import { assert, u8aToU8a } from '@polkadot/util';
import { u8aToU8a } from '@polkadot/util';
import { sr25519Verify as wasmVerify } from '@polkadot/wasm-crypto';
/**
@@ -14,8 +14,11 @@ export function sr25519Verify (message: HexString | Uint8Array | string, signatu
const publicKeyU8a = u8aToU8a(publicKey);
const signatureU8a = u8aToU8a(signature);
assert(publicKeyU8a.length === 32, () => `Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
assert(signatureU8a.length === 64, () => `Invalid signature, received ${signatureU8a.length} bytes, expected 64`);
if (publicKeyU8a.length !== 32) {
throw new Error(`Invalid publicKey, received ${publicKeyU8a.length} bytes, expected 32`);
} else if (signatureU8a.length !== 64) {
throw new Error(`Invalid signature, received ${signatureU8a.length} bytes, expected 64`);
}
return wasmVerify(signatureU8a, u8aToU8a(message), publicKeyU8a);
}
+4 -2
View File
@@ -4,7 +4,7 @@
import type { HexString } from '@polkadot/util/types';
import type { Keypair } from '../types';
import { assert, u8aToU8a } from '@polkadot/util';
import { u8aToU8a } from '@polkadot/util';
import { vrfSign } from '@polkadot/wasm-crypto';
const EMPTY_U8A = new Uint8Array();
@@ -14,7 +14,9 @@ const EMPTY_U8A = new Uint8Array();
* @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 {
assert(secretKey?.length === 64, 'Invalid secretKey, expected 64-bytes');
if (secretKey?.length !== 64) {
throw new Error('Invalid secretKey, expected 64-bytes');
}
return vrfSign(secretKey, u8aToU8a(context), u8aToU8a(message), u8aToU8a(extra));
}
@@ -3,7 +3,7 @@
import type { HexString } from '@polkadot/util/types';
import { assert, u8aToU8a } from '@polkadot/util';
import { u8aToU8a } from '@polkadot/util';
import { vrfVerify } from '@polkadot/wasm-crypto';
const EMPTY_U8A = new Uint8Array();
@@ -16,8 +16,11 @@ export function sr25519VrfVerify (message: HexString | Uint8Array | string, sign
const publicKeyU8a = u8aToU8a(publicKey);
const proofU8a = u8aToU8a(signOutput);
assert(publicKeyU8a.length === 32, 'Invalid publicKey, expected 32-bytes');
assert(proofU8a.length === 96, 'Invalid vrfSign output, expected 96 bytes');
if (publicKeyU8a.length !== 32) {
throw new Error('Invalid publicKey, expected 32-bytes');
} else if (proofU8a.length !== 96) {
throw new Error('Invalid vrfSign output, expected 96 bytes');
}
return vrfVerify(publicKeyU8a, u8aToU8a(context), u8aToU8a(message), u8aToU8a(extra), proofU8a);
}
+3 -3
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import { arrayRange } from '@polkadot/util';
import { performance, performanceCmp } from '@polkadot/util/test/performance';
import { perf, perfCmp } from '@polkadot/util/test/performance';
import { randomAsU8a } from '..';
@@ -11,7 +11,7 @@ type ExecFn = (input: Uint8Array, onlyJs: boolean) => unknown;
const GENERATED = arrayRange(256).map(() => [randomAsU8a()]);
export function performanceWasm (name: string, count: number, exec: ExecFn, inputs = GENERATED): void {
performanceCmp(name, ['WebAssembly', 'JavaScript'], count, inputs, exec);
perfCmp(name, ['WebAssembly', 'JavaScript'], count, inputs, exec);
}
export { performance, performanceCmp };
export { perf, perfCmp };
+7 -7
View File
@@ -34,19 +34,19 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "9.4.1",
"version": "9.7.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.18.3",
"@polkadot/x-bigint": "9.4.1",
"@polkadot/x-global": "9.4.1",
"@polkadot/x-textdecoder": "9.4.1",
"@polkadot/x-textencoder": "9.4.1",
"@babel/runtime": "^7.18.6",
"@polkadot/x-bigint": "9.7.1",
"@polkadot/x-global": "9.7.1",
"@polkadot/x-textdecoder": "9.7.1",
"@polkadot/x-textencoder": "9.7.1",
"@types/bn.js": "^5.1.0",
"bn.js": "^5.2.1",
"ip-regex": "^4.3.0"
},
"devDependencies": {
"@polkadot/x-randomvalues": "9.4.1"
"@polkadot/x-randomvalues": "9.7.1"
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { performance } from '../test/performance';
import { perf } from '../test/performance';
import { arrayChunk, arrayRange } from '.';
describe('arrayChunk', (): void => {
@@ -11,5 +11,5 @@ describe('arrayChunk', (): void => {
).toEqual([[1, 2, 3], [4, 5, 6], [7]]);
});
performance('arrayChunk', 200_000, [[arrayRange(500), 50]], arrayChunk);
perf('arrayChunk', 200_000, [[arrayRange(500), 50]], arrayChunk);
});
+6
View File
@@ -17,6 +17,12 @@
*/
export function arrayChunk <T> (array: T[], chunkSize: number): T[][] {
const outputSize = Math.ceil(array.length / chunkSize);
// noop for the single-split case
if (outputSize === 1) {
return [array];
}
const output = Array<T[]>(outputSize);
for (let i = 0; i < outputSize; i++) {
+4 -8
View File
@@ -1,9 +1,6 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { isNull } from '../is/null';
import { isUndefined } from '../is/undefined';
/**
* @name arrayFilter
* @summary Filters undefined and (optionally) null values from an array
@@ -19,10 +16,9 @@ import { isUndefined } from '../is/undefined';
* arrayFilter([0, void 0, true, null, false, ''], false); // [0, true, false, '']
* ```
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function arrayFilter <T = any> (array: T[], allowNulls = true): T[] {
return array.filter((v) =>
!isUndefined(v) &&
(allowNulls || !isNull(v))
export function arrayFilter <T = unknown> (array: readonly (T | null | undefined)[], allowNulls = true): T[] {
return array.filter((v): v is T =>
v !== undefined &&
(allowNulls || v !== null)
);
}
+6 -1
View File
@@ -18,7 +18,12 @@
* arrayFlatten([[1, 2], [3, 4], [5]]); // [1, 2, 3, 4, 5]
* ```
*/
export function arrayFlatten <T> (arrays: T[][]): T[] {
export function arrayFlatten <T> (arrays: readonly T[][]): T[] {
// noop for the single-entry case
if (arrays.length === 1) {
return arrays[0];
}
// pre-allocate based on the combined size
let size = 0;
+3 -3
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert } from '../assert';
/**
* @name arrayRange
* @summary Returns a range of numbers ith the size and the specified offset
@@ -19,7 +17,9 @@ import { assert } from '../assert';
* ```
*/
export function arrayRange (size: number, startAt = 0): number[] {
assert(size > 0, 'Expected non-zero, positive number as a range size');
if (size <= 0) {
throw new Error('Expected non-zero, positive number as a range size');
}
const result = new Array<number>(size);
+5
View File
@@ -1,8 +1,11 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { perf } from '../test/performance';
import { arrayRange, arrayShuffle } from '.';
const ptest = arrayRange(16284);
describe('arrayShuffle', (): void => {
it('returns an empty array as-is', (): void => {
expect(
@@ -28,4 +31,6 @@ describe('arrayShuffle', (): void => {
JSON.stringify(inp)
).not.toEqual(JSON.stringify(out));
});
perf('arrayShuffle', 1000, [[ptest]], arrayShuffle);
});
+7 -1
View File
@@ -1,16 +1,22 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
/**
* @name arrayShuffle
* @description Shuffles the input array (unlike sort, this is not done in-place)
*/
export function arrayShuffle <T> (input: T[]): T[] {
const result = input.slice();
let curr = result.length;
// noop for the single entry
if (curr === 1) {
return result;
}
while (curr !== 0) {
const rand = Math.floor(Math.random() * curr);
// ~~ is more performant than Math.floor
const rand = ~~(Math.random() * curr);
curr--;
+5 -1
View File
@@ -1,7 +1,11 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
export function arrayZip <K, V> (keys: K[], values: V[]): [K, V][] {
/**
* @name arrayZip
* @description Combines 2 distinct key/value arrays into a single [K, V] array
*/
export function arrayZip <K, V> (keys: readonly K[], values: readonly V[]): [K, V][] {
const result = new Array<[K, V]>(keys.length);
for (let i = 0; i < keys.length; i++) {
+1 -3
View File
@@ -2,8 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
import { isFunction } from './is/function';
import { isNull } from './is/null';
import { isUndefined } from './is/undefined';
type MessageFn = () => string;
@@ -38,7 +36,7 @@ export function assert (condition: unknown, message: string | MessageFn): assert
* @description Returns when the value is not undefined/null, otherwise throws assertion error
*/
export function assertReturn <T> (value: T | undefined | null, message: string | MessageFn): T {
assert(!isUndefined(value) && !isNull(value), message);
assert(value !== undefined && value !== null, message);
return value;
}
+21
View File
@@ -0,0 +1,21 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
/** @internal */
export function createCmp <T> (cmp: (a: T, b: T) => boolean): (...items: T[]) => T {
return (...items: T[]): T => {
if (items.length === 0) {
throw new Error('Must provide one or more arguments');
}
let result = items[0];
for (let i = 1; i < items.length; i++) {
if (cmp(items[i], result)) {
result = items[i];
}
}
return result;
};
}
+1 -1
View File
@@ -25,6 +25,6 @@ describe('nMax', (): void => {
it('fails when no items are available', (): void => {
expect(
() => nMax()
).toThrow(/Must provide one or more bigint arguments/);
).toThrow(/Must provide one or more arguments/);
});
});
+1 -1
View File
@@ -19,6 +19,6 @@ describe('nMin', (): void => {
it('fails when no items are available', (): void => {
expect(
() => nMin()
).toThrow(/Must provide one or more bigint arguments/);
).toThrow(/Must provide one or more arguments/);
});
});
+3 -29
View File
@@ -1,42 +1,16 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert } from '../assert';
function gt (a: bigint, b: bigint): boolean {
return a > b;
}
function lt (a: bigint, b: bigint): boolean {
return a < b;
}
function find (items: bigint[], cmp: (a: bigint, b: bigint) => boolean): bigint {
assert(items.length >= 1, 'Must provide one or more bigint arguments');
let result = items[0];
for (let i = 1; i < items.length; i++) {
if (cmp(items[i], result)) {
result = items[i];
}
}
return result;
}
import { createCmp } from './helpers';
/**
* @name nMax
* @summary Finds and returns the highest value in an array of bigint.
*/
export function nMax (...items: bigint[]): bigint {
return find(items, gt);
}
export const nMax = createCmp<bigint>((a, b) => a > b);
/**
* @name nMin
* @summary Finds and returns the lowest value in an array of bigint.
*/
export function nMin (...items: bigint[]): bigint {
return find(items, lt);
}
export const nMin = createCmp<bigint>((a, b) => a < b);
+14 -1
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import { BN } from '../bn';
import { SQRT_MAX_SAFE_INTEGER } from './sqrt';
import { nSqrt } from '.';
const TESTS: [string | number | BN | bigint, string | number][] = [
@@ -34,9 +35,21 @@ describe('nSqrt', (): void => {
).toThrow(/negative numbers is not supported/);
});
it('has the correct constant for sqrt(Number.MAX_SAFE_INTEGER)', (): void => {
expect(
BigInt(
~~Math.sqrt(
Number.MAX_SAFE_INTEGER
)
) === SQRT_MAX_SAFE_INTEGER
).toEqual(true);
});
TESTS.forEach(([value, expected], index): void => {
it(`calcs for test #${index}`, (): void => {
expect(nSqrt(value) === BigInt(expected)).toEqual(true);
expect(
nSqrt(value) === BigInt(expected)
).toEqual(true);
});
});
});
+8 -5
View File
@@ -6,11 +6,11 @@ import type { ToBigInt, ToBn } from '../types';
import { BigInt } from '@polkadot/x-bigint';
import { assert } from '../assert';
import { _0n, _1n, _2pow53n } from './consts';
import { nToBigInt } from './toBigInt';
const _sqrt2pow53n = BigInt(94906265);
/** @internal */
export const SQRT_MAX_SAFE_INTEGER = BigInt(94906265);
/**
* @name nSqrt
@@ -19,17 +19,20 @@ const _sqrt2pow53n = BigInt(94906265);
export function nSqrt <ExtToBn extends ToBn | ToBigInt> (value: ExtToBn | BN | bigint | string | number | null): bigint {
const n = nToBigInt(value);
assert(n >= _0n, 'square root of negative numbers is not supported');
if (n < _0n) {
throw new Error('square root of negative numbers is not supported');
}
// https://stackoverflow.com/questions/53683995/javascript-big-integer-square-root/
// shortcut <= 2^53 - 1 to use the JS utils
if (n <= _2pow53n) {
return BigInt(Math.floor(Math.sqrt(Number(n))));
// ~~ is more performant that Math.floor
return BigInt(~~Math.sqrt(Number(n)));
}
// Use sqrt(MAX_SAFE_INTEGER) as starting point. since we already know the
// output will be larger than this, we expect this to be a safe start
let x0 = _sqrt2pow53n;
let x0 = SQRT_MAX_SAFE_INTEGER;
while (true) {
const x1 = ((n / x0) + x0) >> _1n;
+1
View File
@@ -8,6 +8,7 @@ import { objectSpread } from '../object/spread';
import { u8aToHex } from '../u8a';
import { nToU8a } from './toU8a';
/** @internal */
const ZERO_STR = '0x00';
/**
+2 -2
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import { arrayRange } from '../array';
import { performance } from '../test/performance';
import { perf } from '../test/performance';
import { nToU8a } from '.';
const ptest = arrayRange(65536).map((v) => [v]);
@@ -56,5 +56,5 @@ describe('nToU8a', (): void => {
).toEqual(new Uint8Array([46, 251, 255, 255]));
});
performance('nToU8a', 250000, ptest, nToU8a);
perf('nToU8a', 250000, ptest, nToU8a);
});
+1 -1
View File
@@ -25,6 +25,6 @@ describe('bnMax', (): void => {
it('fails when no items are available', (): void => {
expect(
() => bnMax()
).toThrow(/Must provide one or more BN arguments/);
).toThrow(/Must provide one or more arguments/);
});
});
+6
View File
@@ -15,4 +15,10 @@ describe('bnMin', (): void => {
bnMin(new BN(1))
).toEqual(new BN(1));
});
it('fails when no items are available', (): void => {
expect(
() => bnMin()
).toThrow(/Must provide one or more arguments/);
});
});
+3 -19
View File
@@ -1,21 +1,9 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert } from '../assert';
import { createCmp } from '../bi/helpers';
import { BN } from './bn';
export function find (items: BN[], cmp: (a: BN, b: BN) => BN): BN {
assert(items.length >= 1, 'Must provide one or more BN arguments');
let result = items[0];
for (let i = 1; i < items.length; i++) {
result = cmp(result, items[i]);
}
return result;
}
/**
* @name bnMax
* @summary Finds and returns the highest value in an array of BNs.
@@ -29,9 +17,7 @@ export function find (items: BN[], cmp: (a: BN, b: BN) => BN): BN {
* bnMax([new BN(1), new BN(3), new BN(2)]).toString(); // => '3'
* ```
*/
export function bnMax (...items: BN[]): BN {
return find(items, BN.max);
}
export const bnMax = createCmp<BN>((a, b) => a.gt(b));
/**
* @name bnMin
@@ -46,6 +32,4 @@ export function bnMax (...items: BN[]): BN {
* bnMin([new BN(1), new BN(3), new BN(2)]).toString(); // => '1'
* ```
*/
export function bnMin (...items: BN[]): BN {
return find(items, BN.min);
}
export const bnMin = createCmp<BN>((a, b) => a.lt(b));
+16 -1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { SQRT_MAX_SAFE_INTEGER } from './sqrt';
import { BN, bnSqrt } from '.';
const TESTS: [string | number | BN | bigint, string | number][] = [
@@ -33,9 +34,23 @@ describe('bnSqrt', (): void => {
).toThrow(/negative numbers is not supported/);
});
it('has the correct constant for sqrt(Number.MAX_SAFE_INTEGER)', (): void => {
expect(
SQRT_MAX_SAFE_INTEGER.eq(
new BN(
~~Math.sqrt(
Number.MAX_SAFE_INTEGER
)
)
)
).toEqual(true);
});
TESTS.forEach(([value, expected], index): void => {
it(`calcs for test #${index}`, (): void => {
expect(bnSqrt(value).eq(new BN(expected))).toEqual(true);
expect(
bnSqrt(value).eq(new BN(expected))
).toEqual(true);
});
});
});
+8 -5
View File
@@ -3,12 +3,12 @@
import type { ToBn } from '../types';
import { assert } from '../assert';
import { BN } from './bn';
import { BN_MAX_INTEGER, BN_ONE, BN_ZERO } from './consts';
import { BN_MAX_INTEGER, BN_ONE } from './consts';
import { bnToBn } from './toBn';
const SQRT_MAX_SAFE_INTEGER = new BN(94906265);
/** @internal */
export const SQRT_MAX_SAFE_INTEGER = new BN(94906265);
/**
* @name bnSqrt
@@ -26,12 +26,15 @@ const SQRT_MAX_SAFE_INTEGER = new BN(94906265);
export function bnSqrt <ExtToBn extends ToBn> (value: ExtToBn | BN | bigint | string | number | null): BN {
const n = bnToBn(value);
assert(n.gte(BN_ZERO), 'square root of negative numbers is not supported');
if (n.isNeg()) {
throw new Error('square root of negative numbers is not supported');
}
// https://stackoverflow.com/questions/53683995/javascript-big-integer-square-root/
// shortcut <= 2^53 - 1 to use the JS utils
if (n.lte(BN_MAX_INTEGER)) {
return new BN(Math.floor(Math.sqrt(n.toNumber())));
// ~~ More performant version of Math.floor
return new BN(~~Math.sqrt(n.toNumber()));
}
// Use sqrt(MAX_SAFE_INTEGER) as starting point. since we already know the
+1 -1
View File
@@ -31,7 +31,7 @@ function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number
/** @deprecated Use bnToHex (value?: ExtToBn | BN | bigint | number | null, options?: NumberOptions) */
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, bitLength?: number, isLe?: boolean): HexString;
/** @deprecated Use bnToHex (value?: ExtToBn | BN | bigint | number | null, options?: NumberOptions) */
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, arg1: number | NumberOptions = DEFAULT_OPTS, arg2?: boolean): HexString {
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, arg1: number | NumberOptions = DEFAULT_OPTS, arg2 = false): HexString {
return !value
? ZERO_STR
: u8aToHex(
+64 -26
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import { arrayRange } from '../array';
import { performance } from '../test/performance';
import { perf } from '../test/performance';
import { BN, bnToU8a } from '.';
const ptest = arrayRange(65536).map((v) => [v]);
@@ -38,30 +38,6 @@ describe('bnToU8a', (): void => {
).toEqual(new Uint8Array([0x56, 0x34, 0x12, 0x00]));
});
it('converts negative numbers', (): void => {
expect(
bnToU8a(new BN(-1234), { isNegative: true })
).toEqual(new Uint8Array([46, 251]));
});
it('converts negative numbers (BE)', (): void => {
expect(
bnToU8a(new BN(-1234), { isLe: false, isNegative: true })
).toEqual(new Uint8Array([251, 46]));
});
it('converts negative numbers (LE)', (): void => {
expect(
bnToU8a(new BN(-1234), { bitLength: 32, isNegative: true })
).toEqual(new Uint8Array([46, 251, 255, 255]));
});
it('converts negative numbers (LE, bitLength)', (): void => {
expect(
bnToU8a(new BN(-123456), { bitLength: 32, isNegative: true })
).toEqual(new Uint8Array([192, 29, 254, 255]));
});
it('handles backwards compatibility', (): void => {
expect(
bnToU8a(new BN(1234), 32, false)
@@ -70,5 +46,67 @@ describe('bnToU8a', (): void => {
);
});
performance('bnToU8a', 250000, ptest, bnToU8a);
describe('signed', (): void => {
it('converts negative numbers (BE)', (): void => {
expect(
bnToU8a(new BN(-1234), { isLe: false, isNegative: true })
).toEqual(new Uint8Array([251, 46]));
});
it('converts negative numbers (LE, i8)', (): void => {
expect(
bnToU8a(new BN(-12), { isNegative: true })
).toEqual(new Uint8Array([244]));
});
it('converts negative numbers (LE, i16)', (): void => {
expect(
bnToU8a(new BN(-1234), { isNegative: true })
).toEqual(new Uint8Array([46, 251]));
});
it('converts negative numbers (LE, i24)', (): void => {
expect(
bnToU8a(new BN(-123456), { isNegative: true })
).toEqual(new Uint8Array([192, 29, 254]));
});
it('converts negative numbers (LE, i32)', (): void => {
expect(
bnToU8a(new BN(-123456789), { isNegative: true })
).toEqual(new Uint8Array([235, 50, 164, 248]));
});
it('converts negative numbers (LE, i40)', (): void => {
expect(
bnToU8a(new BN(-5678999999), { isNegative: true })
).toEqual(new Uint8Array([65, 86, 129, 173, 254]));
});
it('converts negative numbers (LE, i48)', (): void => {
expect(
bnToU8a(new BN(-9999999999999), { isNegative: true })
).toEqual(new Uint8Array([1, 96, 141, 177, 231, 246]));
});
it('converts negative numbers (LE, i64)', (): void => {
expect(
bnToU8a(new BN('-999999999999999999'), { isNegative: true })
).toEqual(new Uint8Array([1, 0, 156, 88, 76, 73, 31, 242]));
});
it('converts negative numbers (LE, bitLength)', (): void => {
expect(
bnToU8a(new BN(-1234), { bitLength: 32, isNegative: true })
).toEqual(new Uint8Array([46, 251, 255, 255]));
});
it('converts negative numbers (LE, bitLength)', (): void => {
expect(
bnToU8a(new BN(-123456), { bitLength: 32, isNegative: true })
).toEqual(new Uint8Array([192, 29, 254, 255]));
});
});
perf('bnToU8a', 250000, ptest, bnToU8a);
});
+4 -8
View File
@@ -5,7 +5,6 @@ import type { NumberOptions, ToBn } from '../types';
import type { BN } from './bn';
import { isNumber } from '../is/number';
import { objectSpread } from '../object/spread';
import { bnToBn } from './toBn';
const DEFAULT_OPTS: NumberOptions = { bitLength: -1, isLe: true, isNegative: false };
@@ -28,13 +27,10 @@ function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number
/** @deprecated Use bnToU8a(value?: ExtToBn | BN | bigint | number | null, options?: NumberOptions) */
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, bitLength?: number, isLe?: boolean): Uint8Array;
/** @deprecated Use bnToU8a(value?: ExtToBn | BN | bigint | number | null, options?: NumberOptions) */
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, arg1: number | NumberOptions = DEFAULT_OPTS, arg2?: boolean): Uint8Array {
const { bitLength, isLe, isNegative }: NumberOptions = objectSpread(
{ bitLength: -1, isLe: true, isNegative: false },
isNumber(arg1)
? { bitLength: arg1, isLe: arg2 }
: arg1
);
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, arg1: number | NumberOptions = DEFAULT_OPTS, arg2 = true): Uint8Array {
const { bitLength = -1, isLe = true, isNegative = false } = isNumber(arg1)
? { bitLength: arg1, isLe: arg2 }
: arg1;
const valueBn = bnToBn(value);
const byteLength = bitLength === -1
+1
View File
@@ -13,6 +13,7 @@ export * from './bn';
export * from './buffer';
export * from './compact';
export * from './extractTime';
export * from './float';
export * from './format';
export * from './has';
export * from './hex';
+1
View File
@@ -3,4 +3,5 @@
import type { BitLength } from './types';
/** @internal */
export const DEFAULT_BITLENGTH: BitLength = 32;
+7 -7
View File
@@ -3,7 +3,7 @@
import { BN } from '../bn/bn';
import { hexToU8a } from '../hex/toU8a';
import { performance } from '../test/performance';
import { perf } from '../test/performance';
import { compactFromU8a, compactFromU8aLim } from '.';
describe('compactFromU8a', (): void => {
@@ -73,10 +73,10 @@ describe('compactFromU8a', (): void => {
).toEqual('100000000');
});
performance('compactFromU8a (u8)', 1_000_000, [[new Uint8Array([63 << 2])]], compactFromU8a);
performance('compactFromU8a (u16)', 1_000_000, [[new Uint8Array([0b11111101, 0b00000111])]], compactFromU8a);
performance('compactFromU8a (u32)', 1_000_000, [[new Uint8Array([254, 255, 3, 0])]], compactFromU8a);
performance('compactFromU8aLim (u32)', 1_000_000, [[new Uint8Array([254, 255, 3, 0])]], compactFromU8aLim);
performance('compactFromU8a (u48)', 1_000_000, [[hexToU8a('0x0b00407a10f35a')]], compactFromU8a);
performance('compactFromU8a (u96)', 250_000, [[new Uint8Array([23, 52, 0x40, 0x7a, 0x10, 0xf3, 0x5a, 0, 0, 18])]], compactFromU8a);
perf('compactFromU8a (u8)', 1_000_000, [[new Uint8Array([63 << 2])]], compactFromU8a);
perf('compactFromU8a (u16)', 1_000_000, [[new Uint8Array([0b11111101, 0b00000111])]], compactFromU8a);
perf('compactFromU8a (u32)', 1_000_000, [[new Uint8Array([254, 255, 3, 0])]], compactFromU8a);
perf('compactFromU8aLim (u32)', 1_000_000, [[new Uint8Array([254, 255, 3, 0])]], compactFromU8aLim);
perf('compactFromU8a (u48)', 1_000_000, [[hexToU8a('0x0b00407a10f35a')]], compactFromU8a);
perf('compactFromU8a (u96)', 250_000, [[new Uint8Array([23, 52, 0x40, 0x7a, 0x10, 0xf3, 0x5a, 0, 0, 18])]], compactFromU8a);
});
+45 -43
View File
@@ -30,35 +30,38 @@ export function compactFromU8a (input: U8aLike): [number, BN] {
return [1, new BN(u8a[0] >>> 2)];
case 0b01:
return [2, new BN((u8a[0] + (u8a[1] * 0x1_00)) >>> 2)];
return [2, new BN((u8a[0] + (u8a[1] << 8)) >>> 2)];
case 0b10:
return [4, new BN((u8a[0] + (u8a[1] * 0x1_00) + (u8a[2] * 0x1_00_00) + (u8a[3] * 0x1_00_00_00)) >>> 2)];
// for the 3rd byte, we don't << 24 - since JS converts all bitwise operators to
// 32-bit, in the case where the top-most bit is set this yields a negative value
return [4, new BN((u8a[0] + (u8a[1] << 8) + (u8a[2] << 16) + (u8a[3] * 0x1_00_00_00)) >>> 2)];
// 0b11
default:
break;
}
default: {
// add 5 to shifted (4 for base length, 1 for this byte)
const offset = (u8a[0] >>> 2) + 5;
// add 5 to shifted (4 for base length, 1 for this byte)
const offset = (u8a[0] >>> 2) + 5;
// we unroll the loop
switch (offset) {
// there still could be 4 bytes data, similar to 0b10 above (with offsets)
case 5:
// for the 3rd byte, we don't << 24 - since JS converts all bitwise operators to
// 32-bit, in the case where the top-most bit is set this yields a negative value
return [5, new BN(u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + (u8a[4] * 0x1_00_00_00))];
// we unroll the loop
switch (offset) {
// there still could be 4 bytes data, similar to 0b10 above (with offsets)
case 5:
return [5, new BN(u8a[1] + (u8a[2] * 0x1_00) + (u8a[3] * 0x1_00_00) + (u8a[4] * 0x1_00_00_00))];
case 6:
return [6, new BN(u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + ((u8a[4] + (u8a[5] << 8)) * 0x1_00_00_00))];
case 6:
return [6, new BN(u8a[1] + (u8a[2] * 0x1_00) + (u8a[3] * 0x1_00_00) + (u8a[4] * 0x1_00_00_00) + (u8a[5] * 0x1_00_00_00_00))];
// 6 bytes data is the maximum, 48 bits (56 would overflow)
case 7:
return [7, new BN(u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + ((u8a[4] + (u8a[5] << 8) + (u8a[6] << 16)) * 0x1_00_00_00))];
// 6 bytes data is the maximum, 48 bits (56 would overflow)
case 7:
return [7, new BN(u8a[1] + (u8a[2] * 0x1_00) + (u8a[3] * 0x1_00_00) + (u8a[4] * 0x1_00_00_00) + (u8a[5] * 0x1_00_00_00_00) + (u8a[6] * 0x1_00_00_00_00_00))];
// for anything else, use the non-unrolled version
default:
return [offset, u8aToBn(u8a.subarray(1, offset))];
// for anything else, use the non-unrolled version
default:
return [offset, u8aToBn(u8a.subarray(1, offset))];
}
}
}
}
@@ -74,34 +77,33 @@ export function compactFromU8aLim (u8a: Uint8Array): [number, number] {
return [1, u8a[0] >>> 2];
case 0b01:
return [2, (u8a[0] + (u8a[1] * 0x1_00)) >>> 2];
return [2, (u8a[0] + (u8a[1] << 8)) >>> 2];
case 0b10:
return [4, (u8a[0] + (u8a[1] * 0x1_00) + (u8a[2] * 0x1_00_00) + (u8a[3] * 0x1_00_00_00)) >>> 2];
// for the 3rd byte, we don't << 24 - since JS converts all bitwise operators to
// 32-bit, in the case where the top-most bit is set this yields a negative value
return [4, (u8a[0] + (u8a[1] << 8) + (u8a[2] << 16) + (u8a[3] * 0x1_00_00_00)) >>> 2];
// 0b11
default:
break;
}
default: {
// add 5 to shifted (4 for base length, 1 for this byte)
// we unroll the loop
switch ((u8a[0] >>> 2) + 5) {
// there still could be 4 bytes data, similar to 0b10 above (with offsets)
case 5:
return [5, u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + (u8a[4] * 0x1_00_00_00)];
// add 5 to shifted (4 for base length, 1 for this byte)
const offset = (u8a[0] >>> 2) + 5;
case 6:
return [6, u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + ((u8a[4] + (u8a[5] << 8)) * 0x1_00_00_00)];
// we unroll the loop
switch (offset) {
// there still could be 4 bytes data, similar to 0b10 above (with offsets)
case 5:
return [5, u8a[1] + (u8a[2] * 0x1_00) + (u8a[3] * 0x1_00_00) + (u8a[4] * 0x1_00_00_00)];
// 6 bytes data is the maximum, 48 bits (56 would overflow)
case 7:
return [7, u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + ((u8a[4] + (u8a[5] << 8) + (u8a[6] << 16)) * 0x1_00_00_00)];
case 6:
return [6, u8a[1] + (u8a[2] * 0x1_00) + (u8a[3] * 0x1_00_00) + (u8a[4] * 0x1_00_00_00) + (u8a[5] * 0x1_00_00_00_00)];
// 6 bytes data is the maximum, 48 bits (56 would overflow)
case 7:
return [7, u8a[1] + (u8a[2] * 0x1_00) + (u8a[3] * 0x1_00_00) + (u8a[4] * 0x1_00_00_00) + (u8a[5] * 0x1_00_00_00_00) + (u8a[6] * 0x1_00_00_00_00_00)];
// for anything else, use the non-unrolled version
default:
throw new Error('Compact input is > Number.MAX_SAFE_INTEGER');
// for anything else, we are above the actual MAX_SAFE_INTEGER - bail out
default:
throw new Error('Compact input is > Number.MAX_SAFE_INTEGER');
}
}
}
}
+3 -2
View File
@@ -1,7 +1,6 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { assert } from '../assert';
import { BN, BN_ONE, BN_TWO, bnToBn, bnToU8a } from '../bn';
import { u8aConcatStrict } from '../u8a';
@@ -42,7 +41,9 @@ export function compactToU8a (value: BN | bigint | number): Uint8Array {
length--;
}
assert(length >= 4, 'Invalid length, previous checks match anything less than 2^30');
if (length < 4) {
throw new Error('Invalid length, previous checks match anything less than 2^30');
}
return u8aConcatStrict([
// subtract 4 as minimum (also catered for in decoding)
+28 -44
View File
@@ -3,67 +3,51 @@
import type { Time } from './types';
import { objectSpread } from './object/spread';
const HRS = 60 * 60;
const DAY = HRS * 24;
const MIN_MS = 60 * 1000;
const HR_MS = MIN_MS * 60;
const DAY_MS = HR_MS * 24;
const ZERO: Time = { days: 0, hours: 0, milliseconds: 0, minutes: 0, seconds: 0 };
/**
* @name addTime
* @summary Add together two Time arrays
*/
function addTime (a: Time, b: Time): Time {
/** @internal */
function add (a: Partial<Time>, b: Time): Time {
return {
days: a.days + b.days,
hours: a.hours + b.hours,
milliseconds: a.milliseconds + b.milliseconds,
minutes: a.minutes + b.minutes,
seconds: a.seconds + b.seconds
days: (a.days || 0) + b.days,
hours: (a.hours || 0) + b.hours,
milliseconds: (a.milliseconds || 0) + b.milliseconds,
minutes: (a.minutes || 0) + b.minutes,
seconds: (a.seconds || 0) + b.seconds
};
}
function extractDays (milliseconds: number, hrs: number): Time {
const days = Math.floor(hrs / 24);
/** @internal */
function extractSecs (ms: number): Time {
const s = ms / 1000;
return addTime(objectSpread({}, ZERO, { days }), extractTime(milliseconds - (days * DAY * 1000)));
}
if (s < 60) {
const seconds = ~~s;
function extractHrs (milliseconds: number, mins: number): Time {
const hrs = mins / 60;
if (hrs < 24) {
const hours = Math.floor(hrs);
return addTime(objectSpread({}, ZERO, { hours }), extractTime(milliseconds - (hours * HRS * 1000)));
return add({ seconds }, extractTime(ms - (seconds * 1000)));
}
return extractDays(milliseconds, hrs);
}
const m = s / 60;
function extractMins (milliseconds: number, secs: number): Time {
const mins = secs / 60;
if (m < 60) {
const minutes = ~~m;
if (mins < 60) {
const minutes = Math.floor(mins);
return addTime(objectSpread({}, ZERO, { minutes }), extractTime(milliseconds - (minutes * 60 * 1000)));
return add({ minutes }, extractTime(ms - (minutes * MIN_MS)));
}
return extractHrs(milliseconds, mins);
}
const h = m / 60;
function extractSecs (milliseconds: number): Time {
const secs = milliseconds / 1000;
if (h < 24) {
const hours = ~~h;
if (secs < 60) {
const seconds = Math.floor(secs);
return addTime(objectSpread({}, ZERO, { seconds }), extractTime(milliseconds - (seconds * 1000)));
return add({ hours }, extractTime(ms - (hours * HR_MS)));
}
return extractMins(milliseconds, secs);
const days = ~~(h / 24);
return add({ days }, extractTime(ms - (days * DAY_MS)));
}
/**
@@ -82,6 +66,6 @@ export function extractTime (milliseconds?: number): Time {
return !milliseconds
? ZERO
: milliseconds < 1000
? objectSpread({}, ZERO, { milliseconds })
? add({ milliseconds }, ZERO)
: extractSecs(milliseconds);
}
+4
View File
@@ -0,0 +1,4 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
export { floatToU8a } from './toU8a';
+90
View File
@@ -0,0 +1,90 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { u8aToHex } from '../u8a';
import { floatToU8a } from '.';
describe('floatToU8a', (): void => {
it('throws on invalid bitLength', (): void => {
expect(
() => floatToU8a(123, { bitLength: 48 as 32 })
).toThrow();
});
describe('32-bit', (): void => {
it('correctly encodes +0.0', (): void => {
expect(
u8aToHex(floatToU8a(+0.0))
).toEqual('0x00000000');
});
it('correctly encodes -0.0', (): void => {
expect(
u8aToHex(floatToU8a(-0.0))
).toEqual('0x00000080');
});
it('correctly encodes -0.0 (BE)', (): void => {
expect(
u8aToHex(floatToU8a(-0.0, { isLe: false }))
).toEqual('0x80000000');
});
it('encodes NaN', (): void => {
expect(
u8aToHex(floatToU8a(Number.NaN, { isLe: true }))
).toEqual('0x0000c07f');
});
describe('equivalency', (): void => {
it('encodes number 123.456', (): void => {
expect(
u8aToHex(floatToU8a(123.456))
).toEqual('0x79e9f642');
});
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';
}
// https://www.h-schmidt.net/FloatConverter/IEEE754.html
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');
});
});
});
+32
View File
@@ -0,0 +1,32 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
// eslint-disable-next-line @typescript-eslint/ban-types
type AnyFloat = number | Number;
interface Options {
bitLength?: 32 | 64;
isLe?: boolean;
}
/**
* @name floatToU8a
* @description Converts a float into a U8a representation (While we don't use BE in SCALE
* we still allow for either representation, although, as elsewhere, isLe is default)
*/
export function floatToU8a (value: string | AnyFloat = 0.0, { bitLength = 32, isLe = true }: Options = {}): Uint8Array {
if (bitLength !== 32 && bitLength !== 64) {
throw new Error('Invalid bitLength provided, expected 32 or 64');
}
const result = new Uint8Array(bitLength / 8);
const dv = new DataView(result.buffer, result.byteOffset);
if (bitLength === 32) {
dv.setFloat32(0, Number(value), isLe);
} else {
dv.setFloat64(0, Number(value), isLe);
}
return result;
}
+2 -3
View File
@@ -6,7 +6,6 @@ import type { SiDef, ToBn } from '../types';
import { bnToBn } from '../bn/toBn';
import { isBoolean } from '../is/boolean';
import { isUndefined } from '../is/undefined';
import { formatDecimal } from './formatDecimal';
import { calcSi, findSi, SI, SI_MID } from './si';
@@ -147,12 +146,12 @@ formatBalance.getOptions = (decimals: number = defaultDecimals): SiDef[] => {
// Sets the default decimals to use for formatting (ui-wide)
// eslint-disable-next-line @typescript-eslint/unbound-method
formatBalance.setDefaults = ({ decimals, unit }: SetDefaults): void => {
defaultDecimals = isUndefined(decimals)
defaultDecimals = decimals === undefined
? defaultDecimals
: Array.isArray(decimals)
? decimals[0]
: decimals;
defaultUnit = isUndefined(unit)
defaultUnit = unit === undefined
? defaultUnit
: Array.isArray(unit)
? unit[0]
+4
View File
@@ -6,6 +6,10 @@ function zeroPad (value: number): string {
return value.toString().padStart(2, '0');
}
/**
* @name formatDate
* @description Formats a date in CCYY-MM-DD HH:MM:SS format
*/
export function formatDate (date: Date): string {
const year = date.getFullYear().toString();
const month = zeroPad((date.getMonth() + 1));
@@ -4,6 +4,10 @@
// eslint-disable-next-line prefer-regex-literals
const NUMBER_REGEX = new RegExp('(\\d+?)(?=(\\d{3})+(?!\\d)|$)', 'g');
/**
* @name formatDecimal
* @description Formats a number into string format with thousand seperators
*/
export function formatDecimal (value: string): string {
// We can do this by adjusting the regx, however for the sake of clarity
// we rather strip and re-add the negative sign in the output
@@ -6,6 +6,7 @@ import type { ToBn } from '../types';
import { bnToBn } from '../bn/toBn';
/** @internal */
function formatValue (elapsed: number): string {
if (elapsed < 15) {
return `${elapsed.toFixed(1)}s`;
@@ -18,6 +19,10 @@ function formatValue (elapsed: number): string {
return `${elapsed / 3600 | 0}h`;
}
/**
* @name formatElapsed
* @description Formats an elapsed value into s, m, h or day segments
*/
export function formatElapsed <ExtToBn extends ToBn> (now?: Date | null, value?: bigint | BN | ExtToBn | Date | number | null): string {
const tsNow = (now && now.getTime()) || 0;
const tsValue = value instanceof Date
+4
View File
@@ -7,6 +7,10 @@ import type { ToBn } from '../types';
import { bnToBn } from '../bn/toBn';
import { formatDecimal } from './formatDecimal';
/**
* @name formatNumber
* @description Formats a number into string format with thousand seperators
*/
export function formatNumber <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null): string {
return formatDecimal(bnToBn(value).toString());
}
+4
View File
@@ -3,8 +3,10 @@
import type { SiDef } from '../types';
/** @internal */
export const SI_MID = 8;
/** @internal */
export const SI: SiDef[] = [
{ power: -24, text: 'yocto', value: 'y' },
{ power: -21, text: 'zepto', value: 'z' },
@@ -26,6 +28,7 @@ export const SI: SiDef[] = [
];
// Given a SI type (e.g. k, m, Y) find the SI definition
/** @internal */
export function findSi (type: string): SiDef {
// use a loop here, better RN support (which doesn't have [].find)
for (let i = 0; i < SI.length; i++) {
@@ -37,6 +40,7 @@ export function findSi (type: string): SiDef {
return SI[SI_MID];
}
/** @internal */
export function calcSi (text: string, decimals: number, forceUnit?: string): SiDef {
if (forceUnit) {
return findSi(forceUnit);
+13
View File
@@ -3,10 +3,23 @@
import { BigInt } from '@polkadot/x-bigint';
/** true if the environment has proper BigInt support */
export const hasBigInt = typeof BigInt === 'function' && typeof BigInt.asIntN === 'function';
/** true if the environment has support for Buffer */
export const hasBuffer = typeof Buffer !== 'undefined';
/** true if the environment is CJS */
export const hasCjs = typeof require === 'function' && typeof module !== 'undefined';
/** true if the environment has __dirname available */
export const hasDirname = typeof __dirname !== 'undefined';
/** true if the environment is ESM */
export const hasEsm = !hasCjs;
/** true if the environment has process available (typically Node.js) */
export const hasProcess = typeof process === 'object';
/** true if the environment has WebAssembly available */
export const hasWasm = typeof WebAssembly !== 'undefined';

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