Skip to content

Commit

Permalink
Merge pull request #3468 from LiskHQ/3459-adapt-tx-broadcast
Browse files Browse the repository at this point in the history
  • Loading branch information
usama authored Apr 9, 2021
2 parents 217f46e + fa23341 commit 0a11e3b
Show file tree
Hide file tree
Showing 20 changed files with 179 additions and 109 deletions.
4 changes: 2 additions & 2 deletions src/components/screens/login/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import grid from 'flexboxgrid/dist/flexboxgrid.css';
import { Link } from 'react-router-dom';
import { routes, networks, networkKeys } from '@constants';
import { parseSearchParams, stringifySearchParams } from '@utils/searchParams';
import { extractAddress } from '@utils/account';
import { extractAddressFromPassphrase } from '@utils/account';
import { getAutoLogInData, findMatchingLoginNetwork } from '@utils/login';
import { getNetworksList } from '@utils/getNetwork';
import Piwik from '@utils/piwik';
Expand Down Expand Up @@ -97,7 +97,7 @@ class Login extends React.Component {
Piwik.trackingEvent('Login', 'button', 'Login submission');
const { network, login } = this.props;
this.secondIteration = true;
if (this.alreadyLoggedWithThisAddress(extractAddress(passphrase), network)) {
if (this.alreadyLoggedWithThisAddress(extractAddressFromPassphrase(passphrase), network)) {
this.redirectToReferrer();
} else {
login({ passphrase });
Expand Down
4 changes: 2 additions & 2 deletions src/components/screens/register/backupPassphrase.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React from 'react';
import { expect } from 'chai';
import { mount } from 'enzyme';
import { spy } from 'sinon';
import { extractAddress } from '../../../utils/account';
import { extractAddressFromPassphrase } from '../../../utils/account';
import { generatePassphrase } from '../../../utils/passphrase';
import BackupPassphrase from './backupPassphrase';

Expand All @@ -12,7 +12,7 @@ describe('Register Process - Backup Passphrase', () => {

const passphrase = generatePassphrase();
const account = {
address: extractAddress(passphrase),
address: extractAddressFromPassphrase(passphrase),
passphrase,
};

Expand Down
4 changes: 2 additions & 2 deletions src/components/screens/register/register.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';
import grid from 'flexboxgrid/dist/flexboxgrid.css';
import { generatePassphrase } from '@utils/passphrase';
import { extractAddress } from '@utils/account';
import { extractAddressFromPassphrase } from '@utils/account';
import { routes } from '@constants';
import ChooseAvatar from './chooseAvatar';
import BackupPassphrase from './backupPassphrase';
Expand All @@ -25,7 +25,7 @@ class Register extends React.Component {
componentDidMount() {
const passphrases = [...Array(5)].map(generatePassphrase);
const accounts = passphrases.map(pass => ({
address: extractAddress(pass),
address: extractAddressFromPassphrase(pass),
passphrase: pass,
}));
this.setState({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const DelegateVotesView = ({
className={`${grid.col} ${grid['col-xs-12']} ${voters.data.length ? styles.votesContainer : ''} votes-container`}
>
<Table
data={voters.data}
data={voters.data.votes}
canLoadMore={voters.meta && voters.data.length < voters.meta.count}
isLoading={voters.isLoading}
iterationKey="address"
Expand Down
5 changes: 4 additions & 1 deletion src/components/screens/wallet/delegateProfile/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ const apis = {
},
voters: {
apiUtil: (network, params) => getVoters({ network, params }),
defaultData: [],
defaultData: {
account: {},
votes: [],
},
getApiParams: (_, ownProps) => ({ address: ownProps.account.summary.address }),
transformResponse: response => (response.data.votes ?? []),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import TransactionAsset from './txAsset';
import DialogLink from '../../../toolbox/dialog/link';
import styles from './transactions.css';

// eslint-disable-next-line complexity
const TransactionRow = ({
data, className, t, host, delegates,
}) => {
Expand Down
12 changes: 2 additions & 10 deletions src/components/screens/wallet/votes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,12 @@ import { getAccounts } from '@utils/api/account';
import withData from '@utils/withData';
import Votes from './votes';

const emptyVotes = {
account: {},
votes: [],
};

const apis = {
votes: {
apiUtil: (network, params) => getVotes({ network, params }),
defaultData: {
account: {},
votes: [],
},
defaultData: [],
autoload: false,
transformResponse: response => response.data?.votes ?? emptyVotes,
transformResponse: response => response.data?.votes ?? [],
},
accounts: {
apiUtil: (network, params) => getAccounts({ network, params }),
Expand Down
8 changes: 4 additions & 4 deletions src/components/screens/wallet/votes/votes.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ const Votes = ({

// Fetch delegate profiles to define rank, productivity and delegate weight
useEffect(() => {
if (isEmpty(accounts.data) && votes.data.votes.length) {
const addressList = votes.data.votes.map(vote => vote.address);
if (isEmpty(accounts.data) && votes.data.length) {
const addressList = votes.data.map(vote => vote.address);
accounts.loadData({ addressList });
}
}, [votes.data]);

const areLoading = accounts.isLoading || votes.isLoading;
const filteredVotes = votes.data.votes.filter((vote) => {
const filteredVotes = votes.data.filter((vote) => {
if (!vote.username) return false;
return vote.username.indexOf(filterValue) > -1;
});
Expand All @@ -68,7 +68,7 @@ const Votes = ({
)}
<Input
className="search"
disabled={!votes.data.votes.length}
disabled={!votes.data.length}
name="filter"
value={filterValue}
placeholder={t('Filter by name')}
Expand Down
4 changes: 2 additions & 2 deletions src/components/toolbox/accountVisual/demo.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import Waypoint from 'react-waypoint';
import { extractAddress } from '@utils/account';
import { extractAddressFromPassphrase } from '@utils/account';
import { generatePassphraseFromSeed } from '@utils/passphrase';
import AccountVisual from '.';
import DemoRenderer from '../demoRenderer';
Expand Down Expand Up @@ -29,7 +29,7 @@ class AccountVisualDemo extends React.Component {
}

const accounts = bytes.map(seed => generatePassphraseFromSeed({ seed }))
.map(extractAddress);
.map(extractAddressFromPassphrase);

function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
Expand Down
2 changes: 1 addition & 1 deletion src/components/toolbox/table/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ const Table = ({
data={emptyState}
error={error}
isLoading={isLoading}
isListEmpty={data.length === 0}
isListEmpty={data?.length === 0}
className={styles.emptyState}
/>
<Error data={error} isLoading={isLoading} />
Expand Down
3 changes: 3 additions & 0 deletions src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import ipcLocale from '@utils/ipcLocale';
import i18n from './i18n';
import App from './app';

// eslint-disable-next-line no-extend-native
BigInt.prototype.toJSON = function () { return `${this.toString()}n`; };

if (PRODUCTION) {
externalLinks.init();
}
Expand Down
8 changes: 6 additions & 2 deletions src/store/actions/account.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { to } from 'await-to-js';
import { toast } from 'react-toastify';
import { loginTypes, actionTypes } from '@constants';
import { loginTypes, actionTypes, tokenMap } from '@constants';
import { getAccount } from '@utils/api/account';
import { getConnectionErrorMessage } from '@utils/getNetwork';
import { networkStatusUpdated } from './network';
Expand Down Expand Up @@ -68,7 +68,11 @@ export const accountDataUpdated = tokensTypes =>
: [settings.token.active];

const params = activeTokens.reduce((acc, token) => {
acc[token] = { address: account.info[token].address };
if (token === tokenMap.LSK.key) {
acc[token] = { address: account.info[tokenMap.LSK.key].summary.address };
} else {
acc[token] = { address: account.info[token].address };
}
return acc;
}, {});

Expand Down
26 changes: 9 additions & 17 deletions src/store/actions/transactions.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import to from 'await-to-js';
import {
actionTypes, tokenMap, MODULE_ASSETS_NAME_ID_MAP, loginTypes,
} from '@constants';
import { extractAddress } from '@utils/account';
import { extractAddressFromPublicKey } from '@utils/account';
import { getTransactions, create, broadcast } from '@utils/api/transaction';
import { signSendTransaction } from '@utils/hwManager';
import { passphraseUsed } from './account';
import { loadingStarted, loadingFinished } from './loading';
import { transformTransaction } from '../../utils/api/transaction/lsk';

/**
* Action trigger when user logout from the application
Expand All @@ -24,10 +25,7 @@ export const emptyTransactionsData = () => ({ type: actionTypes.emptyTransaction
*/
export const addNewPendingTransaction = data => ({
type: actionTypes.addNewPendingTransaction,
data: {
...data,
senderId: extractAddress(data.senderPublicKey),
},
data,
});

/**
Expand Down Expand Up @@ -66,18 +64,16 @@ export const transactionsRetrieved = ({
data: {
offset,
address,
filters,
confirmed: response.data,
count: response.meta.total,
filters,
},
});
})
.catch((error) => {
dispatch({
type: actionTypes.transactionLoadFailed,
data: {
error,
},
data: { error },
});
})
.finally(() => {
Expand All @@ -99,6 +95,7 @@ export const resetTransactionResult = () => ({
* @param {Number} data.dynamicFeePerByte - In raw format, used for creating BTC transaction.
* @param {Number} data.reference - Data field for LSK transactions
*/
// eslint-disable-next-line max-statements
export const transactionCreated = data => async (dispatch, getState) => {
const {
account, settings, network,
Expand Down Expand Up @@ -144,7 +141,7 @@ export const transactionCreated = data => async (dispatch, getState) => {
* @param {Number} transaction.dynamicFeePerByte - In raw format, used for creating BTC transaction.
* @param {Number} transaction.reference - Data field for LSK transactions
*/
export const transactionBroadcasted = (transaction, callback = () => {}) =>
export const transactionBroadcasted = transaction =>
// eslint-disable-next-line max-statements
async (dispatch, getState) => {
const { network, settings } = getState();
Expand All @@ -156,7 +153,6 @@ export const transactionBroadcasted = (transaction, callback = () => {}) =>
activeToken,
));

callback({ success: !error, error, transaction });
if (error) {
dispatch({
type: actionTypes.broadcastedTransactionError,
Expand All @@ -173,12 +169,8 @@ export const transactionBroadcasted = (transaction, callback = () => {}) =>
});

if (activeToken !== tokenMap.BTC.key) {
dispatch(addNewPendingTransaction({
...transaction,
title: MODULE_ASSETS_NAME_ID_MAP[transaction.moduleAssetId],
amount: transaction.asset.amount,
recipientId: transaction.asset.recipientId,
}));
const transformedTransaction = transformTransaction(transaction);
dispatch(addNewPendingTransaction({ ...transformedTransaction, isPending: true }));
}

dispatch(passphraseUsed(new Date()));
Expand Down
2 changes: 1 addition & 1 deletion src/store/actions/voting.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export const votesSubmitted = data =>
export const votesRetrieved = () =>
async (dispatch, getState) => {
const { account, network } = getState();
const address = account.info[tokenMap.LSK.key].address;
const address = account.info[tokenMap.LSK.key].summary.address;
const votes = await getVotes({ network, params: { address } });

dispatch({
Expand Down
4 changes: 2 additions & 2 deletions src/store/middlewares/account.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ const checkTransactionsAndUpdateAccount = async (store, action) => {
const blockContainsRelevantTransaction = txs.filter((transaction) => {
if (!transaction) return false;
return (
account.summary?.address === transaction.senderId
|| account.summary?.address === transaction.recipientId
account.summary?.address === transaction.sender.address
|| account.summary?.address === transaction.asset?.recipient.address
);
}).length > 0;

Expand Down
25 changes: 14 additions & 11 deletions src/store/reducers/voting.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,20 @@ import { actionTypes } from '@constants';
*/
const voting = (state = {}, action) => {
switch (action.type) {
case actionTypes.votesRetrieved:
return action.data
.reduce((votesDict, delegate) => {
votesDict[delegate.address] = {
confirmed: Number(delegate.amount),
unconfirmed: Number(delegate.amount),
username: delegate.username,
};
return votesDict;
}, {});

case actionTypes.votesRetrieved: {
if (action.data.account.votesUsed) {
return action.data
.reduce((votesDict, delegate) => {
votesDict[delegate.address] = {
confirmed: Number(delegate.amount),
unconfirmed: Number(delegate.amount),
username: delegate.username,
};
return votesDict;
}, {});
}
return {};
}
case actionTypes.voteEdited:
return {
...state,
Expand Down
32 changes: 23 additions & 9 deletions src/utils/account.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,24 @@ export const extractPublicKey = (passphrase) => {
if (LiskPassphrase.Mnemonic.validateMnemonic(passphrase)) {
return cryptography.getKeys(passphrase).publicKey.toString('hex');
}
return undefined;
throw Error('Invalid passphrase');
};

export const extractAddressFromPublicKey = (data) => {
if (regex.publicKey.test(data)) {
return cryptography.getBase32AddressFromPublicKey(data).toString('hex');
}
if (Buffer.isBuffer(data)) {
return cryptography.getBase32AddressFromPublicKey(data);
}
throw Error(`Unable to convert publicKey ${data} to address`);
};

export const extractAddressFromPassphrase = (data) => {
if (LiskPassphrase.Mnemonic.validateMnemonic(data)) {
return cryptography.getBase32AddressFromPassphrase(data).toString('hex');
}
throw Error('Invalid passphrase');
};

/**
Expand All @@ -23,16 +40,13 @@ export const extractPublicKey = (passphrase) => {
* @returns {String?} - Extracted address for a given valid passphrase or publicKey
*/
export const extractAddress = (data) => {
if (LiskPassphrase.Mnemonic.validateMnemonic(data)) {
return cryptography.getBase32AddressFromPassphrase(data).toString('hex');
}
if (regex.publicKey.test(data)) {
return cryptography.getBase32AddressFromPublicKey(data).toString('hex');
}
if (regex.address.test(data)) {
if (cryptography.validateBase32Address()(data)) {
return cryptography.getAddressFromBase32Address(data);
}
return undefined;
if (Buffer.isBuffer(data)) {
return cryptography.getBase32AddressFromAddress(data);
}
throw Error('Invalid publicKey or passphrase');
};

export const getActiveTokenAccount = state => ({
Expand Down
9 changes: 6 additions & 3 deletions src/utils/api/account/lsk.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { tokenMap } from '@constants';
import http from '../http';
import ws from '../ws';
import { isEmpty } from '../../helpers';
import { extractAddress, extractPublicKey } from '../../account';
import { extractAddressFromPassphrase, extractAddressFromPublicKey, extractPublicKey } from '../../account';
import regex from '../../regex';

const httpPrefix = '/api/v2';
Expand Down Expand Up @@ -42,8 +42,11 @@ const getAccountParams = (params) => {
// If you have the address, you don't need anything else
if (address) return { address };
// convert other params to address
if (publicKey || passphrase) {
return { address: extractAddress(publicKey || passphrase) };
if (publicKey) {
return { address: extractAddressFromPublicKey(publicKey) };
}
if (passphrase) {
return { address: extractAddressFromPassphrase(passphrase) };
}
// if none of the above, ignore the params
return {};
Expand Down
Loading

0 comments on commit 0a11e3b

Please sign in to comment.