1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-22 11:22:43 +02:00
metamask-extension/ui/app/helpers/utils/transactions.util.js

208 lines
5.8 KiB
JavaScript
Raw Normal View History

import { MethodRegistry } from 'eth-method-registry';
import abi from 'human-standard-token-abi';
import { ethers } from 'ethers';
import log from 'loglevel';
import { addHexPrefix } from '../../../../app/scripts/lib/util';
import { getEtherscanNetworkPrefix } from '../../../lib/etherscan-prefix-for-network';
import {
TRANSACTION_CATEGORIES,
TRANSACTION_GROUP_STATUSES,
TRANSACTION_STATUSES,
TRANSACTION_TYPES,
} from '../../../../shared/constants/transaction';
import fetchWithCache from './fetch-with-cache';
import { addCurrencies } from './conversion-util';
2018-08-31 21:36:07 +02:00
const hstInterface = new ethers.utils.Interface(abi);
/**
* @typedef EthersContractCall
* @type object
* @property {any[]} args - The args/params to the function call.
* An array-like object with numerical and string indices.
* @property {string} name - The name of the function.
* @property {string} signature - The function signature.
* @property {string} sighash - The function signature hash.
* @property {EthersBigNumber} value - The ETH value associated with the call.
* @property {FunctionFragment} functionFragment - The Ethers function fragment
* representation of the function.
*/
/**
* @returns {EthersContractCall | undefined}
*/
2020-11-03 00:41:28 +01:00
export function getTokenData(data) {
try {
return hstInterface.parseTransaction({ data });
} catch (error) {
log.debug('Failed to parse transaction data.', error, data);
return undefined;
}
}
2020-11-03 00:41:28 +01:00
async function getMethodFrom4Byte(fourBytePrefix) {
const fourByteResponse = await fetchWithCache(
`https://www.4byte.directory/api/v1/signatures/?hex_signature=${fourBytePrefix}`,
{
referrerPolicy: 'no-referrer-when-downgrade',
body: null,
method: 'GET',
mode: 'cors',
},
);
if (fourByteResponse.count === 1) {
return fourByteResponse.results[0].text_signature;
}
return null;
}
let registry;
/**
* Attempts to return the method data from the MethodRegistry library, the message registry library and the token abi, in that order of preference
* @param {string} fourBytePrefix - The prefix from the method code associated with the data
* @returns {Object}
*/
2020-11-03 00:41:28 +01:00
export async function getMethodDataAsync(fourBytePrefix) {
try {
const fourByteSig = getMethodFrom4Byte(fourBytePrefix).catch((e) => {
log.error(e);
return null;
});
if (!registry) {
registry = new MethodRegistry({ provider: global.ethereumProvider });
}
let sig = await registry.lookup(fourBytePrefix);
if (!sig) {
sig = await fourByteSig;
}
if (!sig) {
return {};
}
const parsedResult = registry.parse(sig);
return {
name: parsedResult.name,
params: parsedResult.args,
};
} catch (error) {
log.error(error);
return {};
}
}
/**
* Returns four-byte method signature from data
*
* @param {string} data - The hex data (@code txParams.data) of a transaction
* @returns {string} The four-byte method signature
*/
2020-11-03 00:41:28 +01:00
export function getFourBytePrefix(data = '') {
const prefixedData = addHexPrefix(data);
const fourBytePrefix = prefixedData.slice(0, 10);
return fourBytePrefix;
}
/**
2020-11-03 00:41:28 +01:00
* Given an transaction category, returns a boolean which indicates whether the transaction is calling an erc20 token method
*
* @param {string} transactionCategory - The category of transaction being evaluated
* @returns {boolean} whether the transaction is calling an erc20 token method
2020-11-03 00:41:28 +01:00
*/
export function isTokenMethodAction(transactionCategory) {
return [
TRANSACTION_CATEGORIES.TOKEN_METHOD_TRANSFER,
TRANSACTION_CATEGORIES.TOKEN_METHOD_APPROVE,
TRANSACTION_CATEGORIES.TOKEN_METHOD_TRANSFER_FROM,
].includes(transactionCategory);
}
2020-11-03 00:41:28 +01:00
export function getLatestSubmittedTxWithNonce(
transactions = [],
nonce = '0x0',
) {
if (!transactions.length) {
return {};
}
return transactions.reduce((acc, current) => {
const { submittedTime, txParams: { nonce: currentNonce } = {} } = current;
if (currentNonce === nonce) {
if (!acc.submittedTime) {
return current;
}
return submittedTime > acc.submittedTime ? current : acc;
}
return acc;
}, {});
}
2020-11-03 00:41:28 +01:00
export async function isSmartContractAddress(address) {
const code = await global.eth.getCode(address);
// Geth will return '0x', and ganache-core v2.2.1 will return '0x0'
const codeIsEmpty = !code || code === '0x' || code === '0x0';
return !codeIsEmpty;
}
2018-08-31 21:36:07 +02:00
2020-11-03 00:41:28 +01:00
export function sumHexes(...args) {
const total = args.reduce((acc, hexAmount) => {
return addCurrencies(acc, hexAmount, {
2018-08-31 21:36:07 +02:00
toNumericBase: 'hex',
aBase: 16,
bBase: 16,
});
});
2018-08-31 21:36:07 +02:00
return addHexPrefix(total);
2018-08-31 21:36:07 +02:00
}
/**
* Returns a status key for a transaction. Requires parsing the txMeta.txReceipt on top of
* txMeta.status because txMeta.status does not reflect on-chain errors.
* @param {Object} transaction - The txMeta object of a transaction.
* @param {Object} transaction.txReceipt - The transaction receipt.
* @returns {string}
*/
2020-11-03 00:41:28 +01:00
export function getStatusKey(transaction) {
const {
txReceipt: { status: receiptStatus } = {},
type,
status,
} = transaction;
// There was an on-chain failure
2018-12-09 21:48:06 +01:00
if (receiptStatus === '0x0') {
return TRANSACTION_STATUSES.FAILED;
}
2020-11-03 00:41:28 +01:00
if (
status === TRANSACTION_STATUSES.CONFIRMED &&
type === TRANSACTION_TYPES.CANCEL
2020-11-03 00:41:28 +01:00
) {
return TRANSACTION_GROUP_STATUSES.CANCELLED;
2018-12-09 21:48:06 +01:00
}
return transaction.status;
}
New settings custom rpc form (#6490) * Add networks tab to settings, with header. * Adds network list to settings network tab. * Adds form to settings networks tab and connects it to network list. * Network tab: form adding and editing working * Settings network form properly handles input errors * Add translations for settings network form * Clean up styles of settings network tab. * Add popup-view styles and behaviour to settings network tab. * Fix save button on settings network form * Adds 'Add Network' button and addMode to settings networks tab * Lint fix for settings networks tab addition * Fix navigation in settings networks tab. * Editing an rpcurl in networks tab does not create new network, just changes rpc of old * Fix layout of settings tabs other than network * Networks dropdown 'Custom Rpc' item links to networks tab in settings. * Update settings sidebar networks subheader. * Make networks tab buttons width consistent with input widths in extension view. * Fix settings screen subheader height in popup view * Fix height of add networks button in popup view * Add optional label to chainId and symbol form labels in networks setting tab * Style fixes for networks tab headers * Add ability to customize block explorer used by custom rpc * Stylistic improvements+fixes to custom rpc form. * Hide cancel button. * Highlight and show network form of provider by default. * Standardize network subheader name to 'Networks' * Update e2e tests for new settings network form * Update unit tests for new rpcPrefs prop * Extract blockexplorer url construction into method. * Fix broken styles on non-network tabs in popup mode * Fix block explorer url links for cases when provider in state has not been updated. * Fix vertical spacing of network form * Don't allow click of save button on network form if nothing has changed * Ensure add network button is shown in popup view * Lint fix for networks tab * Fix block explorer url preference setting. * Fix e2e tests for custom blockexplorer in account details modal changes. * Update integration test states to include frequentRpcList property * Fix some capitalizations in en/messages.json * Remove some console.logs added during custom rpc form work * Fix external account link text and url for modal and dropdown. * Documentation, url validation, proptype required additions and lint fixes on network tab and form.
2019-05-09 19:27:14 +02:00
/**
* Returns an external block explorer URL at which a transaction can be viewed.
* @param {number} networkId
* @param {string} hash
* @param {Object} rpcPrefs
*/
2020-11-03 00:41:28 +01:00
export function getBlockExplorerUrlForTx(networkId, hash, rpcPrefs = {}) {
New settings custom rpc form (#6490) * Add networks tab to settings, with header. * Adds network list to settings network tab. * Adds form to settings networks tab and connects it to network list. * Network tab: form adding and editing working * Settings network form properly handles input errors * Add translations for settings network form * Clean up styles of settings network tab. * Add popup-view styles and behaviour to settings network tab. * Fix save button on settings network form * Adds 'Add Network' button and addMode to settings networks tab * Lint fix for settings networks tab addition * Fix navigation in settings networks tab. * Editing an rpcurl in networks tab does not create new network, just changes rpc of old * Fix layout of settings tabs other than network * Networks dropdown 'Custom Rpc' item links to networks tab in settings. * Update settings sidebar networks subheader. * Make networks tab buttons width consistent with input widths in extension view. * Fix settings screen subheader height in popup view * Fix height of add networks button in popup view * Add optional label to chainId and symbol form labels in networks setting tab * Style fixes for networks tab headers * Add ability to customize block explorer used by custom rpc * Stylistic improvements+fixes to custom rpc form. * Hide cancel button. * Highlight and show network form of provider by default. * Standardize network subheader name to 'Networks' * Update e2e tests for new settings network form * Update unit tests for new rpcPrefs prop * Extract blockexplorer url construction into method. * Fix broken styles on non-network tabs in popup mode * Fix block explorer url links for cases when provider in state has not been updated. * Fix vertical spacing of network form * Don't allow click of save button on network form if nothing has changed * Ensure add network button is shown in popup view * Lint fix for networks tab * Fix block explorer url preference setting. * Fix e2e tests for custom blockexplorer in account details modal changes. * Update integration test states to include frequentRpcList property * Fix some capitalizations in en/messages.json * Remove some console.logs added during custom rpc form work * Fix external account link text and url for modal and dropdown. * Documentation, url validation, proptype required additions and lint fixes on network tab and form.
2019-05-09 19:27:14 +02:00
if (rpcPrefs.blockExplorerUrl) {
return `${rpcPrefs.blockExplorerUrl.replace(/\/+$/u, '')}/tx/${hash}`;
New settings custom rpc form (#6490) * Add networks tab to settings, with header. * Adds network list to settings network tab. * Adds form to settings networks tab and connects it to network list. * Network tab: form adding and editing working * Settings network form properly handles input errors * Add translations for settings network form * Clean up styles of settings network tab. * Add popup-view styles and behaviour to settings network tab. * Fix save button on settings network form * Adds 'Add Network' button and addMode to settings networks tab * Lint fix for settings networks tab addition * Fix navigation in settings networks tab. * Editing an rpcurl in networks tab does not create new network, just changes rpc of old * Fix layout of settings tabs other than network * Networks dropdown 'Custom Rpc' item links to networks tab in settings. * Update settings sidebar networks subheader. * Make networks tab buttons width consistent with input widths in extension view. * Fix settings screen subheader height in popup view * Fix height of add networks button in popup view * Add optional label to chainId and symbol form labels in networks setting tab * Style fixes for networks tab headers * Add ability to customize block explorer used by custom rpc * Stylistic improvements+fixes to custom rpc form. * Hide cancel button. * Highlight and show network form of provider by default. * Standardize network subheader name to 'Networks' * Update e2e tests for new settings network form * Update unit tests for new rpcPrefs prop * Extract blockexplorer url construction into method. * Fix broken styles on non-network tabs in popup mode * Fix block explorer url links for cases when provider in state has not been updated. * Fix vertical spacing of network form * Don't allow click of save button on network form if nothing has changed * Ensure add network button is shown in popup view * Lint fix for networks tab * Fix block explorer url preference setting. * Fix e2e tests for custom blockexplorer in account details modal changes. * Update integration test states to include frequentRpcList property * Fix some capitalizations in en/messages.json * Remove some console.logs added during custom rpc form work * Fix external account link text and url for modal and dropdown. * Documentation, url validation, proptype required additions and lint fixes on network tab and form.
2019-05-09 19:27:14 +02:00
}
const prefix = getEtherscanNetworkPrefix(networkId);
return `https://${prefix}etherscan.io/tx/${hash}`;
New settings custom rpc form (#6490) * Add networks tab to settings, with header. * Adds network list to settings network tab. * Adds form to settings networks tab and connects it to network list. * Network tab: form adding and editing working * Settings network form properly handles input errors * Add translations for settings network form * Clean up styles of settings network tab. * Add popup-view styles and behaviour to settings network tab. * Fix save button on settings network form * Adds 'Add Network' button and addMode to settings networks tab * Lint fix for settings networks tab addition * Fix navigation in settings networks tab. * Editing an rpcurl in networks tab does not create new network, just changes rpc of old * Fix layout of settings tabs other than network * Networks dropdown 'Custom Rpc' item links to networks tab in settings. * Update settings sidebar networks subheader. * Make networks tab buttons width consistent with input widths in extension view. * Fix settings screen subheader height in popup view * Fix height of add networks button in popup view * Add optional label to chainId and symbol form labels in networks setting tab * Style fixes for networks tab headers * Add ability to customize block explorer used by custom rpc * Stylistic improvements+fixes to custom rpc form. * Hide cancel button. * Highlight and show network form of provider by default. * Standardize network subheader name to 'Networks' * Update e2e tests for new settings network form * Update unit tests for new rpcPrefs prop * Extract blockexplorer url construction into method. * Fix broken styles on non-network tabs in popup mode * Fix block explorer url links for cases when provider in state has not been updated. * Fix vertical spacing of network form * Don't allow click of save button on network form if nothing has changed * Ensure add network button is shown in popup view * Lint fix for networks tab * Fix block explorer url preference setting. * Fix e2e tests for custom blockexplorer in account details modal changes. * Update integration test states to include frequentRpcList property * Fix some capitalizations in en/messages.json * Remove some console.logs added during custom rpc form work * Fix external account link text and url for modal and dropdown. * Documentation, url validation, proptype required additions and lint fixes on network tab and form.
2019-05-09 19:27:14 +02:00
}