1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-28 23:06:37 +01:00
metamask-extension/app/scripts/controllers/swaps.js

1072 lines
34 KiB
JavaScript
Raw Normal View History

import { Web3Provider } from '@ethersproject/providers';
import { Contract } from '@ethersproject/contracts';
import BigNumber from 'bignumber.js';
import { ObservableStore } from '@metamask/obs-store';
import { mapValues, cloneDeep } from 'lodash';
import abi from 'human-standard-token-abi';
2023-08-29 15:15:33 +02:00
import { captureException } from '@sentry/browser';
import {
decGWEIToHexWEI,
sumHexes,
} from '../../../shared/modules/conversion.utils';
2020-10-06 20:28:38 +02:00
import {
DEFAULT_ERC20_APPROVE_GAS,
QUOTES_EXPIRED_ERROR,
QUOTES_NOT_AVAILABLE_ERROR,
SWAPS_FETCH_ORDER_CONFLICT,
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP,
} from '../../../shared/constants/swaps';
import { GasEstimateTypes } from '../../../shared/constants/gas';
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556) The `network` store of the network controller crams two types of data into one place. It roughly tracks whether we have enough information to make requests to the network and whether the network is capable of receiving requests, but it also stores the ID of the network (as obtained via `net_version`). Generally we shouldn't be using the network ID for anything, as it has been completely replaced by chain ID, which all custom RPC endpoints have been required to support for over a year now. However, as the network ID is used in various places within the extension codebase, removing it entirely would be a non-trivial effort. So, minimally, this commit splits `network` into two stores: `networkId` and `networkStatus`. But it also expands the concept of network status. Previously, the network was in one of two states: "loading" and "not-loading". But now it can be in one of four states: - `available`: The network is able to receive and respond to requests. - `unavailable`: The network is not able to receive and respond to requests for unknown reasons. - `blocked`: The network is actively blocking requests based on the user's geolocation. (This is specific to Infura.) - `unknown`: We don't know whether the network can receive and respond to requests, either because we haven't checked or we tried to check and were unsuccessful. This commit also changes how the network status is determined — specifically, how many requests are used to determine that status, when they occur, and whether they are awaited. Previously, the network controller would make 2 to 3 requests during the course of running `lookupNetwork`. * First, if it was an Infura network, it would make a request for `eth_blockNumber` to determine whether Infura was blocking requests or not, then emit an appropriate event. This operation was not awaited. * Then, regardless of the network, it would fetch the network ID via `net_version`. This operation was awaited. * Finally, regardless of the network, it would fetch the latest block via `eth_getBlockByNumber`, then use the result to determine whether the network supported EIP-1559. This operation was awaited. Now: * One fewer request is made, specifically `eth_blockNumber`, as we don't need to make an extra request to determine whether Infura is blocking requests; we can reuse `eth_getBlockByNumber`; * All requests are awaited, which makes `lookupNetwork` run fully in-band instead of partially out-of-band; and * Both requests for `net_version` and `eth_getBlockByNumber` are performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
import { CHAIN_IDS, NetworkStatus } from '../../../shared/constants/network';
2023-08-29 15:15:33 +02:00
import {
MetaMetricsEventCategory,
MetaMetricsEventName,
MetaMetricsEventErrorType,
} from '../../../shared/constants/metametrics';
2022-05-09 18:48:14 +02:00
import {
FALLBACK_SMART_TRANSACTIONS_REFRESH_TIME,
FALLBACK_SMART_TRANSACTIONS_DEADLINE,
FALLBACK_SMART_TRANSACTIONS_MAX_FEE_MULTIPLIER,
} from '../../../shared/constants/smartTransactions';
import { isSwapsDefaultTokenAddress } from '../../../shared/modules/swaps.utils';
2020-10-06 20:28:38 +02:00
import {
fetchTradesInfo as defaultFetchTradesInfo,
2021-09-15 15:13:18 +02:00
getBaseApi,
} from '../../../shared/lib/swaps-utils';
import fetchWithCache from '../../../shared/lib/fetch-with-cache';
import { MINUTE, SECOND } from '../../../shared/constants/time';
import { isEqualCaseInsensitive } from '../../../shared/modules/string-utils';
import {
calcGasTotal,
calcTokenAmount,
} from '../../../shared/lib/transactions-controller-utils';
import fetchEstimatedL1Fee from '../../../ui/helpers/utils/optimism/fetchEstimatedL1Fee';
import { Numeric } from '../../../shared/modules/Numeric';
import { EtherDenomination } from '../../../shared/constants/common';
2020-10-06 20:28:38 +02:00
// The MAX_GAS_LIMIT is a number that is higher than the maximum gas costs we have observed on any aggregator
const MAX_GAS_LIMIT = 2500000;
2020-10-06 20:28:38 +02:00
// To ensure that our serves are not spammed if MetaMask is left idle, we limit the number of fetches for quotes that are made on timed intervals.
// 3 seems to be an appropriate balance of giving users the time they need when MetaMask is not left idle, and turning polling off when it is.
const POLL_COUNT_LIMIT = 3;
2020-10-06 20:28:38 +02:00
// If for any reason the MetaSwap API fails to provide a refresh time,
// provide a reasonable fallback to avoid further errors
const FALLBACK_QUOTE_REFRESH_TIME = MINUTE;
2020-11-03 00:41:28 +01:00
function calculateGasEstimateWithRefund(
maxGas = MAX_GAS_LIMIT,
estimatedRefund = 0,
estimatedGas = 0,
) {
const maxGasMinusRefund = new BigNumber(maxGas, 10).minus(
estimatedRefund,
10,
);
2022-02-07 11:58:31 +01:00
const isMaxGasMinusRefundNegative = maxGasMinusRefund.lt(0);
2020-11-03 00:41:28 +01:00
2022-02-07 11:58:31 +01:00
const gasEstimateWithRefund =
!isMaxGasMinusRefundNegative && maxGasMinusRefund.lt(estimatedGas, 16)
? `0x${maxGasMinusRefund.toString(16)}`
2022-02-07 11:58:31 +01:00
: estimatedGas;
2020-10-06 20:28:38 +02:00
return gasEstimateWithRefund;
2020-10-06 20:28:38 +02:00
}
const initialState = {
swapsState: {
quotes: {},
2021-09-15 15:13:18 +02:00
quotesPollingLimitEnabled: false,
2020-10-06 20:28:38 +02:00
fetchParams: null,
tokens: null,
tradeTxId: null,
approveTxId: null,
quotesLastFetched: null,
customMaxGas: '',
customGasPrice: null,
customMaxFeePerGas: null,
customMaxPriorityFeePerGas: null,
swapsUserFeeLevel: '',
2020-10-06 20:28:38 +02:00
selectedAggId: null,
customApproveTxData: '',
errorKey: '',
topAggId: null,
routeState: '',
swapsFeatureIsLive: true,
saveFetchedQuotes: false,
swapsQuoteRefreshTime: FALLBACK_QUOTE_REFRESH_TIME,
2021-09-15 15:13:18 +02:00
swapsQuotePrefetchingRefreshTime: FALLBACK_QUOTE_REFRESH_TIME,
2022-05-09 18:48:14 +02:00
swapsStxBatchStatusRefreshTime: FALLBACK_SMART_TRANSACTIONS_REFRESH_TIME,
2022-07-31 20:26:40 +02:00
swapsStxGetTransactionsRefreshTime:
FALLBACK_SMART_TRANSACTIONS_REFRESH_TIME,
2022-05-09 18:48:14 +02:00
swapsStxMaxFeeMultiplier: FALLBACK_SMART_TRANSACTIONS_MAX_FEE_MULTIPLIER,
swapsFeatureFlags: {},
2020-10-06 20:28:38 +02:00
},
};
2020-10-06 20:28:38 +02:00
export default class SwapsController {
2023-06-15 20:17:21 +02:00
constructor(
{
getBufferedGasLimit,
networkController,
provider,
getProviderConfig,
getTokenRatesState,
fetchTradesInfo = defaultFetchTradesInfo,
getCurrentChainId,
getEIP1559GasFeeEstimates,
onNetworkStateChange,
2023-08-29 15:15:33 +02:00
trackMetaMetricsEvent,
2023-06-15 20:17:21 +02:00
},
state,
) {
2020-10-06 20:28:38 +02:00
this.store = new ObservableStore({
2023-06-15 20:17:21 +02:00
swapsState: {
...initialState.swapsState,
swapsFeatureFlags: state?.swapsState?.swapsFeatureFlags || {},
},
});
2020-10-06 20:28:38 +02:00
Keep memstore contents after service worker restarts (#15913) * Add all controllers in memstore to store Add methods to controller to reset memstore Reset memstore when popup or tab is closed. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * When profile is loaded, set isFirstTime to true.. After resetting the controllers, set the flag to false. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Remove console.logs Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * For some reason programmatically computing the store is not working. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Proper check for browser.storage Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * do a list of rest methods instead of reset controllers. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Mock controller resetStates and localstore get/set Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Comments about TLC Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * bind this. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * use globalThis instead of locastore to store first time state. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Test to check that resetStates is not called a second time Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Set init state in GasFeeController and other controllers so that their state is persisted accross SW restarts Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Revert localstore changes Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * wrap the reset states changes in MV3 flag Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Remove localstore from metamask-controller Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Always reset state on MMController start in MV2. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Use relative path for import of isManifestV3 Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Fix unit test Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com>
2022-11-22 17:56:26 +01:00
this.resetState = () => {
2023-06-15 20:17:21 +02:00
this.store.updateState({
swapsState: {
...initialState.swapsState,
swapsFeatureFlags: state?.swapsState?.swapsFeatureFlags,
},
});
Keep memstore contents after service worker restarts (#15913) * Add all controllers in memstore to store Add methods to controller to reset memstore Reset memstore when popup or tab is closed. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * When profile is loaded, set isFirstTime to true.. After resetting the controllers, set the flag to false. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Remove console.logs Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * For some reason programmatically computing the store is not working. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Proper check for browser.storage Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * do a list of rest methods instead of reset controllers. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Mock controller resetStates and localstore get/set Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Comments about TLC Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * bind this. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * use globalThis instead of locastore to store first time state. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Test to check that resetStates is not called a second time Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Set init state in GasFeeController and other controllers so that their state is persisted accross SW restarts Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Revert localstore changes Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * wrap the reset states changes in MV3 flag Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Remove localstore from metamask-controller Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Always reset state on MMController start in MV2. Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Use relative path for import of isManifestV3 Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> * Fix unit test Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com> Signed-off-by: Akintayo A. Olusegun <akintayo.segun@gmail.com>
2022-11-22 17:56:26 +01:00
};
this._fetchTradesInfo = fetchTradesInfo;
this._getCurrentChainId = getCurrentChainId;
this._getEIP1559GasFeeEstimates = getEIP1559GasFeeEstimates;
2020-10-06 20:28:38 +02:00
this.getBufferedGasLimit = getBufferedGasLimit;
this.getTokenRatesState = getTokenRatesState;
2023-08-29 15:15:33 +02:00
this.trackMetaMetricsEvent = trackMetaMetricsEvent;
2020-10-06 20:28:38 +02:00
this.pollCount = 0;
this.getProviderConfig = getProviderConfig;
2020-10-06 20:28:38 +02:00
this.indexOfNewestCallInFlight = 0;
this.ethersProvider = new Web3Provider(provider);
Replace NetworkController w/ core version (#19486) This commit fulfills a long-standing desire to get the extension using the same network controller as mobile by removing NetworkController from this repo and replacing it with NetworkController from the `@metamask/network-controller` package. The new version of NetworkController is different the old one in a few ways: - The new controller inherits from BaseControllerV2, so the `state` property is used to access the state instead of `store.getState()`. All references of the latter have been replaced with the former. - As the new controller no longer has a `store` property, it cannot be subscribed to; the controller takes a messenger which can be subscribed to instead. There were various places within MetamaskController where the old way of subscribing has been replaced with the new way. In addition, DetectTokensController has been updated to take a messenger object so that it can listen for NetworkController state changes. - The state of the new controller is not updatable from the outside. This affected BackupController, which dumps state from NetworkController (among other controllers), but also loads the same state into NetworkController on import. A method `loadBackup` has been added to NetworkController to facilitate this use case, and BackupController is now using this method instead of attempting to call `update` on NetworkController. - The new controller does not have a `getCurrentChainId` method; instead, the chain ID can be read from the provider config in state. This affected MmiController. (MmiController was also updated to read custom networks from the new network controller instead of the preferences controller). - The default network that the new controller is set to is always Mainnet (previously it could be either localhost or Goerli in test mode, depending on environment variables). This has been addressed by feeding the NetworkController initial state using the old logic, so this should not apply.
2023-06-22 20:46:09 +02:00
this._currentNetworkId = networkController.state.networkId;
onNetworkStateChange(() => {
const { networkId, networksMetadata, selectedNetworkClientId } =
networkController.state;
const selectedNetworkStatus =
networksMetadata[selectedNetworkClientId]?.status;
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556) The `network` store of the network controller crams two types of data into one place. It roughly tracks whether we have enough information to make requests to the network and whether the network is capable of receiving requests, but it also stores the ID of the network (as obtained via `net_version`). Generally we shouldn't be using the network ID for anything, as it has been completely replaced by chain ID, which all custom RPC endpoints have been required to support for over a year now. However, as the network ID is used in various places within the extension codebase, removing it entirely would be a non-trivial effort. So, minimally, this commit splits `network` into two stores: `networkId` and `networkStatus`. But it also expands the concept of network status. Previously, the network was in one of two states: "loading" and "not-loading". But now it can be in one of four states: - `available`: The network is able to receive and respond to requests. - `unavailable`: The network is not able to receive and respond to requests for unknown reasons. - `blocked`: The network is actively blocking requests based on the user's geolocation. (This is specific to Infura.) - `unknown`: We don't know whether the network can receive and respond to requests, either because we haven't checked or we tried to check and were unsuccessful. This commit also changes how the network status is determined — specifically, how many requests are used to determine that status, when they occur, and whether they are awaited. Previously, the network controller would make 2 to 3 requests during the course of running `lookupNetwork`. * First, if it was an Infura network, it would make a request for `eth_blockNumber` to determine whether Infura was blocking requests or not, then emit an appropriate event. This operation was not awaited. * Then, regardless of the network, it would fetch the network ID via `net_version`. This operation was awaited. * Finally, regardless of the network, it would fetch the latest block via `eth_getBlockByNumber`, then use the result to determine whether the network supported EIP-1559. This operation was awaited. Now: * One fewer request is made, specifically `eth_blockNumber`, as we don't need to make an extra request to determine whether Infura is blocking requests; we can reuse `eth_getBlockByNumber`; * All requests are awaited, which makes `lookupNetwork` run fully in-band instead of partially out-of-band; and * Both requests for `net_version` and `eth_getBlockByNumber` are performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
if (
selectedNetworkStatus === NetworkStatus.Available &&
NetworkController: Split `network` into `networkId` and `networkStatus` (#17556) The `network` store of the network controller crams two types of data into one place. It roughly tracks whether we have enough information to make requests to the network and whether the network is capable of receiving requests, but it also stores the ID of the network (as obtained via `net_version`). Generally we shouldn't be using the network ID for anything, as it has been completely replaced by chain ID, which all custom RPC endpoints have been required to support for over a year now. However, as the network ID is used in various places within the extension codebase, removing it entirely would be a non-trivial effort. So, minimally, this commit splits `network` into two stores: `networkId` and `networkStatus`. But it also expands the concept of network status. Previously, the network was in one of two states: "loading" and "not-loading". But now it can be in one of four states: - `available`: The network is able to receive and respond to requests. - `unavailable`: The network is not able to receive and respond to requests for unknown reasons. - `blocked`: The network is actively blocking requests based on the user's geolocation. (This is specific to Infura.) - `unknown`: We don't know whether the network can receive and respond to requests, either because we haven't checked or we tried to check and were unsuccessful. This commit also changes how the network status is determined — specifically, how many requests are used to determine that status, when they occur, and whether they are awaited. Previously, the network controller would make 2 to 3 requests during the course of running `lookupNetwork`. * First, if it was an Infura network, it would make a request for `eth_blockNumber` to determine whether Infura was blocking requests or not, then emit an appropriate event. This operation was not awaited. * Then, regardless of the network, it would fetch the network ID via `net_version`. This operation was awaited. * Finally, regardless of the network, it would fetch the latest block via `eth_getBlockByNumber`, then use the result to determine whether the network supported EIP-1559. This operation was awaited. Now: * One fewer request is made, specifically `eth_blockNumber`, as we don't need to make an extra request to determine whether Infura is blocking requests; we can reuse `eth_getBlockByNumber`; * All requests are awaited, which makes `lookupNetwork` run fully in-band instead of partially out-of-band; and * Both requests for `net_version` and `eth_getBlockByNumber` are performed in parallel to make `lookupNetwork` run slightly faster.
2023-03-31 00:49:12 +02:00
networkId !== this._currentNetworkId
) {
this._currentNetworkId = networkId;
this.ethersProvider = new Web3Provider(provider);
}
});
2020-10-06 20:28:38 +02:00
}
2022-05-09 18:48:14 +02:00
async fetchSwapsNetworkConfig(chainId) {
2021-09-15 15:13:18 +02:00
const response = await fetchWithCache(
getBaseApi('network', chainId),
2021-09-15 15:13:18 +02:00
{ method: 'GET' },
{ cacheRefreshTime: 600000 },
);
2022-05-09 18:48:14 +02:00
const { refreshRates, parameters = {} } = response || {};
2021-09-15 15:13:18 +02:00
if (
!refreshRates ||
typeof refreshRates.quotes !== 'number' ||
typeof refreshRates.quotesPrefetching !== 'number'
2021-09-15 15:13:18 +02:00
) {
throw new Error(
`MetaMask - invalid response for refreshRates: ${response}`,
);
}
// We presently use milliseconds in the UI.
return {
quotes: refreshRates.quotes * 1000,
quotesPrefetching: refreshRates.quotesPrefetching * 1000,
stxGetTransactions: refreshRates.stxGetTransactions * 1000,
stxBatchStatus: refreshRates.stxBatchStatus * 1000,
stxStatusDeadline: refreshRates.stxStatusDeadline,
2022-05-09 18:48:14 +02:00
stxMaxFeeMultiplier: parameters.stxMaxFeeMultiplier,
2021-09-15 15:13:18 +02:00
};
}
2022-05-09 18:48:14 +02:00
// Sets the network config from the MetaSwap API.
async _setSwapsNetworkConfig() {
const chainId = this._getCurrentChainId();
2022-05-09 18:48:14 +02:00
let swapsNetworkConfig;
try {
2022-05-09 18:48:14 +02:00
swapsNetworkConfig = await this.fetchSwapsNetworkConfig(chainId);
} catch (e) {
2022-05-09 18:48:14 +02:00
console.error('Request for Swaps network config failed: ', e);
}
const { swapsState: latestSwapsState } = this.store.getState();
this.store.updateState({
2021-09-15 15:13:18 +02:00
swapsState: {
...latestSwapsState,
swapsQuoteRefreshTime:
2022-05-09 18:48:14 +02:00
swapsNetworkConfig?.quotes || FALLBACK_QUOTE_REFRESH_TIME,
2021-09-15 15:13:18 +02:00
swapsQuotePrefetchingRefreshTime:
2022-05-09 18:48:14 +02:00
swapsNetworkConfig?.quotesPrefetching || FALLBACK_QUOTE_REFRESH_TIME,
swapsStxGetTransactionsRefreshTime:
2022-05-09 18:48:14 +02:00
swapsNetworkConfig?.stxGetTransactions ||
FALLBACK_SMART_TRANSACTIONS_REFRESH_TIME,
swapsStxBatchStatusRefreshTime:
2022-05-09 18:48:14 +02:00
swapsNetworkConfig?.stxBatchStatus ||
FALLBACK_SMART_TRANSACTIONS_REFRESH_TIME,
swapsStxStatusDeadline:
2022-05-09 18:48:14 +02:00
swapsNetworkConfig?.stxStatusDeadline ||
FALLBACK_SMART_TRANSACTIONS_DEADLINE,
2022-05-09 18:48:14 +02:00
swapsStxMaxFeeMultiplier:
swapsNetworkConfig?.stxMaxFeeMultiplier ||
FALLBACK_SMART_TRANSACTIONS_MAX_FEE_MULTIPLIER,
2021-09-15 15:13:18 +02:00
},
});
}
2020-10-06 20:28:38 +02:00
// Once quotes are fetched, we poll for new ones to keep the quotes up to date. Market and aggregator contract conditions can change fast enough
2021-09-15 15:13:18 +02:00
// that quotes will no longer be available after 1 or 2 minutes. When fetchAndSetQuotes is first called, it receives fetch parameters that are stored in
2020-10-06 20:28:38 +02:00
// state. These stored parameters are used on subsequent calls made during polling.
// Note: we stop polling after 3 requests, until new quotes are explicitly asked for. The logic that enforces that maximum is in the body of fetchAndSetQuotes
2020-11-03 00:41:28 +01:00
pollForNewQuotes() {
const {
2021-09-15 15:13:18 +02:00
swapsState: {
swapsQuoteRefreshTime,
swapsQuotePrefetchingRefreshTime,
quotesPollingLimitEnabled,
},
} = this.store.getState();
2021-09-15 15:13:18 +02:00
// swapsQuoteRefreshTime is used on the View Quote page, swapsQuotePrefetchingRefreshTime is used on the Build Quote page.
const quotesRefreshRateInMs = quotesPollingLimitEnabled
? swapsQuoteRefreshTime
: swapsQuotePrefetchingRefreshTime;
2020-10-06 20:28:38 +02:00
this.pollingTimeout = setTimeout(() => {
const { swapsState } = this.store.getState();
2020-11-03 00:41:28 +01:00
this.fetchAndSetQuotes(
swapsState.fetchParams,
swapsState.fetchParams?.metaData,
true,
);
2021-09-15 15:13:18 +02:00
}, quotesRefreshRateInMs);
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
stopPollingForQuotes() {
2021-09-15 15:13:18 +02:00
if (this.pollingTimeout) {
clearTimeout(this.pollingTimeout);
}
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
async fetchAndSetQuotes(
fetchParams,
fetchParamsMetaData = {},
isPolledRequest,
) {
const { chainId } = fetchParamsMetaData;
const {
swapsState: { quotesPollingLimitEnabled, saveFetchedQuotes },
} = this.store.getState();
2020-10-06 20:28:38 +02:00
if (!fetchParams) {
return null;
2020-10-06 20:28:38 +02:00
}
// Every time we get a new request that is not from the polling, we reset the poll count so we can poll for up to three more sets of quotes with these new params.
if (!isPolledRequest) {
this.pollCount = 0;
2020-10-06 20:28:38 +02:00
}
// If there are any pending poll requests, clear them so that they don't get call while this new fetch is in process
clearTimeout(this.pollingTimeout);
2020-10-06 20:28:38 +02:00
if (!isPolledRequest) {
this.setSwapsErrorKey('');
2020-10-06 20:28:38 +02:00
}
const indexOfCurrentCall = this.indexOfNewestCallInFlight + 1;
this.indexOfNewestCallInFlight = indexOfCurrentCall;
if (!saveFetchedQuotes) {
this.setSaveFetchedQuotes(true);
}
let [newQuotes] = await Promise.all([
this._fetchTradesInfo(fetchParams, {
...fetchParamsMetaData,
}),
2022-05-09 18:48:14 +02:00
this._setSwapsNetworkConfig(),
]);
2020-10-06 20:28:38 +02:00
const {
swapsState: { saveFetchedQuotes: saveFetchedQuotesAfterResponse },
} = this.store.getState();
// If saveFetchedQuotesAfterResponse is false, it means a user left Swaps (we cleaned the state)
// and we don't want to set any API response with quotes into state.
if (!saveFetchedQuotesAfterResponse) {
return [
{}, // quotes
null, // selectedAggId
];
}
2020-10-06 20:28:38 +02:00
newQuotes = mapValues(newQuotes, (quote) => ({
...quote,
sourceTokenInfo: fetchParamsMetaData.sourceTokenInfo,
destinationTokenInfo: fetchParamsMetaData.destinationTokenInfo,
}));
2020-10-06 20:28:38 +02:00
if (chainId === CHAIN_IDS.OPTIMISM && Object.values(newQuotes).length > 0) {
await Promise.all(
Object.values(newQuotes).map(async (quote) => {
if (quote.trade) {
const multiLayerL1TradeFeeTotal = await fetchEstimatedL1Fee(
chainId,
{
txParams: quote.trade,
chainId,
},
this.ethersProvider,
);
quote.multiLayerL1TradeFeeTotal = multiLayerL1TradeFeeTotal;
}
return quote;
}),
);
}
const quotesLastFetched = Date.now();
2020-10-06 20:28:38 +02:00
let approvalRequired = false;
2020-11-03 00:41:28 +01:00
if (
!isSwapsDefaultTokenAddress(fetchParams.sourceToken, chainId) &&
2020-11-03 00:41:28 +01:00
Object.values(newQuotes).length
) {
2020-10-06 20:28:38 +02:00
const allowance = await this._getERC20Allowance(
fetchParams.sourceToken,
fetchParams.fromAddress,
chainId,
);
const [firstQuote] = Object.values(newQuotes);
2020-10-06 20:28:38 +02:00
// For a user to be able to swap a token, they need to have approved the MetaSwap contract to withdraw that token.
// _getERC20Allowance() returns the amount of the token they have approved for withdrawal. If that amount is greater
2021-11-12 15:40:50 +01:00
// than 0, it means that approval has already occurred and is not needed. Otherwise, for tokens to be swapped, a new
2020-10-06 20:28:38 +02:00
// call of the ERC-20 approve method is required.
approvalRequired =
firstQuote.approvalNeeded &&
allowance.eq(0) &&
firstQuote.aggregator !== 'wrappedNative';
2020-10-06 20:28:38 +02:00
if (!approvalRequired) {
newQuotes = mapValues(newQuotes, (quote) => ({
...quote,
approvalNeeded: null,
}));
2020-10-06 20:28:38 +02:00
} else if (!isPolledRequest) {
2020-11-03 00:41:28 +01:00
const { gasLimit: approvalGas } = await this.timedoutGasReturn(
firstQuote.approvalNeeded,
2023-08-29 15:15:33 +02:00
firstQuote.aggregator,
);
2020-10-06 20:28:38 +02:00
newQuotes = mapValues(newQuotes, (quote) => ({
...quote,
approvalNeeded: {
...quote.approvalNeeded,
gas: approvalGas || DEFAULT_ERC20_APPROVE_GAS,
},
}));
2020-10-06 20:28:38 +02:00
}
}
let topAggId = null;
2020-10-06 20:28:38 +02:00
// We can reduce time on the loading screen by only doing this after the
// loading screen and best quote have rendered.
if (!approvalRequired && !fetchParams?.balanceError) {
newQuotes = await this.getAllQuotesWithGasEstimates(newQuotes);
}
2020-10-06 20:28:38 +02:00
if (Object.values(newQuotes).length === 0) {
this.setSwapsErrorKey(QUOTES_NOT_AVAILABLE_ERROR);
} else {
2022-07-31 20:26:40 +02:00
const [_topAggId, quotesWithSavingsAndFeeData] =
await this._findTopQuoteAndCalculateSavings(newQuotes);
topAggId = _topAggId;
newQuotes = quotesWithSavingsAndFeeData;
2020-10-06 20:28:38 +02:00
}
// If a newer call has been made, don't update state with old information
// Prevents timing conflicts between fetches
if (this.indexOfNewestCallInFlight !== indexOfCurrentCall) {
throw new Error(SWAPS_FETCH_ORDER_CONFLICT);
}
const { swapsState } = this.store.getState();
let { selectedAggId } = swapsState;
2020-10-06 20:28:38 +02:00
if (!newQuotes[selectedAggId]) {
selectedAggId = null;
2020-10-06 20:28:38 +02:00
}
2020-10-06 20:28:38 +02:00
this.store.updateState({
swapsState: {
...swapsState,
quotes: newQuotes,
fetchParams: { ...fetchParams, metaData: fetchParamsMetaData },
quotesLastFetched,
selectedAggId,
topAggId,
},
});
2020-10-06 20:28:38 +02:00
2021-09-15 15:13:18 +02:00
if (quotesPollingLimitEnabled) {
// We only want to do up to a maximum of three requests from polling if polling limit is enabled.
// Otherwise we won't increase pollCount, so polling will run without a limit.
this.pollCount += 1;
}
if (!quotesPollingLimitEnabled || this.pollCount < POLL_COUNT_LIMIT + 1) {
this.pollForNewQuotes();
2020-10-06 20:28:38 +02:00
} else {
this.resetPostFetchState();
this.setSwapsErrorKey(QUOTES_EXPIRED_ERROR);
return null;
2020-10-06 20:28:38 +02:00
}
return [newQuotes, topAggId];
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
safeRefetchQuotes() {
const { swapsState } = this.store.getState();
2020-10-06 20:28:38 +02:00
if (!this.pollingTimeout && swapsState.fetchParams) {
this.fetchAndSetQuotes(swapsState.fetchParams);
2020-10-06 20:28:38 +02:00
}
}
2020-11-03 00:41:28 +01:00
setSelectedQuoteAggId(selectedAggId) {
const { swapsState } = this.store.getState();
this.store.updateState({ swapsState: { ...swapsState, selectedAggId } });
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
setSwapsTokens(tokens) {
const { swapsState } = this.store.getState();
this.store.updateState({ swapsState: { ...swapsState, tokens } });
2020-10-06 20:28:38 +02:00
}
2021-09-15 15:13:18 +02:00
clearSwapsQuotes() {
const { swapsState } = this.store.getState();
this.store.updateState({ swapsState: { ...swapsState, quotes: {} } });
}
2020-11-03 00:41:28 +01:00
setSwapsErrorKey(errorKey) {
const { swapsState } = this.store.getState();
this.store.updateState({ swapsState: { ...swapsState, errorKey } });
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
async getAllQuotesWithGasEstimates(quotes) {
2020-10-06 20:28:38 +02:00
const quoteGasData = await Promise.all(
Object.values(quotes).map(async (quote) => {
2020-11-03 00:41:28 +01:00
const { gasLimit, simulationFails } = await this.timedoutGasReturn(
quote.trade,
2023-08-29 15:15:33 +02:00
quote.aggregator,
);
return [gasLimit, simulationFails, quote.aggregator];
2020-10-06 20:28:38 +02:00
}),
);
2020-10-06 20:28:38 +02:00
const newQuotes = {};
2020-10-06 20:28:38 +02:00
quoteGasData.forEach(([gasLimit, simulationFails, aggId]) => {
if (gasLimit && !simulationFails) {
2020-11-03 00:41:28 +01:00
const gasEstimateWithRefund = calculateGasEstimateWithRefund(
quotes[aggId].maxGas,
quotes[aggId].estimatedRefund,
gasLimit,
);
2020-10-06 20:28:38 +02:00
newQuotes[aggId] = {
...quotes[aggId],
gasEstimate: gasLimit,
gasEstimateWithRefund,
};
2020-10-06 20:28:38 +02:00
} else if (quotes[aggId].approvalNeeded) {
// If gas estimation fails, but an ERC-20 approve is needed, then we do not add any estimate property to the quote object
// Such quotes will rely on the maxGas and averageGas properties from the api
newQuotes[aggId] = quotes[aggId];
2020-10-06 20:28:38 +02:00
}
// If gas estimation fails and no approval is needed, then we filter that quote out, so that it is not shown to the user
});
return newQuotes;
2020-10-06 20:28:38 +02:00
}
2023-08-29 15:15:33 +02:00
timedoutGasReturn(tradeTxParams, aggregator = '') {
2020-10-06 20:28:38 +02:00
return new Promise((resolve) => {
let gasTimedOut = false;
2020-10-06 20:28:38 +02:00
const gasTimeout = setTimeout(() => {
gasTimedOut = true;
2023-08-29 15:15:33 +02:00
this.trackMetaMetricsEvent({
event: MetaMetricsEventName.QuoteError,
category: MetaMetricsEventCategory.Swaps,
properties: {
error_type: MetaMetricsEventErrorType.GasTimeout,
aggregator,
},
});
resolve({
gasLimit: null,
simulationFails: true,
});
}, SECOND * 5);
2020-10-06 20:28:38 +02:00
// Remove gas from params that will be passed to the `estimateGas` call
// Including it can cause the estimate to fail if the actual gas needed
// exceeds the passed gas
const tradeTxParamsForGasEstimate = {
data: tradeTxParams.data,
from: tradeTxParams.from,
to: tradeTxParams.to,
value: tradeTxParams.value,
};
this.getBufferedGasLimit({ txParams: tradeTxParamsForGasEstimate }, 1)
2020-10-06 20:28:38 +02:00
.then(({ gasLimit, simulationFails }) => {
if (!gasTimedOut) {
clearTimeout(gasTimeout);
resolve({ gasLimit, simulationFails });
2020-10-06 20:28:38 +02:00
}
})
.catch((e) => {
2023-08-29 15:15:33 +02:00
captureException(e, {
extra: {
aggregator,
},
});
2020-10-06 20:28:38 +02:00
if (!gasTimedOut) {
clearTimeout(gasTimeout);
resolve({ gasLimit: null, simulationFails: true });
2020-10-06 20:28:38 +02:00
}
});
});
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
async setInitialGasEstimate(initialAggId) {
const { swapsState } = this.store.getState();
2020-10-06 20:28:38 +02:00
const quoteToUpdate = { ...swapsState.quotes[initialAggId] };
2020-10-06 20:28:38 +02:00
2022-07-31 20:26:40 +02:00
const { gasLimit: newGasEstimate, simulationFails } =
2023-08-29 15:15:33 +02:00
await this.timedoutGasReturn(
quoteToUpdate.trade,
quoteToUpdate.aggregator,
);
2020-10-06 20:28:38 +02:00
if (newGasEstimate && !simulationFails) {
2020-11-03 00:41:28 +01:00
const gasEstimateWithRefund = calculateGasEstimateWithRefund(
quoteToUpdate.maxGas,
quoteToUpdate.estimatedRefund,
newGasEstimate,
);
2020-10-06 20:28:38 +02:00
quoteToUpdate.gasEstimate = newGasEstimate;
quoteToUpdate.gasEstimateWithRefund = gasEstimateWithRefund;
2020-10-06 20:28:38 +02:00
}
this.store.updateState({
2020-11-03 00:41:28 +01:00
swapsState: {
...swapsState,
quotes: { ...swapsState.quotes, [initialAggId]: quoteToUpdate },
},
});
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
setApproveTxId(approveTxId) {
const { swapsState } = this.store.getState();
this.store.updateState({ swapsState: { ...swapsState, approveTxId } });
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
setTradeTxId(tradeTxId) {
const { swapsState } = this.store.getState();
this.store.updateState({ swapsState: { ...swapsState, tradeTxId } });
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
setQuotesLastFetched(quotesLastFetched) {
const { swapsState } = this.store.getState();
this.store.updateState({
swapsState: { ...swapsState, quotesLastFetched },
});
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
setSwapsTxGasPrice(gasPrice) {
const { swapsState } = this.store.getState();
2020-10-06 20:28:38 +02:00
this.store.updateState({
swapsState: { ...swapsState, customGasPrice: gasPrice },
});
2020-10-06 20:28:38 +02:00
}
setSwapsTxMaxFeePerGas(maxFeePerGas) {
const { swapsState } = this.store.getState();
this.store.updateState({
swapsState: { ...swapsState, customMaxFeePerGas: maxFeePerGas },
});
}
setSwapsUserFeeLevel(swapsUserFeeLevel) {
const { swapsState } = this.store.getState();
this.store.updateState({
swapsState: { ...swapsState, swapsUserFeeLevel },
});
}
2021-09-15 15:13:18 +02:00
setSwapsQuotesPollingLimitEnabled(quotesPollingLimitEnabled) {
const { swapsState } = this.store.getState();
this.store.updateState({
swapsState: { ...swapsState, quotesPollingLimitEnabled },
});
}
setSwapsTxMaxFeePriorityPerGas(maxPriorityFeePerGas) {
const { swapsState } = this.store.getState();
this.store.updateState({
swapsState: {
...swapsState,
customMaxPriorityFeePerGas: maxPriorityFeePerGas,
},
});
}
2020-11-03 00:41:28 +01:00
setSwapsTxGasLimit(gasLimit) {
const { swapsState } = this.store.getState();
2020-10-06 20:28:38 +02:00
this.store.updateState({
swapsState: { ...swapsState, customMaxGas: gasLimit },
});
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
setCustomApproveTxData(data) {
const { swapsState } = this.store.getState();
2020-10-06 20:28:38 +02:00
this.store.updateState({
swapsState: { ...swapsState, customApproveTxData: data },
});
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
setBackgroundSwapRouteState(routeState) {
const { swapsState } = this.store.getState();
this.store.updateState({ swapsState: { ...swapsState, routeState } });
2020-10-06 20:28:38 +02:00
}
setSaveFetchedQuotes(status) {
const { swapsState } = this.store.getState();
this.store.updateState({
swapsState: { ...swapsState, saveFetchedQuotes: status },
});
}
setSwapsLiveness(swapsLiveness) {
const { swapsState } = this.store.getState();
const { swapsFeatureIsLive } = swapsLiveness;
2020-11-03 00:41:28 +01:00
this.store.updateState({
swapsState: { ...swapsState, swapsFeatureIsLive },
});
2020-10-06 20:28:38 +02:00
}
setSwapsFeatureFlags(swapsFeatureFlags) {
const { swapsState } = this.store.getState();
this.store.updateState({
swapsState: { ...swapsState, swapsFeatureFlags },
});
}
2020-11-03 00:41:28 +01:00
resetPostFetchState() {
const { swapsState } = this.store.getState();
2020-10-06 20:28:38 +02:00
this.store.updateState({
swapsState: {
...initialState.swapsState,
tokens: swapsState.tokens,
fetchParams: swapsState.fetchParams,
swapsFeatureIsLive: swapsState.swapsFeatureIsLive,
swapsQuoteRefreshTime: swapsState.swapsQuoteRefreshTime,
2021-09-15 15:13:18 +02:00
swapsQuotePrefetchingRefreshTime:
swapsState.swapsQuotePrefetchingRefreshTime,
swapsFeatureFlags: swapsState.swapsFeatureFlags,
2020-10-06 20:28:38 +02:00
},
});
clearTimeout(this.pollingTimeout);
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
resetSwapsState() {
const { swapsState } = this.store.getState();
2020-10-06 20:28:38 +02:00
this.store.updateState({
2020-11-03 00:41:28 +01:00
swapsState: {
...initialState.swapsState,
swapsQuoteRefreshTime: swapsState.swapsQuoteRefreshTime,
2021-09-15 15:13:18 +02:00
swapsQuotePrefetchingRefreshTime:
swapsState.swapsQuotePrefetchingRefreshTime,
2023-06-15 20:17:21 +02:00
swapsFeatureFlags: swapsState.swapsFeatureFlags,
2020-11-03 00:41:28 +01:00
},
});
clearTimeout(this.pollingTimeout);
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
async _findTopQuoteAndCalculateSavings(quotes = {}) {
2022-07-31 20:26:40 +02:00
const { contractExchangeRates: tokenConversionRates } =
this.getTokenRatesState();
2020-10-06 20:28:38 +02:00
const {
swapsState: { customGasPrice, customMaxPriorityFeePerGas },
} = this.store.getState();
const chainId = this._getCurrentChainId();
2020-10-06 20:28:38 +02:00
const numQuotes = Object.keys(quotes).length;
if (!numQuotes) {
return {};
2020-10-06 20:28:38 +02:00
}
const newQuotes = cloneDeep(quotes);
2022-07-31 20:26:40 +02:00
const { gasFeeEstimates, gasEstimateType } =
await this._getEIP1559GasFeeEstimates();
let usedGasPrice = '0x0';
if (gasEstimateType === GasEstimateTypes.feeMarket) {
const {
high: { suggestedMaxPriorityFeePerGas },
estimatedBaseFee,
} = gasFeeEstimates;
const suggestedMaxPriorityFeePerGasInHexWEI = decGWEIToHexWEI(
suggestedMaxPriorityFeePerGas,
);
const estimatedBaseFeeNumeric = new Numeric(
estimatedBaseFee,
10,
EtherDenomination.GWEI,
).toDenomination(EtherDenomination.WEI);
usedGasPrice = new Numeric(
customMaxPriorityFeePerGas || suggestedMaxPriorityFeePerGasInHexWEI,
16,
)
.add(estimatedBaseFeeNumeric)
.round(6)
.toString();
} else if (gasEstimateType === GasEstimateTypes.legacy) {
usedGasPrice = customGasPrice || decGWEIToHexWEI(gasFeeEstimates.high);
} else if (gasEstimateType === GasEstimateTypes.ethGasPrice) {
usedGasPrice =
customGasPrice || decGWEIToHexWEI(gasFeeEstimates.gasPrice);
}
2020-10-06 20:28:38 +02:00
let topAggId = null;
let overallValueOfBestQuoteForSorting = null;
2020-10-06 20:28:38 +02:00
Object.values(newQuotes).forEach((quote) => {
2020-10-06 20:28:38 +02:00
const {
aggregator,
approvalNeeded,
averageGas,
2020-10-06 20:28:38 +02:00
destinationAmount = 0,
destinationToken,
destinationTokenInfo,
gasEstimateWithRefund,
sourceAmount,
sourceToken,
trade,
fee: metaMaskFee,
multiLayerL1TradeFeeTotal,
} = quote;
const tradeGasLimitForCalculation = gasEstimateWithRefund
? new BigNumber(gasEstimateWithRefund, 16)
: new BigNumber(averageGas || MAX_GAS_LIMIT, 10);
2020-10-06 20:28:38 +02:00
const totalGasLimitForCalculation = tradeGasLimitForCalculation
.plus(approvalNeeded?.gas || '0x0', 16)
.toString(16);
let gasTotalInWeiHex = calcGasTotal(
2020-10-06 20:28:38 +02:00
totalGasLimitForCalculation,
usedGasPrice,
);
if (multiLayerL1TradeFeeTotal !== null) {
gasTotalInWeiHex = sumHexes(
gasTotalInWeiHex || '0x0',
multiLayerL1TradeFeeTotal || '0x0',
);
}
// trade.value is a sum of different values depending on the transaction.
// It always includes any external fees charged by the quote source. In
// addition, if the source asset is the selected chain's default token, trade.value
// includes the amount of that token.
const totalWeiCost = new Numeric(
gasTotalInWeiHex,
2020-11-03 00:41:28 +01:00
16,
EtherDenomination.WEI,
).add(new Numeric(trade.value, 16, EtherDenomination.WEI));
const totalEthCost = totalWeiCost
.toDenomination(EtherDenomination.ETH)
.round(6).value;
2020-10-06 20:28:38 +02:00
// The total fee is aggregator/exchange fees plus gas fees.
// If the swap is from the selected chain's default token, subtract
// the sourceAmount from the total cost. Otherwise, the total fee
// is simply trade.value plus gas fees.
const ethFee = isSwapsDefaultTokenAddress(sourceToken, chainId)
? totalWeiCost
.minus(new Numeric(sourceAmount, 10))
.toDenomination(EtherDenomination.ETH)
.round(6).value
: totalEthCost;
const decimalAdjustedDestinationAmount = calcTokenAmount(
destinationAmount,
destinationTokenInfo.decimals,
);
const tokenPercentageOfPreFeeDestAmount = new BigNumber(100, 10)
.minus(metaMaskFee, 10)
.div(100);
2022-07-31 20:26:40 +02:00
const destinationAmountBeforeMetaMaskFee =
decimalAdjustedDestinationAmount.div(tokenPercentageOfPreFeeDestAmount);
const metaMaskFeeInTokens = destinationAmountBeforeMetaMaskFee.minus(
decimalAdjustedDestinationAmount,
);
const tokenConversionRate =
tokenConversionRates[
Object.keys(tokenConversionRates).find((tokenAddress) =>
isEqualCaseInsensitive(tokenAddress, destinationToken),
)
];
const conversionRateForSorting = tokenConversionRate || 1;
const ethValueOfTokens = decimalAdjustedDestinationAmount.times(
conversionRateForSorting.toString(10),
10,
);
const conversionRateForCalculations = isSwapsDefaultTokenAddress(
destinationToken,
chainId,
)
? 1
: tokenConversionRate;
const overallValueOfQuoteForSorting =
conversionRateForCalculations === undefined
? ethValueOfTokens
: ethValueOfTokens.minus(ethFee, 10);
quote.ethFee = ethFee.toString(10);
if (conversionRateForCalculations !== undefined) {
quote.ethValueOfTokens = ethValueOfTokens.toString(10);
quote.overallValueOfQuote = overallValueOfQuoteForSorting.toString(10);
quote.metaMaskFeeInEth = metaMaskFeeInTokens
.times(conversionRateForCalculations.toString(10))
.toString(10);
}
2020-10-06 20:28:38 +02:00
if (
overallValueOfBestQuoteForSorting === null ||
overallValueOfQuoteForSorting.gt(overallValueOfBestQuoteForSorting)
2020-10-06 20:28:38 +02:00
) {
topAggId = aggregator;
overallValueOfBestQuoteForSorting = overallValueOfQuoteForSorting;
2020-10-06 20:28:38 +02:00
}
});
2020-10-06 20:28:38 +02:00
const isBest =
isSwapsDefaultTokenAddress(
newQuotes[topAggId].destinationToken,
chainId,
) ||
Boolean(
tokenConversionRates[
Object.keys(tokenConversionRates).find((tokenAddress) =>
isEqualCaseInsensitive(
tokenAddress,
newQuotes[topAggId]?.destinationToken,
),
)
],
);
2020-10-06 20:28:38 +02:00
let savings = null;
if (isBest) {
const bestQuote = newQuotes[topAggId];
savings = {};
const {
ethFee: medianEthFee,
metaMaskFeeInEth: medianMetaMaskFee,
ethValueOfTokens: medianEthValueOfTokens,
} = getMedianEthValueQuote(Object.values(newQuotes));
// Performance savings are calculated as:
// (ethValueOfTokens for the best trade) - (ethValueOfTokens for the media trade)
savings.performance = new BigNumber(bestQuote.ethValueOfTokens, 10).minus(
medianEthValueOfTokens,
10,
);
// Fee savings are calculated as:
// (fee for the median trade) - (fee for the best trade)
savings.fee = new BigNumber(medianEthFee).minus(bestQuote.ethFee, 10);
savings.metaMaskFee = bestQuote.metaMaskFeeInEth;
// Total savings are calculated as:
// performance savings + fee savings - metamask fee
savings.total = savings.performance
.plus(savings.fee)
.minus(savings.metaMaskFee)
.toString(10);
savings.performance = savings.performance.toString(10);
savings.fee = savings.fee.toString(10);
savings.medianMetaMaskFee = medianMetaMaskFee;
newQuotes[topAggId].isBestQuote = true;
newQuotes[topAggId].savings = savings;
}
return [topAggId, newQuotes];
2020-10-06 20:28:38 +02:00
}
async _getERC20Allowance(contractAddress, walletAddress, chainId) {
const contract = new Contract(contractAddress, abi, this.ethersProvider);
return await contract.allowance(
walletAddress,
SWAPS_CHAINID_CONTRACT_ADDRESS_MAP[chainId],
);
2020-10-06 20:28:38 +02:00
}
}
/**
* Calculates the median overallValueOfQuote of a sample of quotes.
*
* @param {Array} _quotes - A sample of quote objects with overallValueOfQuote, ethFee, metaMaskFeeInEth, and ethValueOfTokens properties
* @returns {object} An object with the ethValueOfTokens, ethFee, and metaMaskFeeInEth of the quote with the median overallValueOfQuote
*/
function getMedianEthValueQuote(_quotes) {
if (!Array.isArray(_quotes) || _quotes.length === 0) {
throw new Error('Expected non-empty array param.');
}
const quotes = [..._quotes];
quotes.sort((quoteA, quoteB) => {
const overallValueOfQuoteA = new BigNumber(quoteA.overallValueOfQuote, 10);
const overallValueOfQuoteB = new BigNumber(quoteB.overallValueOfQuote, 10);
if (overallValueOfQuoteA.equals(overallValueOfQuoteB)) {
return 0;
}
return overallValueOfQuoteA.lessThan(overallValueOfQuoteB) ? -1 : 1;
});
if (quotes.length % 2 === 1) {
// return middle values
const medianOverallValue =
quotes[(quotes.length - 1) / 2].overallValueOfQuote;
const quotesMatchingMedianQuoteValue = quotes.filter(
(quote) => medianOverallValue === quote.overallValueOfQuote,
);
return meansOfQuotesFeesAndValue(quotesMatchingMedianQuoteValue);
}
// return mean of middle two values
const upperIndex = quotes.length / 2;
const lowerIndex = upperIndex - 1;
const overallValueAtUpperIndex = quotes[upperIndex].overallValueOfQuote;
const overallValueAtLowerIndex = quotes[lowerIndex].overallValueOfQuote;
const quotesMatchingUpperIndexValue = quotes.filter(
(quote) => overallValueAtUpperIndex === quote.overallValueOfQuote,
);
const quotesMatchingLowerIndexValue = quotes.filter(
(quote) => overallValueAtLowerIndex === quote.overallValueOfQuote,
);
const feesAndValueAtUpperIndex = meansOfQuotesFeesAndValue(
quotesMatchingUpperIndexValue,
);
const feesAndValueAtLowerIndex = meansOfQuotesFeesAndValue(
quotesMatchingLowerIndexValue,
);
return {
ethFee: new BigNumber(feesAndValueAtUpperIndex.ethFee, 10)
.plus(feesAndValueAtLowerIndex.ethFee, 10)
.dividedBy(2)
.toString(10),
metaMaskFeeInEth: new BigNumber(
feesAndValueAtUpperIndex.metaMaskFeeInEth,
10,
)
.plus(feesAndValueAtLowerIndex.metaMaskFeeInEth, 10)
.dividedBy(2)
.toString(10),
ethValueOfTokens: new BigNumber(
feesAndValueAtUpperIndex.ethValueOfTokens,
10,
)
.plus(feesAndValueAtLowerIndex.ethValueOfTokens, 10)
.dividedBy(2)
.toString(10),
};
}
/**
* Calculates the arithmetic mean for each of three properties - ethFee, metaMaskFeeInEth and ethValueOfTokens - across
* an array of objects containing those properties.
*
* @param {Array} quotes - A sample of quote objects with overallValueOfQuote, ethFee, metaMaskFeeInEth and
* ethValueOfTokens properties
* @returns {object} An object with the arithmetic mean each of the ethFee, metaMaskFeeInEth and ethValueOfTokens of
* the passed quote objects
*/
function meansOfQuotesFeesAndValue(quotes) {
const feeAndValueSumsAsBigNumbers = quotes.reduce(
(feeAndValueSums, quote) => ({
ethFee: feeAndValueSums.ethFee.plus(quote.ethFee, 10),
metaMaskFeeInEth: feeAndValueSums.metaMaskFeeInEth.plus(
quote.metaMaskFeeInEth,
10,
),
ethValueOfTokens: feeAndValueSums.ethValueOfTokens.plus(
quote.ethValueOfTokens,
10,
),
}),
{
ethFee: new BigNumber(0, 10),
metaMaskFeeInEth: new BigNumber(0, 10),
ethValueOfTokens: new BigNumber(0, 10),
},
);
return {
ethFee: feeAndValueSumsAsBigNumbers.ethFee
.div(quotes.length, 10)
.toString(10),
metaMaskFeeInEth: feeAndValueSumsAsBigNumbers.metaMaskFeeInEth
.div(quotes.length, 10)
.toString(10),
ethValueOfTokens: feeAndValueSumsAsBigNumbers.ethValueOfTokens
.div(quotes.length, 10)
.toString(10),
};
}
2020-10-06 20:28:38 +02:00
export const utils = {
getMedianEthValueQuote,
meansOfQuotesFeesAndValue,
};