You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
359 lines
10 KiB
359 lines
10 KiB
4 years ago
|
import punycode from 'punycode/punycode';
|
||
|
import abi from 'human-standard-token-abi';
|
||
|
import BigNumber from 'bignumber.js';
|
||
4 years ago
|
import * as ethUtil from 'ethereumjs-util';
|
||
4 years ago
|
import { DateTime } from 'luxon';
|
||
4 years ago
|
import { addHexPrefix } from '../../../app/scripts/lib/util';
|
||
4 years ago
|
import {
|
||
|
GOERLI_CHAIN_ID,
|
||
|
KOVAN_CHAIN_ID,
|
||
|
LOCALHOST_CHAIN_ID,
|
||
|
MAINNET_CHAIN_ID,
|
||
|
RINKEBY_CHAIN_ID,
|
||
|
ROPSTEN_CHAIN_ID,
|
||
4 years ago
|
} from '../../../shared/constants/network';
|
||
7 years ago
|
|
||
|
// formatData :: ( date: <Unix Timestamp> ) -> String
|
||
4 years ago
|
export function formatDate(date, format = "M/d/y 'at' T") {
|
||
4 years ago
|
return DateTime.fromMillis(date).toFormat(format);
|
||
7 years ago
|
}
|
||
9 years ago
|
|
||
4 years ago
|
export function formatDateWithYearContext(
|
||
|
date,
|
||
|
formatThisYear = 'MMM d',
|
||
|
fallback = 'MMM d, y',
|
||
|
) {
|
||
4 years ago
|
const dateTime = DateTime.fromMillis(date);
|
||
|
const now = DateTime.local();
|
||
4 years ago
|
return dateTime.toFormat(
|
||
|
now.year === dateTime.year ? formatThisYear : fallback,
|
||
4 years ago
|
);
|
||
5 years ago
|
}
|
||
4 years ago
|
/**
|
||
|
* Determines if the provided chainId is a default MetaMask chain
|
||
|
* @param {string} chainId - chainId to check
|
||
|
*/
|
||
|
export function isDefaultMetaMaskChain(chainId) {
|
||
4 years ago
|
if (
|
||
4 years ago
|
!chainId ||
|
||
|
chainId === MAINNET_CHAIN_ID ||
|
||
|
chainId === ROPSTEN_CHAIN_ID ||
|
||
|
chainId === RINKEBY_CHAIN_ID ||
|
||
|
chainId === KOVAN_CHAIN_ID ||
|
||
|
chainId === GOERLI_CHAIN_ID ||
|
||
|
chainId === LOCALHOST_CHAIN_ID
|
||
4 years ago
|
) {
|
||
4 years ago
|
return true;
|
||
6 years ago
|
}
|
||
|
|
||
4 years ago
|
return false;
|
||
9 years ago
|
}
|
||
|
|
||
4 years ago
|
export function valuesFor(obj) {
|
||
5 years ago
|
if (!obj) {
|
||
4 years ago
|
return [];
|
||
5 years ago
|
}
|
||
4 years ago
|
return Object.keys(obj).map(function (key) {
|
||
4 years ago
|
return obj[key];
|
||
|
});
|
||
9 years ago
|
}
|
||
|
|
||
4 years ago
|
export function addressSummary(
|
||
|
address,
|
||
|
firstSegLength = 10,
|
||
|
lastSegLength = 4,
|
||
|
includeHex = true,
|
||
|
) {
|
||
5 years ago
|
if (!address) {
|
||
4 years ago
|
return '';
|
||
5 years ago
|
}
|
||
4 years ago
|
let checked = checksumAddress(address);
|
||
9 years ago
|
if (!includeHex) {
|
||
4 years ago
|
checked = ethUtil.stripHexPrefix(checked);
|
||
9 years ago
|
}
|
||
4 years ago
|
return checked
|
||
|
? `${checked.slice(0, firstSegLength)}...${checked.slice(
|
||
|
checked.length - lastSegLength,
|
||
|
)}`
|
||
4 years ago
|
: '...';
|
||
9 years ago
|
}
|
||
|
|
||
4 years ago
|
export function isValidDomainName(address) {
|
||
|
const match = punycode
|
||
|
.toASCII(address)
|
||
5 years ago
|
.toLowerCase()
|
||
|
// Checks that the domain consists of at least one valid domain pieces separated by periods, followed by a tld
|
||
|
// Each piece of domain name has only the characters a-z, 0-9, and a hyphen (but not at the start or end of chunk)
|
||
|
// A chunk has minimum length of 1, but minimum tld is set to 2 for now (no 1-character tlds exist yet)
|
||
4 years ago
|
.match(
|
||
|
/^(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)+[a-z0-9][-a-z0-9]*[a-z0-9]$/u,
|
||
4 years ago
|
);
|
||
|
return match !== null;
|
||
7 years ago
|
}
|
||
|
|
||
4 years ago
|
export function isOriginContractAddress(to, sendTokenAddress) {
|
||
|
if (!to || !sendTokenAddress) {
|
||
|
return false;
|
||
|
}
|
||
|
return to.toLowerCase() === sendTokenAddress.toLowerCase();
|
||
|
}
|
||
|
|
||
9 years ago
|
// Takes wei Hex, returns wei BN, even if input is null
|
||
4 years ago
|
export function numericBalance(balance) {
|
||
5 years ago
|
if (!balance) {
|
||
4 years ago
|
return new ethUtil.BN(0, 16);
|
||
5 years ago
|
}
|
||
4 years ago
|
const stripped = ethUtil.stripHexPrefix(balance);
|
||
|
return new ethUtil.BN(stripped, 16);
|
||
9 years ago
|
}
|
||
|
|
||
9 years ago
|
// Takes hex, returns [beforeDecimal, afterDecimal]
|
||
4 years ago
|
export function parseBalance(balance) {
|
||
4 years ago
|
let afterDecimal;
|
||
|
const wei = numericBalance(balance);
|
||
|
const weiString = wei.toString();
|
||
|
const trailingZeros = /0+$/u;
|
||
9 years ago
|
|
||
4 years ago
|
const beforeDecimal =
|
||
4 years ago
|
weiString.length > 18 ? weiString.slice(0, weiString.length - 18) : '0';
|
||
4 years ago
|
afterDecimal = `000000000000000000${wei}`
|
||
|
.slice(-18)
|
||
4 years ago
|
.replace(trailingZeros, '');
|
||
5 years ago
|
if (afterDecimal === '') {
|
||
4 years ago
|
afterDecimal = '0';
|
||
5 years ago
|
}
|
||
4 years ago
|
return [beforeDecimal, afterDecimal];
|
||
9 years ago
|
}
|
||
|
|
||
9 years ago
|
// Takes wei hex, returns an object with three properties.
|
||
|
// Its "formatted" property is what we generally use to render values.
|
||
4 years ago
|
export function formatBalance(
|
||
|
balance,
|
||
|
decimalsToKeep,
|
||
|
needsParse = true,
|
||
|
ticker = 'ETH',
|
||
|
) {
|
||
4 years ago
|
const parsed = needsParse ? parseBalance(balance) : balance.split('.');
|
||
|
const beforeDecimal = parsed[0];
|
||
|
let afterDecimal = parsed[1];
|
||
|
let formatted = 'None';
|
||
9 years ago
|
if (decimalsToKeep === undefined) {
|
||
|
if (beforeDecimal === '0') {
|
||
|
if (afterDecimal !== '0') {
|
||
4 years ago
|
const sigFigs = afterDecimal.match(/^0*(.{2})/u); // default: grabs 2 most significant digits
|
||
5 years ago
|
if (sigFigs) {
|
||
4 years ago
|
afterDecimal = sigFigs[0];
|
||
5 years ago
|
}
|
||
4 years ago
|
formatted = `0.${afterDecimal} ${ticker}`;
|
||
9 years ago
|
}
|
||
|
} else {
|
||
4 years ago
|
formatted = `${beforeDecimal}.${afterDecimal.slice(0, 3)} ${ticker}`;
|
||
9 years ago
|
}
|
||
9 years ago
|
} else {
|
||
4 years ago
|
afterDecimal += Array(decimalsToKeep).join('0');
|
||
4 years ago
|
formatted = `${beforeDecimal}.${afterDecimal.slice(
|
||
|
0,
|
||
|
decimalsToKeep,
|
||
4 years ago
|
)} ${ticker}`;
|
||
9 years ago
|
}
|
||
4 years ago
|
return formatted;
|
||
9 years ago
|
}
|
||
|
|
||
4 years ago
|
export function getContractAtAddress(tokenAddress) {
|
||
4 years ago
|
return global.eth.contract(abi).at(tokenAddress);
|
||
7 years ago
|
}
|
||
7 years ago
|
|
||
4 years ago
|
export function getRandomFileName() {
|
||
4 years ago
|
let fileName = '';
|
||
5 years ago
|
const charBank = [
|
||
|
...'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
|
||
4 years ago
|
];
|
||
|
const fileNameLength = Math.floor(Math.random() * 7 + 6);
|
||
5 years ago
|
|
||
|
for (let i = 0; i < fileNameLength; i++) {
|
||
4 years ago
|
fileName += charBank[Math.floor(Math.random() * charBank.length)];
|
||
5 years ago
|
}
|
||
|
|
||
4 years ago
|
return fileName;
|
||
5 years ago
|
}
|
||
|
|
||
4 years ago
|
export function exportAsFile(filename, data, type = 'text/csv') {
|
||
4 years ago
|
// eslint-disable-next-line no-param-reassign
|
||
4 years ago
|
filename = filename || getRandomFileName();
|
||
7 years ago
|
// source: https://stackoverflow.com/a/33542499 by Ludovic Feltz
|
||
4 years ago
|
const blob = new window.Blob([data], { type });
|
||
7 years ago
|
if (window.navigator.msSaveOrOpenBlob) {
|
||
4 years ago
|
window.navigator.msSaveBlob(blob, filename);
|
||
7 years ago
|
} else {
|
||
4 years ago
|
const elem = window.document.createElement('a');
|
||
|
elem.target = '_blank';
|
||
|
elem.href = window.URL.createObjectURL(blob);
|
||
|
elem.download = filename;
|
||
|
document.body.appendChild(elem);
|
||
|
elem.click();
|
||
|
document.body.removeChild(elem);
|
||
7 years ago
|
}
|
||
|
}
|
||
7 years ago
|
|
||
7 years ago
|
/**
|
||
|
* Safely checksumms a potentially-null address
|
||
7 years ago
|
*
|
||
5 years ago
|
* @param {string} [address] - address to checksum
|
||
4 years ago
|
* @returns {string} checksummed address
|
||
6 years ago
|
*
|
||
7 years ago
|
*/
|
||
4 years ago
|
export function checksumAddress(address) {
|
||
4 years ago
|
const checksummed = address ? ethUtil.toChecksumAddress(address) : '';
|
||
|
return checksummed;
|
||
7 years ago
|
}
|
||
6 years ago
|
|
||
5 years ago
|
/**
|
||
|
* Shortens an Ethereum address for display, preserving the beginning and end.
|
||
|
* Returns the given address if it is no longer than 10 characters.
|
||
|
* Shortened addresses are 13 characters long.
|
||
|
*
|
||
|
* Example output: 0xabcd...1234
|
||
|
*
|
||
|
* @param {string} address - The address to shorten.
|
||
|
* @returns {string} The shortened address, or the original if it was no longer
|
||
|
* than 10 characters.
|
||
|
*/
|
||
4 years ago
|
export function shortenAddress(address = '') {
|
||
6 years ago
|
if (address.length < 11) {
|
||
4 years ago
|
return address;
|
||
6 years ago
|
}
|
||
|
|
||
4 years ago
|
return `${address.slice(0, 6)}...${address.slice(-4)}`;
|
||
6 years ago
|
}
|
||
5 years ago
|
|
||
4 years ago
|
export function getAccountByAddress(accounts = [], targetAddress) {
|
||
4 years ago
|
return accounts.find(({ address }) => address === targetAddress);
|
||
5 years ago
|
}
|
||
5 years ago
|
|
||
|
/**
|
||
|
* Strips the following schemes from URL strings:
|
||
|
* - http
|
||
|
* - https
|
||
|
*
|
||
|
* @param {string} urlString - The URL string to strip the scheme from.
|
||
|
* @returns {string} The URL string, without the scheme, if it was stripped.
|
||
|
*/
|
||
4 years ago
|
export function stripHttpSchemes(urlString) {
|
||
4 years ago
|
return urlString.replace(/^https?:\/\//u, '');
|
||
5 years ago
|
}
|
||
5 years ago
|
|
||
4 years ago
|
/**
|
||
|
* Strips the following schemes from URL strings:
|
||
|
* - https
|
||
|
*
|
||
|
* @param {string} urlString - The URL string to strip the scheme from.
|
||
|
* @returns {string} The URL string, without the scheme, if it was stripped.
|
||
|
*/
|
||
|
export function stripHttpsScheme(urlString) {
|
||
|
return urlString.replace(/^https:\/\//u, '');
|
||
|
}
|
||
|
|
||
5 years ago
|
/**
|
||
|
* Checks whether a URL-like value (object or string) is an extension URL.
|
||
|
*
|
||
|
* @param {string | URL | object} urlLike - The URL-like value to test.
|
||
|
* @returns {boolean} Whether the URL-like value is an extension URL.
|
||
|
*/
|
||
4 years ago
|
export function isExtensionUrl(urlLike) {
|
||
4 years ago
|
const EXT_PROTOCOLS = ['chrome-extension:', 'moz-extension:'];
|
||
5 years ago
|
|
||
|
if (typeof urlLike === 'string') {
|
||
|
for (const protocol of EXT_PROTOCOLS) {
|
||
|
if (urlLike.startsWith(protocol)) {
|
||
4 years ago
|
return true;
|
||
5 years ago
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (urlLike?.protocol) {
|
||
4 years ago
|
return EXT_PROTOCOLS.includes(urlLike.protocol);
|
||
5 years ago
|
}
|
||
4 years ago
|
return false;
|
||
5 years ago
|
}
|
||
4 years ago
|
|
||
|
/**
|
||
|
* Checks whether an address is in a passed list of objects with address properties. The check is performed on the
|
||
|
* lowercased version of the addresses.
|
||
|
*
|
||
|
* @param {string} address - The hex address to check
|
||
4 years ago
|
* @param {Array} list - The array of objects to check
|
||
4 years ago
|
* @returns {boolean} Whether or not the address is in the list
|
||
|
*/
|
||
4 years ago
|
export function checkExistingAddresses(address, list = []) {
|
||
4 years ago
|
if (!address) {
|
||
4 years ago
|
return false;
|
||
4 years ago
|
}
|
||
|
|
||
|
const matchesAddress = (obj) => {
|
||
4 years ago
|
return obj.address.toLowerCase() === address.toLowerCase();
|
||
|
};
|
||
4 years ago
|
|
||
4 years ago
|
return list.some(matchesAddress);
|
||
4 years ago
|
}
|
||
4 years ago
|
|
||
|
/**
|
||
|
* Given a number and specified precision, returns that number in base 10 with a maximum of precision
|
||
|
* significant digits, but without any trailing zeros after the decimal point To be used when wishing
|
||
|
* to display only as much digits to the user as necessary
|
||
|
*
|
||
|
* @param {string | number | BigNumber} n - The number to format
|
||
|
* @param {number} precision - The maximum number of significant digits in the return value
|
||
|
* @returns {string} The number in decimal form, with <= precision significant digits and no decimal trailing zeros
|
||
|
*/
|
||
4 years ago
|
export function toPrecisionWithoutTrailingZeros(n, precision) {
|
||
|
return new BigNumber(n)
|
||
4 years ago
|
.toPrecision(precision)
|
||
4 years ago
|
.replace(/(\.[0-9]*[1-9])0*|(\.0*)/u, '$1');
|
||
4 years ago
|
}
|
||
4 years ago
|
|
||
|
/**
|
||
4 years ago
|
* Given and object where all values are strings, returns the same object with all values
|
||
|
* now prefixed with '0x'
|
||
|
*/
|
||
|
export function addHexPrefixToObjectValues(obj) {
|
||
4 years ago
|
return Object.keys(obj).reduce((newObj, key) => {
|
||
4 years ago
|
return { ...newObj, [key]: addHexPrefix(obj[key]) };
|
||
|
}, {});
|
||
4 years ago
|
}
|
||
|
|
||
|
/**
|
||
|
* Given the standard set of information about a transaction, returns a transaction properly formatted for
|
||
|
* publishing via JSON RPC and web3
|
||
|
*
|
||
4 years ago
|
* @param {boolean} [sendToken] - Indicates whether or not the transaciton is a token transaction
|
||
4 years ago
|
* @param {string} data - A hex string containing the data to include in the transaction
|
||
|
* @param {string} to - A hex address of the tx recipient address
|
||
|
* @param {string} from - A hex address of the tx sender address
|
||
|
* @param {string} gas - A hex representation of the gas value for the transaction
|
||
|
* @param {string} gasPrice - A hex representation of the gas price for the transaction
|
||
4 years ago
|
* @returns {Object} An object ready for submission to the blockchain, with all values appropriately hex prefixed
|
||
4 years ago
|
*/
|
||
4 years ago
|
export function constructTxParams({
|
||
|
sendToken,
|
||
|
data,
|
||
|
to,
|
||
|
amount,
|
||
|
from,
|
||
|
gas,
|
||
|
gasPrice,
|
||
|
}) {
|
||
4 years ago
|
const txParams = {
|
||
|
data,
|
||
|
from,
|
||
|
value: '0',
|
||
|
gas,
|
||
|
gasPrice,
|
||
4 years ago
|
};
|
||
4 years ago
|
|
||
|
if (!sendToken) {
|
||
4 years ago
|
txParams.value = amount;
|
||
|
txParams.to = to;
|
||
4 years ago
|
}
|
||
4 years ago
|
return addHexPrefixToObjectValues(txParams);
|
||
4 years ago
|
}
|