diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 000000000..b6f527147 --- /dev/null +++ b/.eslintignore @@ -0,0 +1,3 @@ +**/build/* +**/coverage/* +**/node_modules/* diff --git a/.eslintrc.js b/.eslintrc.js new file mode 100644 index 000000000..d49f5c73b --- /dev/null +++ b/.eslintrc.js @@ -0,0 +1 @@ +module.exports = require('@polkadot/dev/config/eslint'); diff --git a/docs/examples/keyring/01_create_account/index.js b/docs/examples/keyring/01_create_account/index.js index 5de9967ca..bac5f371c 100755 --- a/docs/examples/keyring/01_create_account/index.js +++ b/docs/examples/keyring/01_create_account/index.js @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ // Import Keyring class and utility function const Keyring = require('@polkadot/keyring').default; const stringToU8a = require('@polkadot/util/string/toU8a').default; @@ -12,8 +13,7 @@ async function main () { // Create pair and add Alice to keyring pair dictionary (with account seed) const pairAlice = keyring.addFromSeed(stringToU8a(ALICE_SEED)); - console.log(`Created keyring pair for Alice with address: ` + - `${keyring.getPair(pairAlice.address).address}`); + console.log(`Created keyring pair for Alice with address: ${keyring.getPair(pairAlice.address).address}`); } -main().catch(console.error).finally(_ => process.exit()); +main().catch(console.error).finally(() => process.exit()); diff --git a/docs/examples/keyring/02_load_accounts/index.js b/docs/examples/keyring/02_load_accounts/index.js index 5457b2b53..42f73f552 100755 --- a/docs/examples/keyring/02_load_accounts/index.js +++ b/docs/examples/keyring/02_load_accounts/index.js @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ // Import Keyring class and utility function const Keyring = require('@polkadot/keyring').default; const stringToU8a = require('@polkadot/util/string/toU8a').default; @@ -23,9 +24,8 @@ async function main () { .forEach((pair, index) => { const { address } = pair; - console.log(`\nAccount with index #${index} has json: `, - JSON.stringify(keyring.toJson(address), null, 2)); + console.log(`\nAccount with index #${index} has json: `, JSON.stringify(keyring.toJson(address), null, 2)); }); } -main().catch(console.error).finally(_ => process.exit()); +main().catch(console.error).finally(() => process.exit()); diff --git a/docs/examples/keyring/03_validate_address/index.js b/docs/examples/keyring/03_validate_address/index.js index 7473f7384..a4434ecf2 100644 --- a/docs/examples/keyring/03_validate_address/index.js +++ b/docs/examples/keyring/03_validate_address/index.js @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ const { encodeAddress, decodeAddress } = require('@polkadot/keyring'); const { isHex, hexToU8a } = require('@polkadot/util'); @@ -13,4 +14,5 @@ const isValidAddressPolkadotAddress = () => { }; const isValid = isValidAddressPolkadotAddress(); + console.log(isValid); diff --git a/docs/examples/trie-db/01_create_patricia_trie/README.md b/docs/examples/trie-db/01_create_patricia_trie/README.md deleted file mode 100644 index 40e45cdd6..000000000 --- a/docs/examples/trie-db/01_create_patricia_trie/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Create Patricia Trie - -The following example shows how to create a Patricia Trie. - -[include](index.js) diff --git a/docs/examples/trie-db/01_create_patricia_trie/index.js b/docs/examples/trie-db/01_create_patricia_trie/index.js deleted file mode 100755 index 6bae9e587..000000000 --- a/docs/examples/trie-db/01_create_patricia_trie/index.js +++ /dev/null @@ -1,13 +0,0 @@ -const Trie = require('@polkadot/trie-db').default; - -async function main () { - const trie = new Trie(); - - // Open the database for each of the trie instances - trie.open(); - - // Initial root value is valid - console.log(`Initial root Uint8Array value: ${trie.getRoot()}`); -} - -main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/trie-db/01_create_patricia_trie/package.json b/docs/examples/trie-db/01_create_patricia_trie/package.json deleted file mode 100644 index ae0e0a187..000000000 --- a/docs/examples/trie-db/01_create_patricia_trie/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "01_create_patricia_trie", - "version": "0.1.0", - "description": "Example showing how to create a Patricia Trie", - "main": "index.js", - "author": "ltfschoen", - "license": "MIT", - "scripts": { - "clean": "rimraf node_modules", - "start": "node index.js" - }, - "dependencies": { - "@polkadot/trie-db": "^0.32.10", - "@polkadot/db": "^0.32.10" - }, - "devDependencies": { - "rimraf": "^2.6.2" - } -} diff --git a/docs/examples/trie-db/02_get_set_del_trie_nodes/README.md b/docs/examples/trie-db/02_get_set_del_trie_nodes/README.md deleted file mode 100644 index 7740be5e2..000000000 --- a/docs/examples/trie-db/02_get_set_del_trie_nodes/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Get & Set & Delete Trie Nodes - -The following example shows how to get, set, and delete nodes of a Patricia Trie. - -[include](index.js) diff --git a/docs/examples/trie-db/02_get_set_del_trie_nodes/index.js b/docs/examples/trie-db/02_get_set_del_trie_nodes/index.js deleted file mode 100755 index fd6dd56ab..000000000 --- a/docs/examples/trie-db/02_get_set_del_trie_nodes/index.js +++ /dev/null @@ -1,48 +0,0 @@ -const toU8a = require('@polkadot/util/u8a/toU8a').default; -const Trie = require('@polkadot/trie-db').default; - -async function main () { - const trie = new Trie(); - - // Open the database for each of the trie instances - trie.open(); - - // Initial root value is valid - console.log(`Initial root Uint8Array value: ${trie.getRoot()}`); - - // Create a branch under the trie root with a key of 'test' and a value of 'one' - trie.put(toU8a('test'), toU8a('one')); - - // Store the root hash of the trie root node in a variable - const trieRootNodeHash = trie.getRoot(); - - // Store the root node object in a variable - const trieRootNode = trie.getNode(trieRootNodeHash); - - // Show the node object of the root node hash - console.log(`Root node object: ${trieRootNode}`); - - // Show the updated root hash value of the trie root node - console.log(`Updated root hash value: ${trie.getRoot()}`); - - const branch = trie.get(toU8a('test')); - // Retrieve the value of a given key named 'test' in the trie - console.log(`Current value of key 'test': ${branch}`); - - // Deletes the value of a given key named 'test' in the trie branch - trie.del(toU8a('test')); - - // Retrieve the value of a given key named 'test' in the trie - console.log(`Updated value of key 'test' after deleting it: ${trie.get(toU8a('test'))}`); - - // Set the root hash value of the trie root node (if necessary) - trie.setRoot(trieRootNodeHash); - - // Show the node object of the root node hash - console.log(`Root node object: ${trie.getRoot()}`); - - // Retrieve the value of a given key named 'test' in the trie - console.log(`Restored value of key 'test' after restoring root node: ${branch}`); -} - -main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/trie-db/02_get_set_del_trie_nodes/package.json b/docs/examples/trie-db/02_get_set_del_trie_nodes/package.json deleted file mode 100644 index 65034a3a7..000000000 --- a/docs/examples/trie-db/02_get_set_del_trie_nodes/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "02_get_set_del_trie_nodes", - "version": "0.1.0", - "description": "Example showing how to get, set, and delete nodes of a Patricia Trie", - "main": "index.js", - "author": "ltfschoen", - "license": "MIT", - "scripts": { - "clean": "rimraf node_modules", - "start": "node index.js" - }, - "dependencies": { - "@polkadot/trie-db": "^0.32.10", - "@polkadot/db": "^0.32.10" - }, - "devDependencies": { - "rimraf": "^2.6.2" - } -} diff --git a/docs/examples/trie-db/03_duplicate_trie_with_snapshot/README.md b/docs/examples/trie-db/03_duplicate_trie_with_snapshot/README.md deleted file mode 100644 index 9e4418910..000000000 --- a/docs/examples/trie-db/03_duplicate_trie_with_snapshot/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Duplicate Patricia Trie with Snapshot - -The following example shows how to duplicate a Patricia Trie by taking a snapshot. - -[include](index.js) diff --git a/docs/examples/trie-db/03_duplicate_trie_with_snapshot/index.js b/docs/examples/trie-db/03_duplicate_trie_with_snapshot/index.js deleted file mode 100755 index 1004b823d..000000000 --- a/docs/examples/trie-db/03_duplicate_trie_with_snapshot/index.js +++ /dev/null @@ -1,24 +0,0 @@ -const Trie = require('@polkadot/trie-db').default; - -async function main () { - const trie = new Trie(); - - // Use `back` to later store a snapshot of the `trie` - const back = new Trie(); - - // Open the database for each of the trie instances - trie.open(); - back.open(); - - // Initial root value is valid - console.log(`Initial root Uint8Array value: ${trie.getRoot()}`); - - // Create a snapshot of the `trie` data into `back` - trie.snapshot(back, () => {}); - - // Show value of snapshot's root is same as original trie's root - console.log(`Snapshot root value matches original trie root: ` + - `${back.getRoot() === trie.getRoot()}`); -} - -main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/trie-db/03_duplicate_trie_with_snapshot/package.json b/docs/examples/trie-db/03_duplicate_trie_with_snapshot/package.json deleted file mode 100644 index dcff9ff96..000000000 --- a/docs/examples/trie-db/03_duplicate_trie_with_snapshot/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "03_duplicate_trie_with_snapshot", - "version": "0.1.0", - "description": "Example showing how to duplicate Patricia Trie nodes with a snapshot", - "main": "index.js", - "author": "ltfschoen", - "license": "MIT", - "scripts": { - "clean": "rimraf node_modules", - "start": "node index.js" - }, - "dependencies": { - "@polkadot/trie-db": "^0.32.10", - "@polkadot/db": "^0.32.10" - }, - "devDependencies": { - "rimraf": "^2.6.2" - } -} diff --git a/docs/examples/trie-db/04_show_size_trie_node_info/README.md b/docs/examples/trie-db/04_show_size_trie_node_info/README.md deleted file mode 100644 index 67358aea3..000000000 --- a/docs/examples/trie-db/04_show_size_trie_node_info/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Show Size and Node Info of a Patricia Trie - -The following example shows how to show the size and node information of a Patricia Trie. - -[include](index.js) diff --git a/docs/examples/trie-db/04_show_size_trie_node_info/index.js b/docs/examples/trie-db/04_show_size_trie_node_info/index.js deleted file mode 100755 index 9b9961b8d..000000000 --- a/docs/examples/trie-db/04_show_size_trie_node_info/index.js +++ /dev/null @@ -1,65 +0,0 @@ -const toU8a = require('@polkadot/util/u8a/toU8a').default; -const Trie = require('@polkadot/trie-db').default; -const { - isEmptyNode, - isKvNode, - isExtensionNode, - isLeafNode, - isBranchNode -} = require('@polkadot/trie-db/util/is'); - -async function main () { - const trie = new Trie(); - - // Use `back` to later store a snapshot of the `trie` - const back = new Trie(); - - // Open the database for each of the trie instances - trie.open(); - back.open(); - - // Initial root value is valid - console.log(`Initial root Uint8Array value: ${trie.getRoot()}`); - - // Create two branches under the trie root with - // key 'branch1' and 'branch2' and a values of 'one' and 'two' - trie.put(toU8a('test'), toU8a('one')); - trie.put(toU8a('test'), toU8a('two')); - - // Store the root hash of the trie root node in a variable - const trieRootNodeHash = trie.getRoot(); - - // Store the root node object in a variable - const trieRootNode = trie.getNode(trieRootNodeHash); - - // Show the node object of the root node hash - console.log(`Root node object: ${trieRootNode}`); - - // Show information about the trie node - console.log(`Is root node object empty? : ${isEmptyNode(trieRootNode)}`); - console.log(`Is root node object a KV node? : ${isKvNode(trieRootNode)}`); - - // Show information about the trie that is Merkle Patricia Trie specific - // Reference: https://github.com/ethereum/wiki/wiki/Patricia-Tree#optimization - console.log(`Is root node object an Extension node? : ${isExtensionNode(trieRootNode)}`); - console.log(`Is root node object an Leaf node? : ${isLeafNode(trieRootNode)}`); - console.log(`Is root node object an Branch node? : ${isBranchNode(trieRootNode)}`); - - // Retrieve the value of a given key named 'test' in the trie - console.log(`Current value of key 'test': ${trie.get(toU8a('test'))}`); - - // Create a snapshot of the `trie` data into `back` - trie.snapshot(back, () => {}); - - // Show that value of the snapshot's root is the same as the original trie's root - console.log(`Snapshot root value matches original trie root: ${back.getRoot() === trie.getRoot()}`); - - // Deletes the value of a given key named 'test' in the trie branch - trie.del(toU8a('test')); - - // Show size of the database for each of the trie instances - console.log(`Size of 'trie' database: ${trie.size()}`); - console.log(`Size of 'back' database: ${back.size()}`); -} - -main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/trie-db/04_show_size_trie_node_info/package.json b/docs/examples/trie-db/04_show_size_trie_node_info/package.json deleted file mode 100644 index 00486e921..000000000 --- a/docs/examples/trie-db/04_show_size_trie_node_info/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "04_show_size_trie_node_info", - "version": "0.1.0", - "description": "Example showing how to show size and node info of a Patricia Trie", - "main": "index.js", - "author": "ltfschoen", - "license": "MIT", - "scripts": { - "clean": "rimraf node_modules", - "start": "node index.js" - }, - "dependencies": { - "@polkadot/trie-db": "^0.32.10", - "@polkadot/db": "^0.32.10" - }, - "devDependencies": { - "rimraf": "^2.6.2" - } -} diff --git a/docs/examples/trie-db/05_empty_close_drop_trie/README.md b/docs/examples/trie-db/05_empty_close_drop_trie/README.md deleted file mode 100644 index b0ea20678..000000000 --- a/docs/examples/trie-db/05_empty_close_drop_trie/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# Empty & Close & Drop a Patricia Trie - -The following example shows how to empty, close, and drop a Patricia Trie. - -[include](index.js) diff --git a/docs/examples/trie-db/05_empty_close_drop_trie/index.js b/docs/examples/trie-db/05_empty_close_drop_trie/index.js deleted file mode 100755 index 8cac90e97..000000000 --- a/docs/examples/trie-db/05_empty_close_drop_trie/index.js +++ /dev/null @@ -1,55 +0,0 @@ -const toU8a = require('@polkadot/util/u8a/toU8a').default; -const Trie = require('@polkadot/trie-db').default; -const { - isEmptyNode, - isKvNode -} = require('@polkadot/trie-db/util/is'); - -async function main () { - const trie = new Trie(); - - // Open the database for each of the trie instances - trie.open(); - - // Initial root value is valid - console.log(`Initial root Uint8Array value: ${trie.getRoot()}`); - - // Create a branch under the trie root with a key of 'branch1' and 'branch2' - // and a value of 'one' and 'two' - trie.put(toU8a('branch1'), toU8a('one')); - trie.put(toU8a('branch2'), toU8a('two')); - - // Retrieve the value of a given key named 'branch1' and 'branch2' in the trie - console.log(`Stored value of key 'branch1': ${trie.get(toU8a('branch1'))}`); - console.log(`Stored value of key 'branch2': ${trie.get(toU8a('branch2'))}`); - - // Store the root hash of the trie root node in a variable - const trieRootNodeHash = trie.getRoot(); - - // Store the root node object in a variable - const trieRootNode = trie.getNode(trieRootNodeHash); - - // Show information about the trie node - console.log(`Is root node object empty? : ${isEmptyNode(trieRootNode)}`); - console.log(`Is root node object a KV node? : ${isKvNode(trieRootNode)}`); - - // Deletes the value of a given key named 'branch1' in the trie branch - trie.del(toU8a('branch1')); - - // Retrieve the value of a given key named 'test' in the trie - console.log(`Stored value of key 'branch1': ${trie.get(toU8a('branch1'))}`); - - // Empty, close, and drop the database for each of the trie instances - trie.empty(); - - // Retrieve the value of a given key named 'test' in the trie - console.log(`Stored value of key 'branch2': ${trie.get(toU8a('branch2'))}`); - - // Close the trie - trie.close(); - - // Drop the trie - trie.drop(); -} - -main().catch(console.error).finally(_ => process.exit()); diff --git a/docs/examples/trie-db/05_empty_close_drop_trie/package.json b/docs/examples/trie-db/05_empty_close_drop_trie/package.json deleted file mode 100644 index f53c6f0d0..000000000 --- a/docs/examples/trie-db/05_empty_close_drop_trie/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "05_empty_close_drop_trie", - "version": "0.1.0", - "description": "Example showing how to empty, close, and drop a Patricia Trie", - "main": "index.js", - "author": "ltfschoen", - "license": "MIT", - "scripts": { - "clean": "rimraf node_modules", - "start": "node index.js" - }, - "dependencies": { - "@polkadot/trie-db": "^0.32.10", - "@polkadot/db": "^0.32.10" - }, - "devDependencies": { - "rimraf": "^2.6.2" - } -} diff --git a/docs/examples/trie-db/README.md b/docs/examples/trie-db/README.md deleted file mode 100644 index 85b939af9..000000000 --- a/docs/examples/trie-db/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Trie-DB Examples - -Here you will find a list of examples that takes you through the basics of creating a Patricia Trie, creating key/value pair branches, retrieving the value of a branch with its key, deleting branches, saving the root node hash to a variable and then later setting the root node hash to restore the trie to its previous state, duplicating the trie with a snapshot, showing the size of the trie and other node information, and emptying, closing, and dropping the trie. - -## Running the examples - -From within each folder run the following to install required dependencies and to execute the example: -```shell -yarn; -yarn start -``` - diff --git a/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/index.js b/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/index.js index e6606e7e2..2b40ae600 100755 --- a/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/index.js +++ b/docs/examples/util-crypto/01_encrypt_decrypt_message_nacl/index.js @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ const { naclEncrypt, naclDecrypt } = require('@polkadot/util-crypto'); async function main () { @@ -20,4 +21,4 @@ async function main () { console.log(`Does the decrypted message match the original message? ${isMatch}`); } -main().catch(console.error).finally(_ => process.exit()); +main().catch(console.error).finally(() => process.exit()); diff --git a/docs/examples/util-crypto/02_sign_verify_message_nacl/index.js b/docs/examples/util-crypto/02_sign_verify_message_nacl/index.js index a12c67c87..042f7ffbc 100755 --- a/docs/examples/util-crypto/02_sign_verify_message_nacl/index.js +++ b/docs/examples/util-crypto/02_sign_verify_message_nacl/index.js @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ const { stringToU8a, u8aToHex } = require('@polkadot/util'); const { naclEncrypt, naclKeypairFromSeed, naclSign, naclVerify, randomAsU8a } = require('@polkadot/util-crypto'); @@ -13,7 +14,7 @@ async function main () { const messagePreEncryption = stringToU8a('please send me DOTs'); const noncePreEncryption = randomAsU8a(24); - const { encrypted, nonce } = naclEncrypt(messagePreEncryption, secret, noncePreEncryption); + const { encrypted } = naclEncrypt(messagePreEncryption, secret, noncePreEncryption); // Sign the message with a valid signature const messageSignature = naclSign(encrypted, secretKey); @@ -26,4 +27,4 @@ async function main () { console.log(`Was the message correctly signed? ${isValidSignature}`); } -main().catch(console.error).finally(_ => process.exit()); +main().catch(console.error).finally(() => process.exit()); diff --git a/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/index.js b/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/index.js index 332db61f4..426276f95 100755 --- a/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/index.js +++ b/docs/examples/util-crypto/03_mnemonic_generate_validate_bip39/index.js @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-var-requires,@typescript-eslint/no-unused-vars */ const { mnemonicGenerate, mnemonicToSeed, mnemonicValidate, naclKeypairFromSeed } = require('@polkadot/util-crypto'); async function main () { @@ -21,4 +22,4 @@ async function main () { // Encrypt, Sign and Validate the message. See Example 'Sign & Verify Message' } -main().catch(console.error).finally(_ => process.exit()); +main().catch(console.error).finally(() => process.exit()); diff --git a/jest.config.js b/jest.config.js index ac444112d..378d10b68 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,3 +1,4 @@ +// eslint-disable-next-line @typescript-eslint/no-var-requires const config = require('@polkadot/dev/config/jest'); module.exports = Object.assign({}, config, { diff --git a/package.json b/package.json index 951abcf84..8e96cfe12 100644 --- a/package.json +++ b/package.json @@ -14,14 +14,14 @@ "scripts": { "build": "polkadot-dev-build-ts && polkadot-dev-build-docs", "check": "yarn lint", - "lint": "tslint --project . && tsc --noEmit --pretty", + "lint": "eslint . --ext .js,.jsx,.ts,.tsx . && tsc --noEmit --pretty", "clean": "polkadot-dev-clean-build", "postinstall": "polkadot-dev-yarn-only", "test": "jest --coverage" }, "devDependencies": { "@babel/core": "^7.5.4", - "@polkadot/dev": "^0.30.0-beta.21", + "@polkadot/dev": "^0.30.0-beta.22", "@polkadot/ts": "^0.1.62", "gh-pages": "^2.0.1" } diff --git a/packages/chainspec/src/alexander.ts b/packages/chainspec/src/alexander.ts index 7b12ff16b..11fd43ba5 100644 --- a/packages/chainspec/src/alexander.ts +++ b/packages/chainspec/src/alexander.ts @@ -4,25 +4,26 @@ import { Chainspec } from './types'; +// eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion export default { - 'name': 'Alexander', - 'id': 'alexander', - 'bootNodes': [ + name: 'Alexander', + id: 'alexander', + bootNodes: [ '/ip4/104.211.54.233/tcp/30363/p2p/QmUghPWmHR8pQbZyBMeYzvPcH7VRcTiBibcyBG7wMKHaSZ', '/ip4/104.211.48.51/tcp/30363/p2p/QmYWrEtg4iQYwV9PG37PhfLHLATQJUTYiZRyoUvSYny9ba', '/ip4/104.211.48.247/tcp/30363/p2p/QmYT3p4qGj1jwb7hDx1A6cDzAPtaHp3VR34vmw5BsXXB8D', '/ip4/40.117.153.33/tcp/30363/p2p/QmPiGU1jwL9UDw2FMyMQFr9FdpF9hURKxkfy6PWw6aLsur' ], - 'telemetryUrl': 'wss://telemetry.polkadot.io/submit/', - 'protocolId': 'dot', - 'consensusEngine': null, - 'properties': { - 'tokenDecimals': 15, - 'tokenSymbol': 'DOT' + telemetryUrl: 'wss://telemetry.polkadot.io/submit/', + protocolId: 'dot', + consensusEngine: null, + properties: { + tokenDecimals: 15, + tokenSymbol: 'DOT' }, - 'genesisRoot': '0xb7d6370bd450b32ca9f7ee8a9c914083bd08367c26586b03dca26672e6fa2707', - 'genesis': { - 'raw': { + genesisRoot: '0xb7d6370bd450b32ca9f7ee8a9c914083bd08367c26586b03dca26672e6fa2707', + genesis: { + raw: { '0x2ec6e5652282d579398fb8fdfa531ef6': '0x0000000000000000', '0x4664fb5d4e16f894df23cadb3faaa9a6': '0x04000000', '0xfc2dc4b8bb0b9ca8f01a73a726f7c7f5': '0x00e1000000000000', diff --git a/packages/chainspec/src/dried-danta.ts b/packages/chainspec/src/dried-danta.ts index f94cde27d..225f11d8e 100644 --- a/packages/chainspec/src/dried-danta.ts +++ b/packages/chainspec/src/dried-danta.ts @@ -4,25 +4,26 @@ import { Chainspec } from './types'; +// eslint-disable-next-line @typescript-eslint/no-object-literal-type-assertion export default { - 'name': 'Dried Danta', - 'id': 'dried-danta', - 'properties': { - 'tokenDecimals': 15, - 'tokenSymbol': 'DAN' + name: 'Dried Danta', + id: 'dried-danta', + properties: { + tokenDecimals: 15, + tokenSymbol: 'DAN' }, - 'bootNodes': [ + bootNodes: [ '/ip4/104.211.54.233/tcp/30333/p2p/QmWxNqJeKEBWjJXeX8s882ZdphuVPgUV43THfGAJn7UBWB', '/ip4/104.211.48.51/tcp/30333/p2p/QmXd7MQAuXkQK1r3ejSbaXKgjXmT2FvbJ3yNfLZpsQ2t8S', '/ip4/104.211.48.247/tcp/30333/p2p/QmV2zjgFRfxbgYZQC9qFr4aHsQt7tDBJRAdgqqxqTq1Kta', '/ip4/40.114.120.164/tcp/30333/p2p/QmQbPCeurXuKhzCw6Ar6ovizNKATMTnkkqFJKgZzbF2MJs' ], - 'telemetryUrl': 'wss://telemetry.polkadot.io/submit/', - 'protocolId': null, - 'consensusEngine': null, - 'genesisRoot': '0x29bbc626c6d5739cc9272a4e3b438bbc8dd18d7872e532137ccea03423ae8986', - 'genesis': { - 'raw': { + telemetryUrl: 'wss://telemetry.polkadot.io/submit/', + protocolId: null, + consensusEngine: null, + genesisRoot: '0x29bbc626c6d5739cc9272a4e3b438bbc8dd18d7872e532137ccea03423ae8986', + genesis: { + raw: { '0xf718f07ec955fb94f1b3069713461089': '0x0010a5d4e80000000000000000000000', '0xdee5bbb035d9ebc2c9338b5aedf744d7': '0x4038000000000000', '0xdfaac108e0d4bc78fc9419a7fcfa84dc': '0x1082c39b31a2b79a90f8e66e7a77fdb85a4ed5517f2ae39f6a80565e8ecae85cf54de37a07567ebcbf8c64568428a835269a566723687058e017b6d69db00a77e7063d7787ebca768b7445dfebe7d62cbb1625ff4dba288ea34488da266dd6dca58101764f45778d4980dadaceee6e8af2517d3ab91ac9bec9cd1714fa5994081c', diff --git a/packages/chainspec/src/types.ts b/packages/chainspec/src/types.ts index ac8157358..d15c0a21c 100644 --- a/packages/chainspec/src/types.ts +++ b/packages/chainspec/src/types.ts @@ -4,20 +4,17 @@ export type Telemetry = [string, number]; -export type Chainspec = { - bootNodes: Array, - id: string, +export interface Chainspec { + bootNodes: string[]; + id: string; genesis: { - raw: { - [index: string]: string - } - }, - genesisRoot?: string, - name: string, - properties: null | { - [index: string]: any - }, - protocolId: string | null, - telemetryUrl?: string | null, - telemetryEndpoints?: Array -}; + raw: Record; + }; + genesisRoot?: string; + name: string; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + properties: null | Record; + protocolId: string | null; + telemetryUrl?: string | null; + telemetryEndpoints?: Telemetry[]; +} diff --git a/packages/db/src/Memory.ts b/packages/db/src/Memory.ts index 84bb21b0a..705a58481 100644 --- a/packages/db/src/Memory.ts +++ b/packages/db/src/Memory.ts @@ -2,8 +2,6 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { BaseDbOptions } from './types'; - import MemoryDb from './engines/MemoryDb'; import TransactionDb from './engines/TransactionDb'; @@ -47,7 +45,7 @@ import TransactionDb from './engines/TransactionDb'; * memoryDb.del(key); * * // Transaction to Store key/value pair in transaction db - * const isTxSuccess = txDb.transaction(() => { + * const isTxSuccess = txDb.transaction((): void => { * txDb.put(key, value); * * // Boolean to indicate whether transaction was successful or not @@ -64,7 +62,7 @@ import TransactionDb from './engines/TransactionDb'; * ``` */ export default class Memory extends TransactionDb { - constructor (options?: BaseDbOptions) { + public constructor () { super(new MemoryDb()); } } diff --git a/packages/db/src/engines/LruDb.spec.ts b/packages/db/src/engines/LruDb.spec.ts index ad6dbbb9b..c488eb096 100644 --- a/packages/db/src/engines/LruDb.spec.ts +++ b/packages/db/src/engines/LruDb.spec.ts @@ -7,11 +7,11 @@ import toU8a from '@polkadot/util/u8a/toU8a'; import LruDb from './LruDb'; import MemoryDb from './MemoryDb'; -describe('LruDb', () => { +describe('LruDb', (): void => { const memory = new MemoryDb(); const db = new LruDb(memory); - it('retrieves an item from the backing when not available (caching it)', () => { + it('retrieves an item from the backing when not available (caching it)', (): void => { const key = toU8a('test1'); const value = toU8a('value1'); @@ -21,7 +21,7 @@ describe('LruDb', () => { expect(db._getLru(key)).toEqual({ value }); }); - it('replaces an item (caching and backing)', () => { + it('replaces an item (caching and backing)', (): void => { const key = toU8a('test1'); const value = toU8a('test'); @@ -32,7 +32,7 @@ describe('LruDb', () => { expect(db._getLru(key)).toEqual({ value }); }); - it('retrieves item from LRU when available', () => { + it('retrieves item from LRU when available', (): void => { const key = toU8a('test1'); const value = toU8a('test'); @@ -41,7 +41,7 @@ describe('LruDb', () => { expect(db.get(key)).toEqual(value); }); - it('puts item both in LRU and backing', () => { + it('puts item both in LRU and backing', (): void => { const key = toU8a('test0'); const value = toU8a('value0'); @@ -51,7 +51,7 @@ describe('LruDb', () => { expect(db._getLru(key)).toEqual({ value }); }); - it('deletes an item from both backing and db', () => { + it('deletes an item from both backing and db', (): void => { const key = toU8a('test0'); db.del(key); diff --git a/packages/db/src/engines/LruDb.ts b/packages/db/src/engines/LruDb.ts index 03276a95c..6df567613 100644 --- a/packages/db/src/engines/LruDb.ts +++ b/packages/db/src/engines/LruDb.ts @@ -7,9 +7,9 @@ import { BaseDb, ProgressCb } from '../types'; import { LRUMap } from 'lru_map'; import { logger } from '@polkadot/util'; -type CachedValue = { - value: Uint8Array | null -}; +interface CachedValue { + value: Uint8Array | null; +} const DEFAULT_ITEM_COUNT = 4096; @@ -17,58 +17,59 @@ const l = logger('db/lru'); export default class LruDb implements BaseDb { private backing: BaseDb; + private lru: LRUMap; - constructor (backing: BaseDb, itemCount: number = DEFAULT_ITEM_COUNT) { + public constructor (backing: BaseDb, itemCount: number = DEFAULT_ITEM_COUNT) { this.backing = backing; this.lru = new LRUMap(itemCount); } - close (): void { - l.debug(() => ['close']); + public close (): void { + l.debug((): string[] => ['close']); this.lru.clear(); this.backing.close(); } - open (): void { - l.debug(() => ['open']); + public open (): void { + l.debug((): string[] => ['open']); this.lru.clear(); this.backing.open(); } - drop (): void { + public drop (): void { this.backing.drop(); } - empty (): void { - l.debug(() => ['empty']); + public empty (): void { + l.debug((): string[] => ['empty']); this.lru.clear(); this.backing.empty(); } - rename (base: string, file: string): void { + public rename (base: string, file: string): void { this.backing.rename(base, file); } - maintain (fn: ProgressCb): void { + public maintain (fn: ProgressCb): void { this.backing.maintain(fn); } - size (): number { + public size (): number { return this.backing.size(); } - del (key: Uint8Array): void { + public del (key: Uint8Array): void { const keyStr = key.toString(); this.backing.del(key); this.lru.set(keyStr, { value: null }); } - get (key: Uint8Array): Uint8Array | null { + public get (key: Uint8Array): Uint8Array | null { const keyStr = key.toString(); const cached = this.lru.get(keyStr); @@ -84,30 +85,30 @@ export default class LruDb implements BaseDb { } // Convenience methods used in tests - _getLru (key: Uint8Array): CachedValue | undefined { + public _getLru (key: Uint8Array): CachedValue | undefined { return this.lru.get(key.toString()); } - put (key: Uint8Array, value: Uint8Array): void { + public put (key: Uint8Array, value: Uint8Array): void { const keyStr = key.toString(); this.backing.put(key, value); this.lru.set(keyStr, { value }); } - txCommit (): void { + public txCommit (): void { if (this.backing.txCommit) { this.backing.txCommit(); } } - txRevert (): void { + public txRevert (): void { if (this.backing.txRevert) { this.backing.txRevert(); } } - txStart (): void { + public txStart (): void { if (this.backing.txStart) { this.backing.txStart(); } diff --git a/packages/db/src/engines/MemoryDb.spec.ts b/packages/db/src/engines/MemoryDb.spec.ts index dfb9ed89c..3e9836225 100644 --- a/packages/db/src/engines/MemoryDb.spec.ts +++ b/packages/db/src/engines/MemoryDb.spec.ts @@ -4,10 +4,10 @@ import MemoryDb from './MemoryDb'; -describe('MemoryDb', () => { +describe('MemoryDb', (): void => { const memory = new MemoryDb(); - it('gets the combioned size of the entry values', () => { + it('gets the combioned size of the entry values', (): void => { memory.put(new Uint8Array([1]), new Uint8Array([1, 2, 3])); memory.put(new Uint8Array([2]), new Uint8Array([1, 2, 3])); memory.put(new Uint8Array([3]), new Uint8Array([1, 2, 3])); @@ -15,13 +15,13 @@ describe('MemoryDb', () => { expect(memory.size()).toEqual(9); }); - it('does not throw on the stubs', (done) => { + it('does not throw on the stubs', (done): void => { memory.close(); memory.open(); memory.drop(); memory.empty(); memory.rename('foo', 'bar'); - memory.maintain(() => done()); + memory.maintain((): void => done()); }); }); diff --git a/packages/db/src/engines/MemoryDb.ts b/packages/db/src/engines/MemoryDb.ts index 1bf93befc..0390ed478 100644 --- a/packages/db/src/engines/MemoryDb.ts +++ b/packages/db/src/engines/MemoryDb.ts @@ -11,27 +11,28 @@ const l = logger('db/memory'); export default class MemoryDb implements BaseDb { private _storage: Map = new Map(); - close (): void { + public close (): void { this.empty(); } - open (): void { + public open (): void { this.empty(); } - drop (): void { + public drop (): void { this.empty(); } - empty (): void { + public empty (): void { this._storage.clear(); } - rename (base: string, file: string): void { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + public rename (base: string, file: string): void { l.warn('rename() is not implemented'); } - maintain (fn: ProgressCb): void { + public maintain (fn: ProgressCb): void { fn({ isCompleted: true, keys: this._storage.size, @@ -39,29 +40,29 @@ export default class MemoryDb implements BaseDb { }); } - size (): number { + public size (): number { let size = 0; - this._storage.forEach((value) => - size += value.length - ); + this._storage.forEach((value): void => { + size += value.length; + }); return size; } - del (key: Uint8Array): void { + public del (key: Uint8Array): void { // l.debug(() => ['del', { key }]); this._storage.delete(key.toString()); } - get (key: Uint8Array): Uint8Array | null { + public get (key: Uint8Array): Uint8Array | null { // l.debug(() => ['get', { key }]); return this._storage.get(key.toString()) || null; } - put (key: Uint8Array, value: Uint8Array): void { + public put (key: Uint8Array, value: Uint8Array): void { // l.debug(() => ['put', { key, value }]); this._storage.set(key.toString(), value); diff --git a/packages/db/src/engines/TransactionDb.spec.ts b/packages/db/src/engines/TransactionDb.spec.ts index 5f0ececda..79dadd0c1 100644 --- a/packages/db/src/engines/TransactionDb.spec.ts +++ b/packages/db/src/engines/TransactionDb.spec.ts @@ -7,11 +7,11 @@ import toU8a from '@polkadot/util/string/toU8a'; import MemoryDb from './MemoryDb'; import TransactionDb from './TransactionDb'; -describe('TransactionDb', () => { +describe('TransactionDb', (): void => { const memory = new MemoryDb(); const db = new TransactionDb(memory); - it('passed through values immediately when not in transaction', () => { + it('passed through values immediately when not in transaction', (): void => { const key = toU8a('test0'); const value = toU8a('value0'); @@ -20,12 +20,12 @@ describe('TransactionDb', () => { expect(memory.get(key)).toEqual(value); }); - it('commits when transaction passes (result = true, put)', () => { + it('commits when transaction passes (result = true, put)', (): void => { const key = toU8a('test1'); const value = toU8a('value1'); expect( - db.transaction(() => { + db.transaction((): boolean => { db.put(key, value); return true; @@ -34,11 +34,11 @@ describe('TransactionDb', () => { expect(memory.get(key)).toEqual(value); }); - it('commits when transaction passes (result = true, del)', () => { + it('commits when transaction passes (result = true, del)', (): void => { const key = toU8a('test0'); expect( - db.transaction(() => { + db.transaction((): boolean => { db.del(key); return true; @@ -47,12 +47,12 @@ describe('TransactionDb', () => { expect(memory.get(key)).toEqual(null); }); - it('does not commit when transaction fails (result = false)', () => { + it('does not commit when transaction fails (result = false)', (): void => { const key = toU8a('test2'); const value = toU8a('value2'); expect( - db.transaction(() => { + db.transaction((): boolean => { db.put(key, value); return false; @@ -61,13 +61,13 @@ describe('TransactionDb', () => { expect(memory.get(key)).toEqual(null); }); - it('does not commit when transaction throws', () => { + it('does not commit when transaction throws', (): void => { const key = toU8a('test2'); const value = toU8a('value2'); expect( - () => { - db.transaction(() => { + (): void => { + db.transaction((): void => { db.put(key, value); throw new Error('test'); @@ -77,11 +77,11 @@ describe('TransactionDb', () => { expect(memory.get(key)).toEqual(null); }); - it('inside the transaction, the value is set', () => { + it('inside the transaction, the value is set', (): void => { const key = toU8a('test2'); const value = toU8a('value2'); - db.transaction(() => { + db.transaction((): boolean => { db.put(key, value); expect(db.get(key)).toEqual(value); diff --git a/packages/db/src/engines/TransactionDb.ts b/packages/db/src/engines/TransactionDb.ts index 96d4fcd72..38a605733 100644 --- a/packages/db/src/engines/TransactionDb.ts +++ b/packages/db/src/engines/TransactionDb.ts @@ -6,25 +6,27 @@ import { BaseDb, TxDb, ProgressCb } from '../types'; import { assert, isNull, logger } from '@polkadot/util'; -type OverlayItem = { - key: Uint8Array, - value: Uint8Array | null -}; +interface OverlayItem { + key: Uint8Array; + value: Uint8Array | null; +} const l = logger('db/transact'); export default class TransactionDb implements TxDb { private backing: BaseDb; + private txOverlay: Map = new Map(); + private txStarted: boolean; - constructor (backing: BaseDb) { + public constructor (backing: BaseDb) { this.backing = backing; this.txStarted = false; } - transaction (fn: () => T): T { - l.debug(() => ['transaction']); + public transaction (fn: () => T): T { + l.debug((): string[] => ['transaction']); try { this.createTx(); @@ -45,37 +47,37 @@ export default class TransactionDb implements TxDb { } } - close (): void { + public close (): void { this.backing.close(); } - open (): void { + public open (): void { this.backing.open(); } - drop (): void { + public drop (): void { this.backing.drop(); } - empty (): void { + public empty (): void { this.backing.empty(); } - rename (base: string, file: string): void { + public rename (base: string, file: string): void { this.backing.rename(base, file); } - maintain (fn: ProgressCb): void { + public maintain (fn: ProgressCb): void { assert(this.txStarted === false, 'Cannot maintain inside an open transaction'); this.backing.maintain(fn); } - size (): number { + public size (): number { return this.backing.size(); } - del (key: Uint8Array): void { + public del (key: Uint8Array): void { if (this.txStarted) { this.txOverlay.set(key.toString(), { key, value: null }); return; @@ -84,7 +86,7 @@ export default class TransactionDb implements TxDb { this.backing.del(key); } - get (key: Uint8Array): Uint8Array | null { + public get (key: Uint8Array): Uint8Array | null { // l.debug(() => ['get', u8aToHex(key)]); if (this.txStarted) { @@ -98,7 +100,7 @@ export default class TransactionDb implements TxDb { return this.backing.get(key); } - put (key: Uint8Array, value: Uint8Array): void { + public put (key: Uint8Array, value: Uint8Array): void { // l.debug(() => ['put', u8aToHex(key), u8aToHex(value)]); if (this.txStarted) { @@ -111,7 +113,7 @@ export default class TransactionDb implements TxDb { } private createTx (): void { - l.debug(() => ['createTx']); + l.debug((): string[] => ['createTx']); assert(!this.txStarted, 'Cannot create a transaction when one is already active'); @@ -120,7 +122,7 @@ export default class TransactionDb implements TxDb { } private commitTx (): void { - l.debug(() => ['commitTx', Object.keys(this.txOverlay).length, 'keys']); + l.debug((): [string, number, string] => ['commitTx', Object.keys(this.txOverlay).length, 'keys']); assert(this.txStarted, 'Cannot commit when not in transaction'); @@ -128,7 +130,7 @@ export default class TransactionDb implements TxDb { this.backing.txStart(); } - this.txOverlay.forEach(({ key, value }) => { + this.txOverlay.forEach(({ key, value }): void => { if (isNull(value)) { this.backing.del(key); } else { @@ -145,7 +147,7 @@ export default class TransactionDb implements TxDb { } private revertTx (): void { - l.debug(() => ['revertTx']); + l.debug((): string[] => ['revertTx']); assert(this.txStarted, 'Cannot revert when not in transaction'); diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts index a0eca752a..b4793a8ad 100644 --- a/packages/db/src/types.ts +++ b/packages/db/src/types.ts @@ -2,19 +2,19 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -export type ProgressValue = { - isCompleted?: boolean, - keys: number, - percent: number -}; +export interface ProgressValue { + isCompleted?: boolean; + keys: number; + percent: number; +} export type ProgressCb = (progress: ProgressValue) => void; -export type BaseDbOptions = { - isCompressed?: boolean, - isLru?: boolean, - isNative?: boolean -}; +export interface BaseDbOptions { + isCompressed?: boolean; + isLru?: boolean; + isNative?: boolean; +} export interface BaseDb { close (): void; diff --git a/packages/keyring/src/index.spec.ts b/packages/keyring/src/index.spec.ts index a787a036b..90148d141 100644 --- a/packages/keyring/src/index.spec.ts +++ b/packages/keyring/src/index.spec.ts @@ -7,31 +7,31 @@ import { cryptoWaitReady, setAddressPrefix } from '@polkadot/util-crypto'; import Keyring from '.'; -describe('keypair', () => { - beforeEach(async () => { +describe('keypair', (): void => { + beforeEach(async (): Promise => { await cryptoWaitReady(); }); - describe('ed25519', () => { + describe('ed25519', (): void => { const publicKeyOne = new Uint8Array([47, 140, 97, 41, 216, 22, 207, 81, 195, 116, 188, 127, 8, 195, 230, 62, 209, 86, 207, 120, 174, 251, 74, 101, 80, 217, 123, 135, 153, 121, 119, 238]); const publicKeyTwo = new Uint8Array([215, 90, 152, 1, 130, 177, 10, 183, 213, 75, 254, 211, 201, 100, 7, 58, 14, 225, 114, 243, 218, 166, 35, 37, 175, 2, 26, 104, 247, 7, 81, 26]); const seedOne = stringToU8a('12345678901234567890123456789012'); const seedTwo = hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60'); let keypair: Keyring; - beforeEach(async () => { + beforeEach(async (): Promise => { keypair = new Keyring({ type: 'ed25519' }); keypair.addFromSeed(seedOne, {}); }); - it('adds the pair', () => { + it('adds the pair', (): void => { expect( keypair.addFromSeed(seedTwo, {}).publicKey ).toEqual(publicKeyTwo); }); - it('creates a ed25519 pair via mnemonicToSeed', () => { + it('creates a ed25519 pair via mnemonicToSeed', (): void => { expect( keypair.addFromUri( 'seed sock milk update focus rotate barely fade car face mechanic mercy' @@ -39,7 +39,7 @@ describe('keypair', () => { ).toEqual('5DkQP32jP4DVJLWWBRBoZF2tpWjqFrcrTBo6H5NcSk7MxKCC'); }); - it('adds from a mnemonic', () => { + it('adds from a mnemonic', (): void => { setAddressPrefix(68); expect( @@ -47,21 +47,21 @@ describe('keypair', () => { ).toEqual('7sPsxWPE5DzAyPT3VuoJYw5NTGscx9QYN9oddQx4kALKC3hH'); }); - it('allows publicKeys retrieval', () => { + it('allows publicKeys retrieval', (): void => { keypair.addFromSeed(seedTwo, {}); expect( keypair.getPublicKeys() - ).toEqual([ publicKeyOne, publicKeyTwo ]); + ).toEqual([publicKeyOne, publicKeyTwo]); }); - it('allows retrieval of a specific item', () => { + it('allows retrieval of a specific item', (): void => { expect( keypair.getPair(publicKeyOne).publicKey ).toEqual(publicKeyOne); }); - it('allows adding from JSON', () => { + it('allows adding from JSON', (): void => { expect( keypair.addFromJson( JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}') @@ -71,7 +71,7 @@ describe('keypair', () => { ); }); - it('signs and verifies', () => { + it('signs and verifies', (): void => { const MESSAGE = stringToU8a('this is a message'); const pair = keypair.getPair(publicKeyOne); const signature = pair.sign(MESSAGE); @@ -80,32 +80,32 @@ describe('keypair', () => { }); }); - describe('sr25519', () => { + describe('sr25519', (): void => { const publicKeyOne = new Uint8Array([116, 28, 8, 160, 111, 65, 197, 150, 96, 143, 103, 116, 37, 155, 217, 4, 51, 4, 173, 250, 93, 62, 234, 98, 118, 11, 217, 190, 151, 99, 77, 99]); const publicKeyTwo = hexToU8a('0x44a996beb1eef7bdcab976ab6d2ca26104834164ecf28fb375600576fcc6eb0f'); const seedOne = stringToU8a('12345678901234567890123456789012'); const seedTwo = hexToU8a('0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60'); let keypair: Keyring; - beforeEach(() => { + beforeEach((): void => { keypair = new Keyring({ type: 'sr25519' }); keypair.addFromSeed(seedOne, {}); }); - it('creates with dev phrase when only path specified', () => { + it('creates with dev phrase when only path specified', (): void => { expect( keypair.createFromUri('//Alice').address ).toEqual('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); }); - it('adds the pair', () => { + it('adds the pair', (): void => { expect( keypair.addFromSeed(seedTwo, {}).publicKey ).toEqual(publicKeyTwo); }); - it('adds from a mnemonic', () => { + it('adds from a mnemonic', (): void => { setAddressPrefix(68); expect( @@ -113,21 +113,21 @@ describe('keypair', () => { ).toEqual('7qQGarA4PWjPPVHG4USn1yuuVZvEHN7XZz8o7EbAp48jayZQ'); }); - it('allows publicKeys retrieval', () => { + it('allows publicKeys retrieval', (): void => { keypair.addFromSeed(seedTwo, {}); expect( keypair.getPublicKeys() - ).toEqual([ publicKeyOne, publicKeyTwo ]); + ).toEqual([publicKeyOne, publicKeyTwo]); }); - it('allows retrieval of a specific item', () => { + it('allows retrieval of a specific item', (): void => { expect( keypair.getPair(publicKeyOne).publicKey ).toEqual(publicKeyOne); }); - it('allows adding from JSON', () => { + it('allows adding from JSON', (): void => { expect( keypair.addFromJson( JSON.parse('{"address":"5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua","encoded":"0xb4a14995d25ab609f3686e9fa45f1fb237cd833f33f00d4b12c51858ca070d96972e47d73aae5eeb0fc06f923826cf0943fdb02c2c2ee30ef52a7912663053940d1da4da66b3a3f520ae07422c1c94b2d95690fca9d1f4a997623bb2923a8833280e19e7f72c3c5cfa343974e60e2b3dc53b404fdaf330756daad5e4e3","encoding":{"content":"pkcs8","type":"xsalsa20-poly1305","version":"0"},"meta":{"isTesting":true,"name":"alice"}}') @@ -137,7 +137,7 @@ describe('keypair', () => { ); }); - it('signs and verifies', () => { + it('signs and verifies', (): void => { const MESSAGE = stringToU8a('this is a message'); const pair = keypair.getPair(publicKeyOne); const signature = pair.sign(MESSAGE); diff --git a/packages/keyring/src/index.ts b/packages/keyring/src/index.ts index ffdd45fcd..a57b66305 100644 --- a/packages/keyring/src/index.ts +++ b/packages/keyring/src/index.ts @@ -5,7 +5,7 @@ import { assertSingletonPackage } from '@polkadot/util'; import { decodeAddress, encodeAddress, setAddressPrefix } from '@polkadot/util-crypto'; -import { default as Keyring } from './keyring'; +import Keyring from './keyring'; assertSingletonPackage('@polkadot/keyring'); diff --git a/packages/keyring/src/keyring.ts b/packages/keyring/src/keyring.ts index 617f1a172..0bca24067 100644 --- a/packages/keyring/src/keyring.ts +++ b/packages/keyring/src/keyring.ts @@ -30,9 +30,16 @@ import Pairs from './pairs'; */ export default class Keyring implements KeyringInstance { private _pairs: Pairs; + private _type: KeypairType; - constructor (options: KeyringOptions = {}) { + public decodeAddress = decodeAddress; + + public encodeAddress = encodeAddress; + + public setAddressPrefix = setAddressPrefix; + + public constructor (options: KeyringOptions = {}) { options.type = options.type || 'ed25519'; assert(options && ['ed25519', 'sr25519'].includes(options.type || 'undefined'), `Expected a keyring type of either 'ed25519' or 'sr25519', found '${options.type}`); @@ -43,28 +50,24 @@ export default class Keyring implements KeyringInstance { setAddressPrefix(isNumber(options.addressPrefix) ? options.addressPrefix : 42); } - decodeAddress = decodeAddress; - encodeAddress = encodeAddress; - setAddressPrefix = setAddressPrefix; - /** * @description retrieve the pairs (alias for getPairs) */ - get pairs (): Array { + public get pairs (): KeyringPair[] { return this.getPairs(); } /** * @description retrieve the publicKeys (alias for getPublicKeys) */ - get publicKeys (): Array { + public get publicKeys (): Uint8Array[] { return this.getPublicKeys(); } /** * @description Returns the type of the keyring, either ed25519 of sr25519 */ - get type (): KeypairType { + public get type (): KeypairType { return this._type; } @@ -72,7 +75,7 @@ export default class Keyring implements KeyringInstance { * @name addPair * @summary Stores an account, given a keyring pair, as a Key/Value (public key, pair) in Keyring Pair Dictionary */ - addPair (pair: KeyringPair): KeyringPair { + public addPair (pair: KeyringPair): KeyringPair { return this._pairs.add(pair); } @@ -84,7 +87,7 @@ export default class Keyring implements KeyringInstance { * of an account backup), and then generates a keyring pair from them that it passes to * `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value. */ - addFromAddress (address: string | Uint8Array, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null, type: KeypairType = this.type, ignoreChecksum?: boolean): KeyringPair { + public addFromAddress (address: string | Uint8Array, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null, type: KeypairType = this.type, ignoreChecksum?: boolean): KeyringPair { const publicKey = this.decodeAddress(address, ignoreChecksum); return this.addPair(createPair(type, { publicKey }, meta, encoded)); @@ -97,7 +100,7 @@ export default class Keyring implements KeyringInstance { * of an account backup), and then generates a keyring pair from it that it passes to * `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value. */ - addFromJson ({ address, encoded, encoding: { content, version }, meta }: KeyringPair$Json, ignoreChecksum?: boolean): KeyringPair { + public addFromJson ({ address, encoded, encoding: { content, version }, meta }: KeyringPair$Json, ignoreChecksum?: boolean): KeyringPair { const type = version === '0' || !Array.isArray(content) ? this.type : content[1]; @@ -113,7 +116,7 @@ export default class Keyring implements KeyringInstance { * of an account backup), and then generates a keyring pair from it that it passes to * `addPair` to stores in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value. */ - addFromMnemonic (mnemonic: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair { + public addFromMnemonic (mnemonic: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair { return this.addFromUri(mnemonic, meta, type); } @@ -124,7 +127,7 @@ export default class Keyring implements KeyringInstance { * Allows user to provide the account seed as an argument, and then generates a keyring pair from it that it passes to * `addPair` to store in a keyring pair dictionary the public key of the generated pair as a key and the pair as the associated value. */ - addFromSeed (seed: Uint8Array, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair { + public addFromSeed (seed: Uint8Array, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair { const keypair = type === 'sr25519' ? schnorrkelFromSeed(seed) : naclFromSeed(seed); @@ -137,7 +140,7 @@ export default class Keyring implements KeyringInstance { * @summary Creates an account via an suri * @description Extracts the phrase, path and password from a SURI format for specifying secret keys `//////` (the `///password` may be omitted, and `/` and `//` maybe repeated and mixed). The secret can be a hex string, mnemonic phrase or a string (to be padded) */ - addFromUri (suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair { + public addFromUri (suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair { return this.addPair( this.createFromUri(suri, meta, type) ); @@ -148,7 +151,7 @@ export default class Keyring implements KeyringInstance { * @summry Creates a Keypair from an suri * @description This creates a pair from the suri, but does not add it to the keyring */ - createFromUri (_suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair { + public createFromUri (_suri: string, meta: KeyringPair$Meta = {}, type: KeypairType = this.type): KeyringPair { // here we only aut-add the dev phrase if we have a hard-derived path const suri = _suri.indexOf('//') === 0 ? `${DEV_PHRASE}${_suri}` @@ -189,7 +192,7 @@ export default class Keyring implements KeyringInstance { * @description Returns a keyring pair value from the keyring pair dictionary by performing * a key lookup using the provided account address or public key (after decoding it). */ - getPair (address: string | Uint8Array): KeyringPair { + public getPair (address: string | Uint8Array): KeyringPair { return this._pairs.get(address); } @@ -198,7 +201,7 @@ export default class Keyring implements KeyringInstance { * @summary Retrieves all account keyring pairs from the Keyring Pair Dictionary * @description Returns an array list of all the keyring pair values that are stored in the keyring pair dictionary. */ - getPairs (): Array { + public getPairs (): KeyringPair[] { return this._pairs.all(); } @@ -207,10 +210,10 @@ export default class Keyring implements KeyringInstance { * @summary Retrieves Public Keys of all Keyring Pairs stored in the Keyring Pair Dictionary * @description Returns an array list of all the public keys associated with each of the keyring pair values that are stored in the keyring pair dictionary. */ - getPublicKeys (): Array { + public getPublicKeys (): Uint8Array[] { return this._pairs .all() - .map(({ publicKey }) => + .map(({ publicKey }): Uint8Array => publicKey ); } @@ -219,7 +222,7 @@ export default class Keyring implements KeyringInstance { * @name removePair * @description Deletes the provided input address or public key from the stored Keyring Pair Dictionary. */ - removePair (address: string | Uint8Array): void { + public removePair (address: string | Uint8Array): void { this._pairs.remove(address); } @@ -231,7 +234,7 @@ export default class Keyring implements KeyringInstance { * is not already unlocked and available in memory. Note that in [Polkadot-JS Apps](https://github.com/polkadot-js/apps) the user * may backup their account to a JSON file that contains this information. */ - toJson (address: string | Uint8Array, passphrase?: string): KeyringPair$Json { + public toJson (address: string | Uint8Array, passphrase?: string): KeyringPair$Json { return this._pairs.get(address).toJson(passphrase); } } diff --git a/packages/keyring/src/pair/decode.spec.ts b/packages/keyring/src/pair/decode.spec.ts index 43b18bca1..dd1d10c15 100644 --- a/packages/keyring/src/pair/decode.spec.ts +++ b/packages/keyring/src/pair/decode.spec.ts @@ -6,18 +6,18 @@ import testingPairs from '../testingPairs'; const keyring = testingPairs({ type: 'ed25519' }, false); -describe('decode', () => { - it('fails when no data provided', () => { +describe('decode', (): void => { + it('fails when no data provided', (): void => { expect( - () => keyring.alice.decodePkcs8() + (): void => keyring.alice.decodePkcs8() ).toThrow(/No encrypted data available/); }); - it('returns correct publicKey from encoded', () => { + it('returns correct publicKey from encoded', (): void => { const PASS = 'testing'; expect( - () => keyring.alice.decodePkcs8( + (): void => keyring.alice.decodePkcs8( PASS, keyring.alice.encodePkcs8(PASS) ) ).not.toThrow(); diff --git a/packages/keyring/src/pair/decode.ts b/packages/keyring/src/pair/decode.ts index 78ef18507..80b9306dc 100644 --- a/packages/keyring/src/pair/decode.ts +++ b/packages/keyring/src/pair/decode.ts @@ -11,7 +11,7 @@ import { NONCE_LENGTH, PKCS8_DIVIDER, PKCS8_HEADER, PUB_LENGTH, SEC_LENGTH, SEED const SEED_OFFSET = PKCS8_HEADER.length; type DecodeResult = PairInfo & { - secretKey: Uint8Array + secretKey: Uint8Array; }; export default function decode (passphrase?: string, _encrypted?: Uint8Array | null): DecodeResult { @@ -20,10 +20,10 @@ export default function decode (passphrase?: string, _encrypted?: Uint8Array | n const encrypted = (_encrypted as Uint8Array); const encoded = passphrase ? (naclDecrypt( - encrypted.subarray(NONCE_LENGTH), - encrypted.subarray(0, NONCE_LENGTH), - u8aFixLength(stringToU8a(passphrase), 256, true) - ) as Uint8Array) + encrypted.subarray(NONCE_LENGTH), + encrypted.subarray(0, NONCE_LENGTH), + u8aFixLength(stringToU8a(passphrase), 256, true) + ) as Uint8Array) : encrypted; assert(encoded, `Unable to unencrypt using the supplied passphrase`); diff --git a/packages/keyring/src/pair/encode.spec.ts b/packages/keyring/src/pair/encode.spec.ts index 7e9befc6a..c79b6261b 100644 --- a/packages/keyring/src/pair/encode.spec.ts +++ b/packages/keyring/src/pair/encode.spec.ts @@ -10,14 +10,14 @@ const ENCODED_LENGTH = 157; const keyring = testingPairs({ type: 'ed25519' }, false); -describe('encode', () => { - it('returns PKCS8 when no passphrase supplied', () => { +describe('encode', (): void => { + it('returns PKCS8 when no passphrase supplied', (): void => { expect( keyring.alice.encodePkcs8() ).toHaveLength(PKCS8_LENGTH); }); - it('returns encoded PKCS8 when passphrase supplied', () => { + it('returns encoded PKCS8 when passphrase supplied', (): void => { expect( keyring.alice.encodePkcs8('testing') ).toHaveLength(ENCODED_LENGTH); diff --git a/packages/keyring/src/pair/index.spec.ts b/packages/keyring/src/pair/index.spec.ts index 1b00ad5b8..6706517e2 100644 --- a/packages/keyring/src/pair/index.spec.ts +++ b/packages/keyring/src/pair/index.spec.ts @@ -9,10 +9,10 @@ import createPair from '.'; const keyring = testingPairs({ type: 'ed25519' }, false); -describe('pair', () => { +describe('pair', (): void => { const SIGNATURE = new Uint8Array([80, 191, 198, 147, 225, 207, 75, 88, 126, 39, 129, 109, 191, 38, 72, 181, 75, 254, 81, 143, 244, 79, 237, 38, 236, 141, 28, 252, 134, 26, 169, 234, 79, 33, 153, 158, 151, 34, 175, 188, 235, 20, 35, 135, 83, 120, 139, 211, 233, 130, 1, 208, 201, 215, 73, 80, 56, 98, 185, 196, 11, 8, 193, 14]); - it('has a publicKey', () => { + it('has a publicKey', (): void => { expect( keyring.alice.publicKey ).toEqual( @@ -20,7 +20,7 @@ describe('pair', () => { ); }); - it('allows signing', () => { + it('allows signing', (): void => { expect( keyring.alice.sign( new Uint8Array([0x61, 0x62, 0x63, 0x64]) @@ -28,7 +28,7 @@ describe('pair', () => { ).toEqual(SIGNATURE); }); - it('validates a correctly signed message', () => { + it('validates a correctly signed message', (): void => { expect( keyring.alice.verify( new Uint8Array([0x61, 0x62, 0x63, 0x64]), @@ -37,7 +37,7 @@ describe('pair', () => { ).toEqual(true); }); - it('fails a correctly signed message (message changed)', () => { + it('fails a correctly signed message (message changed)', (): void => { expect( keyring.alice.verify( new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65]), @@ -46,7 +46,7 @@ describe('pair', () => { ).toEqual(false); }); - it('allows setting/getting of meta', () => { + it('allows setting/getting of meta', (): void => { keyring.bob.setMeta({ foo: 'bar', something: 'else' }); expect(keyring.bob.meta).toMatchObject({ foo: 'bar', something: 'else' }); @@ -56,7 +56,7 @@ describe('pair', () => { expect(keyring.bob.meta).toMatchObject({ foo: 'bar', something: 'thing' }); }); - it('allows encoding of address with different prefixes', () => { + it('allows encoding of address with different prefixes', (): void => { expect(keyring.alice.address).toEqual( '5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua' ); @@ -68,7 +68,7 @@ describe('pair', () => { ); }); - it('allows getting public key after decoding', () => { + it('allows getting public key after decoding', (): void => { const PASS = 'testing'; const encoded = keyring.alice.encodePkcs8(PASS); diff --git a/packages/keyring/src/pair/index.ts b/packages/keyring/src/pair/index.ts index b26034ab5..ed43829c7 100644 --- a/packages/keyring/src/pair/index.ts +++ b/packages/keyring/src/pair/index.ts @@ -15,17 +15,17 @@ import toJson from './toJson'; const isSr25519 = (type: KeypairType): boolean => type === 'sr25519'; -const fromSeed = (type: KeypairType, seed: Uint8Array) => +const fromSeed = (type: KeypairType, seed: Uint8Array): Keypair => isSr25519(type) ? schnorrkelFromSeed(seed) : naclFromSeed(seed); -const sign = (type: KeypairType, message: Uint8Array, pair: Partial) => +const sign = (type: KeypairType, message: Uint8Array, pair: Partial): Uint8Array => isSr25519(type) ? schnorrkelSign(message, pair) : naclSign(message, pair); -const verify = (type: KeypairType, message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array) => +const verify = (type: KeypairType, message: Uint8Array, signature: Uint8Array, publicKey: Uint8Array): boolean => isSr25519(type) ? schnorrkelVerify(message, signature, publicKey) : naclVerify(message, signature, publicKey); @@ -64,7 +64,7 @@ const verify = (type: KeypairType, message: Uint8Array, signature: Uint8Array, p export default function createPair (type: KeypairType, { publicKey, secretKey }: PairInfo, meta: KeyringPair$Meta = {}, encoded: Uint8Array | null = null): KeyringPair { return { type, - get address () { + get address (): string { return encodeAddress(publicKey); }, decodePkcs8: (passphrase?: string, _encoded?: Uint8Array | null): void => { @@ -82,16 +82,16 @@ export default function createPair (type: KeypairType, { publicKey, secretKey }: }, encodePkcs8: (passphrase?: string): Uint8Array => encode({ publicKey, secretKey }, passphrase), - get meta () { + get meta (): KeyringPair$Meta { return meta; }, - get isLocked () { + get isLocked (): boolean { return !secretKey || secretKey.length === 0; }, lock: (): void => { secretKey = new Uint8Array(0); }, - get publicKey () { + get publicKey (): Uint8Array { return publicKey; }, setMeta: (additional: KeyringPair$Meta): void => { diff --git a/packages/keyring/src/pair/nobody.ts b/packages/keyring/src/pair/nobody.ts index 0d26ccced..46b3bd0f0 100644 --- a/packages/keyring/src/pair/nobody.ts +++ b/packages/keyring/src/pair/nobody.ts @@ -27,8 +27,10 @@ export default function everybody (): KeyringPair { return { type: 'ed25519', address, + // eslint-disable-next-line @typescript-eslint/no-unused-vars decodePkcs8: (passphrase?: string, encoded?: Uint8Array): void => undefined, + // eslint-disable-next-line @typescript-eslint/no-unused-vars encodePkcs8: (passphrase?: string): Uint8Array => new Uint8Array(0), meta, @@ -37,12 +39,16 @@ export default function everybody (): KeyringPair { // no locking, it is always locked }, publicKey, + // eslint-disable-next-line @typescript-eslint/no-unused-vars setMeta: (meta: KeyringPair$Meta): void => undefined, + // eslint-disable-next-line @typescript-eslint/no-unused-vars sign: (message: Uint8Array): Uint8Array => new Uint8Array(64), + // eslint-disable-next-line @typescript-eslint/no-unused-vars toJson: (passphrase?: string): KeyringPair$Json => json, + // eslint-disable-next-line @typescript-eslint/no-unused-vars verify: (message: Uint8Array, signature: Uint8Array): boolean => false }; diff --git a/packages/keyring/src/pair/toJson.spec.ts b/packages/keyring/src/pair/toJson.spec.ts index 022055ec6..c7c6d25e1 100644 --- a/packages/keyring/src/pair/toJson.spec.ts +++ b/packages/keyring/src/pair/toJson.spec.ts @@ -6,8 +6,8 @@ import testingPairs from '../testingPairs'; const keyring = testingPairs({ type: 'ed25519' }, false); -describe('toJson', () => { - it('creates an unencoded output with no passphrase', () => { +describe('toJson', (): void => { + it('creates an unencoded output with no passphrase', (): void => { expect( keyring.alice.toJson() ).toMatchObject({ @@ -25,7 +25,7 @@ describe('toJson', () => { }); }); - it('creates an encoded output with passphrase', () => { + it('creates an encoded output with passphrase', (): void => { const json = keyring.alice.toJson('testing'); expect(json.encoded).toHaveLength(316); diff --git a/packages/keyring/src/pair/toJson.ts b/packages/keyring/src/pair/toJson.ts index 1ecc76114..d3c474618 100644 --- a/packages/keyring/src/pair/toJson.ts +++ b/packages/keyring/src/pair/toJson.ts @@ -9,7 +9,7 @@ import { u8aToHex } from '@polkadot/util'; import { encodeAddress } from '@polkadot/util-crypto'; type PairStateJson = KeyringPair$Meta & { - publicKey: Uint8Array + publicKey: Uint8Array; }; export default function toJson (type: KeypairType, { publicKey, meta }: PairStateJson, encoded: Uint8Array, isEncrypted: boolean): KeyringPair$Json { diff --git a/packages/keyring/src/pair/types.ts b/packages/keyring/src/pair/types.ts index 23dee4b6f..71329d266 100644 --- a/packages/keyring/src/pair/types.ts +++ b/packages/keyring/src/pair/types.ts @@ -2,8 +2,8 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -export type PairInfo = { - publicKey: Uint8Array, - secretKey?: Uint8Array, - seed?: Uint8Array | null -}; +export interface PairInfo { + publicKey: Uint8Array; + secretKey?: Uint8Array; + seed?: Uint8Array | null; +} diff --git a/packages/keyring/src/pairs.ts b/packages/keyring/src/pairs.ts index 4d92f25e6..06051725d 100644 --- a/packages/keyring/src/pairs.ts +++ b/packages/keyring/src/pairs.ts @@ -7,34 +7,34 @@ import { KeyringPairs, KeyringPair } from './types'; import { assert, isHex, isU8a, u8aToHex, u8aToU8a } from '@polkadot/util'; import { decodeAddress } from '@polkadot/util-crypto'; -type KeyringPairMap = { +interface KeyringPairMap { // @ts-ignore we use coercion :( - [index: Uint8Array]: KeyringPair -}; + [index: Uint8Array]: KeyringPair; +} export default class Pairs implements KeyringPairs { private _map: KeyringPairMap; - constructor () { + public constructor () { this._map = {}; } - add (pair: KeyringPair): KeyringPair { + public add (pair: KeyringPair): KeyringPair { // @ts-ignore we use coercion :( this._map[pair.publicKey] = pair; return pair; } - all (): Array { + public all (): KeyringPair[] { return Object.values(this._map); } - get (address: string | Uint8Array): KeyringPair { + public get (address: string | Uint8Array): KeyringPair { // @ts-ignore we use coercion :( const pair = this._map[decodeAddress(address)]; - assert(pair, () => { + assert(pair, (): string => { const formatted: string = isU8a(address) || isHex(address) ? u8aToHex(u8aToU8a(address)) : address; @@ -45,7 +45,7 @@ export default class Pairs implements KeyringPairs { return pair; } - remove (address: string | Uint8Array): void { + public remove (address: string | Uint8Array): void { // @ts-ignore we use coercion :( delete this._map[decodeAddress(address)]; } diff --git a/packages/keyring/src/suri.spec.ts b/packages/keyring/src/suri.spec.ts index beba15394..7126a7af5 100644 --- a/packages/keyring/src/suri.spec.ts +++ b/packages/keyring/src/suri.spec.ts @@ -59,15 +59,15 @@ const TESTS = [ } ]; -describe('keyring.addFromUri', () => { +describe('keyring.addFromUri', (): void => { const keyring = new Keyring({ type: 'sr25519' }); - beforeEach(async () => { + beforeEach(async (): Promise => { await cryptoWaitReady(); }); - TESTS.forEach(({ pk, ss, uri }) => { - it(`creates ${uri}`, () => { + TESTS.forEach(({ pk, ss, uri }): void => { + it(`creates ${uri}`, (): void => { const pair = keyring.addFromUri(uri); expect(u8aToHex(pair.publicKey)).toEqual(pk); diff --git a/packages/keyring/src/testing.ts b/packages/keyring/src/testing.ts index efcf8335c..83ee4d782 100644 --- a/packages/keyring/src/testing.ts +++ b/packages/keyring/src/testing.ts @@ -80,7 +80,7 @@ const PAIRS: PairDef[] = [ export default function testKeyring (options: KeyringOptions = {}, isDerived: boolean = true): KeyringInstance { const keyring = new Keyring(options); - PAIRS.forEach(({ name, publicKey, secretKey, seed, type }) => { + PAIRS.forEach(({ name, publicKey, secretKey, seed, type }): void => { const meta = { isTesting: true, name: name || seed.replace('//', '_').toLowerCase() @@ -92,7 +92,7 @@ export default function testKeyring (options: KeyringOptions = {}, isDerived: bo createPair(type || 'sr25519', { publicKey, secretKey }, meta) ); - pair.lock = () => { + pair.lock = (): void => { // we don't have lock/unlock functionality here }; }); diff --git a/packages/keyring/src/testingPairs.spec.ts b/packages/keyring/src/testingPairs.spec.ts index 12adef465..6cfb631da 100644 --- a/packages/keyring/src/testingPairs.spec.ts +++ b/packages/keyring/src/testingPairs.spec.ts @@ -6,24 +6,24 @@ import { cryptoWaitReady } from '@polkadot/util-crypto'; import testingPairs from './testingPairs'; -describe('testingPairs', () => { - beforeEach(async () => { +describe('testingPairs', (): void => { + beforeEach(async (): Promise => { await cryptoWaitReady(); }); - it('creates without failing', () => { + it('creates without failing', (): void => { expect( Object.keys(testingPairs()) ).toHaveLength(2 + 1 + 7); }); - it('has the correct address for Alice (non-HDKD)', () => { + it('has the correct address for Alice (non-HDKD)', (): void => { expect( testingPairs({ type: 'ed25519' }, false).alice.address ).toEqual('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua'); }); - it('has the correct address for Alice (HDKD)', () => { + it('has the correct address for Alice (HDKD)', (): void => { expect( testingPairs({ type: 'ed25519' }).alice.address ).toEqual('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY'); diff --git a/packages/keyring/src/testingPairs.ts b/packages/keyring/src/testingPairs.ts index 4193613cf..03d6acdee 100644 --- a/packages/keyring/src/testingPairs.ts +++ b/packages/keyring/src/testingPairs.ts @@ -7,19 +7,20 @@ import { KeyringPair, KeyringOptions } from './types'; import createKeyring from './testing'; import nobody from './pair/nobody'; -type TestKeyringMap = { - [index: string]: KeyringPair -}; +export interface TestKeyringMap { + [index: string]: KeyringPair; +} export default function testKeyringPairs (options?: KeyringOptions, isDerived: boolean = true): TestKeyringMap { const keyring = createKeyring(options, isDerived); const pairs = keyring.getPairs(); + const map: TestKeyringMap = { nobody: nobody() }; - return pairs.reduce((result, pair) => { + return pairs.reduce((result, pair): TestKeyringMap => { const { name } = pair.meta; result[name as string] = pair; return result; - }, { 'nobody': nobody() } as TestKeyringMap); + }, map); } diff --git a/packages/keyring/src/types.ts b/packages/keyring/src/types.ts index 171eb6c9d..ba193de93 100644 --- a/packages/keyring/src/types.ts +++ b/packages/keyring/src/types.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/class-name-casing */ // Copyright 2017-2019 @polkadot/keyring authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. @@ -5,29 +6,30 @@ import { Prefix } from '@polkadot/util-crypto/address/types'; import { KeypairType } from '@polkadot/util-crypto/types'; -export type KeyringOptions = { - addressPrefix?: Prefix, - type?: KeypairType -}; +export interface KeyringOptions { + addressPrefix?: Prefix; + type?: KeypairType; +} -export type KeyringPair$Meta = { - [index: string]: any -}; +export interface KeyringPair$Meta { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [index: string]: any; +} export type KeyringPair$JsonVersion = '0' | '1' | '2'; -export type KeyringPair$JsonEncoding = { - content: ['pkcs8', KeypairType], - type: 'xsalsa20-poly1305' | 'none', - version: KeyringPair$JsonVersion -}; +export interface KeyringPair$JsonEncoding { + content: ['pkcs8', KeypairType]; + type: 'xsalsa20-poly1305' | 'none'; + version: KeyringPair$JsonVersion; +} -export type KeyringPair$Json = { - address: string, - encoded: string, - encoding: KeyringPair$JsonEncoding, - meta: KeyringPair$Meta -}; +export interface KeyringPair$Json { + address: string; + encoded: string; + encoding: KeyringPair$JsonEncoding; + meta: KeyringPair$Meta; +} export interface KeyringPair { readonly type: KeypairType; @@ -47,14 +49,14 @@ export interface KeyringPair { export interface KeyringPairs { add: (pair: KeyringPair) => KeyringPair; - all: () => Array; + all: () => KeyringPair[]; get: (address: string | Uint8Array) => KeyringPair; remove: (address: string | Uint8Array) => void; } export interface KeyringInstance { - readonly pairs: Array; - readonly publicKeys: Array; + readonly pairs: KeyringPair[]; + readonly publicKeys: Uint8Array[]; readonly type: KeypairType; decodeAddress (encoded: string | Uint8Array, ignoreChecksum?: boolean): Uint8Array; @@ -69,8 +71,8 @@ export interface KeyringInstance { addFromUri (suri: string, meta?: KeyringPair$Meta, type?: KeypairType): KeyringPair; createFromUri (suri: string, meta?: KeyringPair$Meta, type?: KeypairType): KeyringPair; getPair (address: string | Uint8Array): KeyringPair; - getPairs (): Array; - getPublicKeys (): Array; + getPairs (): KeyringPair[]; + getPublicKeys (): Uint8Array[]; removePair (address: string | Uint8Array): void; toJson (address: string | Uint8Array, passphrase?: string): KeyringPair$Json; } diff --git a/packages/trie-codec/src/NodeHeader.ts b/packages/trie-codec/src/NodeHeader.ts index b4f3d4342..f7eba30d7 100644 --- a/packages/trie-codec/src/NodeHeader.ts +++ b/packages/trie-codec/src/NodeHeader.ts @@ -18,9 +18,10 @@ export type LeafHeader = NibbleHeader; export default class NodeHeader { private _nodeType: NodeType; + private _value: Null | BranchHeader | ExtensionHeader | LeafHeader; - constructor (input?: null | Uint8Array | Array) { + public constructor (input?: null | Uint8Array | (null | Uint8Array)[]) { const [nodeType, value] = Array.isArray(input) ? NodeHeader.decodeNodeHeaderArray(input) : NodeHeader.decodeNodeHeaderU8a(input); @@ -29,7 +30,7 @@ export default class NodeHeader { this._value = value; } - private static decodeNodeHeaderArray (input: Array): [NodeType, Null | BranchHeader | ExtensionHeader | LeafHeader] { + private static decodeNodeHeaderArray (input: (null | Uint8Array)[]): [NodeType, Null | BranchHeader | ExtensionHeader | LeafHeader] { if (input.length === 0) { return [NODE_TYPE_NULL, null]; } else if (input.length === 2) { @@ -70,7 +71,7 @@ export default class NodeHeader { throw new Error('Unreachable'); } - get encodedLength (): number { + public get encodedLength (): number { switch (this.nodeType) { case NODE_TYPE_NULL: case NODE_TYPE_BRANCH: @@ -91,15 +92,15 @@ export default class NodeHeader { } } - get nodeType (): number { + public get nodeType (): number { return this._nodeType; } - get value (): Null | BranchHeader | ExtensionHeader | LeafHeader { + public get value (): Null | BranchHeader | ExtensionHeader | LeafHeader { return this._value; } - toU8a (): Uint8Array { + public toU8a (): Uint8Array { switch (this.nodeType) { case NODE_TYPE_NULL: return new Uint8Array([EMPTY_TRIE]); diff --git a/packages/trie-codec/src/constants.ts b/packages/trie-codec/src/constants.ts index bb3af5a83..5dd2de04c 100644 --- a/packages/trie-codec/src/constants.ts +++ b/packages/trie-codec/src/constants.ts @@ -29,7 +29,7 @@ export const EXTENSION_NODE_BIG = 253; export const BRANCH_NODE_NO_VALUE = 254; export const BRANCH_NODE_WITH_VALUE = 255; export const LEAF_NODE_THRESHOLD = LEAF_NODE_BIG - LEAF_NODE_OFFSET; -export const EXTENSION_NODE_THRESHOLD = EXTENSION_NODE_BIG - EXTENSION_NODE_OFFSET; // 125 +export const EXTENSION_NODE_THRESHOLD = EXTENSION_NODE_BIG - EXTENSION_NODE_OFFSET; // 125 export const LEAF_NODE_SMALL_MAX = LEAF_NODE_BIG - 1; export const EXTENSION_NODE_SMALL_MAX = EXTENSION_NODE_BIG - 1; diff --git a/packages/trie-codec/src/decode.spec.ts b/packages/trie-codec/src/decode.spec.ts index 22d93dbc3..fb9b33659 100644 --- a/packages/trie-codec/src/decode.spec.ts +++ b/packages/trie-codec/src/decode.spec.ts @@ -6,8 +6,8 @@ import { hexToU8a } from '@polkadot/util'; import decode from './decode'; -describe('decode', () => { - it('decodes a leaf', () => { +describe('decode', (): void => { + it('decodes a leaf', (): void => { expect( decode(Uint8Array.from([ 0x05, 0x48, 0x19, 0x04, 0xfe @@ -18,7 +18,7 @@ describe('decode', () => { ]); }); - it('decodes a branch', () => { + it('decodes a branch', (): void => { expect( decode(Uint8Array.from([ 0xfe, 0x00, 0x0c, 0x48, 0x81, 0x0a, 0x3c, 0xff, 0x00, 0x0c, 0x04, 0xa0, 0x10, 0x02, 0x0a, 0x04, @@ -38,7 +38,7 @@ describe('decode', () => { ]); }); - it('decodes a complex branch', () => { + it('decodes a complex branch', (): void => { expect( decode(hexToU8a( '0xfe8c00682007b3872d47181b4a2dc15f0da43e702620e80300000000000080170d322ac49d8708f151346c68d9e58452d83a9d3b710e1ead35eb3269ab235368200935e46f94f24b82716c0142e2271de9200087000000000000' diff --git a/packages/trie-codec/src/decode.ts b/packages/trie-codec/src/decode.ts index 7c7fdeecd..88005e2d6 100644 --- a/packages/trie-codec/src/decode.ts +++ b/packages/trie-codec/src/decode.ts @@ -9,7 +9,7 @@ import { BITMAP, NODE_TYPE_BRANCH, NODE_TYPE_EXT, NODE_TYPE_LEAF, NODE_TYPE_NULL import { addNibblesTerminator, encodeNibbles } from './nibbles'; import { toNibbles } from './util'; -const EMPTY_BRANCH: Array = [ +const EMPTY_BRANCH: (Uint8Array | null)[] = [ null, null, null, null, null, null, null, null, null, null, null, null, @@ -19,7 +19,7 @@ const l = logger('trie/codec'); l.noop(); -function _decodeBranch (header: NodeHeader, input: Uint8Array): Array { +function _decodeBranch (header: NodeHeader, input: Uint8Array): (null | Uint8Array | [Uint8Array, Uint8Array])[] { let offset = header.encodedLength; const branch = header.value as BranchHeader; const bitmap = input[offset] + (input[offset + 1] << 8); @@ -36,7 +36,7 @@ function _decodeBranch (header: NodeHeader, input: Uint8Array): Array { + return EMPTY_BRANCH.concat(value).map((value, index): null | Uint8Array | [Uint8Array, Uint8Array] => { let result: null | Uint8Array | [Uint8Array, Uint8Array] = value; if ((index < 16) && (bitmap & BITMAP[index])) { @@ -44,6 +44,7 @@ function _decodeBranch (header: NodeHeader, input: Uint8Array): Array { +function _decodeKv (header: NodeHeader, input: Uint8Array): (null | Uint8Array | [Uint8Array, Uint8Array])[] { const offset = header.encodedLength; const nibbleCount = (header.value as NibbleHeader); const nibbleLength = (nibbleCount + 1) >> 1; @@ -72,7 +73,7 @@ function _decodeKv (header: NodeHeader, input: Uint8Array): Array { +export default function decode (input: null | Uint8Array): Uint8Array | null | (null | Uint8Array | [Uint8Array, Uint8Array])[] { const header = new NodeHeader(input); const nodeType = header.nodeType; diff --git a/packages/trie-codec/src/encode.spec.ts b/packages/trie-codec/src/encode.spec.ts index 42aa2b6b5..463a20ed8 100644 --- a/packages/trie-codec/src/encode.spec.ts +++ b/packages/trie-codec/src/encode.spec.ts @@ -6,8 +6,8 @@ import { hexToU8a } from '@polkadot/util'; import encode from './encode'; -describe('encoding', () => { - it('encode a small sub-tree', () => { +describe('encoding', (): void => { + it('encode a small sub-tree', (): void => { expect( encode([ null, @@ -21,22 +21,23 @@ describe('encoding', () => { null, null, [ - Uint8Array.from([ 58 ]), - Uint8Array.from([ 170 ]) + Uint8Array.from([58]), + Uint8Array.from([170]) ], null, null, null, null, null, - Uint8Array.from([ 160 ]) + Uint8Array.from([160]) + // eslint-disable-next-line @typescript-eslint/no-explicit-any ] as any) ).toEqual(Uint8Array.from([ 255, 0, 4, 4, 160, 16, 2, 10, 4, 170 ])); }); - it('encodes a sub-tree', () => { + it('encodes a sub-tree', (): void => { expect( encode([ null, @@ -50,25 +51,26 @@ describe('encoding', () => { null, null, [ - Uint8Array.from([ 58 ]), - Uint8Array.from([ 170 ]) + Uint8Array.from([58]), + Uint8Array.from([170]) ], [ - Uint8Array.from([ 59 ]), - Uint8Array.from([ 171 ]) + Uint8Array.from([59]), + Uint8Array.from([171]) ], null, null, null, null, - Uint8Array.from([ 160 ]) + Uint8Array.from([160]) + // eslint-disable-next-line @typescript-eslint/no-explicit-any ] as any) ).toEqual(Uint8Array.from([ 255, 0, 12, 4, 160, 16, 2, 10, 4, 170, 16, 2, 11, 4, 171 ])); }); - it('encodes a complex tree (with hash)', () => { + it('encodes a complex tree (with hash)', (): void => { expect( encode([ null, @@ -96,6 +98,7 @@ describe('encoding', () => { null, null, null + // eslint-disable-next-line @typescript-eslint/no-explicit-any ] as any) ).toEqual(hexToU8a( '0xfe8c00682007b3872d47181b4a2dc15f0da43e702620e80300000000000080170d322ac49d8708f151346c68d9e58452d83a9d3b710e1ead35eb3269ab235368200935e46f94f24b82716c0142e2271de9200087000000000000' diff --git a/packages/trie-codec/src/encode.ts b/packages/trie-codec/src/encode.ts index f324371c5..1a92b18e8 100644 --- a/packages/trie-codec/src/encode.ts +++ b/packages/trie-codec/src/encode.ts @@ -29,18 +29,19 @@ function encodeKey (input: null | Uint8Array): Uint8Array { : fromNibbles(nibbles); } -function encodeValue (input: null | Uint8Array | Array): Uint8Array { +function encodeValue (input: null | Uint8Array | (null | Uint8Array)[]): Uint8Array { if (!input) { return EMPTY; } // l.debug(() => ['encodeValue', { input, encoded }]); + // eslint-disable-next-line @typescript-eslint/no-use-before-define return compactAddLength(encode(input)); } -function _encodeBranch (header: NodeHeader, input: Array): Uint8Array { - let values: Array = []; +function _encodeBranch (header: NodeHeader, input: (null | Uint8Array)[]): Uint8Array { + const values: Uint8Array[] = []; let bitmap = 0; for (let index = 0; index < BRANCH_VALUE_INDEX; index++) { @@ -61,7 +62,7 @@ function _encodeBranch (header: NodeHeader, input: Array): Ui ); } -function _encodeKv (header: NodeHeader, input: Array): Uint8Array { +function _encodeKv (header: NodeHeader, input: (null | Uint8Array)[]): Uint8Array { const [path, value] = input; return u8aConcat( @@ -71,7 +72,7 @@ function _encodeKv (header: NodeHeader, input: Array): Uint8A ); } -export default function encode (input?: null | Uint8Array | Array): Uint8Array { +export default function encode (input?: null | Uint8Array | (null | Uint8Array)[]): Uint8Array { if (isU8a(input)) { return input; } diff --git a/packages/trie-codec/src/nibbles.ts b/packages/trie-codec/src/nibbles.ts index 0a390ede2..d9ff234a7 100644 --- a/packages/trie-codec/src/nibbles.ts +++ b/packages/trie-codec/src/nibbles.ts @@ -12,18 +12,6 @@ const NIBBLE_TERMINATOR = 16; const NEEDS_TERMINATOR = [HP_FLAG_2, HP_FLAG_2 + 1]; const IS_ODD_LENGTH = [HP_FLAG_0 + 1, HP_FLAG_2 + 1]; -export function extractKey (key: null | Uint8Array): Uint8Array { - return removeNibblesTerminator( - decodeNibbles(key) - ); -} - -export function extractNodeKey ([key]: Array): Uint8Array { - return removeNibblesTerminator( - decodeNibbles(key) - ); -} - export function isNibblesTerminated (nibbles: Uint8Array): boolean { return nibbles[nibbles.length - 1] === NIBBLE_TERMINATOR; } @@ -77,3 +65,15 @@ export function encodeNibbles (nibbles: Uint8Array): Uint8Array { return fromNibbles(prefixed); } + +export function extractKey (key: null | Uint8Array): Uint8Array { + return removeNibblesTerminator( + decodeNibbles(key) + ); +} + +export function extractNodeKey ([key]: (null | Uint8Array)[]): Uint8Array { + return removeNibblesTerminator( + decodeNibbles(key) + ); +} diff --git a/packages/trie-codec/src/stream/createBranch.ts b/packages/trie-codec/src/stream/createBranch.ts index 7d637a47e..a1985a97a 100644 --- a/packages/trie-codec/src/stream/createBranch.ts +++ b/packages/trie-codec/src/stream/createBranch.ts @@ -7,7 +7,7 @@ import { u8aConcat } from '@polkadot/util'; import { BITMAP, BRANCH_NODE_NO_VALUE, BRANCH_NODE_WITH_VALUE } from '../constants'; import createValue from './createValue'; -export default function createBranch (value: Uint8Array | null, hasChildren: Array): Uint8Array { +export default function createBranch (value: Uint8Array | null, hasChildren: boolean[]): Uint8Array { let bitmap = 0; for (let i = 0; i < hasChildren.length; i++) { diff --git a/packages/trie-codec/src/stream/endBranch.ts b/packages/trie-codec/src/stream/endBranch.ts index 5a938aba2..35ed8d97c 100644 --- a/packages/trie-codec/src/stream/endBranch.ts +++ b/packages/trie-codec/src/stream/endBranch.ts @@ -4,6 +4,7 @@ const NO_VALUE = new Uint8Array(); +// eslint-disable-next-line @typescript-eslint/no-unused-vars export default function encBranch (value: Uint8Array | null): Uint8Array { return NO_VALUE; } diff --git a/packages/trie-codec/src/types.ts b/packages/trie-codec/src/types.ts index 7c2db4112..dbd8df365 100644 --- a/packages/trie-codec/src/types.ts +++ b/packages/trie-codec/src/types.ts @@ -2,9 +2,9 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -export type Codec = { - decode: (input: null | Uint8Array) => Uint8Array | null | Array>, - encode: (input?: null | Uint8Array | Array) => Uint8Array - hashing: (input: Uint8Array) => Uint8Array, - type: string -}; +export interface Codec { + decode: (input: null | Uint8Array) => Uint8Array | null | (null | Uint8Array | (null | Uint8Array)[])[]; + encode: (input?: null | Uint8Array | (null | Uint8Array)[]) => Uint8Array; + hashing: (input: Uint8Array) => Uint8Array; + type: string; +} diff --git a/packages/trie-codec/src/util/fromNibbles.spec.ts b/packages/trie-codec/src/util/fromNibbles.spec.ts index d8c1ac916..ff2c21639 100644 --- a/packages/trie-codec/src/util/fromNibbles.spec.ts +++ b/packages/trie-codec/src/util/fromNibbles.spec.ts @@ -6,8 +6,8 @@ import stringToU8a from '@polkadot/util/string/toU8a'; import fromNibbles from './fromNibbles'; -describe('fromNibbles', () => { - it('converts a single', () => { +describe('fromNibbles', (): void => { + it('converts a single', (): void => { expect( fromNibbles( new Uint8Array([4, 1]) @@ -17,7 +17,7 @@ describe('fromNibbles', () => { ); }); - it('converts an number of values', () => { + it('converts an number of values', (): void => { expect( fromNibbles( new Uint8Array([3, 1, 2, 3, 4, 5]) @@ -27,7 +27,7 @@ describe('fromNibbles', () => { ); }); - it('converts an number of values (array)', () => { + it('converts an number of values (array)', (): void => { expect( fromNibbles(Uint8Array.from([ 3, 1, 2, 3, 4, 5, 7, 8 diff --git a/packages/trie-codec/src/util/fuseNibbles.ts b/packages/trie-codec/src/util/fuseNibbles.ts index 216d28728..6f444b2ca 100644 --- a/packages/trie-codec/src/util/fuseNibbles.ts +++ b/packages/trie-codec/src/util/fuseNibbles.ts @@ -15,7 +15,7 @@ export default function fuseNibbles (nibbles: Uint8Array, isLeaf: boolean): Uint const [firstByteSmall, bigThreshold] = isLeaf ? [LEAF_NODE_OFFSET, LEAF_NODE_BIG - LEAF_NODE_OFFSET] : [EXTENSION_NODE_OFFSET, EXTENSION_NODE_BIG - EXTENSION_NODE_OFFSET]; - const result: Array = [ + const result: Uint8Array[] = [ Uint8Array.from([firstByteSmall + Math.min(nibbles.length, bigThreshold)]) ]; const oddFlag = nibbles.length % 2; diff --git a/packages/trie-codec/src/util/toNibbles.spec.ts b/packages/trie-codec/src/util/toNibbles.spec.ts index 39b0ab740..566a2ba36 100644 --- a/packages/trie-codec/src/util/toNibbles.spec.ts +++ b/packages/trie-codec/src/util/toNibbles.spec.ts @@ -6,8 +6,8 @@ import stringToU8a from '@polkadot/util/string/toU8a'; import toNibbles from './toNibbles'; -describe('toNibbles', () => { - it('converts an array', () => { +describe('toNibbles', (): void => { + it('converts an array', (): void => { expect( toNibbles(Uint8Array.from([ 0x31, 0x23, 0x45 @@ -17,7 +17,7 @@ describe('toNibbles', () => { ); }); - it('converts a single', () => { + it('converts a single', (): void => { expect( toNibbles( stringToU8a('A') diff --git a/packages/trie-db/src/Checkpoint.ts b/packages/trie-db/src/Checkpoint.ts index e09f8f4b3..5e9f54e2f 100644 --- a/packages/trie-db/src/Checkpoint.ts +++ b/packages/trie-db/src/Checkpoint.ts @@ -4,9 +4,10 @@ export default class Checkpoint { protected txRoot: Uint8Array; + protected rootHash: Uint8Array; - constructor (rootHash: Uint8Array) { + public constructor (rootHash: Uint8Array) { this.rootHash = rootHash; this.txRoot = rootHash; } diff --git a/packages/trie-db/src/Impl.ts b/packages/trie-db/src/Impl.ts index 35b700459..5cbeaf071 100644 --- a/packages/trie-db/src/Impl.ts +++ b/packages/trie-db/src/Impl.ts @@ -8,7 +8,7 @@ import { EncodedPath, TrieDb, Node, NodeBranch, NodeEncodedOrEmpty, NodeKv, Node import substrateCodec from '@polkadot/trie-codec'; import { decodeNibbles, encodeNibbles, extractNodeKey } from '@polkadot/trie-codec/nibbles'; -import { isNull , u8aConcat } from '@polkadot/util'; +import { isNull, u8aConcat } from '@polkadot/util'; import { isBranchNode, isEmptyNode, isExtensionNode, isKvNode, isLeafNode } from './util/is'; import { keyEquals, keyStartsWith, computeExtensionKey, computeLeafKey, consumeCommonPrefix } from './util/key'; @@ -16,7 +16,12 @@ import { getNodeType, decodeNode, encodeNode } from './util/node'; import Checkpoint from './Checkpoint'; import constants, { Constants } from './constants'; -const BLANK_BRANCH: Array = [ +interface Normalized { + index: number; + value: EncodedPath; +} + +const BLANK_BRANCH: EncodedPath[] = [ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ]; @@ -31,11 +36,13 @@ const BLANK_BRANCH: Array = [ * @example See [Polkadot-JS Common Trie-DB Examples](https://polkadot.js.org/api/common/examples/trie-db/) */ export default class Impl extends Checkpoint { - readonly db: TxDb; + public readonly db: TxDb; + protected codec: Codec; + protected constants: Constants; - constructor (db: TxDb, rootHash?: Uint8Array, codec: Codec = substrateCodec) { + public constructor (db: TxDb, rootHash?: Uint8Array, codec: Codec = substrateCodec) { const _constants = constants(codec); super(rootHash || _constants.EMPTY_HASH); @@ -52,10 +59,10 @@ export default class Impl extends Checkpoint { return null; } - return [root, encoded, node.filter((u8a) => u8a && u8a.length === 32) as Array]; + return [root, encoded, node.filter((u8a): boolean => !!u8a && u8a.length === 32) as Uint8Array[]]; } - protected _entries (root: Uint8Array, entries: Array = []): Array { + protected _entries (root: Uint8Array, entries: TrieEntry[] = []): TrieEntry[] { // l.debug(() => ['entries', { root }]); const entry = this._entry(root); @@ -64,7 +71,9 @@ export default class Impl extends Checkpoint { } entries.push(entry); - entry[2].forEach((u8a) => this._entries(u8a, entries)); + entry[2].forEach((u8a): void => { + this._entries(u8a, entries); + }); return entries; } @@ -82,7 +91,7 @@ export default class Impl extends Checkpoint { fn && fn({ keys: ++keys, percent }); - node.forEach((u8a) => { + node.forEach((u8a): void => { if (u8a && u8a.length === 32) { keys = this._snapshot(dest, fn, u8a, keys, percent, depth + 1); } @@ -255,6 +264,7 @@ export default class Impl extends Checkpoint { const encoded = encodeNode(this.codec, node); return (encoded.length < 32) + // eslint-disable-next-line @typescript-eslint/no-explicit-any ? [node as any, null] : [this.codec.hashing(encoded), encoded]; } @@ -263,8 +273,8 @@ export default class Impl extends Checkpoint { // l.debug(() => ['_normaliseBranchNode', { node }]); const mapped = node - .map((value, index) => ({ index, value })) - .filter(({ value }) => !!value && value.length !== 0); + .map((value, index): Normalized => ({ index, value })) + .filter(({ value }): boolean => !!value && value.length !== 0); if (mapped.length >= 2) { return node; diff --git a/packages/trie-db/src/constants.ts b/packages/trie-db/src/constants.ts index 2bdbc59bd..ee0da161a 100644 --- a/packages/trie-db/src/constants.ts +++ b/packages/trie-db/src/constants.ts @@ -6,12 +6,12 @@ import { Codec } from '@polkadot/trie-codec/types'; import { trieRoot } from '@polkadot/trie-hash'; -export type Constants = { - EMPTY_NODE: Uint8Array, - EMPTY_HASH: Uint8Array, - EMPTY_HASH_STR: string, - EMPTY_U8A: Uint8Array -}; +export interface Constants { + EMPTY_NODE: Uint8Array; + EMPTY_HASH: Uint8Array; + EMPTY_HASH_STR: string; + EMPTY_U8A: Uint8Array; +} export default function (codec: Codec): Constants { const EMPTY_NODE = new Uint8Array(); diff --git a/packages/trie-db/src/ethereum.spec.ts b/packages/trie-db/src/ethereum.spec.ts index 075b6a7e4..30d6105fa 100644 --- a/packages/trie-db/src/ethereum.spec.ts +++ b/packages/trie-db/src/ethereum.spec.ts @@ -13,17 +13,17 @@ import getTests from '../../util-rlp/test/getTests'; const trieanyorder = getTests('TrieTests/trieanyorder.json'); // FIXME These are not working, the trie-hash implementation is now substrate-specific -describe.skip('official tests', () => { +describe.skip('official tests', (): void => { let trie: Trie; - beforeEach(() => { + beforeEach((): void => { trie = new Trie(undefined, undefined, ethereumCodec); }); // FIXME (maybe) These all have empty/null values, we don't allow those atm as a key nor value - // describe.skip('ordered tests', () => { + // describe.skip('ordered tests', (): void => { // trietest.forEach(({ name, input, root }) => { - // it(name, () => { + // it(name, (): void => { // input.map((input) => // trie.put(toU8a(input[0]), toU8a(input[1])) // ); @@ -37,14 +37,16 @@ describe.skip('official tests', () => { // }); // }); - describe('unordered tests', () => { - trieanyorder.forEach(({ name, input, root }) => { + describe('unordered tests', (): void => { + trieanyorder.forEach(({ name, input, root }): void => { const keys = Object.keys(input); - it(name, () => { - keys.map((key) => - trie.put(toU8a(key), toU8a(input[key])) - ); + it(name, (): void => { + keys.forEach((key: string): void => { + // @ts-ignore + // eslint-disable-next-line @typescript-eslint/no-explicit-any + trie.put(toU8a(key), toU8a(input[key as any])); + }); expect( u8aToHex(trie.getRoot()) diff --git a/packages/trie-db/src/genesis.spec.ts b/packages/trie-db/src/genesis.spec.ts index 602e4ea99..8b1053899 100644 --- a/packages/trie-db/src/genesis.spec.ts +++ b/packages/trie-db/src/genesis.spec.ts @@ -7,12 +7,12 @@ import { hexToU8a, u8aToHex } from '@polkadot/util'; import Trie from '.'; -describe('genesis roots', () => { - [alexander, driedDanta].forEach(({ genesis: { raw }, genesisRoot, name }) => { - it(`has the correct root for ${name}`, () => { +describe('genesis roots', (): void => { + [alexander, driedDanta].forEach(({ genesis: { raw }, genesisRoot, name }): void => { + it(`has the correct root for ${name}`, (): void => { const trie = new Trie(); - Object.keys(raw).forEach((key) => { + Object.keys(raw).forEach((key): void => { trie.put(hexToU8a(key), hexToU8a(raw[key])); }); diff --git a/packages/trie-db/src/index.spec.ts b/packages/trie-db/src/index.spec.ts index b49c59d4a..b13072b2b 100644 --- a/packages/trie-db/src/index.spec.ts +++ b/packages/trie-db/src/index.spec.ts @@ -10,14 +10,14 @@ import ethereumCodec from './ethereumCodec'; import Trie from '.'; // FIXME These are not working, the trie-hash implementation is now substrate-specific -describe.skip('Ethereum', () => { - const createTrie = () => +describe.skip('Ethereum', (): void => { + const createTrie = (): Trie => new Trie(undefined, undefined, ethereumCodec); - describe('simple save and retrieve', () => { + describe('simple save and retrieve', (): void => { const trie = createTrie(); - it('starts with a valid root', () => { + it('starts with a valid root', (): void => { expect( trie.getRoot() ).toEqual( @@ -27,7 +27,7 @@ describe.skip('Ethereum', () => { ); }); - it('save a value', () => { + it('save a value', (): void => { trie.put(toU8a('test'), toU8a('one')); expect( @@ -39,13 +39,13 @@ describe.skip('Ethereum', () => { ); }); - it('should get a value', () => { + it('should get a value', (): void => { expect( trie.get(toU8a('test')) ).toEqual(toU8a('one')); }); - it('should update a value', () => { + it('should update a value', (): void => { trie.put(toU8a('test'), toU8a('two')); expect( @@ -60,7 +60,7 @@ describe.skip('Ethereum', () => { ); }); - it('should delete a value', () => { + it('should delete a value', (): void => { trie.del(toU8a('test')); expect( @@ -75,7 +75,7 @@ describe.skip('Ethereum', () => { ); }); - it('should recreate a value', () => { + it('should recreate a value', (): void => { trie.put(toU8a('test'), toU8a('one')); expect( @@ -87,13 +87,13 @@ describe.skip('Ethereum', () => { ); }); - it('should get updated a value', () => { + it('should get updated a value', (): void => { expect( trie.get(toU8a('test')) ).toEqual(toU8a('one')); }); - it('should create a branch here', () => { + it('should create a branch here', (): void => { trie.put(toU8a('doge'), toU8a('coin')); expect( @@ -103,13 +103,13 @@ describe.skip('Ethereum', () => { ); }); - it('should get a value that is in a branch', () => { + it('should get a value that is in a branch', (): void => { expect( trie.get(toU8a('doge')) ).toEqual(toU8a('coin')); }); - it('should delete from a branch', () => { + it('should delete from a branch', (): void => { trie.del(toU8a('doge')); expect( @@ -125,12 +125,12 @@ describe.skip('Ethereum', () => { }); }); - describe('storing longer values', () => { + describe('storing longer values', (): void => { const trie = createTrie(); const longString = 'this will be a really really really long value'; const longStringRoot = '0xb173e2db29e79c78963cff5196f8a983fbe0171388972106b114ef7f5c24dfa3'; - it('should store a longer string', () => { + it('should store a longer string', (): void => { trie.put(toU8a('done'), toU8a(longString)); expect( @@ -140,29 +140,29 @@ describe.skip('Ethereum', () => { ])); }); - it('should retrieve a longer value (first pass)', () => { + it('should retrieve a longer value (first pass)', (): void => { expect( trie.get(toU8a('done')) ).toEqual(toU8a(longString)); }); - it('should store subsequent values', () => { + it('should store subsequent values', (): void => { trie.put(toU8a('doge'), toU8a('coin')); expect(longStringRoot).toEqual(u8aToHex(trie.getRoot())); }); - it('should retrieve a longer value (second pass)', () => { + it('should retrieve a longer value (second pass)', (): void => { expect( trie.get(toU8a('done')) ).toEqual(toU8a(longString)); }); - it('should retrieve subsequent values', () => { + it('should retrieve subsequent values', (): void => { expect(trie.get(toU8a('doge'))).toEqual(toU8a('coin')); }); - it('should when being modified delete the old value', () => { + it('should when being modified delete the old value', (): void => { trie.put(toU8a('done'), toU8a('test')); expect( @@ -173,14 +173,14 @@ describe.skip('Ethereum', () => { }); }); - describe('testing Extentions and branches', () => { + describe('testing Extentions and branches', (): void => { const trie = createTrie(); - it('should store a value', () => { + it('should store a value', (): void => { trie.put(toU8a('doge'), toU8a('coin')); }); - it('should create extention to store this value', () => { + it('should create extention to store this value', (): void => { trie.put(toU8a('do'), toU8a('verb')); expect( @@ -188,7 +188,7 @@ describe.skip('Ethereum', () => { ).toEqual(trie.getRoot()); }); - it('should store this value under the extention ', () => { + it('should store this value under the extention ', (): void => { trie.put(toU8a('done'), toU8a('finished')); expect( @@ -197,10 +197,10 @@ describe.skip('Ethereum', () => { }); }); - describe.skip('testing Extentions and branches - reverse', () => { + describe.skip('testing Extentions and branches - reverse', (): void => { const trie = createTrie(); - it('should create extention to store this value', () => { + it('should create extention to store this value', (): void => { trie.put(toU8a('do'), toU8a('verb')); const value = trie.get(toU8a('do')); @@ -208,11 +208,11 @@ describe.skip('Ethereum', () => { expect(value).toEqual(toU8a('verb')); }); - it('should store a value', () => { + it('should store a value', (): void => { trie.put(toU8a('doge'), toU8a('coin')); }); - it('should store this value under the extention ', () => { + it('should store this value under the extention ', (): void => { trie.put(toU8a('done'), toU8a('finished')); expect( @@ -221,10 +221,10 @@ describe.skip('Ethereum', () => { }); }); - describe('testing deletions cases', () => { + describe('testing deletions cases', (): void => { const trie = createTrie(); - it('should delete from a branch->branch-branch', () => { + it('should delete from a branch->branch-branch', (): void => { trie.put(new Uint8Array([11, 11, 11]), toU8a('first')); trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch')); trie.put(new Uint8Array([12, 34, 44]), toU8a('create the last branch')); @@ -235,7 +235,7 @@ describe.skip('Ethereum', () => { expect(null).toEqual(value); }); - it('should delete from a branch->branch-extension', () => { + it('should delete from a branch->branch-extension', (): void => { trie.put(new Uint8Array([11, 11, 11]), toU8a('first')); trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch')); trie.put(new Uint8Array([12, 33, 33]), toU8a('create the middle branch')); @@ -247,7 +247,7 @@ describe.skip('Ethereum', () => { expect(null).toEqual(value); }); - it('should delete from a extension->branch-extension', () => { + it('should delete from a extension->branch-extension', (): void => { trie.put(new Uint8Array([11, 11, 11]), toU8a('first')); trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch')); trie.put(new Uint8Array([12, 33, 33]), toU8a('create the middle branch')); @@ -259,7 +259,7 @@ describe.skip('Ethereum', () => { expect(null).toEqual(value); }); - it('should delete from a extension->branch-branch', () => { + it('should delete from a extension->branch-branch', (): void => { trie.put(new Uint8Array([11, 11, 11]), toU8a('first')); trie.put(new Uint8Array([12, 22, 22]), toU8a('create the first branch')); trie.put(new Uint8Array([12, 33, 33]), toU8a('create the middle branch')); diff --git a/packages/trie-db/src/index.ts b/packages/trie-db/src/index.ts index 59ffac25a..65978e6cc 100644 --- a/packages/trie-db/src/index.ts +++ b/packages/trie-db/src/index.ts @@ -25,13 +25,13 @@ const l = logger('trie/db'); * @example See [Polkadot-JS Common Trie-DB Examples](https://polkadot.js.org/api/common/examples/trie-db/) */ export default class Trie extends Impl implements TrieDb { - constructor (db: TxDb = new MemoryDb(), rootHash?: Uint8Array, codec?: Codec) { + public constructor (db: TxDb = new MemoryDb(), rootHash?: Uint8Array, codec?: Codec) { super(db, rootHash, codec); - l.debug(() => `Created with ${this.codec.type} codec, root ${u8aToHex(this.rootHash, 64)}`); + l.debug((): string => `Created with ${this.codec.type} codec, root ${u8aToHex(this.rootHash, 64)}`); } - transaction (fn: () => T): T { + public transaction (fn: () => T): T { try { this.createCheckpoint(); @@ -51,35 +51,35 @@ export default class Trie extends Impl implements TrieDb { } } - open (): void { + public open (): void { this.db.open(); } - close (): void { + public close (): void { this.db.close(); } - empty (): void { + public empty (): void { this.db.empty(); } - drop (): void { + public drop (): void { this.db.drop(); } - maintain (fn: ProgressCb): void { + public maintain (fn: ProgressCb): void { this.db.maintain(fn); } - rename (base: string, file: string): void { + public rename (base: string, file: string): void { this.db.rename(base, file); } - size (): number { + public size (): number { return this.db.size(); } - del (key: Uint8Array) { + public del (key: Uint8Array): void { // l.debug(() => ['del', { key }]); this._setRootNode( @@ -90,7 +90,7 @@ export default class Trie extends Impl implements TrieDb { ); } - get (key: Uint8Array): Uint8Array | null { + public get (key: Uint8Array): Uint8Array | null { // l.debug(() => ['get', { key }]); return this._get( @@ -99,7 +99,7 @@ export default class Trie extends Impl implements TrieDb { ); } - put (key: Uint8Array, value: Uint8Array): void { + public put (key: Uint8Array, value: Uint8Array): void { // l.debug(() => ['put', { key, value }]); this._setRootNode( @@ -111,7 +111,7 @@ export default class Trie extends Impl implements TrieDb { ); } - getRoot (): Uint8Array { + public getRoot (): Uint8Array { const rootNode = this.getNode(); if (isNull(rootNode)) { @@ -121,33 +121,33 @@ export default class Trie extends Impl implements TrieDb { return this.rootHash; } - setRoot (rootHash: Uint8Array): void { + public setRoot (rootHash: Uint8Array): void { this.rootHash = rootHash; // return this._setRootNode(rootNode); } - getEntry (hash?: Uint8Array): TrieEntry | null { + public getEntry (hash?: Uint8Array): TrieEntry | null { return this._entry(hash || this.rootHash); } - getNode (hash?: Uint8Array): Node { + public getNode (hash?: Uint8Array): Node { return this._getNode(hash || this.rootHash); } - entries (): Array { - l.debug(() => 'retrieving trie entries'); + public entries (): TrieEntry[] { + l.debug((): string => 'retrieving trie entries'); const start = Date.now(); const entries = this._entries(this.rootHash); const elapsed = (Date.now() - start) / 1000; - l.debug(() => `entries retrieved in ${elapsed.toFixed(2)}s, ${(entries.length / 1000).toFixed(2)}k keys`); + l.debug((): string => `entries retrieved in ${elapsed.toFixed(2)}s, ${(entries.length / 1000).toFixed(2)}k keys`); return entries; } - snapshot (dest: TrieDb, fn?: ProgressCb): number { - l.debug(() => 'creating current state snapshot'); + public snapshot (dest: TrieDb, fn?: ProgressCb): number { + l.debug((): string => 'creating current state snapshot'); const start = Date.now(); const keys = this._snapshot(dest, fn, this.rootHash, 0, 0, 0); @@ -155,7 +155,7 @@ export default class Trie extends Impl implements TrieDb { dest.setRoot(this.rootHash); - l.debug(() => `snapshot created in ${elapsed.toFixed(2)}s, ${(keys / 1000).toFixed(2)}k keys`); + l.debug((): string => `snapshot created in ${elapsed.toFixed(2)}s, ${(keys / 1000).toFixed(2)}k keys`); fn && fn({ isCompleted: true, diff --git a/packages/trie-db/src/snapshot.spec.ts b/packages/trie-db/src/snapshot.spec.ts index d20256442..645cf9512 100644 --- a/packages/trie-db/src/snapshot.spec.ts +++ b/packages/trie-db/src/snapshot.spec.ts @@ -7,7 +7,7 @@ import { u8aToHex, u8aToU8a as toU8a } from '@polkadot/util'; import Trie from '.'; -describe('snapshots', () => { +describe('snapshots', (): void => { const values = [ { k: toU8a('test'), v: toU8a('one') }, { k: toU8a('one'), v: toU8a('testing') }, @@ -21,12 +21,12 @@ describe('snapshots', () => { let trie: Trie; let back: Trie; - beforeEach(() => { + beforeEach((): void => { trie = new Trie(); back = new Trie(); }); - it('creates a snapshot of the (relevant) trie data', () => { + it('creates a snapshot of the (relevant) trie data', (): void => { const root = trieRoot([values[0]]); trie.put(values[0].k, values[0].v); @@ -36,41 +36,45 @@ describe('snapshots', () => { trie.put(toU8a('doge'), toU8a('coin')); trie.del(toU8a('doge')); - trie.snapshot(back, () => void 0); + trie.snapshot(back, (): undefined => void 0); expect(u8aToHex(back.getRoot())).toEqual(u8aToHex(root)); expect(back.get(values[0].k)).toEqual(values[0].v); }); - it('creates a snapshot of the (relevant) data', () => { + it('creates a snapshot of the (relevant) data', (): void => { const root = trieRoot(values); - values.forEach(({ k, v }) => trie.put(k, v)); - trie.snapshot(back, () => void 0); + values.forEach(({ k, v }): void => { + trie.put(k, v); + }); + trie.snapshot(back, (): undefined => void 0); expect(u8aToHex(back.getRoot())).toEqual(u8aToHex(root)); - values.forEach(({ k, v }) => - expect(back.get(k)).toEqual(v) - ); + values.forEach(({ k, v }): void => { + expect(back.get(k)).toEqual(v); + }); }); - it('retrieves entries, which can re-create', () => { + it('retrieves entries, which can re-create', (): void => { const root = trieRoot(values); - values.forEach(({ k, v }) => trie.put(k, v)); + values.forEach(({ k, v }): void => { + trie.put(k, v); + }); const entries = trie.entries(); - entries.forEach(([key, encoded, children]) => { + entries.forEach(([key, encoded, children]): void => { back.db.put(key, encoded); - console.log(u8aToHex(key), ...children.map((child) => `\n\t${u8aToHex(child)}`)); + console.log(u8aToHex(key), ...children.map((child): string => `\n\t${u8aToHex(child)}`)); }); back.setRoot(root); - values.forEach(({ k, v }) => - expect(back.get(k)).toEqual(v) - ); + values.forEach(({ k, v }): void => { + expect(back.get(k)).toEqual(v); + }); }); }); diff --git a/packages/trie-db/src/subtrate.spec.ts b/packages/trie-db/src/subtrate.spec.ts index 1d1f39af8..a669ce9cb 100644 --- a/packages/trie-db/src/subtrate.spec.ts +++ b/packages/trie-db/src/subtrate.spec.ts @@ -7,34 +7,36 @@ import { u8aToHex } from '@polkadot/util'; import testdata, { TestData } from '../../trie-hash/test/data'; import Trie from '.'; -describe('substrate tests', () => { +describe('substrate tests', (): void => { let trie: Trie; - const checkRoot = ({ root }: TestData) => + const checkRoot = ({ root }: TestData): void => { expect( u8aToHex(trie.getRoot()) ).toEqual( u8aToHex(root) ); + }; - const putValues = ({ input }: TestData) => - input.forEach(({ k, v }) => - trie.put(k, v) - ); + const putValues = ({ input }: TestData): void => { + input.forEach(({ k, v }): void => { + trie.put(k, v); + }); + }; - beforeEach(() => { + beforeEach((): void => { trie = new Trie(); }); - Object.values(testdata).forEach((test) => { - it(`hashes ${test.desc}`, () => { + Object.values(testdata).forEach((test): void => { + it(`hashes ${test.desc}`, (): void => { putValues(test); checkRoot(test); }); }); // When we have a specific test failing and we want to debug it - // it('does extensionBranch', () => { + // it('does extensionBranch', (): void => { // putValues(testdata.extensionBranch); // checkRoot(testdata.extensionBranch); // }); diff --git a/packages/trie-db/src/types.ts b/packages/trie-db/src/types.ts index f9e9b523b..42e7fdb26 100644 --- a/packages/trie-db/src/types.ts +++ b/packages/trie-db/src/types.ts @@ -34,7 +34,7 @@ export type NodeNotEmpty = NodeKv | NodeBranch; export type Node = NodeEmpty | NodeNotEmpty; // root, encoded, childroots -export type TrieEntry = [Uint8Array, Uint8Array, Array]; +export type TrieEntry = [Uint8Array, Uint8Array, Uint8Array[]]; export interface TrieDb extends TxDb { readonly db: TxDb; @@ -45,6 +45,6 @@ export interface TrieDb extends TxDb { getEntry (root?: Uint8Array): TrieEntry | null; getNode (hash?: Uint8Array): Node; - entries (): Array; + entries (): TrieEntry[]; snapshot (dest: TrieDb, fn?: ProgressCb): number; } diff --git a/packages/trie-db/src/util/key.ts b/packages/trie-db/src/util/key.ts index ff30a79a2..034fae538 100644 --- a/packages/trie-db/src/util/key.ts +++ b/packages/trie-db/src/util/key.ts @@ -7,16 +7,6 @@ import { isNull } from '@polkadot/util'; import { EncodedPath } from '../types'; -export function keyEquals (key: Uint8Array | null, test: Uint8Array | null): boolean { - if (isNull(key) && isNull(test)) { - return true; - } else if (isNull(key) || isNull(test) || (key.length !== test.length)) { - return false; - } - - return keyStartsWith(key, test); -} - export function keyStartsWith (key: Uint8Array | null, partial: Uint8Array | null): boolean { if (isNull(key) && isNull(partial)) { return true; @@ -33,6 +23,16 @@ export function keyStartsWith (key: Uint8Array | null, partial: Uint8Array | nul return true; } +export function keyEquals (key: Uint8Array | null, test: Uint8Array | null): boolean { + if (isNull(key) && isNull(test)) { + return true; + } else if (isNull(key) || isNull(test) || (key.length !== test.length)) { + return false; + } + + return keyStartsWith(key, test); +} + export function computeExtensionKey (nibbles: Uint8Array): EncodedPath { return encodeNibbles(nibbles); } diff --git a/packages/trie-db/src/util/node.ts b/packages/trie-db/src/util/node.ts index 1a81dbbd6..e2172aa87 100644 --- a/packages/trie-db/src/util/node.ts +++ b/packages/trie-db/src/util/node.ts @@ -36,7 +36,7 @@ export function decodeNode (codec: Codec, encoded: Uint8Array | Node): Node { const node = codec.decode(encoded) as NodeNotEmpty; - return node.map((value) => + return node.map((value): Uint8Array | null => value && value.length ? value : null diff --git a/packages/trie-hash/src/buildTrie.ts b/packages/trie-hash/src/buildTrie.ts index 2cc14d392..18cbdbe78 100644 --- a/packages/trie-hash/src/buildTrie.ts +++ b/packages/trie-hash/src/buildTrie.ts @@ -12,7 +12,8 @@ import { DEFAULT_CODEC, DEFAULT_STREAM } from './defaults'; const EMPTY = new Uint8Array(); // FIXME This is problematic, the stream implementation is Substrate-only as is the branch here -function _buildTrie (input: Array<[Uint8Array, Uint8Array]>, cursor: number, codec: Codec, stream: any): Uint8Array { +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _buildTrie (input: [Uint8Array, Uint8Array][], cursor: number, codec: Codec, stream: any): Uint8Array { if (input.length === 0) { return stream.createEmpty(); } @@ -23,7 +24,7 @@ function _buildTrie (input: Array<[Uint8Array, Uint8Array]>, cursor: number, cod return stream.createLeaf(firstKey.subarray(cursor), firstValue); } - const sharedNibbleCount = input.reduce((min, [key], index) => { + const sharedNibbleCount = input.reduce((min, [key], index): number => { return index === 0 ? key.length : Math.min(min, sharedPrefixLength(key, firstKey)); @@ -33,6 +34,7 @@ function _buildTrie (input: Array<[Uint8Array, Uint8Array]>, cursor: number, cod return u8aConcat( stream.createExtension(firstKey.subarray(cursor, sharedNibbleCount)), stream.createSubstream( + // eslint-disable-next-line @typescript-eslint/no-use-before-define buildTrie(input, sharedNibbleCount, codec, stream) ) ); @@ -47,8 +49,8 @@ function _buildTrie (input: Array<[Uint8Array, Uint8Array]>, cursor: number, cod for (let index = 0; index < 16; index++) { sharedNibbleCounts[index] = input - .filter((_, index) => index >= begin) - .filter(([key]) => key[cursor] === index) + .filter((_, index): boolean => index >= begin) + .filter(([key]): boolean => key[cursor] === index) .length; begin += sharedNibbleCounts[index]; @@ -57,12 +59,13 @@ function _buildTrie (input: Array<[Uint8Array, Uint8Array]>, cursor: number, cod begin = start; return u8aConcat( - stream.createBranch(value, sharedNibbleCounts.map((value) => value > 0)), - ...sharedNibbleCounts.map((count) => { + stream.createBranch(value, sharedNibbleCounts.map((value): boolean => value > 0)), + ...sharedNibbleCounts.map((count): Uint8Array => { let result = EMPTY; if (count > 0) { result = stream.createSubstream( + // eslint-disable-next-line @typescript-eslint/no-use-before-define buildTrie(input.slice(begin, begin + count), cursor + 1, codec, stream) ); begin += count; @@ -74,7 +77,8 @@ function _buildTrie (input: Array<[Uint8Array, Uint8Array]>, cursor: number, cod ); } -export default function buildTrie (input: Array<[Uint8Array, Uint8Array]>, cursor: number = 0, codec: Codec = DEFAULT_CODEC, stream: any = DEFAULT_STREAM): Uint8Array { +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export default function buildTrie (input: [Uint8Array, Uint8Array][], cursor: number = 0, codec: Codec = DEFAULT_CODEC, stream: any = DEFAULT_STREAM): Uint8Array { const trie = _buildTrie(input, cursor, codec, stream); return trie; diff --git a/packages/trie-hash/src/genesis.spec.ts b/packages/trie-hash/src/genesis.spec.ts index 6cd97b7f0..b8d715267 100644 --- a/packages/trie-hash/src/genesis.spec.ts +++ b/packages/trie-hash/src/genesis.spec.ts @@ -2,18 +2,20 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +import { TriePair } from './types'; + import { alexander, driedDanta } from '@polkadot/chainspec'; import { hexToU8a, u8aToHex } from '@polkadot/util'; import trieRoot from './trieRoot'; -describe('genesis roots', () => { - [alexander, driedDanta].forEach(({ genesis: { raw }, genesisRoot, name }) => { - it(`has the correct root for ${name}`, () => { +describe('genesis roots', (): void => { + [alexander, driedDanta].forEach(({ genesis: { raw }, genesisRoot, name }): void => { + it(`has the correct root for ${name}`, (): void => { expect( u8aToHex( trieRoot( - Object.keys(raw).map((key) => ({ + Object.keys(raw).map((key): TriePair => ({ k: hexToU8a(key), v: hexToU8a(raw[key]) })) diff --git a/packages/trie-hash/src/trieRoot.spec.ts b/packages/trie-hash/src/trieRoot.spec.ts index 5de8ed992..98dadf39e 100644 --- a/packages/trie-hash/src/trieRoot.spec.ts +++ b/packages/trie-hash/src/trieRoot.spec.ts @@ -7,9 +7,9 @@ import { u8aToHex } from '@polkadot/util'; import trieRoot from './trieRoot'; import testdata from '../test/data'; -describe('trieRoot', () => { - Object.values(testdata).forEach(({ desc, input, root }) => { - it(`hashes ${desc}`, () => { +describe('trieRoot', (): void => { + Object.values(testdata).forEach(({ desc, input, root }): void => { + it(`hashes ${desc}`, (): void => { expect( u8aToHex(trieRoot(input)) ).toEqual( diff --git a/packages/trie-hash/src/trieRoot.ts b/packages/trie-hash/src/trieRoot.ts index 926194b79..9df444030 100644 --- a/packages/trie-hash/src/trieRoot.ts +++ b/packages/trie-hash/src/trieRoot.ts @@ -26,7 +26,7 @@ import unhashedTrie from './unhashedTrie'; * }]); // => 0xd23786fb4a010da3ce639d66d5e904a11dbc02746d1ce25029e53290cabf28ab * ``` */ -export default function trieRoot (input: Array, codec: Codec = DEFAULT_CODEC): Uint8Array { +export default function trieRoot (input: TriePair[], codec: Codec = DEFAULT_CODEC): Uint8Array { return codec.hashing( unhashedTrie(input, codec) ); diff --git a/packages/trie-hash/src/trieRootOrdered.spec.ts b/packages/trie-hash/src/trieRootOrdered.spec.ts index 35abec5b9..493049005 100644 --- a/packages/trie-hash/src/trieRootOrdered.spec.ts +++ b/packages/trie-hash/src/trieRootOrdered.spec.ts @@ -6,8 +6,8 @@ import { stringToU8a, u8aToHex } from '@polkadot/util'; import { trieRootOrdered } from '.'; -describe('trieRootOrdered', () => { - it('encodes values', () => { +describe('trieRootOrdered', (): void => { + it('encodes values', (): void => { expect( u8aToHex( trieRootOrdered([ diff --git a/packages/trie-hash/src/trieRootOrdered.ts b/packages/trie-hash/src/trieRootOrdered.ts index 284d1ac13..2175c81b7 100644 --- a/packages/trie-hash/src/trieRootOrdered.ts +++ b/packages/trie-hash/src/trieRootOrdered.ts @@ -3,6 +3,7 @@ // of the Apache-2.0 license. See the LICENSE file for details. import { Codec } from '@polkadot/trie-codec/types'; +import { TriePair } from './types'; import { compactToU8a } from '@polkadot/util'; @@ -27,9 +28,9 @@ import trieRoot from './trieRoot'; * ]); // => 0xe766d5d51b89dc39d981b41bda63248d7abce4f0225eefd023792a540bcffee3 * ``` */ -export default function trieRootOrdered (input: Array, codec: Codec = DEFAULT_CODEC): Uint8Array { +export default function trieRootOrdered (input: Uint8Array[], codec: Codec = DEFAULT_CODEC): Uint8Array { return trieRoot( - input.map((v, index) => ({ + input.map((v, index): TriePair => ({ k: compactToU8a(index), v })), diff --git a/packages/trie-hash/src/types.ts b/packages/trie-hash/src/types.ts index d52b24772..4499fc18a 100644 --- a/packages/trie-hash/src/types.ts +++ b/packages/trie-hash/src/types.ts @@ -2,7 +2,7 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -export type TriePair = { - k: Uint8Array, - v: Uint8Array -}; +export interface TriePair { + k: Uint8Array; + v: Uint8Array; +} diff --git a/packages/trie-hash/src/unhashedTrie.spec.ts b/packages/trie-hash/src/unhashedTrie.spec.ts index bce39b6c1..56835fd23 100644 --- a/packages/trie-hash/src/unhashedTrie.spec.ts +++ b/packages/trie-hash/src/unhashedTrie.spec.ts @@ -7,9 +7,9 @@ import { u8aToHex } from '@polkadot/util'; import unhashedTrie from './unhashedTrie'; import testdata from '../test/data'; -describe('unhashedTrie', () => { - Object.values(testdata).forEach(({ desc, input, output }) => { - it(`encodes ${desc}`, () => { +describe('unhashedTrie', (): void => { + Object.values(testdata).forEach(({ desc, input, output }): void => { + it(`encodes ${desc}`, (): void => { expect( u8aToHex(unhashedTrie(input)) ).toEqual( diff --git a/packages/trie-hash/src/unhashedTrie.ts b/packages/trie-hash/src/unhashedTrie.ts index 0c663b90b..592052f6e 100644 --- a/packages/trie-hash/src/unhashedTrie.ts +++ b/packages/trie-hash/src/unhashedTrie.ts @@ -11,17 +11,18 @@ import { u8aToHex } from '@polkadot/util'; import buildTrie from './buildTrie'; import { DEFAULT_CODEC } from './defaults'; -export default function unhashedTrie (input: Array, codec: Codec = DEFAULT_CODEC): Uint8Array { - const map = input.reduce((result, pair) => { - result[u8aToHex(pair.k)] = pair; +export default function unhashedTrie (input: TriePair[], codec: Codec = DEFAULT_CODEC): Uint8Array { + const map: { [index: string]: TriePair } = {}; + + input.forEach((pair): void => { + map[u8aToHex(pair.k)] = pair; + }); - return result; - }, ({} as { [index: string]: TriePair })); const pairs = Object .keys(map) .sort() - .map((key) => map[key]) - .map(({ k, v }) => ([toNibbles(k), v] as [Uint8Array, Uint8Array])); + .map((key): TriePair => map[key]) + .map(({ k, v }): [Uint8Array, Uint8Array] => ([toNibbles(k), v] as [Uint8Array, Uint8Array])); return buildTrie(pairs, 0, codec); } diff --git a/packages/trie-hash/test/data.ts b/packages/trie-hash/test/data.ts index c5ddfe94b..1ee567557 100644 --- a/packages/trie-hash/test/data.ts +++ b/packages/trie-hash/test/data.ts @@ -6,12 +6,12 @@ import { TriePair } from '../src/types'; import { hexToU8a, stringToU8a } from '@polkadot/util'; -export type TestData = { - desc: string, - input: Array, - output: Uint8Array, - root: Uint8Array -}; +export interface TestData { + desc: string; + input: TriePair[]; + output: Uint8Array; + root: Uint8Array; +} const data: { [index: string]: TestData } = { simpleBranch: { @@ -130,10 +130,10 @@ const data: { [index: string]: TestData } = { { k: Uint8Array.from([0xaa]), v: Uint8Array.from([0xbb]) } ], output: Uint8Array.from([ - 0x03, // leaf (0x01) with (+) key of 2 nibbles (0x02) - 0xaa, // key data + 0x03, // leaf (0x01) with (+) key of 2 nibbles (0x02) + 0xaa, // key data 1 << 2, // length of value in bytes as Compact - 0xbb // value data + 0xbb // value data ]), root: hexToU8a('0xe778a32590ed4f3f39608b77af87fb59163a89bb9702f477375e1a574736d6f0') }, @@ -154,21 +154,21 @@ const data: { [index: string]: TestData } = { { k: Uint8Array.from([0x13, 0x14]), v: Uint8Array.from([0xff]) } ], output: Uint8Array.from([ - 0xfe, // branch, no value - 0x12, // slots 1 & 4 are taken from 0-7 - 0x00, // no slots from 8-15 + 0xfe, // branch, no value + 0x12, // slots 1 & 4 are taken from 0-7 + 0x00, // no slots from 8-15 0x05 << 2, // first slot: LEAF, 5 bytes long. - 0x04, // leaf with 3 nibbles - 0x03, // first nibble - 0x14, // second & third nibble + 0x04, // leaf with 3 nibbles + 0x03, // first nibble + 0x14, // second & third nibble 0x01 << 2, // 1 byte data - 0xff, // value data + 0xff, // value data 0x05 << 2, // second slot: LEAF, 5 bytes long. - 0x04, // leaf with 3 nibbles - 0x08, // first nibble - 0x19, // second & third nibble + 0x04, // leaf with 3 nibbles + 0x08, // first nibble + 0x19, // second & third nibble 0x01 << 2, // 1 byte data - 0xfe // data + 0xfe // data ]), root: hexToU8a('0x72813a09bf563fdb6af1d8326329950499fc33c30f3534893381517dc54640b2') }, diff --git a/packages/util-crypto/src/address/decode.spec.ts b/packages/util-crypto/src/address/decode.spec.ts index f34ec1d91..3c340fb6f 100644 --- a/packages/util-crypto/src/address/decode.spec.ts +++ b/packages/util-crypto/src/address/decode.spec.ts @@ -3,17 +3,17 @@ // of the Apache-2.0 license. See the LICENSE file for details. // @flow -import testingPairs from '../../../keyring/src/testingPairs'; +import testingPairs, { TestKeyringMap } from '../../../keyring/src/testingPairs'; import decode from './decode'; -describe('decode', () => { - let keyring: any; +describe('decode', (): void => { + let keyring: TestKeyringMap; - beforeAll(async () => { + beforeAll(async (): Promise => { keyring = testingPairs({ type: 'sr25519' }); }); - it('decodes an address', () => { + it('decodes an address', (): void => { expect( decode('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY') ).toEqual( @@ -21,7 +21,7 @@ describe('decode', () => { ); }); - it('converts a publicKey (u8a) as-is', () => { + it('converts a publicKey (u8a) as-is', (): void => { expect( decode(new Uint8Array([1, 2, 3])) ).toEqual( @@ -29,7 +29,7 @@ describe('decode', () => { ); }); - it('converts a publicKey (hex) as-is', () => { + it('converts a publicKey (hex) as-is', (): void => { expect( decode('0x01020304') ).toEqual( @@ -37,54 +37,54 @@ describe('decode', () => { ); }); - it('decodes a short address', () => { + it('decodes a short address', (): void => { expect( decode('F7NZ') ).toEqual(new Uint8Array([1])); }); - it('decodes a 1-byte accountId (with prefix)', () => { + it('decodes a 1-byte accountId (with prefix)', (): void => { expect( decode('PqtB', false, 68) ).toEqual(new Uint8Array([1])); }); - it('decodes a 2-byte accountId', () => { + it('decodes a 2-byte accountId', (): void => { expect( decode('2jpAFn', false, 68) ).toEqual(new Uint8Array([0, 1])); }); - it('encodes a 4-byte address', () => { + it('encodes a 4-byte address', (): void => { expect( decode('as7QnGMf', false, 68) ).toEqual(new Uint8Array([1, 2, 3, 4])); }); - it('decodes a 8-byte address', () => { + it('decodes a 8-byte address', (): void => { expect( decode('4q7qY5RBG7Z4wv', false, 68) ).toEqual(new Uint8Array([42, 44, 10, 0, 0, 0, 0, 0])); }); - it.skip('allows invalid prefix (in list)', () => { + it.skip('allows invalid prefix (in list)', (): void => { expect( - () => decode('6GfvWUvHvU8otbZ7sFhXH4eYeMcKdUkL61P3nFy52efEPVUx') + (): Uint8Array => decode('6GfvWUvHvU8otbZ7sFhXH4eYeMcKdUkL61P3nFy52efEPVUx') ).toThrow(/address prefix/); }); - it('fails when length is invalid', () => { + it('fails when length is invalid', (): void => { expect( - () => decode('y9EMHt34JJo4rWLSaxoLGdYXvjgSXEd4zHUnQgfNzwES8b') + (): Uint8Array => decode('y9EMHt34JJo4rWLSaxoLGdYXvjgSXEd4zHUnQgfNzwES8b') ).toThrow(/address length/); }); - it('fails when the checksum does not match', () => { + it('fails when the checksum does not match', (): void => { expect( - () => decode('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMa9cj') + (): Uint8Array => decode('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMa9cj') ).toThrow(/address checksum/); expect( - () => decode('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDwU') + (): Uint8Array => decode('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaDwU') ).toThrow(/address checksum/); }); }); diff --git a/packages/util-crypto/src/address/decode.ts b/packages/util-crypto/src/address/decode.ts index 7c1a2c911..dd32ac6c1 100644 --- a/packages/util-crypto/src/address/decode.ts +++ b/packages/util-crypto/src/address/decode.ts @@ -12,13 +12,14 @@ import { assert, bufferToU8a, isHex, isU8a, u8aToU8a } from '@polkadot/util'; import defaults from './defaults'; import sshash from './sshash'; +// eslint-disable-next-line @typescript-eslint/no-unused-vars export default function decode (encoded: string | Uint8Array, ignoreChecksum?: boolean, prefix: Prefix = defaults.prefix): Uint8Array { if (isU8a(encoded) || isHex(encoded)) { return u8aToU8a(encoded); } const decoded = bufferToU8a(bs58.decode(encoded)); - const error = (message: string) => + const error = (message: string): string => `Decoding ${encoded}: ${message}`; // assert(defaults.allowedPrefix.includes(decoded[0] as Prefix), error('Invalid decoded address prefix')); diff --git a/packages/util-crypto/src/address/defaults.ts b/packages/util-crypto/src/address/defaults.ts index 559388f3d..bd7d8a1db 100644 --- a/packages/util-crypto/src/address/defaults.ts +++ b/packages/util-crypto/src/address/defaults.ts @@ -8,7 +8,7 @@ const defaults = { allowedDecodedLengths: [1, 2, 4, 8, 32], // publicKey has prefix + 2 checksum bytes, short only prefix + 1 checksum byte allowedEncodedLengths: [3, 4, 6, 10, 35], - allowedPrefix: [0, 1, 3, 42, 43, 68, 69] as Array, + allowedPrefix: [0, 1, 3, 42, 43, 68, 69] as Prefix[], prefix: 42 as Prefix }; diff --git a/packages/util-crypto/src/address/encode.spec.ts b/packages/util-crypto/src/address/encode.spec.ts index c971220b1..2b3e0b608 100644 --- a/packages/util-crypto/src/address/encode.spec.ts +++ b/packages/util-crypto/src/address/encode.spec.ts @@ -8,22 +8,22 @@ import encode from './encode'; const keyring = testingPairs({ type: 'ed25519' }, false); -describe('encode', () => { - it('encodes an address to a valid value', () => { +describe('encode', (): void => { + it('encodes an address to a valid value', (): void => { expect( keyring.alice.address ).toEqual('5GoKvZWG5ZPYL1WUovuHW3zJBWBP5eT8CbqjdRY4Q6iMaQua'); }); - it('fails when non-valid publicKey provided', () => { + it('fails when non-valid publicKey provided', (): void => { expect( - () => encode( + (): string => encode( keyring.alice.publicKey.slice(0, 30) ) ).toThrow(/Expected a valid key/); }); - it('encodes a 1-byte address', () => { + it('encodes a 1-byte address', (): void => { expect( encode( new Uint8Array([1]) @@ -31,7 +31,7 @@ describe('encode', () => { ).toEqual('F7NZ'); }); - it('encodes a 1-byte address (with prefix)', () => { + it('encodes a 1-byte address (with prefix)', (): void => { expect( encode( new Uint8Array([1]), 68 @@ -39,7 +39,7 @@ describe('encode', () => { ).toEqual('PqtB'); }); - it('encodes a 2-byte address', () => { + it('encodes a 2-byte address', (): void => { expect( encode( new Uint8Array([0, 1]), 68 @@ -47,7 +47,7 @@ describe('encode', () => { ).toEqual('2jpAFn'); }); - it('encodes a 4-byte address', () => { + it('encodes a 4-byte address', (): void => { expect( encode( new Uint8Array([1, 2, 3, 4]), 68 @@ -55,7 +55,7 @@ describe('encode', () => { ).toEqual('as7QnGMf'); }); - it('enodes a 8-byte address', () => { + it('enodes a 8-byte address', (): void => { expect( encode( new Uint8Array([42, 44, 10, 0, 0, 0, 0, 0]), 68 diff --git a/packages/util-crypto/src/address/setPrefix.spec.ts b/packages/util-crypto/src/address/setPrefix.spec.ts index c75e1e825..469dd4c1e 100644 --- a/packages/util-crypto/src/address/setPrefix.spec.ts +++ b/packages/util-crypto/src/address/setPrefix.spec.ts @@ -5,12 +5,12 @@ import encode from './encode'; import setPrefix from './setPrefix'; -describe('setPrefix', () => { - beforeEach(() => { +describe('setPrefix', (): void => { + beforeEach((): void => { setPrefix(68); }); - it('sets and allows encoding using', () => { + it('sets and allows encoding using', (): void => { expect( encode( new Uint8Array([1]) diff --git a/packages/util-crypto/src/blake2/asHex.spec.ts b/packages/util-crypto/src/blake2/asHex.spec.ts index e25c0e6e3..7319bf21b 100644 --- a/packages/util-crypto/src/blake2/asHex.spec.ts +++ b/packages/util-crypto/src/blake2/asHex.spec.ts @@ -7,36 +7,36 @@ import { waitReady } from '@polkadot/wasm-crypto'; import { blake2AsHex } from '.'; -describe('blake2AsHex', () => { - beforeEach(async () => { +describe('blake2AsHex', (): void => { + beforeEach(async (): Promise => { await waitReady(); }); - it('returns a 64-bit value (specified)', () => { + it('returns a 64-bit value (specified)', (): void => { expect( blake2AsHex('abc', 64) ).toEqual('0xd8bb14d833d59559'); }); - it('returns a 128-bit value (as specified)', () => { + it('returns a 128-bit value (as specified)', (): void => { expect( blake2AsHex('abc', 128) ).toEqual('0xcf4ab791c62b8d2b2109c90275287816'); }); - it('returns a 256-bit value (default)', () => { + it('returns a 256-bit value (default)', (): void => { expect( blake2AsHex('abc') ).toEqual('0xbddd813c634239723171ef3fee98579b94964e3bb1cb3e427262c8c068d52319'); }); - it('returns a 512-bit value (as specified)', () => { + it('returns a 512-bit value (as specified)', (): void => { expect( blake2AsHex('abc', 512) ).toEqual('0xba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923'); }); - it('matches with the Rust implementation', () => { + it('matches with the Rust implementation', (): void => { expect( blake2AsHex( hexToU8a('0x454545454545454545454545454545454545454545454545454545454545454501000000000000002481853da20b9f4322f34650fea5f240dcbfb266d02db94bfa0153c31f4a29dbdbf025dd4a69a6f4ee6e1577b251b655097e298b692cb34c18d3182cac3de0dc00000000'), 256 diff --git a/packages/util-crypto/src/blake2/asU8a.spec.ts b/packages/util-crypto/src/blake2/asU8a.spec.ts index 90f2ed0fb..3bc69a4b6 100644 --- a/packages/util-crypto/src/blake2/asU8a.spec.ts +++ b/packages/util-crypto/src/blake2/asU8a.spec.ts @@ -7,12 +7,12 @@ import { waitReady } from '@polkadot/wasm-crypto'; import { blake2AsU8a } from '.'; -describe('blake2AsU8a', () => { - beforeEach(async () => { +describe('blake2AsU8a', (): void => { + beforeEach(async (): Promise => { await waitReady(); }); - it('returns a 64-bit value by default', () => { + it('returns a 64-bit value by default', (): void => { expect( blake2AsU8a('abc') ).toEqual( @@ -20,7 +20,7 @@ describe('blake2AsU8a', () => { ); }); - it('returns a 128-bit value (as specified)', () => { + it('returns a 128-bit value (as specified)', (): void => { expect( blake2AsU8a('abc', 128) ).toEqual( @@ -28,7 +28,7 @@ describe('blake2AsU8a', () => { ); }); - it('returns a 256-bit value (as specified)', () => { + it('returns a 256-bit value (as specified)', (): void => { expect( blake2AsU8a('abc', 256) ).toEqual( @@ -36,7 +36,7 @@ describe('blake2AsU8a', () => { ); }); - it('returns a 512-bit value (as specified)', () => { + it('returns a 512-bit value (as specified)', (): void => { expect( blake2AsU8a('abc', 512) ).toEqual( diff --git a/packages/util-crypto/src/index.ts b/packages/util-crypto/src/index.ts index 9582557eb..d6aebf8f4 100644 --- a/packages/util-crypto/src/index.ts +++ b/packages/util-crypto/src/index.ts @@ -21,8 +21,8 @@ export * from './xxhash'; export function cryptoWaitReady (): Promise { return wasmCrypto .waitReady() - .then(() => true) - .catch((error) => { + .then((): boolean => true) + .catch((error): boolean => { console.error('Unable to initialize @polkadot/util-crypto', error); return false; @@ -30,6 +30,6 @@ export function cryptoWaitReady (): Promise { } // start init process immediately -cryptoWaitReady().catch(() => { +cryptoWaitReady().catch((): void => { // shouldn't happen, logged above }); diff --git a/packages/util-crypto/src/keccak/asHex.spec.ts b/packages/util-crypto/src/keccak/asHex.spec.ts index 04fb79d20..43fa82b90 100644 --- a/packages/util-crypto/src/keccak/asHex.spec.ts +++ b/packages/util-crypto/src/keccak/asHex.spec.ts @@ -9,12 +9,12 @@ import { keccakAsHex } from '.'; const value = 'test value'; const result = '2d07364b5c231c56ce63d49430e085ea3033c750688ba532b24029124c26ca5e'; -describe('keccakAsHex', () => { - beforeEach(async () => { +describe('keccakAsHex', (): void => { + beforeEach(async (): Promise => { await waitReady(); }); - it('returns a prefixed hex representation', () => { + it('returns a prefixed hex representation', (): void => { expect( keccakAsHex(value) ).toEqual(`0x${result}`); diff --git a/packages/util-crypto/src/keccak/asU8a.spec.ts b/packages/util-crypto/src/keccak/asU8a.spec.ts index 8c72ba713..a47a25f1d 100644 --- a/packages/util-crypto/src/keccak/asU8a.spec.ts +++ b/packages/util-crypto/src/keccak/asU8a.spec.ts @@ -7,8 +7,8 @@ import { waitReady } from '@polkadot/wasm-crypto'; import { keccakAsU8a } from '.'; -describe('keccakAsU8a', () => { - beforeEach(async () => { +describe('keccakAsU8a', (): void => { + beforeEach(async (): Promise => { await waitReady(); }); @@ -17,13 +17,13 @@ describe('keccakAsU8a', () => { '0x2d07364b5c231c56ce63d49430e085ea3033c750688ba532b24029124c26ca5e' ); - it('returns an hex representation (string)', () => { + it('returns an hex representation (string)', (): void => { expect( keccakAsU8a(input) ).toEqual(output); }); - it('returns an hex representation (Buffer)', () => { + it('returns an hex representation (Buffer)', (): void => { expect( keccakAsU8a( Buffer.from(input) @@ -31,7 +31,7 @@ describe('keccakAsU8a', () => { ).toEqual(output); }); - it('returns an hex representation (Uint8Array)', () => { + it('returns an hex representation (Uint8Array)', (): void => { expect( keccakAsU8a( stringToU8a(input) diff --git a/packages/util-crypto/src/key/DeriveJunction.ts b/packages/util-crypto/src/key/DeriveJunction.ts index 15941699b..94a3d948c 100644 --- a/packages/util-crypto/src/key/DeriveJunction.ts +++ b/packages/util-crypto/src/key/DeriveJunction.ts @@ -9,7 +9,7 @@ import blake2AsU8a from '../blake2/asU8a'; const RE_NUMBER = /^\d+$/; -const JUNCTION_ID_LEN: number = 32; +const JUNCTION_ID_LEN = 32; const BN_OPTIONS = { bitLength: 256, isLe: true @@ -17,9 +17,10 @@ const BN_OPTIONS = { export default class DeriveJunction { private _chainCode: Uint8Array = new Uint8Array(32); + private _isHard: boolean = false; - static from (value: string): DeriveJunction { + public static from (value: string): DeriveJunction { const [code, isHard] = value[0] === '/' ? [value.substr(1), true] : [value, false]; @@ -36,29 +37,29 @@ export default class DeriveJunction { : result; } - get chainCode (): Uint8Array { + public get chainCode (): Uint8Array { return this._chainCode; } - get isHard (): boolean { + public get isHard (): boolean { return this._isHard; } - get isSoft (): boolean { + public get isSoft (): boolean { return !this._isHard; } - hard (value: number | BN | string | Uint8Array): DeriveJunction { + public hard (value: number | BN | string | Uint8Array): DeriveJunction { return this.soft(value).harden(); } - harden (): DeriveJunction { + public harden (): DeriveJunction { this._isHard = true; return this; } - soft (value: number | BN | string | Uint8Array): DeriveJunction { + public soft (value: number | BN | string | Uint8Array): DeriveJunction { if (isNumber(value) || isBn(value)) { return this.soft(bnToHex(value, BN_OPTIONS)); } else if (isString(value)) { @@ -77,7 +78,7 @@ export default class DeriveJunction { return this; } - soften (): DeriveJunction { + public soften (): DeriveJunction { this._isHard = false; return this; diff --git a/packages/util-crypto/src/key/extractPath.spec.ts b/packages/util-crypto/src/key/extractPath.spec.ts index 3ab5c187f..d7f467d82 100644 --- a/packages/util-crypto/src/key/extractPath.spec.ts +++ b/packages/util-crypto/src/key/extractPath.spec.ts @@ -2,10 +2,10 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import keyExtractPath from './extractPath'; +import keyExtractPath, { ExtractResult } from './extractPath'; -describe('keyExtractPath', () => { - it('extracts properly from soft', () => { +describe('keyExtractPath', (): void => { + it('extracts properly from soft', (): void => { expect( keyExtractPath('/1') ).toEqual({ @@ -16,7 +16,7 @@ describe('keyExtractPath', () => { }); }); - it('extracts properly from hard', () => { + it('extracts properly from hard', (): void => { expect( keyExtractPath('//1') ).toEqual({ @@ -27,7 +27,7 @@ describe('keyExtractPath', () => { }); }); - it('extracts properly from hard/soft', () => { + it('extracts properly from hard/soft', (): void => { expect( keyExtractPath('//1/2') ).toEqual({ @@ -39,15 +39,15 @@ describe('keyExtractPath', () => { }); }); - it('does not extract from invalid paths', () => { + it('does not extract from invalid paths', (): void => { expect( - () => keyExtractPath('1/2') + (): ExtractResult => keyExtractPath('1/2') ).toThrow(/does not match input/); }); - it('does not extract from invalid paths', () => { + it('does not extract from invalid paths', (): void => { expect( - () => keyExtractPath('hello') + (): ExtractResult => keyExtractPath('hello') ).toThrow(/does not match input/); }); }); diff --git a/packages/util-crypto/src/key/extractPath.ts b/packages/util-crypto/src/key/extractPath.ts index 3d9b315e7..e16a6f6d1 100644 --- a/packages/util-crypto/src/key/extractPath.ts +++ b/packages/util-crypto/src/key/extractPath.ts @@ -5,25 +5,25 @@ import DeriveJunction from './DeriveJunction'; import { assert } from '@polkadot/util'; -const RE_JUNCTION = /\/(\/?)([^\/]+)/g; +const RE_JUNCTION = /\/(\/?)([^/]+)/g; -type ExtractResult = { - parts: null | Array, - path: Array -}; +export interface ExtractResult { + parts: null | string[]; + path: DeriveJunction[]; +} /** * @description Extract derivation juntions from the supplied path */ export default function keyExtractPath (derivePath: string): ExtractResult { const parts = derivePath.match(RE_JUNCTION); - const path: Array = []; + const path: DeriveJunction[] = []; let constructed = ''; if (parts) { constructed = parts.join(''); - parts.forEach((value: string) => { + parts.forEach((value: string): void => { path.push(DeriveJunction.from(value.substr(1))); }); } diff --git a/packages/util-crypto/src/key/extractSuri.spec.ts b/packages/util-crypto/src/key/extractSuri.spec.ts index 509f059dd..e50153301 100644 --- a/packages/util-crypto/src/key/extractSuri.spec.ts +++ b/packages/util-crypto/src/key/extractSuri.spec.ts @@ -2,16 +2,16 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import keyExtractSuri from './extractSuri'; +import keyExtractSuri, { ExtractResult } from './extractSuri'; -describe('keyExtractSuri', () => { - it('does not extract from invalid suri', () => { +describe('keyExtractSuri', (): void => { + it('does not extract from invalid suri', (): void => { expect( - () => keyExtractSuri('//2') + (): ExtractResult => keyExtractSuri('//2') ).toThrow(/to a secret URI/); }); - it('derives on "hello world"', () => { + it('derives on "hello world"', (): void => { expect( keyExtractSuri('hello world') ).toEqual({ @@ -20,7 +20,7 @@ describe('keyExtractSuri', () => { }); }); - it('derives on "hello world/1', () => { + it('derives on "hello world/1', (): void => { expect( keyExtractSuri('hello world/1') ).toEqual({ @@ -31,7 +31,7 @@ describe('keyExtractSuri', () => { }); }); - it('derives on "hello world/DOT', () => { + it('derives on "hello world/DOT', (): void => { expect( keyExtractSuri('hello world/DOT') ).toEqual({ @@ -42,7 +42,7 @@ describe('keyExtractSuri', () => { }); }); - it('derives on "hello world//1', () => { + it('derives on "hello world//1', (): void => { expect( keyExtractSuri('hello world//1') ).toEqual({ @@ -53,7 +53,7 @@ describe('keyExtractSuri', () => { }); }); - it('derives on "hello world//DOT', () => { + it('derives on "hello world//DOT', (): void => { expect( keyExtractSuri('hello world//DOT') ).toEqual({ @@ -64,7 +64,7 @@ describe('keyExtractSuri', () => { }); }); - it('derives on "hello world//1/DOT', () => { + it('derives on "hello world//1/DOT', (): void => { expect( keyExtractSuri('hello world//1/DOT') ).toEqual({ @@ -76,7 +76,7 @@ describe('keyExtractSuri', () => { }); }); - it('derives on "hello world//DOT/1', () => { + it('derives on "hello world//DOT/1', (): void => { expect( keyExtractSuri('hello world//DOT/1') ).toEqual({ @@ -88,7 +88,7 @@ describe('keyExtractSuri', () => { }); }); - it('derives on "hello world///password"', () => { + it('derives on "hello world///password"', (): void => { expect( keyExtractSuri('hello world///password') ).toEqual({ @@ -98,7 +98,7 @@ describe('keyExtractSuri', () => { }); }); - it('derives on "hello world//1/DOT///password"', () => { + it('derives on "hello world//1/DOT///password"', (): void => { expect( keyExtractSuri('hello world//1/DOT///password') ).toEqual({ @@ -111,7 +111,7 @@ describe('keyExtractSuri', () => { }); }); - it('derives on "hello world/1//DOT///password"', () => { + it('derives on "hello world/1//DOT///password"', (): void => { expect( keyExtractSuri('hello world/1//DOT///password') ).toEqual({ @@ -124,7 +124,7 @@ describe('keyExtractSuri', () => { }); }); - it('derives on actual Alice', () => { + it('derives on actual Alice', (): void => { expect( keyExtractSuri('bottom drive obey lake curtain smoke basket hold race lonely fit walk//Alice') ).toEqual({ diff --git a/packages/util-crypto/src/key/extractSuri.ts b/packages/util-crypto/src/key/extractSuri.ts index cfb800d9f..538efa361 100644 --- a/packages/util-crypto/src/key/extractSuri.ts +++ b/packages/util-crypto/src/key/extractSuri.ts @@ -7,13 +7,13 @@ import { assert, isNull } from '@polkadot/util'; import DeriveJunction from './DeriveJunction'; import keyExtractPath from './extractPath'; -type ExtractResult = { - password?: string, - path: Array, - phrase: string -}; +export interface ExtractResult { + password?: string; + path: DeriveJunction[]; + phrase: string; +} -const RE_CAPTURE = /^(\w+( \w+)*)((\/\/?[^\/]+)*)(\/\/\/(.*))?$/; +const RE_CAPTURE = /^(\w+( \w+)*)((\/\/?[^/]+)*)(\/\/\/(.*))?$/; /** * @description Extracts the phrase, path and password from a SURI format for specifying secret keys `//////` (the `///password` may be omitted, and `/` and `//` maybe repeated and mixed). @@ -23,7 +23,7 @@ export default function keyExtract (suri: string): ExtractResult { assert(!isNull(matches), `Unable to match '${suri}' to a secret URI`); - const [, phrase, , derivePath, , , password] = matches as Array; + const [, phrase, , derivePath, , , password] = matches as string[]; const { path } = keyExtractPath(derivePath); return { diff --git a/packages/util-crypto/src/key/fromPath.ts b/packages/util-crypto/src/key/fromPath.ts index 5aca2ba49..67e519d91 100644 --- a/packages/util-crypto/src/key/fromPath.ts +++ b/packages/util-crypto/src/key/fromPath.ts @@ -8,10 +8,10 @@ import DeriveJunction from './DeriveJunction'; import keyHdkdEd15519 from './hdkdEd25519'; import keyHdkdSr15519 from './hdkdSr25519'; -export default function keyFromPath (pair: Keypair, path: Array, type: KeypairType): Keypair { +export default function keyFromPath (pair: Keypair, path: DeriveJunction[], type: KeypairType): Keypair { const isEd25519 = type === 'ed25519'; - return path.reduce((pair, junction) => { + return path.reduce((pair, junction): Keypair => { return isEd25519 ? keyHdkdEd15519(pair, junction) : keyHdkdSr15519(pair, junction); diff --git a/packages/util-crypto/src/mnemonic/generate.spec.ts b/packages/util-crypto/src/mnemonic/generate.spec.ts index 2d9506870..f9d92e91f 100644 --- a/packages/util-crypto/src/mnemonic/generate.spec.ts +++ b/packages/util-crypto/src/mnemonic/generate.spec.ts @@ -2,16 +2,16 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import generate from './generate'; +import generate, { WordCount } from './generate'; import validate from './validate'; import { cryptoWaitReady } from '..'; -describe('mnemonicGenerate', () => { - beforeEach(async () => { +describe('mnemonicGenerate', (): void => { + beforeEach(async (): Promise => { await cryptoWaitReady(); }); - it('generates a valid mnemonic (default strength)', () => { + it('generates a valid mnemonic (default strength)', (): void => { const mnemonic = generate(); console.error(mnemonic); @@ -21,9 +21,9 @@ describe('mnemonicGenerate', () => { ).toEqual(true); }); - [12, 15, 18, 21, 24].forEach((num) => { - it(`generates a valid mnemonic (${num} words)`, () => { - const mnemonic = generate(num as any); + ([12, 15, 18, 21, 24] as WordCount[]).forEach((num: WordCount): void => { + it(`generates a valid mnemonic (${num} words)`, (): void => { + const mnemonic = generate(num); const isValid = validate(mnemonic); console.error(mnemonic); diff --git a/packages/util-crypto/src/mnemonic/generate.ts b/packages/util-crypto/src/mnemonic/generate.ts index 81fd092cd..60ddc5a8f 100644 --- a/packages/util-crypto/src/mnemonic/generate.ts +++ b/packages/util-crypto/src/mnemonic/generate.ts @@ -7,7 +7,7 @@ import '../polyfill'; import { generateMnemonic } from 'bip39'; import { bip39Generate, isReady } from '@polkadot/wasm-crypto'; -type WordCount = 12 | 15 | 18 | 21 | 24; +export type WordCount = 12 | 15 | 18 | 21 | 24; // mapping of words to the actual strength (as expected) const STRENGTH_MAP = { diff --git a/packages/util-crypto/src/mnemonic/toEntropy.spec.ts b/packages/util-crypto/src/mnemonic/toEntropy.spec.ts index f5d5e9bcb..89a381af3 100644 --- a/packages/util-crypto/src/mnemonic/toEntropy.spec.ts +++ b/packages/util-crypto/src/mnemonic/toEntropy.spec.ts @@ -8,13 +8,13 @@ import toEntropy from './toEntropy'; import tests from '../schnorrkel/keypair/testing'; import { cryptoWaitReady } from '..'; -describe('mnemonicToEntropy', () => { - beforeEach(async () => { +describe('mnemonicToEntropy', (): void => { + beforeEach(async (): Promise => { await cryptoWaitReady(); }); - tests.forEach(([mnemonic, entropy], index) => { - it(`Created correct entropy for ${index}`, () => { + tests.forEach(([mnemonic, entropy], index): void => { + it(`Created correct entropy for ${index}`, (): void => { expect(u8aToHex(toEntropy(mnemonic))).toEqual(entropy); }); }); diff --git a/packages/util-crypto/src/mnemonic/toMiniSecret.spec.ts b/packages/util-crypto/src/mnemonic/toMiniSecret.spec.ts index 710d73568..637c69651 100644 --- a/packages/util-crypto/src/mnemonic/toMiniSecret.spec.ts +++ b/packages/util-crypto/src/mnemonic/toMiniSecret.spec.ts @@ -8,19 +8,19 @@ import mnemonicToMiniSecret from './toMiniSecret'; import tests from '../schnorrkel/keypair/testing'; import { cryptoWaitReady } from '..'; -describe('mnemonicToMiniSecret', () => { - beforeEach(async () => { +describe('mnemonicToMiniSecret', (): void => { + beforeEach(async (): Promise => { await cryptoWaitReady(); }); - it('generates a valid seed', () => { + it('generates a valid seed', (): void => { expect( u8aToHex(mnemonicToMiniSecret('seed sock milk update focus rotate barely fade car face mechanic mercy')) ).toEqual('0x4d1ab2a57929edfd018aaa974e62ed557e3f54b4104acabedf73c8f5a1dbb029'); }); - tests.forEach(([mnemonic, , seed], index) => { - it(`Created correct seed for ${index}`, () => { + tests.forEach(([mnemonic, , seed], index): void => { + it(`Created correct seed for ${index}`, (): void => { expect( u8aToHex(mnemonicToMiniSecret(mnemonic, 'Substrate')) ).toEqual( diff --git a/packages/util-crypto/src/mnemonic/toSeed.spec.ts b/packages/util-crypto/src/mnemonic/toSeed.spec.ts index d7e257cd0..86f69d6b7 100644 --- a/packages/util-crypto/src/mnemonic/toSeed.spec.ts +++ b/packages/util-crypto/src/mnemonic/toSeed.spec.ts @@ -6,8 +6,8 @@ import { u8aToHex } from '@polkadot/util'; import toSeed from './toSeed'; -describe('mnemonicToSeed', () => { - it('generates a valid seed', () => { +describe('mnemonicToSeed', (): void => { + it('generates a valid seed', (): void => { expect( u8aToHex(toSeed('seed sock milk update focus rotate barely fade car face mechanic mercy')) ).toEqual('0x3c121e20de068083b49c2315697fb59a2d9e8643c24e5ea7628132c58969a027'); diff --git a/packages/util-crypto/src/mnemonic/validate.spec.ts b/packages/util-crypto/src/mnemonic/validate.spec.ts index b9f014b3b..57b83999c 100644 --- a/packages/util-crypto/src/mnemonic/validate.spec.ts +++ b/packages/util-crypto/src/mnemonic/validate.spec.ts @@ -5,18 +5,18 @@ import validate from './validate'; import { cryptoWaitReady } from '..'; -describe('mnemonicValidate', () => { - beforeEach(async () => { +describe('mnemonicValidate', (): void => { + beforeEach(async (): Promise => { await cryptoWaitReady(); }); - it('returns true on valid', () => { + it('returns true on valid', (): void => { expect( validate('seed sock milk update focus rotate barely fade car face mechanic mercy') ).toEqual(true); }); - it('returns false on invalid', () => { + it('returns false on invalid', (): void => { expect( validate('wine photo extra cushion basket dwarf humor cloud truck job boat submit') ).toEqual(false); diff --git a/packages/util-crypto/src/nacl/decrypt.spec.ts b/packages/util-crypto/src/nacl/decrypt.spec.ts index 9289babcf..c36574742 100644 --- a/packages/util-crypto/src/nacl/decrypt.spec.ts +++ b/packages/util-crypto/src/nacl/decrypt.spec.ts @@ -4,8 +4,8 @@ import { naclDecrypt, naclEncrypt } from '.'; -describe('naclDecrypt', () => { - it('decrypts a encrypted message', () => { +describe('naclDecrypt', (): void => { + it('decrypts a encrypted message', (): void => { const secret = new Uint8Array(32); const message = new Uint8Array([1, 2, 3, 4, 5, 4, 3, 2, 1]); const { encrypted, nonce } = naclEncrypt(message, secret); @@ -17,7 +17,7 @@ describe('naclDecrypt', () => { ); }); - it('returns null on invalid', () => { + it('returns null on invalid', (): void => { expect( naclDecrypt(new Uint8Array(), new Uint8Array(24), new Uint8Array(32)) ).toEqual(null); diff --git a/packages/util-crypto/src/nacl/encrypt.spec.ts b/packages/util-crypto/src/nacl/encrypt.spec.ts index 2a4b4715f..0edbcde5d 100644 --- a/packages/util-crypto/src/nacl/encrypt.spec.ts +++ b/packages/util-crypto/src/nacl/encrypt.spec.ts @@ -4,8 +4,8 @@ import { naclEncrypt } from '.'; -describe('naclEncrypt', () => { - it('encrypts a message', () => { +describe('naclEncrypt', (): void => { + it('encrypts a message', (): void => { const secret = new Uint8Array(32); const message = new Uint8Array([1, 2, 3, 4, 5, 4, 3, 2, 1]); diff --git a/packages/util-crypto/src/nacl/encrypt.ts b/packages/util-crypto/src/nacl/encrypt.ts index f5b0b7ee7..c6fea341c 100644 --- a/packages/util-crypto/src/nacl/encrypt.ts +++ b/packages/util-crypto/src/nacl/encrypt.ts @@ -6,10 +6,10 @@ import nacl from 'tweetnacl'; import randomAsU8a from '../random/asU8a'; -type Encrypted = { - encrypted: Uint8Array, - nonce: Uint8Array -}; +interface Encrypted { + encrypted: Uint8Array; + nonce: Uint8Array; +} /** * @name naclEncrypt diff --git a/packages/util-crypto/src/nacl/keypair/fromRandom.spec.ts b/packages/util-crypto/src/nacl/keypair/fromRandom.spec.ts index ee020d6b3..bafad600d 100644 --- a/packages/util-crypto/src/nacl/keypair/fromRandom.spec.ts +++ b/packages/util-crypto/src/nacl/keypair/fromRandom.spec.ts @@ -6,20 +6,20 @@ import { Keypair } from '../../types'; import { naclKeypairFromRandom } from '..'; -describe('naclKeypairFromRandom', () => { +describe('naclKeypairFromRandom', (): void => { let keypair: Keypair; - beforeEach(() => { + beforeEach((): void => { keypair = naclKeypairFromRandom(); }); - it('generates a valid publicKey', () => { + it('generates a valid publicKey', (): void => { expect( keypair.publicKey ).toHaveLength(32); }); - it('generates a valid secretKey', () => { + it('generates a valid secretKey', (): void => { expect( keypair.secretKey ).toHaveLength(64); diff --git a/packages/util-crypto/src/nacl/keypair/fromSecret.spec.ts b/packages/util-crypto/src/nacl/keypair/fromSecret.spec.ts index d2f280fc0..f4d31c251 100644 --- a/packages/util-crypto/src/nacl/keypair/fromSecret.spec.ts +++ b/packages/util-crypto/src/nacl/keypair/fromSecret.spec.ts @@ -4,7 +4,7 @@ import { naclKeypairFromSecret } from '..'; -describe('naclKeypairFromSecret', () => { +describe('naclKeypairFromSecret', (): void => { const secretKey = new Uint8Array([ 18, 52, 86, 120, 144, 18, 52, 86, 120, 144, 18, 52, 86, 120, 144, 18, @@ -16,7 +16,7 @@ describe('naclKeypairFromSecret', () => { 216, 214, 0, 41, 45, 138, 13, 53 ]); - it('generates a valid publicKey/secretKey pair', () => { + it('generates a valid publicKey/secretKey pair', (): void => { expect( naclKeypairFromSecret(secretKey) ).toEqual({ diff --git a/packages/util-crypto/src/nacl/keypair/fromSeed.spec.ts b/packages/util-crypto/src/nacl/keypair/fromSeed.spec.ts index b087ce96f..1f9d09269 100644 --- a/packages/util-crypto/src/nacl/keypair/fromSeed.spec.ts +++ b/packages/util-crypto/src/nacl/keypair/fromSeed.spec.ts @@ -7,7 +7,7 @@ import { waitReady } from '@polkadot/wasm-crypto'; import { naclKeypairFromSeed } from '..'; -describe('naclKeypairFromSeed', () => { +describe('naclKeypairFromSeed', (): void => { // NOTE: Aligned with Rust test, b"12345678901234567890123456789012" const TEST = stringToU8a('12345678901234567890123456789012'); const RESULT = { @@ -27,11 +27,11 @@ describe('naclKeypairFromSeed', () => { ]) }; - beforeEach(async () => { + beforeEach(async (): Promise => { await waitReady(); }); - it('generates a valid publicKey/secretKey pair (u8a)', () => { + it('generates a valid publicKey/secretKey pair (u8a)', (): void => { expect( naclKeypairFromSeed(TEST) ).toEqual(RESULT); diff --git a/packages/util-crypto/src/nacl/keypair/fromString.spec.ts b/packages/util-crypto/src/nacl/keypair/fromString.spec.ts index a1a2c3e0b..d8b4da767 100644 --- a/packages/util-crypto/src/nacl/keypair/fromString.spec.ts +++ b/packages/util-crypto/src/nacl/keypair/fromString.spec.ts @@ -4,8 +4,8 @@ import { naclKeypairFromString } from '..'; -describe('naclKeypairFromSeed', () => { - it('generates a valid publicKey/secretKey pair', () => { +describe('naclKeypairFromSeed', (): void => { + it('generates a valid publicKey/secretKey pair', (): void => { expect( naclKeypairFromString('test') ).toEqual({ diff --git a/packages/util-crypto/src/nacl/sign.spec.ts b/packages/util-crypto/src/nacl/sign.spec.ts index 0b8bca196..8b4b4df12 100644 --- a/packages/util-crypto/src/nacl/sign.spec.ts +++ b/packages/util-crypto/src/nacl/sign.spec.ts @@ -7,12 +7,12 @@ import { waitReady } from '@polkadot/wasm-crypto'; import { naclSign, naclKeypairFromSeed } from '.'; -describe('naclSign', () => { - beforeEach(async () => { +describe('naclSign', (): void => { + beforeEach(async (): Promise => { await waitReady(); }); - it('returns a valid signature for the message', () => { + it('returns a valid signature for the message', (): void => { expect( naclSign( new Uint8Array([0x61, 0x62, 0x63, 0x64]), diff --git a/packages/util-crypto/src/nacl/verify.spec.ts b/packages/util-crypto/src/nacl/verify.spec.ts index 833d4cd70..bc762cef2 100644 --- a/packages/util-crypto/src/nacl/verify.spec.ts +++ b/packages/util-crypto/src/nacl/verify.spec.ts @@ -7,11 +7,11 @@ import { waitReady } from '@polkadot/wasm-crypto'; import { naclVerify, naclKeypairFromSeed } from '.'; -describe('naclSign', () => { +describe('naclSign', (): void => { let publicKey: Uint8Array; let signature: Uint8Array; - beforeEach(async () => { + beforeEach(async (): Promise => { await waitReady(); publicKey = naclKeypairFromSeed( @@ -20,7 +20,7 @@ describe('naclSign', () => { signature = new Uint8Array([28, 58, 206, 239, 249, 70, 59, 191, 166, 40, 219, 218, 235, 170, 25, 79, 10, 94, 9, 197, 34, 126, 1, 150, 246, 68, 28, 238, 36, 26, 172, 163, 168, 90, 202, 211, 126, 246, 57, 212, 43, 24, 88, 197, 240, 113, 118, 76, 37, 81, 91, 110, 236, 50, 144, 134, 100, 223, 220, 238, 34, 185, 211, 7]); }); - it('validates a correctly signed message', () => { + it('validates a correctly signed message', (): void => { expect( naclVerify( new Uint8Array([0x61, 0x62, 0x63, 0x64]), @@ -30,7 +30,7 @@ describe('naclSign', () => { ).toEqual(true); }); - it('fails a correctly signed message (message changed)', () => { + it('fails a correctly signed message (message changed)', (): void => { expect( naclVerify( new Uint8Array([0x61, 0x62, 0x63, 0x64, 0x65]), @@ -40,7 +40,7 @@ describe('naclSign', () => { ).toEqual(false); }); - it('fails a correctly signed message (signature changed)', () => { + it('fails a correctly signed message (signature changed)', (): void => { signature[0] = 0xff; expect( diff --git a/packages/util-crypto/src/random/asHex.spec.ts b/packages/util-crypto/src/random/asHex.spec.ts index a3ea20523..cc8aed02b 100644 --- a/packages/util-crypto/src/random/asHex.spec.ts +++ b/packages/util-crypto/src/random/asHex.spec.ts @@ -6,8 +6,8 @@ import { isHex } from '@polkadot/util'; import { randomAsHex } from '.'; -describe('randomAsBuffer', () => { - it('generated results does not match', () => { +describe('randomAsBuffer', (): void => { + it('generated results does not match', (): void => { expect( randomAsHex() ).not.toEqual( @@ -15,7 +15,7 @@ describe('randomAsBuffer', () => { ); }); - it('is a valid hex number', () => { + it('is a valid hex number', (): void => { expect( isHex( randomAsHex() @@ -23,13 +23,13 @@ describe('randomAsBuffer', () => { ).toEqual(true); }); - it('generates 32 bytes by default', () => { + it('generates 32 bytes by default', (): void => { expect( randomAsHex() ).toHaveLength(32 * 2 + 2); }); - it('generates with the supplied length', () => { + it('generates with the supplied length', (): void => { expect( randomAsHex(66) ).toHaveLength(66 * 2 + 2); diff --git a/packages/util-crypto/src/random/asNumber.spec.ts b/packages/util-crypto/src/random/asNumber.spec.ts index 0ceb26d2b..83fb653df 100644 --- a/packages/util-crypto/src/random/asNumber.spec.ts +++ b/packages/util-crypto/src/random/asNumber.spec.ts @@ -4,8 +4,8 @@ import { randomAsNumber } from '.'; -describe('randomAsNumber', () => { - it('generates subsequent non-matching numbers', () => { +describe('randomAsNumber', (): void => { + it('generates subsequent non-matching numbers', (): void => { expect( randomAsNumber() ).not.toEqual( diff --git a/packages/util-crypto/src/random/asU8a.spec.ts b/packages/util-crypto/src/random/asU8a.spec.ts index 746dfd929..5ec7021c2 100644 --- a/packages/util-crypto/src/random/asU8a.spec.ts +++ b/packages/util-crypto/src/random/asU8a.spec.ts @@ -6,14 +6,14 @@ import { isU8a } from '@polkadot/util'; import { randomAsU8a } from '.'; -describe('randomAsU8a', () => { - it('generates a Uint8Array', () => { +describe('randomAsU8a', (): void => { + it('generates a Uint8Array', (): void => { expect( isU8a(randomAsU8a()) ).toEqual(true); }); - it('generated results does not match', () => { + it('generated results does not match', (): void => { expect( randomAsU8a() ).not.toEqual( @@ -21,13 +21,13 @@ describe('randomAsU8a', () => { ); }); - it('generates 32 bytes by default', () => { + it('generates 32 bytes by default', (): void => { expect( randomAsU8a() ).toHaveLength(32); }); - it('generates with the suuplied length', () => { + it('generates with the suuplied length', (): void => { expect( randomAsU8a(66) ).toHaveLength(66); diff --git a/packages/util-crypto/src/schnorrkel/keypair/fromSeed.spec.ts b/packages/util-crypto/src/schnorrkel/keypair/fromSeed.spec.ts index 9708ea617..7a5e43898 100644 --- a/packages/util-crypto/src/schnorrkel/keypair/fromSeed.spec.ts +++ b/packages/util-crypto/src/schnorrkel/keypair/fromSeed.spec.ts @@ -9,25 +9,25 @@ import { mnemonicToMiniSecret } from '../../mnemonic'; import { schnorrkelKeypairFromSeed } from '..'; import tests from './testing'; -describe('schnorrkelKeypairFromSeed', () => { +describe('schnorrkelKeypairFromSeed', (): void => { const TEST = stringToU8a('12345678901234567890123456789012'); const RESULT = { publicKey: new Uint8Array([116, 28, 8, 160, 111, 65, 197, 150, 96, 143, 103, 116, 37, 155, 217, 4, 51, 4, 173, 250, 93, 62, 234, 98, 118, 11, 217, 190, 151, 99, 77, 99]), secretKey: new Uint8Array([240, 16, 102, 96, 195, 221, 162, 63, 22, 218, 169, 172, 91, 129, 27, 150, 48, 119, 245, 188, 10, 248, 159, 133, 128, 79, 13, 232, 228, 36, 240, 80, 249, 141, 102, 243, 148, 66, 80, 111, 249, 71, 253, 145, 31, 24, 199, 167, 165, 218, 99, 154, 99, 232, 211, 180, 226, 51, 247, 65, 67, 217, 81, 193]) }; - beforeEach(async () => { - return waitReady(); + beforeEach(async (): Promise => { + await waitReady(); }); - it('generates a valid publicKey/secretKey pair (u8a)', () => { + it('generates a valid publicKey/secretKey pair (u8a)', (): void => { expect( schnorrkelKeypairFromSeed(TEST) ).toEqual(RESULT); }); - tests.forEach(([mnemonic, , , secret], index) => { - it(`creates valid against known (${index})`, () => { + tests.forEach(([mnemonic, , , secret], index): void => { + it(`creates valid against known (${index})`, (): void => { const seed = mnemonicToMiniSecret(mnemonic, 'Substrate'); const pair = schnorrkelKeypairFromSeed(seed); diff --git a/packages/util-crypto/src/schnorrkel/keypair/testing.ts b/packages/util-crypto/src/schnorrkel/keypair/testing.ts index f45850f5d..8aec6a75b 100644 --- a/packages/util-crypto/src/schnorrkel/keypair/testing.ts +++ b/packages/util-crypto/src/schnorrkel/keypair/testing.ts @@ -5,7 +5,7 @@ // mnemonic, entropy, seed, secret (expanded) type Test = [string, string, string, string]; -const tests: Array = [ +const tests: Test[] = [ [ 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about', '0x00000000000000000000000000000000', diff --git a/packages/util-crypto/src/schnorrkel/signVerify.spec.ts b/packages/util-crypto/src/schnorrkel/signVerify.spec.ts index 49d887697..b688aa042 100644 --- a/packages/util-crypto/src/schnorrkel/signVerify.spec.ts +++ b/packages/util-crypto/src/schnorrkel/signVerify.spec.ts @@ -12,18 +12,18 @@ import verify from './verify'; const MESSAGE = stringToU8a('this is a message'); -describe('sign and verify', () => { - beforeEach(async () => { - return waitReady(); +describe('sign and verify', (): void => { + beforeEach(async (): Promise => { + await waitReady(); }); - it('has 64-byte signatures', () => { + it('has 64-byte signatures', (): void => { const pair = pairFromSeed(randomAsU8a()); expect(sign(MESSAGE, pair)).toHaveLength(64); }); - it('can sign and verify a message', () => { + it('can sign and verify a message', (): void => { const pair = pairFromSeed(randomAsU8a()); const signature = sign(MESSAGE, pair); diff --git a/packages/util-crypto/src/sha512/asU8a.spec.ts b/packages/util-crypto/src/sha512/asU8a.spec.ts index 383706309..9ce990ef6 100644 --- a/packages/util-crypto/src/sha512/asU8a.spec.ts +++ b/packages/util-crypto/src/sha512/asU8a.spec.ts @@ -6,12 +6,12 @@ import { waitReady } from '@polkadot/wasm-crypto'; import { sha512AsU8a } from '.'; -describe('sha512AsU8a', () => { - beforeEach(async () => { +describe('sha512AsU8a', (): void => { + beforeEach(async (): Promise => { await waitReady(); }); - it('creates a sha-512 hash', () => { + it('creates a sha-512 hash', (): void => { expect( sha512AsU8a( Uint8Array.from([0x61, 0x62, 0x63, 0x64]) diff --git a/packages/util-crypto/src/types.ts b/packages/util-crypto/src/types.ts index b010a8c13..5fc06037b 100644 --- a/packages/util-crypto/src/types.ts +++ b/packages/util-crypto/src/types.ts @@ -2,14 +2,14 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -export type Keypair = { +export interface Keypair { publicKey: Uint8Array; secretKey: Uint8Array; -}; +} -export type Seedpair = { +export interface Seedpair { publicKey: Uint8Array; seed: Uint8Array; -}; +} export type KeypairType = 'ed25519' | 'sr25519'; diff --git a/packages/util-crypto/src/xxhash/asHex.spec.ts b/packages/util-crypto/src/xxhash/asHex.spec.ts index a8fe11950..633b6cfd9 100644 --- a/packages/util-crypto/src/xxhash/asHex.spec.ts +++ b/packages/util-crypto/src/xxhash/asHex.spec.ts @@ -6,24 +6,24 @@ import { waitReady } from '@polkadot/wasm-crypto'; import { xxhashAsHex } from '.'; -describe('xxhashAsHex', () => { - beforeEach(async () => { +describe('xxhashAsHex', (): void => { + beforeEach(async (): Promise => { await waitReady(); }); - it('returns a 64-bit value by default', () => { + it('returns a 64-bit value by default', (): void => { expect( xxhashAsHex('abc') ).toEqual('0x990977adf52cbc44'); }); - it('returns a 128-bit value (as specified)', () => { + it('returns a 128-bit value (as specified)', (): void => { expect( xxhashAsHex('abc', 128) ).toEqual('0x990977adf52cbc440889329981caa9be'); }); - it('returns a 256-bit value (as specified)', () => { + it('returns a 256-bit value (as specified)', (): void => { expect( xxhashAsHex('abc', 256) ).toEqual('0x990977adf52cbc440889329981caa9bef7da5770b2b8a05303b75d95360dd62b'); diff --git a/packages/util-crypto/src/xxhash/asU8a.spec.ts b/packages/util-crypto/src/xxhash/asU8a.spec.ts index 7794eef88..dce80133d 100644 --- a/packages/util-crypto/src/xxhash/asU8a.spec.ts +++ b/packages/util-crypto/src/xxhash/asU8a.spec.ts @@ -7,12 +7,12 @@ import { waitReady } from '@polkadot/wasm-crypto'; import { xxhashAsU8a } from '.'; -describe('xxhashAsU8a', () => { - beforeEach(async () => { +describe('xxhashAsU8a', (): void => { + beforeEach(async (): Promise => { await waitReady(); }); - it('returns a 64-bit value by default', () => { + it('returns a 64-bit value by default', (): void => { expect( xxhashAsU8a('abc') ).toEqual( @@ -20,7 +20,7 @@ describe('xxhashAsU8a', () => { ); }); - it('returns a 128-bit value (as specified)', () => { + it('returns a 128-bit value (as specified)', (): void => { expect( xxhashAsU8a('abc', 128) ).toEqual( @@ -28,7 +28,7 @@ describe('xxhashAsU8a', () => { ); }); - it('returns a 256-bit value (as specified)', () => { + it('returns a 256-bit value (as specified)', (): void => { expect( xxhashAsU8a('abc', 256) ).toEqual( diff --git a/packages/util-crypto/src/xxhash/xxhash64/asBn.spec.ts b/packages/util-crypto/src/xxhash/xxhash64/asBn.spec.ts index 9d803e4f9..adf1ee2ad 100644 --- a/packages/util-crypto/src/xxhash/xxhash64/asBn.spec.ts +++ b/packages/util-crypto/src/xxhash/xxhash64/asBn.spec.ts @@ -4,8 +4,8 @@ import { xxhash64AsBn } from '.'; -describe('xxhash64AsBn', () => { - it('creates the correct BN output', () => { +describe('xxhash64AsBn', (): void => { + it('creates the correct BN output', (): void => { expect( xxhash64AsBn('abcd', 0xabcd).toString(16) ).toEqual('e29f70f8b8c96df7'); diff --git a/packages/util-crypto/src/xxhash/xxhash64/asHex.spec.ts b/packages/util-crypto/src/xxhash/xxhash64/asHex.spec.ts index 6d9d941f2..ffdc6220a 100644 --- a/packages/util-crypto/src/xxhash/xxhash64/asHex.spec.ts +++ b/packages/util-crypto/src/xxhash/xxhash64/asHex.spec.ts @@ -4,8 +4,8 @@ import { xxhash64AsHex } from '.'; -describe('xxhash64AsHex', () => { - it('creates the correct hex output', () => { +describe('xxhash64AsHex', (): void => { + it('creates the correct hex output', (): void => { expect( xxhash64AsHex('abcd', 0xabcd) ).toEqual('0xe29f70f8b8c96df7'); diff --git a/packages/util-crypto/src/xxhash/xxhash64/asRaw.spec.ts b/packages/util-crypto/src/xxhash/xxhash64/asRaw.spec.ts index 94f8d9b22..1fd480e04 100644 --- a/packages/util-crypto/src/xxhash/xxhash64/asRaw.spec.ts +++ b/packages/util-crypto/src/xxhash/xxhash64/asRaw.spec.ts @@ -4,8 +4,8 @@ import { xxhash64AsRaw } from '.'; -describe('xxhash64AsRaw', () => { - it('creates the correct non-prefixed hex output', () => { +describe('xxhash64AsRaw', (): void => { + it('creates the correct non-prefixed hex output', (): void => { expect( xxhash64AsRaw('abcd', 0xabcd) ).toEqual('e29f70f8b8c96df7'); diff --git a/packages/util-crypto/src/xxhash/xxhash64/asValue.spec.ts b/packages/util-crypto/src/xxhash/xxhash64/asValue.spec.ts index c0eb0e02a..5785dde1a 100644 --- a/packages/util-crypto/src/xxhash/xxhash64/asValue.spec.ts +++ b/packages/util-crypto/src/xxhash/xxhash64/asValue.spec.ts @@ -4,20 +4,20 @@ import xxhash64AsValue from './asValue'; -describe('xxhash64AsValue', () => { - it('creates the correct output (string input)', () => { +describe('xxhash64AsValue', (): void => { + it('creates the correct output (string input)', (): void => { expect( xxhash64AsValue('abcd', 0xabcd).toString(16) ).toEqual('e29f70f8b8c96df7'); }); - it('creates the correct output (Buffer input)', () => { + it('creates the correct output (Buffer input)', (): void => { expect( xxhash64AsValue(Buffer.from([0x61, 0x62, 0x63, 0x64]), 0xabcd).toString(16) ).toEqual('e29f70f8b8c96df7'); }); - it('creates the correct output (Uint8Array input)', () => { + it('creates the correct output (Uint8Array input)', (): void => { expect( xxhash64AsValue(new Uint8Array([0x61, 0x62, 0x63, 0x64]), 0xabcd).toString(16) ).toEqual('e29f70f8b8c96df7'); diff --git a/packages/util-crypto/src/xxhash/xxhash64/asValue.ts b/packages/util-crypto/src/xxhash/xxhash64/asValue.ts index 38fc3dd12..9b10a9e20 100644 --- a/packages/util-crypto/src/xxhash/xxhash64/asValue.ts +++ b/packages/util-crypto/src/xxhash/xxhash64/asValue.ts @@ -29,5 +29,5 @@ export default function xxhash64AsValue (data: Buffer | Uint8Array | string, see return xxhashjs.h64( u8aToBuffer(data), seed - ) as any; + ) as number; } diff --git a/packages/util-rlp/src/decode.spec.ts b/packages/util-rlp/src/decode.spec.ts index 29164ece9..718c788a5 100644 --- a/packages/util-rlp/src/decode.spec.ts +++ b/packages/util-rlp/src/decode.spec.ts @@ -10,8 +10,8 @@ import getTests from '../test/getTests'; const rlptests = getTests('RLPTests/rlptest.json'); -describe('decode', () => { - it('returns empty list for undefined inputs', () => { +describe('decode', (): void => { + it('returns empty list for undefined inputs', (): void => { expect( decode() ).toEqual( @@ -19,7 +19,7 @@ describe('decode', () => { ); }); - it('returns empty list for empty inputs', () => { + it('returns empty list for empty inputs', (): void => { expect( decode(new Uint8Array()) ).toEqual( @@ -27,8 +27,8 @@ describe('decode', () => { ); }); - rlptests.forEach(({ name, output }) => { - it(`passes official ${name}`, () => { + rlptests.forEach(({ name, output }): void => { + it(`passes official ${name}`, (): void => { expect( u8aToHex( encode( diff --git a/packages/util-rlp/src/decoder/decode.ts b/packages/util-rlp/src/decoder/decode.ts index 43ec715a2..1f985eb30 100644 --- a/packages/util-rlp/src/decoder/decode.ts +++ b/packages/util-rlp/src/decoder/decode.ts @@ -12,12 +12,12 @@ import decodeNumber from './number'; import decodeSingle from './single'; import decodeString from './string'; -type Decoder = { - max: number, - fn: (decode: DecodeFunc, input: Uint8Array) => DecodeOutput -}; +interface Decoder { + max: number; + fn: (decode: DecodeFunc, input: Uint8Array) => DecodeOutput; +} -const decoders: Array = [ +const decoders: Decoder[] = [ { max: 0x7f, fn: decodeSingle }, { max: 0xb7, fn: decodeString }, { max: 0xbf, fn: decodeNumber }, @@ -26,7 +26,7 @@ const decoders: Array = [ ]; export default function decode (input: Uint8Array): DecodeOutput { - const decoder = decoders.find(({ max }) => input[0] <= max); + const decoder = decoders.find(({ max }): boolean => input[0] <= max); assert(decoder, 'Unable to find decoder for input type'); diff --git a/packages/util-rlp/src/decoder/index.ts b/packages/util-rlp/src/decoder/index.ts index 1913274ae..b3cf69218 100644 --- a/packages/util-rlp/src/decoder/index.ts +++ b/packages/util-rlp/src/decoder/index.ts @@ -20,7 +20,7 @@ import internalDecode from './decode'; * decode(new Uint8Array([0x83, 0x64, 0x6f, 0x67])); // => 'dog' as Uint8Array * ``` */ -export default function decoder (input?: null | Uint8Array): Uint8Array | Array { +export default function decoder (input?: null | Uint8Array): Uint8Array | Uint8Array[] { try { if (!input || input.length === 0) { return new Uint8Array([]); @@ -30,7 +30,7 @@ export default function decoder (input?: null | Uint8Array): Uint8Array | Array< assert(remainder.length === 0, 'invalid remainder'); - return decoded; + return decoded as Uint8Array; } catch (error) { console.error(`RLP failed on input ${u8aToHex(input)}`); diff --git a/packages/util-rlp/src/decoder/listLong.ts b/packages/util-rlp/src/decoder/listLong.ts index 46ccfce57..47e8a8a1b 100644 --- a/packages/util-rlp/src/decoder/listLong.ts +++ b/packages/util-rlp/src/decoder/listLong.ts @@ -12,7 +12,7 @@ export default function decodeListLong (decode: DecodeFunc, input: Uint8Array): const llength = input[0] - 0xf6; const length = safeParseInt(input.slice(1, llength)); const totalLength = llength + length; - const decoded: Array = []; + const decoded: Uint8Array[] = []; assert(totalLength <= input.length, 'invalid rlp: total length is larger than the data'); @@ -23,7 +23,7 @@ export default function decodeListLong (decode: DecodeFunc, input: Uint8Array): while (innerRemainder.length) { const d = decode(innerRemainder); - decoded.push(d.decoded); + decoded.push(d.decoded as Uint8Array); innerRemainder = d.remainder; } diff --git a/packages/util-rlp/src/decoder/listShort.ts b/packages/util-rlp/src/decoder/listShort.ts index ffec1cc87..a6e3d5031 100644 --- a/packages/util-rlp/src/decoder/listShort.ts +++ b/packages/util-rlp/src/decoder/listShort.ts @@ -5,14 +5,14 @@ import { DecodeFunc, DecodeOutput } from './types'; export default function decodeListShort (decode: DecodeFunc, input: Uint8Array): DecodeOutput { - const decoded: Array = []; + const decoded: Uint8Array[] = []; const length = input[0] - 0xbf; let innerRemainder = input.slice(1, length); while (innerRemainder.length) { const d = decode(innerRemainder); - decoded.push(d.decoded); + decoded.push(d.decoded as Uint8Array); innerRemainder = d.remainder; } diff --git a/packages/util-rlp/src/decoder/safeParseInt.spec.ts b/packages/util-rlp/src/decoder/safeParseInt.spec.ts index 1a636e4c4..abfaa4cb5 100644 --- a/packages/util-rlp/src/decoder/safeParseInt.spec.ts +++ b/packages/util-rlp/src/decoder/safeParseInt.spec.ts @@ -5,16 +5,16 @@ import safeParseInt from './safeParseInt'; -describe('safeParseInt', () => { - it('does not allow 0 in first position', () => { +describe('safeParseInt', (): void => { + it('does not allow 0 in first position', (): void => { expect( - () => safeParseInt( + (): number => safeParseInt( new Uint8Array([0]) ) ).toThrow(/invalid rlp, extra zeros found/); }); - it('converts a value to the correct number', () => { + it('converts a value to the correct number', (): void => { expect( safeParseInt( new Uint8Array([0x12, 0x34, 0x56]) diff --git a/packages/util-rlp/src/decoder/safeParseInt.ts b/packages/util-rlp/src/decoder/safeParseInt.ts index 80356c841..c605068e3 100644 --- a/packages/util-rlp/src/decoder/safeParseInt.ts +++ b/packages/util-rlp/src/decoder/safeParseInt.ts @@ -7,5 +7,5 @@ import { assert } from '@polkadot/util'; export default function safeParseInt (input: Uint8Array): number { assert(input[0] > 0, 'invalid rlp, extra zeros found'); - return input.reduce((result, value) => (result * 256) + value, 0); + return input.reduce((result, value): number => (result * 256) + value, 0); } diff --git a/packages/util-rlp/src/decoder/types.ts b/packages/util-rlp/src/decoder/types.ts index 9c689a412..b66d59c7d 100644 --- a/packages/util-rlp/src/decoder/types.ts +++ b/packages/util-rlp/src/decoder/types.ts @@ -2,9 +2,9 @@ // This software may be modified and distributed under the terms // of the MPL-2.0 license. See the LICENSE file for details. -export type DecodeOutput = { - decoded: Uint8Array | Array, - remainder: Uint8Array -}; +export interface DecodeOutput { + decoded: Uint8Array | (Uint8Array | Uint8Array[])[]; + remainder: Uint8Array; +} export type DecodeFunc = (input: Uint8Array) => DecodeOutput; diff --git a/packages/util-rlp/src/encode.spec.ts b/packages/util-rlp/src/encode.spec.ts index 6c1ec0a65..491a4aef7 100644 --- a/packages/util-rlp/src/encode.spec.ts +++ b/packages/util-rlp/src/encode.spec.ts @@ -10,9 +10,9 @@ import getTests from '../test/getTests'; const rlptests = getTests('RLPTests/rlptest.json'); -describe('encode', () => { - rlptests.forEach(({ name, input, output }) => { - it(`passes official ${name}`, () => { +describe('encode', (): void => { + rlptests.forEach(({ name, input, output }): void => { + it(`passes official ${name}`, (): void => { expect( u8aToHex( encode(input) diff --git a/packages/util-rlp/src/encoder/array.ts b/packages/util-rlp/src/encoder/array.ts index f5cd6b196..090f239ef 100644 --- a/packages/util-rlp/src/encoder/array.ts +++ b/packages/util-rlp/src/encoder/array.ts @@ -8,7 +8,7 @@ import { u8aConcat } from '@polkadot/util'; import encodeLength from './length'; -export default function encodeArray (encoder: EncodeFunc, input: any): Uint8Array { +export default function encodeArray (encoder: EncodeFunc, input: (Uint8Array | null)[]): Uint8Array { const encoded = u8aConcat.apply(null, input.map(encoder)); return u8aConcat( diff --git a/packages/util-rlp/src/encoder/index.ts b/packages/util-rlp/src/encoder/index.ts index 33e9bc04c..f9e94e954 100644 --- a/packages/util-rlp/src/encoder/index.ts +++ b/packages/util-rlp/src/encoder/index.ts @@ -20,7 +20,7 @@ import encodeU8a from './u8a'; * encode('dog'); // => [0x83, 0x64, 0x6f, 0x67] * ``` */ -export default function encoder (input: any): Uint8Array { +export default function encoder (input?: null | Uint8Array | (null | Uint8Array)[] | string): Uint8Array { if (input instanceof Array) { return encodeArray(encoder, input); } diff --git a/packages/util-rlp/src/encoder/length.spec.ts b/packages/util-rlp/src/encoder/length.spec.ts index c7db8681d..511cb6d9d 100644 --- a/packages/util-rlp/src/encoder/length.spec.ts +++ b/packages/util-rlp/src/encoder/length.spec.ts @@ -4,8 +4,8 @@ import encodeLength from './length'; -describe('encodeLength', () => { - it('returns offset + length where <= 55', () => { +describe('encodeLength', (): void => { + it('returns offset + length where <= 55', (): void => { expect( encodeLength(5, 6) ).toEqual( @@ -13,7 +13,7 @@ describe('encodeLength', () => { ); }); - it('encodes > 55 length properly (short)', () => { + it('encodes > 55 length properly (short)', (): void => { expect( encodeLength(56, 6) ).toEqual( @@ -21,7 +21,7 @@ describe('encodeLength', () => { ); }); - it('encodes > 55 length properly (long)', () => { + it('encodes > 55 length properly (long)', (): void => { expect( encodeLength(512, 6) ).toEqual( diff --git a/packages/util-rlp/src/encoder/toU8a.spec.ts b/packages/util-rlp/src/encoder/toU8a.spec.ts index e4ef62c44..7674917e3 100644 --- a/packages/util-rlp/src/encoder/toU8a.spec.ts +++ b/packages/util-rlp/src/encoder/toU8a.spec.ts @@ -6,8 +6,8 @@ import BN from 'bn.js'; import toU8a from './toU8a'; -describe('toU8a', () => { - it('returns a Uint8Array input as-is', () => { +describe('toU8a', (): void => { + it('returns a Uint8Array input as-is', (): void => { expect( toU8a(new Uint8Array([1, 2, 3])) ).toEqual( @@ -15,7 +15,7 @@ describe('toU8a', () => { ); }); - it('converts Buffers (uses as Uint8Array)', () => { + it('converts Buffers (uses as Uint8Array)', (): void => { expect( toU8a(Buffer.from([0x12, 0x34, 0x56])) ).toEqual( @@ -23,7 +23,7 @@ describe('toU8a', () => { ); }); - it('returns undefined as empty', () => { + it('returns undefined as empty', (): void => { expect( toU8a() ).toEqual( @@ -31,7 +31,7 @@ describe('toU8a', () => { ); }); - it('returns null as empty', () => { + it('returns null as empty', (): void => { expect( toU8a(null) ).toEqual( @@ -39,7 +39,7 @@ describe('toU8a', () => { ); }); - it('converts hex strings', () => { + it('converts hex strings', (): void => { expect( toU8a('0x123456') ).toEqual( @@ -47,7 +47,7 @@ describe('toU8a', () => { ); }); - it('converts UTF-8 strings', () => { + it('converts UTF-8 strings', (): void => { expect( toU8a('Привет, мир!') ).toEqual( @@ -55,7 +55,7 @@ describe('toU8a', () => { ); }); - it('converts numbers', () => { + it('converts numbers', (): void => { expect( toU8a(0x123456) ).toEqual( @@ -63,7 +63,7 @@ describe('toU8a', () => { ); }); - it('converts BN', () => { + it('converts BN', (): void => { expect( toU8a(new BN(0x123456)) ).toEqual( @@ -71,9 +71,9 @@ describe('toU8a', () => { ); }); - it('throws on unknown type', () => { + it('throws on unknown type', (): void => { expect( - () => toU8a(true) + (): Uint8Array => toU8a(true) ).toThrow(/invalid type/); }); }); diff --git a/packages/util-rlp/src/encoder/toU8a.ts b/packages/util-rlp/src/encoder/toU8a.ts index 2b6010b0d..d2ccc2a36 100644 --- a/packages/util-rlp/src/encoder/toU8a.ts +++ b/packages/util-rlp/src/encoder/toU8a.ts @@ -4,10 +4,12 @@ import { assert, bnToU8a, bufferToU8a, hexHasPrefix, hexToU8a, isBn, isBuffer, isNull, isNumber, isString, isU8a, isUndefined, numberToU8a, stringToU8a } from '@polkadot/util'; -type Encoder = { - check: (value: any) => boolean, - fn: (value: any) => Uint8Array -}; +interface Encoder { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + check: (value: any) => boolean; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + fn: (value: any) => Uint8Array; +} function newEmpty (): Uint8Array { return new Uint8Array([]); @@ -25,19 +27,21 @@ function convertU8a (value: Uint8Array): Uint8Array { return value; } -const encoders: Array = [ +const encoders: Encoder[] = [ { check: isNull, fn: newEmpty }, { check: isUndefined, fn: newEmpty }, // NOTE: Buffer before U8a { check: isBuffer, fn: bufferToU8a }, { check: isU8a, fn: convertU8a }, - { check: isBn, fn: (value: any) => bnToU8a(value, -1, false) }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + { check: isBn, fn: (value: any): Uint8Array => bnToU8a(value, -1, false) }, { check: isNumber, fn: numberToU8a }, { check: isString, fn: convertString } ]; +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function toU8a (value?: any): Uint8Array { - const encoder = encoders.find(({ check }) => check(value)); + const encoder = encoders.find(({ check }): boolean => check(value)); assert(encoder, 'invalid type'); diff --git a/packages/util-rlp/src/encoder/types.ts b/packages/util-rlp/src/encoder/types.ts index fef017cb1..259f0513b 100644 --- a/packages/util-rlp/src/encoder/types.ts +++ b/packages/util-rlp/src/encoder/types.ts @@ -2,4 +2,5 @@ // This software may be modified and distributed under the terms // of the MPL-2.0 license. See the LICENSE file for details. +// eslint-disable-next-line @typescript-eslint/no-explicit-any export type EncodeFunc = (input: any) => Uint8Array; diff --git a/packages/util-rlp/test/getTests.ts b/packages/util-rlp/test/getTests.ts index 914cff1b1..7c53fb36b 100644 --- a/packages/util-rlp/test/getTests.ts +++ b/packages/util-rlp/test/getTests.ts @@ -7,17 +7,17 @@ import { getSingleFile } from 'ethereumjs-testing'; import bnToU8a from '@polkadot/util/bn/toU8a'; -type Tests = Array<{ - name: string, - input: any, - output?: string, - root: string -}>; +interface Test { + name: string; + input: string | Uint8Array; + output?: string; + root: string; +} -export default function getTests (file: string): Tests { +export default function getTests (file: string): Test[] { const tests = getSingleFile(file); - return Object.keys(tests).map((name) => ({ + return Object.keys(tests).map((name): Test => ({ name, input: tests[name].in[0] !== '#' ? tests[name].in diff --git a/packages/util/src/array/filter.spec.ts b/packages/util/src/array/filter.spec.ts index 77a236610..d791fbe11 100644 --- a/packages/util/src/array/filter.spec.ts +++ b/packages/util/src/array/filter.spec.ts @@ -4,14 +4,14 @@ import { arrayFilter } from '.'; -describe('filterArray', () => { - it('filters arrays, removing undefined', () => { +describe('filterArray', (): void => { + it('filters arrays, removing undefined', (): void => { expect( arrayFilter([0, '', null, false, void 0, NaN]) ).toEqual([0, '', null, false, NaN]); }); - it('filters arrays, removing undefined & null (allowNull = false)', () => { + it('filters arrays, removing undefined & null (allowNull = false)', (): void => { expect( arrayFilter([0, '', null, false, void 0, NaN], false) ).toEqual([0, '', false, NaN]); diff --git a/packages/util/src/array/filter.ts b/packages/util/src/array/filter.ts index 21f276a65..7db286879 100644 --- a/packages/util/src/array/filter.ts +++ b/packages/util/src/array/filter.ts @@ -20,8 +20,9 @@ import isUndefined from '../is/undefined'; * arrayFilter([0, void 0, true, null, false, ''], false); // [0, true, false, ''] * ``` */ -export default function arrayFilter (array: Array, allowNulls: boolean = true): Array { - return array.filter((value) => { +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export default function arrayFilter (array: any[], allowNulls: boolean = true): any[] { + return array.filter((value): boolean => { return !isUndefined(value) && (allowNulls || !isNull(value)); }); } diff --git a/packages/util/src/assert.spec.ts b/packages/util/src/assert.spec.ts index 4fecd6724..e2cb5c42b 100644 --- a/packages/util/src/assert.spec.ts +++ b/packages/util/src/assert.spec.ts @@ -4,31 +4,31 @@ import { assert } from '.'; -describe('assert', () => { - it('should not throw an error when test is true', () => { +describe('assert', (): void => { + it('should not throw an error when test is true', (): void => { expect( assert(true, 'nothing should be thrown') ).toEqual(true); }); - it('should throw an error when test is not true', () => { + it('should throw an error when test is not true', (): void => { expect( - () => assert(false, 'error thrown') + (): boolean => assert(false, 'error thrown') ).toThrow(/error thrown/); }); - it('should throw an error when message: () => string', () => { + it('should throw an error when message: () => string', (): void => { expect( - () => assert(false, () => 'message from function') + (): boolean => assert(false, (): string => 'message from function') ).toThrow(/message from function/); }); - it('throws a valid constructed ExtError', () => { + it('throws a valid constructed ExtError', (): void => { try { - assert(false, 'error', -666, { some: 'data' }); + assert(false, 'error', -666, 'data'); } catch (error) { expect(error.code).toEqual(-666); - expect(error.data).toEqual({ some: 'data' }); + expect(error.data).toEqual('data'); expect(error.message).toEqual('error'); } }); diff --git a/packages/util/src/assert.ts b/packages/util/src/assert.ts index 8e4890e9c..5fd69493c 100644 --- a/packages/util/src/assert.ts +++ b/packages/util/src/assert.ts @@ -25,7 +25,7 @@ type Falsy = null | undefined | false | 0 | ''; // No NaN type * assert(false, () => 'message'); // ExtError with 'message' * ``` */ -export default function assert (test: Falsy | T, message: string | MessageFn, code: number = ExtError.CODES.ASSERT, data?: any): test is T { +export default function assert (test: Falsy | T, message: string | MessageFn, code: number = ExtError.CODES.ASSERT, data?: string | number): test is T { if (test) { return true; } diff --git a/packages/util/src/assertSingletonPackage.spec.ts b/packages/util/src/assertSingletonPackage.spec.ts index 9fc763c69..99cf2dcdf 100644 --- a/packages/util/src/assertSingletonPackage.spec.ts +++ b/packages/util/src/assertSingletonPackage.spec.ts @@ -4,18 +4,18 @@ import { assertSingletonPackage } from '.'; -describe('assertSingletonPackage', () => { +describe('assertSingletonPackage', (): void => { const NAME = 'assertSingletonPackage'; - it('should not throw the first time', () => { + it('should not throw the first time', (): void => { expect( - () => assertSingletonPackage(NAME) + (): void => assertSingletonPackage(NAME) ).not.toThrow(); }); - it('should throw the second time', () => { + it('should throw the second time', (): void => { expect( - () => assertSingletonPackage(NAME) + (): void => assertSingletonPackage(NAME) ).toThrow(/Multiple versions of assertSingletonPackage detected/); }); }); diff --git a/packages/util/src/assertSingletonPackage.ts b/packages/util/src/assertSingletonPackage.ts index 1daf03fda..78b8897f0 100644 --- a/packages/util/src/assertSingletonPackage.ts +++ b/packages/util/src/assertSingletonPackage.ts @@ -5,15 +5,21 @@ import isUndefined from './is/undefined'; import assert from './assert'; +interface PjsChecks { + __polkadotjs: Record; +} + +type PjsGlobal = NodeJS.Global & PjsChecks; +type PjsWindow = Window & PjsChecks; + /** * @name assertSingletonPackage * @summary Checks that a specific package is only imported once */ export default function assertSingletonPackage (name: string): void { - // tslint:disable-next-line - const _global: any = typeof window !== 'undefined' - ? window - : global; + const _global = typeof window !== 'undefined' + ? window as PjsWindow + : global as PjsGlobal; if (!_global.__polkadotjs) { _global.__polkadotjs = {}; diff --git a/packages/util/src/bn/fromHex.spec.ts b/packages/util/src/bn/fromHex.spec.ts index cd5db3aff..c45839979 100644 --- a/packages/util/src/bn/fromHex.spec.ts +++ b/packages/util/src/bn/fromHex.spec.ts @@ -6,8 +6,8 @@ import isFunction from '../is/function'; import { bnFromHex } from '.'; -describe('bnFromHex', () => { - it('exists as a function', () => { +describe('bnFromHex', (): void => { + it('exists as a function', (): void => { expect( isFunction(bnFromHex) ).toEqual(true); diff --git a/packages/util/src/bn/max.spec.ts b/packages/util/src/bn/max.spec.ts index cf4c16f99..df36c2218 100644 --- a/packages/util/src/bn/max.spec.ts +++ b/packages/util/src/bn/max.spec.ts @@ -6,8 +6,8 @@ import BN from 'bn.js'; import { bnMax } from '.'; -describe('bnMax', () => { - it('finds BN maximum', () => { +describe('bnMax', (): void => { + it('finds BN maximum', (): void => { expect( bnMax(new BN(1), new BN(2), new BN(3)) ).toEqual(new BN(3)); diff --git a/packages/util/src/bn/max.ts b/packages/util/src/bn/max.ts index 06803aa72..e1ece595b 100644 --- a/packages/util/src/bn/max.ts +++ b/packages/util/src/bn/max.ts @@ -19,13 +19,8 @@ import assert from '../assert'; * max([new BN(1), new BN(3), new BN(2)]).toString(); // => '3' * ``` */ -export default function max ( - ...items: BN[] -): BN { - assert( - items && items.length >= 1, - 'Must provide one or more BN arguments' - ); +export default function max (...items: BN[]): BN { + assert(items && items.length >= 1, 'Must provide one or more BN arguments'); - return items.reduce((acc: BN, val: BN) => BN.max(acc, val), items[0]); + return items.reduce((acc: BN, val: BN): BN => BN.max(acc, val), items[0]); } diff --git a/packages/util/src/bn/min.spec.ts b/packages/util/src/bn/min.spec.ts index 158eac90f..e5c63c9b2 100644 --- a/packages/util/src/bn/min.spec.ts +++ b/packages/util/src/bn/min.spec.ts @@ -6,8 +6,8 @@ import BN from 'bn.js'; import { bnMin } from '.'; -describe('bnMin', () => { - it('finds BN minimum', () => { +describe('bnMin', (): void => { + it('finds BN minimum', (): void => { expect( bnMin(new BN(1), new BN(2), new BN(3)) ).toEqual(new BN(1)); diff --git a/packages/util/src/bn/min.ts b/packages/util/src/bn/min.ts index 8773a7db2..5266e68b0 100644 --- a/packages/util/src/bn/min.ts +++ b/packages/util/src/bn/min.ts @@ -19,13 +19,8 @@ import assert from '../assert'; * min([new BN(1), new BN(3), new BN(2)]).toString(); // => '1' * ``` */ -export default function min ( - ...items: BN[] -): BN { - assert( - items && items.length >= 1, - 'Must provide one or more BN arguments' - ); +export default function min (...items: BN[]): BN { + assert(items && items.length >= 1, 'Must provide one or more BN arguments'); - return items.reduce((acc: BN, val: BN) => BN.min(acc, val), items[0]); + return items.reduce((acc: BN, val: BN): BN => BN.min(acc, val), items[0]); } diff --git a/packages/util/src/bn/toBn.spec.ts b/packages/util/src/bn/toBn.spec.ts index 194245485..ad6551464 100644 --- a/packages/util/src/bn/toBn.spec.ts +++ b/packages/util/src/bn/toBn.spec.ts @@ -6,20 +6,20 @@ import BN from 'bn.js'; import { bnToBn } from '.'; -describe('bnToBn', () => { - it('converts null values to 0x00', () => { +describe('bnToBn', (): void => { + it('converts null values to 0x00', (): void => { expect( bnToBn(null) ).toEqual(new BN(0)); }); - it('converts BN values to BN', () => { + it('converts BN values to BN', (): void => { expect( bnToBn(new BN(128)) ).toEqual(new BN(128)); }); - it('converts number values to BN', () => { + it('converts number values to BN', (): void => { expect( bnToBn(128) ).toEqual(new BN(128)); diff --git a/packages/util/src/bn/toHex.spec.ts b/packages/util/src/bn/toHex.spec.ts index a34bc00df..2053d76e8 100644 --- a/packages/util/src/bn/toHex.spec.ts +++ b/packages/util/src/bn/toHex.spec.ts @@ -6,44 +6,44 @@ import BN from 'bn.js'; import { bnToHex } from '.'; -describe('bnToHex', () => { - it('converts null values to 0x00', () => { +describe('bnToHex', (): void => { + it('converts null values to 0x00', (): void => { expect( bnToHex(null) ).toBe('0x00'); }); - it('converts BN values to a prefixed hex representation', () => { + it('converts BN values to a prefixed hex representation', (): void => { expect( bnToHex(new BN(128)) ).toBe('0x80'); }); - it('converts BN values to a prefixed hex representation (bitLength)', () => { + it('converts BN values to a prefixed hex representation (bitLength)', (): void => { expect( bnToHex(new BN(128), 16) ).toBe('0x0080'); }); - it('converts BN values to a prefixed hex representation (LE)', () => { + it('converts BN values to a prefixed hex representation (LE)', (): void => { expect( bnToHex(new BN(128), { bitLength: 16, isLe: true }) ).toBe('0x8000'); }); - it('handles negative numbers', () => { + it('handles negative numbers', (): void => { expect( bnToHex(new BN(-1234), { isNegative: true }) ).toBe('0xfb2e'); }); - it('handles negative numbers (with bitLength)', () => { + it('handles negative numbers (with bitLength)', (): void => { expect( bnToHex(new BN(-1234), { bitLength: 32, isNegative: true }) ).toBe('0xfffffb2e'); }); - it('handles backwards compatibility', () => { + it('handles backwards compatibility', (): void => { expect( bnToHex(new BN(1234), 32) ).toBe( diff --git a/packages/util/src/bn/toU8a.spec.ts b/packages/util/src/bn/toU8a.spec.ts index 998479ef5..0d4febefc 100644 --- a/packages/util/src/bn/toU8a.spec.ts +++ b/packages/util/src/bn/toU8a.spec.ts @@ -6,56 +6,56 @@ import BN from 'bn.js'; import { bnToU8a } from '.'; -describe('bnToU8a', () => { - it('converts null values to 0x00', () => { +describe('bnToU8a', (): void => { + it('converts null values to 0x00', (): void => { expect( bnToU8a(null, -1, false) ).toEqual(new Uint8Array([])); }); - it('converts null values to 0x00000000 (bitLength)', () => { + it('converts null values to 0x00000000 (bitLength)', (): void => { expect( bnToU8a(null, 32, false) ).toEqual(new Uint8Array([0, 0, 0, 0])); }); - it('converts BN values to a prefixed hex representation', () => { + it('converts BN values to a prefixed hex representation', (): void => { expect( bnToU8a(new BN(0x123456), -1, false) ).toEqual(new Uint8Array([0x12, 0x34, 0x56])); }); - it('converts BN values to a prefixed hex representation (bitLength)', () => { + it('converts BN values to a prefixed hex representation (bitLength)', (): void => { expect( bnToU8a(new BN(0x123456), 32, false) ).toEqual(new Uint8Array([0x00, 0x12, 0x34, 0x56])); }); - it('converts using little endian (as set)', () => { + it('converts using little endian (as set)', (): void => { expect( bnToU8a(new BN(0x123456), 32, true) ).toEqual(new Uint8Array([0x56, 0x34, 0x12, 0x00])); }); - it('converts negative numbers', () => { + it('converts negative numbers', (): void => { expect( bnToU8a(new BN(-1234), { isNegative: true }) ).toEqual(new Uint8Array([46, 251])); }); - it('converts negative numbers (BE)', () => { + it('converts negative numbers (BE)', (): void => { expect( bnToU8a(new BN(-1234), { isNegative: true, isLe: false }) ).toEqual(new Uint8Array([251, 46])); }); - it('converts negative numbers (bitLength)', () => { + it('converts negative numbers (bitLength)', (): void => { expect( bnToU8a(new BN(-1234), { isNegative: true, bitLength: 32 }) ).toEqual(new Uint8Array([46, 251, 255, 255])); }); - it('handles backwards compatibility', () => { + it('handles backwards compatibility', (): void => { expect( bnToU8a(new BN(1234), 32, false) ).toEqual( diff --git a/packages/util/src/bn/toU8a.ts b/packages/util/src/bn/toU8a.ts index 1efec8c41..1645f3635 100644 --- a/packages/util/src/bn/toU8a.ts +++ b/packages/util/src/bn/toU8a.ts @@ -26,9 +26,9 @@ interface Options extends ToBnOptions { * bnToU8a(new BN(0x1234)); // => [0x12, 0x34] * ``` */ -export default function bnToU8a (value: BN | number | null, options?: Options): Uint8Array; -export default function bnToU8a (value: BN | number | null, bitLength?: number, isLe?: boolean): Uint8Array; -export default function bnToU8a ( +function bnToU8a (value: BN | number | null, options?: Options): Uint8Array; +function bnToU8a (value: BN | number | null, bitLength?: number, isLe?: boolean): Uint8Array; +function bnToU8a ( value: BN | number | null, arg1: number | Options = { bitLength: -1, isLe: true, isNegative: false }, arg2?: boolean @@ -41,9 +41,9 @@ export default function bnToU8a ( }; const valueBn = bnToBn(value); - let byteLength = _options.bitLength === -1 + const byteLength = _options.bitLength === -1 ? Math.ceil(valueBn.bitLength() / 8) - : Math.ceil(_options.bitLength! / 8); + : Math.ceil((_options.bitLength || 0) / 8); if (!value) { return _options.bitLength === -1 @@ -61,3 +61,5 @@ export default function bnToU8a ( return output; } + +export default bnToU8a; diff --git a/packages/util/src/buffer/toU8a.spec.ts b/packages/util/src/buffer/toU8a.spec.ts index 1f6f991e1..f90794f17 100644 --- a/packages/util/src/buffer/toU8a.spec.ts +++ b/packages/util/src/buffer/toU8a.spec.ts @@ -4,14 +4,14 @@ import { bufferToU8a } from '.'; -describe('bufferToU8a', () => { - it('returns an empty buffer when null provided', () => { +describe('bufferToU8a', (): void => { + it('returns an empty buffer when null provided', (): void => { expect( bufferToU8a(null) ).toEqual(new Uint8Array([])); }); - it('returns a Uint8Buffer with the correct values', () => { + it('returns a Uint8Buffer with the correct values', (): void => { expect( bufferToU8a(Buffer.from([128, 0, 10])) ).toEqual(new Uint8Array([128, 0, 10])); diff --git a/packages/util/src/compact/addLength.spec.ts b/packages/util/src/compact/addLength.spec.ts index 2d3f5ebd4..f1dee5fb0 100644 --- a/packages/util/src/compact/addLength.spec.ts +++ b/packages/util/src/compact/addLength.spec.ts @@ -4,8 +4,8 @@ import compactAddLength from './addLength'; -describe('compactAddLength', () => { - it('correctly adds the length prefix', () => { +describe('compactAddLength', (): void => { + it('correctly adds the length prefix', (): void => { expect( compactAddLength(Uint8Array.from([12, 13])) ).toEqual(Uint8Array.from([2 << 2, 12, 13])); diff --git a/packages/util/src/compact/fromU8a.spec.ts b/packages/util/src/compact/fromU8a.spec.ts index 52d264252..ec8f9c49a 100644 --- a/packages/util/src/compact/fromU8a.spec.ts +++ b/packages/util/src/compact/fromU8a.spec.ts @@ -7,38 +7,38 @@ import BN from 'bn.js'; import hexToU8a from '../hex/toU8a'; import compactFromU8a from './fromU8a'; -describe('compactFromU8a', () => { - it('decoded u8 value', () => { +describe('compactFromU8a', (): void => { + it('decoded u8 value', (): void => { expect( compactFromU8a(new Uint8Array([0b11111100])) ).toEqual([1, new BN(63)]); }); - it('decodes from same u16 encoded value', () => { + it('decodes from same u16 encoded value', (): void => { expect( compactFromU8a(new Uint8Array([0b11111101, 0b00000111]), 32) ).toEqual([2, new BN(511)]); }); - it('decodes from same u32 encoded value (short)', () => { + it('decodes from same u32 encoded value (short)', (): void => { expect( compactFromU8a(new Uint8Array([254, 255, 3, 0]), 32) ).toEqual([4, new BN(0xffff)]); }); - it('decodes from same u32 encoded value (full)', () => { + it('decodes from same u32 encoded value (full)', (): void => { expect( compactFromU8a(new Uint8Array([3, 249, 255, 255, 255]), 32) ).toEqual([5, new BN(0xfffffff9)]); }); - it('decodes from same u32 as u64 encoded value (full, default)', () => { + it('decodes from same u32 as u64 encoded value (full, default)', (): void => { expect( compactFromU8a(new Uint8Array([3 + ((4 - 4) << 2), 249, 255, 255, 255]), 64) ).toEqual([5, new BN(0xfffffff9)]); }); - it('decodes an actual value', () => { + it('decodes an actual value', (): void => { expect( compactFromU8a( hexToU8a('0x0b00407a10f35a') diff --git a/packages/util/src/compact/fromU8a.ts b/packages/util/src/compact/fromU8a.ts index 6be6e9a2b..58e6846de 100644 --- a/packages/util/src/compact/fromU8a.ts +++ b/packages/util/src/compact/fromU8a.ts @@ -23,6 +23,7 @@ import { DEFAULT_BITLENGTH } from './defaults'; * console.log('value offset=', offset, 'length=', length); // 4, 0xffff * ``` */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars export default function compactFromU8a (_input: Uint8Array | string, bitLength: BitLength = DEFAULT_BITLENGTH): [number, BN] { const input = u8aToU8a(_input); const flag = input[0] & 0b11; diff --git a/packages/util/src/compact/stripLength.spec.ts b/packages/util/src/compact/stripLength.spec.ts index d00c8ed7f..98d5d1986 100644 --- a/packages/util/src/compact/stripLength.spec.ts +++ b/packages/util/src/compact/stripLength.spec.ts @@ -4,8 +4,8 @@ import compactStripLength from './stripLength'; -describe('compactStripLength', () => { - it('correctly removes the length prefix', () => { +describe('compactStripLength', (): void => { + it('correctly removes the length prefix', (): void => { expect( compactStripLength(Uint8Array.from([2 << 2, 12, 13])) ).toEqual([ diff --git a/packages/util/src/compact/toU8a.spec.ts b/packages/util/src/compact/toU8a.spec.ts index 75da1ab4c..55902f359 100644 --- a/packages/util/src/compact/toU8a.spec.ts +++ b/packages/util/src/compact/toU8a.spec.ts @@ -6,8 +6,8 @@ import BN from 'bn.js'; import compactToU8a from './toU8a'; -describe('encode', () => { - it('encodes short u8', () => { +describe('encode', (): void => { + it('encodes short u8', (): void => { expect( compactToU8a(18) ).toEqual( @@ -15,7 +15,7 @@ describe('encode', () => { ); }); - it('encodes max u8 values', () => { + it('encodes max u8 values', (): void => { expect( compactToU8a(new BN(63)) ).toEqual( @@ -23,7 +23,7 @@ describe('encode', () => { ); }); - it('encodes basic u16 value', () => { + it('encodes basic u16 value', (): void => { expect( compactToU8a(511) ).toEqual( @@ -31,7 +31,7 @@ describe('encode', () => { ); }); - it('encodes basic u16 (not at edge)', () => { + it('encodes basic u16 (not at edge)', (): void => { expect( compactToU8a(111) ).toEqual( @@ -39,7 +39,7 @@ describe('encode', () => { ); }); - it('encodes basic u32 values (< 2^30)', () => { + it('encodes basic u32 values (< 2^30)', (): void => { expect( compactToU8a(0x1fff) ).toEqual( @@ -47,7 +47,7 @@ describe('encode', () => { ); }); - it('encodes basic u32 values (short)', () => { + it('encodes basic u32 values (short)', (): void => { expect( compactToU8a(0xffff) ).toEqual( @@ -55,7 +55,7 @@ describe('encode', () => { ); }); - it('encodes basic u32 values (full)', () => { + it('encodes basic u32 values (full)', (): void => { expect( compactToU8a(0xfffffff9) ).toEqual( @@ -63,7 +63,7 @@ describe('encode', () => { ); }); - it('encodes a large value', () => { + it('encodes a large value', (): void => { expect( compactToU8a( new BN('00005af3107a4000', 16) @@ -73,7 +73,7 @@ describe('encode', () => { ); }); - describe('from Rust', () => { + describe('from Rust', (): void => { // Copied from https://github.com/paritytech/parity-codec/blob/master/src/codec.rs const testCases = [ { value: new BN('0'), expected: '00' }, @@ -92,19 +92,18 @@ describe('encode', () => { { value: new BN(`${1}${'0'.repeat(64)}`, 2).subn(1), expected: '13 ff ff ff ff ff ff ff ff' } ]; - function testEncode (value: BN, expected: string) { - it(`encodes ${value.toString()}`, () => { + function testEncode (value: BN, expected: string): void { + it(`encodes ${value.toString()}`, (): void => { expect( compactToU8a(value) ).toEqual( Uint8Array.from( - expected.split(' ').map(s => parseInt(s, 16)) + expected.split(' ').map((s): number => parseInt(s, 16)) ) ); }); } - testCases.forEach((({ value, expected }) => testEncode(value, expected))); + testCases.forEach(({ value, expected }): void => testEncode(value, expected)); }); - }); diff --git a/packages/util/src/ext/error.spec.ts b/packages/util/src/ext/error.spec.ts index e2402025f..fc65721d7 100644 --- a/packages/util/src/ext/error.spec.ts +++ b/packages/util/src/ext/error.spec.ts @@ -5,9 +5,9 @@ import isError from '../is/error'; import { ExtError } from '.'; -describe('ExtError', () => { - describe('constructor', () => { - it('constructs an Error that is still an Error', () => { +describe('ExtError', (): void => { + describe('constructor', (): void => { + it('constructs an Error that is still an Error', (): void => { expect( isError( new ExtError() @@ -16,41 +16,41 @@ describe('ExtError', () => { }); }); - describe('static', () => { - it('exposes the .CODES as a static', () => { + describe('static', (): void => { + it('exposes the .CODES as a static', (): void => { expect( Object.keys(ExtError.CODES) ).not.toEqual(0); }); }); - describe('constructor properties', () => { - it('sets the .message property', () => { + describe('constructor properties', (): void => { + it('sets the .message property', (): void => { expect( new ExtError('test message').message ).toEqual('test message'); }); - it("sets the .message to '' when not set", () => { + it("sets the .message to '' when not set", (): void => { expect( new ExtError().message ).toEqual(''); }); - it('sets the .code property', () => { + it('sets the .code property', (): void => { expect( new ExtError('test message', 1234).code ).toEqual(1234); }); - it('sets the .code to UKNOWN when not set', () => { + it('sets the .code to UKNOWN when not set', (): void => { expect( new ExtError('test message').code ).toEqual(ExtError.CODES.UNKNOWN); }); - it('sets the .data property', () => { - const data = { some: { value: 'here' } }; + it('sets the .data property', (): void => { + const data = 'here'; expect( new ExtError('test message', 1234, data).data @@ -58,16 +58,17 @@ describe('ExtError', () => { }); }); - describe('stack traces', () => { - let captureStackTrace: any; + describe('stack traces', (): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let captureStackTrace: (targetObject: Record, constructorOpt?: Function | undefined) => void; - beforeEach(() => { + beforeEach((): void => { captureStackTrace = Error.captureStackTrace; - Error.captureStackTrace = function (error) { + Error.captureStackTrace = function (error): void { Object.defineProperty(error, 'stack', { configurable: true, - get: function getStack () { + get: function getStack (): string { const value = 'some stack returned'; Object.defineProperty(this, 'stack', { value }); @@ -78,18 +79,19 @@ describe('ExtError', () => { }; }); - afterEach(() => { + afterEach((): void => { Error.captureStackTrace = captureStackTrace; }); - it('captures via captureStackTrace when available', () => { + it('captures via captureStackTrace when available', (): void => { expect( new ExtError().stack ).toEqual('some stack returned'); }); - it('captures via stack when captureStackTrace not available', () => { - Error.captureStackTrace = null as any; // grrr + it('captures via stack when captureStackTrace not available', (): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Error.captureStackTrace = null as any; expect( new ExtError().stack.length diff --git a/packages/util/src/ext/error.ts b/packages/util/src/ext/error.ts index 3ef29da40..9adc04e0f 100644 --- a/packages/util/src/ext/error.ts +++ b/packages/util/src/ext/error.ts @@ -8,7 +8,7 @@ import isFunction from '../is/function'; const UNKNOWN = -99999; -function extend (that: any, name: string, value: any): void { +function extend (that: ExtError, name: string, value?: string | number): void { Object.defineProperty(that, name, { configurable: true, enumerable: false, @@ -32,17 +32,21 @@ function extend (that: any, name: string, value: any): void { */ export default class ExtError extends Error implements ExtErrorInterface { // @ts-ignore we are assigning it via extend - code: number; - // @ts-ignore we are assigning it via extend - data: any; - // @ts-ignore we are assigning it via extend - message: string; - // @ts-ignore we are assigning it via extend - name: string; - // @ts-ignore we are assigning it via extend - stack: string; + public code: number; - constructor (message: string = '', code: number = UNKNOWN, data?: any) { + // @ts-ignore we are assigning it via extend + public data: number | string | undefined; + + // @ts-ignore we are assigning it via extend + public message: string; + // @ts-ignore we are assigning it via extend + + public name: string; + + // @ts-ignore we are assigning it via extend + public stack: string; + + public constructor (message: string = '', code: number = UNKNOWN, data?: number | string) { super(); extend(this, 'message', String(message)); @@ -57,7 +61,7 @@ export default class ExtError extends Error implements ExtErrorInterface { } } - static CODES = { + public static CODES = { ASSERT: -90009, UNKNOWN, INVALID_JSONRPC: -99998, diff --git a/packages/util/src/format/formatBalance.spec.ts b/packages/util/src/format/formatBalance.spec.ts index b4f496635..4d9630e0c 100644 --- a/packages/util/src/format/formatBalance.spec.ts +++ b/packages/util/src/format/formatBalance.spec.ts @@ -6,105 +6,105 @@ import BN from 'bn.js'; import formatBalance from './formatBalance'; -describe('formatBalance', () => { +describe('formatBalance', (): void => { const TESTVAL = new BN('123456789000'); - it('does not allow float inputs', () => { + it('does not allow float inputs', (): void => { expect( - () => formatBalance(0.01234) + (): string => formatBalance(0.01234) ).toThrow(/integer input value/); }); - it('formats empty to 0', () => { + it('formats empty to 0', (): void => { expect(formatBalance()).toEqual('0'); expect(formatBalance('0')).toEqual('0'); }); - it('formats 123,456,789,000 (decimals=15)', () => { + it('formats 123,456,789,000 (decimals=15)', (): void => { expect( formatBalance(TESTVAL, true, 15) ).toEqual('123.456µ Unit'); }); - it('formats 123,456,789,000 (decimals=12)', () => { + it('formats 123,456,789,000 (decimals=12)', (): void => { expect( formatBalance(TESTVAL, true, 12) ).toEqual('123.456m Unit'); }); - it('formats 123,456,789,000 (decimals=12, no SI)', () => { + it('formats 123,456,789,000 (decimals=12, no SI)', (): void => { expect( formatBalance(TESTVAL, false, 12) ).toEqual('123.456'); }); - it('formats 123,456,789,000 (decimals=9)', () => { + it('formats 123,456,789,000 (decimals=9)', (): void => { expect( formatBalance(TESTVAL, true, 9) ).toEqual('123.456 Unit'); }); - it('formats 123,456,789,000 (decimals=6)', () => { + it('formats 123,456,789,000 (decimals=6)', (): void => { expect( formatBalance(TESTVAL, true, 6) ).toEqual('123.456k Unit'); }); - it('formats 123,456,789,000 * 10 (decimals=12)', () => { + it('formats 123,456,789,000 * 10 (decimals=12)', (): void => { expect( formatBalance(TESTVAL.muln(10), true, 12) ).toEqual('1.234 Unit'); }); - it('formats 123,456,789,000 * 100 (decimals=12)', () => { + it('formats 123,456,789,000 * 100 (decimals=12)', (): void => { expect( formatBalance(TESTVAL.muln(100), true, 12) ).toEqual('12.345 Unit'); }); - it('formats 123,456,789,000 * 1000 (decimals=12)', () => { + it('formats 123,456,789,000 * 1000 (decimals=12)', (): void => { expect( formatBalance(TESTVAL.muln(1000), true, 12) ).toEqual('123.456 Unit'); }); - it('formats -123,456,789,000 (decimals=15)', () => { + it('formats -123,456,789,000 (decimals=15)', (): void => { expect( formatBalance(new BN('-123456789000'), true, 15) ).toEqual('-123.456µ Unit'); }); - describe('calcSi', () => { - it('exposes calcSi on formatBalance', () => { + describe('calcSi', (): void => { + it('exposes calcSi on formatBalance', (): void => { expect( formatBalance.calcSi('12345').value ).toEqual('k'); }); }); - describe('findSi', () => { - it('finds the SI value', () => { + describe('findSi', (): void => { + it('finds the SI value', (): void => { expect( formatBalance.findSi('k') ).toEqual({ power: 3, value: 'k', text: 'Kilo' }); }); - it('returns default on not found', () => { + it('returns default on not found', (): void => { expect( formatBalance.findSi('blah') ).toEqual({ power: 0, value: '-', text: 'Unit' }); }); }); - describe('defaults', () => { - it('returns defaults', () => { + describe('defaults', (): void => { + it('returns defaults', (): void => { expect(formatBalance.getDefaults()).toEqual({ decimals: 0, unit: 'Unit' }); }); - it('formats 123,456,789,000 (defaultDecimals=12)', () => { + it('formats 123,456,789,000 (defaultDecimals=12)', (): void => { formatBalance.setDefaults({ decimals: 12 }); expect( @@ -112,7 +112,7 @@ describe('formatBalance', () => { ).toEqual('123.456m Unit'); }); - it('formats 123,456,789,000 (defaultUnit=TEST)', () => { + it('formats 123,456,789,000 (defaultUnit=TEST)', (): void => { formatBalance.setDefaults({ unit: 'TEST' }); expect( @@ -121,7 +121,7 @@ describe('formatBalance', () => { }); }); - it('returns options for dropdown', () => { + it('returns options for dropdown', (): void => { formatBalance.setDefaults({ decimals: 0, unit: 'TEST' }); expect( diff --git a/packages/util/src/format/formatBalance.ts b/packages/util/src/format/formatBalance.ts index f25864bb6..73300973d 100644 --- a/packages/util/src/format/formatBalance.ts +++ b/packages/util/src/format/formatBalance.ts @@ -9,17 +9,17 @@ import isUndefined from '../is/undefined'; import formatDecimal from './formatDecimal'; import { SI, SI_MID, SiDef, calcSi, findSi } from './si'; -type Defaults = { - decimals: number, - unit: string -}; +interface Defaults { + decimals: number; + unit: string; +} interface BalanceFormatter { (input?: number | string | BN, withSi?: boolean, decimals?: number): string; calcSi (text: string, decimals?: number): SiDef; findSi (type: string): SiDef; getDefaults (): Defaults; - getOptions (decimals?: number): Array; + getOptions (decimals?: number): SiDef[]; setDefaults (defaults: Partial): void; } @@ -79,8 +79,8 @@ formatBalance.getDefaults = (): Defaults => { }; // get allowable options to display in a dropdown -formatBalance.getOptions = (decimals: number = defaultDecimals): Array => { - return SI.filter(({ power }) => +formatBalance.getOptions = (decimals: number = defaultDecimals): SiDef[] => { + return SI.filter(({ power }): boolean => power < 0 ? (decimals + power) >= 0 : true diff --git a/packages/util/src/format/formatDecimal.spec.ts b/packages/util/src/format/formatDecimal.spec.ts index 9ac7e437b..2be77c9d1 100644 --- a/packages/util/src/format/formatDecimal.spec.ts +++ b/packages/util/src/format/formatDecimal.spec.ts @@ -4,24 +4,24 @@ import formatDecimal from './formatDecimal'; -describe('formatDecimal', () => { - it('formats decimals in number groupings', () => { +describe('formatDecimal', (): void => { + it('formats decimals in number groupings', (): void => { expect(formatDecimal('12345')).toEqual('12,345'); }); - it('formats decimal-only in number groupings', () => { + it('formats decimal-only in number groupings', (): void => { expect(formatDecimal('test6789')).toEqual('6,789'); }); - it('returns input for non-decimal', () => { + it('returns input for non-decimal', (): void => { expect(formatDecimal('test')).toEqual('test'); }); - it('returns non-sensical negative text', () => { + it('returns non-sensical negative text', (): void => { expect(formatDecimal('-test')).toEqual('-test'); }); - it('formats negative numbers', () => { + it('formats negative numbers', (): void => { expect(formatDecimal('-123456')).toEqual('-123,456'); }); }); diff --git a/packages/util/src/format/formatElapsed.spec.ts b/packages/util/src/format/formatElapsed.spec.ts index 8ec261b75..e22431e59 100644 --- a/packages/util/src/format/formatElapsed.spec.ts +++ b/packages/util/src/format/formatElapsed.spec.ts @@ -2,41 +2,42 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { Compact } from './types'; - import BN from 'bn.js'; import formatElapsed from './formatElapsed'; -describe('formatElapsed', () => { +describe('formatElapsed', (): void => { const start = 12345678; const now = new Date(12345678); - it('formats a Date', () => { + it('formats a Date', (): void => { expect( formatElapsed(now, new Date(start + 9700)) ).toEqual('9.7s'); }); - it('formats a BN', () => { + it('formats a BN', (): void => { expect( formatElapsed(now, new BN(start + 42700)) ).toEqual('42s'); }); - it('formats a Compact', () => { + it('formats a Compact', (): void => { expect( - formatElapsed(now, { unwrap: () => new BN(start + (5.3 * 60000)) } as Compact) + formatElapsed(now, { + toBn: (): BN => new BN(0), + unwrap: (): BN => new BN(start + (5.3 * 60000)) + }) ).toEqual('5m'); }); - it('formats a number', () => { + it('formats a number', (): void => { expect( formatElapsed(now, start + (42 * 60 * 60000)) ).toEqual('42h'); }); - it('formats defaults', () => { + it('formats defaults', (): void => { expect( formatElapsed() ).toEqual('0.0s'); diff --git a/packages/util/src/format/formatElapsed.ts b/packages/util/src/format/formatElapsed.ts index 18ff900f2..dda7d1e40 100644 --- a/packages/util/src/format/formatElapsed.ts +++ b/packages/util/src/format/formatElapsed.ts @@ -8,7 +8,7 @@ import BN from 'bn.js'; function getValue (value?: BN | Compact | Date | number | null): number { if (value) { - if ((value as any).unwrap) { + if ((value as Compact).unwrap) { return getValue((value as Compact).unwrap()); } else if (value instanceof Date) { return getValue(value.getTime()); diff --git a/packages/util/src/format/formatNumber.spec.ts b/packages/util/src/format/formatNumber.spec.ts index 775f1b2e7..43d2ecb61 100644 --- a/packages/util/src/format/formatNumber.spec.ts +++ b/packages/util/src/format/formatNumber.spec.ts @@ -2,34 +2,35 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import { Compact } from './types'; - import BN from 'bn.js'; import formatNumber from './formatNumber'; -describe('formatNumber', () => { - it('formats empty', () => { +describe('formatNumber', (): void => { + it('formats empty', (): void => { expect( formatNumber() ).toEqual('0'); }); - it('formats negative numbers', () => { + it('formats negative numbers', (): void => { expect( formatNumber(-123456) ).toEqual('-123,456'); }); - it('formats BN numbers', () => { + it('formats BN numbers', (): void => { expect( formatNumber(new BN(12345)) ).toEqual('12,345'); }); - it('formats Compact', () => { + it('formats Compact', (): void => { expect( - formatNumber({ toBn: () => new BN(12345) } as Compact) + formatNumber({ + toBn: (): BN => new BN(12345), + unwrap: (): BN => new BN(0) + }) ).toEqual('12,345'); }); }); diff --git a/packages/util/src/format/formatNumber.ts b/packages/util/src/format/formatNumber.ts index 710021903..79677f12f 100644 --- a/packages/util/src/format/formatNumber.ts +++ b/packages/util/src/format/formatNumber.ts @@ -14,7 +14,7 @@ export default function formatNumber (_value?: Compact | BN | number | null): st return '0'; } - const value = (_value as any).toBn + const value = (_value as Compact).toBn ? (_value as Compact).toBn() : bnToBn(_value as BN); diff --git a/packages/util/src/format/si.ts b/packages/util/src/format/si.ts index 0f0b4763f..29c091fa5 100644 --- a/packages/util/src/format/si.ts +++ b/packages/util/src/format/si.ts @@ -2,15 +2,15 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -export type SiDef = { - power: number, - text: string, - value: string -}; +export interface SiDef { + power: number; + text: string; + value: string; +} export const SI_MID = 8; -export const SI: Array = [ +export const SI: SiDef[] = [ { power: -24, value: 'y', text: 'yocto' }, { power: -21, value: 'z', text: 'zepto' }, { power: -18, value: 'a', text: 'atto' }, diff --git a/packages/util/src/hex/addPrefix.spec.ts b/packages/util/src/hex/addPrefix.spec.ts index fda83d2a0..22ecd3526 100644 --- a/packages/util/src/hex/addPrefix.spec.ts +++ b/packages/util/src/hex/addPrefix.spec.ts @@ -4,26 +4,26 @@ import { hexAddPrefix } from '.'; -describe('hexAddPrefix', () => { - it('does not add when prefix is available', () => { +describe('hexAddPrefix', (): void => { + it('does not add when prefix is available', (): void => { expect( hexAddPrefix('0x0123') ).toEqual('0x0123'); }); - it('adds the prefix when it is not available', () => { + it('adds the prefix when it is not available', (): void => { expect( hexAddPrefix('0123') ).toEqual('0x0123'); }); - it('adds extra 0 when length % 2 === 1', () => { + it('adds extra 0 when length % 2 === 1', (): void => { expect( hexAddPrefix('123') ).toEqual('0x0123'); }); - it('returns null as 0x', () => { + it('returns null as 0x', (): void => { expect( hexAddPrefix(null) ).toEqual('0x'); diff --git a/packages/util/src/hex/fixLength.spec.ts b/packages/util/src/hex/fixLength.spec.ts index 93bc99aeb..c3afa3327 100644 --- a/packages/util/src/hex/fixLength.spec.ts +++ b/packages/util/src/hex/fixLength.spec.ts @@ -4,38 +4,38 @@ import { hexFixLength } from '.'; -describe('hexFixLength', () => { - it('returns bitLength === -1 as-is', () => { +describe('hexFixLength', (): void => { + it('returns bitLength === -1 as-is', (): void => { expect( hexFixLength('0x12345678') ).toEqual('0x12345678'); }); - it('returns bitLength === -1 as-is (adding missing 0)', () => { + it('returns bitLength === -1 as-is (adding missing 0)', (): void => { expect( hexFixLength('0x1234567') ).toEqual('0x01234567'); }); - it('does not change when bitlength === length', () => { + it('does not change when bitlength === length', (): void => { expect( hexFixLength('0x12345678', 32) ).toEqual('0x12345678'); }); - it('trims values when bitLength > length', () => { + it('trims values when bitLength > length', (): void => { expect( hexFixLength('0x12345678', 16) ).toEqual('0x5678'); }); - it('returns as-is when bitLength < length', () => { + it('returns as-is when bitLength < length', (): void => { expect( hexFixLength('0x1234', 32) ).toEqual('0x1234'); }); - it('adds zeros when bitLength < length (withPadded)', () => { + it('adds zeros when bitLength < length (withPadded)', (): void => { expect( hexFixLength('0x1234', 32, true) ).toEqual('0x00001234'); diff --git a/packages/util/src/hex/hasPrefix.spec.ts b/packages/util/src/hex/hasPrefix.spec.ts index bb10a86a9..2693f181b 100644 --- a/packages/util/src/hex/hasPrefix.spec.ts +++ b/packages/util/src/hex/hasPrefix.spec.ts @@ -4,27 +4,28 @@ import { hexHasPrefix } from '.'; -describe('hexHasPrefix', () => { - it('returns true when hex prefix is found', () => { +describe('hexHasPrefix', (): void => { + it('returns true when hex prefix is found', (): void => { expect( hexHasPrefix('0x123') ).toEqual(true); }); - it('returns false when no prefix attached', () => { + it('returns false when no prefix attached', (): void => { expect( hexHasPrefix('123') ).toEqual(false); }); - it('returns false when null value supplied', () => { + it('returns false when null value supplied', (): void => { expect( hexHasPrefix(null) ).toEqual(false); }); - it('returns false when non-string value supplied', () => { + it('returns false when non-string value supplied', (): void => { expect( + // eslint-disable-next-line @typescript-eslint/no-explicit-any hexHasPrefix(false as any) ).toEqual(false); }); diff --git a/packages/util/src/hex/stripPrefix.spec.ts b/packages/util/src/hex/stripPrefix.spec.ts index 46aca5155..9a67feae6 100644 --- a/packages/util/src/hex/stripPrefix.spec.ts +++ b/packages/util/src/hex/stripPrefix.spec.ts @@ -4,28 +4,28 @@ import { hexStripPrefix } from '.'; -describe('hexStripPrefix', () => { - it('returns an empty string when null value supplied', () => { +describe('hexStripPrefix', (): void => { + it('returns an empty string when null value supplied', (): void => { expect( hexStripPrefix(null) ).toEqual(''); }); - it('strips the prefix from hex strings', () => { + it('strips the prefix from hex strings', (): void => { expect( hexStripPrefix('0x1223') ).toEqual('1223'); }); - it('returns un-prefixed hex as-is', () => { + it('returns un-prefixed hex as-is', (): void => { expect( hexStripPrefix('abcd1223') ).toEqual('abcd1223'); }); - it('throws when invalid hex', () => { + it('throws when invalid hex', (): void => { expect( - () => hexStripPrefix('0x0x01ab') + (): string => hexStripPrefix('0x0x01ab') ).toThrow(/Invalid hex/); }); }); diff --git a/packages/util/src/hex/toBn.spec.ts b/packages/util/src/hex/toBn.spec.ts index 41f4cead1..d3cbc50bb 100644 --- a/packages/util/src/hex/toBn.spec.ts +++ b/packages/util/src/hex/toBn.spec.ts @@ -4,68 +4,68 @@ import { hexToBn } from '.'; -describe('hexToBn', () => { - it('converts prefixed hex values to BN', () => { +describe('hexToBn', (): void => { + it('converts prefixed hex values to BN', (): void => { expect( hexToBn(0x81).toString(16) ).toBe('81'); }); - it('converts null values to BN(0)', () => { + it('converts null values to BN(0)', (): void => { expect( hexToBn(null).toNumber() ).toBe(0); }); - it('converts 0x values to BN(0)', () => { + it('converts 0x values to BN(0)', (): void => { expect( hexToBn('0x').toNumber() ).toBe(0); }); - it('should convert with Big Endian by default', () => { + it('should convert with Big Endian by default', (): void => { expect( hexToBn('0x0100').toNumber() ).toBe(256); }); - it('converts 0x values to BN(0) (LE)', () => { + it('converts 0x values to BN(0) (LE)', (): void => { expect( hexToBn('0x', { isLe: true }).toNumber() ).toBe(0); }); - it('converts little-endian', () => { + it('converts little-endian', (): void => { expect( hexToBn('0x4500000000000000', { isLe: true }).toNumber() ).toBe(69); }); - it('handles negative numbers (LE)', () => { + it('handles negative numbers (LE)', (): void => { expect( hexToBn('0x2efb', { isLe: true, isNegative: true }).toNumber() ).toBe(-1234); }); - it('handles negative numbers (BE)', () => { + it('handles negative numbers (BE)', (): void => { expect( hexToBn('0xfb2e', { isLe: false, isNegative: true }).toNumber() ).toBe(-1234); }); - it('handles starting zeros correctly (BE)', () => { + it('handles starting zeros correctly (BE)', (): void => { expect( hexToBn('0x0000000000000100', { isLe: false }).toNumber() ).toBe(256); }); - it('handles starting zeros correctly (LE)', () => { + it('handles starting zeros correctly (LE)', (): void => { expect( hexToBn('0x0001000000000000', { isLe: true }).toNumber() ).toBe(256); }); - it('handles backwards compatibility', () => { + it('handles backwards compatibility', (): void => { expect( hexToBn('0x0001000000000000', false).eq( hexToBn('0x0001000000000000', { isLe: false }) diff --git a/packages/util/src/hex/toNumber.spec.ts b/packages/util/src/hex/toNumber.spec.ts index 5e67dfbd1..02d632d96 100644 --- a/packages/util/src/hex/toNumber.spec.ts +++ b/packages/util/src/hex/toNumber.spec.ts @@ -4,14 +4,14 @@ import { hexToNumber } from '.'; -describe('hexToNumber', () => { - it('converts an empty to NaN', () => { +describe('hexToNumber', (): void => { + it('converts an empty to NaN', (): void => { expect( hexToNumber() ).toEqual(NaN); }); - it('converts to a number from hex', () => { + it('converts to a number from hex', (): void => { expect( hexToNumber('0x1234') ).toEqual(0x1234); diff --git a/packages/util/src/hex/toU8a.spec.ts b/packages/util/src/hex/toU8a.spec.ts index f43b88af7..8bc6887c4 100644 --- a/packages/util/src/hex/toU8a.spec.ts +++ b/packages/util/src/hex/toU8a.spec.ts @@ -4,14 +4,14 @@ import { hexToU8a } from '.'; -describe('hexToU8a', () => { - it('returns an empty Uint8Array when null provided', () => { +describe('hexToU8a', (): void => { + it('returns an empty Uint8Array when null provided', (): void => { expect( hexToU8a(null) ).toHaveLength(0); }); - it('returns a Uint8Array with the correct values', () => { + it('returns a Uint8Array with the correct values', (): void => { expect( hexToU8a('0x80000a') ).toEqual( @@ -19,7 +19,7 @@ describe('hexToU8a', () => { ); }); - it('returns a Uint8Array with the correct values (bitLengfth)', () => { + it('returns a Uint8Array with the correct values (bitLengfth)', (): void => { expect( hexToU8a('0x80000a', 32) ).toEqual( @@ -27,9 +27,9 @@ describe('hexToU8a', () => { ); }); - it('fails when non-hex value provided', () => { + it('fails when non-hex value provided', (): void => { expect( - () => hexToU8a('notahex') + (): Uint8Array => hexToU8a('notahex') ).toThrow(/hex value to convert/); }); }); diff --git a/packages/util/src/index.spec.ts b/packages/util/src/index.spec.ts index 2ae6940ea..39a40d201 100644 --- a/packages/util/src/index.spec.ts +++ b/packages/util/src/index.spec.ts @@ -4,8 +4,8 @@ import { assert } from '.'; -describe('index', () => { - it('exports ok', () => { +describe('index', (): void => { + it('exports ok', (): void => { expect(assert).toBeDefined(); }); }); diff --git a/packages/util/src/is/bn.spec.ts b/packages/util/src/is/bn.spec.ts index 3bfc85ea2..f4ba66901 100644 --- a/packages/util/src/is/bn.spec.ts +++ b/packages/util/src/is/bn.spec.ts @@ -6,14 +6,14 @@ import BN from 'bn.js'; import { isBn } from '.'; -describe('isBN', () => { - it('returns true when a BN value', () => { +describe('isBN', (): void => { + it('returns true when a BN value', (): void => { expect( isBn(new BN(123)) ).toEqual(true); }); - it('returns false on non-BN values', () => { + it('returns false on non-BN values', (): void => { expect( isBn(0) ).toEqual(false); diff --git a/packages/util/src/is/bn.ts b/packages/util/src/is/bn.ts index d24b5af1e..f00b13555 100644 --- a/packages/util/src/is/bn.ts +++ b/packages/util/src/is/bn.ts @@ -19,6 +19,7 @@ import BN from 'bn.js'; * console.log('isBn', isBn(new BN(1))); // => true * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isBn (value: any): value is BN { return BN.isBN(value); } diff --git a/packages/util/src/is/boolean.spec.ts b/packages/util/src/is/boolean.spec.ts index 914d8ff7d..414746fea 100644 --- a/packages/util/src/is/boolean.spec.ts +++ b/packages/util/src/is/boolean.spec.ts @@ -4,20 +4,20 @@ import { isBoolean } from '.'; -describe('isBoolean', () => { - it('returns true on false', () => { +describe('isBoolean', (): void => { + it('returns true on false', (): void => { expect( isBoolean(false) ).toEqual(true); }); - it('returns true on true', () => { + it('returns true on true', (): void => { expect( isBoolean(true) ).toEqual(true); }); - it('returns false on invalid booleans', () => { + it('returns false on invalid booleans', (): void => { expect( isBoolean('notABool') ).toEqual(false); diff --git a/packages/util/src/is/boolean.ts b/packages/util/src/is/boolean.ts index e2595d4c3..7fdb88bc4 100644 --- a/packages/util/src/is/boolean.ts +++ b/packages/util/src/is/boolean.ts @@ -16,6 +16,7 @@ * isBoolean(false); // => true * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isBoolean (value: any): value is boolean { return typeof value === 'boolean'; } diff --git a/packages/util/src/is/buffer.spec.ts b/packages/util/src/is/buffer.spec.ts index 670404481..f31f6c06e 100644 --- a/packages/util/src/is/buffer.spec.ts +++ b/packages/util/src/is/buffer.spec.ts @@ -4,14 +4,14 @@ import { isBuffer } from '.'; -describe('isBuffer', () => { - it('returns true when a Buffer value', () => { +describe('isBuffer', (): void => { + it('returns true when a Buffer value', (): void => { expect( isBuffer(Buffer.from([])) ).toEqual(true); }); - it('returns false on non-Buffer values', () => { + it('returns false on non-Buffer values', (): void => { expect( isBuffer(0) ).toEqual(false); diff --git a/packages/util/src/is/buffer.ts b/packages/util/src/is/buffer.ts index 787778644..9b78ad685 100644 --- a/packages/util/src/is/buffer.ts +++ b/packages/util/src/is/buffer.ts @@ -18,6 +18,7 @@ import isInstanceOf from './instanceOf'; * console.log('isBuffer', isBuffer(Buffer.from([]))); // => true * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isBuffer (value: any): value is Buffer { return isInstanceOf(value, Buffer); } diff --git a/packages/util/src/is/error.spec.ts b/packages/util/src/is/error.spec.ts index f34c337b9..6619ca08c 100644 --- a/packages/util/src/is/error.spec.ts +++ b/packages/util/src/is/error.spec.ts @@ -4,14 +4,14 @@ import { isError } from '.'; -describe('isError', () => { - it('returns true when an Error value', () => { +describe('isError', (): void => { + it('returns true when an Error value', (): void => { expect( isError(new Error('testing')) ).toEqual(true); }); - it('returns false on non-Error values', () => { + it('returns false on non-Error values', (): void => { expect( isError(0) ).toEqual(false); diff --git a/packages/util/src/is/error.ts b/packages/util/src/is/error.ts index b520d4a26..4fb94b1a3 100644 --- a/packages/util/src/is/error.ts +++ b/packages/util/src/is/error.ts @@ -18,6 +18,7 @@ import isInstanceOf from './instanceOf'; * console.log('isError', isError(new Error('message'))); // => true * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isError (value: any): value is Error { return isInstanceOf(value, Error); } diff --git a/packages/util/src/is/function.spec.ts b/packages/util/src/is/function.spec.ts index 9b06bca20..efcac7c97 100644 --- a/packages/util/src/is/function.spec.ts +++ b/packages/util/src/is/function.spec.ts @@ -4,14 +4,14 @@ import { isFunction } from '.'; -describe('isFunction', () => { - it('returns true on valid functions', () => { +describe('isFunction', (): void => { + it('returns true on valid functions', (): void => { expect( isFunction(isFunction) ).toEqual(true); }); - it('returns false on invalid functions', () => { + it('returns false on invalid functions', (): void => { expect( isFunction('notAFunction') ).toEqual(false); diff --git a/packages/util/src/is/function.ts b/packages/util/src/is/function.ts index ab295fc41..0fb0da939 100644 --- a/packages/util/src/is/function.ts +++ b/packages/util/src/is/function.ts @@ -16,6 +16,7 @@ * isFunction(() => false); // => true * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isFunction (value: any): value is Function { return typeof value === 'function'; } diff --git a/packages/util/src/is/hex.spec.ts b/packages/util/src/is/hex.spec.ts index 342016a36..1c0404995 100644 --- a/packages/util/src/is/hex.spec.ts +++ b/packages/util/src/is/hex.spec.ts @@ -4,58 +4,58 @@ import { isHex } from '.'; -describe('isHex', () => { +describe('isHex', (): void => { const test = '1234abcd'; - it('returns true on 0x hex values', () => { + it('returns true on 0x hex values', (): void => { expect( isHex('0x') ).toEqual(true); }); - it('returns true on hex values', () => { + it('returns true on hex values', (): void => { expect( isHex(`0x${test}`) ).toEqual(true); }); - it('returns true on hex values with String', () => { + it('returns true on hex values with String', (): void => { expect( - isHex(new String(`0x${test}`)) + isHex(String(`0x${test}`)) ).toEqual(true); }); - it('returns false on hex values (non % 2)', () => { + it('returns false on hex values (non % 2)', (): void => { expect( isHex(`0x${test}0`) ).toEqual(false); }); - it('returns true on uppercase values', () => { + it('returns true on uppercase values', (): void => { expect( isHex(`0x${test.toUpperCase()}`) ).toEqual(true); }); - it('return false on hex values unprefixed', () => { + it('return false on hex values unprefixed', (): void => { expect( isHex(test) ).toEqual(false); }); - it('returns false on non-string values', () => { + it('returns false on non-string values', (): void => { expect( isHex(false) ).toEqual(false); }); - it('returns true when valid hex and bitLength matches', () => { + it('returns true when valid hex and bitLength matches', (): void => { expect( isHex('0x1234', 16) ).toEqual(true); }); - it('returns true when valid hex and bitLength does not match', () => { + it('returns true when valid hex and bitLength does not match', (): void => { expect( isHex('0x1234', 8) ).toEqual(false); diff --git a/packages/util/src/is/hex.ts b/packages/util/src/is/hex.ts index ceaedac40..14e2b8450 100644 --- a/packages/util/src/is/hex.ts +++ b/packages/util/src/is/hex.ts @@ -21,6 +21,7 @@ const HEX_REGEX = /^0x[a-fA-F0-9]+$/; * isHex('0x1234', 8); // => false * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/ban-types export default function isHex (value: any, bitLength: number = -1, ignoreLength: boolean = false): value is string | String { const isValidHex = value === '0x' || (isString(value) && HEX_REGEX.test(value.toString())); diff --git a/packages/util/src/is/instanceOf.spec.ts b/packages/util/src/is/instanceOf.spec.ts index c83384044..9d900a857 100644 --- a/packages/util/src/is/instanceOf.spec.ts +++ b/packages/util/src/is/instanceOf.spec.ts @@ -4,32 +4,32 @@ import { isInstanceOf } from '.'; -describe('isInstanceOf', () => { - it('returns true on real instances', () => { +describe('isInstanceOf', (): void => { + it('returns true on real instances', (): void => { expect( isInstanceOf(new Array(2), Array) ).toEqual(true); }); - it('returns false on non-allocated instances', () => { + it('returns false on non-allocated instances', (): void => { expect( isInstanceOf([], Array) ).toEqual(true); }); - it('returns false on non-instances', () => { + it('returns false on non-instances', (): void => { expect( isInstanceOf('array', Array) ).toEqual(false); }); - it('returns false when class not specified', () => { + it('returns false when class not specified', (): void => { expect( isInstanceOf('array', Array) ).toEqual(false); }); - it('returns false on wrong class type', () => { + it('returns false on wrong class type', (): void => { expect( isInstanceOf(new Array(2), String) ).toEqual(false); diff --git a/packages/util/src/is/instanceOf.ts b/packages/util/src/is/instanceOf.ts index 62a60ae79..33f2c910e 100644 --- a/packages/util/src/is/instanceOf.ts +++ b/packages/util/src/is/instanceOf.ts @@ -16,6 +16,7 @@ * console.log('isInstanceOf', isInstanceOf(new Array(0), Array)); // => true * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isInstanceOf (value: any, clazz: any): boolean { return value instanceof clazz; } diff --git a/packages/util/src/is/ip.spec.ts b/packages/util/src/is/ip.spec.ts index 1a9210c1d..11204de81 100644 --- a/packages/util/src/is/ip.spec.ts +++ b/packages/util/src/is/ip.spec.ts @@ -4,44 +4,44 @@ import { isIp } from '.'; -describe('isIp', () => { - it('returns false when non-ip found', () => { +describe('isIp', (): void => { + it('returns false when non-ip found', (): void => { expect( isIp('not.an.ip.1') ).toEqual(false); }); - it('returns true on IPv4 addresses', () => { + it('returns true on IPv4 addresses', (): void => { expect( isIp('192.168.0.1') ).toEqual(true); }); - it('returns true on IPv4 addresses (IPV4 type)', () => { + it('returns true on IPv4 addresses (IPV4 type)', (): void => { expect( isIp('192.168.0.1', 'v4') ).toEqual(true); }); - it('returns false on IPv4 addresses (IPv6 type)', () => { + it('returns false on IPv4 addresses (IPv6 type)', (): void => { expect( isIp('192.168.0.1', 'v6') ).toEqual(false); }); - it('returns true on IPv6 addresses', () => { + it('returns true on IPv6 addresses', (): void => { expect( isIp('1:2:3:4:5:6:7:8') ).toEqual(true); }); - it('returns true on IPv6 addresses (IPv6 type)', () => { + it('returns true on IPv6 addresses (IPv6 type)', (): void => { expect( isIp('1:2:3:4:5:6:7:8', 'v6') ).toEqual(true); }); - it('returns false on IPv6 addresses (IPv4 type)', () => { + it('returns false on IPv6 addresses (IPv4 type)', (): void => { expect( isIp('1:2:3:4:5:6:7:8', 'v4') ).toEqual(false); diff --git a/packages/util/src/is/jsonObject.spec.ts b/packages/util/src/is/jsonObject.spec.ts index 002a9457d..04edd824e 100644 --- a/packages/util/src/is/jsonObject.spec.ts +++ b/packages/util/src/is/jsonObject.spec.ts @@ -11,38 +11,38 @@ const jsonObject = `{ } }`; -describe('isJsonObject', () => { - it('returns true on empty objects', () => { +describe('isJsonObject', (): void => { + it('returns true on empty objects', (): void => { expect( isJsonObject({}) ).toEqual(true); }); - it('returns true on JSON objects', () => { + it('returns true on JSON objects', (): void => { expect( isJsonObject(jsonObject) ).toEqual(true); }); - it('returns false on JSON parsable value typeof number', () => { + it('returns false on JSON parsable value typeof number', (): void => { expect( isJsonObject(1234) ).toEqual(false); }); - it('returns false on JSON parsable value null', () => { + it('returns false on JSON parsable value null', (): void => { expect( isJsonObject(null) ).toEqual(false); }); - it('returns false on invalid objects', () => { + it('returns false on invalid objects', (): void => { expect( isJsonObject('notAnObject') ).toEqual(false); }); - it('returns false on invalid JSON', () => { + it('returns false on invalid JSON', (): void => { expect( isJsonObject(`{"abc", "def"}`) ).toEqual(false); diff --git a/packages/util/src/is/jsonObject.ts b/packages/util/src/is/jsonObject.ts index b7a20296d..ece8c9a51 100644 --- a/packages/util/src/is/jsonObject.ts +++ b/packages/util/src/is/jsonObject.ts @@ -2,9 +2,10 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -type ObjectIndexed = { - [index: string]: any -}; +interface ObjectIndexed { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [index: string]: any; +} /** * @name isJsonObject @@ -31,8 +32,8 @@ type ObjectIndexed = { * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isJsonObject (value: any): value is ObjectIndexed { - value = typeof value !== 'string' ? JSON.stringify(value) : value; diff --git a/packages/util/src/is/null.spec.ts b/packages/util/src/is/null.spec.ts index 96bde2dba..b19ada4dd 100644 --- a/packages/util/src/is/null.spec.ts +++ b/packages/util/src/is/null.spec.ts @@ -4,14 +4,14 @@ import { isNull } from '.'; -describe('isNull', () => { - it('returns true when a null value', () => { +describe('isNull', (): void => { + it('returns true when a null value', (): void => { expect( isNull(null) ).toEqual(true); }); - it('returns false on non-null values', () => { + it('returns false on non-null values', (): void => { expect( isNull() ).toEqual(false); diff --git a/packages/util/src/is/null.ts b/packages/util/src/is/null.ts index b3a70a780..94ae67652 100644 --- a/packages/util/src/is/null.ts +++ b/packages/util/src/is/null.ts @@ -16,6 +16,7 @@ * console.log('isNull', isNull(null)); // => true * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isNull (value?: any): value is null { return value === null; } diff --git a/packages/util/src/is/number.spec.ts b/packages/util/src/is/number.spec.ts index 2617550db..df53b4957 100644 --- a/packages/util/src/is/number.spec.ts +++ b/packages/util/src/is/number.spec.ts @@ -4,14 +4,14 @@ import { isNumber } from '.'; -describe('isNumber', () => { - it('returns true on valid numbers', () => { +describe('isNumber', (): void => { + it('returns true on valid numbers', (): void => { expect( isNumber(2) ).toEqual(true); }); - it('returns false on invalid numbers', () => { + it('returns false on invalid numbers', (): void => { expect( isNumber('2') ).toEqual(false); diff --git a/packages/util/src/is/number.ts b/packages/util/src/is/number.ts index a63946ebc..b5dd039ee 100644 --- a/packages/util/src/is/number.ts +++ b/packages/util/src/is/number.ts @@ -16,6 +16,7 @@ * console.log('isNumber', isNumber(1234)); // => true * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isNumber (value: any): value is number { return typeof value === 'number'; } diff --git a/packages/util/src/is/object.spec.ts b/packages/util/src/is/object.spec.ts index d0ea408f5..dbf8a61a7 100644 --- a/packages/util/src/is/object.spec.ts +++ b/packages/util/src/is/object.spec.ts @@ -4,14 +4,14 @@ import { isObject } from '.'; -describe('isObject', () => { - it('returns true on valid objects', () => { +describe('isObject', (): void => { + it('returns true on valid objects', (): void => { expect( isObject({}) ).toEqual(true); }); - it('returns false on invalid objects', () => { + it('returns false on invalid objects', (): void => { expect( isObject('notAnObject') ).toEqual(false); diff --git a/packages/util/src/is/object.ts b/packages/util/src/is/object.ts index ab2e55e5b..74a658ea7 100644 --- a/packages/util/src/is/object.ts +++ b/packages/util/src/is/object.ts @@ -2,9 +2,10 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -type ObjectIndexed = { - [index: string]: any -}; +interface ObjectIndexed { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [index: string]: any; +} /** * @name isObject @@ -21,6 +22,7 @@ type ObjectIndexed = { * isObject('something'); // => false * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isObject (value: any): value is ObjectIndexed { return typeof value === 'object'; } diff --git a/packages/util/src/is/observable.spec.ts b/packages/util/src/is/observable.spec.ts index e697272dc..4f893de18 100644 --- a/packages/util/src/is/observable.spec.ts +++ b/packages/util/src/is/observable.spec.ts @@ -4,20 +4,20 @@ import { isObservable } from '.'; -describe('isObservable', () => { - it('returns true on valid observables', () => { +describe('isObservable', (): void => { + it('returns true on valid observables', (): void => { expect( - isObservable({ next: () => true }) + isObservable({ next: (): boolean => true }) ).toEqual(true); }); - it('returns false on invalid objects', () => { + it('returns false on invalid objects', (): void => { expect( isObservable('notAnObservable') ).toEqual(false); }); - it('returns false on invalid next functions', () => { + it('returns false on invalid next functions', (): void => { expect( isObservable({ next: true }) ).toEqual(false); diff --git a/packages/util/src/is/observable.ts b/packages/util/src/is/observable.ts index 42dffe4a9..582aed962 100644 --- a/packages/util/src/is/observable.ts +++ b/packages/util/src/is/observable.ts @@ -5,9 +5,10 @@ import isFunction from './function'; import isObject from './object'; -type Observable = { - next: (...paarams: any[]) => any -}; +interface Observable { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + next: (...params: any[]) => any; +} /** * @name isBObservable @@ -23,6 +24,7 @@ type Observable = { * console.log('isObservable', isObservable(...)); * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isObservable (value: any): value is Observable { return isObject(value) && isFunction((value as Observable).next); } diff --git a/packages/util/src/is/string.spec.ts b/packages/util/src/is/string.spec.ts index 0f2e17fee..6852e1eed 100644 --- a/packages/util/src/is/string.spec.ts +++ b/packages/util/src/is/string.spec.ts @@ -4,26 +4,26 @@ import { isString } from '.'; -describe('isString', () => { - it('returns true on valid strings', () => { +describe('isString', (): void => { + it('returns true on valid strings', (): void => { expect( isString('123') ).toEqual(true); }); - it('returns true on empty strings', () => { + it('returns true on empty strings', (): void => { expect( isString('') ).toEqual(true); }); - it('returns true on String object', () => { + it('returns true on String object', (): void => { expect( - isString(new String('foo')) + isString(String('foo')) ).toEqual(true); }); - it('returns false on invalid numbers', () => { + it('returns false on invalid numbers', (): void => { expect( isString(2) ).toEqual(false); diff --git a/packages/util/src/is/string.ts b/packages/util/src/is/string.ts index a01ec07f6..f8363eb1f 100644 --- a/packages/util/src/is/string.ts +++ b/packages/util/src/is/string.ts @@ -16,6 +16,7 @@ * console.log('isString', isString('test')); // => true * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/ban-types export default function isString (value: any): value is string | String { return typeof value === 'string' || value instanceof String; } diff --git a/packages/util/src/is/testChain.spec.ts b/packages/util/src/is/testChain.spec.ts index 7fb8e1f3c..a2290e0da 100644 --- a/packages/util/src/is/testChain.spec.ts +++ b/packages/util/src/is/testChain.spec.ts @@ -4,21 +4,21 @@ import isTestChain from './testChain'; -describe('isTestChain', () => { - it('enables test environment when chain specification matches text of dev or loc(al)', () => { +describe('isTestChain', (): void => { + it('enables test environment when chain specification matches text of dev or loc(al)', (): void => { const validTestModeChainSpecsWithDev = ['Development']; const validTestModeChainSpecsWithLoc = ['Local Testnet']; - validTestModeChainSpecsWithDev.concat(validTestModeChainSpecsWithLoc).forEach((s) => - expect(isTestChain(s)).toEqual(true) - ); + validTestModeChainSpecsWithDev.concat(validTestModeChainSpecsWithLoc).forEach((s): void => { + expect(isTestChain(s)).toEqual(true); + }); }); - it('disables keyring test mode when chain specification is not a test mode or undefined or number type', () => { + it('disables keyring test mode when chain specification is not a test mode or undefined or number type', (): void => { const invalidTestModeChainSpecs = ['dev', 'local', 'development', 'PoC-1 Testnet', 'Staging Testnet', 'future PoC-2 Testnet', 'a pocadot?', undefined]; - invalidTestModeChainSpecs.forEach((s) => - expect(isTestChain(s)).toEqual(false) - ); + invalidTestModeChainSpecs.forEach((s): void => { + expect(isTestChain(s)).toEqual(false); + }); }); }); diff --git a/packages/util/src/is/u8a.spec.ts b/packages/util/src/is/u8a.spec.ts index f1196b61c..66cf7bd1e 100644 --- a/packages/util/src/is/u8a.spec.ts +++ b/packages/util/src/is/u8a.spec.ts @@ -4,20 +4,20 @@ import { isU8a } from '.'; -describe('isUint8Array', () => { - it('returns false on undefined values', () => { +describe('isUint8Array', (): void => { + it('returns false on undefined values', (): void => { expect( isU8a() ).toEqual(false); }); - it('returns false on Array values', () => { + it('returns false on Array values', (): void => { expect( isU8a([]) ).toEqual(false); }); - it('returns true on Uint8Array values', () => { + it('returns true on Uint8Array values', (): void => { expect( isU8a(new Uint8Array([])) ).toEqual(true); diff --git a/packages/util/src/is/u8a.ts b/packages/util/src/is/u8a.ts index 10d23d314..a1fa2b3e7 100644 --- a/packages/util/src/is/u8a.ts +++ b/packages/util/src/is/u8a.ts @@ -18,6 +18,7 @@ import isInstanceOf from './instanceOf'; * console.log('isU8a', isU8a([])); // => false * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isU8a (value?: any): value is Uint8Array { return isInstanceOf(value, Uint8Array); } diff --git a/packages/util/src/is/undefined.spec.ts b/packages/util/src/is/undefined.spec.ts index 84a1226c7..dfe95ba29 100644 --- a/packages/util/src/is/undefined.spec.ts +++ b/packages/util/src/is/undefined.spec.ts @@ -4,14 +4,14 @@ import { isUndefined } from '.'; -describe('isUndefined', () => { - it('returns true on undefined values', () => { +describe('isUndefined', (): void => { + it('returns true on undefined values', (): void => { expect( isUndefined() ).toEqual(true); }); - it('returns false on defined values', () => { + it('returns false on defined values', (): void => { expect( isUndefined(null) ).toEqual(false); diff --git a/packages/util/src/is/undefined.ts b/packages/util/src/is/undefined.ts index 80e19cbfb..eed109be6 100644 --- a/packages/util/src/is/undefined.ts +++ b/packages/util/src/is/undefined.ts @@ -16,6 +16,7 @@ * console.log('isUndefined', isUndefined(void(0))); // => true * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function isUndefined (value?: any): value is undefined { return typeof value === 'undefined'; } diff --git a/packages/util/src/logger.spec.ts b/packages/util/src/logger.spec.ts index dafb2eb86..6322d1a52 100644 --- a/packages/util/src/logger.spec.ts +++ b/packages/util/src/logger.spec.ts @@ -2,18 +2,22 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +import { Logger } from './types'; + import { logger } from '.'; import { format } from './logger'; -describe('logger', () => { +describe('logger', (): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any let dateMatch: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any let prefixMatch: any; - let l: any; - let ln: any; - let spy: any; - let oldEnv: any; + let l: Logger; + let ln: Logger; + let spy: Partial; + let oldEnv: NodeJS.ProcessEnv; - beforeEach(() => { + beforeEach((): void => { oldEnv = process.env; process.env.NODE_ENV = 'development'; @@ -28,28 +32,28 @@ describe('logger', () => { log: jest.fn(), warn: jest.fn() }; - (global as any).console = spy; + global.console = spy as Console; dateMatch = expect.stringMatching(/20[0-9]{2}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/); prefixMatch = expect.stringMatching(/TEST:/); }); - afterEach(() => { + afterEach((): void => { process.env = oldEnv; jest.restoreAllMocks(); }); - describe('format', () => { - it('returns null as-is', () => { + describe('format', (): void => { + it('returns null as-is', (): void => { expect(format(null)).toEqual(null); }); - it('returns undefined as-is', () => { + it('returns undefined as-is', (): void => { expect(format(undefined)).toEqual(undefined); }); }); - it('logs to console.log with .log', () => { + it('logs to console.log with .log', (): void => { l.log('console.log test'); expect(spy.log).toHaveBeenCalledWith( @@ -59,7 +63,7 @@ describe('logger', () => { ); }); - it('logs with mulptiple values', () => { + it('logs with mulptiple values', (): void => { l.log('test', 'a', 2); expect(spy.log).toHaveBeenCalledWith( @@ -71,8 +75,8 @@ describe('logger', () => { ); }); - it('logs when called with function', () => { - l.log(() => 'a function test'); + it('logs when called with function', (): void => { + l.log((): string => 'a function test'); expect(spy.log).toHaveBeenCalledWith( dateMatch, @@ -81,7 +85,7 @@ describe('logger', () => { ); }); - it('logs to console.error with .error', () => { + it('logs to console.error with .error', (): void => { l.error('console.error test'); expect(spy.error).toHaveBeenCalledWith( @@ -91,7 +95,7 @@ describe('logger', () => { ); }); - it('logs to console.warn with .warn', () => { + it('logs to console.warn with .warn', (): void => { l.warn('console.warn test'); expect(spy.warn).toHaveBeenCalledWith( @@ -101,7 +105,7 @@ describe('logger', () => { ); }); - it('does debug log when DEBUG specified', () => { + it('does debug log when DEBUG specified', (): void => { l.debug('test'); expect(spy.log).toHaveBeenCalledWith( @@ -111,7 +115,7 @@ describe('logger', () => { ); }); - it('does debug log when DEBUG partial specified', () => { + it('does debug log when DEBUG partial specified', (): void => { l = logger('testing'); l.debug('test'); @@ -122,7 +126,7 @@ describe('logger', () => { ); }); - it('does not debug log when non-matching DEBUG specified', () => { + it('does not debug log when non-matching DEBUG specified', (): void => { process.env.DEBUG = 'blah'; l = logger('test'); @@ -131,7 +135,7 @@ describe('logger', () => { expect(spy.log).not.toHaveBeenCalled(); }); - it('does debug log when NODE_ENV=test specified', () => { + it('does debug log when NODE_ENV=test specified', (): void => { process.env.DEBUG = 'blah'; process.env.NODE_ENV = 'test'; @@ -141,7 +145,8 @@ describe('logger', () => { expect(spy.log).toHaveBeenCalled(); }); - it('does not debug log when no process.env', () => { + it('does not debug log when no process.env', (): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any process.env = void 0 as any; l = logger('test'); @@ -150,7 +155,7 @@ describe('logger', () => { expect(spy.log).not.toHaveBeenCalled(); }); - it('does not debug log when no DEBUG specified', () => { + it('does not debug log when no DEBUG specified', (): void => { ln.debug('test'); expect(spy.log).not.toHaveBeenCalled(); diff --git a/packages/util/src/logger.ts b/packages/util/src/logger.ts index 1121148dd..723b8d3cd 100644 --- a/packages/util/src/logger.ts +++ b/packages/util/src/logger.ts @@ -31,14 +31,21 @@ const chalked = { warn: chalk.yellow }; -function formatObject (value: { [index: string]: any }): any { - return Object.keys(value).reduce((result, key) => { +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function formatObject (value: Record): any { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const result: Record = {}; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return Object.keys(value).reduce((result, key): Record => { + // eslint-disable-next-line @typescript-eslint/no-use-before-define result[key] = format(value[key]); return result; - }, {} as { [index: string]: any }); + }, result); } +// eslint-disable-next-line @typescript-eslint/no-explicit-any export function format (value: any): any { if (Array.isArray(value)) { return value.map(format); @@ -83,6 +90,7 @@ function apply (log: LogType, type: string, values: Logger$Data): void { ); } +// eslint-disable-next-line @typescript-eslint/no-unused-vars function noop (...values: Logger$Data): void { // noop } @@ -109,7 +117,7 @@ export default function logger (_type: string): Logger { const isTest = process.env.NODE_ENV === 'test'; const debugList = (process.env.DEBUG || '').split(','); - isDebug = isTest || !!debugList.find((entry) => _type.indexOf(entry) === 0); + isDebug = isTest || !!debugList.find((entry): boolean => _type.indexOf(entry) === 0); } catch (error) { isDebug = false; } diff --git a/packages/util/src/number/toHex.spec.ts b/packages/util/src/number/toHex.spec.ts index 016db9126..9e220b8db 100644 --- a/packages/util/src/number/toHex.spec.ts +++ b/packages/util/src/number/toHex.spec.ts @@ -4,38 +4,38 @@ import { numberToHex } from '.'; -describe('numberToHex', () => { - it('converts undefined to 0x', () => { +describe('numberToHex', (): void => { + it('converts undefined to 0x', (): void => { expect( numberToHex() ).toEqual('0x'); }); - it('converts null to 0x', () => { + it('converts null to 0x', (): void => { expect( numberToHex(null) ).toEqual('0x'); }); - it('converts Nan to 0x', () => { + it('converts Nan to 0x', (): void => { expect( numberToHex(NaN) ).toEqual('0x'); }); - it('converts 0 to 0x00', () => { + it('converts 0 to 0x00', (): void => { expect( numberToHex(0) ).toEqual('0x00'); }); - it('converts number to hex', () => { + it('converts number to hex', (): void => { expect( numberToHex(0x1245) ).toEqual('0x1245'); }); - it('converts number to hex (specfified bitLength)', () => { + it('converts number to hex (specfified bitLength)', (): void => { expect( numberToHex(0x1245, 32) ).toEqual('0x00001245'); diff --git a/packages/util/src/number/toU8a.spec.ts b/packages/util/src/number/toU8a.spec.ts index 310d941ac..47d875ba6 100644 --- a/packages/util/src/number/toU8a.spec.ts +++ b/packages/util/src/number/toU8a.spec.ts @@ -4,38 +4,38 @@ import { numberToU8a } from '.'; -describe('numberToU8a', () => { - it('converts 0 to empty', () => { +describe('numberToU8a', (): void => { + it('converts 0 to empty', (): void => { expect( numberToU8a(0) ).toEqual(new Uint8Array([])); }); - it('converts undefined to empty', () => { + it('converts undefined to empty', (): void => { expect( numberToU8a() ).toEqual(new Uint8Array([])); }); - it('converts null to empty', () => { + it('converts null to empty', (): void => { expect( numberToU8a(null) ).toEqual(new Uint8Array([])); }); - it('converts NaN to empty', () => { + it('converts NaN to empty', (): void => { expect( numberToU8a(NaN) ).toEqual(new Uint8Array([])); }); - it('converts values to the u8a', () => { + it('converts values to the u8a', (): void => { expect( numberToU8a(0x3456) ).toEqual(new Uint8Array([0x34, 0x56])); }); - it('converts values to the u8a (bitLength)', () => { + it('converts values to the u8a (bitLength)', (): void => { expect( numberToU8a(0x3456, 32) ).toEqual(new Uint8Array([0x00, 0x00, 0x34, 0x56])); diff --git a/packages/util/src/polyfill/fill.spec.ts b/packages/util/src/polyfill/fill.spec.ts index 2378f60f9..4fddf3ff1 100644 --- a/packages/util/src/polyfill/fill.spec.ts +++ b/packages/util/src/polyfill/fill.spec.ts @@ -2,28 +2,33 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -describe('Array.fill', () => { - let arrayFill: any; - let u8aFill: any; +describe('Array.fill', (): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let arrayFill: (value: any, start?: number | undefined, end?: number | undefined) => any[]; + let u8aFill: (value: number, start?: number | undefined, end?: number | undefined) => Uint8Array; - beforeEach(() => { + beforeEach((): void => { arrayFill = Array.prototype.fill; u8aFill = Uint8Array.prototype.fill; // @ts-ignore + // eslint-disable-next-line no-extend-native Array.prototype.fill = null; // @ts-ignore + // eslint-disable-next-line no-extend-native Uint8Array.prototype.fill = null; require('./fill'); }); - afterEach(() => { + afterEach((): void => { + // eslint-disable-next-line no-extend-native Array.prototype.fill = arrayFill; + // eslint-disable-next-line no-extend-native Uint8Array.prototype.fill = u8aFill; }); - it('uses the polyfills', () => { + it('uses the polyfills', (): void => { expect( [1, 2, 3, 4, 5, 6, 7, 8].fill(5, 3) ).toEqual([1, 2, 3, 5, 5, 5, 5, 5]); diff --git a/packages/util/src/polyfill/fill.ts b/packages/util/src/polyfill/fill.ts index b79316b16..03f092690 100644 --- a/packages/util/src/polyfill/fill.ts +++ b/packages/util/src/polyfill/fill.ts @@ -3,7 +3,8 @@ // of the Apache-2.0 license. See the LICENSE file for details. if (!Array.prototype.fill) { - Array.prototype.fill = function fill (value: any, start: number = 0, end?: number) { + // eslint-disable-next-line no-extend-native,@typescript-eslint/no-explicit-any + Array.prototype.fill = function fill (value: any, start: number = 0, end?: number): any[] { // Steps 1-2. if (!this) { throw new TypeError('this is null or not defined'); @@ -45,5 +46,6 @@ if (!Array.prototype.fill) { if (!Uint8Array.prototype.fill) { // @ts-ignore + // eslint-disable-next-line no-extend-native Uint8Array.prototype.fill = Array.prototype.fill; } diff --git a/packages/util/src/polyfill/padEnd.spec.ts b/packages/util/src/polyfill/padEnd.spec.ts index 8ae6c6295..71a739004 100644 --- a/packages/util/src/polyfill/padEnd.spec.ts +++ b/packages/util/src/polyfill/padEnd.spec.ts @@ -2,22 +2,24 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -describe('String padEnd', () => { +describe('String padEnd', (): void => { let stringEnd: (length: number, fill?: string) => string; - beforeEach(() => { + beforeEach((): void => { stringEnd = String.prototype.padEnd; + // eslint-disable-next-line no-extend-native,@typescript-eslint/no-explicit-any String.prototype.padEnd = null as any; require('./padEnd'); }); - afterEach(() => { + afterEach((): void => { + // eslint-disable-next-line no-extend-native String.prototype.padEnd = stringEnd; }); - it('does padding', () => { + it('does padding', (): void => { expect('test'.padEnd(8, 'A')).toEqual('testAAAA'); expect('test'.padEnd(8)).toEqual('test '); }); diff --git a/packages/util/src/polyfill/padEnd.ts b/packages/util/src/polyfill/padEnd.ts index b1d4a888c..bbd236945 100644 --- a/packages/util/src/polyfill/padEnd.ts +++ b/packages/util/src/polyfill/padEnd.ts @@ -3,8 +3,9 @@ // of the Apache-2.0 license. See the LICENSE file for details. if (!String.prototype.padEnd) { - String.prototype.padEnd = function padEnd (length: number, char: string = ' ') { - let result: string = String(this); + // eslint-disable-next-line no-extend-native + String.prototype.padEnd = function padEnd (length: number, char: string = ' '): string { + let result = String(this); while (result.length < length) { result = result + char; diff --git a/packages/util/src/polyfill/padStart.spec.ts b/packages/util/src/polyfill/padStart.spec.ts index 175d82a4b..594112ab9 100644 --- a/packages/util/src/polyfill/padStart.spec.ts +++ b/packages/util/src/polyfill/padStart.spec.ts @@ -2,22 +2,24 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -describe('String padStart', () => { +describe('String padStart', (): void => { let stringStart: (length: number, fill?: string) => string; - beforeEach(() => { + beforeEach((): void => { stringStart = String.prototype.padStart; + // eslint-disable-next-line no-extend-native,@typescript-eslint/no-explicit-any String.prototype.padStart = null as any; require('./padStart'); }); - afterEach(() => { + afterEach((): void => { + // eslint-disable-next-line no-extend-native String.prototype.padStart = stringStart; }); - it('does padding', () => { + it('does padding', (): void => { expect('test'.padStart(8, 'A')).toEqual('AAAAtest'); expect('test'.padStart(8)).toEqual(' test'); }); diff --git a/packages/util/src/polyfill/padStart.ts b/packages/util/src/polyfill/padStart.ts index b660dcac9..95fb21e06 100644 --- a/packages/util/src/polyfill/padStart.ts +++ b/packages/util/src/polyfill/padStart.ts @@ -3,8 +3,9 @@ // of the Apache-2.0 license. See the LICENSE file for details. if (!String.prototype.padStart) { - String.prototype.padStart = function padStart (length: number, char: string = ' ') { - let result: string = String(this); + // eslint-disable-next-line no-extend-native + String.prototype.padStart = function padStart (length: number, char: string = ' '): string { + let result = String(this); while (result.length < length) { result = char + result; diff --git a/packages/util/src/polyfill/setPrototypeOf.spec.ts b/packages/util/src/polyfill/setPrototypeOf.spec.ts index e483896eb..4482e31d7 100644 --- a/packages/util/src/polyfill/setPrototypeOf.spec.ts +++ b/packages/util/src/polyfill/setPrototypeOf.spec.ts @@ -2,10 +2,11 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -describe('setPrototypeOf', () => { +describe('setPrototypeOf', (): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any let orig: (o: any, proto: object | null) => any; - beforeEach(() => { + beforeEach((): void => { orig = Object.setPrototypeOf; // @ts-ignore @@ -14,14 +15,15 @@ describe('setPrototypeOf', () => { require('./setPrototypeOf'); }); - afterEach(() => { + afterEach((): void => { Object.setPrototypeOf = orig; }); - it('polyfills with no exceptions', () => { + it('polyfills with no exceptions', (): void => { const obj = {}; const proto = { foo: 'bar' }; + // eslint-disable-next-line no-proto expect(Object.setPrototypeOf(obj, proto).__proto__).toBe(proto); }); }); diff --git a/packages/util/src/polyfill/setPrototypeOf.ts b/packages/util/src/polyfill/setPrototypeOf.ts index e8fdf65dd..8449c822c 100644 --- a/packages/util/src/polyfill/setPrototypeOf.ts +++ b/packages/util/src/polyfill/setPrototypeOf.ts @@ -4,7 +4,9 @@ // React Native does not have Object.setPrototypeOf if (!Object.setPrototypeOf) { - Object.setPrototypeOf = function (obj: any, proto: any) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.setPrototypeOf = function (obj: any, proto: object | null): void { + // eslint-disable-next-line no-proto obj.__proto__ = proto; return obj; diff --git a/packages/util/src/polyfill/textDecoder.spec.ts b/packages/util/src/polyfill/textDecoder.spec.ts index b2c62a814..ea1a11f2b 100644 --- a/packages/util/src/polyfill/textDecoder.spec.ts +++ b/packages/util/src/polyfill/textDecoder.spec.ts @@ -2,28 +2,34 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -describe('TextDecoder', () => { +describe('TextDecoder', (): void => { let origTD: TextDecoder; - beforeEach(() => { + beforeEach((): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any origTD = (global as any).TextDecoder; }); - afterEach(() => { + afterEach((): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any (global as any).TextDecoder = origTD; }); - it('polyfills with no exceptions (without TextDecoder)', () => { + it('polyfills with no exceptions (without TextDecoder)', (): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any (global as any).TextDecoder = null; expect(require('./textDecoder')).toBeDefined(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((global as any).TextDecoder).toBeDefined(); }); - it('polyfills with no exceptions (with TextDecoder)', () => { + it('polyfills with no exceptions (with TextDecoder)', (): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any (global as any).TextDecoder = require('util').TextDecoder; expect(require('./textDecoder')).toBeDefined(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((global as any).TextDecoder).toBeDefined(); }); }); diff --git a/packages/util/src/polyfill/textDecoder.ts b/packages/util/src/polyfill/textDecoder.ts index 6a0f8626d..688cd3d36 100644 --- a/packages/util/src/polyfill/textDecoder.ts +++ b/packages/util/src/polyfill/textDecoder.ts @@ -2,7 +2,6 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -// tslint:disable-next-line if (typeof TextDecoder === 'undefined') { try { // @ts-ignore diff --git a/packages/util/src/polyfill/textEncoder.spec.ts b/packages/util/src/polyfill/textEncoder.spec.ts index ef09a7ad9..4df1b1bab 100644 --- a/packages/util/src/polyfill/textEncoder.spec.ts +++ b/packages/util/src/polyfill/textEncoder.spec.ts @@ -2,28 +2,34 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -describe('TextEncoder', () => { +describe('TextEncoder', (): void => { let origTE: TextEncoder; - beforeEach(() => { + beforeEach((): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any origTE = (global as any).TextEncoder; }); - afterEach(() => { + afterEach((): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any (global as any).TextEncoder = origTE; }); - it('polyfills with no exceptions (without TextEncoder)', () => { + it('polyfills with no exceptions (without TextEncoder)', (): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any (global as any).TextEncoder = null; expect(require('./textEncoder')).toBeDefined(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((global as any).TextEncoder).toBeDefined(); }); - it('polyfills with no exceptions (with TextEncoder)', () => { + it('polyfills with no exceptions (with TextEncoder)', (): void => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any (global as any).TextEncoder = require('util').TextEncoder; expect(require('./textEncoder')).toBeDefined(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((global as any).TextEncoder).toBeDefined(); }); }); diff --git a/packages/util/src/polyfill/textEncoder.ts b/packages/util/src/polyfill/textEncoder.ts index 8fe6a76e1..9d92c293a 100644 --- a/packages/util/src/polyfill/textEncoder.ts +++ b/packages/util/src/polyfill/textEncoder.ts @@ -2,7 +2,6 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -// tslint:disable-next-line if (typeof TextEncoder === 'undefined') { try { // @ts-ignore For the Node.js case diff --git a/packages/util/src/promisify.spec.ts b/packages/util/src/promisify.spec.ts index d7bdbdb5e..c2470fd4f 100644 --- a/packages/util/src/promisify.spec.ts +++ b/packages/util/src/promisify.spec.ts @@ -4,46 +4,56 @@ import { promisify } from '.'; -describe('promisify', () => { - it('handles functions with no parameters (resolve)', () => { - const fn = (cb: Function) => cb(null, [true, 'test', 1]); +describe('promisify', (): void => { + it('handles functions with no parameters (resolve)', (): Promise => { + const fn = (cb: (error: null, value: [boolean, string, number]) => void): void => + cb(null, [true, 'test', 1]); - return promisify(null, fn).then((result) => { + return promisify(null, fn).then((result): void => { expect(result).toEqual([true, 'test', 1]); }); }); - it('handles functions with no parameters (reject)', () => { - const fn = (cb: Function) => cb(new Error('test reject')); + it('handles functions with no parameters (reject)', (): Promise => { + const fn = (cb: (error: Error, result?: boolean) => void): void => + cb(new Error('test reject')); - return promisify(null, fn).catch((error) => { - expect(error.message).toEqual('test reject'); + return promisify(null, fn) + .then((): void => { + throw new Error('Received unexpected result'); + }) + .catch((error): void => { + expect(error.message).toEqual('test reject'); + }); + }); + + it('handles functions with parameters (resolve)', (): Promise => { + const fn = (a: number, b: boolean, cb: (error: Error | null, result?: [number, boolean]) => void): void => + cb(null, [a, b]); + + // @ts-ignore + return promisify(null, fn, 2, false).then((result: [number, boolean]): void => { + expect(result).toEqual([2, false]); }); }); - it('handles functions with parameters (resolve)', () => { - const fn = (a: any, b: any, c: any, cb: Function) => cb(null, [a, b, c]); + it('handles functions with parameters (reject)', (): Promise => { + const fn = (a: number, b: boolean, c: string, cb: (error: Error | null, result?: [number, boolean, string]) => void): void => + cb(new Error(`test reject: ${a},${b},${c}`)); - return promisify(null, fn, 2, false, null).then((result) => { - expect(result).toEqual([2, false, null]); - }); - }); - - it('handles functions with parameters (reject)', () => { - const fn = (a: any, b: any, c: any, cb: Function) => cb(new Error(`test reject: ${a},${b},${c}`)); - - return promisify(null, fn, 3, 'string', true).catch((error) => { + // @ts-ignore + return promisify(null, fn, 3, 'string', true).catch((error: Error): void => { expect(error.message).toEqual('test reject: 3,string,true'); }); }); - it('applies the correct this argument', () => { + it('applies the correct this argument', (): Promise => { const self = { something: 'something' }; - return promisify(self, function (cb: Function) { + return promisify(self, function (cb: (error: Error | null) => void): void { // @ts-ignore expect(this).toEqual(self); - cb(); + cb(null); }); }); }); diff --git a/packages/util/src/promisify.ts b/packages/util/src/promisify.ts index 1b6cfd41f..e363eedb5 100644 --- a/packages/util/src/promisify.ts +++ b/packages/util/src/promisify.ts @@ -2,6 +2,21 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. +/* eslint-disable @typescript-eslint/no-explicit-any */ + +// this is horrible, but we want it typed, so... 6 params should be enough for everybody? +export interface PromisifyFn { + (cb: (error: Error | null, result?: any) => any): any; + (a: any, cb: (error: Error | null, result?: any) => any): any; + (a: any, b: any, cb: (error: Error | null, result?: any) => any): any; + (a: any, b: any, c: any, cb: (error: Error | null, result?: any) => any): any; + (a: any, b: any, c: any, d: any, cb: (error: Error | null, result?: any) => any): any; + (a: any, b: any, c: any, d: any, e: any, cb: (error: Error | null, result?: any) => any): any; + (a: any, b: any, c: any, d: any, e: any, f: any, cb: (error: Error | null, result?: any) => any): any; +} + +type ParamType = [] | [any] | [any, any] | [any, any, any]| [any, any, any, any]| [any, any, any, any, any]| [any, any, any, any, any, any]; + /** * @name promisify * @summary Wraps an async callback into a `Promise` @@ -17,10 +32,11 @@ * await promisify(null, (cb) => cb(new Error('error!'))); // rejects with `error!` * ``` */ -export default function promisify (self: any, fn: Function, ...params: Array): Promise { - return new Promise((resolve, reject) => { +export default function promisify (self: any, fn: PromisifyFn, ...params: ParamType): Promise { + return new Promise((resolve, reject): void => { fn.apply(self, params.concat([ - (error: Error | null, result: any): void => { + // @ts-ignore + (error: Error | null, result?: any): void => { if (error) { reject(error); } else { diff --git a/packages/util/src/string/camelCase.spec.ts b/packages/util/src/string/camelCase.spec.ts index bdb6e2897..33fb2854c 100644 --- a/packages/util/src/string/camelCase.spec.ts +++ b/packages/util/src/string/camelCase.spec.ts @@ -4,8 +4,8 @@ import { stringCamelCase } from '.'; -describe('stringCamelCase', () => { - it('works correctly', () => { +describe('stringCamelCase', (): void => { + it('works correctly', (): void => { expect( stringCamelCase('Snake_case') ).toBe('snakeCase'); diff --git a/packages/util/src/string/lowerFirst.spec.ts b/packages/util/src/string/lowerFirst.spec.ts index a777db707..fa7ff4069 100644 --- a/packages/util/src/string/lowerFirst.spec.ts +++ b/packages/util/src/string/lowerFirst.spec.ts @@ -4,26 +4,26 @@ import { stringLowerFirst } from '.'; -describe('stringLowerFirst', () => { - it("lowers the first letter if it's a capital letter", () => { +describe('stringLowerFirst', (): void => { + it("lowers the first letter if it's a capital letter", (): void => { expect( stringLowerFirst('ABC') ).toBe('aBC'); }); - it("lowers the first letter if it's a lowercase letter", () => { + it("lowers the first letter if it's a lowercase letter", (): void => { expect( stringLowerFirst('abc') ).toBe('abc'); }); - it('returns undefined as empty', () => { + it('returns undefined as empty', (): void => { expect( stringLowerFirst() ).toBe(''); }); - it('returns null as empty', () => { + it('returns null as empty', (): void => { expect( stringLowerFirst(null) ).toBe(''); diff --git a/packages/util/src/string/shorten.spec.ts b/packages/util/src/string/shorten.spec.ts index 7783dd5af..7dcf06c4c 100644 --- a/packages/util/src/string/shorten.spec.ts +++ b/packages/util/src/string/shorten.spec.ts @@ -4,26 +4,26 @@ import { stringShorten } from '.'; -describe('stringShorten', () => { - it('returns the value as-is when <= maxLength', () => { +describe('stringShorten', (): void => { + it('returns the value as-is when <= maxLength', (): void => { expect( stringShorten('0123456789', 4) ).toEqual('0123456789'); }); - it('returns the shortened value when > maxLength', () => { + it('returns the shortened value when > maxLength', (): void => { expect( stringShorten('0123456789', 3) ).toEqual('012..789'); }); - it('returns undefined as undefined', () => { + it('returns undefined as undefined', (): void => { expect( stringShorten() ).toEqual('undefined'); }); - it('returns non-string values as strings', () => { + it('returns non-string values as strings', (): void => { expect( stringShorten(12345678, 2) ).toEqual('12..78'); diff --git a/packages/util/src/string/shorten.ts b/packages/util/src/string/shorten.ts index f6f59fa43..ad7042964 100644 --- a/packages/util/src/string/shorten.ts +++ b/packages/util/src/string/shorten.ts @@ -16,6 +16,7 @@ * stringShorten('1234567890', 2); // => 12..90 * ``` */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any export default function stringShorten (_value?: any, prefixLength: number = 6): string { const value = `${_value}`; diff --git a/packages/util/src/string/toU8a.spec.ts b/packages/util/src/string/toU8a.spec.ts index 5f906a9c9..bdc285544 100644 --- a/packages/util/src/string/toU8a.spec.ts +++ b/packages/util/src/string/toU8a.spec.ts @@ -4,14 +4,14 @@ import { stringToU8a } from '..'; -describe('stringToU8a', () => { - it('decodes to an empty string for undefined', () => { +describe('stringToU8a', (): void => { + it('decodes to an empty string for undefined', (): void => { expect( stringToU8a() ).toEqual(new Uint8Array([])); }); - it('encodes the string correctly', () => { + it('encodes the string correctly', (): void => { expect( stringToU8a('Привет, мир!') ).toEqual( diff --git a/packages/util/src/string/upperFirst.spec.ts b/packages/util/src/string/upperFirst.spec.ts index ba6920ccf..1c55c5da8 100644 --- a/packages/util/src/string/upperFirst.spec.ts +++ b/packages/util/src/string/upperFirst.spec.ts @@ -4,26 +4,26 @@ import { stringUpperFirst } from '.'; -describe('stringUpperFirst', () => { - it("uppers the first letter if it's a capital letter", () => { +describe('stringUpperFirst', (): void => { + it("uppers the first letter if it's a capital letter", (): void => { expect( stringUpperFirst('ABC') ).toBe('ABC'); }); - it("uppers the first letter if it's a lowercase letter", () => { + it("uppers the first letter if it's a lowercase letter", (): void => { expect( stringUpperFirst('abc') ).toBe('Abc'); }); - it('returns undefined as empty', () => { + it('returns undefined as empty', (): void => { expect( stringUpperFirst() ).toBe(''); }); - it('returns null as empty', () => { + it('returns null as empty', (): void => { expect( stringUpperFirst(null) ).toBe(''); diff --git a/packages/util/src/types.ts b/packages/util/src/types.ts index 9cc7828a7..cf571dca7 100644 --- a/packages/util/src/types.ts +++ b/packages/util/src/types.ts @@ -6,21 +6,23 @@ import BN from 'bn.js'; export interface ExtErrorInterface { code: number; - data: any; + data: string | number; message: string; stack: string; } -type Logger$Data$Fn = () => Array; -export type Logger$Data = Array; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Logger$Data$Fn = () => any[]; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type Logger$Data = (any | Logger$Data$Fn)[]; -export type Logger = { - debug: (...values: Logger$Data) => void, - error: (...values: Logger$Data) => void, - log: (...values: Logger$Data) => void, - noop: (...values: Logger$Data) => void, - warn: (...values: Logger$Data) => void -}; +export interface Logger { + debug: (...values: Logger$Data) => void; + error: (...values: Logger$Data) => void; + log: (...values: Logger$Data) => void; + noop: (...values: Logger$Data) => void; + warn: (...values: Logger$Data) => void; +} export interface ToBnOptions { isLe?: boolean; @@ -28,6 +30,6 @@ export interface ToBnOptions { } export type BnList = { - 0: BN, - 1: BN -} & Array; + 0: BN; + 1: BN; +} & BN[]; diff --git a/packages/util/src/u8a/concat.spec.ts b/packages/util/src/u8a/concat.spec.ts index 4665fbb44..0329b282d 100644 --- a/packages/util/src/u8a/concat.spec.ts +++ b/packages/util/src/u8a/concat.spec.ts @@ -4,8 +4,8 @@ import { u8aConcat } from '.'; -describe('u8aConcat', () => { - it('concatenates arrays', () => { +describe('u8aConcat', (): void => { + it('concatenates arrays', (): void => { expect( u8aConcat( new Uint8Array([1, 2, 3, 4]), @@ -17,7 +17,7 @@ describe('u8aConcat', () => { ); }); - it('concatenates arrays & hex values', () => { + it('concatenates arrays & hex values', (): void => { expect( u8aConcat( new Uint8Array([1, 2, 3, 4]), diff --git a/packages/util/src/u8a/concat.ts b/packages/util/src/u8a/concat.ts index 3207e92fe..a36237d7e 100644 --- a/packages/util/src/u8a/concat.ts +++ b/packages/util/src/u8a/concat.ts @@ -21,13 +21,13 @@ import u8aToU8a from './toU8a'; * ); // [1, 2, 3, 4, 5, 6] * ``` */ -export default function u8aConcat (..._list: Array): Uint8Array { - const list: Array = _list.map(u8aToU8a); - const length = list.reduce((total, item) => total + item.length, 0); +export default function u8aConcat (..._list: (Uint8Array | string)[]): Uint8Array { + const list: Uint8Array[] = _list.map(u8aToU8a); + const length = list.reduce((total, item): number => total + item.length, 0); const result = new Uint8Array(length); let offset = 0; - return list.reduce((result, item) => { + return list.reduce((result, item): Uint8Array => { result.set(item, offset); offset += item.length; diff --git a/packages/util/src/u8a/fixLength.spec.ts b/packages/util/src/u8a/fixLength.spec.ts index 4b2c435a2..962a76640 100644 --- a/packages/util/src/u8a/fixLength.spec.ts +++ b/packages/util/src/u8a/fixLength.spec.ts @@ -4,8 +4,8 @@ import { u8aFixLength } from '.'; -describe('u8aFixLength', () => { - it('returns bitLength === -1 as-is', () => { +describe('u8aFixLength', (): void => { + it('returns bitLength === -1 as-is', (): void => { expect( u8aFixLength( new Uint8Array([0x12, 0x34, 0x56, 0x78]) @@ -13,19 +13,19 @@ describe('u8aFixLength', () => { ).toEqual(new Uint8Array([0x12, 0x34, 0x56, 0x78])); }); - it('does not change when bitlength === length', () => { + it('does not change when bitlength === length', (): void => { expect( u8aFixLength(new Uint8Array([0x12, 0x34, 0x56, 0x78]), 32) ).toEqual(new Uint8Array([0x12, 0x34, 0x56, 0x78])); }); - it('trims values when bitLength > length', () => { + it('trims values when bitLength > length', (): void => { expect( u8aFixLength(new Uint8Array([0x12, 0x34, 0x56, 0x78]), 16) ).toEqual(new Uint8Array([0x12, 0x34])); }); - it('adds zeros when bitLength < length (withPadded)', () => { + it('adds zeros when bitLength < length (withPadded)', (): void => { expect( u8aFixLength(new Uint8Array([0x12, 0x34]), 32) ).toEqual(new Uint8Array([0, 0, 0x12, 0x34])); diff --git a/packages/util/src/u8a/toBn.spec.ts b/packages/util/src/u8a/toBn.spec.ts index 172a485db..714c42f32 100644 --- a/packages/util/src/u8a/toBn.spec.ts +++ b/packages/util/src/u8a/toBn.spec.ts @@ -4,15 +4,15 @@ import { u8aToBn } from '.'; -describe('u8aToBn', () => { - it('converts little-endian by default', () => { +describe('u8aToBn', (): void => { + it('converts little-endian by default', (): void => { expect( u8aToBn( new Uint8Array([0x12, 0x34]) ).toString(16) ).toBe('3412'); }); - it('converts values (big-endian)', () => { + it('converts values (big-endian)', (): void => { expect( u8aToBn( new Uint8Array([0x12, 0x34]), @@ -21,7 +21,7 @@ describe('u8aToBn', () => { ).toBe('1234'); }); - it('converts values (little-endian)', () => { + it('converts values (little-endian)', (): void => { expect( u8aToBn( new Uint8Array([0x12, 0x34]), @@ -30,7 +30,7 @@ describe('u8aToBn', () => { ).toBe('3412'); }); - it('converts empty', () => { + it('converts empty', (): void => { expect( u8aToBn( new Uint8Array([]), @@ -39,7 +39,7 @@ describe('u8aToBn', () => { ).toBe('0'); }); - it('handles negative numbers (little-endian)', () => { + it('handles negative numbers (little-endian)', (): void => { expect( u8aToBn( new Uint8Array([46, 251]), @@ -48,7 +48,7 @@ describe('u8aToBn', () => { ).toBe(-1234); }); - it('handles negative numbers (big-endian)', () => { + it('handles negative numbers (big-endian)', (): void => { expect( u8aToBn( new Uint8Array([251, 46]), @@ -57,7 +57,7 @@ describe('u8aToBn', () => { ).toBe(-1234); }); - it('handles overflows correctly (little-endian)', () => { + it('handles overflows correctly (little-endian)', (): void => { expect( u8aToBn( new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0]), @@ -66,7 +66,7 @@ describe('u8aToBn', () => { ).toBe(256); }); - it('handles backward compatibility)', () => { + it('handles backward compatibility)', (): void => { expect( u8aToBn( new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0]), diff --git a/packages/util/src/u8a/toBuffer.spec.ts b/packages/util/src/u8a/toBuffer.spec.ts index 9e67ad37b..6259f2077 100644 --- a/packages/util/src/u8a/toBuffer.spec.ts +++ b/packages/util/src/u8a/toBuffer.spec.ts @@ -4,14 +4,14 @@ import { u8aToBuffer } from '.'; -describe('u8aToBuffer', () => { - it('returns [] when the buffer is null', () => { +describe('u8aToBuffer', (): void => { + it('returns [] when the buffer is null', (): void => { expect( u8aToBuffer(null) ).toEqual(Buffer.from([])); }); - it('returns the Buffer value for the Uint8Array', () => { + it('returns the Buffer value for the Uint8Array', (): void => { expect( u8aToBuffer(new Uint8Array([128, 0, 10])) ).toEqual(Buffer.from([128, 0, 10])); diff --git a/packages/util/src/u8a/toHex.spec.ts b/packages/util/src/u8a/toHex.spec.ts index 17575d4aa..34333982d 100644 --- a/packages/util/src/u8a/toHex.spec.ts +++ b/packages/util/src/u8a/toHex.spec.ts @@ -4,20 +4,20 @@ import { u8aToHex } from '.'; -describe('u8aToHex', () => { - it('returns empty as 0x', () => { +describe('u8aToHex', (): void => { + it('returns empty as 0x', (): void => { expect( u8aToHex() ).toEqual('0x'); }); - it('returns empty as "" (unprefixed)', () => { + it('returns empty as "" (unprefixed)', (): void => { expect( u8aToHex(null, -1, false) ).toEqual(''); }); - it('returns the hex value for the array', () => { + it('returns the hex value for the array', (): void => { expect( u8aToHex( new Uint8Array([128, 0, 10]) @@ -25,7 +25,7 @@ describe('u8aToHex', () => { ).toEqual('0x80000a'); }); - it('returns the hex value for the array (unprefixed)', () => { + it('returns the hex value for the array (unprefixed)', (): void => { expect( u8aToHex( new Uint8Array([128, 0, 10]), @@ -34,15 +34,15 @@ describe('u8aToHex', () => { ).toEqual('80000a'); }); - it('handles starting zeros correctly', () => { + it('handles starting zeros correctly', (): void => { expect( u8aToHex( - new Uint8Array([ 0, 1, 0, 0, 0, 0, 0, 0 ]) + new Uint8Array([0, 1, 0, 0, 0, 0, 0, 0]) ) ).toEqual('0x0001000000000000'); }); - it('returns the hex value where allowed < max', () => { + it('returns the hex value where allowed < max', (): void => { expect( u8aToHex( new Uint8Array(Uint8Array.from([128, 0, 10, 11]), 64) @@ -50,7 +50,7 @@ describe('u8aToHex', () => { ).toEqual('0x80000a0b'); }); - it('returns the trimmed hex value where allowed >= max', () => { + it('returns the trimmed hex value where allowed >= max', (): void => { expect( u8aToHex( new Uint8Array([128, 0, 10, 11, 12, 13]), diff --git a/packages/util/src/u8a/toHex.ts b/packages/util/src/u8a/toHex.ts index 954412f3d..4426bf1dc 100644 --- a/packages/util/src/u8a/toHex.ts +++ b/packages/util/src/u8a/toHex.ts @@ -38,7 +38,7 @@ export default function u8aToHex (value?: Uint8Array | null, bitLength: number = // based on comments in https://stackoverflow.com/questions/40031688/javascript-arraybuffer-to-hex and // implementation in http://jsben.ch/Vjx2V - optimisation here suggests that a forEach loop is faster // than reduce as well (clocking at in 90% of the reduce speed with tweaking in the playpen above) - return value.reduce((result, value) => { + return value.reduce((result, value): string => { return result + ALPHABET[value >> 4] + ALPHABET[value & 15]; }, prefix); } diff --git a/packages/util/src/u8a/toString.spec.ts b/packages/util/src/u8a/toString.spec.ts index c0ebc9d3c..8125e8c23 100644 --- a/packages/util/src/u8a/toString.spec.ts +++ b/packages/util/src/u8a/toString.spec.ts @@ -4,20 +4,20 @@ import { u8aToString } from '..'; -describe('u8aToString', () => { - it('decodes to an empty string for undefined', () => { +describe('u8aToString', (): void => { + it('decodes to an empty string for undefined', (): void => { expect( u8aToString() ).toEqual(''); }); - it('decodes to an empty string for empty buffer', () => { + it('decodes to an empty string for empty buffer', (): void => { expect( u8aToString(new Uint8Array([])) ).toEqual(''); }); - it('decodes the buffer correctly', () => { + it('decodes the buffer correctly', (): void => { expect( u8aToString( new Uint8Array([208, 159, 209, 128, 208, 184, 208, 178, 208, 181, 209, 130, 44, 32, 208, 188, 208, 184, 209, 128, 33]) diff --git a/packages/util/src/u8a/toString.ts b/packages/util/src/u8a/toString.ts index 1874c5c5c..dc174e37c 100644 --- a/packages/util/src/u8a/toString.ts +++ b/packages/util/src/u8a/toString.ts @@ -5,7 +5,7 @@ let decoder: { decode: (value: Uint8Array) => string }; function polyfilledDecode (value: Uint8Array): string { - return value.reduce((str, code) => { + return value.reduce((str, code): string => { return str + String.fromCharCode(code); }, ''); } diff --git a/packages/util/src/u8a/toU8a.spec.ts b/packages/util/src/u8a/toU8a.spec.ts index df4eed5a6..333da3b17 100644 --- a/packages/util/src/u8a/toU8a.spec.ts +++ b/packages/util/src/u8a/toU8a.spec.ts @@ -4,14 +4,14 @@ import { u8aToU8a } from '.'; -describe('u8aToU8a', () => { - it('returns an empty Uint8Array when null provided', () => { +describe('u8aToU8a', (): void => { + it('returns an empty Uint8Array when null provided', (): void => { expect( u8aToU8a(null) ).toHaveLength(0); }); - it('returns a Uint8Array (hex input)', () => { + it('returns a Uint8Array (hex input)', (): void => { expect( u8aToU8a('0x80000a') ).toEqual( @@ -19,13 +19,13 @@ describe('u8aToU8a', () => { ); }); - it('returns Uint8Array (string input)', () => { + it('returns Uint8Array (string input)', (): void => { expect( u8aToU8a('abcde fghij') ).toEqual(new Uint8Array([97, 98, 99, 100, 101, 32, 102, 103, 104, 105, 106])); }); - it('returns a Uint8Array (buffer input)', () => { + it('returns a Uint8Array (buffer input)', (): void => { expect( u8aToU8a(Buffer.from('80000a', 'hex')) ).toEqual( @@ -33,7 +33,7 @@ describe('u8aToU8a', () => { ); }); - it('creates from Array', () => { + it('creates from Array', (): void => { expect( u8aToU8a([128, 0, 10, 11, 12]) ).toEqual( @@ -41,7 +41,7 @@ describe('u8aToU8a', () => { ); }); - it('returns a Uint8Array as-is (u8a input)', () => { + it('returns a Uint8Array as-is (u8a input)', (): void => { expect( u8aToU8a(new Uint8Array([128, 0, 10])) ).toEqual( diff --git a/packages/util/src/u8a/toU8a.ts b/packages/util/src/u8a/toU8a.ts index 4aa3a7a72..d61d414c3 100644 --- a/packages/util/src/u8a/toU8a.ts +++ b/packages/util/src/u8a/toU8a.ts @@ -24,7 +24,7 @@ import stringToU8a from '../string/toU8a'; * u8aToU8a(0x1234); // => Uint8Array([0x12, 0x34]) * ``` */ -export default function u8aToU8a (value?: Array | Buffer | Uint8Array | string | null): Uint8Array { +export default function u8aToU8a (value?: number[] | Buffer | Uint8Array | string | null): Uint8Array { if (!value) { return new Uint8Array(); } diff --git a/tslint.json b/tslint.json deleted file mode 100644 index c16776a16..000000000 --- a/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "@polkadot/dev/config/tslint" -} diff --git a/yarn.lock b/yarn.lock index 99ffeac9c..1a6899ab2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1739,13 +1739,13 @@ integrity sha512-shAmDyaQC4H92APFoIaVDHCx5bStIocgvbwQyxPRrbUY20V1EYTbSDchWbuwlMG3V17cprZhA6+78JfB+3DTPw== "@octokit/endpoint@^5.1.0": - version "5.2.1" - resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-5.2.1.tgz#e5ef98bc4a41fad62b17e71af1a1710f6076b8df" - integrity sha512-GoUsRSRhtbCQugRY8eDWg5BnsczUZNq00qArrP7tKPHFmvz2KzJ8DoEq6IAQhLGwAOBHbZQ/Zml3DiaEKAWwkA== + version "5.2.2" + resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-5.2.2.tgz#8fbb2e99ae0d8e6b30099f73063801e64467e761" + integrity sha512-VhKxM4CQanIUZDffExqpdpgqu3heF51qbY1wazoNtvIKXAAVoFjqLq2BOhesXkTqxXMO1Ze1XbS8DkIjUxAB+g== dependencies: deepmerge "4.0.0" is-plain-object "^3.0.0" - universal-user-agent "^2.1.0" + universal-user-agent "^3.0.0" url-template "^2.0.8" "@octokit/plugin-enterprise-rest@^2.1.1": @@ -1762,9 +1762,9 @@ once "^1.4.0" "@octokit/request@^5.0.0": - version "5.0.0" - resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.0.0.tgz#d044d6e049aaa0580f78249c688a78a3cfab758b" - integrity sha512-eAknm2Aq+/uQDLHUn7KHHpXB7A/NFfWgaVN+ZhC6mQlCNRzCv242eLYgt6cC4h2DZL7mM+QidS/UtZVwYvQXBw== + version "5.0.1" + resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.0.1.tgz#6705c9a883db0ac0f58cee717e806b6575d4a199" + integrity sha512-SHOk/APYpfrzV1RNf7Ux8SZi+vZXhMIB2dBr4TQR6ExMX8R4jcy/0gHw26HLe1dWV7Wxe9WzYyDSEC0XwnoCSQ== dependencies: "@octokit/endpoint" "^5.1.0" "@octokit/request-error" "^1.0.1" @@ -1772,12 +1772,12 @@ is-plain-object "^3.0.0" node-fetch "^2.3.0" once "^1.4.0" - universal-user-agent "^2.1.0" + universal-user-agent "^3.0.0" "@octokit/rest@^16.16.0": - version "16.28.3" - resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-16.28.3.tgz#bf0fe6b3c50b0cc7838cfd4bf19701f763efbf9f" - integrity sha512-hzM2VvVn9o0+sS08y2pp33UF5tKy0XdR2z+/AFD583TjhHlX/9Lmdv3SmRiz0UC6rNqNXe1X7BiZ/QNUwVm27Q== + version "16.28.4" + resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-16.28.4.tgz#2f8ef08305033bc91256530d6a3c98eada700660" + integrity sha512-ZBsfD46t3VNkwealxm5zloVgQta8d8o4KYBR/hMAZ582IgjmSDKZdkjyv5w37IUCM3tcPZWKUT+kml9pEIC2GA== dependencies: "@octokit/request" "^5.0.0" "@octokit/request-error" "^1.0.2" @@ -1790,13 +1790,13 @@ lodash.uniq "^4.5.0" octokit-pagination-methods "^1.1.0" once "^1.4.0" - universal-user-agent "^2.0.0" + universal-user-agent "^3.0.0" url-template "^2.0.8" -"@polkadot/dev@^0.30.0-beta.21": - version "0.30.0-beta.21" - resolved "https://registry.yarnpkg.com/@polkadot/dev/-/dev-0.30.0-beta.21.tgz#f94369c48bf5d5d3ea5543fad9d317e5e37fd288" - integrity sha512-tCfjoSnhkCBEbDO5M0Tt1vTctlXlzFUj9NbjrVx9k4Lgy5b1l1KpuJZCVpUD8MRTUhUgEciYobECP7eSkJMStA== +"@polkadot/dev@^0.30.0-beta.22": + version "0.30.0-beta.22" + resolved "https://registry.yarnpkg.com/@polkadot/dev/-/dev-0.30.0-beta.22.tgz#c8dc31c9c76b5e6560404db87fd0ed87cb2ac4bf" + integrity sha512-yYIDiujMUalIs0NXRMxuXMLDvbnQHrkHj7aXNi2faIMV39O8fPfchzTT7hBoWOB8zEdKTP/YO79aVf4AUyNSMg== dependencies: "@babel/cli" "^7.5.0" "@babel/core" "^7.5.4" @@ -1811,17 +1811,17 @@ "@babel/runtime" "^7.5.4" "@types/jest" "^24.0.15" "@types/node" "^12.6.2" - "@typescript-eslint/eslint-plugin" "^1.11.0" - "@typescript-eslint/parser" "^1.11.0" + "@typescript-eslint/eslint-plugin" "^1.12.0" + "@typescript-eslint/parser" "^1.12.0" babel-core "^7.0.0-bridge.0" babel-jest "^24.8.0" babel-plugin-module-resolver "^3.2.0" chalk "^2.4.2" - coveralls "^3.0.3" + coveralls "^3.0.5" cpx "^1.5.0" eslint "^6.0.1" - eslint-config-semistandard "^13.0.0" - eslint-config-standard "^13.0.0" + eslint-config-semistandard "^14.0.0" + eslint-config-standard "^13.0.1" eslint-plugin-import "^2.18.0" eslint-plugin-node "^9.1.0" eslint-plugin-promise "^4.2.1" @@ -1835,8 +1835,8 @@ tslint "^5.18.0" tslint-config-standard "^8.0.1" typedoc "^0.14.2" - typedoc-plugin-markdown "^2.0.8" - typedoc-plugin-no-inherit "^1.1.8" + typedoc-plugin-markdown "^2.0.9" + typedoc-plugin-no-inherit "^1.1.9" typescript "^3.5.3" vuepress "^1.0.2" @@ -2071,39 +2071,39 @@ resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-12.0.12.tgz#45dd1d0638e8c8f153e87d296907659296873916" integrity sha512-SOhuU4wNBxhhTHxYaiG5NY4HBhDIDnJF60GU+2LqHAdKKer86//e4yg69aENCtQ04n0ovz+tq2YPME5t5yp4pw== -"@typescript-eslint/eslint-plugin@^1.11.0": - version "1.11.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-1.11.0.tgz#870f752c520db04db6d3668af7479026a6f2fb9a" - integrity sha512-mXv9ccCou89C8/4avKHuPB2WkSZyY/XcTQUXd5LFZAcLw1I3mWYVjUu6eS9Ja0QkP/ClolbcW9tb3Ov/pMdcqw== +"@typescript-eslint/eslint-plugin@^1.12.0": + version "1.12.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-1.12.0.tgz#96b4e08b5f998a198b8414508b1a289f9e8c549a" + integrity sha512-J/ZTZF+pLNqjXBGNfq5fahsoJ4vJOkYbitWPavA05IrZ7BXUaf4XWlhUB/ic1lpOGTRpLWF+PLAePjiHp6dz8g== dependencies: - "@typescript-eslint/experimental-utils" "1.11.0" + "@typescript-eslint/experimental-utils" "1.12.0" eslint-utils "^1.3.1" functional-red-black-tree "^1.0.1" regexpp "^2.0.1" tsutils "^3.7.0" -"@typescript-eslint/experimental-utils@1.11.0": - version "1.11.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-1.11.0.tgz#594abe47091cbeabac1d6f9cfed06d0ad99eb7e3" - integrity sha512-7LbfaqF6B8oa8cp/315zxKk8FFzosRzzhF8Kn/ZRsRsnpm7Qcu25cR/9RnAQo5utZ2KIWVgaALr+ZmcbG47ruw== +"@typescript-eslint/experimental-utils@1.12.0": + version "1.12.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-1.12.0.tgz#98417ee2e0c6fe8d1e50d934a6535d9c0f4277b6" + integrity sha512-s0soOTMJloytr9GbPteMLNiO2HvJ+qgQkRNplABXiVw6vq7uQRvidkby64Gqt/nA7pys74HksHwRULaB/QRVyw== dependencies: - "@typescript-eslint/typescript-estree" "1.11.0" + "@typescript-eslint/typescript-estree" "1.12.0" eslint-scope "^4.0.0" -"@typescript-eslint/parser@^1.11.0": - version "1.11.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-1.11.0.tgz#2f6d4f7e64eeb1e7c25b422f8df14d0c9e508e36" - integrity sha512-5xBExyXaxVyczrZvbRKEXvaTUFFq7gIM9BynXukXZE0zF3IQP/FxF4mPmmh3gJ9egafZFqByCpPTFm3dk4SY7Q== +"@typescript-eslint/parser@^1.12.0": + version "1.12.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-1.12.0.tgz#9965895ec4745578185965d63f21510f93a3f35a" + integrity sha512-0uzbaa9ZLCA5yMWJywnJJ7YVENKGWVUhJDV5UrMoldC5HoI54W5kkdPhTfmtFKpPFp93MIwmJj0/61ztvmz5Dw== dependencies: "@types/eslint-visitor-keys" "^1.0.0" - "@typescript-eslint/experimental-utils" "1.11.0" - "@typescript-eslint/typescript-estree" "1.11.0" + "@typescript-eslint/experimental-utils" "1.12.0" + "@typescript-eslint/typescript-estree" "1.12.0" eslint-visitor-keys "^1.0.0" -"@typescript-eslint/typescript-estree@1.11.0": - version "1.11.0" - resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-1.11.0.tgz#b7b5782aab22e4b3b6d84633652c9f41e62d37d5" - integrity sha512-fquUHF5tAx1sM2OeRCC7wVxFd1iMELWMGCzOSmJ3pLzArj9+kRixdlC4d5MncuzXpjEqc6045p3KwM0o/3FuUA== +"@typescript-eslint/typescript-estree@1.12.0": + version "1.12.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-1.12.0.tgz#d8dd0a7cffb5e3c0c3e98714042d83e316dfc9a9" + integrity sha512-nwN6yy//XcVhFs0ZyU+teJHB8tbCm7AIA8mu6E2r5hu6MajwYBY3Uwop7+rPZWUN/IUOHpL8C+iUPMDVYUU3og== dependencies: lodash.unescape "4.0.1" semver "5.5.0" @@ -3050,9 +3050,9 @@ bcrypt-pbkdf@^1.0.0: tweetnacl "^0.14.3" before-after-hook@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.0.1.tgz#a21dc15582fee3f035c39dcbb77f6892a99ada36" - integrity sha512-dpgMHA51KZyCu7uuxF6FCkN+scfGd/6aLxEr/14vKUo/1nPxcd2fhFv4BgYCbWxKt7JfgpbjJq9nc30Ip/p2uw== + version "2.1.0" + resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.1.0.tgz#b6c03487f44e24200dd30ca5e6a1979c5d2fb635" + integrity sha512-IWIbu7pMqyw3EAJHzzHbWa85b6oud/yfKYg5rqB5hNE8CeMi3nX+2C2sj0HswfblST86hpVEOAb9x34NZd6P7A== big.js@^3.1.3: version "3.2.0" @@ -3252,12 +3252,12 @@ browserify-zlib@^0.2.0: pako "~1.0.5" browserslist@^4.0.0, browserslist@^4.3.4, browserslist@^4.6.0, browserslist@^4.6.2, browserslist@^4.6.3: - version "4.6.4" - resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.6.4.tgz#fd0638b3f8867fec2c604ed0ed9300379f8ec7c2" - integrity sha512-ErJT8qGfRt/VWHSr1HeqZzz50DvxHtr1fVL1m5wf20aGrG8e1ce8fpZ2EjZEfs09DDZYSvtRaDlMpWslBf8Low== + version "4.6.6" + resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.6.6.tgz#6e4bf467cde520bc9dbdf3747dafa03531cec453" + integrity sha512-D2Nk3W9JL9Fp/gIcWei8LrERCS+eXu9AM5cfXA8WEZ84lFks+ARnZ0q/R69m2SV3Wjma83QDDPxsNKXUwdIsyA== dependencies: - caniuse-lite "^1.0.30000981" - electron-to-chromium "^1.3.188" + caniuse-lite "^1.0.30000984" + electron-to-chromium "^1.3.191" node-releases "^1.1.25" bs58@^4.0.1: @@ -3474,10 +3474,10 @@ caniuse-api@^3.0.0: lodash.memoize "^4.1.2" lodash.uniq "^4.5.0" -caniuse-lite@^1.0.0, caniuse-lite@^1.0.30000980, caniuse-lite@^1.0.30000981: - version "1.0.30000983" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30000983.tgz#ab3c70061ca2a3467182a10ac75109b199b647f8" - integrity sha512-/llD1bZ6qwNkt41AsvjsmwNOoA4ZB+8iqmf5LVyeSXuBODT/hAMFNVOh84NdUzoiYiSKqo5vQ3ZzeYHSi/olDQ== +caniuse-lite@^1.0.0, caniuse-lite@^1.0.30000980, caniuse-lite@^1.0.30000984: + version "1.0.30000984" + resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30000984.tgz#dc96c3c469e9bcfc6ad5bdd24c77ec918ea76fe0" + integrity sha512-n5tKOjMaZ1fksIpQbjERuqCyfgec/m9pferkFQbLmWtqLUdmt12hNhjSwsmPdqeiG2NkITOQhr1VYIwWSAceiA== capture-exit@^2.0.0: version "2.0.0" @@ -4027,13 +4027,13 @@ cosmiconfig@^5.0.0, cosmiconfig@^5.1.0: js-yaml "^3.13.1" parse-json "^4.0.0" -coveralls@^3.0.3: - version "3.0.4" - resolved "https://registry.yarnpkg.com/coveralls/-/coveralls-3.0.4.tgz#f50233c9c62fd0973f710fce85fd19dba24cff4b" - integrity sha512-eyqUWA/7RT0JagiL0tThVhjbIjoiEUyWCjtUJoOPcWoeofP5WK/jb2OJYoBFrR6DvplR+AxOyuBqk4JHkk5ykA== +coveralls@^3.0.5: + version "3.0.5" + resolved "https://registry.yarnpkg.com/coveralls/-/coveralls-3.0.5.tgz#28d7274c6c9827aa85537eab82d66e7e62d0d527" + integrity sha512-/KD7PGfZv/tjKB6LoW97jzIgFqem0Tu9tZL9/iwBnBd8zkIZp7vT1ZSHNvnr0GSQMV/LTMxUstWg8WcDDUVQKg== dependencies: growl "~> 1.10.0" - js-yaml "^3.11.0" + js-yaml "^3.13.1" lcov-parse "^0.0.10" log-driver "^1.2.7" minimist "^1.2.0" @@ -4768,10 +4768,10 @@ ee-first@1.1.1: resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d" integrity sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0= -electron-to-chromium@^1.3.188: - version "1.3.189" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.189.tgz#aa84055eb36d364a68852ad2d25e1315a1d06196" - integrity sha512-C26Kv6/rLNmGDaPR5HORMtTQat9aWBBKjQk9aFtN1Bk6cQBSw8cYdsel/mcrQlNlMMjt1sAKsTYqf77+sK2uTw== +electron-to-chromium@^1.3.191: + version "1.3.191" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.191.tgz#c451b422cd8b2eab84dedabab5abcae1eaefb6f0" + integrity sha512-jasjtY5RUy/TOyiUYM2fb4BDaPZfm6CXRFeJDMfFsXYADGxUN49RBqtgB7EL2RmJXeIRUk9lM1U6A5yk2YJMPQ== elliptic@^6.0.0, elliptic@^6.4.1: version "6.5.0" @@ -4921,15 +4921,15 @@ escodegen@^1.9.1: optionalDependencies: source-map "~0.6.1" -eslint-config-semistandard@^13.0.0: - version "13.0.0" - resolved "https://registry.yarnpkg.com/eslint-config-semistandard/-/eslint-config-semistandard-13.0.0.tgz#52ecf19081e1b6b1ccc839d049f6429ca6252ad7" - integrity sha512-ZuImKnf/9LeZjr6dtRJ0zEdQbjBwXu0PJR3wXJXoQeMooICMrYPyD70O1tIA9Ng+wutgLjB7UXvZOKYPvzHg+w== +eslint-config-semistandard@^14.0.0: + version "14.0.0" + resolved "https://registry.yarnpkg.com/eslint-config-semistandard/-/eslint-config-semistandard-14.0.0.tgz#e3e00d232768f2e76685959de640f22c207e74aa" + integrity sha512-m01m2BQzG7nrrLVIG2Wr+htnfhc5RjzeXFESvSsh24uE8uLSrxo8nbcu6RAShfulrsv7Gp850Gct/oMaLHXUkg== -eslint-config-standard@^13.0.0: - version "13.0.0" - resolved "https://registry.yarnpkg.com/eslint-config-standard/-/eslint-config-standard-13.0.0.tgz#8032d6fe954f651399763ba4607294aa3c201a23" - integrity sha512-GRvEpe2lnML3qPqNryLPjgbU0nDeGBEWOC/IMfn/DjDLyO7DoASyDtGtPhN+Z+XDGUzrHWF8dKDLdDx2bO6CGw== +eslint-config-standard@^13.0.1: + version "13.0.1" + resolved "https://registry.yarnpkg.com/eslint-config-standard/-/eslint-config-standard-13.0.1.tgz#c9c6ffe0cfb8a51535bc5c7ec9f70eafb8c6b2c0" + integrity sha512-zLKp4QOgq6JFgRm1dDCVv1Iu0P5uZ4v5Wa4DTOkg2RFMxdCX/9Qf7lz9ezRj2dBRa955cWQF/O/LWEiYWAHbTw== eslint-import-resolver-node@^0.3.2: version "0.3.2" @@ -7490,9 +7490,9 @@ levn@^0.3.0, levn@~0.3.0: type-check "~0.3.2" linkify-it@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-2.1.0.tgz#c4caf38a6cd7ac2212ef3c7d2bde30a91561f9db" - integrity sha512-4REs8/062kV2DSHxNfq5183zrqXMl7WP0WzABH9IeJI+NLm429FgE1PDecltYfnOoFDFlZGh2T8PfZn0r+GTRg== + version "2.2.0" + resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-2.2.0.tgz#e3b54697e78bf915c70a38acd78fd09e0058b1cf" + integrity sha512-GnAl/knGn+i1U/wjBz3akz2stz+HrHLsxMwHQGofCDfPvlf+gDKN58UtfmUquTY4/MXeE2x7k19KQmeoZi94Iw== dependencies: uc.micro "^1.0.1" @@ -9076,9 +9076,9 @@ pn@^1.1.0: integrity sha512-2qHaIQr2VLRFoxe2nASzsV6ef4yOOH+Fi9FBOVH6cqeSgUnoyySPZkxzLuzd+RYOQTRpROA0ztTMqxROKSb/nA== portfinder@^1.0.13, portfinder@^1.0.20: - version "1.0.20" - resolved "https://registry.yarnpkg.com/portfinder/-/portfinder-1.0.20.tgz#bea68632e54b2e13ab7b0c4775e9b41bf270e44a" - integrity sha512-Yxe4mTyDzTd59PZJY4ojZR8F+E5e97iq2ZOHPz3HDgSvYC5siNad2tLooQ5y5QHyQhc3xVqvyk/eNA3wuoa7Sw== + version "1.0.21" + resolved "https://registry.yarnpkg.com/portfinder/-/portfinder-1.0.21.tgz#60e1397b95ac170749db70034ece306b9a27e324" + integrity sha512-ESabpDCzmBS3ekHbmpAIiESq3udRsCBGiBZLsC+HgBKv2ezb0R4oG+7RnYEVZ/ZCfhel5Tx3UzdNWA0Lox2QCA== dependencies: async "^1.5.2" debug "^2.2.0" @@ -11366,15 +11366,15 @@ typedoc-default-themes@^0.5.0: resolved "https://registry.yarnpkg.com/typedoc-default-themes/-/typedoc-default-themes-0.5.0.tgz#6dc2433e78ed8bea8e887a3acde2f31785bd6227" integrity sha1-bcJDPnjti+qOiHo6zeLzF4W9Yic= -typedoc-plugin-markdown@^2.0.8: - version "2.0.8" - resolved "https://registry.yarnpkg.com/typedoc-plugin-markdown/-/typedoc-plugin-markdown-2.0.8.tgz#9b63a0ad5a6dfe11c62c04016ab34422db00276d" - integrity sha512-lpaesvB5N2teG6uI9CvaX0YF0O78EGo8HAk24LYe8lkEfR4+ymgZe178luGaJiOc54fKycW+MoS8qZPoX065fg== +typedoc-plugin-markdown@^2.0.9: + version "2.0.9" + resolved "https://registry.yarnpkg.com/typedoc-plugin-markdown/-/typedoc-plugin-markdown-2.0.9.tgz#0c20ad777813393bb4ee97a1d7790dc1c2bf8ec8" + integrity sha512-EKuJ7TaNliHno+vGW3GHjOaO/zNdnsK7wZlTbF+jSFJ/HGSNHysnnT/MO20TnDtmQfRgMAz7ltag5Ko6r/hr/Q== -typedoc-plugin-no-inherit@^1.1.8: - version "1.1.8" - resolved "https://registry.yarnpkg.com/typedoc-plugin-no-inherit/-/typedoc-plugin-no-inherit-1.1.8.tgz#4abc1ca18babb1ad73ff303fb358ffff111b76bc" - integrity sha512-bcyYnRxXG1Wz1pA9ZUeFQHoO1sZJsgbPc7ynC+HxSCfeamUX228pVed03OzMJPFsmSNdV0/OmD/SPYhQ6jQXig== +typedoc-plugin-no-inherit@^1.1.9: + version "1.1.9" + resolved "https://registry.yarnpkg.com/typedoc-plugin-no-inherit/-/typedoc-plugin-no-inherit-1.1.9.tgz#918b05247136ac1252f4444e685a175922156cb6" + integrity sha512-Mw9569aOopX/OdcVgjG2GxsfDpPhvXPbptlYLgDWjvgWYZjzeKxkMFZOU9zbTUnB9KGDj8fFuG9yvcczq09Kyw== typedoc@^0.14.2: version "0.14.2" @@ -11492,10 +11492,10 @@ unique-slug@^2.0.0: dependencies: imurmurhash "^0.1.4" -universal-user-agent@^2.0.0, universal-user-agent@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/universal-user-agent/-/universal-user-agent-2.1.0.tgz#5abfbcc036a1ba490cb941f8fd68c46d3669e8e4" - integrity sha512-8itiX7G05Tu3mGDTdNY2fB4KJ8MgZLS54RdG6PkkfwMAavrXu1mV/lls/GABx9O3Rw4PnTtasxrvbMQoBYY92Q== +universal-user-agent@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/universal-user-agent/-/universal-user-agent-3.0.0.tgz#4cc88d68097bffd7ac42e3b7c903e7481424b4b9" + integrity sha512-T3siHThqoj5X0benA5H0qcDnrKGXzU8TKoX15x/tQHw1hQBvIEBHjxQ2klizYsqBOO/Q+WuxoQUihadeeqDnoA== dependencies: os-name "^3.0.0"