1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-12 20:57:12 +01:00
metamask-extension/app/scripts/controllers/transactions/lib/util.js
MetaMask Bot 31d5c1cf22
Version v10.18.4 RC (#15643)
* Version v10.18.4

* Fix default currency symbol for `wallet_addEthereumChain` + improve warnings for data that doesn't match our validation expectations (#15201)

* set more appropriate default for ticker symbol when wallet_addEthereumChain is called

* throw error to dapp when site suggests network with same chainId but different ticker symbol from already added network, instead of showing error and disabled notification to user

* Fix Provider Tracking Metrics (#15082)

* fix filetype audit (#15334)

* Remove decentralized 4byte function signature registry since it contains incorrect signatures and we can't algorithmically check for best option when 4byte.directory is down (#15300)

* remove decentralized 4byte function signature registry since it is griefed and we can't algorithmically check for best option when 4byte is down

* add migration

* remove nock of on chain registry call in getMethodDataAsync test

* remove audit exclusion (#15346)

* Updates `eth-lattice-keyring` to v0.10.0 (#15261)

This is mainly associated with an update in GridPlus SDK and enables
better strategies for fetching calldata decoder data.
`eth-lattice-keyring` changes:
GridPlus/eth-lattice-keyring@v0.7.3...v0.10.0
`gridplus-sdk` changes (which includes a codebase rewrite):
GridPlus/gridplus-sdk@v1.2.3...v2.2.2

* Fix 'block link explorer on custom networks' (#13870)

* Created a logic for the 'Add a block explorer URL'

Removed unused message

Message logic rollback

Modified history push operation

WIP: Pushing before rebasing

Applied requested changes

Removed unintenionally added code

* Lint fix

* Metrics fixed

* Stop injecting provider on docs.google.com (#15459)

* Fix setting of gasPrice when on non-eip 1559 networks (#15628)

* Fix setting of gasPrice when on non-eip 1559 networks

* Fix unit tests

* Fix logic

* Update ui/ducks/send/send.test.js

Co-authored-by: Mark Stacey <markjstacey@gmail.com>

Co-authored-by: Mark Stacey <markjstacey@gmail.com>

* [GridPlus] Bumps `eth-lattice-keyring` to v0.11.0 (#15490)

* [GridPlus] Bumps `gridplus-sdk` to v2.2.4 (#15561)

* remove exclusions for mismatched object jsdoc type casing (#15351)

* Improve `tokenId` parsing and clean up `useAssetDetails` hook (#15304)

* Fix state creation in setupSentryGetStateGlobal (#15635)

* filter breadcrumbs for improved clarity while debugging sentry errors (#15639)

* Update v10.18.4 changelog (#15645)

* Auto generated changelog

* Update 10.18.4 changelog

* Run lavamoat:auto

* Call metrics event for wallet type selection at the right time (#15591)

* Fix Sentry in LavaMoat contexts (#15672)

Our Sentry setup relies upon application state, but it wasn't able to
access it in LavaMoat builds because it's running in a separate
Compartment.

A patch has been introduced to the LavaMoat runtime to allow the root
Compartment to mutate the `rootGlobals` object, which is accessible
from outside the compartment as well. This lets us expose application
state to our Sentry integration.

* Fix Sentry deduplication of events that were never sent (#15677)

The Sentry `Dedupe` integration has been filtering out our events, even
when they were never sent due to our `beforeSend` handler. It was
wrongly identifying them as duplicates because it has no knowledge of
`beforeSend` or whether they were actually sent or not.

To resolve this, the filtering we were doing in `beforeSend` has been
moved to a Sentry integration. This integration is installed ahead of
the `Dedupe` integration, so `Dedupe` should never find out about any
events that we filter out, and thus will never consider them as sent
when they were not.

* Replace `lavamoat-runtime.js` patch (#15682)

A patch made in #15672 was found to be unnecessary. Instead of setting
a `rootGlobals` object upon construction of the root compartment, we
are now creating a `sentryHooks` object in the initial top-level
compartment. I hadn't realized at the time that the root compartment
would inherit all properties of the initial compartment `globalThis`.

This accomplishes the same goals as #15672 except without needing a
patch.

* Update v10.18.4 changelog

* Fix lint issues

* Update yarn.lock

* Update `depcheck` to latest version (#15690)

`depcheck` has been updated to the latest version. This version pins
`@babel/parser` to v7.16.4 because of unresolved bugs in v7.16.5 that
result in `depcheck` failing to parse TypeScript files correctly.

We had a Yarn resolution in place to ensure `@babel/parser@7.16.4` was
being used already. That resolution is no longer needed so it has been
removed. This should resove the issue the dev team has been seeing
lately where `yarn` and `yarn-deduplicate` disagree about the state the
lockfile should be in.

* Update yarn.lock

* Update LavaMoat policy

* deduplicate

* Update LavaMoat build policy

Co-authored-by: MetaMask Bot <metamaskbot@users.noreply.github.com>
Co-authored-by: Alex Donesky <adonesky@gmail.com>
Co-authored-by: Brad Decker <bhdecker84@gmail.com>
Co-authored-by: Alex Miller <asmiller1989@gmail.com>
Co-authored-by: Filip Sekulic <filip.sekulic@consensys.net>
Co-authored-by: Erik Marks <25517051+rekmarks@users.noreply.github.com>
Co-authored-by: Dan J Miller <danjm.com@gmail.com>
Co-authored-by: Mark Stacey <markjstacey@gmail.com>
Co-authored-by: seaona <54408225+seaona@users.noreply.github.com>
Co-authored-by: seaona <mariona@gmx.es>
Co-authored-by: PeterYinusa <peter.yinusa@consensys.net>
2022-08-24 19:57:47 +01:00

330 lines
11 KiB
JavaScript

import { ethErrors } from 'eth-rpc-errors';
import { addHexPrefix } from '../../../lib/util';
import {
TRANSACTION_ENVELOPE_TYPES,
TRANSACTION_STATUSES,
} from '../../../../../shared/constants/transaction';
import { isEIP1559Transaction } from '../../../../../shared/modules/transaction.utils';
import { isValidHexAddress } from '../../../../../shared/modules/hexstring-utils';
const normalizers = {
from: addHexPrefix,
to: (to, lowerCase) =>
lowerCase ? addHexPrefix(to).toLowerCase() : addHexPrefix(to),
nonce: addHexPrefix,
value: addHexPrefix,
data: addHexPrefix,
gas: addHexPrefix,
gasPrice: addHexPrefix,
maxFeePerGas: addHexPrefix,
maxPriorityFeePerGas: addHexPrefix,
type: addHexPrefix,
estimateSuggested: (estimate) => estimate,
estimateUsed: (estimate) => estimate,
};
export function normalizeAndValidateTxParams(txParams, lowerCase = true) {
const normalizedTxParams = normalizeTxParams(txParams, lowerCase);
validateTxParams(normalizedTxParams);
return normalizedTxParams;
}
/**
* Normalizes the given txParams
*
* @param {object} txParams - The transaction params
* @param {boolean} [lowerCase] - Whether to lowercase the 'to' address.
* Default: true
* @returns {object} the normalized tx params
*/
export function normalizeTxParams(txParams, lowerCase = true) {
// apply only keys in the normalizers
const normalizedTxParams = {};
for (const key in normalizers) {
if (txParams[key]) {
normalizedTxParams[key] = normalizers[key](txParams[key], lowerCase);
}
}
return normalizedTxParams;
}
/**
* Given two fields, ensure that the second field is not included in txParams,
* and if it is throw an invalidParams error.
*
* @param {object} txParams - the transaction parameters object
* @param {string} fieldBeingValidated - the current field being validated
* @param {string} mutuallyExclusiveField - the field to ensure is not provided
* @throws {ethErrors.rpc.invalidParams} Throws if mutuallyExclusiveField is
* present in txParams.
*/
function ensureMutuallyExclusiveFieldsNotProvided(
txParams,
fieldBeingValidated,
mutuallyExclusiveField,
) {
if (typeof txParams[mutuallyExclusiveField] !== 'undefined') {
throw ethErrors.rpc.invalidParams(
`Invalid transaction params: specified ${fieldBeingValidated} but also included ${mutuallyExclusiveField}, these cannot be mixed`,
);
}
}
/**
* Ensures that the provided value for field is a string, throws an
* invalidParams error if field is not a string.
*
* @param {object} txParams - the transaction parameters object
* @param {string} field - the current field being validated
* @throws {ethErrors.rpc.invalidParams} Throws if field is not a string
*/
function ensureFieldIsString(txParams, field) {
if (typeof txParams[field] !== 'string') {
throw ethErrors.rpc.invalidParams(
`Invalid transaction params: ${field} is not a string. got: (${txParams[field]})`,
);
}
}
/**
* Ensures that the provided txParams has the proper 'type' specified for the
* given field, if it is provided. If types do not match throws an
* invalidParams error.
*
* @param {object} txParams - the transaction parameters object
* @param {'gasPrice' | 'maxFeePerGas' | 'maxPriorityFeePerGas'} field - the
* current field being validated
* @throws {ethErrors.rpc.invalidParams} Throws if type does not match the
* expectations for provided field.
*/
function ensureProperTransactionEnvelopeTypeProvided(txParams, field) {
switch (field) {
case 'maxFeePerGas':
case 'maxPriorityFeePerGas':
if (
txParams.type &&
txParams.type !== TRANSACTION_ENVELOPE_TYPES.FEE_MARKET
) {
throw ethErrors.rpc.invalidParams(
`Invalid transaction envelope type: specified type "${txParams.type}" but including maxFeePerGas and maxPriorityFeePerGas requires type: "${TRANSACTION_ENVELOPE_TYPES.FEE_MARKET}"`,
);
}
break;
case 'gasPrice':
default:
if (
txParams.type &&
txParams.type === TRANSACTION_ENVELOPE_TYPES.FEE_MARKET
) {
throw ethErrors.rpc.invalidParams(
`Invalid transaction envelope type: specified type "${txParams.type}" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`,
);
}
}
}
/**
* Validates the given tx parameters
*
* @param {object} txParams - the tx params
* @param {boolean} eip1559Compatibility - whether or not the current network supports EIP-1559 transactions
* @throws {Error} if the tx params contains invalid fields
*/
export function validateTxParams(txParams, eip1559Compatibility = true) {
if (!txParams || typeof txParams !== 'object' || Array.isArray(txParams)) {
throw ethErrors.rpc.invalidParams(
'Invalid transaction params: must be an object.',
);
}
if (!txParams.to && !txParams.data) {
throw ethErrors.rpc.invalidParams(
'Invalid transaction params: must specify "data" for contract deployments, or "to" (and optionally "data") for all other types of transactions.',
);
}
if (isEIP1559Transaction({ txParams }) && !eip1559Compatibility) {
throw ethErrors.rpc.invalidParams(
'Invalid transaction params: params specify an EIP-1559 transaction but the current network does not support EIP-1559',
);
}
Object.entries(txParams).forEach(([key, value]) => {
// validate types
switch (key) {
case 'from':
validateFrom(txParams);
break;
case 'to':
validateRecipient(txParams);
break;
case 'gasPrice':
ensureProperTransactionEnvelopeTypeProvided(txParams, 'gasPrice');
ensureMutuallyExclusiveFieldsNotProvided(
txParams,
'gasPrice',
'maxFeePerGas',
);
ensureMutuallyExclusiveFieldsNotProvided(
txParams,
'gasPrice',
'maxPriorityFeePerGas',
);
ensureFieldIsString(txParams, 'gasPrice');
break;
case 'maxFeePerGas':
ensureProperTransactionEnvelopeTypeProvided(txParams, 'maxFeePerGas');
ensureMutuallyExclusiveFieldsNotProvided(
txParams,
'maxFeePerGas',
'gasPrice',
);
ensureFieldIsString(txParams, 'maxFeePerGas');
break;
case 'maxPriorityFeePerGas':
ensureProperTransactionEnvelopeTypeProvided(
txParams,
'maxPriorityFeePerGas',
);
ensureMutuallyExclusiveFieldsNotProvided(
txParams,
'maxPriorityFeePerGas',
'gasPrice',
);
ensureFieldIsString(txParams, 'maxPriorityFeePerGas');
break;
case 'value':
ensureFieldIsString(txParams, 'value');
if (value.toString().includes('-')) {
throw ethErrors.rpc.invalidParams(
`Invalid transaction value "${value}": not a positive number.`,
);
}
if (value.toString().includes('.')) {
throw ethErrors.rpc.invalidParams(
`Invalid transaction value of "${value}": number must be in wei.`,
);
}
if (!value.match(/^0x[a-fA-F0-9]+$/u)) {
throw ethErrors.rpc.invalidParams(
`Invalid transaction value of "${value}": not a valid hex string.`,
);
}
break;
case 'chainId':
if (typeof value !== 'number' && typeof value !== 'string') {
throw ethErrors.rpc.invalidParams(
`Invalid transaction params: ${key} is not a Number or hex string. got: (${value})`,
);
}
break;
default:
ensureFieldIsString(txParams, key);
}
});
}
/**
* Validates the {@code from} field in the given tx params
*
* @param {object} txParams
* @throws {Error} if the from address isn't valid
*/
export function validateFrom(txParams) {
if (!(typeof txParams.from === 'string')) {
throw ethErrors.rpc.invalidParams(
`Invalid "from" address "${txParams.from}": not a string.`,
);
}
if (!isValidHexAddress(txParams.from, { allowNonPrefixed: false })) {
throw ethErrors.rpc.invalidParams('Invalid "from" address.');
}
}
/**
* Validates the {@code to} field in the given tx params
*
* @param {object} txParams - the tx params
* @returns {object} the tx params
* @throws {Error} if the recipient is invalid OR there isn't tx data
*/
export function validateRecipient(txParams) {
if (txParams.to === '0x' || txParams.to === null) {
if (txParams.data) {
delete txParams.to;
} else {
throw ethErrors.rpc.invalidParams('Invalid "to" address.');
}
} else if (
txParams.to !== undefined &&
!isValidHexAddress(txParams.to, { allowNonPrefixed: false })
) {
throw ethErrors.rpc.invalidParams('Invalid "to" address.');
}
return txParams;
}
export const validateConfirmedExternalTransaction = ({
txMeta,
pendingTransactions,
confirmedTransactions,
} = {}) => {
if (!txMeta || !txMeta.txParams) {
throw ethErrors.rpc.invalidParams(
'"txMeta" or "txMeta.txParams" is missing',
);
}
if (txMeta.status !== TRANSACTION_STATUSES.CONFIRMED) {
throw ethErrors.rpc.invalidParams(
'External transaction status should be "confirmed"',
);
}
const externalTxNonce = txMeta.txParams.nonce;
if (pendingTransactions && pendingTransactions.length > 0) {
const foundPendingTxByNonce = pendingTransactions.find(
(el) => el.txParams?.nonce === externalTxNonce,
);
if (foundPendingTxByNonce) {
throw ethErrors.rpc.invalidParams(
'External transaction nonce should not be in pending txs',
);
}
}
if (confirmedTransactions && confirmedTransactions.length > 0) {
const foundConfirmedTxByNonce = confirmedTransactions.find(
(el) => el.txParams?.nonce === externalTxNonce,
);
if (foundConfirmedTxByNonce) {
throw ethErrors.rpc.invalidParams(
'External transaction nonce should not be in confirmed txs',
);
}
}
};
/**
* Returns a list of final states
*
* @returns {string[]} the states that can be considered final states
*/
export function getFinalStates() {
return [
TRANSACTION_STATUSES.REJECTED, // the user has responded no!
TRANSACTION_STATUSES.CONFIRMED, // the tx has been included in a block.
TRANSACTION_STATUSES.FAILED, // the tx failed for some reason, included on tx data.
TRANSACTION_STATUSES.DROPPED, // the tx nonce was already used
];
}
/**
* Normalizes tx receipt gas used to be a hexadecimal string.
* It seems that sometimes the numerical values being returned from
* this.query.getTransactionReceipt are BN instances and not strings.
*
* @param {string or BN instance} gasUsed
* @returns normalized gas used as hexadecimal string
*/
export function normalizeTxReceiptGasUsed(gasUsed) {
return typeof gasUsed === 'string' ? gasUsed : gasUsed.toString(16);
}