Compare commits

...
164 Commits
Author SHA1 Message Date
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
github-actions[bot] a14bec79f8 [CI Skip] release/stable 9.4.1
skip-checks: true
2022-06-04 05:10:26 +00:00
Jaco c0de5ac3c8 9.4.1 (#1514) 2022-06-04 08:05:32 +03:00
github-actions[bot] 8d7f810556 [CI Skip] release/beta 9.3.2-4
skip-checks: true
2022-06-04 04:48:08 +00:00
Jaco 5c6526a6bd Bump deps (#1513) 2022-06-04 07:44:30 +03:00
github-actions[bot] e9635ab75b [CI Skip] release/beta 9.3.2-3
skip-checks: true
2022-06-03 15:57:54 +00:00
Jaco e946243b6f Additional performance tests (#1512) 2022-06-03 18:53:57 +03:00
github-actions[bot] ca6a4177b5 [CI Skip] release/beta 9.3.2-2
skip-checks: true
2022-06-03 07:24:22 +00:00
Jaco 7817311f84 Bump dev deps (#1511) 2022-06-03 10:20:26 +03:00
github-actions[bot] 77659aae2a [CI Skip] release/beta 9.3.2-1
skip-checks: true
2022-06-01 05:18:41 +00:00
Jaco 7cc619fbb0 Add nextTick (#1510)
* Add nextTick

* ss58Registry test results
2022-06-01 08:14:42 +03:00
github-actions[bot] 887654049e [CI Skip] release/beta 9.3.2-0
skip-checks: true
2022-05-30 07:51:32 +00:00
Jaco d07b79f578 Bump TS (#1508)
* Bump TS

* Override
2022-05-30 10:46:38 +03:00
github-actions[bot] cefeb0bb51 [CI Skip] release/stable 9.3.1
skip-checks: true
2022-05-29 06:27:05 +00:00
Jaco 1d675ec803 9.3.1 (#1507) 2022-05-29 09:23:01 +03:00
github-actions[bot] 7596dfa65c [CI Skip] release/beta 9.2.2-16
skip-checks: true
2022-05-28 10:40:10 +00:00
Jaco 508e997c64 Bump deps (#1506) 2022-05-28 13:35:56 +03:00
github-actions[bot] 89563ee05c [CI Skip] release/beta 9.2.2-15
skip-checks: true
2022-05-27 08:15:04 +00:00
Jaco 8b72584d53 Add compactFromU8aLim (Remove extraneous *Strict) (#1505)
* Add compactFromU8aLim (Remove extraoneous *Strict)

* Fix build
2022-05-27 11:10:56 +03:00
github-actions[bot] 4ae62c114b [CI Skip] release/beta 9.2.2-14
skip-checks: true
2022-05-27 06:20:09 +00:00
Jaco 823fb51d18 Use for loop in string{Came, Pascal}Case conversions (#1504)
* Use for loop in string{Came, Pascal}Case conversions

* Missing +-= (removed as test)
2022-05-27 09:15:56 +03:00
github-actions[bot] a840b815bd [CI Skip] release/beta 9.2.2-13
skip-checks: true
2022-05-25 07:06:12 +00:00
Jaco fbf973dc2a Add u8a-only strict variants (#1503) 2022-05-25 10:02:01 +03:00
github-actions[bot] 2698f6779f [CI Skip] release/beta 9.2.2-12
skip-checks: true
2022-05-25 04:30:46 +00:00
Jaco 3b5de80c54 Compact loop unrolling (#1502) 2022-05-25 07:26:07 +03:00
github-actions[bot] 041f5a7c2b [CI Skip] release/beta 9.2.2-11
skip-checks: true
2022-05-24 15:32:58 +00:00
Jaco cb8f1130af No indirection via isCompact call (#1501) 2022-05-24 18:28:43 +03:00
github-actions[bot] f480df7504 [CI Skip] release/beta 9.2.2-10
skip-checks: true
2022-05-24 15:00:08 +00:00
Jaco 51763d3bf9 Adjust instanceof checks (#1500) 2022-05-24 17:56:01 +03:00
github-actions[bot] d2b7e88060 [CI Skip] release/beta 9.2.2-9
skip-checks: true
2022-05-24 14:31:54 +00:00
Jaco b20df563ce Buffer short-circuit (onlky convert when non-Uint8Array) (#1499) 2022-05-24 17:27:47 +03:00
github-actions[bot] 5ada180d66 [CI Skip] release/beta 9.2.2-8
skip-checks: true
2022-05-24 13:47:16 +00:00
Jaco a4256de444 Small u8aToU8a optimizations (#1498)
* Small u8aToU8a optimizations

* Slight order adjustments

* Adjust
2022-05-24 16:42:58 +03:00
github-actions[bot] bce5553a4b [CI Skip] release/beta 9.2.2-7
skip-checks: true
2022-05-24 11:44:49 +00:00
Carlo Sala 670743cbcf some changes to KnownLedger (#1497)
* add `nodle-para` chain

* add astar and polkadex to KnownLedger

* remove `nodle-chain`
2022-05-24 14:39:50 +03:00
github-actions[bot] ffed9ceb6d [CI Skip] release/beta 9.2.2-6
skip-checks: true
2022-05-22 08:44:56 +00:00
Jaco bbacb1b80a Bump deps (#1496) 2022-05-22 11:40:09 +03:00
github-actions[bot] 5ea38c9898 [CI Skip] release/beta 9.2.2-5
skip-checks: true
2022-05-20 12:21:52 +00:00
Jaco 7177722a49 Fix buffer imports (#1495) 2022-05-20 15:17:39 +03:00
github-actions[bot] 6083923604 [CI Skip] release/beta 9.2.2-4
skip-checks: true
2022-05-20 10:04:53 +00:00
Jaco 7a3e1c23aa Internal bip32 mnemonicGenerate takes numWords param (#1494)
* Internal bip32 mnemonicGenerate takes numWords param

* Bump deps

* Calculate Calculate strength

* Remove duplicated assert
2022-05-20 13:00:07 +03:00
github-actions[bot] cab50dbf7a [CI Skip] release/beta 9.2.2-3
skip-checks: true
2022-05-20 09:01:11 +00:00
Jaco 9964b308ce Small readability cleanups (#1493) 2022-05-20 11:56:01 +03:00
github-actions[bot] 247a0e7227 [CI Skip] release/beta 9.2.2-2
skip-checks: true
2022-05-20 06:07:23 +00:00
Jaco f2dba8aff8 Small typo cleanups (#1492) 2022-05-20 09:02:32 +03:00
github-actions[bot] 2ef18335e3 [CI Skip] release/beta 9.2.2-1
skip-checks: true
2022-05-20 05:59:47 +00:00
Jaco fa0818d088 Small addressToEvm non-local change (#1491) 2022-05-20 08:55:58 +03:00
github-actions[bot] 2106626f22 [CI Skip] release/beta 9.2.2-0
skip-checks: true
2022-05-16 09:17:38 +00:00
Carlo Sala fceab0becc add parallel to KnownLedger (#1490) 2022-05-16 12:13:31 +03:00
github-actions[bot] bdf42368f7 [CI Skip] release/stable 9.2.1
skip-checks: true
2022-05-13 19:21:22 +00:00
Jaco 36ab5ea5e2 9.2.1 (#1489) 2022-05-13 22:16:25 +03:00
github-actions[bot] c5c8469038 [CI Skip] release/beta 9.1.2-11
skip-checks: true
2022-05-13 08:24:30 +00:00
Jaco 83d0121a28 Additional deprecations (#1488)
* Additional deprecations

* Unsigned shift

* Adjust

* offset calc
2022-05-13 11:19:20 +03:00
github-actions[bot] aff74ebde3 [CI Skip] release/beta 9.1.2-10
skip-checks: true
2022-05-13 06:46:09 +00:00
Jaco be4619ba3d MArk deprecated function signatures (#1487) 2022-05-13 09:40:43 +03:00
github-actions[bot] 17bc2e9fa0 [CI Skip] release/beta 9.1.2-9
skip-checks: true
2022-05-13 05:39:36 +00:00
Jaco 66e2382f26 Re-add top-level cryptoWaitReady (#1486) 2022-05-13 08:34:53 +03:00
github-actions[bot] 6c299f81c6 [CI Skip] release/beta 9.1.2-8
skip-checks: true
2022-05-13 04:33:17 +00:00
Nantian a4fcba6ff6 add acala ledger config (#1485) 2022-05-13 07:29:10 +03:00
github-actions[bot] 1a3507366e [CI Skip] release/beta 9.1.2-7
skip-checks: true
2022-05-12 09:18:43 +00:00
Jaco 65939dbe9d Signed conversion on empty u8a (#1484) 2022-05-12 12:14:34 +03:00
github-actions[bot] 6914411232 [CI Skip] release/beta 9.1.2-6
skip-checks: true
2022-05-12 07:59:10 +00:00
Jaco c79f46aaa2 Bump to beta @polkadot/wasm-* (#1483) 2022-05-12 10:55:00 +03:00
github-actions[bot] cea09b2c8b [CI Skip] release/beta 9.1.2-5
skip-checks: true
2022-05-12 05:14:44 +00:00
Jaco bc23ed9fc9 Bump deps (#1482) 2022-05-12 08:09:53 +03:00
github-actions[bot] a4f286e89a [CI Skip] release/beta 9.1.2-4
skip-checks: true
2022-05-10 07:02:34 +00:00
Jaco f112f9eb5e Bump deps (#1480) 2022-05-10 09:57:45 +03:00
github-actions[bot] 010552ca44 [CI Skip] release/beta 9.1.2-3
skip-checks: true
2022-05-09 09:54:37 +00:00
Jaco 9ae4b1066e Change all occurences of .substr(...) to .substring(...) (#1479) 2022-05-09 12:50:13 +03:00
github-actions[bot] 1a57abde6e [CI Skip] release/beta 9.1.2-2
skip-checks: true
2022-05-09 08:11:13 +00:00
Jaco cf4b44940e Bump dev (#1478) 2022-05-09 11:05:53 +03:00
github-actions[bot] 81e19aace4 [CI Skip] release/beta 9.1.2-1
skip-checks: true
2022-05-07 08:58:12 +00:00
Jaco 7341c32df5 Optimize u8aToHex with direct (non-hex) conversion (#1477)
* Optimize `u8aToHex` with direct (non-hex) conversion

* Adjust compactFromU8a tests
2022-05-07 11:54:08 +03:00
github-actions[bot] bb1ed6cfcd [CI Skip] release/beta 9.1.2-0
skip-checks: true
2022-05-05 06:07:20 +00:00
Jaco 55dcfb5e18 Bump @polkadot/dev (#1476) 2022-05-05 09:03:33 +03:00
github-actions[bot] 2fe9e5a125 [CI Skip] release/stable 9.1.1
skip-checks: true
2022-04-30 05:30:01 +00:00
Jaco e24385213d 9.1.1 (#1473) 2022-04-30 08:25:32 +03:00
github-actions[bot] 9cd81a23e7 [CI Skip] release/beta 9.0.2-11
skip-checks: true
2022-04-30 05:08:24 +00:00
Jaco 64348860cb Bump dev (#1472) 2022-04-30 08:04:24 +03:00
github-actions[bot] ecfceb5d0a [CI Skip] release/beta 9.0.2-10
skip-checks: true
2022-04-29 11:28:19 +00:00
Jaco cc840c37a2 Bump TS (#1471) 2022-04-29 14:24:27 +03:00
github-actions[bot] 527af12b0f [CI Skip] release/beta 9.0.2-9
skip-checks: true
2022-04-29 05:40:33 +00:00
Jaco 9f2b98d5a8 New Rococo genesis (#1470)
* New Rococo genesis

* CHANGELOG
2022-04-29 08:35:39 +03:00
github-actions[bot] 4bd767fb62 [CI Skip] release/beta 9.0.2-8
skip-checks: true
2022-04-28 10:18:44 +00:00
Jaco cff29dfd2d Jg type comments (#1469)
* Add some field-level comments on the keyring

* CHANGELOG
2022-04-28 13:13:32 +03:00
github-actions[bot] d26b80905c [CI Skip] release/beta 9.0.2-7
skip-checks: true
2022-04-27 17:26:43 +00:00
Carlo Sala 4249679882 feat(networks): add statemint to KnownLedger (#1467)
* feat(networks): add statemint

* feat(hw-ledger): add statemint
2022-04-27 20:21:27 +03:00
github-actions[bot] ff27055808 [CI Skip] release/beta 9.0.2-6
skip-checks: true
2022-04-27 06:57:00 +00:00
Jaco 54f8acb27f Bump @polkadot/dev (#1466) 2022-04-27 09:51:59 +03:00
github-actions[bot] 017bebe8bb [CI Skip] release/beta 9.0.2-5
skip-checks: true
2022-04-24 09:21:21 +00:00
Jaco 89f5670d8b Bump @polkadot/dev (#1464) 2022-04-24 12:17:18 +03:00
github-actions[bot] b9e2293bee [CI Skip] release/beta 9.0.2-4
skip-checks: true
2022-04-20 17:40:13 +00:00
xx networkandBernardo Cardoso 3b45418e47 Add xxnetwork genesis hash and ledger app (#1463)
* Add xxnetwork genesis hash and ledger app

* Update test

Co-authored-by: Bernardo Cardoso <bernardo@xx.network>
2022-04-20 20:35:20 +03:00
github-actions[bot] 6af7f6ef24 [CI Skip] release/beta 9.0.2-3
skip-checks: true
2022-04-19 14:02:14 +00:00
Jaco a0b85ee7f8 Bump deps (#1462) 2022-04-19 16:58:00 +03:00
github-actions[bot] 2e0c6c3368 [CI Skip] release/beta 9.0.2-2
skip-checks: true
2022-04-14 04:21:59 +00:00
Jaco 1d36284369 Adjust isHex performance test (#1461) 2022-04-14 07:18:01 +03:00
github-actions[bot] 94788692bb [CI Skip] release/beta 9.0.2-1
skip-checks: true
2022-04-13 05:37:51 +00:00
Jaco 1f3f5d5980 Adjust detectPackage formatting (#1460) 2022-04-13 08:33:37 +03:00
github-actions[bot] 90c2638221 [CI Skip] release/beta 9.0.2-0
skip-checks: true
2022-04-12 05:02:30 +00:00
Jaco 98e02a0baa Bump deps (#1459) 2022-04-12 07:58:00 +03:00
github-actions[bot] e96a204bb5 [CI Skip] release/stable 9.0.1
skip-checks: true
2022-04-09 07:44:36 +00:00
Jaco 0dc4ec48da 9.0.1 (#1457) 2022-04-09 10:40:27 +03:00
github-actions[bot] 5d5c7e4c0a [CI Skip] release/beta 8.7.2-3
skip-checks: true
2022-04-06 08:53:01 +00:00
Jaco 76c973f5c5 Be explicit in re-exports from @polkadot/networks (#1455) 2022-04-06 11:48:34 +03:00
github-actions[bot] 7608f2eed9 [CI Skip] release/beta 8.7.2-2
skip-checks: true
2022-04-06 08:20:38 +00:00
Jaco e585aa1899 Bump dev (w/ bundleInit shim build) (#1454) 2022-04-06 11:15:52 +03:00
github-actions[bot] 82152352ea [CI Skip] release/beta 8.7.2-1
skip-checks: true
2022-04-05 05:29:20 +00:00
Jaco 515e1d62af Bump to latest @polkadot/dev (#1453) 2022-04-05 08:25:15 +03:00
github-actions[bot] 2d2e6bc1bf [CI Skip] release/beta 8.7.2-0
skip-checks: true
2022-04-01 07:50:06 +00:00
Jaco 5bb89db279 Bump dev deps (#1451) 2022-04-01 10:45:59 +03:00
158 changed files with 3819 additions and 2369 deletions
+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
+2
View File
@@ -1,6 +1,8 @@
--test-*
_book/
build/
build-cjs/
build-esm/
build-docs/
coverage/
docs/.vuepress/dist/
+87
View File
@@ -1,5 +1,92 @@
# CHANGELOG
## 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:
- Add `nextTick` to `@polkadot/util` to defer execution to the queue
- Upgrade dependencies to latest stable versions
## 9.3.1 May 29, 2022
Contributed:
- Add Ledger support for Parallel (Thanks to https://github.com/carlosala)
- Add Ledger support for Astar & Polkadex (Thanks to https://github.com/carlosala)
Changes:
- Adjust `u8aToU8a` checks with better `isU8a` shortcut
- Adjust compact conversion with unrolled loops
- Adjust `string{Camel, Pascal}Case` with loop (no map)
- Add `compactFromU8aLim` variant with Uint8Array-only inputs
- Add `u8aConcatStrict` variant with Uint8Array-only inputs
- Internal code maintainability enhancements
- Upgrade dependencies to latest stable versions
## 9.2.1 May 13, 2022
Contributed:
- Add Ledger support for Acala (Thanks to https://github.com/ntduan)
Changes:
- Optimize `u8aToHex` with direct (non-hex) conversion
- Change all occurences of `.substr(...)` to `.substring(...)`
- Sync with upstream Substrate ss58 registry
- Mark deprecated function signatures (no removals)
- Re-enable auto init of `cryptoWaitReady()`
- Upgrade to `@polkadot/wasm-crypto` 6.1.1
## 9.1.1 Apr 30, 2022
Contributed:
- Add Ledger support for Statemint (Thanks to https://github.com/carlosala)
- Add Ledger support for xxnetwork (Thanks to https://github.com/xx-labs)
Changes:
- Adjust/dedupe output from `detectPackage`
- Adjust `isHex` performance test
- Add field-level comments to some `*Options` structures
- Add new Rococo genesisHash (reset)
## 9.0.1 Apr 9, 2022
- **Breaking change** In this major version the commonjs outputs are moved to a sub-folder. Since the export map and main field in package.json does reflect this change, there should be no usage changes. However the packages here will all need to be on the same version for internal linkage.
Changes:
- Be explicit in `@polkadot/util-crypto` re-exports from `@polkadot/networks`
- Output commonjs files under the `cjs/**` root
- Upgrade to `@polkadot/wasm-crypto` 6.0.1
## 8.7.1 Mar 27, 2022
Changes:
+5 -2
View File
@@ -1,10 +1,12 @@
1288 Jaco 8.7.1 (#1449)
1363 Jaco 9.5.1 (#1545)
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 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)
@@ -12,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)
@@ -33,6 +34,7 @@
1 Mario Neises remove redudant export (#257)
1 Miguel Hervas Add CFG Ledger Support (#1057)
1 nahuseyoum Reserving 65 for Aventus based on the new extended range (#871)
1 Nantian add acala ledger config (#1485)
1 qwer951123 Add acala genesis (#1161)
1 Raoul Millais Fix yarn add instructions in x-global README (#873)
1 Raymond Zhong Add Edgeware ledger app (#1006)
@@ -44,4 +46,5 @@
1 Tore19 Add stafi genesis hash (#1096)
1 Wei Tang ss58: add Kulupu prefix to the list (#595)
1 WoeOm Handing high precision scenes (#450)
1 xx network Add xxnetwork genesis hash and ledger app (#1463)
1 Yuri Extra check for process for browser bundles (#923)
+5 -5
View File
@@ -10,7 +10,7 @@
"url": "https://github.com/polkadot-js/common.git"
},
"sideEffects": false,
"version": "8.7.1",
"version": "9.5.1",
"workspaces": [
"packages/*"
],
@@ -27,11 +27,11 @@
"test:one": "polkadot-dev-run-test --runInBand"
},
"devDependencies": {
"@babel/core": "^7.17.8",
"@polkadot/dev": "^0.65.101",
"@types/jest": "^27.4.1"
"@babel/core": "^7.18.5",
"@polkadot/dev": "^0.67.4",
"@types/jest": "^28.1.2"
},
"resolutions": {
"typescript": "^4.6.3"
"typescript": "^4.7.3"
}
}
+7 -7
View File
@@ -16,18 +16,18 @@
},
"sideEffects": false,
"type": "module",
"version": "8.7.1",
"version": "9.5.1",
"browser": "browser.js",
"main": "node.js",
"react-native": "react-native.js",
"dependencies": {
"@babel/runtime": "^7.17.8",
"@ledgerhq/hw-transport": "^6.24.1",
"@ledgerhq/hw-transport-webhid": "^6.24.1",
"@ledgerhq/hw-transport-webusb": "^6.24.1",
"@polkadot/util": "8.7.1"
"@babel/runtime": "^7.18.3",
"@ledgerhq/hw-transport": "^6.27.1",
"@ledgerhq/hw-transport-webhid": "^6.27.1",
"@ledgerhq/hw-transport-webusb": "^6.27.1",
"@polkadot/util": "9.5.1"
},
"optionalDependencies": {
"@ledgerhq/hw-transport-node-hid-singleton": "^6.26.0"
"@ledgerhq/hw-transport-node-hid-singleton": "^6.27.1"
}
}
@@ -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: '8.7.1' };
export const packageInfo = { name: '@polkadot/hw-ledger-transports', path: 'auto', type: 'auto', version: '9.5.1' };
+6 -6
View File
@@ -19,13 +19,13 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.7.1",
"version": "9.5.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.17.8",
"@ledgerhq/hw-transport": "^6.24.1",
"@polkadot/hw-ledger-transports": "8.7.1",
"@polkadot/util": "8.7.1",
"@zondax/ledger-substrate": "^0.24.0"
"@babel/runtime": "^7.18.3",
"@ledgerhq/hw-transport": "^6.27.1",
"@polkadot/hw-ledger-transports": "9.5.1",
"@polkadot/util": "9.5.1",
"@zondax/ledger-substrate": "^0.31.0"
}
}
+11 -3
View File
@@ -4,20 +4,28 @@
import type Transport from '@ledgerhq/hw-transport';
import type { SubstrateApp } from '@zondax/ledger-substrate';
import { newBifrostApp, newCentrifugeApp, newDockApp, newEdgewareApp, newEquilibriumApp, newGenshiroApp, newKusamaApp, newNodleApp, newPolkadotApp, newPolymeshApp, newSoraApp, newStatemineApp } 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> = {
acala: newAcalaApp,
astar: newAstarApp,
bifrost: newBifrostApp,
centrifuge: newCentrifugeApp,
composable: newComposableApp,
'dock-mainnet': newDockApp,
edgeware: newEdgewareApp,
equilibrium: newEquilibriumApp,
genshiro: newGenshiroApp,
karura: newKaruraApp,
kusama: newKusamaApp,
'nodle-chain': newNodleApp,
'nodle-para': newNodleApp,
parallel: newParallelApp,
polkadex: newPolkadexApp,
polkadot: newPolkadotApp,
polymesh: newPolymeshApp,
sora: newSoraApp,
statemine: newStatemineApp
statemine: newStatemineApp,
statemint: newStatemintApp,
xxnetwork: newXXNetworkApp
};
+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: '8.7.1' };
export const packageInfo = { name: '@polkadot/hw-ledger', path: 'auto', type: 'auto', version: '9.5.1' };
+4 -1
View File
@@ -13,7 +13,7 @@ export interface AccountOptions {
export interface LedgerAddress {
address: string;
publicKey: string;
publicKey: HexString;
}
export interface LedgerSignature {
@@ -23,5 +23,8 @@ export interface LedgerSignature {
export interface LedgerVersion {
isLocked: boolean;
isTestMode: boolean;
/**
* @description Tuple with major, minor, patch
*/
version: [number, number, number];
}
+6 -6
View File
@@ -20,15 +20,15 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.7.1",
"version": "9.5.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.17.8",
"@polkadot/util": "8.7.1",
"@polkadot/util-crypto": "8.7.1"
"@babel/runtime": "^7.18.3",
"@polkadot/util": "9.5.1",
"@polkadot/util-crypto": "9.5.1"
},
"peerDependencies": {
"@polkadot/util": "8.7.1",
"@polkadot/util-crypto": "8.7.1"
"@polkadot/util": "9.5.1",
"@polkadot/util-crypto": "9.5.1"
}
}
+1 -1
View File
@@ -3,4 +3,4 @@
// Do not edit, auto-generated by @polkadot/dev
export const packageInfo = { name: '@polkadot/keyring', path: 'auto', type: 'auto', version: '8.7.1' };
export const packageInfo = { name: '@polkadot/keyring', path: 'auto', type: 'auto', version: '9.5.1' };
+9
View File
@@ -5,7 +5,13 @@ import type { HexString } from '@polkadot/util/types';
import type { EncryptedJson, Keypair, KeypairType, Prefix } from '@polkadot/util-crypto/types';
export interface KeyringOptions {
/**
* @description The ss58Format to use for address encoding (defaults to 42)
*/
ss58Format?: Prefix;
/**
* @description The type of keyring to create (defaults to ed25519)
*/
type?: KeypairType;
}
@@ -17,6 +23,9 @@ export interface KeyringPair$Json extends EncryptedJson {
}
export interface SignOptions {
/**
* @description Create a MultiSignature-compatible output with an indicator type
**/
withType?: boolean;
}
+6 -6
View File
@@ -17,15 +17,15 @@
},
"sideEffects": false,
"type": "module",
"version": "8.7.1",
"version": "9.5.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.17.8",
"@polkadot/util": "8.7.1",
"@substrate/ss58-registry": "^1.17.0"
"@babel/runtime": "^7.18.3",
"@polkadot/util": "9.5.1",
"@substrate/ss58-registry": "^1.22.0"
},
"devDependencies": {
"@polkadot/hw-ledger": "8.7.1",
"@polkadot/x-fetch": "8.7.1"
"@polkadot/hw-ledger": "9.5.1",
"@polkadot/x-fetch": "9.5.1"
}
}
+20 -3
View File
@@ -18,11 +18,15 @@ export const knownGenesis: KnownGenesis = {
'0xa85cfb9b9fd4d622a5b28289a02347af987d8f73fa3108450e2b4a11c1ce5755'
],
bifrost: [
'0x9f28c6a68e0fc9646eff64935684f6eeeece527e37bbe1f213d22caa1d9d6bed'
'0x262e1b2ad728475fd6fe88e62d34c200abe6fd693931ddad144059b1eb884e5b'
],
centrifuge: [
'0xb3db41421702df9a7fcac62b53ffeac85f7853cc4e689e0b93aeb3db18c09d82',
'0x67dddf2673b69e5f875f6f25277495834398eafd67f492e09f3f3345e003d1b5'
],
composable: [
'0xdaab8df776eb52ec604a5df5d388bb62a050a0aaec4556a64265b9d42755552d'
],
'dock-mainnet': [
'0x6bfe24dca2a3be10f22212678ac13a6446ec764103c0f3471c71609eac384aae',
'0xf73467c6544aa68df2ee546b135f955c46b90fa627e9b5d7935f41061bb8a5a9'
@@ -53,12 +57,18 @@ export const knownGenesis: KnownGenesis = {
'0xe3777fa922cafbff200cadeaea1a76bd7898ad5b89f7848999058b50e715f636', // Kusama CC2
'0x3fd7b9eb6a00376e5be61f01abb429ffb0b104be05eaff4d458da48fcd425baf' // Kusama CC1
],
'nodle-chain': [
'0xa3d114c2b8d0627c1aa9b134eafcf7d05ca561fdc19fb388bb9457f81809fb23'
'nodle-para': [
'0x97da7ede98d7bad4e36b4d734b6055425a3be036da2a332ea5a7037656427a21'
],
parallel: [
'0xe61a41c53f5dcd0beb09df93b34402aada44cb05117b71059cce40a2723a4e97'
],
picasso: [
'0xe8e7f0f4c4f5a00720b4821dbfddefea7490bcf0b19009961cc46957984e2c1c'
],
polkadex: [
'0x3920bcb4960a1eef5580cd5367ff3f430eef052774f78468852f7b9cb39f8a3c'
],
polkadot: [
'0x91b171bb158e2d3848fa23a9f1c25182fb8e20313b2c1eb49219da7a70ce90c3'
],
@@ -66,6 +76,7 @@ export const knownGenesis: KnownGenesis = {
'0x6fbd74e5e1d0a61d52ccfe9d4adaed16dd3a7caa37c6bc4d0c2fa12e8b2f4063'
],
rococo: [
'0x6408de7737c59c238890533af25896a2c20608d8b380bb01029acb392781063e',
'0xaaf2cd1b74b5f726895921259421b534124726263982522174147046b8827897',
'0x037f5f3c8e67b314062025fc886fcd6238ea25a4a9b45dce8d246815c9ebe770',
'0xc196f81260cf1686172b47a79cf002120735d7cb0eb1474e8adce56618456fff',
@@ -87,10 +98,16 @@ export const knownGenesis: KnownGenesis = {
statemine: [
'0x48239ef607d7928874027a43a67689209727dfb3d3dc5e5b03a39bdc2eda771a'
],
statemint: [
'0x68d56f15f85d3136970ec16946040bc1752654e906147f7e43e9d539d7c3de2f'
],
subsocial: [
'0x0bd72c1c305172e1275278aaeb3f161e02eccb7a819e63f62d47bd53a28189f8'
],
westend: [
'0xe143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e'
],
xxnetwork: [
'0x50dd5d206917bf10502c68fb4d18a59fc8aa31586f4e8856b493e43544aa82aa'
]
};
+10 -2
View File
@@ -8,16 +8,24 @@ import type { KnownLedger } from '../types';
//
// NOTE: Any network here needs to have a genesisHash attached in the ./genesis.ts config
export const knownLedger: KnownLedger = {
acala: 0x00000313,
astar: 0x0000032a,
bifrost: 0x00000314,
centrifuge: 0x000002eb,
composable: 0x00000162,
'dock-mainnet': 0x00000252,
edgeware: 0x0000020b,
equilibrium: 0x05f5e0fd,
genshiro: 0x05f5e0fc,
karura: 0x000002ae,
kusama: 0x000001b2,
'nodle-chain': 0x000003eb,
'nodle-para': 0x000003eb,
parallel: 0x00000162,
polkadex: 0x0000031f,
polkadot: 0x00000162,
polymesh: 0x00000253,
sora: 0x00000269,
statemine: 0x000001b2 // common-good on Kusama, shares derivation
statemine: 0x000001b2, // common-good on Kusama, shares derivation
statemint: 0x00000162, // common-good on Polkadot, shares derivation
xxnetwork: 0x000007a3
};
+1 -1
View File
@@ -113,6 +113,6 @@ describe('selectableNetworks', (): void => {
it('has a sorted list (first external, last external)', (): void => {
expect(selectableNetworks[3].displayName).toEqual('Acala');
expect(selectableNetworks[selectableNetworks.length - 1].displayName).toEqual('Stafi');
expect(selectableNetworks[selectableNetworks.length - 1].displayName).toEqual('xx network');
});
});
+4
View File
@@ -1,5 +1,9 @@
// Copyright 2017-2022 @polkadot/networks authors & contributors
// SPDX-License-Identifier: Apache-2.0
// TODO: This was removed, really cannot recall the reason...
// ... put it back, but keep it removed
// import './detectPackage';
export * from './interfaces';
export { packageInfo } from './packageInfo';
+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: '8.7.1' };
export const packageInfo = { name: '@polkadot/networks', path: 'auto', type: 'auto', version: '9.5.1' };
+113 -22
View File
@@ -245,22 +245,9 @@
"standardAccount": "*25519",
"website": "https://stafi.io"
},
{
"prefix": 21,
"network": "dock-testnet",
"displayName": "Dock Testnet",
"symbols": [
"DCK"
],
"decimals": [
6
],
"standardAccount": "*25519",
"website": "https://dock.io"
},
{
"prefix": 22,
"network": "dock-mainnet",
"network": "dock-pos-mainnet",
"displayName": "Dock Mainnet",
"symbols": [
"DCK"
@@ -459,12 +446,12 @@
{
"prefix": 38,
"network": "kilt",
"displayName": "KILT Chain",
"displayName": "KILT Spiritnet",
"symbols": [
"KILT"
],
"decimals": [
18
15
],
"standardAccount": "*25519",
"website": "https://kilt.io/"
@@ -646,6 +633,19 @@
"standardAccount": "*25519",
"website": "https://dico.io"
},
{
"prefix": 54,
"network": "cere",
"displayName": "Cere Network",
"symbols": [
"CERE"
],
"decimals": [
10
],
"standardAccount": "*25519",
"website": "https://cere.network"
},
{
"prefix": 55,
"network": "xxnetwork",
@@ -793,6 +793,32 @@
"standardAccount": "*25519",
"website": "https://polkadex.trade"
},
{
"prefix": 89,
"network": "polkadexparachain",
"displayName": "Polkadex Parachain",
"symbols": [
"PDEX"
],
"decimals": [
12
],
"standardAccount": "*25519",
"website": "https://polkadex.trade"
},
{
"prefix": 93,
"network": "fragnova",
"displayName": "Fragnova Network",
"symbols": [
"NOVA"
],
"decimals": [
12
],
"standardAccount": "*25519",
"website": "https://fragnova.com"
},
{
"prefix": 98,
"network": "polkasmith",
@@ -824,13 +850,13 @@
"network": "origintrail-parachain",
"displayName": "OriginTrail Parachain",
"symbols": [
"TRAC"
"OTP"
],
"decimals": [
18
12
],
"standardAccount": "secp256k1",
"website": "https://origintrail.io"
"standardAccount": "*25519",
"website": "https://parachain.origintrail.io/"
},
{
"prefix": 105,
@@ -867,6 +893,19 @@
"standardAccount": "*25519",
"website": "https://integritee.network"
},
{
"prefix": 117,
"network": "tinker",
"displayName": "Tinker",
"symbols": [
"TNKR"
],
"decimals": [
12
],
"standardAccount": "*25519",
"website": "https://invarch.network"
},
{
"prefix": 128,
"network": "clover",
@@ -1024,7 +1063,7 @@
"website": "https://moonbeam.network"
},
{
"prefix": 1337,
"prefix": 1328,
"network": "ajuna",
"displayName": "Ajuna Network",
"symbols": [
@@ -1033,7 +1072,20 @@
"decimals": [
12
],
"standardAccount": "Sr25519",
"standardAccount": "*25519",
"website": "https://ajuna.io"
},
{
"prefix": 1337,
"network": "bajun",
"displayName": "Bajun Network",
"symbols": [
"BAJU"
],
"decimals": [
12
],
"standardAccount": "*25519",
"website": "https://ajuna.io"
},
{
@@ -1101,6 +1153,19 @@
"standardAccount": "*25519",
"website": "https://subspace.network"
},
{
"prefix": 7007,
"network": "tidefi",
"displayName": "Tidefi",
"symbols": [
"TIFI"
],
"decimals": [
12
],
"standardAccount": "*25519",
"website": "https://tidefi.com"
},
{
"prefix": 7391,
"network": "unique_mainnet",
@@ -1114,6 +1179,19 @@
"standardAccount": "*25519",
"website": "https://unique.network"
},
{
"prefix": 9807,
"network": "dentnet",
"displayName": "DENTNet",
"symbols": [
"DENTX"
],
"decimals": [
18
],
"standardAccount": "*25519",
"website": "https://www.dentnet.io"
},
{
"prefix": 10041,
"network": "basilisk",
@@ -1165,5 +1243,18 @@
],
"standardAccount": "*25519",
"website": "https://ata.network"
},
{
"prefix": 12191,
"network": "nftmart",
"displayName": "NFTMart",
"symbols": [
"NMT"
],
"decimals": [
12
],
"standardAccount": "*25519",
"website": "https://nftmart.io"
}
]
+11 -11
View File
@@ -22,22 +22,22 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.7.1",
"version": "9.5.1",
"browser": {
"crypto": false,
"stream": false
},
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.17.8",
"@noble/hashes": "1.0.0",
"@noble/secp256k1": "1.5.5",
"@polkadot/networks": "8.7.1",
"@polkadot/util": "8.7.1",
"@polkadot/wasm-crypto": "^5.1.1",
"@polkadot/x-bigint": "8.7.1",
"@polkadot/x-randomvalues": "8.7.1",
"@scure/base": "1.0.0",
"@babel/runtime": "^7.18.3",
"@noble/hashes": "1.1.1",
"@noble/secp256k1": "1.6.0",
"@polkadot/networks": "9.5.1",
"@polkadot/util": "9.5.1",
"@polkadot/wasm-crypto": "^6.1.1",
"@polkadot/x-bigint": "9.5.1",
"@polkadot/x-randomvalues": "9.5.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": "8.7.1"
"@polkadot/util": "9.5.1"
}
}
@@ -10,7 +10,5 @@ import { decodeAddress } from './decode';
* @summary Converts an SS58 address to its corresponding EVM address.
*/
export function addressToEvm (address: HexString | string | Uint8Array, ignoreChecksum?: boolean): Uint8Array {
const decoded = decodeAddress(address, ignoreChecksum);
return decoded.subarray(0, 20);
return decodeAddress(address, ignoreChecksum).subarray(0, 20);
}
+1 -7
View File
@@ -1,18 +1,12 @@
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { Network } from '@polkadot/networks/types';
import { availableNetworks } from '../networks';
function networkToPrefix ({ prefix }: Network): number {
return prefix;
}
export const defaults = {
allowedDecodedLengths: [1, 2, 4, 8, 32, 33],
// publicKey has prefix + 2 checksum bytes, short only prefix + 1 checksum byte
allowedEncodedLengths: [3, 4, 6, 10, 35, 36, 37, 38],
allowedPrefix: availableNetworks.map(networkToPrefix),
allowedPrefix: availableNetworks.map(({ prefix }) => prefix),
prefix: 42
};
@@ -14,7 +14,7 @@ const l = logger('setSS58Format');
* @deprecated Use keyring.setSS58Format
*/
export function setSS58Format (prefix: Prefix): void {
l.warn('Global setting of the ss58Format is deprecated and not recommended. Set format on the keyring (if used) or as pat of the address encode function');
l.warn('Global setting of the ss58Format is deprecated and not recommended. Set format on the keyring (if used) or as part of the address encode function');
defaults.prefix = prefix;
}
+5 -1
View File
@@ -27,18 +27,20 @@ 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);
return coder.decode(
ipfs && ipfsCompat
? value.substr(1)
? value.substring(1)
: value
);
};
}
/** @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`);
+1 -3
View File
@@ -10,8 +10,6 @@ import { blake2b, isReady } from '@polkadot/wasm-crypto';
import { createAsHex } from '../helpers';
type BitLength = 64 | 128 | 256 | 384 | 512;
/**
* @name blake2AsU8a
* @summary Creates a blake2b u8a from the input.
@@ -26,7 +24,7 @@ type BitLength = 64 | 128 | 256 | 384 | 512;
* blake2AsU8a('abc'); // => [0xba, 0x80, 0xa5, 0x3f, 0x98, 0x1c, 0x4d, 0x0d]
* ```
*/
export function blake2AsU8a (data: HexString | Uint8Array | string, bitLength: BitLength = 256, key?: Uint8Array | null, onlyJs?: boolean): Uint8Array {
export function blake2AsU8a (data: HexString | Uint8Array | string, bitLength: 64 | 128 | 256 | 384 | 512 = 256, key?: Uint8Array | null, onlyJs?: boolean): Uint8Array {
const byteLength = Math.ceil(bitLength / 8);
const u8a = u8aToU8a(data);
+5 -5
View File
@@ -7,7 +7,7 @@ import { utils as utilsNobleSecp256k1 } from '@noble/secp256k1';
import { u8aConcat } from '@polkadot/util';
// import { cryptoWaitReady } from './crypto';
import { cryptoWaitReady } from './crypto';
import { hmacSha256AsU8a } from './hmac';
// Set overrides on the secp256k1 utils
@@ -15,7 +15,7 @@ import { hmacSha256AsU8a } from './hmac';
utilsNobleSecp256k1.hmacSha256Sync = (key: Uint8Array, ...messages: Uint8Array[]) =>
hmacSha256AsU8a(key, u8aConcat(...messages));
// // start init process immediately
// cryptoWaitReady().catch((): void => {
// // shouldn't happen, logged above
// });
// start init process immediately
cryptoWaitReady().catch((): void => {
// shouldn't happen, logged and caught inside cryptoWaitReady
});
+5 -3
View File
@@ -14,17 +14,19 @@ interface DualHash {
512: (u8a: Uint8Array) => Uint8Array;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function createAsHex <T extends (...args: any[]) => Uint8Array> (fn: T): (...args: Parameters<T>) => HexString {
/** @internal */
export function createAsHex <T extends (...args: never[]) => Uint8Array> (fn: T): (...args: Parameters<T>) => HexString {
return (...args: Parameters<T>): HexString =>
u8aToHex(fn(...args));
}
export function createBitHasher <T> (bitLength: T, fn: (data: HexString | Buffer | Uint8Array | string, bitLength: T, onlyJs?: boolean) => Uint8Array): (data: HexString | Buffer | Uint8Array | string, onlyJs?: boolean) => Uint8Array {
/** @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);
+2 -4
View File
@@ -8,8 +8,6 @@ import { sha512 } from '@noble/hashes/sha512';
import { hasBigInt, u8aToU8a } from '@polkadot/util';
import { hmacSha256, hmacSha512, isReady } from '@polkadot/wasm-crypto';
type BitLength = 256 | 512;
const JS_HASH = {
256: sha256,
512: sha512
@@ -20,7 +18,7 @@ const WA_MHAC = {
512: hmacSha512
};
function createSha (bitLength: BitLength): (key: Uint8Array | string, data: Uint8Array, onlyJs?: boolean) => Uint8Array {
function createSha (bitLength: 256 | 512): (key: Uint8Array | string, data: Uint8Array, onlyJs?: boolean) => Uint8Array {
return (key: Uint8Array | string, data: Uint8Array, onlyJs?: boolean): Uint8Array =>
hmacShaAsU8a(key, data, bitLength, onlyJs);
}
@@ -29,7 +27,7 @@ function createSha (bitLength: BitLength): (key: Uint8Array | string, data: Uint
* @name hmacShaAsU8a
* @description creates a Hmac Sha (256/512) Uint8Array from the key & data
*/
export function hmacShaAsU8a (key: Uint8Array | string, data: Uint8Array, bitLength: BitLength = 256, onlyJs?: boolean): Uint8Array {
export function hmacShaAsU8a (key: Uint8Array | string, data: Uint8Array, bitLength: 256 | 512 = 256, onlyJs?: boolean): Uint8Array {
const u8aKey = u8aToU8a(key);
return !hasBigInt || (!onlyJs && isReady())
@@ -20,7 +20,7 @@ export class DeriveJunction {
public static from (value: string): DeriveJunction {
const result = new DeriveJunction();
const [code, isHard] = value.startsWith('/')
? [value.substr(1), true]
? [value.substring(1), true]
: [value, false];
result.soft(
+1 -1
View File
@@ -24,7 +24,7 @@ export function keyExtractPath (derivePath: string): ExtractResult {
constructed = parts.join('');
for (const p of parts) {
path.push(DeriveJunction.from(p.substr(1)));
path.push(DeriveJunction.from(p.substring(1)));
}
}
+5 -8
View File
@@ -12,6 +12,7 @@
// - Use util-crypto randomAsU8a (instead of randombytes)
// - Remove setting of wordlist passing of wordlist in functions
// - Remove mnemonicToSeed (we only use the sync variant)
// - generateMnemonic takes number of words (instead of strength)
import { assert, stringToU8a, u8aToU8a } from '@polkadot/util';
@@ -73,7 +74,7 @@ export function mnemonicToEntropy (mnemonic: string): Uint8Array {
// calculate the checksum and compare
const entropyBytes = entropyBits.match(/(.{1,8})/g)?.map(binaryToByte);
assert(entropyBytes && entropyBytes.length % 4 === 0 && entropyBytes.length >= 16 && entropyBytes.length <= 32, INVALID_ENTROPY);
assert(entropyBytes && (entropyBytes.length % 4 === 0) && (entropyBytes.length >= 16) && (entropyBytes.length <= 32), INVALID_ENTROPY);
const entropy = u8aToU8a(entropyBytes);
const newChecksum = deriveChecksumBits(entropy);
@@ -85,7 +86,7 @@ export function mnemonicToEntropy (mnemonic: string): Uint8Array {
export function entropyToMnemonic (entropy: Uint8Array): string {
// 128 <= ENT <= 256
assert(entropy.length % 4 === 0 && entropy.length >= 16 && entropy.length <= 32, INVALID_ENTROPY);
assert((entropy.length % 4 === 0) && (entropy.length >= 16) && (entropy.length <= 32), INVALID_ENTROPY);
const entropyBits = bytesToBinary(Array.from(entropy));
const checksumBits = deriveChecksumBits(entropy);
@@ -97,12 +98,8 @@ export function entropyToMnemonic (entropy: Uint8Array): string {
.join(' ');
}
export function generateMnemonic (strength?: number): string {
strength = strength || 128;
assert(strength % 32 === 0, INVALID_ENTROPY);
return entropyToMnemonic(randomAsU8a(strength / 8));
export function generateMnemonic (numWords: 12 | 15 | 18 | 21 | 24): string {
return entropyToMnemonic(randomAsU8a((numWords / 3) * 4));
}
export function validateMnemonic (mnemonic: string): boolean {
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import { cryptoWaitReady } from '..';
import { mnemonicGenerate, WordCount } from './generate';
import { mnemonicGenerate } from './generate';
import { mnemonicValidate } from './validate';
describe('mnemonicGenerate', (): void => {
@@ -17,7 +17,7 @@ describe('mnemonicGenerate', (): void => {
});
describe.each([false, true])('onlyJs=%p', (onlyJs): void => {
it.each([12, 15, 18, 21, 24] as WordCount[])('generates a valid mnemonic (%p words)', (num): void => {
it.each([12, 15, 18, 21, 24] as 12[])('generates a valid mnemonic (%p words)', (num): void => {
const mnemonic = mnemonicGenerate(num, onlyJs);
const isValid = mnemonicValidate(mnemonic);
+2 -13
View File
@@ -6,17 +6,6 @@ import { bip39Generate, isReady } from '@polkadot/wasm-crypto';
import { generateMnemonic } from './bip39';
export type WordCount = 12 | 15 | 18 | 21 | 24;
// mapping of words to the actual strength (as expected)
const STRENGTH_MAP = {
12: 16 * 8,
15: 20 * 8,
18: 24 * 8,
21: 28 * 8,
24: 32 * 8
};
/**
* @name mnemonicGenerate
* @summary Creates a valid mnemonic string using using [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).
@@ -29,8 +18,8 @@ const STRENGTH_MAP = {
* const mnemonic = mnemonicGenerate(); // => string
* ```
*/
export function mnemonicGenerate (numWords: WordCount = 12, onlyJs?: boolean): string {
export function mnemonicGenerate (numWords: 12 | 15 | 18 | 21 | 24 = 12, onlyJs?: boolean): string {
return !hasBigInt || (!onlyJs && isReady())
? bip39Generate(numWords)
: generateMnemonic(STRENGTH_MAP[numWords]);
: generateMnemonic(numWords);
}
@@ -43,7 +43,7 @@ describe('mnemonicToMiniSecret', (): void => {
u8aToHex(mnemonicToMiniSecret(mnemonic, 'Substrate', onlyJs))
).toEqual(
// mini returned here, only check first 32-bytes (64 hex + 2 prefix)
seed.substr(0, 66)
seed.substring(0, 66)
);
});
});
+2 -1
View File
@@ -1,4 +1,5 @@
// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
// SPDX-License-Identifier: Apache-2.0
export * from '@polkadot/networks/interfaces';
// Don't use a export * since we don't want to duplicate packageInfo
export { allNetworks, availableNetworks, selectableNetworks } from '@polkadot/networks';
+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: '8.7.1' };
export const packageInfo = { name: '@polkadot/util-crypto', path: 'auto', type: 'auto', version: '9.5.1' };
+1 -3
View File
@@ -9,8 +9,6 @@ import { isReady, twox } from '@polkadot/wasm-crypto';
import { createAsHex } from '../helpers';
import { xxhash64 } from './xxhash64';
type BitLength = 64 | 128 | 192 | 256 | 320 | 384 | 448 | 512;
/**
* @name xxhashAsU8a
* @summary Creates a xxhash64 u8a from the input.
@@ -25,7 +23,7 @@ type BitLength = 64 | 128 | 192 | 256 | 320 | 384 | 448 | 512;
* xxhashAsU8a('abc'); // => 0x44bc2cf5ad770999
* ```
*/
export function xxhashAsU8a (data: HexString | Buffer | Uint8Array | string, bitLength: BitLength = 64, onlyJs?: boolean): Uint8Array {
export function xxhashAsU8a (data: HexString | Buffer | Uint8Array | string, bitLength: 64 | 128 | 192 | 256 | 320 | 384 | 448 | 512 = 64, onlyJs?: boolean): Uint8Array {
const rounds = Math.ceil(bitLength / 64);
const u8a = u8aToU8a(data);
+10 -10
View File
@@ -9,13 +9,13 @@
"exports": {
"./hex/toU8a": {
"node": {
"require": "./hex/toU8aBuffer.cjs",
"require": "./cjs/hex/toU8aBuffer.js",
"default": "./hex/toU8aBuffer.js"
}
},
"./u8a/toHex": {
"node": {
"require": "./u8a/toHexBuffer.cjs",
"require": "./cjs/u8a/toHexBuffer.js",
"default": "./u8a/toHexBuffer.js"
}
}
@@ -34,19 +34,19 @@
"./detectPackage.cjs"
],
"type": "module",
"version": "8.7.1",
"version": "9.5.1",
"main": "index.js",
"dependencies": {
"@babel/runtime": "^7.17.8",
"@polkadot/x-bigint": "8.7.1",
"@polkadot/x-global": "8.7.1",
"@polkadot/x-textdecoder": "8.7.1",
"@polkadot/x-textencoder": "8.7.1",
"@babel/runtime": "^7.18.3",
"@polkadot/x-bigint": "9.5.1",
"@polkadot/x-global": "9.5.1",
"@polkadot/x-textdecoder": "9.5.1",
"@polkadot/x-textencoder": "9.5.1",
"@types/bn.js": "^5.1.0",
"bn.js": "^5.2.0",
"bn.js": "^5.2.1",
"ip-regex": "^4.3.0"
},
"devDependencies": {
"@polkadot/x-randomvalues": "8.7.1"
"@polkadot/x-randomvalues": "9.5.1"
}
}
+4 -1
View File
@@ -1,7 +1,8 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { arrayChunk } from '.';
import { performance } from '../test/performance';
import { arrayChunk, arrayRange } from '.';
describe('arrayChunk', (): void => {
it('chunks arrays', (): void => {
@@ -9,4 +10,6 @@ describe('arrayChunk', (): void => {
arrayChunk([1, 2, 3, 4, 5, 6, 7], 3)
).toEqual([[1, 2, 3], [4, 5, 6], [7]]);
});
performance('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++) {
+2 -3
View File
@@ -19,9 +19,8 @@ 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) =>
export function arrayFilter <T = unknown> (array: (T | null | undefined)[], allowNulls = true): T[] {
return array.filter((v): v is T =>
!isUndefined(v) &&
(allowNulls || !isNull(v))
);
+5
View File
@@ -19,6 +19,11 @@
* ```
*/
export function arrayFlatten <T> (arrays: 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 { performance } 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));
});
performance('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--;
+4
View File
@@ -1,6 +1,10 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
/**
* @name arrayZip
* @description Combines 2 distinct key/value arrays into a single [K, V] array
*/
export function arrayZip <K, V> (keys: K[], values: V[]): [K, V][] {
const result = new Array<[K, V]>(keys.length);
+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;
+3 -6
View File
@@ -2,23 +2,20 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '../bn/bn';
import type { HexString, ToBigInt, ToBn, ToBnOptions } from '../types';
import type { HexString, NumberOptions, ToBigInt, ToBn } from '../types';
import { objectSpread } from '../object/spread';
import { u8aToHex } from '../u8a';
import { nToU8a } from './toU8a';
interface Options extends ToBnOptions {
bitLength?: number;
}
/** @internal */
const ZERO_STR = '0x00';
/**
* @name nToHex
* @summary Creates a hex value from a bigint object.
*/
export function nToHex <ExtToBn extends ToBn | ToBigInt> (value?: ExtToBn | BN | bigint | number | null, options?: Options): HexString {
export function nToHex <ExtToBn extends ToBn | ToBigInt> (value?: ExtToBn | BN | bigint | number | null, options?: NumberOptions): HexString {
return !value
? ZERO_STR
: u8aToHex(
+7 -15
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import type { BN } from '../bn/bn';
import type { ToBigInt, ToBn, ToBnOptions } from '../types';
import type { NumberOptions, ToBigInt, ToBn } from '../types';
import { BigInt } from '@polkadot/x-bigint';
@@ -10,20 +10,10 @@ import { objectSpread } from '../object/spread';
import { _0n, _1n } from './consts';
import { nToBigInt } from './toBigInt';
interface Options extends ToBnOptions {
bitLength?: number;
}
const DIV = BigInt(256);
const NEG_MASK = BigInt(0xff);
function createEmpty ({ bitLength = 0 }: Options): Uint8Array {
return bitLength === -1
? new Uint8Array()
: new Uint8Array(Math.ceil(bitLength / 8));
}
function toU8a (value: bigint, { isLe, isNegative }: Options): Uint8Array {
function toU8a (value: bigint, { isLe, isNegative }: NumberOptions): Uint8Array {
const arr: number[] = [];
if (isNegative) {
@@ -54,8 +44,8 @@ function toU8a (value: bigint, { isLe, isNegative }: Options): Uint8Array {
* @name nToU8a
* @summary Creates a Uint8Array object from a bigint.
*/
export function nToU8a <ExtToBn extends ToBn | ToBigInt> (value?: ExtToBn | BN | bigint | number | null, options?: Options): Uint8Array {
const opts: Options = objectSpread(
export function nToU8a <ExtToBn extends ToBn | ToBigInt> (value?: ExtToBn | BN | bigint | number | null, options?: NumberOptions): Uint8Array {
const opts: NumberOptions = objectSpread(
{ bitLength: -1, isLe: true, isNegative: false },
options
);
@@ -63,7 +53,9 @@ export function nToU8a <ExtToBn extends ToBn | ToBigInt> (value?: ExtToBn | BN |
const valueBi = nToBigInt(value);
if (valueBi === _0n) {
return createEmpty(opts);
return opts.bitLength === -1
? new Uint8Array()
: new Uint8Array(Math.ceil((opts.bitLength || 0) / 8));
}
const u8a = toU8a(valueBi, opts);
+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
+5 -5
View File
@@ -27,10 +27,9 @@ import { BN } from './bn';
* ```
*/
export function bnToBn <ExtToBn extends ToBigInt | ToBn> (value?: HexString | ExtToBn | BN | bigint | string | number | null): BN {
return BN.isBN(value)
? value
: !value
? new BN(0)
return value
? BN.isBN(value)
? value
: isHex(value)
? hexToBn(value.toString())
: isBigInt(value)
@@ -39,5 +38,6 @@ export function bnToBn <ExtToBn extends ToBigInt | ToBn> (value?: HexString | Ex
? value.toBn()
: isToBigInt(value)
? new BN(value.toBigInt().toString())
: new BN(value);
: new BN(value)
: new BN(0);
}
+1 -1
View File
@@ -46,7 +46,7 @@ describe('bnToHex', (): void => {
).toBe('0xfffffb2e');
});
it('handles backwards compatibility', (): void => {
it('handles legacy compatibility', (): void => {
expect(
bnToHex(new BN(1234), 32)
).toBe(
+6 -8
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { HexString, ToBn, ToBnOptions } from '../types';
import type { HexString, NumberOptions, ToBn } from '../types';
import type { BN } from './bn';
import { isNumber } from '../is/number';
@@ -9,12 +9,8 @@ import { objectSpread } from '../object/spread';
import { u8aToHex } from '../u8a';
import { bnToU8a } from './toU8a';
interface Options extends ToBnOptions {
bitLength?: number;
}
const ZERO_STR = '0x00';
const DEFAULT_OPTS: Options = { bitLength: -1, isLe: false, isNegative: false };
const DEFAULT_OPTS: NumberOptions = { bitLength: -1, isLe: false, isNegative: false };
/**
* @name bnToHex
@@ -31,9 +27,11 @@ const DEFAULT_OPTS: Options = { bitLength: -1, isLe: false, isNegative: false };
* bnToHex(new BN(0x123456)); // => '0x123456'
* ```
*/
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, options?: Options): HexString;
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, options?: NumberOptions): HexString;
/** @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;
function bnToHex <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, arg1: number | Options = DEFAULT_OPTS, arg2?: 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 = false): HexString {
return !value
? ZERO_STR
: u8aToHex(
+62 -24
View File
@@ -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 => {
);
});
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]));
});
});
performance('bnToU8a', 250000, ptest, bnToU8a);
});
+25 -37
View File
@@ -1,35 +1,13 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { ToBn, ToBnOptions } from '../types';
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';
interface Options extends ToBnOptions {
bitLength?: number;
}
const DEFAULT_OPTS: Options = { bitLength: -1, isLe: true, isNegative: false };
function createEmpty (byteLength: number, options: Options): Uint8Array {
return options.bitLength === -1
? new Uint8Array()
: new Uint8Array(byteLength);
}
function createValue (valueBn: BN, byteLength: number, { isLe, isNegative }: Options): Uint8Array {
const output = new Uint8Array(byteLength);
const bn = isNegative
? valueBn.toTwos(byteLength * 8)
: valueBn;
output.set(bn.toArray(isLe ? 'le' : 'be', byteLength), 0);
return output;
}
const DEFAULT_OPTS: NumberOptions = { bitLength: -1, isLe: true, isNegative: false };
/**
* @name bnToU8a
@@ -45,24 +23,34 @@ function createValue (valueBn: BN, byteLength: number, { isLe, isNegative }: Opt
* bnToU8a(new BN(0x1234)); // => [0x12, 0x34]
* ```
*/
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, options?: Options): Uint8Array;
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, options?: NumberOptions): Uint8Array;
/** @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;
function bnToU8a <ExtToBn extends ToBn> (value?: ExtToBn | BN | bigint | number | null, arg1: number | Options = DEFAULT_OPTS, arg2?: boolean): Uint8Array {
const options: Options = objectSpread(
{ bitLength: -1, isLe: true, isNegative: false },
isNumber(arg1)
? { bitLength: arg1, isLe: arg2 }
: arg1
);
/** @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 = true): Uint8Array {
const { bitLength = -1, isLe = true, isNegative = false } = isNumber(arg1)
? { bitLength: arg1, isLe: arg2 }
: arg1;
const valueBn = bnToBn(value);
const byteLength = options.bitLength === -1
const byteLength = bitLength === -1
? Math.ceil(valueBn.bitLength() / 8)
: Math.ceil((options.bitLength || 0) / 8);
: Math.ceil((bitLength || 0) / 8);
return value
? createValue(valueBn, byteLength, options)
: createEmpty(byteLength, options);
if (!value) {
return bitLength === -1
? new Uint8Array()
: new Uint8Array(byteLength);
}
const output = new Uint8Array(byteLength);
const bn = isNegative
? valueBn.toTwos(byteLength * 8)
: valueBn;
output.set(bn.toArray(isLe ? 'le' : 'be', byteLength), 0);
return output;
}
export { bnToU8a };
+1
View File
@@ -20,6 +20,7 @@ export * from './is';
export * from './lazy';
export * from './logger';
export * from './memoize';
export * from './nextTick';
export * from './number';
export * from './object';
export * from './promisify';
+3 -3
View File
@@ -1,7 +1,7 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { u8aConcat } from '../u8a';
import { u8aConcatStrict } from '../u8a';
import { compactToU8a } from './toU8a';
/**
@@ -17,8 +17,8 @@ import { compactToU8a } from './toU8a';
* ```
*/
export function compactAddLength (input: Uint8Array): Uint8Array {
return u8aConcat(
return u8aConcatStrict([
compactToU8a(input.length),
input
);
]);
}
+1
View File
@@ -3,4 +3,5 @@
import type { BitLength } from './types';
/** @internal */
export const DEFAULT_BITLENGTH: BitLength = 32;
+31 -6
View File
@@ -3,7 +3,8 @@
import { BN } from '../bn/bn';
import { hexToU8a } from '../hex/toU8a';
import { compactFromU8a } from '.';
import { performance } from '../test/performance';
import { compactFromU8a, compactFromU8aLim } from '.';
describe('compactFromU8a', (): void => {
it('decoded u8 value', (): void => {
@@ -14,16 +15,25 @@ describe('compactFromU8a', (): void => {
it('decodes from same u16 encoded value', (): void => {
expect(
compactFromU8a(new Uint8Array([0b11111101, 0b00000111]))
).toEqual([2, new BN(511)]);
compactFromU8a(new Uint8Array([0b11111101, 0b00000111])).toString()
).toEqual(
[2, new BN(511)].toString()
);
});
it('decodes from same u32 encoded value (short)', (): void => {
expect(
compactFromU8a(new Uint8Array([254, 255, 3, 0]))
compactFromU8a(new Uint8Array([254, 255, 3, 0])).toString()
).toEqual(
// since we use in-place, the words are different... HACK it
[4, new BN(0xffff).ishln(16).ishrn(16)]
[4, new BN(0xffff)].toString()
);
});
it('decodes from same u32 encoded value (short)', (): void => {
expect(
compactFromU8a(new Uint8Array([254, 255, 255, 255])).toString()
).toEqual(
[4, new BN(1073741823)].toString()
);
});
@@ -47,6 +57,14 @@ describe('compactFromU8a', (): void => {
).toEqual([7, new BN('5af3107a4000', 16)]);
});
it('decodes an actual value (Buffer)', (): void => {
expect(
compactFromU8a(
Buffer.from('0b00407a10f35a', 'hex')
)
).toEqual([7, new BN('5af3107a4000', 16)]);
});
it('decodes an actual value', (): void => {
expect(
compactFromU8a(
@@ -54,4 +72,11 @@ describe('compactFromU8a', (): void => {
)[1].toString()
).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);
});
+84 -18
View File
@@ -3,12 +3,12 @@
import type { U8aLike } from '../types';
import { BN, BN_FOUR } from '../bn';
import { BN } from '../bn';
import { u8aToBn, u8aToU8a } from '../u8a';
/**
* @name compactFromU8a
* @description Retrievs the offset and encoded length from a compact-prefixed value
* @description Retrives the offset and encoded length from a compact-prefixed value
* @example
* <BR>
*
@@ -22,22 +22,88 @@ import { u8aToBn, u8aToU8a } from '../u8a';
*/
export function compactFromU8a (input: U8aLike): [number, BN] {
const u8a = u8aToU8a(input);
const flag = u8a[0] & 0b11;
if (flag === 0b00) {
return [1, new BN(u8a[0]).ishrn(2)];
} else if (flag === 0b01) {
return [2, u8aToBn(u8a.subarray(0, 2), true).ishrn(2)];
} else if (flag === 0b10) {
return [4, u8aToBn(u8a.subarray(0, 4), true).ishrn(2)];
// The u8a is manually converted here for 1, 2 & 4 lengths, it is 2x faster
// than doing an additional call to u8aToBn (as with variable length)
switch (u8a[0] & 0b11) {
case 0b00:
return [1, new BN(u8a[0] >>> 2)];
case 0b01:
return [2, new BN((u8a[0] + (u8a[1] << 8)) >>> 2)];
case 0b10:
// 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: {
// 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))];
case 6:
return [6, new BN(u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + ((u8a[4] + (u8a[5] << 8)) * 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] << 8) + (u8a[3] << 16) + ((u8a[4] + (u8a[5] << 8) + (u8a[6] << 16)) * 0x1_00_00_00))];
// for anything else, use the non-unrolled version
default:
return [offset, u8aToBn(u8a.subarray(1, offset))];
}
}
}
}
/**
* @name compactFromU8aLim
* @description A limited version of [[compactFromU8a]], accepting only Uint8Array inputs for values <= 48 bits
*/
export function compactFromU8aLim (u8a: Uint8Array): [number, number] {
// The u8a is manually converted here for 1, 2 & 4 lengths, it is 2x faster
// than doing an additional call to u8aToBn (as with variable length)
switch (u8a[0] & 0b11) {
case 0b00:
return [1, u8a[0] >>> 2];
case 0b01:
return [2, (u8a[0] + (u8a[1] << 8)) >>> 2];
case 0b10:
// 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: {
// 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)];
case 6:
return [6, u8a[1] + (u8a[2] << 8) + (u8a[3] << 16) + ((u8a[4] + (u8a[5] << 8)) * 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)];
// for anything else, we are above the actual MAX_SAFE_INTEGER - bail out
default:
throw new Error('Compact input is > Number.MAX_SAFE_INTEGER');
}
}
}
const offset = 1 + (
new BN(u8a[0])
.ishrn(2) // clear flag
.iadd(BN_FOUR) // add 4 for base length
.toNumber()
);
return [offset, u8aToBn(u8a.subarray(1, offset), true)];
}
+1 -1
View File
@@ -24,5 +24,5 @@
export { compactAddLength } from './addLength';
export { compactStripLength } from './stripLength';
export { compactFromU8a } from './fromU8a';
export { compactFromU8a, compactFromU8aLim } from './fromU8a';
export { compactToU8a } from './toU8a';
+11 -1
View File
@@ -61,7 +61,7 @@ describe('encode', (): void => {
);
});
it('encodes a large value', (): void => {
it('encodes a large value (6 bytes)', (): void => {
expect(
compactToU8a(
new BN('00005af3107a4000', 16)
@@ -71,6 +71,16 @@ describe('encode', (): void => {
);
});
it('encodes a large value (9 bytes)', (): void => {
expect(
compactToU8a(
new BN('1200005af3107a4034', 16)
)
).toEqual(
new Uint8Array([23, 52, 0x40, 0x7a, 0x10, 0xf3, 0x5a, 0, 0, 18])
);
});
it('does not modify the original', (): void => {
const original = new BN(123456);
+11 -8
View File
@@ -1,13 +1,14 @@
// 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 { u8aConcat } from '../u8a';
import { u8aConcatStrict } from '../u8a';
const MAX_U8 = BN_TWO.pow(new BN(8 - 2)).isub(BN_ONE);
const MAX_U16 = BN_TWO.pow(new BN(16 - 2)).isub(BN_ONE);
const MAX_U32 = BN_TWO.pow(new BN(32 - 2)).isub(BN_ONE);
const BL_16 = { bitLength: 16 };
const BL_32 = { bitLength: 32 };
/**
* @name compactToU8a
@@ -27,9 +28,9 @@ export function compactToU8a (value: BN | bigint | number): Uint8Array {
if (bn.lte(MAX_U8)) {
return new Uint8Array([bn.toNumber() << 2]);
} else if (bn.lte(MAX_U16)) {
return bnToU8a(bn.shln(2).iadd(BN_ONE), 16, true);
return bnToU8a(bn.shln(2).iadd(BN_ONE), BL_16);
} else if (bn.lte(MAX_U32)) {
return bnToU8a(bn.shln(2).iadd(BN_TWO), 32, true);
return bnToU8a(bn.shln(2).iadd(BN_TWO), BL_32);
}
const u8a = bnToU8a(bn);
@@ -40,11 +41,13 @@ 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 u8aConcat(
return u8aConcatStrict([
// subtract 4 as minimum (also catered for in decoding)
[((length - 4) << 2) + 0b11],
new Uint8Array([((length - 4) << 2) + 0b11]),
u8a.subarray(0, length)
);
]);
}
+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);
}
+19
View File
@@ -21,14 +21,33 @@ interface SetDefaults {
}
interface Options {
/**
* @description The number of decimals
*/
decimals?: number;
/**
* @description Format the number with this specific unit
*/
forceUnit?: string;
/**
* @description Format with SI, i.e. m/M/etc.
*/
withSi?: boolean;
/**
* @description Format with full SI, i.e. mili/Mega/etc.
*/
withSiFull?: boolean;
/**
* @description Add the unit (useful in Balance formats)
*/
withUnit?: boolean | string;
}
interface BalanceFormatter {
<ExtToBn extends ToBn> (input?: number | string | BN | bigint | ExtToBn, options?: Options): string;
/** @deprecated Use balanceFormat(input?: number | string | BN | bigint | ExtToBn, options?: Options) */
<ExtToBn extends ToBn> (input?: number | string | BN | bigint | ExtToBn, options?: boolean, decimals?: number): string;
/** @deprecated Use balanceFormat(input?: number | string | BN | bigint | ExtToBn, options?: Options) */
<ExtToBn extends ToBn> (input?: number | string | BN | bigint | ExtToBn, options?: Options, decimals?: number): string;
calcSi (text: string, decimals?: number): SiDef;
findSi (type: string): SiDef;
+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));
+5 -1
View File
@@ -4,12 +4,16 @@
// 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
const isNegative = value[0].startsWith('-');
const matched = isNegative
? value.substr(1).match(NUMBER_REGEX)
? value.substring(1).match(NUMBER_REGEX)
: value.match(NUMBER_REGEX);
return matched
@@ -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';
-27
View File
@@ -1,27 +0,0 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
const U8_TO_HEX = new Array<string>(256);
const U16_TO_HEX = new Array<string>(256 * 256);
const HEX_TO_U8: Record<string, number> = {};
const HEX_TO_U16: Record<string, number> = {};
for (let n = 0; n < 256; n++) {
const hex = n.toString(16).padStart(2, '0');
U8_TO_HEX[n] = hex;
HEX_TO_U8[hex] = n;
}
for (let i = 0; i < 256; i++) {
for (let j = 0; j < 256; j++) {
const hex = U8_TO_HEX[i] + U8_TO_HEX[j];
const n = (i << 8) | j;
U16_TO_HEX[n] = hex;
HEX_TO_U16[hex] = n;
}
}
export { HEX_TO_U16, HEX_TO_U8, U16_TO_HEX, U8_TO_HEX };
+1 -1
View File
@@ -21,7 +21,7 @@ export function hexStripPrefix (value?: string | null): string {
if (!value || value === '0x') {
return '';
} else if (REGEX_HEX_PREFIXED.test(value)) {
return value.substr(2);
return value.substring(2);
} else if (REGEX_HEX_NOPREFIX.test(value)) {
return value;
}
+1 -1
View File
@@ -70,7 +70,7 @@ describe('hexToBn', (): void => {
).toBe(256);
});
it('handles backwards compatibility', (): void => {
it('handles legacy compatibility', (): void => {
expect(
hexToBn('0x0001000000000000', false).eq(
hexToBn('0x0001000000000000', { isLe: false })
+12 -11
View File
@@ -5,11 +5,8 @@ import type { ToBnOptions } from '../types';
import { BN } from '../bn/bn';
import { isBoolean } from '../is/boolean';
import { objectSpread } from '../object/spread';
import { hexStripPrefix } from './stripPrefix';
const DEFAULT_OPTS: ToBnOptions = { isLe: false, isNegative: false };
/**
* @name hexToBn
* @summary Creates a BN.js object from a hex string.
@@ -28,23 +25,27 @@ const DEFAULT_OPTS: ToBnOptions = { isLe: false, isNegative: false };
* hexToBn('0x123480001f'); // => BN(0x123480001f)
* ```
*/
export function hexToBn (value?: string | null, options: ToBnOptions | boolean = DEFAULT_OPTS): BN {
function hexToBn (value?: string | null, options?: ToBnOptions): BN;
/** @deprecated Use hexToBn (value?: string | null, options?: ToBnOptions) */
function hexToBn (value?: string | null, options?: boolean): BN;
/** @deprecated Use hexToBn (value?: string | null, options?: ToBnOptions) */
function hexToBn (value?: string | null, options: ToBnOptions | boolean = {}): BN {
if (!value || value === '0x') {
return new BN(0);
}
const { isLe, isNegative }: ToBnOptions = objectSpread(
{ isLe: false, isNegative: false },
isBoolean(options)
? { isLe: options }
: options
);
// For hex, default to BE
const { isLe = false, isNegative = false } = isBoolean(options)
? { isLe: options }
: options;
const stripped = hexStripPrefix(value);
const bn = new BN(stripped, 16, isLe ? 'le' : 'be');
// fromTwos takes as parameter the number of bits, which is the hex length
// multiplied by 4.
// multiplied by 4 (2 bytes being 8 bits)
return isNegative
? bn.fromTwos(stripped.length * 4)
: bn;
}
export { hexToBn };
+3 -4
View File
@@ -2,14 +2,13 @@
// SPDX-License-Identifier: Apache-2.0
import { performanceCmp } from '../test/performance';
import { U16_TO_HEX } from './alphabet';
import { hexToU8a as hexToU8aBuffer } from './toU8aBuffer';
import { hexToU8a } from '.';
let ptest = '0x';
for (let i = 0; i < 500000; i++) {
ptest += U16_TO_HEX[i % (256 * 256)];
for (let i = 0; i < 1_000_000; i++) {
ptest += (i % 256).toString(16);
}
describe('hexToU8a', (): void => {
@@ -55,7 +54,7 @@ describe('hexToU8a', (): void => {
).toThrow(/hex value to convert/);
});
performanceCmp('hexToU8a', ['hexToU8aBuffer', 'hexToU8a'], 10, [[ptest]], (s: string, isSecond) =>
performanceCmp('hexToU8a', ['hexToU8aBuffer', 'hexToU8a'], 20, [[ptest]], (s: string, isSecond) =>
isSecond
? hexToU8a(s)
: hexToU8aBuffer(s)
+24 -17
View File
@@ -3,9 +3,19 @@
import type { HexString } from '../types';
import { HEX_TO_U8, HEX_TO_U16 } from './alphabet';
import { hexStripPrefix } from './stripPrefix';
const CHARS = '0123456789abcdef';
const UNHEX = new Array<number>(256);
for (let i = 0; i < CHARS.length; i++) {
UNHEX[CHARS[i].charCodeAt(0)] = i;
if (i > 9) {
UNHEX[CHARS[i].toUpperCase().charCodeAt(0)] = i;
}
}
/**
* @name hexToU8a
* @summary Creates a Uint8Array object from a hex string.
@@ -21,32 +31,29 @@ import { hexStripPrefix } from './stripPrefix';
* hexToU8a('0x80001f', 32); // Uint8Array([0x00, 0x80, 0x00, 0x1f])
* ```
*/
export function hexToU8a (_value?: HexString | string | null, bitLength = -1): Uint8Array {
if (!_value) {
export function hexToU8a (value?: HexString | string | null, bitLength = -1): Uint8Array {
if (!value) {
return new Uint8Array();
}
const value = hexStripPrefix(_value).toLowerCase();
const valLength = value.length / 2;
const str = hexStripPrefix(value);
const strLength = str.length / 2;
const endLength = Math.ceil(
bitLength === -1
? valLength
? strLength
: bitLength / 8
);
const result = new Uint8Array(endLength);
const offset = endLength > valLength
? endLength - valLength
const offset = endLength > strLength
? endLength - strLength
: 0;
const dv = new DataView(result.buffer, offset);
const mod = (endLength - offset) % 2;
const length = endLength - offset - mod;
for (let i = 0; i < length; i += 2) {
dv.setUint16(i, HEX_TO_U16[value.substr(i * 2, 4)]);
}
if (mod) {
dv.setUint8(length, HEX_TO_U8[value.substr(value.length - 2, 2)]);
for (let i = offset, s = 0; i < endLength; i++, s += 2) {
// The big factor here is actually the string lookups. If we do
// HEX_TO_U16[value.substring()] we get an 10x slowdown. In the
// same vein using charCodeAt (as opposed to value[s] or value.charAt(s)) is
// also the faster operation by at least 2x with the character map above
result[i] = ((UNHEX[str.charCodeAt(s)] << 4) + UNHEX[str.charCodeAt(s + 1)]) | 0;
}
return result;
+3
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { performance } from '../test/performance';
import { isAscii } from '.';
describe('isAscii', (): void => {
@@ -35,4 +36,6 @@ describe('isAscii', (): void => {
it('returns false for hex input, non-ascii', (): void => {
expect(isAscii('0x010203')).toEqual(false);
});
performance('isAscii', 100_000, [[[0x31, 0x32, 0x20, 10, 9, 13, 65, 66, 67, 68, 69, 70]]], isAscii);
});
+33 -19
View File
@@ -1,24 +1,42 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import type { U8aLike } from '../types';
import type { AnyString, U8aLike } from '../types';
import { u8aToU8a } from '../u8a/toU8a';
import { isHex } from './hex';
import { isString } from './string';
const FORMAT = [9, 10, 13];
/** @internal */
function isAsciiByte (b: number): boolean {
return (b < 127) && (
(b >= 32) ||
FORMAT.includes(b)
);
function isAsciiStr (str: AnyString): boolean {
const count = str.length;
for (let i = 0; i < count; i++) {
const b = str.charCodeAt(i);
// check is inlined here, it is faster than making a call
if (!((b < 127) && ((b >= 32) || (b === 10) || (b === 9) || (b === 13)))) {
return false;
}
}
return true;
}
function isAsciiChar (s: string): boolean {
return isAsciiByte(s.charCodeAt(0));
/** @internal */
function isAsciiU8a (u8a: Uint8Array): boolean {
const count = u8a.length;
for (let i = 0; i < count; i++) {
const b = u8a[i];
// check is inlined here, it is faster than making a call
if (!((b < 127) && ((b >= 32) || (b === 10) || (b === 9) || (b === 13)))) {
return false;
}
}
return true;
}
/**
@@ -28,13 +46,9 @@ function isAsciiChar (s: string): boolean {
* Checks to see if the input string or Uint8Array is printable ASCII, 32-127 + formatters
*/
export function isAscii (value?: U8aLike | null): boolean {
const isStringIn = isString(value);
if (value) {
return isStringIn && !isHex(value)
? value.toString().split('').every(isAsciiChar)
: u8aToU8a(value).every(isAsciiByte);
}
return isStringIn;
return isString(value) && !isHex(value)
? isAsciiStr(value)
: value
? isAsciiU8a(u8aToU8a(value))
: false;
}
+8 -2
View File
@@ -10,9 +10,15 @@ describe('isBuffer', (): void => {
).toEqual(true);
});
it('returns false on non-Buffer values', (): void => {
it('returns false on non-Buffer values (number)', (): void => {
expect(
isBuffer(0)
isBuffer(123)
).toEqual(false);
});
it('returns false on non-Buffer values (null)', (): void => {
expect(
isBuffer(null)
).toEqual(false);
});
});
+3 -1
View File
@@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
import { hasBuffer } from '../has';
import { isFunction } from './function';
/**
* @name isBuffer
@@ -18,5 +19,6 @@ import { hasBuffer } from '../has';
* ```
*/
export function isBuffer (value: unknown): value is Buffer {
return hasBuffer && Buffer.isBuffer(value);
// we do check a function first, since it is slightly faster than isBuffer itself
return hasBuffer && isFunction(value && (value as Buffer).readDoubleLE) && Buffer.isBuffer(value);
}
+15
View File
@@ -1,8 +1,17 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { performanceCmp } from '../test/performance';
import { isCodec } from '.';
const ptest = {
registry: {
get: () => null
},
toHex: () => '0x',
toU8a: () => new Uint8Array()
};
describe('isCodec', (): void => {
it('is false on no value', (): void => {
expect(isCodec()).toEqual(false);
@@ -37,4 +46,10 @@ describe('isCodec', (): void => {
})
).toEqual(false);
});
performanceCmp('isCodec', ['isCodec', 'instanceof'], 500_000, [[ptest]], (v: unknown, isSecond) =>
isSecond
? !(v instanceof String)
: isCodec(v)
);
});
+1 -5
View File
@@ -12,12 +12,8 @@ interface Compact<T> {
unwrap (): T;
}
const checker = isOnObject('toBigInt', 'toBn', 'toNumber', 'unwrap');
/**
* @name isCompact
* @summary Tests for SCALE-Compact-like object instance.
*/
export function isCompact <T> (value?: unknown): value is Compact<T> {
return checker(value);
}
export const isCompact: <T> (value?: unknown) => value is Compact<T> = isOnObject('toBigInt', 'toBn', 'toNumber', 'unwrap');
+4 -1
View File
@@ -16,5 +16,8 @@
* ```
*/
export function isError (value: unknown): value is Error {
return value instanceof Error;
return (
((value && (value as Error).constructor) === Error) ||
value instanceof Error
);
}
+2 -2
View File
@@ -6,7 +6,7 @@ import { isHex } from '.';
describe('isHex', (): void => {
const test = '1234abcd';
const ptest = '0x1234adbcdef5798351773526352876adbcdef2358735adbcdef2623587adbcdef11234adbcdef5798351773526352876adbcdef2358735adbcdef2623587adbcdef11234adbcdef5798351773526352876adbcdef2358735adbcdef2623587adbcdef11234adbcdef5798351773526352876adbcdef2358735adbcdef2623587adbcdef1';
const ptest = `0x${'1234567890abcdef'.repeat(8192)}`;
it('returns true on 0x hex values', (): void => {
expect(
@@ -71,5 +71,5 @@ describe('isHex', (): void => {
).toEqual(true);
});
performance('isHex (1024-bit)', 1000000, [[ptest]], isHex);
performance(`isHex (${(ptest.length - 2) / 2} bytes)`, 5000, [[ptest]], isHex);
});
+10
View File
@@ -10,6 +10,16 @@ describe('isInstanceOf', (): void => {
).toEqual(true);
});
it('returns true on real instances (inherited)', (): void => {
class Test extends Array {
// default
}
expect(
isInstanceOf(new Test(2), Array)
).toEqual(true);
});
it('returns false on non-allocated instances', (): void => {
expect(
isInstanceOf([], Array)
+5 -2
View File
@@ -16,6 +16,9 @@
* ```
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function isInstanceOf (value: unknown, clazz: Function): boolean {
return value instanceof clazz;
export function isInstanceOf (value: unknown, Clazz: Function): boolean {
return (
((value && (value as Record<string, unknown>).constructor) === Clazz) ||
value instanceof Clazz
);
}
+17 -1
View File
@@ -1,6 +1,7 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { performance } from '../test/performance';
import { isU8a } from '.';
describe('isU8a', (): void => {
@@ -10,15 +11,30 @@ describe('isU8a', (): void => {
).toEqual(false);
});
it('returns false on null values', (): void => {
expect(
isU8a(null)
).toEqual(false);
});
it('returns false on Array values', (): void => {
expect(
isU8a([])
isU8a([1, 2, 3])
).toEqual(false);
});
it('returns true on Buffer values', (): void => {
// under Node, Buffer implements Uint8Array
expect(
isU8a(Buffer.from([1, 2, 3]))
).toEqual(true);
});
it('returns true on Uint8Array values', (): void => {
expect(
isU8a(new Uint8Array())
).toEqual(true);
});
performance('isU8a', 2_000_000, [[new Uint8Array()]], isU8a);
});
+6 -1
View File
@@ -16,5 +16,10 @@
* ```
*/
export function isU8a (value?: unknown): value is Uint8Array {
return value instanceof Uint8Array;
// here we defer the instanceof check which is actually slightly
// slower than just checking the constrctor (direct instances)
return (
((value && (value as Uint8Array).constructor) === Uint8Array) ||
value instanceof Uint8Array
);
}

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