1
0
mirror of https://github.com/trezor/trezor-wallet synced 2024-11-15 12:59:09 +00:00
trezor-wallet/src/reducers/TokensReducer.js
2018-08-27 17:15:22 +02:00

82 lines
2.7 KiB
JavaScript

/* @flow */
import * as CONNECT from 'actions/constants/TrezorConnect';
import * as WALLET from 'actions/constants/wallet';
import * as TOKEN from 'actions/constants/token';
import type { Action, TrezorDevice } from 'flowtype';
import type { Account } from './AccountsReducer';
export type Token = {
loaded: boolean;
+deviceState: string;
+network: string;
+name: string;
+symbol: string;
+address: string;
+ethAddress: string; // foreign key
+decimals: number;
balance: string;
}
export type State = Array<Token>;
const initialState: State = [];
// Helper for actions
export const findToken = (state: Array<Token>, address: string, symbol: string, deviceState: string): ?Token => state.find(t => t.ethAddress === address && t.symbol === symbol && t.deviceState === deviceState);
export const findAccountTokens = (state: Array<Token>, account: Account): Array<Token> => state.filter(t => t.ethAddress === account.address && t.network === account.network && t.deviceState === account.deviceState);
// const setBalance = (state: State, payload: any): State => {
// const newState: Array<Token> = [ ...state ];
// let index: number = state.findIndex(t => t.address === payload.address && t.ethAddress === payload.ethAddress);
// if (index >= 0) {
// newState[index].loaded = true;
// newState[index].balance = payload.balance;
// }
// return newState;
// }
const create = (state: State, token: Token): State => {
const newState: State = [...state];
newState.push(token);
return newState;
};
const forget = (state: State, device: TrezorDevice): State => state.filter(t => t.deviceState !== device.state);
const clear = (state: State, devices: Array<TrezorDevice>): State => {
let newState: State = [...state];
devices.forEach((d) => {
newState = forget(newState, d);
});
return newState;
};
const remove = (state: State, token: Token): State => state.filter(t => !(t.ethAddress === token.ethAddress && t.address === token.address && t.deviceState === token.deviceState));
export default (state: State = initialState, action: Action): State => {
switch (action.type) {
case TOKEN.FROM_STORAGE:
return action.payload;
case TOKEN.ADD:
return create(state, action.payload);
case TOKEN.REMOVE:
return remove(state, action.token);
case TOKEN.SET_BALANCE:
return action.payload;
case CONNECT.FORGET:
case CONNECT.FORGET_SINGLE:
return forget(state, action.device);
case WALLET.CLEAR_UNAVAILABLE_DEVICE_DATA:
return clear(state, action.devices);
default:
return state;
}
};