1
0
mirror of https://github.com/trezor/trezor-wallet synced 2024-11-24 09:18:09 +00:00

fixed token balance + decimal regexp

This commit is contained in:
Szymon Lesisz 2018-05-07 18:04:04 +02:00
parent 3dabc7dda6
commit 9020ecc176
5 changed files with 61 additions and 29 deletions

View File

@ -192,11 +192,6 @@ const begin = (device: TrezorDevice, network: string): AsyncAction => {
const discoverAddress = (device: TrezorDevice, discoveryProcess: Discovery): AsyncAction => { const discoverAddress = (device: TrezorDevice, discoveryProcess: Discovery): AsyncAction => {
return async (dispatch: Dispatch, getState: GetState): Promise<void> => { return async (dispatch: Dispatch, getState: GetState): Promise<void> => {
//const hdKey = discoveryProcess.hdKey
console.log("TYPEOF", typeof discoveryProcess.hdKey.derive, discoveryProcess.hdKey)
console.log("TYPEOF", typeof discoveryProcess.hdKey.derive === typeof HDKey);
const derivedKey = discoveryProcess.hdKey.derive(`m/${discoveryProcess.accountIndex}`); const derivedKey = discoveryProcess.hdKey.derive(`m/${discoveryProcess.accountIndex}`);
const path = discoveryProcess.basePath.concat(discoveryProcess.accountIndex); const path = discoveryProcess.basePath.concat(discoveryProcess.accountIndex);
const publicAddress: string = EthereumjsUtil.publicToAddress(derivedKey.publicKey, true).toString('hex'); const publicAddress: string = EthereumjsUtil.publicToAddress(derivedKey.publicKey, true).toString('hex');
@ -300,9 +295,9 @@ const discoverAddress = (device: TrezorDevice, discoveryProcess: Discovery): Asy
// ]; // ];
for (let i = 0; i < userTokens.length; i++) { for (let i = 0; i < userTokens.length; i++) {
const tokenBalance = await getTokenBalanceAsync(web3instance.erc20, userTokens[i].address, ethAddress); const tokenBalance: string = await getTokenBalanceAsync(web3instance.erc20, userTokens[i]);
if (discoveryProcess.interrupted) return; if (discoveryProcess.interrupted) return;
dispatch( setTokenBalance(userTokens[i].address, ethAddress, tokenBalance.toString()) ) dispatch( setTokenBalance(userTokens[i].address, ethAddress, tokenBalance) )
} }
const nonce: number = await getNonceAsync(web3instance.web3, ethAddress); const nonce: number = await getNonceAsync(web3instance.web3, ethAddress);

View File

@ -86,7 +86,7 @@ export type SendFormAction = {
}; };
//const numberRegExp = new RegExp('^([0-9]{0,10}\\.)?[0-9]{1,18}$'); //const numberRegExp = new RegExp('^([0-9]{0,10}\\.)?[0-9]{1,18}$');
const numberRegExp: RegExp = new RegExp('^(0|0\\.([0-9]+)?|[1-9]+\\.?([0-9]+)?|\\.[0-9]+)$'); const numberRegExp: RegExp = new RegExp('^(0|0\\.([0-9]+)?|[1-9][0-9]*\\.?([0-9]+)?|\\.[0-9]+)$');
const calculateFee = (gasPrice: string, gasLimit: string): string => { const calculateFee = (gasPrice: string, gasLimit: string): string => {
return EthereumjsUnits.convert( new BigNumber(gasPrice).times(gasLimit), 'gwei', 'ether'); return EthereumjsUnits.convert( new BigNumber(gasPrice).times(gasLimit), 'gwei', 'ether');
@ -289,7 +289,7 @@ export const validation = (): ThunkAction => {
if (token) { if (token) {
if (parseInt(token.decimals) > 0) { if (parseInt(token.decimals) > 0) {
//decimalRegExp = new RegExp('^(0|0\\.([0-9]{0,' + token.decimals + '})?|[1-9]+\\.?([0-9]{0,' + token.decimals + '})?|\\.[0-9]{1,' + token.decimals + '})$'); //decimalRegExp = new RegExp('^(0|0\\.([0-9]{0,' + token.decimals + '})?|[1-9]+\\.?([0-9]{0,' + token.decimals + '})?|\\.[0-9]{1,' + token.decimals + '})$');
decimalRegExp = new RegExp('^(0|0\\.([0-9]{0,' + token.decimals + '})?|[1-9]+\\.?([0-9]{0,' + token.decimals + '})?|\\.[0-9]{1,' + token.decimals + '})$'); decimalRegExp = new RegExp('^(0|0\\.([0-9]{0,' + token.decimals + '})?|[1-9][0-9]*\\.?([0-9]{0,' + token.decimals + '})?|\\.[0-9]{1,' + token.decimals + '})$');
} else { } else {
// decimalRegExp = new RegExp('^(0|0\\.?|[1-9]+\\.?)$'); // decimalRegExp = new RegExp('^(0|0\\.?|[1-9]+\\.?)$');
decimalRegExp = new RegExp('^[0-9]+$'); decimalRegExp = new RegExp('^[0-9]+$');
@ -307,7 +307,7 @@ export const validation = (): ThunkAction => {
} }
} else { } else {
decimalRegExp = new RegExp('^(0|0\\.([0-9]{0,18})?|[1-9]+\\.?([0-9]{0,18})?|\\.[0-9]{0,18})$'); decimalRegExp = new RegExp('^(0|0\\.([0-9]{0,18})?|[1-9][0-9]*\\.?([0-9]{0,18})?|\\.[0-9]{0,18})$');
if (!state.amount.match(decimalRegExp)) { if (!state.amount.match(decimalRegExp)) {
errors.amount = `Maximum 18 decimals allowed`; errors.amount = `Maximum 18 decimals allowed`;
} else if (new BigNumber(state.total).greaterThan(account.balance)) { } else if (new BigNumber(state.total).greaterThan(account.balance)) {

View File

@ -6,7 +6,6 @@ import * as SUMMARY from './constants/summary';
import * as TOKEN from './constants/token'; import * as TOKEN from './constants/token';
import * as ADDRESS from './constants/address'; import * as ADDRESS from './constants/address';
import { resolveAfter } from '../utils/promiseUtils'; import { resolveAfter } from '../utils/promiseUtils';
import { getTokenInfoAsync, getTokenBalanceAsync } from './Web3Actions';
import { initialState } from '../reducers/SummaryReducer'; import { initialState } from '../reducers/SummaryReducer';
import { findSelectedDevice } from '../reducers/TrezorConnectReducer'; import { findSelectedDevice } from '../reducers/TrezorConnectReducer';

View File

@ -70,23 +70,25 @@ export const add = (token: NetworkToken, account: Account): AsyncAction => {
const web3instance = getState().web3.find(w3 => w3.network === account.network); const web3instance = getState().web3.find(w3 => w3.network === account.network);
if (!web3instance) return; if (!web3instance) return;
const tkn: Token = {
loaded: false,
deviceState: account.deviceState,
network: account.network,
name: token.name,
symbol: token.symbol,
address: token.address,
ethAddress: account.address,
decimals: token.decimals,
balance: '0'
}
dispatch({ dispatch({
type: TOKEN.ADD, type: TOKEN.ADD,
payload: { payload: tkn
loaded: false,
deviceState: account.deviceState,
network: account.network,
name: token.name,
symbol: token.symbol,
address: token.address,
ethAddress: account.address,
decimals: token.decimals,
balance: '0'
}
}); });
const tokenBalance = await getTokenBalanceAsync(web3instance.erc20, token.address, account.address); const tokenBalance = await getTokenBalanceAsync(web3instance.erc20, tkn);
dispatch( setBalance(token.address, account.address, tokenBalance.toString()) ) dispatch( setBalance(token.address, account.address, tokenBalance) )
} }
} }

View File

@ -11,6 +11,7 @@ import * as ADDRESS from './constants/address';
import * as WEB3 from './constants/web3'; import * as WEB3 from './constants/web3';
import * as PENDING from './constants/pendingTx'; import * as PENDING from './constants/pendingTx';
import * as AddressActions from '../actions/AddressActions'; import * as AddressActions from '../actions/AddressActions';
import * as TokenActions from '../actions/TokenActions';
import type { import type {
Dispatch, Dispatch,
@ -23,6 +24,7 @@ import type { ContractFactory } from 'web3';
import type { Account } from '../reducers/AccountsReducer'; import type { Account } from '../reducers/AccountsReducer';
import type { PendingTx } from '../reducers/PendingTxReducer'; import type { PendingTx } from '../reducers/PendingTxReducer';
import type { Web3Instance } from '../reducers/Web3Reducer'; import type { Web3Instance } from '../reducers/Web3Reducer';
import type { Token } from '../reducers/TokensReducer';
export type Web3Action = { export type Web3Action = {
type: typeof WEB3.READY, type: typeof WEB3.READY,
@ -171,6 +173,11 @@ export function init(web3: ?Web3, coinIndex: number = 0): AsyncAction {
dispatch( getNonce(addr) ); dispatch( getNonce(addr) );
} }
const tokens = getState().tokens.filter(t => t.network === network);
for (const token of tokens) {
dispatch( getTokenBalance(token) );
}
dispatch( getGasPrice(network) ); dispatch( getGasPrice(network) );
const pending = getState().pending.filter(p => p.network === network); const pending = getState().pending.filter(p => p.network === network);
@ -281,6 +288,32 @@ export function getBalance(account: Account): AsyncAction {
} }
} }
export function getTokenBalance(token: Token): AsyncAction {
return async (dispatch: Dispatch, getState: GetState): Promise<void> => {
const web3instance = getState().web3.filter(w3 => w3.network === token.network)[0];
const web3 = web3instance.web3;
const contract = web3instance.erc20.at(token.address);
console.warn("Get bal", token)
contract.balanceOf(token.ethAddress, (error: ?Error, balance: ?BigNumber) => {
if (balance) {
const newBalance: string = balance.dividedBy( Math.pow(10, token.decimals) ).toString();
if (newBalance !== token.balance) {
dispatch(TokenActions.setBalance(
token.address,
token.ethAddress,
newBalance
));
}
console.log("BALANCE!", balance, newBalance);
}
});
}
}
export function getNonce(account: Account): AsyncAction { export function getNonce(account: Account): AsyncAction {
return async (dispatch: Dispatch, getState: GetState): Promise<void> => { return async (dispatch: Dispatch, getState: GetState): Promise<void> => {
@ -359,15 +392,18 @@ export const getBalanceAsync = (web3: Web3, address: string): Promise<any> => {
}); });
} }
export const getTokenBalanceAsync = (erc20: any, token: string, address: string): Promise<string> => {
export const getTokenBalanceAsync = (erc20: ContractFactory, token: Token): Promise<string> => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const contr = erc20.at(token); const contract = erc20.at(token.address);
contr.balanceOf(address, (error: Error, result) => { contract.balanceOf(token.ethAddress, (error: ?Error, balance: ?BigNumber) => {
if (error) { if (error) {
reject(error); reject(error);
} else { } else if (balance) {
resolve(result); const newBalance: string = balance.dividedBy( Math.pow(10, token.decimals) ).toString();
resolve(newBalance);
} }
}); });
}); });