Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix flow bugs #91

Merged
merged 6 commits into from
Nov 7, 2018
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
{
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 6,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is because the version of eslint we use is super recent so it can support a higher version of babel than we support for our actual codebase. Notably, it includes some change that requires you to change the order decorators are associated in your class. To disable this feature on linting (to match the version we are actually compiling with) I had to add this very cryptic extra field.

You can see the occasional Github issue come up related to this topic: babel/babel-eslint#662

"sourceType": "module",
"ecmaFeatures": {
"legacyDecorators": true
}
},
"extends": "airbnb",
"env": {
"browser": true,
Expand All @@ -16,18 +23,35 @@
"import/no-unresolved": ["error", { "ignore": ["electron"] }],
"import/no-extraneous-dependencies": "off",
"import/no-dynamic-require": "off",
"import/no-named-as-default": "off",
"import/no-named-as-default-member": "off",
"import/prefer-default-export": "off",
"import/order": "off",
"lines-between-class-members": "off",
"no-multi-spaces": "off",
"no-restricted-globals": "off",
"no-restricted-syntax": "off",
"no-return-await": "off",
"no-use-before-define": "off",
"object-curly-newline": "off",
"operator-linebreak": 0,
"prefer-destructuring": 0,
"promise/param-names": 2,
"promise/always-return": 2,
"promise/catch-or-return": 2,
"promise/no-native": 0,
"react/button-has-type": 1,
"react/destructuring-assignment": 0,
"react/no-array-index-key": 1,
"react/jsx-no-bind": "off",
"react/jsx-filename-extension": ["error", { "extensions": [".js", ".jsx"] }],
"react/jsx-closing-bracket-location": 1,
"react/jsx-one-expression-per-line": "off",
"react/jsx-wrap-multilines": "off",
"react/prefer-stateless-function": "off",
"react/no-unused-prop-types": "off",
"react/prop-types": 0,
"react/require-default-props": 1,
"react/sort-comp": 0,
"class-methods-use-this": 0,
"no-duplicate-imports": 0,
Expand All @@ -40,7 +64,7 @@
"prefer-template": 0,
"no-unused-vars": 1,
"no-trailing-spaces": 1,
"padded-blocks": 1,
"padded-blocks": 0,
"no-undef": 1,
"arrow-body-style": 1,
"key-spacing": 1,
Expand All @@ -52,7 +76,6 @@
"spaced-comment": 1,
"quotes": 1,
"import/imports-first": 1,
"no-multi-spaces": 1,
"no-multiple-empty-lines": 1,
"react/jsx-indent": 1,
"flowtype/define-flow-type": 1,
Expand Down
1 change: 1 addition & 0 deletions .flowconfig
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
.*/.circleci/.*

[include]
../node_modules/eslint-plugin-jsx-a11y
SebastienGllmt marked this conversation as resolved.
Show resolved Hide resolved

[libs]
flow/declarations/
Expand Down
4 changes: 2 additions & 2 deletions app/api/ada/adaAccount.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ export function createCryptoAccount(
accountIndex: number = ACCOUNT_INDEX
): CryptoAccount {
const cryptoWallet = getCryptoWalletFromMasterKey(masterKey, walletPassword);
const result = getResultOrFail(Wallet.newAccount(cryptoWallet, accountIndex));
return Object.assign({ account: accountIndex }, result);
const result: CryptoAccount = getResultOrFail(Wallet.newAccount(cryptoWallet, accountIndex));
return Object.assign({}, { account: accountIndex }, result);
}
11 changes: 6 additions & 5 deletions app/api/ada/adaAddress.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const { MAX_ALLOWED_UNUSED_ADDRESSES } = config.wallets;

export function isValidAdaAddress(address: string): Promise<boolean> {
try {
const result = getResultOrFail(Wallet.checkAddress(getAddressInHex(address)));
const result: boolean = getResultOrFail(Wallet.checkAddress(getAddressInHex(address)));
return Promise.resolve(result);
} catch (validateAddressError) {
Logger.error('adaAddress::isValidAdaAddress error: ' +
Expand Down Expand Up @@ -94,8 +94,9 @@ export async function createAdaAddress(
): Promise<AdaAddress> {
const filteredAddresses = await getAdaAddressesByType(addressType);
const addressIndex = filteredAddresses.length;
const [address] = getResultOrFail(
Wallet.generateAddresses(cryptoAccount, addressType, [addressIndex]));
const [address]: Array<string> = getResultOrFail(
Wallet.generateAddresses(cryptoAccount, addressType, [addressIndex])
);
return toAdaAddress(cryptoAccount.account, addressType, addressIndex, address);
}

Expand All @@ -112,8 +113,8 @@ export async function saveAsAdaAddresses(
addresses: Array<string>,
addressType: AddressType
): Promise<void> {
const mappedAddresses: Array<AdaAddress> = addresses.map((hash, index) =>
const mappedAddresses: Array<AdaAddress> = addresses.map((hash, index) => (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I’m curious. I think it shouldn’t be necessary to add those 2 extra ( ). is it a configuration of the eslint?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The rule in Javascript is you can have a => on a new line without putting any parenthesis.

The eslint rules says if you put a => on a separate line, you should put () around it even if it's not required.

I think this makes sense. It's the same reason linters for various languages complain when you have an if that don't use curly braces. It's a common source of bugs when refactoring code.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general though eslint is super strict that parenthesis should go on new lines. I agree that in cases like this it improves readability but in other places in the PR it you can see it just kind of bloats the code. Usually in cases where there is upside & downside to a linter rule I tend to just follow what the linter says since at least it allows us to standardize on some rule even if we don't always agree with it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eslint is a rule applier so it depends on the rules that we want. I didn’t know if you added the rule / if you preferred that way or both. 👍

toAdaAddress(cryptoAccount.account, addressType, index, hash)
);
));
return saveAddresses(mappedAddresses, addressType);
}
2 changes: 1 addition & 1 deletion app/api/ada/adaLocalStorage.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @flow
import type { AdaWallet } from '../ada/adaTypes';
import type { AdaWallet } from './adaTypes';

const storageKeys = {
ACCOUNT_KEY: 'ACCOUNT',
Expand Down
18 changes: 12 additions & 6 deletions app/api/ada/adaTransactions/adaNewTransactions.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
import { getResultOrFail } from '../lib/cardanoCrypto/cryptoUtils';
import type {
AdaAddresses,
AdaAddress,
AdaTransactionFee,
UTXO
} from '../adaTypes';
Expand Down Expand Up @@ -74,6 +75,7 @@ export async function newAdaTransaction(
): Promise<any> {
const masterKey = getWalletMasterKey();
const cryptoWallet = getCryptoWalletFromMasterKey(masterKey, password);
// eslint-disable-next-line camelcase
const [{ cbor_encoded_tx, changed_used }, changeAdaAddr] =
await _getAdaTransaction(receiver, amount, cryptoWallet);
const signedTx = Buffer.from(cbor_encoded_tx).toString('base64');
Expand All @@ -99,10 +101,12 @@ export async function getAllUTXOsForAddresses(
): Promise<Array<UTXO>> {
try {
const groupsOfAddresses = _.chunk(addresses, addressesLimit);
const promises = groupsOfAddresses.map(groupOfAddresses =>
getUTXOsForAddresses(groupOfAddresses));
return Promise.all(promises).then(groupsOfUTXOs =>
groupsOfUTXOs.reduce((acc, groupOfUTXOs) => acc.concat(groupOfUTXOs), []));
const promises = groupsOfAddresses
.map(groupOfAddresses => getUTXOsForAddresses(groupOfAddresses));
return Promise.all(promises)
.then(groupsOfUTXOs => (
groupsOfUTXOs.reduce((acc, groupOfUTXOs) => acc.concat(groupOfUTXOs), [])
));
} catch (getUtxosError) {
Logger.error('adaNewTransactions::getAllUTXOsForAddresses error: ' +
stringifyError(getUtxosError));
Expand All @@ -115,7 +119,7 @@ export async function getAdaTransactionFromSenders(
receiver: string,
amount: string,
cryptoWallet: CryptoWallet
) {
): Promise<[SpendResponse, AdaAddress]> {
const cryptoAccount = getSingleCryptoAccount();
const addressesMap = await getAdaAddressesMap();
const addresses = mapToList(addressesMap);
Expand All @@ -124,7 +128,9 @@ export async function getAdaTransactionFromSenders(
const outputs = [{ address: receiver, value: amount }];
const senderUtxos = await getAllUTXOsForAddresses(_getAddresses(senders));
const inputs = _mapUTXOsToInputs(senderUtxos, addressesMap);
const result = getResultOrFail(Wallet.spend(cryptoWallet, inputs, outputs, changeAddr));
const result: SpendResponse = getResultOrFail(
Wallet.spend(cryptoWallet, inputs, outputs, changeAddr)
);
return [result, changeAdaAddr];
}

Expand Down
20 changes: 11 additions & 9 deletions app/api/ada/adaTransactions/adaTransactionsHistory.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
UpdateAdaTxsHistoryError,
} from '../errors';
import type
{
{
AdaTransaction,
AdaTransactions,
AdaTransactionInputOutput
Expand Down Expand Up @@ -72,12 +72,12 @@ async function _updateAdaTxsHistory(
) {
try {
const mostRecentTx = Object.assign({}, existingTransactions[0]);
const dateFrom = mostRecentTx.ctMeta ?
moment(mostRecentTx.ctMeta.ctmUpdate) :
moment(new Date(0));
const mappedTxs = await _getTxsForChunksOfAddresses(addresses, groupOfAddresses =>
const dateFrom = mostRecentTx.ctMeta
? moment(mostRecentTx.ctMeta.ctmUpdate)
: moment(new Date(0));
const mappedTxs = await _getTxsForChunksOfAddresses(addresses, groupOfAddresses => (
_updateAdaTxsHistoryForGroupOfAddresses([], groupOfAddresses, dateFrom, addresses)
);
));
return saveTxs(mappedTxs);
} catch (error) {
Logger.error('adaTransactionsHistory::updateAdaTxsHistory error: ' + stringifyError(error));
Expand Down Expand Up @@ -113,7 +113,8 @@ async function _updateAdaTxsHistoryForGroupOfAddresses(
}

const transactions = previousTxs.concat(
_mapToAdaTxs(history, allAddresses));
_mapToAdaTxs(history, allAddresses)
);
if (history.length === transactionsLimit) {
return await _updateAdaTxsHistoryForGroupOfAddresses(
transactions,
Expand Down Expand Up @@ -145,7 +146,7 @@ function _mapInputOutput(addresses, amounts): AdaTransactionInputOutput {
}

function _spenderData(txInputs, txOutputs, addresses) {
const sum = toSum =>
const sum = toSum => (
toSum.reduce(
({ totalAmount, count }, [address, { getCCoin }]) => {
if (addresses.indexOf(address) < 0) return { totalAmount, count };
Expand All @@ -158,7 +159,8 @@ function _spenderData(txInputs, txOutputs, addresses) {
totalAmount: new BigNumber(0),
count: 0
}
);
)
);

const incoming = sum(txOutputs);
const outgoing = sum(txInputs);
Expand Down
20 changes: 14 additions & 6 deletions app/api/ada/adaWallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,13 @@ export function createAdaWallet({
return [adaWallet, masterKey];
}

export const isValidMnemonic = (phrase: string, numberOfWords: ?number) =>
isValidAdaMnemonic(phrase, numberOfWords);
export const isValidMnemonic = (phrase: string, numberOfWords: ?number) => (
isValidAdaMnemonic(phrase, numberOfWords)
);

export const getAdaAccountRecoveryPhrase = (): AdaWalletRecoveryPhraseResponse =>
generateAdaMnemonic();
export const getAdaAccountRecoveryPhrase = (): AdaWalletRecoveryPhraseResponse => (
generateAdaMnemonic()
);

export async function getBalance(
addresses: Array<string>
Expand All @@ -108,8 +110,14 @@ export async function getBalance(
const promises =
groupsOfAddresses.map(groupOfAddresses => getUTXOsSumsForAddresses(groupOfAddresses));
const partialAmounts = await Promise.all(promises);
return partialAmounts.reduce((acc, partialAmount) =>
acc.plus(partialAmount.sum ? new BigNumber(partialAmount.sum) : new BigNumber(0)),
return partialAmounts.reduce(
(acc, partialAmount) => (
acc.plus(
partialAmount.sum
? new BigNumber(partialAmount.sum)
: new BigNumber(0)
)
),
new BigNumber(0)
);
} catch (error) {
Expand Down
14 changes: 8 additions & 6 deletions app/api/ada/daedalusTransfer.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
Logger,
stringifyError,
} from '../../utils/logging';
import { getResultOrFail } from '../ada/lib//cardanoCrypto/cryptoUtils';
import { getResultOrFail } from './lib/cardanoCrypto/cryptoUtils';
import { LOVELACES_PER_ADA } from '../../config/numbersConfig';
import { getBalance } from './adaWallet';
import {
Expand Down Expand Up @@ -39,10 +39,12 @@ export function getAddressesWithFunds(payload: {
}): Array<CryptoDaedalusAddressRestored> {
try {
const { secretWords, addresses } = payload;
const checker =
getResultOrFail(RandomAddressChecker.newCheckerFromMnemonics(secretWords));
const addressesWithFunds =
getResultOrFail(RandomAddressChecker.checkAddresses(checker, addresses));
const checker: CryptoAddressChecker = getResultOrFail(
RandomAddressChecker.newCheckerFromMnemonics(secretWords)
);
const addressesWithFunds: Array<CryptoDaedalusAddressRestored> = getResultOrFail(
RandomAddressChecker.checkAddresses(checker, addresses)
);
return addressesWithFunds;
} catch (error) {
Logger.error(`daedalusTransfer::getAddressesWithFunds ${stringifyError(error)}`);
Expand All @@ -65,7 +67,7 @@ export async function generateTransferTx(payload: {
const wallet = getCryptoDaedalusWalletFromMnemonics(secretWords);
const inputs = _getInputs(senderUtxos, addressesWithFunds);
const output = await _getReceiverAddress();
const tx = getResultOrFail(Wallet.move(wallet, inputs, output));
const tx: MoveResponse = getResultOrFail(Wallet.move(wallet, inputs, output));
return {
recoveredBalance: recoveredBalance.dividedBy(LOVELACES_PER_ADA),
fee: new BigNumber(tx.fee).dividedBy(LOVELACES_PER_ADA),
Expand Down
14 changes: 0 additions & 14 deletions app/api/ada/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,6 @@ import { defineMessages } from 'react-intl';
import LocalizableError from '../../i18n/LocalizableError';

const messages = defineMessages({
apiMethodNotYetImplementedError: {
id: 'api.errors.ApiMethodNotYetImplementedError',
defaultMessage: '!!!This API method is not yet implemented.',
description: '"This API method is not yet implemented." error message.'
},
walletAlreadyImportedError: {
id: 'api.errors.WalletAlreadyImportedError',
defaultMessage: '!!!Wallet you are trying to import already exists.',
Expand Down Expand Up @@ -114,15 +109,6 @@ const messages = defineMessages({
}
});

export class ApiMethodNotYetImplementedError extends LocalizableError {
constructor() {
super({
id: messages.apiMethodNotYetImplementedError.id,
defaultMessage: messages.apiMethodNotYetImplementedError.defaultMessage,
});
}
}

export class WalletAlreadyImportedError extends LocalizableError {
constructor() {
super({
Expand Down
Loading