1
0
mirror of https://github.com/trezor/trezor-wallet synced 2024-11-15 21:08:57 +00:00
trezor-wallet/src/utils/ethUtils.js

49 lines
1.5 KiB
JavaScript
Raw Normal View History

2017-12-13 11:01:37 +00:00
/* @flow */
2018-07-30 10:52:13 +00:00
import BigNumber from 'bignumber.js';
import EthereumjsUtil from 'ethereumjs-util';
2018-07-30 10:52:13 +00:00
export const decimalToHex = (dec: number): string => new BigNumber(dec).toString(16);
2017-12-13 11:01:37 +00:00
2018-09-23 06:28:12 +00:00
export const padLeftEven = (hex: string): string => (hex.length % 2 !== 0 ? `0${hex}` : hex);
2017-12-13 11:01:37 +00:00
export const sanitizeHex = ($hex: string): string => {
const hex = $hex.toLowerCase().substring(0, 2) === '0x' ? $hex.substring(2) : $hex;
2017-12-13 11:01:37 +00:00
if (hex === '') return '';
2018-07-30 10:52:13 +00:00
return `0x${padLeftEven(hex)}`;
};
2017-12-13 11:01:37 +00:00
2018-09-06 15:04:28 +00:00
export const hexToDecimal = (hex: number): string => {
const sanitized: ?string = sanitizeHex(hex.toString());
2018-09-06 15:04:28 +00:00
return !sanitized ? 'null' : new BigNumber(sanitized).toString();
2018-07-30 10:52:13 +00:00
};
2017-12-13 11:01:37 +00:00
export const strip = (str: string): string => {
if (str.indexOf('0x') === 0) {
2018-07-30 10:52:13 +00:00
return padLeftEven(str.substring(2, str.length));
2017-12-13 11:01:37 +00:00
}
return padLeftEven(str);
2018-07-30 10:52:13 +00:00
};
2017-12-13 11:01:37 +00:00
2019-03-04 12:33:02 +00:00
export const calcGasPrice = (price: BigNumber, limit: string): string =>
price.times(limit).toString();
export const validateAddress = (address: string): ?string => {
const hasUpperCase = new RegExp('^(.*[A-Z].*)$');
if (address.length < 1) {
return 'Address is not set';
2018-09-23 06:28:12 +00:00
}
if (!EthereumjsUtil.isValidAddress(address)) {
return 'Address is not valid';
2018-09-23 06:28:12 +00:00
}
if (address.match(hasUpperCase) && !EthereumjsUtil.isValidChecksumAddress(address)) {
return 'Address is not a valid checksum';
}
return null;
2018-10-09 08:42:36 +00:00
};
export const isHex = (str: string): boolean => {
const regExp = /^(0x|0X)?[0-9A-Fa-f]+$/g;
return regExp.test(str);
2019-03-04 12:33:02 +00:00
};