Send all swaps requests to api2, remove useNewSwapsApi boolean (#12792)

* Send all swaps requests to api2, remove useNewSwapsApi boolean

* Switch token bucket priority

* Fix tests

* Trigger Build

* Trigger Build
feature/default_network_editable
Matthew Epps 3 years ago committed by GitHub
parent d0c1fd713d
commit 8e6a0ff879
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 23
      app/scripts/controllers/swaps.js
  2. 4
      app/scripts/controllers/swaps.test.js
  3. 13
      shared/constants/swaps.js
  4. 4
      test/jest/constants.js
  5. 1
      test/jest/mock-store.js
  6. 9
      ui/ducks/swaps/swaps.js
  7. 21
      ui/ducks/swaps/swaps.test.js
  8. 10
      ui/hooks/useTokensToSearch.js
  9. 48
      ui/pages/swaps/index.js
  10. 12
      ui/pages/swaps/index.test.js
  11. 4
      ui/pages/swaps/searchable-item-list/list-item-search/list-item-search.component.js
  12. 49
      ui/pages/swaps/swaps.util.js
  13. 21
      ui/pages/swaps/swaps.util.test.js

@ -79,7 +79,6 @@ const initialState = {
topAggId: null, topAggId: null,
routeState: '', routeState: '',
swapsFeatureIsLive: true, swapsFeatureIsLive: true,
useNewSwapsApi: false,
saveFetchedQuotes: false, saveFetchedQuotes: false,
swapsQuoteRefreshTime: FALLBACK_QUOTE_REFRESH_TIME, swapsQuoteRefreshTime: FALLBACK_QUOTE_REFRESH_TIME,
swapsQuotePrefetchingRefreshTime: FALLBACK_QUOTE_REFRESH_TIME, swapsQuotePrefetchingRefreshTime: FALLBACK_QUOTE_REFRESH_TIME,
@ -123,9 +122,9 @@ export default class SwapsController {
}); });
} }
async fetchSwapsRefreshRates(chainId, useNewSwapsApi) { async fetchSwapsRefreshRates(chainId) {
const response = await fetchWithCache( const response = await fetchWithCache(
getBaseApi('network', chainId, useNewSwapsApi), getBaseApi('network', chainId),
{ method: 'GET' }, { method: 'GET' },
{ cacheRefreshTime: 600000 }, { cacheRefreshTime: 600000 },
); );
@ -149,13 +148,9 @@ export default class SwapsController {
// Sets the refresh rate for quote updates from the MetaSwap API // Sets the refresh rate for quote updates from the MetaSwap API
async _setSwapsRefreshRates() { async _setSwapsRefreshRates() {
const chainId = this._getCurrentChainId(); const chainId = this._getCurrentChainId();
const { swapsState } = this.store.getState();
let swapsRefreshRates; let swapsRefreshRates;
try { try {
swapsRefreshRates = await this.fetchSwapsRefreshRates( swapsRefreshRates = await this.fetchSwapsRefreshRates(chainId);
chainId,
swapsState.useNewSwapsApi,
);
} catch (e) { } catch (e) {
console.error('Request for swaps quote refresh time failed: ', e); console.error('Request for swaps quote refresh time failed: ', e);
} }
@ -210,11 +205,7 @@ export default class SwapsController {
) { ) {
const { chainId } = fetchParamsMetaData; const { chainId } = fetchParamsMetaData;
const { const {
swapsState: { swapsState: { quotesPollingLimitEnabled, saveFetchedQuotes },
useNewSwapsApi,
quotesPollingLimitEnabled,
saveFetchedQuotes,
},
} = this.store.getState(); } = this.store.getState();
if (!fetchParams) { if (!fetchParams) {
@ -242,7 +233,6 @@ export default class SwapsController {
let [newQuotes] = await Promise.all([ let [newQuotes] = await Promise.all([
this._fetchTradesInfo(fetchParams, { this._fetchTradesInfo(fetchParams, {
...fetchParamsMetaData, ...fetchParamsMetaData,
useNewSwapsApi,
}), }),
this._setSwapsRefreshRates(), this._setSwapsRefreshRates(),
]); ]);
@ -574,9 +564,9 @@ export default class SwapsController {
setSwapsLiveness(swapsLiveness) { setSwapsLiveness(swapsLiveness) {
const { swapsState } = this.store.getState(); const { swapsState } = this.store.getState();
const { swapsFeatureIsLive, useNewSwapsApi } = swapsLiveness; const { swapsFeatureIsLive } = swapsLiveness;
this.store.updateState({ this.store.updateState({
swapsState: { ...swapsState, swapsFeatureIsLive, useNewSwapsApi }, swapsState: { ...swapsState, swapsFeatureIsLive },
}); });
} }
@ -588,7 +578,6 @@ export default class SwapsController {
tokens: swapsState.tokens, tokens: swapsState.tokens,
fetchParams: swapsState.fetchParams, fetchParams: swapsState.fetchParams,
swapsFeatureIsLive: swapsState.swapsFeatureIsLive, swapsFeatureIsLive: swapsState.swapsFeatureIsLive,
useNewSwapsApi: swapsState.useNewSwapsApi,
swapsQuoteRefreshTime: swapsState.swapsQuoteRefreshTime, swapsQuoteRefreshTime: swapsState.swapsQuoteRefreshTime,
swapsQuotePrefetchingRefreshTime: swapsQuotePrefetchingRefreshTime:
swapsState.swapsQuotePrefetchingRefreshTime, swapsState.swapsQuotePrefetchingRefreshTime,

@ -131,7 +131,6 @@ const EMPTY_INIT_STATE = {
topAggId: null, topAggId: null,
routeState: '', routeState: '',
swapsFeatureIsLive: true, swapsFeatureIsLive: true,
useNewSwapsApi: false,
swapsQuoteRefreshTime: 60000, swapsQuoteRefreshTime: 60000,
swapsQuotePrefetchingRefreshTime: 60000, swapsQuotePrefetchingRefreshTime: 60000,
swapsUserFeeLevel: '', swapsUserFeeLevel: '',
@ -707,7 +706,6 @@ describe('SwapsController', function () {
assert.strictEqual( assert.strictEqual(
fetchTradesInfoStub.calledOnceWithExactly(MOCK_FETCH_PARAMS, { fetchTradesInfoStub.calledOnceWithExactly(MOCK_FETCH_PARAMS, {
...MOCK_FETCH_METADATA, ...MOCK_FETCH_METADATA,
useNewSwapsApi: false,
}), }),
true, true,
); );
@ -885,7 +883,6 @@ describe('SwapsController', function () {
const tokens = 'test'; const tokens = 'test';
const fetchParams = 'test'; const fetchParams = 'test';
const swapsFeatureIsLive = false; const swapsFeatureIsLive = false;
const useNewSwapsApi = false;
const swapsQuoteRefreshTime = 0; const swapsQuoteRefreshTime = 0;
const swapsQuotePrefetchingRefreshTime = 0; const swapsQuotePrefetchingRefreshTime = 0;
swapsController.store.updateState({ swapsController.store.updateState({
@ -893,7 +890,6 @@ describe('SwapsController', function () {
tokens, tokens,
fetchParams, fetchParams,
swapsFeatureIsLive, swapsFeatureIsLive,
useNewSwapsApi,
swapsQuoteRefreshTime, swapsQuoteRefreshTime,
swapsQuotePrefetchingRefreshTime, swapsQuotePrefetchingRefreshTime,
}, },

@ -84,12 +84,7 @@ export const WBNB_CONTRACT_ADDRESS =
export const WMATIC_CONTRACT_ADDRESS = export const WMATIC_CONTRACT_ADDRESS =
'0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270'; '0x0d500b1d8e8ef31e21c99d1db9a6444d3adf1270';
const METASWAP_ETH_API_HOST = 'https://api.metaswap.codefi.network';
const METASWAP_BSC_API_HOST = 'https://bsc-api.metaswap.codefi.network';
const SWAPS_TESTNET_CHAIN_ID = '0x539'; const SWAPS_TESTNET_CHAIN_ID = '0x539';
const SWAPS_TESTNET_HOST = 'https://metaswap-api.airswap-dev.codefi.network';
export const SWAPS_API_V2_BASE_URL = 'https://api2.metaswap.codefi.network'; export const SWAPS_API_V2_BASE_URL = 'https://api2.metaswap.codefi.network';
export const SWAPS_DEV_API_V2_BASE_URL = export const SWAPS_DEV_API_V2_BASE_URL =
@ -111,14 +106,6 @@ export const ALLOWED_SWAPS_CHAIN_IDS = {
[RINKEBY_CHAIN_ID]: true, [RINKEBY_CHAIN_ID]: true,
}; };
// This is mapping for v1 URLs and will be removed once we migrate to v2.
export const METASWAP_CHAINID_API_HOST_MAP = {
[MAINNET_CHAIN_ID]: METASWAP_ETH_API_HOST,
[SWAPS_TESTNET_CHAIN_ID]: `${SWAPS_API_V2_BASE_URL}/networks/1`,
[BSC_CHAIN_ID]: METASWAP_BSC_API_HOST,
[RINKEBY_CHAIN_ID]: SWAPS_TESTNET_HOST,
};
export const SWAPS_CHAINID_CONTRACT_ADDRESS_MAP = { export const SWAPS_CHAINID_CONTRACT_ADDRESS_MAP = {
[MAINNET_CHAIN_ID]: MAINNET_CONTRACT_ADDRESS, [MAINNET_CHAIN_ID]: MAINNET_CONTRACT_ADDRESS,
[SWAPS_TESTNET_CHAIN_ID]: TESTNET_CONTRACT_ADDRESS, [SWAPS_TESTNET_CHAIN_ID]: TESTNET_CONTRACT_ADDRESS,

@ -1,2 +1,2 @@
export const METASWAP_BASE_URL = 'https://api.metaswap.codefi.network'; export const METASWAP_BASE_URL = 'https://api2.metaswap.codefi.network';
export const METASWAP_API_V2_BASE_URL = 'https://api2.metaswap.codefi.network'; export const GAS_API_URL = 'https://gas-api.metaswap.codefi.network';

@ -221,7 +221,6 @@ export const createSwapsMockStore = () => {
topAggId: 'TEST_AGG_BEST', topAggId: 'TEST_AGG_BEST',
routeState: '', routeState: '',
swapsFeatureIsLive: false, swapsFeatureIsLive: false,
useNewSwapsApi: false,
}, },
useTokenDetection: true, useTokenDetection: true,
tokenList: { tokenList: {

@ -237,9 +237,6 @@ const getSwapsState = (state) => state.metamask.swapsState;
export const getSwapsFeatureIsLive = (state) => export const getSwapsFeatureIsLive = (state) =>
state.metamask.swapsState.swapsFeatureIsLive; state.metamask.swapsState.swapsFeatureIsLive;
export const getUseNewSwapsApi = (state) =>
state.metamask.swapsState.useNewSwapsApi;
export const getSwapsQuoteRefreshTime = (state) => export const getSwapsQuoteRefreshTime = (state) =>
state.metamask.swapsState.swapsQuoteRefreshTime; state.metamask.swapsState.swapsQuoteRefreshTime;
@ -403,7 +400,6 @@ export const fetchSwapsLiveness = () => {
return async (dispatch, getState) => { return async (dispatch, getState) => {
let swapsLivenessForNetwork = { let swapsLivenessForNetwork = {
swapsFeatureIsLive: false, swapsFeatureIsLive: false,
useNewSwapsApi: false,
}; };
try { try {
const swapsFeatureFlags = await fetchSwapsFeatureFlags(); const swapsFeatureFlags = await fetchSwapsFeatureFlags();
@ -431,7 +427,6 @@ export const fetchQuotesAndSetQuoteState = (
const chainId = getCurrentChainId(state); const chainId = getCurrentChainId(state);
let swapsLivenessForNetwork = { let swapsLivenessForNetwork = {
swapsFeatureIsLive: false, swapsFeatureIsLive: false,
useNewSwapsApi: false,
}; };
try { try {
const swapsFeatureFlags = await fetchSwapsFeatureFlags(); const swapsFeatureFlags = await fetchSwapsFeatureFlags();
@ -655,7 +650,6 @@ export const signAndSendTransactions = (history, metaMetricsEvent) => {
); );
let swapsLivenessForNetwork = { let swapsLivenessForNetwork = {
swapsFeatureIsLive: false, swapsFeatureIsLive: false,
useNewSwapsApi: false,
}; };
try { try {
const swapsFeatureFlags = await fetchSwapsFeatureFlags(); const swapsFeatureFlags = await fetchSwapsFeatureFlags();
@ -913,13 +907,12 @@ export function fetchMetaSwapsGasPriceEstimates() {
return async (dispatch, getState) => { return async (dispatch, getState) => {
const state = getState(); const state = getState();
const chainId = getCurrentChainId(state); const chainId = getCurrentChainId(state);
const useNewSwapsApi = getUseNewSwapsApi(state);
dispatch(swapGasPriceEstimatesFetchStarted()); dispatch(swapGasPriceEstimatesFetchStarted());
let priceEstimates; let priceEstimates;
try { try {
priceEstimates = await fetchSwapsGasPrices(chainId, useNewSwapsApi); priceEstimates = await fetchSwapsGasPrices(chainId);
} catch (e) { } catch (e) {
log.warn('Fetching swaps gas prices failed:', e); log.warn('Fetching swaps gas prices failed:', e);

@ -61,7 +61,6 @@ describe('Ducks - Swaps', () => {
const mockDispatch = jest.fn(); const mockDispatch = jest.fn();
const expectedSwapsLiveness = { const expectedSwapsLiveness = {
swapsFeatureIsLive: true, swapsFeatureIsLive: true,
useNewSwapsApi: true,
}; };
const featureFlagsResponse = MOCKS.createFeatureFlagsResponse(); const featureFlagsResponse = MOCKS.createFeatureFlagsResponse();
const featureFlagApiNock = mockFeatureFlagsApiResponse({ const featureFlagApiNock = mockFeatureFlagsApiResponse({
@ -81,7 +80,6 @@ describe('Ducks - Swaps', () => {
const mockDispatch = jest.fn(); const mockDispatch = jest.fn();
const expectedSwapsLiveness = { const expectedSwapsLiveness = {
swapsFeatureIsLive: true, swapsFeatureIsLive: true,
useNewSwapsApi: false,
}; };
const featureFlagsResponse = MOCKS.createFeatureFlagsResponse(); const featureFlagsResponse = MOCKS.createFeatureFlagsResponse();
featureFlagsResponse.ethereum.extension_active = false; featureFlagsResponse.ethereum.extension_active = false;
@ -102,7 +100,6 @@ describe('Ducks - Swaps', () => {
const mockDispatch = jest.fn(); const mockDispatch = jest.fn();
const expectedSwapsLiveness = { const expectedSwapsLiveness = {
swapsFeatureIsLive: false, swapsFeatureIsLive: false,
useNewSwapsApi: false,
}; };
const featureFlagsResponse = MOCKS.createFeatureFlagsResponse(); const featureFlagsResponse = MOCKS.createFeatureFlagsResponse();
featureFlagsResponse.ethereum.extension_active = false; featureFlagsResponse.ethereum.extension_active = false;
@ -124,7 +121,6 @@ describe('Ducks - Swaps', () => {
const mockDispatch = jest.fn(); const mockDispatch = jest.fn();
const expectedSwapsLiveness = { const expectedSwapsLiveness = {
swapsFeatureIsLive: false, swapsFeatureIsLive: false,
useNewSwapsApi: false,
}; };
const featureFlagApiNock = mockFeatureFlagsApiResponse({ const featureFlagApiNock = mockFeatureFlagsApiResponse({
replyWithError: true, replyWithError: true,
@ -143,7 +139,6 @@ describe('Ducks - Swaps', () => {
const mockDispatch = jest.fn(); const mockDispatch = jest.fn();
const expectedSwapsLiveness = { const expectedSwapsLiveness = {
swapsFeatureIsLive: true, swapsFeatureIsLive: true,
useNewSwapsApi: true,
}; };
const featureFlagsResponse = MOCKS.createFeatureFlagsResponse(); const featureFlagsResponse = MOCKS.createFeatureFlagsResponse();
const featureFlagApiNock = mockFeatureFlagsApiResponse({ const featureFlagApiNock = mockFeatureFlagsApiResponse({
@ -210,22 +205,6 @@ describe('Ducks - Swaps', () => {
}); });
}); });
describe('getUseNewSwapsApi', () => {
it('returns true for "useNewSwapsApi"', () => {
const state = createSwapsMockStore();
const useNewSwapsApi = true;
state.metamask.swapsState.useNewSwapsApi = useNewSwapsApi;
expect(swaps.getUseNewSwapsApi(state)).toBe(useNewSwapsApi);
});
it('returns false for "useNewSwapsApi"', () => {
const state = createSwapsMockStore();
const useNewSwapsApi = false;
state.metamask.swapsState.useNewSwapsApi = useNewSwapsApi;
expect(swaps.getUseNewSwapsApi(state)).toBe(useNewSwapsApi);
});
});
describe('getUsedQuote', () => { describe('getUsedQuote', () => {
it('returns selected quote', () => { it('returns selected quote', () => {
const state = createSwapsMockStore(); const state = createSwapsMockStore();

@ -154,15 +154,15 @@ export function useTokensToSearch({
tokenList, tokenList,
useTokenDetection, useTokenDetection,
); );
if ( if (memoizedTopTokens[token.address.toLowerCase()]) {
tokensToSearchBuckets.top[
memoizedTopTokens[token.address.toLowerCase()].index
] = renderableDataToken;
} else if (
isSwapsDefaultTokenSymbol(renderableDataToken.symbol, chainId) || isSwapsDefaultTokenSymbol(renderableDataToken.symbol, chainId) ||
usersTokensAddressMap[token.address.toLowerCase()] usersTokensAddressMap[token.address.toLowerCase()]
) { ) {
tokensToSearchBuckets.owned.push(renderableDataToken); tokensToSearchBuckets.owned.push(renderableDataToken);
} else if (memoizedTopTokens[token.address.toLowerCase()]) {
tokensToSearchBuckets.top[
memoizedTopTokens[token.address.toLowerCase()].index
] = renderableDataToken;
} else { } else {
tokensToSearchBuckets.others.push(renderableDataToken); tokensToSearchBuckets.others.push(renderableDataToken);
} }

@ -35,7 +35,6 @@ import {
prepareToLeaveSwaps, prepareToLeaveSwaps,
fetchAndSetSwapsGasPriceInfo, fetchAndSetSwapsGasPriceInfo,
fetchSwapsLiveness, fetchSwapsLiveness,
getUseNewSwapsApi,
getFromToken, getFromToken,
getReviewSwapClickedTimestamp, getReviewSwapClickedTimestamp,
} from '../../ducks/swaps/swaps'; } from '../../ducks/swaps/swaps';
@ -117,8 +116,6 @@ export default function Swap() {
const swapsEnabled = useSelector(getSwapsFeatureIsLive); const swapsEnabled = useSelector(getSwapsFeatureIsLive);
const chainId = useSelector(getCurrentChainId); const chainId = useSelector(getCurrentChainId);
const isSwapsChain = useSelector(getIsSwapsChain); const isSwapsChain = useSelector(getIsSwapsChain);
const useNewSwapsApi = useSelector(getUseNewSwapsApi);
const prevUseNewSwapsApi = useRef(useNewSwapsApi);
const networkAndAccountSupports1559 = useSelector( const networkAndAccountSupports1559 = useSelector(
checkNetworkAndAccountSupports1559, checkNetworkAndAccountSupports1559,
); );
@ -194,35 +191,24 @@ export default function Swap() {
// eslint-disable-next-line // eslint-disable-next-line
useEffect(() => { useEffect(() => {
if (isFeatureFlagLoaded && prevUseNewSwapsApi.current === useNewSwapsApi) { fetchTokens(chainId)
fetchTokens(chainId, useNewSwapsApi) .then((tokens) => {
.then((tokens) => { dispatch(setSwapsTokens(tokens));
dispatch(setSwapsTokens(tokens)); })
}) .catch((error) => console.error(error));
.catch((error) => console.error(error)); fetchTopAssets(chainId).then((topAssets) => {
fetchTopAssets(chainId, useNewSwapsApi).then((topAssets) => { dispatch(setTopAssets(topAssets));
dispatch(setTopAssets(topAssets)); });
}); fetchAggregatorMetadata(chainId).then((newAggregatorMetadata) => {
fetchAggregatorMetadata(chainId, useNewSwapsApi).then( dispatch(setAggregatorMetadata(newAggregatorMetadata));
(newAggregatorMetadata) => { });
dispatch(setAggregatorMetadata(newAggregatorMetadata)); if (!networkAndAccountSupports1559) {
}, dispatch(fetchAndSetSwapsGasPriceInfo(chainId));
);
if (!networkAndAccountSupports1559) {
dispatch(fetchAndSetSwapsGasPriceInfo(chainId));
}
return () => {
dispatch(prepareToLeaveSwaps());
};
} }
prevUseNewSwapsApi.current = useNewSwapsApi; return () => {
}, [ dispatch(prepareToLeaveSwaps());
dispatch, };
chainId, }, [dispatch, chainId, networkAndAccountSupports1559]);
isFeatureFlagLoaded,
useNewSwapsApi,
networkAndAccountSupports1559,
]);
const hardwareWalletUsed = useSelector(isHardwareWallet); const hardwareWalletUsed = useSelector(isHardwareWallet);
const hardwareWalletType = useSelector(getHardwareWalletType); const hardwareWalletType = useSelector(getHardwareWalletType);

@ -30,7 +30,7 @@ describe('Swap', () => {
beforeEach(() => { beforeEach(() => {
nock(CONSTANTS.METASWAP_BASE_URL) nock(CONSTANTS.METASWAP_BASE_URL)
.get('/topAssets') .get('/networks/1/topAssets')
.reply(200, MOCKS.TOP_ASSETS_GET_RESPONSE); .reply(200, MOCKS.TOP_ASSETS_GET_RESPONSE);
nock(CONSTANTS.METASWAP_BASE_URL) nock(CONSTANTS.METASWAP_BASE_URL)
@ -38,18 +38,18 @@ describe('Swap', () => {
.reply(200, MOCKS.REFRESH_TIME_GET_RESPONSE); .reply(200, MOCKS.REFRESH_TIME_GET_RESPONSE);
nock(CONSTANTS.METASWAP_BASE_URL) nock(CONSTANTS.METASWAP_BASE_URL)
.get('/aggregatorMetadata') .get('/networks/1/aggregatorMetadata')
.reply(200, MOCKS.AGGREGATOR_METADATA_GET_RESPONSE); .reply(200, MOCKS.AGGREGATOR_METADATA_GET_RESPONSE);
nock(CONSTANTS.METASWAP_BASE_URL) nock(CONSTANTS.GAS_API_URL)
.get('/gasPrices') .get('/networks/1/gasPrices')
.reply(200, MOCKS.GAS_PRICES_GET_RESPONSE); .reply(200, MOCKS.GAS_PRICES_GET_RESPONSE);
nock(CONSTANTS.METASWAP_BASE_URL) nock(CONSTANTS.METASWAP_BASE_URL)
.get('/tokens') .get('/networks/1/tokens')
.reply(200, MOCKS.TOKENS_GET_RESPONSE); .reply(200, MOCKS.TOKENS_GET_RESPONSE);
featureFlagsNock = nock(CONSTANTS.METASWAP_API_V2_BASE_URL) featureFlagsNock = nock(CONSTANTS.METASWAP_BASE_URL)
.get('/featureFlags') .get('/featureFlags')
.reply(200, MOCKS.createFeatureFlagsResponse()); .reply(200, MOCKS.createFeatureFlagsResponse());
}); });

@ -9,7 +9,6 @@ import { usePrevious } from '../../../../hooks/usePrevious';
import { isValidHexAddress } from '../../../../../shared/modules/hexstring-utils'; import { isValidHexAddress } from '../../../../../shared/modules/hexstring-utils';
import { fetchToken } from '../../swaps.util'; import { fetchToken } from '../../swaps.util';
import { getCurrentChainId } from '../../../../selectors/selectors'; import { getCurrentChainId } from '../../../../selectors/selectors';
import { getUseNewSwapsApi } from '../../../../ducks/swaps/swaps';
const renderAdornment = () => ( const renderAdornment = () => (
<InputAdornment position="start" style={{ marginRight: '12px' }}> <InputAdornment position="start" style={{ marginRight: '12px' }}>
@ -29,7 +28,6 @@ export default function ListItemSearch({
const fuseRef = useRef(); const fuseRef = useRef();
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
const chainId = useSelector(getCurrentChainId); const chainId = useSelector(getCurrentChainId);
const useNewSwapsApi = useSelector(getUseNewSwapsApi);
/** /**
* Search a custom token for import based on a contract address. * Search a custom token for import based on a contract address.
@ -38,7 +36,7 @@ export default function ListItemSearch({
const handleSearchTokenForImport = async (contractAddress) => { const handleSearchTokenForImport = async (contractAddress) => {
setSearchQuery(contractAddress); setSearchQuery(contractAddress);
try { try {
const token = await fetchToken(contractAddress, chainId, useNewSwapsApi); const token = await fetchToken(contractAddress, chainId);
if (token) { if (token) {
token.primaryLabel = token.symbol; token.primaryLabel = token.symbol;
token.secondaryLabel = token.name; token.secondaryLabel = token.name;

@ -3,7 +3,6 @@ import BigNumber from 'bignumber.js';
import abi from 'human-standard-token-abi'; import abi from 'human-standard-token-abi';
import { import {
SWAPS_CHAINID_DEFAULT_TOKEN_MAP, SWAPS_CHAINID_DEFAULT_TOKEN_MAP,
METASWAP_CHAINID_API_HOST_MAP,
ALLOWED_CONTRACT_ADDRESSES, ALLOWED_CONTRACT_ADDRESSES,
SWAPS_WRAPPED_TOKENS_ADDRESSES, SWAPS_WRAPPED_TOKENS_ADDRESSES,
ETHEREUM, ETHEREUM,
@ -79,14 +78,8 @@ const getBaseUrlForNewSwapsApi = (type, chainId) => {
return `${v2ApiBaseUrl}/networks/${chainIdDecimal}`; return `${v2ApiBaseUrl}/networks/${chainIdDecimal}`;
}; };
export const getBaseApi = function ( export const getBaseApi = function (type, chainId = MAINNET_CHAIN_ID) {
type, const baseUrl = getBaseUrlForNewSwapsApi(type, chainId);
chainId = MAINNET_CHAIN_ID,
useNewSwapsApi = false,
) {
const baseUrl = useNewSwapsApi
? getBaseUrlForNewSwapsApi(type, chainId)
: METASWAP_CHAINID_API_HOST_MAP[chainId];
const chainIdDecimal = chainId && parseInt(chainId, 16); const chainIdDecimal = chainId && parseInt(chainId, 16);
if (!baseUrl) { if (!baseUrl) {
throw new Error(`Swaps API calls are disabled for chainId: ${chainId}`); throw new Error(`Swaps API calls are disabled for chainId: ${chainId}`);
@ -300,7 +293,7 @@ export async function fetchTradesInfo(
fromAddress, fromAddress,
exchangeList, exchangeList,
}, },
{ chainId, useNewSwapsApi }, { chainId },
) { ) {
const urlParams = { const urlParams = {
destinationToken, destinationToken,
@ -319,11 +312,7 @@ export async function fetchTradesInfo(
} }
const queryString = new URLSearchParams(urlParams).toString(); const queryString = new URLSearchParams(urlParams).toString();
const tradeURL = `${getBaseApi( const tradeURL = `${getBaseApi('trade', chainId)}${queryString}`;
'trade',
chainId,
useNewSwapsApi,
)}${queryString}`;
const tradesResponse = await fetchWithCache( const tradesResponse = await fetchWithCache(
tradeURL, tradeURL,
{ method: 'GET', headers: clientIdHeader }, { method: 'GET', headers: clientIdHeader },
@ -367,8 +356,8 @@ export async function fetchTradesInfo(
return newQuotes; return newQuotes;
} }
export async function fetchToken(contractAddress, chainId, useNewSwapsApi) { export async function fetchToken(contractAddress, chainId) {
const tokenUrl = getBaseApi('token', chainId, useNewSwapsApi); const tokenUrl = getBaseApi('token', chainId);
const token = await fetchWithCache( const token = await fetchWithCache(
`${tokenUrl}?address=${contractAddress}`, `${tokenUrl}?address=${contractAddress}`,
{ method: 'GET', headers: clientIdHeader }, { method: 'GET', headers: clientIdHeader },
@ -377,8 +366,8 @@ export async function fetchToken(contractAddress, chainId, useNewSwapsApi) {
return token; return token;
} }
export async function fetchTokens(chainId, useNewSwapsApi) { export async function fetchTokens(chainId) {
const tokensUrl = getBaseApi('tokens', chainId, useNewSwapsApi); const tokensUrl = getBaseApi('tokens', chainId);
const tokens = await fetchWithCache( const tokens = await fetchWithCache(
tokensUrl, tokensUrl,
{ method: 'GET', headers: clientIdHeader }, { method: 'GET', headers: clientIdHeader },
@ -399,12 +388,8 @@ export async function fetchTokens(chainId, useNewSwapsApi) {
return filteredTokens; return filteredTokens;
} }
export async function fetchAggregatorMetadata(chainId, useNewSwapsApi) { export async function fetchAggregatorMetadata(chainId) {
const aggregatorMetadataUrl = getBaseApi( const aggregatorMetadataUrl = getBaseApi('aggregatorMetadata', chainId);
'aggregatorMetadata',
chainId,
useNewSwapsApi,
);
const aggregators = await fetchWithCache( const aggregators = await fetchWithCache(
aggregatorMetadataUrl, aggregatorMetadataUrl,
{ method: 'GET', headers: clientIdHeader }, { method: 'GET', headers: clientIdHeader },
@ -425,8 +410,8 @@ export async function fetchAggregatorMetadata(chainId, useNewSwapsApi) {
return filteredAggregators; return filteredAggregators;
} }
export async function fetchTopAssets(chainId, useNewSwapsApi) { export async function fetchTopAssets(chainId) {
const topAssetsUrl = getBaseApi('topAssets', chainId, useNewSwapsApi); const topAssetsUrl = getBaseApi('topAssets', chainId);
const response = await fetchWithCache( const response = await fetchWithCache(
topAssetsUrl, topAssetsUrl,
{ method: 'GET', headers: clientIdHeader }, { method: 'GET', headers: clientIdHeader },
@ -473,8 +458,8 @@ export async function fetchTokenBalance(address, userAddress) {
return usersToken; return usersToken;
} }
export async function fetchSwapsGasPrices(chainId, useNewSwapsApi) { export async function fetchSwapsGasPrices(chainId) {
const gasPricesUrl = getBaseApi('gasPrices', chainId, useNewSwapsApi); const gasPricesUrl = getBaseApi('gasPrices', chainId);
const response = await fetchWithCache( const response = await fetchWithCache(
gasPricesUrl, gasPricesUrl,
{ method: 'GET', headers: clientIdHeader }, { method: 'GET', headers: clientIdHeader },
@ -816,7 +801,7 @@ export const getNetworkNameByChainId = (chainId) => {
* It returns info about if Swaps are enabled and if we should use our new APIs for it. * It returns info about if Swaps are enabled and if we should use our new APIs for it.
* @param {object} swapsFeatureFlags * @param {object} swapsFeatureFlags
* @param {string} chainId * @param {string} chainId
* @returns object with 2 items: "swapsFeatureIsLive" and "useNewSwapsApi" * @returns object with 2 items: "swapsFeatureIsLive"
*/ */
export const getSwapsLivenessForNetwork = (swapsFeatureFlags = {}, chainId) => { export const getSwapsLivenessForNetwork = (swapsFeatureFlags = {}, chainId) => {
const networkName = getNetworkNameByChainId(chainId); const networkName = getNetworkNameByChainId(chainId);
@ -824,14 +809,12 @@ export const getSwapsLivenessForNetwork = (swapsFeatureFlags = {}, chainId) => {
if ([LOCALHOST_CHAIN_ID, RINKEBY_CHAIN_ID].includes(chainId)) { if ([LOCALHOST_CHAIN_ID, RINKEBY_CHAIN_ID].includes(chainId)) {
return { return {
swapsFeatureIsLive: true, swapsFeatureIsLive: true,
useNewSwapsApi: false,
}; };
} }
// If a network name is not found in the list of feature flags, disable Swaps. // If a network name is not found in the list of feature flags, disable Swaps.
if (!swapsFeatureFlags[networkName]) { if (!swapsFeatureFlags[networkName]) {
return { return {
swapsFeatureIsLive: false, swapsFeatureIsLive: false,
useNewSwapsApi: false,
}; };
} }
const isNetworkEnabledForNewApi = const isNetworkEnabledForNewApi =
@ -839,12 +822,10 @@ export const getSwapsLivenessForNetwork = (swapsFeatureFlags = {}, chainId) => {
if (isNetworkEnabledForNewApi) { if (isNetworkEnabledForNewApi) {
return { return {
swapsFeatureIsLive: true, swapsFeatureIsLive: true,
useNewSwapsApi: true,
}; };
} }
return { return {
swapsFeatureIsLive: swapsFeatureFlags[networkName].fallback_to_v1, swapsFeatureIsLive: swapsFeatureFlags[networkName].fallback_to_v1,
useNewSwapsApi: false,
}; };
}; };

@ -91,8 +91,8 @@ describe('Swaps Util', () => {
}, },
}; };
it('should fetch trade info on prod', async () => { it('should fetch trade info on prod', async () => {
nock('https://api.metaswap.codefi.network') nock('https://api2.metaswap.codefi.network')
.get('/trades') .get('/networks/1/trades')
.query(true) .query(true)
.reply(200, MOCK_TRADE_RESPONSE_2); .reply(200, MOCK_TRADE_RESPONSE_2);
@ -117,9 +117,9 @@ describe('Swaps Util', () => {
describe('fetchTokens', () => { describe('fetchTokens', () => {
beforeAll(() => { beforeAll(() => {
nock('https://api.metaswap.codefi.network') nock('https://api2.metaswap.codefi.network')
.persist() .persist()
.get('/tokens') .get('/networks/1/tokens')
.reply(200, TOKENS); .reply(200, TOKENS);
}); });
@ -136,9 +136,9 @@ describe('Swaps Util', () => {
describe('fetchAggregatorMetadata', () => { describe('fetchAggregatorMetadata', () => {
beforeAll(() => { beforeAll(() => {
nock('https://api.metaswap.codefi.network') nock('https://api2.metaswap.codefi.network')
.persist() .persist()
.get('/aggregatorMetadata') .get('/networks/1/aggregatorMetadata')
.reply(200, AGGREGATOR_METADATA); .reply(200, AGGREGATOR_METADATA);
}); });
@ -155,9 +155,9 @@ describe('Swaps Util', () => {
describe('fetchTopAssets', () => { describe('fetchTopAssets', () => {
beforeAll(() => { beforeAll(() => {
nock('https://api.metaswap.codefi.network') nock('https://api2.metaswap.codefi.network')
.persist() .persist()
.get('/topAssets') .get('/networks/1/topAssets')
.reply(200, TOP_ASSETS); .reply(200, TOP_ASSETS);
}); });
@ -327,7 +327,6 @@ describe('Swaps Util', () => {
it('returns info that Swaps are enabled and cannot use API v2 for localhost chain ID', () => { it('returns info that Swaps are enabled and cannot use API v2 for localhost chain ID', () => {
const expectedSwapsLiveness = { const expectedSwapsLiveness = {
swapsFeatureIsLive: true, swapsFeatureIsLive: true,
useNewSwapsApi: false,
}; };
expect( expect(
getSwapsLivenessForNetwork( getSwapsLivenessForNetwork(
@ -340,7 +339,6 @@ describe('Swaps Util', () => {
it('returns info that Swaps are enabled and cannot use API v2 for Rinkeby chain ID', () => { it('returns info that Swaps are enabled and cannot use API v2 for Rinkeby chain ID', () => {
const expectedSwapsLiveness = { const expectedSwapsLiveness = {
swapsFeatureIsLive: true, swapsFeatureIsLive: true,
useNewSwapsApi: false,
}; };
expect( expect(
getSwapsLivenessForNetwork( getSwapsLivenessForNetwork(
@ -353,7 +351,6 @@ describe('Swaps Util', () => {
it('returns info that Swaps are disabled and cannot use API v2 if network name is not found', () => { it('returns info that Swaps are disabled and cannot use API v2 if network name is not found', () => {
const expectedSwapsLiveness = { const expectedSwapsLiveness = {
swapsFeatureIsLive: false, swapsFeatureIsLive: false,
useNewSwapsApi: false,
}; };
expect( expect(
getSwapsLivenessForNetwork( getSwapsLivenessForNetwork(
@ -366,7 +363,6 @@ describe('Swaps Util', () => {
it('returns info that Swaps are enabled and can use API v2 for mainnet chain ID', () => { it('returns info that Swaps are enabled and can use API v2 for mainnet chain ID', () => {
const expectedSwapsLiveness = { const expectedSwapsLiveness = {
swapsFeatureIsLive: true, swapsFeatureIsLive: true,
useNewSwapsApi: true,
}; };
expect( expect(
getSwapsLivenessForNetwork( getSwapsLivenessForNetwork(
@ -379,7 +375,6 @@ describe('Swaps Util', () => {
it('returns info that Swaps are enabled but can only use API v1 for mainnet chain ID', () => { it('returns info that Swaps are enabled but can only use API v1 for mainnet chain ID', () => {
const expectedSwapsLiveness = { const expectedSwapsLiveness = {
swapsFeatureIsLive: true, swapsFeatureIsLive: true,
useNewSwapsApi: false,
}; };
const swapsFeatureFlags = MOCKS.createFeatureFlagsResponse(); const swapsFeatureFlags = MOCKS.createFeatureFlagsResponse();
swapsFeatureFlags[ETHEREUM].extension_active = false; swapsFeatureFlags[ETHEREUM].extension_active = false;

Loading…
Cancel
Save