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

Implement creating future transactions #5390

Merged
merged 23 commits into from
Oct 25, 2023
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
04016c2
Implemented initial account nonce sync
ikem-legend Oct 13, 2023
b7bbd4b
Optimized nonce hook and minor Redux fix
ikem-legend Oct 17, 2023
c656a9a
Implemented nonce hook in transaction signing process
ikem-legend Oct 17, 2023
e8226e5
:test_tube: Fix failing tests
ikem-legend Oct 17, 2023
30483d5
:test_tube: Fixed remaining failing tests
ikem-legend Oct 18, 2023
e8b51bc
Refactored nonce hook, reducer and minor changes
ikem-legend Oct 18, 2023
2faef57
Implemented nonce sync test
ikem-legend Oct 18, 2023
1e73365
Merge branch 'release/3.0.0' of github.com:LiskHQ/lisk-desktop into 5…
ikem-legend Oct 18, 2023
2044aa9
Implemented changes based on PR review
ikem-legend Oct 19, 2023
938d2fa
Minor refactor to fix default account nonce and failing tests
ikem-legend Oct 19, 2023
70235e6
Refactored nonce hook logic
ikem-legend Oct 23, 2023
f1b852a
Fixed nonce bug during transaction signing
ikem-legend Oct 23, 2023
2475a52
:test_tube: Fixed failing test
ikem-legend Oct 23, 2023
eb172de
Fixed coverage issues
ikem-legend Oct 24, 2023
e456f67
Implemented PR feedback
ikem-legend Oct 24, 2023
d3a7e18
Merge branch 'release/3.0.0' of github.com:LiskHQ/lisk-desktop into 5…
ikem-legend Oct 24, 2023
fc4a70c
Implemented nonce reset feature
ikem-legend Oct 24, 2023
f7888a9
Updated nonce reset icon and fixed failing tests
ikem-legend Oct 24, 2023
a5aa841
Minor DeepScan fix
ikem-legend Oct 24, 2023
4c5cc31
Fixed coverage issue and minor changes
ikem-legend Oct 25, 2023
b273f6a
Implementing Redux state clear on nonce reset
ikem-legend Oct 25, 2023
c7190c7
Fixed bugs regarding reset of nonce
oskarleonard Oct 25, 2023
9e3a707
PR feedback and coverage issue fixes
ikem-legend Oct 25, 2023
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
13 changes: 11 additions & 2 deletions src/modules/account/hooks/useAccounts.js
Copy link
Contributor

@eniolam1000752 eniolam1000752 Oct 25, 2023

Choose a reason for hiding this comment

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

The present implementation of the nonce caching is scary in the sense that there is no history clean up strategy.

Since for every multi sig transaction a user creates, we are always keeping a record of it at a point a user would have like eg 200 transactions possibly from different accounts on that device and since there is no way a transaction done at index 0 would have a nonce greater than the transaction done at index 100.

I think there should be a sanitisation of this states so as not to fill up local storage space (remember it has a max size of 10mb) since transactions HEX can be quite very lengthy.

Copy link
Member Author

Choose a reason for hiding this comment

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

The fact that a transaction might most likely be completed on a different device than it was initiated on plays a role in why this can be tricky to solve. However, the fix for clearing all stored nonce can play a role in this

Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { useMemo, useCallback } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { selectAccounts } from '@account/store/selectors';
import { selectAccounts, selectAccountNonce } from '@account/store/selectors';
import { selectHWAccounts } from '@hardwareWallet/store/selectors/hwSelectors';
import { addAccount, deleteAccount } from '../store/action';
import { addAccount, deleteAccount, setAccountNonce } from '../store/action';

// eslint-disable-next-line
export function useAccounts() {
Expand All @@ -22,11 +22,20 @@ export function useAccounts() {
const getAccountByPublicKey = (pubkey) =>
accounts.find((account) => account.metadata.pubkey === pubkey);

const setNonceByAccount = useCallback(
(address, nonce) => dispatch(setAccountNonce(address, nonce)),
[]
);

const getNonceByAccount = (address) => useSelector(selectAccountNonce)[address];

return {
accounts,
setAccount,
deleteAccountByAddress,
getAccountByPublicKey,
getAccountByAddress,
setNonceByAccount,
getNonceByAccount,
};
}
6 changes: 6 additions & 0 deletions src/modules/account/store/action.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ export const addAccount = (encryptedAccount) => ({
encryptedAccount,
});

export const setAccountNonce = (address, nonce) => ({
type: actionTypes.setAccountNonce,
address,
nonce,
});

export const updateAccount = ({ encryptedAccount, accountDetail }) => ({
type: actionTypes.updateAccount,
encryptedAccount,
Expand Down
1 change: 1 addition & 0 deletions src/modules/account/store/actionTypes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const actionTypes = {
setCurrentAccount: 'SET_CURRENT_ACCOUNT',
updateCurrentAccount: 'UPDATE_CURRENT_ACCOUNT',
addAccount: 'ADD_ACCOUNT',
setAccountNonce: 'SET_ACCOUNT_NONCE',
updateAccount: 'UPDATE_ACCOUNT',
deleteAccount: 'DELETE_ACCOUNT',
};
Expand Down
17 changes: 15 additions & 2 deletions src/modules/account/store/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,27 @@ export const list = (state = {}, { type, encryptedAccount, accountDetail, addres
}
};

export const localNonce = (state = {}, { type, address, nonce }) => {
switch (type) {
case actionTypes.setAccountNonce:
return {
...state,
[address]: nonce,
};

default:
return state;
}
};

const persistConfig = {
key: 'account',
storage,
whitelist: ['list', 'current'], // only navigation will be persisted
whitelist: ['list', 'current', 'localNonce'], // only navigation will be persisted
blacklist: [],
};

const accountReducer = combineReducers({ current, list });
const accountReducer = combineReducers({ current, list, localNonce });

// eslint-disable-next-line import/prefer-default-export
export const account = persistReducer(persistConfig, accountReducer);
14 changes: 13 additions & 1 deletion src/modules/account/store/reducer.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import mockSavedAccounts from '@tests/fixtures/accounts';
import actionTypes from './actionTypes';
import { list, current } from './reducer';
import { list, current, localNonce } from './reducer';

describe('Auth reducer', () => {
it('Should return encryptedAccount if setCurrentAccount action type is triggered', async () => {
Expand Down Expand Up @@ -82,4 +82,16 @@ describe('Auth reducer', () => {
expect(list(defaultState, actionData)).toEqual({});
expect(current(mockSavedAccounts[0], actionData)).toEqual(mockSavedAccounts[0]);
});

it('Should not remove current account when deleting not current account', async () => {
const actionData = {
type: actionTypes.setAccountNonce,
address: mockSavedAccounts[1].metadata.address,
nonce: 1,
};
const expectedState = {
[mockSavedAccounts[1].metadata.address]: 1,
};
expect(localNonce({}, actionData)).toEqual(expectedState);
});
});
1 change: 1 addition & 0 deletions src/modules/account/store/selectors.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export const selectCurrentAccount = (state) => state.account.current;
export const selectAccounts = (state) => state.account.list || [];
export const selectAccountNonce = (state) => state.account.localNonce || {};
55 changes: 55 additions & 0 deletions src/modules/auth/hooks/useNonceSync.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { useEffect, useState, useCallback } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useCurrentApplication } from '@blockchainApplication/manage/hooks';
import { useCurrentAccount, useAccounts } from '@account/hooks';
import useSettings from '@settings/hooks/useSettings';
import { AUTH } from 'src/const/queries';
import { useAuthConfig } from './queries';

// eslint-disable-next-line max-statements
const useNonceSync = () => {
const queryClient = useQueryClient();
oskarleonard marked this conversation as resolved.
Show resolved Hide resolved
const [currentApplication] = useCurrentApplication();
const [currentAccount] = useCurrentAccount();
const { setNonceByAccount, getNonceByAccount } = useAccounts();
const currentAccountAddress = currentAccount.metadata.address;
const currentAccountNonce = getNonceByAccount(currentAccountAddress);
const { mainChainNetwork } = useSettings('mainChainNetwork');
const chainID = currentApplication.chainID;
const customConfig = {
params: {
address: currentAccountAddress,
},
};
const baseUrl = mainChainNetwork?.serviceUrl;
ikem-legend marked this conversation as resolved.
Show resolved Hide resolved
const config = useAuthConfig(customConfig);
const authData = queryClient.getQueryData([AUTH, chainID, config, baseUrl]);
const onChainNonce = authData?.data.nonce;
const [accountNonce, setAccountNonce] = useState(onChainNonce);
ikem-legend marked this conversation as resolved.
Show resolved Hide resolved

// Store nonce by address in accounts store
const handleLocalNonce = (currentNonce) => {
let localNonce = parseInt(currentAccountNonce || 0, 10);
ikem-legend marked this conversation as resolved.
Show resolved Hide resolved
if (localNonce < currentNonce) {
localNonce = currentNonce;
}
setNonceByAccount(currentAccountAddress, localNonce);

setAccountNonce(localNonce);
};

useEffect(() => {
handleLocalNonce(parseInt(onChainNonce, 10));
}, [onChainNonce]);

// Call incrementNonce after transaction signing
const incrementNonce = useCallback(() => {
let localNonce = currentAccountNonce;
localNonce += 1;
ikem-legend marked this conversation as resolved.
Show resolved Hide resolved
setNonceByAccount(currentAccountAddress, localNonce);
}, []);

return { accountNonce, onChainNonce, incrementNonce };
ikem-legend marked this conversation as resolved.
Show resolved Hide resolved
};

export default useNonceSync;
ikem-legend marked this conversation as resolved.
Show resolved Hide resolved
58 changes: 58 additions & 0 deletions src/modules/auth/hooks/useNonceSync.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { renderHook } from '@testing-library/react-hooks';
import * as ReactQuery from '@tanstack/react-query';
import { queryWrapper as wrapper } from 'src/utils/test/queryWrapper';
import mockSavedAccounts from '@tests/fixtures/accounts';
import { useAccounts } from 'src/modules/account/hooks';
import { mockAuth } from '@auth/__fixtures__';
import useNonceSync from './useNonceSync';

const mockedCurrentAccount = mockSavedAccounts[0];
const mockSetNonceByAccount = jest.fn();
const mockModifiedMockAuth = { ...mockAuth, data: { ...mockAuth.data, nonce: '2' } };

jest.mock('@account/hooks/useCurrentAccount', () => ({
useCurrentAccount: jest.fn(() => [mockedCurrentAccount, jest.fn()]),
}));
jest.mock('@account/hooks/useAccounts');
jest.mock('@auth/hooks/queries/useAuth');

describe('useNonceSync', () => {
it('renders properly', async () => {
jest
.spyOn(ReactQuery, 'useQueryClient')
.mockReturnValue({ getQueryData: () => mockModifiedMockAuth });
useAccounts.mockReturnValue({
accounts: mockedCurrentAccount,
setNonceByAccount: mockSetNonceByAccount,
getNonceByAccount: jest.fn().mockReturnValue(3),
});
const { result } = renderHook(() => useNonceSync(), { wrapper });
expect(result.current.accountNonce).toEqual(3);
result.current.incrementNonce();
expect(mockSetNonceByAccount).toHaveBeenCalled();
});

it('renders properly if auth nonce is undefined and no local nonce has been previously stored', () => {
jest.spyOn(ReactQuery, 'useQueryClient').mockReturnValue({ getQueryData: () => {} });
useAccounts.mockReturnValue({
accounts: mockedCurrentAccount,
setNonceByAccount: mockSetNonceByAccount,
getNonceByAccount: jest.fn().mockReturnValue(undefined),
});
const { result } = renderHook(() => useNonceSync(), { wrapper });
expect(result.current.accountNonce).toEqual(0);
});

it("updates local nonce if it's less than on-chain nonce", () => {
jest
.spyOn(ReactQuery, 'useQueryClient')
.mockReturnValue({ getQueryData: () => mockModifiedMockAuth });
useAccounts.mockReturnValue({
accounts: mockedCurrentAccount,
setNonceByAccount: mockSetNonceByAccount,
getNonceByAccount: jest.fn().mockReturnValue(1),
});
const { result } = renderHook(() => useNonceSync(), { wrapper });
expect(result.current.accountNonce).toEqual(2);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ useCurrentAccount.mockReturnValue([mockCurrentAccount, mockSetCurrentAccount]);
useAccounts.mockReturnValue({
getAccountByAddress: () => mockSavedAccounts[0],
accounts: mockSavedAccounts,
setNonceByAccount: jest.fn(),
getNonceByAccount: () => 1,
});

useBlockchainApplicationMeta.mockReturnValue({
Expand Down
1 change: 1 addition & 0 deletions src/modules/legacy/components/Summary/summary.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const mockedCurrentAccount = mockSavedAccounts[0];

jest.mock('@auth/hooks/queries/useAuth');
jest.mock('@account/hooks', () => ({
...jest.requireActual('@account/hooks'),
useCurrentAccount: jest.fn(() => [mockedCurrentAccount, jest.fn()]),
}));

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { screen, fireEvent } from '@testing-library/react';
import { smartRender } from 'src/utils/testHelpers';
import mockSavedAccounts from '@tests/fixtures/accounts';
import { useRewardsClaimable } from '@pos/reward/hooks/queries';
import wallets from '@tests/constants/wallets';
Expand All @@ -8,10 +8,10 @@ import { useAuth } from '@auth/hooks/queries';
import { mockAuth } from '@auth/__fixtures__';
import { mockAppsTokens } from '@token/fungible/__fixtures__';
import usePosToken from '@pos/validator/hooks/usePosToken';
import { mount } from 'enzyme';
import ClaimRewardsSummary from './index';

jest.mock('@account/hooks', () => ({
...jest.requireActual('@account/hooks'),
useCurrentAccount: jest.fn(() => [mockSavedAccounts[0], jest.fn()]),
}));
jest.mock('@auth/hooks/queries');
Expand Down Expand Up @@ -56,24 +56,25 @@ describe('ClaimRewardsSummary', () => {
useAuth.mockReturnValue({ data: mockAuth });
usePosToken.mockReturnValue({ token: mockAppsTokens.data[0] });
useRewardsClaimable.mockReturnValue({ data: mockRewardsClaimableWithToken });
const config = { queryClient: true /* renderType: 'mount' */ };

it('should display properly', async () => {
render(<ClaimRewardsSummary {...props} />);
smartRender(ClaimRewardsSummary, props, config);

expect(screen.getByText('Confirm')).toBeTruthy();
});

it('should go to prev page when click Go back button', () => {
const wrapper = mount(<ClaimRewardsSummary {...props} />);
smartRender(ClaimRewardsSummary, props, config);
expect(props.prevStep).not.toBeCalled();
wrapper.find('button.cancel-button').simulate('click');
fireEvent.click(screen.getByAltText('arrowLeftTailed'));
expect(props.prevStep).toBeCalled();
});

it('should submit transaction and action function when click in confirm button', () => {
const wrapper = mount(<ClaimRewardsSummary {...props} />);
smartRender(ClaimRewardsSummary, props, config);
expect(props.nextStep).not.toBeCalled();
wrapper.find('button.confirm-button').simulate('click');
fireEvent.click(screen.getByText('Confirm'));
expect(props.nextStep).toBeCalledWith({
actionFunction: props.claimedRewards,
formProps: props.formProps,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import React from 'react';
import { mount } from 'enzyme';
import { mountWithRouterAndStore } from 'src/utils/testHelpers';
import { smartRender } from 'src/utils/testHelpers';
import accounts from '@tests/constants/wallets';
import { useAuth } from '@auth/hooks/queries';
import mockSavedAccounts from '@tests/fixtures/accounts';
Expand All @@ -10,8 +8,10 @@ import Summary from './RegisterValidatorSummary';
const mockedCurrentAccount = mockSavedAccounts[0];
jest.mock('@auth/hooks/queries');
jest.mock('@account/hooks', () => ({
...jest.requireActual('@account/hooks'),
useCurrentAccount: jest.fn(() => [mockedCurrentAccount, jest.fn()]),
}));
const config = { renderType: 'mount', queryClient: true };

describe('Validator Registration Summary', () => {
const props = {
Expand Down Expand Up @@ -58,7 +58,7 @@ describe('Validator Registration Summary', () => {
useAuth.mockReturnValue({ data: mockAuth });

it('renders properly Summary component', () => {
const wrapper = mount(<Summary {...props} />);
const wrapper = smartRender(Summary, props, config).wrapper;
expect(wrapper).toContainMatchingElement('.username-label');
expect(wrapper).toContainMatchingElement('.username');
expect(wrapper).toContainMatchingElement('.address');
Expand All @@ -67,14 +67,14 @@ describe('Validator Registration Summary', () => {
});

it('go to prev page when click Go back button', () => {
const wrapper = mount(<Summary {...props} />);
const wrapper = smartRender(Summary, props, config).wrapper;
expect(props.prevStep).not.toBeCalled();
wrapper.find('button.cancel-button').simulate('click');
expect(props.prevStep).toBeCalled();
});

it('submit user data when click in confirm button', () => {
const wrapper = mountWithRouterAndStore(Summary, props, {}, {});
const wrapper = smartRender(Summary, props, config).wrapper;
expect(props.nextStep).not.toBeCalled();
wrapper.find('button.confirm-button').simulate('click');
expect(props.nextStep).toBeCalledWith({
Expand Down
Loading