Do not allow custom tokens to be added with the same address (#1770)

* Do not allow custom tokens to be added with the same address

* prettify
This commit is contained in:
HenryNguyen5 2018-05-13 00:20:36 -04:00 committed by Daniel Ternyak
parent 0e7a2ef2e8
commit 039aab09a2

View File

@ -16,8 +16,13 @@ interface IGenerateSymbolLookup {
[tokenSymbol: string]: boolean;
}
interface IGenerateAddressLookup {
[address: string]: boolean;
}
interface State {
tokenSymbolLookup: IGenerateSymbolLookup;
tokenAddressLookup: IGenerateAddressLookup;
address: string;
symbol: string;
decimal: string;
@ -25,20 +30,13 @@ interface State {
export default class AddCustomTokenForm extends React.PureComponent<Props, State> {
public state: State = {
tokenSymbolLookup: {},
tokenSymbolLookup: this.generateSymbolLookup(),
tokenAddressLookup: this.generateAddressMap(),
address: '',
symbol: '',
decimal: ''
};
constructor(props: Props) {
super(props);
this.state = {
...this.state,
tokenSymbolLookup: this.generateSymbolLookup(props.allTokens)
};
}
public render() {
const { address, symbol, decimal } = this.state;
const errors = this.getErrors();
@ -76,7 +74,7 @@ export default class AddCustomTokenForm extends React.PureComponent<Props, State
value={field.value}
onChange={this.onFieldChange}
/>
{typeof errors[field.name] === 'string' && (
{errors[field.name] && (
<div className="AddCustom-field-error">{errors[field.name]}</div>
)}
</label>
@ -106,14 +104,19 @@ export default class AddCustomTokenForm extends React.PureComponent<Props, State
public getErrors() {
const { address, symbol, decimal } = this.state;
const errors: { [key: string]: boolean | string } = {};
const errors: { [key: string]: string } = {};
// Formatting errors
if (decimal && !isPositiveIntegerOrZero(Number(decimal))) {
errors.decimal = true;
errors.decimal = 'Invalid decimal';
}
if (address && !isValidETHAddress(address)) {
errors.address = true;
if (address) {
if (!isValidETHAddress(address)) {
errors.address = 'Not a valid address';
}
if (this.state.tokenAddressLookup[address]) {
errors.address = 'A token with this address already exists';
}
}
// Message errors
@ -146,13 +149,19 @@ export default class AddCustomTokenForm extends React.PureComponent<Props, State
this.props.onSave({ address, symbol, decimal: parseInt(decimal, 10) });
};
private generateSymbolLookup(tokens: Token[]) {
return tokens.reduce(
(prev, tk) => {
prev[tk.symbol] = true;
return prev;
},
{} as IGenerateSymbolLookup
);
private generateSymbolLookup() {
return this.tknArrToMap('symbol');
}
private generateAddressMap() {
return this.tknArrToMap('address');
}
private tknArrToMap(key: Exclude<keyof Token, 'error'>) {
const tokens = this.props.allTokens;
return tokens.reduce<{ [k: string]: boolean }>((prev, tk) => {
prev[tk[key]] = true;
return prev;
}, {});
}
}