Skip to content

Commit

Permalink
Create sorted copy of the recovery phrase with original index
Browse files Browse the repository at this point in the history
  • Loading branch information
neuodev committed Mar 16, 2023
1 parent a3fc20b commit f4653cf
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
@@ -1,5 +1,5 @@
// @flow
import { Node, ComponentType, useState } from 'react';
import { Node, ComponentType, useState, useMemo } from 'react';
import { defineMessages, injectIntl, FormattedHTMLMessage } from 'react-intl';
import { observer } from 'mobx-react';
import type { $npm$ReactIntl$IntlShape } from 'react-intl';
Expand Down Expand Up @@ -74,6 +74,31 @@ function VerifyRecoveryPhraseStep(props: Props & Intl): Node {
return () => setCurrentStep(CREATE_WALLET_SETPS.ADD_WALLET_DETAILS)
};

const shortedRecoveryPhrase = useMemo(() => {
const sorted = recoveryPhrase.slice().sort();

const wordIndexes = new Set();

return sorted.map((sortedWord, sortedWordIdx) => {
const originalIdx = recoveryPhrase.findIndex((originalWord, idx) => {
return sortedWord === originalWord && !wordIndexes.has(idx)
});

if (originalIdx === -1) throw new Error('Word not found in the original recovery phrase. Should never happen');

// Mark word index as watched to handle recovery phrase with duplicates
wordIndexes.add(originalIdx);

return {
word: sortedWord,
originalIdx,
id: sortedWordIdx,
};
});
}, [recoveryPhrase]);

console.log(shortedRecoveryPhrase);

return (
<Stack alignItems='center' justifyContent='center' className={styles.component}>
<Stack direction='column' alignItems='left' justifyContent='center' maxWidth='690px'>
Expand Down
29 changes: 29 additions & 0 deletions packages/yoroi-extension/app/utils/recoveryPhrase.js
@@ -0,0 +1,29 @@
// @flow

export type SortedRecoveryPhraseEntry = {|
id: number,
word: string,
originalIdx: number,
|};

export function makeSortedPhrase(recoveryPhrase: Array<string>): SortedRecoveryPhraseEntry[] {
const sorted = recoveryPhrase.slice().sort();
const wordIndexes = new Set();

return sorted.map((sortedWord, sortedWordIdx) => {
const originalIdx = recoveryPhrase.findIndex((originalWord, idx) => {
return sortedWord === originalWord && !wordIndexes.has(idx)
});

if (originalIdx === -1) throw new Error('Word not found in the original recovery phrase. Should never happen');

// Mark word index as watched to handle recovery phrase with duplicates
wordIndexes.add(originalIdx);

return {
id: sortedWordIdx,
word: sortedWord,
originalIdx,
};
});
}

0 comments on commit f4653cf

Please sign in to comment.