2020-10-06 20:28:38 +02:00
|
|
|
import { createSlice } from '@reduxjs/toolkit'
|
|
|
|
import BigNumber from 'bignumber.js'
|
|
|
|
import log from 'loglevel'
|
|
|
|
|
2020-11-24 16:38:04 +01:00
|
|
|
import { getStorageItem, setStorageItem } from '../../../lib/storage-helpers'
|
|
|
|
|
2020-10-06 20:28:38 +02:00
|
|
|
import {
|
|
|
|
addToken,
|
|
|
|
addUnapprovedTransaction,
|
|
|
|
fetchAndSetQuotes,
|
|
|
|
forceUpdateMetamaskState,
|
|
|
|
resetSwapsPostFetchState,
|
|
|
|
setBackgroundSwapRouteState,
|
|
|
|
setInitialGasEstimate,
|
|
|
|
setSwapsErrorKey,
|
|
|
|
setSwapsTxGasPrice,
|
|
|
|
setApproveTxId,
|
|
|
|
setTradeTxId,
|
|
|
|
stopPollingForQuotes,
|
|
|
|
updateAndApproveTx,
|
|
|
|
updateTransaction,
|
|
|
|
resetBackgroundSwapsState,
|
|
|
|
setSwapsLiveness,
|
2020-11-12 20:12:04 +01:00
|
|
|
setSelectedQuoteAggId,
|
|
|
|
setSwapsTxGasLimit,
|
2020-10-06 20:28:38 +02:00
|
|
|
} from '../../store/actions'
|
2020-11-03 00:41:28 +01:00
|
|
|
import {
|
|
|
|
AWAITING_SWAP_ROUTE,
|
|
|
|
BUILD_QUOTE_ROUTE,
|
|
|
|
LOADING_QUOTES_ROUTE,
|
|
|
|
SWAPS_ERROR_ROUTE,
|
|
|
|
SWAPS_MAINTENANCE_ROUTE,
|
|
|
|
} from '../../helpers/constants/routes'
|
2020-11-04 17:14:08 +01:00
|
|
|
import {
|
|
|
|
fetchSwapsFeatureLiveness,
|
|
|
|
fetchSwapsGasPrices,
|
|
|
|
} from '../../pages/swaps/swaps.util'
|
2020-10-06 20:28:38 +02:00
|
|
|
import { calcGasTotal } from '../../pages/send/send.utils'
|
2020-11-03 00:41:28 +01:00
|
|
|
import {
|
|
|
|
decimalToHex,
|
|
|
|
getValueFromWeiHex,
|
|
|
|
decGWEIToHexWEI,
|
|
|
|
hexToDecimal,
|
|
|
|
hexWEIToDecGWEI,
|
|
|
|
} from '../../helpers/utils/conversions.util'
|
2020-11-04 17:14:08 +01:00
|
|
|
import { conversionLessThan } from '../../helpers/utils/conversion-util'
|
2020-10-06 20:28:38 +02:00
|
|
|
import { calcTokenAmount } from '../../helpers/utils/token-util'
|
|
|
|
import {
|
|
|
|
getSelectedAccount,
|
|
|
|
getTokenExchangeRates,
|
2020-11-10 18:39:45 +01:00
|
|
|
getUSDConversionRate,
|
2020-10-06 20:28:38 +02:00
|
|
|
} from '../../selectors'
|
|
|
|
import {
|
|
|
|
ERROR_FETCHING_QUOTES,
|
|
|
|
QUOTES_NOT_AVAILABLE_ERROR,
|
|
|
|
ETH_SWAPS_TOKEN_OBJECT,
|
|
|
|
SWAP_FAILED_ERROR,
|
2020-10-21 22:05:48 +02:00
|
|
|
SWAPS_FETCH_ORDER_CONFLICT,
|
2020-10-06 20:28:38 +02:00
|
|
|
} from '../../helpers/constants/swaps'
|
2020-11-03 23:57:51 +01:00
|
|
|
import { TRANSACTION_CATEGORIES } from '../../../../shared/constants/transaction'
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-11-04 17:14:08 +01:00
|
|
|
const GAS_PRICES_LOADING_STATES = {
|
|
|
|
INITIAL: 'INITIAL',
|
|
|
|
LOADING: 'LOADING',
|
|
|
|
FAILED: 'FAILED',
|
|
|
|
COMPLETED: 'COMPLETED',
|
|
|
|
}
|
|
|
|
|
2020-12-15 18:16:51 +01:00
|
|
|
export const FALLBACK_GAS_MULTIPLIER = 1.5
|
|
|
|
|
2020-10-06 20:28:38 +02:00
|
|
|
const initialState = {
|
|
|
|
aggregatorMetadata: null,
|
|
|
|
approveTxId: null,
|
|
|
|
balanceError: false,
|
|
|
|
fetchingQuotes: false,
|
|
|
|
fromToken: null,
|
|
|
|
quotesFetchStartTime: null,
|
|
|
|
topAssets: {},
|
|
|
|
toToken: null,
|
2020-11-04 17:14:08 +01:00
|
|
|
customGas: {
|
|
|
|
price: null,
|
|
|
|
limit: null,
|
|
|
|
loading: GAS_PRICES_LOADING_STATES.INITIAL,
|
|
|
|
priceEstimates: {},
|
|
|
|
priceEstimatesLastRetrieved: 0,
|
|
|
|
fallBackPrice: null,
|
|
|
|
},
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const slice = createSlice({
|
|
|
|
name: 'swaps',
|
|
|
|
initialState,
|
|
|
|
reducers: {
|
|
|
|
clearSwapsState: () => initialState,
|
|
|
|
navigatedBackToBuildQuote: (state) => {
|
|
|
|
state.approveTxId = null
|
|
|
|
state.balanceError = false
|
|
|
|
state.fetchingQuotes = false
|
2020-11-12 20:12:04 +01:00
|
|
|
state.customGas.limit = null
|
|
|
|
state.customGas.price = null
|
2020-10-06 20:28:38 +02:00
|
|
|
},
|
|
|
|
retriedGetQuotes: (state) => {
|
|
|
|
state.approveTxId = null
|
|
|
|
state.balanceError = false
|
|
|
|
state.fetchingQuotes = false
|
|
|
|
},
|
|
|
|
setAggregatorMetadata: (state, action) => {
|
|
|
|
state.aggregatorMetadata = action.payload
|
|
|
|
},
|
|
|
|
setBalanceError: (state, action) => {
|
|
|
|
state.balanceError = action.payload
|
|
|
|
},
|
|
|
|
setFetchingQuotes: (state, action) => {
|
|
|
|
state.fetchingQuotes = action.payload
|
|
|
|
},
|
|
|
|
setFromToken: (state, action) => {
|
|
|
|
state.fromToken = action.payload
|
|
|
|
},
|
|
|
|
setQuotesFetchStartTime: (state, action) => {
|
|
|
|
state.quotesFetchStartTime = action.payload
|
|
|
|
},
|
|
|
|
setTopAssets: (state, action) => {
|
|
|
|
state.topAssets = action.payload
|
|
|
|
},
|
|
|
|
setToToken: (state, action) => {
|
|
|
|
state.toToken = action.payload
|
|
|
|
},
|
2020-11-12 20:12:04 +01:00
|
|
|
swapCustomGasModalClosed: (state) => {
|
|
|
|
state.customGas.price = null
|
|
|
|
state.customGas.limit = null
|
|
|
|
},
|
2020-11-04 17:14:08 +01:00
|
|
|
swapCustomGasModalPriceEdited: (state, action) => {
|
|
|
|
state.customGas.price = action.payload
|
|
|
|
},
|
|
|
|
swapCustomGasModalLimitEdited: (state, action) => {
|
|
|
|
state.customGas.limit = action.payload
|
|
|
|
},
|
|
|
|
swapGasPriceEstimatesFetchStarted: (state) => {
|
|
|
|
state.customGas.loading = GAS_PRICES_LOADING_STATES.LOADING
|
|
|
|
},
|
|
|
|
swapGasPriceEstimatesFetchFailed: (state) => {
|
|
|
|
state.customGas.loading = GAS_PRICES_LOADING_STATES.FAILED
|
|
|
|
},
|
|
|
|
swapGasPriceEstimatesFetchCompleted: (state, action) => {
|
|
|
|
state.customGas.priceEstimates = action.payload.priceEstimates
|
|
|
|
state.customGas.loading = GAS_PRICES_LOADING_STATES.COMPLETED
|
|
|
|
state.customGas.priceEstimatesLastRetrieved =
|
|
|
|
action.payload.priceEstimatesLastRetrieved
|
|
|
|
},
|
|
|
|
retrievedFallbackSwapsGasPrice: (state, action) => {
|
|
|
|
state.customGas.fallBackPrice = action.payload
|
|
|
|
},
|
2020-10-06 20:28:38 +02:00
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
const { actions, reducer } = slice
|
|
|
|
|
|
|
|
export default reducer
|
|
|
|
|
|
|
|
// Selectors
|
|
|
|
|
|
|
|
export const getAggregatorMetadata = (state) => state.swaps.aggregatorMetadata
|
|
|
|
|
|
|
|
export const getBalanceError = (state) => state.swaps.balanceError
|
|
|
|
|
|
|
|
export const getFromToken = (state) => state.swaps.fromToken
|
|
|
|
|
|
|
|
export const getTopAssets = (state) => state.swaps.topAssets
|
|
|
|
|
|
|
|
export const getToToken = (state) => state.swaps.toToken
|
|
|
|
|
|
|
|
export const getFetchingQuotes = (state) => state.swaps.fetchingQuotes
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export const getQuotesFetchStartTime = (state) =>
|
|
|
|
state.swaps.quotesFetchStartTime
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-11-04 17:14:08 +01:00
|
|
|
export const getSwapsCustomizationModalPrice = (state) =>
|
|
|
|
state.swaps.customGas.price
|
|
|
|
|
|
|
|
export const getSwapsCustomizationModalLimit = (state) =>
|
|
|
|
state.swaps.customGas.limit
|
|
|
|
|
|
|
|
export const swapGasPriceEstimateIsLoading = (state) =>
|
|
|
|
state.swaps.customGas.loading === GAS_PRICES_LOADING_STATES.LOADING
|
|
|
|
|
|
|
|
export const swapGasEstimateLoadingHasFailed = (state) =>
|
|
|
|
state.swaps.customGas.loading === GAS_PRICES_LOADING_STATES.INITIAL
|
|
|
|
|
|
|
|
export const getSwapGasPriceEstimateData = (state) =>
|
|
|
|
state.swaps.customGas.priceEstimates
|
|
|
|
|
|
|
|
export const getSwapsPriceEstimatesLastRetrieved = (state) =>
|
|
|
|
state.swaps.customGas.priceEstimatesLastRetrieved
|
|
|
|
|
|
|
|
export const getSwapsFallbackGasPrice = (state) =>
|
|
|
|
state.swaps.customGas.fallBackPrice
|
|
|
|
|
|
|
|
export function shouldShowCustomPriceTooLowWarning(state) {
|
|
|
|
const { average } = getSwapGasPriceEstimateData(state)
|
|
|
|
|
|
|
|
const customGasPrice = getSwapsCustomizationModalPrice(state)
|
|
|
|
|
|
|
|
if (!customGasPrice || average === undefined) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
const customPriceRisksSwapFailure = conversionLessThan(
|
|
|
|
{
|
|
|
|
value: customGasPrice,
|
|
|
|
fromNumericBase: 'hex',
|
|
|
|
fromDenomination: 'WEI',
|
|
|
|
toDenomination: 'GWEI',
|
|
|
|
},
|
|
|
|
{ value: average, fromNumericBase: 'dec' },
|
|
|
|
)
|
|
|
|
|
|
|
|
return customPriceRisksSwapFailure
|
|
|
|
}
|
|
|
|
|
2020-10-06 20:28:38 +02:00
|
|
|
// Background selectors
|
|
|
|
|
|
|
|
const getSwapsState = (state) => state.metamask.swapsState
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export const getSwapsFeatureLiveness = (state) =>
|
|
|
|
state.metamask.swapsState.swapsFeatureIsLive
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-12-15 21:24:22 +01:00
|
|
|
export const getSwapsQuoteRefreshTime = (state) =>
|
|
|
|
state.metamask.swapsState.swapsQuoteRefreshTime
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export const getBackgroundSwapRouteState = (state) =>
|
|
|
|
state.metamask.swapsState.routeState
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export const getCustomSwapsGas = (state) =>
|
|
|
|
state.metamask.swapsState.customMaxGas
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export const getCustomSwapsGasPrice = (state) =>
|
|
|
|
state.metamask.swapsState.customGasPrice
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
export const getFetchParams = (state) => state.metamask.swapsState.fetchParams
|
|
|
|
|
|
|
|
export const getQuotes = (state) => state.metamask.swapsState.quotes
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export const getQuotesLastFetched = (state) =>
|
|
|
|
state.metamask.swapsState.quotesLastFetched
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
export const getSelectedQuote = (state) => {
|
|
|
|
const { selectedAggId, quotes } = getSwapsState(state)
|
|
|
|
return quotes[selectedAggId]
|
|
|
|
}
|
|
|
|
|
|
|
|
export const getSwapsErrorKey = (state) => getSwapsState(state)?.errorKey
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export const getShowQuoteLoadingScreen = (state) =>
|
|
|
|
state.swaps.showQuoteLoadingScreen
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
export const getSwapsTokens = (state) => state.metamask.swapsState.tokens
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export const getSwapsWelcomeMessageSeenStatus = (state) =>
|
|
|
|
state.metamask.swapsWelcomeMessageHasBeenShown
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
export const getTopQuote = (state) => {
|
|
|
|
const { topAggId, quotes } = getSwapsState(state)
|
|
|
|
return quotes[topAggId]
|
|
|
|
}
|
|
|
|
|
|
|
|
export const getApproveTxId = (state) => state.metamask.swapsState.approveTxId
|
|
|
|
|
|
|
|
export const getTradeTxId = (state) => state.metamask.swapsState.tradeTxId
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export const getUsedQuote = (state) =>
|
|
|
|
getSelectedQuote(state) || getTopQuote(state)
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
// Compound selectors
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export const getDestinationTokenInfo = (state) =>
|
|
|
|
getFetchParams(state)?.metaData?.destinationTokenInfo
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-11-04 17:14:08 +01:00
|
|
|
export const getUsedSwapsGasPrice = (state) =>
|
|
|
|
getCustomSwapsGasPrice(state) || getSwapsFallbackGasPrice(state)
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
export const getApproveTxParams = (state) => {
|
|
|
|
const { approvalNeeded } = getSelectedQuote(state) || getTopQuote(state) || {}
|
|
|
|
|
|
|
|
if (!approvalNeeded) {
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
const data = getSwapsState(state)?.customApproveTxData || approvalNeeded.data
|
|
|
|
|
|
|
|
const gasPrice = getCustomSwapsGasPrice(state) || approvalNeeded.gasPrice
|
|
|
|
return { ...approvalNeeded, gasPrice, data }
|
|
|
|
}
|
|
|
|
|
|
|
|
// Actions / action-creators
|
|
|
|
|
|
|
|
const {
|
|
|
|
clearSwapsState,
|
|
|
|
navigatedBackToBuildQuote,
|
|
|
|
retriedGetQuotes,
|
2020-11-04 17:14:08 +01:00
|
|
|
swapGasPriceEstimatesFetchCompleted,
|
|
|
|
swapGasPriceEstimatesFetchStarted,
|
|
|
|
swapGasPriceEstimatesFetchFailed,
|
2020-10-06 20:28:38 +02:00
|
|
|
setAggregatorMetadata,
|
|
|
|
setBalanceError,
|
|
|
|
setFetchingQuotes,
|
|
|
|
setFromToken,
|
|
|
|
setQuotesFetchStartTime,
|
|
|
|
setTopAssets,
|
|
|
|
setToToken,
|
2020-11-04 17:14:08 +01:00
|
|
|
swapCustomGasModalPriceEdited,
|
|
|
|
swapCustomGasModalLimitEdited,
|
|
|
|
retrievedFallbackSwapsGasPrice,
|
2020-11-12 20:12:04 +01:00
|
|
|
swapCustomGasModalClosed,
|
2020-10-06 20:28:38 +02:00
|
|
|
} = actions
|
|
|
|
|
|
|
|
export {
|
|
|
|
clearSwapsState,
|
|
|
|
setAggregatorMetadata,
|
|
|
|
setBalanceError,
|
|
|
|
setFetchingQuotes,
|
|
|
|
setFromToken as setSwapsFromToken,
|
|
|
|
setQuotesFetchStartTime as setSwapQuotesFetchStartTime,
|
|
|
|
setTopAssets,
|
|
|
|
setToToken as setSwapToToken,
|
2020-11-04 17:14:08 +01:00
|
|
|
swapCustomGasModalPriceEdited,
|
|
|
|
swapCustomGasModalLimitEdited,
|
2020-11-12 20:12:04 +01:00
|
|
|
swapCustomGasModalClosed,
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export const navigateBackToBuildQuote = (history) => {
|
|
|
|
return async (dispatch) => {
|
|
|
|
// TODO: Ensure any fetch in progress is cancelled
|
2021-01-22 20:00:56 +01:00
|
|
|
await dispatch(setBackgroundSwapRouteState(''))
|
2020-10-06 20:28:38 +02:00
|
|
|
dispatch(navigatedBackToBuildQuote())
|
|
|
|
history.push(BUILD_QUOTE_ROUTE)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const prepareForRetryGetQuotes = () => {
|
|
|
|
return async (dispatch) => {
|
|
|
|
// TODO: Ensure any fetch in progress is cancelled
|
|
|
|
await dispatch(resetSwapsPostFetchState())
|
|
|
|
dispatch(retriedGetQuotes())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const prepareToLeaveSwaps = () => {
|
|
|
|
return async (dispatch) => {
|
|
|
|
dispatch(clearSwapsState())
|
|
|
|
await dispatch(resetBackgroundSwapsState())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-12 20:12:04 +01:00
|
|
|
export const swapsQuoteSelected = (aggId) => {
|
|
|
|
return (dispatch) => {
|
|
|
|
dispatch(swapCustomGasModalLimitEdited(null))
|
|
|
|
dispatch(setSelectedQuoteAggId(aggId))
|
|
|
|
dispatch(setSwapsTxGasLimit(''))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-06 20:28:38 +02:00
|
|
|
export const fetchAndSetSwapsGasPriceInfo = () => {
|
|
|
|
return async (dispatch) => {
|
2020-11-04 17:14:08 +01:00
|
|
|
const basicEstimates = await dispatch(fetchMetaSwapsGasPriceEstimates())
|
|
|
|
|
|
|
|
if (basicEstimates?.fast) {
|
|
|
|
dispatch(setSwapsTxGasPrice(decGWEIToHexWEI(basicEstimates.fast)))
|
|
|
|
}
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
export const fetchQuotesAndSetQuoteState = (
|
|
|
|
history,
|
|
|
|
inputValue,
|
|
|
|
maxSlippage,
|
|
|
|
metaMetricsEvent,
|
|
|
|
) => {
|
2020-10-06 20:28:38 +02:00
|
|
|
return async (dispatch, getState) => {
|
|
|
|
let swapsFeatureIsLive = false
|
|
|
|
try {
|
|
|
|
swapsFeatureIsLive = await fetchSwapsFeatureLiveness()
|
|
|
|
} catch (error) {
|
|
|
|
log.error('Failed to fetch Swaps liveness, defaulting to false.', error)
|
|
|
|
}
|
|
|
|
await dispatch(setSwapsLiveness(swapsFeatureIsLive))
|
|
|
|
|
|
|
|
if (!swapsFeatureIsLive) {
|
|
|
|
await history.push(SWAPS_MAINTENANCE_ROUTE)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
const state = getState()
|
|
|
|
const fetchParams = getFetchParams(state)
|
|
|
|
const selectedAccount = getSelectedAccount(state)
|
|
|
|
const balanceError = getBalanceError(state)
|
2020-11-03 00:41:28 +01:00
|
|
|
const fetchParamsFromToken =
|
|
|
|
fetchParams?.metaData?.sourceTokenInfo?.symbol === 'ETH'
|
|
|
|
? {
|
|
|
|
...ETH_SWAPS_TOKEN_OBJECT,
|
|
|
|
string: getValueFromWeiHex({
|
|
|
|
value: selectedAccount.balance,
|
|
|
|
numberOfDecimals: 4,
|
|
|
|
toDenomination: 'ETH',
|
|
|
|
}),
|
|
|
|
balance: hexToDecimal(selectedAccount.balance),
|
|
|
|
}
|
|
|
|
: fetchParams?.metaData?.sourceTokenInfo
|
2020-10-06 20:28:38 +02:00
|
|
|
const selectedFromToken = getFromToken(state) || fetchParamsFromToken || {}
|
2020-11-03 00:41:28 +01:00
|
|
|
const selectedToToken =
|
|
|
|
getToToken(state) || fetchParams?.metaData?.destinationTokenInfo || {}
|
2020-10-06 20:28:38 +02:00
|
|
|
const {
|
|
|
|
address: fromTokenAddress,
|
|
|
|
symbol: fromTokenSymbol,
|
|
|
|
decimals: fromTokenDecimals,
|
|
|
|
iconUrl: fromTokenIconUrl,
|
|
|
|
balance: fromTokenBalance,
|
|
|
|
} = selectedFromToken
|
|
|
|
const {
|
|
|
|
address: toTokenAddress,
|
|
|
|
symbol: toTokenSymbol,
|
|
|
|
decimals: toTokenDecimals,
|
|
|
|
iconUrl: toTokenIconUrl,
|
|
|
|
} = selectedToToken
|
|
|
|
await dispatch(setBackgroundSwapRouteState('loading'))
|
|
|
|
history.push(LOADING_QUOTES_ROUTE)
|
|
|
|
dispatch(setFetchingQuotes(true))
|
|
|
|
|
|
|
|
const contractExchangeRates = getTokenExchangeRates(state)
|
|
|
|
|
|
|
|
let destinationTokenAddedForSwap = false
|
|
|
|
if (toTokenSymbol !== 'ETH' && !contractExchangeRates[toTokenAddress]) {
|
|
|
|
destinationTokenAddedForSwap = true
|
2020-11-03 00:41:28 +01:00
|
|
|
await dispatch(
|
|
|
|
addToken(
|
|
|
|
toTokenAddress,
|
|
|
|
toTokenSymbol,
|
|
|
|
toTokenDecimals,
|
|
|
|
toTokenIconUrl,
|
|
|
|
true,
|
|
|
|
),
|
|
|
|
)
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
2020-11-03 00:41:28 +01:00
|
|
|
if (
|
|
|
|
fromTokenSymbol !== 'ETH' &&
|
|
|
|
!contractExchangeRates[fromTokenAddress] &&
|
|
|
|
fromTokenBalance &&
|
|
|
|
new BigNumber(fromTokenBalance, 16).gt(0)
|
|
|
|
) {
|
|
|
|
dispatch(
|
|
|
|
addToken(
|
|
|
|
fromTokenAddress,
|
|
|
|
fromTokenSymbol,
|
|
|
|
fromTokenDecimals,
|
|
|
|
fromTokenIconUrl,
|
|
|
|
true,
|
|
|
|
),
|
|
|
|
)
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
const swapsTokens = getSwapsTokens(state)
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
const sourceTokenInfo =
|
|
|
|
swapsTokens?.find(({ address }) => address === fromTokenAddress) ||
|
|
|
|
selectedFromToken
|
|
|
|
const destinationTokenInfo =
|
|
|
|
swapsTokens?.find(({ address }) => address === toTokenAddress) ||
|
|
|
|
selectedToToken
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
dispatch(setFromToken(selectedFromToken))
|
|
|
|
|
|
|
|
metaMetricsEvent({
|
|
|
|
event: 'Quotes Requested',
|
|
|
|
category: 'swaps',
|
2020-12-02 22:41:30 +01:00
|
|
|
sensitiveProperties: {
|
2020-10-06 20:28:38 +02:00
|
|
|
token_from: fromTokenSymbol,
|
|
|
|
token_from_amount: String(inputValue),
|
|
|
|
token_to: toTokenSymbol,
|
|
|
|
request_type: balanceError ? 'Quote' : 'Order',
|
|
|
|
slippage: maxSlippage,
|
|
|
|
custom_slippage: maxSlippage !== 2,
|
|
|
|
anonymizedData: true,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
|
|
|
try {
|
|
|
|
const fetchStartTime = Date.now()
|
|
|
|
dispatch(setQuotesFetchStartTime(fetchStartTime))
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
const fetchAndSetQuotesPromise = dispatch(
|
|
|
|
fetchAndSetQuotes(
|
|
|
|
{
|
|
|
|
slippage: maxSlippage,
|
|
|
|
sourceToken: fromTokenAddress,
|
|
|
|
destinationToken: toTokenAddress,
|
|
|
|
value: inputValue,
|
|
|
|
fromAddress: selectedAccount.address,
|
|
|
|
destinationTokenAddedForSwap,
|
|
|
|
balanceError,
|
|
|
|
sourceDecimals: fromTokenDecimals,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
sourceTokenInfo,
|
|
|
|
destinationTokenInfo,
|
|
|
|
accountBalance: selectedAccount.balance,
|
|
|
|
},
|
|
|
|
),
|
|
|
|
)
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
const gasPriceFetchPromise = dispatch(fetchAndSetSwapsGasPriceInfo())
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
const [[fetchedQuotes, selectedAggId]] = await Promise.all([
|
|
|
|
fetchAndSetQuotesPromise,
|
|
|
|
gasPriceFetchPromise,
|
|
|
|
])
|
2020-10-06 20:28:38 +02:00
|
|
|
|
|
|
|
if (Object.values(fetchedQuotes)?.length === 0) {
|
|
|
|
metaMetricsEvent({
|
|
|
|
event: 'No Quotes Available',
|
|
|
|
category: 'swaps',
|
2020-12-02 22:41:30 +01:00
|
|
|
sensitiveProperties: {
|
2020-10-06 20:28:38 +02:00
|
|
|
token_from: fromTokenSymbol,
|
|
|
|
token_from_amount: String(inputValue),
|
|
|
|
token_to: toTokenSymbol,
|
|
|
|
request_type: balanceError ? 'Quote' : 'Order',
|
|
|
|
slippage: maxSlippage,
|
|
|
|
custom_slippage: maxSlippage !== 2,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
dispatch(setSwapsErrorKey(QUOTES_NOT_AVAILABLE_ERROR))
|
|
|
|
} else {
|
|
|
|
const newSelectedQuote = fetchedQuotes[selectedAggId]
|
|
|
|
|
|
|
|
metaMetricsEvent({
|
|
|
|
event: 'Quotes Received',
|
|
|
|
category: 'swaps',
|
2020-12-02 22:41:30 +01:00
|
|
|
sensitiveProperties: {
|
2020-10-06 20:28:38 +02:00
|
|
|
token_from: fromTokenSymbol,
|
|
|
|
token_from_amount: String(inputValue),
|
|
|
|
token_to: toTokenSymbol,
|
2020-11-03 00:41:28 +01:00
|
|
|
token_to_amount: calcTokenAmount(
|
|
|
|
newSelectedQuote.destinationAmount,
|
|
|
|
newSelectedQuote.decimals || 18,
|
|
|
|
),
|
2020-10-06 20:28:38 +02:00
|
|
|
request_type: balanceError ? 'Quote' : 'Order',
|
|
|
|
slippage: maxSlippage,
|
|
|
|
custom_slippage: maxSlippage !== 2,
|
|
|
|
response_time: Date.now() - fetchStartTime,
|
|
|
|
best_quote_source: newSelectedQuote.aggregator,
|
|
|
|
available_quotes: Object.values(fetchedQuotes)?.length,
|
|
|
|
anonymizedData: true,
|
|
|
|
},
|
|
|
|
})
|
|
|
|
|
2020-10-07 21:00:17 +02:00
|
|
|
dispatch(setInitialGasEstimate(selectedAggId))
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
} catch (e) {
|
2020-10-21 22:05:48 +02:00
|
|
|
// A newer swap request is running, so simply bail and let the newer request respond
|
|
|
|
if (e.message === SWAPS_FETCH_ORDER_CONFLICT) {
|
2020-10-26 23:22:46 +01:00
|
|
|
log.debug(`Swap fetch order conflict detected; ignoring older request`)
|
2020-10-21 22:05:48 +02:00
|
|
|
return
|
|
|
|
}
|
2020-10-26 23:22:46 +01:00
|
|
|
// TODO: Check for any errors we should expect to occur in production, and report others to Sentry
|
|
|
|
log.error(`Error fetching quotes: `, e)
|
2020-11-04 17:14:08 +01:00
|
|
|
|
2020-10-06 20:28:38 +02:00
|
|
|
dispatch(setSwapsErrorKey(ERROR_FETCHING_QUOTES))
|
|
|
|
}
|
|
|
|
|
|
|
|
dispatch(setFetchingQuotes(false))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const signAndSendTransactions = (history, metaMetricsEvent) => {
|
|
|
|
return async (dispatch, getState) => {
|
|
|
|
let swapsFeatureIsLive = false
|
|
|
|
try {
|
|
|
|
swapsFeatureIsLive = await fetchSwapsFeatureLiveness()
|
|
|
|
} catch (error) {
|
|
|
|
log.error('Failed to fetch Swaps liveness, defaulting to false.', error)
|
|
|
|
}
|
|
|
|
await dispatch(setSwapsLiveness(swapsFeatureIsLive))
|
|
|
|
|
|
|
|
if (!swapsFeatureIsLive) {
|
|
|
|
await history.push(SWAPS_MAINTENANCE_ROUTE)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
const state = getState()
|
|
|
|
const customSwapsGas = getCustomSwapsGas(state)
|
|
|
|
const fetchParams = getFetchParams(state)
|
|
|
|
const { metaData, value: swapTokenValue, slippage } = fetchParams
|
|
|
|
const { sourceTokenInfo = {}, destinationTokenInfo = {} } = metaData
|
|
|
|
await dispatch(setBackgroundSwapRouteState('awaiting'))
|
|
|
|
await dispatch(stopPollingForQuotes())
|
|
|
|
history.push(AWAITING_SWAP_ROUTE)
|
|
|
|
|
2020-11-04 17:14:08 +01:00
|
|
|
const { fast: fastGasEstimate } = getSwapGasPriceEstimateData(state)
|
|
|
|
|
2020-10-06 20:28:38 +02:00
|
|
|
const usedQuote = getUsedQuote(state)
|
2020-10-09 16:56:23 +02:00
|
|
|
const usedTradeTxParams = usedQuote.trade
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-12-15 18:16:51 +01:00
|
|
|
const estimatedGasLimit = new BigNumber(usedQuote?.gasEstimate || `0x0`, 16)
|
2020-11-03 00:41:28 +01:00
|
|
|
const estimatedGasLimitWithMultiplier = estimatedGasLimit
|
2020-12-15 18:16:51 +01:00
|
|
|
.times(usedQuote?.gasMultiplier || FALLBACK_GAS_MULTIPLIER, 10)
|
2020-11-03 00:41:28 +01:00
|
|
|
.round(0)
|
|
|
|
.toString(16)
|
|
|
|
const maxGasLimit =
|
|
|
|
customSwapsGas ||
|
2020-12-15 18:16:51 +01:00
|
|
|
(usedQuote?.gasEstimate
|
|
|
|
? estimatedGasLimitWithMultiplier
|
2021-01-04 19:13:44 +01:00
|
|
|
: `0x${decimalToHex(usedQuote?.maxGas || 0)}`)
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-11-04 17:14:08 +01:00
|
|
|
const usedGasPrice = getUsedSwapsGasPrice(state)
|
|
|
|
usedTradeTxParams.gas = maxGasLimit
|
2020-10-06 20:28:38 +02:00
|
|
|
usedTradeTxParams.gasPrice = usedGasPrice
|
|
|
|
|
2020-11-10 18:39:45 +01:00
|
|
|
const usdConversionRate = getUSDConversionRate(state)
|
2020-11-03 00:41:28 +01:00
|
|
|
const destinationValue = calcTokenAmount(
|
|
|
|
usedQuote.destinationAmount,
|
|
|
|
destinationTokenInfo.decimals || 18,
|
|
|
|
).toPrecision(8)
|
|
|
|
const usedGasLimitEstimate =
|
|
|
|
usedQuote?.gasEstimateWithRefund ||
|
|
|
|
`0x${decimalToHex(usedQuote?.averageGas || 0)}`
|
|
|
|
const totalGasLimitEstimate = new BigNumber(usedGasLimitEstimate, 16)
|
|
|
|
.plus(usedQuote.approvalNeeded?.gas || '0x0', 16)
|
|
|
|
.toString(16)
|
2020-11-10 18:39:45 +01:00
|
|
|
const gasEstimateTotalInUSD = getValueFromWeiHex({
|
2020-10-06 20:28:38 +02:00
|
|
|
value: calcGasTotal(totalGasLimitEstimate, usedGasPrice),
|
|
|
|
toCurrency: 'usd',
|
2020-11-10 18:39:45 +01:00
|
|
|
conversionRate: usdConversionRate,
|
2020-10-06 20:28:38 +02:00
|
|
|
numberOfDecimals: 6,
|
|
|
|
})
|
2020-10-27 20:12:06 +01:00
|
|
|
|
2020-10-06 20:28:38 +02:00
|
|
|
const swapMetaData = {
|
|
|
|
token_from: sourceTokenInfo.symbol,
|
|
|
|
token_from_amount: String(swapTokenValue),
|
|
|
|
token_to: destinationTokenInfo.symbol,
|
|
|
|
token_to_amount: destinationValue,
|
|
|
|
slippage,
|
|
|
|
custom_slippage: slippage !== 2,
|
|
|
|
best_quote_source: getTopQuote(state)?.aggregator,
|
|
|
|
available_quotes: getQuotes(state)?.length,
|
2020-11-03 00:41:28 +01:00
|
|
|
other_quote_selected:
|
|
|
|
usedQuote.aggregator !== getTopQuote(state)?.aggregator,
|
|
|
|
other_quote_selected_source:
|
|
|
|
usedQuote.aggregator === getTopQuote(state)?.aggregator
|
|
|
|
? ''
|
|
|
|
: usedQuote.aggregator,
|
2020-11-10 18:39:45 +01:00
|
|
|
gas_fees: gasEstimateTotalInUSD,
|
2020-10-22 22:04:34 +02:00
|
|
|
estimated_gas: estimatedGasLimit.toString(10),
|
2020-11-04 17:14:08 +01:00
|
|
|
suggested_gas_price: fastGasEstimate,
|
|
|
|
used_gas_price: hexWEIToDecGWEI(usedGasPrice),
|
2020-11-09 20:49:41 +01:00
|
|
|
average_savings: usedQuote.savings?.total,
|
|
|
|
performance_savings: usedQuote.savings?.performance,
|
|
|
|
fee_savings: usedQuote.savings?.fee,
|
|
|
|
median_metamask_fee: usedQuote.savings?.medianMetaMaskFee,
|
2020-10-06 20:28:38 +02:00
|
|
|
}
|
|
|
|
|
2020-12-02 22:41:30 +01:00
|
|
|
metaMetricsEvent({
|
2020-10-06 20:28:38 +02:00
|
|
|
event: 'Swap Started',
|
|
|
|
category: 'swaps',
|
2020-12-02 22:41:30 +01:00
|
|
|
sensitiveProperties: swapMetaData,
|
2020-11-03 00:41:28 +01:00
|
|
|
})
|
2020-10-06 20:28:38 +02:00
|
|
|
|
2020-10-12 21:56:53 +02:00
|
|
|
let finalApproveTxMeta
|
2020-10-06 20:28:38 +02:00
|
|
|
const approveTxParams = getApproveTxParams(state)
|
|
|
|
if (approveTxParams) {
|
2020-11-03 00:41:28 +01:00
|
|
|
const approveTxMeta = await dispatch(
|
|
|
|
addUnapprovedTransaction(
|
|
|
|
{ ...approveTxParams, amount: '0x0' },
|
|
|
|
'metamask',
|
|
|
|
),
|
|
|
|
)
|
2020-10-06 20:28:38 +02:00
|
|
|
await dispatch(setApproveTxId(approveTxMeta.id))
|
2020-11-03 00:41:28 +01:00
|
|
|
finalApproveTxMeta = await dispatch(
|
|
|
|
updateTransaction(
|
|
|
|
{
|
|
|
|
...approveTxMeta,
|
2020-11-03 23:57:51 +01:00
|
|
|
transactionCategory: TRANSACTION_CATEGORIES.SWAP_APPROVAL,
|
2020-11-03 00:41:28 +01:00
|
|
|
sourceTokenSymbol: sourceTokenInfo.symbol,
|
|
|
|
},
|
|
|
|
true,
|
|
|
|
),
|
|
|
|
)
|
2020-10-06 20:28:38 +02:00
|
|
|
try {
|
|
|
|
await dispatch(updateAndApproveTx(finalApproveTxMeta, true))
|
|
|
|
} catch (e) {
|
|
|
|
await dispatch(setSwapsErrorKey(SWAP_FAILED_ERROR))
|
|
|
|
history.push(SWAPS_ERROR_ROUTE)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
const tradeTxMeta = await dispatch(
|
|
|
|
addUnapprovedTransaction(usedTradeTxParams, 'metamask'),
|
|
|
|
)
|
2020-10-06 20:28:38 +02:00
|
|
|
dispatch(setTradeTxId(tradeTxMeta.id))
|
2021-01-22 22:14:57 +01:00
|
|
|
|
|
|
|
// The simulationFails property is added during the transaction controllers
|
|
|
|
// addUnapprovedTransaction call if the estimateGas call fails. In cases
|
|
|
|
// when no approval is required, this indicates that the swap will likely
|
|
|
|
// fail. There was an earlier estimateGas call made by the swaps controller,
|
|
|
|
// but it is possible that external conditions have change since then, and
|
|
|
|
// a previously succeeding estimate gas call could now fail. By checking for
|
|
|
|
// the `simulationFails` property here, we can reduce the number of swap
|
|
|
|
// transactions that get published to the blockchain only to fail and thereby
|
|
|
|
// waste the user's funds on gas.
|
|
|
|
if (!approveTxParams && tradeTxMeta.simulationFails) {
|
|
|
|
await dispatch(setSwapsErrorKey(SWAP_FAILED_ERROR))
|
|
|
|
history.push(SWAPS_ERROR_ROUTE)
|
|
|
|
return
|
|
|
|
}
|
2020-11-03 00:41:28 +01:00
|
|
|
const finalTradeTxMeta = await dispatch(
|
|
|
|
updateTransaction(
|
|
|
|
{
|
|
|
|
...tradeTxMeta,
|
|
|
|
sourceTokenSymbol: sourceTokenInfo.symbol,
|
|
|
|
destinationTokenSymbol: destinationTokenInfo.symbol,
|
2020-11-03 23:57:51 +01:00
|
|
|
transactionCategory: TRANSACTION_CATEGORIES.SWAP,
|
2020-11-03 00:41:28 +01:00
|
|
|
destinationTokenDecimals: destinationTokenInfo.decimals,
|
|
|
|
destinationTokenAddress: destinationTokenInfo.address,
|
|
|
|
swapMetaData,
|
|
|
|
swapTokenValue,
|
|
|
|
approvalTxId: finalApproveTxMeta?.id,
|
|
|
|
},
|
|
|
|
true,
|
|
|
|
),
|
|
|
|
)
|
2020-10-06 20:28:38 +02:00
|
|
|
try {
|
|
|
|
await dispatch(updateAndApproveTx(finalTradeTxMeta, true))
|
|
|
|
} catch (e) {
|
|
|
|
await dispatch(setSwapsErrorKey(SWAP_FAILED_ERROR))
|
|
|
|
history.push(SWAPS_ERROR_ROUTE)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
await forceUpdateMetamaskState(dispatch)
|
|
|
|
}
|
|
|
|
}
|
2020-11-04 17:14:08 +01:00
|
|
|
|
|
|
|
export function fetchMetaSwapsGasPriceEstimates() {
|
|
|
|
return async (dispatch, getState) => {
|
|
|
|
const state = getState()
|
|
|
|
const priceEstimatesLastRetrieved = getSwapsPriceEstimatesLastRetrieved(
|
|
|
|
state,
|
|
|
|
)
|
|
|
|
const timeLastRetrieved =
|
|
|
|
priceEstimatesLastRetrieved ||
|
2020-11-24 16:38:04 +01:00
|
|
|
(await getStorageItem('METASWAP_GAS_PRICE_ESTIMATES_LAST_RETRIEVED')) ||
|
2020-11-04 17:14:08 +01:00
|
|
|
0
|
|
|
|
|
|
|
|
dispatch(swapGasPriceEstimatesFetchStarted())
|
|
|
|
|
|
|
|
let priceEstimates
|
|
|
|
try {
|
|
|
|
if (Date.now() - timeLastRetrieved > 30000) {
|
|
|
|
priceEstimates = await fetchSwapsGasPrices()
|
|
|
|
} else {
|
2020-11-24 16:38:04 +01:00
|
|
|
const cachedPriceEstimates = await getStorageItem(
|
2020-11-04 17:14:08 +01:00
|
|
|
'METASWAP_GAS_PRICE_ESTIMATES',
|
|
|
|
)
|
|
|
|
priceEstimates = cachedPriceEstimates || (await fetchSwapsGasPrices())
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
log.warn('Fetching swaps gas prices failed:', e)
|
|
|
|
|
|
|
|
if (!e.message?.match(/NetworkError|Fetch failed with status:/u)) {
|
|
|
|
throw e
|
|
|
|
}
|
|
|
|
|
|
|
|
dispatch(swapGasPriceEstimatesFetchFailed())
|
|
|
|
|
|
|
|
try {
|
|
|
|
const gasPrice = await global.ethQuery.gasPrice()
|
|
|
|
const gasPriceInDecGWEI = hexWEIToDecGWEI(gasPrice.toString(10))
|
|
|
|
|
|
|
|
dispatch(retrievedFallbackSwapsGasPrice(gasPriceInDecGWEI))
|
|
|
|
return null
|
|
|
|
} catch (networkGasPriceError) {
|
|
|
|
console.error(
|
|
|
|
`Failed to retrieve fallback gas price: `,
|
|
|
|
networkGasPriceError,
|
|
|
|
)
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const timeRetrieved = Date.now()
|
|
|
|
|
2020-11-24 16:38:04 +01:00
|
|
|
await Promise.all([
|
|
|
|
setStorageItem('METASWAP_GAS_PRICE_ESTIMATES', priceEstimates),
|
|
|
|
setStorageItem(
|
|
|
|
'METASWAP_GAS_PRICE_ESTIMATES_LAST_RETRIEVED',
|
|
|
|
timeRetrieved,
|
|
|
|
),
|
|
|
|
])
|
2020-11-04 17:14:08 +01:00
|
|
|
|
|
|
|
dispatch(
|
|
|
|
swapGasPriceEstimatesFetchCompleted({
|
|
|
|
priceEstimates,
|
|
|
|
priceEstimatesLastRetrieved: timeRetrieved,
|
|
|
|
}),
|
|
|
|
)
|
|
|
|
return priceEstimates
|
|
|
|
}
|
|
|
|
}
|